comment
stringlengths
11
2.99k
function_code
stringlengths
165
3.15k
version
stringclasses
80 values
// Useless Function ( Public ) //??? Function 01 - Store Comission From Unfinished Hodl
function StoreComission(address tokenAddress, uint256 amount) private { _systemReserves[tokenAddress] = add(_systemReserves[tokenAddress], amount); bool isNew = true; for(uint256 i = 0; i < _listedReserves.length; i++) { if(_listedReserves[i] == tokenAddress) { isNew = false; break; } } if(isNew) _listedReserves.push(tokenAddress); }
0.4.25
//??? Function 02 - Delete Safe Values In Storage
function DeleteSafe(Safe s) private { _totalSaved[s.tokenAddress] = sub(_totalSaved[s.tokenAddress], s.amount); delete _safes[s.id]; uint256[] storage vector = _userSafes[msg.sender]; uint256 size = vector.length; for(uint256 i = 0; i < size; i++) { if(vector[i] == s.id) { vector[i] = vector[size-1]; vector.length--; break; } } }
0.4.25
//??? Function 04 - Get User's Any Token Balance
function GetHodlTokensBalance(address tokenAddress) public view returns (uint256 balance) { require(tokenAddress != 0x0); for(uint256 i = 1; i < _currentIndex; i++) { Safe storage s = _safes[i]; if(s.user == msg.sender && s.tokenAddress == tokenAddress) balance += s.amount; } return balance; }
0.4.25
// 07 Withdraw All Eth And All Tokens Fees
function WithdrawAllFees() onlyOwner public { // Ether uint256 x = _systemReserves[0x0]; if(x > 0 && x <= address(this).balance) { _systemReserves[0x0] = 0; msg.sender.transfer(_systemReserves[0x0]); } // Tokens address ta; ERC20Interface token; for(uint256 i = 0; i < _listedReserves.length; i++) { ta = _listedReserves[i]; if(_systemReserves[ta] > 0) { x = _systemReserves[ta]; _systemReserves[ta] = 0; token = ERC20Interface(ta); token.transfer(msg.sender, x); } } _listedReserves.length = 0; }
0.4.25
// 08 - Returns All Tokens Addresses With Fees
function GetTokensAddressesWithFees() onlyOwner public view returns (address[], string[], uint256[]) { uint256 length = _listedReserves.length; address[] memory tokenAddress = new address[](length); string[] memory tokenSymbol = new string[](length); uint256[] memory tokenFees = new uint256[](length); for (uint256 i = 0; i < length; i++) { tokenAddress[i] = _listedReserves[i]; ERC20Interface token = ERC20Interface(tokenAddress[i]); tokenSymbol[i] = token.symbol(); tokenFees[i] = GetTokenFees(tokenAddress[i]); } return (tokenAddress, tokenSymbol, tokenFees); }
0.4.25
// 09 - Return All Tokens To Their Respective Addresses
function ReturnAllTokens(bool onlyAXPR) onlyOwner public { uint256 returned; for(uint256 i = 1; i < _currentIndex; i++) { Safe storage s = _safes[i]; if (s.id != 0) { if ( (onlyAXPR && s.tokenAddress == AXPRtoken) || !onlyAXPR ) { PayToken(s.user, s.tokenAddress, s.amountbalance); _countSafes--; returned++; } } } emit onReturnAll(returned); }
0.4.25
/** * SAFE MATH FUNCTIONS * * @dev Multiplies two numbers, throws on overflow. */
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; }
0.4.25
/** * Creates the contract and sets the owners * @param owners_dot_recipient - array of 16 owner records (MultiOwnable.Owner.recipient fields) * @param owners_dot_share - array of 16 owner records (MultiOwnable.Owner.share fields) */
function BlindCroupierTokenDistribution (address[16] owners_dot_recipient, uint[16] owners_dot_share) MultiOwnable(owners_dot_recipient, owners_dot_share) { MultiOwnable.Owner[16] memory owners; for(uint __recipient_iterator__ = 0; __recipient_iterator__ < owners_dot_recipient.length;__recipient_iterator__++) owners[__recipient_iterator__].recipient = address(owners_dot_recipient[__recipient_iterator__]); for(uint __share_iterator__ = 0; __share_iterator__ < owners_dot_share.length;__share_iterator__++) owners[__share_iterator__].share = uint(owners_dot_share[__share_iterator__]); state = State.NotStarted; }
0.4.15
/** * @notice Sets integrator fee percentage. * @param _amount Percentage amount. */
function setIntegratorFeePct(uint256 _amount) external { require( accessControls.hasAdminRole(msg.sender), "MISOTokenFactory: Sender must be operator" ); /// @dev this is out of 1000, ie 25% = 250 require( _amount <= INTEGRATOR_FEE_PRECISION, "MISOTokenFactory: Range is from 0 to 1000" ); integratorFeePct = _amount; }
0.6.12
/** * @notice Sets the current template ID for any type. * @param _templateType Type of template. * @param _templateId The ID of the current template for that type */
function setCurrentTemplateId(uint256 _templateType, uint256 _templateId) external { require( accessControls.hasAdminRole(msg.sender) || accessControls.hasOperatorRole(msg.sender), "MISOTokenFactory: Sender must be admin" ); require(tokenTemplates[_templateId] != address(0), "MISOTokenFactory: incorrect _templateId"); require(IMisoToken(tokenTemplates[_templateId]).tokenTemplate() == _templateType, "MISOTokenFactory: incorrect _templateType"); currentTemplateId[_templateType] = _templateId; }
0.6.12
/** * @notice Creates a token corresponding to template id and transfers fees. * @dev Initializes token with parameters passed * @param _templateId Template id of token to create. * @param _integratorFeeAccount Address to pay the fee to. * @return token Token address. */
function deployToken( uint256 _templateId, address payable _integratorFeeAccount ) public payable returns (address token) { /// @dev If the contract is locked, only admin and minters can deploy. if (locked) { require(accessControls.hasAdminRole(msg.sender) || accessControls.hasMinterRole(msg.sender) || hasTokenMinterRole(msg.sender), "MISOTokenFactory: Sender must be minter if locked" ); } require(msg.value >= minimumFee, "MISOTokenFactory: Failed to transfer minimumFee"); require(tokenTemplates[_templateId] != address(0), "MISOTokenFactory: incorrect _templateId"); uint256 integratorFee = 0; uint256 misoFee = msg.value; if (_integratorFeeAccount != address(0) && _integratorFeeAccount != misoDiv) { integratorFee = misoFee * integratorFeePct / INTEGRATOR_FEE_PRECISION; misoFee = misoFee - integratorFee; } token = createClone(tokenTemplates[_templateId]); /// @dev GP: Triple check the token index is correct. tokenInfo[token] = Token(true, _templateId, tokens.length); tokens.push(token); emit TokenCreated(msg.sender, token, tokenTemplates[_templateId]); if (misoFee > 0) { misoDiv.transfer(misoFee); } if (integratorFee > 0) { _integratorFeeAccount.transfer(integratorFee); } }
0.6.12
/** * @notice Creates a token corresponding to template id. * @dev Initializes token with parameters passed. * @param _templateId Template id of token to create. * @param _integratorFeeAccount Address to pay the fee to. * @param _data Data to be passed to the token contract for init. * @return token Token address. */
function createToken( uint256 _templateId, address payable _integratorFeeAccount, bytes calldata _data ) external payable returns (address token) { token = deployToken(_templateId, _integratorFeeAccount); emit TokenInitialized(address(token), _templateId, _data); IMisoToken(token).initToken(_data); uint256 initialTokens = IERC20(token).balanceOf(address(this)); if (initialTokens > 0 ) { _safeTransfer(token, msg.sender, initialTokens); } }
0.6.12
/** * @notice Function to add a token template to create through factory. * @dev Should have operator access. * @param _template Token template to create a token. */
function addTokenTemplate(address _template) external { require( accessControls.hasAdminRole(msg.sender) || accessControls.hasOperatorRole(msg.sender), "MISOTokenFactory: Sender must be operator" ); uint256 templateType = IMisoToken(_template).tokenTemplate(); require(templateType > 0, "MISOTokenFactory: Incorrect template code "); require(tokenTemplateToId[_template] == 0, "MISOTokenFactory: Template exists"); tokenTemplateId++; tokenTemplates[tokenTemplateId] = _template; tokenTemplateToId[_template] = tokenTemplateId; currentTemplateId[templateType] = tokenTemplateId; emit TokenTemplateAdded(_template, tokenTemplateId); }
0.6.12
/** * @notice Function to remove a token template. * @dev Should have operator access. * @param _templateId Refers to template that is to be deleted. */
function removeTokenTemplate(uint256 _templateId) external { require( accessControls.hasAdminRole(msg.sender) || accessControls.hasOperatorRole(msg.sender), "MISOTokenFactory: Sender must be operator" ); require(tokenTemplates[_templateId] != address(0)); address template = tokenTemplates[_templateId]; uint256 templateType = IMisoToken(tokenTemplates[_templateId]).tokenTemplate(); if (currentTemplateId[templateType] == _templateId) { delete currentTemplateId[templateType]; } tokenTemplates[_templateId] = address(0); delete tokenTemplateToId[template]; emit TokenTemplateRemoved(template, _templateId); }
0.6.12
/** * @notice Transfer `_amount` from `msg.sender.address()` to `_to`. * * @param _to Address that will receive. * @param _amount Amount to be transferred. */
function transfer(address _to, uint256 _amount) returns (bool success) { assert(allowTransactions); assert(!frozenAccount[msg.sender]); assert(balanceOf[msg.sender] >= _amount); assert(balanceOf[_to] + _amount >= balanceOf[_to]); activateAccount(msg.sender); activateAccount(_to); balanceOf[msg.sender] -= _amount; if (_to == address(this)) treasuryBalance += _amount; else balanceOf[_to] += _amount; Transfer(msg.sender, _to, _amount); return true; }
0.3.6
/** * @notice Transfer `_amount` from `_from` to `_to`. * * @param _from Origin address * @param _to Address that will receive * @param _amount Amount to be transferred. * @return result of the method call */
function transferFrom(address _from, address _to, uint256 _amount) returns (bool success) { assert(allowTransactions); assert(!frozenAccount[msg.sender]); assert(!frozenAccount[_from]); assert(balanceOf[_from] >= _amount); assert(balanceOf[_to] + _amount >= balanceOf[_to]); assert(_amount <= allowance[_from][msg.sender]); balanceOf[_from] -= _amount; balanceOf[_to] += _amount; allowance[_from][msg.sender] -= _amount; activateAccount(_from); activateAccount(_to); activateAccount(msg.sender); Transfer(_from, _to, _amount); return true; }
0.3.6
/** * @notice Approve spender `_spender` to transfer `_amount` from `msg.sender.address()` * * @param _spender Address that receives the cheque * @param _amount Amount on the cheque * @param _extraData Consequential contract to be executed by spender in same transcation. * @return result of the method call */
function approveAndCall(address _spender, uint256 _amount, bytes _extraData) returns (bool success) { assert(allowTransactions); assert(!frozenAccount[msg.sender]); allowance[msg.sender][_spender] = _amount; activateAccount(msg.sender); activateAccount(_spender); activateAllowanceRecord(msg.sender, _spender); TokenRecipient spender = TokenRecipient(_spender); spender.receiveApproval(msg.sender, _amount, this, _extraData); Approval(msg.sender, _spender, _amount); return true; }
0.3.6
/// @dev Called by the DSProxy contract which owns the Compound position /// @notice Adds the users Compound poistion in the list of subscriptions so it can be monitored /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalBoost Ratio amount which boost should target /// @param _optimalRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled
function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) external { // if boost is not enabled, set max ratio to max uint uint128 localMaxRatio = _boostEnabled ? _maxRatio : uint128(-1); require(checkParams(_minRatio, localMaxRatio), "Must be correct params"); SubPosition storage subInfo = subscribersPos[msg.sender]; CompoundHolder memory subscription = CompoundHolder({ minRatio: _minRatio, maxRatio: localMaxRatio, optimalRatioBoost: _optimalBoost, optimalRatioRepay: _optimalRepay, user: msg.sender, boostEnabled: _boostEnabled }); changeIndex++; if (subInfo.subscribed) { subscribers[subInfo.arrPos] = subscription; emit Updated(msg.sender); emit ParamUpdates(msg.sender, _minRatio, localMaxRatio, _optimalBoost, _optimalRepay, _boostEnabled); } else { subscribers.push(subscription); subInfo.arrPos = subscribers.length - 1; subInfo.subscribed = true; emit Subscribed(msg.sender); } }
0.6.6
/// @dev Internal method to remove a subscriber from the list /// @param _user The actual address that owns the Compound position
function _unsubscribe(address _user) internal { require(subscribers.length > 0, "Must have subscribers in the list"); SubPosition storage subInfo = subscribersPos[_user]; require(subInfo.subscribed, "Must first be subscribed"); address lastOwner = subscribers[subscribers.length - 1].user; SubPosition storage subInfo2 = subscribersPos[lastOwner]; subInfo2.arrPos = subInfo.arrPos; subscribers[subInfo.arrPos] = subscribers[subscribers.length - 1]; subscribers.pop(); // remove last element and reduce arr length changeIndex++; subInfo.subscribed = false; subInfo.arrPos = 0; emit Unsubscribed(msg.sender); }
0.6.6
/// @notice Helper method for the frontend, returns all the subscribed CDPs paginated /// @param _page What page of subscribers you want /// @param _perPage Number of entries per page /// @return List of all subscribers for that page
function getSubscribersByPage(uint _page, uint _perPage) public view returns (CompoundHolder[] memory) { CompoundHolder[] memory holders = new CompoundHolder[](_perPage); uint start = _page * _perPage; uint end = start + _perPage; end = (end > holders.length) ? holders.length : end; uint count = 0; for (uint i = start; i < end; i++) { holders[count] = subscribers[i]; count++; } return holders; }
0.6.6
/** * @notice 'Returns the fee for a transfer from `from` to `to` on an amount `amount`. * * Fee's consist of a possible * - import fee on transfers to an address * - export fee on transfers from an address * DVIP ownership on an address * - reduces fee on a transfer from this address to an import fee-ed address * - reduces the fee on a transfer to this address from an export fee-ed address * DVIP discount does not work for addresses that have an import fee or export fee set up against them. * * DVIP discount goes up to 100% * * @param from From address * @param to To address * @param amount Amount for which fee needs to be calculated. * */
function feeFor(address from, address to, uint256 amount) constant external returns (uint256 value) { uint256 fee = exportFee[from] + importFee[to]; if (fee == 0) return 0; uint256 amountHeld; bool discounted = true; uint256 oneDVIPUnit; if (exportFee[from] == 0 && balanceOf[from] != 0 && now < expiry) { amountHeld = balanceOf[from]; } else if (importFee[to] == 0 && balanceOf[to] != 0 && now < expiry) { amountHeld = balanceOf[to]; } else discounted = false; if (discounted) { oneDVIPUnit = pow10(1, decimals); if (amountHeld > oneDVIPUnit) amountHeld = oneDVIPUnit; uint256 remaining = oneDVIPUnit - amountHeld; return div10(amount*fee*remaining, decimals*2); } return div10(amount*fee, decimals); }
0.3.6
/** * @dev low level token purchase ***DO NOT OVERRIDE*** * This function has a non-reentrancy guard, so it shouldn't be called by * another `nonReentrant` function. */
function buyTokens() public payable { uint256 weiAmount = msg.value; _preValidatePurchase(_msgSender(), weiAmount); // calculate token amount to be created uint256 tokens = _getTokenAmount(weiAmount); // update state require(_weiRaised <= _maxCapETH); _weiRaised = _weiRaised.add(weiAmount); emit TokensPurchased(_msgSender(), _msgSender(), weiAmount, tokens); _forwardFunds(); _currentSaleToken = _currentSaleToken.add(tokens); require(_capTokenSale >= _currentSaleToken); _balances[_msgSender()] = _balances[_msgSender()].add(tokens); }
0.6.12
/** * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. * Use `super` in contracts that inherit from Crowdsale to extend their validations. * Example from CappedCrowdsale.sol's _preValidatePurchase method: * super._preValidatePurchase(beneficiary, weiAmount); * require(weiRaised().add(weiAmount) <= cap); * @param beneficiary Address performing the token purchase * @param weiAmount Value in wei involved in the purchase */
function _preValidatePurchase(address beneficiary, uint256 weiAmount) internal virtual { require( beneficiary != address(0), "Crowdsale: beneficiary is the zero address" ); require(weiAmount != 0, "Crowdsale: weiAmount is 0"); require( weiAmount >= _individualMinCap, "Crowdsale: Min individual cap" ); _balancesPurchased[beneficiary] = _balancesPurchased[beneficiary].add( weiAmount ); require( _balancesPurchased[beneficiary] <= _individualMaxCap, "Crowdsale: Max individual cap" ); }
0.6.12
/** * @dev Upper bound search function which is kind of binary search algoritm. It searches sorted * array to find index of the element value. If element is found then returns it's index otherwise * it returns index of first element which is grater than searched value. If searched element is * bigger than any array element function then returns first index after last element (i.e. all * values inside the array are smaller than the target). Complexity O(log n). * @param array The array sorted in ascending order. * @param element The element's value to be find. * @return The calculated index value. Returns 0 for empty array. */
function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) { if (array.length == 0) { return 0; } uint256 low = 0; uint256 high = array.length; while (low < high) { uint256 mid = Math.average(low, high); // Note that mid will always be strictly less than high (i.e. it will be a valid array index) // because Math.average rounds down (it does integer division with truncation). if (array[mid] > element) { high = mid; } else { low = mid + 1; } } // At this point `low` is the exclusive upper bound. We will return the inclusive upper bound. if (low > 0 && array[low - 1] == element) { return low - 1; } else { return low; } }
0.5.0
/** * @notice Query if a contract supports ERC165 * @param account The address of the contract to query for support of ERC165 * @return true if the contract at account implements ERC165 */
function _supportsERC165(address account) internal view returns (bool) { // Any contract that implements ERC165 must explicitly indicate support of // InterfaceId_ERC165 and explicitly indicate non-support of InterfaceId_Invalid return _supportsERC165Interface(account, _INTERFACE_ID_ERC165) && !_supportsERC165Interface(account, _INTERFACE_ID_INVALID); }
0.5.0
/** * @notice Query if a contract implements interfaces, also checks support of ERC165 * @param account The address of the contract to query for support of an interface * @param interfaceIds A list of interface identifiers, as specified in ERC-165 * @return true if the contract at account indicates support all interfaces in the * interfaceIds list, false otherwise * @dev Interface identification is specified in ERC-165. */
function _supportsAllInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool) { // query support of ERC165 itself if (!_supportsERC165(account)) { return false; } // query support of each interface in _interfaceIds for (uint256 i = 0; i < interfaceIds.length; i++) { if (!_supportsERC165Interface(account, interfaceIds[i])) { return false; } } // all interfaces supported return true; }
0.5.0
/** * @notice Query if a contract implements an interface, does not check ERC165 support * @param account The address of the contract to query for support of an interface * @param interfaceId The interface identifier, as specified in ERC-165 * @return true if the contract at account indicates support of the interface with * identifier interfaceId, false otherwise * @dev Assumes that account contains a contract that supports ERC165, otherwise * the behavior of this method is undefined. This precondition can be checked * with the `supportsERC165` method in this library. * Interface identification is specified in ERC-165. */
function _supportsERC165Interface(address account, bytes4 interfaceId) private view returns (bool) { // success determines whether the staticcall succeeded and result determines // whether the contract at account indicates support of _interfaceId (bool success, bool result) = _callERC165SupportsInterface(account, interfaceId); return (success && result); }
0.5.0
/** * @notice Calls the function with selector 0x01ffc9a7 (ERC165) and suppresses throw * @param account The address of the contract to query for support of an interface * @param interfaceId The interface identifier, as specified in ERC-165 * @return success true if the STATICCALL succeeded, false otherwise * @return result true if the STATICCALL succeeded and the contract at account * indicates support of the interface with identifier interfaceId, false otherwise */
function _callERC165SupportsInterface(address account, bytes4 interfaceId) private view returns (bool success, bool result) { bytes memory encodedParams = abi.encodeWithSelector(_INTERFACE_ID_ERC165, interfaceId); // solhint-disable-next-line no-inline-assembly assembly { let encodedParams_data := add(0x20, encodedParams) let encodedParams_size := mload(encodedParams) let output := mload(0x40) // Find empty storage location using "free memory pointer" mstore(output, 0x0) success := staticcall( 30000, // 30k gas account, // To addr encodedParams_data, encodedParams_size, output, 0x20 // Outputs are 32 bytes long ) result := mload(output) // Load the result } }
0.5.0
/** * @dev Appends a byte array to the end of the buffer. Resizes if doing so * would exceed the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer. */
function append(buffer memory buf, bytes data) internal pure returns(buffer memory) { if(data.length + buf.buf.length > buf.capacity) { resize(buf, max(buf.capacity, data.length) * 2); } uint dest; uint src; uint len = data.length; assembly { // Memory address of the buffer data let bufptr := mload(buf) // Length of existing buffer data let buflen := mload(bufptr) // Start address = buffer address + buffer length + sizeof(buffer length) dest := add(add(bufptr, buflen), 32) // Update buffer length mstore(bufptr, add(buflen, mload(data))) src := add(data, 32) } // Copy word-length chunks while possible for(; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } // Copy remaining bytes uint mask = 256 ** (32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } return buf; }
0.4.24
// "addresses" may not be longer than 256
function arrayContainsAddress256(address[] addresses, address value) internal pure returns (bool) { for (uint8 i = 0; i < addresses.length; i++) { if (addresses[i] == value) { return true; } } return false; }
0.4.16
// creates clone using minimal proxy
function createClone(bytes32 _salt, address _target) internal returns (address _result) { bytes20 _targetBytes = bytes20(_target); assembly { let clone := mload(0x40) mstore(clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(clone, 0x14), _targetBytes) mstore(add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) _result := create2(0, clone, 0x37, _salt) } require(_result != address(0), "Create2: Failed on minimal deploy"); }
0.7.3
// parseInt(parseFloat*10^_b)
function parseInt(string _a, uint _b) internal pure returns (uint) { bytes memory bresult = bytes(_a); uint mint = 0; bool decimals = false; for (uint i=0; i<bresult.length; i++){ if ((bresult[i] >= 48)&&(bresult[i] <= 57)){ if (decimals){ if (_b == 0) break; else _b--; } mint *= 10; mint += uint(bresult[i]) - 48; } else if (bresult[i] == 46) decimals = true; } if (_b > 0) mint *= 10**_b; return mint; }
0.4.24
// the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset) internal pure returns (bytes) { uint minLength = length + toOffset; // Buffer too small require(to.length >= minLength); // Should be a better way? // NOTE: the offset 32 is added to skip the `size` field of both bytes variables uint i = 32 + fromOffset; uint j = 32 + toOffset; while (i < (32 + fromOffset + length)) { assembly { let tmp := mload(add(from, i)) mstore(add(to, j), tmp) } i += 32; j += 32; } return to; }
0.4.24
// the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license // Duplicate Solidity's ecrecover, but catching the CALL return value
function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) { // We do our own memory management here. Solidity uses memory offset // 0x40 to store the current end of memory. We write past it (as // writes are memory extensions), but don't update the offset so // Solidity will reuse it. The memory used here is only needed for // this context. // FIXME: inline assembly can't access return values bool ret; address addr; assembly { let size := mload(0x40) mstore(size, hash) mstore(add(size, 32), v) mstore(add(size, 64), r) mstore(add(size, 96), s) // NOTE: we can reuse the request memory because we deal with // the return code ret := call(3000, 1, 0, size, 128, size, 32) addr := mload(size) } return (ret, addr); }
0.4.24
/** * Hook on `transfer` and call `Withdraw.beforeBalanceChange` function. */
function transfer(address _to, uint256 _value) public returns (bool) { /** * Validates the destination is not 0 address. */ require(_to != address(0), "this is illegal address"); require(_value != 0, "illegal transfer value"); /** * Calls Withdraw contract via Allocator contract. * Passing through the Allocator contract is due to the historical reason for the old Property contract. */ IAllocator(config().allocator()).beforeBalanceChange( address(this), msg.sender, _to ); /** * Calls the transfer of ERC20. */ _transfer(msg.sender, _to, _value); return true; }
0.5.17
/** * Hook on `transferFrom` and call `Withdraw.beforeBalanceChange` function. */
function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { /** * Validates the source and destination is not 0 address. */ require(_from != address(0), "this is illegal address"); require(_to != address(0), "this is illegal address"); require(_value != 0, "illegal transfer value"); /** * Calls Withdraw contract via Allocator contract. * Passing through the Allocator contract is due to the historical reason for the old Property contract. */ IAllocator(config().allocator()).beforeBalanceChange( address(this), _from, _to ); /** * Calls the transfer of ERC20. */ _transfer(_from, _to, _value); /** * Reduces the allowance amount. */ uint256 allowanceAmount = allowance(_from, msg.sender); _approve( _from, msg.sender, allowanceAmount.sub( _value, "ERC20: transfer amount exceeds allowance" ) ); return true; }
0.5.17
/** * Transfers the staking amount to the original owner. */
function withdraw(address _sender, uint256 _value) external { /** * Validates the sender is Lockup contract. */ require(msg.sender == config().lockup(), "this is illegal address"); /** * Transfers the passed amount to the original owner. */ ERC20 devToken = ERC20(config().token()); bool result = devToken.transfer(_sender, _value); require(result, "dev transfer failed"); }
0.5.17
/** * Sets EToken2 address, assigns symbol and name. * * Can be set only once. * * @param _etoken2 EToken2 contract address. * @param _symbol assigned symbol. * @param _name assigned name. * * @return success. */
function init(EToken2Interface _etoken2, string _symbol, string _name) returns(bool) { if (address(etoken2) != 0x0) { return false; } etoken2 = _etoken2; etoken2Symbol = _bytes32(_symbol); name = _name; symbol = _symbol; return true; }
0.4.15
/** * Propose next asset implementation contract address. * * Can only be called by current asset owner. * * Note: freeze-time should not be applied for the initial setup. * * @param _newVersion asset implementation contract address. * * @return success. */
function proposeUpgrade(address _newVersion) onlyAssetOwner() returns(bool) { // Should not already be in the upgrading process. if (pendingVersion != 0x0) { return false; } // New version address should be other than 0x0. if (_newVersion == 0x0) { return false; } // Don't apply freeze-time for the initial setup. if (latestVersion == 0x0) { latestVersion = _newVersion; return true; } pendingVersion = _newVersion; pendingVersionTimestamp = now; UpgradeProposal(_newVersion); return true; }
0.4.15
/** * Finalize an upgrade process setting new asset implementation contract address. * * Can only be called after an upgrade freeze-time. * * @return success. */
function commitUpgrade() returns(bool) { if (pendingVersion == 0x0) { return false; } if (pendingVersionTimestamp + UPGRADE_FREEZE_TIME > now) { return false; } latestVersion = pendingVersion; delete pendingVersion; delete pendingVersionTimestamp; return true; }
0.4.15
/* * @dev Returns a newly allocated string containing the concatenation of * `self` and `other`. * @param self The first slice to concatenate. * @param other The second slice to concatenate. * @return The concatenation of the two strings. */
function concat(slice memory self, slice memory other) internal pure returns (string memory) { string memory ret = new string(self._len + other._len); uint retptr; assembly { retptr := add(ret, 32) } memcpy(retptr, self._ptr, self._len); memcpy(retptr + self._len, other._ptr, other._len); return ret; }
0.5.0
// SCALE-encode payload
function encodeCall( address _token, address _sender, bytes32 _recipient, uint256 _amount ) private pure returns (bytes memory) { return abi.encodePacked( MINT_CALL, _token, _sender, byte(0x00), // Encode recipient as MultiAddress::Id _recipient, _amount.encode256() ); }
0.7.6
// Decodes a SCALE encoded uint256 by converting bytes (bid endian) to little endian format
function decodeUint256(bytes memory data) public pure returns (uint256) { uint256 number; for (uint256 i = data.length; i > 0; i--) { number = number + uint256(uint8(data[i - 1])) * (2**(8 * (i - 1))); } return number; }
0.7.6
// Sources: // * https://ethereum.stackexchange.com/questions/15350/how-to-convert-an-bytes-to-address-in-solidity/50528 // * https://graphics.stanford.edu/~seander/bithacks.html#ReverseParallel
function reverse256(uint256 input) internal pure returns (uint256 v) { v = input; // swap bytes v = ((v & 0xFF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00) >> 8) | ((v & 0x00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF) << 8); // swap 2-byte long pairs v = ((v & 0xFFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000) >> 16) | ((v & 0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF) << 16); // swap 4-byte long pairs v = ((v & 0xFFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000) >> 32) | ((v & 0x00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF) << 32); // swap 8-byte long pairs v = ((v & 0xFFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF0000000000000000) >> 64) | ((v & 0x0000000000000000FFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF) << 64); // swap 16-byte long pairs v = (v >> 128) | (v << 128); }
0.7.6
// ========== Claiming ==========
function burnForPhysical(uint16[] calldata _burnTokenIds, uint16 editionId, uint16 editionTokenId, bool claimNFT) public whenNotPaused nonReentrant { require(editionId <= numBurnEditions, "Edition not found"); require(_burnTokenIds.length > 0, "No tokens to burn"); BurnEdition storage edition = burnEditions[editionId]; require(edition.supportedToken == editionTokenId, "Token Id is not supported for edition"); // Calculate quantity require(_burnTokenIds.length % edition.tokenCost == 0, "Quantity must be a multiple of token cost"); uint16 _quantity = uint16(_burnTokenIds.length) / edition.tokenCost; // Can only claim if there is supply remaining numClaimsByTokenID[editionTokenId] += _quantity; require(numClaimsByTokenID[editionTokenId] <= maximumSupplyByTokenID[editionTokenId], "Not enough tokens remaining"); // Check that tokens are owned by the caller and burn if(edition.contractType == ContractType.ERC721) { IERC721Burnable supportedContract = IERC721Burnable(edition.contractAddress); for (uint16 i=0; i < _burnTokenIds.length; i++) { supportedContract.burn(_burnTokenIds[i]); } } else if (edition.contractType == ContractType.ERC1155) { IERC1155Burnable supportedContract = IERC1155Burnable(edition.contractAddress); for (uint16 i=0; i < _burnTokenIds.length; i++) { supportedContract.burn(msg.sender, _burnTokenIds[i], 1); } } if(claimNFT) { _mint(msg.sender, editionTokenId, _quantity, ""); } emit ClaimedPhysicalEdition(msg.sender, editionId, editionTokenId); }
0.8.9
/* setWinner function - set the winning contract */
function setWinner(uint256 _gameId) public onlyGameContractOrOwner { require(_gameId == gameContractObject.gameId()); assert(gameContractObject.state() == GameContract.GameState.RandomReceived); assert(!isWinner); isWinner = true; address houseAddressOne = gameContractObject.getHouseAddressOne(); address houseAddressTwo = gameContractObject.getHouseAddressTwo(); address referralAddress = gameContractObject.getReferralAddress(); if (totalBid == 0) { houseAddressOne.transfer((address(this).balance * 70)/100); houseAddressTwo.transfer(address(this).balance); settlementType = 0; } else if (totalBid == address(this).balance) { settlementType = 1; } else { totalBalance = address(this).balance - totalBid; uint256 houseAddressShare = gameContractObject.getHouseAddressShare(); houseAddressOne.transfer((totalBalance * houseAddressShare * 70) / 10000);/* 70 percent of house share goes to bucket one */ houseAddressTwo.transfer((totalBalance * houseAddressShare * 30) / 10000);/* 30 percent of house share goes to bucket one */ referralAmount = (totalBalance * gameContractObject.getReferralAddressShare())/100; referralAddress.transfer(referralAmount); totalBalance = address(this).balance; settlementType = 2; } processed = 0; remaining = betters.length; }
0.4.25
// ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to a smart contract and receive approval // - Owner's account must have sufficient balance to transfer // - Smartcontract must accept the payment // - 0 value transfers are allowed // ------------------------------------------------------------------------
function transferAndCall(address to, uint tokens, bytes memory data) public returns (bool success) { require (tokens <= balances[msg.sender] ); balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); require (TransferAndCallFallBack(to).receiveTransfer(msg.sender, tokens, data)); emit Transfer(msg.sender, to, tokens); return true; }
0.7.4
// ---------------------------------------------------------------------------- // Buy EASY tokens for ETH by exchange rate // ----------------------------------------------------------------------------
function buyTokens() public payable returns (bool success) { require (msg.value > 0, "ETH amount should be greater than zero"); uint tokenAmount = _exchangeRate * msg.value; balances[owner] = safeSub(balances[owner], tokenAmount); balances[msg.sender] = safeAdd(balances[msg.sender], tokenAmount); emit Transfer(owner, msg.sender, tokenAmount); return true; }
0.7.4
/// @dev Courtesy of https://github.com/gnosis/MultiSigWallet/blob/master/contracts/MultiSigWallet.sol /// This method allows the pre-defined recipient to call other smart contracts.
function externalCall(address destination, uint256 value, bytes data) public returns (bool) { require(msg.sender == recipient, "Sender must be the recipient."); uint256 dataLength = data.length; bool result; assembly { let x := mload(0x40) // "Allocate" memory for output (0x40 is where "free memory" pointer is stored by convention) let d := add(data, 32) // First 32 bytes are the padded length of data, so exclude that result := call( sub(gas, 34710), // 34710 is the value that solidity is currently emitting // It includes callGas (700) + callVeryLow (3, to pay for SUB) + callValueTransferGas (9000) + // callNewAccountGas (25000, in case the destination address does not exist and needs creating) destination, value, d, dataLength, // Size of the input (in bytes) - this is what fixes the padding problem x, 0 // Output is ignored, therefore the output size is zero ) } return result; }
0.4.24
// effects // energy + metabolism // OG1/2 // ghost aura effect // indiv equip effect // make sure this amt roughly on same magnitude with 1e18
function getVirtualAmt(uint256 tamagId) public view returns (uint256) { // cater to both tamag versions. Assume that any id is only either V1 OR V2, not both. uint256 trait = 0; bool isV2 = tamag.exists(tamagId); if (isV2){ // it's a V2; trait = tamag.getTrait(tamagId); } else { trait = oldTamag.getTrait(tamagId); } // uint256 cheerfulness = getCheerfulness(trait); uint256 energy = getEnergy(trait); uint256 metabolism = getMetabolism(trait); // values obtained are out of 0-31 inclusive uint256 result = energy.add(metabolism).mul(1e18); // range of 0-64 1E18 uint256 tempTamagId = isV2 ? tamagId : tamagId + 1; // see constructor for explanation if (og1.contains(tempTamagId)){ result = result.mul(OG1_BONUS).div(100); }else if (og2.contains(tempTamagId)){ result = result.mul(OG2_BONUS).div(100); } if (isV2){ uint256 bonuses = getBonuses(tamagId); if (bonuses > 0){ result = result.mul(bonuses.add(100)).div(100); } } return result; }
0.6.12
/** * @notice Create PixelCon `(_tokenId)` * @dev Throws if the token ID already exists * @param _to Address that will own the PixelCon * @param _tokenId ID of the PixelCon to be creates * @param _name PixelCon name (not required) * @return The index of the new PixelCon */
function create(address _to, uint256 _tokenId, bytes8 _name) public payable validAddress(_to) validId(_tokenId) returns(uint64) { TokenLookup storage lookupData = tokenLookup[_tokenId]; require(pixelcons.length < uint256(2 ** 64) - 1, "Max number of PixelCons has been reached"); require(lookupData.owner == address(0), "PixelCon already exists"); //get created timestamp (zero as date indicates null) uint32 dateCreated = 0; if (now < uint256(2 ** 32)) dateCreated = uint32(now); //create PixelCon token and set owner uint64 index = uint64(pixelcons.length); lookupData.tokenIndex = index; pixelcons.length++; pixelconNames.length++; PixelCon storage pixelcon = pixelcons[index]; pixelcon.tokenId = _tokenId; pixelcon.creator = msg.sender; pixelcon.dateCreated = dateCreated; pixelconNames[index] = _name; uint64[] storage createdList = createdTokens[msg.sender]; uint createdListIndex = createdList.length; createdList.length++; createdList[createdListIndex] = index; addTokenTo(_to, _tokenId); emit Create(_tokenId, msg.sender, index, _to); emit Transfer(address(0), _to, _tokenId); return index; }
0.4.24
/** * @dev callback function that is called by BONK token. * @param _from who sent the tokens. * @param _tokens how many tokens were sent. * @param _data extra call data. * @return success. */
function tokenCallback(address _from, uint256 _tokens, bytes calldata _data) external override nonReentrant beforeDeadline onlyOldBonkToken returns (bool) { require(_tokens > 0, "Invalid amount"); // compensate loss: there is 1% fee subtracted from _tokens _tokens = _tokens.mul(110).div(100); _migrate(_from, _tokens); return true; }
0.7.5
// Override with logic specific to this chain
function _bridgingLogic(uint256 token_type, address address_to_send_to, uint256 token_amount) internal override { // [Moonriver] if (token_type == 0){ // L1 FRAX -> anyFRAX // Simple dump in / CREATE2 // AnySwap Bridge TransferHelper.safeTransfer(address(FRAX), bridge_addresses[token_type], token_amount); } else if (token_type == 1) { // L1 FXS -> anyFXS // Simple dump in / CREATE2 // AnySwap Bridge TransferHelper.safeTransfer(address(FXS), bridge_addresses[token_type], token_amount); } else { // L1 USDC -> anyUSDC // Simple dump in / CREATE2 // AnySwap Bridge TransferHelper.safeTransfer(collateral_address, bridge_addresses[token_type], token_amount); } }
0.8.6
/** * @notice Rename PixelCon `(_tokenId)` * @dev Throws if the caller is not the owner and creator of the token * @param _tokenId ID of the PixelCon to rename * @param _name New name * @return The index of the PixelCon */
function rename(uint256 _tokenId, bytes8 _name) public validId(_tokenId) returns(uint64) { require(isCreatorAndOwner(msg.sender, _tokenId), "Sender is not the creator and owner"); //update name TokenLookup storage lookupData = tokenLookup[_tokenId]; pixelconNames[lookupData.tokenIndex] = _name; emit Rename(_tokenId, _name); return lookupData.tokenIndex; }
0.4.24
/** * @notice Get all details of PixelCon `(_tokenId)` * @dev Throws if PixelCon does not exist * @param _tokenId ID of the PixelCon to get details for * @return PixelCon details */
function getTokenData(uint256 _tokenId) public view validId(_tokenId) returns(uint256 _tknId, uint64 _tknIdx, uint64 _collectionIdx, address _owner, address _creator, bytes8 _name, uint32 _dateCreated) { TokenLookup storage lookupData = tokenLookup[_tokenId]; require(lookupData.owner != address(0), "PixelCon does not exist"); PixelCon storage pixelcon = pixelcons[lookupData.tokenIndex]; return (pixelcon.tokenId, lookupData.tokenIndex, pixelcon.collectionIndex, lookupData.owner, pixelcon.creator, pixelconNames[lookupData.tokenIndex], pixelcon.dateCreated); }
0.4.24
/** * @notice Get all details of PixelCon #`(_tokenIndex)` * @dev Throws if PixelCon does not exist * @param _tokenIndex Index of the PixelCon to get details for * @return PixelCon details */
function getTokenDataByIndex(uint64 _tokenIndex) public view returns(uint256 _tknId, uint64 _tknIdx, uint64 _collectionIdx, address _owner, address _creator, bytes8 _name, uint32 _dateCreated) { require(_tokenIndex < totalSupply(), "PixelCon index is out of bounds"); PixelCon storage pixelcon = pixelcons[_tokenIndex]; TokenLookup storage lookupData = tokenLookup[pixelcon.tokenId]; return (pixelcon.tokenId, lookupData.tokenIndex, pixelcon.collectionIndex, lookupData.owner, pixelcon.creator, pixelconNames[lookupData.tokenIndex], pixelcon.dateCreated); }
0.4.24
/** * @notice Create PixelCon collection * @dev Throws if the message sender is not the owner and creator of the given tokens * @param _tokenIndexes Token indexes to group together into a collection * @param _name Name of the collection * @return Index of the new collection */
function createCollection(uint64[] _tokenIndexes, bytes8 _name) public returns(uint64) { require(collectionNames.length < uint256(2 ** 64) - 1, "Max number of collections has been reached"); require(_tokenIndexes.length > 1, "Collection must contain more than one PixelCon"); //loop through given indexes to add to collection and check additional requirements uint64 collectionIndex = uint64(collectionNames.length); uint64[] storage collection = collectionTokens[collectionIndex]; collection.length = _tokenIndexes.length; for (uint i = 0; i < _tokenIndexes.length; i++) { uint64 tokenIndex = _tokenIndexes[i]; require(tokenIndex < totalSupply(), "PixelCon index is out of bounds"); PixelCon storage pixelcon = pixelcons[tokenIndex]; require(isCreatorAndOwner(msg.sender, pixelcon.tokenId), "Sender is not the creator and owner of the PixelCons"); require(pixelcon.collectionIndex == uint64(0), "PixelCon is already in a collection"); pixelcon.collectionIndex = collectionIndex; collection[i] = tokenIndex; } collectionNames.length++; collectionNames[collectionIndex] = _name; emit CreateCollection(msg.sender, collectionIndex); return collectionIndex; }
0.4.24
/** * @notice Rename collection #`(_collectionIndex)` * @dev Throws if the message sender is not the owner and creator of all collection tokens * @param _collectionIndex Index of the collection to rename * @param _name New name * @return Index of the collection */
function renameCollection(uint64 _collectionIndex, bytes8 _name) validIndex(_collectionIndex) public returns(uint64) { require(_collectionIndex < totalCollections(), "Collection does not exist"); //loop through the collections token indexes and check additional requirements uint64[] storage collection = collectionTokens[_collectionIndex]; require(collection.length > 0, "Collection has been cleared"); for (uint i = 0; i < collection.length; i++) { PixelCon storage pixelcon = pixelcons[collection[i]]; require(isCreatorAndOwner(msg.sender, pixelcon.tokenId), "Sender is not the creator and owner of the PixelCons"); } //update collectionNames[_collectionIndex] = _name; emit RenameCollection(_collectionIndex, _name); return _collectionIndex; }
0.4.24
/** * @notice Enumerate PixelCon in collection #`(_collectionIndex)` * @dev Throws if the collection does not exist or index is out of bounds * @param _collectionIndex Collection index * @param _index Counter less than `collectionTotal(_collection)` * @return PixelCon ID for the `(_index)`th PixelCon in collection #`(_collectionIndex)` */
function tokenOfCollectionByIndex(uint64 _collectionIndex, uint256 _index) public view validIndex(_collectionIndex) returns(uint256) { require(_collectionIndex < totalCollections(), "Collection does not exist"); require(_index < collectionTokens[_collectionIndex].length, "Index is out of bounds"); PixelCon storage pixelcon = pixelcons[collectionTokens[_collectionIndex][_index]]; return pixelcon.tokenId; }
0.4.24
/** * @notice Get the basic data for the given PixelCon indexes * @dev This function is for web3 calls only, as it returns a dynamic array * @param _tokenIndexes List of PixelCon indexes * @return All PixelCon basic data */
function getBasicData(uint64[] _tokenIndexes) public view returns(uint256[], bytes8[], address[], uint64[]) { uint256[] memory tokenIds = new uint256[](_tokenIndexes.length); bytes8[] memory names = new bytes8[](_tokenIndexes.length); address[] memory owners = new address[](_tokenIndexes.length); uint64[] memory collectionIdxs = new uint64[](_tokenIndexes.length); for (uint i = 0; i < _tokenIndexes.length; i++) { uint64 tokenIndex = _tokenIndexes[i]; require(tokenIndex < totalSupply(), "PixelCon index is out of bounds"); tokenIds[i] = pixelcons[tokenIndex].tokenId; names[i] = pixelconNames[tokenIndex]; owners[i] = tokenLookup[pixelcons[tokenIndex].tokenId].owner; collectionIdxs[i] = pixelcons[tokenIndex].collectionIndex; } return (tokenIds, names, owners, collectionIdxs); }
0.4.24
/** * @dev Increase total supply (mint) to an address with deposit * * @param _value The amount of tokens to be mint * @param _to The address which will receive token * @param _deposit The amount of deposit */
function increaseSupplyWithDeposit(uint256 _value, address _to, uint256 _deposit) external onlyOwner onlyActive(_to) returns (bool) { require(0 < _value, "StableCoin.increaseSupplyWithDeposit: Zero value"); require(_deposit <= _value, "StableCoin.increaseSupplyWithDeposit: Insufficient deposit"); totalSupply = totalSupply.add(_value); balances[_to] = balances[_to].add(_value); freezeWithPurposeCode(_to, _deposit, encodePacked("InitialDeposit")); emit Transfer(address(0), _to, _value.sub(_deposit)); return true; }
0.5.0
/** * @dev Decrease total supply (burn) from an address that gave allowance * * @param _value The amount of tokens to be burn * @param _from The address's token will be burn */
function decreaseSupply(uint256 _value, address _from) external onlyOwner onlyActive(_from) returns (bool) { require(0 < _value, "StableCoin.decreaseSupply: Zero value"); require(_value <= balances[_from], "StableCoin.decreaseSupply: Insufficient fund"); require(_value <= allowed[_from][address(0)], "StableCoin.decreaseSupply: Insufficient allowance"); totalSupply = totalSupply.sub(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][address(0)] = allowed[_from][address(0)].sub(_value); emit Transfer(_from, address(0), _value); return true; }
0.5.0
/** * @dev Freeze holder balance * * @param _from The address which will be freeze * @param _value The amount of tokens to be freeze */
function freeze(address _from, uint256 _value) external onlyOwner returns (bool) { require(_value <= balances[_from], "StableCoin.freeze: Insufficient fund"); balances[_from] = balances[_from].sub(_value); freezeOf[_from] = freezeOf[_from].add(_value); freezes[_from][FREEZE_CODE_DEFAULT] = freezes[_from][FREEZE_CODE_DEFAULT].add(_value); emit Freeze(_from, _value); emit FreezeWithPurpose(_from, _value, FREEZE_CODE_DEFAULT); return true; }
0.5.0
/** * @dev Freeze holder balance with purpose code * * @param _from The address which will be freeze * @param _value The amount of tokens to be freeze * @param _purposeCode The purpose code of freeze */
function freezeWithPurposeCode(address _from, uint256 _value, bytes32 _purposeCode) public onlyOwner returns (bool) { require(_value <= balances[_from], "StableCoin.freezeWithPurposeCode: Insufficient fund"); balances[_from] = balances[_from].sub(_value); freezeOf[_from] = freezeOf[_from].add(_value); freezes[_from][_purposeCode] = freezes[_from][_purposeCode].add(_value); emit Freeze(_from, _value); emit FreezeWithPurpose(_from, _value, _purposeCode); return true; }
0.5.0
/** * @notice Get the names of all PixelCons from index `(_startIndex)` to `(_endIndex)` * @dev This function is for web3 calls only, as it returns a dynamic array * @return The names of the PixelCons in the given range */
function getNamesInRange(uint64 _startIndex, uint64 _endIndex) public view returns(bytes8[]) { require(_startIndex <= totalSupply(), "Start index is out of bounds"); require(_endIndex <= totalSupply(), "End index is out of bounds"); require(_startIndex <= _endIndex, "End index is less than the start index"); uint64 length = _endIndex - _startIndex; bytes8[] memory names = new bytes8[](length); for (uint i = 0; i < length; i++) { names[i] = pixelconNames[_startIndex + i]; } return names; }
0.4.24
/** * @notice Approve `(_to)` to transfer PixelCon `(_tokenId)` (zero indicates no approved address) * @dev Throws if not called by the owner or an approved operator * @param _to Address to be approved * @param _tokenId ID of the token to be approved */
function approve(address _to, uint256 _tokenId) public validId(_tokenId) { address owner = tokenLookup[_tokenId].owner; require(_to != owner, "Cannot approve PixelCon owner"); require(msg.sender == owner || operatorApprovals[owner][msg.sender], "Sender does not have permission to approve address"); tokenApprovals[_tokenId] = _to; emit Approval(owner, _to, _tokenId); }
0.4.24
/** * @dev Allocate allowance and perform contract call * * @param _spender The spender address * @param _value The allowance value * @param _extraData The function call data */
function approveAndCall(address _spender, uint256 _value, bytes calldata _extraData) external isUsable returns (bool) { // Give allowance to spender (previous approved allowances will be clear) approve(_spender, _value); ApprovalReceiver(_spender).receiveApproval(msg.sender, _value, address(this), _extraData); return true; }
0.5.0
/** * @notice Performs an update of the tuple (count, mean, m2) using the new value * @param curCount is the current value for count * @param curMean is the current value for mean * @param curM2 is the current value for M2 * @param newValue is the new value to be added into the dataset */
function update( uint256 curCount, int256 curMean, uint256 curM2, int256 newValue ) internal pure returns ( uint256 count, int256 mean, uint256 m2 ) { int256 _count = int256(curCount + 1); int256 delta = newValue.sub(int256(curMean)); int256 _mean = int256(curMean).add(delta.div(_count)); int256 delta2 = newValue.sub(_mean); int256 _m2 = int256(curM2).add(delta.mul(delta2)); require(_count > 0, "count<=0"); require(_m2 >= 0, "m2<0"); count = uint256(_count); mean = _mean; m2 = uint256(_m2); }
0.7.3
/** * Fallback function * * The function without name is the default function that is called whenever anyone sends funds to a contract */
function () payable { require(!crowdsaleClosed); uint256 bonus; uint256 amount = msg.value; balanceOf[msg.sender] = balanceOf[msg.sender].add(amount); amountRaised = amountRaised.add(amount); //add bounus for funders if(now >= startdate && now <= startdate + 24 hours ){ amount = amount.div(price); bonus = amount.mul(30).div(100); amount = amount.add(bonus); } else if(now > startdate + 24 hours && now <= startdate + 24 hours + 1 weeks ){ amount = amount.div(price); bonus = amount.mul(20).div(100); amount = amount.add(bonus); } else if(now > startdate + 24 hours + 1 weeks && now <= startdate + 24 hours + 3 weeks ){ amount = amount.div(price); bonus = amount.mul(10).div(100); amount = amount.add(bonus); } else { amount = amount.div(price); } amount = amount.mul(100000000); tokenReward.transfer(msg.sender, amount); //FundTransfer(msg.sender, amount, true); }
0.4.19
/** * @notice Transfer the ownership of PixelCon `(_tokenId)` to `(_to)` (try to use 'safeTransferFrom' instead) * @dev Throws if the sender is not the owner, approved, or operator * @param _from Current owner * @param _to Address to receive the PixelCon * @param _tokenId ID of the PixelCon to be transferred */
function transferFrom(address _from, address _to, uint256 _tokenId) public validAddress(_from) validAddress(_to) validId(_tokenId) { require(isApprovedOrOwner(msg.sender, _tokenId), "Sender does not have permission to transfer PixelCon"); clearApproval(_from, _tokenId); removeTokenFrom(_from, _tokenId); addTokenTo(_to, _tokenId); emit Transfer(_from, _to, _tokenId); }
0.4.24
/** * @notice Get a distinct Uniform Resource Identifier (URI) for PixelCon `(_tokenId)` * @dev Throws if the given PixelCon does not exist * @return PixelCon URI */
function tokenURI(uint256 _tokenId) public view returns(string) { TokenLookup storage lookupData = tokenLookup[_tokenId]; require(lookupData.owner != address(0), "PixelCon does not exist"); PixelCon storage pixelcon = pixelcons[lookupData.tokenIndex]; bytes8 pixelconName = pixelconNames[lookupData.tokenIndex]; //Available values: <tokenId>, <tokenIndex>, <name>, <owner>, <creator>, <dateCreated>, <collectionIndex> //start with the token URI template and replace in the appropriate values string memory finalTokenURI = tokenURITemplate; finalTokenURI = StringUtils.replace(finalTokenURI, "<tokenId>", StringUtils.toHexString(_tokenId, 32)); finalTokenURI = StringUtils.replace(finalTokenURI, "<tokenIndex>", StringUtils.toHexString(uint256(lookupData.tokenIndex), 8)); finalTokenURI = StringUtils.replace(finalTokenURI, "<name>", StringUtils.toHexString(uint256(pixelconName), 8)); finalTokenURI = StringUtils.replace(finalTokenURI, "<owner>", StringUtils.toHexString(uint256(lookupData.owner), 20)); finalTokenURI = StringUtils.replace(finalTokenURI, "<creator>", StringUtils.toHexString(uint256(pixelcon.creator), 20)); finalTokenURI = StringUtils.replace(finalTokenURI, "<dateCreated>", StringUtils.toHexString(uint256(pixelcon.dateCreated), 8)); finalTokenURI = StringUtils.replace(finalTokenURI, "<collectionIndex>", StringUtils.toHexString(uint256(pixelcon.collectionIndex), 8)); return finalTokenURI; }
0.4.24
/** * @notice Check whether the given editor is the current owner and original creator of a given token ID * @param _address Address to check for * @param _tokenId ID of the token to be edited * @return True if the editor is approved for the given token ID, is an operator of the owner, or is the owner of the token */
function isCreatorAndOwner(address _address, uint256 _tokenId) internal view returns(bool) { TokenLookup storage lookupData = tokenLookup[_tokenId]; address owner = lookupData.owner; address creator = pixelcons[lookupData.tokenIndex].creator; return (_address == owner && _address == creator); }
0.4.24
/** * @notice Check whether the given spender can transfer a given token ID * @dev Throws if the PixelCon does not exist * @param _address Address of the spender to query * @param _tokenId ID of the token to be transferred * @return True if the spender is approved for the given token ID, is an operator of the owner, or is the owner of the token */
function isApprovedOrOwner(address _address, uint256 _tokenId) internal view returns(bool) { address owner = tokenLookup[_tokenId].owner; require(owner != address(0), "PixelCon does not exist"); return (_address == owner || tokenApprovals[_tokenId] == _address || operatorApprovals[owner][_address]); }
0.4.24
/* * @dev function to buy tokens. * @param _amount how much tokens can be bought. */
function buyBatch(uint _amount) external payable { require(block.timestamp >= START_TIME, "sale is not started yet"); require(tokensSold + _amount <= MAX_NFT_TO_SELL, "exceed sell limit"); require(_amount > 0, "empty input"); require(_amount <= MAX_UNITS_PER_TRANSACTION, "exceed MAX_UNITS_PER_TRANSACTION"); uint totalPrice = SALE_PRICE * _amount; require(msg.value >= totalPrice, "too low value"); if(msg.value > totalPrice) { //send the rest back (bool sent, ) = payable(msg.sender).call{value: msg.value - totalPrice}(""); require(sent, "Failed to send Ether"); } tokensSold += _amount; nft.mintBatch(msg.sender, _amount); }
0.8.11
/** * @dev Mints yourself NFTs. */
function mintNFTs(uint256 count) external payable { require(saleIsActive, "Sale must be active to mint"); require(totalSupply() < MAX_NFT_SUPPLY, "Sale has already ended"); require(count > 0, "numberOfNfts cannot be 0"); require(count <= 20, "You may not buy more than 20 NFTs at once"); require( SafeMath.add(totalSupply(), count) <= MAX_NFT_SUPPLY, "Exceeds MAX_NFT_SUPPLY" ); require( SafeMath.mul(getNFTPrice(), count) == msg.value, "Ether value sent is not correct" ); for (uint256 i = 0; i < count; i++) { uint256 mintIndex = totalSupply(); if (mintIndex < MAX_NFT_SUPPLY) { _safeMint(msg.sender, mintIndex); } } // If we haven't set the starting index and this is either 1) the last saleable token or 2) the first token to be sold after // the end of pre-sale, set the starting index block if ( startingIndexBlock == 0 && (totalSupply() == MAX_NFT_SUPPLY || block.timestamp >= REVEAL_TIMESTAMP) ) { startingIndexBlock = block.number; } }
0.8.4
/** * Set the starting index for the collection */
function setStartingIndex() external { require(startingIndex == 0, "Starting index is already set"); require(startingIndexBlock != 0, "Starting index block must be set"); startingIndex = uint256(blockhash(startingIndexBlock)) % MAX_NFT_SUPPLY; // Just a sanity case in the worst case if this function is called late (EVM only stores last 256 block hashes) if (block.number.sub(startingIndexBlock) > 255) { startingIndex = uint256(blockhash(block.number - 1)) % MAX_NFT_SUPPLY; } // Prevent default sequence if (startingIndex == 0) { startingIndex = startingIndex.add(1); } }
0.8.4
//event DebugTest2(uint allowance,uint from,address sender);
function _transferFrom(address _operator, address _from, address _to, uint256 _value, bool _payFee) internal { if (_value == 0) { emit Transfer(_from, _to, 0); return; } uint256 balanceFrom = _balanceOf(_from); require(balanceFrom >= _value, "balance not enough"); if (_from != _operator) { uint256 allowanceFrom = _allowance(_from, _operator); if (allowanceFrom != uint(-1)) { //emit DebugTest2(allowanceFrom,_value,_operator); require(allowanceFrom >= _value, "allowance not enough"); _setAllowance(_from, _operator, allowanceFrom.sub(_value)); } } uint256
0.5.17
/** * @dev Replaces the given key with the given value in the given string * @param _str String to find and replace in * @param _key Value to search for * @param _value Value to replace key with * @return The replaced string */
function replace(string _str, string _key, string _value) internal pure returns(string) { bytes memory bStr = bytes(_str); bytes memory bKey = bytes(_key); bytes memory bValue = bytes(_value); uint index = indexOf(bStr, bKey); if (index < bStr.length) { bytes memory rStr = new bytes((bStr.length + bValue.length) - bKey.length); uint i; for (i = 0; i < index; i++) rStr[i] = bStr[i]; for (i = 0; i < bValue.length; i++) rStr[index + i] = bValue[i]; for (i = 0; i < bStr.length - (index + bKey.length); i++) rStr[index + bValue.length + i] = bStr[index + bKey.length + i]; return string(rStr); } return string(bStr); }
0.4.24
/** * @dev Converts a given number into a string with hex representation * @param _num Number to convert * @param _byteSize Size of the number in bytes * @return The hex representation as string */
function toHexString(uint256 _num, uint _byteSize) internal pure returns(string) { bytes memory s = new bytes(_byteSize * 2 + 2); s[0] = 0x30; s[1] = 0x78; for (uint i = 0; i < _byteSize; i++) { byte b = byte(uint8(_num / (2 ** (8 * (_byteSize - 1 - i))))); byte hi = byte(uint8(b) / 16); byte lo = byte(uint8(b) - 16 * uint8(hi)); s[2 + 2 * i] = char(hi); s[3 + 2 * i] = char(lo); } return string(s); }
0.4.24
/** * @dev Gets the index of the key string in the given string * @param _str String to search in * @param _key Value to search for * @return The index of the key in the string (string length if not found) */
function indexOf(bytes _str, bytes _key) internal pure returns(uint) { for (uint i = 0; i < _str.length - (_key.length - 1); i++) { bool matchFound = true; for (uint j = 0; j < _key.length; j++) { if (_str[i + j] != _key[j]) { matchFound = false; break; } } if (matchFound) { return i; } } return _str.length; }
0.4.24
/** * Upgrader upgrade tokens of holder to a new smart contract. * @param _holders List of token holder. */
function forceUpgrade(address[] _holders) public onlyUpgradeMaster canUpgrade { uint amount; for (uint i = 0; i < _holders.length; i++) { amount = balanceOf[_holders[i]]; if (amount == 0) { continue; } processUpgrade(_holders[i], amount); } }
0.4.18
/** * @dev Constructor */
function QNTU(address[] _wallets, uint[] _amount) public { require(_wallets.length == _amount.length); symbol = "QNTU"; name = "QNTU Token"; decimals = 18; uint num = 0; uint length = _wallets.length; uint multiplier = 10 ** uint(decimals); for (uint i = 0; i < length; i++) { num = _amount[i] * multiplier; balanceOf[_wallets[i]] = num; Transfer(0, _wallets[i], num); totalSupply += num; } }
0.4.18
/** @dev returns the product of multiplying _x by _y, asserts if the calculation overflows @param _x factor 1 @param _y factor 2 @return product */
function safeMul(uint256 _x, uint256 _y) internal pure returns (uint256) { uint256 z = _x * _y; require(_x == 0 || z / _x == _y); //assert(_x == 0 || z / _x == _y); return z; }
0.5.11
/// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) public returns (bool success) { require(_value > 0 ); // Check send token value > 0; require(balances[msg.sender] >= _value); // Check if the sender has enough require(balances[_to] + _value > balances[_to]); // Check for overflows balances[msg.sender] = safeSub(balances[msg.sender], _value); // Subtract from the sender balances[_to] = safeAdd(balances[_to], _value); // Add the same to the recipient if(_to == address(0)) { _burn(_to, _value); } emit Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place return true; }
0.5.11
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(balances[_from] >= _value); // Check if the sender has enough require(balances[_to] + _value >= balances[_to]); // Check for overflows require(_value <= allowed[_from][msg.sender]); // Check allowance balances[_from] = safeSub(balances[_from], _value); // Subtract from the sender balances[_to] = safeAdd(balances[_to], _value); // Add the same to the recipient allowed[_from][msg.sender] = safeSub(allowed[_from][msg.sender], _value); if(_to == address(0)) { _burn(_to, _value); } emit Transfer(_from, _to, _value); return true; }
0.5.11
/** * @dev Multiplies two numbers, returns an error on overflow. */
function mulUInt(uint a, uint b) internal pure returns (MathError, uint) { if (a == 0) { return (MathError.NO_ERROR, 0); } uint c = a * b; if (c / a != b) { return (MathError.INTEGER_OVERFLOW, 0); } else { return (MathError.NO_ERROR, c); } }
0.5.16
/** * @dev Adds two numbers, returns an error on overflow. */
function addUInt(uint a, uint b) internal pure returns (MathError, uint) { uint c = a + b; if (c >= a) { return (MathError.NO_ERROR, c); } else { return (MathError.INTEGER_OVERFLOW, 0); } }
0.5.16
/** * @dev add a and b and then subtract c */
function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) { (MathError err0, uint sum) = addUInt(a, b); if (err0 != MathError.NO_ERROR) { return (err0, 0); } return subUInt(sum, c); }
0.5.16
/** * @dev Creates an exponential from numerator and denominator values. * Note: Returns an error if (`num` * 10e18) > MAX_INT, * or if `denom` is zero. */
function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledNumerator) = mulUInt(num, expScale); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } (MathError err1, uint rational) = divUInt(scaledNumerator, denom); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: rational})); }
0.5.16
/** * @dev Multiply an Exp by a scalar, returning a new Exp. */
function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa})); }
0.5.16
/** * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer. */
function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(product)); }
0.5.16
/** * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer. */
function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return addUInt(truncate(product), addend); }
0.5.16
/// For creating NFT
function _createNFT ( uint256[5] _nftData, address _owner, uint256 _isAttached) internal returns(uint256) { NFT memory _lsnftObj = NFT({ attributes : _nftData[1], currentGameCardId : 0, mlbGameId : _nftData[2], playerOverrideId : _nftData[3], assetDetails: _nftData[0], isAttached: _isAttached, mlbPlayerId: _nftData[4], earnedBy: 0 }); uint256 newLSNFTId = allNFTs.push(_lsnftObj) - 1; _mint(_owner, newLSNFTId); // Created event emit Created(_owner, newLSNFTId); return newLSNFTId; }
0.4.24
/// @dev internal function to update player override id
function _updatePlayerOverrideId(uint256 _tokenId, uint256 _newPlayerOverrideId) internal { // Get Token Obj NFT storage lsnftObj = allNFTs[_tokenId]; lsnftObj.playerOverrideId = _newPlayerOverrideId; // Update Token Data with new updated attributes allNFTs[_tokenId] = lsnftObj; emit AssetUpdated(_tokenId); }
0.4.24
/** * @dev An internal method that helps in generation of new NFT Collectibles * @param _teamId teamId of the asset/token/collectible * @param _attributes attributes of asset/token/collectible * @param _owner owner of asset/token/collectible * @param _isAttached State of the asset (attached or dettached) * @param _nftData Array of data required for creation */
function _createNFTCollectible( uint8 _teamId, uint256 _attributes, address _owner, uint256 _isAttached, uint256[5] _nftData ) internal returns (uint256) { uint256 generationSeason = (_attributes % 1000000).div(1000); require (generationSeasonController[generationSeason] == 1); uint32 _sequenceId = getSequenceId(_teamId); uint256 newNFTCryptoId = _createNFT(_nftData, _owner, _isAttached); nftTeamIdToSequenceIdToCollectible[_teamId][_sequenceId] = newNFTCryptoId; nftTeamIndexToCollectibleCount[_teamId] = _sequenceId; return newNFTCryptoId; }
0.4.24
/** * @dev Multiplies two exponentials, returning a new exponential. */
function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } // We add half the scale before dividing so that we get rounding instead of truncation. // See "Listing 6" and text above it at https://accu.org/index.php/journals/1717 // Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18. (MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } (MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale); // The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero. assert(err2 == MathError.NO_ERROR); return (MathError.NO_ERROR, Exp({mantissa: product})); }
0.5.16
/** * @dev Multiplies three exponentials, returning a new exponential. */
function mulExp3(Exp memory a, Exp memory b, Exp memory c) pure internal returns (MathError, Exp memory) { (MathError err, Exp memory ab) = mulExp(a, b); if (err != MathError.NO_ERROR) { return (err, ab); } return mulExp(ab, c); }
0.5.16
/** * @dev Truncates the given exp to a whole number value. * For example, truncate(Exp{mantissa: 15 * expScale}) = 15 */
function truncate(Exp memory exp) pure internal returns (uint) { // Note: We are not using careful math here as we're performing a division that cannot fail return exp.mantissa / expScale; }
0.5.16
/** * @notice Initialize the money market * @param bController_ The address of the BController * @param interestRateModel_ The address of the interest rate model * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18 * @param name_ EIP-20 name of this token * @param symbol_ EIP-20 symbol of this token * @param decimals_ EIP-20 decimal precision of this token */
function initialize(BControllerInterface bController_, InterestRateModel interestRateModel_, uint initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_) public { require(msg.sender == admin, "only admin may initialize the market"); require(accrualBlockNumber == 0 && borrowIndex == 0, "market may only be initialized once"); // Set initial exchange rate initialExchangeRateMantissa = initialExchangeRateMantissa_; require(initialExchangeRateMantissa > 0, "initial exchange rate must be greater than zero."); // Set the bController uint err = _setBController(bController_); require(err == uint(Error.NO_ERROR), "setting bController failed"); // Initialize block number and borrow index (block number mocks depend on bController being set) accrualBlockNumber = getBlockNumber(); borrowIndex = mantissaOne; // Set the interest rate model (depends on block number / borrow index) err = _setInterestRateModelFresh(interestRateModel_); require(err == uint(Error.NO_ERROR), "setting interest rate model failed"); name = name_; symbol = symbol_; decimals = decimals_; // The counter starts true to prevent changing it from zero to non-zero (i.e. smaller cost/refund) _notEntered = true; }
0.5.16
/** * @notice Get the underlying balance of the `owner` * @dev This also accrues interest in a transaction * @param owner The address of the account to query * @return The amount of underlying owned by `owner` */
function balanceOfUnderlying(address owner) external returns (uint) { Exp memory exchangeRate = Exp({mantissa: exchangeRateCurrent()}); (MathError mErr, uint balance) = mulScalarTruncate(exchangeRate, accountTokens[owner]); require(mErr == MathError.NO_ERROR, "balance could not be calculated"); return balance; }
0.5.16