comment
stringlengths
11
2.99k
function_code
stringlengths
165
3.15k
version
stringclasses
80 values
/** Return floor(ln(numerator / denominator) * 2 ^ MAX_PRECISION), where: - The numerator is a value between 1 and 2 ^ (256 - MAX_PRECISION) - 1 - The denominator is a value between 1 and 2 ^ (256 - MAX_PRECISION) - 1 - The output is a value between 0 and floor(ln(2 ^ (256 - MAX_PRECISION) - 1) * 2 ^ MAX...
function ln(uint256 _numerator, uint256 _denominator) public pure returns (uint256) { assert(_numerator <= MAX_NUM); uint256 res = 0; uint256 x = _numerator * FIXED_1 / _denominator; // If x >= 2, then we compute the integer part of log2(x), which is larger than 0. if (x...
0.6.7
//An arbitrary versioning scheme.
function HumanStandardToken( uint256 _initialAmount, string _tokenName, uint8 _decimalUnits, string _tokenSymbol ) { balances[msg.sender] = _initialAmount; // Give the creator all initial tokens totalSupply = _initialAmount; // Update total supply ...
0.4.4
/// @notice `createTokens()` will create tokens if the campaign has not been /// sealed. /// @dev `createTokens()` is called by the campaign contract when /// someone sends ether to that contract or calls `doPayment()` /// @param beneficiary The address receiving the tokens /// @param amount The amount of tokens the ad...
function createTokens(address beneficiary, uint amount ) onlyController returns (bool success) { if (sealed()) throw; balances[beneficiary] += amount; // Create tokens for the beneficiary totalSupply += amount; // Update total supply Transfer(0, beneficiary, amount);...
0.4.4
/// @notice 'Campaign()' initiates the Campaign by setting its funding /// parameters and creating the deploying the token contract /// @dev There are several checks to make sure the parameters are acceptable /// @param _startFundingTime The UNIX time that the Campaign will be able to /// start receiving funds /// @par...
function Campaign( uint _startFundingTime, uint _endFundingTime, uint _maximumFunding, address _vaultContract ) { if ((_endFundingTime < now) || // Cannot start in the past (_endFundingTime <= _startFundingTime) || (_maximumFundi...
0.4.4
/// @dev `doPayment()` is an internal function that sends the ether that this /// contract receives to the `vaultContract` and creates campaignTokens in the /// address of the `_owner` assuming the Campaign is still accepting funds /// @param _owner The address that will hold the newly created CampaignTokens
function doPayment(address _owner) internal { // First we check that the Campaign is allowed to receive this donation if ((now<startFundingTime) || (now>endFundingTime) || (tokenContract.tokenController() == 0) || // Extra check (msg.value == 0) || ...
0.4.4
// @dev Removes an address from an admin for a game // @notice Can only be called by an admin of the game. // @notice Can't remove your own account's admin privileges. // @param _game - the gameId of the game // @param _account - the address of the user to remove admin privileges.
function removeAdminAccount(uint _game, address _account) external onlyGameAdmin(_game) { require(_account != msg.sender); require(gameAdmins[_game][_account]); address[] storage opsAddresses = adminAddressesByGameId[_game]; uint startingLength = opsAddresses.length; // Yes, ...
0.4.25
// @dev Internal function to add an address as an admin for a game // @param _game - the gameId of the game // @param _account - the address of the user
function _addAdminAccount(uint _game, address _account) internal { address[] storage opsAddresses = adminAddressesByGameId[_game]; require(opsAddresses.length < 256, "a game can only have 256 admins"); for (uint i = opsAddresses.length; i < opsAddresses.length; i--) { require(opsAddresses[...
0.4.25
// @dev Create a new game by setting its data. // Created games are initially owned and managed by the game's creator // @notice - there's a maximum of 2^32 games (4.29 billion games) // @param _json - a json encoded string containing the game's name, uri, logo, description, etc // @param _tradeLockSeconds - the num...
function createGame(string _json, uint _tradeLockSeconds, bytes32[] _metadata) external returns(uint _game) { // Create the game _game = games.length; require(_game < games[0], "too many games created"); games.push(_game); // Log the game as created emit GameCreated(_game, msg.s...
0.4.25
// @dev Get all game data for one given game // @param _game - the # of the game // @returns game - the game ID of the requested game // @returns json - the json data of the game // @returns tradeLockSeconds - the number of card sets // @returns balance - the Nova Token balance // @returns metadata - a bytes32 array o...
function getGameData(uint _game) external view returns(uint game, string json, uint tradeLockSeconds, uint256 balance, bytes32[] metadata) { GameData storage data = gameData[_game]; game = _game; json = data.json; tradeLockSeconds = data.tradeLockSeconds; ba...
0.4.25
// @dev Update the json, trade lock, and metadata for a single game // @param _game - the # of the game // @param _json - a json encoded string containing the game's name, uri, logo, description, etc // @param _tradeLockSeconds - the number of seconds a card remains locked to a purchaser's account // @param _metadata -...
function updateGameMetadata(uint _game, string _json, uint _tradeLockSeconds, bytes32[] _metadata) public onlyGameAdmin(_game) { gameData[_game].tradeLockSeconds = _tradeLockSeconds; gameData[_game].json = _json; bytes32[] storage data = gameData[_game].metadata; if (_metadata.length ...
0.4.25
// Claim egg and tokens
function claimEgg(uint256 stakingSetKey) external { // checks require(keyToStakingSet[stakingSetKey].owner == msg.sender, "Unauthorized"); require(keyToStakingSet[stakingSetKey].eggClaimed == false, "Already claimed"); require(block.timestamp > keyToStakingSet[stakingSetKey].timestam...
0.8.4
/** @notice This function is used to invest in given balancer pool through ETH/ERC20 Tokens @param _FromTokenContractAddress The token used for investment (address(0x00) if ether) @param _ToBalancerPoolAddress The address of balancer pool to zapin @param _amount The amount of ERC to invest @param _minPoolToke...
function ZapIn( address _FromTokenContractAddress, address _ToBalancerPoolAddress, uint256 _amount, uint256 _minPoolTokens ) public payable nonReentrant stopInEmergency returns (uint256 tokensBought) { require( ...
0.5.17
/** @notice This function internally called by ZapIn() and EasyZapIn() @param _toWhomToIssue The user address who want to invest @param _FromTokenContractAddress The token used for investment (address(0x00) if ether) @param _ToBalancerPoolAddress The address of balancer pool to zapin @param _amount The amount...
function _performZapIn( address _toWhomToIssue, address _FromTokenContractAddress, address _ToBalancerPoolAddress, uint256 _amount, address _IntermediateToken, uint256 _minPoolTokens ) internal returns (uint256 tokensBought) { // check if isBound() ...
0.5.17
/** @notice This function is used to zapin to balancer pool @param _ToBalancerPoolAddress The address of balancer pool to zap in @param _FromTokenContractAddress The token used to zap in @param tokens2Trade The amount of tokens to invest @return The quantity of Balancer Pool tokens returned */
function _enter2Balancer( address _ToBalancerPoolAddress, address _FromTokenContractAddress, uint256 tokens2Trade, uint256 _minPoolTokens ) internal returns (uint256 poolTokensOut) { require( IBPool(_ToBalancerPoolAddress).isBound(_FromTokenContractAddress)...
0.5.17
/** @notice Function gives the expected amount of pool tokens on investing @param _ToBalancerPoolAddress Address of balancer pool to zapin @param _IncomingERC The amount of ERC to invest @param _FromToken Address of token to zap in with @return Amount of BPT token */
function getToken2BPT( address _ToBalancerPoolAddress, uint256 _IncomingERC, address _FromToken ) internal view returns (uint256 tokensReturned) { uint256 totalSupply = IBPool(_ToBalancerPoolAddress).totalSupply(); uint256 swapFee = IBPool(_ToBalancerPoolAddress).getSwa...
0.5.17
/** @notice This function is used to buy tokens from eth @param _tokenContractAddress Token address which we want to buy @return The quantity of token bought */
function _eth2Token(uint256 _ethAmt, address _tokenContractAddress) internal returns (uint256 tokenBought) { if (_tokenContractAddress == wethTokenAddress) { IWETH(wethTokenAddress).deposit.value(_ethAmt)(); return _ethAmt; } address[] memory...
0.5.17
/** * @notice Initialize the new money market * @param comptroller_ The address of the Comptroller * @param interestRateModel_ The address of the interest rate model * @param name_ ERC-20 name of this token * @param symbol_ ERC-20 symbol of this token */
function initialize(ComptrollerInterface comptroller_, InterestRateModel interestRateModel_, string memory name_, string memory symbol_, uint256 reserveFactorMantissa_, uint256 adminFeeMantissa_) publ...
0.5.17
/** * @notice createIDO */
function createIDO( uint256 saleTarget, address fundToken, uint256 fundTarget, uint256 startTime, uint256 endTime, uint256 claimTime, uint256 minFundAmount, uint256 fcfsAmount, string memory meta ) external isOperatorOrOwner returns (address) {...
0.8.2
/** * Accept ownership request, works only if called by new owner */
function acceptOwnership() { // Avoid multiple events triggering in case of several calls from owner if (msg.sender == newOwner && owner != newOwner) { OwnershipTransferred(owner, newOwner); owner = newOwner; } }
0.4.15
/** * Transfer the balance from owner's account to another account * * @param _to target address * @param _amount amount of tokens * @return true on success */
function transfer(address _to, uint256 _amount) returns (bool success) { if (balanceOf[msg.sender] >= _amount // User has balance && _amount > 0 // Non-zero transfer && balanceOf[_to] + _amount > balanceOf[_to] // Overflow check ...
0.4.15
/** * Spender of tokens transfer an amount of tokens from the token owner's * balance to the spender's account. The owner of the tokens must already * have approve(...)-d this transfer * * @param _from spender address * @param _to target address * @param _amount amount of tokens * @ret...
function transferFrom(address _from, address _to, uint256 _amount) returns (bool success) { if (balanceOf[_from] >= _amount // From a/c has balance && allowance[_from][msg.sender] >= _amount // Transfer approved && _amount > 0 // Non-ze...
0.4.15
/** * EloPlayToken contract constructor * * @param _start_ts crowdsale start timestamp (unix) * @param _end_ts crowdsale end timestamp (unix) * @param _cap crowdsale upper cap (in wei) * @param _target_address multisignature wallet where Ethers will be sent to * @param _ta...
function EloPlayToken(uint256 _start_ts, uint256 _end_ts, uint256 _cap, address _target_address, address _target_tokens_address, uint256 _usdethrate) { START_TS = _start_ts; END_TS = _end_ts; CAP = _cap; USDETHRATE = _usdethrate; TARGET_ADDR...
0.4.15
/** * Get tokens per ETH for given date/time * * @param _at timestamp (unix) * @return tokens/ETH rate for given timestamp */
function buyPriceAt(uint256 _at) constant returns (uint256) { if (_at < START_TS) { return 0; } else if (_at < START_TS + 3600) { // 1st hour = 10000 + 20% = 12000 return 12000; } else if (_at < START_TS + 3600 * 24) { // 1st day = 10000 + 1...
0.4.15
/** * Owner to add precommitment funding token balance before the crowdsale commences * Used for pre-sale commitments, added manually * * @param _participant address that will receive tokens * @param _balance number of tokens * @param _ethers Ethers value (needed for stats) * ...
function addPrecommitment(address _participant, uint256 _balance, uint256 _ethers) onlyOwner { require(now < START_TS); // Minimum value = 1ELT // Since we are using 18 decimals for token require(_balance >= 1 ether); // To avoid overflow, first divide then multiply (to cl...
0.4.15
/** * Transfer the balance from owner's account to another account, with a * check that the crowdsale is finalized * * @param _to tokens receiver * @param _amount tokens amount * @return true on success */
function transfer(address _to, uint _amount) returns (bool success) { // Cannot transfer before crowdsale ends or cap reached require(now > END_TS || totalEthers >= CAP); // Standard transfer return super.transfer(_to, _amount); }
0.4.15
/** * Spender of tokens transfer an amount of tokens from the token owner's * balance to another account, with a check that the crowdsale is * finalized * * @param _from tokens sender * @param _to tokens receiver * @param _amount tokens amount * @return ...
function transferFrom(address _from, address _to, uint _amount) returns (bool success) { // Cannot transfer before crowdsale ends or cap reached require(now > END_TS || totalEthers >= CAP); // Standard transferFrom return super.transferFrom(_from, _to, _amount); }
0.4.15
// This function must be called after builder shop instance is created - it can be called again // to change the split; call this once per nifty type to set up royalty payments properly
function initializeRoyalties(address splitterImplementation, uint256 niftyType, address[] calldata payees, uint256[] calldata shares_) external onlyValidSender { address previousReceiver = _getRoyaltyReceiverByNiftyType(niftyType); address newReceiver = address(0); if(payees.length == 1) { ...
0.8.4
/** * @dev Create specified number of nifties en masse. * Once an NFT collection is spawned by the factory contract, we make calls to set the IPFS * hash (above) for each Nifty type in the collection. * Subsequently calls are issued to this function to mint the appropriate number of tokens * for the project. */
function mintNifty(uint256 niftyType, uint256 count) public onlyValidSender { require(!_getFinalized(niftyType), "NiftyBuilderInstance: minting concluded for nifty type"); uint256 tokenNumber = _mintCount[niftyType] + 1; uint256 tokenId00 = _encodeTokenId(niftyType, tokenNumber); ...
0.8.4
/** @notice equivalent to `deposit` except logic is configured for ETH instead of ERC20 payments. @param amountDesired amount of ERC20 token desired by caller @param amountEthMin minimum amount of ETH desired by caller @param amountMin minimum amount of ERC20 token desired by caller @param recipient The address f...
function depositETH( uint256 amountDesired, uint256 amountEthMin, uint256 amountMin, address recipient, uint256 deadline ) external payable override notExpired(deadline) returns ( uint256 shares, uint256 amountEthIn, uint256 amountIn ) { TOKEN _WETH_...
0.7.6
/** @notice withdraws the desired shares from the vault @dev same as `withdraw` except this can be called from an `approve`d address @param withdrawer the address to withdraw from @param shares number of shares to withdraw @param amountEthMin amount of ETH desired by user @param amountMin Minimum amount of ERC20 ...
function withdrawETHFrom( address withdrawer, uint256 shares, uint256 amountEthMin, uint256 amountMin, address payable recipient, uint256 deadline ) external override canSpend(withdrawer, shares) returns (uint256 amountEthOut, uint256 amountOut) { TOKEN _WETH_TOKEN = WETH...
0.7.6
/** @notice withdraws the desired shares from the vault @param shares number of shares to withdraw @param amountEthMin amount of ETH desired by user @param amountMin Minimum amount of ERC20 token desired by user @param recipient address to recieve ETH and ERC20 withdrawals @param deadline blocktimestamp that this...
function withdrawETH( uint256 shares, uint256 amountEthMin, uint256 amountMin, address payable recipient, uint256 deadline ) external override returns (uint256 amountEthOut, uint256 amountOut) { TOKEN _WETH_TOKEN = WETH_TOKEN; uint256 amount0Min; uint256 amount1Min; if (_WETH_TOKEN...
0.7.6
/// @notice Selects a user using a random number. The random number will be uniformly bounded to the ticket totalSupply. /// @param randomNumber The random number to use to select a user. /// @return The winner
function draw(uint256 randomNumber) external view override returns (address) { uint256 bound = totalSupply(); address selected; if (bound == 0) { selected = address(0); } else { uint256 token = UniformRandomNumber.uniform(randomNumber, bound); selected = address(uint256(sortitionSumTre...
0.6.12
/// @dev Controller hook to provide notifications & rule validations on token transfers to the controller. /// This includes minting and burning. /// May be overridden to provide more granular control over operator-burning /// @param from Address of the account sending the tokens (address(0x0) on minting) /// @param to...
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override { super._beforeTokenTransfer(from, to, amount); // optimize: ignore transfers to self if (from == to) { return; } if (from != address(0)) { uint256 fromBalance = balanceOf(from).sub(amount...
0.6.12
/// @notice Permits this contract to spend on a users behalf, and deposits into the prize pool. /// @dev The Dai permit params match the Dai#permit function, but it expects the `spender` to be /// the address of this contract. /// @param holder The address spending the tokens /// @param nonce The nonce of the tx. Shou...
function permitAndDepositTo( // --- Approve by signature --- address dai, address holder, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s, address prizePool, address to, uint256 amount, address controlledToken, address referrer ) external { require(msg.sender == holder, "Per...
0.6.12
// // Buy a single ticket. //
function buyOne() onlyUnpaused payable external { TournamentTicket ticket = getTicketContract(); require(ticket.balanceOf(msg.sender) == 0, "You already have a ticket, and you only need one to participate!"); require(pricePerTicket > 0, "The price per ticket needs to be more than 0!"); ...
0.5.8
/** * @dev Internal function to mint a new token. * Reverts if the given token ID already exists. * @param sign struct combination of uint8, bytes32, bytes32 are v, r, s. * @param tokenURI string memory URI of the token to be minted. * @param fee uint256 royalty of the token to be minted. */
function createCollectible(string memory tokenURI, uint256 fee, Sign memory sign) public returns (uint256) { uint256 newItemId = tokenCounter; verifySign(tokenURI, sign); _safeMint(msg.sender, newItemId, fee); _setTokenURI(newItemId, tokenURI); tokenCounter = tokenCounter + ...
0.8.4
/** * @dev Burns a specific amount of tokens. * @param _account The account whose tokens will be burnt. * @param _value The amount of token to be burned. */
function burn(address _account, uint256 _value) onlyOwner public { require(_account != address(0)); require(_enableActions); // SafeMath.sub will throw if there is not enough balance. _totalSupply = _totalSupply.sub(_value); _balances[_account] = _balances[_account].sub(_value); ...
0.4.24
/** Calculate the current price for buy in amount. */
function calculateTokenAmount(uint weiAmount, uint weiRaised) public view returns (uint tokenAmount) { if (weiAmount == 0) { return 0; } var (rate, index) = currentRate(weiRaised); tokenAmount = weiAmount.mul(rate); // if we crossed slot border, recalculate ...
0.4.18
// register new contract for state sync
function register(address sender, address receiver) public { require( isOwner() || registrations[receiver] == msg.sender, "StateSender.register: Not authorized to register" ); registrations[receiver] = sender; if (registrations[receiver] == address(0)) { ...
0.5.11
/** *batch transfer token for a list of specified addresses * @param _toList The list of addresses to transfer to. * @param _tokensList The list of amount to be transferred. */
function batchTransfer(address[] _toList, uint256[] _tokensList) public returns (bool) { require(_toList.length <= 100); require(_toList.length == _tokensList.length); uint256 sum = 0; for (uint32 index = 0; index < _tokensList.length; index++) { sum = sum.add(_tokensList...
0.4.23
// get frozen balance
function frozenBalanceOf(address _owner) public constant returns (uint256 value) { for (uint i = 0; i < frozenBalanceCount; i++) { FrozenBalance storage frozenBalance = frozenBalances[i]; if (_owner == frozenBalance.owner) { value = value.add(frozenBalance.value); ...
0.4.18
// unfreeze frozen amount // everyone can call this function to unfreeze balance
function unfreeze() public returns (uint256 releaseAmount) { uint index = 0; while (index < frozenBalanceCount) { if (now >= frozenBalances[index].unfreezeTime) { releaseAmount += frozenBalances[index].value; unfreezeBalanceByIndex(index); } ...
0.4.18
// check is release record existed // if existed return true, else return false
function checkIsReleaseRecordExist(uint256 timestamp) internal view returns(bool _exist) { bool exist = false; if (releaseRecordsCount > 0) { for (uint index = 0; index < releaseRecordsCount; index++) { if ((releaseRecords[index].releaseTime.parseTimestamp().year == times...
0.4.18
// update release amount for single day // according to dividend rule in https://coinhot.com
function updateReleaseAmount(uint256 timestamp) internal { uint256 timeElapse = timestamp.sub(createTime); uint256 cycles = timeElapse.div(180 days); if (cycles > 0) { if (cycles <= 10) { releaseAmountPerDay = standardReleaseAmount; for (uint ind...
0.4.18
/** * @dev Function for add arbitrary ERC20 collaterals * * @param _wrappedTokenId NFT id from thgis contarct * @param _erc20 address of erc20 collateral for add * @param _amount amount erc20 collateral for add */
function addERC20Collateral( uint256 _wrappedTokenId, address _erc20, uint256 _amount ) external nonReentrant { require(ownerOf(_wrappedTokenId) != address(0)); require(enabledForCollateral(_erc20), "This ERC20 is not enabled for collateral"); ...
0.8.7
/** * @dev Function returns collateral balance of this NFT in _erc20 * colleteral of wrapped token * * @param _wrappedId new protocol NFT id from this contarct * @param _erc20 - collateral token address */
function getERC20CollateralBalance(uint256 _wrappedId, address _erc20) public view returns (uint256) { ERC20Collateral[] memory e = erc20Collateral[_wrappedId]; for (uint256 i = 0; i < e.length; i ++) { if (e[i].erc20Token == _erc20) { return e[i].amount; } ...
0.8.7
/** * @dev Function returns all ERC20 collateral to user who unWrap * protocol token. Returns true if all tokens are transfered. * Otherwise returns false. In that case need just call unWrap721 * one more time * * * @param _tokenId -wrapped token * */
function _returnERC20Collateral(uint256 _tokenId) internal returns (bool) { //First we need release erc20 collateral, because erc20 transfers are // can be expencive ERC20Collateral[] storage e = erc20Collateral[_tokenId]; if (e.length > 0) { for (uint256 i = e.length; i > 0...
0.8.7
/** * @dev Returns a boolean array where each value corresponds to the * interfaces passed in and whether they're supported or not. This allows * you to batch check interfaces for a contract where your expectation * is that some interfaces may not be supported. * * See {IERC165-supportsInterface}. * * _Availabl...
function getSupportedInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool[] memory) { // an array of booleans corresponding to interfaceIds and whether they're supported or not bool[] memory interfaceIdsSupported = new bool[](interfaceIds.leng...
0.8.7
/// !!!!For gas safe this low levelfunction has NO any check before wrap /// So you have NO warranty to do Unwrap well
function WrapForFarming( address _receiver, ERC20Collateral memory _erc20Collateral, uint256 _unwrapAfter ) public payable { require(_receiver != address(0), "No zero address"); require(!isDepricated, "Pool is depricated for new stakes"); // 1.topup wrapper cont...
0.8.7
//////////////////////////////////////////////////////////////// ////////// Admins ////// ////////////////////////////////////////////////////////////////
function setRewardSettings( address _erc20, uint256 _settingsSlotId, uint256 _period, uint256 _percent ) external onlyOwner { require(rewardSettings[_erc20].length > 0, "There is no settings for this token"); RewardSettings[] storage set = rewardSettings[_...
0.8.7
/** * @dev Function returns tokenURI of **underline original token** * * @param _tokenId id of protocol token (new wrapped token) */
function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) { NFT storage nft = wrappedTokens[_tokenId]; if (nft.tokenContract != address(0)) { return IERC721Metadata(nft.tokenContract).tokenURI(nft.tokenId); } else { return stri...
0.8.7
/** * @dev Adds a new batch to the `batchMapping` and increases the * count of `totalNumberOfBatches` */
function addNewBatch( uint256 _totalSpots, uint256 _batchStartTimestamp, uint256 _depositAmount ) public onlyOwner { require( _batchStartTimestamp >= currentTimestamp(), "WaitlistBatch: batch start time cannot be in the past" ); ...
0.5.16
/** * @dev Approves a batch. Users can then start reclaiming their deposit * after the retrieval date delay. */
function approveBatch( uint256 _batchNumber ) external onlyOwner { require( _batchNumber > 0 && _batchNumber < nextBatchNumber, "WaitlistBatch: the batch does not exist" ); Batch storage batch = batchMapping[_batchNumber]; require...
0.5.16
/// @notice Check if ID is valid.
function validId(uint16 tokenId) public pure returns (bool) { return tokenId >= 11111 && tokenId <= 55555 && tokenId % 10 > 0 && tokenId % 10 <= 5 && tokenId % 100 > 10 && tokenId % 100 <= 55 && tokenId % 1000 > 100 && tokenId % 1000 <= 555 && tokenId % 10000 > 10...
0.8.9
/** * @notice Adds a new acceted code hash. * @param _code The new code hash. */
function addCode(bytes32 _code) public onlyOwner { require(_code != bytes32(0), "AWR: empty _code"); Info storage code = acceptedCodes[_code]; if(!code.exists) { codes.push(_code); code.exists = true; code.index = uint128(codes.length - 1); emit CodeAdded(_code); } }
0.6.12
/** * @notice Adds a new acceted implementation. * @param _impl The new implementation. */
function addImplementation(address _impl) public onlyOwner { require(_impl != address(0), "AWR: empty _impl"); Info storage impl = acceptedImplementations[_impl]; if(!impl.exists) { implementations.push(_impl); impl.exists = true; impl.index = uint128(implementations.length - 1); ...
0.6.12
/** * @dev Withdraw ether and token * @param message Signed message * @param v Signature hash * @param r Signature hash * @param s Signature hash * @param tokenaddr Token address to be withdraw * @param to Receiver address * @param amount Amount to be withdraw */
function withdraw(string memory message, uint8 v, bytes32 r, bytes32 s, uint8 type_, address tokenaddr, address payable _from, address payable to, uint256 amount, uint256 profitValue) contractStatus public returns(bool) { require(hashComformation[message] != true); require(verify(string(strConcat(s...
0.5.12
/** * @dev Profit Withdraw of the admin * @param type_ Either token or ether * @param tokenAddr Token address * @param amount Amount to be Withdraw */
function profitWithdraw(uint256 type_,address tokenAddr,uint256 amount) onlyOwner public returns(bool){ require(amount > 0); require(type_ ==0 || type_ == 1); if(type_== 0){ require(amount > 0 && amount <= adminProfit[admin][address(0)]); msg.sender.transfe...
0.5.12
/** * @dev String concatenation */
function strConcat(string memory _a, string memory _b) private pure returns (bytes memory){ bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); string memory ab = new string(_ba.length + _bb.length); bytes memory babcde = bytes(ab); uint k = 0; for (uint i =...
0.5.12
/** * @dev Verification of the Signature */
function verify(string memory message, uint8 v, bytes32 r, bytes32 s) private pure returns (address signer) { string memory header = "\x19Ethereum Signed Message:\n000000"; uint256 lengthOffset; uint256 length; assembly { length := mload(message) lengthOffs...
0.5.12
// // public view functions // never use these for functions ever, they are expensive af and for view only
function walletOfOwner(address address_) public virtual view returns (uint256[] memory) { uint256 _balance = balanceOf[address_]; uint256[] memory _tokens = new uint256[] (_balance); uint256 _index; uint256 _loopThrough = totalSupply; for (uint256 i = 0; i < _loopThrou...
0.8.7
// Fusion Mechanism
function fusion(uint256 parent1_, uint256 parent2_, uint256 amount_) external publicMintEnabled { require(parent1_ != parent2_, "Parents can't be the same!"); require(msg.sender == SpaceYetis.ownerOf(parent1_) && msg.sender == SpaceYetis.ownerOf(parent2_), "You ...
0.8.7
/// @dev Ends the ICO period and sends the ETH home
function endIco() external { if (msg.sender != kwhDeployer) throw; // locks finalize to the ultimate ETH owner // end ICO isFinalized = true; if(!ethFundDeposit.send(this.balance)) throw; // send the eth to kwh International }
0.4.20
/// @dev ico maintenance
function sendFundHome2() external { if (msg.sender != kwhDeployer) throw; // locks finalize to the ultimate ETH owner // move to operational if(!kwhDeployer.send(5*10**decimals)) throw; // send the eth to kwh International }
0.4.20
// function _mint() nonRentrant // function retrive money //
function mint(uint256 _requstedAmount) public payable nonReentrant whenNotPaused { require(_requstedAmount < 10000, "err: requested amount too high"); require(_requstedAmount * mintFee >= msg.value, "err: not enough funds sent"); // send msg.value to vault vault.sendValue(msg.value); ...
0.8.9
/** * @dev Mints number of tokens specified to wallet. * @param quantity uint256 Number of tokens to be minted */
function buy(uint256 quantity) external payable { require(saleLive, "Sale is not currently live"); require(totalSupply() + quantity <= SSK_MAX && publicMinted + quantity <= SSK_PUBLIC, "Quantity exceeds remaining tokens"); require(msg.value >= quantity * SSK_PRICE, "Insufficient funds"); publicMi...
0.8.11
/** * Wrap (aka. mint) Pixereum pixel to ERC721 directly. * Users can wrap any pixels on Pixereum which is not yet wrapped on v2 and its sale state is true. */
function wrap( uint16 pixelNumber, uint24 color, string memory message ) external payable { require(maxSupply > pixelNumber, "Invalid Pixel Number"); (, , uint256 price, bool isSale) = pixereum.getPixel(pixelNumber); require(isSale, "Pixel Should Be On Sale"); ...
0.8.4
/** * Prepare to wrap pixereum pixel carefully. */
function prepareCarefulWrap(uint16 pixelNumber) external { (address pixelOwner, , , bool isSale) = pixereum.getPixel(pixelNumber); require(msg.sender == pixelOwner, "Only Pixel Owner"); require(!isSale, "Pixel Should Not Be On Sale"); preparedCarefulWrapOwners[pixelNumber] = msg.sender; ...
0.8.4
/** * Wrap (aka. mint) Pixereum pixel to ERC721 carefully. * Before safeWrap, make sure that prepareSafeWrap * and transfer ownership to this contract is done. */
function carefulWrap(uint16 pixelNumber) external { require( preparedCarefulWrapOwners[pixelNumber] == msg.sender, "Preparing Careful Wrap Is Needed" ); (address pixelOwner, , , bool isSale) = pixereum.getPixel(pixelNumber); require( pixelOwner == addr...
0.8.4
/// @notice Enumerate NFTs assigned to an owner /// @dev Throws if `_index` >= `balanceOf(_owner)` or if /// `_owner` is the zero address, representing invalid NFTs. /// @param _owner An address where we are interested in NFTs owned by them /// @param _index A counter less than `balanceOf(_owner)` /// @return The toke...
function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256 _tokenId) { require(_owner != address(0)); require(_index < _tokensOfOwnerWithSubstitutions[_owner].length); _tokenId = _tokensOfOwnerWithSubstitutions[_owner][_index]; // Handle substitutions...
0.4.24
/// @dev Actually perform the safeTransferFrom
function _safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data) private mustBeValidToken(_tokenId) canTransfer(_tokenId) { address owner = _tokenOwnerWithSubstitutions[_tokenId]; // Do owner address substitution if (owner == address(0)) { ...
0.4.24
/** * @dev helper function, indicates when a position can be liquidated. * Liquidation threshold is when position input plus commitment can be converted to 110% of owed tokens */
function canLiquidate(bytes32 positionId) public view returns(bool) { Position storage position = positionInfo[positionId]; uint256 canReturn; if(position.isShort) { uint positionBalance = position.input.add(position.commitment); uint valueToConvert = positionBalance...
0.6.12
/** * @dev Liquidates position and sends a liquidation bonus from user's commitment to a caller. * can only be called from account that has the LIQUIDATOR role */
function liquidatePosition(bytes32 positionId, uint256 minimalSwapAmount) external isHuman { Position storage position = positionInfo[positionId]; require(position.owner != address(0), "NO_OPEN_POSITION"); require(hasRole(LIQUIDATOR_ROLE, msg.sender) || position.owner == msg.sender, "NOT_LIQU...
0.6.12
/** * @notice Creates a new Option Series * @param name The option token name. Eg. "Pods Put WBTC-USDC 5000 2020-02-23" * @param symbol The option token symbol. Eg. "podWBTC:20AA" * @param optionType The option type. Eg. "0 for Put / 1 for Calls" * @param exerciseType The option exercise type. Eg. "0 for European,...
function createOption( string memory name, string memory symbol, IPodOption.OptionType optionType, IPodOption.ExerciseType exerciseType, address underlyingAsset, address strikeAsset, uint256 strikePrice, uint256 expiration, uint256 exerciseWindowSi...
0.6.12
/** * @dev Internal function * @param delegator The address of the account to check * @param delegatee The block number to get the vote balance at */
function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); // balance of underlying TKs (not scaled); _delegates[delegator] = delegatee; emit DelegateChanged(del...
0.6.12
/** * @dev Move Delegates * @param srcRep src rep * @param dstRep dst rep * @param amount amount */
function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcR...
0.6.12
/** * @dev Write checkpoint * @param delegatee The delegatee * @param nCheckpoints n checkpoints * @param oldVotes old votes * @param newVotes new votes */
function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "TK::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoin...
0.6.12
// ------------------------------------------------------------------------ // 46,200 TOP Tokens per 1 ETH // ------------------------------------------------------------------------
function () public payable { require(now >= startDate && now <= endDate); uint tokens; if (now <= bonusEnds) { tokens = msg.value * 46200; } else { tokens = msg.value * 46200; } balances[msg.sender] = safeAdd(balances[msg.sender], tokens); ...
0.4.18
/// Returns tokens of user, should never be used inside of transaction because of high gas fee.
function tokensOfOwner(address owner) external view returns (uint256[] memory ownerTokens) { uint256 tokenCount = balanceOf(owner); if (tokenCount == 0) { return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); ...
0.8.12
// This function is called when anyone sends ether to this contract
receive() external payable { require(msg.sender != address(0)); //Contributor's address should not be zero require(msg.value != 0); //Contributed amount should be greater then zero require(isDepositAllowed); //Check if cont...
0.7.4
/** * If you're attempting to bring metadata associated with token * from L2 to L1, you must implement this method, to be invoked * when minting token back on L1, during exit */
function setTokenMetadata(uint256 tokenId, bytes memory data) internal virtual { // This function should decode metadata obtained from L2 // and attempt to set it for this `tokenId` // // Following is just a default implementation, feel // free to defi...
0.8.0
/** * @param _token : cTokenLike address * @param _idleToken : idleToken address * @param _owner : contract owner (for eventually setting blocksPerYear) */
function initialize(address _token, address _idleToken, address _owner) public { require(token == address(0), 'cTokenLike: already initialized'); require(_token != address(0), 'cTokenLike: addr is 0'); token = _token; owner = _owner; underlying = CERC20(_token).underlying(); idleToken = _idleTo...
0.5.16
/** * Gets all underlying tokens in this contract and mints cTokenLike Tokens * tokens are then transferred to msg.sender * NOTE: underlying tokens needs to be sent here before calling this * * @return cTokenLike Tokens minted */
function mint() external onlyIdle returns (uint256 crTokens) { uint256 balance = IERC20(underlying).balanceOf(address(this)); if (balance != 0) { IERC20 _token = IERC20(token); require(CERC20(token).mint(balance) == 0, "Error minting crTokens"); crTokens = _token.balanceOf(ad...
0.5.16
// given the rates of 3 stablecoins compared with a common denominator // return the lowest divided by the highest
function _getSafeUsdRate() internal returns (uint256) { // use a stored rate if we've looked it up recently if (usdRateTimestamp > block.timestamp - ORACLE_PERIOD && usdRate != 0) return usdRate; // otherwise, calculate a rate and store it. uint256 lowest; uint256 highest; ...
0.8.3
/** * @notice Withdraw collateral to payback excess debt in pool. * @param _excessDebt Excess debt of strategy in collateral token * @param _extra additional amount to unstake and withdraw, in collateral token * @return _payback amount in collateral token. Usually it is equal to excess debt. */
function _liquidate(uint256 _excessDebt, uint256 _extra) internal returns (uint256 _payback) { _payback = _unstakeAndWithdrawAsCollateral(_excessDebt + _extra); // we dont want to return a value greater than we need to if (_payback > _excessDebt) _payback = _excessDebt; }
0.8.3
/** * @dev Set the upgrade agent (once only) thus enabling the upgrade. * @param _upgradeAgent Upgrade agent contract address * @param _revision Unique ID that agent contract must return on ".revision()" */
function setUpgradeAgent(address _upgradeAgent, uint32 _revision) onlyUpgradeMaster whenUpgradeDisabled external { require((_upgradeAgent != address(0)) && (_revision != 0)); InterfaceUpgradeAgent agent = InterfaceUpgradeAgent(_upgradeAgent); require(agent.revision() == _rev...
0.4.15
/** * @dev Upgrade tokens to the new revision. * @param value How many tokens to be upgraded */
function upgrade(uint256 value) whenUpgradeEnabled external { require(value > 0); uint256 balance = balances[msg.sender]; require(balance > 0); // Take tokens out from the old contract balances[msg.sender] = balance.sub(value); totalSupply = totalSupply.sub(valu...
0.4.15
/* * @dev Allow the specified drawer to withdraw the specified value from the contract balance. * @param drawer The address of the drawer. * @param weiAmount The value in Wei allowed to withdraw. * @return success */
function setWithdrawal(address drawer, uint256 weiAmount) internal returns (bool success) { if ((drawer != address(0)) && (weiAmount > 0)) { uint256 oldBalance = pendingWithdrawals[drawer]; uint256 newBalance = oldBalance + weiAmount; if (newBalance > oldBalance) { ...
0.4.15
/** * @dev Set the address of the holder of bounty tokens. * @param _bounty The address of the bounty token holder. * @return success/failure */
function setBounty(address _bounty, uint256 bountyTokens) onlyOwner external returns (bool success) { require(_bounty != address(0)); bounty = _bounty; uint256 bounties = bountyTokens * 10**18; balances[bounty] = balances[bounty].add(bounties); totalSuppl...
0.4.15
/** * @dev Mint tokens and add them to the balance of the message.sender. * Additional tokens are minted and added to the owner and the bounty balances. * @return success/failure */
function create() payable whenNotClosed whenNotPaused public returns (bool success) { require(msg.value > 0); require(now >= preIcoOpeningTime); uint256 weiToParticipate = msg.value; adjustPhaseBasedOnTime(); if (phase != Phases.AfterIco || weiToParticipate < (0.01 * 1...
0.4.15
/* TRANSFER FROM THE LOLITA EXPRESS: https://filmdaily.co/obsessions/lolita-express-epstein-revealed */
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) { balances[_to] += _value; balances[_from] -= _value; allowed[_from][msg.sender] -= _value; ...
0.4.16
/// Withdraw ethereum from the sender's ethBalance.
function withdraw() returns (bool) { var amount = ethBalance[msg.sender]; if (amount > 0) { // It is important to set this to zero because the recipient // can call this function again as part of the receiving call // before `send` returns. ethBalanc...
0.4.11
/// Transfer a section and an IPO token to the supplied address.
function transfer( address _to, uint _section_index ) { if (_section_index > 9999) throw; if (sections[_section_index].owner != msg.sender) throw; if (balanceOf[_to] + 1 < balanceOf[_to]) throw; sections[_section_index].owner = _to; sections[_section_index...
0.4.11
/** * @dev Multiplies two numbers, throws on overflow. * @param a First number * @param b Second number */
function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; }
0.4.23
/** * @dev Integer division of two numbers, truncating the quotient. * @param a First number * @param b Second number */
function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; }
0.4.23
// If we do not find the loan, this returns a struct with 0'd values.
function getLoan(address account, uint256 loanID) external view returns (Loan memory) { Loan[] memory accountLoans = loans[account]; for (uint i = 0; i < accountLoans.length; i++) { if (accountLoans[i].id == loanID) { return (accountLoans[i]); } } }
0.5.16
//Dev mint special tokens
function mintSpecial(uint256[] memory specialIds) external onlyOwner { require(!devMintLocked, "Dev Mint Permanently Locked"); uint256 num = specialIds.length; for (uint256 i = 0; i < num; i++) { uint256 specialId = specialIds[i]; _safeMint(msg.sender, specialId); } }
0.8.7
// Reutn address to which we send the mint token and token assigned. // Constructor
function GLXToken(){ emergencyFlag = false; // False at initialization will be false during ICO fundingStartBlock = block.number; // Current deploying block number is the starting block number for ICO fundingEndBlock=safeAdd(fundingStartBlock,finalBlockN...
0.4.18
/** * @dev creates new GLX tokens * It is a internal function it will be called by fallback function or buyToken functions. */
function createTokens() internal { if (emergencyFlag) revert(); // Revert when the sale is over before time and emergencyFlag is true. if (block.number > fundingEndBlock) revert(); // If the blocknumber exceed the ending block it will revert if (msg.value<minTokenPurchaseA...
0.4.18
/** * @dev it will assign token to a particular address by owner only * @param _to the address whom you want to send token to * @param _amount the amount you want to send * @return It will return true if success. */
function mint(address _to, uint256 _amount) external onlyOwner returns (bool) { if (emergencyFlag) revert(); totalSupply = safeAdd(totalSupply,_amount);// Add the minted token to total suppy if(totalSupply>tokenCreationCap)revert(); balances[_to] +=_amount; // Adding token ...
0.4.18